posipaki 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
- import Process, { spawn, Message, ProcessCtx, ProcessFn } from './process';
2
- import { ExitMessage, runDispatch } from './util';
3
- export { Process, spawn, runDispatch, Message, ExitMessage, ProcessCtx, ProcessFn };
1
+ import { a as runDispatchAsync, c as ExitMessage, d as ProcessCtx, f as ProcessFn, i as AsyncProcess, l as Message, n as spawn, o as spawnAsync, p as SupervisorState, r as runDispatch, s as AsyncProcessFn, t as Process, u as PipeState } from "./process-jEWRVEFG.js";
2
+
3
+ //#region src/adapters.d.ts
4
+ declare function asyncify<A, S, IM extends Message, OM extends Message>(fn: ProcessFn<A, S, IM, OM>): AsyncProcessFn<A, S, IM, OM>;
5
+ //#endregion
6
+ export { AsyncProcess, type AsyncProcessFn, type ExitMessage, type Message, type PipeState, Process, type ProcessCtx, type ProcessFn, type SupervisorState, asyncify, runDispatch, runDispatchAsync, spawn, spawnAsync };
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/adapters.ts"],"mappings":";;;iBAEgB,QAAA,kBAA0B,OAAA,aAAoB,OAAA,EAC5D,EAAA,EAAI,SAAA,CAAU,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA,IACvB,cAAA,CAAe,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,245 @@
1
- import Process, { spawn } from './process';
2
- import { runDispatch } from './util';
3
- export { Process, spawn, runDispatch };
1
+ import { i as runDispatch, n as defer, r as makeWaiter, t as debugLog } from "./util-Cw64MseZ.js";
2
+ //#region src/process.async.ts
3
+ /**
4
+ * Async equivalent of `runDispatch`. Loops, yielding `null` and feeding
5
+ * each incoming message to an `async` reducer. Exits when `readyFn()`
6
+ * returns true.
7
+ */
8
+ async function* runDispatchAsync(name, fn, readyFn = () => false, debugLevel = false) {
9
+ let msg;
10
+ while (!readyFn()) {
11
+ msg = yield null;
12
+ debugLog(debugLevel, "msg", name, " <- ", msg);
13
+ await fn(msg);
14
+ }
15
+ }
16
+ const noop = () => null;
17
+ /**
18
+ * A process driven by an async generator. Functionally identical to
19
+ * {@link Process} but supports `await` inside reducers.
20
+ *
21
+ * Messages are processed **one at a time** — if a tick is already
22
+ * in-flight, new messages are buffered and processed when the current
23
+ * tick completes.
24
+ */
25
+ var AsyncProcess = class AsyncProcess {
26
+ constructor(fn, pname, toParent) {
27
+ this.current = null;
28
+ this.buffer = [];
29
+ this.nextTick = null;
30
+ this.children = [];
31
+ this.subscribers = [];
32
+ this._isPaused = false;
33
+ this._tickInProgress = false;
34
+ this._exitReject = null;
35
+ this.pgenerator = fn;
36
+ this.pname = pname;
37
+ this.toParent = toParent || noop;
38
+ this.id = Symbol(pname);
39
+ this.state = null;
40
+ this.exitWaiter = makeWaiter();
41
+ this._ready = makeWaiter();
42
+ this._resolveReady = this._ready.resolve;
43
+ }
44
+ /** Promise that resolves once the initial state is available. */
45
+ ready() {
46
+ return this._ready.promise;
47
+ }
48
+ /**
49
+ * Kick off the async generator. The first `yield` sets the initial
50
+ * state; for async generators this happens in a microtask.
51
+ */
52
+ start(arg0) {
53
+ const ctx = {
54
+ pname: this.pname,
55
+ fork: this.fork.bind(this),
56
+ send: this.send.bind(this),
57
+ toParent: this.toParent
58
+ };
59
+ this.current = this._watchExit(ctx, arg0);
60
+ this.current.next().then((ret) => {
61
+ this.state = ret.value ?? null;
62
+ this._resolveReady();
63
+ if (ret.done) {
64
+ this.exitWaiter.resolve();
65
+ return;
66
+ }
67
+ this._eatResult(this.current.next({ type: "__ADVANCE__" }));
68
+ });
69
+ }
70
+ /** Wrap the user's generator so EXIT/STOP logic fires on completion. */
71
+ async *_watchExit(ctx, arg0) {
72
+ try {
73
+ yield* this.pgenerator(ctx, arg0);
74
+ } finally {
75
+ this.toAllChildren({ type: "STOP" });
76
+ this.toParent({
77
+ type: "EXIT",
78
+ pid: this.id
79
+ });
80
+ }
81
+ }
82
+ fork(fn, pname) {
83
+ return (args) => {
84
+ const child = new AsyncProcess(fn, pname, this.fromChild.bind(this));
85
+ this.children.push(child);
86
+ child.start(args);
87
+ return child;
88
+ };
89
+ }
90
+ async _tick() {
91
+ if (!this.current || this._tickInProgress) return;
92
+ this._tickInProgress = true;
93
+ try {
94
+ let msg;
95
+ let ret = null;
96
+ while ((msg = this.buffer.shift()) !== void 0) {
97
+ ret = await this._safeNext(msg);
98
+ if (!ret || ret.done) break;
99
+ }
100
+ this.notify();
101
+ this._eatResult(ret);
102
+ } catch (e) {
103
+ this._exitReject?.(e);
104
+ this._exitReject = null;
105
+ } finally {
106
+ this._tickInProgress = false;
107
+ }
108
+ }
109
+ /** Call `.next()` and redirect unhandled rejections. */
110
+ async _safeNext(msg) {
111
+ try {
112
+ return await this.current.next(msg);
113
+ } catch (e) {
114
+ this._exitReject?.(e);
115
+ this._exitReject = null;
116
+ return {
117
+ done: true,
118
+ value: void 0
119
+ };
120
+ }
121
+ }
122
+ _eatResult(ret) {
123
+ if (!ret) return;
124
+ Promise.resolve(ret).then((r) => {
125
+ if (r.done) this.exitWaiter.resolve();
126
+ });
127
+ }
128
+ /** Broadcast a message to all children. */
129
+ toAllChildren(msg) {
130
+ this.children.forEach((p) => p.send(msg));
131
+ }
132
+ /** Enqueue a message. Processing is async (microtask). */
133
+ send(msg) {
134
+ this.buffer.push(msg);
135
+ this._scheduleTick();
136
+ }
137
+ /**
138
+ * Synchronously flush the buffer. For sync processes use {@link Process.tick};
139
+ * for async processes this is **not guaranteed** to process everything
140
+ * immediately if reducers contain `await`. Prefer `send()` + `await proc.wait()`.
141
+ */
142
+ tick() {
143
+ this.nextTick?.flush();
144
+ this.nextTick = null;
145
+ }
146
+ _scheduleTick() {
147
+ if (this._isPaused) return;
148
+ this.nextTick?.cancel();
149
+ this.nextTick = defer(() => {
150
+ this.nextTick = null;
151
+ this._tick();
152
+ });
153
+ }
154
+ notify() {
155
+ this.subscribers.forEach((f) => f());
156
+ }
157
+ get isListenedTo() {
158
+ return this.subscribers.length > 0;
159
+ }
160
+ subscribe(f) {
161
+ this.subscribers.push(f);
162
+ return () => {
163
+ const idx = this.subscribers.indexOf(f);
164
+ if (idx < 0) return;
165
+ this.subscribers.splice(idx, 1);
166
+ };
167
+ }
168
+ pause() {
169
+ this.nextTick?.cancel();
170
+ this.nextTick = null;
171
+ this._isPaused = true;
172
+ }
173
+ resume() {
174
+ this._isPaused = false;
175
+ this._scheduleTick();
176
+ }
177
+ /**
178
+ * Returns a promise that resolves when the generator completes, or
179
+ * rejects if an unhandled error occurs during message processing.
180
+ */
181
+ wait() {
182
+ return new Promise((resolve, reject) => {
183
+ this._exitReject = reject;
184
+ this.exitWaiter.promise.then(() => {
185
+ this._exitReject = null;
186
+ resolve();
187
+ }, (e) => {
188
+ this._exitReject = null;
189
+ reject(e);
190
+ });
191
+ });
192
+ }
193
+ fromChild(msg) {
194
+ if (msg.type === "EXIT") this.children = this.children.filter((p) => p.id !== msg.pid);
195
+ this.send(msg);
196
+ }
197
+ };
198
+ /**
199
+ * Spawn a new async process. Accepts both sync and async process
200
+ * functions — sync ones are automatically wrapped with {@link asyncify}.
201
+ */
202
+ function spawnAsync(fn, pname, toParent) {
203
+ return (args) => {
204
+ const proc = new AsyncProcess(fn, pname, toParent);
205
+ proc.start(args);
206
+ return proc;
207
+ };
208
+ }
209
+ //#endregion
210
+ //#region src/adapters.ts
211
+ function asyncify(fn) {
212
+ return async function* (ctx, args) {
213
+ yield* fn(ctx, args);
214
+ };
215
+ }
216
+ //#endregion
217
+ //#region src/process.ts
218
+ function spawn(fn, pname, tp) {
219
+ return (a) => new Process(fn, pname, tp).start(a);
220
+ }
221
+ var Process = class extends AsyncProcess {
222
+ constructor(fn, pname, tp) {
223
+ super(asyncify(fn), pname, tp);
224
+ }
225
+ start(a) {
226
+ super.start(a);
227
+ return this;
228
+ }
229
+ tick() {
230
+ return super._tick();
231
+ }
232
+ };
233
+ //#endregion
234
+ //#region src/index.ts
235
+ /**
236
+ * Posipaki — Erlang-inspired lightweight actor processes built on
237
+ * generator functions. Processes communicate via message-passing,
238
+ * can fork children, and expose their state reactively.
239
+ *
240
+ * @module
241
+ */
242
+ //#endregion
243
+ export { AsyncProcess, Process, asyncify, runDispatch, runDispatchAsync, spawn, spawnAsync };
244
+
4
245
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,KAAK,EAAkC,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAe,WAAW,EAAE,MAAM,QAAQ,CAAC;AAElD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAA+C,CAAA"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/process.async.ts","../src/adapters.ts","../src/process.ts","../src/index.ts"],"sourcesContent":["import { defer, makeWaiter, debugLog } from \"./util.js\";\nimport type { DeferredCall, Waiter } from \"./util.js\";\nimport type {\n Message,\n ExitMessage,\n ProcessCtx,\n AsyncProcessFn,\n} from \"./types.js\";\n\n// ---- types ------------------------------------------------------------------\n\n/** An async iterator over process state. */\ntype AsyncProcessGenerator<ProcessState, InMessage> = AsyncGenerator<\n ProcessState | null,\n void,\n InMessage\n>;\n\ntype NotifyFn = () => void;\n\n// ---- runDispatchAsync -------------------------------------------------------\n\ntype AsyncReducer<M> = (msg: M) => Promise<void>;\ntype ReadyFn = () => boolean;\n\n/**\n * Async equivalent of `runDispatch`. Loops, yielding `null` and feeding\n * each incoming message to an `async` reducer. Exits when `readyFn()`\n * returns true.\n */\nexport async function* runDispatchAsync<M>(\n name: string,\n fn: AsyncReducer<M>,\n readyFn: ReadyFn = () => false,\n debugLevel = false,\n): AsyncGenerator<null, void, M> {\n let msg: M;\n while (!readyFn()) {\n msg = yield null;\n debugLog(debugLevel, \"msg\", name, \" <- \", msg);\n await fn(msg);\n }\n}\n\n// ---- AsyncProcess -----------------------------------------------------------\n\ntype ProcessMessageCb<M> = (msg: M) => void;\n\nconst noop = () => null;\n\n/**\n * A process driven by an async generator. Functionally identical to\n * {@link Process} but supports `await` inside reducers.\n *\n * Messages are processed **one at a time** — if a tick is already\n * in-flight, new messages are buffered and processed when the current\n * tick completes.\n */\nexport class AsyncProcess<\n Args,\n State,\n InMessage extends Message,\n OutMessage extends Message,\n> {\n pgenerator: AsyncProcessFn<Args, State, InMessage, OutMessage>;\n pname: string;\n toParent: ProcessMessageCb<OutMessage>;\n id: symbol;\n state: State | null;\n\n private current: AsyncProcessGenerator<State, InMessage> | null = null;\n private buffer: Array<InMessage> = [];\n private nextTick: DeferredCall | null = null;\n private children: Array<AsyncProcess<unknown, unknown, Message, Message>> =\n [];\n private subscribers: Array<NotifyFn> = [];\n private exitWaiter: Waiter;\n private _isPaused: boolean = false;\n private _tickInProgress: boolean = false;\n private _exitReject: ((e: unknown) => void) | null = null;\n private _ready!: Waiter;\n private _resolveReady!: () => void;\n\n constructor(\n fn: AsyncProcessFn<Args, State, InMessage, OutMessage>,\n pname: string,\n toParent: ProcessMessageCb<OutMessage> | undefined,\n ) {\n this.pgenerator = fn;\n this.pname = pname;\n this.toParent = toParent || (noop as ProcessMessageCb<OutMessage>);\n this.id = Symbol(pname);\n this.state = null;\n this.exitWaiter = makeWaiter();\n this._ready = makeWaiter();\n this._resolveReady = this._ready.resolve;\n }\n\n /** Promise that resolves once the initial state is available. */\n ready(): Promise<void> {\n return this._ready.promise;\n }\n\n // ---- lifecycle ------------------------------------------------------------\n\n /**\n * Kick off the async generator. The first `yield` sets the initial\n * state; for async generators this happens in a microtask.\n */\n start(arg0: Args): void {\n const ctx: ProcessCtx<InMessage, OutMessage> = {\n pname: this.pname,\n fork: this.fork.bind(this) as any,\n send: this.send.bind(this),\n toParent: this.toParent,\n };\n\n this.current = this._watchExit(ctx, arg0);\n void this.current.next().then((ret: IteratorResult<State | null, void>) => {\n this.state = ret.value ?? null;\n this._resolveReady();\n if (ret.done) { this.exitWaiter.resolve(); return; }\n // Advance past the initial yield so the _watchExit generator\n // runs its finally block (EXIT/STOP) and the inner generator\n // enters its dispatch loop. The second .next() sends no\n // message — it just consumes the _watchExit wrapper's own\n // yield, not the user's generator.\n this._eatResult(this.current!.next({ type: \"__ADVANCE__\" } as any));\n });\n }\n\n /** Wrap the user's generator so EXIT/STOP logic fires on completion. */\n private async *_watchExit(\n ctx: ProcessCtx<InMessage, OutMessage>,\n arg0: Args,\n ): AsyncProcessGenerator<State, InMessage> {\n try {\n yield* this.pgenerator(ctx, arg0);\n } finally {\n this.toAllChildren({ type: \"STOP\" } as Message);\n this.toParent({\n type: \"EXIT\",\n pid: this.id,\n } as unknown as OutMessage);\n }\n }\n\n // ---- fork -----------------------------------------------------------------\n\n fork<ChildArgs, ChildState, ChildIM extends Message, ChildOM extends Message>(\n fn: AsyncProcessFn<ChildArgs, ChildState, ChildIM, ChildOM>,\n pname: string,\n ): (\n args: ChildArgs,\n ) => AsyncProcess<ChildArgs, ChildState, ChildIM, ChildOM> {\n return (args: ChildArgs) => {\n const child = new AsyncProcess<ChildArgs, ChildState, ChildIM, ChildOM>(\n fn,\n pname,\n this.fromChild.bind(this) as unknown as ProcessMessageCb<ChildOM>,\n );\n this.children.push(\n child as unknown as AsyncProcess<unknown, unknown, Message, Message>,\n );\n child.start(args);\n return child;\n };\n }\n\n // ---- message processing ---------------------------------------------------\n\n protected async _tick(): Promise<void> {\n if (!this.current || this._tickInProgress) return;\n\n this._tickInProgress = true;\n try {\n let msg: InMessage | undefined;\n let ret: IteratorResult<State | null, void> | null = null;\n while ((msg = this.buffer.shift()) !== undefined) {\n ret = await this._safeNext(msg);\n if (!ret || ret.done) break;\n }\n this.notify();\n this._eatResult(ret);\n } catch (e) {\n this._exitReject?.(e);\n this._exitReject = null;\n } finally {\n this._tickInProgress = false;\n }\n }\n\n /** Call `.next()` and redirect unhandled rejections. */\n private async _safeNext(\n msg: InMessage,\n ): Promise<IteratorResult<State | null, void> | null> {\n try {\n return await this.current!.next(msg);\n } catch (e) {\n this._exitReject?.(e);\n this._exitReject = null;\n return { done: true, value: undefined };\n }\n }\n\n private _eatResult(\n ret:\n | IteratorResult<State | null, void>\n | Promise<IteratorResult<State | null, void>>\n | null,\n ): void {\n if (!ret) return;\n Promise.resolve(ret).then((r) => {\n if (r.done) {\n this.exitWaiter.resolve();\n }\n });\n }\n\n /** Broadcast a message to all children. */\n toAllChildren(msg: Message): void {\n this.children.forEach((p) => p.send(msg));\n }\n\n /** Enqueue a message. Processing is async (microtask). */\n send(msg: InMessage): void {\n this.buffer.push(msg);\n this._scheduleTick();\n }\n\n /**\n * Synchronously flush the buffer. For sync processes use {@link Process.tick};\n * for async processes this is **not guaranteed** to process everything\n * immediately if reducers contain `await`. Prefer `send()` + `await proc.wait()`.\n */\n tick(): void {\n this.nextTick?.flush();\n this.nextTick = null;\n }\n\n private _scheduleTick(): void {\n if (this._isPaused) return;\n\n this.nextTick?.cancel();\n this.nextTick = defer(() => {\n this.nextTick = null;\n void this._tick();\n });\n }\n\n // ---- subscribers ----------------------------------------------------------\n\n notify(): void {\n this.subscribers.forEach((f) => f());\n }\n\n get isListenedTo(): boolean {\n return this.subscribers.length > 0;\n }\n\n subscribe(f: NotifyFn): () => void {\n this.subscribers.push(f);\n return () => {\n const idx = this.subscribers.indexOf(f);\n if (idx < 0) return;\n this.subscribers.splice(idx, 1);\n };\n }\n\n // ---- pause / resume -------------------------------------------------------\n\n pause(): void {\n this.nextTick?.cancel();\n this.nextTick = null;\n this._isPaused = true;\n }\n\n resume(): void {\n this._isPaused = false;\n this._scheduleTick();\n }\n\n // ---- waiting --------------------------------------------------------------\n\n /**\n * Returns a promise that resolves when the generator completes, or\n * rejects if an unhandled error occurs during message processing.\n */\n wait(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this._exitReject = reject;\n\n this.exitWaiter.promise.then(\n () => {\n this._exitReject = null;\n resolve();\n },\n (e) => {\n this._exitReject = null;\n reject(e);\n },\n );\n });\n }\n\n // ---- child messages -------------------------------------------------------\n\n private fromChild(msg: InMessage): void {\n if (msg.type === \"EXIT\") {\n this.children = this.children.filter(\n (p) => p.id !== (msg as unknown as ExitMessage).pid,\n );\n }\n this.send(msg);\n }\n}\n\n// ---- spawnAsync -------------------------------------------------------------\n\n/**\n * Spawn a new async process. Accepts both sync and async process\n * functions — sync ones are automatically wrapped with {@link asyncify}.\n */\nexport function spawnAsync<\n Args,\n State,\n InMessage extends Message = Message,\n OutMessage extends Message = ExitMessage,\n>(\n fn: AsyncProcessFn<Args, State, InMessage, OutMessage>,\n pname: string,\n toParent?: ProcessMessageCb<OutMessage>,\n): (args: Args) => AsyncProcess<Args, State, InMessage, OutMessage> {\n return (args: Args) => {\n const proc = new AsyncProcess<Args, State, InMessage, OutMessage>(\n fn,\n pname,\n toParent,\n );\n proc.start(args);\n return proc;\n };\n}\n","import type { ProcessFn, AsyncProcessFn, Message } from \"./types.js\"\n\nexport function asyncify<A, S, IM extends Message, OM extends Message>(\n fn: ProcessFn<A, S, IM, OM>,\n): AsyncProcessFn<A, S, IM, OM> {\n return async function* (ctx, args) {\n yield* fn(ctx, args) as any\n }\n}\n","import { AsyncProcess } from \"./process.async.js\";\nimport { asyncify } from \"./adapters.js\";\nimport type { Message, ExitMessage, ProcessFn } from \"./types.js\";\n\nexport type { Message, ProcessFn, ProcessCtx } from \"./types.js\";\nexport { runDispatch } from \"./util.js\";\n\nexport function spawn<\n A,\n S,\n IM extends Message = Message,\n OM extends Message = ExitMessage,\n>(\n fn: ProcessFn<A, S, IM, OM>,\n pname: string,\n tp?: (m: OM) => void,\n): (a: A) => Process<A, S, IM, OM> {\n return (a: A) => new Process(fn, pname, tp).start(a) as Process<A, S, IM, OM>;\n}\n\nclass Process<\n A,\n S,\n IM extends Message,\n OM extends Message,\n> extends AsyncProcess<A, S, IM, OM> {\n constructor(\n fn: ProcessFn<A, S, IM, OM>,\n pname: string,\n tp?: (m: OM) => void,\n ) {\n super(asyncify(fn), pname, tp);\n }\n\n start(a: A): this {\n super.start(a);\n return this;\n }\n tick(): Promise<void> {\n return super._tick();\n }\n}\n\nexport { Process };\n","/**\n * Posipaki — Erlang-inspired lightweight actor processes built on\n * generator functions. Processes communicate via message-passing,\n * can fork children, and expose their state reactively.\n *\n * @module\n */\n\nimport { Process, spawn } from \"./process\"\nimport { runDispatch } from \"./util\"\nimport { AsyncProcess, spawnAsync, runDispatchAsync } from \"./process.async\"\nimport { asyncify } from \"./adapters\"\n\nexport { Process, spawn, runDispatch }\nexport { AsyncProcess, spawnAsync, runDispatchAsync, asyncify }\n\nexport type {\n Message, ExitMessage, ProcessFn, ProcessCtx,\n AsyncProcessFn, PipeState, SupervisorState,\n} from \"./types\"\n"],"mappings":";;;;;;;AA8BA,gBAAuB,iBACrB,MACA,IACA,gBAAyB,OACzB,aAAa,OACkB;CAC/B,IAAI;CACJ,OAAO,CAAC,QAAQ,GAAG;EACjB,MAAM,MAAM;EACZ,SAAS,YAAY,OAAO,MAAM,QAAQ,GAAG;EAC7C,MAAM,GAAG,GAAG;CACd;AACF;AAMA,MAAM,aAAa;;;;;;;;;AAUnB,IAAa,eAAb,MAAa,aAKX;CAoBA,YACE,IACA,OACA,UACA;iBAjBgE;gBAC/B,CAAC;kBACI;kBAEtC,CAAC;qBACoC,CAAC;mBAEX;yBACM;qBACkB;EASnD,KAAK,aAAa;EAClB,KAAK,QAAQ;EACb,KAAK,WAAW,YAAa;EAC7B,KAAK,KAAK,OAAO,KAAK;EACtB,KAAK,QAAQ;EACb,KAAK,aAAa,WAAW;EAC7B,KAAK,SAAS,WAAW;EACzB,KAAK,gBAAgB,KAAK,OAAO;CACnC;;CAGA,QAAuB;EACrB,OAAO,KAAK,OAAO;CACrB;;;;;CAQA,MAAM,MAAkB;EACtB,MAAM,MAAyC;GAC7C,OAA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;IACL,KAAK,cAAc;IACnB,OAAO,CAAC;GACV,CACF;EACF,CAAC;CACH;CAIA,UAAkB,KAAsB;EACtC,IAAI,IAAI,SAAS,QACf,KAAK,WAAW,KAAK,SAAS,QAC3B,MAAM,EAAE,OAAQ,IAA+B,GAClD;EAEF,KAAK,KAAK,GAAG;CACf;AACF;;;;;AAQA,SAAgB,WAMd,IACA,OACA,UACkE;CAClE,QAAQ,SAAe;EACrB,MAAM,OAAO,IAAI,aACf,IACA,OACA,QACF;EACA,KAAK,MAAM,IAAI;EACf,OAAO;CACT;AACF;;;ACpVA,SAAgB,SACd,IAC8B;CAC9B,OAAO,iBAAiB,KAAK,MAAM;EACjC,OAAO,GAAG,KAAK,IAAI;CACrB;AACF;;;ACDA,SAAgB,MAMd,IACA,OACA,IACiC;CACjC,QAAQ,MAAS,IAAI,QAAQ,IAAI,OAAO,EAAE,EAAE,MAAM,CAAC;AACrD;AAEA,IAAM,UAAN,cAKU,aAA2B;CACnC,YACE,IACA,OACA,IACA;EACA,MAAM,SAAS,EAAE,GAAG,OAAO,EAAE;CAC/B;CAEA,MAAM,GAAY;EAChB,MAAM,MAAM,CAAC;EACb,OAAO;CACT;CACA,OAAsB;EACpB,OAAO,MAAM,MAAM;CACrB;AACF"}
package/dist/pipe.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { c as ExitMessage, f as ProcessFn, l as Message } from "./process-jEWRVEFG.js";
2
+
3
+ //#region src/pipe.d.ts
4
+ /**
5
+ * State yielded by the pipe process. `params` starts as a copy of the
6
+ * initial args and is updated after each child exits by merging the
7
+ * child's `state.result` into it.
8
+ */
9
+ interface PipeState<Params, Result> {
10
+ params: Params | null;
11
+ result: Result | null;
12
+ running: boolean;
13
+ }
14
+ /**
15
+ * Chain process functions so each runs after the previous one exits.
16
+ * The `.state.result` of each completed child is spread into the params
17
+ * of the next.
18
+ */
19
+ declare function pipe<Params, Result>(fns: ProcessFn<Params, any, any, any>[]): ProcessFn<Params, PipeState<Params, Result>, Message, Message | ExitMessage>;
20
+ //#endregion
21
+ export { PipeState, pipe };
22
+ //# sourceMappingURL=pipe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipe.d.ts","names":[],"sources":["../src/pipe.ts"],"mappings":";;;AAWA;;;;;AAAA,UAAiB,SAAA;EACf,MAAA,EAAQ,MAAA;EACR,MAAA,EAAQ,MAAM;EACd,OAAA;AAAA;;;AAAO;AACR;;iBAOQ,IAAA,iBACP,GAAA,EAAK,SAAA,CAAU,MAAA,qBACd,SAAA,CACD,MAAA,EACA,SAAA,CAAU,MAAA,EAAQ,MAAA,GAClB,OAAA,EACA,OAAA,GAAU,WAAA"}
package/dist/pipe.js ADDED
@@ -0,0 +1,49 @@
1
+ import { i as runDispatch } from "./util-Cw64MseZ.js";
2
+ //#region src/pipe.ts
3
+ /**
4
+ * Chain process functions so each runs after the previous one exits.
5
+ * The `.state.result` of each completed child is spread into the params
6
+ * of the next.
7
+ */
8
+ function pipe(fns) {
9
+ return function* ({ pname, fork }, params) {
10
+ const state = {
11
+ params: { ...params },
12
+ result: null,
13
+ running: false
14
+ };
15
+ yield state;
16
+ const queue = [...fns];
17
+ let task;
18
+ function spawnNext() {
19
+ const fn = queue.shift();
20
+ task = fork(fn, `${pname} [${fn.name || "<anonymous>"}]`)(state.params);
21
+ }
22
+ function hasNext() {
23
+ return queue.length > 0;
24
+ }
25
+ spawnNext();
26
+ state.running = hasNext();
27
+ yield* runDispatch(pname, (msg) => {
28
+ if (msg.type === "STOP") {
29
+ state.params = null;
30
+ state.running = false;
31
+ return;
32
+ }
33
+ if (msg.type === "EXIT" && msg.pid === task.id) if (hasNext()) {
34
+ state.params = {
35
+ ...state.params,
36
+ ...task.state?.result
37
+ };
38
+ spawnNext();
39
+ } else {
40
+ state.running = false;
41
+ state.result = task.state?.result;
42
+ }
43
+ }, () => !state.running, true);
44
+ };
45
+ }
46
+ //#endregion
47
+ export { pipe };
48
+
49
+ //# sourceMappingURL=pipe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipe.js","names":[],"sources":["../src/pipe.ts"],"sourcesContent":["import { runDispatch } from \"./util.js\";\nimport type { ExitMessage } from \"./util.js\";\nimport type { ProcessFn, ProcessCtx } from \"./process.js\";\nimport { Process } from \"./process.js\";\nimport type { Message } from \"./types.js\";\n\n/**\n * State yielded by the pipe process. `params` starts as a copy of the\n * initial args and is updated after each child exits by merging the\n * child's `state.result` into it.\n */\nexport interface PipeState<Params, Result> {\n params: Params | null;\n result: Result | null;\n running: boolean;\n}\n\n/**\n * Chain process functions so each runs after the previous one exits.\n * The `.state.result` of each completed child is spread into the params\n * of the next.\n */\nfunction pipe<Params, Result>(\n fns: ProcessFn<Params, any, any, any>[],\n): ProcessFn<\n Params,\n PipeState<Params, Result>,\n Message,\n Message | ExitMessage\n> {\n return function* (\n { pname, fork }: ProcessCtx<Message, Message | ExitMessage>,\n params: Params,\n ) {\n const state: PipeState<Params, Result> = {\n params: { ...params },\n result: null,\n running: false,\n };\n yield state;\n\n const queue = [...fns];\n let task: Process<any, any, any, any>;\n\n function spawnNext(): void {\n const fn = queue.shift()!;\n task = fork(\n fn,\n `${pname} [${fn.name || \"<anonymous>\"}]`,\n )(state.params as Params);\n }\n\n function hasNext(): boolean {\n return queue.length > 0;\n }\n\n spawnNext();\n state.running = hasNext();\n\n yield* runDispatch<Message | ExitMessage>(\n pname,\n (msg) => {\n if (msg.type === \"STOP\") {\n state.params = null;\n state.running = false;\n return;\n }\n\n if (msg.type === \"EXIT\" && (msg as ExitMessage).pid === task.id) {\n if (hasNext()) {\n state.params = {\n ...state.params!,\n ...task.state?.result,\n } as Params;\n spawnNext();\n } else {\n state.running = false;\n state.result = task.state?.result as Result;\n }\n }\n },\n () => !state.running,\n true,\n );\n };\n}\n\nexport { pipe };\n"],"mappings":";;;;;;;AAsBA,SAAS,KACP,KAMA;CACA,OAAO,WACL,EAAE,OAAO,QACT,QACA;EACA,MAAM,QAAmC;GACvC,QAAQ,EAAE,GAAG,OAAO;GACpB,QAAQ;GACR,SAAS;EACX;EACA,MAAM;EAEN,MAAM,QAAQ,CAAC,GAAG,GAAG;EACrB,IAAI;EAEJ,SAAS,YAAkB;GACzB,MAAM,KAAK,MAAM,MAAM;GACvB,OAAO,KACL,IACA,GAAG,MAAM,IAAI,GAAG,QAAQ,cAAc,EACxC,EAAE,MAAM,MAAgB;EAC1B;EAEA,SAAS,UAAmB;GAC1B,OAAO,MAAM,SAAS;EACxB;EAEA,UAAU;EACV,MAAM,UAAU,QAAQ;EAExB,OAAO,YACL,QACC,QAAQ;GACP,IAAI,IAAI,SAAS,QAAQ;IACvB,MAAM,SAAS;IACf,MAAM,UAAU;IAChB;GACF;GAEA,IAAI,IAAI,SAAS,UAAW,IAAoB,QAAQ,KAAK,IAC3D,IAAI,QAAQ,GAAG;IACb,MAAM,SAAS;KACb,GAAG,MAAM;KACT,GAAG,KAAK,OAAO;IACjB;IACA,UAAU;GACZ,OAAO;IACL,MAAM,UAAU;IAChB,MAAM,SAAS,KAAK,OAAO;GAC7B;EAEJ,SACM,CAAC,MAAM,SACb,IACF;CACF;AACF"}
@@ -0,0 +1,147 @@
1
+ //#region src/types.d.ts
2
+ /**
3
+ * Public API types for Posipaki.
4
+ *
5
+ * @module
6
+ */
7
+ /** Base message type. All messages must include a `type` field
8
+ * for discrimination in reducers. */
9
+ interface Message {
10
+ type: string;
11
+ }
12
+ /** Message emitted by a process to its parent when it terminates. */
13
+ type ExitMessage = {
14
+ type: "EXIT";
15
+ pid: symbol;
16
+ };
17
+ type ProcessFn<Args, State, InMessage extends Message, OutMessage extends Message> = (ctx: ProcessCtx<InMessage, OutMessage>, args: Args) => Generator<State | null, void, InMessage>;
18
+ type AsyncProcessFn<Args, State, InMessage extends Message, OutMessage extends Message> = (ctx: ProcessCtx<InMessage, OutMessage>, args: Args) => AsyncGenerator<State | null, void, InMessage>;
19
+ type ProcessMessageCb$1<M> = (msg: M) => void;
20
+ /** Fork a child process. Takes a ProcessFn and a name, returns a
21
+ * curried function that accepts the child's initial args. */
22
+ type Fork<_IM extends Message, _OM extends Message> = <CA, CS, CIM extends Message, COM extends Message>(fn: ProcessFn<CA, CS, CIM, COM>, pname: string) => (a: CA) => any;
23
+ /** Context injected into every running process. */
24
+ type ProcessCtx<IM extends Message, OM extends Message> = {
25
+ pname: string;
26
+ fork: Fork<IM, OM>;
27
+ send: (msg: IM) => void;
28
+ toParent: ProcessMessageCb$1<OM>;
29
+ };
30
+ /** State yielded by the pipe process. */
31
+ interface PipeState<Params, Result> {
32
+ params: Params | null;
33
+ result: Result | null;
34
+ running: boolean;
35
+ }
36
+ /** State yielded by the supervisor process. */
37
+ interface SupervisorState {
38
+ processes: any[];
39
+ phase: "wait" | "running" | "stopping";
40
+ }
41
+ //#endregion
42
+ //#region src/process.async.d.ts
43
+ type NotifyFn = () => void;
44
+ type AsyncReducer<M> = (msg: M) => Promise<void>;
45
+ type ReadyFn$1 = () => boolean;
46
+ /**
47
+ * Async equivalent of `runDispatch`. Loops, yielding `null` and feeding
48
+ * each incoming message to an `async` reducer. Exits when `readyFn()`
49
+ * returns true.
50
+ */
51
+ declare function runDispatchAsync<M>(name: string, fn: AsyncReducer<M>, readyFn?: ReadyFn$1, debugLevel?: boolean): AsyncGenerator<null, void, M>;
52
+ type ProcessMessageCb<M> = (msg: M) => void;
53
+ /**
54
+ * A process driven by an async generator. Functionally identical to
55
+ * {@link Process} but supports `await` inside reducers.
56
+ *
57
+ * Messages are processed **one at a time** — if a tick is already
58
+ * in-flight, new messages are buffered and processed when the current
59
+ * tick completes.
60
+ */
61
+ declare class AsyncProcess<Args, State, InMessage extends Message, OutMessage extends Message> {
62
+ pgenerator: AsyncProcessFn<Args, State, InMessage, OutMessage>;
63
+ pname: string;
64
+ toParent: ProcessMessageCb<OutMessage>;
65
+ id: symbol;
66
+ state: State | null;
67
+ private current;
68
+ private buffer;
69
+ private nextTick;
70
+ private children;
71
+ private subscribers;
72
+ private exitWaiter;
73
+ private _isPaused;
74
+ private _tickInProgress;
75
+ private _exitReject;
76
+ private _ready;
77
+ private _resolveReady;
78
+ constructor(fn: AsyncProcessFn<Args, State, InMessage, OutMessage>, pname: string, toParent: ProcessMessageCb<OutMessage> | undefined);
79
+ /** Promise that resolves once the initial state is available. */
80
+ ready(): Promise<void>;
81
+ /**
82
+ * Kick off the async generator. The first `yield` sets the initial
83
+ * state; for async generators this happens in a microtask.
84
+ */
85
+ start(arg0: Args): void;
86
+ /** Wrap the user's generator so EXIT/STOP logic fires on completion. */
87
+ private _watchExit;
88
+ fork<ChildArgs, ChildState, ChildIM extends Message, ChildOM extends Message>(fn: AsyncProcessFn<ChildArgs, ChildState, ChildIM, ChildOM>, pname: string): (args: ChildArgs) => AsyncProcess<ChildArgs, ChildState, ChildIM, ChildOM>;
89
+ protected _tick(): Promise<void>;
90
+ /** Call `.next()` and redirect unhandled rejections. */
91
+ private _safeNext;
92
+ private _eatResult;
93
+ /** Broadcast a message to all children. */
94
+ toAllChildren(msg: Message): void;
95
+ /** Enqueue a message. Processing is async (microtask). */
96
+ send(msg: InMessage): void;
97
+ /**
98
+ * Synchronously flush the buffer. For sync processes use {@link Process.tick};
99
+ * for async processes this is **not guaranteed** to process everything
100
+ * immediately if reducers contain `await`. Prefer `send()` + `await proc.wait()`.
101
+ */
102
+ tick(): void;
103
+ private _scheduleTick;
104
+ notify(): void;
105
+ get isListenedTo(): boolean;
106
+ subscribe(f: NotifyFn): () => void;
107
+ pause(): void;
108
+ resume(): void;
109
+ /**
110
+ * Returns a promise that resolves when the generator completes, or
111
+ * rejects if an unhandled error occurs during message processing.
112
+ */
113
+ wait(): Promise<void>;
114
+ private fromChild;
115
+ }
116
+ /**
117
+ * Spawn a new async process. Accepts both sync and async process
118
+ * functions — sync ones are automatically wrapped with {@link asyncify}.
119
+ */
120
+ declare function spawnAsync<Args, State, InMessage extends Message = Message, OutMessage extends Message = ExitMessage>(fn: AsyncProcessFn<Args, State, InMessage, OutMessage>, pname: string, toParent?: ProcessMessageCb<OutMessage>): (args: Args) => AsyncProcess<Args, State, InMessage, OutMessage>;
121
+ //#endregion
122
+ //#region src/util.d.ts
123
+ type ReducerClosure<M> = (msg: M) => void;
124
+ type ReadyFn = () => boolean;
125
+ /**
126
+ * Generator helper that loops, yielding `null` and feeding incoming
127
+ * messages to `fn` until `readyFn()` returns true. Used inside
128
+ * process generators to build the main message loop.
129
+ */
130
+ declare function runDispatch<M>(name: string, fn: ReducerClosure<M>, readyFn?: ReadyFn, debugLevel?: boolean): Generator<null, void, M>;
131
+ /**
132
+ * Wrap a process generator so that on completion it sends STOP to
133
+ * all children and EXIT to the parent. Useful for custom process
134
+ * wrappers that need lifecycle management without extending
135
+ * AsyncProcess.
136
+ */
137
+ //#endregion
138
+ //#region src/process.d.ts
139
+ declare function spawn<A, S, IM extends Message = Message, OM extends Message = ExitMessage>(fn: ProcessFn<A, S, IM, OM>, pname: string, tp?: (m: OM) => void): (a: A) => Process<A, S, IM, OM>;
140
+ declare class Process<A, S, IM extends Message, OM extends Message> extends AsyncProcess<A, S, IM, OM> {
141
+ constructor(fn: ProcessFn<A, S, IM, OM>, pname: string, tp?: (m: OM) => void);
142
+ start(a: A): this;
143
+ tick(): Promise<void>;
144
+ }
145
+ //#endregion
146
+ export { runDispatchAsync as a, ExitMessage as c, ProcessCtx as d, ProcessFn as f, AsyncProcess as i, Message as l, spawn as n, spawnAsync as o, SupervisorState as p, runDispatch as r, AsyncProcessFn as s, Process as t, PipeState as u };
147
+ //# sourceMappingURL=process-jEWRVEFG.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-jEWRVEFG.d.ts","names":[],"sources":["../src/types.ts","../src/process.async.ts","../src/util.ts","../src/process.ts"],"mappings":";;AAUA;;;;AACM;AAIN;AAJM,UADW,OAAA;EACf,IAAI;AAAA;AAMD;AAAA,KAFO,WAAA;EACV,IAAA;EACA,GAAG;AAAA;AAAA,KAKO,SAAA,gCAAyC,OAAA,qBAA4B,OAAA,KAC/E,GAAA,EAAK,UAAA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AAA,EAAM,IAAA,KAAS,YAAA,CAAa,IAAA,EAAM,KAAA,EAAO,SAAA,EAAW,UAAA;;;KCrUnD,cAAA,OAAqB,GAAA,EAAK,CAAC;AAAA,KAC3B,OAAA;AFGC;AAIN;;;;AAJM,iBEKI,WAAA,IACR,IAAA,UACA,EAAA,EAAI,cAAA,CAAe,CAAA,GACnB,OAAA,GAAS,OAAA,EACT,UAAA,aACC,SAAA,aAAsB,CAAA;AFCzB;;;;;;;;iBGfgB,KAAA,kBAGH,OAAA,GAAU,OAAA,aACV,OAAA,GAAU,WAAA,EAErB,EAAA,EAAI,SAAA,CAAU,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA,GACxB,KAAA,UACA,EAAA,IAAM,CAAA,EAAG,EAAA,aACP,CAAA,EAAG,CAAA,KAAM,OAAA,CAAQ,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA;AAAA,cAIzB,OAAA,kBAGO,OAAA,aACA,OAAA,UACH,YAAA,CAAa,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA;cAE7B,EAAA,EAAI,SAAA,CAAU,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA,GACxB,KAAA,UACA,EAAA,IAAM,CAAA,EAAG,EAAA;EAKX,KAAA,CAAM,CAAA,EAAG,CAAA;EAIT,IAAA,IAAQ,OAAA;AAAA"}
@@ -0,0 +1,45 @@
1
+ import { c as ExitMessage, d as ProcessCtx, f as ProcessFn, t as Process } from "./process-jEWRVEFG.js";
2
+
3
+ //#region src/supervisor.d.ts
4
+ type SupMsg = ExitMessage | RunMsg | StopMsg | ErrorMsg | OkMsg;
5
+ interface RunMsg {
6
+ type: "RUN";
7
+ fn: ProcessFn<any, any, any, any>;
8
+ args: any[];
9
+ pname: string;
10
+ }
11
+ interface StopMsg {
12
+ type: "STOP";
13
+ }
14
+ interface ErrorMsg {
15
+ type: "ERROR";
16
+ }
17
+ interface OkMsg {
18
+ type: "OK";
19
+ [key: string]: unknown;
20
+ }
21
+ interface SupervisorState {
22
+ processes: Process<any, any, any, any>[];
23
+ phase: "wait" | "running" | "stopping";
24
+ }
25
+ /**
26
+ * A supervisor process. Call `attach` to send it `RUN` messages —
27
+ * it will fork the given function as a child. The supervisor exits
28
+ * when it enters `'stopping'` phase (triggered by `ERROR` or `STOP`).
29
+ *
30
+ * @param wrap optional transformation applied to the state before
31
+ * each yield (e.g. `reactive` from Vue)
32
+ */
33
+ declare function supervise({
34
+ pname,
35
+ toParent,
36
+ fork
37
+ }: ProcessCtx<SupMsg, SupMsg>, wrap?: (s: SupervisorState) => SupervisorState, debugLevel?: boolean): Generator<SupervisorState | null, void, SupMsg>;
38
+ /**
39
+ * Bind a process function to a supervisor. The returned function,
40
+ * when called, sends a `RUN` message so the supervisor forks the child.
41
+ */
42
+ declare function attach<Args extends any[]>(supervisor: Process<any, any, SupMsg, SupMsg>, fn: ProcessFn<Args, any, any, any>, pname: string): (...args: Args) => void;
43
+ //#endregion
44
+ export { SupervisorState, attach, supervise };
45
+ //# sourceMappingURL=supervisor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor.d.ts","names":[],"sources":["../src/supervisor.ts"],"mappings":";;;KAMK,MAAA,GAAS,WAAA,GAAc,MAAA,GAAS,OAAA,GAAU,QAAA,GAAW,KAAA;AAAA,UAEhD,MAAA;EACR,IAAA;EACA,EAAA,EAAI,SAAS;EACb,IAAA;EACA,KAAA;AAAA;AAAA,UAGQ,OAAA;EACR,IAAI;AAAA;AAAA,UAGI,QAAA;EACR,IAAI;AAAA;AAAA,UAGI,KAAA;EACR,IAAA;EAAA,CACC,GAAW;AAAA;AAAA,UAKG,eAAA;EACf,SAAA,EAAW,OAAO;EAClB,KAAA;AAAA;;;;;;;;AApBK;iBAiCG,SAAA;EACN,KAAA;EAAO,QAAA;EAAU;AAAA,GAAQ,UAAA,CAAW,MAAA,EAAQ,MAAA,GAC9C,IAAA,IAAO,CAAA,EAAG,eAAA,KAAoB,eAAA,EAC9B,UAAA,aACC,SAAA,CAAU,eAAA,eAA8B,MAAA;;;;AAjCrC;iBAoEG,MAAA,qBACP,UAAA,EAAY,OAAA,WAAkB,MAAA,EAAQ,MAAA,GACtC,EAAA,EAAI,SAAA,CAAU,IAAA,kBACd,KAAA,eACK,IAAA,EAAM,IAAA"}
@@ -0,0 +1,53 @@
1
+ import { i as runDispatch } from "./util-Cw64MseZ.js";
2
+ //#region src/supervisor.ts
3
+ /**
4
+ * A supervisor process. Call `attach` to send it `RUN` messages —
5
+ * it will fork the given function as a child. The supervisor exits
6
+ * when it enters `'stopping'` phase (triggered by `ERROR` or `STOP`).
7
+ *
8
+ * @param wrap optional transformation applied to the state before
9
+ * each yield (e.g. `reactive` from Vue)
10
+ */
11
+ function* supervise({ pname, toParent, fork }, wrap = (a) => a, debugLevel = false) {
12
+ const state = wrap({
13
+ processes: [],
14
+ phase: "wait"
15
+ });
16
+ yield state;
17
+ yield* runDispatch(pname, (msg) => {
18
+ switch (msg.type) {
19
+ case "RUN":
20
+ fork(msg.fn, msg.pname)(...msg.args);
21
+ state.phase = "running";
22
+ break;
23
+ case "ERROR":
24
+ case "STOP":
25
+ state.phase = "stopping";
26
+ break;
27
+ case "EXIT":
28
+ state.processes = state.processes.filter((p) => p.id !== msg.pid);
29
+ break;
30
+ case "OK":
31
+ toParent(msg);
32
+ break;
33
+ }
34
+ }, () => state.phase === "stopping", debugLevel);
35
+ }
36
+ /**
37
+ * Bind a process function to a supervisor. The returned function,
38
+ * when called, sends a `RUN` message so the supervisor forks the child.
39
+ */
40
+ function attach(supervisor, fn, pname) {
41
+ return (...args) => {
42
+ supervisor.send({
43
+ type: "RUN",
44
+ fn,
45
+ args,
46
+ pname
47
+ });
48
+ };
49
+ }
50
+ //#endregion
51
+ export { attach, supervise };
52
+
53
+ //# sourceMappingURL=supervisor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor.js","names":[],"sources":["../src/supervisor.ts"],"sourcesContent":["import { runDispatch } from \"./util.js\";\nimport type { Process, ProcessFn, ProcessCtx } from \"./process.js\";\nimport type { ExitMessage } from \"./util.js\";\n\n// ---- messages ---------------------------------------------------------------\n\ntype SupMsg = ExitMessage | RunMsg | StopMsg | ErrorMsg | OkMsg;\n\ninterface RunMsg {\n type: \"RUN\";\n fn: ProcessFn<any, any, any, any>;\n args: any[];\n pname: string;\n}\n\ninterface StopMsg {\n type: \"STOP\";\n}\n\ninterface ErrorMsg {\n type: \"ERROR\";\n}\n\ninterface OkMsg {\n type: \"OK\";\n [key: string]: unknown;\n}\n\n// ---- state ------------------------------------------------------------------\n\nexport interface SupervisorState {\n processes: Process<any, any, any, any>[];\n phase: \"wait\" | \"running\" | \"stopping\";\n}\n\n// ---- supervise --------------------------------------------------------------\n\n/**\n * A supervisor process. Call `attach` to send it `RUN` messages —\n * it will fork the given function as a child. The supervisor exits\n * when it enters `'stopping'` phase (triggered by `ERROR` or `STOP`).\n *\n * @param wrap optional transformation applied to the state before\n * each yield (e.g. `reactive` from Vue)\n */\nfunction* supervise(\n { pname, toParent, fork }: ProcessCtx<SupMsg, SupMsg>,\n wrap: (s: SupervisorState) => SupervisorState = (a) => a,\n debugLevel = false,\n): Generator<SupervisorState | null, void, SupMsg> {\n const state = wrap({ processes: [], phase: \"wait\" });\n yield state;\n\n yield* runDispatch<SupMsg>(\n pname,\n (msg) => {\n switch (msg.type) {\n case \"RUN\":\n (fork as (...a: any[]) => any)(msg.fn, msg.pname)(...msg.args);\n state.phase = \"running\";\n break;\n case \"ERROR\":\n case \"STOP\":\n state.phase = \"stopping\";\n break;\n case \"EXIT\":\n state.processes = state.processes.filter((p) => p.id !== msg.pid);\n break;\n case \"OK\":\n toParent(msg);\n break;\n }\n },\n () => state.phase === \"stopping\",\n debugLevel,\n );\n}\n\n// ---- attach -----------------------------------------------------------------\n\n/**\n * Bind a process function to a supervisor. The returned function,\n * when called, sends a `RUN` message so the supervisor forks the child.\n */\nfunction attach<Args extends any[]>(\n supervisor: Process<any, any, SupMsg, SupMsg>,\n fn: ProcessFn<Args, any, any, any>,\n pname: string,\n): (...args: Args) => void {\n return (...args) => {\n supervisor.send({ type: \"RUN\", fn, args, pname } as SupMsg);\n };\n}\n\nexport { attach, supervise };\n"],"mappings":";;;;;;;;;;AA6CA,UAAU,UACR,EAAE,OAAO,UAAU,QACnB,QAAiD,MAAM,GACvD,aAAa,OACoC;CACjD,MAAM,QAAQ,KAAK;EAAE,WAAW,CAAC;EAAG,OAAO;CAAO,CAAC;CACnD,MAAM;CAEN,OAAO,YACL,QACC,QAAQ;EACP,QAAQ,IAAI,MAAZ;GACE,KAAK;IACH,KAA+B,IAAI,IAAI,IAAI,KAAK,EAAE,GAAG,IAAI,IAAI;IAC7D,MAAM,QAAQ;IACd;GACF,KAAK;GACL,KAAK;IACH,MAAM,QAAQ;IACd;GACF,KAAK;IACH,MAAM,YAAY,MAAM,UAAU,QAAQ,MAAM,EAAE,OAAO,IAAI,GAAG;IAChE;GACF,KAAK;IACH,SAAS,GAAG;IACZ;EACJ;CACF,SACM,MAAM,UAAU,YACtB,UACF;AACF;;;;;AAQA,SAAS,OACP,YACA,IACA,OACyB;CACzB,QAAQ,GAAG,SAAS;EAClB,WAAW,KAAK;GAAE,MAAM;GAAO;GAAI;GAAM;EAAM,CAAW;CAC5D;AACF"}