durable-fn
v1.0.0
Published
Durable functions in under 300 bytes — pure JavaScript, zero dependencies, no infrastructure required.
Downloads
149
Readme
durable-fn
Durable functions in under 300 bytes.
Durable functions in pure JavaScript — zero dependencies, no infrastructure required.
Getting started
import durable from 'durable-fn';
const quiz = durable(function* (suspend) {
const answer = yield* suspend(() => 'What year did the first iPhone launch?');
if (answer === '2007') return 'Correct!';
const hint = yield* suspend(() => 'Nope — want a hint? (yes/no)');
return hint === 'yes' ? 'Same year as the first Kindle.' : 'The answer was 2007.';
});
// Each call replays the event log and resumes at the next suspend.
quiz([]).value; // 'What year did the first iPhone launch?'
quiz(['2007']).value; // 'Correct!'
quiz(['1999']).value; // 'Nope — want a hint? (yes/no)'
quiz(['1999', 'yes']).value; // 'Same year as the first Kindle.'suspend(() => output) checkpoints the function and returns output to the caller. The next
call replays the event log, skips completed checkpoints, and resumes at the first unanswered
suspend with the new reply. Your handler just persists the event log between requests.
For example, an Express handler that keeps the event log in the URL — no session store needed:
import express from 'express';
express()
.get('/quiz', (req, res) => {
const events: string[] = JSON.parse(String(req.query.events ?? '[]'));
if (req.query.answer) events.push(String(req.query.answer));
const step = quiz(events);
if (step.done) return res.send(step.value);
res.send(`${step.value}
<form>
<input type="hidden" name="events" value='${JSON.stringify(events)}'>
<input name="answer" autofocus> <button>Submit</button>
</form>`);
})
.listen(3000);See test/ for advanced patterns: going back, async, recording nondeterminism, and passing context.
