@raphy-js/raph 1.0.0-dev.2 → 1.0.1-dev.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 (211) hide show
  1. package/README.md +1096 -0
  2. package/dist/api/Raph.d.ts +59 -190
  3. package/dist/api/RaphFacadeSession.d.ts +90 -0
  4. package/dist/api/RaphReactivityInstance.d.ts +72 -0
  5. package/dist/api/errors.d.ts +9 -4
  6. package/dist/api/types.d.ts +162 -17
  7. package/dist/core-CyilRD7s.js +1055 -0
  8. package/dist/core-ugchZNqC.cjs +1 -0
  9. package/dist/debug/api/Raph.cjs +1 -1
  10. package/dist/debug/api/Raph.js +368 -366
  11. package/dist/debug/api/RaphFacadeSession.cjs +1 -0
  12. package/dist/debug/api/RaphFacadeSession.js +306 -0
  13. package/dist/debug/api/RaphReactivityInstance.cjs +1 -0
  14. package/dist/debug/api/RaphReactivityInstance.js +149 -0
  15. package/dist/debug/api/errors.cjs +1 -1
  16. package/dist/debug/api/errors.js +10 -7
  17. package/dist/debug/path/DataPath.cjs +1 -0
  18. package/dist/debug/path/{data-path.js → DataPath.js} +151 -180
  19. package/dist/debug/path/PathRouter.cjs +1 -0
  20. package/dist/debug/path/{path-router.js → PathRouter.js} +1 -1
  21. package/dist/debug/path/RaphKernel.cjs +1 -1
  22. package/dist/debug/path/RaphKernel.js +258 -207
  23. package/dist/debug/path/data-path.utils.cjs +1 -0
  24. package/dist/debug/path/data-path.utils.js +56 -0
  25. package/dist/debug/path/derived/DerivedRegistry.cjs +1 -0
  26. package/dist/debug/path/{DerivedRegistry.js → derived/DerivedRegistry.js} +5 -5
  27. package/dist/debug/path/derived/derived-collection.utils.cjs +1 -0
  28. package/dist/debug/path/{derived-collection.js → derived/derived-collection.utils.js} +1 -1
  29. package/dist/debug/path/derived/derived-strategy.types.cjs +1 -0
  30. package/dist/debug/path/derived/derived-strategy.types.js +1 -0
  31. package/dist/debug/path/{MetaController.cjs → meta/MetaController.cjs} +1 -1
  32. package/dist/debug/path/{MetaController.js → meta/MetaController.js} +3 -3
  33. package/dist/debug/path/meta/RaphMetaStore.cjs +1 -0
  34. package/dist/debug/path/{RaphMetaStore.js → meta/RaphMetaStore.js} +1 -1
  35. package/dist/debug/path/meta/meta.types.cjs +1 -0
  36. package/dist/debug/path/meta/meta.types.js +1 -0
  37. package/dist/debug/path/storage/AdapterPathStore.cjs +1 -0
  38. package/dist/debug/path/{AdapterPathStore.js → storage/AdapterPathStore.js} +9 -9
  39. package/dist/debug/path/storage/DefaultDataAdapter.cjs +1 -0
  40. package/dist/debug/path/{data-adapter.js → storage/DefaultDataAdapter.js} +2 -2
  41. package/dist/debug/path/storage/PathEventHub.cjs +1 -0
  42. package/dist/debug/path/{PathEventHub.js → storage/PathEventHub.js} +34 -34
  43. package/dist/debug/path/storage/PathStore.cjs +1 -0
  44. package/dist/debug/path/{PathStore.js → storage/PathStore.js} +28 -28
  45. package/dist/debug/path/storage/data-adapter.types.cjs +1 -0
  46. package/dist/debug/path/storage/data-adapter.types.js +1 -0
  47. package/dist/debug/reactivity/engine.cjs +1 -1
  48. package/dist/debug/reactivity/engine.js +478 -306
  49. package/dist/debug/reactivity/reactive-object.cjs +1 -0
  50. package/dist/debug/reactivity/reactive-object.js +280 -0
  51. package/dist/debug/runtime/RaphRuntime.cjs +1 -1
  52. package/dist/debug/runtime/RaphRuntime.js +798 -519
  53. package/dist/debug/runtime/diagnostics/RaphDebug.cjs +1 -0
  54. package/dist/debug/runtime/diagnostics/RaphDebug.js +297 -0
  55. package/dist/debug/runtime/errors.cjs +1 -1
  56. package/dist/debug/runtime/errors.js +6 -3
  57. package/dist/debug/runtime/ownership/RaphEffectScope.cjs +1 -0
  58. package/dist/debug/runtime/ownership/RaphEffectScope.js +171 -0
  59. package/dist/debug/runtime/ownership/RaphNode.cjs +1 -0
  60. package/dist/debug/runtime/ownership/RaphNode.js +206 -0
  61. package/dist/debug/runtime/ownership/RaphScope.cjs +1 -0
  62. package/dist/debug/runtime/ownership/RaphScope.js +101 -0
  63. package/dist/debug/runtime/ownership/parent-graph.types.cjs +1 -0
  64. package/dist/debug/runtime/ownership/parent-graph.types.js +1 -0
  65. package/dist/debug/runtime/phases/RaphPhasePipeline.cjs +1 -0
  66. package/dist/debug/runtime/phases/RaphPhasePipeline.js +587 -0
  67. package/dist/debug/runtime/phases/orderPhaseTasks.cjs +1 -0
  68. package/dist/debug/runtime/phases/orderPhaseTasks.js +59 -0
  69. package/dist/debug/runtime/reactivity/PathHandle.cjs +1 -0
  70. package/dist/debug/runtime/{PathHandle.js → reactivity/PathHandle.js} +75 -39
  71. package/dist/debug/runtime/reactivity/RaphMetaSource.cjs +1 -0
  72. package/dist/debug/runtime/reactivity/RaphMetaSource.js +112 -0
  73. package/dist/debug/runtime/reactivity/RaphWorkGraph.cjs +1 -0
  74. package/dist/debug/runtime/reactivity/RaphWorkGraph.js +995 -0
  75. package/dist/debug/runtime/reactivity/RuntimeReactivity.cjs +1 -0
  76. package/dist/debug/runtime/reactivity/RuntimeReactivity.js +156 -0
  77. package/dist/debug/runtime/reactivity/RuntimeWatch.cjs +1 -0
  78. package/dist/debug/runtime/reactivity/RuntimeWatch.js +88 -0
  79. package/dist/debug/runtime/reactivity/runtime-reactivity.types.cjs +1 -0
  80. package/dist/debug/runtime/reactivity/runtime-reactivity.types.js +1 -0
  81. package/dist/entrypoints/machine-testing.d.ts +2 -0
  82. package/dist/entrypoints/machine.d.ts +5 -0
  83. package/dist/entrypoints/path.d.ts +14 -0
  84. package/dist/entrypoints/reactivity.d.ts +1 -0
  85. package/dist/entrypoints/runtime.d.ts +17 -0
  86. package/dist/index.cjs +1 -1
  87. package/dist/index.js +46 -38
  88. package/dist/machine/compiler.d.ts +71 -0
  89. package/dist/machine/core.d.ts +50 -0
  90. package/dist/machine/persistence.d.ts +5 -0
  91. package/dist/machine/runtime.d.ts +4 -0
  92. package/dist/machine/testing.d.ts +43 -0
  93. package/dist/machine/types.d.ts +155 -0
  94. package/dist/machine-testing.cjs +1 -0
  95. package/dist/machine-testing.js +188 -0
  96. package/dist/machine.cjs +1 -0
  97. package/dist/machine.js +837 -0
  98. package/dist/main.d.ts +20 -0
  99. package/dist/path/{data-path.d.ts → DataPath.d.ts} +16 -40
  100. package/dist/path/{path-router.d.ts → PathRouter.d.ts} +1 -1
  101. package/dist/path/RaphKernel.d.ts +13 -10
  102. package/dist/path/data-path.types.d.ts +34 -0
  103. package/dist/path/data-path.utils.d.ts +9 -0
  104. package/dist/path/{DerivedRegistry.d.ts → derived/DerivedRegistry.d.ts} +2 -2
  105. package/dist/path/{RaphDerivedHandle.d.ts → derived/RaphDerivedHandle.d.ts} +3 -3
  106. package/dist/path/derived/derived-collection.types.d.ts +12 -0
  107. package/dist/path/{derived-collection.d.ts → derived/derived-collection.utils.d.ts} +3 -13
  108. package/dist/path/{derived-strategies.d.ts → derived/derived-strategy.types.d.ts} +0 -3
  109. package/dist/path/derived/derived-strategy.utils.d.ts +4 -0
  110. package/dist/path/{MetaController.d.ts → meta/MetaController.d.ts} +4 -4
  111. package/dist/path/{RaphMeta.d.ts → meta/RaphMeta.d.ts} +2 -2
  112. package/dist/path/{RaphMetaStore.d.ts → meta/RaphMetaStore.d.ts} +1 -1
  113. package/dist/path/{meta.types.d.ts → meta/meta.types.d.ts} +2 -4
  114. package/dist/path/path.types.d.ts +3 -2
  115. package/dist/path/{segment-key.d.ts → pathSegmentKey.d.ts} +1 -1
  116. package/dist/path/{AdapterPathStore.d.ts → storage/AdapterPathStore.d.ts} +4 -4
  117. package/dist/path/{data-adapter.d.ts → storage/DefaultDataAdapter.d.ts} +2 -17
  118. package/dist/path/{PathEventHub.d.ts → storage/PathEventHub.d.ts} +9 -9
  119. package/dist/path/{PathStore.d.ts → storage/PathStore.d.ts} +3 -3
  120. package/dist/path/storage/data-adapter.types.d.ts +17 -0
  121. package/dist/path.cjs +1 -1
  122. package/dist/path.js +16 -16
  123. package/dist/raph.cjs +1 -1
  124. package/dist/raph.js +46 -38
  125. package/dist/reactivity/engine.d.ts +17 -3
  126. package/dist/reactivity/reactive-object.d.ts +36 -0
  127. package/dist/reactivity/types.d.ts +25 -0
  128. package/dist/reactivity.cjs +1 -1
  129. package/dist/reactivity.js +12 -12
  130. package/dist/runtime/RaphRuntime.d.ts +132 -192
  131. package/dist/runtime/diagnostics/RaphDebug.d.ts +239 -0
  132. package/dist/runtime/errors.d.ts +5 -0
  133. package/dist/runtime/ownership/RaphEffectScope.d.ts +29 -0
  134. package/dist/runtime/ownership/RaphNode.d.ts +40 -0
  135. package/dist/runtime/ownership/RaphScope.d.ts +38 -0
  136. package/dist/runtime/{parent-graph.d.ts → ownership/parent-graph.types.d.ts} +0 -1
  137. package/dist/runtime/ownership/parentGraph.d.ts +3 -0
  138. package/dist/runtime/phases/RaphPhasePipeline.d.ts +79 -0
  139. package/dist/runtime/phases/orderPhaseTasks.d.ts +6 -0
  140. package/dist/runtime/phases/phase.types.d.ts +92 -0
  141. package/dist/runtime/{PathHandle.d.ts → reactivity/PathHandle.d.ts} +14 -6
  142. package/dist/runtime/reactivity/RaphMetaSource.d.ts +32 -0
  143. package/dist/runtime/reactivity/RaphWorkGraph.d.ts +171 -0
  144. package/dist/runtime/{RuntimeReactivity.d.ts → reactivity/RuntimeReactivity.d.ts} +14 -9
  145. package/dist/runtime/{RuntimeWatch.d.ts → reactivity/RuntimeWatch.d.ts} +9 -3
  146. package/dist/runtime/{runtime-reactivity.types.d.ts → reactivity/runtime-reactivity.types.d.ts} +3 -1
  147. package/dist/runtime.cjs +1 -1
  148. package/dist/runtime.js +21 -16
  149. package/package.json +68 -35
  150. package/ReadMe.md +0 -153
  151. package/dist/api/public.d.ts +0 -22
  152. package/dist/debug/api/public.cjs +0 -1
  153. package/dist/debug/api/public.js +0 -40
  154. package/dist/debug/path/AdapterPathStore.cjs +0 -1
  155. package/dist/debug/path/DerivedRegistry.cjs +0 -1
  156. package/dist/debug/path/PathEventHub.cjs +0 -1
  157. package/dist/debug/path/PathStore.cjs +0 -1
  158. package/dist/debug/path/RaphMetaStore.cjs +0 -1
  159. package/dist/debug/path/data-adapter.cjs +0 -1
  160. package/dist/debug/path/data-path.cjs +0 -1
  161. package/dist/debug/path/derived-collection.cjs +0 -1
  162. package/dist/debug/path/path-router.cjs +0 -1
  163. package/dist/debug/path/public.cjs +0 -1
  164. package/dist/debug/path/public.js +0 -18
  165. package/dist/debug/runtime/PathHandle.cjs +0 -1
  166. package/dist/debug/runtime/RaphDebug.cjs +0 -1
  167. package/dist/debug/runtime/RaphDebug.js +0 -15
  168. package/dist/debug/runtime/RaphNode.cjs +0 -1
  169. package/dist/debug/runtime/RaphNode.js +0 -143
  170. package/dist/debug/runtime/RaphPhasePipeline.cjs +0 -1
  171. package/dist/debug/runtime/RaphPhasePipeline.js +0 -526
  172. package/dist/debug/runtime/RaphScope.cjs +0 -1
  173. package/dist/debug/runtime/RaphScope.js +0 -64
  174. package/dist/debug/runtime/RuntimeReactivity.cjs +0 -1
  175. package/dist/debug/runtime/RuntimeReactivity.js +0 -154
  176. package/dist/debug/runtime/RuntimeWatch.cjs +0 -1
  177. package/dist/debug/runtime/RuntimeWatch.js +0 -71
  178. package/dist/debug/runtime/public.cjs +0 -1
  179. package/dist/debug/runtime/public.js +0 -18
  180. package/dist/path/public.d.ts +0 -14
  181. package/dist/runtime/RaphDebug.d.ts +0 -32
  182. package/dist/runtime/RaphNode.d.ts +0 -68
  183. package/dist/runtime/RaphPhasePipeline.d.ts +0 -133
  184. package/dist/runtime/RaphScope.d.ts +0 -50
  185. package/dist/runtime/phase.types.d.ts +0 -49
  186. package/dist/runtime/public.d.ts +0 -13
  187. /package/dist/debug/path/{meta.types.cjs → data-path.types.cjs} +0 -0
  188. /package/dist/debug/path/{meta.types.js → data-path.types.js} +0 -0
  189. /package/dist/debug/path/{RaphDerivedHandle.cjs → derived/RaphDerivedHandle.cjs} +0 -0
  190. /package/dist/debug/path/{RaphDerivedHandle.js → derived/RaphDerivedHandle.js} +0 -0
  191. /package/dist/debug/{runtime/runtime-reactivity.types.cjs → path/derived/derived-collection.types.cjs} +0 -0
  192. /package/dist/debug/{runtime/runtime-reactivity.types.js → path/derived/derived-collection.types.js} +0 -0
  193. /package/dist/debug/path/{derived-strategies.cjs → derived/derived-strategy.utils.cjs} +0 -0
  194. /package/dist/debug/path/{derived-strategies.js → derived/derived-strategy.utils.js} +0 -0
  195. /package/dist/debug/path/{RaphMeta.cjs → meta/RaphMeta.cjs} +0 -0
  196. /package/dist/debug/path/{RaphMeta.js → meta/RaphMeta.js} +0 -0
  197. /package/dist/debug/path/{segment-key.cjs → pathSegmentKey.cjs} +0 -0
  198. /package/dist/debug/path/{segment-key.js → pathSegmentKey.js} +0 -0
  199. /package/dist/debug/path/{data-draft.cjs → storage/createDataDraft.cjs} +0 -0
  200. /package/dist/debug/path/{data-draft.js → storage/createDataDraft.js} +0 -0
  201. /package/dist/debug/runtime/{parent-graph.cjs → ownership/parentGraph.cjs} +0 -0
  202. /package/dist/debug/runtime/{parent-graph.js → ownership/parentGraph.js} +0 -0
  203. /package/dist/debug/runtime/{disposal.cjs → ownership/throwDisposalErrors.cjs} +0 -0
  204. /package/dist/debug/runtime/{disposal.js → ownership/throwDisposalErrors.js} +0 -0
  205. /package/dist/debug/runtime/{RaphFrameLoop.cjs → phases/RaphFrameLoop.cjs} +0 -0
  206. /package/dist/debug/runtime/{RaphFrameLoop.js → phases/RaphFrameLoop.js} +0 -0
  207. /package/dist/debug/runtime/{phase.types.cjs → phases/phase.types.cjs} +0 -0
  208. /package/dist/debug/runtime/{phase.types.js → phases/phase.types.js} +0 -0
  209. /package/dist/path/{data-draft.d.ts → storage/createDataDraft.d.ts} +0 -0
  210. /package/dist/runtime/{disposal.d.ts → ownership/throwDisposalErrors.d.ts} +0 -0
  211. /package/dist/runtime/{RaphFrameLoop.d.ts → phases/RaphFrameLoop.d.ts} +0 -0
@@ -0,0 +1,155 @@
1
+ import { Disposer, ReadonlySignal } from '../reactivity/types';
2
+ import { RaphNode } from '../runtime/ownership/RaphNode';
3
+ import { RaphScope } from '../runtime/ownership/RaphScope';
4
+ export interface MachineEvent {
5
+ readonly type: string;
6
+ }
7
+ export type MachineStatus = 'active' | 'done' | 'stopped';
8
+ export type MachineEventStatus = 'ignored' | 'queued' | 'transitioned';
9
+ export interface MachineSnapshot<Context, Output = unknown> {
10
+ readonly active: readonly string[];
11
+ readonly context: Readonly<Context>;
12
+ readonly history: Readonly<Record<string, readonly string[]>>;
13
+ readonly output?: Output;
14
+ readonly revision: number;
15
+ readonly status: MachineStatus;
16
+ }
17
+ export interface MachineGuardArgs<Context, Event extends MachineEvent, Input> {
18
+ readonly context: Readonly<Context>;
19
+ readonly event: Event;
20
+ readonly input: Input;
21
+ }
22
+ export interface MachineReducerArgs<Context, Event extends MachineEvent, Input> extends MachineGuardArgs<Context, Event, Input> {
23
+ }
24
+ export interface MachineOutputArgs<Context, Event extends MachineEvent, Input> extends MachineGuardArgs<Context, Event, Input> {
25
+ readonly snapshot: MachineSnapshot<Context>;
26
+ }
27
+ export type MachineGuard<Context, Event extends MachineEvent, Input> = (args: MachineGuardArgs<Context, Event, Input>) => boolean;
28
+ export type MachineReducer<Context, Event extends MachineEvent, Input> = (args: MachineReducerArgs<Context, Event, Input>) => Context;
29
+ export type MachineOutput<Context, Event extends MachineEvent, Input> = (args: MachineOutputArgs<Context, Event, Input>) => void;
30
+ export type MachineGuardRef<Context, Event extends MachineEvent, Input> = MachineGuard<Context, Event, Input> | string;
31
+ export type MachineReducerRef<Context, Event extends MachineEvent, Input> = MachineReducer<Context, Event, Input> | string;
32
+ export type MachineOutputRef<Context, Event extends MachineEvent, Input> = MachineOutput<Context, Event, Input> | string;
33
+ export interface MachineTransitionConfig<Context, Event extends MachineEvent, Input> {
34
+ readonly emit?: MachineOutputRef<Context, Event, Input> | readonly MachineOutputRef<Context, Event, Input>[];
35
+ readonly guard?: MachineGuardRef<Context, Event, Input>;
36
+ readonly raise?: Event | ((args: MachineReducerArgs<Context, Event, Input>) => Event);
37
+ readonly reason?: string;
38
+ readonly reduce?: MachineReducerRef<Context, Event, Input> | readonly MachineReducerRef<Context, Event, Input>[];
39
+ readonly reenter?: boolean;
40
+ readonly target?: string;
41
+ }
42
+ export type MachineTransitionDefinition<Context, Event extends MachineEvent, Input> = MachineTransitionConfig<Context, Event, Input> | readonly MachineTransitionConfig<Context, Event, Input>[] | string;
43
+ export interface MachineInvokeConfig<Context, Event extends MachineEvent, Input> {
44
+ readonly id?: string;
45
+ readonly input?: unknown | ((args: MachineGuardArgs<Context, Event, Input>) => unknown);
46
+ readonly onDone?: MachineTransitionDefinition<Context, Event, Input>;
47
+ readonly onError?: MachineTransitionDefinition<Context, Event, Input>;
48
+ readonly src: string | MachineModel<unknown, MachineEvent, unknown, unknown>;
49
+ readonly type?: 'machine' | 'task';
50
+ }
51
+ export interface MachineStateConfig<Context, Event extends MachineEvent, Input, Output> {
52
+ readonly after?: Readonly<Record<string, MachineTransitionDefinition<Context, Event, Input>>>;
53
+ readonly always?: MachineTransitionDefinition<Context, Event, Input>;
54
+ readonly entry?: MachineOutputRef<Context, Event, Input> | readonly MachineOutputRef<Context, Event, Input>[];
55
+ readonly exit?: MachineOutputRef<Context, Event, Input> | readonly MachineOutputRef<Context, Event, Input>[];
56
+ readonly history?: 'deep' | 'shallow';
57
+ readonly initial?: string;
58
+ readonly invoke?: MachineInvokeConfig<Context, Event, Input> | readonly MachineInvokeConfig<Context, Event, Input>[];
59
+ readonly meta?: Readonly<Record<string, unknown>>;
60
+ readonly on?: Readonly<Partial<Record<Event['type'], MachineTransitionDefinition<Context, Event, Input>>>> | Readonly<Record<string, MachineTransitionDefinition<Context, Event, Input>>>;
61
+ readonly onDone?: MachineTransitionDefinition<Context, Event, Input>;
62
+ readonly output?: Output | ((args: MachineGuardArgs<Context, Event, Input>) => Output);
63
+ readonly resources?: string | readonly string[];
64
+ readonly states?: Readonly<Record<string, MachineStateConfig<Context, Event, Input, Output>>>;
65
+ readonly tags?: string | readonly string[];
66
+ readonly target?: string;
67
+ readonly type?: 'atomic' | 'compound' | 'final' | 'history' | 'parallel';
68
+ }
69
+ export interface PersistedMachineSnapshot<Context = unknown, Output = unknown> {
70
+ readonly active: readonly string[];
71
+ readonly context: Context;
72
+ readonly history: Readonly<Record<string, readonly string[]>>;
73
+ readonly modelId: string;
74
+ readonly output?: Output;
75
+ readonly revision: number;
76
+ readonly status: MachineStatus;
77
+ readonly version: number;
78
+ }
79
+ export type MachineMigration = (snapshot: PersistedMachineSnapshot) => PersistedMachineSnapshot;
80
+ export interface MachineConfig<Context, Event extends MachineEvent, Input, Output> {
81
+ readonly context: Context | ((input: Input) => Context);
82
+ readonly id: string;
83
+ readonly initial: string;
84
+ readonly migrations?: Readonly<Record<number, MachineMigration>>;
85
+ readonly output?: Output | ((args: MachineGuardArgs<Context, Event, Input>) => Output);
86
+ readonly states: Readonly<Record<string, MachineStateConfig<Context, Event, Input, Output>>>;
87
+ readonly version?: number;
88
+ }
89
+ declare const MACHINE_MODEL_TYPES: unique symbol;
90
+ export interface MachineModel<Context, Event extends MachineEvent, Input, Output> {
91
+ readonly id: string;
92
+ readonly version: number;
93
+ readonly [MACHINE_MODEL_TYPES]?: {
94
+ readonly context: Context;
95
+ readonly event: Event;
96
+ readonly input: Input;
97
+ readonly output: Output;
98
+ };
99
+ }
100
+ export interface MachineClock {
101
+ clearTimeout: (handle: unknown) => void;
102
+ now: () => number;
103
+ setTimeout: (callback: () => void, delay: number) => unknown;
104
+ }
105
+ export interface MachineTaskArgs<Context, Event extends MachineEvent, Input> extends MachineGuardArgs<Context, Event, Input> {
106
+ readonly send: (event: Event) => void;
107
+ readonly signal: AbortSignal;
108
+ }
109
+ export type MachineTask<Context, Event extends MachineEvent, Input> = (args: MachineTaskArgs<Context, Event, Input>) => unknown | Promise<unknown>;
110
+ export interface MachineResourceArgs<Context, Event extends MachineEvent, Input> extends MachineOutputArgs<Context, Event, Input> {
111
+ readonly owner: RaphNode | RaphScope;
112
+ readonly signal: AbortSignal;
113
+ }
114
+ export type MachineResource<Context, Event extends MachineEvent, Input> = (args: MachineResourceArgs<Context, Event, Input>) => void | Disposer;
115
+ export interface MachineBindings<Context, Event extends MachineEvent, Input> {
116
+ readonly actors?: Readonly<Record<string, MachineModel<unknown, MachineEvent, unknown, unknown>>>;
117
+ readonly delays?: Readonly<Record<string, number | ((args: MachineGuardArgs<Context, Event, Input>) => number)>>;
118
+ readonly guards?: Readonly<Record<string, MachineGuard<Context, Event, Input>>>;
119
+ readonly outputs?: Readonly<Record<string, MachineOutput<Context, Event, Input>>>;
120
+ readonly reducers?: Readonly<Record<string, MachineReducer<Context, Event, Input>>>;
121
+ readonly resources?: Readonly<Record<string, MachineResource<Context, Event, Input>>>;
122
+ readonly tasks?: Readonly<Record<string, MachineTask<Context, Event, Input>>>;
123
+ }
124
+ export interface CreateMachineOptions<Context, Input, Output> {
125
+ readonly clock?: MachineClock;
126
+ readonly errorPolicy?: 'ignore' | 'stop' | 'throw';
127
+ readonly id?: string;
128
+ readonly input?: Input;
129
+ readonly parentId?: string;
130
+ readonly persisted?: PersistedMachineSnapshot<Context, Output>;
131
+ }
132
+ export interface MachineSendResult<Context, Output> {
133
+ readonly snapshot: MachineSnapshot<Context, Output>;
134
+ readonly status: MachineEventStatus;
135
+ }
136
+ export interface MachineActorRef<Event extends MachineEvent = MachineEvent> {
137
+ readonly id: string;
138
+ send: (event: Event) => MachineSendResult<unknown, unknown>;
139
+ stop: () => void;
140
+ }
141
+ export interface MachineInstance<Context, Event extends MachineEvent, Input, Output> {
142
+ readonly id: string;
143
+ readonly model: MachineModel<Context, Event, Input, Output>;
144
+ readonly snapshot: ReadonlySignal<MachineSnapshot<Context, Output>>;
145
+ readonly started: boolean;
146
+ hasTag: (tag: string) => boolean;
147
+ matches: (path: string) => boolean;
148
+ persist: () => PersistedMachineSnapshot<Context, Output>;
149
+ send: (event: Event) => MachineSendResult<Context, Output>;
150
+ sendTo: (actorId: string, event: MachineEvent) => MachineSendResult<unknown, unknown>;
151
+ start: () => MachineInstance<Context, Event, Input, Output>;
152
+ stop: () => void;
153
+ subscribe: (listener: (snapshot: MachineSnapshot<Context, Output>) => void) => Disposer;
154
+ }
155
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./core-ugchZNqC.cjs");function y(n){const i=h.getCompiledMachine(n),c=M(i),a=i.states.filter(t=>t.kind!=="history"&&!c.has(t.id)).map(t=>t.path),o=i.states.filter(t=>t.kind==="atomic"&&t.on.size===0&&t.always.length===0&&t.after.size===0&&t.invokes.length===0).map(t=>t.path),r=[];for(const t of i.states)t.kind==="parallel"&&t.children.length===0&&r.push(`Parallel state "${t.path}" has no regions.`),t.kind==="compound"&&t.initial===void 0&&r.push(`Compound state "${t.path}" has no initial child.`);return Object.freeze({deadEnds:Object.freeze(o),inconsistencies:Object.freeze(r),reachable:Object.freeze([...c].map(t=>i.states[t].path)),unreachable:Object.freeze(a),valid:r.length===0})}function k(n,i={}){const c=h.getCompiledMachine(n),a=i.maxDepth??12,o=i.maxPaths??1e3;j(a,"maxDepth"),j(o,"maxPaths");const r=i.events??c.eventTypes.map(l=>({type:l})),t=h.getInitialSnapshot(n,i.input),s=[{events:Object.freeze([]),snapshot:t}],e=[s[0]],f=new Set([b(t)]);let u=0;for(;u<e.length&&s.length<o;){const l=e[u++];if(!(l.events.length>=a||l.snapshot.status!=="active"))for(const m of r){const p=h.transition(n,l.snapshot,m,i.bindings);if(p===l.snapshot)continue;const g=b(p);if(f.has(g))continue;f.add(g);const v=Object.freeze({events:Object.freeze([...l.events,m]),snapshot:p});if(s.push(v),e.push(v),s.length>=o)break}}return Object.freeze(s)}function w(){const n=new Map,i=new Map,c=new Map;return{guard:(a,o)=>{const r=c.get(a)??{failed:0,passed:0};o?r.passed++:r.failed++,c.set(a,r)},record:(a,o,r)=>{for(const t of r.active)n.set(t,(n.get(t)??0)+1);if(a!==r){const t=`${a.active.join("|")} --${o.type}--> ${r.active.join("|")}`;i.set(t,(i.get(t)??0)+1)}},report:()=>Object.freeze({guards:Object.freeze(Object.fromEntries([...c].map(([a,o])=>[a,Object.freeze({...o})]))),states:Object.freeze(Object.fromEntries(n)),transitions:Object.freeze(Object.fromEntries(i))}),reset:()=>{n.clear(),i.clear(),c.clear()},transition:(a,o,r,t)=>{const s=h.transition(a,o,r,t,{guard:(e,f)=>{const u=c.get(e)??{failed:0,passed:0};f?u.passed++:u.failed++,c.set(e,u)}});for(const e of s.active)n.set(e,(n.get(e)??0)+1);if(o!==s){const e=`${o.active.join("|")} --${r.type}--> ${s.active.join("|")}`;i.set(e,(i.get(e)??0)+1)}return s}}}function O(n=0){if(!Number.isFinite(n))throw new TypeError("[Raph machine] Manual clock initial time must be finite.");let i=n,c=1;const a=new Map;return{advance:s=>{if(!Number.isFinite(s)||s<0)throw new TypeError("[Raph machine] Clock advance duration must be non-negative and finite.");const e=i+s;r(e),i=e},clearTimeout:s=>{const e=a.get(s);e!==void 0&&(e.active=!1,a.delete(e.id))},now:()=>i,get pending(){return a.size},runAll:()=>{let s=0;for(;a.size!==0;){if(++s>1e5)throw new Error("[Raph machine] Manual clock exceeded 100000 timer turns.");const e=t();if(e===void 0)break;r(e.at),i=e.at}},setTimeout:(s,e)=>{if(!Number.isFinite(e)||e<0)throw new TypeError("[Raph machine] Timer delay must be non-negative and finite.");const f={active:!0,at:i+e,callback:s,id:c++};return a.set(f.id,f),f.id}};function r(s){for(;;){const e=t();if(e===void 0||e.at>s)return;i=e.at,a.delete(e.id),e.active&&(e.active=!1,e.callback())}}function t(){let s;for(const e of a.values())e.active&&(s===void 0||e.at<s.at||e.at===s.at&&e.id<s.id)&&(s=e);return s}}function M(n){const i=new Set,c=new Set,a=[n.initial];let o=0;for(;o<a.length;){const r=a[o++];if(c.has(r))continue;c.add(r);for(const e of n.ancestry[r])c.has(e)||a.push(e),i.add(e);const t=n.states[r];if(t.kind==="history"){if(t.historyFallback!==void 0)a.push(t.historyFallback);else if(t.parent!==void 0){const e=n.states[t.parent];e.initial!==void 0&&a.push(e.initial)}}t.initial!==void 0&&a.push(t.initial),t.kind==="parallel"&&a.push(...t.children.filter(e=>n.states[e].kind!=="history"));const s=[t.always,t.onDone,...t.on.values(),...t.after.values()];for(const e of t.invokes)s.push(e.onDone,e.onError);for(const e of s)for(const f of e)f.target!==void 0&&a.push(f.target)}return i}function b(n){return[n.status,n.active.join("|"),d(n.context),d(n.history),d(n.output)].join(":")}function d(n){return n===null||typeof n!="object"?JSON.stringify(n):Array.isArray(n)?`[${n.map(d).join(",")}]`:`{${Object.keys(n).sort().map(i=>`${JSON.stringify(i)}:${d(n[i])}`).join(",")}}`}function j(n,i){if(!Number.isSafeInteger(n)||n<=0)throw new TypeError(`[Raph machine] ${i} must be a positive safe integer.`)}exports.createMachineCoverage=w;exports.createManualMachineClock=O;exports.enumerateMachinePaths=k;exports.inspectMachine=y;
@@ -0,0 +1,188 @@
1
+ import { t as j, g as y, a as k } from "./core-CyilRD7s.js";
2
+ function z(n) {
3
+ const i = y(n), c = w(i), a = i.states.filter((t) => t.kind !== "history" && !c.has(t.id)).map((t) => t.path), o = i.states.filter((t) => t.kind === "atomic" && t.on.size === 0 && t.always.length === 0 && t.after.size === 0 && t.invokes.length === 0).map((t) => t.path), r = [];
4
+ for (const t of i.states)
5
+ t.kind === "parallel" && t.children.length === 0 && r.push(`Parallel state "${t.path}" has no regions.`), t.kind === "compound" && t.initial === void 0 && r.push(`Compound state "${t.path}" has no initial child.`);
6
+ return Object.freeze({
7
+ deadEnds: Object.freeze(o),
8
+ inconsistencies: Object.freeze(r),
9
+ reachable: Object.freeze([...c].map((t) => i.states[t].path)),
10
+ unreachable: Object.freeze(a),
11
+ valid: r.length === 0
12
+ });
13
+ }
14
+ function x(n, i = {}) {
15
+ const c = y(n), a = i.maxDepth ?? 12, o = i.maxPaths ?? 1e3;
16
+ b(a, "maxDepth"), b(o, "maxPaths");
17
+ const r = i.events ?? c.eventTypes.map((l) => ({ type: l })), t = k(n, i.input), s = [{
18
+ events: Object.freeze([]),
19
+ snapshot: t
20
+ }], e = [s[0]], f = /* @__PURE__ */ new Set([v(t)]);
21
+ let u = 0;
22
+ for (; u < e.length && s.length < o; ) {
23
+ const l = e[u++];
24
+ if (!(l.events.length >= a || l.snapshot.status !== "active"))
25
+ for (const p of r) {
26
+ const d = j(n, l.snapshot, p, i.bindings);
27
+ if (d === l.snapshot)
28
+ continue;
29
+ const m = v(d);
30
+ if (f.has(m))
31
+ continue;
32
+ f.add(m);
33
+ const g = Object.freeze({
34
+ events: Object.freeze([...l.events, p]),
35
+ snapshot: d
36
+ });
37
+ if (s.push(g), e.push(g), s.length >= o)
38
+ break;
39
+ }
40
+ }
41
+ return Object.freeze(s);
42
+ }
43
+ function $() {
44
+ const n = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
45
+ return {
46
+ guard: (a, o) => {
47
+ const r = c.get(a) ?? { failed: 0, passed: 0 };
48
+ o ? r.passed++ : r.failed++, c.set(a, r);
49
+ },
50
+ record: (a, o, r) => {
51
+ for (const t of r.active)
52
+ n.set(t, (n.get(t) ?? 0) + 1);
53
+ if (a !== r) {
54
+ const t = `${a.active.join("|")} --${o.type}--> ${r.active.join("|")}`;
55
+ i.set(t, (i.get(t) ?? 0) + 1);
56
+ }
57
+ },
58
+ report: () => Object.freeze({
59
+ guards: Object.freeze(Object.fromEntries(
60
+ [...c].map(([a, o]) => [a, Object.freeze({ ...o })])
61
+ )),
62
+ states: Object.freeze(Object.fromEntries(n)),
63
+ transitions: Object.freeze(Object.fromEntries(i))
64
+ }),
65
+ reset: () => {
66
+ n.clear(), i.clear(), c.clear();
67
+ },
68
+ transition: (a, o, r, t) => {
69
+ const s = j(a, o, r, t, {
70
+ guard: (e, f) => {
71
+ const u = c.get(e) ?? { failed: 0, passed: 0 };
72
+ f ? u.passed++ : u.failed++, c.set(e, u);
73
+ }
74
+ });
75
+ for (const e of s.active)
76
+ n.set(e, (n.get(e) ?? 0) + 1);
77
+ if (o !== s) {
78
+ const e = `${o.active.join("|")} --${r.type}--> ${s.active.join("|")}`;
79
+ i.set(e, (i.get(e) ?? 0) + 1);
80
+ }
81
+ return s;
82
+ }
83
+ };
84
+ }
85
+ function M(n = 0) {
86
+ if (!Number.isFinite(n))
87
+ throw new TypeError("[Raph machine] Manual clock initial time must be finite.");
88
+ let i = n, c = 1;
89
+ const a = /* @__PURE__ */ new Map();
90
+ return {
91
+ advance: (s) => {
92
+ if (!Number.isFinite(s) || s < 0)
93
+ throw new TypeError("[Raph machine] Clock advance duration must be non-negative and finite.");
94
+ const e = i + s;
95
+ r(e), i = e;
96
+ },
97
+ clearTimeout: (s) => {
98
+ const e = a.get(s);
99
+ e !== void 0 && (e.active = !1, a.delete(e.id));
100
+ },
101
+ now: () => i,
102
+ get pending() {
103
+ return a.size;
104
+ },
105
+ runAll: () => {
106
+ let s = 0;
107
+ for (; a.size !== 0; ) {
108
+ if (++s > 1e5)
109
+ throw new Error("[Raph machine] Manual clock exceeded 100000 timer turns.");
110
+ const e = t();
111
+ if (e === void 0)
112
+ break;
113
+ r(e.at), i = e.at;
114
+ }
115
+ },
116
+ setTimeout: (s, e) => {
117
+ if (!Number.isFinite(e) || e < 0)
118
+ throw new TypeError("[Raph machine] Timer delay must be non-negative and finite.");
119
+ const f = { active: !0, at: i + e, callback: s, id: c++ };
120
+ return a.set(f.id, f), f.id;
121
+ }
122
+ };
123
+ function r(s) {
124
+ for (; ; ) {
125
+ const e = t();
126
+ if (e === void 0 || e.at > s)
127
+ return;
128
+ i = e.at, a.delete(e.id), e.active && (e.active = !1, e.callback());
129
+ }
130
+ }
131
+ function t() {
132
+ let s;
133
+ for (const e of a.values())
134
+ e.active && (s === void 0 || e.at < s.at || e.at === s.at && e.id < s.id) && (s = e);
135
+ return s;
136
+ }
137
+ }
138
+ function w(n) {
139
+ const i = /* @__PURE__ */ new Set(), c = /* @__PURE__ */ new Set(), a = [n.initial];
140
+ let o = 0;
141
+ for (; o < a.length; ) {
142
+ const r = a[o++];
143
+ if (c.has(r))
144
+ continue;
145
+ c.add(r);
146
+ for (const e of n.ancestry[r])
147
+ c.has(e) || a.push(e), i.add(e);
148
+ const t = n.states[r];
149
+ if (t.kind === "history") {
150
+ if (t.historyFallback !== void 0)
151
+ a.push(t.historyFallback);
152
+ else if (t.parent !== void 0) {
153
+ const e = n.states[t.parent];
154
+ e.initial !== void 0 && a.push(e.initial);
155
+ }
156
+ }
157
+ t.initial !== void 0 && a.push(t.initial), t.kind === "parallel" && a.push(...t.children.filter((e) => n.states[e].kind !== "history"));
158
+ const s = [t.always, t.onDone, ...t.on.values(), ...t.after.values()];
159
+ for (const e of t.invokes)
160
+ s.push(e.onDone, e.onError);
161
+ for (const e of s)
162
+ for (const f of e)
163
+ f.target !== void 0 && a.push(f.target);
164
+ }
165
+ return i;
166
+ }
167
+ function v(n) {
168
+ return [
169
+ n.status,
170
+ n.active.join("|"),
171
+ h(n.context),
172
+ h(n.history),
173
+ h(n.output)
174
+ ].join(":");
175
+ }
176
+ function h(n) {
177
+ return n === null || typeof n != "object" ? JSON.stringify(n) : Array.isArray(n) ? `[${n.map(h).join(",")}]` : `{${Object.keys(n).sort().map((i) => `${JSON.stringify(i)}:${h(n[i])}`).join(",")}}`;
178
+ }
179
+ function b(n, i) {
180
+ if (!Number.isSafeInteger(n) || n <= 0)
181
+ throw new TypeError(`[Raph machine] ${i} must be a positive safe integer.`);
182
+ }
183
+ export {
184
+ $ as createMachineCoverage,
185
+ M as createManualMachineClock,
186
+ x as enumerateMachinePaths,
187
+ z as inspectMachine
188
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("./core-ugchZNqC.cjs"),J=require("./debug/runtime/ownership/RaphScope.cjs");class m extends Error{}function B(o,t){return g.assertMachineSnapshot(o,t),w(t.context,"context"),t.output!==void 0&&w(t.output,"output"),Object.freeze({active:Object.freeze([...t.active]),context:k(t.context),history:Object.freeze(Object.fromEntries(Object.entries(t.history).map(([e,r])=>[e,Object.freeze([...r])]))),modelId:o.id,...t.output===void 0?{}:{output:k(t.output)},revision:t.revision,status:t.status,version:o.version})}function L(o,t,e){const r=g.getCompiledMachine(o);try{if(typeof t!="object"||t===null||Array.isArray(t))throw new m("[Raph machine] Persisted snapshot must be an object.");if(t.modelId!==o.id)throw new m(`[Raph machine] Snapshot model "${t.modelId}" is incompatible with "${o.id}".`);if(!Number.isSafeInteger(t.version)||t.version<1)throw new m("[Raph machine] Persisted version must be a positive integer.");let i=t;for(;i.version<o.version;){const s=r.migrations.get(i.version);if(s===void 0)throw new m(`[Raph machine] Missing migration from version ${i.version} for "${o.id}".`);const n=s(i);if(n.version!==i.version+1||n.modelId!==o.id)throw new m(`[Raph machine] Migration from version ${i.version} must produce version ${i.version+1}.`);i=n}if(i.version!==o.version)throw new m(`[Raph machine] Snapshot version ${i.version} is newer than model version ${o.version}.`);return w(i.context,"context"),i.output!==void 0&&w(i.output,"output"),g.hydrateSnapshot(o,i,e)}catch(i){throw i instanceof m?i:new m(`[Raph machine] Persisted snapshot is invalid: ${i instanceof Error?i.message:String(i)}`)}}function w(o,t,e=new Set){if(o===null)return;const r=typeof o;if(r==="string"||r==="boolean")return;if(r==="number"){if(!Number.isFinite(o))throw new m(`[Raph machine] ${t} contains a non-finite number.`);return}if(r!=="object")throw new m(`[Raph machine] ${t} is not JSON-safe.`);const i=o;if(e.has(i))throw new m(`[Raph machine] ${t} contains a cycle.`);if(e.add(i),Array.isArray(o))o.forEach((s,n)=>w(s,`${t}[${n}]`,e));else{const s=Object.getPrototypeOf(o);if(s!==Object.prototype&&s!==null)throw new m(`[Raph machine] ${t} contains a non-plain object.`);for(const[n,a]of Object.entries(o))w(a,`${t}.${n}`,e)}e.delete(i)}function k(o){return JSON.parse(JSON.stringify(o))}const A=new WeakMap,R=Symbol("RaphMachineActivationCancelled"),z=Object.freeze({type:"@@init"}),Q=Object.freeze({clearTimeout:o=>clearTimeout(o),now:()=>Date.now(),setTimeout:(o,t)=>setTimeout(o,t)});class C{constructor(t,e,r,i){if(this.id=void 0,this.model=void 0,this.snapshot=void 0,this._owner=void 0,this._runtime=void 0,this._compiled=void 0,this._bindings=void 0,this._clock=void 0,this._input=void 0,this._errorPolicy=void 0,this._releaseSnapshot=E,this._writeSnapshotInBoundary=void 0,this._currentSnapshot=void 0,this._queue=void 0,this._listeners=void 0,this._stateCleanups=void 0,this._invocations=void 0,this._actors=void 0,this._releaseOwnership=E,this._releaseDebug=E,this._restored=!1,this._initialPlan=void 0,this._onError=void 0,this._queueCursor=0,this._processing=!1,this._started=!1,this._stopped=!1,this._lastIgnoredSnapshot=void 0,this._lastIgnoredResult=void 0,!(t instanceof J.RaphScope))throw new TypeError("[Raph machine] Machine owner must be a Raph Runtime scope or node.");if(t._assertAlive(),this._owner=t,this._runtime=t.runtime,this._compiled=g.getCompiledMachine(e),this.model=e,this._bindings=r,this._clock=i.clock??Q,this._input=i.input,this._errorPolicy=i.errorPolicy??"throw",this._errorPolicy!=="ignore"&&this._errorPolicy!=="stop"&&this._errorPolicy!=="throw")throw new TypeError(`[Raph machine] Unknown error policy "${String(this._errorPolicy)}".`);this._onError=i.onError;const s=(A.get(this._runtime)??0)+1;if(A.set(this._runtime,s),this.id=i.id??`${e.id}#${s}`,!this.id.trim())throw new TypeError("[Raph machine] Instance id must not be empty.");if(this._runtime._hasMachineDebug(this.id))throw new Error(`[Raph] Machine diagnostic id "${this.id}" is already registered.`);const n=i.persisted===void 0?this._runtime.untracked(()=>g.createInitialSnapshot(e,this._input,r,this._runtime._traces("machine")?this._traceHooks():void 0)):void 0,a=(n==null?void 0:n.snapshot)??L(e,i.persisted,this._input);this._initialPlan=n==null?void 0:n.plan,this._restored=i.persisted!==void 0;const c=H(this._runtime,t,a);this._releaseSnapshot=c.dispose,this._writeSnapshotInBoundary=c.writeInBoundary,this._currentSnapshot=a,this.snapshot=c.source;try{this._releaseDebug=this._runtime._registerMachineDebug({id:this.id,ownerId:t.id,...i.parentId===void 0?{}:{parentId:i.parentId},snapshot:()=>{var _;const h=this._currentSnapshot,u=Object.fromEntries(this._activeClosure(h).flatMap(f=>{const d=this._compiled.states[f].meta;return d===void 0?[]:[[this._compiled.states[f].path,d]]}));return Object.freeze({active:h.active,actors:Object.freeze([...((_=this._actors)==null?void 0:_.keys())??[]]),contextKeys:Object.freeze(N(h.context)?Object.keys(h.context):[]),id:this.id,meta:Object.freeze(u),modelId:e.id,ownerId:t.id,...i.parentId===void 0?{}:{parentId:i.parentId},revision:h.revision,status:h.status})}}),this._releaseOwnership=t.own(()=>this._dispose(!1))}catch(h){const u=[h];try{this._releaseDebug()}catch(_){u.push(_)}try{this._releaseSnapshot()}catch(_){u.push(_)}throw u.length>1?new AggregateError(u,`[Raph machine] Machine "${this.id}" construction rollback failed.`):h}}get started(){return this._started&&!this._stopped}start(){var s,n;if(this._stopped)throw new Error(`[Raph machine] Machine "${this.id}" is stopped.`);if(this._started)return this;this._owner._assertAlive();const t=this._currentSnapshot;if(t.status==="stopped")throw new Error(`[Raph machine] Persisted machine "${this.id}" is stopped.`);if(this._started=!0,this._compiled.flat)return this;const e=this._activeClosure(t).sort((a,c)=>this._compiled.states[a].depth-this._compiled.states[c].depth);let r=!1,i;this._processing=!0;try{const a=[];if(!this._restored){try{this._runOutputs(((s=this._initialPlan)==null?void 0:s.exitOutputs)??[],t,this._runtime._currentTraceCauseId())}catch(c){a.push(c)}if(this.started)try{this._runOutputs(((n=this._initialPlan)==null?void 0:n.transitionOutputs)??[],t,this._runtime._currentTraceCauseId())}catch(c){a.push(c)}if(this.started){const c=e.flatMap(h=>this._compiled.states[h].entry.map(u=>({event:z,ref:u})));try{this._runOutputs(c,t,this._runtime._currentTraceCauseId())}catch(h){a.push(h)}}}if(this.started&&t.status==="active")for(const c of e){if(!this.started)break;try{this._activateState(c,z,t)}catch(h){a.push(h)}}v(a,`[Raph machine] Machine "${this.id}" start work failed.`)}catch(a){try{this._handlePostCommitError(a,"start",this._runtime._currentTraceCauseId())}catch(c){r=!0,i=c}}finally{this._processing=!1,r?(this._queue!==void 0&&(this._queue.length=0),this._queueCursor=0):this._drainQueued()}if(r)throw i;return this}send(t){return this._enqueue(t)}sendTo(t,e){var i;const r=(i=this._actors)==null?void 0:i.get(t);if(r===void 0)throw new Error(`[Raph machine] Actor "${t}" is not active in "${this.id}".`);return r.send(e)}matches(t){return this.snapshot.get().active.some(e=>e===t||e.startsWith(`${t}.`))}hasTag(t){for(const e of this._activeClosure(this.snapshot.get()))if(this._compiled.states[e].tags.includes(t))return!0;return!1}subscribe(t){if(typeof t!="function")throw new TypeError("[Raph machine] Subscriber must be a function.");if(this._stopped)return()=>{};const e={listener:t},r=this._listeners;return this._listeners=r===void 0?[e]:[...r,e],()=>this._removeListener(e)}persist(){return B(this.model,this.snapshot.get())}stop(){let t;try{this._dispose(!0)}catch(e){(t??(t=[])).push(e)}try{this._releaseOwnership()}catch(e){(t??(t=[])).push(e)}v(t,`[Raph machine] Machine "${this.id}" stop failed.`)}_enqueue(t,e){if(!this.started)throw new Error(`[Raph machine] Machine "${this.id}" must be started before send().`);if(F(t),this._processing)return(this._queue??(this._queue=[])).push({event:t,...e===void 0?{}:{transitions:e}}),{snapshot:this._currentSnapshot,status:"queued"};this._processing=!0;let r;try{r=this._process(t,e),this._drainQueuedItems()}finally{this._queue!==void 0&&(this._queue.length=0),this._queueCursor=0,this._processing=!1}return r}_process(t,e){const r=this._currentSnapshot,i=this._runtime._nextTraceOperation("machine"),s=this._runtime._currentTraceCauseId()??i;let n;i!==void 0&&this._trace(t.type,"start",i,s,r);try{const a=e===void 0?this._compiled.eventIndexes.get(t.type):void 0;if(e===void 0&&a===void 0)return i!==void 0&&this._trace(t.type,"ignored",i,s,r),this._ignored(r);const c=i===void 0?void 0:this._traceHooks(i,s),h=this._runtime._hasActiveReactiveContext()?this._runtime.untracked(()=>this._evaluate(r,t,a,e,c)):this._evaluate(r,t,a,e,c);if(!h.changed)return i!==void 0&&this._trace(t.type,"ignored",i,s,r),this._ignored(r);this._runtime._batchReactive(()=>{this._writeSnapshotInBoundary(h.snapshot),this._currentSnapshot=h.snapshot,n=h.snapshot});let u;try{this._applyPlan(h.plan,h.snapshot,s)}catch(d){(u??(u=[])).push(d)}const _=this._listeners;if(this.started&&_!==void 0){const d=this._notifyListeners(_,h.snapshot);d!==void 0&&(u??(u=[])).push(...d)}if(this.started&&h.snapshot.status==="done")try{this._stopStateResources()}catch(d){(u??(u=[])).push(d)}u!==void 0&&v(u,`[Raph machine] Machine "${this.id}" post-commit work failed.`);const f=this.started?h.snapshot:this._currentSnapshot;return i!==void 0&&this._trace(t.type,"end",i,s,f),{snapshot:f,status:"transitioned"}}catch(a){if(n!==void 0)return this._handlePostCommitError(a,t.type,s),{snapshot:this._currentSnapshot,status:"transitioned"};if(this._traceError(t.type,a,i,s),this._onError!==void 0)return this._onError(a),this._ignored(this._currentSnapshot);if(this._errorPolicy==="stop"&&this._dispose(!0),this._errorPolicy==="ignore")return this._ignored(this._currentSnapshot);throw a}}_ignored(t){return this._lastIgnoredSnapshot!==t&&(this._lastIgnoredSnapshot=t,this._lastIgnoredResult={snapshot:t,status:"ignored"}),this._lastIgnoredResult}_evaluate(t,e,r,i,s){return i===void 0?g.runValidatedMacrostep(this.model,t,e,this._bindings,this._input,s,this._compiled,r):g.runExplicitTransitions(this.model,t,e,i,this._bindings,this._input,s)}_drainQueued(){if(this._queue===void 0||this._queue.length===0||!this.started){this._queue!==void 0&&(this._queue.length=0),this._queueCursor=0;return}this._processing=!0;try{this._drainQueuedItems()}finally{this._queue!==void 0&&(this._queue.length=0),this._queueCursor=0,this._processing=!1}}_drainQueuedItems(){const t=this._queue;if(t!==void 0)for(;this._queueCursor<t.length&&this.started;){const e=t[this._queueCursor++];this._process(e.event,e.transitions)}}_applyPlan(t,e,r){if(t.exited.length===0&&t.exitOutputs.length===0&&t.transitionOutputs.length===0&&t.transitionOutputRefs===void 0&&t.entryOutputs.length===0&&t.entered.length===0)return;const i=[];for(const s of t.exited){try{this._cleanupState(s)}catch(n){i.push(n)}if(!this.started)break}if(this.started&&t.exitOutputs.length!==0)try{this._runOutputs(t.exitOutputs,e,r)}catch(s){i.push(s)}if(this.started&&t.transitionOutputRefs!==void 0)try{this._runOutputRefs(t.transitionOutputRefs,t.event,e,r)}catch(s){i.push(s)}else if(this.started&&t.transitionOutputs.length!==0)try{this._runOutputs(t.transitionOutputs,e,r)}catch(s){i.push(s)}if(this.started&&t.entryOutputs.length!==0)try{this._runOutputs(t.entryOutputs,e,r)}catch(s){i.push(s)}if(this.started)for(const s of t.entered){if(!this.started)break;try{this._activateState(s,t.event,e)}catch(n){i.push(n)}}v(i,`[Raph machine] Machine "${this.id}" post-commit work failed.`)}_activateState(t,e,r){var a,c;if(!this.started||(a=this._stateCleanups)!=null&&a.has(t))return;const i=this._compiled.states[t];if(i.resources.length===0&&i.after.size===0&&i.invokes.length===0)return;const s=[],n=this._stateCleanups??(this._stateCleanups=new Map);n.set(t,s);try{for(const h of i.resources){const u=(c=this._bindings.resources)==null?void 0:c[h];if(u===void 0)throw new Error(`[Raph machine] Resource binding "${h}" is not defined.`);const _=new AbortController;let f;try{const d=this._runtime.untracked(()=>u({context:r.context,event:e,input:this._input,owner:this._owner,signal:_.signal,snapshot:r}));typeof d=="function"&&(f=d)}catch(d){throw _.abort(),d}if(s.push(O(()=>{_.abort(),f==null||f()})),!this.started)throw R}for(const[h,u]of i.after){const _=this._resolveDelay(h,r,e);if(!this.started)throw R;const f=this._clock.setTimeout(()=>{var d;!this.started||!((d=this._stateCleanups)!=null&&d.has(t))||this._enqueue(Object.freeze({type:`@@after:${i.path}:${h}`}),u)},_);if(s.push(O(()=>this._clock.clearTimeout(f))),!this.started)throw R}for(const h of i.invokes)if(this._startInvoke(i,h,e,r,s),!this.started)throw R}catch(h){n.get(t)===s&&n.delete(t),n.size===0&&this._stateCleanups===n&&(this._stateCleanups=void 0);const u=D(s);v(h===R?u:[h,...u],`[Raph machine] State "${i.path}" activation failed.`)}}_startInvoke(t,e,r,i,s){var M,x,T,q,I,P;const n=this._invocations??(this._invocations=new Map);if(n.has(e.id))throw new Error(`[Raph machine] Invoke id "${e.id}" is already active.`);const a=new AbortController,c={},h={controller:a,invoke:e,token:c};n.set(e.id,h);const u=()=>{var y;a.abort();const l=n.get(e.id);(l==null?void 0:l.token)===c&&n.delete(e.id),n.size===0&&this._invocations===n&&(this._invocations=void 0);const p=this._actors;p==null||p.delete(e.id),(p==null?void 0:p.size)===0&&this._actors===p&&(this._actors=void 0),(y=h.actor)==null||y.stop()};s.push(O(u));const _=typeof e.input=="function"?e.input({context:i.context,event:r,input:this._input}):e.input;if(!this.started)return;if(e.type==="machine"){const l=typeof e.src=="string"?(M=this._bindings.actors)==null?void 0:M[e.src]:e.src;if(l===void 0)throw new Error(`[Raph machine] Actor source "${String(e.src)}" is not defined.`);const p=new C(this._owner,l,{},{errorPolicy:e.onError.length===0?"throw":"ignore",id:`${this.id}/${e.id}`,input:_,onError:e.onError.length===0?void 0:$=>{var b,S;!this.started||((S=(b=this._invocations)==null?void 0:b.get(e.id))==null?void 0:S.token)!==c||this._enqueue(Object.freeze({error:$,type:`@@error.actor:${e.id}`}),e.onError)},parentId:this.id});if(!this.started||((T=(x=this._invocations)==null?void 0:x.get(e.id))==null?void 0:T.token)!==c||a.signal.aborted){p.stop();return}h.actor=p,(this._actors??(this._actors=new Map)).set(e.id,p);const y=p.subscribe($=>{var b,S;$.status==="done"&&((S=(b=this._invocations)==null?void 0:b.get(e.id))==null?void 0:S.token)===c&&this._enqueue(Object.freeze({output:$.output,type:`@@done.actor:${e.id}`}),e.onDone)});if(s.push(O(y)),p.start(),!this.started)return;const j=p.snapshot.peek();j.status==="done"&&((I=(q=this._invocations)==null?void 0:q.get(e.id))==null?void 0:I.token)===c&&this._enqueue(Object.freeze({output:j.output,type:`@@done.actor:${e.id}`}),e.onDone);return}if(typeof e.src!="string")throw new TypeError(`[Raph machine] Task invoke "${e.id}" requires a string source.`);const f=(P=this._bindings.tasks)==null?void 0:P[e.src];if(f===void 0)throw new Error(`[Raph machine] Task binding "${e.src}" is not defined.`);let d;try{d=this._runtime.untracked(()=>f({context:i.context,event:r,input:this._input,send:l=>{var y;const p=(y=this._invocations)==null?void 0:y.get(e.id);!this.started||(p==null?void 0:p.token)!==c||a.signal.aborted||this.send(l)},signal:a.signal}))}catch(l){this._completeInvoke(e,c,!1,l);return}this.started&&Promise.resolve(d).then(l=>this._completeInvoke(e,c,!0,l),l=>this._completeInvoke(e,c,!1,l))}_completeInvoke(t,e,r,i){var n;const s=(n=this._invocations)==null?void 0:n.get(t.id);!this.started||(s==null?void 0:s.token)!==e||s.controller.signal.aborted||this._enqueue(Object.freeze(r?{data:i,type:`@@done.invoke:${t.id}`}:{error:i,type:`@@error.invoke:${t.id}`}),r?t.onDone:t.onError)}_resolveDelay(t,e,r){var a;const i=Number(t),s=Number.isFinite(i)&&t.trim()!==""?i:(a=this._bindings.delays)==null?void 0:a[t];if(s===void 0)throw new Error(`[Raph machine] Delay binding "${t}" is not defined.`);const n=typeof s=="function"?s({context:e.context,event:r,input:this._input}):s;if(!Number.isFinite(n)||n<0)throw new TypeError(`[Raph machine] Delay "${t}" must resolve to a non-negative finite number.`);return n}_runOutputs(t,e,r){if(t.length===0)return;let i;for(const s of t){try{const n=this._resolveOutput(s.ref);this._runtime._runWithTraceCause(r,()=>this._runtime.untracked(()=>n({context:e.context,event:s.event,input:this._input,snapshot:e})))}catch(n){(i??(i=[])).push(n)}if(!this.started)break}i!==void 0&&v(i,`[Raph machine] Machine "${this.id}" output work failed.`)}_notifyListeners(t,e){let r;for(let i=0;i<t.length;i+=1)try{t[i].listener(e)}catch(s){(r??(r=[])).push(s)}return r}_removeListener(t){const e=this._listeners;if(e===void 0)return;const r=e.indexOf(t);r!==-1&&(this._listeners=e.length===1?void 0:[...e.slice(0,r),...e.slice(r+1)])}_runOutputRefs(t,e,r,i){let s;for(const n of t){try{const a=this._resolveOutput(n);this._runtime._runWithTraceCause(i,()=>this._runtime.untracked(()=>a({context:r.context,event:e,input:this._input,snapshot:r})))}catch(a){(s??(s=[])).push(a)}if(!this.started)break}s!==void 0&&v(s,`[Raph machine] Machine "${this.id}" output work failed.`)}_resolveOutput(t){var r;if(typeof t=="function")return t;const e=(r=this._bindings.outputs)==null?void 0:r[t];if(e===void 0)throw new Error(`[Raph machine] Output binding "${t}" is not defined.`);return e}_cleanupState(t){const e=this._stateCleanups,r=e==null?void 0:e.get(t);e===void 0||r===void 0||(e.delete(t),e.size===0&&this._stateCleanups===e&&(this._stateCleanups=void 0),v(D(r),`[Raph machine] State "${this._compiled.states[t].path}" cleanup failed.`))}_stopStateResources(){if(this._stateCleanups===void 0)return;const t=[...this._stateCleanups.keys()].sort((r,i)=>this._compiled.states[i].depth-this._compiled.states[r].depth),e=[];for(const r of t)try{this._cleanupState(r)}catch(i){e.push(i)}v(e,`[Raph machine] Machine "${this.id}" final cleanup failed.`)}_dispose(t){if(this._stopped)return;this._stopped=!0,this._started=!1;let e;try{this._stopStateResources()}catch(r){(e??(e=[])).push(r)}this._queue!==void 0&&(this._queue.length=0),this._queueCursor=0,this._listeners=void 0;try{this._releaseDebug()}catch(r){(e??(e=[])).push(r)}if(t&&!this._runtime.disposed){const r=this._currentSnapshot,i=g.stopMachineSnapshot(this.model,r);try{this._runtime._batchReactive(()=>{this._writeSnapshotInBoundary(i),this._currentSnapshot=i})}catch(s){(e??(e=[])).push(s)}}try{this._releaseSnapshot()}catch(r){(e??(e=[])).push(r)}v(e,`[Raph machine] Machine "${this.id}" stop failed.`)}_activeClosure(t){const e=new Set;for(const r of t.active){let i=this._compiled.pathToState.get(r);for(;i!==void 0;)e.add(i),i=this._compiled.states[i].parent}return[...e]}_traceHooks(t,e=this._runtime._currentTraceCauseId()??t){return{guard:(r,i,s)=>this._runtime._recordTrace({...e===void 0?{}:{causeId:e},...s===void 0?{}:{context:s},guard:i?"passed":"failed",kind:"machine",name:`${this.id}:guard:${r}`,...t===void 0?{}:{operationId:t}}),transition:r=>this._runtime._recordTrace({...e===void 0?{}:{causeId:e},details:r,kind:"machine",name:`${this.id}:transition`,...t===void 0?{}:{operationId:t}})}}_trace(t,e,r,i,s){this._runtime._recordTrace({...i===void 0?{}:{causeId:i},context:N(s.context)?s.context:void 0,details:{active:s.active,revision:s.revision},kind:"machine",name:`${this.id}:${t}`,...r===void 0?{}:{operationId:r},status:e})}_traceError(t,e,r,i){const s={message:e instanceof Error?e.message:String(e)};this._runtime._recordTrace({...i===void 0?{}:{causeId:i},details:s,kind:"machine",name:`${this.id}:${t}`,...r===void 0?{}:{operationId:r},status:"error"}),this._runtime._recordTrace({...i===void 0?{}:{causeId:i},details:s,kind:"error",name:`machine:${this.id}`,...r===void 0?{}:{operationId:r},status:"error"})}_handlePostCommitError(t,e,r){if(this._traceError(e,t,void 0,r),this._onError!==void 0){this._onError(t);return}if(this._errorPolicy==="stop"&&this._dispose(!0),this._errorPolicy==="throw")throw t}}function W(o,t,e={},r={}){return new C(o,t,e,r)}function H(o,t,e){const r=o._getWorkGraph(),i=r.createProducer(t),s=o._getReactivity()._ownedSignal(e,r.producerHooks(i));let n=s.source,a=e;const c=Object.freeze({get:()=>(o._assertSourceReadable(t),n===void 0?a:n.get()),peek:()=>(t._assertAlive(),n===void 0?a:n.peek())});return r.attachProducer(i,c),{dispose:()=>{const h=n;h!==void 0&&(a=h.peek(),n=void 0,s.dispose())},source:c,writeInBoundary:h=>{t._assertAlive(),n.set(h),a=h}}}function D(o){const t=[];for(let e=o.length-1;e>=0;e--)try{o[e]()}catch(r){t.push(r)}return t}function v(o,t){if((o==null?void 0:o.length)===1)throw o[0];if(o!==void 0&&o.length>1)throw new AggregateError(o,t)}function F(o){if(typeof o!="object"||o===null||typeof o.type!="string"||!o.type)throw new TypeError("[Raph machine] Event must contain a non-empty string type.")}function N(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function E(){}function O(o){let t=!0;return()=>{t&&(t=!1,o())}}exports.defineMachine=g.defineMachine;exports.getInitialSnapshot=g.getInitialSnapshot;exports.transition=g.transition;exports.MachinePersistenceError=m;exports.createMachine=W;exports.persistMachineSnapshot=B;exports.restoreMachineSnapshot=L;