ihsm 0.0.14 → 0.0.20

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 (50) hide show
  1. package/README.md +330 -5
  2. package/lib/cjs/index.d.ts +934 -0
  3. package/lib/cjs/index.js +493 -0
  4. package/lib/cjs/index.js.map +1 -0
  5. package/lib/cjs/internal/defs.private.d.ts +31 -0
  6. package/lib/cjs/internal/defs.private.js +3 -0
  7. package/lib/cjs/internal/defs.private.js.map +1 -0
  8. package/lib/cjs/internal/dispatch.debug.d.ts +4 -0
  9. package/lib/cjs/internal/dispatch.debug.js +330 -0
  10. package/lib/cjs/internal/dispatch.debug.js.map +1 -0
  11. package/lib/cjs/internal/dispatch.production.d.ts +6 -0
  12. package/lib/cjs/internal/dispatch.production.js +239 -0
  13. package/lib/cjs/internal/dispatch.production.js.map +1 -0
  14. package/lib/cjs/internal/dispatch.trace.d.ts +4 -0
  15. package/lib/cjs/internal/dispatch.trace.js +410 -0
  16. package/lib/cjs/internal/dispatch.trace.js.map +1 -0
  17. package/lib/cjs/internal/hsm.d.ts +54 -0
  18. package/lib/cjs/internal/hsm.js +182 -0
  19. package/lib/cjs/internal/hsm.js.map +1 -0
  20. package/lib/cjs/internal/utils.d.ts +18 -0
  21. package/lib/cjs/internal/utils.js +51 -0
  22. package/lib/cjs/internal/utils.js.map +1 -0
  23. package/lib/cjs/package.json +3 -0
  24. package/lib/esm/index.d.ts +934 -0
  25. package/lib/esm/index.js +476 -0
  26. package/lib/esm/index.js.map +1 -0
  27. package/lib/esm/internal/defs.private.d.ts +31 -0
  28. package/lib/esm/internal/defs.private.js +2 -0
  29. package/lib/esm/internal/defs.private.js.map +1 -0
  30. package/lib/esm/internal/dispatch.debug.d.ts +4 -0
  31. package/lib/esm/internal/dispatch.debug.js +326 -0
  32. package/lib/esm/internal/dispatch.debug.js.map +1 -0
  33. package/lib/esm/internal/dispatch.production.d.ts +6 -0
  34. package/lib/esm/internal/dispatch.production.js +235 -0
  35. package/lib/esm/internal/dispatch.production.js.map +1 -0
  36. package/lib/esm/internal/dispatch.trace.d.ts +4 -0
  37. package/lib/esm/internal/dispatch.trace.js +406 -0
  38. package/lib/esm/internal/dispatch.trace.js.map +1 -0
  39. package/lib/esm/internal/hsm.d.ts +54 -0
  40. package/lib/esm/internal/hsm.js +178 -0
  41. package/lib/esm/internal/hsm.js.map +1 -0
  42. package/lib/esm/internal/utils.d.ts +18 -0
  43. package/lib/esm/internal/utils.js +41 -0
  44. package/lib/esm/internal/utils.js.map +1 -0
  45. package/lib/esm/package.json +3 -0
  46. package/package.json +116 -66
  47. package/lib/index.browser.js +0 -523
  48. package/lib/index.d.ts +0 -104
  49. package/lib/index.js +0 -374
  50. package/tsconfig.json +0 -72
@@ -0,0 +1,493 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FatalErrorState = exports.InitializationError = exports.FatalError = exports.InitialStateError = exports.UnhandledEventError = exports.EventHandlerError = exports.TransitionError = exports.RuntimeError = exports.HsmError = exports.TopState = exports.TraceLevel = void 0;
4
+ exports.InitialState = InitialState;
5
+ exports.defineStateName = defineStateName;
6
+ exports.registerStateNames = registerStateNames;
7
+ exports.makeHsm = makeHsm;
8
+ const hsm_1 = require("./internal/hsm");
9
+ const utils_1 = require("./internal/utils");
10
+ // export type DispatchErrorCallback<Context, Protocol extends {} | undefined> = (hsm: Hsm<Context, Protocol>, traceWriter: TraceWriter, err: Error) => void;
11
+ /**
12
+ * Controls how much diagnostic detail the runtime emits through {@link TraceWriter}.
13
+ *
14
+ * Set at construction via {@link makeHsm} or mutate {@link Properties.traceLevel} on a
15
+ * live instance. Changing the level swaps the internal dispatch tracer implementation.
16
+ *
17
+ * @category Factory
18
+ */
19
+ var TraceLevel;
20
+ (function (TraceLevel) {
21
+ /**
22
+ * Production mode: minimal tracing overhead, no verbose dispatch steps.
23
+ * Use in hot paths and shipped bundles when trace output is disabled.
24
+ */
25
+ TraceLevel[TraceLevel["PRODUCTION"] = 0] = "PRODUCTION";
26
+ /**
27
+ * Debug mode: transition boundaries, handler entry/exit, and error summaries.
28
+ * Default for {@link makeHsm}. Suitable for development and integration tests.
29
+ */
30
+ TraceLevel[TraceLevel["DEBUG"] = 1] = "DEBUG";
31
+ /**
32
+ * Verbose debug: includes prototype-chain lookup walks, cache hits/misses, and
33
+ * nested trace domains. Use when correlating handler code with tutorial trace panels.
34
+ */
35
+ TraceLevel[TraceLevel["VERBOSE_DEBUG"] = 2] = "VERBOSE_DEBUG";
36
+ })(TraceLevel || (exports.TraceLevel = TraceLevel = {}));
37
+ /**
38
+ * Abstract root class for every state in the hierarchy.
39
+ *
40
+ * States are **never constructed directly** — the runtime binds one instance object whose
41
+ * prototype moves along the class chain. Subclass `TopState` (or a child state), implement
42
+ * your `Protocol` methods, and pass the root class to {@link makeHsm}.
43
+ *
44
+ * Forwards {@link State} / {@link Properties} APIs and default {@link StateEvents} behavior.
45
+ *
46
+ * @category State machine
47
+ */
48
+ class TopState {
49
+ /** Domain context (injected by runtime — do not assign in constructors). */
50
+ ctx;
51
+ /** Handler view of the machine (`this` inside methods delegates here for core operations). */
52
+ hsm;
53
+ constructor() {
54
+ throw new Error('Fatal error: States cannot be instantiated');
55
+ }
56
+ /** @inheritdoc Properties.eventName */
57
+ get eventName() {
58
+ return this.hsm.eventName;
59
+ }
60
+ /** @inheritdoc Properties.eventPayload */
61
+ get eventPayload() {
62
+ return this.hsm.eventPayload;
63
+ }
64
+ /** @inheritdoc Properties.traceHeader */
65
+ get traceHeader() {
66
+ return this.hsm.traceHeader;
67
+ }
68
+ /** @inheritdoc Properties.topState */
69
+ get topState() {
70
+ return this.hsm.topState;
71
+ }
72
+ /** @inheritdoc Properties.currentStateName */
73
+ get currentStateName() {
74
+ return this.hsm.currentStateName;
75
+ }
76
+ /** @inheritdoc Properties.currentState */
77
+ get currentState() {
78
+ return this.hsm.currentState;
79
+ }
80
+ /** @inheritdoc Properties.ctxTypeName */
81
+ get ctxTypeName() {
82
+ return this.hsm.ctxTypeName;
83
+ }
84
+ /** @inheritdoc Properties.traceLevel */
85
+ set traceLevel(value) {
86
+ this.hsm.traceLevel = value;
87
+ }
88
+ /** @inheritdoc Properties.traceLevel */
89
+ get traceLevel() {
90
+ return this.hsm.traceLevel;
91
+ }
92
+ /** @inheritdoc Properties.topStateName */
93
+ get topStateName() {
94
+ return this.hsm.topStateName;
95
+ }
96
+ /** @inheritdoc Properties.traceWriter */
97
+ get traceWriter() {
98
+ return this.hsm.traceWriter;
99
+ }
100
+ /** @inheritdoc Properties.traceWriter */
101
+ set traceWriter(value) {
102
+ this.hsm.traceWriter = value;
103
+ }
104
+ /** @inheritdoc Properties.dispatchErrorCallback */
105
+ get dispatchErrorCallback() {
106
+ return this.hsm.dispatchErrorCallback;
107
+ }
108
+ /** @inheritdoc Properties.dispatchErrorCallback */
109
+ set dispatchErrorCallback(value) {
110
+ this.hsm.dispatchErrorCallback = value;
111
+ }
112
+ /** @inheritdoc State.transition */
113
+ transition(nextState) {
114
+ this.hsm.transition(nextState);
115
+ }
116
+ /** @inheritdoc State.unhandled */
117
+ unhandled() {
118
+ this.hsm.unhandled();
119
+ }
120
+ /** @inheritdoc State.sleep */
121
+ sleep(millis) {
122
+ return this.hsm.sleep(millis);
123
+ }
124
+ /** @inheritdoc Base.post */
125
+ post(eventName, ...eventPayload) {
126
+ this.hsm.post(eventName, ...eventPayload);
127
+ }
128
+ /** @inheritdoc Base.deferredPost */
129
+ deferredPost(millis, eventName, ...eventPayload) {
130
+ this.hsm.deferredPost(millis, eventName, ...eventPayload);
131
+ }
132
+ /** @inheritdoc State.postNow */
133
+ postNow(eventName, ...eventPayload) {
134
+ this.hsm.postNow(eventName, ...eventPayload);
135
+ }
136
+ /** @inheritdoc StateEvents.onExit */
137
+ onExit() { }
138
+ /** @inheritdoc StateEvents.onEntry */
139
+ onEntry() { }
140
+ /** @inheritdoc StateEvents.onError */
141
+ onError(error) {
142
+ throw error;
143
+ }
144
+ /** @inheritdoc StateEvents.onUnhandled */
145
+ onUnhandled(error) {
146
+ throw error;
147
+ }
148
+ }
149
+ exports.TopState = TopState;
150
+ /**
151
+ * Base class for all ihsm runtime errors carrying machine context.
152
+ *
153
+ * @typeParam Context - Domain context at failure time
154
+ * @typeParam Protocol - Vocabulary type (for typed subclasses)
155
+ *
156
+ * @category Error
157
+ */
158
+ class HsmError extends Error {
159
+ /** Discriminator matching the class name (`EventHandlerError`, etc.). */
160
+ name;
161
+ /** {@link Properties.topStateName} when the error was constructed. */
162
+ topStateName;
163
+ /** {@link Properties.currentStateName} when the error was constructed. */
164
+ stateName;
165
+ /** Snapshot of {@link State.ctx} when the error was constructed. */
166
+ context;
167
+ /** Original thrown value when this error wraps a handler or lifecycle failure. */
168
+ cause;
169
+ constructor(name, hsm, message, cause) {
170
+ super(message);
171
+ this.name = name;
172
+ this.topStateName = hsm.topStateName;
173
+ this.stateName = hsm.currentStateName;
174
+ this.context = hsm.ctx;
175
+ this.cause = cause;
176
+ }
177
+ }
178
+ exports.HsmError = HsmError;
179
+ /**
180
+ * Error base for failures during **event dispatch**, with correlated event metadata.
181
+ *
182
+ * @typeParam Context - Domain context
183
+ * @typeParam Protocol - Vocabulary interface
184
+ * @typeParam EventName - Event or service key being processed
185
+ *
186
+ * @category Error
187
+ */
188
+ class RuntimeError extends HsmError {
189
+ /** Event or service name that was active when the failure occurred. */
190
+ eventName;
191
+ /** Client-supplied arguments (excluding resolve/reject for services). */
192
+ eventPayload;
193
+ constructor(errorName, hsm, message, cause) {
194
+ super(errorName, hsm, message, cause);
195
+ this.eventName = hsm.eventName;
196
+ this.eventPayload = hsm.eventPayload;
197
+ }
198
+ }
199
+ exports.RuntimeError = RuntimeError;
200
+ /**
201
+ * Thrown when {@link StateEvents.onExit} or {@link StateEvents.onEntry} throws during a transition.
202
+ *
203
+ * @category Error
204
+ */
205
+ class TransitionError extends RuntimeError {
206
+ failedStateName;
207
+ failedCallback;
208
+ fromStateName;
209
+ toStateName;
210
+ /**
211
+ * @param hsm - Machine view at failure time
212
+ * @param cause - Error thrown from the lifecycle hook
213
+ * @param failedStateName - Display name of the state whose hook failed
214
+ * @param failedCallback - Which hook failed (`onExit` or `onEntry`)
215
+ * @param fromStateName - Leaf state before the transition
216
+ * @param toStateName - Requested destination state
217
+ */
218
+ constructor(hsm, cause, failedStateName, failedCallback, fromStateName, toStateName) {
219
+ super('TransitionError', hsm, `${failedStateName}.${failedCallback}() has failed while executing a transition from ${fromStateName} to ${toStateName}`, cause);
220
+ this.failedStateName = failedStateName;
221
+ this.failedCallback = failedCallback;
222
+ this.fromStateName = fromStateName;
223
+ this.toStateName = toStateName;
224
+ }
225
+ }
226
+ exports.TransitionError = TransitionError;
227
+ /**
228
+ * Thrown when an event handler body throws and {@link StateEvents.onError} does not recover.
229
+ *
230
+ * @category Error
231
+ */
232
+ class EventHandlerError extends RuntimeError {
233
+ /**
234
+ * @param hsm - Machine view with {@link eventName} set to the failing handler
235
+ * @param cause - Error thrown from handler code
236
+ */
237
+ constructor(hsm, cause) {
238
+ super('EventHandlerError', hsm, `an error was thrown while executing event handler #${hsm.eventName} in state ${hsm.currentStateName}`, cause);
239
+ }
240
+ }
241
+ exports.EventHandlerError = EventHandlerError;
242
+ /**
243
+ * Thrown when no handler matches the dispatched event and {@link StateEvents.onUnhandled} rethrows.
244
+ *
245
+ * @category Error
246
+ */
247
+ class UnhandledEventError extends RuntimeError {
248
+ /** @param hsm - Machine view with the unmatched {@link eventName} */
249
+ constructor(hsm) {
250
+ super('UnhandledEventError', hsm, `event #${hsm.eventName} was unhandled in state ${hsm.currentStateName}`);
251
+ }
252
+ }
253
+ exports.UnhandledEventError = UnhandledEventError;
254
+ /**
255
+ * Thrown at **class definition** time when {@link InitialState} is applied twice to one parent.
256
+ *
257
+ * @category Error
258
+ */
259
+ class InitialStateError extends Error {
260
+ /** Display name of the state passed to the duplicate {@link InitialState} call. */
261
+ targetStateName;
262
+ /** @param targetState - The state class whose parent already has an initial substate */
263
+ constructor(targetState) {
264
+ super(`State '${(0, utils_1.getStateName)(Object.getPrototypeOf(targetState.prototype).constructor)}' must not have more than one initial state`);
265
+ this.name = 'InitialStateError';
266
+ this.targetStateName = (0, utils_1.getStateName)(targetState);
267
+ }
268
+ }
269
+ exports.InitialStateError = InitialStateError;
270
+ /**
271
+ * Thrown when {@link StateEvents.onError} itself throws, leaving the machine unrecoverable.
272
+ *
273
+ * @category Error
274
+ */
275
+ class FatalError extends RuntimeError {
276
+ /**
277
+ * @param hsm - Machine view at failure time
278
+ * @param cause - Error thrown from `onError`
279
+ */
280
+ constructor(hsm, cause) {
281
+ super('FatalError', hsm, `onError() has thrown ${(0, utils_1.quoteError)(cause)}`, cause);
282
+ }
283
+ }
284
+ exports.FatalError = FatalError;
285
+ /**
286
+ * Thrown when {@link StateEvents.onEntry} fails during the initial `@InitialState` walk at startup.
287
+ *
288
+ * @category Error
289
+ */
290
+ class InitializationError extends HsmError {
291
+ failedState;
292
+ /**
293
+ * @param hsm - Partially initialized machine
294
+ * @param failedState - State class whose `onEntry` threw
295
+ * @param cause - Original error from `onEntry`
296
+ */
297
+ constructor(hsm, failedState, cause) {
298
+ super('InitializationError', hsm, `state ${(0, utils_1.getStateName)(failedState)} has thrown ${(0, utils_1.quoteError)(cause)} during initialization`, cause);
299
+ this.failedState = failedState;
300
+ }
301
+ }
302
+ exports.InitializationError = InitializationError;
303
+ /**
304
+ * Terminal sink state class used when the runtime cannot recover from an error.
305
+ *
306
+ * Assign or transition here from custom {@link StateEvents.onError} handlers when you need a
307
+ * well-defined quiescent state. Display name is pre-registered as `'FatalErrorState'`.
308
+ *
309
+ * @category State machine
310
+ */
311
+ class FatalErrorState extends TopState {
312
+ }
313
+ exports.FatalErrorState = FatalErrorState;
314
+ (0, utils_1.defineStateName)(TopState, 'TopState');
315
+ (0, utils_1.defineStateName)(FatalErrorState, 'FatalErrorState');
316
+ /**
317
+ * Declares `TargetState` as the **initial substate** of its direct parent composite.
318
+ *
319
+ * Apply as a TypeScript decorator or call as a function at class definition time. Exactly **one**
320
+ * initial child is allowed per parent; a second mark throws {@link InitialStateError}.
321
+ *
322
+ * @typeParam Context - Domain context type
323
+ * @typeParam Protocol - Vocabulary interface
324
+ * @param TargetState - Child state class whose **parent** is `Object.getPrototypeOf(TargetState.prototype).constructor`
325
+ *
326
+ * @throws {@link InitialStateError} when the parent already has an initial substate
327
+ *
328
+ * @remarks
329
+ * During {@link makeHsm} initialization, the runtime descends `@InitialState` chains from the
330
+ * root until the deepest initial leaf is active, running {@link StateEvents.onEntry} along the path.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * class Composite extends TopState {}
335
+ *
336
+ * @InitialState
337
+ * class Idle extends Composite {}
338
+ * ```
339
+ */
340
+ function InitialState(TargetState) {
341
+ const ParentOfTargetState = Object.getPrototypeOf(TargetState.prototype).constructor;
342
+ if ((0, utils_1.hasInitialState)(ParentOfTargetState))
343
+ throw new InitialStateError(TargetState);
344
+ Object.defineProperty(TargetState, '_isInitialState', {
345
+ value: true,
346
+ writable: false,
347
+ configurable: false,
348
+ enumerable: false,
349
+ });
350
+ Object.defineProperty(ParentOfTargetState, '_initialState', {
351
+ value: TargetState,
352
+ writable: false,
353
+ configurable: false,
354
+ enumerable: false,
355
+ });
356
+ }
357
+ /**
358
+ * Assigns a stable **display name** to a single state class.
359
+ *
360
+ * Minifiers rewrite `Class.name` in production browser bundles; explicit registration keeps
361
+ * {@link Properties.currentStateName}, trace output, and error messages readable everywhere.
362
+ *
363
+ * @typeParam Context - Domain context type
364
+ * @typeParam Protocol - Vocabulary interface
365
+ * @param state - State class constructor to tag
366
+ * @param name - Non-empty display string used in traces and errors (not required to match `Class.name`)
367
+ *
368
+ * @remarks
369
+ * Stored as a non-enumerable own property — never inherited by subclasses from the prototype chain.
370
+ * {@link registerStateNames} is preferred when every state is a named export from one module.
371
+ *
372
+ * @example
373
+ * ```ts
374
+ * class Door extends TopState {}
375
+ * defineStateName(Door, 'Door');
376
+ * ```
377
+ *
378
+ * @category State machine
379
+ */
380
+ function defineStateName(state, name) {
381
+ (0, utils_1.defineStateName)(state, name);
382
+ }
383
+ /**
384
+ * Registers display names for **every** state class in an exports object, using each **export key** as the name.
385
+ *
386
+ * @param exports - Module namespace (`import * as machine`) or object literal of state classes.
387
+ * Non-constructor exports (constants, functions, types) are silently skipped
388
+ *
389
+ * @remarks
390
+ * Export keys survive minification even when class identifiers are mangled — this is the recommended
391
+ * approach for browser bundles without `keep_classnames`. Call once at module load after all state
392
+ * classes are defined.
393
+ *
394
+ * @example Single module
395
+ * ```ts
396
+ * export class DoorTop extends TopState {}
397
+ * export class Open extends DoorTop {}
398
+ * export class Closed extends DoorTop {}
399
+ * registerStateNames({ DoorTop, Open, Closed });
400
+ * ```
401
+ *
402
+ * @example Re-exporting namespace
403
+ * ```ts
404
+ * import * as machine from './machine';
405
+ * registerStateNames(machine);
406
+ * ```
407
+ *
408
+ * @category State machine
409
+ */
410
+ function registerStateNames(exports) {
411
+ for (const [exportName, value] of Object.entries(exports)) {
412
+ if (isStateClass(value)) {
413
+ (0, utils_1.defineStateName)(value, exportName);
414
+ }
415
+ }
416
+ }
417
+ /** @internal — structural guard: a constructor whose prototype derives from {@link TopState}. */
418
+ function isStateClass(value) {
419
+ if (typeof value !== 'function')
420
+ return false;
421
+ const prototype = value.prototype;
422
+ return typeof prototype === 'object' && prototype !== null && TopState.prototype.isPrototypeOf(prototype);
423
+ }
424
+ /** @internal */
425
+ class ConsoleTraceWriter {
426
+ write(hsm, Message) {
427
+ if (typeof Message == 'string') {
428
+ console.log(`${hsm.traceHeader}${hsm.currentStateName}: ${Message}`);
429
+ }
430
+ else {
431
+ console.log(Message);
432
+ }
433
+ }
434
+ }
435
+ function defaultDispatchErrorCallback(hsm, err) {
436
+ const writer = hsm.traceWriter;
437
+ writer.write(hsm, `An event dispatch has failed; error ${err.name}: ${err.message} has not been managed`);
438
+ writer.write(hsm, err);
439
+ throw err;
440
+ }
441
+ const defaultTraceWriter = new ConsoleTraceWriter();
442
+ const defaultTraceLevel = TraceLevel.DEBUG;
443
+ const defaultInitialize = true;
444
+ /**
445
+ * Creates and optionally initializes a hierarchical state machine **actor** bound to `ctx`.
446
+ *
447
+ * The returned {@link Hsm} is the single runtime object: external clients call `post` / `call` /
448
+ * `sync`; the active state is the instance prototype chain updated by {@link State.transition}.
449
+ *
450
+ * @typeParam Context - Domain context type (inferred from `ctx` when passed inline)
451
+ * @typeParam Protocol - Event/service vocabulary (inferred from `topState` when it implements `Protocol`)
452
+ * @param topState - Root state **class** constructor (must extend {@link TopState})
453
+ * @param ctx - Mutable domain object shared by all states; stored on the instance as {@link Hsm.ctx}
454
+ * @param initialize - When `true` (default), enqueue the initial walk: descend `@InitialState`
455
+ * chains from `topState` and run {@link StateEvents.onEntry} on each entered state until the
456
+ * initial leaf is active. When `false`, prototype starts at `topState` with **no** entry hooks
457
+ * @param traceLevel - Initial {@link TraceLevel} (default {@link TraceLevel.DEBUG})
458
+ * @param traceWriter - {@link TraceWriter} implementation (default: prefixes strings with state name and logs to `console`)
459
+ * @param dispatchErrorCallback - Last-resort error hook (default: trace + rethrow)
460
+ * @returns Client handle implementing {@link Hsm} for the same `Context` and `Protocol`
461
+ *
462
+ * @remarks
463
+ * - Await {@link Hsm.sync} after creation when `initialize: true` before asserting initial state
464
+ * - Zero runtime npm dependencies; safe to embed in browsers when state names are registered
465
+ * - Transition LCA paths are cached per machine instance for the lifetime of the actor
466
+ *
467
+ * @example Minimal door machine
468
+ * ```ts
469
+ * const door = makeHsm(DoorTop, { openCount: 0 });
470
+ * await door.sync();
471
+ * door.post('open');
472
+ * await door.sync();
473
+ * ```
474
+ *
475
+ * @example Custom tracing in tests
476
+ * ```ts
477
+ * const writer = { write: (_hsm, msg) => logs.push(msg) };
478
+ * const sm = makeHsm(Top, ctx, true, TraceLevel.VERBOSE_DEBUG, writer);
479
+ * await sm.sync();
480
+ * ```
481
+ *
482
+ * @category Factory
483
+ */
484
+ function makeHsm(topState, ctx, initialize = defaultInitialize, traceLevel = defaultTraceLevel, traceWriter = defaultTraceWriter, dispatchErrorCallback = defaultDispatchErrorCallback) {
485
+ const instance = {
486
+ hsm: undefined,
487
+ ctx: ctx,
488
+ };
489
+ Object.setPrototypeOf(instance, topState.prototype);
490
+ instance.hsm = new hsm_1.HsmObject(topState, instance, traceWriter, traceLevel, dispatchErrorCallback, initialize);
491
+ return instance.hsm;
492
+ }
493
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAs9BA,oCAeC;AAyBD,0CAEC;AA6BD,gDAMC;AAuED,0BAQC;AAjnCD,wCAA2C;AAC3C,4CAAyH;AA2EzH,6JAA6J;AAE7J;;;;;;;GAOG;AACH,IAAY,UAgBX;AAhBD,WAAY,UAAU;IACrB;;;OAGG;IACH,uDAAU,CAAA;IACV;;;OAGG;IACH,6CAAK,CAAA;IACL;;;OAGG;IACH,6DAAa,CAAA;AACd,CAAC,EAhBW,UAAU,0BAAV,UAAU,QAgBrB;AAujBD;;;;;;;;;;GAUG;AACH,MAAsB,QAAQ;IAC7B,4EAA4E;IACnE,GAAG,CAAW;IACvB,8FAA8F;IACrF,GAAG,CAA4B;IACxC;QACC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAC/D,CAAC;IACD,uCAAuC;IACvC,IAAI,SAAS;QACZ,OAAO,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;IAC3B,CAAC;IACD,0CAA0C;IAC1C,IAAI,YAAY;QACf,OAAO,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC;IAC9B,CAAC;IACD,yCAAyC;IACzC,IAAI,WAAW;QACd,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC;IAC7B,CAAC;IACD,sCAAsC;IACtC,IAAI,QAAQ;QACX,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;IAC1B,CAAC;IACD,8CAA8C;IAC9C,I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B,kBAAkB,EAAE,wBAAkE,4BAA4B;IAC1V,MAAM,QAAQ,GAAgC;QAC7C,GAAG,EAAE,SAAyD;QAC9D,GAAG,EAAE,GAAG;KACR,CAAC;IACF,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,GAAG,GAAG,IAAI,eAAS,CAAC,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,qBAAqB,EAAE,UAAU,CAAC,CAAC;IAC7G,OAAO,QAAQ,CAAC,GAAG,CAAC;AACrB,CAAC"}
@@ -0,0 +1,31 @@
1
+ import { PostedEvent, EventPayload, Hsm, StateClass, State } from '../';
2
+ /** @internal */
3
+ export interface Instance<Context, Protocol extends {} | undefined> {
4
+ ctx: Context;
5
+ hsm: HsmWithTracing<Context, Protocol>;
6
+ }
7
+ /** @internal */
8
+ export interface Transition<Context, Protocol extends {} | undefined> {
9
+ execute(hsm: HsmWithTracing<Context, Protocol>, srcState: StateClass<Context, Protocol>, dstState: StateClass<Context, Protocol>): Promise<void>;
10
+ }
11
+ /** @internal */
12
+ export type DoneCallback = () => void;
13
+ /** @internal */
14
+ export type Task = (done: DoneCallback) => void;
15
+ /** @internal */
16
+ export interface HsmWithTracing<Context, Protocol extends {} | undefined> extends Hsm<Context, Protocol>, State<Context, Protocol> {
17
+ _transitionCache: Map<string, Transition<Context, Protocol>>;
18
+ _createInitTask: <DispatchContext, DispatchProtocol extends {} | undefined>(hsm: HsmWithTracing<DispatchContext, DispatchProtocol>) => Task;
19
+ _createEventDispatchTask: <DispatchContext, DispatchProtocol extends {} | undefined, EventName extends keyof DispatchProtocol>(hsm: HsmWithTracing<DispatchContext, DispatchProtocol>, eventName: PostedEvent<DispatchProtocol, EventName>, ...eventPayload: EventPayload<DispatchProtocol, EventName>) => Task;
20
+ _instance: Instance<Context, Protocol>;
21
+ _transitionState?: StateClass<Context, Protocol>;
22
+ _currentEventName?: string;
23
+ _currentEventPayload?: any[];
24
+ currentState: StateClass<Context, Protocol>;
25
+ _tracePush(domain: string, msg: string): void;
26
+ _tracePopDone(msg: string): void;
27
+ _tracePopError(msg: string): void;
28
+ _traceWrite(msg: any): void;
29
+ unshiftHiPriorityTask(t: Task): void;
30
+ pushHiPriorityTask(t: Task): void;
31
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=defs.private.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defs.private.js","sourceRoot":"","sources":["../../../src/internal/defs.private.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ import { PostedEvent, EventPayload } from '../';
2
+ import { HsmWithTracing, Task } from './defs.private';
3
+ export declare function createInitTask<DispatchContext, DispatchProtocol extends {} | undefined>(hsm: HsmWithTracing<DispatchContext, DispatchProtocol>): Task;
4
+ export declare function createEventDispatchTask<DispatchContext, DispatchProtocol extends {} | undefined, EventName extends keyof DispatchProtocol>(hsm: HsmWithTracing<DispatchContext, DispatchProtocol>, eventName: PostedEvent<DispatchProtocol, EventName>, ...eventPayload: EventPayload<DispatchProtocol, EventName>): Task;