ihsm 0.0.26 → 0.1.21

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.
Files changed (103) hide show
  1. package/README.md +105 -113
  2. package/lib/cjs/index.d.ts +8 -1394
  3. package/lib/cjs/index.js +65 -764
  4. package/lib/cjs/index.js.map +1 -1
  5. package/lib/cjs/internal/console-instrumentation.d.ts +34 -0
  6. package/lib/cjs/internal/console-instrumentation.js +71 -0
  7. package/lib/cjs/internal/console-instrumentation.js.map +1 -0
  8. package/lib/cjs/internal/identity.d.ts +16 -0
  9. package/lib/cjs/internal/identity.js +170 -0
  10. package/lib/cjs/internal/identity.js.map +1 -0
  11. package/lib/cjs/internal/instrumentation.d.ts +47 -0
  12. package/lib/cjs/internal/instrumentation.js +201 -0
  13. package/lib/cjs/internal/instrumentation.js.map +1 -0
  14. package/lib/cjs/internal/runtime.d.ts +376 -0
  15. package/lib/cjs/internal/runtime.js +2530 -0
  16. package/lib/cjs/internal/runtime.js.map +1 -0
  17. package/lib/cjs/internal/types.d.ts +515 -0
  18. package/lib/cjs/internal/types.js +9 -0
  19. package/lib/cjs/internal/types.js.map +1 -0
  20. package/lib/cjs/test-only.d.ts +5 -0
  21. package/lib/cjs/test-only.js +21 -0
  22. package/lib/cjs/test-only.js.map +1 -0
  23. package/lib/cjs/testing.d.ts +120 -88
  24. package/lib/cjs/testing.js +126 -38
  25. package/lib/cjs/testing.js.map +1 -1
  26. package/lib/cjs/transition-routines.d.ts +3 -0
  27. package/lib/cjs/transition-routines.js +11 -0
  28. package/lib/cjs/transition-routines.js.map +1 -0
  29. package/lib/cjs/types.d.ts +5 -0
  30. package/lib/cjs/{internal/defs.private.js → types.js} +1 -1
  31. package/lib/cjs/types.js.map +1 -0
  32. package/lib/esm/index.d.ts +8 -1394
  33. package/lib/esm/index.js +5 -742
  34. package/lib/esm/index.js.map +1 -1
  35. package/lib/esm/internal/console-instrumentation.d.ts +34 -0
  36. package/lib/esm/internal/console-instrumentation.js +68 -0
  37. package/lib/esm/internal/console-instrumentation.js.map +1 -0
  38. package/lib/esm/internal/identity.d.ts +16 -0
  39. package/lib/esm/internal/identity.js +159 -0
  40. package/lib/esm/internal/identity.js.map +1 -0
  41. package/lib/esm/internal/instrumentation.d.ts +47 -0
  42. package/lib/esm/internal/instrumentation.js +178 -0
  43. package/lib/esm/internal/instrumentation.js.map +1 -0
  44. package/lib/esm/internal/runtime.d.ts +376 -0
  45. package/lib/esm/internal/runtime.js +2462 -0
  46. package/lib/esm/internal/runtime.js.map +1 -0
  47. package/lib/esm/internal/types.d.ts +515 -0
  48. package/lib/esm/internal/types.js +6 -0
  49. package/lib/esm/internal/types.js.map +1 -0
  50. package/lib/esm/test-only.d.ts +5 -0
  51. package/lib/esm/test-only.js +15 -0
  52. package/lib/esm/test-only.js.map +1 -0
  53. package/lib/esm/testing.d.ts +120 -88
  54. package/lib/esm/testing.js +125 -38
  55. package/lib/esm/testing.js.map +1 -1
  56. package/lib/esm/transition-routines.d.ts +3 -0
  57. package/lib/esm/transition-routines.js +3 -0
  58. package/lib/esm/transition-routines.js.map +1 -0
  59. package/lib/esm/types.d.ts +5 -0
  60. package/lib/esm/types.js +2 -0
  61. package/lib/esm/types.js.map +1 -0
  62. package/package.json +22 -4
  63. package/lib/cjs/internal/defs.private.d.ts +0 -41
  64. package/lib/cjs/internal/defs.private.js.map +0 -1
  65. package/lib/cjs/internal/dispatch.debug.d.ts +0 -4
  66. package/lib/cjs/internal/dispatch.debug.js +0 -332
  67. package/lib/cjs/internal/dispatch.debug.js.map +0 -1
  68. package/lib/cjs/internal/dispatch.production.d.ts +0 -6
  69. package/lib/cjs/internal/dispatch.production.js +0 -241
  70. package/lib/cjs/internal/dispatch.production.js.map +0 -1
  71. package/lib/cjs/internal/dispatch.trace.d.ts +0 -4
  72. package/lib/cjs/internal/dispatch.trace.js +0 -418
  73. package/lib/cjs/internal/dispatch.trace.js.map +0 -1
  74. package/lib/cjs/internal/hsm.d.ts +0 -60
  75. package/lib/cjs/internal/hsm.js +0 -215
  76. package/lib/cjs/internal/hsm.js.map +0 -1
  77. package/lib/cjs/internal/lookup.d.ts +0 -15
  78. package/lib/cjs/internal/lookup.js +0 -32
  79. package/lib/cjs/internal/lookup.js.map +0 -1
  80. package/lib/cjs/internal/utils.d.ts +0 -26
  81. package/lib/cjs/internal/utils.js +0 -63
  82. package/lib/cjs/internal/utils.js.map +0 -1
  83. package/lib/esm/internal/defs.private.d.ts +0 -41
  84. package/lib/esm/internal/defs.private.js +0 -2
  85. package/lib/esm/internal/defs.private.js.map +0 -1
  86. package/lib/esm/internal/dispatch.debug.d.ts +0 -4
  87. package/lib/esm/internal/dispatch.debug.js +0 -328
  88. package/lib/esm/internal/dispatch.debug.js.map +0 -1
  89. package/lib/esm/internal/dispatch.production.d.ts +0 -6
  90. package/lib/esm/internal/dispatch.production.js +0 -237
  91. package/lib/esm/internal/dispatch.production.js.map +0 -1
  92. package/lib/esm/internal/dispatch.trace.d.ts +0 -4
  93. package/lib/esm/internal/dispatch.trace.js +0 -414
  94. package/lib/esm/internal/dispatch.trace.js.map +0 -1
  95. package/lib/esm/internal/hsm.d.ts +0 -60
  96. package/lib/esm/internal/hsm.js +0 -211
  97. package/lib/esm/internal/hsm.js.map +0 -1
  98. package/lib/esm/internal/lookup.d.ts +0 -15
  99. package/lib/esm/internal/lookup.js +0 -29
  100. package/lib/esm/internal/lookup.js.map +0 -1
  101. package/lib/esm/internal/utils.d.ts +0 -26
  102. package/lib/esm/internal/utils.js +0 -52
  103. package/lib/esm/internal/utils.js.map +0 -1
package/lib/cjs/index.js CHANGED
@@ -1,767 +1,68 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultInitialize = exports.defaultTraceWriter = exports.FatalErrorState = exports.InitializationError = exports.FatalError = exports.InitialStateError = exports.UnhandledEventError = exports.EventHandlerError = exports.TransitionError = exports.RuntimeError = exports.HsmError = exports.TopState = exports.Port = exports.BasePort = exports.TraceLevel = void 0;
4
- exports.InitialState = InitialState;
5
- exports.defineStateName = defineStateName;
6
- exports.registerStateNames = registerStateNames;
7
- exports.defaultDispatchErrorCallback = defaultDispatchErrorCallback;
8
- exports.makeHsm = makeHsm;
9
- exports.makeActor = makeActor;
10
- const hsm_1 = require("./internal/hsm");
11
- const utils_1 = require("./internal/utils");
12
- // export type DispatchErrorCallback<Context, Protocol extends {} | undefined> = (hsm: Hsm<Context, Protocol>, traceWriter: TraceWriter, err: Error) => void;
13
- /**
14
- * Controls how much diagnostic detail the runtime emits through {@link TraceWriter}.
15
- *
16
- * Set at construction via {@link makeHsm} or mutate {@link Properties.traceLevel} on a
17
- * live instance. Changing the level swaps the internal dispatch tracer implementation.
18
- *
19
- * @category Factory
20
- */
21
- var TraceLevel;
22
- (function (TraceLevel) {
23
- /**
24
- * Production mode: minimal tracing overhead, no verbose dispatch steps.
25
- * Use in hot paths and shipped bundles when trace output is disabled.
26
- */
27
- TraceLevel[TraceLevel["PRODUCTION"] = 0] = "PRODUCTION";
28
- /**
29
- * Debug mode: transition boundaries, handler entry/exit, and error summaries.
30
- * Default for {@link makeHsm}. Suitable for development and integration tests.
31
- */
32
- TraceLevel[TraceLevel["DEBUG"] = 1] = "DEBUG";
33
- /**
34
- * Verbose debug: includes prototype-chain lookup walks, cache hits/misses, and
35
- * nested trace domains. Use when correlating handler code with tutorial trace panels.
36
- */
37
- TraceLevel[TraceLevel["VERBOSE_DEBUG"] = 2] = "VERBOSE_DEBUG";
38
- })(TraceLevel || (exports.TraceLevel = TraceLevel = {}));
39
- /**
40
- * Abstract base class for **any** port production or test.
41
- *
42
- * It takes the machine's root {@link TopState} as its single type argument and derives the
43
- * context and internal protocol from it (via {@link MachineContext} / {@link MachineInternal}),
44
- * so the `TopState` is the one place those types are declared. Extend {@link Port} (not `BasePort`
45
- * directly) for production ports so timer and random services are available.
46
- *
47
- * The {@link BasePort.actor | actor} link is **bound lazily** by the runtime: construct the port
48
- * with no arguments and pass the instance to a factory, which wires the actor in afterwards.
49
- *
50
- * @typeParam T - The machine's root {@link TopState} subclass (e.g. `ConnTop`)
51
- *
52
- * @category Port
53
- */
54
- class BasePort {
55
- /**
56
- * @inheritdoc PortHandle.actor
57
- *
58
- * Set once by the runtime right after the machine is built; `undefined` before binding.
59
- */
60
- actor;
61
- /** @inheritdoc PortHandle.hsm */
62
- hsm() {
63
- return this.actor;
64
- }
65
- /**
66
- * Post an internal event inward through the bound {@link BasePort.actor | actor}.
67
- *
68
- * This is the one channel a port (or a test driving the port) uses to feed the machine its
69
- * internal protocol. Because emission is explicit — never a side effect of the outbound call
70
- * the machine made — a single mock works across many tests: the test decides *when* (and
71
- * whether) to push each internal event.
72
- *
73
- * @param eventName - Internal event to post
74
- * @param payload - Arguments for the event
75
- * @throws If called before the actor has been bound by a factory
76
- */
77
- send(eventName, ...payload) {
78
- if (this.actor === undefined) {
79
- throw new Error('ihsm: port.send called before the actor was bound — pass the port to makeActor/makeHsm/makeTestActor first');
80
- }
81
- this.actor.post(eventName, ...payload);
82
- }
83
- }
84
- exports.BasePort = BasePort;
85
- /**
86
- * Production port base with standard JavaScript timer and random services.
87
- *
88
- * Extend this class for domain ports in production code. It inherits the lazily-bound
89
- * {@link BasePort.actor | actor}, {@link BasePort.hsm | hsm}, and {@link BasePort.send | send}
90
- * from {@link BasePort}, and adds {@link Port.setTimeout | setTimeout} /
91
- * {@link Port.setInterval | setInterval} / {@link Port.clearTimeout | clearTimeout} /
92
- * {@link Port.clearInterval | clearInterval} plus the {@link RandomService} methods
93
- * ({@link Port.random | random}, {@link Port.cryptoRandom | cryptoRandom},
94
- * {@link Port.randomUUID | randomUUID}, {@link Port.getRandomValues | getRandomValues}).
95
- *
96
- * {@link State.deferredPost} delegates to {@link Port.setTimeout}. When no custom port is
97
- * supplied the runtime instantiates a plain `Port` for that purpose.
98
- *
99
- * @typeParam T - The machine's root {@link TopState} subclass (e.g. `ConnTop`)
100
- *
101
- * @example A minimal domain port
102
- * ```ts
103
- * class ConnPortImpl extends ihsm.Port<ConnTop> implements ConnPort {
104
- * private nextId = 1;
105
- * connect(host: string): ihsm.ResultWithSubscription<number> {
106
- * const id = this.nextId++;
107
- * return { value: id, subscription: { dispose: () => {} } };
108
- * }
109
- * disconnect(id: number): void {}
110
- * }
111
- * const port = new ConnPortImpl();
112
- * const conn = ihsm.makeActor(ConnTop, ctx, port); // binds port.actor
113
- * ```
114
- *
115
- * @category Port
116
- */
117
- class Port extends BasePort {
118
- _timerSeq = 0;
119
- _timeoutHandles = new Map();
120
- _intervalHandles = new Map();
121
- /**
122
- * Schedule `callback` after `millis` milliseconds — same argument order as `globalThis.setTimeout`.
123
- *
124
- * @returns An opaque handle for {@link Port.clearTimeout}
125
- */
126
- setTimeout(callback, millis) {
127
- const id = ++this._timerSeq;
128
- const handle = globalThis.setTimeout(() => {
129
- this._timeoutHandles.delete(id);
130
- callback();
131
- }, Math.max(0, millis ?? 0));
132
- this._timeoutHandles.set(id, handle);
133
- return id;
134
- }
135
- /** Cancel a pending {@link Port.setTimeout} handle. No-op when `id` is `undefined` or unknown. */
136
- clearTimeout(id) {
137
- if (id === undefined) {
138
- return;
139
- }
140
- const handle = this._timeoutHandles.get(id);
141
- if (handle !== undefined) {
142
- globalThis.clearTimeout(handle);
143
- this._timeoutHandles.delete(id);
144
- }
145
- }
146
- /**
147
- * Schedule `callback` every `millis` milliseconds — same argument order as `globalThis.setInterval`.
148
- *
149
- * @returns An opaque handle for {@link Port.clearInterval}
150
- */
151
- setInterval(callback, millis) {
152
- const id = ++this._timerSeq;
153
- const handle = globalThis.setInterval(callback, Math.max(0, millis ?? 0));
154
- this._intervalHandles.set(id, handle);
155
- return id;
156
- }
157
- /** Cancel a pending {@link Port.setInterval} handle. No-op when `id` is `undefined` or unknown. */
158
- clearInterval(id) {
159
- if (id === undefined) {
160
- return;
161
- }
162
- const handle = this._intervalHandles.get(id);
163
- if (handle !== undefined) {
164
- globalThis.clearInterval(handle);
165
- this._intervalHandles.delete(id);
166
- }
167
- }
168
- /** @inheritdoc RandomService.random */
169
- random() {
170
- return Math.random();
171
- }
172
- /** @inheritdoc RandomService.cryptoRandom */
173
- cryptoRandom() {
174
- const crypto = globalThis.crypto;
175
- return crypto.random?.() ?? Math.random();
176
- }
177
- /** @inheritdoc RandomService.randomUUID */
178
- randomUUID() {
179
- return globalThis.crypto.randomUUID();
180
- }
181
- /** @inheritdoc RandomService.getRandomValues */
182
- getRandomValues(array) {
183
- // crypto.getRandomValues accepts a narrower union than ArrayBufferView; the runtime call is safe.
184
- globalThis.crypto.getRandomValues(array);
185
- return array;
186
- }
187
- }
188
- exports.Port = Port;
189
- /**
190
- * Abstract root class for every state in the hierarchy.
191
- *
192
- * States are **never constructed directly** — the runtime binds one instance object whose
193
- * prototype moves along the class chain. Subclass `TopState` (or a child state), implement
194
- * your `Protocol` methods, and pass the root class to {@link makeHsm}.
195
- *
196
- * Forwards {@link State} / {@link Properties} APIs and default {@link StateEvents} behavior.
197
- *
198
- * @category State machine
199
- */
200
- class TopState {
201
- /** Domain context (injected by runtime — do not assign in constructors). */
202
- ctx;
203
- /** Handler view of the machine (`this` inside methods delegates here for core operations). */
204
- hsm;
205
- constructor() {
206
- throw new Error('Fatal error: States cannot be instantiated');
207
- }
208
- /**
209
- * Outbound boundary — the `port` instance passed to {@link makeActor} / {@link testing!makeTestActor};
210
- * all impure I/O flows through here.
211
- *
212
- * Typed `undefined` for machines created without a port (the default), so existing
213
- * port-less machines are unaffected. At runtime a {@link Port} always backs such
214
- * machines — it is what {@link State.deferredPost} uses for its timer service.
215
- */
216
- get port() {
217
- return this.hsm.port;
218
- }
219
- /** @inheritdoc Properties.eventName */
220
- get eventName() {
221
- return this.hsm.eventName;
222
- }
223
- /** @inheritdoc Properties.eventPayload */
224
- get eventPayload() {
225
- return this.hsm.eventPayload;
226
- }
227
- /** @inheritdoc Properties.traceHeader */
228
- get traceHeader() {
229
- return this.hsm.traceHeader;
230
- }
231
- /** @inheritdoc Properties.topState */
232
- get topState() {
233
- return this.hsm.topState;
234
- }
235
- /** @inheritdoc Properties.currentStateName */
236
- get currentStateName() {
237
- return this.hsm.currentStateName;
238
- }
239
- /** @inheritdoc Properties.currentState */
240
- get currentState() {
241
- return this.hsm.currentState;
242
- }
243
- /** @inheritdoc Properties.ctxTypeName */
244
- get ctxTypeName() {
245
- return this.hsm.ctxTypeName;
246
- }
247
- /** @inheritdoc Properties.traceLevel */
248
- set traceLevel(value) {
249
- this.hsm.traceLevel = value;
250
- }
251
- /** @inheritdoc Properties.traceLevel */
252
- get traceLevel() {
253
- return this.hsm.traceLevel;
254
- }
255
- /** @inheritdoc Properties.topStateName */
256
- get topStateName() {
257
- return this.hsm.topStateName;
258
- }
259
- /** @inheritdoc Properties.traceWriter */
260
- get traceWriter() {
261
- return this.hsm.traceWriter;
262
- }
263
- /** @inheritdoc Properties.traceWriter */
264
- set traceWriter(value) {
265
- this.hsm.traceWriter = value;
266
- }
267
- /** @inheritdoc Properties.dispatchErrorCallback */
268
- get dispatchErrorCallback() {
269
- return this.hsm.dispatchErrorCallback;
270
- }
271
- /** @inheritdoc Properties.dispatchErrorCallback */
272
- set dispatchErrorCallback(value) {
273
- this.hsm.dispatchErrorCallback = value;
274
- }
275
- /** @inheritdoc State.transition */
276
- transition(nextState) {
277
- this.hsm.transition(nextState);
278
- }
279
- /** @inheritdoc State.unhandled */
280
- unhandled() {
281
- this.hsm.unhandled();
282
- }
283
- /** @inheritdoc State.sleep */
284
- sleep(millis) {
285
- return this.hsm.sleep(millis);
286
- }
287
- /** @inheritdoc Base.post */
288
- post(eventName, ...eventPayload) {
289
- this.hsm.post(eventName, ...eventPayload);
290
- }
291
- /** @inheritdoc State.deferredPost */
292
- deferredPost(millis, eventName, ...eventPayload) {
293
- this.hsm.deferredPost(millis, eventName, ...eventPayload);
294
- }
295
- /** @inheritdoc State.postNow */
296
- postNow(eventName, ...eventPayload) {
297
- this.hsm.postNow(eventName, ...eventPayload);
298
- }
299
- /** @inheritdoc StateEvents.onExit */
300
- onExit() { }
301
- /** @inheritdoc StateEvents.onEntry */
302
- onEntry() { }
303
- /** @inheritdoc StateEvents.onError */
304
- onError(error) {
305
- throw error;
306
- }
307
- /** @inheritdoc StateEvents.onUnhandled */
308
- onUnhandled(error) {
309
- throw error;
310
- }
311
- }
312
- exports.TopState = TopState;
313
- /**
314
- * Base class for all ihsm runtime errors carrying machine context.
315
- *
316
- * @typeParam Context - Domain context at failure time
317
- * @typeParam Protocol - Vocabulary type (for typed subclasses)
318
- *
319
- * @category Error
320
- */
321
- class HsmError extends Error {
322
- /** Discriminator matching the class name (`EventHandlerError`, etc.). */
323
- name;
324
- /** {@link Properties.topStateName} when the error was constructed. */
325
- topStateName;
326
- /** {@link Properties.currentStateName} when the error was constructed. */
327
- stateName;
328
- /** Snapshot of {@link State.ctx} when the error was constructed. */
329
- context;
330
- /** Original thrown value when this error wraps a handler or lifecycle failure. */
331
- cause;
332
- constructor(name, hsm, message, cause) {
333
- super(message);
334
- this.name = name;
335
- this.topStateName = hsm.topStateName;
336
- this.stateName = hsm.currentStateName;
337
- this.context = hsm.ctx;
338
- this.cause = cause;
339
- }
340
- }
341
- exports.HsmError = HsmError;
342
- /**
343
- * Error base for failures during **event dispatch**, with correlated event metadata.
344
- *
345
- * @typeParam Context - Domain context
346
- * @typeParam Protocol - Vocabulary interface
347
- * @typeParam EventName - Event or service key being processed
348
- *
349
- * @category Error
350
- */
351
- class RuntimeError extends HsmError {
352
- /** Event or service name that was active when the failure occurred. */
353
- eventName;
354
- /** Client-supplied arguments (excluding resolve/reject for services). */
355
- eventPayload;
356
- constructor(errorName, hsm, message, cause) {
357
- super(errorName, hsm, message, cause);
358
- this.eventName = hsm.eventName;
359
- this.eventPayload = hsm.eventPayload;
360
- }
361
- }
362
- exports.RuntimeError = RuntimeError;
363
- /**
364
- * Thrown when {@link StateEvents.onExit} or {@link StateEvents.onEntry} throws during a transition.
365
- *
366
- * @category Error
367
- */
368
- class TransitionError extends RuntimeError {
369
- failedStateName;
370
- failedCallback;
371
- fromStateName;
372
- toStateName;
373
- /**
374
- * @param hsm - Machine view at failure time
375
- * @param cause - Error thrown from the lifecycle hook
376
- * @param failedStateName - Display name of the state whose hook failed
377
- * @param failedCallback - Which hook failed (`onExit` or `onEntry`)
378
- * @param fromStateName - Leaf state before the transition
379
- * @param toStateName - Requested destination state
380
- */
381
- constructor(hsm, cause, failedStateName, failedCallback, fromStateName, toStateName) {
382
- super('TransitionError', hsm, `${failedStateName}.${failedCallback}() has failed while executing a transition from ${fromStateName} to ${toStateName}`, cause);
383
- this.failedStateName = failedStateName;
384
- this.failedCallback = failedCallback;
385
- this.fromStateName = fromStateName;
386
- this.toStateName = toStateName;
387
- }
388
- }
389
- exports.TransitionError = TransitionError;
390
- /**
391
- * Thrown when an event handler body throws and {@link StateEvents.onError} does not recover.
392
- *
393
- * @category Error
394
- */
395
- class EventHandlerError extends RuntimeError {
396
- /**
397
- * @param hsm - Machine view with {@link eventName} set to the failing handler
398
- * @param cause - Error thrown from handler code
399
- */
400
- constructor(hsm, cause) {
401
- super('EventHandlerError', hsm, `an error was thrown while executing event handler #${hsm.eventName} in state ${hsm.currentStateName}`, cause);
402
- }
403
- }
404
- exports.EventHandlerError = EventHandlerError;
405
- /**
406
- * Thrown when no handler matches the dispatched event and {@link StateEvents.onUnhandled} rethrows.
407
- *
408
- * @category Error
409
- */
410
- class UnhandledEventError extends RuntimeError {
411
- /** @param hsm - Machine view with the unmatched {@link eventName} */
412
- constructor(hsm) {
413
- super('UnhandledEventError', hsm, `event #${hsm.eventName} was unhandled in state ${hsm.currentStateName}`);
414
- }
415
- }
416
- exports.UnhandledEventError = UnhandledEventError;
417
- /**
418
- * Thrown at **class definition** time when {@link InitialState} is applied twice to one parent.
419
- *
420
- * @category Error
421
- */
422
- class InitialStateError extends Error {
423
- /** Display name of the state passed to the duplicate {@link InitialState} call. */
424
- targetStateName;
425
- /** @param targetState - The state class whose parent already has an initial substate */
426
- constructor(targetState) {
427
- super(`State '${(0, utils_1.getStateName)(Object.getPrototypeOf(targetState.prototype).constructor)}' must not have more than one initial state`);
428
- this.name = 'InitialStateError';
429
- this.targetStateName = (0, utils_1.getStateName)(targetState);
430
- }
431
- }
432
- exports.InitialStateError = InitialStateError;
433
- /**
434
- * Thrown when {@link StateEvents.onError} itself throws, leaving the machine unrecoverable.
435
- *
436
- * @category Error
437
- */
438
- class FatalError extends RuntimeError {
439
- /**
440
- * @param hsm - Machine view at failure time
441
- * @param cause - Error thrown from `onError`
442
- */
443
- constructor(hsm, cause) {
444
- super('FatalError', hsm, `onError() has thrown ${(0, utils_1.quoteError)(cause)}`, cause);
445
- }
446
- }
447
- exports.FatalError = FatalError;
448
- /**
449
- * Thrown when {@link StateEvents.onEntry} fails during the initial `@InitialState` walk at startup.
450
- *
451
- * @category Error
452
- */
453
- class InitializationError extends HsmError {
454
- failedState;
455
- /**
456
- * @param hsm - Partially initialized machine
457
- * @param failedState - State class whose `onEntry` threw
458
- * @param cause - Original error from `onEntry`
459
- */
460
- constructor(hsm, failedState, cause) {
461
- super('InitializationError', hsm, `state ${(0, utils_1.getStateName)(failedState)} has thrown ${(0, utils_1.quoteError)(cause)} during initialization`, cause);
462
- this.failedState = failedState;
463
- }
464
- }
465
- exports.InitializationError = InitializationError;
466
- /**
467
- * Terminal sink state class used when the runtime cannot recover from an error.
468
- *
469
- * Assign or transition here from custom {@link StateEvents.onError} handlers when you need a
470
- * well-defined quiescent state. Display name is pre-registered as `'FatalErrorState'`.
471
- *
472
- * @category State machine
473
- */
474
- class FatalErrorState extends TopState {
475
- }
476
- exports.FatalErrorState = FatalErrorState;
477
- (0, utils_1.defineStateName)(TopState, 'TopState');
478
- (0, utils_1.defineStateName)(FatalErrorState, 'FatalErrorState');
479
- /**
480
- * Declares `TargetState` as the **initial substate** of its direct parent composite.
481
- *
482
- * Apply as a TypeScript decorator or call as a function at class definition time. Exactly **one**
483
- * initial child is allowed per parent; a second mark throws {@link InitialStateError}.
484
- *
485
- * @typeParam Context - Domain context type
486
- * @typeParam Protocol - Vocabulary interface
487
- * @param TargetState - Child state class whose **parent** is `Object.getPrototypeOf(TargetState.prototype).constructor`
488
- *
489
- * @throws {@link InitialStateError} when the parent already has an initial substate
490
- *
491
- * @remarks
492
- * During {@link makeHsm} initialization, the runtime descends `@InitialState` chains from the
493
- * root until the deepest initial leaf is active, running {@link StateEvents.onEntry} along the path.
494
- *
495
- * @example
496
- * ```ts
497
- * class Composite extends TopState {}
498
- *
499
- * @InitialState
500
- * class Idle extends Composite {}
501
- * ```
502
- */
503
- function InitialState(TargetState) {
504
- const ParentOfTargetState = Object.getPrototypeOf(TargetState.prototype).constructor;
505
- if ((0, utils_1.hasInitialState)(ParentOfTargetState))
506
- throw new InitialStateError(TargetState);
507
- Object.defineProperty(TargetState, '_isInitialState', {
508
- value: true,
509
- writable: false,
510
- configurable: false,
511
- enumerable: false,
512
- });
513
- Object.defineProperty(ParentOfTargetState, '_initialState', {
514
- value: TargetState,
515
- writable: false,
516
- configurable: false,
517
- enumerable: false,
518
- });
519
- }
520
- /**
521
- * Assigns a stable **display name** to a single state class.
522
- *
523
- * Minifiers rewrite `Class.name` in production browser bundles; explicit registration keeps
524
- * {@link Properties.currentStateName}, trace output, and error messages readable everywhere.
525
- *
526
- * @typeParam Context - Domain context type
527
- * @typeParam Protocol - Vocabulary interface
528
- * @param state - State class constructor to tag
529
- * @param name - Non-empty display string used in traces and errors (not required to match `Class.name`)
530
- *
531
- * @remarks
532
- * Stored as a non-enumerable own property — never inherited by subclasses from the prototype chain.
533
- * {@link registerStateNames} is preferred when every state is a named export from one module.
534
- *
535
- * @example
536
- * ```ts
537
- * class Door extends TopState {}
538
- * defineStateName(Door, 'Door');
539
- * ```
540
- *
541
- * @category State machine
542
- */
543
- function defineStateName(state, name) {
544
- (0, utils_1.defineStateName)(state, name);
545
- }
546
- /**
547
- * Registers display names for **every** state class in an exports object, using each **export key** as the name.
548
- *
549
- * @param exports - Module namespace (`import * as machine`) or object literal of state classes.
550
- * Non-constructor exports (constants, functions, types) are silently skipped
551
- *
552
- * @remarks
553
- * Export keys survive minification even when class identifiers are mangled — this is the recommended
554
- * approach for browser bundles without `keep_classnames`. Call once at module load after all state
555
- * classes are defined.
556
- *
557
- * @example Single module
558
- * ```ts
559
- * export class DoorTop extends TopState {}
560
- * export class Open extends DoorTop {}
561
- * export class Closed extends DoorTop {}
562
- * registerStateNames({ DoorTop, Open, Closed });
563
- * ```
564
- *
565
- * @example Re-exporting namespace
566
- * ```ts
567
- * import * as machine from './machine';
568
- * registerStateNames(machine);
569
- * ```
570
- *
571
- * @category State machine
572
- */
573
- function registerStateNames(exports) {
574
- for (const [exportName, value] of Object.entries(exports)) {
575
- if (isStateClass(value)) {
576
- (0, utils_1.defineStateName)(value, exportName);
577
- }
578
- }
579
- }
580
- /** @internal — structural guard: a constructor whose prototype derives from {@link TopState}. */
581
- function isStateClass(value) {
582
- if (typeof value !== 'function')
583
- return false;
584
- const prototype = value.prototype;
585
- return typeof prototype === 'object' && prototype !== null && TopState.prototype.isPrototypeOf(prototype);
586
- }
587
- /** @internal */
588
- class ConsoleTraceWriter {
589
- write(hsm, Message) {
590
- if (typeof Message == 'string') {
591
- console.log(`${hsm.traceHeader}${hsm.currentStateName}: ${Message}`);
592
- }
593
- else {
594
- console.log(Message);
595
- }
596
- }
597
- }
598
- /** @internal — shared by the core factories and (via re-export) the `ihsm/testing` factories. */
599
- function defaultDispatchErrorCallback(hsm, err) {
600
- const writer = hsm.traceWriter;
601
- writer.write(hsm, `An event dispatch has failed; error ${err.name}: ${err.message} has not been managed`);
602
- writer.write(hsm, err);
603
- throw err;
604
- }
605
- /** @internal */
606
- exports.defaultTraceWriter = new ConsoleTraceWriter();
607
- const defaultTraceLevel = TraceLevel.DEBUG;
608
- /** @internal */
609
- exports.defaultInitialize = true;
610
- /**
611
- * Creates and optionally initializes a hierarchical state machine **actor** bound to `ctx`.
612
- *
613
- * The returned {@link Hsm} is the single runtime object: external clients call `post` / `call` /
614
- * `sync`; the active state is the instance prototype chain updated by {@link State.transition}.
615
- *
616
- * @typeParam Context - Domain context type (inferred from `ctx` when passed inline)
617
- * @typeParam Protocol - Event/service vocabulary (inferred from `topState` when it implements `Protocol`)
618
- * @param topState - Root state **class** constructor (must extend {@link TopState})
619
- * @param ctx - Mutable domain object shared by all states; stored on the instance as {@link Hsm.ctx}
620
- * @param initialize - When `true` (default), enqueue the initial walk: descend `@InitialState`
621
- * chains from `topState` and run {@link StateEvents.onEntry} on each entered state until the
622
- * initial leaf is active. When `false`, prototype starts at `topState` with **no** entry hooks
623
- * @param traceLevel - Initial {@link TraceLevel} (default {@link TraceLevel.DEBUG})
624
- * @param traceWriter - {@link TraceWriter} implementation (default: prefixes strings with state name and logs to `console`)
625
- * @param dispatchErrorCallback - Last-resort error hook (default: trace + rethrow)
626
- * @returns Client handle implementing {@link Hsm} for the same `Context` and `Protocol`
627
- *
628
- * @remarks
629
- * - Await {@link Hsm.sync} after creation when `initialize: true` before asserting initial state
630
- * - Zero runtime npm dependencies; safe to embed in browsers when state names are registered
631
- * - Transition LCA paths are cached per machine instance for the lifetime of the actor
632
- *
633
- * @example Minimal door machine
634
- * ```ts
635
- * const door = makeHsm(DoorTop, { openCount: 0 });
636
- * await door.sync();
637
- * door.post('open');
638
- * await door.sync();
639
- * ```
640
- *
641
- * @example Custom tracing in tests
642
- * ```ts
643
- * const writer = { write: (_hsm, msg) => logs.push(msg) };
644
- * const sm = makeHsm(Top, ctx, true, TraceLevel.VERBOSE_DEBUG, writer);
645
- * await sm.sync();
646
- * ```
647
- *
648
- * @category Factory
649
- */
650
- function makeHsm(topState, ctx, initialize = exports.defaultInitialize, traceLevel = defaultTraceLevel, traceWriter = exports.defaultTraceWriter, dispatchErrorCallback = defaultDispatchErrorCallback, port) {
651
- return instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port);
652
- }
653
- /** @internal — single construction path shared by {@link makeHsm}, {@link makeActor}, {@link testing!makeTestActor}. */
654
- function instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port) {
655
- const instance = {
656
- hsm: undefined,
657
- ctx: ctx,
658
- };
659
- Object.setPrototypeOf(instance, topState.prototype);
660
- instance.hsm = new hsm_1.HsmObject(topState, instance, traceWriter, traceLevel, dispatchErrorCallback, initialize);
661
- // A port is always present: the supplied instance, otherwise a Port that backs
662
- // `deferredPost`'s timer service. Its `actor` is bound here, lazily — synchronously, before
663
- // the queued initialization walk, so `this.port` is available inside the first `onEntry`.
664
- const boundPort = port ?? new Port();
665
- boundPort.actor = instance.hsm;
666
- instance.portRef = boundPort;
667
- return instance.hsm;
668
- }
669
- /**
670
- * @internal
671
- *
672
- * Wrap a live machine in a **structural, public-only** {@link Actor} facade (proposal T5).
673
- *
674
- * Replaces the old `hsm as unknown as Actor<…>` double cast. The returned object is annotated
675
- * `Actor<Context, Public>`, so the compiler verifies it implements **exactly** the public surface —
676
- * a regression that leaked an internal member would fail to compile, and if {@link Hsm} gains a
677
- * member this factory stops compiling until the facade forwards it. Each forwarded `post` / `call`
678
- * is narrowed from the merged-protocol instance down to the public protocol with a single local
679
- * cast; properties delegate through get/set accessors so reads and writes still hit the live machine.
680
- */
681
- function narrowToActor(hsm) {
682
- const actor = {
683
- get ctx() {
684
- return hsm.ctx;
685
- },
686
- get currentState() {
687
- return hsm.currentState;
688
- },
689
- get currentStateName() {
690
- return hsm.currentStateName;
691
- },
692
- get topState() {
693
- return hsm.topState;
694
- },
695
- get topStateName() {
696
- return hsm.topStateName;
697
- },
698
- get ctxTypeName() {
699
- return hsm.ctxTypeName;
700
- },
701
- get traceHeader() {
702
- return hsm.traceHeader;
703
- },
704
- get eventName() {
705
- return hsm.eventName;
706
- },
707
- get eventPayload() {
708
- return hsm.eventPayload;
709
- },
710
- get traceLevel() {
711
- return hsm.traceLevel;
712
- },
713
- set traceLevel(level) {
714
- hsm.traceLevel = level;
715
- },
716
- get traceWriter() {
717
- return hsm.traceWriter;
718
- },
719
- set traceWriter(writer) {
720
- hsm.traceWriter = writer;
721
- },
722
- get dispatchErrorCallback() {
723
- return hsm.dispatchErrorCallback;
724
- },
725
- set dispatchErrorCallback(cb) {
726
- hsm.dispatchErrorCallback = cb;
727
- },
728
- post: hsm.post.bind(hsm),
729
- call: hsm.call.bind(hsm),
730
- sync: hsm.sync.bind(hsm),
731
- restore: hsm.restore.bind(hsm),
732
- };
733
- return actor;
734
- }
735
- /**
736
- * Creates an actor exposing only its **public** protocol, with an optional outbound {@link Port}.
737
- *
738
- * Like {@link makeHsm} but separates the public, client-callable protocol from an
739
- * `InternalProtocol` that only the port may post inward. The returned {@link Actor} surfaces
740
- * just the public events; handlers (and the port) may post the merged {@link Dispatch} protocol.
741
- *
742
- * The trailing `Disjoint` guard is a compile-time gate: if `Public` and `Internal` share an event
743
- * name, the call fails to type-check, pointing at the overlapping keys.
744
- *
745
- * @typeParam Context - Domain context type
746
- * @typeParam Public - Public, client-callable protocol
747
- * @typeParam Internal - Internal protocol — only postable by the port / handlers
748
- * @typeParam P - Concrete {@link Port} type assigned to `this.port`
749
- * @param topState - Root state class; `Context` / `Public` / `Internal` are inferred from it (see {@link TopStateArg})
750
- * @param ctx - Mutable domain object shared by all states
751
- * @param port - Outbound port instance (its `actor` is bound by the factory; use {@link Port} if none)
752
- * @param options - Optional tuning: `initialize` / `traceLevel` / `traceWriter` / … (see {@link ActorOptions})
753
- * @returns A public-only {@link Actor} handle
754
- *
755
- * @example
756
- * ```ts
757
- * const conn = makeActor(ConnTop, new ConnCtx(), port, { traceLevel: TraceLevel.PRODUCTION });
758
- * ```
759
- *
760
- * @category Factory
761
- */
762
- function makeActor(topState, ctx, port, options = {}, ..._disjointGuard) {
763
- const { initialize = exports.defaultInitialize, traceLevel = defaultTraceLevel, traceWriter = exports.defaultTraceWriter, dispatchErrorCallback = defaultDispatchErrorCallback } = options;
764
- const hsm = instantiate(topState, ctx, initialize, traceLevel, traceWriter, dispatchErrorCallback, port);
765
- return narrowToActor(hsm);
766
- }
3
+ exports.getRunNamespace = exports.getRunSeed = exports.configureRunSeed = exports.kParentLink = exports.kHandlerMachine = exports.makeChildActor = exports.asParentActor = exports.makeActor = exports.defaultDispatchErrorCallback = exports.defaultInitialize = exports.defaultTraceWriter = exports.currentTraceAnchor = exports.serviceCallWithTimeout = exports.splitServiceArgs = exports.isServiceCallOptions = exports.isRequestingPort = exports.RuntimeTransitionResolver = exports.transitionTraceLines = exports.createTransitionTracer = exports.executeTransitionRoutine = exports.planTransitionClasses = exports.TransitionTableError = exports.SelfCallDeadlockError = exports.CallTimeoutError = exports.buildProtocolIndex = exports.ReservedNames = exports.ProtocolCollisionError = exports.registerStateNames = exports.InitialState = exports.FatalErrorState = exports.InitializationError = exports.FatalError = exports.InitialStateError = exports.UnhandledEventError = exports.EventHandlerError = exports.TransitionError = exports.RuntimeError = exports.HsmError = exports.TopState = exports.RequestingPort = exports.Port = exports.getStateName = exports.defineStateName = exports.getTransitionKey = exports.hasInitialState = exports.getInitialState = exports.quoteError = exports.quoteUnknown = exports.asError = exports.TraceLevel = void 0;
4
+ exports.getCollectorCount = exports.clearCollectors = exports.registerCollector = exports.createConsoleInstrumentation = exports.mintActorIdentity = void 0;
5
+ /**
6
+ * ihsm — hierarchical state machines for TypeScript.
7
+ *
8
+ * Curated public runtime surface; protocol types live in {@link ./types}.
9
+ */
10
+ var runtime_1 = require("./internal/runtime");
11
+ Object.defineProperty(exports, "TraceLevel", { enumerable: true, get: function () { return runtime_1.TraceLevel; } });
12
+ Object.defineProperty(exports, "asError", { enumerable: true, get: function () { return runtime_1.asError; } });
13
+ Object.defineProperty(exports, "quoteUnknown", { enumerable: true, get: function () { return runtime_1.quoteUnknown; } });
14
+ Object.defineProperty(exports, "quoteError", { enumerable: true, get: function () { return runtime_1.quoteError; } });
15
+ Object.defineProperty(exports, "getInitialState", { enumerable: true, get: function () { return runtime_1.getInitialState; } });
16
+ Object.defineProperty(exports, "hasInitialState", { enumerable: true, get: function () { return runtime_1.hasInitialState; } });
17
+ Object.defineProperty(exports, "getTransitionKey", { enumerable: true, get: function () { return runtime_1.getTransitionKey; } });
18
+ Object.defineProperty(exports, "defineStateName", { enumerable: true, get: function () { return runtime_1.defineStateName; } });
19
+ Object.defineProperty(exports, "getStateName", { enumerable: true, get: function () { return runtime_1.getStateName; } });
20
+ Object.defineProperty(exports, "Port", { enumerable: true, get: function () { return runtime_1.Port; } });
21
+ Object.defineProperty(exports, "RequestingPort", { enumerable: true, get: function () { return runtime_1.RequestingPort; } });
22
+ Object.defineProperty(exports, "TopState", { enumerable: true, get: function () { return runtime_1.TopState; } });
23
+ Object.defineProperty(exports, "HsmError", { enumerable: true, get: function () { return runtime_1.HsmError; } });
24
+ Object.defineProperty(exports, "RuntimeError", { enumerable: true, get: function () { return runtime_1.RuntimeError; } });
25
+ Object.defineProperty(exports, "TransitionError", { enumerable: true, get: function () { return runtime_1.TransitionError; } });
26
+ Object.defineProperty(exports, "EventHandlerError", { enumerable: true, get: function () { return runtime_1.EventHandlerError; } });
27
+ Object.defineProperty(exports, "UnhandledEventError", { enumerable: true, get: function () { return runtime_1.UnhandledEventError; } });
28
+ Object.defineProperty(exports, "InitialStateError", { enumerable: true, get: function () { return runtime_1.InitialStateError; } });
29
+ Object.defineProperty(exports, "FatalError", { enumerable: true, get: function () { return runtime_1.FatalError; } });
30
+ Object.defineProperty(exports, "InitializationError", { enumerable: true, get: function () { return runtime_1.InitializationError; } });
31
+ Object.defineProperty(exports, "FatalErrorState", { enumerable: true, get: function () { return runtime_1.FatalErrorState; } });
32
+ Object.defineProperty(exports, "InitialState", { enumerable: true, get: function () { return runtime_1.InitialState; } });
33
+ Object.defineProperty(exports, "registerStateNames", { enumerable: true, get: function () { return runtime_1.registerStateNames; } });
34
+ Object.defineProperty(exports, "ProtocolCollisionError", { enumerable: true, get: function () { return runtime_1.ProtocolCollisionError; } });
35
+ Object.defineProperty(exports, "ReservedNames", { enumerable: true, get: function () { return runtime_1.ReservedNames; } });
36
+ Object.defineProperty(exports, "buildProtocolIndex", { enumerable: true, get: function () { return runtime_1.buildProtocolIndex; } });
37
+ Object.defineProperty(exports, "CallTimeoutError", { enumerable: true, get: function () { return runtime_1.CallTimeoutError; } });
38
+ Object.defineProperty(exports, "SelfCallDeadlockError", { enumerable: true, get: function () { return runtime_1.SelfCallDeadlockError; } });
39
+ Object.defineProperty(exports, "TransitionTableError", { enumerable: true, get: function () { return runtime_1.TransitionTableError; } });
40
+ Object.defineProperty(exports, "planTransitionClasses", { enumerable: true, get: function () { return runtime_1.planTransitionClasses; } });
41
+ Object.defineProperty(exports, "executeTransitionRoutine", { enumerable: true, get: function () { return runtime_1.executeTransitionRoutine; } });
42
+ Object.defineProperty(exports, "createTransitionTracer", { enumerable: true, get: function () { return runtime_1.createTransitionTracer; } });
43
+ Object.defineProperty(exports, "transitionTraceLines", { enumerable: true, get: function () { return runtime_1.transitionTraceLines; } });
44
+ Object.defineProperty(exports, "RuntimeTransitionResolver", { enumerable: true, get: function () { return runtime_1.RuntimeTransitionResolver; } });
45
+ Object.defineProperty(exports, "isRequestingPort", { enumerable: true, get: function () { return runtime_1.isRequestingPort; } });
46
+ Object.defineProperty(exports, "isServiceCallOptions", { enumerable: true, get: function () { return runtime_1.isServiceCallOptions; } });
47
+ Object.defineProperty(exports, "splitServiceArgs", { enumerable: true, get: function () { return runtime_1.splitServiceArgs; } });
48
+ Object.defineProperty(exports, "serviceCallWithTimeout", { enumerable: true, get: function () { return runtime_1.serviceCallWithTimeout; } });
49
+ Object.defineProperty(exports, "currentTraceAnchor", { enumerable: true, get: function () { return runtime_1.currentTraceAnchor; } });
50
+ Object.defineProperty(exports, "defaultTraceWriter", { enumerable: true, get: function () { return runtime_1.defaultTraceWriter; } });
51
+ Object.defineProperty(exports, "defaultInitialize", { enumerable: true, get: function () { return runtime_1.defaultInitialize; } });
52
+ Object.defineProperty(exports, "defaultDispatchErrorCallback", { enumerable: true, get: function () { return runtime_1.defaultDispatchErrorCallback; } });
53
+ Object.defineProperty(exports, "makeActor", { enumerable: true, get: function () { return runtime_1.makeActor; } });
54
+ Object.defineProperty(exports, "asParentActor", { enumerable: true, get: function () { return runtime_1.asParentActor; } });
55
+ Object.defineProperty(exports, "makeChildActor", { enumerable: true, get: function () { return runtime_1.makeChildActor; } });
56
+ Object.defineProperty(exports, "kHandlerMachine", { enumerable: true, get: function () { return runtime_1.kHandlerMachine; } });
57
+ Object.defineProperty(exports, "kParentLink", { enumerable: true, get: function () { return runtime_1.kParentLink; } });
58
+ Object.defineProperty(exports, "configureRunSeed", { enumerable: true, get: function () { return runtime_1.configureRunSeed; } });
59
+ Object.defineProperty(exports, "getRunSeed", { enumerable: true, get: function () { return runtime_1.getRunSeed; } });
60
+ Object.defineProperty(exports, "getRunNamespace", { enumerable: true, get: function () { return runtime_1.getRunNamespace; } });
61
+ Object.defineProperty(exports, "mintActorIdentity", { enumerable: true, get: function () { return runtime_1.mintActorIdentity; } });
62
+ var console_instrumentation_1 = require("./internal/console-instrumentation");
63
+ Object.defineProperty(exports, "createConsoleInstrumentation", { enumerable: true, get: function () { return console_instrumentation_1.createConsoleInstrumentation; } });
64
+ var instrumentation_1 = require("./internal/instrumentation");
65
+ Object.defineProperty(exports, "registerCollector", { enumerable: true, get: function () { return instrumentation_1.registerCollector; } });
66
+ Object.defineProperty(exports, "clearCollectors", { enumerable: true, get: function () { return instrumentation_1.clearCollectors; } });
67
+ Object.defineProperty(exports, "getCollectorCount", { enumerable: true, get: function () { return instrumentation_1.getCollectorCount; } });
767
68
  //# sourceMappingURL=index.js.map