@tinyactors/node 0.1.0 → 0.2.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.
@@ -0,0 +1,2966 @@
1
+ /**
2
+ * tinyactors — the binding-independent core of the JavaScript API (shared by
3
+ * the Node.js N-API binding and the wasm/browser binding).
4
+ *
5
+ * An xstate-style API on top of the tinyactors SCXML actor runtime. Machines
6
+ * compile to readable SCXML: guards and actions appear by name
7
+ * (`cond="isAdult"`, `<script>track({"tag":"t"})</script>`), inline functions
8
+ * by their source, literals as JSON. Each machine keeps a registry from that
9
+ * text to the JavaScript function implementing it; when a chart is attached
10
+ * to a system the datamodel resolves every expression of the chart once, so
11
+ * evaluation is an indexed call — the index never appears in the chart.
12
+ *
13
+ * All actors of a `System` live in one native actor system. Machines are
14
+ * linked into the system image when the first actor starts; machines defined
15
+ * after that are linked into an additional segment, and segments talk
16
+ * SCXML-to-SCXML through the runtime's remote I/O processor.
17
+ *
18
+ * `native` is the procedural interface of a backend (addon.c for Node,
19
+ * web/native.mjs over the wasm module for browsers); `platform` supplies the
20
+ * clock, timers, deferral and logging.
21
+ */
22
+
23
+ import { createEcmascript } from './ecmascript.mjs';
24
+
25
+ export function createRuntime({ native, platform }) {
26
+ /* fuel per slice; yielded work continues on platform.defer. The budget adapts
27
+ * so a slice takes about SLICE_MS of wall time (backends differ in speed; in
28
+ * browsers a slice must stay well inside a frame). */
29
+ const NONE = Object.freeze([]);
30
+ const BUDGET = 10000;
31
+ const SLICE_MS = 4;
32
+
33
+ /* ---------------------------------------------------------------- creators */
34
+
35
+ function assign(assignment) {
36
+ return { type: 'xstate.assign', assignment };
37
+ }
38
+ function raise(event, options = {}) {
39
+ return { type: 'xstate.raise', event, delay: options.delay, id: options.id };
40
+ }
41
+ function sendTo(to, event, options = {}) {
42
+ return { type: 'xstate.sendTo', to, event, delay: options.delay, id: options.id };
43
+ }
44
+ function sendParent(event, options = {}) {
45
+ return { type: 'xstate.sendParent', event, delay: options.delay, id: options.id };
46
+ }
47
+ function log(value = ({ context, event }) => ({ context, event }), label) {
48
+ return { type: 'xstate.log', value, label };
49
+ }
50
+ function cancel(sendID) {
51
+ return { type: 'xstate.cancel', sendID };
52
+ }
53
+ function stateIn(stateValue) {
54
+ return { type: 'xstate.stateIn', stateValue };
55
+ }
56
+ function and(guards) {
57
+ return { type: 'xstate.and', guards };
58
+ }
59
+ function or(guards) {
60
+ return { type: 'xstate.or', guards };
61
+ }
62
+ function not(guard) {
63
+ return { type: 'xstate.not', guards: [guard] };
64
+ }
65
+
66
+ /* ------------------------------------------------------------- XML output */
67
+
68
+ const toArray = (x) => (x === undefined ? [] : Array.isArray(x) ? x : [x]);
69
+ const norm = (s) => String(s).replace(/\s+/g, ' ').trim();
70
+ const escText = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
71
+
72
+ function attrText(v) {
73
+ const s = String(v);
74
+ if (s.includes('"') && !s.includes("'")) return `'${escText(s)}'`;
75
+ return `"${escText(s).replace(/"/g, '&quot;')}"`;
76
+ }
77
+
78
+ /** el('state', { id: 'a' }, ...children) — attributes with undefined values are dropped */
79
+ function el(tag, attrs, ...children) {
80
+ return { tag, attrs: attrs || {}, children: children.flat(Infinity).filter(Boolean) };
81
+ }
82
+
83
+ function serialize(node, indent = '') {
84
+ if (typeof node === 'string') return indent + escText(node);
85
+ const attrs = Object.entries(node.attrs)
86
+ .filter(([, v]) => v !== undefined)
87
+ .map(([k, v]) => ` ${k}=${attrText(v)}`)
88
+ .join('');
89
+ const open = `${indent}<${node.tag}${attrs}`;
90
+ if (!node.children.length) return `${open}/>`;
91
+ if (node.children.length === 1 && typeof node.children[0] === 'string')
92
+ return `${open}>${escText(node.children[0])}</${node.tag}>`;
93
+ const inner = node.children.map((c) => serialize(c, indent + ' ')).join('\n');
94
+ return `${open}>\n${inner}\n${indent}</${node.tag}>`;
95
+ }
96
+
97
+ /* ---------------------------------------------------------------- compiler */
98
+
99
+ const fnIDs = new WeakMap();
100
+ let fnSeq = 0;
101
+ function fnKey(f) {
102
+ if (!fnIDs.has(f)) fnIDs.set(f, `f${++fnSeq}`);
103
+ return fnIDs.get(f);
104
+ }
105
+ const json = (v) => (v === undefined ? 'undefined' : JSON.stringify(v));
106
+ const clone = (v) => (v !== null && typeof v === 'object' ? structuredClone(v) : v);
107
+
108
+ /** A readable expression: source text, implementation, identity. */
109
+ const X = (text, fn, key) => ({ text, fn, key });
110
+ const literal = (v) => X(json(v), () => clone(v), `lit:${json(v)}`);
111
+ const userFn = (f, params) =>
112
+ X(f.toString(), (args) => f(args, params), params === undefined ? fnKey(f) : `${fnKey(f)}(${json(params)})`);
113
+ const valueOf = (v) => (typeof v === 'function' ? userFn(v) : literal(v));
114
+
115
+ /* --------------------------------------------- per-property decomposition
116
+ * A context (`{ a: 1 }` or `({ input }) => ({ a: input.a, b: [] })`) becomes
117
+ * one <data> per property, an assignment one <assign> per property. Function
118
+ * sources are split at the top-level commas of a returned object literal;
119
+ * anything else (block bodies, spreads, computed keys, methods) is opaque. */
120
+
121
+ /** Index just past the bracket/string/comment/regex starting at s[i]. */
122
+ function skip(s, i) {
123
+ const c = s[i];
124
+ if (c === '"' || c === "'") {
125
+ for (i++; i < s.length && s[i] !== c; i++) if (s[i] === '\\') i++;
126
+ return i + 1;
127
+ }
128
+ if (c === '`') {
129
+ for (i++; i < s.length && s[i] !== '`'; i++) {
130
+ if (s[i] === '\\') i++;
131
+ else if (s[i] === '$' && s[i + 1] === '{') i = skip(s, i + 1) - 1;
132
+ }
133
+ return i + 1;
134
+ }
135
+ if (c === '/' && s[i + 1] === '/') return s.indexOf('\n', i) < 0 ? s.length : s.indexOf('\n', i);
136
+ if (c === '/' && s[i + 1] === '*') return s.indexOf('*/', i) < 0 ? s.length : s.indexOf('*/', i) + 2;
137
+ if (c === '/') {
138
+ /* a regex literal (only where an operand may start), else division */
139
+ let j = i - 1;
140
+ while (j >= 0 && /\s/.test(s[j])) j--;
141
+ if (j >= 0 && !/[(,=:[!&|?{};+\-*%<>~^]/.test(s[j])) return i + 1;
142
+ for (i++; i < s.length && s[i] !== '/'; i++) {
143
+ if (s[i] === '\\') i++;
144
+ else if (s[i] === '[') while (++i < s.length && s[i] !== ']') if (s[i] === '\\') i++;
145
+ }
146
+ return i + 1;
147
+ }
148
+ const close = { '(': ')', '[': ']', '{': '}' }[c];
149
+ if (!close) return i + 1;
150
+ for (i++; i < s.length && s[i] !== close; ) i = skip(s, i);
151
+ return i + 1;
152
+ }
153
+
154
+ /** [{ key, text }] for the properties of an object literal source `{ ... }`, or null. */
155
+ function objectProps(src) {
156
+ src = src.trim();
157
+ if (src[0] !== '{' || skip(src, 0) !== src.length || src[src.length - 1] !== '}') return null;
158
+ const props = [];
159
+ const body = src.slice(1, -1);
160
+ let start = 0;
161
+ for (let i = 0; i <= body.length; ) {
162
+ if (i === body.length || body[i] === ',') {
163
+ const part = body.slice(start, i).replace(/^(\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)+/, '').trim();
164
+ if (part) {
165
+ const m = /^(?:([A-Za-z_$][\w$]*)|"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')\s*(:|$)/.exec(part);
166
+ if (!m || (m[4] !== ':' && m[1] === undefined)) return null; // spread, computed key, method
167
+ const key = m[1] !== undefined ? m[1] : m[2] !== undefined ? m[2] : m[3];
168
+ let text = m[4] === ':' ? part.slice(m[0].length) : key;
169
+ text = text.replace(/(\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)+$/, '').trim();
170
+ if (!text) return null;
171
+ props.push({ key, text: norm(text) });
172
+ }
173
+ start = ++i;
174
+ } else i = skip(body, i);
175
+ }
176
+ return props;
177
+ }
178
+
179
+ /** The returned object literal's properties of an expression-bodied arrow function, or null. */
180
+ function returnedProps(f) {
181
+ const src = f.toString().trim();
182
+ let i = 0;
183
+ if (src[0] === '(') i = skip(src, 0);
184
+ else {
185
+ const m = /^[A-Za-z_$][\w$]*/.exec(src);
186
+ if (!m) return null;
187
+ i = m[0].length;
188
+ }
189
+ const rest = src.slice(i).trimStart();
190
+ if (!rest.startsWith('=>')) return null;
191
+ const body = rest.slice(2).trim();
192
+ if (body[0] !== '(' || skip(body, 0) !== body.length) return null;
193
+ return objectProps(body.slice(1, -1));
194
+ }
195
+
196
+ /** The body of an expression-bodied arrow `({ ... }) => expr`, for display. */
197
+ function bodyText(f) {
198
+ const src = f.toString().trim();
199
+ if (src[0] !== '(') return null;
200
+ const rest = src.slice(skip(src, 0)).trimStart();
201
+ if (!rest.startsWith('=>')) return null;
202
+ const body = rest.slice(2).trim();
203
+ if (body[0] === '{') return null;
204
+ return norm(body[0] === '(' && skip(body, 0) === body.length ? body.slice(1, -1) : body);
205
+ }
206
+
207
+ /** A JS literal written as a property value (`0`, `null`, `[]`, `''`, `"x"`), as { v } or null. */
208
+ function literalText(text) {
209
+ if (text === 'undefined') return { v: undefined };
210
+ const q = /^'((?:[^'\\"]|\\.)*)'$/.exec(text);
211
+ try {
212
+ return { v: JSON.parse(q ? `"${q[1]}"` : text) };
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+
218
+ /* Picks of one computation: the first evaluates `compute` and keeps the
219
+ * result for the others (keyed by the evaluating actor), so every property
220
+ * sees the same inputs — xstate computes all of an assignment's properties
221
+ * from the previous context. Groups are evaluated contiguously by one actor. */
222
+ const pending = new Map();
223
+ function picks(compute, entries, key) {
224
+ const n = entries.length;
225
+ return entries.map(({ key: k, text }, i) => {
226
+ let fn;
227
+ if (n === 1) fn = (args, $) => objectOf(compute(args, $))[k];
228
+ else if (i === 0)
229
+ fn = (args, $) => {
230
+ const r = objectOf(compute(args, $));
231
+ pending.set(`${$.self}|${key}`, r);
232
+ return r[k];
233
+ };
234
+ else
235
+ fn = (args, $) => {
236
+ const m = `${$.self}|${key}`;
237
+ const r = pending.has(m) ? pending.get(m) : objectOf(compute(args, $));
238
+ if (i === n - 1) pending.delete(m);
239
+ return r[k];
240
+ };
241
+ return { k, x: X(text, fn, `pick:${key}:${i}/${n}`) };
242
+ });
243
+ }
244
+ function objectOf(r) {
245
+ if (r === null || typeof r !== 'object') throw new TypeError('expected an object of context properties');
246
+ return r;
247
+ }
248
+
249
+ class Compiler {
250
+ constructor() {
251
+ this.registry = new Map(); /* normalized text -> { fn, key } */
252
+ this.invokeSeq = 0;
253
+ }
254
+
255
+ /** Register an expression; returns the text to write into the chart. */
256
+ expr(x) {
257
+ const base = norm(x.text);
258
+ for (let n = 1, text = base; ; text = `${base} /* ${++n} */`) {
259
+ const e = this.registry.get(text);
260
+ if (!e) {
261
+ this.registry.set(text, { fn: x.fn, key: x.key });
262
+ return text;
263
+ }
264
+ if (e.key === x.key) return text; // same implementation: share the expression
265
+ }
266
+ }
267
+
268
+ /** Compile a machine (and, recursively, invoked child machines) to an SCXML element tree. */
269
+ machine(machine) {
270
+ const config = machine.config;
271
+ const chart = { impl: machine.implementations, nodes: new Map(), ids: new Map(), byID: new Map(), doneID: null };
272
+ if (!this.rootChart) this.rootChart = chart; // the model of the outermost machine (state values, tags)
273
+ const root = this.collect(chart, config, '', null);
274
+ root.id = machine.id;
275
+ const machineLevel = ['on', 'entry', 'exit', 'always', 'after', 'invoke'].some((k) => config[k] !== undefined);
276
+ const wrap = machineLevel || root.type === 'parallel' || !root.children.length;
277
+ if (wrap) {
278
+ let id = machine.id;
279
+ while (chart.nodes.has(id)) id = `${id}_`;
280
+ root.id = id;
281
+ }
282
+ chart.byID.set(root.id, root);
283
+ chart.root = root;
284
+ chart.wrapped = wrap;
285
+
286
+ const finals = root.children.filter((c) => c.type === 'final');
287
+ const others = root.children.filter((c) => c.type !== 'final');
288
+ const body = [];
289
+ const output = config.output;
290
+ const doneID = `${root.id}.done`;
291
+ if (wrap && root.type === 'parallel') {
292
+ // a parallel machine is done when all regions are: leave through a top-level final
293
+ body.push(this.state(chart, root, [el('transition', { event: `done.state.${root.id}`, target: doneID })]));
294
+ chart.doneID = doneID;
295
+ body.push(el('final', { id: doneID }, output !== undefined && this.donedata(valueOf(output))));
296
+ } else {
297
+ if (wrap) body.push(this.state(chart, root, [], others));
298
+ else body.push(...others.map((k) => this.state(chart, k)));
299
+ for (const f of finals) body.push(this.state(chart, f, [], undefined, output));
300
+ }
301
+ const ctx = config.context;
302
+ const initialNode = wrap ? root : this.initialChild(root);
303
+ return el(
304
+ 'scxml',
305
+ {
306
+ xmlns: 'http://www.w3.org/2005/07/scxml',
307
+ version: '1.0',
308
+ datamodel: 'xstate',
309
+ name: machine.id,
310
+ initial: initialNode.id,
311
+ },
312
+ ctx !== undefined && el('datamodel', null, this.contextData(ctx)),
313
+ body,
314
+ );
315
+ }
316
+
317
+ /** <data> per context property; an opaque factory stays one <data id="context">. */
318
+ contextData(ctx) {
319
+ const plain = ctx !== null && typeof ctx === 'object' && !Array.isArray(ctx);
320
+ const props = typeof ctx === 'function' ? returnedProps(ctx) : null;
321
+ if (plain && !('context' in ctx))
322
+ return Object.entries(ctx).map(([k, v]) => el('data', { id: k, expr: this.expr(literal(v)) }));
323
+ if (!props || props.some((p) => p.key === 'context'))
324
+ return el('data', { id: 'context', expr: this.expr(valueOf(ctx)) });
325
+ // the factory runs once per instance; each <data> shows its property's source
326
+ const computed = props.filter((p) => !literalText(p.text));
327
+ const x = new Map(picks((args) => ctx(args), computed, `ctx:${fnKey(ctx)}`).map((p) => [p.k, p.x]));
328
+ return props.map((p) => {
329
+ const lit = literalText(p.text);
330
+ const v = lit && lit.v;
331
+ return el('data', { id: p.key, expr: this.expr(lit ? X(p.text, () => clone(v), `lit:${json(v)}`) : x.get(p.key)) });
332
+ });
333
+ }
334
+
335
+ collect(chart, config, path, parent) {
336
+ const node = {
337
+ key: path.split('.').pop(),
338
+ path,
339
+ id: path,
340
+ parent,
341
+ config,
342
+ children: [],
343
+ tags: toArray(config.tags),
344
+ type: config.type || (config.states && Object.keys(config.states).length ? 'compound' : 'atomic'),
345
+ };
346
+ if (parent) {
347
+ chart.nodes.set(path, node);
348
+ chart.byID.set(path, node);
349
+ if (config.id) chart.ids.set(config.id, path);
350
+ }
351
+ for (const [k, c] of Object.entries(config.states || {}))
352
+ node.children.push(this.collect(chart, c, parent ? `${path}.${k}` : k, node));
353
+ return node;
354
+ }
355
+
356
+ initialChild(node) {
357
+ const init = node.config.initial !== undefined ? node.config.initial : node.children[0].key;
358
+ const child = node.children.find((k) => k.key === init);
359
+ if (!child) throw new Error(`initial state "${init}" not found in "${node.path || '(machine)'}"`);
360
+ return child;
361
+ }
362
+
363
+ resolveTarget(chart, node, target) {
364
+ if (target.startsWith('#')) {
365
+ const p = chart.ids.get(target.slice(1));
366
+ if (p === undefined) throw new Error(`unknown state id ${target}`);
367
+ return p;
368
+ }
369
+ const base = target.startsWith('.') ? node : node.parent || node;
370
+ const rel = target.startsWith('.') ? target.slice(1) : target;
371
+ const p = base.parent ? `${base.path}.${rel}` : rel;
372
+ if (!chart.nodes.has(p)) throw new Error(`unknown target "${target}" from "${node.path || '(machine)'}"`);
373
+ return p;
374
+ }
375
+
376
+ /* guards -> readable expressions */
377
+ guardExpr(chart, g, params) {
378
+ if (typeof g === 'function') return userFn(g, params);
379
+ if (typeof g === 'string') return this.guardExpr(chart, { type: g });
380
+ switch (g.type) {
381
+ case 'xstate.stateIn': {
382
+ let p = g.stateValue;
383
+ if (typeof p !== 'string') throw new Error('stateIn() expects a state path string');
384
+ if (p.startsWith('#')) p = this.resolveTarget(chart, chart.root, p);
385
+ return X(`In('${p}')`, (args, $) => $.in(p), `in:${p}`);
386
+ }
387
+ case 'xstate.and':
388
+ case 'xstate.or':
389
+ case 'xstate.not': {
390
+ const subs = g.guards.map((s) => this.guardExpr(chart, s));
391
+ const name = g.type.slice(7);
392
+ const fns = subs.map((s) => s.fn);
393
+ const fn =
394
+ name === 'and'
395
+ ? (args, $) => fns.every((f) => f(args, $))
396
+ : name === 'or'
397
+ ? (args, $) => fns.some((f) => f(args, $))
398
+ : (args, $) => !fns[0](args, $);
399
+ return X(`${name}(${subs.map((s) => s.text).join(', ')})`, fn, `${name}(${subs.map((s) => s.key).join(',')})`);
400
+ }
401
+ default: {
402
+ const named = chart.impl.guards && chart.impl.guards[g.type];
403
+ if (named === undefined) throw new Error(`unknown guard "${g.type}"`);
404
+ const p = g.params;
405
+ if (typeof named !== 'function') return this.guardExpr(chart, named, p);
406
+ const text = p === undefined ? g.type : `${g.type}(${json(p)})`;
407
+ return X(text, (args) => named(args, p), `guard:${text}`);
408
+ }
409
+ }
410
+ }
411
+
412
+ delayAttrs(chart, delay) {
413
+ if (delay === undefined) return {};
414
+ if (typeof delay === 'number') return { delay: `${delay}ms` };
415
+ if (typeof delay === 'function') return { delayexpr: this.expr(userFn(delay)) };
416
+ const named = chart.impl.delays && chart.impl.delays[delay];
417
+ if (named === undefined) throw new Error(`unknown delay "${delay}"`);
418
+ const fn = typeof named === 'function' ? (args) => named(args) : () => named;
419
+ return { delayexpr: this.expr(X(delay, fn, `delay:${delay}`)) };
420
+ }
421
+
422
+ donedata(x) {
423
+ return el('donedata', null, el('content', { expr: this.expr(x) }));
424
+ }
425
+
426
+ /* actions -> executable content */
427
+ actions(chart, list) {
428
+ return toArray(list).map((a) => this.action(chart, a));
429
+ }
430
+
431
+ action(chart, a, params) {
432
+ if (typeof a === 'function') return el('script', null, this.expr(userFn(a, params)));
433
+ if (typeof a === 'string') return this.action(chart, { type: a });
434
+ switch (a.type) {
435
+ case 'xstate.assign':
436
+ return this.assignAction(a.assignment, params);
437
+ case 'xstate.raise':
438
+ case 'xstate.sendTo':
439
+ case 'xstate.sendParent':
440
+ return this.sendAction(chart, a);
441
+ case 'xstate.log':
442
+ return el('log', { label: a.label, expr: this.expr(valueOf(a.value)) });
443
+ case 'xstate.cancel':
444
+ return el('cancel', { sendid: a.sendID });
445
+ default: {
446
+ const named = chart.impl.actions && chart.impl.actions[a.type];
447
+ if (named === undefined) throw new Error(`unknown action "${a.type}"`);
448
+ if (typeof named !== 'function') return this.action(chart, named, a.params);
449
+ const p = a.params;
450
+ const text = p === undefined ? a.type : `${a.type}(${json(p)})`;
451
+ return el('script', null, this.expr(X(text, (args) => named(args, p), `action:${text}`)));
452
+ }
453
+ }
454
+ }
455
+
456
+ /* assign() -> one <assign location="prop"> per property. Computed
457
+ * properties come first and are evaluated together against the previous
458
+ * context (xstate semantics); constants follow. */
459
+ assignAction(spec, params) {
460
+ const one = (k, x) => el('assign', { location: k, expr: this.expr(x) });
461
+ const pkey = params === undefined ? '' : json(params);
462
+ if (typeof spec === 'function') {
463
+ const props = returnedProps(spec);
464
+ if (!props || !props.length) return el('assign', { location: 'context', expr: this.expr(userFn(spec, params)) });
465
+ const computed = props.filter((p) => !literalText(p.text));
466
+ const consts = props.filter((p) => literalText(p.text));
467
+ return [
468
+ picks((args) => spec(args, params), computed, `as:${fnKey(spec)}${pkey}`).map((p) => one(p.k, p.x)),
469
+ consts.map((p) => {
470
+ const { v } = literalText(p.text);
471
+ return one(p.key, X(p.text, () => clone(v), `lit:${json(v)}`));
472
+ }),
473
+ ];
474
+ }
475
+ const keys = Object.keys(spec);
476
+ const fns = keys.filter((k) => typeof spec[k] === 'function');
477
+ const consts = keys.filter((k) => typeof spec[k] !== 'function');
478
+ const shown = (f) => bodyText(f) || f.toString();
479
+ let computed;
480
+ if (fns.length === 1) {
481
+ const f = spec[fns[0]];
482
+ computed = [{ k: fns[0], x: X(shown(f), (args) => f(args, params), params === undefined ? fnKey(f) : `${fnKey(f)}(${pkey})`) }];
483
+ } else {
484
+ const all = (args) => Object.fromEntries(fns.map((k) => [k, spec[k](args, params)]));
485
+ const key = `as:{${fns.map((k) => `${k}=${fnKey(spec[k])}`).join(',')}}${pkey}`;
486
+ computed = picks(all, fns.map((k) => ({ key: k, text: shown(spec[k]) })), key);
487
+ }
488
+ return [computed.map((p) => one(p.k, p.x)), consts.map((k) => one(k, literal(spec[k])))];
489
+ }
490
+
491
+ sendAction(chart, a) {
492
+ const ev = a.event;
493
+ const attrs = {};
494
+ let content = null;
495
+ if (typeof ev === 'function') {
496
+ const text = this.expr(userFn(ev));
497
+ attrs.eventexpr = text; // an event object stands for its type
498
+ content = el('content', { expr: text });
499
+ } else {
500
+ const obj = typeof ev === 'string' ? { type: ev } : ev;
501
+ attrs.event = obj.type;
502
+ if (Object.keys(obj).length > 1) content = el('content', { expr: this.expr(literal(obj)) });
503
+ }
504
+ if (a.type === 'xstate.raise') {
505
+ if (a.delay === undefined && a.id === undefined && !content) return el('raise', { event: attrs.event });
506
+ if (a.delay === undefined) attrs.target = '#_internal';
507
+ } else if (a.type === 'xstate.sendParent') {
508
+ attrs.target = '#_parent';
509
+ } else if (typeof a.to === 'string') {
510
+ attrs.target = `#_${a.to}`;
511
+ } else if (typeof a.to === 'function') {
512
+ const f = a.to;
513
+ attrs.targetexpr = this.expr(X(f.toString(), (args) => addressOf(f(args)), `to:${fnKey(f)}`));
514
+ } else if (a.to instanceof ActorRef) {
515
+ const ref = a.to;
516
+ attrs.targetexpr = this.expr(X(`ref(${json(ref.address)})`, () => ref.address, `to:ref:${ref.address}`));
517
+ } else if (a.to instanceof Actor) {
518
+ const ref = a.to;
519
+ const name = ref.options.systemID || ref.id;
520
+ attrs.targetexpr = this.expr(X(`system.get(${json(name)})`, () => addressOf(ref), `to:actor:${name}`));
521
+ } else {
522
+ throw new Error('sendTo() expects a child id, an actor, or a function returning one');
523
+ }
524
+ Object.assign(attrs, this.delayAttrs(chart, a.delay));
525
+ if (a.id !== undefined) attrs.id = a.id;
526
+ return el('send', attrs, content);
527
+ }
528
+
529
+ transitions(chart, node, event, spec) {
530
+ return toArray(spec).map((t) => {
531
+ if (typeof t === 'string') t = { target: t };
532
+ let targets = toArray(t.target).map((x) => this.resolveTarget(chart, node, x));
533
+ // xstate v5: transitions to the source itself do not re-enter by default
534
+ if (!t.reenter && targets.length === 1 && targets[0] === node.path) targets = [];
535
+ // targets inside the source do not exit it (SCXML type="internal"); for the
536
+ // machine root that is everything except its finals, which live outside it
537
+ const inside =
538
+ targets.length &&
539
+ targets.every((p) =>
540
+ node === chart.root
541
+ ? !(chart.nodes.get(p).parent === node && chart.nodes.get(p).type === 'final')
542
+ : p.startsWith(`${node.path}.`),
543
+ );
544
+ return el(
545
+ 'transition',
546
+ {
547
+ event: event === null ? undefined : event,
548
+ cond: t.guard === undefined ? undefined : this.expr(this.guardExpr(chart, t.guard)),
549
+ target: targets.length ? targets.join(' ') : undefined,
550
+ type: inside && !t.reenter ? 'internal' : undefined,
551
+ },
552
+ this.actions(chart, t.actions),
553
+ );
554
+ });
555
+ }
556
+
557
+ /** <state>/<parallel>/<final>/<history> for a node; `kids` overrides the children. */
558
+ state(chart, node, extra = [], kids = node.children, machineOutput) {
559
+ const c = node.config;
560
+ const tag = { parallel: 'parallel', final: 'final', history: 'history' }[node.type] || 'state';
561
+ if (tag === 'history') {
562
+ const t = c.target ? this.resolveTarget(chart, node, c.target) : node.parent.children.find((k) => k !== node).path;
563
+ return el('history', { id: node.id, type: c.history === 'deep' ? 'deep' : 'shallow' }, el('transition', { target: t }));
564
+ }
565
+ const attrs = { id: node.id };
566
+ if (tag === 'state' && kids.length) attrs.initial = this.initialChild(node).id;
567
+ // delayed transitions: send on entry, cancel on exit
568
+ const afterEntries = [];
569
+ const afterExits = [];
570
+ const afterTransitions = [];
571
+ for (const [delay, spec] of Object.entries(c.after || {})) {
572
+ const ev = `xstate.after.${delay}.${node.id}`;
573
+ const d = /^\d+(\.\d+)?$/.test(delay) ? this.delayAttrs(chart, Number(delay)) : this.delayAttrs(chart, delay);
574
+ afterEntries.push(el('send', { event: ev, ...d, id: ev }));
575
+ afterExits.push(el('cancel', { sendid: ev }));
576
+ afterTransitions.push(this.transitions(chart, node, ev, spec));
577
+ }
578
+ const entry = [this.actions(chart, c.entry), afterEntries].flat(Infinity);
579
+ const exit = [afterExits, this.actions(chart, c.exit)].flat(Infinity);
580
+ const body = [];
581
+ if (entry.length) body.push(el('onentry', null, entry));
582
+ if (exit.length) body.push(el('onexit', null, exit));
583
+ if (tag !== 'final') {
584
+ for (const [event, spec] of Object.entries(c.on || {})) body.push(this.transitions(chart, node, event, spec));
585
+ body.push(afterTransitions);
586
+ if (c.always) body.push(this.transitions(chart, node, null, c.always));
587
+ for (const inv of toArray(c.invoke)) body.push(this.invoke(chart, node, inv));
588
+ }
589
+ body.push(extra);
590
+ if (tag === 'final') {
591
+ const own = c.output !== undefined ? valueOf(c.output) : null;
592
+ if (machineOutput !== undefined) {
593
+ // the machine's output sees the final state's output as event.output
594
+ const out = valueOf(machineOutput);
595
+ const fn = own
596
+ ? (args, $) => out.fn({ ...args, event: { type: `xstate.done.state.${node.id}`, output: own.fn(args, $) } }, $)
597
+ : out.fn;
598
+ body.push(this.donedata(X(out.text, fn, own ? `${out.key}<-${own.key}` : out.key)));
599
+ } else if (own) {
600
+ body.push(this.donedata(own));
601
+ }
602
+ }
603
+ for (const k of kids) body.push(this.state(chart, k));
604
+ return el(tag, attrs, body);
605
+ }
606
+
607
+ invoke(chart, node, inv) {
608
+ const id = inv.id || `${node.id || 'machine'}.invoke${this.invokeSeq++}`;
609
+ let src = inv.src;
610
+ if (typeof src === 'string') {
611
+ const named = chart.impl.actors && chart.impl.actors[src];
612
+ if (!named) throw new Error(`unknown actor "${src}"`);
613
+ src = named;
614
+ }
615
+ if (!src || !src.config) throw new Error('invoke.src must be a machine created by createMachine()');
616
+ const child = this.machine(src);
617
+ return [
618
+ el(
619
+ 'invoke',
620
+ { id },
621
+ inv.input !== undefined && el('param', { name: 'input', expr: this.expr(valueOf(inv.input)) }),
622
+ el('content', null, child),
623
+ ),
624
+ inv.onDone ? this.transitions(chart, node, `done.invoke.${id}`, inv.onDone) : null,
625
+ ];
626
+ }
627
+ }
628
+
629
+ /* ----------------------------------------------------------------- machines */
630
+
631
+ class StateMachine {
632
+ constructor(config, implementations = {}) {
633
+ this.config = config;
634
+ this.implementations = {
635
+ actions: { ...(implementations.actions || {}) },
636
+ guards: { ...(implementations.guards || {}) },
637
+ delays: { ...(implementations.delays || {}) },
638
+ actors: { ...(implementations.actors || {}) },
639
+ };
640
+ this.id = config.id || 'machine';
641
+ this._compiled = null;
642
+ registry.add(this);
643
+ }
644
+ /** A copy with additional/overridden implementations (like xstate's machine.provide). */
645
+ provide(implementations) {
646
+ const merged = {};
647
+ for (const k of ['actions', 'guards', 'delays', 'actors'])
648
+ merged[k] = { ...this.implementations[k], ...((implementations || {})[k] || {}) };
649
+ return new StateMachine(this.config, merged);
650
+ }
651
+ /** The generated SCXML document. */
652
+ toSCXML() {
653
+ return this._compile().xml;
654
+ }
655
+ _compile() {
656
+ if (!this._compiled) {
657
+ const c = new Compiler();
658
+ const xml = serialize(c.machine(this));
659
+ this._compiled = { xml, registry: c.registry, chart: c.rootChart };
660
+ }
661
+ return this._compiled;
662
+ }
663
+ }
664
+
665
+ /** Machines created so far; the default system links them all at once. */
666
+ const registry = new Set();
667
+
668
+ function createMachine(config, implementations) {
669
+ return new StateMachine(config, implementations);
670
+ }
671
+
672
+ function setup(implementations = {}) {
673
+ return {
674
+ createMachine: (config) => createMachine(config, implementations),
675
+ };
676
+ }
677
+
678
+ /* ------------------------------------------------------- SCXML documents
679
+ * fromSCXML(xml, { id, documents }) runs a W3C SCXML document as actor
680
+ * logic. Its datamodel attribute picks the semantics: "ecmascript"
681
+ * (SCXML B.2, bindings/shared/ecmascript.mjs) or "null". `documents` maps
682
+ * invoke src names to further SCXML documents linked alongside. Events sent
683
+ * to such an actor: _event.name is `type`, _event.data the event's `data`
684
+ * property, else the event's other properties (if any). The snapshot's
685
+ * context is the datamodel's variables; its value the active states (by id)
686
+ * as a nested state value. */
687
+ const STATE_KINDS = ['atomic', 'compound', 'parallel', 'final', 'history', 'history'];
688
+
689
+ class SCXMLLogic {
690
+ constructor(xml, options = {}) {
691
+ if (typeof xml !== 'string') throw new TypeError('fromSCXML(xml): xml must be a string');
692
+ this.xml = xml;
693
+ this.documents = options.documents || {};
694
+ const m = /<scxml\b[^>]*?\sname\s*=\s*(["'])(.*?)\1/.exec(xml);
695
+ this.id = options.id || (m && m[2]) || 'scxml';
696
+ this.scxml = true;
697
+ this._compiled = null;
698
+ }
699
+ toSCXML() {
700
+ return this.xml;
701
+ }
702
+ /* compiled once on its own: validates the document and yields the state tree */
703
+ _compile() {
704
+ if (this._compiled) return this._compiled;
705
+ /* SCXML documents become charts of the image; every document (also e.g.
706
+ * <data src> text) is available to src="..." at compile time */
707
+ const files = Object.entries(this.documents).map(([name, xml]) => ({ name, xml }));
708
+ const docs = files.filter((f) => /<scxml[\s>]/.test(f.xml));
709
+ const image = native.compile([{ name: '__main', xml: this.xml }, ...docs], files);
710
+ const main = native.chartIndex(image, '__main');
711
+ const dm = native.imageInfo(image).charts[main].datamodel;
712
+ if (dm && dm !== 'ecmascript' && dm !== 'null') throw new Error(`fromSCXML: the "${dm}" datamodel is not supported (use "ecmascript" or "null")`);
713
+ const states = native.states(image, main);
714
+ const nodes = states.map((s) => ({ id: s.id, key: s.id, type: STATE_KINDS[s.kind] || 'atomic', children: [], tags: [] }));
715
+ states.forEach((s, i) => s.parent >= 0 && nodes[s.parent].children.push(nodes[i]));
716
+ const byPath = new Map();
717
+ (function walk(n, prefix) {
718
+ for (const k of n.children) {
719
+ const p = prefix ? `${prefix}.${k.key}` : k.key;
720
+ byPath.set(p, k);
721
+ walk(k, p);
722
+ }
723
+ })(nodes[0], '');
724
+ this._compiled = { xml: this.xml, registry: new Map(), chart: { root: nodes[0], nodes: byPath }, sources: docs, files };
725
+ return this._compiled;
726
+ }
727
+ _eventData(event) {
728
+ if (event.data !== undefined) return event.data;
729
+ const { type, ...rest } = event;
730
+ return Object.keys(rest).length ? rest : undefined;
731
+ }
732
+ }
733
+
734
+ function fromSCXML(xml, options) {
735
+ return new SCXMLLogic(xml, options);
736
+ }
737
+
738
+ /* --------------------------------------------------------- system images
739
+ * A compiled system image (a <system> manifest: charts and the actors to
740
+ * boot), from compileSystem() or loaded as bytes (loadImage(), e.g. what
741
+ * the `tac` compiler wrote). system.boot(image) starts its actors;
742
+ * image.chart(name) is logic for createActor. */
743
+ const toNodes = (states) => {
744
+ const nodes = states.map((s) => ({ id: s.id, key: s.id, type: STATE_KINDS[s.kind] || 'atomic', children: [], tags: [] }));
745
+ states.forEach((s, i) => s.parent >= 0 && nodes[s.parent].children.push(nodes[i]));
746
+ const byPath = new Map();
747
+ (function walk(n, prefix) {
748
+ for (const k of n.children) {
749
+ const p = prefix ? `${prefix}.${k.key}` : k.key;
750
+ byPath.set(p, k);
751
+ walk(k, p);
752
+ }
753
+ })(nodes[0], '');
754
+ return { root: nodes[0], nodes: byPath };
755
+ };
756
+
757
+ class ImageChart {
758
+ constructor(image, chart, name) {
759
+ this.image = image;
760
+ this.id = name;
761
+ this.scxml = true;
762
+ this._index = chart;
763
+ this._compiled = null;
764
+ }
765
+ _compile() {
766
+ if (!this._compiled) this._compiled = { registry: new Map(), chart: toNodes(native.states(this.image._native, this._index)) };
767
+ return this._compiled;
768
+ }
769
+ _eventData(event) {
770
+ return SCXMLLogic.prototype._eventData.call(this, event);
771
+ }
772
+ }
773
+
774
+ class SystemImage {
775
+ constructor(nat) {
776
+ this._native = nat;
777
+ const info = native.imageInfo(nat);
778
+ /** The charts: { name, src, datamodel }. */
779
+ this.charts = info.charts;
780
+ /** The actors system.boot() starts: { name, chart } (chart: an index into charts). */
781
+ this.actors = info.bootActors;
782
+ this._charts = info.charts.map((c, i) => new ImageChart(this, i, c.name || c.src));
783
+ }
784
+ /** The image as bytes (store it; loadImage() reads it back). */
785
+ get bytes() {
786
+ return native.imageBytes(this._native);
787
+ }
788
+ /** Actor logic for one of its charts (by <chart name>, or its src). */
789
+ chart(name) {
790
+ const i = this.charts.findIndex((c) => c.name === name || c.src === name);
791
+ if (i < 0) throw new Error(`no chart "${name}" in the image`);
792
+ return this._charts[i];
793
+ }
794
+ }
795
+
796
+ /** Compile a <system> manifest; `files` maps the src names it uses to their text. */
797
+ function compileSystem(manifest, options = {}) {
798
+ const files = Object.entries(options.files || {}).map(([name, xml]) => ({ name, xml }));
799
+ return new SystemImage(native.compileSystem(manifest, files));
800
+ }
801
+
802
+ /** A compiled image from bytes (compileSystem(...).bytes, or the tac compiler's output). */
803
+ function loadImage(bytes) {
804
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('loadImage(bytes: Uint8Array)');
805
+ return new SystemImage(native.openImage(bytes));
806
+ }
807
+
808
+ /* ------------------------------------------------------------ actor systems */
809
+
810
+ function addressOf(ref) {
811
+ if (typeof ref === 'string') return `#_${ref}`; // child invoke id
812
+ if (ref instanceof Actor) {
813
+ if (!ref._live) throw new Error(`actor "${ref.id}" is not running`);
814
+ return `${ref.system._base}#_scxml_${ref._session}`;
815
+ }
816
+ if (ref instanceof ActorRef) return ref.address;
817
+ throw new Error('cannot address this actor');
818
+ }
819
+
820
+ /** A reference to an actor anywhere — this system, another segment, or a
821
+ * system on the other side of a link. Sendable from host code, usable as a
822
+ * sendTo() target, and it survives being sent in events (as its address). */
823
+ class ActorRef {
824
+ constructor(system, address) {
825
+ this.system = system;
826
+ this.address = address;
827
+ const m = /@([^/]+)$/.exec(address);
828
+ this.id = m ? m[1] : address;
829
+ }
830
+ send(event) {
831
+ if (typeof event === 'string') event = { type: event };
832
+ this.system._do(() => {
833
+ this.system._hostRoute({ target: this.address, name: event.type, data: event });
834
+ this.system._pump();
835
+ });
836
+ }
837
+ toJSON() {
838
+ return { $actor: this.address };
839
+ }
840
+ }
841
+
842
+ /* ---- values across hibernation and links: tagged JSON. Keeps undefined,
843
+ * NaN/Infinity, BigInt, Date, Map, Set, RegExp, shared references and cycles;
844
+ * actors travel as their address. Functions cannot be encoded. */
845
+ /* bytes as base64 (portable: no Buffer/btoa needed) */
846
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
847
+ function toBase64(b) {
848
+ let out = '';
849
+ for (let i = 0; i < b.length; i += 3) {
850
+ const n = (b[i] << 16) | ((b[i + 1] || 0) << 8) | (b[i + 2] || 0);
851
+ out += B64[n >> 18] + B64[(n >> 12) & 63] + (i + 1 < b.length ? B64[(n >> 6) & 63] : '=') + (i + 2 < b.length ? B64[n & 63] : '=');
852
+ }
853
+ return out;
854
+ }
855
+ function fromBase64(s) {
856
+ const pad = s.endsWith('==') ? 2 : s.endsWith('=') ? 1 : 0;
857
+ const out = new Uint8Array((s.length / 4) * 3 - pad);
858
+ for (let i = 0, o = 0; i < s.length; i += 4) {
859
+ const n = (B64.indexOf(s[i]) << 18) | (B64.indexOf(s[i + 1]) << 12) | ((B64.indexOf(s[i + 2]) & 63) << 6) | (B64.indexOf(s[i + 3]) & 63);
860
+ out[o++] = n >> 16;
861
+ if (o < out.length) out[o++] = (n >> 8) & 255;
862
+ if (o < out.length) out[o++] = n & 255;
863
+ }
864
+ return out;
865
+ }
866
+
867
+ function encodeTagged(root) {
868
+ const count = new Map();
869
+ (function scan(v) {
870
+ if (v === null || typeof v !== 'object' || v instanceof Actor || v instanceof ActorRef || v instanceof Uint8Array) return;
871
+ const n = (count.get(v) || 0) + 1;
872
+ count.set(v, n);
873
+ if (n > 1) return;
874
+ if (v instanceof Map) for (const [k, x] of v) scan(k), scan(x);
875
+ else if (v instanceof Set) for (const x of v) scan(x);
876
+ else if (!(v instanceof Date) && !(v instanceof RegExp)) for (const k of Object.keys(v)) scan(v[k]);
877
+ })(root);
878
+ const ids = new Map();
879
+ let next = 0;
880
+ function enc(v) {
881
+ switch (typeof v) {
882
+ case 'undefined': return { $: 'u' };
883
+ case 'number': return Number.isFinite(v) ? v : { $: 'n', v: String(v) };
884
+ case 'bigint': return { $: 'b', v: String(v) };
885
+ case 'string': case 'boolean': return v;
886
+ case 'function': case 'symbol': throw new TypeError(`cannot encode a ${typeof v}`);
887
+ }
888
+ if (v === null) return null;
889
+ if (v instanceof Actor) return { $: 'a', v: addressOf(v) };
890
+ if (v instanceof Uint8Array) return { $: 'y', v: toBase64(v) };
891
+ if (v instanceof ActorRef) return { $: 'a', v: v.address };
892
+ if (ids.has(v)) return { $: 'r', v: ids.get(v) };
893
+ const shared = count.get(v) > 1;
894
+ const id = shared ? next++ : -1;
895
+ if (shared) ids.set(v, id);
896
+ let out;
897
+ if (v instanceof Date) out = { $: 'd', v: v.getTime() };
898
+ else if (v instanceof RegExp) out = { $: 'x', v: v.source, f: v.flags };
899
+ else if (v instanceof Map) out = { $: 'm', v: [...v].map(([k, x]) => [enc(k), enc(x)]) };
900
+ else if (v instanceof Set) out = { $: 's', v: [...v].map(enc) };
901
+ else if (Array.isArray(v)) out = shared ? { $: 'A', v: v.map(enc) } : v.map(enc);
902
+ else {
903
+ const o = {};
904
+ for (const k of Object.keys(v)) o[k] = enc(v[k]);
905
+ out = shared || '$' in v ? { $: 'o', v: o } : o;
906
+ }
907
+ if (shared) out.i = id;
908
+ return out;
909
+ }
910
+ return enc(root);
911
+ }
912
+ function decodeTagged(root, system) {
913
+ const ids = new Map();
914
+ function dec(v) {
915
+ if (v === null || typeof v !== 'object') return v;
916
+ if (Array.isArray(v)) return v.map(dec);
917
+ if (typeof v.$ !== 'string') {
918
+ const o = {};
919
+ for (const k of Object.keys(v)) o[k] = dec(v[k]);
920
+ return o;
921
+ }
922
+ let out;
923
+ switch (v.$) {
924
+ case 'u': return undefined;
925
+ case 'n': return Number(v.v);
926
+ case 'b': return BigInt(v.v);
927
+ case 'a': return system ? system.ref(v.v) : v.v;
928
+ case 'r': return ids.get(v.v);
929
+ case 'y': return fromBase64(v.v);
930
+ case 'd': out = new Date(v.v); break;
931
+ case 'x': out = new RegExp(v.v, v.f); break;
932
+ case 'm': out = new Map(); if (v.i !== undefined) ids.set(v.i, out); for (const [k, x] of v.v) out.set(dec(k), dec(x)); return out;
933
+ case 's': out = new Set(); if (v.i !== undefined) ids.set(v.i, out); for (const x of v.v) out.add(dec(x)); return out;
934
+ case 'A': out = []; if (v.i !== undefined) ids.set(v.i, out); for (const x of v.v) out.push(dec(x)); return out;
935
+ case 'o': out = {}; if (v.i !== undefined) ids.set(v.i, out); for (const k of Object.keys(v.v)) out[k] = dec(v.v[k]); return out;
936
+ default: throw new TypeError(`unknown tag ${v.$}`);
937
+ }
938
+ if (v.i !== undefined) ids.set(v.i, out);
939
+ return out;
940
+ }
941
+ return dec(root);
942
+ }
943
+ /* ---- neutral values (docs/protocol.md, "Values"): what other systems
944
+ * understand whatever their language — JSON plus {"$ref": address},
945
+ * {"$bytes": base64} and {"$": {...}} for objects with "$" keys. Lossy for
946
+ * JS (no undefined, Map, Set, Date, cycles), so links between two JS systems
947
+ * negotiate the richer "js" profile (the tagged JSON above). */
948
+ function encodeWire(root) {
949
+ const seen = new Set();
950
+ function enc(v) {
951
+ switch (typeof v) {
952
+ case 'undefined': case 'function': case 'symbol': return undefined;
953
+ case 'number': return Number.isFinite(v) ? v : null;
954
+ case 'bigint': return String(v);
955
+ case 'string': case 'boolean': return v;
956
+ }
957
+ if (v === null) return null;
958
+ if (v instanceof Actor) return { $ref: addressOf(v) };
959
+ if (v instanceof ActorRef) return { $ref: v.address };
960
+ if (ArrayBuffer.isView(v)) return { $bytes: toBase64(new Uint8Array(v.buffer, v.byteOffset, v.byteLength)) };
961
+ if (v instanceof ArrayBuffer) return { $bytes: toBase64(new Uint8Array(v)) };
962
+ if (typeof v.toJSON === 'function') return enc(v.toJSON());
963
+ if (seen.has(v)) throw new TypeError('a cyclic value is not a neutral value');
964
+ seen.add(v);
965
+ let out;
966
+ if (Array.isArray(v) || v instanceof Set) {
967
+ out = [...v].map((x) => {
968
+ const e = enc(x);
969
+ return e === undefined ? null : e;
970
+ });
971
+ } else {
972
+ const o = {};
973
+ let dollar = false;
974
+ for (const [k, x] of v instanceof Map ? [...v].map(([k, x]) => [String(k), x]) : Object.entries(v)) {
975
+ const e = enc(x);
976
+ if (e === undefined) continue;
977
+ o[k] = e;
978
+ if (k[0] === '$') dollar = true;
979
+ }
980
+ out = dollar ? { $: o } : o;
981
+ }
982
+ seen.delete(v);
983
+ return out;
984
+ }
985
+ const e = enc(root);
986
+ return e === undefined ? null : e;
987
+ }
988
+ function decodeWire(v, system) {
989
+ if (v === null || typeof v !== 'object') return v;
990
+ if (Array.isArray(v)) return v.map((x) => decodeWire(x, system));
991
+ const keys = Object.keys(v);
992
+ if (keys.length === 1) {
993
+ const x = v[keys[0]];
994
+ if (keys[0] === '$ref' && typeof x === 'string') return system ? system.ref(x) : x;
995
+ if (keys[0] === '$bytes' && typeof x === 'string') return fromBase64(x);
996
+ if (keys[0] === '$' && x && typeof x === 'object' && !Array.isArray(x)) {
997
+ const o = {};
998
+ for (const k of Object.keys(x)) o[k] = decodeWire(x[k], system);
999
+ return o;
1000
+ }
1001
+ }
1002
+ const o = {};
1003
+ for (const k of keys) o[k] = decodeWire(v[k], system);
1004
+ return o;
1005
+ }
1006
+
1007
+ const textEncoder = new TextEncoder();
1008
+ const textDecoder = new TextDecoder();
1009
+ function encodeValue(v) {
1010
+ return textEncoder.encode(JSON.stringify(encodeTagged(v)));
1011
+ }
1012
+ function decodeValue(bytes, system) {
1013
+ return decodeTagged(JSON.parse(textDecoder.decode(bytes)), system);
1014
+ }
1015
+ const sameBytes = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
1016
+
1017
+ /** A hibernation store kept in memory (tests, or as a write-behind cache). */
1018
+ function createMemoryStore() {
1019
+ const m = new Map();
1020
+ return {
1021
+ get: (key) => m.get(key),
1022
+ set: (key, value) => void m.set(key, value),
1023
+ delete: (key) => void m.delete(key),
1024
+ get size() {
1025
+ return m.size;
1026
+ },
1027
+ };
1028
+ }
1029
+
1030
+ /* ---------------------------------------------------------------- addresses
1031
+ * docs/protocol.md, "Addresses" — the JS twin of include/tinyactors/address.h, held
1032
+ * to the same vectors (tests/conformance/addresses.json). Session ids are
1033
+ * BigInt: exact up to 2^64-1. */
1034
+ const SYSTEM_ID = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
1035
+ const MAX_SESSION = (1n << 64n) - 1n;
1036
+ function systemIDValid(id) {
1037
+ return typeof id === 'string' && SYSTEM_ID.test(id);
1038
+ }
1039
+ function parseLocal(local) {
1040
+ let m = /^#_scxml_([1-9][0-9]{0,19})$/.exec(local);
1041
+ if (m) {
1042
+ const session = BigInt(m[1]);
1043
+ return session <= MAX_SESSION ? { kind: 'session', session } : null;
1044
+ }
1045
+ m = /^@((?:[A-Za-z0-9\-._~]|%[0-9A-Fa-f]{2})+)$/.exec(local);
1046
+ if (!m) return null;
1047
+ try {
1048
+ return { kind: 'name', name: decodeURIComponent(m[1]), encoded: m[1] };
1049
+ } catch {
1050
+ return null; /* escapes that are not UTF-8 */
1051
+ }
1052
+ }
1053
+ function parseAddress(text) {
1054
+ const m = /^tinyactors:\/\/([^/]*)\/(.*)$/s.exec(typeof text === 'string' ? text : '');
1055
+ if (!m || !systemIDValid(m[1])) return null;
1056
+ const local = parseLocal(m[2]);
1057
+ return local ? { system: m[1], local: m[2], ...local } : null;
1058
+ }
1059
+ /* IDs from the wire are BigInt (exact up to 2^64-1). This host numbers its
1060
+ * own sessions segment << 32 | counter, below 2^53, so they fit a JS number
1061
+ * in calls to the native host; a larger id names no session here (0). */
1062
+ function hostSession(id) {
1063
+ return id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : 0;
1064
+ }
1065
+ function formatAddress(system, local) {
1066
+ if (!systemIDValid(system)) throw new TypeError(`not a system id: ${system}`);
1067
+ if (typeof local === 'bigint' || typeof local === 'number') {
1068
+ const s = BigInt(local);
1069
+ if (s < 1n || s > MAX_SESSION) throw new RangeError('session ids are 1 .. 2^64-1');
1070
+ return `tinyactors://${system}/#_scxml_${s}`;
1071
+ }
1072
+ const enc = new TextEncoder().encode(String(local));
1073
+ if (!enc.length) throw new TypeError('empty name');
1074
+ let out = '';
1075
+ for (const b of enc) {
1076
+ const c = String.fromCharCode(b);
1077
+ out += /[A-Za-z0-9\-._~]/.test(c) ? c : `%${b.toString(16).toUpperCase().padStart(2, '0')}`;
1078
+ }
1079
+ return `tinyactors://${system}/@${out}`;
1080
+ }
1081
+
1082
+ const randomID = () =>
1083
+ (globalThis.crypto && globalThis.crypto.randomUUID ? globalThis.crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`)
1084
+ .replace(/-/g, '')
1085
+ .slice(0, 12);
1086
+
1087
+ class System {
1088
+ constructor(options = {}) {
1089
+ this.options = options;
1090
+ /** This system's name in actor addresses (tinyactors://<id>/...); unique across links. */
1091
+ const restored = options.restore ? decodeValue(options.restore, null) : null;
1092
+ if (restored && restored.format !== 'tinyactors-system-snapshot') throw new TypeError('options.restore is not a system snapshot');
1093
+ this.id = (restored && restored.id) || options.id || randomID();
1094
+ if (!systemIDValid(this.id)) throw new TypeError(`createSystem: "${this.id}" is not a valid system id (lowercase a-z, 0-9, "-", dots; docs/protocol.md)`);
1095
+ this._base = `tinyactors://${this.id}/`;
1096
+ this._peers = new Map(); /* router peer handle -> the transport connection moving its envelopes */
1097
+ this._links = new Set(); /* client links (closed with the system) */
1098
+ this._refs = new Map(); /* address -> ActorRef */
1099
+ const hib = options.hibernation;
1100
+ this._store = hib ? hib.store || createMemoryStore() : null;
1101
+ this._pending = new Map(); /* session -> blob while the store is writing it */
1102
+ this._sleeping = new Map(); /* session -> root Actor (for cached snapshots) */
1103
+ this._waking = new Set(); /* sessions whose blob is being loaded */
1104
+ this._stats = { hibernations: 0, wakes: 0 };
1105
+ if (hib && hib.sweepMs !== 0) this._armSweep(hib.sweepMs || 30000);
1106
+ this._images = []; /* by segment: the compiled image */
1107
+ this._sources = new Map(); /* source name -> compiled machine */
1108
+ this._linked = new Map(); /* machine -> { segment, chart } */
1109
+ this._byChart = new Map(); /* `${segment}:${chart}` -> machine */
1110
+ this._versions = new Map(); /* machine id -> { version, machine } after reload() */
1111
+ this._actors = new Map(); /* session -> Actor (started with createActor) */
1112
+ this._ids = new Map(); /* systemID -> Actor */
1113
+ this._observed = new Set();
1114
+ this._jobs = new Map(); /* migration job -> { result, done } */
1115
+ this._settle = []; /* resolvers called once the system is idle */
1116
+ this._queue = [];
1117
+ this._running = false;
1118
+ this._dirty = false;
1119
+ this._yielded = false;
1120
+ this._deadline = -1;
1121
+ this._timer = null;
1122
+ this._immediate = null;
1123
+ this._clockTimers = null; /* { at, fn } on this system's clock (with a `clock` option) */
1124
+ this._version = 0;
1125
+ this._t0 = platform.now();
1126
+ this._budget = BUDGET;
1127
+ this._api = { get: (id) => this._ids.get(id) };
1128
+ this._segInfo = []; /* by segment: what it was made from (for snapshots) */
1129
+ this._imageSegs = new Map(); /* SystemImage -> segment */
1130
+ /* the native host: the datamodels and a ta_host — segments, routing between
1131
+ * them, versions, migration jobs and the hibernation sweep live in C */
1132
+ const callbacks = [(chart, texts) => this._resolve(chart, texts), { encode: (v) => encodeValue(v), decode: (b) => decodeValue(b, this) }, this.id, createEcmascript()];
1133
+ if (restored) this._restoreFrom(restored, callbacks);
1134
+ else this._host = native.createHost(...callbacks);
1135
+ }
1136
+
1137
+ /* ---- system images ---- */
1138
+ _linkImage(image) {
1139
+ let segment = this._imageSegs.get(image);
1140
+ if (segment !== undefined) return segment;
1141
+ native.advance(this._host, this._now());
1142
+ segment = native.addImage(this._host, image._native);
1143
+ this._images[segment] = image._native;
1144
+ this._imageSegs.set(image, segment);
1145
+ this._segInfo[segment] = { kind: 'image', bytes: image.bytes };
1146
+ image._charts.forEach((logic, chart) => {
1147
+ this._linked.set(logic, { segment, chart });
1148
+ this._byChart.set(`${segment}:${chart}`, logic);
1149
+ });
1150
+ return segment;
1151
+ }
1152
+
1153
+ /** Start the actors a system image declares (<system><actor name chart/>);
1154
+ * returns them by name. */
1155
+ boot(image) {
1156
+ if (!(image instanceof SystemImage)) throw new TypeError('boot() expects an image from compileSystem() or loadImage()');
1157
+ if (this._stopped) throw new Error('the system was stopped');
1158
+ const out = {};
1159
+ this._do(() => {
1160
+ const segment = this._linkImage(image);
1161
+ if (!native.boot(this._host, segment)) throw new Error('cannot boot the image');
1162
+ for (const { name, chart } of image.actors) {
1163
+ const session = native.actorByName(this._host, name);
1164
+ if (!session) continue;
1165
+ const actor = new Actor(image._charts[chart], { system: this, id: name, systemID: name });
1166
+ this._adopt(actor, session);
1167
+ out[name] = actor;
1168
+ }
1169
+ this._dirty = true;
1170
+ this._pump();
1171
+ });
1172
+ return out;
1173
+ }
1174
+
1175
+ /* an Actor object for a session the native host already runs */
1176
+ _adopt(actor, session, hibernated = false) {
1177
+ actor._started = true;
1178
+ actor._live = true;
1179
+ actor._session = actor._serial = session;
1180
+ actor._chart = actor.logic._compile().chart;
1181
+ actor._hibernated = hibernated;
1182
+ this._actors.set(session, actor);
1183
+ if (hibernated) this._sleeping.set(session, actor);
1184
+ if (actor.options.systemID) this._ids.set(actor.options.systemID, actor);
1185
+ }
1186
+
1187
+ /* ---- snapshot / restore ---- */
1188
+
1189
+ /**
1190
+ * The whole system as bytes: every actor (state, variables, queued events,
1191
+ * timers), and what it runs (machine XML, SCXML documents, images).
1192
+ * Restore with createSystem({ restore, machines }). Needs a quiet moment:
1193
+ * not during a migration; context values must be encodable (no functions).
1194
+ * Hibernated actors stay in the hibernation store: restore with the same store.
1195
+ */
1196
+ snapshot() {
1197
+ if (this._stopped) throw new Error('the system was stopped');
1198
+ if (this._running) throw new Error('snapshot() cannot run inside an action');
1199
+ if (this._jobs.size) throw new Error('snapshot() cannot run during a migration');
1200
+ const { host, dm } = native.snapshot(this._host);
1201
+ const keyOf = (logic) => {
1202
+ const l = this._linked.get(logic);
1203
+ return l ? `${l.segment}:${l.chart}` : null;
1204
+ };
1205
+ return encodeValue({
1206
+ format: 'tinyactors-system-snapshot',
1207
+ version: 1,
1208
+ id: this.id,
1209
+ now: this._now(),
1210
+ segments: this._segInfo.map((info, segment) => (this._images[segment] ? info : null)),
1211
+ versions: [...this._versions].map(([id, v]) => ({ id, version: v.version })),
1212
+ actors: [...this._actors.values()].filter((a) => a._live).map((a) => ({ session: a._session, id: a.id, systemID: a.options.systemID, logic: keyOf(a.logic), hibernated: a._hibernated })),
1213
+ host,
1214
+ dm: encodeValue(dm), /* decoded once the restoring system exists (actor references) */
1215
+ });
1216
+ }
1217
+
1218
+ /* the native image of a segment as recorded in a snapshot or an export, and its
1219
+ * charts' logic: [chart, logic, compiled machine or null] */
1220
+ _segmentImage(info, machines = [], what = 'restore: machine "%" as of the snapshot', lenient = false) {
1221
+ if (info.kind === 'image') {
1222
+ const image = loadImage(info.bytes);
1223
+ const links = [];
1224
+ image._charts.forEach((logic, chart) => links.push([chart, logic, null, image]));
1225
+ return { image: image._native, links, missing: [] };
1226
+ }
1227
+ const missing = [];
1228
+ const all = [...machines, ...(this.options.machines || []), ...registry];
1229
+ const sources = info.sources.map((src) => {
1230
+ let logic = null;
1231
+ if (src.logic && src.logic.kind === 'scxml') logic = new SCXMLLogic(src.logic.xml, { id: src.logic.id, documents: src.logic.documents });
1232
+ else if (src.logic) {
1233
+ logic = all.find((m) => m instanceof StateMachine && m.id === src.logic.id && m._compile().xml === src.xml);
1234
+ if (!logic) {
1235
+ const why = `${what.replace('%', src.logic.id)} is not defined (create it, or pass it in options.machines; or it changed since: restore with the old version, then reload())`;
1236
+ if (!lenient) throw new Error(why);
1237
+ missing.push([src.name, why]);
1238
+ }
1239
+ }
1240
+ return { ...src, logic };
1241
+ });
1242
+ const image = native.compile(sources.map(({ name, xml }) => ({ name, xml })), info.files || []);
1243
+ const links = sources.filter((s) => s.logic).map((s) => [native.chartIndex(image, s.name), s.logic, s.logic._compile(), null, s.name]);
1244
+ return { image, links, missing: missing.map(([name, why]) => [native.chartIndex(image, name), why]) };
1245
+ }
1246
+
1247
+ _register(segment, info, links) {
1248
+ this._segInfo[segment] = info;
1249
+ for (const [chart, logic, compiled, image, name] of links) {
1250
+ if (image) this._imageSegs.set(image, segment);
1251
+ if (compiled) this._sources.set(name, compiled);
1252
+ this._linked.set(logic, { segment, chart });
1253
+ this._byChart.set(`${segment}:${chart}`, logic);
1254
+ }
1255
+ }
1256
+
1257
+ _restoreFrom(rec, callbacks) {
1258
+ const images = rec.segments.map((info, segment) => {
1259
+ if (!info) return null;
1260
+ const { image, links } = this._segmentImage(info);
1261
+ this._register(segment, info, links);
1262
+ return image;
1263
+ });
1264
+ this._host = native.restore(...callbacks, images, rec.host, decodeValue(rec.dm, this));
1265
+ images.forEach((im, segment) => (this._images[segment] = im || undefined));
1266
+ for (const v of rec.versions || []) {
1267
+ let machine = null;
1268
+ for (const [key, logic] of this._byChart) if (logic.id === v.id && (!machine || Number(key.split(':')[0]) > machine.seg)) machine = { logic, seg: Number(key.split(':')[0]) };
1269
+ if (machine) this._versions.set(v.id, { version: v.version, machine: machine.logic });
1270
+ }
1271
+ for (const a of rec.actors) {
1272
+ const logic = a.logic && this._byChart.get(a.logic);
1273
+ if (!logic) continue;
1274
+ this._adopt(new Actor(logic, { system: this, id: a.id, systemID: a.systemID }), a.session, a.hibernated);
1275
+ }
1276
+ this._t0 = platform.now() - rec.now; /* (with a clock option, the clock says what time it is) */
1277
+ native.advance(this._host, this._now());
1278
+ this._dirty = true;
1279
+ this._immediate = platform.defer(() => this._pump());
1280
+ }
1281
+
1282
+ /** A reference to the actor at `address` (a local Actor when it is one of ours). */
1283
+ ref(address) {
1284
+ if (address instanceof Actor || address instanceof ActorRef) return address;
1285
+ const m = /^tinyactors:\/\/([^/]+)\/#_scxml_(\d+)$/.exec(address);
1286
+ if (m && m[1] === this.id) {
1287
+ const a = this._actors.get(Number(m[2]));
1288
+ if (a) return a;
1289
+ }
1290
+ let r = this._refs.get(address);
1291
+ if (!r) this._refs.set(address, (r = new ActorRef(this, address)));
1292
+ return r;
1293
+ }
1294
+
1295
+ /* ---- other systems: routing decisions are the native router's (ta_host:
1296
+ * peers, routes, relaying, origin checks, policy, dedup — docs/protocol.md);
1297
+ * transports only move envelopes between it and the wire. */
1298
+
1299
+ /** Hand an envelope (docs/protocol.md, "Envelope": target, name, data,
1300
+ * origin, sendid, msgid, dedup, hops) to the router, as this system's host
1301
+ * code: delivered to a local actor, or to the peer its target routes to.
1302
+ * Returns 'delivered', 'relayed', 'duplicate' or 'refused'. */
1303
+ deliver(envelope) {
1304
+ if (!envelope || typeof envelope.target !== 'string' || typeof envelope.name !== 'string') throw new TypeError('deliver({ target, name, ... })');
1305
+ let out = -1;
1306
+ this._do(() => {
1307
+ native.advance(this._host, this._now());
1308
+ out = native.deliverEnvelope(this._host, 0, { origin: formatAddress(this.id, 'host'), ...envelope });
1309
+ this._dirty = true;
1310
+ this._pump();
1311
+ });
1312
+ return ['delivered', 'relayed', 'duplicate', 'refused'][out] || (out === -1 && this._running ? 'queued' : 'refused');
1313
+ }
1314
+
1315
+ /* an envelope from this system's host code (no origin checks): delivered
1316
+ * here or handed to the peer its target routes to */
1317
+ _hostRoute(env) {
1318
+ native.advance(this._host, this._now());
1319
+ const out = native.deliverEnvelope(this._host, 0, { origin: formatAddress(this.id, 'host'), ...env });
1320
+ this._dirty = true;
1321
+ return out === 0 || out === 1;
1322
+ }
1323
+
1324
+ /* a frame from the transport of router peer `peer`: `ev` (an envelope) or `err` */
1325
+ _fromPeer(peer, msg) {
1326
+ this._do(() => {
1327
+ if (!this._peers.has(peer)) return;
1328
+ native.advance(this._host, this._now());
1329
+ if (msg.t === 'ev') {
1330
+ const conn = this._peers.get(peer);
1331
+ native.deliverEnvelope(this._host, peer, {
1332
+ target: str(msg.target),
1333
+ name: str(msg.name),
1334
+ data: msg.data === undefined ? undefined : conn.decode(msg.data),
1335
+ origin: str(msg.origin),
1336
+ origintype: str(msg.origintype),
1337
+ sendid: str(msg.sendid),
1338
+ msgid: str(msg.msgid),
1339
+ dedup: str(msg.dedup),
1340
+ hops: Number.isInteger(msg.hops) && msg.hops >= 0 ? msg.hops : 0,
1341
+ });
1342
+ } else if (msg.t === 'err') {
1343
+ const reason = REASONS.indexOf(msg.reason);
1344
+ native.peerError(this._host, peer, str(msg.origin), str(msg.msgid), str(msg.sendid), reason > 0 ? reason : REASONS.indexOf('unreachable'));
1345
+ }
1346
+ this._dirty = true;
1347
+ this._pump();
1348
+ });
1349
+ }
1350
+
1351
+ /* a transport connection carries router peer conn.peer (from now on) */
1352
+ _attach(conn) {
1353
+ this._peers.set(conn.peer, conn);
1354
+ }
1355
+
1356
+ _detach(conn) {
1357
+ if (this._peers.get(conn.peer) === conn) this._peers.delete(conn.peer);
1358
+ }
1359
+
1360
+ /* the peer said hello: what it reaches, and it is up (queued envelopes go out) */
1361
+ _peerHello(conn, reach) {
1362
+ this._do(() => {
1363
+ native.peerReach(this._host, conn.peer, reach);
1364
+ native.peerUp(this._host, conn.peer, true);
1365
+ this._dirty = true;
1366
+ this._pump();
1367
+ this._announce();
1368
+ });
1369
+ }
1370
+
1371
+ _peerDown(conn, remove) {
1372
+ this._do(() => {
1373
+ if (remove) {
1374
+ native.advance(this._host, this._now());
1375
+ native.peerRemove(this._host, conn.peer); /* queued envelopes fail: error.communication */
1376
+ this._detach(conn);
1377
+ } else native.peerUp(this._host, conn.peer, false);
1378
+ this._dirty = true;
1379
+ this._pump();
1380
+ this._announce();
1381
+ });
1382
+ }
1383
+
1384
+ /* the systems reachable through us, as announced to `conn` (links with
1385
+ * announce: true, or a list: only those): our other open peers and what
1386
+ * they reach */
1387
+ _reachFor(conn) {
1388
+ const out = new Set();
1389
+ for (const c of new Set(this._peers.values())) {
1390
+ if (c === conn || !c.open || !c.remoteID) continue;
1391
+ out.add(c.remoteID);
1392
+ for (const r of c.reach) out.add(r);
1393
+ }
1394
+ out.delete(this.id);
1395
+ if (conn.remoteID) out.delete(conn.remoteID);
1396
+ const only = Array.isArray(conn.options.announce) ? new Set(conn.options.announce) : null;
1397
+ return [...out].filter((id) => !only || only.has(id)).sort();
1398
+ }
1399
+
1400
+ /* re-announce (a repeated hello) where what we reach changed */
1401
+ _announce() {
1402
+ for (const c of new Set(this._peers.values())) if (c.announce && c.open) c.hello();
1403
+ }
1404
+
1405
+ /* ---- moving actors between systems (another process, Node or web) ---- */
1406
+
1407
+ /**
1408
+ * Move `actor` out of this system, as bytes that another system — in this
1409
+ * or another process — takes in with adopt(): its states, variables,
1410
+ * delayed events with their data, the actors it invoked, and what it runs
1411
+ * (machine SCXML, documents or image). The actor stops here, without a done
1412
+ * event. It must be awake, not in a step, with nothing queued for it.
1413
+ */
1414
+ export(actor) {
1415
+ if (!(actor instanceof Actor) || actor.system !== this) throw new TypeError('export() expects an actor of this system');
1416
+ if (this._stopped) throw new Error('the system was stopped');
1417
+ if (this._running) throw new Error('export() cannot run inside an action');
1418
+ if (!actor._live || actor._status !== 'active') throw new Error('export(): the actor is not running');
1419
+ if (actor._hibernated) throw new Error('export(): the actor is hibernated (send it an event to wake it first)');
1420
+ native.advance(this._host, this._now());
1421
+ const snap = actor._makeSnapshot();
1422
+ const r = native.exportActor(this._host, actor._session);
1423
+ if (!r) {
1424
+ const why = native.storeError(this._host);
1425
+ throw new Error(`export(): ${why ? why.message || why : 'the actor is busy (events or requests queued for it): export it once the system is idle'}`);
1426
+ }
1427
+ const rec = {
1428
+ format: 'tinyactors-actor',
1429
+ version: 1,
1430
+ id: actor.id,
1431
+ systemID: actor.options.systemID,
1432
+ now: this._now(), /* the adopting system keeps what its timers had left */
1433
+ segment: this._segInfo[r.segment],
1434
+ chart: r.chart,
1435
+ blob: r.blob,
1436
+ };
1437
+ this._forget(actor);
1438
+ actor._snapshot = { ...snap, status: 'stopped' };
1439
+ actor._hibernated = true; /* (no session to read from any more) */
1440
+ actor._halt();
1441
+ actor._hibernated = false;
1442
+ return encodeValue(rec);
1443
+ }
1444
+
1445
+ /**
1446
+ * Take in an actor another system exported: the same session (its address
1447
+ * under this system's id), states and variables; delayed events keep the
1448
+ * time they had left. Its machine is found as for createSystem({ restore })
1449
+ * (defined in this process or in `options.machines`); SCXML documents and
1450
+ * images travel with it.
1451
+ */
1452
+ adopt(bytes, options = {}) {
1453
+ if (this._stopped) throw new Error('the system was stopped');
1454
+ if (this._running) throw new Error('adopt() cannot run inside an action');
1455
+ let rec = null;
1456
+ try {
1457
+ rec = decodeValue(bytes, null);
1458
+ } catch {
1459
+ /* not ours */
1460
+ }
1461
+ if (!rec || rec.format !== 'tinyactors-actor') throw new TypeError('adopt() expects bytes from system.export()');
1462
+ const want = encodeValue(rec.segment);
1463
+ let segment = this._segInfo.findIndex((info, i) => info && this._images[i] && sameBytes(encodeValue(info), want));
1464
+ if (segment < 0) {
1465
+ /* (only the actor's own machine must be defined here) */
1466
+ const { image, links, missing } = this._segmentImage(rec.segment, options.machines, 'adopt(): machine "%" as exported', true);
1467
+ const own = missing.find(([chart]) => chart === rec.chart);
1468
+ if (own) throw new Error(own[1]);
1469
+ for (const [, , compiled, , name] of links) if (compiled) this._sources.set(name, compiled); /* (resolved when linked) */
1470
+ native.advance(this._host, this._now());
1471
+ segment = native.addImage(this._host, image);
1472
+ this._images[segment] = image;
1473
+ this._register(segment, rec.segment, links);
1474
+ }
1475
+ const logic = this._byChart.get(`${segment}:${rec.chart}`);
1476
+ if (!logic) throw new Error('adopt(): the actor\'s machine is not known here');
1477
+ native.advance(this._host, this._now());
1478
+ const session = native.adopt(this._host, segment, rec.blob, rec.now, this._now());
1479
+ const actor = new Actor(logic, { system: this, id: rec.id, systemID: rec.systemID });
1480
+ this._adopt(actor, session);
1481
+ this._dirty = true;
1482
+ this._pump();
1483
+ return actor;
1484
+ }
1485
+
1486
+ /* ---- hibernation (the system never does I/O: blobs go to options.hibernation.store) */
1487
+ _armSweep(ms) {
1488
+ const t = platform.setTimer(() => {
1489
+ this._do(() => {
1490
+ this.hibernate();
1491
+ this._pump();
1492
+ });
1493
+ this._armSweep(ms);
1494
+ }, ms);
1495
+ if (t && typeof t.unref === 'function') t.unref();
1496
+ this._sweepTimer = t;
1497
+ }
1498
+
1499
+ /** Hibernate `actor` now, or (no argument) every actor that has been idle
1500
+ * since the previous sweep. Returns how many were unloaded. An actor whose
1501
+ * data cannot be stored throws (the message names the variable); the sweep
1502
+ * leaves such actors resident. */
1503
+ hibernate(actor) {
1504
+ if (!this._store) throw new Error('createSystem({ hibernation: { store } }) is needed to hibernate');
1505
+ if (this._running) return 0;
1506
+ let n = 0;
1507
+ const one = (session) => {
1508
+ const key = String(session);
1509
+ const root = this._actors.get(session);
1510
+ if (root) root._snapshot = root._makeSnapshot(); /* answered from cache while asleep */
1511
+ const blob = native.hibernate(this._host, session);
1512
+ if (!blob) {
1513
+ const why = native.storeError(this._host);
1514
+ if (why && actor) throw new Error(`cannot hibernate the actor: ${why.message || why}`);
1515
+ return;
1516
+ }
1517
+ n++;
1518
+ this._stats.hibernations++;
1519
+ if (root) {
1520
+ root._hibernated = true;
1521
+ this._sleeping.set(session, root);
1522
+ }
1523
+ this._pending.set(session, blob);
1524
+ const done = () => this._pending.get(session) === blob && this._pending.delete(session);
1525
+ const w = this._store.set(key, blob);
1526
+ if (w && typeof w.then === 'function') w.then(done, (e) => platform.log('hibernation store:', e));
1527
+ else done();
1528
+ };
1529
+ if (actor) {
1530
+ if (actor._live && actor._status === 'active' && !actor._hibernated) one(actor._session);
1531
+ } else {
1532
+ for (const session of native.sweep(this._host, 1 << 30)) one(session);
1533
+ }
1534
+ return n;
1535
+ }
1536
+
1537
+ /* load an actor's blob (it has work, or a migration wants it) */
1538
+ _wake(session) {
1539
+ if (this._waking.has(session) || !this._store) return; // already being loaded
1540
+ this._waking.add(session);
1541
+ const key = String(session);
1542
+ const finish = (blob) => {
1543
+ this._do(() => {
1544
+ this._waking.delete(session);
1545
+ if (this._stopped) return;
1546
+ if (!blob || !native.wake(this._host, session, blob)) {
1547
+ platform.log(`tinyactors: cannot wake actor ${key} (no blob in the store)`);
1548
+ return;
1549
+ }
1550
+ this._stats.wakes++;
1551
+ this._pending.delete(session);
1552
+ const root = this._sleeping.get(session);
1553
+ if (root) {
1554
+ root._hibernated = false;
1555
+ this._sleeping.delete(session);
1556
+ }
1557
+ const d = this._store.delete(key);
1558
+ if (d && typeof d.then === 'function') d.catch(() => {});
1559
+ this._dirty = true;
1560
+ this._pump();
1561
+ });
1562
+ };
1563
+ const blob = this._pending.get(session) || this._store.get(key);
1564
+ if (blob && typeof blob.then === 'function')
1565
+ blob.then(finish, (e) => {
1566
+ this._waking.delete(session);
1567
+ platform.log('hibernation store:', e);
1568
+ });
1569
+ else finish(blob);
1570
+ }
1571
+
1572
+ /** The actor registered with `createActor(logic, { systemID })`. */
1573
+ get(systemID) {
1574
+ return this._ids.get(systemID);
1575
+ }
1576
+
1577
+ _now() {
1578
+ return this.options.clock ? this.options.clock() : platform.now() - this._t0;
1579
+ }
1580
+
1581
+ /** Run `fn` when this system's clock passes `at` (system time); returns a
1582
+ * cancel function. Without a `clock` option that is a platform timer; with
1583
+ * one, the callback waits for flush() — time moves only there. Used for
1584
+ * link resumption, whose window follows the router's queue TTL. */
1585
+ _at(at, fn) {
1586
+ if (!this.options.clock) {
1587
+ const t = platform.setTimer(fn, Math.max(0, at - this._now()));
1588
+ if (t && typeof t.unref === 'function') t.unref();
1589
+ return () => platform.clearTimer(t);
1590
+ }
1591
+ const timers = (this._clockTimers ||= []);
1592
+ const entry = { at, fn };
1593
+ timers.push(entry);
1594
+ return () => {
1595
+ const i = timers.indexOf(entry);
1596
+ if (i >= 0) timers.splice(i, 1);
1597
+ };
1598
+ }
1599
+
1600
+ _expire() { /* run the clock timers that are due (with a `clock` option) */
1601
+ const timers = this._clockTimers;
1602
+ if (!timers || !timers.length) return;
1603
+ const now = this._now();
1604
+ const due = [];
1605
+ for (let i = timers.length - 1; i >= 0; i--) if (timers[i].at <= now) due.push(timers.splice(i, 1)[0]);
1606
+ for (let i = due.length - 1; i >= 0; i--) due[i].fn();
1607
+ }
1608
+
1609
+ /**
1610
+ * Run everything that is due now — events, eventless chains, timers whose
1611
+ * time has come on the system's clock — until the system is idle (or
1612
+ * `maxSlices` slices ran). With a `clock` option this is how time moves:
1613
+ * advance the clock, then flush(). Returns true when idle.
1614
+ */
1615
+ flush(maxSlices = 100000) {
1616
+ if (this._running || this._stopped) return false;
1617
+ for (let i = 0; i < maxSlices; i++) {
1618
+ if (this._deadline >= 0 && this._deadline <= this._now()) this._dirty = true;
1619
+ this._expire();
1620
+ if (!this._dirty && !this._yielded && !this._queue.length) return true;
1621
+ this._pump();
1622
+ platform.cancelDefer(this._immediate);
1623
+ this._immediate = null;
1624
+ }
1625
+ return false;
1626
+ }
1627
+
1628
+ _resolve(chartName, texts) {
1629
+ const compiled = this._sources.get(chartName.split('#')[0]);
1630
+ const sys = this._api;
1631
+ return texts.map((t) => {
1632
+ const e = compiled && t !== undefined ? compiled.registry.get(norm(t)) : undefined;
1633
+ if (!e) return undefined;
1634
+ const f = e.fn;
1635
+ return (args, $) => {
1636
+ args.system = sys;
1637
+ if ($ && $.self) args.self = this.ref($.self);
1638
+ return f(args, $);
1639
+ };
1640
+ });
1641
+ }
1642
+
1643
+ /** Link `machine` (and every machine not linked yet) into a new segment. */
1644
+ _link(machine) {
1645
+ const hit = this._linked.get(machine);
1646
+ if (hit) return hit;
1647
+ if (machine.image) {
1648
+ this._linkImage(machine.image);
1649
+ return this._linked.get(machine);
1650
+ }
1651
+ const superseded = (m) => this._current(m) !== m;
1652
+ const batch = [
1653
+ machine,
1654
+ ...[...(this === defaultSystem ? registry : [])].filter((m) => m !== machine && !this._linked.has(m) && !superseded(m)),
1655
+ ];
1656
+ const sources = [];
1657
+ const names = new Map();
1658
+ for (const m of batch) {
1659
+ let compiled;
1660
+ try {
1661
+ compiled = m._compile();
1662
+ } catch (e) {
1663
+ if (m === machine) throw e;
1664
+ continue; // another machine's problem surfaces when it is started
1665
+ }
1666
+ let name = m.id.replace(/[#\s]/g, '_') || 'machine';
1667
+ for (let n = 2; this._sources.has(name) || names.has(name); n++) name = `${m.id.replace(/[#\s]/g, '_')}-${n}`;
1668
+ names.set(name, m);
1669
+ sources.push({ name, xml: compiled.xml, compiled, machine: m });
1670
+ /* SCXML documents: the documents their <invoke src> names */
1671
+ for (const d of compiled.sources || []) {
1672
+ if (names.has(d.name)) continue;
1673
+ names.set(d.name, null);
1674
+ sources.push({ name: d.name, xml: d.xml });
1675
+ }
1676
+ }
1677
+ const files = sources.flatMap((s) => (s.compiled && s.compiled.files) || []);
1678
+ const image = native.compile(
1679
+ sources.map(({ name, xml }) => ({ name, xml })),
1680
+ files,
1681
+ );
1682
+ for (const s of sources) if (s.compiled) this._sources.set(s.name, s.compiled);
1683
+ native.advance(this._host, this._now());
1684
+ const segment = native.addImage(this._host, image);
1685
+ this._images[segment] = image;
1686
+ this._segInfo[segment] = {
1687
+ kind: 'sources',
1688
+ files,
1689
+ sources: sources.map(({ name, xml, machine: m }) => ({
1690
+ name,
1691
+ xml,
1692
+ logic: !m ? null : m.scxml ? { kind: 'scxml', id: m.id, xml: m.xml, documents: m.documents } : { kind: 'machine', id: m.id },
1693
+ })),
1694
+ };
1695
+ for (const s of sources) {
1696
+ if (!s.machine) continue;
1697
+ const chart = native.chartIndex(image, s.name);
1698
+ this._linked.set(s.machine, { segment, chart });
1699
+ this._byChart.set(`${segment}:${chart}`, s.machine);
1700
+ }
1701
+ return this._linked.get(machine);
1702
+ }
1703
+
1704
+ /** The newest version of a machine (see reload()). */
1705
+ _current(machine) {
1706
+ const v = this._versions.get(machine.id);
1707
+ return v ? v.machine : machine;
1708
+ }
1709
+
1710
+ /**
1711
+ * Hot reload (CGI style): `machine` becomes the current version of the
1712
+ * machines with its id. Actors started afterwards run it; running actors
1713
+ * stay on their version until they finish or migrate() moves them. A
1714
+ * version whose actors are all gone is freed. Returns the version number.
1715
+ */
1716
+ reload(machine) {
1717
+ if (!(machine instanceof StateMachine) && !(machine instanceof SCXMLLogic)) throw new TypeError('reload() expects a machine (createMachine) or an SCXML document (fromSCXML)');
1718
+ if (this._stopped) throw new Error('the system was stopped');
1719
+ const prev = this._versions.get(machine.id);
1720
+ const version = (prev ? prev.version : 1) + 1;
1721
+ this._versions.set(machine.id, { version, machine });
1722
+ if (!this._linked.has(machine)) {
1723
+ try {
1724
+ this._link(machine); // compile errors surface here
1725
+ } catch (e) {
1726
+ if (prev) this._versions.set(machine.id, prev);
1727
+ else this._versions.delete(machine.id);
1728
+ throw e;
1729
+ }
1730
+ }
1731
+ return version;
1732
+ }
1733
+
1734
+ /**
1735
+ * Live migration: move running actors to the current version of their
1736
+ * machine at their next stable point (a job of the native host layer,
1737
+ * advanced in bounded steps as the system runs). States are matched by
1738
+ * id, history and context are kept, the session (address) stays the same,
1739
+ * and each actor receives `error.platform.upgrade` with the previous
1740
+ * context as `event.data`. `target`: an actor, a machine (its actors), or
1741
+ * nothing (every actor on an old version). Busy actors move at their next
1742
+ * stable point; hibernated ones are loaded first (`wake`, default: when
1743
+ * the system has a hibernation store) or move when they wake; `timeoutMs`
1744
+ * ends the job with whoever is left on its version. Returns
1745
+ * `{ migrated, pending, done }`: `migrated` moved during the call,
1746
+ * `pending` (computed when read) still on old versions, `done` resolves
1747
+ * with `{ migrated, failed, pending }` once the moved actors processed
1748
+ * their upgrade.
1749
+ */
1750
+ migrate(target, options = {}) {
1751
+ if (this._stopped) throw new Error('the system was stopped');
1752
+ const { wake = !!this._store, timeoutMs } = options;
1753
+ if (wake && !this._store) throw new Error('migrate({ wake: true }) needs a hibernation store');
1754
+ const single = target instanceof Actor ? target : null;
1755
+ // only machines that were reloaded have older versions
1756
+ const ids = single ? [single.logic.id] : target ? [target.id] : [...this._versions.keys()];
1757
+ const wanted = (a) => ids.includes(a.logic.id) && a._live && a._status === 'active' && this._current(a.logic) !== a.logic;
1758
+ const jobs = [];
1759
+ for (const id of ids) {
1760
+ if (!this._versions.has(id) || (single && !wanted(single))) continue;
1761
+ const job = native.migrate(this._host, id, single ? single._session : 0, wake, timeoutMs === undefined ? 0 : Math.max(1, timeoutMs));
1762
+ const entry = { moved: [], result: null };
1763
+ entry.done = new Promise((resolve) => (entry.resolve = resolve));
1764
+ this._jobs.set(job, entry);
1765
+ jobs.push(entry);
1766
+ }
1767
+ this._dirty = true; // jobs advance inside native.run
1768
+ if (!this._running) this._pump(); // the first step, and the upgrade events
1769
+ const migrated = jobs.flatMap((j) => j.moved);
1770
+ const done = Promise.all(jobs.map((j) => j.done)).then((rs) => ({
1771
+ migrated: rs.reduce((n, r) => n + r.migrated, 0),
1772
+ failed: rs.reduce((n, r) => n + r.failed, 0),
1773
+ pending: rs.flatMap((r) => r.pending),
1774
+ }));
1775
+ const system = this;
1776
+ return {
1777
+ migrated,
1778
+ done,
1779
+ /* computed when read (a walk over the actors) */
1780
+ get pending() {
1781
+ return single ? (wanted(single) ? [single] : []) : [...system._actors.values()].filter(wanted);
1782
+ },
1783
+ };
1784
+ }
1785
+
1786
+ /* Calls into the native system are never nested: work requested while it
1787
+ * runs (e.g. actor.send() inside an action) is queued and done afterwards. */
1788
+ _do(fn) {
1789
+ if (this._stopped) return;
1790
+ if (this._running) this._queue.push(fn);
1791
+ else fn();
1792
+ }
1793
+
1794
+ /** Stop the whole system: every actor stops, links close, timers end and
1795
+ * the native memory is freed. The system cannot be used afterwards. */
1796
+ stop() {
1797
+ if (this._stopped || this._running) return;
1798
+ for (const c of [...this._links]) c.disconnect();
1799
+ for (const a of [...this._actors.values()]) a._halt();
1800
+ this._stopped = true;
1801
+ platform.clearTimer(this._timer);
1802
+ platform.clearTimer(this._sweepTimer);
1803
+ platform.cancelDefer(this._immediate);
1804
+ this._clockTimers = null;
1805
+ native.destroy(this._host);
1806
+ this._actors.clear();
1807
+ for (const [, j] of this._jobs) j.resolve({ migrated: 0, failed: 0, pending: [] });
1808
+ this._jobs.clear();
1809
+ for (const resolve of this._settle.splice(0)) resolve();
1810
+ this._ids.clear();
1811
+ this._observed.clear();
1812
+ }
1813
+
1814
+ _spawn(actor) {
1815
+ actor.logic = this._current(actor.logic); // new actors run the newest version
1816
+ actor._chart = actor.logic._compile().chart;
1817
+ const { segment, chart } = this._link(actor.logic);
1818
+ native.advance(this._host, this._now());
1819
+ const logic = actor.logic;
1820
+ const session = logic.scxml
1821
+ ? native.spawn(this._host, segment, chart, undefined, actor.options.input || {}, actor.options.systemID) /* <data> overrides */
1822
+ : native.spawn(this._host, segment, chart, actor.options.input, undefined, actor.options.systemID);
1823
+ actor._session = session;
1824
+ actor._serial = session;
1825
+ actor._live = true;
1826
+ this._actors.set(session, actor);
1827
+ if (actor.options.systemID) this._ids.set(actor.options.systemID, actor);
1828
+ this._dirty = true;
1829
+ }
1830
+
1831
+ _send(actor, event) {
1832
+ native.send(this._host, actor._session, event.type, actor.logic.scxml ? actor.logic._eventData(event) : event);
1833
+ this._dirty = true;
1834
+ }
1835
+
1836
+ /** Send many events at once (one native call; batched per segment in C).
1837
+ * `items`: [actor, event] pairs. Returns how many were delivered. */
1838
+ sendMany(items) {
1839
+ const sessions = [];
1840
+ const types = [];
1841
+ const events = [];
1842
+ for (const [actor, ev] of items) {
1843
+ const event = typeof ev === 'string' ? { type: ev } : ev;
1844
+ if (!(actor instanceof Actor) || !actor._live || actor._status !== 'active') continue;
1845
+ sessions.push(actor._session);
1846
+ types.push(event.type);
1847
+ events.push(actor.logic.scxml ? actor.logic._eventData(event) : event);
1848
+ }
1849
+ let n = 0;
1850
+ this._do(() => {
1851
+ n = native.sendMany(this._host, sessions, types, events);
1852
+ this._dirty = true;
1853
+ this._pump();
1854
+ });
1855
+ return n;
1856
+ }
1857
+
1858
+ _terminate(actor) {
1859
+ native.terminate(this._host, actor._session); // the session exits on the next run
1860
+ this._forget(actor);
1861
+ this._dirty = true;
1862
+ }
1863
+
1864
+ _forget(actor) {
1865
+ if (!actor._live) return;
1866
+ actor._live = false;
1867
+ this._actors.delete(actor._session);
1868
+ if (actor.options.systemID && this._ids.get(actor.options.systemID) === actor) this._ids.delete(actor.options.systemID);
1869
+ this._observed.delete(actor);
1870
+ }
1871
+
1872
+ _pump() {
1873
+ if (this._running || this._stopped) return;
1874
+ platform.cancelDefer(this._immediate);
1875
+ this._immediate = null;
1876
+ native.advance(this._host, this._now());
1877
+ if (this._yielded) {
1878
+ this._yielded = false;
1879
+ this._dirty = true;
1880
+ }
1881
+ const started = platform.now();
1882
+ for (let round = 0; round < 16; round++) {
1883
+ let ran = false;
1884
+ if (this._dirty) {
1885
+ this._dirty = false;
1886
+ ran = true;
1887
+ this._running = true;
1888
+ let r;
1889
+ const t0 = platform.now();
1890
+ try {
1891
+ r = native.run(this._host, this._budget);
1892
+ } finally {
1893
+ this._running = false;
1894
+ }
1895
+ if (r.status === 'yielded') {
1896
+ const dt = platform.now() - t0;
1897
+ if (dt > SLICE_MS) this._budget = Math.max(500, Math.floor(this._budget / 2));
1898
+ else if (dt < SLICE_MS / 4) this._budget = Math.min(200000, Math.floor(this._budget * 1.5));
1899
+ }
1900
+ this._version++;
1901
+ this._handle(r);
1902
+ this._deadline = r.deadline;
1903
+ if (r.status !== 'idle') this._yielded = true;
1904
+ }
1905
+ const queued = this._queue.splice(0);
1906
+ for (const fn of queued) fn();
1907
+ if (!ran && !queued.length) break;
1908
+ if (platform.now() - started > SLICE_MS) break; // the rest in the next pump (deferred below)
1909
+ }
1910
+ if (this._settle.length && !this._yielded && !this._dirty) for (const resolve of this._settle.splice(0)) resolve();
1911
+ for (const actor of [...this._observed]) actor._notify();
1912
+ if (this._yielded || this._dirty) this._immediate = platform.defer(() => this._pump());
1913
+ this._schedule();
1914
+ }
1915
+
1916
+ _schedule() {
1917
+ platform.clearTimer(this._timer);
1918
+ this._timer = null;
1919
+ if (this._deadline < 0 || this.options.clock) return; /* own clock: flush() moves time */
1920
+ this._timer = platform.setTimer(() => {
1921
+ this._timer = null;
1922
+ if (this._deadline >= 0 && this._deadline <= this._now() + 1) this._dirty = true;
1923
+ this._pump();
1924
+ }, Math.max(0, this._deadline - this._now()));
1925
+ }
1926
+
1927
+ _handle(r) {
1928
+ /* (native.run lists only what happened) */
1929
+ for (const l of r.logs || NONE) {
1930
+ const a = this._actors.get(l.session);
1931
+ const logger = (a && a.options.logger) || this.options.logger || platform.log;
1932
+ if (l.label) logger(l.label, l.message);
1933
+ else logger(l.message);
1934
+ }
1935
+ for (const e of r.errors || NONE) {
1936
+ const a = this._actors.get(e.session);
1937
+ if (a) a._fail(e.error);
1938
+ }
1939
+ const ended = new Map((r.ended || NONE).map((g) => [g.session, g]));
1940
+ for (const d of r.done || NONE) {
1941
+ const a = this._actors.get(d.session);
1942
+ if (!a) continue;
1943
+ const g = ended.get(d.session);
1944
+ a._finish(d.state, d.output, g && g.context, g && g.config);
1945
+ }
1946
+ for (const p of r.peers || NONE) {
1947
+ const c = this._peers.get(p.peer);
1948
+ if (c) c.envelope(p);
1949
+ }
1950
+ for (const e of r.peerErrors || NONE) {
1951
+ const c = this._peers.get(e.peer);
1952
+ if (c) c.post({ t: 'err', origin: e.origin, msgid: e.msgid, sendid: e.sendid, reason: REASONS[e.reason] || 'unreachable' });
1953
+ }
1954
+ for (const c of this._links) c.sync();
1955
+ for (const session of r.wakes || NONE) this._wake(session);
1956
+ for (const q of r.requests || NONE) {
1957
+ // an invoke whose src is not a chart of its image: look it up by source name
1958
+ const image = this._images[q.segment];
1959
+ const chart = image ? native.chartIndex(image, q.src.replace(/^(file:(\/\/)?|\.\/)/, '')) : -1;
1960
+ native.resume(this._host, q.segment, q.token, chart);
1961
+ this._dirty = true;
1962
+ }
1963
+ for (const m of r.migrated || NONE) {
1964
+ const a = this._actors.get(m.session);
1965
+ const machine = this._byChart.get(`${m.segment}:${m.chart}`);
1966
+ if (a && machine) {
1967
+ a.logic = machine;
1968
+ a._chart = machine._compile().chart;
1969
+ a._snapVersion = -1;
1970
+ }
1971
+ const job = this._jobs.get(m.job);
1972
+ if (job && a) job.moved.push(a);
1973
+ }
1974
+ for (const j of r.jobs || NONE) {
1975
+ const job = this._jobs.get(j.job);
1976
+ if (!job) continue;
1977
+ this._jobs.delete(j.job);
1978
+ const pending = j.pending.map((s) => this._actors.get(s)).filter(Boolean);
1979
+ // settled once the system is idle: the upgrade events have been processed
1980
+ this._settle.push(() => job.resolve({ migrated: j.migrated, failed: j.failed, pending }));
1981
+ }
1982
+ for (const segment of r.freed || NONE) {
1983
+ // a retired version: its machines link anew if they are started again
1984
+ for (const [m, l] of this._linked) if (l.segment === segment) this._linked.delete(m);
1985
+ for (const k of this._byChart.keys()) if (k.startsWith(`${segment}:`)) this._byChart.delete(k);
1986
+ this._images[segment] = undefined;
1987
+ }
1988
+ }
1989
+
1990
+ /** Native resources in use, per live version (segment). */
1991
+ stats() {
1992
+ const st = native.stats(this._host);
1993
+ return st.versions.map((v) => ({
1994
+ maxActors: v.maxActors,
1995
+ actors: v.actors,
1996
+ hibernated: v.hibernated,
1997
+ sessions: st.sessions,
1998
+ payloads: st.payloads,
1999
+ ...this._stats,
2000
+ }));
2001
+ }
2002
+ }
2003
+
2004
+ let defaultSystem = null;
2005
+ function getDefaultSystem() {
2006
+ if (!defaultSystem) defaultSystem = new System();
2007
+ return defaultSystem;
2008
+ }
2009
+
2010
+ /** A new, empty actor system. `createActor(machine, { system })` starts actors in it. */
2011
+ function createSystem(options) {
2012
+ return new System(options);
2013
+ }
2014
+
2015
+ /* ------------------------------------------------------------------- actors */
2016
+
2017
+ function stateValue(node, active) {
2018
+ const kids = node.children.filter((k) => active.has(k.id) && k.type !== 'history');
2019
+ const leaf = (k) => !k.children.some((c) => c.type !== 'history');
2020
+ if (node.type === 'parallel') {
2021
+ const out = {};
2022
+ for (const k of kids) out[k.key] = leaf(k) ? {} : stateValue(k, active);
2023
+ return out;
2024
+ }
2025
+ const k = kids[0];
2026
+ if (!k) return {};
2027
+ return leaf(k) ? k.key : { [k.key]: stateValue(k, active) };
2028
+ }
2029
+
2030
+ function flattenValue(v, prefix) {
2031
+ if (typeof v === 'string') return [prefix ? `${prefix}.${v}` : v];
2032
+ const out = [];
2033
+ for (const [k, sub] of Object.entries(v)) {
2034
+ const p = prefix ? `${prefix}.${k}` : k;
2035
+ out.push(p);
2036
+ out.push(...flattenValue(sub, p).filter((x) => x !== p));
2037
+ }
2038
+ return out;
2039
+ }
2040
+
2041
+ class Actor {
2042
+ constructor(logic, options = {}) {
2043
+ this.logic = logic;
2044
+ this.options = options;
2045
+ this.id = options.id || logic.id;
2046
+ this.system = options.system || getDefaultSystem();
2047
+ this._observers = new Set();
2048
+ this._status = 'active';
2049
+ this._started = false;
2050
+ this._live = false; /* spawned and not finished */
2051
+ this._session = 0; /* its session id: names it for life (also after migration) */
2052
+ this._serial = 0;
2053
+ this._snapshot = null;
2054
+ this._snapVersion = -1;
2055
+ this._lastNotified = null;
2056
+ this._output = undefined;
2057
+ this._error = undefined;
2058
+ this._final = null; /* { ids, context } once done */
2059
+ this._hibernated = false;
2060
+ }
2061
+
2062
+ /** True while the actor is hibernated (unloaded to the system's store). */
2063
+ get hibernated() {
2064
+ return this._hibernated;
2065
+ }
2066
+
2067
+ /** This actor's address (usable from other systems across a link). */
2068
+ get address() {
2069
+ return this._live ? addressOf(this) : undefined;
2070
+ }
2071
+
2072
+ start() {
2073
+ if (this._started) return this;
2074
+ this._started = true;
2075
+ this._chart = this.logic._compile().chart;
2076
+ this.system._do(() => {
2077
+ this.system._spawn(this);
2078
+ this.system._pump();
2079
+ });
2080
+ return this;
2081
+ }
2082
+
2083
+ send(event) {
2084
+ if (typeof event === 'string') event = { type: event };
2085
+ if (!event || typeof event.type !== 'string') throw new TypeError('events must be objects with a string "type"');
2086
+ if (!this._started || this._status !== 'active') return;
2087
+ this.system._do(() => {
2088
+ if (this._status !== 'active') return;
2089
+ this.system._send(this, event);
2090
+ this.system._pump();
2091
+ });
2092
+ }
2093
+
2094
+ _fail(error) {
2095
+ this._error = error;
2096
+ for (const o of this._observers) o.error && o.error(error);
2097
+ }
2098
+
2099
+ _finish(state, output, context, config) {
2100
+ this._status = 'done';
2101
+ this._output = output;
2102
+ const ids = config && state === this._chart.doneID ? config : [state];
2103
+ this._final = { ids, context };
2104
+ this.system._forget(this);
2105
+ this._snapVersion = -1;
2106
+ const snap = this.getSnapshot();
2107
+ for (const o of this._observers) o.next && o.next(snap);
2108
+ for (const o of this._observers) o.complete && o.complete();
2109
+ this._observers.clear();
2110
+ }
2111
+
2112
+ _notify() {
2113
+ if (!this._observers.size || this._status !== 'active') return;
2114
+ const s = this.getSnapshot();
2115
+ const key = JSON.stringify(s.value);
2116
+ const last = this._lastNotified;
2117
+ if (last && last.key === key && last.context === s.context) return;
2118
+ this._lastNotified = { key, context: s.context };
2119
+ for (const o of this._observers) o.next && o.next(s);
2120
+ }
2121
+
2122
+ _makeSnapshot() {
2123
+ let ids;
2124
+ let context;
2125
+ if (this._final) {
2126
+ ids = this._final.ids;
2127
+ context = this._final.context;
2128
+ } else if (this._live && this._status === 'active') {
2129
+ ids = native.config(this.system._host, this._session);
2130
+ context = native.context(this.system._host, this._session);
2131
+ } else {
2132
+ return this._snapshot;
2133
+ }
2134
+ const active = new Set(ids);
2135
+ const chart = this._chart;
2136
+ const value = active.size ? stateValue(chart.root, active) : {};
2137
+ const { _status: status, _output: output, _error: error } = this;
2138
+ const paths = new Set(flattenValue(value, ''));
2139
+ return {
2140
+ value,
2141
+ context,
2142
+ status,
2143
+ output,
2144
+ error,
2145
+ matches(v) {
2146
+ return flattenValue(v, '').every((p) => paths.has(p));
2147
+ },
2148
+ hasTag(tag) {
2149
+ for (const p of paths) {
2150
+ const n = chart.nodes.get(p);
2151
+ if (n && n.tags.includes(tag)) return true;
2152
+ }
2153
+ return false;
2154
+ },
2155
+ toJSON() {
2156
+ return { value, context, status, output };
2157
+ },
2158
+ };
2159
+ }
2160
+
2161
+ getSnapshot() {
2162
+ if (!this._started) return { value: {}, context: undefined, status: 'active', matches: () => false, hasTag: () => false };
2163
+ const frozen = this._status !== 'active';
2164
+ if (this._hibernated && this._snapshot) return this._snapshot;
2165
+ if (!frozen && this._snapVersion !== this.system._version) {
2166
+ this._snapshot = this._makeSnapshot();
2167
+ this._snapVersion = this.system._version;
2168
+ } else if (this._snapVersion === -1) {
2169
+ this._snapshot = this._makeSnapshot();
2170
+ this._snapVersion = this.system._version;
2171
+ }
2172
+ return this._snapshot;
2173
+ }
2174
+
2175
+ subscribe(nextOrObserver, error, complete) {
2176
+ const o = typeof nextOrObserver === 'function' ? { next: nextOrObserver, error, complete } : nextOrObserver;
2177
+ this._observers.add(o);
2178
+ if (this._status === 'active') {
2179
+ this.system._observed.add(this);
2180
+ const s = this.getSnapshot();
2181
+ if (s && s.value) this._lastNotified = { key: JSON.stringify(s.value), context: s.context };
2182
+ }
2183
+ return {
2184
+ unsubscribe: () => {
2185
+ this._observers.delete(o);
2186
+ if (!this._observers.size) this.system._observed.delete(this);
2187
+ },
2188
+ };
2189
+ }
2190
+
2191
+ stop() {
2192
+ if (this._halt())
2193
+ this.system._do(() => {
2194
+ this.system._terminate(this);
2195
+ this.system._pump();
2196
+ });
2197
+ return this;
2198
+ }
2199
+
2200
+ /* the JS side of stopping: freeze the snapshot, complete observers */
2201
+ _halt() {
2202
+ let was = false;
2203
+ if (this._status === 'active' && this._started) {
2204
+ was = true;
2205
+ if (!this._hibernated) this._snapshot = this._makeSnapshot();
2206
+ this._status = 'stopped';
2207
+ if (this._snapshot) this._snapshot = { ...this._snapshot, status: 'stopped' };
2208
+ this._snapVersion = this.system._version;
2209
+ }
2210
+ for (const o of this._observers) o.complete && o.complete();
2211
+ this._observers.clear();
2212
+ this.system._observed.delete(this);
2213
+ return was;
2214
+ }
2215
+ }
2216
+
2217
+ function createActor(logic, options) {
2218
+ return new Actor(logic, options);
2219
+ }
2220
+
2221
+ /* ------------------------------------------------------------------- links
2222
+ * A link carries envelopes between two systems over a WebSocket-like
2223
+ * transport, speaking the link protocol v1 (docs/protocol.md, "Link
2224
+ * protocol"): hello {v, id, reach, caps, cred}, ev (an envelope), err,
2225
+ * ping/pong. Routing is the native router's: each connection is one router
2226
+ * peer, and this code only moves frames between it and the wire. The client
2227
+ * side of a link is an actor whose state is the connection status. A
2228
+ * transport is WebSocket-like (one text per message) or a byte stream
2229
+ * (length-prefixed frames, streamTransport below). */
2230
+ const LINK_V = 1;
2231
+ const PEER_TRUSTED = 1, PEER_QUEUE = 2;
2232
+ const REASONS = ['', 'unknown-target', 'unreachable', 'denied', 'expired', 'hops', 'malformed'];
2233
+ const str = (v) => (typeof v === 'string' ? v : '');
2234
+ const parseFrame = (text) => {
2235
+ try {
2236
+ const m = JSON.parse(text);
2237
+ return m && typeof m === 'object' && typeof m.t === 'string' ? m : null;
2238
+ } catch {
2239
+ return null;
2240
+ }
2241
+ };
2242
+ /* what a hello announces: valid system ids only */
2243
+ const reachOf = (msg) => (Array.isArray(msg.reach) ? msg.reach.filter(systemIDValid) : []);
2244
+
2245
+ /* what both sides of a link share: frames, envelopes, values on the wire */
2246
+ class PeerConn {
2247
+ constructor(system, options) {
2248
+ this.system = system;
2249
+ this.options = options;
2250
+ this.ws = null;
2251
+ this.open = false;
2252
+ this.peer = 0; /* the router's handle */
2253
+ this.remoteID = null;
2254
+ this.reach = [];
2255
+ this.announce = !!options.announce;
2256
+ this.announced = null;
2257
+ this.profile = 'neutral'; /* "js" once both hellos announced it */
2258
+ this.maxFrame = options.maxFrame || FRAME_MAX; /* what we accept, announced in our hello */
2259
+ this.peerMax = FRAME_MAX; /* what the peer accepts (its hello's caps.max_frame) */
2260
+ }
2261
+ /* the value encoding both sides understand (docs/protocol.md, "Link protocol") */
2262
+ negotiate(msg) {
2263
+ const caps = msg.caps && typeof msg.caps === 'object' ? msg.caps : {};
2264
+ this.profile = caps.profile === 'js' && this.options.profile !== 'neutral' ? 'js' : 'neutral';
2265
+ this.peerMax = Number.isInteger(caps.max_frame) && caps.max_frame > 0 ? caps.max_frame : FRAME_MAX;
2266
+ }
2267
+ send(msg) {
2268
+ this.ws.send(JSON.stringify(msg));
2269
+ }
2270
+ hello() {
2271
+ const reach = this.announce ? this.system._reachFor(this) : [];
2272
+ const key = reach.join(' ');
2273
+ if (this.announced === key) return;
2274
+ this.announced = key;
2275
+ const profile = this.options.profile === 'neutral' ? 'neutral' : 'js';
2276
+ const msg = { t: 'hello', v: LINK_V, id: this.system.id, reach, caps: { profile, ordered: true, acks: false, max_frame: this.maxFrame } };
2277
+ if (this.options.credential !== undefined) msg.cred = this.options.credential;
2278
+ this.send(msg);
2279
+ }
2280
+ /* a TA_HOST_EFFECT_PEER effect: the envelope goes out on the wire */
2281
+ envelope(p) {
2282
+ const msg = { t: 'ev', target: p.target, name: p.name, origin: p.origin, msgid: p.msgid, hops: p.hops };
2283
+ const fail = (reason) => this.system._fromPeer(this.peer, { t: 'err', origin: p.origin, msgid: p.msgid, sendid: p.sendid, reason });
2284
+ if (p.sendid) msg.sendid = p.sendid;
2285
+ let text;
2286
+ try {
2287
+ if (p.data !== undefined) msg.data = this.profile === 'js' ? encodeTagged(p.data) : encodeWire(p.data);
2288
+ text = JSON.stringify(msg);
2289
+ } catch {
2290
+ return fail('malformed'); /* not representable (a cycle on a neutral link, a function) */
2291
+ }
2292
+ /* the peer refuses frames above its max_frame: fail it here, where the origin is known */
2293
+ if (text.length * 3 > this.peerMax && utf8.encode(text).length > this.peerMax) return fail('malformed');
2294
+ /* the connection went away under the router's feet: it is undeliverable */
2295
+ if (!this.post(msg, text)) fail('unreachable');
2296
+ }
2297
+ post(msg, text = JSON.stringify(msg)) {
2298
+ if (!this.open || !this.ws) return false;
2299
+ this.ws.send(text);
2300
+ return true;
2301
+ }
2302
+ decode(data) {
2303
+ return this.profile === 'js' ? decodeTagged(data, this.system) : decodeWire(data, this.system);
2304
+ }
2305
+ /* frames every connection handles alike; false: not one of them */
2306
+ common(ws, msg) {
2307
+ if (msg.t === 'hello') return false;
2308
+ if (msg.t === 'ping') ws.send(JSON.stringify({ t: 'pong', at: msg.at }));
2309
+ else if ((msg.t === 'ev' || msg.t === 'err') && this.peer && this.remoteID) this.system._fromPeer(this.peer, msg);
2310
+ return true; /* pong is the caller's; ack and unknown types are ignored */
2311
+ }
2312
+ }
2313
+
2314
+ const linkConns = new Map();
2315
+ let linkSeq = 0;
2316
+ const linkMachine = createMachine(
2317
+ {
2318
+ id: 'link',
2319
+ initial: 'connecting',
2320
+ context: ({ input }) => ({ link: input.link, url: input.url, attempts: 0, rtt: null, queued: 0, openedAt: null, peer: null, error: null }),
2321
+ on: {
2322
+ CLOSE: '.closed',
2323
+ QUEUED: { actions: assign({ queued: ({ event }) => event.n }) },
2324
+ },
2325
+ states: {
2326
+ connecting: {
2327
+ entry: 'connect',
2328
+ on: {
2329
+ OPENED: { target: 'open', actions: assign(({ event }) => ({ attempts: 0, openedAt: event.at, peer: event.peer, error: null })) },
2330
+ DROPPED: { target: 'reconnecting', actions: assign(({ context, event }) => ({ attempts: context.attempts + 1, error: event.error || null })) },
2331
+ },
2332
+ },
2333
+ open: {
2334
+ on: {
2335
+ RTT: { actions: assign({ rtt: ({ event }) => event.ms }) },
2336
+ DROPPED: { target: 'reconnecting', actions: assign(({ event }) => ({ attempts: 1, openedAt: null, rtt: null, error: event.error || null })) },
2337
+ },
2338
+ },
2339
+ reconnecting: { after: { backoff: 'connecting' } },
2340
+ closed: { type: 'final', entry: 'disconnect' },
2341
+ },
2342
+ },
2343
+ {
2344
+ actions: {
2345
+ connect: ({ context }) => linkConns.get(context.link) && linkConns.get(context.link).connect(),
2346
+ disconnect: ({ context }) => linkConns.get(context.link) && linkConns.get(context.link).disconnect(),
2347
+ },
2348
+ delays: { backoff: ({ context }) => Math.min(30000, 250 * 2 ** Math.min(context.attempts - 1, 7)) },
2349
+ },
2350
+ );
2351
+ registry.delete(linkMachine); /* linked on demand, not into every default image */
2352
+
2353
+ class LinkConn extends PeerConn {
2354
+ constructor(system, options) {
2355
+ super(system, options);
2356
+ this.id = ++linkSeq;
2357
+ this.alias = options.name || 'remote';
2358
+ if (!systemIDValid(this.alias)) throw new TypeError(`createLink: name "${this.alias}" is not a system id`);
2359
+ this.closed = false;
2360
+ this.pinger = null;
2361
+ this.actor = null;
2362
+ this.queued = 0;
2363
+ const queue = options.maxQueue !== 0;
2364
+ const flags = (options.trusted === false ? 0 : PEER_TRUSTED) | (queue ? PEER_QUEUE : 0);
2365
+ this.peer = native.peerAdd(system._host, this.alias, [], flags, options.maxQueue || 1000, options.queueTTLMs || 0);
2366
+ if (!this.peer) throw new Error(`createLink: cannot add a peer "${this.alias}"`);
2367
+ native.peerUp(system._host, this.peer, false); /* not connected yet: envelopes queue */
2368
+ linkConns.set(this.id, this);
2369
+ system._attach(this);
2370
+ system._links.add(this);
2371
+ }
2372
+ connect() {
2373
+ if (this.closed) return;
2374
+ let ws;
2375
+ try {
2376
+ ws = this.options.transport ? asTransport(this.options.transport(), this.maxFrame) : new WebSocket(this.options.url);
2377
+ } catch (e) {
2378
+ platform.defer(() => this.dropped(ws, String(e && e.message ? e.message : e)));
2379
+ return;
2380
+ }
2381
+ this.ws = ws;
2382
+ this.announced = null;
2383
+ ws.onopen = () => this.hello();
2384
+ ws.onmessage = (ev) => this.message(ws, String(ev.data));
2385
+ ws.onclose = () => this.dropped(ws, 'connection closed');
2386
+ ws.onerror = () => {}; /* followed by onclose */
2387
+ }
2388
+ message(ws, text) {
2389
+ if (ws !== this.ws) return;
2390
+ const msg = parseFrame(text);
2391
+ if (!msg || this.common(ws, msg)) {
2392
+ if (msg && msg.t === 'pong') {
2393
+ const ms = Math.round((this.system._now() - msg.at) * 10) / 10;
2394
+ native.peerRtt(this.system._host, this.peer, ms);
2395
+ this.actor.send({ type: 'RTT', ms });
2396
+ }
2397
+ return;
2398
+ }
2399
+ /* hello: the server's id and what it reaches (repeated when that changes) */
2400
+ if (msg.v !== LINK_V || !systemIDValid(msg.id)) {
2401
+ ws.close();
2402
+ return;
2403
+ }
2404
+ const first = !this.open;
2405
+ this.remoteID = msg.id;
2406
+ this.reach = reachOf(msg);
2407
+ this.negotiate(msg);
2408
+ this.open = true;
2409
+ this.system._peerHello(this, [msg.id, ...this.reach]);
2410
+ if (!first) return;
2411
+ this.actor.send({ type: 'OPENED', peer: msg.id, at: this.system._now() });
2412
+ const every = this.options.pingMs === undefined ? 5000 : this.options.pingMs;
2413
+ if (every > 0) {
2414
+ const ping = () => ws.send(JSON.stringify({ t: 'ping', at: this.system._now() }));
2415
+ ping();
2416
+ this.pinger = setInterval(ping, every);
2417
+ if (this.pinger.unref) this.pinger.unref();
2418
+ }
2419
+ }
2420
+ /* our name for the server (the link's alias) becomes its own id on the wire */
2421
+ envelope(p) {
2422
+ const a = this.remoteID && this.alias !== this.remoteID ? parseAddress(p.target) : null;
2423
+ super.envelope(a && a.system === this.alias ? { ...p, target: `tinyactors://${this.remoteID}/${a.local}` } : p);
2424
+ }
2425
+ /* the router's queue for this peer, reported to the link actor */
2426
+ sync() {
2427
+ const st = native.peerStatus(this.system._host, this.peer);
2428
+ const n = st ? st.queued : 0;
2429
+ if (n !== this.queued && this.actor) {
2430
+ this.queued = n;
2431
+ this.actor.send({ type: 'QUEUED', n });
2432
+ }
2433
+ }
2434
+ dropped(ws, error) {
2435
+ if (ws !== this.ws) return;
2436
+ this.ws = null;
2437
+ this.open = false;
2438
+ clearInterval(this.pinger);
2439
+ this.pinger = null;
2440
+ if (this.closed) return;
2441
+ this.system._peerDown(this, false);
2442
+ this.actor.send({ type: 'DROPPED', error });
2443
+ }
2444
+ disconnect() {
2445
+ if (this.closed) return;
2446
+ this.closed = true;
2447
+ this.open = false;
2448
+ clearInterval(this.pinger);
2449
+ const ws = this.ws;
2450
+ this.ws = null;
2451
+ if (ws) ws.close();
2452
+ this.system._links.delete(this);
2453
+ linkConns.delete(this.id);
2454
+ if (!this.system._stopped) this.system._peerDown(this, true);
2455
+ }
2456
+ }
2457
+
2458
+ /** Link `system` to another system (e.g. a browser to its server). */
2459
+ function createLink(system, options = {}) {
2460
+ if (!(system instanceof System)) throw new TypeError('createLink(system, options): system expected');
2461
+ if (!options.url && !options.transport) throw new TypeError('createLink: { url } or { transport } needed');
2462
+ const conn = new LinkConn(system, options);
2463
+ const actor = createActor(linkMachine, { system, id: `link:${conn.alias}`, input: { link: conn.id, url: options.url } });
2464
+ conn.actor = actor;
2465
+ actor.get = (systemID) => system.ref(formatAddress(conn.alias, systemID));
2466
+ actor.close = () => actor.send({ type: 'CLOSE' });
2467
+ actor.status = () => native.peerStatus(system._host, conn.peer);
2468
+ return actor.start();
2469
+ }
2470
+
2471
+ /* exports: ['lobby', ...] or { lobby: 'JOIN LEAVE', ... } -> [name, events] */
2472
+ function exportsOf(x) {
2473
+ if (!x) return [];
2474
+ if (Array.isArray(x)) return x.map((n) => [String(n), '']);
2475
+ return Object.entries(x).map(([n, ev]) => [n, Array.isArray(ev) ? ev.join(' ') : String(ev || '')]);
2476
+ }
2477
+
2478
+ class ServerConn extends PeerConn {
2479
+ constructor(system, options, ws, server) {
2480
+ super(system, options);
2481
+ this.ws = ws;
2482
+ this.server = server;
2483
+ }
2484
+ }
2485
+
2486
+ /** Accept links into `system`: `accept(onConnection)` registers a source of
2487
+ * open transports (WebSocket-like or byte streams) and may return a function
2488
+ * that stops it. Untrusted peers
2489
+ * (the default) may only send to what `exports` lists; trusted ones
2490
+ * (`trusted: true`, or `trust(hello)` returning true) may send anything and
2491
+ * relay through this system. A peer that reconnects with the same system id
2492
+ * within `resumeMs` resumes: what was queued for it meanwhile is delivered.
2493
+ * The resumption window runs on the system's clock, like the router's queue
2494
+ * TTL — with a `clock` option, flush() moves it. */
2495
+ function serveLinks(system, options = {}) {
2496
+ if (typeof options.accept !== 'function') throw new TypeError('serveLinks(system, { accept }) needs an accept function here');
2497
+ const conns = new Set();
2498
+ const byID = new Map(); /* remote system id -> its ServerConn (also while it is away) */
2499
+ const expiry = new Map(); /* remote system id -> cancels the resumption of its peer */
2500
+ const resumeMs = options.resumeMs === undefined ? 30000 : options.resumeMs;
2501
+ const rules = exportsOf(options.exports);
2502
+ const trusts = (hello) => (typeof options.trust === 'function' ? !!options.trust(hello) : !!options.trusted);
2503
+ const server = { closed: false };
2504
+ const forget = (c) => {
2505
+ const cancel = expiry.get(c.remoteID);
2506
+ if (cancel) cancel();
2507
+ expiry.delete(c.remoteID);
2508
+ if (byID.get(c.remoteID) === c) byID.delete(c.remoteID);
2509
+ system._peerDown(c, true);
2510
+ };
2511
+ const hello = (c, ws, msg) => {
2512
+ if (msg.v !== LINK_V || !systemIDValid(msg.id) || msg.id === system.id) return ws.close();
2513
+ c.reach = reachOf(msg);
2514
+ c.negotiate(msg);
2515
+ if (c.peer) return system._peerHello(c, c.reach); /* a repeated hello: new reach */
2516
+ c.remoteID = msg.id;
2517
+ const before = byID.get(msg.id);
2518
+ if (before) {
2519
+ /* the same system again: the newer connection wins and resumes its peer */
2520
+ const cancel = expiry.get(msg.id);
2521
+ if (cancel) cancel();
2522
+ expiry.delete(msg.id);
2523
+ if (before.ws && before.ws !== ws) {
2524
+ const old = before.ws;
2525
+ before.ws = null;
2526
+ before.open = false;
2527
+ conns.delete(before);
2528
+ old.close();
2529
+ }
2530
+ c.peer = before.peer;
2531
+ } else {
2532
+ const flags = (trusts(msg) ? PEER_TRUSTED : 0) | (resumeMs > 0 ? PEER_QUEUE : 0);
2533
+ c.peer = native.peerAdd(system._host, msg.id, c.reach, flags, options.maxQueue || 1000, resumeMs);
2534
+ if (!c.peer) return ws.close();
2535
+ for (const [name, events] of rules) native.exportName(system._host, c.peer, name, events);
2536
+ }
2537
+ byID.set(msg.id, c);
2538
+ system._attach(c);
2539
+ c.open = true;
2540
+ c.hello();
2541
+ system._peerHello(c, c.reach);
2542
+ };
2543
+ const onConnection = (transport) => {
2544
+ const ws = asTransport(transport, options.maxFrame || FRAME_MAX);
2545
+ if (server.closed) return ws.close();
2546
+ const c = new ServerConn(system, options, ws, server);
2547
+ conns.add(c);
2548
+ ws.onmessage = (ev) => {
2549
+ if (c.ws !== ws) return;
2550
+ const msg = parseFrame(String(ev.data));
2551
+ if (msg && !c.common(ws, msg)) hello(c, ws, msg);
2552
+ };
2553
+ ws.onclose = () => {
2554
+ conns.delete(c);
2555
+ if (c.ws !== ws) return; /* replaced by a newer connection */
2556
+ c.ws = null;
2557
+ c.open = false;
2558
+ if (!c.peer || byID.get(c.remoteID) !== c) return;
2559
+ if (resumeMs > 0 && !server.closed) {
2560
+ system._peerDown(c, false); /* queue for it until it is back or resumeMs passed */
2561
+ const id = c.remoteID;
2562
+ /* the resumption window on the system's clock (with a `clock`
2563
+ * option, forget runs when flush() moves time past it) */
2564
+ expiry.set(id, system._at(system._now() + resumeMs, () => byID.get(id) === c && !c.ws && forget(c)));
2565
+ } else forget(c);
2566
+ };
2567
+ };
2568
+ const stop = options.accept(onConnection);
2569
+ return {
2570
+ connections: () => [...conns].filter((c) => c.open).map((c) => c.remoteID),
2571
+ status: (id) => (byID.get(id) ? native.peerStatus(system._host, byID.get(id).peer) : null),
2572
+ close: async () => {
2573
+ server.closed = true;
2574
+ for (const c of [...conns]) {
2575
+ const ws = c.ws;
2576
+ c.ws = null;
2577
+ c.open = false;
2578
+ if (ws) ws.close();
2579
+ }
2580
+ conns.clear();
2581
+ for (const c of [...byID.values()]) if (!system._stopped) forget(c);
2582
+ if (typeof stop === 'function') await stop();
2583
+ },
2584
+ };
2585
+ }
2586
+
2587
+ /* ------------------------------------------------------------- store links
2588
+ * A store link connects the system to a database of actors (docs/protocol.md,
2589
+ * "Store links": PostgreSQL's tinyactors extension) through SQL — with the
2590
+ * caller's client, whatever it is: `query(sql, params) -> Promise<rows>` and
2591
+ * optionally `listen(channel, onPayload) -> unlisten`. The database is one
2592
+ * router peer: envelopes for it go in with tinyactors.deliver(envelope)
2593
+ * (in order, retried until the database takes them: at-least-once, the
2594
+ * database drops repeats by msgid); envelopes from it are claimed from its
2595
+ * outbox (claim_for, ordered) when it NOTIFYs or every pollMs, handed to the
2596
+ * router and acked; errors travel both ways. Values are neutral. */
2597
+ class StoreConn extends PeerConn {
2598
+ constructor(system, options) {
2599
+ super(system, { ...options, announce: options.announce !== false, profile: 'neutral' });
2600
+ this.q = options.query;
2601
+ this.remoteID = options.id || null;
2602
+ this.worker = options.worker || `${system.id}/${randomID()}`;
2603
+ this.batch = options.batch || 100;
2604
+ this.out = []; /* frames for the database, in order */
2605
+ this.peerMax = Infinity; /* rows, not frames */
2606
+ this.pumping = false;
2607
+ this.draining = false;
2608
+ this.again = false;
2609
+ this.closed = false;
2610
+ this.error = null;
2611
+ this.idle = [];
2612
+ }
2613
+ async start() {
2614
+ if (!this.remoteID) {
2615
+ const r = await this.q('SELECT tinyactors.system_id() AS id', []);
2616
+ this.remoteID = r[0].id;
2617
+ }
2618
+ if (!systemIDValid(this.remoteID)) throw new TypeError(`createStoreLink: "${this.remoteID}" is not a system id`);
2619
+ const flags = (this.options.trusted === false ? 0 : PEER_TRUSTED) | PEER_QUEUE;
2620
+ this.peer = native.peerAdd(this.system._host, this.remoteID, [], flags, this.options.maxQueue || 10000, this.options.queueTTLMs || 0);
2621
+ if (!this.peer) throw new Error(`createStoreLink: cannot add a peer "${this.remoteID}"`);
2622
+ this.system._attach(this);
2623
+ this.system._links.add(this);
2624
+ this.open = true;
2625
+ this.hello(); /* tinyactors.hello(): what we reach is claimed by us */
2626
+ this.system._peerHello(this, []);
2627
+ if (this.options.listen) {
2628
+ this.unlisten = await this.options.listen('tinyactors_outbox', (payload) => {
2629
+ if (payload === this.system.id) this.drain();
2630
+ });
2631
+ }
2632
+ const every = this.options.pollMs === undefined ? 1000 : this.options.pollMs;
2633
+ if (every > 0) {
2634
+ this.poller = platform.setTimer(function tick() {
2635
+ this.drain();
2636
+ this.poller = platform.setTimer(tick.bind(this), every);
2637
+ if (this.poller && this.poller.unref) this.poller.unref();
2638
+ }.bind(this), every);
2639
+ if (this.poller && this.poller.unref) this.poller.unref();
2640
+ }
2641
+ await this.drain();
2642
+ }
2643
+ /* frames become SQL, in order */
2644
+ send(msg) {
2645
+ this.out.push(msg);
2646
+ this.pump();
2647
+ }
2648
+ post(msg) {
2649
+ if (this.closed) return false;
2650
+ this.send(msg);
2651
+ return true;
2652
+ }
2653
+ async pump() {
2654
+ if (this.pumping) return;
2655
+ this.pumping = true;
2656
+ try {
2657
+ while (this.out.length && !this.closed) {
2658
+ const msg = this.out[0];
2659
+ let r;
2660
+ try {
2661
+ r = await this.sql(msg);
2662
+ } catch (e) {
2663
+ this.failed(e); /* down: keep it, try again later */
2664
+ await new Promise((ok) => platform.setTimer(ok, 500));
2665
+ continue;
2666
+ }
2667
+ this.out.shift();
2668
+ this.recovered();
2669
+ if (msg.t === 'ev' && r !== 'ok' && r !== 'duplicate') {
2670
+ this.system._fromPeer(this.peer, { t: 'err', origin: msg.origin, msgid: msg.msgid, sendid: msg.sendid, reason: REASONS.includes(r) ? r : 'unreachable' });
2671
+ }
2672
+ }
2673
+ } finally {
2674
+ this.pumping = false;
2675
+ this.settled();
2676
+ }
2677
+ }
2678
+ async sql(msg) {
2679
+ if (msg.t === 'hello') {
2680
+ const r = await this.q('SELECT tinyactors.hello($1, $2::text[]) AS id', [msg.id, `{${msg.reach.join(',')}}`]);
2681
+ return r[0] && r[0].id;
2682
+ }
2683
+ if (msg.t === 'ev') {
2684
+ const { t, ...env } = msg;
2685
+ /* as this system: the database checks the origin against what we announced */
2686
+ const r = await this.q('SELECT tinyactors.deliver($1::jsonb, $2) AS r', [JSON.stringify(env), this.system.id]);
2687
+ return r[0] && r[0].r;
2688
+ }
2689
+ if (msg.t === 'err') {
2690
+ await this.q('SELECT tinyactors.deliver_error($1::jsonb)', [JSON.stringify({ origin: msg.origin, msgid: msg.msgid, sendid: msg.sendid, reason: msg.reason })]);
2691
+ }
2692
+ return null;
2693
+ }
2694
+ /* claim what the database has for us (and the systems we announced) */
2695
+ async drain() {
2696
+ if (this.closed || !this.peer) return;
2697
+ if (this.draining) {
2698
+ this.again = true;
2699
+ return;
2700
+ }
2701
+ this.draining = true;
2702
+ try {
2703
+ do {
2704
+ this.again = false;
2705
+ const rows = await this.q('SELECT id, envelope FROM tinyactors.claim_for($1, $2, $3)', [this.system.id, this.batch, this.worker]);
2706
+ for (const row of rows) {
2707
+ const env = typeof row.envelope === 'string' ? JSON.parse(row.envelope) : row.envelope;
2708
+ this.system._fromPeer(this.peer, { ...env, t: 'ev' });
2709
+ }
2710
+ if (rows.length) await this.q('SELECT tinyactors.ack(id) FROM unnest($1::bigint[]) AS id', [`{${rows.map((r) => r.id).join(',')}}`]);
2711
+ if (rows.length === this.batch) this.again = true;
2712
+ this.recovered();
2713
+ } while (this.again && !this.closed);
2714
+ } catch (e) {
2715
+ this.failed(e);
2716
+ } finally {
2717
+ this.draining = false;
2718
+ this.settled();
2719
+ }
2720
+ }
2721
+ failed(e) {
2722
+ this.error = String(e && e.message ? e.message : e);
2723
+ if (this.open) {
2724
+ this.open = false;
2725
+ this.system._peerDown(this, false); /* the router queues meanwhile */
2726
+ }
2727
+ }
2728
+ recovered() {
2729
+ if (this.open || this.closed) return;
2730
+ this.open = true;
2731
+ this.error = null;
2732
+ this.announced = null;
2733
+ this.hello();
2734
+ this.system._peerHello(this, []);
2735
+ }
2736
+ settled() {
2737
+ if (!this.pumping && !this.draining && !this.out.length) for (const ok of this.idle.splice(0)) ok();
2738
+ }
2739
+ sync() {}
2740
+ disconnect() {
2741
+ if (this.closed) return;
2742
+ this.closed = true;
2743
+ this.open = false;
2744
+ platform.clearTimer(this.poller);
2745
+ if (this.unlisten) Promise.resolve(this.unlisten()).catch(() => {});
2746
+ this.system._links.delete(this);
2747
+ if (!this.system._stopped) this.system._peerDown(this, true);
2748
+ this.settled();
2749
+ }
2750
+ }
2751
+
2752
+ /** Connect `system` to a database of actors (PostgreSQL + the tinyactors
2753
+ * extension) through your own client: `query(sql, params)` resolving to rows,
2754
+ * optionally `listen(channel, onPayload)`. */
2755
+ function createStoreLink(system, options = {}) {
2756
+ if (!(system instanceof System)) throw new TypeError('createStoreLink(system, options): system expected');
2757
+ if (typeof options.query !== 'function') throw new TypeError('createStoreLink: { query(sql, params) } is needed');
2758
+ const conn = new StoreConn(system, options);
2759
+ const ready = conn.start();
2760
+ ready.catch(() => {});
2761
+ return {
2762
+ get id() {
2763
+ return conn.remoteID;
2764
+ },
2765
+ ready,
2766
+ /** Claim and deliver what the database has for us now. */
2767
+ drain: () => ready.then(() => conn.drain()),
2768
+ /** Resolves once everything handed to the link reached the database and nothing is being claimed. */
2769
+ flush: () =>
2770
+ ready.then(
2771
+ () =>
2772
+ new Promise((ok) => {
2773
+ conn.idle.push(ok);
2774
+ conn.settled();
2775
+ }),
2776
+ ),
2777
+ status: () => (conn.peer ? { ...native.peerStatus(system._host, conn.peer), error: conn.error, pending: conn.out.length } : null),
2778
+ close: async () => {
2779
+ conn.disconnect();
2780
+ },
2781
+ };
2782
+ }
2783
+
2784
+ return {
2785
+ parseAddress,
2786
+ formatAddress,
2787
+ createStoreLink,
2788
+ encodeWire,
2789
+ decodeWire,
2790
+ createMachine,
2791
+ createActor,
2792
+ createSystem,
2793
+ fromSCXML,
2794
+ SCXMLLogic,
2795
+ compileSystem,
2796
+ loadImage,
2797
+ SystemImage,
2798
+ setup,
2799
+ assign,
2800
+ raise,
2801
+ sendTo,
2802
+ sendParent,
2803
+ log,
2804
+ cancel,
2805
+ stateIn,
2806
+ and,
2807
+ or,
2808
+ not,
2809
+ StateMachine,
2810
+ Actor,
2811
+ System,
2812
+ ActorRef,
2813
+ createLink,
2814
+ serveLinks,
2815
+ encodeFrame,
2816
+ FrameDecoder,
2817
+ createMemoryStore,
2818
+ encodeValue,
2819
+ decodeValue,
2820
+ };
2821
+ }
2822
+
2823
+ /* ------------------------------------------------------------------ frames
2824
+ * The link protocol over byte streams — TCP, stdio, serial (docs/protocol.md,
2825
+ * "Framing"): a 4-byte big-endian length, then that many bytes of UTF-8 JSON.
2826
+ * A frame above the receiver's max_frame (default 1 MiB) is refused as
2827
+ * malformed: skipped as it passes, never buffered, so the stream stays in
2828
+ * step. No platform APIs beyond TextEncoder/TextDecoder: any transport can
2829
+ * use the codec. */
2830
+ export const FRAME_MAX = 1 << 20;
2831
+ const utf8 = new TextEncoder();
2832
+ const utf8Strict = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
2833
+ const u32 = (b, i) => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0;
2834
+
2835
+ /** One frame: the length prefix and the UTF-8 bytes of `text`. */
2836
+ export function encodeFrame(text) {
2837
+ const body = utf8.encode(String(text));
2838
+ const out = new Uint8Array(4 + body.length);
2839
+ new DataView(out.buffer).setUint32(0, body.length);
2840
+ out.set(body, 4);
2841
+ return out;
2842
+ }
2843
+
2844
+ /** Bytes in, frames out: push() takes chunks as they arrive (any split) and
2845
+ * returns the frames they complete — a string each, or for a refused frame
2846
+ * { reason: 'malformed', length, detail }. */
2847
+ export class FrameDecoder {
2848
+ constructor({ maxFrame = FRAME_MAX } = {}) {
2849
+ this.maxFrame = maxFrame;
2850
+ this.head = new Uint8Array(4); /* a length prefix split across chunks */
2851
+ this.headN = 0;
2852
+ this.body = null; /* the frame being completed */
2853
+ this.bodyN = 0;
2854
+ this.skip = 0; /* bytes of a refused frame still to pass */
2855
+ }
2856
+ push(chunk) {
2857
+ const out = [];
2858
+ const n = chunk.length;
2859
+ let i = 0;
2860
+ while (i < n) {
2861
+ if (this.skip) {
2862
+ const k = Math.min(this.skip, n - i);
2863
+ this.skip -= k;
2864
+ i += k;
2865
+ continue;
2866
+ }
2867
+ if (!this.body) {
2868
+ let len;
2869
+ if (!this.headN && n - i >= 4) {
2870
+ len = u32(chunk, i);
2871
+ i += 4;
2872
+ } else {
2873
+ this.head[this.headN++] = chunk[i++];
2874
+ if (this.headN < 4) continue;
2875
+ this.headN = 0;
2876
+ len = u32(this.head, 0);
2877
+ }
2878
+ if (len > this.maxFrame) {
2879
+ out.push({ reason: 'malformed', length: len, detail: `a frame of ${len} bytes is above max_frame (${this.maxFrame})` });
2880
+ this.skip = len;
2881
+ continue;
2882
+ }
2883
+ if (n - i >= len) {
2884
+ out.push(this._text(chunk.subarray(i, i + len)));
2885
+ i += len;
2886
+ continue;
2887
+ }
2888
+ this.body = new Uint8Array(len);
2889
+ this.bodyN = 0;
2890
+ }
2891
+ const k = Math.min(this.body.length - this.bodyN, n - i);
2892
+ this.body.set(chunk.subarray(i, i + k), this.bodyN);
2893
+ this.bodyN += k;
2894
+ i += k;
2895
+ if (this.bodyN === this.body.length) {
2896
+ out.push(this._text(this.body));
2897
+ this.body = null;
2898
+ }
2899
+ }
2900
+ return out;
2901
+ }
2902
+ _text(bytes) {
2903
+ try {
2904
+ return utf8Strict.decode(bytes);
2905
+ } catch {
2906
+ return { reason: 'malformed', length: bytes.length, detail: 'a frame that is not UTF-8' };
2907
+ }
2908
+ }
2909
+ }
2910
+
2911
+ /* A byte stream as a link transport (the WebSocket-like shape links use):
2912
+ * a Node-style duplex (a net.Socket) or a { readable, writable } pair of
2913
+ * Node-style streams (a child process's stdout/stdin, or process.stdin/stdout
2914
+ * inside the child). Anything with send() is a transport already. */
2915
+ function asTransport(x, maxFrame) {
2916
+ return x && typeof x.send !== 'function' && (typeof x.write === 'function' || (x.writable && typeof x.writable.write === 'function'))
2917
+ ? streamTransport(x, maxFrame)
2918
+ : x;
2919
+ }
2920
+
2921
+ function streamTransport(stream, maxFrame) {
2922
+ const pair = typeof stream.write !== 'function';
2923
+ const r = pair ? stream.readable : stream;
2924
+ const w = pair ? stream.writable : stream;
2925
+ const decoder = new FrameDecoder({ maxFrame });
2926
+ const t = { onopen: null, onmessage: null, onclose: null, onerror: null, readyState: 0 };
2927
+ let done = false;
2928
+ const data = (chunk) => {
2929
+ for (const f of decoder.push(chunk)) {
2930
+ if (done) return;
2931
+ if (typeof f === 'string') t.onmessage && t.onmessage({ data: f });
2932
+ else t.onerror && t.onerror(f); /* refused (skipped); the stream stays in step */
2933
+ }
2934
+ };
2935
+ const finish = () => {
2936
+ if (done) return;
2937
+ done = true;
2938
+ t.readyState = 3;
2939
+ r.off('data', data);
2940
+ queueMicrotask(() => t.onclose && t.onclose({}));
2941
+ };
2942
+ t.send = (text) => {
2943
+ if (!done) w.write(encodeFrame(text));
2944
+ };
2945
+ t.close = () => {
2946
+ if (done) return;
2947
+ try {
2948
+ w.end();
2949
+ if (pair && r.destroy) r.destroy();
2950
+ } catch {
2951
+ /* e.g. process.stdout cannot be ended */
2952
+ }
2953
+ finish();
2954
+ };
2955
+ r.on('data', data);
2956
+ for (const s of pair ? [r, w] : [r]) for (const ev of ['end', 'close', 'error']) s.on(ev, finish);
2957
+ if (r.destroyed || r.readableEnded) finish();
2958
+ else if (w.connecting) w.once('connect', () => !done && ((t.readyState = 1), t.onopen && t.onopen({})));
2959
+ else
2960
+ queueMicrotask(() => {
2961
+ if (done) return;
2962
+ t.readyState = 1;
2963
+ if (t.onopen) t.onopen({});
2964
+ });
2965
+ return t;
2966
+ }