@graphvideo/kernel 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1104 @@
1
+ //#region kernel/src/observation.ts
2
+ var e = 2, t = {
3
+ now: () => Date.now(),
4
+ monotonicNow: () => typeof performance < "u" ? performance.now() : Date.now()
5
+ }, n = { next: () => Math.random() }, r = class {
6
+ clock;
7
+ randomSource;
8
+ counter = 0;
9
+ constructor(e = t, r = n) {
10
+ this.clock = e, this.randomSource = r;
11
+ }
12
+ nextId(e) {
13
+ return `${e}-${this.clock.now()}-${++this.counter}-${Math.floor(this.randomSource.next() * 65536).toString(16).padStart(4, "0")}`;
14
+ }
15
+ }, i = class {
16
+ defaultOptions;
17
+ constructor(e = {}) {
18
+ this.defaultOptions = e;
19
+ }
20
+ encode(e, t = {}) {
21
+ let n = {
22
+ ...this.defaultOptions,
23
+ ...t
24
+ };
25
+ return this._encodeValue(e, n.maxDepth ?? 8, n.rootPath ?? [], n);
26
+ }
27
+ _encodeValue(e, t, n, r) {
28
+ if (e == null) return {
29
+ $type: "primitive",
30
+ value: e
31
+ };
32
+ let i = typeof e;
33
+ if (i === "string" || i === "number" || i === "boolean") return {
34
+ $type: "primitive",
35
+ value: e
36
+ };
37
+ if (i === "bigint" || i === "symbol" || i === "function") return {
38
+ $type: "ref",
39
+ kind: i,
40
+ summary: String(e)
41
+ };
42
+ if (t <= 0) return {
43
+ $type: "truncated",
44
+ originalType: i,
45
+ summary: "[Max Depth Reached]"
46
+ };
47
+ if (e instanceof Map) {
48
+ let i = [];
49
+ for (let [a, o] of e.entries()) i.push([this._encodeValue(a, t - 1, [...n, String(a)], r), this._encodeValue(o, t - 1, [...n, String(a)], r)]);
50
+ return {
51
+ $type: "map",
52
+ entries: i
53
+ };
54
+ }
55
+ if (e instanceof Set) return {
56
+ $type: "set",
57
+ values: Array.from(e.values()).map((e, i) => this._encodeValue(e, t - 1, [...n, String(i)], r))
58
+ };
59
+ if (Array.isArray(e)) {
60
+ let i = r.maxArrayLength ?? 100;
61
+ return {
62
+ $type: "array",
63
+ value: e.slice(0, i).map((e, i) => this._encodeValue(e, t - 1, [...n, String(i)], r))
64
+ };
65
+ }
66
+ if (e instanceof Uint8Array || typeof Buffer < "u" && Buffer.isBuffer(e)) return {
67
+ $type: "bytes",
68
+ value: typeof Buffer < "u" ? Buffer.from(e).toString("base64") : "",
69
+ byteLength: e.byteLength
70
+ };
71
+ if (i === "object") {
72
+ let i = {}, a = e, o = Object.keys(a);
73
+ for (let e of o) i[e] = r.redactedKeys?.includes(e) ? {
74
+ $type: "ref",
75
+ kind: "redacted",
76
+ summary: "[REDACTED]"
77
+ } : this._encodeValue(a[e], t - 1, [...n, e], r);
78
+ return {
79
+ $type: "object",
80
+ value: i
81
+ };
82
+ }
83
+ return {
84
+ $type: "primitive",
85
+ value: String(e)
86
+ };
87
+ }
88
+ decode(e) {
89
+ if (!e || typeof e != "object") return e;
90
+ switch (e.$type) {
91
+ case "primitive": return e.value;
92
+ case "array": return e.value.map((e) => this.decode(e));
93
+ case "map": {
94
+ let t = /* @__PURE__ */ new Map();
95
+ for (let [n, r] of e.entries) t.set(this.decode(n), this.decode(r));
96
+ return t;
97
+ }
98
+ case "set": {
99
+ let t = /* @__PURE__ */ new Set();
100
+ for (let n of e.values) t.add(this.decode(n));
101
+ return t;
102
+ }
103
+ case "object": {
104
+ let t = {};
105
+ for (let [n, r] of Object.entries(e.value)) t[n] = this.decode(r);
106
+ return t;
107
+ }
108
+ case "bytes": return typeof Buffer < "u" ? Buffer.from(e.value, "base64") : e.value;
109
+ case "ref":
110
+ case "truncated": return e.summary;
111
+ default: return e;
112
+ }
113
+ }
114
+ }, a = new i();
115
+ function o(e) {
116
+ let t = 2166136261;
117
+ for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t += (t << 1) + (t << 4) + (t << 7) + (t << 8) + (t << 24);
118
+ return `fnv1a32:${(t >>> 0).toString(16).padStart(8, "0")}`;
119
+ }
120
+ var s = class {
121
+ events = [];
122
+ append(e) {
123
+ this.events.push(e);
124
+ }
125
+ getEvents() {
126
+ return [...this.events];
127
+ }
128
+ clear() {
129
+ this.events = [];
130
+ }
131
+ }, c = class {
132
+ traceId;
133
+ runId;
134
+ idProvider;
135
+ clock;
136
+ traceStore;
137
+ sequence = 0;
138
+ events = [];
139
+ records = [];
140
+ constructor(e, t, n, r, i) {
141
+ this.traceId = e, this.runId = t, this.idProvider = n, this.clock = r, this.traceStore = i;
142
+ }
143
+ record(e) {
144
+ let t = {
145
+ schemaVersion: 2,
146
+ traceId: this.traceId,
147
+ runId: this.runId,
148
+ eventId: this.idProvider.nextId("event"),
149
+ sequence: ++this.sequence,
150
+ timestamp: this.clock.now(),
151
+ ...e
152
+ };
153
+ if (this.events.push(t), this.traceStore) try {
154
+ this.traceStore.append(t);
155
+ } catch {}
156
+ return t;
157
+ }
158
+ recordChange(e) {
159
+ this.records.push(e);
160
+ }
161
+ };
162
+ function l(e, t) {
163
+ if (typeof e != "object" || !e || e.$type !== "object") throw Error("StateDelta 只能应用到对象 State Snapshot");
164
+ let n = { ...e.value };
165
+ for (let e of t) {
166
+ let t = n[e.field];
167
+ if (JSON.stringify(t) !== JSON.stringify(e.before)) throw Error(`StateDelta 基线不匹配: ${e.field}#${e.ordinal}`);
168
+ n[e.field] = e.after;
169
+ }
170
+ return {
171
+ $type: "object",
172
+ value: n
173
+ };
174
+ }
175
+ //#endregion
176
+ //#region kernel/src/internal-access.ts
177
+ var u = Symbol("node-runtime-capability"), d = Symbol("change-context-capability"), f = class {
178
+ node;
179
+ rawInfo;
180
+ changeId;
181
+ envelope;
182
+ signal;
183
+ reads = /* @__PURE__ */ new Set();
184
+ writes = /* @__PURE__ */ new Set();
185
+ spans = [];
186
+ stateDeltas = [];
187
+ traceValues = /* @__PURE__ */ new Map();
188
+ constructor(e, t, n, r, i) {
189
+ this.node = e, this.rawInfo = t, this.changeId = n, this.envelope = r, this.signal = i;
190
+ let a = e.getState();
191
+ if (a && typeof a == "object") for (let e of Object.keys(a)) this.traceValues.set(e, this.node.encodeTraceValue(e, a[e]));
192
+ }
193
+ read(e) {
194
+ this.signal?.throwIfAborted();
195
+ let t = String(e);
196
+ return this.reads.add(t), this.node.getState()[e];
197
+ }
198
+ write(e, t) {
199
+ this.signal?.throwIfAborted();
200
+ let n = String(e);
201
+ this.writes.add(n);
202
+ let r = this.traceValues.get(n) ?? this.node.encodeTraceValue(n, void 0), i = this.node.encodeTraceValue(n, t);
203
+ this.node.commitStateFromChange(d, this.changeId, { [e]: t }, this.rawInfo), this.traceValues.set(n, i), this.stateDeltas.push({
204
+ ordinal: this.stateDeltas.length + 1,
205
+ field: n,
206
+ before: r,
207
+ after: i
208
+ });
209
+ }
210
+ patchState(e) {
211
+ this.signal?.throwIfAborted();
212
+ let t = Object.keys(e);
213
+ for (let e of t) this.writes.add(e);
214
+ let n = new Map(t.map((e) => [e, this.traceValues.get(e) ?? this.node.encodeTraceValue(e, void 0)])), r = new Map(t.map((t) => [t, this.node.encodeTraceValue(t, e[t])]));
215
+ this.node.commitStateFromChange(d, this.changeId, e, this.rawInfo);
216
+ for (let e of t) {
217
+ let t = r.get(e);
218
+ this.traceValues.set(e, t), this.stateDeltas.push({
219
+ ordinal: this.stateDeltas.length + 1,
220
+ field: e,
221
+ before: n.get(e),
222
+ after: t
223
+ });
224
+ }
225
+ }
226
+ send(e, t) {
227
+ if (this.signal?.throwIfAborted(), !t) return;
228
+ let n = this.node.runtimeId("info");
229
+ this.node._sendFromChange(d, e, t, {
230
+ infoId: n,
231
+ causedByChangeId: this.changeId,
232
+ causeInfoId: this.envelope?.infoId,
233
+ submissionId: this.envelope?.submissionId,
234
+ signal: this.signal
235
+ });
236
+ }
237
+ async effectAdapter(e, t, n = {}) {
238
+ if (this.signal?.throwIfAborted(), !this.node.isWorldNode) throw Error(`[Architecture Violation]: Pure domain node "${this.node.name}" (${this.node.id}) cannot execute physical effect! Side effects are strictly restricted to World nodes.`);
239
+ if (!e.id.trim()) throw Error("EffectAdapter id 不能为空");
240
+ let r = n.signal ?? this.signal;
241
+ r?.throwIfAborted();
242
+ let i = this.node.runtimeValueRef("effect-request", t), a = e.id, o = this.node.runtimeId("effect");
243
+ this.node.recordEffectRequested({
244
+ effectId: o,
245
+ changeId: this.changeId,
246
+ nodeId: this.node.id,
247
+ name: a,
248
+ adapterId: e.id,
249
+ requestRef: i
250
+ });
251
+ try {
252
+ let n = await e.execute(t, {
253
+ clock: {
254
+ now: () => this.node.runtimeNow(),
255
+ monotonicNow: () => this.node.runtimeMonotonicNow()
256
+ },
257
+ signal: r
258
+ });
259
+ r?.throwIfAborted();
260
+ let s = this.node.runtimeValueRef("effect-observation", n);
261
+ return this.node.recordEffectObserved({
262
+ effectId: o,
263
+ changeId: this.changeId,
264
+ nodeId: this.node.id,
265
+ name: a,
266
+ status: "succeeded",
267
+ adapterId: e.id,
268
+ requestRef: i,
269
+ observationRef: s
270
+ }), n;
271
+ } catch (t) {
272
+ throw this.node.recordEffectObserved({
273
+ effectId: o,
274
+ changeId: this.changeId,
275
+ nodeId: this.node.id,
276
+ name: a,
277
+ status: "failed",
278
+ adapterId: e.id,
279
+ requestRef: i
280
+ }), t;
281
+ }
282
+ }
283
+ async span(e, t) {
284
+ this.signal?.throwIfAborted();
285
+ let n = this.node.runtimeMonotonicNow(), r = this.node.runtimeNow();
286
+ try {
287
+ let i = await t(), a = this.node.runtimeMonotonicNow() - n;
288
+ return this.spans.push({
289
+ name: e,
290
+ durationMs: a,
291
+ timestamp: r
292
+ }), i;
293
+ } catch (t) {
294
+ let i = this.node.runtimeMonotonicNow() - n;
295
+ throw this.spans.push({
296
+ name: `${e}:failed`,
297
+ durationMs: i,
298
+ timestamp: r
299
+ }), t;
300
+ }
301
+ }
302
+ }, p = new r(t, n);
303
+ function m(e) {
304
+ if (e.reason instanceof Error) return e.reason;
305
+ if (e.reason && typeof e.reason == "object") {
306
+ let t = e.reason;
307
+ if (typeof t.message == "string") {
308
+ let e = Error(t.message);
309
+ return typeof t.name == "string" && (e.name = t.name), e;
310
+ }
311
+ }
312
+ let t = Error(typeof e.reason == "string" ? e.reason : "Graph execution canceled");
313
+ return t.name = "AbortError", t;
314
+ }
315
+ var h = class {
316
+ id;
317
+ name;
318
+ factoryKey;
319
+ isWorldNode = !1;
320
+ status = "IDLE";
321
+ executionCount = 0;
322
+ lastActiveTime = 0;
323
+ lastErrorMessage = null;
324
+ state;
325
+ regionVersions = /* @__PURE__ */ new Map();
326
+ globalVersion = 0;
327
+ mailbox = [];
328
+ drainingMailbox = !1;
329
+ activeChangeId;
330
+ disposers = /* @__PURE__ */ new Set();
331
+ abortController = new AbortController();
332
+ kernel = null;
333
+ constructor(e, t, n = {}, r) {
334
+ this.id = e, this.name = t, this.factoryKey = r || e, this.state = { ...n };
335
+ }
336
+ getState() {
337
+ return this.state;
338
+ }
339
+ getStateRegionVersions() {
340
+ return Object.fromEntries(this.regionVersions.entries());
341
+ }
342
+ getGlobalStateVersion() {
343
+ return this.globalVersion;
344
+ }
345
+ getMailboxSize() {
346
+ return this.mailbox.length;
347
+ }
348
+ getActiveChangeId() {
349
+ return this.activeChangeId;
350
+ }
351
+ _restoreStateSnapshot(e, t, n) {
352
+ if (e !== u) throw Error("[Kernel]: Invalid runtime capability");
353
+ if (t.nodeId !== this.id) throw Error(`State Snapshot 节点不匹配: 期望 ${this.id},实际 ${t.nodeId}`);
354
+ this.state = n, this.globalVersion = t.globalVersion, this.regionVersions = new Map(Object.entries(t.regionVersions || {}));
355
+ }
356
+ _mountKernel(e, t) {
357
+ if (e !== u) throw Error("[Kernel]: Invalid runtime capability");
358
+ if (this.kernel && this.kernel !== t) throw Error(`[Kernel]: Node "${this.name}" (${this.id}) 已挂载到其他 Runtime`);
359
+ this.kernel = t;
360
+ }
361
+ _unmountKernel(e, t) {
362
+ if (e !== u) throw Error("[Kernel]: Invalid runtime capability");
363
+ this.kernel === t && (this.kernel = null);
364
+ }
365
+ _enqueueMailbox(e, t, n, r = {}) {
366
+ return e === u ? new Promise((e, i) => {
367
+ this.mailbox.push({
368
+ info: t,
369
+ envelope: n,
370
+ options: r,
371
+ resolve: e,
372
+ reject: i
373
+ });
374
+ }) : Promise.reject(/* @__PURE__ */ Error("[Kernel]: Invalid runtime capability"));
375
+ }
376
+ async _drainMailbox(e) {
377
+ if (e !== u) throw Error("[Kernel]: Invalid runtime capability");
378
+ if (!this.drainingMailbox) {
379
+ this.drainingMailbox = !0;
380
+ try {
381
+ for (; this.mailbox.length > 0;) {
382
+ let e = this.mailbox.shift();
383
+ try {
384
+ if (e.options.signal?.aborted) {
385
+ e.reject(m(e.options.signal));
386
+ continue;
387
+ }
388
+ await this.runWithinChangeContext(e.info, e.envelope, e.options), e.resolve();
389
+ } catch (t) {
390
+ e.reject(t);
391
+ }
392
+ }
393
+ } finally {
394
+ this.drainingMailbox = !1;
395
+ }
396
+ }
397
+ }
398
+ async runWithinChangeContext(e, t, n = {}) {
399
+ if (this.activeChangeId) throw Error(`[Single-Flight Violation]: 节点 "${this.name}" (${this.id}) 正在运行变迁 ${this.activeChangeId},严禁并发执行 change`);
400
+ let r = this.runtimeId("change");
401
+ this.activeChangeId = r;
402
+ let i = this.globalVersion, a = t?.infoId || this.runtimeId("info-root"), o = e.type || "Info";
403
+ this.recordChangeStarted({
404
+ changeId: r,
405
+ nodeId: this.id,
406
+ causeInfoId: a,
407
+ causeInfoType: o,
408
+ stateVersionBefore: i
409
+ }), this.kernel?.beginChangeExecution?.(r);
410
+ let s = this.createChangeContext(e, r, t, n.signal), c = this.runtimeMonotonicNow(), l = this.runtimeNow();
411
+ this.status = "RUNNING";
412
+ try {
413
+ await this.change(e, s), s.stateDeltas.length > 0 && this.kernel?.traceSession?.record?.({
414
+ type: "StateDeltaCommitted",
415
+ changeId: r,
416
+ nodeId: this.id,
417
+ stateVersionAfter: this.globalVersion,
418
+ deltas: s.stateDeltas
419
+ }), this.status = "IDLE", this.executionCount++, this.lastActiveTime = this.runtimeNow();
420
+ let n = {
421
+ changeId: r,
422
+ nodeId: this.id,
423
+ causeInfoId: a,
424
+ causeInfoType: o,
425
+ causedByChangeId: t?.causedByChangeId,
426
+ stateVersionBefore: i,
427
+ stateVersionAfter: this.globalVersion,
428
+ reads: Array.from(s.reads),
429
+ writes: Array.from(s.writes),
430
+ stateDeltas: s.stateDeltas,
431
+ spans: s.spans,
432
+ durationMs: this.runtimeMonotonicNow() - c,
433
+ timestamp: l
434
+ };
435
+ this.recordChange(n);
436
+ } catch (e) {
437
+ let u = n.signal?.aborted || e?.name === "AbortError" || typeof e?.message == "string" && e.message.toLowerCase().includes("abort");
438
+ this.status = u ? "ABORTED" : "ERROR", this.lastErrorMessage = e?.message || String(e);
439
+ let d = {
440
+ changeId: r,
441
+ nodeId: this.id,
442
+ causeInfoId: a,
443
+ causeInfoType: o,
444
+ causedByChangeId: t?.causedByChangeId,
445
+ stateVersionBefore: i,
446
+ stateVersionAfter: this.globalVersion,
447
+ reads: Array.from(s.reads),
448
+ writes: Array.from(s.writes),
449
+ stateDeltas: s.stateDeltas,
450
+ spans: s.spans,
451
+ durationMs: this.runtimeMonotonicNow() - c,
452
+ timestamp: l,
453
+ error: this.lastErrorMessage || void 0
454
+ };
455
+ throw this.recordChange(d), e;
456
+ } finally {
457
+ this.kernel?.endChangeExecution?.(r), this.activeChangeId = void 0;
458
+ }
459
+ }
460
+ createChangeContext(e, t, n, r) {
461
+ return new f(this, e, t, n, r);
462
+ }
463
+ get stateVersion() {
464
+ return this.globalVersion;
465
+ }
466
+ commitStateFromChange(e, t, n, r) {
467
+ if (e !== d) throw Error(`[State Write Violation]: Node ${this.id} 拒绝非 ChangeContext 写入`);
468
+ if (!this.activeChangeId || this.activeChangeId !== t) throw Error(`[State Write Violation]: Node ${this.id} 只能在 change context 内提交 State`);
469
+ let i = r?.type || "change";
470
+ this.regionVersions.set(i, (this.regionVersions.get(i) || 0) + 1), this.globalVersion += 1, this.state = {
471
+ ...this.state,
472
+ ...n
473
+ };
474
+ }
475
+ _sendFromChange(e, t, n, r) {
476
+ if (e !== d) throw Error(`[Send Violation]: Node ${this.id} 拒绝非 ChangeContext 发信`);
477
+ if (!this.activeChangeId || r?.causedByChangeId !== this.activeChangeId) throw Error(`[Send Violation]: Node ${this.id} 只能通过当前 change context 发信`);
478
+ if (!this.kernel) throw Error(`[Kernel]: Node "${this.name}" (${this.id}) 尚未挂载,无法发信`);
479
+ this.kernel._deliverSendFromChange(this, t, n, r);
480
+ }
481
+ change(e, t) {}
482
+ runtimeNow() {
483
+ return this.kernel?.now?.() ?? t.now();
484
+ }
485
+ runtimeMonotonicNow() {
486
+ return this.kernel?.monotonicNow?.() ?? t.monotonicNow();
487
+ }
488
+ runtimeId(e) {
489
+ return this.kernel?.nextId?.(e) ?? p.nextId(e);
490
+ }
491
+ encodeTraceValue(e, t) {
492
+ return this.kernel?.encodeTraceValue?.(this.id, e, t) ?? {
493
+ $type: "primitive",
494
+ value: t ?? null
495
+ };
496
+ }
497
+ runtimeValueRef(e, t) {
498
+ return this.kernel?.recordValueRef?.(e, t) ?? `${e}:${this.runtimeId("effect")}`;
499
+ }
500
+ recordChangeStarted(e) {
501
+ this.kernel?.recordChangeStarted?.(e);
502
+ }
503
+ recordChange(e) {
504
+ this.kernel?.recordChange?.(e);
505
+ }
506
+ recordEffectRequested(e) {
507
+ this.kernel?.recordEffectRequested?.(e);
508
+ }
509
+ recordEffectObserved(e) {
510
+ this.kernel?.recordEffectObserved?.(e);
511
+ }
512
+ onMount() {}
513
+ onUnmount() {}
514
+ registerDisposer(e) {
515
+ this.disposers.add(e);
516
+ }
517
+ async dispose() {
518
+ this.abort();
519
+ for (let e of this.disposers) try {
520
+ await e();
521
+ } catch (e) {
522
+ console.error(`[Node ${this.id}] Disposer failed:`, e);
523
+ }
524
+ this.disposers.clear(), this.onUnmount(), this.status = "IDLE";
525
+ }
526
+ abort(e) {
527
+ this.abortController.abort(e), this.status = "ABORTED", this.lastErrorMessage = e || "Execution aborted", this.abortController = new AbortController();
528
+ }
529
+ reset() {
530
+ this.status = "IDLE", this.lastErrorMessage = null, this.mailbox.length = 0;
531
+ }
532
+ }, g = class extends h {
533
+ isWorldNode = !0;
534
+ };
535
+ //#endregion
536
+ //#region kernel/src/scheduler.ts
537
+ function _(e) {
538
+ if (e.reason instanceof Error) return e.reason;
539
+ let t = Error(typeof e.reason == "string" ? e.reason : "等待 Kernel 静止已取消");
540
+ return t.name = "AbortError", t;
541
+ }
542
+ function v(e) {
543
+ return {
544
+ pendingDeliveries: e.pendingDeliveryCount,
545
+ activeChanges: e.activeChangeIds.size,
546
+ scheduledGraphMicrotasks: e.scheduledGraphMicrotaskCount,
547
+ isQuiescent: e.pendingDeliveryCount === 0 && e.activeChangeIds.size === 0 && e.scheduledGraphMicrotaskCount === 0
548
+ };
549
+ }
550
+ function y(e, t) {
551
+ return e.schedulerListeners.add(t), () => {
552
+ e.schedulerListeners.delete(t);
553
+ };
554
+ }
555
+ function b(e) {
556
+ let t = v(e);
557
+ for (let n of e.schedulerListeners) try {
558
+ n(t);
559
+ } catch {}
560
+ }
561
+ function x(e, t) {
562
+ return e.scheduledGraphMicrotaskCount += 1, b(e), new Promise((n, r) => {
563
+ queueMicrotask(async () => {
564
+ try {
565
+ n(await t());
566
+ } catch (e) {
567
+ r(e);
568
+ } finally {
569
+ --e.scheduledGraphMicrotaskCount, b(e);
570
+ }
571
+ });
572
+ });
573
+ }
574
+ async function S(e, t = {}) {
575
+ for (;;) {
576
+ if (t.signal?.aborted) throw _(t.signal);
577
+ let n = v(e);
578
+ if (n.isQuiescent) return n;
579
+ await new Promise((n, r) => {
580
+ let i = () => void 0, a = y(e, (e) => {
581
+ e.isQuiescent && (i(), n());
582
+ }), o = () => {
583
+ i(), r(_(t.signal));
584
+ };
585
+ i = () => {
586
+ a(), t.signal?.removeEventListener("abort", o);
587
+ }, t.signal?.addEventListener("abort", o, { once: !0 }), t.signal?.aborted && o();
588
+ });
589
+ }
590
+ }
591
+ //#endregion
592
+ //#region kernel/src/delivery.ts
593
+ function C(e, t, n, r, i) {
594
+ e.ensureInitialStateSnapshot();
595
+ let a = typeof r == "string" ? e.nodes.get(r) : r;
596
+ if (!a) {
597
+ console.warn(`[Kernel]: Target node "${String(r)}" not found for send from "${t.name}" (${t.id})`);
598
+ return;
599
+ }
600
+ let o = e.now(), s = i?.infoId ?? e.nextId("info");
601
+ e.logicalClock++;
602
+ let c = {
603
+ infoId: s,
604
+ senderNodeId: t.id,
605
+ targetNodeId: a.id,
606
+ causedByChangeId: i?.causedByChangeId,
607
+ causeInfoId: i?.causeInfoId,
608
+ submissionId: i?.submissionId,
609
+ sequence: e.logicalClock,
610
+ timestamp: o,
611
+ payload: n
612
+ };
613
+ e.envelopes.length >= 1e3 && e.envelopes.shift(), e.envelopes.push(c), c.causedByChangeId && e.traceSession.record({
614
+ type: "InfoEmitted",
615
+ envelope: c
616
+ }), e.traceSession.record({
617
+ type: "InfoDelivered",
618
+ envelope: c
619
+ }), T(e, a, n, c, { signal: i?.signal });
620
+ }
621
+ function w(e, t, n, r = {}) {
622
+ r.signal?.throwIfAborted(), e.ensureInitialStateSnapshot();
623
+ let i = e.now(), a = {
624
+ infoId: e.nextId("info-root"),
625
+ senderNodeId: "external-root",
626
+ targetNodeId: t.id,
627
+ submissionId: r.submissionId,
628
+ sequence: ++e.logicalClock,
629
+ timestamp: i,
630
+ payload: n
631
+ };
632
+ e.envelopes.length >= 1e3 && e.envelopes.shift(), e.envelopes.push(a), e.traceSession.record({
633
+ type: "InfoDelivered",
634
+ envelope: a
635
+ }), T(e, t, n, a, { signal: r?.signal });
636
+ }
637
+ function T(e, t, n, r, i) {
638
+ e.trackSubmissionDeliveryEnqueued(r.submissionId), e.pendingDeliveryCount += 1, e.publishSchedulerState(), t._enqueueMailbox(u, n, r, i).then(() => D(e, r.submissionId), (t) => D(e, r.submissionId, t)), E(e, t);
639
+ }
640
+ function E(e, t) {
641
+ e.scheduledMailboxNodeIds.has(t.id) || (e.scheduledMailboxNodeIds.add(t.id), queueMicrotask(async () => {
642
+ try {
643
+ await t._drainMailbox(u);
644
+ } finally {
645
+ e.scheduledMailboxNodeIds.delete(t.id), t.getMailboxSize() > 0 && E(e, t);
646
+ }
647
+ }));
648
+ }
649
+ function D(e, t, n) {
650
+ e.pendingDeliveryCount = Math.max(0, e.pendingDeliveryCount - 1), e.trackSubmissionDeliverySettled(t, n), e.publishSchedulerState();
651
+ }
652
+ //#endregion
653
+ //#region kernel/src/snapshot.ts
654
+ function O(e, t = "manual", n) {
655
+ let r = (n ? n.map((t) => {
656
+ let n = e.nodes.get(t);
657
+ if (!n) throw Error(`State Snapshot 找不到 Node: ${t}`);
658
+ return n;
659
+ }) : [...e.nodes.values()]).sort((e, t) => e.id.localeCompare(t.id)), i = {
660
+ snapshotId: e.nextId("snapshot"),
661
+ traceId: e.traceSession.traceId,
662
+ runId: e.traceSession.runId,
663
+ capturedAt: e.now(),
664
+ reason: t,
665
+ nodes: r.map((t) => ({
666
+ nodeId: t.id,
667
+ factoryKey: t.factoryKey,
668
+ state: e.valueCodec.encode(t.getState(), {
669
+ ...e.valueCodecOptions,
670
+ rootPath: [t.id, "$state"]
671
+ }),
672
+ globalVersion: t.getGlobalStateVersion(),
673
+ regionVersions: { ...t.getStateRegionVersions() }
674
+ }))
675
+ };
676
+ return e.traceSession.record({
677
+ type: "StateSnapshotCaptured",
678
+ snapshot: i
679
+ }), i;
680
+ }
681
+ function k(e, t) {
682
+ let n = t.nodes.map((t) => {
683
+ let n = e.nodes.get(t.nodeId);
684
+ if (!n) throw Error(`State Snapshot 找不到已挂载 Node: ${t.nodeId}`);
685
+ if (n.factoryKey !== t.factoryKey) throw Error(`State Snapshot 工厂不匹配: ${n.id} 期望 ${n.factoryKey},实际 ${t.factoryKey}`);
686
+ if (!Number.isSafeInteger(t.globalVersion) || t.globalVersion < 0) throw Error(`State Snapshot globalVersion 非法: ${n.id}`);
687
+ for (let [e, r] of Object.entries(t.regionVersions)) if (!e || !Number.isSafeInteger(r) || r < 0) throw Error(`State Snapshot regionVersion 非法: ${n.id}.${e}`);
688
+ return {
689
+ node: n,
690
+ nodeSnapshot: t,
691
+ state: e.valueCodec.decode(t.state)
692
+ };
693
+ });
694
+ for (let e of n) e.node._restoreStateSnapshot(u, e.nodeSnapshot, e.state);
695
+ e.traceSession.record({
696
+ type: "StateSnapshotRestored",
697
+ snapshotId: t.snapshotId,
698
+ nodeIds: n.map(({ node: e }) => e.id)
699
+ });
700
+ }
701
+ //#endregion
702
+ //#region kernel/src/runtime.ts
703
+ function A(e) {
704
+ return e instanceof Error ? e : Error(String(e));
705
+ }
706
+ var j = class {
707
+ nodes = /* @__PURE__ */ new Map();
708
+ envelopes = [];
709
+ probes = [];
710
+ clock;
711
+ idProvider;
712
+ randomSource;
713
+ valueCodec;
714
+ valueCodecOptions;
715
+ traceStore;
716
+ traceSession;
717
+ logicalClock = 0;
718
+ pendingDeliveryCount = 0;
719
+ activeChangeIds = /* @__PURE__ */ new Set();
720
+ scheduledGraphMicrotaskCount = 0;
721
+ schedulerListeners = /* @__PURE__ */ new Set();
722
+ scheduledMailboxNodeIds = /* @__PURE__ */ new Set();
723
+ projectionListeners = /* @__PURE__ */ new Set();
724
+ projectionRevision = 0;
725
+ submissions = /* @__PURE__ */ new Map();
726
+ captureInitialStateSnapshot = !0;
727
+ initialStateSnapshotCaptured = !1;
728
+ isDisposed = !1;
729
+ constructor(e = {}) {
730
+ this.clock = e.clock ?? t, this.randomSource = e.randomSource ?? n, this.idProvider = e.idProvider ?? new r(this.clock, this.randomSource), this.valueCodec = e.valueCodec ?? a, this.valueCodecOptions = e.valueCodecOptions ?? {}, this.traceStore = e.traceStore, this.captureInitialStateSnapshot = e.stateSnapshots?.captureInitial ?? !0;
731
+ let i = this.idProvider.nextId("trace"), o = this.idProvider.nextId("run");
732
+ this.traceSession = new c(i, o, this.idProvider, this.clock, this.traceStore), this.traceSession.record({
733
+ type: "TraceStarted",
734
+ runtimeVersion: "2.0.0-in-process"
735
+ });
736
+ }
737
+ now() {
738
+ return this.clock.now();
739
+ }
740
+ monotonicNow() {
741
+ return this.clock.monotonicNow();
742
+ }
743
+ nextId(e) {
744
+ return this.idProvider.nextId(e);
745
+ }
746
+ mount(...e) {
747
+ for (let t of e) {
748
+ if (!t.id) throw Error("挂载节点必须具有非空 id");
749
+ if (this.nodes.has(t.id)) throw Error(`不能挂载重复的 Node ID: ${t.id}`);
750
+ this.nodes.set(t.id, t), t._mountKernel(u, this), t.onMount();
751
+ }
752
+ return this.traceSession.record({
753
+ type: "GraphMounted",
754
+ nodeIds: e.map((e) => e.id),
755
+ nodeFactories: Object.fromEntries(e.map((e) => [e.id, e.factoryKey]))
756
+ }), this;
757
+ }
758
+ unmount(...e) {
759
+ for (let t of e) {
760
+ let e = this.nodes.get(t);
761
+ e && (e._unmountKernel(u, this), e.onUnmount(), this.nodes.delete(t));
762
+ }
763
+ return this;
764
+ }
765
+ getNode(e) {
766
+ return this.nodes.get(e);
767
+ }
768
+ getNodes() {
769
+ return Array.from(this.nodes.values());
770
+ }
771
+ _deliverSendFromChange(e, t, n, r) {
772
+ C(this, e, t, n, r);
773
+ }
774
+ injectRootInfo(e, t, n = {}) {
775
+ let r = n.submissionId ?? this.nextId("submission"), i = this.createSubmission(r, n.signal);
776
+ try {
777
+ w(this, e, t, {
778
+ signal: i.controller.signal,
779
+ submissionId: r
780
+ });
781
+ } catch (e) {
782
+ throw i.failure = A(e), this.settleSubmissionIfComplete(i), e;
783
+ }
784
+ return r;
785
+ }
786
+ async inject(e) {
787
+ let t = this.getNode(e.targetNodeId);
788
+ if (!t) return {
789
+ status: "rejected",
790
+ submissionId: e.submissionId,
791
+ reason: `Target node not found: ${e.targetNodeId}`
792
+ };
793
+ try {
794
+ this.injectRootInfo(t, e.info, {
795
+ signal: e.signal,
796
+ submissionId: e.submissionId
797
+ });
798
+ } catch (t) {
799
+ return {
800
+ status: "rejected",
801
+ submissionId: e.submissionId,
802
+ reason: A(t).message
803
+ };
804
+ }
805
+ return {
806
+ status: "accepted",
807
+ submissionId: e.submissionId
808
+ };
809
+ }
810
+ cancel(e) {
811
+ let t = this.submissions.get(e);
812
+ if (!t || t.settled || t.cancelled) return !1;
813
+ t.cancelled = !0;
814
+ let n = /* @__PURE__ */ Error(`Submission cancelled: ${e}`);
815
+ return n.name = "AbortError", t.controller.abort(n), this.settleSubmissionIfComplete(t), !0;
816
+ }
817
+ async waitForSubmission(e) {
818
+ let t = this.submissions.get(e);
819
+ if (!t) throw Error(`Submission not found: ${e}`);
820
+ let n = await t.completion;
821
+ if (n.status !== "completed") throw n.error;
822
+ }
823
+ trackSubmissionDeliveryEnqueued(e) {
824
+ if (!e) return;
825
+ let t = this.submissions.get(e);
826
+ if (!t || t.settled) throw Error(`Submission delivery has no active scope: ${e}`);
827
+ t.pendingDeliveries += 1;
828
+ }
829
+ trackSubmissionDeliverySettled(e, t) {
830
+ if (!e) return;
831
+ let n = this.submissions.get(e);
832
+ n && !n.settled && (t && !n.failure && (n.failure = A(t), n.controller.abort(n.failure)), n.pendingDeliveries = Math.max(0, n.pendingDeliveries - 1), this.settleSubmissionIfComplete(n));
833
+ }
834
+ snapshot() {
835
+ return this.captureStateSnapshot("manual");
836
+ }
837
+ publishSchedulerState() {
838
+ b(this), this.publishProjection();
839
+ }
840
+ readProjection() {
841
+ let e = [];
842
+ for (let t of this.nodes.values()) e.push({
843
+ nodeId: t.id,
844
+ state: this.valueCodec.encode(t.getState(), {
845
+ ...this.valueCodecOptions,
846
+ maxDepth: Infinity,
847
+ maxArrayLength: Infinity,
848
+ rootPath: [t.id, "$projection"]
849
+ }),
850
+ version: t.getGlobalStateVersion(),
851
+ status: t.status
852
+ });
853
+ let t = this.getSchedulerSnapshot();
854
+ return {
855
+ revision: this.projectionRevision,
856
+ scheduler: {
857
+ pendingDeliveries: t.pendingDeliveries,
858
+ activeChanges: t.activeChanges,
859
+ scheduledGraphMicrotasks: t.scheduledGraphMicrotasks
860
+ },
861
+ nodes: e
862
+ };
863
+ }
864
+ subscribeProjection(e) {
865
+ return this.projectionListeners.add(e), () => {
866
+ this.projectionListeners.delete(e);
867
+ };
868
+ }
869
+ publishProjection() {
870
+ this.projectionRevision++;
871
+ let e = this.readProjection();
872
+ for (let t of this.projectionListeners) try {
873
+ t(e);
874
+ } catch (e) {
875
+ console.error("[KernelRuntime] Projection listener error:", e);
876
+ }
877
+ }
878
+ getSchedulerSnapshot() {
879
+ return v(this);
880
+ }
881
+ subscribeScheduler(e) {
882
+ return y(this, e);
883
+ }
884
+ scheduleMicrotask(e) {
885
+ return x(this, e);
886
+ }
887
+ waitForQuiescence(e = {}) {
888
+ return S(this, e);
889
+ }
890
+ captureStateSnapshot(e = "manual", t) {
891
+ let n = O(this, e, t);
892
+ return e === "initial" && (this.initialStateSnapshotCaptured = !0), n;
893
+ }
894
+ restoreStateSnapshot(e) {
895
+ k(this, e);
896
+ }
897
+ ensureInitialStateSnapshot() {
898
+ this.captureInitialStateSnapshot && !this.initialStateSnapshotCaptured && this.captureStateSnapshot("initial");
899
+ }
900
+ encodeTraceValue(e, t, n) {
901
+ return this.valueCodec.encode(n, {
902
+ ...this.valueCodecOptions,
903
+ rootPath: [e, t]
904
+ });
905
+ }
906
+ recordValueRef(e, t) {
907
+ let n = this.valueCodec.encode(t, {
908
+ ...this.valueCodecOptions,
909
+ maxBytes: 1024,
910
+ rootPath: ["ref", e]
911
+ });
912
+ return `${e}:${o(JSON.stringify(n))}`;
913
+ }
914
+ beginChangeExecution(e) {
915
+ this.activeChangeIds.add(e), this.publishSchedulerState();
916
+ }
917
+ endChangeExecution(e) {
918
+ this.activeChangeIds.delete(e), this.publishSchedulerState();
919
+ }
920
+ recordChangeStarted(e) {
921
+ this.traceSession.record({
922
+ type: "ChangeStarted",
923
+ ...e
924
+ });
925
+ }
926
+ get causalRecords() {
927
+ return this.traceSession.records;
928
+ }
929
+ get events() {
930
+ return this.traceSession.events;
931
+ }
932
+ recordChange(e) {
933
+ this.traceSession.recordChange(e), this.traceSession.record({
934
+ type: "ChangeCompleted",
935
+ record: e
936
+ });
937
+ for (let t of this.probes) try {
938
+ t.onChangeRecord?.(e);
939
+ } catch {}
940
+ }
941
+ recordEffectRequested(e) {
942
+ this.traceSession.record({
943
+ type: "EffectRequested",
944
+ ...e
945
+ });
946
+ }
947
+ recordEffectObserved(e) {
948
+ this.traceSession.record({
949
+ type: "EffectObserved",
950
+ ...e
951
+ });
952
+ }
953
+ addProbe(e) {
954
+ return this.probes.push(e), this;
955
+ }
956
+ removeProbe(e) {
957
+ let t = this.probes.indexOf(e);
958
+ return t !== -1 && this.probes.splice(t, 1), this;
959
+ }
960
+ async dispose() {
961
+ if (!this.isDisposed) {
962
+ this.isDisposed = !0;
963
+ for (let e of this.submissions.values()) e.settled || this.cancel(e.id);
964
+ for (let e of this.nodes.values()) try {
965
+ await e.dispose();
966
+ } catch (t) {
967
+ console.error(`[KernelRuntime]: Failed to dispose node ${e.id}:`, t);
968
+ }
969
+ this.nodes.clear(), this.schedulerListeners.clear(), this.projectionListeners.clear(), this.probes.length = 0, this.traceSession.record({
970
+ type: "TraceCompleted",
971
+ status: "completed"
972
+ });
973
+ }
974
+ }
975
+ createSubmission(e, t) {
976
+ if (!e.trim()) throw Error("submissionId 不能为空");
977
+ if (this.submissions.has(e)) throw Error(`submissionId 已存在: ${e}`);
978
+ let n = new AbortController(), r, i = new Promise((e) => {
979
+ r = e;
980
+ }), a = () => {
981
+ let r = this.submissions.get(e);
982
+ r && !r.settled && (r.cancelled = !0, n.abort(t?.reason), this.settleSubmissionIfComplete(r));
983
+ };
984
+ t?.addEventListener("abort", a, { once: !0 });
985
+ let o = {
986
+ id: e,
987
+ controller: n,
988
+ completion: i,
989
+ resolve: r,
990
+ removeExternalAbort: () => t?.removeEventListener("abort", a),
991
+ pendingDeliveries: 0,
992
+ settled: !1,
993
+ cancelled: !1
994
+ };
995
+ return this.submissions.set(e, o), t?.aborted && a(), o;
996
+ }
997
+ settleSubmissionIfComplete(e) {
998
+ if (!(e.settled || e.pendingDeliveries > 0)) {
999
+ if (e.settled = !0, e.removeExternalAbort(), e.cancelled) {
1000
+ let t = A(e.controller.signal.reason ?? "Submission cancelled");
1001
+ t.name = "AbortError", e.resolve({
1002
+ status: "cancelled",
1003
+ error: t
1004
+ });
1005
+ } else e.failure ? e.resolve({
1006
+ status: "failed",
1007
+ error: e.failure
1008
+ }) : e.resolve({ status: "completed" });
1009
+ if (this.submissions.size > 1e3) {
1010
+ let e = Array.from(this.submissions.values()).find((e) => e.settled);
1011
+ e && this.submissions.delete(e.id);
1012
+ }
1013
+ }
1014
+ }
1015
+ };
1016
+ function M(e) {
1017
+ return new j(e);
1018
+ }
1019
+ //#endregion
1020
+ //#region kernel/src/effect-harness.ts
1021
+ var N = 65536, P = 2048, F = class {
1022
+ clock;
1023
+ valueCodec;
1024
+ valueCodecOptions;
1025
+ maxFixtureBytes;
1026
+ maxRawSummaryCharacters;
1027
+ constructor(e = {}) {
1028
+ if (this.clock = e.clock ?? t, this.valueCodec = e.valueCodec ?? new i(), this.valueCodecOptions = e.valueCodecOptions ?? {}, this.maxFixtureBytes = e.maxFixtureBytes ?? N, this.maxRawSummaryCharacters = e.maxRawSummaryCharacters ?? P, !Number.isSafeInteger(this.maxFixtureBytes) || this.maxFixtureBytes <= 0) throw Error("EffectHarness maxFixtureBytes 必须是正安全整数");
1029
+ if (!Number.isSafeInteger(this.maxRawSummaryCharacters) || this.maxRawSummaryCharacters <= 0) throw Error("EffectHarness maxRawSummaryCharacters 必须是正安全整数");
1030
+ }
1031
+ async run(e, t, n = {}) {
1032
+ if (!e.id.trim()) throw Error("EffectAdapter id 不能为空");
1033
+ if (t.schemaVersion !== 1) throw Error(`EffectFixture schemaVersion 不支持: ${t.schemaVersion}`);
1034
+ if (!t.fixtureId.trim()) throw Error("EffectFixture fixtureId 不能为空");
1035
+ if (n.signal?.aborted) throw n.signal.reason ?? /* @__PURE__ */ Error("Effect 已取消");
1036
+ let r = this.valueCodec.encode(t.request, {
1037
+ ...this.valueCodecOptions,
1038
+ maxBytes: Math.min(this.valueCodecOptions.maxBytes ?? this.maxFixtureBytes, this.maxFixtureBytes),
1039
+ rootPath: ["fixture", "request"]
1040
+ }), i = [], a = [], o = this.clock.now(), s = this.clock.monotonicNow(), c = `${t.fixtureId}/${e.id}`, l = {
1041
+ clock: this.clock,
1042
+ signal: n.signal,
1043
+ recordTransport: (e) => {
1044
+ i.push(this.valueCodec.encode(e, {
1045
+ ...this.valueCodecOptions,
1046
+ maxBytes: this.maxFixtureBytes,
1047
+ rootPath: ["transportMetadata", String(i.length)]
1048
+ }));
1049
+ },
1050
+ recordRawSummary: (e) => {
1051
+ if (!e.kind.trim()) throw Error("Effect raw summary kind 不能为空");
1052
+ if (e.text.length > this.maxRawSummaryCharacters) throw Error(`Effect raw summary 超过 ${this.maxRawSummaryCharacters} 字符限制`);
1053
+ a.push({
1054
+ kind: e.kind,
1055
+ text: e.text,
1056
+ redacted: e.redacted ?? !1
1057
+ });
1058
+ }
1059
+ };
1060
+ try {
1061
+ let n = await e.execute(t.request, l), u = this.valueCodec.encode(n, {
1062
+ ...this.valueCodecOptions,
1063
+ maxBytes: this.maxFixtureBytes,
1064
+ rootPath: ["fixture", "observation"]
1065
+ }), d = this.clock.now(), f = this.clock.monotonicNow() - s;
1066
+ return {
1067
+ observation: n,
1068
+ record: {
1069
+ schemaVersion: 1,
1070
+ fixtureId: t.fixtureId,
1071
+ executionId: c,
1072
+ adapterId: e.id,
1073
+ request: r,
1074
+ observation: u,
1075
+ transportMetadata: i,
1076
+ rawSummaries: a,
1077
+ startedAt: o,
1078
+ completedAt: d,
1079
+ durationMs: f,
1080
+ status: "succeeded",
1081
+ ...t.expectedObservation === void 0 ? {} : { expectedMatched: JSON.stringify(u) === JSON.stringify(t.expectedObservation) }
1082
+ }
1083
+ };
1084
+ } catch (n) {
1085
+ let l = this.clock.now();
1086
+ return { record: {
1087
+ schemaVersion: 1,
1088
+ fixtureId: t.fixtureId,
1089
+ executionId: c,
1090
+ adapterId: e.id,
1091
+ request: r,
1092
+ transportMetadata: i,
1093
+ rawSummaries: a,
1094
+ startedAt: o,
1095
+ completedAt: l,
1096
+ durationMs: this.clock.monotonicNow() - s,
1097
+ status: "failed",
1098
+ error: n instanceof Error ? n.message : String(n)
1099
+ } };
1100
+ }
1101
+ }
1102
+ };
1103
+ //#endregion
1104
+ export { f as ChangeContextImpl, F as EffectHarness, j as KernelRuntime, s as MemoryTraceStore, h as Node, r as TimeRandomIdProvider, c as TraceSession, i as ValueCodec, g as WorldNode, l as applyStateDeltas, v as computeSchedulerSnapshot, M as createKernelRuntime, a as defaultValueCodec, o as fnv1a32, b as publishSchedulerStateHelper, x as scheduleGraphMicrotaskHelper, _ as schedulerCancellationError, y as subscribeSchedulerHelper, t as systemClock, n as systemRandomSource, e as traceSchemaVersion, S as waitForQuiescenceHelper };