@graphrefly/graphrefly 0.15.0 → 0.16.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.
Files changed (71) hide show
  1. package/dist/{chunk-2ZICUAUJ.js → chunk-26A4E7J7.js} +10 -12
  2. package/dist/chunk-26A4E7J7.js.map +1 -0
  3. package/dist/{chunk-CRACCCJY.js → chunk-3BLRREFM.js} +29 -5
  4. package/dist/chunk-3BLRREFM.js.map +1 -0
  5. package/dist/{chunk-XQ4UMAU7.js → chunk-ITDVOCFO.js} +2 -2
  6. package/dist/{chunk-YW6LFCFS.js → chunk-LKP7IWRV.js} +3 -3
  7. package/dist/{chunk-4APC3AFN.js → chunk-RLVFZDCE.js} +22 -49
  8. package/dist/chunk-RLVFZDCE.js.map +1 -0
  9. package/dist/{chunk-GKRKDYNT.js → chunk-RZSQ7P2C.js} +3 -3
  10. package/dist/{chunk-ZHTHUX5D.js → chunk-SHRJH2DN.js} +3 -3
  11. package/dist/{chunk-H243FWYP.js → chunk-VZY2B2LU.js} +1 -1
  12. package/dist/{chunk-H243FWYP.js.map → chunk-VZY2B2LU.js.map} +1 -1
  13. package/dist/{chunk-QVYZD65U.js → chunk-YX263TXI.js} +10 -38
  14. package/dist/chunk-YX263TXI.js.map +1 -0
  15. package/dist/compat/nestjs/index.cjs +38 -41
  16. package/dist/compat/nestjs/index.cjs.map +1 -1
  17. package/dist/compat/nestjs/index.d.cts +4 -4
  18. package/dist/compat/nestjs/index.d.ts +4 -4
  19. package/dist/compat/nestjs/index.js +7 -7
  20. package/dist/core/index.cjs.map +1 -1
  21. package/dist/core/index.d.cts +2 -2
  22. package/dist/core/index.d.ts +2 -2
  23. package/dist/core/index.js +3 -3
  24. package/dist/extra/index.cjs +27 -78
  25. package/dist/extra/index.cjs.map +1 -1
  26. package/dist/extra/index.d.cts +4 -4
  27. package/dist/extra/index.d.ts +4 -4
  28. package/dist/extra/index.js +3 -3
  29. package/dist/graph/index.cjs +26 -2
  30. package/dist/graph/index.cjs.map +1 -1
  31. package/dist/graph/index.d.cts +3 -3
  32. package/dist/graph/index.d.ts +3 -3
  33. package/dist/graph/index.js +4 -4
  34. package/dist/{graph-BXIK5Dq5.d.ts → graph-Dc-P9BVm.d.ts} +15 -3
  35. package/dist/{graph-BhADtuFU.d.cts → graph-fCsaaVIa.d.cts} +15 -3
  36. package/dist/{index-DSp5R3Xq.d.ts → index-BBVBYPxr.d.cts} +4 -4
  37. package/dist/{index-BkToATim.d.ts → index-BR19vQME.d.ts} +1 -1
  38. package/dist/{index-BNB0KjKe.d.ts → index-BmoUvOGN.d.ts} +1 -1
  39. package/dist/{index-DBhLjWSV.d.cts → index-ClaKZFPl.d.cts} +100 -31
  40. package/dist/{index-Dqemj9q0.d.cts → index-DWq0P9T6.d.ts} +4 -4
  41. package/dist/{index-Wa8jXne6.d.cts → index-Db27z6Ki.d.cts} +1 -1
  42. package/dist/{index-fYObbpUw.d.ts → index-DhXznWyH.d.ts} +2 -2
  43. package/dist/{index-DANO9Gg7.d.cts → index-DlGMf_Qe.d.cts} +2 -2
  44. package/dist/{index-CKyYg4IP.d.ts → index-N704txAA.d.ts} +100 -31
  45. package/dist/{index-DKIyo4Bq.d.cts → index-YlOH1Gw6.d.cts} +1 -1
  46. package/dist/index.cjs +109 -186
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +22 -35
  49. package/dist/index.d.ts +22 -35
  50. package/dist/index.js +63 -111
  51. package/dist/index.js.map +1 -1
  52. package/dist/{meta-CrZUQAJ6.d.cts → meta-BV4pj9ML.d.cts} +6 -0
  53. package/dist/{meta-CrZUQAJ6.d.ts → meta-BV4pj9ML.d.ts} +6 -0
  54. package/dist/observable-Cz-AWhwR.d.cts +42 -0
  55. package/dist/observable-DCqlwGyl.d.ts +42 -0
  56. package/dist/patterns/reactive-layout/index.cjs +26 -2
  57. package/dist/patterns/reactive-layout/index.cjs.map +1 -1
  58. package/dist/patterns/reactive-layout/index.d.cts +3 -3
  59. package/dist/patterns/reactive-layout/index.d.ts +3 -3
  60. package/dist/patterns/reactive-layout/index.js +4 -4
  61. package/package.json +1 -1
  62. package/dist/chunk-2ZICUAUJ.js.map +0 -1
  63. package/dist/chunk-4APC3AFN.js.map +0 -1
  64. package/dist/chunk-CRACCCJY.js.map +0 -1
  65. package/dist/chunk-QVYZD65U.js.map +0 -1
  66. package/dist/reactive-log-ChbpUrY2.d.cts +0 -137
  67. package/dist/reactive-log-DV--7BWd.d.ts +0 -137
  68. /package/dist/{chunk-XQ4UMAU7.js.map → chunk-ITDVOCFO.js.map} +0 -0
  69. /package/dist/{chunk-YW6LFCFS.js.map → chunk-LKP7IWRV.js.map} +0 -0
  70. /package/dist/{chunk-GKRKDYNT.js.map → chunk-RZSQ7P2C.js.map} +0 -0
  71. /package/dist/{chunk-ZHTHUX5D.js.map → chunk-SHRJH2DN.js.map} +0 -0
@@ -11,7 +11,7 @@ import {
11
11
  producer,
12
12
  state,
13
13
  wallClockNs
14
- } from "./chunk-H243FWYP.js";
14
+ } from "./chunk-VZY2B2LU.js";
15
15
 
16
16
  // src/extra/observable.ts
17
17
  import { Observable } from "rxjs";
@@ -617,25 +617,7 @@ function createWatermarkController(sendUp, opts) {
617
617
  };
618
618
  }
619
619
 
620
- // src/extra/reactive-base.ts
621
- function snapshotEqualsVersion(a, b) {
622
- if (typeof a !== "object" || a == null || typeof b !== "object" || b == null) {
623
- return Object.is(a, b);
624
- }
625
- if (!("version" in a) || !("version" in b)) return Object.is(a, b);
626
- return a.version === b.version;
627
- }
628
- function bumpVersion(current, nextValue, v0) {
629
- if (v0 != null) {
630
- return { version: current.version + 1, value: nextValue, v0 };
631
- }
632
- return { version: current.version + 1, value: nextValue };
633
- }
634
-
635
620
  // src/extra/reactive-log.ts
636
- function emptySnapshot() {
637
- return { version: 0, value: { entries: [] } };
638
- }
639
621
  function keepaliveDerived(n) {
640
622
  return n.subscribe(() => {
641
623
  });
@@ -649,22 +631,16 @@ function reactiveLog(initial, options = {}) {
649
631
  if (maxSize !== void 0 && buf.length > maxSize) {
650
632
  buf.splice(0, buf.length - maxSize);
651
633
  }
652
- let current = buf.length > 0 ? { version: 1, value: { entries: [...buf] } } : emptySnapshot();
653
- const entries = state(current, {
634
+ const entries = state(buf.length > 0 ? [...buf] : [], {
654
635
  name,
655
636
  describeKind: "state",
656
- equals: snapshotEqualsVersion
637
+ equals: (a, b) => a === b
657
638
  });
658
639
  function pushSnapshot() {
659
- const ev = entries.v;
660
- current = bumpVersion(
661
- current,
662
- { entries: [...buf] },
663
- ev ? { id: ev.id, version: ev.version } : void 0
664
- );
640
+ const snapshot = [...buf];
665
641
  batch(() => {
666
642
  entries.down([[DIRTY]]);
667
- entries.down([[DATA, current]]);
643
+ entries.down([[DATA, snapshot]]);
668
644
  });
669
645
  }
670
646
  function trimBuf() {
@@ -707,13 +683,12 @@ function reactiveLog(initial, options = {}) {
707
683
  if (n < 0) {
708
684
  throw new RangeError("n must be >= 0");
709
685
  }
710
- const snap = entries.get();
711
- const e = snap.value.entries;
686
+ const e = entries.get();
712
687
  const init = n === 0 ? [] : e.slice(Math.max(0, e.length - n));
713
688
  const out = derived(
714
689
  [entries],
715
690
  ([s]) => {
716
- const list = s.value.entries;
691
+ const list = s;
717
692
  return n === 0 ? [] : list.slice(Math.max(0, list.length - n));
718
693
  },
719
694
  { initial: init, describeKind: "derived" }
@@ -728,13 +703,12 @@ function logSlice(log, start, stop) {
728
703
  if (start < 0) {
729
704
  throw new RangeError("start must be >= 0");
730
705
  }
731
- const snap = log.entries.get();
732
- const e = snap.value.entries;
706
+ const e = log.entries.get();
733
707
  const init = stop === void 0 ? e.slice(start) : e.slice(start, stop);
734
708
  const out = derived(
735
709
  [log.entries],
736
710
  ([s]) => {
737
- const list = s.value.entries;
711
+ const list = s;
738
712
  return stop === void 0 ? list.slice(start) : list.slice(start, stop);
739
713
  },
740
714
  { initial: init, describeKind: "derived" }
@@ -773,9 +747,7 @@ export {
773
747
  firstValueFrom,
774
748
  shareReplay,
775
749
  createWatermarkController,
776
- snapshotEqualsVersion,
777
- bumpVersion,
778
750
  reactiveLog,
779
751
  logSlice
780
752
  };
781
- //# sourceMappingURL=chunk-QVYZD65U.js.map
753
+ //# sourceMappingURL=chunk-YX263TXI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extra/observable.ts","../src/extra/cron.ts","../src/extra/sources.ts","../src/extra/backpressure.ts","../src/extra/reactive-log.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// RxJS bridge — reactive interop between GraphReFly nodes and RxJS Observables.\n// ---------------------------------------------------------------------------\n// Generic utilities for bridging GraphReFly's message protocol to RxJS\n// Observables. Works anywhere RxJS is available (NestJS, Angular, standalone).\n//\n// Usage:\n// import { toObservable, observeNode$ } from '@graphrefly/graphrefly-ts/extra';\n// const values$ = toObservable(myNode); // Observable<T>\n// const msgs$ = toMessages$(myNode); // Observable<Messages>\n// const node$ = observeNode$(graph, \"path\"); // Observable<T> via graph.observe\n// const all$ = observeGraph$(graph); // Observable<{ path, messages }>\n// ---------------------------------------------------------------------------\n\nimport { Observable } from \"rxjs\";\nimport { COMPLETE, DATA, ERROR, type Messages } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport type { Graph, GraphObserveAll, GraphObserveOne, ObserveOptions } from \"../graph/graph.js\";\n\n/**\n * Bridge a `Node<T>` to an RxJS `Observable<T>`.\n *\n * Emits the node's value on each `DATA` message. Maps `ERROR` to\n * `subscriber.error()` and `COMPLETE` to `subscriber.complete()`.\n * Protocol-internal signals (DIRTY, RESOLVED, PAUSE, etc.) are skipped.\n *\n * Unsubscribing the Observable unsubscribes the node.\n */\nexport function toObservable<T>(node: Node<T>): Observable<T> {\n\treturn new Observable<T>((subscriber) => {\n\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsubscriber.next(m[1] as T);\n\t\t\t\t} else if (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Bridge a `Node<T>` to an `Observable<Messages>` — raw message batches.\n *\n * Each emission is a full `[[Type, Data?], ...]` batch. The Observable\n * terminates on ERROR or COMPLETE (the terminal batch is still emitted\n * as the final `next()` before the Observable signal).\n */\nexport function toMessages$<T>(node: Node<T>): Observable<Messages> {\n\treturn new Observable<Messages>((subscriber) => {\n\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\tif (subscriber.closed) return;\n\t\t\tsubscriber.next(msgs);\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Observe a single node in a `Graph` as an `Observable<T>`.\n *\n * Equivalent to `toObservable(graph.resolve(path))` but routes through\n * `graph.observe()` so actor guards are respected when provided.\n */\nexport function observeNode$<T>(\n\tgraph: Graph,\n\tpath: string,\n\toptions?: ObserveOptions,\n): Observable<T> {\n\treturn new Observable<T>((subscriber) => {\n\t\tconst handle: GraphObserveOne = graph.observe(path, options);\n\t\tconst unsub = handle.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsubscriber.next(m[1] as T);\n\t\t\t\t} else if (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Observe all nodes in a `Graph` as an `Observable<{ path, messages }>`.\n *\n * Each emission carries the qualified node path and the raw message batch.\n * The Observable never self-completes (graphs are long-lived); dispose by\n * unsubscribing.\n */\nexport function observeGraph$(\n\tgraph: Graph,\n\toptions?: ObserveOptions,\n): Observable<{ path: string; messages: Messages }> {\n\treturn new Observable((subscriber) => {\n\t\tconst handle: GraphObserveAll = graph.observe(options);\n\t\tconst unsub = handle.subscribe((nodePath, messages) => {\n\t\t\tif (subscriber.closed) return;\n\t\t\tsubscriber.next({ path: nodePath, messages });\n\t\t});\n\t\treturn unsub;\n\t});\n}\n","/**\n * Minimal 5-field cron parser and matcher (minute hour day-of-month month day-of-week).\n * Ported from callbag-recharge `extra/cron.ts` for `fromCron` (roadmap §2.3).\n */\nexport interface CronSchedule {\n\tminutes: Set<number>;\n\thours: Set<number>;\n\tdaysOfMonth: Set<number>;\n\tmonths: Set<number>;\n\tdaysOfWeek: Set<number>;\n}\n\nfunction parseField(field: string, min: number, max: number): Set<number> {\n\tconst result = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tconst [range, stepStr] = part.split(\"/\");\n\t\tconst step = stepStr ? Number.parseInt(stepStr, 10) : 1;\n\t\tif (Number.isNaN(step) || step < 1) throw new Error(`Invalid cron step: ${part}`);\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b] = range.split(\"-\");\n\t\t\tstart = Number.parseInt(a, 10);\n\t\t\tend = Number.parseInt(b, 10);\n\t\t} else {\n\t\t\tstart = Number.parseInt(range, 10);\n\t\t\tend = start;\n\t\t}\n\t\tif (Number.isNaN(start) || Number.isNaN(end)) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (start < min || end > max)\n\t\t\tthrow new Error(`Cron field out of range: ${field} (${min}-${max})`);\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) result.add(i);\n\t}\n\treturn result;\n}\n\n/**\n * Parses a standard 5-field cron expression into a {@link CronSchedule}.\n *\n * Supports `*`, ranges (`1-5`), steps (`*\\/5`, `0-30/10`), and comma-separated\n * lists. Fields are: minute (0–59), hour (0–23), day-of-month (1–31),\n * month (1–12), day-of-week (0–6, Sunday = 0).\n *\n * @param expr - Five-field whitespace-separated cron string (e.g. `\"0 9 * * 1-5\"`).\n * @returns Parsed {@link CronSchedule} with one `Set<number>` per field.\n * @throws Error when the expression does not have exactly 5 fields, contains\n * out-of-range values, or uses an invalid step.\n *\n * @example\n * ```ts\n * import { parseCron } from \"@graphrefly/graphrefly-ts\";\n *\n * const sched = parseCron(\"0 9 * * 1-5\"); // weekdays at 09:00\n * sched.hours; // Set { 9 }\n * sched.daysOfWeek; // Set { 1, 2, 3, 4, 5 }\n * ```\n */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5) throw new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\treturn {\n\t\tminutes: parseField(parts[0], 0, 59),\n\t\thours: parseField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseField(parts[2], 1, 31),\n\t\tmonths: parseField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseField(parts[4], 0, 6),\n\t};\n}\n\n/**\n * Returns `true` if `date` satisfies every field of `schedule`.\n *\n * @param schedule - Parsed schedule from {@link parseCron}.\n * @param date - Moment to test (local time via `getMinutes`, `getHours`, etc.).\n * @returns `true` when all five cron fields match the given date.\n *\n * @example\n * ```ts\n * import { parseCron, matchesCron } from \"@graphrefly/graphrefly-ts\";\n *\n * const sched = parseCron(\"30 8 * * 1\"); // Mondays at 08:30\n * const monday = new Date(\"2026-03-30T08:30:00\"); // a Monday\n * matchesCron(sched, monday); // true\n * ```\n */\nexport function matchesCron(schedule: CronSchedule, date: Date): boolean {\n\treturn (\n\t\tschedule.minutes.has(date.getMinutes()) &&\n\t\tschedule.hours.has(date.getHours()) &&\n\t\tschedule.daysOfMonth.has(date.getDate()) &&\n\t\tschedule.months.has(date.getMonth() + 1) &&\n\t\tschedule.daysOfWeek.has(date.getDay())\n\t);\n}\n","/**\n * Core reactive sources, sinks, and utilities (roadmap §2.3).\n *\n * Each API returns a {@link Node} built with {@link node}, {@link producer},\n * {@link derived}, or {@link effect} — no second protocol.\n *\n * Protocol/system/ingest adapters (fromHTTP, fromWebSocket, fromKafka, etc.)\n * live in {@link ./adapters.ts}.\n */\n\nimport { existsSync, watch } from \"node:fs\";\nimport { resolve as resolvePath } from \"node:path\";\nimport { wallClockNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, ERROR, type Message } from \"../core/messages.js\";\nimport { type Node, type NodeOptions, type NodeSink, node } from \"../core/node.js\";\nimport { producer } from \"../core/sugar.js\";\nimport { type CronSchedule, matchesCron, parseCron } from \"./cron.js\";\n\ntype ExtraOpts = Omit<NodeOptions, \"describeKind\">;\n\nfunction sourceOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"producer\", ...opts };\n}\n\n/** @internal kept for toArray which is an operator, not a producer */\nfunction operatorOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"operator\", ...opts };\n}\n\n/** Options for {@link fromTimer} / {@link fromPromise} / {@link fromAsyncIter}. */\nexport type AsyncSourceOpts = ExtraOpts & { signal?: AbortSignal };\n\n/**\n * Values accepted by {@link fromAny}.\n *\n * @category extra\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Options for {@link fromCron}. */\nexport type FromCronOptions = ExtraOpts & {\n\t/** Polling interval in ms. Default `60_000`. */\n\ttickMs?: number;\n\t/** Output format: `\"timestamp_ns\"` (default) emits wall-clock nanoseconds; `\"date\"` emits a `Date` object. */\n\toutput?: \"timestamp_ns\" | \"date\";\n};\n\n/** DOM-style event target (browser or `node:events`). */\nexport type EventTargetLike = {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n};\n\nexport type FSEventType = \"change\" | \"rename\" | \"create\" | \"delete\";\nexport type FSEvent = {\n\ttype: FSEventType;\n\tpath: string;\n\troot: string;\n\trelative_path: string;\n\tsrc_path?: string;\n\tdest_path?: string;\n\ttimestamp_ns: number;\n};\n\nexport type FromFSWatchOptions = ExtraOpts & {\n\trecursive?: boolean;\n\tdebounce?: number;\n\tinclude?: string[];\n\texclude?: string[];\n};\n\n/** @internal Shared with adapters.ts for glob matching in fromFSWatch / fromGitHook. */\nexport function escapeRegexChar(ch: string): string {\n\treturn /[\\\\^$+?.()|[\\]{}]/.test(ch) ? `\\\\${ch}` : ch;\n}\n\n/** @internal */\nexport function globToRegExp(glob: string): RegExp {\n\tlet out = \"^\";\n\tfor (let i = 0; i < glob.length; i += 1) {\n\t\tconst ch = glob[i];\n\t\tif (ch === \"*\") {\n\t\t\tconst next = glob[i + 1];\n\t\t\tif (next === \"*\") {\n\t\t\t\tout += \".*\";\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tout += \"[^/]*\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tout += escapeRegexChar(ch);\n\t}\n\tout += \"$\";\n\treturn new RegExp(out);\n}\n\n/** @internal */\nexport function matchesAnyPattern(path: string, patterns: RegExp[]): boolean {\n\tfor (const pattern of patterns) {\n\t\tif (pattern.test(path)) return true;\n\t}\n\treturn false;\n}\n\nfunction wrapSubscribeHook<T>(inner: Node<T>, before: (sink: NodeSink) => void): Node<T> {\n\tconst wrapper = node<T>([inner], ([val]) => val as T, {\n\t\tdescribeKind: \"operator\",\n\t\tinitial: inner.get(),\n\t});\n\tconst origSubscribe = wrapper.subscribe.bind(wrapper);\n\t(wrapper as { subscribe: typeof wrapper.subscribe }).subscribe = (sink, hints) => {\n\t\tbefore(sink);\n\t\treturn origSubscribe(sink, hints);\n\t};\n\treturn wrapper;\n}\n\n/**\n * Builds a timer-driven source: one-shot (first tick then `COMPLETE`) or periodic (`0`, `1`, `2`, …).\n *\n * @param ms - Milliseconds before the first emission.\n * @param opts - Producer options plus optional `period` for repeating ticks and optional `signal` (`AbortSignal`) to cancel with `ERROR`.\n * @returns `Node<number>` — tick counter from `0`; teardown clears timers.\n *\n * @example\n * ```ts\n * import { fromTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * fromTimer(250, { period: 1_000 });\n * ```\n *\n * @category extra\n */\nexport function fromTimer(ms: number, opts?: AsyncSourceOpts & { period?: number }): Node<number> {\n\tconst { signal, period, ...rest } = opts ?? {};\n\treturn producer<number>((_d, a) => {\n\t\tlet done = false;\n\t\tlet count = 0;\n\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tdone = true;\n\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst finish = () => {\n\t\t\tif (done) return;\n\t\t\ta.emit(count++);\n\t\t\tif (period != null) {\n\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\tif (done) return;\n\t\t\t\t\ta.emit(count++);\n\t\t\t\t}, period);\n\t\t\t} else {\n\t\t\t\tdone = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tqueueMicrotask(() => a.down([[COMPLETE]]));\n\t\t\t}\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (done) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tt = setTimeout(finish, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\treturn cleanup;\n\t}, sourceOpts(rest));\n}\n\n/**\n * Polls on an interval; when the current minute matches a 5-field cron expression, emits once (see {@link parseCron}).\n *\n * @param expr - Cron string (`min hour dom month dow`).\n * @param opts - Producer options plus `tickMs` (default `60_000`) and `output` (`timestamp_ns` default, or `date` for `Date` values).\n * @returns `Node<number>` (nanosecond timestamp) or `Node<Date>` when `output: \"date\"`.\n *\n * @example\n * ```ts\n * import { fromCron } from \"@graphrefly/graphrefly-ts\";\n *\n * fromCron(\"0 9 * * 1\");\n * ```\n *\n * @category extra\n */\nexport function fromCron(expr: string, opts?: FromCronOptions & { output: \"date\" }): Node<Date>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number | Date> {\n\tconst schedule: CronSchedule = parseCron(expr);\n\tconst { tickMs: tickOpt, output, ...rest } = opts ?? {};\n\tconst tickMs = tickOpt ?? 60_000;\n\tconst emitDate = output === \"date\";\n\treturn producer<number | Date>(\n\t\t(_d, a) => {\n\t\t\tlet lastFiredKey = -1;\n\t\t\tconst check = () => {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key =\n\t\t\t\t\tnow.getFullYear() * 100_000_000 +\n\t\t\t\t\t(now.getMonth() + 1) * 1_000_000 +\n\t\t\t\t\tnow.getDate() * 10_000 +\n\t\t\t\t\tnow.getHours() * 100 +\n\t\t\t\t\tnow.getMinutes();\n\t\t\t\tif (key !== lastFiredKey && matchesCron(schedule, now)) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\ta.emit(emitDate ? now : wallClockNs());\n\t\t\t\t}\n\t\t\t};\n\t\t\tcheck();\n\t\t\tconst id = setInterval(check, tickMs);\n\t\t\treturn () => clearInterval(id);\n\t\t},\n\t\t{ ...sourceOpts(rest), name: rest.name ?? `cron:${expr}` },\n\t);\n}\n\n/**\n * Wraps a DOM-style `addEventListener` target; each event becomes a `DATA` emission.\n *\n * @param target - Object with `addEventListener` / `removeEventListener`.\n * @param type - Event name (e.g. `\"click\"`).\n * @param opts - Producer options plus listener options (`capture`, `passive`, `once`).\n * @returns `Node<T>` — event payloads; teardown removes the listener.\n *\n * @example\n * ```ts\n * import { fromEvent } from \"@graphrefly/graphrefly-ts\";\n *\n * fromEvent(document.body, \"click\");\n * ```\n *\n * @category extra\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts?: ExtraOpts & { capture?: boolean; passive?: boolean; once?: boolean },\n): Node<T> {\n\tconst { capture, passive, once, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tconst handler = (e: unknown) => {\n\t\t\ta.emit(e as T);\n\t\t};\n\t\tconst options = { capture, passive, once };\n\t\ttarget.addEventListener(type, handler, options);\n\t\treturn () => target.removeEventListener(type, handler, options);\n\t}, sourceOpts(rest));\n}\n\n/**\n * Watches filesystem paths and emits debounced change events.\n *\n * Uses `fs.watch` only (no polling fallback). Teardown closes all watchers.\n *\n * @category extra\n */\nexport function fromFSWatch(paths: string | string[], opts?: FromFSWatchOptions): Node<FSEvent> {\n\tconst list = Array.isArray(paths) ? paths : [paths];\n\tif (list.length === 0) {\n\t\tthrow new RangeError(\"fromFSWatch expects at least one path\");\n\t}\n\tconst { recursive = true, debounce = 100, include, exclude, ...rest } = opts ?? {};\n\tconst includePatterns = include?.map(globToRegExp) ?? [];\n\tconst excludePatterns = (exclude ?? [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\"]).map(\n\t\tglobToRegExp,\n\t);\n\treturn producer<FSEvent>((_d, a) => {\n\t\tconst pending = new Map<string, FSEvent>();\n\t\tconst watchers: ReturnType<typeof watch>[] = [];\n\t\tlet stopped = false;\n\t\tlet terminalEmitted = false;\n\t\tlet generation = 0;\n\t\tconst closeWatchers = () => {\n\t\t\tfor (const watcher of watchers.splice(0)) watcher.close();\n\t\t};\n\t\tconst emitError = (err: unknown) => {\n\t\t\tif (terminalEmitted) return;\n\t\t\tterminalEmitted = true;\n\t\t\tstopped = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tpending.clear();\n\t\t\tcloseWatchers();\n\t\t\ta.down([[ERROR, err]]);\n\t\t};\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst flush = (token: number) => {\n\t\t\ttimer = undefined;\n\t\t\tif (stopped || terminalEmitted) return;\n\t\t\tif (pending.size === 0) return;\n\t\t\tconst batchMessages: Message[] = [];\n\t\t\tfor (const evt of pending.values()) batchMessages.push([DATA, evt]);\n\t\t\tpending.clear();\n\t\t\tif (stopped || terminalEmitted || token !== generation) return;\n\t\t\ta.down(batchMessages);\n\t\t};\n\t\ttry {\n\t\t\tfor (const basePath of list) {\n\t\t\t\tconst watcher = watch(\n\t\t\t\t\tbasePath,\n\t\t\t\t\t{ recursive },\n\t\t\t\t\t(eventType: \"rename\" | \"change\", fileName: string | Buffer | null) => {\n\t\t\t\t\t\tif (stopped || terminalEmitted) return;\n\t\t\t\t\t\tif (fileName == null) return;\n\t\t\t\t\t\tconst rel = String(fileName).replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst abs = resolvePath(basePath, String(fileName));\n\t\t\t\t\t\tconst normalized = abs.replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst root = resolvePath(basePath).replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst relForMatch = rel.startsWith(\"./\") ? rel.slice(2) : rel;\n\t\t\t\t\t\tconst included =\n\t\t\t\t\t\t\tincludePatterns.length === 0 ||\n\t\t\t\t\t\t\tmatchesAnyPattern(normalized, includePatterns) ||\n\t\t\t\t\t\t\tmatchesAnyPattern(relForMatch, includePatterns);\n\t\t\t\t\t\tif (!included) return;\n\t\t\t\t\t\tconst excluded =\n\t\t\t\t\t\t\tmatchesAnyPattern(normalized, excludePatterns) ||\n\t\t\t\t\t\t\tmatchesAnyPattern(relForMatch, excludePatterns);\n\t\t\t\t\t\tif (excluded) return;\n\t\t\t\t\t\tlet kind: FSEventType = \"change\";\n\t\t\t\t\t\tif (eventType === \"rename\") {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tkind = existsSync(normalized) ? \"create\" : \"delete\";\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tkind = \"rename\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpending.set(normalized, {\n\t\t\t\t\t\t\ttype: kind,\n\t\t\t\t\t\t\tpath: normalized,\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\trelative_path: relForMatch,\n\t\t\t\t\t\t\ttimestamp_ns: wallClockNs(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\t\t\tconst token = generation;\n\t\t\t\t\t\ttimer = setTimeout(() => flush(token), debounce);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\twatcher.on(\"error\", (err) => emitError(err));\n\t\t\t\twatchers.push(watcher);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\temitError(err);\n\t\t}\n\t\treturn () => {\n\t\t\tstopped = true;\n\t\t\tgeneration += 1;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tcloseWatchers();\n\t\t\tpending.clear();\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Drains a synchronous iterable; each item is `DATA`, then `COMPLETE`, or `ERROR` if iteration throws.\n *\n * @param iterable - Values to emit in order.\n * @param opts - Optional producer options.\n * @returns `Node<T>` — one emission per element.\n *\n * @example\n * ```ts\n * import { fromIter } from \"@graphrefly/graphrefly-ts\";\n *\n * fromIter([1, 2, 3]);\n * ```\n *\n * @category extra\n */\nexport function fromIter<T>(iterable: Iterable<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\tlet cancelled = false;\n\t\ttry {\n\t\t\tfor (const x of iterable) {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ta.emit(x);\n\t\t\t}\n\t\t\tif (!cancelled) a.down([[COMPLETE]]);\n\t\t} catch (e) {\n\t\t\tif (!cancelled) a.down([[ERROR, e]]);\n\t\t}\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t}, sourceOpts(opts));\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\n/**\n * Lifts a Promise (or thenable) to a single-value stream: one `DATA` then `COMPLETE`, or `ERROR` on rejection.\n *\n * @param p - Promise to await.\n * @param opts - Producer options plus optional `signal` for abort → `ERROR` with reason.\n * @returns `Node<T>` — settles once.\n *\n * @example\n * ```ts\n * import { fromPromise } from \"@graphrefly/graphrefly-ts\";\n *\n * fromPromise(Promise.resolve(42));\n * ```\n *\n * @category extra\n */\nexport function fromPromise<T>(p: Promise<T> | PromiseLike<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tlet settled = false;\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid Promise.resolve(p).then(\n\t\t\t(v) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.emit(v as T);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t},\n\t\t\t(e) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.down([[ERROR, e]]);\n\t\t\t},\n\t\t);\n\t\treturn () => {\n\t\t\tsettled = true;\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Reads an async iterable; each `next()` value becomes `DATA`; `COMPLETE` when done; `ERROR` on failure.\n *\n * @param iterable - Async source (`for await` shape).\n * @param opts - Producer options plus optional `signal` to abort the pump.\n * @returns `Node<T>` — async pull stream.\n *\n * @example\n * ```ts\n * import { fromAsyncIter } from \"@graphrefly/graphrefly-ts\";\n *\n * async function* gen() {\n * yield 1;\n * }\n * fromAsyncIter(gen());\n * ```\n *\n * @category extra\n */\nexport function fromAsyncIter<T>(iterable: AsyncIterable<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal: outerSignal, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tconst ac = new AbortController();\n\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\tif (outerSignal?.aborted) {\n\t\t\tac.abort(outerSignal.reason);\n\t\t} else {\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t}\n\t\tconst signal = outerSignal ?? ac.signal;\n\t\tlet cancelled = false;\n\t\tconst it = iterable[Symbol.asyncIterator]();\n\t\tconst pump = (): void => {\n\t\t\tif (cancelled || signal.aborted) return;\n\t\t\tvoid Promise.resolve(it.next()).then(\n\t\t\t\t(step) => {\n\t\t\t\t\tif (cancelled || signal.aborted) return;\n\t\t\t\t\tif (step.done) {\n\t\t\t\t\t\tqueueMicrotask(() => a.down([[COMPLETE]]));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ta.emit(step.value as T);\n\t\t\t\t\tqueueMicrotask(pump);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (!cancelled && !signal.aborted) a.down([[ERROR, e]]);\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\t\tqueueMicrotask(pump);\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\tac.abort();\n\t\t\tvoid Promise.resolve(it.return?.()).catch(() => undefined);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof (x as Node).subscribe === \"function\" &&\n\t\ttypeof (x as Node).get === \"function\"\n\t);\n}\n\n/**\n * Coerces a value to a `Node` by shape: existing `Node` passthrough, thenable → {@link fromPromise},\n * async iterable → {@link fromAsyncIter}, sync iterable → {@link fromIter}, else scalar → {@link of}.\n *\n * @param input - Any value to wrap.\n * @param opts - Passed through when a Promise/async path is chosen.\n * @returns `Node` of the inferred element type.\n *\n * @example\n * ```ts\n * import { fromAny, state } from \"@graphrefly/graphrefly-ts\";\n *\n * fromAny(state(1));\n * fromAny(Promise.resolve(2));\n * ```\n *\n * @category extra\n */\nexport function fromAny<T>(input: NodeInput<T>, opts?: AsyncSourceOpts): Node<T> {\n\tif (isNode(input)) {\n\t\treturn input as Node<T>;\n\t}\n\tif (isThenable(input)) {\n\t\treturn fromPromise(input as PromiseLike<T>, opts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as { [Symbol.asyncIterator]?: unknown; [Symbol.iterator]?: unknown };\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn fromAsyncIter(input as AsyncIterable<T>, opts);\n\t\t}\n\t\tif (typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn fromIter(input as Iterable<T>, opts);\n\t\t}\n\t}\n\t// scalar fallback\n\treturn of(input as T);\n}\n\n/**\n * Emits each argument as `DATA` in order, then `COMPLETE` (implemented via {@link fromIter}).\n *\n * @param values - Values to emit.\n * @returns `Node<T>` — finite sequence.\n *\n * @example\n * ```ts\n * import { of } from \"@graphrefly/graphrefly-ts\";\n *\n * of(1, 2, 3);\n * ```\n *\n * @category extra\n */\nexport function of<T>(...values: T[]): Node<T> {\n\treturn fromIter(values, undefined);\n}\n\n/**\n * Completes immediately with no `DATA` (cold `EMPTY` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — terminal `COMPLETE` only.\n *\n * @example\n * ```ts\n * import { empty } from \"@graphrefly/graphrefly-ts\";\n *\n * empty();\n * ```\n *\n * @category extra\n */\nexport function empty<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\ta.down([[COMPLETE]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Never emits and never completes until teardown (cold `NEVER` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — silent until unsubscribed.\n *\n * @example\n * ```ts\n * import { never } from \"@graphrefly/graphrefly-ts\";\n *\n * never();\n * ```\n *\n * @category extra\n */\nexport function never<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(() => undefined, sourceOpts(opts));\n}\n\n/**\n * Emits `ERROR` as soon as the producer starts (cold error source).\n *\n * @param err - Error payload forwarded as `ERROR` data.\n * @param opts - Optional producer options.\n * @returns `Node<never>` — terminates with `ERROR`.\n *\n * @example\n * ```ts\n * import { throwError } from \"@graphrefly/graphrefly-ts\";\n *\n * throwError(new Error(\"fail\"));\n * ```\n *\n * @category extra\n */\nexport function throwError(err: unknown, opts?: ExtraOpts): Node<never> {\n\treturn producer<never>((_d, a) => {\n\t\ta.down([[ERROR, err]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Subscribes immediately and runs `fn` for each upstream `DATA`; returns unsubscribe.\n *\n * @param source - Upstream node.\n * @param fn - Side effect per value.\n * @param opts - Effect node options.\n * @returns Unsubscribe function (idempotent).\n *\n * @example\n * ```ts\n * import { forEach, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const u = forEach(state(1), (v) => console.log(v));\n * u();\n * ```\n *\n * @category extra\n */\nexport function forEach<T>(source: Node<T>, fn: (value: T) => void, opts?: ExtraOpts): () => void {\n\tconst inner = node([source as Node], () => undefined, {\n\t\tdescribeKind: \"effect\",\n\t\t...opts,\n\t\tonMessage(msg: Message, _i, _a) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tfn(msg[1] as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n\treturn inner.subscribe(() => {});\n}\n\n/**\n * Buffers every `DATA`; on upstream `COMPLETE` emits one `DATA` with the full array then `COMPLETE`.\n *\n * @param source - Upstream node.\n * @param opts - Optional node options (operator describe kind).\n * @returns `Node<T[]>` — single array emission before completion.\n *\n * @example\n * ```ts\n * import { of, toArray } from \"@graphrefly/graphrefly-ts\";\n *\n * toArray(of(1, 2, 3));\n * ```\n *\n * @category extra\n */\nexport function toArray<T>(source: Node<T>, opts?: ExtraOpts): Node<T[]> {\n\tconst acc: T[] = [];\n\treturn node<T[]>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg: Message, _i, a) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tacc.push(msg[1] as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\ta.emit([...acc]);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Multicasts upstream: one subscription to `source` while this wrapper has subscribers (via {@link producer}).\n *\n * @param source - Upstream node to share.\n * @param opts - Producer options; `initial` seeds from `source.get()` when set by factory.\n * @returns `Node<T>` — hot ref-counted bridge.\n *\n * @example\n * ```ts\n * import { share, state } from \"@graphrefly/graphrefly-ts\";\n *\n * share(state(0));\n * ```\n *\n * @category extra\n */\nexport function share<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(\n\t\t(_d, a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts(opts), initial: source.get() },\n\t);\n}\n\n/**\n * Like {@link share} with a bounded replay buffer: new subscribers receive the last `bufferSize`\n * `DATA` payloads (as separate batches) before live updates.\n *\n * @param source - Upstream node.\n * @param bufferSize - Maximum past values to replay (≥ 1).\n * @param opts - Producer options.\n * @returns `Node<T>` — multicast with replay on subscribe.\n *\n * @example\n * ```ts\n * import { replay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * replay(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function replay<T>(source: Node<T>, bufferSize: number, opts?: ExtraOpts): Node<T> {\n\tif (bufferSize < 1) throw new RangeError(\"replay expects bufferSize >= 1\");\n\tconst buf: T[] = [];\n\tconst inner = producer<T>(\n\t\t(_d, a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tbuf.push(m[1] as T);\n\t\t\t\t\t\tif (buf.length > bufferSize) buf.shift();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts(opts), initial: source.get() },\n\t);\n\treturn wrapSubscribeHook(inner, (sink) => {\n\t\tfor (const v of buf) {\n\t\t\tsink([[DATA, v]]);\n\t\t}\n\t});\n}\n\n/**\n * {@link replay} with `bufferSize === 1` — replays the latest `DATA` to new subscribers.\n *\n * @param source - Upstream node.\n * @param opts - Producer options.\n * @returns `Node<T>` — share + last-value replay.\n *\n * @example\n * ```ts\n * import { cached, state } from \"@graphrefly/graphrefly-ts\";\n *\n * cached(state(0));\n * ```\n *\n * @category extra\n */\nexport function cached<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn replay(source, 1, opts);\n}\n\n/**\n * Converts the first `DATA` on `source` into a Promise; rejects on `ERROR` or `COMPLETE` without data.\n *\n * @param source - Node to read once.\n * @returns Promise of the first value.\n *\n * @example\n * ```ts\n * import { firstValueFrom, of } from \"@graphrefly/graphrefly-ts\";\n *\n * await firstValueFrom(of(42));\n * ```\n *\n * @category extra\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst unsub = source.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (settled) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tresolve(m[1] as T);\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(m[1]);\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(new Error(\"completed without DATA\"));\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n\n// ——————————————————————————————————————————————————————————————\n// RxJS-compatible aliases\n// ——————————————————————————————————————————————————————————————\n\n/**\n * RxJS-named alias for {@link replay} — multicast with a replay buffer of size `bufferSize`.\n *\n * @param source - Upstream node.\n * @param bufferSize - Replay depth (≥ 1).\n * @param opts - Producer options.\n * @returns Same behavior as `replay`.\n *\n * @example\n * ```ts\n * import { shareReplay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * shareReplay(state(0), 5);\n * ```\n *\n * @category extra\n */\nexport const shareReplay = replay;\n","/**\n * Watermark-based backpressure controller — reactive PAUSE/RESUME flow control.\n *\n * Purely synchronous, event-driven. No timers, no polling, no Promises.\n * Each controller instance uses a unique lockId so multiple controllers\n * on the same upstream node do not collide.\n *\n * @module\n */\n\nimport { type Messages, PAUSE, RESUME } from \"../core/messages.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type WatermarkOptions = {\n\t/** Pending count at which PAUSE is sent upstream. */\n\thighWaterMark: number;\n\t/** Pending count at which RESUME is sent upstream (after being paused). */\n\tlowWaterMark: number;\n};\n\nexport type WatermarkController = {\n\t/** Call when a DATA message is buffered/enqueued. Returns `true` if PAUSE was just sent. */\n\tonEnqueue(): boolean;\n\t/** Call when a buffered item is consumed. Returns `true` if RESUME was just sent. */\n\tonDequeue(): boolean;\n\t/** Current un-consumed item count. */\n\treadonly pending: number;\n\t/** Whether upstream is currently paused by this controller. */\n\treadonly paused: boolean;\n\t/** Dispose: if paused, sends RESUME to unblock upstream. */\n\tdispose(): void;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nlet nextLockId = 0;\n\n/**\n * Creates a watermark-based backpressure controller.\n *\n * @param sendUp - Callback that delivers messages upstream (typically `handle.up`).\n * @param opts - High/low watermark thresholds (item counts).\n * @returns A {@link WatermarkController}.\n *\n * @example\n * ```ts\n * const handle = graph.observe(\"fast-source\");\n * const wm = createWatermarkController(\n * (msgs) => handle.up(msgs),\n * { highWaterMark: 64, lowWaterMark: 16 },\n * );\n *\n * // In sink callback:\n * handle.subscribe((msgs) => {\n * for (const msg of msgs) {\n * if (msg[0] === DATA) {\n * buffer.push(msg[1]);\n * wm.onEnqueue();\n * }\n * }\n * });\n *\n * // When consumer drains:\n * const item = buffer.shift();\n * wm.onDequeue();\n * ```\n *\n * @category extra\n */\nexport function createWatermarkController(\n\tsendUp: (messages: Messages) => void,\n\topts: WatermarkOptions,\n): WatermarkController {\n\tif (opts.highWaterMark < 1) throw new RangeError(\"highWaterMark must be >= 1\");\n\tif (opts.lowWaterMark < 0) throw new RangeError(\"lowWaterMark must be >= 0\");\n\tif (opts.lowWaterMark >= opts.highWaterMark)\n\t\tthrow new RangeError(\"lowWaterMark must be < highWaterMark\");\n\tconst lockId = Symbol(`bp-${++nextLockId}`);\n\tlet pending = 0;\n\tlet paused = false;\n\n\treturn {\n\t\tonEnqueue(): boolean {\n\t\t\tpending += 1;\n\t\t\tif (!paused && pending >= opts.highWaterMark) {\n\t\t\t\tpaused = true;\n\t\t\t\tsendUp([[PAUSE, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tonDequeue(): boolean {\n\t\t\tif (pending > 0) pending -= 1;\n\t\t\tif (paused && pending <= opts.lowWaterMark) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tget pending() {\n\t\t\treturn pending;\n\t\t},\n\t\tget paused() {\n\t\t\treturn paused;\n\t\t},\n\t\tdispose() {\n\t\t\tif (paused) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Reactive append-only log (roadmap §3.2) — emits `readonly T[]` snapshots directly.\n *\n * Internal version counter drives efficient equality without leaking `Versioned`\n * into the public API (spec §5.12).\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\n\nexport type ReactiveLogOptions = {\n\tname?: string;\n\tmaxSize?: number;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits `readonly T[]` on each append/clear (two-phase). */\n\treadonly entries: Node<readonly T[]>;\n\tappend: (value: T) => void;\n\t/** Push all values, trim once, emit one snapshot. */\n\tappendMany: (values: readonly T[]) => void;\n\tclear: () => void;\n\t/** Remove the first `n` entries; emits snapshot. */\n\ttrimHead: (n: number) => void;\n\t/** Last `n` entries (or fewer); updates when the log changes. */\n\ttail: (n: number) => Node<readonly T[]>;\n};\n\n/**\n * Keep a derived node's dep wiring alive for `get()` without a user sink.\n * Returns the unsubscribe handle so callers can clean up.\n *\n * @remarks Derived views (`tail`, `logSlice`) install this so `get()` stays\n * wired without an external sink. The returned disposer is currently not\n * exposed on the bundle — subscriptions are released when the log bundle\n * becomes unreachable and the GC collects the closure.\n */\nfunction keepaliveDerived(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n/**\n * Creates an append-only reactive log with immutable array snapshots.\n *\n * @param initial - Optional seed entries (copied).\n * @param options - Optional `name` for `describe()` / debugging.\n * @returns Bundle with `entries` (state node), `append`, `clear`, and {@link ReactiveLogBundle.tail}.\n *\n * @remarks\n * **Derived views:** {@link tail} and {@link logSlice} install an internal noop subscription so\n * `get()` stays wired without an external sink; creating very many disposable derived nodes can\n * retain subscriptions until the log bundle is unreachable.\n *\n * @example\n * ```ts\n * import { reactiveLog } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([1, 2], { name: \"audit\" });\n * lg.append(3);\n * lg.entries.subscribe((msgs) => console.log(msgs));\n * ```\n *\n * @category extra\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLogBundle<T> {\n\tconst { name, maxSize } = options;\n\tif (maxSize !== undefined && maxSize < 1) {\n\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t}\n\tconst buf: T[] = initial ? [...initial] : [];\n\tif (maxSize !== undefined && buf.length > maxSize) {\n\t\tbuf.splice(0, buf.length - maxSize);\n\t}\n\n\tconst entries = state<readonly T[]>(buf.length > 0 ? [...buf] : [], {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: (a, b) => a === b,\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst snapshot: readonly T[] = [...buf];\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, snapshot]]);\n\t\t});\n\t}\n\n\tfunction trimBuf(): void {\n\t\tif (maxSize !== undefined && buf.length > maxSize) {\n\t\t\tbuf.splice(0, buf.length - maxSize);\n\t\t}\n\t}\n\n\tconst bundle: ReactiveLogBundle<T> = {\n\t\tentries,\n\n\t\tappend(value: T): void {\n\t\t\tbuf.push(value);\n\t\t\ttrimBuf();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tbuf.push(...values);\n\t\t\ttrimBuf();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tclear(): void {\n\t\t\tif (buf.length === 0) return;\n\t\t\tbuf.length = 0;\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\ttrimHead(n: number): void {\n\t\t\tif (n < 0) {\n\t\t\t\tthrow new RangeError(\"n must be >= 0\");\n\t\t\t}\n\t\t\tif (n === 0) return;\n\t\t\tif (n >= buf.length) {\n\t\t\t\tif (buf.length === 0) return;\n\t\t\t\tbuf.length = 0;\n\t\t\t} else {\n\t\t\t\tbuf.splice(0, n);\n\t\t\t}\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\ttail(n: number): Node<readonly T[]> {\n\t\t\tif (n < 0) {\n\t\t\t\tthrow new RangeError(\"n must be >= 0\");\n\t\t\t}\n\t\t\tconst e = entries.get() as readonly T[];\n\t\t\tconst init = n === 0 ? [] : e.slice(Math.max(0, e.length - n));\n\t\t\tconst out = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = s as readonly T[];\n\t\t\t\t\treturn n === 0 ? [] : list.slice(Math.max(0, list.length - n));\n\t\t\t\t},\n\t\t\t\t{ initial: init, describeKind: \"derived\" },\n\t\t\t);\n\t\t\tkeepaliveDerived(out);\n\t\t\treturn out;\n\t\t},\n\t};\n\n\treturn bundle;\n}\n\n/**\n * Builds a derived node for `entries.slice(start, stop)` (same semantics as `Array.prototype.slice`; `stop` exclusive).\n *\n * @param log - Log from {@link reactiveLog}.\n * @param start - Start index (must be `>= 0`).\n * @param stop - End index (exclusive); omit to slice to the end.\n * @returns Derived node emitting the sliced readonly array.\n *\n * @example\n * ```ts\n * import { reactiveLog, logSlice } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([10, 20, 30, 40, 50]);\n * const slice$ = logSlice(lg, 1, 4); // reactive view of [20, 30, 40]\n * slice$.subscribe((msgs) => console.log(msgs));\n *\n * lg.append(60); // slice$ now reflects [20, 30, 40] (indices 1–3 of updated log)\n * ```\n *\n * @category extra\n */\nexport function logSlice<T>(\n\tlog: ReactiveLogBundle<T>,\n\tstart: number,\n\tstop?: number,\n): Node<readonly T[]> {\n\tif (start < 0) {\n\t\tthrow new RangeError(\"start must be >= 0\");\n\t}\n\tconst e = log.entries.get() as readonly T[];\n\tconst init = stop === undefined ? e.slice(start) : e.slice(start, stop);\n\tconst out = derived(\n\t\t[log.entries],\n\t\t([s]) => {\n\t\t\tconst list = s as readonly T[];\n\t\t\treturn stop === undefined ? list.slice(start) : list.slice(start, stop);\n\t\t},\n\t\t{ initial: init, describeKind: \"derived\" },\n\t);\n\tkeepaliveDerived(out);\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAcpB,SAAS,aAAgBA,OAA8B;AAC7D,SAAO,IAAI,WAAc,CAAC,eAAe;AACxC,UAAM,QAAQA,MAAK,UAAU,CAAC,SAAS;AACtC,iBAAW,KAAK,MAAM;AACrB,YAAI,WAAW,OAAQ;AACvB,YAAI,EAAE,CAAC,MAAM,MAAM;AAClB,qBAAW,KAAK,EAAE,CAAC,CAAM;AAAA,QAC1B,WAAW,EAAE,CAAC,MAAM,OAAO;AAC1B,qBAAW,MAAM,EAAE,CAAC,CAAC;AACrB;AAAA,QACD,WAAW,EAAE,CAAC,MAAM,UAAU;AAC7B,qBAAW,SAAS;AACpB;AAAA,QACD;AAAA,MACD;AAAA,IACD,CAAC;AACD,WAAO;AAAA,EACR,CAAC;AACF;AASO,SAAS,YAAeA,OAAqC;AACnE,SAAO,IAAI,WAAqB,CAAC,eAAe;AAC/C,UAAM,QAAQA,MA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A,QACX,CAAC,OAAO;AAAA,QACR,CAAC,CAAC,CAAC,MAAM;AACR,gBAAM,OAAO;AACb,iBAAO,MAAM,IAAI,CAAC,IAAI,KAAK,MAAM,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC,CAAC;AAAA,QAC9D;AAAA,QACA,EAAE,SAAS,MAAM,cAAc,UAAU;AAAA,MAC1C;AACA,uBAAiB,GAAG;AACpB,aAAO;AAAA,IACR;AAAA,EACD;AAEA,SAAO;AACR;AAuBO,SAAS,SACf,KACA,OACA,MACqB;AACrB,MAAI,QAAQ,GAAG;AACd,UAAM,IAAI,WAAW,oBAAoB;AAAA,EAC1C;AACA,QAAM,IAAI,IAAI,QAAQ,IAAI;AAC1B,QAAM,OAAO,SAAS,SAAY,EAAE,MAAM,KAAK,IAAI,EAAE,MAAM,OAAO,IAAI;AACtE,QAAM,MAAM;AAAA,IACX,CAAC,IAAI,OAAO;AAAA,IACZ,CAAC,CAAC,CAAC,MAAM;AACR,YAAM,OAAO;AACb,aAAO,SAAS,SAAY,KAAK,MAAM,KAAK,IAAI,KAAK,MAAM,OAAO,IAAI;AAAA,IACvE;AAAA,IACA,EAAE,SAAS,MAAM,cAAc,UAAU;AAAA,EAC1C;AACA,mBAAiB,GAAG;AACpB,SAAO;AACR;","names":["node"]}
@@ -1568,15 +1568,14 @@ var GraphReflyEventExplorer = class {
1568
1568
  if (!cqrsGraph) return;
1569
1569
  cqrsGraph.event(meta.eventName);
1570
1570
  const eventNode = cqrsGraph.resolve(meta.eventName);
1571
- const currentSnap = eventNode.get();
1572
- const existingEntries = currentSnap?.value?.entries;
1571
+ const existingEntries = eventNode.get();
1573
1572
  let lastSeq = existingEntries && existingEntries.length > 0 ? existingEntries[existingEntries.length - 1].seq : 0;
1574
1573
  const handle = this.observeNodeOn(cqrsGraph, meta.eventName);
1575
1574
  const unsub = handle.subscribe((msgs) => {
1576
1575
  for (const m of msgs) {
1577
1576
  if (m[0] === DATA) {
1578
- const snap = m[1];
1579
- for (const entry of snap.value.entries) {
1577
+ const entries = m[1];
1578
+ for (const entry of entries) {
1580
1579
  if (entry.seq > lastSeq) {
1581
1580
  bound(entry);
1582
1581
  lastSeq = entry.seq;
@@ -2958,6 +2957,7 @@ var Graph = class _Graph {
2958
2957
  /** @internal — exposed for {@link teardownMountedGraph}. */
2959
2958
  _mounts = /* @__PURE__ */ new Map();
2960
2959
  _autoCheckpointDisposers = /* @__PURE__ */ new Set();
2960
+ _disposers = /* @__PURE__ */ new Set();
2961
2961
  _defaultVersioningLevel;
2962
2962
  static registerFactory(pattern, factory) {
2963
2963
  if (!pattern) {
@@ -4093,10 +4093,33 @@ var Graph = class _Graph {
4093
4093
  // Lifecycle & persistence (§3.7–§3.8)
4094
4094
  // ——————————————————————————————————————————————————————————————
4095
4095
  /**
4096
- * Sends `[[TEARDOWN]]` to all nodes, then clears registries on this graph and every
4097
- * mounted subgraph (§3.7). The instance is left empty and may be reused with {@link Graph.add}.
4096
+ * Register a cleanup function to be called on {@link Graph.destroy}.
4097
+ *
4098
+ * Factories use this to attach teardown logic for internal nodes, keepalive
4099
+ * subscriptions, or other resources that are not registered on the graph and
4100
+ * would otherwise leak on repeated create/destroy cycles.
4101
+ *
4102
+ * Returns a removal function — call it to unregister the disposer early.
4103
+ */
4104
+ addDisposer(fn) {
4105
+ this._disposers.add(fn);
4106
+ return () => {
4107
+ this._disposers.delete(fn);
4108
+ };
4109
+ }
4110
+ /**
4111
+ * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all
4112
+ * nodes and clears registries on this graph and every mounted subgraph (§3.7).
4113
+ * The instance is left empty and may be reused with {@link Graph.add}.
4098
4114
  */
4099
4115
  destroy() {
4116
+ for (const dispose of [...this._disposers]) {
4117
+ try {
4118
+ dispose();
4119
+ } catch {
4120
+ }
4121
+ }
4122
+ this._disposers.clear();
4100
4123
  this.signal([[TEARDOWN]], { internal: true });
4101
4124
  for (const dispose of [...this._autoCheckpointDisposers]) {
4102
4125
  try {
@@ -4499,25 +4522,7 @@ var Graph = class _Graph {
4499
4522
  }
4500
4523
  };
4501
4524
 
4502
- // src/extra/reactive-base.ts
4503
- function snapshotEqualsVersion(a, b) {
4504
- if (typeof a !== "object" || a == null || typeof b !== "object" || b == null) {
4505
- return Object.is(a, b);
4506
- }
4507
- if (!("version" in a) || !("version" in b)) return Object.is(a, b);
4508
- return a.version === b.version;
4509
- }
4510
- function bumpVersion(current, nextValue, v0) {
4511
- if (v0 != null) {
4512
- return { version: current.version + 1, value: nextValue, v0 };
4513
- }
4514
- return { version: current.version + 1, value: nextValue };
4515
- }
4516
-
4517
4525
  // src/extra/reactive-log.ts
4518
- function emptySnapshot() {
4519
- return { version: 0, value: { entries: [] } };
4520
- }
4521
4526
  function keepaliveDerived(n) {
4522
4527
  return n.subscribe(() => {
4523
4528
  });
@@ -4531,22 +4536,16 @@ function reactiveLog(initial, options = {}) {
4531
4536
  if (maxSize !== void 0 && buf.length > maxSize) {
4532
4537
  buf.splice(0, buf.length - maxSize);
4533
4538
  }
4534
- let current = buf.length > 0 ? { version: 1, value: { entries: [...buf] } } : emptySnapshot();
4535
- const entries = state(current, {
4539
+ const entries = state(buf.length > 0 ? [...buf] : [], {
4536
4540
  name,
4537
4541
  describeKind: "state",
4538
- equals: snapshotEqualsVersion
4542
+ equals: (a, b) => a === b
4539
4543
  });
4540
4544
  function pushSnapshot() {
4541
- const ev = entries.v;
4542
- current = bumpVersion(
4543
- current,
4544
- { entries: [...buf] },
4545
- ev ? { id: ev.id, version: ev.version } : void 0
4546
- );
4545
+ const snapshot = [...buf];
4547
4546
  batch(() => {
4548
4547
  entries.down([[DIRTY]]);
4549
- entries.down([[DATA, current]]);
4548
+ entries.down([[DATA, snapshot]]);
4550
4549
  });
4551
4550
  }
4552
4551
  function trimBuf() {
@@ -4589,13 +4588,12 @@ function reactiveLog(initial, options = {}) {
4589
4588
  if (n < 0) {
4590
4589
  throw new RangeError("n must be >= 0");
4591
4590
  }
4592
- const snap = entries.get();
4593
- const e = snap.value.entries;
4591
+ const e = entries.get();
4594
4592
  const init = n === 0 ? [] : e.slice(Math.max(0, e.length - n));
4595
4593
  const out = derived(
4596
4594
  [entries],
4597
4595
  ([s]) => {
4598
- const list = s.value.entries;
4596
+ const list = s;
4599
4597
  return n === 0 ? [] : list.slice(Math.max(0, list.length - n));
4600
4598
  },
4601
4599
  { initial: init, describeKind: "derived" }
@@ -4762,8 +4760,8 @@ var CqrsGraph = class extends Graph {
4762
4760
  (snapshots) => {
4763
4761
  const allEvents = [];
4764
4762
  for (const snapshot of snapshots) {
4765
- const snap = snapshot;
4766
- allEvents.push(...snap.value.entries);
4763
+ const entries = snapshot;
4764
+ allEvents.push(...entries);
4767
4765
  }
4768
4766
  allEvents.sort((a, b) => a.timestampNs - b.timestampNs || a.seq - b.seq);
4769
4767
  return reducer(initial, allEvents);
@@ -4804,9 +4802,8 @@ var CqrsGraph = class extends Graph {
4804
4802
  (snapshots) => {
4805
4803
  const errNode = sagaRef.n.meta.error;
4806
4804
  for (let i = 0; i < snapshots.length; i++) {
4807
- const snap = snapshots[i];
4805
+ const entries = snapshots[i];
4808
4806
  const eName = eventNames[i];
4809
- const entries = snap.value.entries;
4810
4807
  const lastCount = lastCounts.get(eName) ?? 0;
4811
4808
  if (entries.length > lastCount) {
4812
4809
  const newEntries = entries.slice(lastCount);