@graphrefly/graphrefly 0.1.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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +234 -0
  3. package/dist/chunk-5X3LAO3B.js +1571 -0
  4. package/dist/chunk-5X3LAO3B.js.map +1 -0
  5. package/dist/chunk-6W5SGIGB.js +1793 -0
  6. package/dist/chunk-6W5SGIGB.js.map +1 -0
  7. package/dist/chunk-CP6MNKAA.js +97 -0
  8. package/dist/chunk-CP6MNKAA.js.map +1 -0
  9. package/dist/chunk-HP7OKEOE.js +107 -0
  10. package/dist/chunk-HP7OKEOE.js.map +1 -0
  11. package/dist/chunk-KWXPDASV.js +781 -0
  12. package/dist/chunk-KWXPDASV.js.map +1 -0
  13. package/dist/chunk-O3PI7W45.js +68 -0
  14. package/dist/chunk-O3PI7W45.js.map +1 -0
  15. package/dist/chunk-QW7H3ICI.js +1372 -0
  16. package/dist/chunk-QW7H3ICI.js.map +1 -0
  17. package/dist/chunk-VPS7L64N.js +4785 -0
  18. package/dist/chunk-VPS7L64N.js.map +1 -0
  19. package/dist/chunk-Z4Y4FMQN.js +1097 -0
  20. package/dist/chunk-Z4Y4FMQN.js.map +1 -0
  21. package/dist/compat/nestjs/index.cjs +4883 -0
  22. package/dist/compat/nestjs/index.cjs.map +1 -0
  23. package/dist/compat/nestjs/index.d.cts +7 -0
  24. package/dist/compat/nestjs/index.d.ts +7 -0
  25. package/dist/compat/nestjs/index.js +84 -0
  26. package/dist/compat/nestjs/index.js.map +1 -0
  27. package/dist/core/index.cjs +1632 -0
  28. package/dist/core/index.cjs.map +1 -0
  29. package/dist/core/index.d.cts +2 -0
  30. package/dist/core/index.d.ts +2 -0
  31. package/dist/core/index.js +90 -0
  32. package/dist/core/index.js.map +1 -0
  33. package/dist/extra/index.cjs +6885 -0
  34. package/dist/extra/index.cjs.map +1 -0
  35. package/dist/extra/index.d.cts +5 -0
  36. package/dist/extra/index.d.ts +5 -0
  37. package/dist/extra/index.js +290 -0
  38. package/dist/extra/index.js.map +1 -0
  39. package/dist/graph/index.cjs +3225 -0
  40. package/dist/graph/index.cjs.map +1 -0
  41. package/dist/graph/index.d.cts +3 -0
  42. package/dist/graph/index.d.ts +3 -0
  43. package/dist/graph/index.js +25 -0
  44. package/dist/graph/index.js.map +1 -0
  45. package/dist/graph-CL_ZDAj9.d.cts +605 -0
  46. package/dist/graph-D18qmsNm.d.ts +605 -0
  47. package/dist/index-B6SsZs2h.d.cts +3463 -0
  48. package/dist/index-B7eOdgEx.d.ts +449 -0
  49. package/dist/index-BHUvlQ3v.d.ts +3463 -0
  50. package/dist/index-BtK55IE2.d.ts +231 -0
  51. package/dist/index-BvhgZRHK.d.cts +231 -0
  52. package/dist/index-Bvy_6CaN.d.ts +452 -0
  53. package/dist/index-C3BMRmmp.d.cts +449 -0
  54. package/dist/index-C5mqLhMX.d.cts +452 -0
  55. package/dist/index-CP_QvbWu.d.ts +940 -0
  56. package/dist/index-D_geH2Bm.d.cts +940 -0
  57. package/dist/index.cjs +14843 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.cts +1517 -0
  60. package/dist/index.d.ts +1517 -0
  61. package/dist/index.js +3649 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/meta-BsF6Sag9.d.cts +607 -0
  64. package/dist/meta-BsF6Sag9.d.ts +607 -0
  65. package/dist/patterns/reactive-layout/index.cjs +4143 -0
  66. package/dist/patterns/reactive-layout/index.cjs.map +1 -0
  67. package/dist/patterns/reactive-layout/index.d.cts +3 -0
  68. package/dist/patterns/reactive-layout/index.d.ts +3 -0
  69. package/dist/patterns/reactive-layout/index.js +38 -0
  70. package/dist/patterns/reactive-layout/index.js.map +1 -0
  71. package/dist/reactive-log-BfvfNWQh.d.cts +137 -0
  72. package/dist/reactive-log-ohLmTXoZ.d.ts +137 -0
  73. package/package.json +256 -0
@@ -0,0 +1,1571 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
+ }) : x)(function(x) {
13
+ if (typeof require !== "undefined") return require.apply(this, arguments);
14
+ throw Error('Dynamic require of "' + x + '" is not supported');
15
+ });
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
21
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
22
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
23
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
24
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
25
+ var __runInitializers = (array, flags, self, value) => {
26
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
27
+ return value;
28
+ };
29
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
30
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
31
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
32
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
33
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
34
+ return __privateGet(this, extra);
35
+ }, set [name](x) {
36
+ return __privateSet(this, extra, x);
37
+ } }, name));
38
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
39
+ for (var i = decorators.length - 1; i >= 0; i--) {
40
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
41
+ if (k) {
42
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
43
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
44
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
45
+ }
46
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
47
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
48
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
49
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
50
+ }
51
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
52
+ };
53
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
54
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
55
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
56
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
57
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
58
+
59
+ // src/core/actor.ts
60
+ var DEFAULT_ACTOR = { type: "system", id: "" };
61
+ function normalizeActor(actor) {
62
+ if (actor == null) return DEFAULT_ACTOR;
63
+ const { type, id, ...rest } = actor;
64
+ return {
65
+ type: type ?? "system",
66
+ id: id ?? "",
67
+ ...rest
68
+ };
69
+ }
70
+
71
+ // src/core/messages.ts
72
+ var DATA = /* @__PURE__ */ Symbol.for("graphrefly/DATA");
73
+ var DIRTY = /* @__PURE__ */ Symbol.for("graphrefly/DIRTY");
74
+ var RESOLVED = /* @__PURE__ */ Symbol.for("graphrefly/RESOLVED");
75
+ var INVALIDATE = /* @__PURE__ */ Symbol.for("graphrefly/INVALIDATE");
76
+ var PAUSE = /* @__PURE__ */ Symbol.for("graphrefly/PAUSE");
77
+ var RESUME = /* @__PURE__ */ Symbol.for("graphrefly/RESUME");
78
+ var TEARDOWN = /* @__PURE__ */ Symbol.for("graphrefly/TEARDOWN");
79
+ var COMPLETE = /* @__PURE__ */ Symbol.for("graphrefly/COMPLETE");
80
+ var ERROR = /* @__PURE__ */ Symbol.for("graphrefly/ERROR");
81
+ var knownMessageTypes = [
82
+ DATA,
83
+ DIRTY,
84
+ RESOLVED,
85
+ INVALIDATE,
86
+ PAUSE,
87
+ RESUME,
88
+ TEARDOWN,
89
+ COMPLETE,
90
+ ERROR
91
+ ];
92
+ function isKnownMessageType(t) {
93
+ return knownMessageTypes.includes(t);
94
+ }
95
+ function messageTier(t) {
96
+ if (t === DIRTY || t === INVALIDATE) return 0;
97
+ if (t === PAUSE || t === RESUME) return 1;
98
+ if (t === DATA || t === RESOLVED) return 2;
99
+ if (t === COMPLETE || t === ERROR) return 3;
100
+ if (t === TEARDOWN) return 4;
101
+ return 0;
102
+ }
103
+ function isPhase2Message(msg) {
104
+ const t = msg[0];
105
+ return t === DATA || t === RESOLVED;
106
+ }
107
+ function isTerminalMessage(t) {
108
+ return t === COMPLETE || t === ERROR;
109
+ }
110
+ function propagatesToMeta(t) {
111
+ return t === TEARDOWN;
112
+ }
113
+
114
+ // src/core/batch.ts
115
+ var MAX_DRAIN_ITERATIONS = 1e3;
116
+ var batchDepth = 0;
117
+ var flushInProgress = false;
118
+ var pendingPhase2 = [];
119
+ var pendingPhase3 = [];
120
+ function isBatching() {
121
+ return batchDepth > 0 || flushInProgress;
122
+ }
123
+ function batch(fn) {
124
+ batchDepth += 1;
125
+ let threw = false;
126
+ try {
127
+ fn();
128
+ } catch (e) {
129
+ threw = true;
130
+ throw e;
131
+ } finally {
132
+ batchDepth -= 1;
133
+ if (batchDepth === 0) {
134
+ if (threw) {
135
+ if (!flushInProgress) {
136
+ pendingPhase2.length = 0;
137
+ pendingPhase3.length = 0;
138
+ }
139
+ } else {
140
+ drainPending();
141
+ }
142
+ }
143
+ }
144
+ }
145
+ function drainPending() {
146
+ const ownsFlush = !flushInProgress;
147
+ if (ownsFlush) {
148
+ flushInProgress = true;
149
+ }
150
+ let firstError;
151
+ let hasError = false;
152
+ try {
153
+ let iterations = 0;
154
+ while (pendingPhase2.length > 0 || pendingPhase3.length > 0) {
155
+ while (pendingPhase2.length > 0) {
156
+ iterations += 1;
157
+ if (iterations > MAX_DRAIN_ITERATIONS) {
158
+ pendingPhase2.length = 0;
159
+ pendingPhase3.length = 0;
160
+ throw new Error(
161
+ `batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations \u2014 likely a reactive cycle`
162
+ );
163
+ }
164
+ const ops = pendingPhase2.splice(0);
165
+ for (const run of ops) {
166
+ try {
167
+ run();
168
+ } catch (e) {
169
+ if (!hasError) {
170
+ firstError = e;
171
+ hasError = true;
172
+ }
173
+ }
174
+ }
175
+ }
176
+ if (pendingPhase3.length > 0) {
177
+ iterations += 1;
178
+ if (iterations > MAX_DRAIN_ITERATIONS) {
179
+ pendingPhase2.length = 0;
180
+ pendingPhase3.length = 0;
181
+ throw new Error(
182
+ `batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations \u2014 likely a reactive cycle`
183
+ );
184
+ }
185
+ const ops = pendingPhase3.splice(0);
186
+ for (const run of ops) {
187
+ try {
188
+ run();
189
+ } catch (e) {
190
+ if (!hasError) {
191
+ firstError = e;
192
+ hasError = true;
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+ } finally {
199
+ if (ownsFlush) {
200
+ flushInProgress = false;
201
+ }
202
+ }
203
+ if (hasError) {
204
+ throw firstError;
205
+ }
206
+ }
207
+ function partitionForBatch(messages) {
208
+ const immediate = [];
209
+ const deferred = [];
210
+ const terminal = [];
211
+ for (const m of messages) {
212
+ if (isPhase2Message(m)) {
213
+ deferred.push(m);
214
+ } else if (isTerminalMessage(m[0])) {
215
+ terminal.push(m);
216
+ } else {
217
+ immediate.push(m);
218
+ }
219
+ }
220
+ return { immediate, deferred, terminal };
221
+ }
222
+ function emitWithBatch(emit, messages, phase = 2) {
223
+ if (messages.length === 0) {
224
+ return;
225
+ }
226
+ const queue = phase === 3 ? pendingPhase3 : pendingPhase2;
227
+ if (messages.length === 1) {
228
+ const t = messages[0][0];
229
+ if (t === DATA || t === RESOLVED) {
230
+ if (isBatching()) {
231
+ queue.push(() => emit(messages));
232
+ } else {
233
+ emit(messages);
234
+ }
235
+ } else if (isTerminalMessage(t)) {
236
+ if (isBatching()) {
237
+ queue.push(() => emit(messages));
238
+ } else {
239
+ emit(messages);
240
+ }
241
+ } else {
242
+ emit(messages);
243
+ }
244
+ return;
245
+ }
246
+ const { immediate, deferred, terminal } = partitionForBatch(messages);
247
+ if (immediate.length > 0) {
248
+ emit(immediate);
249
+ }
250
+ if (isBatching()) {
251
+ if (deferred.length > 0) {
252
+ queue.push(() => emit(deferred));
253
+ }
254
+ if (terminal.length > 0) {
255
+ queue.push(() => emit(terminal));
256
+ }
257
+ } else {
258
+ if (deferred.length > 0) {
259
+ emit(deferred);
260
+ }
261
+ if (terminal.length > 0) {
262
+ emit(terminal);
263
+ }
264
+ }
265
+ }
266
+
267
+ // src/core/clock.ts
268
+ function monotonicNs() {
269
+ return Math.trunc(performance.now() * 1e6);
270
+ }
271
+ function wallClockNs() {
272
+ return Date.now() * 1e6;
273
+ }
274
+
275
+ // src/core/guard.ts
276
+ var GuardDenied = class extends Error {
277
+ actor;
278
+ action;
279
+ nodeName;
280
+ /**
281
+ * @param details - Actor, action, and optional node name for the denial.
282
+ * @param message - Optional override for the default error message.
283
+ */
284
+ constructor(details, message) {
285
+ super(
286
+ message ?? `GuardDenied: action "${String(details.action)}" denied for actor type "${String(details.actor.type)}"`
287
+ );
288
+ this.name = "GuardDenied";
289
+ this.actor = details.actor;
290
+ this.action = details.action;
291
+ this.nodeName = details.nodeName;
292
+ }
293
+ /** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */
294
+ get node() {
295
+ return this.nodeName;
296
+ }
297
+ };
298
+ function normalizeActions(action) {
299
+ if (Array.isArray(action)) {
300
+ return [...action];
301
+ }
302
+ return [action];
303
+ }
304
+ function matchesActions(set, action) {
305
+ return set.has(action) || set.has("*");
306
+ }
307
+ function policy(build) {
308
+ const rules = [];
309
+ const allow = (action, opts) => {
310
+ rules.push({
311
+ kind: "allow",
312
+ actions: new Set(normalizeActions(action)),
313
+ where: opts?.where ?? (() => true)
314
+ });
315
+ };
316
+ const deny = (action, opts) => {
317
+ rules.push({
318
+ kind: "deny",
319
+ actions: new Set(normalizeActions(action)),
320
+ where: opts?.where ?? (() => true)
321
+ });
322
+ };
323
+ build(allow, deny);
324
+ return (actor, action) => {
325
+ let denied = false;
326
+ let allowed = false;
327
+ for (const r of rules) {
328
+ if (!matchesActions(r.actions, action)) continue;
329
+ if (!r.where(actor)) continue;
330
+ if (r.kind === "deny") {
331
+ denied = true;
332
+ } else {
333
+ allowed = true;
334
+ }
335
+ }
336
+ if (denied) return false;
337
+ return allowed;
338
+ };
339
+ }
340
+ function policyFromRules(rules) {
341
+ return policy((allow, deny) => {
342
+ for (const rule of rules) {
343
+ const actorTypes = rule.actorType == null ? null : new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);
344
+ const actorIds = rule.actorId == null ? null : new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);
345
+ const claimEntries = Object.entries(rule.claims ?? {});
346
+ const where = (actor) => {
347
+ if (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;
348
+ if (actorIds !== null && !actorIds.has(String(actor.id ?? ""))) return false;
349
+ for (const [key, value] of claimEntries) {
350
+ if (actor[key] !== value) return false;
351
+ }
352
+ return true;
353
+ };
354
+ if (rule.effect === "deny") {
355
+ deny(rule.action, { where });
356
+ } else {
357
+ allow(rule.action, { where });
358
+ }
359
+ }
360
+ });
361
+ }
362
+ var STANDARD_WRITE_TYPES = ["human", "llm", "wallet", "system"];
363
+ function accessHintForGuard(guard) {
364
+ const allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: "" }, "write"));
365
+ if (allowed.length === 0) return "restricted";
366
+ if (allowed.includes("human") && allowed.includes("llm") && allowed.every((t) => t === "human" || t === "llm" || t === "system")) {
367
+ return "both";
368
+ }
369
+ if (allowed.length === 1) return allowed[0];
370
+ return allowed.join("+");
371
+ }
372
+
373
+ // src/core/versioning.ts
374
+ import { createHash, randomUUID } from "crypto";
375
+ function canonicalizeForHash(value) {
376
+ if (value === void 0) return null;
377
+ if (typeof value === "number") {
378
+ if (!Number.isFinite(value)) {
379
+ throw new TypeError(`Cannot hash non-finite number: ${value}`);
380
+ }
381
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
382
+ throw new TypeError(
383
+ `Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. Cross-language cid parity is not guaranteed for unsafe integers.`
384
+ );
385
+ }
386
+ return value;
387
+ }
388
+ if (typeof value === "string" || typeof value === "boolean" || value === null) {
389
+ return value;
390
+ }
391
+ if (Array.isArray(value)) {
392
+ return value.map(canonicalizeForHash);
393
+ }
394
+ if (typeof value === "object" && value !== null) {
395
+ const sorted = {};
396
+ for (const k of Object.keys(value).sort()) {
397
+ sorted[k] = canonicalizeForHash(value[k]);
398
+ }
399
+ return sorted;
400
+ }
401
+ return null;
402
+ }
403
+ function defaultHash(value) {
404
+ const canonical = canonicalizeForHash(value ?? null);
405
+ const json = JSON.stringify(canonical);
406
+ return createHash("sha256").update(json).digest("hex").slice(0, 16);
407
+ }
408
+ function createVersioning(level, initialValue, opts) {
409
+ const id = opts?.id ?? randomUUID();
410
+ if (level === 0) {
411
+ return { id, version: 0 };
412
+ }
413
+ const hash = opts?.hash ?? defaultHash;
414
+ const cid = hash(initialValue);
415
+ return { id, version: 0, cid, prev: null };
416
+ }
417
+ function advanceVersion(info, newValue, hashFn) {
418
+ info.version += 1;
419
+ if ("cid" in info) {
420
+ info.prev = info.cid;
421
+ info.cid = hashFn(newValue);
422
+ }
423
+ }
424
+ function isV1(info) {
425
+ return "cid" in info;
426
+ }
427
+
428
+ // src/core/node.ts
429
+ function createIntBitSet() {
430
+ let bits = 0;
431
+ return {
432
+ set(i) {
433
+ bits |= 1 << i;
434
+ },
435
+ clear(i) {
436
+ bits &= ~(1 << i);
437
+ },
438
+ has(i) {
439
+ return (bits & 1 << i) !== 0;
440
+ },
441
+ covers(other) {
442
+ return (bits & other._bits()) === other._bits();
443
+ },
444
+ any() {
445
+ return bits !== 0;
446
+ },
447
+ reset() {
448
+ bits = 0;
449
+ },
450
+ _bits() {
451
+ return bits;
452
+ }
453
+ };
454
+ }
455
+ function createArrayBitSet(size) {
456
+ const words = new Uint32Array(Math.ceil(size / 32));
457
+ return {
458
+ set(i) {
459
+ words[i >>> 5] |= 1 << (i & 31);
460
+ },
461
+ clear(i) {
462
+ words[i >>> 5] &= ~(1 << (i & 31));
463
+ },
464
+ has(i) {
465
+ return (words[i >>> 5] & 1 << (i & 31)) !== 0;
466
+ },
467
+ covers(other) {
468
+ const ow = other._words;
469
+ for (let w = 0; w < words.length; w++) {
470
+ if ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;
471
+ }
472
+ return true;
473
+ },
474
+ any() {
475
+ for (let w = 0; w < words.length; w++) {
476
+ if (words[w] !== 0) return true;
477
+ }
478
+ return false;
479
+ },
480
+ reset() {
481
+ words.fill(0);
482
+ },
483
+ _words: words
484
+ };
485
+ }
486
+ function createBitSet(size) {
487
+ return size <= 31 ? createIntBitSet() : createArrayBitSet(size);
488
+ }
489
+ var isNodeArray = (value) => Array.isArray(value);
490
+ var isNodeOptions = (value) => typeof value === "object" && value != null && !Array.isArray(value);
491
+ var isCleanupFn = (value) => typeof value === "function";
492
+ var statusAfterMessage = (status, msg) => {
493
+ const t = msg[0];
494
+ if (t === DIRTY) return "dirty";
495
+ if (t === DATA) return "settled";
496
+ if (t === RESOLVED) return "resolved";
497
+ if (t === COMPLETE) return "completed";
498
+ if (t === ERROR) return "errored";
499
+ if (t === INVALIDATE) return "dirty";
500
+ if (t === TEARDOWN) return "disconnected";
501
+ return status;
502
+ };
503
+ var NodeImpl = class {
504
+ // --- Configuration (set once, never reassigned) ---
505
+ _optsName;
506
+ _registryName;
507
+ /** @internal — read by {@link describeNode} before inference. */
508
+ _describeKind;
509
+ meta;
510
+ _deps;
511
+ _fn;
512
+ _opts;
513
+ _equals;
514
+ _onMessage;
515
+ /** @internal — read by {@link describeNode} for `accessHintForGuard`. */
516
+ _guard;
517
+ _lastMutation;
518
+ _hasDeps;
519
+ _autoComplete;
520
+ _isSingleDep;
521
+ // --- Mutable state ---
522
+ _cached;
523
+ _status;
524
+ _terminal = false;
525
+ _connected = false;
526
+ _producerStarted = false;
527
+ _connecting = false;
528
+ _manualEmitUsed = false;
529
+ _sinkCount = 0;
530
+ _singleDepSinkCount = 0;
531
+ // --- Object/collection state ---
532
+ _depDirtyMask;
533
+ _depSettledMask;
534
+ _depCompleteMask;
535
+ _allDepsCompleteMask;
536
+ _lastDepValues;
537
+ _cleanup;
538
+ _sinks = null;
539
+ _singleDepSinks = /* @__PURE__ */ new WeakSet();
540
+ _upstreamUnsubs = [];
541
+ _actions;
542
+ _boundEmitToSinks;
543
+ _inspectorHook;
544
+ _versioning;
545
+ _hashFn;
546
+ constructor(deps, fn, opts) {
547
+ this._deps = deps;
548
+ this._fn = fn;
549
+ this._opts = opts;
550
+ this._optsName = opts.name;
551
+ this._describeKind = opts.describeKind;
552
+ this._equals = opts.equals ?? Object.is;
553
+ this._onMessage = opts.onMessage;
554
+ this._guard = opts.guard;
555
+ this._hasDeps = deps.length > 0;
556
+ this._autoComplete = opts.completeWhenDepsComplete ?? true;
557
+ this._isSingleDep = deps.length === 1 && fn != null;
558
+ this._cached = opts.initial;
559
+ this._status = this._hasDeps ? "disconnected" : "settled";
560
+ this._hashFn = opts.versioningHash ?? defaultHash;
561
+ this._versioning = opts.versioning != null ? createVersioning(opts.versioning, this._cached, {
562
+ id: opts.versioningId,
563
+ hash: this._hashFn
564
+ }) : void 0;
565
+ this._depDirtyMask = createBitSet(deps.length);
566
+ this._depSettledMask = createBitSet(deps.length);
567
+ this._depCompleteMask = createBitSet(deps.length);
568
+ this._allDepsCompleteMask = createBitSet(deps.length);
569
+ for (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);
570
+ const meta = {};
571
+ for (const [k, v] of Object.entries(opts.meta ?? {})) {
572
+ meta[k] = node({
573
+ initial: v,
574
+ name: `${opts.name ?? "node"}:meta:${k}`,
575
+ describeKind: "state",
576
+ ...opts.guard != null ? { guard: opts.guard } : {}
577
+ });
578
+ }
579
+ Object.freeze(meta);
580
+ this.meta = meta;
581
+ const self = this;
582
+ this._actions = {
583
+ down(messages) {
584
+ self._manualEmitUsed = true;
585
+ self._downInternal(messages);
586
+ },
587
+ emit(value) {
588
+ self._manualEmitUsed = true;
589
+ self._emitAutoValue(value);
590
+ },
591
+ up(messages) {
592
+ self._upInternal(messages);
593
+ }
594
+ };
595
+ this.down = this.down.bind(this);
596
+ this.up = this.up.bind(this);
597
+ this._boundEmitToSinks = this._emitToSinks.bind(this);
598
+ }
599
+ get name() {
600
+ return this._registryName ?? this._optsName;
601
+ }
602
+ /**
603
+ * When a node is registered with {@link Graph.add} without an options `name`,
604
+ * the graph assigns the registry local name for introspection (parity with graphrefly-py).
605
+ */
606
+ _assignRegistryName(localName) {
607
+ if (this._optsName !== void 0 || this._registryName !== void 0) return;
608
+ this._registryName = localName;
609
+ }
610
+ /**
611
+ * @internal Attach/remove inspector hook for graph-level observability.
612
+ * Returns a disposer that restores the previous hook.
613
+ */
614
+ _setInspectorHook(hook) {
615
+ const prev = this._inspectorHook;
616
+ this._inspectorHook = hook;
617
+ return () => {
618
+ if (this._inspectorHook === hook) {
619
+ this._inspectorHook = prev;
620
+ }
621
+ };
622
+ }
623
+ // --- Public interface (Node<T>) ---
624
+ get status() {
625
+ return this._status;
626
+ }
627
+ get lastMutation() {
628
+ return this._lastMutation;
629
+ }
630
+ get v() {
631
+ return this._versioning;
632
+ }
633
+ /**
634
+ * Retroactively apply versioning to a node that was created without it.
635
+ * No-op if versioning is already enabled.
636
+ *
637
+ * Version starts at 0 regardless of prior DATA emissions — it tracks
638
+ * changes from the moment versioning is enabled, not historical ones.
639
+ *
640
+ * @internal — used by {@link Graph.setVersioning}.
641
+ */
642
+ _applyVersioning(level, opts) {
643
+ if (this._versioning != null) return;
644
+ this._hashFn = opts?.hash ?? this._hashFn;
645
+ this._versioning = createVersioning(level, this._cached, {
646
+ id: opts?.id,
647
+ hash: this._hashFn
648
+ });
649
+ }
650
+ hasGuard() {
651
+ return this._guard != null;
652
+ }
653
+ allowsObserve(actor) {
654
+ if (this._guard == null) return true;
655
+ return this._guard(normalizeActor(actor), "observe");
656
+ }
657
+ get() {
658
+ return this._cached;
659
+ }
660
+ down(messages, options) {
661
+ if (messages.length === 0) return;
662
+ if (!options?.internal && this._guard != null) {
663
+ const actor = normalizeActor(options?.actor);
664
+ const delivery = options?.delivery ?? "write";
665
+ const action = delivery === "signal" ? "signal" : "write";
666
+ if (!this._guard(actor, action)) {
667
+ throw new GuardDenied({ actor, action, nodeName: this.name });
668
+ }
669
+ this._lastMutation = { actor, timestamp_ns: wallClockNs() };
670
+ }
671
+ this._downInternal(messages);
672
+ }
673
+ _downInternal(messages) {
674
+ if (messages.length === 0) return;
675
+ let lifecycleMessages = messages;
676
+ let sinkMessages = messages;
677
+ if (this._terminal && !this._opts.resubscribable) {
678
+ const terminalPassthrough = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);
679
+ if (terminalPassthrough.length === 0) return;
680
+ lifecycleMessages = terminalPassthrough;
681
+ sinkMessages = terminalPassthrough;
682
+ }
683
+ this._handleLocalLifecycle(lifecycleMessages);
684
+ if (this._canSkipDirty()) {
685
+ let hasPhase2 = false;
686
+ for (let i = 0; i < sinkMessages.length; i++) {
687
+ const t = sinkMessages[i][0];
688
+ if (t === DATA || t === RESOLVED) {
689
+ hasPhase2 = true;
690
+ break;
691
+ }
692
+ }
693
+ if (hasPhase2) {
694
+ const filtered = [];
695
+ for (let i = 0; i < sinkMessages.length; i++) {
696
+ if (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);
697
+ }
698
+ if (filtered.length > 0) {
699
+ emitWithBatch(this._boundEmitToSinks, filtered);
700
+ }
701
+ return;
702
+ }
703
+ }
704
+ emitWithBatch(this._boundEmitToSinks, sinkMessages);
705
+ }
706
+ subscribe(sink, hints) {
707
+ if (hints?.actor != null && this._guard != null) {
708
+ const actor = normalizeActor(hints.actor);
709
+ if (!this._guard(actor, "observe")) {
710
+ throw new GuardDenied({ actor, action: "observe", nodeName: this.name });
711
+ }
712
+ }
713
+ if (this._terminal && this._opts.resubscribable) {
714
+ this._terminal = false;
715
+ this._status = this._hasDeps ? "disconnected" : "settled";
716
+ this._opts.onResubscribe?.();
717
+ }
718
+ this._sinkCount += 1;
719
+ if (hints?.singleDep) {
720
+ this._singleDepSinkCount += 1;
721
+ this._singleDepSinks.add(sink);
722
+ }
723
+ if (this._sinks == null) {
724
+ this._sinks = sink;
725
+ } else if (typeof this._sinks === "function") {
726
+ this._sinks = /* @__PURE__ */ new Set([this._sinks, sink]);
727
+ } else {
728
+ this._sinks.add(sink);
729
+ }
730
+ if (this._hasDeps) {
731
+ this._connectUpstream();
732
+ } else if (this._fn) {
733
+ this._startProducer();
734
+ }
735
+ let removed = false;
736
+ return () => {
737
+ if (removed) return;
738
+ removed = true;
739
+ this._sinkCount -= 1;
740
+ if (this._singleDepSinks.has(sink)) {
741
+ this._singleDepSinkCount -= 1;
742
+ this._singleDepSinks.delete(sink);
743
+ }
744
+ if (this._sinks == null) return;
745
+ if (typeof this._sinks === "function") {
746
+ if (this._sinks === sink) this._sinks = null;
747
+ } else {
748
+ this._sinks.delete(sink);
749
+ if (this._sinks.size === 1) {
750
+ const [only] = this._sinks;
751
+ this._sinks = only;
752
+ } else if (this._sinks.size === 0) {
753
+ this._sinks = null;
754
+ }
755
+ }
756
+ if (this._sinks == null) {
757
+ this._disconnectUpstream();
758
+ this._stopProducer();
759
+ }
760
+ };
761
+ }
762
+ up(messages, options) {
763
+ if (!this._hasDeps) return;
764
+ if (!options?.internal && this._guard != null) {
765
+ const actor = normalizeActor(options?.actor);
766
+ if (!this._guard(actor, "write")) {
767
+ throw new GuardDenied({ actor, action: "write", nodeName: this.name });
768
+ }
769
+ this._lastMutation = { actor, timestamp_ns: wallClockNs() };
770
+ }
771
+ for (const dep of this._deps) {
772
+ if (options === void 0) {
773
+ dep.up?.(messages);
774
+ } else {
775
+ dep.up?.(messages, options);
776
+ }
777
+ }
778
+ }
779
+ _upInternal(messages) {
780
+ if (!this._hasDeps) return;
781
+ for (const dep of this._deps) {
782
+ dep.up?.(messages, { internal: true });
783
+ }
784
+ }
785
+ unsubscribe() {
786
+ if (!this._hasDeps) return;
787
+ this._disconnectUpstream();
788
+ }
789
+ // --- Private methods (prototype, _ prefix) ---
790
+ _emitToSinks(messages) {
791
+ if (this._sinks == null) return;
792
+ if (typeof this._sinks === "function") {
793
+ this._sinks(messages);
794
+ return;
795
+ }
796
+ const snapshot = [...this._sinks];
797
+ for (const sink of snapshot) {
798
+ sink(messages);
799
+ }
800
+ }
801
+ _handleLocalLifecycle(messages) {
802
+ for (const m of messages) {
803
+ const t = m[0];
804
+ if (t === DATA) {
805
+ this._cached = m[1];
806
+ if (this._versioning != null) {
807
+ advanceVersion(this._versioning, m[1], this._hashFn);
808
+ }
809
+ }
810
+ if (t === INVALIDATE) {
811
+ const cleanupFn = this._cleanup;
812
+ this._cleanup = void 0;
813
+ cleanupFn?.();
814
+ this._cached = void 0;
815
+ this._lastDepValues = void 0;
816
+ }
817
+ this._status = statusAfterMessage(this._status, m);
818
+ if (t === COMPLETE || t === ERROR) {
819
+ this._terminal = true;
820
+ }
821
+ if (t === TEARDOWN) {
822
+ if (this._opts.resetOnTeardown) {
823
+ this._cached = void 0;
824
+ }
825
+ const teardownCleanup = this._cleanup;
826
+ this._cleanup = void 0;
827
+ teardownCleanup?.();
828
+ try {
829
+ this._propagateToMeta(t);
830
+ } finally {
831
+ this._disconnectUpstream();
832
+ this._stopProducer();
833
+ }
834
+ }
835
+ if (t !== TEARDOWN && propagatesToMeta(t)) {
836
+ this._propagateToMeta(t);
837
+ }
838
+ }
839
+ }
840
+ /** Propagate a signal to all companion meta nodes (best-effort). */
841
+ _propagateToMeta(t) {
842
+ for (const metaNode of Object.values(this.meta)) {
843
+ try {
844
+ metaNode._downInternal([[t]]);
845
+ } catch {
846
+ }
847
+ }
848
+ }
849
+ _canSkipDirty() {
850
+ return this._sinkCount === 1 && this._singleDepSinkCount === 1;
851
+ }
852
+ _emitAutoValue(value) {
853
+ const wasDirty = this._status === "dirty";
854
+ const unchanged = this._equals(this._cached, value);
855
+ if (unchanged) {
856
+ this._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);
857
+ return;
858
+ }
859
+ this._cached = value;
860
+ this._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);
861
+ }
862
+ _runFn() {
863
+ if (!this._fn) return;
864
+ if (this._terminal && !this._opts.resubscribable) return;
865
+ if (this._connecting) return;
866
+ try {
867
+ const n = this._deps.length;
868
+ const depValues = new Array(n);
869
+ for (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();
870
+ const prev = this._lastDepValues;
871
+ if (n > 0 && prev != null && prev.length === n) {
872
+ let allSame = true;
873
+ for (let i = 0; i < n; i++) {
874
+ if (!Object.is(depValues[i], prev[i])) {
875
+ allSame = false;
876
+ break;
877
+ }
878
+ }
879
+ if (allSame) {
880
+ if (this._status === "dirty") {
881
+ this._downInternal([[RESOLVED]]);
882
+ }
883
+ return;
884
+ }
885
+ }
886
+ const prevCleanup = this._cleanup;
887
+ this._cleanup = void 0;
888
+ prevCleanup?.();
889
+ this._manualEmitUsed = false;
890
+ this._lastDepValues = depValues;
891
+ this._inspectorHook?.({ kind: "run", depValues });
892
+ const out = this._fn(depValues, this._actions);
893
+ if (isCleanupFn(out)) {
894
+ this._cleanup = out;
895
+ return;
896
+ }
897
+ if (this._manualEmitUsed) return;
898
+ if (out === void 0) return;
899
+ this._emitAutoValue(out);
900
+ } catch (err) {
901
+ this._downInternal([[ERROR, err]]);
902
+ }
903
+ }
904
+ _onDepDirty(index) {
905
+ const wasDirty = this._depDirtyMask.has(index);
906
+ this._depDirtyMask.set(index);
907
+ this._depSettledMask.clear(index);
908
+ if (!wasDirty) {
909
+ this._downInternal([[DIRTY]]);
910
+ }
911
+ }
912
+ _onDepSettled(index) {
913
+ if (!this._depDirtyMask.has(index)) {
914
+ this._onDepDirty(index);
915
+ }
916
+ this._depSettledMask.set(index);
917
+ if (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {
918
+ this._depDirtyMask.reset();
919
+ this._depSettledMask.reset();
920
+ this._runFn();
921
+ }
922
+ }
923
+ _maybeCompleteFromDeps() {
924
+ if (this._autoComplete && this._deps.length > 0 && this._depCompleteMask.covers(this._allDepsCompleteMask)) {
925
+ this._downInternal([[COMPLETE]]);
926
+ }
927
+ }
928
+ _handleDepMessages(index, messages) {
929
+ for (const msg of messages) {
930
+ this._inspectorHook?.({ kind: "dep_message", depIndex: index, message: msg });
931
+ const t = msg[0];
932
+ if (this._onMessage) {
933
+ try {
934
+ if (this._onMessage(msg, index, this._actions)) continue;
935
+ } catch (err) {
936
+ this._downInternal([[ERROR, err]]);
937
+ return;
938
+ }
939
+ }
940
+ if (!this._fn) {
941
+ if (t === COMPLETE && this._deps.length > 1) {
942
+ this._depCompleteMask.set(index);
943
+ this._maybeCompleteFromDeps();
944
+ continue;
945
+ }
946
+ this._downInternal([msg]);
947
+ continue;
948
+ }
949
+ if (t === DIRTY) {
950
+ this._onDepDirty(index);
951
+ continue;
952
+ }
953
+ if (t === DATA || t === RESOLVED) {
954
+ this._onDepSettled(index);
955
+ continue;
956
+ }
957
+ if (t === COMPLETE) {
958
+ this._depCompleteMask.set(index);
959
+ this._depDirtyMask.clear(index);
960
+ this._depSettledMask.clear(index);
961
+ if (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {
962
+ this._depDirtyMask.reset();
963
+ this._depSettledMask.reset();
964
+ this._runFn();
965
+ } else if (!this._depDirtyMask.any() && this._status === "dirty") {
966
+ this._depSettledMask.reset();
967
+ this._runFn();
968
+ }
969
+ this._maybeCompleteFromDeps();
970
+ continue;
971
+ }
972
+ if (t === ERROR) {
973
+ this._downInternal([msg]);
974
+ continue;
975
+ }
976
+ if (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {
977
+ this._downInternal([msg]);
978
+ continue;
979
+ }
980
+ this._downInternal([msg]);
981
+ }
982
+ }
983
+ _connectUpstream() {
984
+ if (!this._hasDeps || this._connected) return;
985
+ this._connected = true;
986
+ this._depDirtyMask.reset();
987
+ this._depSettledMask.reset();
988
+ this._depCompleteMask.reset();
989
+ this._status = "settled";
990
+ const subHints = this._isSingleDep ? { singleDep: true } : void 0;
991
+ this._connecting = true;
992
+ try {
993
+ for (let i = 0; i < this._deps.length; i += 1) {
994
+ const dep = this._deps[i];
995
+ this._upstreamUnsubs.push(
996
+ dep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints)
997
+ );
998
+ }
999
+ } finally {
1000
+ this._connecting = false;
1001
+ }
1002
+ if (this._fn) {
1003
+ this._runFn();
1004
+ }
1005
+ }
1006
+ _stopProducer() {
1007
+ if (!this._producerStarted) return;
1008
+ this._producerStarted = false;
1009
+ const producerCleanup = this._cleanup;
1010
+ this._cleanup = void 0;
1011
+ producerCleanup?.();
1012
+ }
1013
+ _startProducer() {
1014
+ if (this._deps.length !== 0 || !this._fn || this._producerStarted) return;
1015
+ this._producerStarted = true;
1016
+ this._runFn();
1017
+ }
1018
+ _disconnectUpstream() {
1019
+ if (!this._connected) return;
1020
+ for (const unsub of this._upstreamUnsubs.splice(0)) {
1021
+ unsub();
1022
+ }
1023
+ this._connected = false;
1024
+ this._depDirtyMask.reset();
1025
+ this._depSettledMask.reset();
1026
+ this._depCompleteMask.reset();
1027
+ this._status = "disconnected";
1028
+ }
1029
+ };
1030
+ function node(depsOrFn, fnOrOpts, optsArg) {
1031
+ const deps = isNodeArray(depsOrFn) ? depsOrFn : [];
1032
+ const fn = typeof depsOrFn === "function" ? depsOrFn : typeof fnOrOpts === "function" ? fnOrOpts : void 0;
1033
+ let opts = {};
1034
+ if (isNodeArray(depsOrFn)) {
1035
+ opts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
1036
+ } else if (isNodeOptions(depsOrFn)) {
1037
+ opts = depsOrFn;
1038
+ } else {
1039
+ opts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};
1040
+ }
1041
+ return new NodeImpl(deps, fn, opts);
1042
+ }
1043
+
1044
+ // src/core/dynamic-node.ts
1045
+ function dynamicNode(fn, opts) {
1046
+ return new DynamicNodeImpl(fn, opts ?? {});
1047
+ }
1048
+ var DynamicNodeImpl = class {
1049
+ _optsName;
1050
+ _registryName;
1051
+ _describeKind;
1052
+ meta;
1053
+ _fn;
1054
+ _equals;
1055
+ _resubscribable;
1056
+ _resetOnTeardown;
1057
+ _autoComplete;
1058
+ _onMessage;
1059
+ _onResubscribe;
1060
+ /** @internal — read by {@link describeNode} for `accessHintForGuard`. */
1061
+ _guard;
1062
+ _lastMutation;
1063
+ _inspectorHook;
1064
+ // Sink tracking
1065
+ _sinkCount = 0;
1066
+ _singleDepSinkCount = 0;
1067
+ _singleDepSinks = /* @__PURE__ */ new WeakSet();
1068
+ // Actions object (for onMessage handler)
1069
+ _actions;
1070
+ _boundEmitToSinks;
1071
+ // Mutable state
1072
+ _cached;
1073
+ _status = "disconnected";
1074
+ _terminal = false;
1075
+ _connected = false;
1076
+ _rewiring = false;
1077
+ // re-entrancy guard
1078
+ // Dynamic deps tracking
1079
+ _deps = [];
1080
+ _depUnsubs = [];
1081
+ _depIndexMap = /* @__PURE__ */ new Map();
1082
+ // node → index in _deps
1083
+ _dirtyBits = /* @__PURE__ */ new Set();
1084
+ _settledBits = /* @__PURE__ */ new Set();
1085
+ _completeBits = /* @__PURE__ */ new Set();
1086
+ // Sinks
1087
+ _sinks = null;
1088
+ constructor(fn, opts) {
1089
+ this._fn = fn;
1090
+ this._optsName = opts.name;
1091
+ this._describeKind = opts.describeKind;
1092
+ this._equals = opts.equals ?? Object.is;
1093
+ this._resubscribable = opts.resubscribable ?? false;
1094
+ this._resetOnTeardown = opts.resetOnTeardown ?? false;
1095
+ this._autoComplete = opts.completeWhenDepsComplete ?? true;
1096
+ this._onMessage = opts.onMessage;
1097
+ this._onResubscribe = opts.onResubscribe;
1098
+ this._guard = opts.guard;
1099
+ this._inspectorHook = void 0;
1100
+ const meta = {};
1101
+ for (const [k, v] of Object.entries(opts.meta ?? {})) {
1102
+ meta[k] = node({
1103
+ initial: v,
1104
+ name: `${opts.name ?? "dynamicNode"}:meta:${k}`,
1105
+ describeKind: "state",
1106
+ ...opts.guard != null ? { guard: opts.guard } : {}
1107
+ });
1108
+ }
1109
+ Object.freeze(meta);
1110
+ this.meta = meta;
1111
+ const self = this;
1112
+ this._actions = {
1113
+ down(messages) {
1114
+ self._downInternal(messages);
1115
+ },
1116
+ emit(value) {
1117
+ self._emitAutoValue(value);
1118
+ },
1119
+ up(messages) {
1120
+ for (const dep of self._deps) {
1121
+ dep.up?.(messages, { internal: true });
1122
+ }
1123
+ }
1124
+ };
1125
+ this._boundEmitToSinks = this._emitToSinks.bind(this);
1126
+ }
1127
+ get name() {
1128
+ return this._registryName ?? this._optsName;
1129
+ }
1130
+ /** @internal */
1131
+ _assignRegistryName(localName) {
1132
+ if (this._optsName !== void 0 || this._registryName !== void 0) return;
1133
+ this._registryName = localName;
1134
+ }
1135
+ /**
1136
+ * @internal Attach/remove inspector hook for graph-level observability.
1137
+ * Returns a disposer that restores the previous hook.
1138
+ */
1139
+ _setInspectorHook(hook) {
1140
+ const prev = this._inspectorHook;
1141
+ this._inspectorHook = hook;
1142
+ return () => {
1143
+ if (this._inspectorHook === hook) {
1144
+ this._inspectorHook = prev;
1145
+ }
1146
+ };
1147
+ }
1148
+ get status() {
1149
+ return this._status;
1150
+ }
1151
+ get lastMutation() {
1152
+ return this._lastMutation;
1153
+ }
1154
+ /** Versioning not yet supported on DynamicNodeImpl. */
1155
+ get v() {
1156
+ return void 0;
1157
+ }
1158
+ hasGuard() {
1159
+ return this._guard != null;
1160
+ }
1161
+ allowsObserve(actor) {
1162
+ if (this._guard == null) return true;
1163
+ return this._guard(normalizeActor(actor), "observe");
1164
+ }
1165
+ get() {
1166
+ return this._cached;
1167
+ }
1168
+ down(messages, options) {
1169
+ if (messages.length === 0) return;
1170
+ if (!options?.internal && this._guard != null) {
1171
+ const actor = normalizeActor(options?.actor);
1172
+ const delivery = options?.delivery ?? "write";
1173
+ const action = delivery === "signal" ? "signal" : "write";
1174
+ if (!this._guard(actor, action)) {
1175
+ throw new GuardDenied({ actor, action, nodeName: this.name });
1176
+ }
1177
+ this._lastMutation = { actor, timestamp_ns: wallClockNs() };
1178
+ }
1179
+ this._downInternal(messages);
1180
+ }
1181
+ _downInternal(messages) {
1182
+ if (messages.length === 0) return;
1183
+ let sinkMessages = messages;
1184
+ if (this._terminal && !this._resubscribable) {
1185
+ const pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);
1186
+ if (pass.length === 0) return;
1187
+ sinkMessages = pass;
1188
+ }
1189
+ this._handleLocalLifecycle(sinkMessages);
1190
+ if (this._canSkipDirty()) {
1191
+ let hasPhase2 = false;
1192
+ for (let i = 0; i < sinkMessages.length; i++) {
1193
+ const t = sinkMessages[i][0];
1194
+ if (t === DATA || t === RESOLVED) {
1195
+ hasPhase2 = true;
1196
+ break;
1197
+ }
1198
+ }
1199
+ if (hasPhase2) {
1200
+ const filtered = [];
1201
+ for (let i = 0; i < sinkMessages.length; i++) {
1202
+ if (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);
1203
+ }
1204
+ if (filtered.length > 0) {
1205
+ emitWithBatch(this._boundEmitToSinks, filtered);
1206
+ }
1207
+ return;
1208
+ }
1209
+ }
1210
+ emitWithBatch(this._boundEmitToSinks, sinkMessages);
1211
+ }
1212
+ _canSkipDirty() {
1213
+ return this._sinkCount === 1 && this._singleDepSinkCount === 1;
1214
+ }
1215
+ subscribe(sink, hints) {
1216
+ if (hints?.actor != null && this._guard != null) {
1217
+ const actor = normalizeActor(hints.actor);
1218
+ if (!this._guard(actor, "observe")) {
1219
+ throw new GuardDenied({ actor, action: "observe", nodeName: this.name });
1220
+ }
1221
+ }
1222
+ if (this._terminal && this._resubscribable) {
1223
+ this._terminal = false;
1224
+ this._status = "disconnected";
1225
+ this._onResubscribe?.();
1226
+ }
1227
+ this._sinkCount += 1;
1228
+ if (hints?.singleDep) {
1229
+ this._singleDepSinkCount += 1;
1230
+ this._singleDepSinks.add(sink);
1231
+ }
1232
+ if (this._sinks == null) {
1233
+ this._sinks = sink;
1234
+ } else if (typeof this._sinks === "function") {
1235
+ this._sinks = /* @__PURE__ */ new Set([this._sinks, sink]);
1236
+ } else {
1237
+ this._sinks.add(sink);
1238
+ }
1239
+ if (!this._connected) {
1240
+ this._connect();
1241
+ }
1242
+ let removed = false;
1243
+ return () => {
1244
+ if (removed) return;
1245
+ removed = true;
1246
+ this._sinkCount -= 1;
1247
+ if (this._singleDepSinks.has(sink)) {
1248
+ this._singleDepSinkCount -= 1;
1249
+ this._singleDepSinks.delete(sink);
1250
+ }
1251
+ if (this._sinks == null) return;
1252
+ if (typeof this._sinks === "function") {
1253
+ if (this._sinks === sink) this._sinks = null;
1254
+ } else {
1255
+ this._sinks.delete(sink);
1256
+ if (this._sinks.size === 1) {
1257
+ const [only] = this._sinks;
1258
+ this._sinks = only;
1259
+ } else if (this._sinks.size === 0) {
1260
+ this._sinks = null;
1261
+ }
1262
+ }
1263
+ if (this._sinks == null) {
1264
+ this._disconnect();
1265
+ }
1266
+ };
1267
+ }
1268
+ up(messages, options) {
1269
+ if (this._deps.length === 0) return;
1270
+ if (!options?.internal && this._guard != null) {
1271
+ const actor = normalizeActor(options?.actor);
1272
+ if (!this._guard(actor, "write")) {
1273
+ throw new GuardDenied({ actor, action: "write", nodeName: this.name });
1274
+ }
1275
+ this._lastMutation = { actor, timestamp_ns: wallClockNs() };
1276
+ }
1277
+ for (const dep of this._deps) {
1278
+ dep.up?.(messages, options);
1279
+ }
1280
+ }
1281
+ unsubscribe() {
1282
+ this._disconnect();
1283
+ }
1284
+ // --- Private methods ---
1285
+ _emitToSinks(messages) {
1286
+ if (this._sinks == null) return;
1287
+ if (typeof this._sinks === "function") {
1288
+ this._sinks(messages);
1289
+ return;
1290
+ }
1291
+ const snapshot = [...this._sinks];
1292
+ for (const sink of snapshot) {
1293
+ sink(messages);
1294
+ }
1295
+ }
1296
+ _handleLocalLifecycle(messages) {
1297
+ for (const m of messages) {
1298
+ const t = m[0];
1299
+ if (t === DATA) this._cached = m[1];
1300
+ if (t === INVALIDATE) {
1301
+ this._cached = void 0;
1302
+ }
1303
+ if (t === DATA || t === RESOLVED) {
1304
+ this._status = "settled";
1305
+ } else if (t === DIRTY) {
1306
+ this._status = "dirty";
1307
+ } else if (t === COMPLETE) {
1308
+ this._status = "completed";
1309
+ this._terminal = true;
1310
+ } else if (t === ERROR) {
1311
+ this._status = "errored";
1312
+ this._terminal = true;
1313
+ }
1314
+ if (t === TEARDOWN) {
1315
+ if (this._resetOnTeardown) this._cached = void 0;
1316
+ try {
1317
+ this._propagateToMeta(t);
1318
+ } finally {
1319
+ this._disconnect();
1320
+ }
1321
+ }
1322
+ if (t !== TEARDOWN && propagatesToMeta(t)) {
1323
+ this._propagateToMeta(t);
1324
+ }
1325
+ }
1326
+ }
1327
+ /** Propagate a signal to all companion meta nodes (best-effort). */
1328
+ _propagateToMeta(t) {
1329
+ for (const metaNode of Object.values(this.meta)) {
1330
+ try {
1331
+ metaNode.down([[t]], { internal: true });
1332
+ } catch {
1333
+ }
1334
+ }
1335
+ }
1336
+ _emitAutoValue(value) {
1337
+ const wasDirty = this._status === "dirty";
1338
+ const unchanged = this._equals(this._cached, value);
1339
+ if (unchanged) {
1340
+ this._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);
1341
+ return;
1342
+ }
1343
+ this._cached = value;
1344
+ this._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);
1345
+ }
1346
+ _connect() {
1347
+ if (this._connected) return;
1348
+ this._connected = true;
1349
+ this._status = "settled";
1350
+ this._dirtyBits.clear();
1351
+ this._settledBits.clear();
1352
+ this._completeBits.clear();
1353
+ this._runFn();
1354
+ }
1355
+ _disconnect() {
1356
+ if (!this._connected) return;
1357
+ for (const unsub of this._depUnsubs) unsub();
1358
+ this._depUnsubs = [];
1359
+ this._deps = [];
1360
+ this._depIndexMap.clear();
1361
+ this._dirtyBits.clear();
1362
+ this._settledBits.clear();
1363
+ this._completeBits.clear();
1364
+ this._connected = false;
1365
+ this._status = "disconnected";
1366
+ }
1367
+ _runFn() {
1368
+ if (this._terminal && !this._resubscribable) return;
1369
+ if (this._rewiring) return;
1370
+ const trackedDeps = [];
1371
+ const trackedSet = /* @__PURE__ */ new Set();
1372
+ const get = (dep) => {
1373
+ if (!trackedSet.has(dep)) {
1374
+ trackedSet.add(dep);
1375
+ trackedDeps.push(dep);
1376
+ }
1377
+ return dep.get();
1378
+ };
1379
+ try {
1380
+ const depValues = [];
1381
+ for (const dep of this._deps) {
1382
+ depValues.push(dep.get());
1383
+ }
1384
+ this._inspectorHook?.({ kind: "run", depValues });
1385
+ const result = this._fn(get);
1386
+ this._rewire(trackedDeps);
1387
+ if (result === void 0) return;
1388
+ this._emitAutoValue(result);
1389
+ } catch (err) {
1390
+ this._downInternal([[ERROR, err]]);
1391
+ }
1392
+ }
1393
+ _rewire(newDeps) {
1394
+ this._rewiring = true;
1395
+ try {
1396
+ const oldMap = this._depIndexMap;
1397
+ const newMap = /* @__PURE__ */ new Map();
1398
+ const newUnsubs = [];
1399
+ for (let i = 0; i < newDeps.length; i++) {
1400
+ const dep = newDeps[i];
1401
+ newMap.set(dep, i);
1402
+ const oldIdx = oldMap.get(dep);
1403
+ if (oldIdx !== void 0) {
1404
+ newUnsubs.push(this._depUnsubs[oldIdx]);
1405
+ this._depUnsubs[oldIdx] = () => {
1406
+ };
1407
+ } else {
1408
+ const idx = i;
1409
+ const unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));
1410
+ newUnsubs.push(unsub);
1411
+ }
1412
+ }
1413
+ for (const [dep, oldIdx] of oldMap) {
1414
+ if (!newMap.has(dep)) {
1415
+ this._depUnsubs[oldIdx]();
1416
+ }
1417
+ }
1418
+ this._deps = newDeps;
1419
+ this._depUnsubs = newUnsubs;
1420
+ this._depIndexMap = newMap;
1421
+ this._dirtyBits.clear();
1422
+ this._settledBits.clear();
1423
+ const newCompleteBits = /* @__PURE__ */ new Set();
1424
+ for (const oldIdx of this._completeBits) {
1425
+ const dep = [...oldMap.entries()].find(([, idx]) => idx === oldIdx)?.[0];
1426
+ if (dep && newMap.has(dep)) {
1427
+ newCompleteBits.add(newMap.get(dep));
1428
+ }
1429
+ }
1430
+ this._completeBits = newCompleteBits;
1431
+ } finally {
1432
+ this._rewiring = false;
1433
+ }
1434
+ }
1435
+ _handleDepMessages(index, messages) {
1436
+ if (this._rewiring) return;
1437
+ for (const msg of messages) {
1438
+ this._inspectorHook?.({ kind: "dep_message", depIndex: index, message: msg });
1439
+ const t = msg[0];
1440
+ if (this._onMessage) {
1441
+ try {
1442
+ if (this._onMessage(msg, index, this._actions)) continue;
1443
+ } catch (err) {
1444
+ this._downInternal([[ERROR, err]]);
1445
+ return;
1446
+ }
1447
+ }
1448
+ if (t === DIRTY) {
1449
+ this._dirtyBits.add(index);
1450
+ this._settledBits.delete(index);
1451
+ if (this._dirtyBits.size === 1) {
1452
+ emitWithBatch(this._boundEmitToSinks, [[DIRTY]]);
1453
+ }
1454
+ continue;
1455
+ }
1456
+ if (t === DATA || t === RESOLVED) {
1457
+ if (!this._dirtyBits.has(index)) {
1458
+ this._dirtyBits.add(index);
1459
+ emitWithBatch(this._boundEmitToSinks, [[DIRTY]]);
1460
+ }
1461
+ this._settledBits.add(index);
1462
+ if (this._allDirtySettled()) {
1463
+ this._dirtyBits.clear();
1464
+ this._settledBits.clear();
1465
+ this._runFn();
1466
+ }
1467
+ continue;
1468
+ }
1469
+ if (t === COMPLETE) {
1470
+ this._completeBits.add(index);
1471
+ this._dirtyBits.delete(index);
1472
+ this._settledBits.delete(index);
1473
+ if (this._allDirtySettled()) {
1474
+ this._dirtyBits.clear();
1475
+ this._settledBits.clear();
1476
+ this._runFn();
1477
+ }
1478
+ if (this._autoComplete && this._completeBits.size >= this._deps.length && this._deps.length > 0) {
1479
+ this._downInternal([[COMPLETE]]);
1480
+ }
1481
+ continue;
1482
+ }
1483
+ if (t === ERROR) {
1484
+ this._downInternal([msg]);
1485
+ continue;
1486
+ }
1487
+ if (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {
1488
+ this._downInternal([msg]);
1489
+ continue;
1490
+ }
1491
+ this._downInternal([msg]);
1492
+ }
1493
+ }
1494
+ _allDirtySettled() {
1495
+ if (this._dirtyBits.size === 0) return false;
1496
+ for (const idx of this._dirtyBits) {
1497
+ if (!this._settledBits.has(idx)) return false;
1498
+ }
1499
+ return true;
1500
+ }
1501
+ };
1502
+
1503
+ // src/core/sugar.ts
1504
+ function state(initial, opts) {
1505
+ return node([], { ...opts, initial });
1506
+ }
1507
+ function producer(fn, opts) {
1508
+ return node(fn, { describeKind: "producer", ...opts });
1509
+ }
1510
+ function derived(deps, fn, opts) {
1511
+ return node(deps, fn, { describeKind: "derived", ...opts });
1512
+ }
1513
+ function effect(deps, fn) {
1514
+ return node(deps, fn, { describeKind: "effect" });
1515
+ }
1516
+ function pipe(source, ...ops) {
1517
+ let current = source;
1518
+ for (const op of ops) {
1519
+ current = op(current);
1520
+ }
1521
+ return current;
1522
+ }
1523
+
1524
+ export {
1525
+ __require,
1526
+ __export,
1527
+ __decoratorStart,
1528
+ __runInitializers,
1529
+ __decorateElement,
1530
+ DEFAULT_ACTOR,
1531
+ normalizeActor,
1532
+ DATA,
1533
+ DIRTY,
1534
+ RESOLVED,
1535
+ INVALIDATE,
1536
+ PAUSE,
1537
+ RESUME,
1538
+ TEARDOWN,
1539
+ COMPLETE,
1540
+ ERROR,
1541
+ knownMessageTypes,
1542
+ isKnownMessageType,
1543
+ messageTier,
1544
+ isPhase2Message,
1545
+ isTerminalMessage,
1546
+ propagatesToMeta,
1547
+ isBatching,
1548
+ batch,
1549
+ partitionForBatch,
1550
+ emitWithBatch,
1551
+ monotonicNs,
1552
+ wallClockNs,
1553
+ GuardDenied,
1554
+ policy,
1555
+ policyFromRules,
1556
+ accessHintForGuard,
1557
+ defaultHash,
1558
+ createVersioning,
1559
+ advanceVersion,
1560
+ isV1,
1561
+ NodeImpl,
1562
+ node,
1563
+ dynamicNode,
1564
+ DynamicNodeImpl,
1565
+ state,
1566
+ producer,
1567
+ derived,
1568
+ effect,
1569
+ pipe
1570
+ };
1571
+ //# sourceMappingURL=chunk-5X3LAO3B.js.map