@deviltea/widget-core 0.0.5 → 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.
package/dist/index.mjs CHANGED
@@ -1,18 +1,18 @@
1
- import { a as runRuntimeOperation, i as invokeListenerIsolated, n as createEventPrimitive, o as writeDeferringFlush, r as createTrackedSubscription, t as buildEventEmitter } from "./event-BMif_vRJ.mjs";
2
- import { a as createWidgetPlugin, c as readWidgetPluginDefinition, i as WIDGET_CONFIG_JSON_SCHEMA_DIALECT, l as createReadonlyMap, o as createWidgetValueContract, r as runtimeInternals, s as isCoreWidgetPlugin } from "./internals-L391flXY.mjs";
1
+ import { C as EMPTY_DIAGNOSTICS, S as runOutsideCallbacks, T as WidgetSystemRuntimeReentrancyError, _ as setIsolatedErrorHandler, a as throwClosedCallbackMember, b as createCallbackOwner, c as createTrackedSubscription, d as invokeListenerIsolated, f as isEngineStackOverflow, g as runRuntimeWrite, h as runRuntimeOperation, i as assertSyncValue, l as deliverWhenIdle, m as readUntracked, n as createEventPrimitive, o as throwClosedCollector, p as isRuntimeIdle, r as createMethodEmitFragment, s as createDistinctTrackedSubscription, u as endBatchDeferringFlush, v as writeDeferringFlush, w as WidgetSystemRuntimeDisposedError, x as createRuntimeContext, y as callbackScope } from "./event-Bk-mkL1E.mjs";
2
+ import { a as createWidgetPlugin, c as readWidgetPluginDefinition, i as WIDGET_CONFIG_JSON_SCHEMA_DIALECT, l as createReadonlyMap, o as createWidgetValueContract, r as runtimeInternals, s as isCoreWidgetPlugin } from "./internals-CVKUQDIN.mjs";
3
3
  import { a as readCompiledBlueprint, n as compiledDependencyBrand, r as isCompiledDependency, t as blueprintInternals } from "./contract-CRpMqCY2.mjs";
4
- import { computed, endBatch, signal, startBatch } from "alien-signals";
5
- //#region src/diagnostic.ts
6
- const EMPTY_DIAGNOSTICS = Object.freeze([]);
7
- var WidgetSystemRuntimeDisposedError = class extends Error {
8
- name = "WidgetSystemRuntimeDisposedError";
9
- code = "runtime-disposed";
10
- constructor(message = "The widget system runtime has been disposed.") {
11
- super(message);
12
- }
13
- };
14
- //#endregion
4
+ import { computed, endBatch, getActiveSub, setActiveSub, signal, startBatch } from "alien-signals";
15
5
  //#region src/json.ts
6
+ /**
7
+ * The maximum JSON nesting depth of authored source and SourcePatch operands: the number of containers
8
+ * (objects and arrays) a value may be nested inside, counting the value's own container. A value nested
9
+ * deeper is outside the JSON domain (`json-incompatible-value`, reason `max-depth-exceeded`) and is never
10
+ * descended into, so arbitrarily deep input yields a diagnostic or an operation failure instead of exhausting
11
+ * the call stack. A widget node nests three containers per tree level (node, `slots`, slot Array), so the
12
+ * limit allows widget trees about 85 levels deep. The value leaves a wide margin below the call-stack limit of
13
+ * Node 22/24 and of smaller-stack embedded engines, and is part of the public contract.
14
+ */
15
+ const MAX_JSON_DEPTH = 256;
16
16
  function jsonDiagnostic(path, reason) {
17
17
  return {
18
18
  code: "json-incompatible-value",
@@ -30,7 +30,12 @@ function accessDiagnostic(path) {
30
30
  message: "Authored source could not be safely inspected."
31
31
  };
32
32
  }
33
- function inspectJsonValueAt(value, path, active, diagnostics) {
33
+ /**
34
+ * `path` is one shared stack, pushed before and popped after each child visit; diagnostics copy it. With
35
+ * `firstOnly` the walk stops at the first diagnostic, so a caller that only needs to know whether (and where
36
+ * first) a value leaves the JSON domain never diagnoses the rest of it.
37
+ */
38
+ function inspectJsonValueAt(value, path, active, diagnostics, depth, firstOnly) {
34
39
  if (value === null || typeof value === "string" || typeof value === "boolean") return;
35
40
  if (typeof value === "number") {
36
41
  if (!Number.isFinite(value)) diagnostics.push(jsonDiagnostic(path, "non-finite-number"));
@@ -53,6 +58,10 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
53
58
  return;
54
59
  }
55
60
  if (typeof value !== "object") return;
61
+ if (depth >= 256) {
62
+ diagnostics.push(jsonDiagnostic(path, "max-depth-exceeded"));
63
+ return;
64
+ }
56
65
  let isArray;
57
66
  try {
58
67
  isArray = Array.isArray(value);
@@ -98,6 +107,7 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
98
107
  return;
99
108
  }
100
109
  for (const key of keys) {
110
+ if (firstOnly && diagnostics.length > 0) return;
101
111
  if (typeof key === "symbol") {
102
112
  diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
103
113
  continue;
@@ -107,6 +117,7 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
107
117
  diagnostics.push(jsonDiagnostic([...path, key], "array-extra-property"));
108
118
  }
109
119
  for (let index = 0; index < length; index++) {
120
+ if (firstOnly && diagnostics.length > 0) return;
110
121
  let descriptor;
111
122
  try {
112
123
  descriptor = Object.getOwnPropertyDescriptor(value, String(index));
@@ -122,11 +133,14 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
122
133
  diagnostics.push(jsonDiagnostic([...path, index], "accessor-property"));
123
134
  continue;
124
135
  }
125
- inspectJsonValueAt(descriptor.value, [...path, index], active, diagnostics);
136
+ path.push(index);
137
+ inspectJsonValueAt(descriptor.value, path, active, diagnostics, depth + 1, firstOnly);
138
+ path.pop();
126
139
  }
127
140
  return;
128
141
  }
129
142
  for (const key of keys) {
143
+ if (firstOnly && diagnostics.length > 0) return;
130
144
  if (typeof key === "symbol") {
131
145
  diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
132
146
  continue;
@@ -146,7 +160,9 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
146
160
  diagnostics.push(jsonDiagnostic([...path, key], "accessor-property"));
147
161
  continue;
148
162
  }
149
- inspectJsonValueAt(descriptor.value, [...path, key], active, diagnostics);
163
+ path.push(key);
164
+ inspectJsonValueAt(descriptor.value, path, active, diagnostics, depth + 1, firstOnly);
165
+ path.pop();
150
166
  }
151
167
  } finally {
152
168
  active.delete(value);
@@ -159,14 +175,53 @@ function inspectJsonValueAt(value, path, active, diagnostics) {
159
175
  */
160
176
  function inspectJsonValue(value) {
161
177
  const diagnostics = [];
162
- inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics);
178
+ inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics, 0, false);
163
179
  return {
164
180
  compatible: diagnostics.length === 0,
165
181
  diagnostics
166
182
  };
167
183
  }
184
+ /**
185
+ * The first diagnostic {@link inspectJsonValue} reports for `value`, found by the same walk, or `null` when
186
+ * `value` is inside the JSON domain. The walk stops there instead of diagnosing the rest of the value.
187
+ */
188
+ function findFirstJsonViolation(value) {
189
+ const diagnostics = [];
190
+ inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics, 0, true);
191
+ return diagnostics[0] ?? null;
192
+ }
193
+ const JSON_PARSE_PROVEN = Object.freeze({
194
+ compatible: true,
195
+ diagnostics: Object.freeze([])
196
+ });
197
+ /**
198
+ * {@link inspectJsonValue} for a value Core itself produced with `JSON.parse` (no reviver). Such a value
199
+ * is made only of plain objects, arrays, strings, booleans, `null` and numbers, so the only way it can be
200
+ * outside the JSON domain is a non-finite number (`JSON.parse('1e400')` is `Infinity`) or nesting deeper
201
+ * than {@link MAX_JSON_DEPTH}. A cheap iterative scan therefore stands in for the full descriptor-level
202
+ * inspection; as soon as it finds anything the scan cannot prove, the full inspection supplies the exact
203
+ * diagnostics.
204
+ */
205
+ function inspectParsedJsonValue(value) {
206
+ const pending = [value];
207
+ const depths = [0];
208
+ while (pending.length > 0) {
209
+ const current = pending.pop();
210
+ const depth = depths.pop();
211
+ if (typeof current === "number") {
212
+ if (!Number.isFinite(current)) return inspectJsonValue(value);
213
+ } else if (typeof current === "object" && current !== null) {
214
+ if (depth >= 256) return inspectJsonValue(value);
215
+ for (const child of Array.isArray(current) ? current : Object.values(current)) {
216
+ pending.push(child);
217
+ depths.push(depth + 1);
218
+ }
219
+ }
220
+ }
221
+ return JSON_PARSE_PROVEN;
222
+ }
168
223
  function isJsonValue(value) {
169
- return inspectJsonValue(value).compatible;
224
+ return findFirstJsonViolation(value) === null;
170
225
  }
171
226
  /**
172
227
  * SameValueZero: `+0` equals `-0` and `NaN` equals `NaN`. Used only for SourcePatch comparisons
@@ -209,10 +264,12 @@ function jsonEqual(left, right, seen = /* @__PURE__ */ new Set()) {
209
264
  //#region src/source-patch.ts
210
265
  const PATCH_ERROR_MESSAGES = {
211
266
  "invalid-path": "The SourcePath is malformed.",
267
+ "invalid-operation": "The SourcePatch operation is malformed.",
212
268
  "path-not-found": "The SourcePath does not identify an existing location.",
213
269
  "path-not-traversable": "The SourcePath passes through a non-traversable value.",
214
270
  "invalid-array-index": "The SourcePath contains an invalid Array index.",
215
271
  "invalid-move-target": "The move destination is invalid relative to its source.",
272
+ "max-depth-exceeded": "The SourcePatch path or the addressed value is nested deeper than the maximum JSON depth.",
216
273
  "test-failed": "The test operation did not match the addressed value.",
217
274
  "json-incompatible-value": "The SourcePatch operand is outside the JSON value domain.",
218
275
  "source-access-failed": "The source could not be inspected safely."
@@ -226,7 +283,19 @@ function failure(code, message = PATCH_ERROR_MESSAGES[code]) {
226
283
  }
227
284
  };
228
285
  }
286
+ /**
287
+ * The most segments a SourcePatch path may have: the longest source path of a widget node a Blueprint
288
+ * materializes. Recovery stops at a node nested inside `MAX_JSON_DEPTH` or more containers, and that node is
289
+ * three segments (`slots`, slot name, index) below a parent nested inside fewer, so its path has at most
290
+ * `MAX_JSON_DEPTH + 2` segments. Removing or replacing exactly that node must stay possible.
291
+ */
292
+ const MAX_PATH_SEGMENTS = 258;
229
293
  function parsePath(path) {
294
+ const parsed = parsePathSegments(path);
295
+ if (parsed.ok && parsed.value.segments.length > MAX_PATH_SEGMENTS) return failure("max-depth-exceeded");
296
+ return parsed;
297
+ }
298
+ function parsePathSegments(path) {
230
299
  if (typeof path === "string") {
231
300
  if (path === "") return {
232
301
  ok: true,
@@ -520,12 +589,13 @@ function copyValue(value, canonicalizeNegativeZero = false) {
520
589
  value
521
590
  };
522
591
  const seen = /* @__PURE__ */ new WeakMap();
523
- function clone(current) {
592
+ function clone(current, depth) {
524
593
  const previous = seen.get(current);
525
594
  if (previous !== void 0) return {
526
595
  ok: true,
527
596
  value: previous
528
597
  };
598
+ if (depth > 256) return failure("max-depth-exceeded");
529
599
  const result = createContainer(current);
530
600
  if (!result.ok) return result;
531
601
  seen.set(current, result.value);
@@ -544,7 +614,7 @@ function copyValue(value, canonicalizeNegativeZero = false) {
544
614
  if (child !== null && typeof child === "object") {
545
615
  const childKind = inspectStructuralContainer(child);
546
616
  if (!childKind.ok) return childKind;
547
- if (childKind.value !== "opaque") copied = clone(child);
617
+ if (childKind.value !== "opaque") copied = clone(child, depth + 1);
548
618
  }
549
619
  if (!copied.ok) return copied;
550
620
  const defined = define(result.value, key, {
@@ -555,22 +625,23 @@ function copyValue(value, canonicalizeNegativeZero = false) {
555
625
  }
556
626
  return result;
557
627
  }
558
- return clone(value);
628
+ return clone(value, 1);
559
629
  }
560
630
  function structurallyEqual(left, right) {
561
631
  const matched = /* @__PURE__ */ new WeakMap();
562
- function equal(currentLeft, currentRight) {
632
+ function equal(currentLeft, currentRight, depth) {
563
633
  if (sameValueZero(currentLeft, currentRight)) return true;
564
634
  if (typeof currentLeft !== "object" || currentLeft === null || typeof currentRight !== "object" || currentRight === null) return false;
565
635
  const leftKind = inspectStructuralContainer(currentLeft);
566
636
  const rightKind = inspectStructuralContainer(currentRight);
567
637
  if (!leftKind.ok || !rightKind.ok) return false;
568
638
  if (leftKind.value === "opaque" || rightKind.value === "opaque") return false;
639
+ if (depth > 256) return false;
569
640
  const previous = matched.get(currentLeft);
570
641
  if (previous !== void 0) return previous === currentRight;
571
642
  matched.set(currentLeft, currentRight);
572
643
  try {
573
- if (Object.getPrototypeOf(currentLeft) !== Object.getPrototypeOf(currentRight)) return false;
644
+ if (leftKind.value !== rightKind.value) return false;
574
645
  const leftKeys = Reflect.ownKeys(currentLeft);
575
646
  const rightKeys = Reflect.ownKeys(currentRight);
576
647
  if (leftKeys.length !== rightKeys.length) return false;
@@ -582,7 +653,7 @@ function structurallyEqual(left, right) {
582
653
  const leftData = "value" in leftDescriptor;
583
654
  if (leftData !== "value" in rightDescriptor) return false;
584
655
  if (leftData) {
585
- if (!equal(leftDescriptor.value, rightDescriptor.value)) return false;
656
+ if (!equal(leftDescriptor.value, rightDescriptor.value, depth + 1)) return false;
586
657
  } else if (leftDescriptor.get !== rightDescriptor.get || leftDescriptor.set !== rightDescriptor.set) return false;
587
658
  }
588
659
  return true;
@@ -590,7 +661,7 @@ function structurallyEqual(left, right) {
590
661
  return false;
591
662
  }
592
663
  }
593
- return equal(left, right);
664
+ return equal(left, right, 1);
594
665
  }
595
666
  function samePathSegment(left, right) {
596
667
  return String(left) === String(right);
@@ -605,24 +676,48 @@ function operationError(index, error) {
605
676
  return Object.freeze({
606
677
  code: error.code,
607
678
  operationIndex: index,
608
- message: error.message
679
+ message: error.message,
680
+ ...error.path === void 0 ? {} : { path: error.path },
681
+ ...error.reason === void 0 ? {} : { reason: error.reason }
609
682
  });
610
683
  }
684
+ /**
685
+ * `null` when `value` is inside Core's JSON domain; otherwise the failure locating the first offending part
686
+ * of the operand (the same facts the Blueprint reports for the same code).
687
+ */
688
+ function operandFailure(value) {
689
+ const first = findFirstJsonViolation(value);
690
+ if (first === null) return null;
691
+ return {
692
+ code: "json-incompatible-value",
693
+ message: PATCH_ERROR_MESSAGES["json-incompatible-value"],
694
+ path: Object.freeze([...first.path]),
695
+ ...first.code === "json-incompatible-value" ? { reason: first.reason } : {}
696
+ };
697
+ }
698
+ const PATCH_OPERATIONS = /* @__PURE__ */ new Set([
699
+ "add",
700
+ "remove",
701
+ "replace",
702
+ "move",
703
+ "copy",
704
+ "test"
705
+ ]);
611
706
  function applySourcePatch(source, patch) {
612
707
  if (!Array.isArray(patch)) return {
613
708
  ok: false,
614
709
  failure: operationError(0, {
615
- code: "invalid-path",
710
+ code: "invalid-operation",
616
711
  message: "SourcePatch must be an array."
617
712
  })
618
713
  };
619
714
  let working = source;
620
715
  for (let operationIndex = 0; operationIndex < patch.length; operationIndex++) {
621
716
  const operation = patch[operationIndex];
622
- if (typeof operation !== "object" || operation === null || !("op" in operation)) return {
717
+ if (typeof operation !== "object" || operation === null || !("op" in operation) || !PATCH_OPERATIONS.has(operation.op)) return {
623
718
  ok: false,
624
719
  failure: operationError(operationIndex, {
625
- code: "invalid-path",
720
+ code: "invalid-operation",
626
721
  message: "SourcePatch operation is malformed."
627
722
  })
628
723
  };
@@ -638,12 +733,10 @@ function applySourcePatch(source, patch) {
638
733
  case "add":
639
734
  case "replace": {
640
735
  const value = operation.value;
641
- if (!isJsonValue(value)) return {
736
+ const operandProblem = operandFailure(value);
737
+ if (operandProblem !== null) return {
642
738
  ok: false,
643
- failure: operationError(operationIndex, {
644
- code: "json-incompatible-value",
645
- message: PATCH_ERROR_MESSAGES["json-incompatible-value"]
646
- })
739
+ failure: operationError(operationIndex, operandProblem)
647
740
  };
648
741
  const copied = copyValue(value, true);
649
742
  if (!copied.ok) return {
@@ -666,12 +759,10 @@ function applySourcePatch(source, patch) {
666
759
  break;
667
760
  case "test": {
668
761
  const value = operation.value;
669
- if (!isJsonValue(value)) return {
762
+ const operandProblem = operandFailure(value);
763
+ if (operandProblem !== null) return {
670
764
  ok: false,
671
- failure: operationError(operationIndex, {
672
- code: "json-incompatible-value",
673
- message: PATCH_ERROR_MESSAGES["json-incompatible-value"]
674
- })
765
+ failure: operationError(operationIndex, operandProblem)
675
766
  };
676
767
  const actual = readAt(working, path);
677
768
  if (!actual.ok) return {
@@ -738,7 +829,7 @@ function applySourcePatch(source, patch) {
738
829
  default: return {
739
830
  ok: false,
740
831
  failure: operationError(operationIndex, {
741
- code: "invalid-path",
832
+ code: "invalid-operation",
742
833
  message: "SourcePatch operation is malformed."
743
834
  })
744
835
  };
@@ -808,14 +899,20 @@ function createWidgetDocument(options) {
808
899
  changed: false
809
900
  };
810
901
  const nextBlueprint = options.system.createBlueprint(result.value.source);
902
+ const previous = snapshot;
811
903
  blueprint = nextBlueprint;
812
904
  snapshot = Object.freeze({
813
905
  revision: snapshot.revision + 1,
814
906
  blueprint: nextBlueprint
815
907
  });
908
+ const committed = snapshot;
909
+ const commit = Object.freeze({
910
+ previous,
911
+ patch
912
+ });
816
913
  phase = "notifying";
817
914
  const audience = subscribers.slice();
818
- for (const subscriber of audience) invokeListenerIsolated(subscriber.listener, snapshot);
915
+ for (const subscriber of audience) invokeListenerIsolated(() => subscriber.listener(committed, commit), void 0);
819
916
  return {
820
917
  ok: true,
821
918
  changed: true
@@ -964,39 +1061,146 @@ function copyRecoveryValue(value) {
964
1061
  function diagnosticPath(path, key) {
965
1062
  return [...path, key];
966
1063
  }
1064
+ /** The own keys of an authored widget node; everything else cannot be carried by the separated representation. */
1065
+ const SOURCE_WIDGET_FIELDS = /* @__PURE__ */ new Set([
1066
+ "id",
1067
+ "type",
1068
+ "config",
1069
+ "slots",
1070
+ "meta"
1071
+ ]);
967
1072
  /**
968
1073
  * Projects canonical nested authored source into the explicit separated representation.
1074
+ *
1075
+ * The input is `unknown`: projection never throws on malformed input. Everything it cannot project
1076
+ * faithfully (a malformed shape, a duplicate id, a non-JSON `config`/`meta`, a cyclic or too deep tree, an
1077
+ * unrecognized field) is reported as a diagnostic located by its path in the input (`area: 'source'`), and
1078
+ * the unprojectable part is left out of the best-effort result. When `diagnostics` is empty,
1079
+ * `normalizeSeparatedWidgetSource(separated).source` is structurally equal to `source`.
1080
+ *
969
1081
  * Projection preserves nested slot order and emits flat data in deterministic depth-first order.
970
1082
  */
971
1083
  function separateWidgetSource(source) {
1084
+ const diagnostics = [];
972
1085
  const widgets = [];
973
- function projectNode(node) {
974
- const value = node;
975
- const id = value.id;
976
- const data = {
977
- id,
978
- type: value.type
979
- };
980
- if (Object.hasOwn(value, "config")) data.config = cloneJsonValue(value.config);
981
- widgets.push(Object.freeze(data));
982
- const structure = { id };
983
- if (Object.hasOwn(value, "slots")) {
984
- const slotsValue = value.slots;
985
- const slots = Object.create(null);
986
- const slotNames = ownStringKeys(slotsValue);
987
- if (slotNames === null) throw new TypeError("WidgetSource slots could not be inspected safely.");
988
- for (const slot of slotNames) {
989
- const children = slotsValue[slot];
990
- slots[slot] = Object.freeze(children.map(projectNode));
1086
+ const seenIds = /* @__PURE__ */ new Set();
1087
+ const activeNodes = /* @__PURE__ */ new Set();
1088
+ const addDiagnostic = (code, path, message, fields) => {
1089
+ diagnostics.push(freezeDiagnostic(code, {
1090
+ area: "source",
1091
+ path
1092
+ }, message, fields));
1093
+ };
1094
+ function readJsonField(node, key, path, reason) {
1095
+ const property = readDataProperty(node, key);
1096
+ if (!property.found) return { present: false };
1097
+ if (!property.accessible || !isJsonValue(property.value)) {
1098
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget "${key}" must be an accessible JSON value.`, { reason });
1099
+ return { present: false };
1100
+ }
1101
+ try {
1102
+ return {
1103
+ present: true,
1104
+ value: cloneJsonValue(property.value)
1105
+ };
1106
+ } catch {
1107
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget "${key}" must be an accessible JSON value.`, { reason });
1108
+ return { present: false };
1109
+ }
1110
+ }
1111
+ function projectNode(value, path) {
1112
+ if (!isPlainObject(value)) {
1113
+ addDiagnostic("invalid-separated-structure", path, "Widget source must be a plain object.", { reason: "invalid-node" });
1114
+ return null;
1115
+ }
1116
+ if (path.length >= 256) {
1117
+ addDiagnostic("invalid-separated-structure", path, `Widget source is nested deeper than the maximum supported depth (256).`, { reason: "max-depth-exceeded" });
1118
+ return null;
1119
+ }
1120
+ if (activeNodes.has(value)) {
1121
+ addDiagnostic("invalid-separated-structure", path, "Widget source contains a cyclic reference; the repeated node was omitted.", { reason: "invalid-node" });
1122
+ return null;
1123
+ }
1124
+ const idProperty = readDataProperty(value, "id");
1125
+ if (!idProperty.found || !idProperty.accessible || typeof idProperty.value !== "string") {
1126
+ addDiagnostic("invalid-separated-widget", diagnosticPath(path, "id"), "Widget source must have a string id.", { reason: "invalid-id" });
1127
+ return null;
1128
+ }
1129
+ const id = idProperty.value;
1130
+ activeNodes.add(value);
1131
+ try {
1132
+ const typeProperty = readDataProperty(value, "type");
1133
+ const hasType = typeProperty.found && typeProperty.accessible && typeof typeProperty.value === "string";
1134
+ if (!hasType) addDiagnostic("invalid-separated-widget", diagnosticPath(path, "type"), "Widget source must have a string type.", { reason: "invalid-type" });
1135
+ const duplicate = seenIds.has(id);
1136
+ if (duplicate) addDiagnostic("duplicate-widget-id", diagnosticPath(path, "id"), `Widget source id "${id}" occurs more than once.`, { widgetId: id });
1137
+ seenIds.add(id);
1138
+ let keys;
1139
+ try {
1140
+ keys = Reflect.ownKeys(value);
1141
+ } catch {
1142
+ keys = [];
1143
+ }
1144
+ for (const key of keys) if (!SOURCE_WIDGET_FIELDS.has(key)) addDiagnostic("invalid-separated-widget", diagnosticPath(path, key), `Widget field "${String(key)}" cannot be carried by the separated representation.`, { reason: "unexpected-field" });
1145
+ const config = readJsonField(value, "config", path, "invalid-config");
1146
+ const meta = readJsonField(value, "meta", path, "invalid-meta");
1147
+ if (hasType && !duplicate) {
1148
+ const data = {
1149
+ id,
1150
+ type: typeProperty.value
1151
+ };
1152
+ if (config.present) data.config = config.value;
1153
+ if (meta.present) data.meta = meta.value;
1154
+ widgets.push(Object.freeze(data));
1155
+ }
1156
+ const structure = { id };
1157
+ const slotsProperty = readDataProperty(value, "slots");
1158
+ const slotsPath = diagnosticPath(path, "slots");
1159
+ if (slotsProperty.found) {
1160
+ if (!slotsProperty.accessible || !isPlainObject(slotsProperty.value)) addDiagnostic("invalid-separated-structure", slotsPath, "Widget slots must be an accessible plain object.", { reason: "invalid-slots" });
1161
+ else {
1162
+ const slotNames = ownStringKeys(slotsProperty.value);
1163
+ if (slotNames === null) addDiagnostic("invalid-separated-structure", slotsPath, "Widget slots could not be inspected safely.", { reason: "invalid-slots" });
1164
+ else {
1165
+ const slots = Object.create(null);
1166
+ for (const slot of slotNames) {
1167
+ const slotPath = diagnosticPath(slotsPath, slot);
1168
+ const slotProperty = readDataProperty(slotsProperty.value, slot);
1169
+ const slotArray = readArrayInfo$1(slotProperty.value);
1170
+ if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
1171
+ addDiagnostic("invalid-separated-structure", slotPath, "Widget slot must be an Array.", { reason: "invalid-slot-children" });
1172
+ continue;
1173
+ }
1174
+ const children = [];
1175
+ const childArray = slotProperty.value;
1176
+ for (let index = 0; index < slotArray.length; index++) {
1177
+ const childPath = diagnosticPath(slotPath, index);
1178
+ const childProperty = readDataProperty(childArray, String(index));
1179
+ if (!childProperty.found || !childProperty.accessible) {
1180
+ addDiagnostic("invalid-separated-structure", childPath, "Widget slot child could not be inspected safely.", { reason: "invalid-slot-children" });
1181
+ continue;
1182
+ }
1183
+ const child = projectNode(childProperty.value, childPath);
1184
+ if (child !== null) children.push(child);
1185
+ }
1186
+ slots[slot] = Object.freeze(children);
1187
+ }
1188
+ structure.slots = slots;
1189
+ }
1190
+ }
991
1191
  }
992
- structure.slots = slots;
1192
+ return Object.freeze(structure);
1193
+ } finally {
1194
+ activeNodes.delete(value);
993
1195
  }
994
- return Object.freeze(structure);
995
1196
  }
996
- const structure = projectNode(source);
1197
+ const structure = projectNode(source, []);
997
1198
  return Object.freeze({
998
- structure,
999
- widgets: Object.freeze(widgets)
1199
+ separated: structure === null ? null : Object.freeze({
1200
+ structure,
1201
+ widgets: Object.freeze(widgets)
1202
+ }),
1203
+ diagnostics: Object.freeze(diagnostics)
1000
1204
  });
1001
1205
  }
1002
1206
  /**
@@ -1025,12 +1229,9 @@ function normalizeSeparatedWidgetSource(input) {
1025
1229
  if (envelope === null || !structureProperty.found || !structureProperty.accessible) addDiagnostic("invalid-separated-source", {
1026
1230
  area: "structure",
1027
1231
  path: []
1028
- }, " separated source must contain an accessible structure root.", { reason: "missing-structure" });
1232
+ }, "separated source must contain an accessible structure root.", { reason: "missing-structure" });
1029
1233
  const widgetsArray = readArrayInfo$1(widgetsProperty.value);
1030
- if (!widgetsProperty.found || !widgetsProperty.accessible || !widgetsArray.isArray || !widgetsArray.accessible) addDiagnostic("invalid-separated-source", {
1031
- area: "widgets",
1032
- index: 0
1033
- }, " separated source widgets must be an Array.", { reason: "invalid-widgets" });
1234
+ if (!widgetsProperty.found || !widgetsProperty.accessible || !widgetsArray.isArray || !widgetsArray.accessible) addDiagnostic("invalid-separated-source", { area: "widgets" }, "separated source widgets must be an Array.", { reason: "invalid-widgets" });
1034
1235
  if (widgetsArray.isArray && widgetsArray.accessible) {
1035
1236
  const widgets = widgetsProperty.value;
1036
1237
  for (let index = 0; index < widgetsArray.length; index++) {
@@ -1078,6 +1279,13 @@ function normalizeSeparatedWidgetSource(input) {
1078
1279
  }, "structure entry must be an object.", { reason: "invalid-node" });
1079
1280
  return value;
1080
1281
  }
1282
+ if (path.length >= 256) {
1283
+ addDiagnostic("invalid-separated-structure", {
1284
+ area: "structure",
1285
+ path
1286
+ }, `structure is nested deeper than the maximum supported depth (256); the node was omitted.`, { reason: "max-depth-exceeded" });
1287
+ return Object.create(null);
1288
+ }
1081
1289
  const objectValue = value;
1082
1290
  if (activeStructureNodes.has(objectValue)) {
1083
1291
  addDiagnostic("invalid-separated-structure", {
@@ -1126,6 +1334,13 @@ function normalizeSeparatedWidgetSource(input) {
1126
1334
  index: data.index,
1127
1335
  path: ["config"]
1128
1336
  }, "flat Widget data config could not be inspected safely.", { reason: "invalid-entry" });
1337
+ const metaProperty = readDataProperty(data.value, "meta");
1338
+ if (metaProperty.found && metaProperty.accessible) output.meta = copyRecoveryValue(metaProperty.value);
1339
+ else if (metaProperty.found && !metaProperty.accessible) addDiagnostic("invalid-separated-widget", {
1340
+ area: "widgets",
1341
+ index: data.index,
1342
+ path: ["meta"]
1343
+ }, "flat Widget data meta could not be inspected safely.", { reason: "invalid-entry" });
1129
1344
  }
1130
1345
  }
1131
1346
  const slotsProperty = readDataProperty(value, "slots");
@@ -1202,10 +1417,18 @@ function freezeArray(value) {
1202
1417
  function freezeObject(value) {
1203
1418
  if (typeof value === "object" && value !== null) Object.freeze(value);
1204
1419
  }
1420
+ /**
1421
+ * `related` arrays this module has already frozen together with their entries. Diagnostics may share one
1422
+ * `related` array (every diagnostic of one dependency cycle does), and walking a shared array once per
1423
+ * diagnostic is quadratic in the cycle length. An array frozen by someone else is not enough to skip the
1424
+ * walk: its entries may still be unfrozen.
1425
+ */
1426
+ const deeplyFrozenRelated = /* @__PURE__ */ new WeakSet();
1205
1427
  function freezeRelated(related) {
1206
- if (!Array.isArray(related)) return;
1428
+ if (!Array.isArray(related) || deeplyFrozenRelated.has(related)) return;
1207
1429
  for (const item of related) freezeObject(item);
1208
1430
  Object.freeze(related);
1431
+ deeplyFrozenRelated.add(related);
1209
1432
  }
1210
1433
  function freezeDependency(dependency) {
1211
1434
  if (typeof dependency !== "object" || dependency === null) return;
@@ -1214,7 +1437,17 @@ function freezeDependency(dependency) {
1214
1437
  freezeObject(record.operation);
1215
1438
  Object.freeze(dependency);
1216
1439
  }
1217
- /** Freeze the framework-owned diagnostic record without executing or freezing arbitrary payload objects. */
1440
+ /**
1441
+ * Freeze the framework-owned diagnostic record without executing or freezing arbitrary payload objects.
1442
+ *
1443
+ * A diagnostic's `cause` is not walked again. Only a wrapped dependency failure carries one, and its cause
1444
+ * is always a diagnostic of the dependency's own finalized snapshot (`wrapTargetFailure` in `./deps`), which
1445
+ * was deep-frozen when that snapshot was created: every State, Property and Method snapshot passes through
1446
+ * {@link freezeDiagnosticSnapshot}. Diagnostic records are only ever created and frozen here, and a record
1447
+ * is frozen after its parts, so a frozen cause is a deep-frozen cause. Re-walking it on every wrap cost
1448
+ * O(depth) per dependent and recursed once per level of a failing dependency chain (quadratic work, and a
1449
+ * stack overflow for a long chain).
1450
+ */
1218
1451
  function deepFreezeDiagnostic(diagnostic) {
1219
1452
  if (typeof diagnostic !== "object" || diagnostic === null) return diagnostic;
1220
1453
  const record = diagnostic;
@@ -1222,8 +1455,7 @@ function deepFreezeDiagnostic(diagnostic) {
1222
1455
  freezeArray(record.path);
1223
1456
  freezeRelated(record.related);
1224
1457
  freezeDependency(record.dependency);
1225
- if (record.cause !== void 0) deepFreezeDiagnostic(record.cause);
1226
- Object.freeze(diagnostic);
1458
+ Object.freeze(record);
1227
1459
  return diagnostic;
1228
1460
  }
1229
1461
  function freezeDiagnosticSnapshot(diagnostics) {
@@ -1399,9 +1631,9 @@ function buildWidgetDiagnosticSnapshot(entry) {
1399
1631
  /**
1400
1632
  * Builds the live-gated `getDiagnostics`/`subscribeDiagnostics` pair one `RuntimeWidget` exposes, composing
1401
1633
  * {@link buildWidgetDiagnosticSnapshot} the same way {@link createRuntimeAggregate} composes it for every
1402
- * widget at the Runtime level.
1634
+ * widget at the Runtime level. `widgetId` names the widget in the report of the subscription limit.
1403
1635
  */
1404
- function createRuntimeWidgetDiagnosticsAggregate(context, entry) {
1636
+ function createRuntimeWidgetDiagnosticsAggregate(context, entry, widgetId) {
1405
1637
  const snapshot = () => buildWidgetDiagnosticSnapshot(entry);
1406
1638
  return {
1407
1639
  getDiagnostics() {
@@ -1410,21 +1642,77 @@ function createRuntimeWidgetDiagnosticsAggregate(context, entry) {
1410
1642
  },
1411
1643
  subscribeDiagnostics(listener) {
1412
1644
  context.assertActive();
1413
- return createTrackedSubscription(context, snapshot, listener);
1645
+ return createTrackedSubscription(context, snapshot, listener, "the diagnostics of widget", widgetId);
1414
1646
  }
1415
1647
  };
1416
1648
  }
1649
+ /** Index of the first element of the ascending `positions` that is `>= position`. */
1650
+ function lowerBound(positions, position) {
1651
+ let low = 0;
1652
+ let high = positions.length;
1653
+ while (low < high) {
1654
+ const middle = low + high >>> 1;
1655
+ if (positions[middle] < position) low = middle + 1;
1656
+ else high = middle;
1657
+ }
1658
+ return low;
1659
+ }
1660
+ /**
1661
+ * Builds the Runtime-level aggregate. Created before the primitives (they need {@link
1662
+ * RuntimeAggregate.commitHookFor}); `registry` is only read once a snapshot is requested.
1663
+ */
1417
1664
  function createRuntimeAggregate(context, compiled, registry, runtimeLevelDiagnostics) {
1418
- let previousChildren;
1419
- let previousSnapshot;
1420
- const snapshot = () => {
1421
- const children = compiled.semanticOrder.map((nodeId) => registry.get(nodeId)).filter((entry) => entry !== void 0).map((entry) => buildWidgetDiagnosticSnapshot(entry));
1422
- if (previousSnapshot !== void 0 && previousChildren !== void 0 && previousChildren.length === children.length && previousChildren.every((child, index) => child === children[index])) return previousSnapshot;
1665
+ const { semanticOrder } = compiled;
1666
+ const positionByNodeId = new Int32Array(compiled.nodes.length).fill(-1);
1667
+ for (let position = 0; position < semanticOrder.length; position++) positionByNodeId[semanticOrder[position]] = position;
1668
+ const widgetSnapshots = Array.from({ length: semanticOrder.length }).fill(EMPTY_DIAGNOSTICS);
1669
+ const nonEmptyPositions = [];
1670
+ let dirtyPositions = [];
1671
+ const isDirty = new Uint8Array(semanticOrder.length);
1672
+ let needsFullScan = true;
1673
+ let cached = null;
1674
+ let revision = 0;
1675
+ const revisionSignal = signal(revision);
1676
+ function markDirty(position) {
1677
+ if (isDirty[position] === 1) return;
1678
+ isDirty[position] = 1;
1679
+ dirtyPositions.push(position);
1680
+ }
1681
+ /** Re-aggregates one widget; returns whether its snapshot identity changed. */
1682
+ function refreshWidget(position) {
1683
+ const entry = registry.get(semanticOrder[position]);
1684
+ const next = entry === void 0 ? EMPTY_DIAGNOSTICS : buildWidgetDiagnosticSnapshot(entry);
1685
+ const previous = widgetSnapshots[position];
1686
+ if (next === previous) return false;
1687
+ widgetSnapshots[position] = next;
1688
+ if (previous.length === 0 !== (next.length === 0)) {
1689
+ const index = lowerBound(nonEmptyPositions, position);
1690
+ if (next.length === 0) nonEmptyPositions.splice(index, 1);
1691
+ else nonEmptyPositions.splice(index, 0, position);
1692
+ }
1693
+ return true;
1694
+ }
1695
+ function refreshDirtyWidgets() {
1696
+ let changed = false;
1697
+ if (needsFullScan) {
1698
+ needsFullScan = false;
1699
+ for (let position = 0; position < semanticOrder.length; position++) changed = refreshWidget(position) || changed;
1700
+ } else for (const position of dirtyPositions) changed = refreshWidget(position) || changed;
1701
+ for (const position of dirtyPositions) isDirty[position] = 0;
1702
+ dirtyPositions = [];
1703
+ return changed;
1704
+ }
1705
+ function compose() {
1706
+ if (nonEmptyPositions.length === 0) return runtimeLevelDiagnostics.length === 0 ? EMPTY_DIAGNOSTICS : runtimeLevelDiagnostics;
1423
1707
  const result = [...runtimeLevelDiagnostics];
1424
- for (const child of children) result.push(...child);
1425
- previousChildren = children;
1426
- previousSnapshot = toDiagnosticSnapshot(result);
1427
- return previousSnapshot;
1708
+ for (const position of nonEmptyPositions) for (const diagnostic of widgetSnapshots[position]) result.push(diagnostic);
1709
+ return toDiagnosticSnapshot(result);
1710
+ }
1711
+ const snapshot = () => {
1712
+ revisionSignal();
1713
+ if (cached !== null && !needsFullScan && dirtyPositions.length === 0) return cached;
1714
+ if (readUntracked(refreshDirtyWidgets) || cached === null) cached = compose();
1715
+ return cached;
1428
1716
  };
1429
1717
  return {
1430
1718
  getDiagnostics() {
@@ -1433,7 +1721,14 @@ function createRuntimeAggregate(context, compiled, registry, runtimeLevelDiagnos
1433
1721
  },
1434
1722
  subscribeDiagnostics(listener) {
1435
1723
  context.assertActive();
1436
- return createTrackedSubscription(context, snapshot, listener);
1724
+ return createDistinctTrackedSubscription(context, snapshot, listener, readUntracked(snapshot));
1725
+ },
1726
+ commitHookFor(nodeId) {
1727
+ const position = positionByNodeId[nodeId] ?? -1;
1728
+ return () => {
1729
+ if (position !== -1) markDirty(position);
1730
+ revisionSignal(++revision);
1731
+ };
1437
1732
  }
1438
1733
  };
1439
1734
  }
@@ -1451,65 +1746,58 @@ function buildBlueprintView(blueprint) {
1451
1746
  return Object.freeze(view);
1452
1747
  }
1453
1748
  //#endregion
1454
- //#region src/runtime/context.ts
1455
- function createRuntimeContext() {
1456
- let disposed = false;
1457
- let activeCollector = null;
1458
- const owned = /* @__PURE__ */ new Set();
1459
- function assertActive() {
1460
- if (disposed) throw new WidgetSystemRuntimeDisposedError();
1461
- }
1749
+ //#region src/runtime/collector.ts
1750
+ function createOperationCollector() {
1751
+ let entries = null;
1752
+ let seenAnchorsByScope = null;
1753
+ let closed = false;
1462
1754
  return {
1463
- isDisposed: () => disposed,
1464
- assertActive,
1465
- withActiveCollector(collector, fn) {
1466
- const previous = activeCollector;
1467
- activeCollector = collector;
1468
- try {
1469
- return fn();
1470
- } finally {
1471
- activeCollector = previous;
1755
+ addDiagnostic(input) {
1756
+ if (closed) throwClosedCollector("addDiagnostic");
1757
+ (entries ??= []).push({
1758
+ kind: "relative",
1759
+ input
1760
+ });
1761
+ },
1762
+ addFinalizedDiagnostic(diagnostic, dedupe) {
1763
+ if (dedupe !== void 0) {
1764
+ seenAnchorsByScope ??= /* @__PURE__ */ new Map();
1765
+ let seenAnchors = seenAnchorsByScope.get(dedupe.scope);
1766
+ if (seenAnchors === void 0) {
1767
+ seenAnchors = /* @__PURE__ */ new Set();
1768
+ seenAnchorsByScope.set(dedupe.scope, seenAnchors);
1769
+ }
1770
+ if (seenAnchors.has(dedupe.anchor)) return;
1771
+ seenAnchors.add(dedupe.anchor);
1472
1772
  }
1773
+ (entries ??= []).push({
1774
+ kind: "final",
1775
+ diagnostic
1776
+ });
1473
1777
  },
1474
- getActiveCollector: () => activeCollector,
1475
- registerSubscription(rawDispose) {
1476
- let unsubscribed = false;
1477
- const handle = () => {
1478
- if (unsubscribed) return;
1479
- unsubscribed = true;
1480
- owned.delete(handle);
1481
- rawDispose();
1482
- };
1483
- owned.add(handle);
1484
- return handle;
1778
+ hasAnyDiagnostic() {
1779
+ if (closed) throwClosedCollector("hasAnyDiagnostic");
1780
+ return entries !== null;
1781
+ },
1782
+ finalize(toFinalDiagnostic) {
1783
+ if (entries === null) return EMPTY_DIAGNOSTICS;
1784
+ return freezeDiagnosticSnapshot(entries.map((entry) => entry.kind === "relative" ? toFinalDiagnostic(entry.input) : entry.diagnostic));
1485
1785
  },
1486
- dispose() {
1487
- if (disposed) return;
1488
- disposed = true;
1489
- for (const handle of [...owned]) handle();
1490
- owned.clear();
1786
+ close() {
1787
+ closed = true;
1491
1788
  }
1492
1789
  };
1493
1790
  }
1494
1791
  //#endregion
1495
- //#region src/runtime/sync.ts
1792
+ //#region src/runtime/deps.ts
1496
1793
  /**
1497
- * Synchronous semantic-boundary guard.
1498
- *
1499
- * Normative source: diagnostic #10 amendment "synchronous core boundary and future async seams" /
1500
- * consolidated handoff §16: a semantic callback returning a thenable is an implementation-contract
1501
- * violation, not a Blueprint/Runtime Diagnostic and not an `ExecutionResult.failure`, so it throws.
1502
- *
1503
- * `PromiseLike` is a structural (duck-typed) contract, not a nominal one, and its `then` method may
1504
- * live on an object *or* on a callable (a function value with a `.then` property is still thenable).
1505
- * Checking `typeof value === 'object'` alone misses that callable case, so both representations are
1506
- * treated as thenable candidates before inspecting `.then`.
1794
+ * The guard every materialized callable runs before anything else: disposal first (the established
1795
+ * post-dispose error surface), then the callback-context lifetime.
1507
1796
  */
1508
- function assertSyncValue(value, description) {
1509
- if ((typeof value === "object" && value !== null || typeof value === "function") && "then" in value && typeof value.then === "function") throw new TypeError(`${description} returned a thenable. The widget-core semantic boundary is synchronous only.`);
1797
+ function assertCallableOpen(params) {
1798
+ params.context.assertActive();
1799
+ if (callbackScope.owner !== params.owner) throwClosedCallbackMember("deps");
1510
1800
  }
1511
- //#endregion
1512
- //#region src/runtime/deps.ts
1513
1801
  function consumerDependencyDiagnostic(params, dependency, message, received, related, cause) {
1514
1802
  const base = {
1515
1803
  widgetId: params.ownerWidgetId,
@@ -1523,7 +1811,7 @@ function consumerDependencyDiagnostic(params, dependency, message, received, rel
1523
1811
  return params.consumer === "property" ? buildPropertyDependencyDiagnostic(base) : buildMethodDependencyDiagnostic(base);
1524
1812
  }
1525
1813
  function reportDependencyDiagnostic(params, diagnostic, dedupe) {
1526
- params.context.getActiveCollector()?.addFinalizedDiagnostic(diagnostic, dedupe);
1814
+ params.owner.sink?.addFinalizedDiagnostic(diagnostic, dedupe);
1527
1815
  }
1528
1816
  /**
1529
1817
  * Per-dependency-leaf unique id, assigned once when a leaf's callable is materialized and closed over
@@ -1561,20 +1849,29 @@ function dependencyDedupeDescriptor(leafId, failureAnchor) {
1561
1849
  * is captured as `unknown` and passed through the sync-boundary guard *before* being interpreted as a
1562
1850
  * boolean — a `Promise.resolve(false)` escape hatch is truthy and would otherwise make a rejection look
1563
1851
  * like an accepted refinement.
1852
+ *
1853
+ * A refinement owns no dependency or `emit` callables, so no callback is open while it runs (see
1854
+ * `callbackScope`): not even the consumer whose dependency read invoked it.
1564
1855
  */
1565
1856
  function applyRefinements(value, refinements) {
1566
- for (const refine of refinements) {
1567
- const accepted = refine(value);
1568
- assertSyncValue(accepted, "A dependency .validate() refinement");
1569
- if (!accepted) return {
1570
- ok: false,
1571
- received: value
1857
+ const previousOwner = callbackScope.owner;
1858
+ callbackScope.owner = null;
1859
+ try {
1860
+ for (const refine of refinements) {
1861
+ const accepted = refine(value);
1862
+ assertSyncValue(accepted, "A dependency .validate() refinement");
1863
+ if (!accepted) return {
1864
+ ok: false,
1865
+ received: value
1866
+ };
1867
+ }
1868
+ return {
1869
+ ok: true,
1870
+ value
1572
1871
  };
1872
+ } finally {
1873
+ callbackScope.owner = previousOwner;
1573
1874
  }
1574
- return {
1575
- ok: true,
1576
- value
1577
- };
1578
1875
  }
1579
1876
  function locationOf(operation, widgetId) {
1580
1877
  switch (operation.type) {
@@ -1601,21 +1898,30 @@ function resolveTargetWidgetId(nodes, nodeId) {
1601
1898
  if (node === void 0 || !node.resolved) throw new Error(`widget-core: internal error — dependency target node ${nodeId} is not a resolved node.`);
1602
1899
  return node.id;
1603
1900
  }
1604
- function materializeAbsentLeaf(operation) {
1901
+ function materializeAbsentLeaf(operation, params) {
1605
1902
  switch (operation.type) {
1606
- case "state-set": return (candidate) => ({
1607
- ok: true,
1608
- value: candidate
1609
- });
1610
- case "method-invoke": return (..._args) => ({
1611
- ok: true,
1612
- value: null
1613
- });
1903
+ case "state-set": return (candidate) => {
1904
+ assertCallableOpen(params);
1905
+ return {
1906
+ ok: true,
1907
+ value: candidate
1908
+ };
1909
+ };
1910
+ case "method-invoke": return (..._args) => {
1911
+ assertCallableOpen(params);
1912
+ return {
1913
+ ok: true,
1914
+ value: null
1915
+ };
1916
+ };
1614
1917
  case "state-get":
1615
- case "property-get": return () => ({
1616
- ok: true,
1617
- value: null
1618
- });
1918
+ case "property-get": return () => {
1919
+ assertCallableOpen(params);
1920
+ return {
1921
+ ok: true,
1922
+ value: null
1923
+ };
1924
+ };
1619
1925
  }
1620
1926
  }
1621
1927
  function missingRegistryEntry(targetNodeId) {
@@ -1636,25 +1942,35 @@ function materializeResolvedLeaf(leaf, params) {
1636
1942
  const related = locationOf(operation, resolveTargetWidgetId(params.nodes, leaf.targetNodeId));
1637
1943
  const leafId = nextLeafId++;
1638
1944
  switch (operation.type) {
1639
- case "state-get": return () => {
1640
- const target = resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1641
- if (target === void 0) throw new Error(`widget-core: internal error — resolved state-get target "${operation.key}" is missing.`);
1642
- const refined = applyRefinements(target.internal.get(), leaf.refinements);
1643
- if (!refined.ok) {
1644
- const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
1645
- const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
1646
- reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
1945
+ case "state-get": {
1946
+ let target;
1947
+ return () => {
1948
+ assertCallableOpen(params);
1949
+ target ??= resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1950
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved state-get target "${operation.key}" is missing.`);
1951
+ const raw = target.internal.get();
1952
+ if (leaf.refinements.length === 0) return {
1953
+ ok: true,
1954
+ value: raw
1955
+ };
1956
+ const refined = applyRefinements(raw, leaf.refinements);
1957
+ if (!refined.ok) {
1958
+ const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
1959
+ const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
1960
+ reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
1961
+ return {
1962
+ ok: false,
1963
+ failure: { diagnostics }
1964
+ };
1965
+ }
1647
1966
  return {
1648
- ok: false,
1649
- failure: { diagnostics }
1967
+ ok: true,
1968
+ value: refined.value
1650
1969
  };
1651
- }
1652
- return {
1653
- ok: true,
1654
- value: refined.value
1655
1970
  };
1656
- };
1971
+ }
1657
1972
  case "state-set": return (candidate) => {
1973
+ assertCallableOpen(params);
1658
1974
  const target = resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1659
1975
  if (target === void 0) throw new Error(`widget-core: internal error — resolved state-set target "${operation.key}" is missing.`);
1660
1976
  const result = target.internal.attemptSet(candidate);
@@ -1667,30 +1983,40 @@ function materializeResolvedLeaf(leaf, params) {
1667
1983
  failure: { diagnostics: wrapTargetFailure(params, reference, result.failure.diagnostics, related, leafId) }
1668
1984
  };
1669
1985
  };
1670
- case "property-get": return () => {
1671
- const target = resolveEntry(params, leaf.targetNodeId).properties.get(operation.name);
1672
- if (target === void 0) throw new Error(`widget-core: internal error — resolved property-get target "${operation.name}" is missing.`);
1673
- const targetResult = target.internal.getResult();
1674
- if (!targetResult.ok) return {
1675
- ok: false,
1676
- failure: { diagnostics: wrapTargetFailure(params, reference, targetResult.failure.diagnostics, related, leafId) }
1677
- };
1678
- const refined = applyRefinements(targetResult.value, leaf.refinements);
1679
- if (!refined.ok) {
1680
- const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
1681
- const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
1682
- reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
1683
- return {
1986
+ case "property-get": {
1987
+ let target;
1988
+ const fromProperty = params.consumer === "property";
1989
+ return () => {
1990
+ assertCallableOpen(params);
1991
+ target ??= resolveEntry(params, leaf.targetNodeId).properties.get(operation.name);
1992
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved property-get target "${operation.name}" is missing.`);
1993
+ const targetResult = fromProperty ? target.internal.readFromProperty() : target.internal.getResult();
1994
+ if (!targetResult.ok) return {
1684
1995
  ok: false,
1685
- failure: { diagnostics }
1996
+ failure: { diagnostics: wrapTargetFailure(params, reference, targetResult.failure.diagnostics, related, leafId) }
1997
+ };
1998
+ if (leaf.refinements.length === 0) return {
1999
+ ok: true,
2000
+ value: targetResult.value
2001
+ };
2002
+ const refined = applyRefinements(targetResult.value, leaf.refinements);
2003
+ if (!refined.ok) {
2004
+ const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
2005
+ const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
2006
+ reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
2007
+ return {
2008
+ ok: false,
2009
+ failure: { diagnostics }
2010
+ };
2011
+ }
2012
+ return {
2013
+ ok: true,
2014
+ value: refined.value
1686
2015
  };
1687
- }
1688
- return {
1689
- ok: true,
1690
- value: refined.value
1691
2016
  };
1692
- };
2017
+ }
1693
2018
  case "method-invoke": return (...args) => {
2019
+ assertCallableOpen(params);
1694
2020
  const target = resolveEntry(params, leaf.targetNodeId).methods.get(operation.name);
1695
2021
  if (target === void 0) throw new Error(`widget-core: internal error — resolved method-invoke target "${operation.name}" is missing.`);
1696
2022
  const targetResult = target.public(...args);
@@ -1730,7 +2056,7 @@ function wrapTargetFailure(params, reference, targetDiagnostics, related, leafId
1730
2056
  return wrapped;
1731
2057
  }
1732
2058
  function materializeLeaf(leaf, params) {
1733
- if (leaf.status === "absent") return materializeAbsentLeaf(leaf.reference.operation);
2059
+ if (leaf.status === "absent") return materializeAbsentLeaf(leaf.reference.operation, params);
1734
2060
  if (leaf.status === "invalid") throw new Error("widget-core: internal error — an invalid dependency reached Runtime materialization; Runtime must only be created from a valid Blueprint.");
1735
2061
  return materializeResolvedLeaf(leaf, params);
1736
2062
  }
@@ -1742,49 +2068,21 @@ function materializeDependencyTree(tree, params) {
1742
2068
  return result;
1743
2069
  }
1744
2070
  //#endregion
1745
- //#region src/runtime/collector.ts
1746
- function createOperationCollector() {
1747
- const entries = [];
1748
- const seenAnchorsByScope = /* @__PURE__ */ new Map();
1749
- return {
1750
- addDiagnostic(input) {
1751
- entries.push({
1752
- kind: "relative",
1753
- input
1754
- });
1755
- },
1756
- addFinalizedDiagnostic(diagnostic, dedupe) {
1757
- if (dedupe !== void 0) {
1758
- let seenAnchors = seenAnchorsByScope.get(dedupe.scope);
1759
- if (seenAnchors === void 0) {
1760
- seenAnchors = /* @__PURE__ */ new Set();
1761
- seenAnchorsByScope.set(dedupe.scope, seenAnchors);
1762
- }
1763
- if (seenAnchors.has(dedupe.anchor)) return;
1764
- seenAnchors.add(dedupe.anchor);
1765
- }
1766
- entries.push({
1767
- kind: "final",
1768
- diagnostic
1769
- });
1770
- },
1771
- hasAnyDiagnostic() {
1772
- return entries.length > 0;
1773
- },
1774
- finalize(toFinalDiagnostic) {
1775
- return freezeDiagnosticSnapshot(entries.map((entry) => entry.kind === "relative" ? toFinalDiagnostic(entry.input) : entry.diagnostic));
1776
- }
1777
- };
1778
- }
1779
- //#endregion
1780
2071
  //#region src/runtime/method.ts
1781
2072
  function createMethodPrimitive(context, params) {
1782
2073
  const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
1783
- function invoke(...args) {
1784
- context.assertActive();
1785
- return runRuntimeOperation(() => invokeWithinOperation(...args));
2074
+ let committedDiagnostics = EMPTY_DIAGNOSTICS;
2075
+ function commitDiagnostics(next) {
2076
+ if (next === committedDiagnostics) return;
2077
+ committedDiagnostics = next;
2078
+ writeDeferringFlush(() => {
2079
+ diagnosticsSignal(next);
2080
+ params.onDiagnosticsCommitted();
2081
+ });
1786
2082
  }
1787
- function invokeWithinOperation(...args) {
2083
+ let deps;
2084
+ let emitFragment;
2085
+ function invokeWithinOperation(args) {
1788
2086
  startBatch();
1789
2087
  try {
1790
2088
  const argsCollector = createOperationCollector();
@@ -1793,33 +2091,65 @@ function createMethodPrimitive(context, params) {
1793
2091
  addDiagnostic: argsCollector.addDiagnostic,
1794
2092
  hasAnyDiagnostic: argsCollector.hasAnyDiagnostic
1795
2093
  };
1796
- const validArgs = params.definition.validateArgs(args, argsCtx);
1797
- assertSyncValue(validArgs, `Method "${params.name}"'s validateArgs`);
1798
- if (!validArgs || argsCollector.hasAnyDiagnostic()) {
2094
+ let validArgs;
2095
+ let hasArgsDiagnostic;
2096
+ const previousArgsOwner = callbackScope.owner;
2097
+ callbackScope.owner = null;
2098
+ try {
2099
+ validArgs = params.definition.validateArgs(args, argsCtx);
2100
+ assertSyncValue(validArgs, "Method", params.name, "validateArgs");
2101
+ hasArgsDiagnostic = argsCollector.hasAnyDiagnostic();
2102
+ } finally {
2103
+ callbackScope.owner = previousArgsOwner;
2104
+ argsCollector.close();
2105
+ }
2106
+ if (!validArgs || hasArgsDiagnostic) {
1799
2107
  const finalized = argsCollector.finalize((input) => buildMethodArgsDiagnostic(params.widgetId, params.name, args, input));
1800
2108
  const diagnostics = finalized.length > 0 ? finalized : freezeDiagnosticSnapshot([buildDefaultMethodArgsDiagnostic(params.widgetId, params.name, args)]);
1801
- writeDeferringFlush(() => diagnosticsSignal(diagnostics));
2109
+ commitDiagnostics(diagnostics);
1802
2110
  return Object.freeze({
1803
2111
  ok: false,
1804
2112
  failure: { diagnostics }
1805
2113
  });
1806
2114
  }
2115
+ deps ??= materializeDependencyTree(params.depsTree, {
2116
+ consumer: "method",
2117
+ ownerWidgetId: params.widgetId,
2118
+ ownerName: params.name,
2119
+ registry: params.registry,
2120
+ nodes: params.nodes,
2121
+ context,
2122
+ owner: params.owner
2123
+ });
2124
+ emitFragment ??= createMethodEmitFragment(context, params.owner, params.pluginType, params.eventDefinitions, params.events, params.definition.emits);
1807
2125
  const execCollector = createOperationCollector();
1808
2126
  const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => execCollector.addFinalizedDiagnostic(diagnostic, dedupe) };
1809
2127
  const executeCtx = {
1810
2128
  args,
1811
2129
  widget: params.selfNode,
1812
2130
  blueprint: params.blueprintView,
1813
- deps: params.deps,
1814
- ...params.emitFragment,
2131
+ deps,
2132
+ ...emitFragment,
1815
2133
  ...params.buildConfigFragment(),
1816
2134
  addDiagnostic: execCollector.addDiagnostic,
1817
2135
  hasAnyDiagnostic: execCollector.hasAnyDiagnostic
1818
2136
  };
1819
- const value = context.withActiveCollector(sink, () => params.definition.execute(executeCtx));
1820
- assertSyncValue(value, `Method "${params.name}"'s execute`);
2137
+ const { owner } = params;
2138
+ const previousOwner = callbackScope.owner;
2139
+ const previousSink = owner.sink;
2140
+ callbackScope.owner = owner;
2141
+ owner.sink = sink;
2142
+ let value;
2143
+ try {
2144
+ value = params.definition.execute(executeCtx);
2145
+ } finally {
2146
+ callbackScope.owner = previousOwner;
2147
+ owner.sink = previousSink;
2148
+ execCollector.close();
2149
+ }
2150
+ assertSyncValue(value, "Method", params.name, "execute");
1821
2151
  const diagnostics = execCollector.finalize((input) => buildMethodResultDiagnostic(params.widgetId, params.name, value, input));
1822
- writeDeferringFlush(() => diagnosticsSignal(toDiagnosticSnapshot(diagnostics)));
2152
+ commitDiagnostics(toDiagnosticSnapshot(diagnostics));
1823
2153
  const result = diagnostics.length > 0 ? {
1824
2154
  ok: false,
1825
2155
  failure: { diagnostics }
@@ -1829,10 +2159,13 @@ function createMethodPrimitive(context, params) {
1829
2159
  };
1830
2160
  return Object.freeze(result);
1831
2161
  } finally {
1832
- endBatch();
2162
+ endBatchDeferringFlush();
1833
2163
  }
1834
2164
  }
1835
- const callable = ((...args) => invoke(...args));
2165
+ const callable = ((...args) => {
2166
+ context.assertActive();
2167
+ return runRuntimeOperation(invokeWithinOperation, args);
2168
+ });
1836
2169
  Object.assign(callable, {
1837
2170
  getDiagnostics() {
1838
2171
  context.assertActive();
@@ -1840,7 +2173,7 @@ function createMethodPrimitive(context, params) {
1840
2173
  },
1841
2174
  subscribeDiagnostics(listener) {
1842
2175
  context.assertActive();
1843
- return createTrackedSubscription(context, () => diagnosticsSignal(), listener);
2176
+ return createTrackedSubscription(context, () => diagnosticsSignal(), listener, "the diagnostics of Method", params);
1844
2177
  }
1845
2178
  });
1846
2179
  return {
@@ -1902,47 +2235,466 @@ function resolveStateOverrides(compiled, overrideStateDefaults) {
1902
2235
  //#region src/runtime/property.ts
1903
2236
  /** The frozen singleton every Property inspection channel starts at and returns to before first evaluation. */
1904
2237
  const NEVER_EVALUATED_SNAPSHOT = Object.freeze({ status: "never-evaluated" });
2238
+ const computeExceptionKey = Symbol("@deviltea/widget-core:compute-exception");
2239
+ /** alien-signals@3.2.1 `ReactiveFlags.Dirty`. */
2240
+ const ALIEN_DIRTY = 16;
2241
+ /**
2242
+ * Makes the evaluation running for `node`, which is abandoned, leave the computed dirty, so that its next read
2243
+ * evaluates it again, and keep every dependency link it had, also those it has not read again (alien-signals
2244
+ * would drop them when the getter returns), so that nothing it depends on is torn down. See ALIEN-SIGNALS
2245
+ * COUPLING 2 and 3.
2246
+ */
2247
+ function keepAbandoned(node) {
2248
+ node.flags |= ALIEN_DIRTY;
2249
+ let last = node.depsTail ?? node.deps;
2250
+ if (last === void 0) return;
2251
+ while (last.nextDep !== void 0) last = last.nextDep;
2252
+ node.depsTail = last;
2253
+ }
2254
+ /**
2255
+ * How many Property evaluations may nest on one stack segment (see {@link segment}) before the evaluation
2256
+ * that would nest deeper is abandoned and completed later from a shallower stack. Internal: not API, not
2257
+ * configurable, and it may change.
2258
+ *
2259
+ * The figure that bounds it is the smallest stack Core has to run on. Older QuickJS builds default to a
2260
+ * smaller stack than quickjs-ng's 1 MiB, so it is 256 KB: there quickjs-ng 0.18.0 reads the head of a chain
2261
+ * of trivial `compute`s cold, without this limit, only up to 31 nested evaluations (63 at 512 KB, 128 at
2262
+ * 1 MiB: about 8 KB of stack per evaluation). Core's read path nests a little more stack per evaluation than
2263
+ * that measurement's: in V8 without its JIT (an interpreter like QuickJS) a chain read cold without the limit
2264
+ * reached 942 evaluations against 1 072, so about 27 at 256 KB. 12 leaves more than twice that margin, for
2265
+ * real `compute` bodies (refinements, diagnostics, helper calls), the host's own stack below the read,
2266
+ * listener and flush frames, and further segments a read can open on top of this one (a Method a `compute`
2267
+ * depends on reads its own Properties on a new segment), even if QuickJS's frames turn out an eighth larger
2268
+ * than that estimate.
2269
+ *
2270
+ * A smaller limit only adds driver rounds, hardly `compute` calls: a chain whose every link is evaluated
2271
+ * (read cold, or re-read with every link stale) costs about two `compute` calls per Property whatever the
2272
+ * limit, since each link nested beyond it runs `compute` once until it is abandoned and once to completion.
2273
+ * Measured on the differential test's graphs that the unmodified Core can read (cold reads, and State writes
2274
+ * under subscriptions) against the unmodified Core's 446 and 447 calls: 8 cost 606 and 461, 12 cost 542 and
2275
+ * 447, 15 and 16 cost 491 to 494 and 447, 32 cost 446 and 447; on a Property reading 250 or 1 000 chains of
2276
+ * 40 links, a cold read costs 2.0x (8), 1.9x (12), 1.75x (15) and 1.8x (16 and 32) the unmodified Core's
2277
+ * calls, writes the same at every limit. A 300-link chain whose every link reads its own State, or one shared
2278
+ * State, first, re-read with every link stale, costs 1.96x the unmodified Core's calls at 12; a write that
2279
+ * leaves one link stale at a time (re-evaluated without nesting) costs the same.
2280
+ */
2281
+ const EVALUATION_NESTING_LIMIT = 12;
2282
+ /**
2283
+ * Thrown by a Property's dependency read through `compute` to abandon the evaluation in progress (see
2284
+ * {@link evaluate}). Internal: plugin code must not rely on it. A `compute` that catches it has its return
2285
+ * value discarded anyway; one that keeps it and throws it in a later evaluation throws an ordinary compute
2286
+ * exception, cached and rethrown by `get()` like any other. An `Error` only so that code which logs what it
2287
+ * caught says what it is.
2288
+ */
2289
+ const ABANDONMENT = Object.freeze(/* @__PURE__ */ new Error("widget-core: internal — this Property evaluation was abandoned to be completed from a shallower stack; do not catch it."));
2290
+ /**
2291
+ * The cached outcome of an abandoned evaluation: like an engine stack overflow it is an outcome that is not
2292
+ * kept. The computed that caches it stays dirty (see `keepAbandoned`), so its next read evaluates it again.
2293
+ * One shared object, recognized by identity: an ABANDONMENT that plugin code keeps and throws later is cached
2294
+ * as an ordinary compute exception.
2295
+ */
2296
+ const ABANDONED_OUTCOME = Object.freeze({ [computeExceptionKey]: ABANDONMENT });
2297
+ /**
2298
+ * Evaluation-nesting bookkeeping of the current stack segment. A segment is the stretch of the stack between
2299
+ * one boundary read and the next: every read of a Property other than a Property's own dependency read (the
2300
+ * public `get()`, a subscription effect, a Method's dependency read, ...) is a boundary, which saves these
2301
+ * three fields, starts the segment from zero and restores them when it returns. The abandonment therefore
2302
+ * only ever travels through Property `compute` frames: it never reaches a Method's failure handling,
2303
+ * listener isolation, the isolated-exception reporting or the host.
2304
+ *
2305
+ * A mutable holder updated with plain assignments, like `callbackScope`, so the bookkeeping survives an
2306
+ * exhausted stack, and realm-wide, since segments follow the stack, not a Runtime. Its fields are read on
2307
+ * every warm read, which costs less than reading module `let` bindings from inside closures.
2308
+ */
2309
+ const segment = {
2310
+ nesting: 0,
2311
+ abandonedAt: null,
2312
+ recordedTarget: null
2313
+ };
2314
+ /** Numbers the driver loops, for their no-progress guard. */
2315
+ let drives = 0;
2316
+ /**
2317
+ * How many times one drive may find a Property it already completed abandoned again. Without a write
2318
+ * during the drive this never happens (completed outcomes stay cached and the dependency graph is acyclic);
2319
+ * code that keeps invalidating what the drive completes (a `compute` writing by closure, say) would otherwise
2320
+ * make it spin.
2321
+ */
2322
+ const MAX_DRIVE_STALLS = 256;
2323
+ /**
2324
+ * Completes a boundary read whose attempt was abandoned: a loop over an explicit stack of Properties, which
2325
+ * evaluates the recorded target first (itself possibly abandoned further down, which pushes the next
2326
+ * target) and then attempts the waiting Property again, until the read's own Property completes. Runs
2327
+ * inside the boundary's Runtime operation, so the diagnostic propagations deferred by every attempt are
2328
+ * released once, after the read's own result has been committed, as for any other outermost read.
2329
+ *
2330
+ * Every attempt runs with no active subscriber (the boundary read cleared it, see
2331
+ * `getResultWithInspectionPublish`). A completed target publishes no inspection completion here: its reader,
2332
+ * attempted again, reads it as any reader does, and publishes it then, exactly when a read without the limit
2333
+ * would have. A target whose evaluation ends in an engine stack overflow (the host called from an already
2334
+ * deep stack) ends the read with that overflow, as an overflowing read always did: the overflow is not
2335
+ * cached for good (see `getResultWithInspectionPublish`), and the waiting Properties stay abandoned, so a
2336
+ * later read evaluates them again. Disposal during the loop ends it with the post-dispose error: a `compute`
2337
+ * that catches what its dependency reads throw after the disposal could otherwise complete the read with
2338
+ * values computed from a disposed Runtime.
2339
+ */
2340
+ function driveAbandonedRead(root) {
2341
+ const drive = ++drives;
2342
+ const pending = [];
2343
+ let current = root;
2344
+ let outcome = ABANDONED_OUTCOME;
2345
+ let stalls = 0;
2346
+ for (;;) {
2347
+ if (outcome === ABANDONED_OUTCOME) {
2348
+ const target = segment.recordedTarget;
2349
+ if (target === null || target === current || target.pendingIn === drive) throw new Error("widget-core: internal error — an abandoned Property evaluation did not record a deeper evaluation to complete first.");
2350
+ if (target.completedBy === drive && ++stalls > MAX_DRIVE_STALLS) throw new Error("widget-core: internal error — completing an abandoned Property evaluation made no progress.");
2351
+ current.pendingIn = drive;
2352
+ pending.push(current);
2353
+ current = target;
2354
+ } else {
2355
+ if (current === root || computeExceptionKey in outcome && isEngineStackOverflow(outcome[computeExceptionKey])) return outcome;
2356
+ current.completedBy = drive;
2357
+ current = pending.pop();
2358
+ current.pendingIn = 0;
2359
+ }
2360
+ root.context.assertActive();
2361
+ segment.nesting = 0;
2362
+ segment.abandonedAt = null;
2363
+ segment.recordedTarget = null;
2364
+ outcome = current.attempt();
2365
+ }
2366
+ }
1905
2367
  function createPropertyPrimitive(context, params) {
2368
+ const { owner } = params;
1906
2369
  const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2370
+ let committedDiagnostics = EMPTY_DIAGNOSTICS;
1907
2371
  let inspectionSnapshot = NEVER_EVALUATED_SNAPSHOT;
1908
2372
  let inspectionListeners = null;
1909
2373
  let lastPublishedResult = null;
1910
- function publishInspectionCompletion(result) {
1911
- inspectionSnapshot = Object.freeze({
2374
+ function readInspectionSnapshot() {
2375
+ return inspectionSnapshot ??= Object.freeze({
1912
2376
  status: "completed",
1913
- result
2377
+ result: lastPublishedResult
1914
2378
  });
1915
- if (inspectionListeners === null) return;
2379
+ }
2380
+ /**
2381
+ * Commits the completion as the retained fact at once (`getSnapshot()` returns it from now on) and delivers
2382
+ * it to the listeners registered now once no Runtime operation is in progress (see `deliverWhenIdle`), so
2383
+ * that a listener never runs while alien-signals is evaluating, checking or flushing (issue #198). Each
2384
+ * completion is delivered with its own snapshot, in completion order. A listener unsubscribed before the
2385
+ * delivery is skipped, one subscribed after the completion does not receive it, and nothing is delivered
2386
+ * once the Runtime is disposed (its subscriptions are detached without a final call).
2387
+ */
2388
+ function publishInspectionCompletion() {
2389
+ inspectionSnapshot = null;
2390
+ if (inspectionListeners === null || inspectionListeners.length === 0) return;
2391
+ const snapshot = readInspectionSnapshot();
1916
2392
  const listenersSnapshot = inspectionListeners.slice();
1917
- for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, inspectionSnapshot);
2393
+ deliverWhenIdle(() => {
2394
+ if (context.isDisposed()) return;
2395
+ for (const entry of listenersSnapshot) if (entry.active) invokeListenerIsolated(entry.listener, snapshot);
2396
+ });
2397
+ }
2398
+ let evaluations = 0;
2399
+ let deps;
2400
+ let retries = 0;
2401
+ let retrySignal = null;
2402
+ let currentNode = null;
2403
+ let cachedAbandoned = false;
2404
+ let inProgress = 0;
2405
+ let linksCompleted = false;
2406
+ /**
2407
+ * Whether the computed whose alien-signals node is `target` has dependency links left by an evaluation that
2408
+ * completed: it is neither new nor torn down (ALIEN-SIGNALS COUPLING 4). A reader links such a computed at
2409
+ * once; any other one it reads without linking until it has completed (see `readFromProperty`).
2410
+ */
2411
+ function hasCompletedLinks(target) {
2412
+ return linksCompleted && target.deps !== void 0;
2413
+ }
2414
+ const node = {
2415
+ attempt,
2416
+ context,
2417
+ completedBy: 0,
2418
+ pendingIn: 0
2419
+ };
2420
+ /**
2421
+ * The computed's getter. Besides a completed result or a cached compute exception, an evaluation can yield
2422
+ * the abandoned outcome (see {@link ABANDONED_OUTCOME}), which is never kept; it then leaves the computed dirty
2423
+ * with every dependency link it had (see `keepAbandoned`):
2424
+ *
2425
+ * - one that would start with {@link EVALUATION_NESTING_LIMIT} evaluations already in progress on the
2426
+ * segment does not run `compute`: it records itself as where the unwinding started ({@link segment}) and
2427
+ * yields it. The dependency read in the enclosing `compute` then throws the internal
2428
+ * {@link ABANDONMENT} (see `readFromProperty`), so the enclosing evaluation finishes too;
2429
+ * - one that finishes while the segment unwinds yields it whatever its `compute` did (returned a fallback
2430
+ * after catching the abandonment, or threw anything else), and commits no diagnostics;
2431
+ * - one that would start while the segment unwinds yields it without running `compute`.
2432
+ *
2433
+ * The getter itself never throws, also not the abandonment: it returns the abandoned outcome instead. The
2434
+ * outermost evaluation of the segment ends the unwinding and hands the target to the segment's driver.
2435
+ *
2436
+ * `this` is the alien-signals node of the computed this evaluation runs for (see `currentNode`). A computed
2437
+ * replaced while it ran drops every dependency link when it finishes, so nothing evaluates it again; one
2438
+ * alien-signals would still evaluate (only reachable after an engine stack overflow; not covered by a
2439
+ * deterministic test) reads nothing and yields the abandoned outcome without running `compute`.
2440
+ * A plain function rather than a closure per computed: no extra call frame per nesting level.
2441
+ */
2442
+ function evaluate() {
2443
+ if (currentNode !== this && !claimCurrentNode(this)) return ABANDONED_OUTCOME;
2444
+ ++evaluations;
2445
+ if (!hasCompletedLinks(this)) linksCompleted = false;
2446
+ (retrySignal ??= signal(0))();
2447
+ if (segment.abandonedAt !== null) return abandonAtStart(this);
2448
+ if (segment.nesting >= EVALUATION_NESTING_LIMIT) {
2449
+ segment.abandonedAt = node;
2450
+ return abandonAtStart(this);
2451
+ }
2452
+ ++segment.nesting;
2453
+ ++inProgress;
2454
+ let abandoned = false;
2455
+ try {
2456
+ deps ??= materializeDependencyTree(params.depsTree, {
2457
+ consumer: "property",
2458
+ ownerWidgetId: params.widgetId,
2459
+ ownerName: params.name,
2460
+ registry: params.registry,
2461
+ nodes: params.nodes,
2462
+ context,
2463
+ owner
2464
+ });
2465
+ const collector = createOperationCollector();
2466
+ const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => collector.addFinalizedDiagnostic(diagnostic, dedupe) };
2467
+ const ctx = {
2468
+ widget: params.selfNode,
2469
+ blueprint: params.blueprintView,
2470
+ deps,
2471
+ ...params.buildConfigFragment(),
2472
+ addDiagnostic: collector.addDiagnostic,
2473
+ hasAnyDiagnostic: collector.hasAnyDiagnostic
2474
+ };
2475
+ const previousOwner = callbackScope.owner;
2476
+ const previousSink = owner.sink;
2477
+ callbackScope.owner = owner;
2478
+ owner.sink = sink;
2479
+ let value;
2480
+ try {
2481
+ value = params.definition.compute(ctx);
2482
+ } finally {
2483
+ callbackScope.owner = previousOwner;
2484
+ owner.sink = previousSink;
2485
+ collector.close();
2486
+ }
2487
+ if (segment.abandonedAt !== null) {
2488
+ abandoned = true;
2489
+ return ABANDONED_OUTCOME;
2490
+ }
2491
+ assertSyncValue(value, "Property", params.name, "compute");
2492
+ const diagnostics = collector.finalize((input) => buildPropertyResultDiagnostic(params.widgetId, params.name, value, input));
2493
+ const snapshot = toDiagnosticSnapshot(diagnostics);
2494
+ if (snapshot !== committedDiagnostics) {
2495
+ committedDiagnostics = snapshot;
2496
+ writeDeferringFlush(() => {
2497
+ diagnosticsSignal(snapshot);
2498
+ params.onDiagnosticsCommitted();
2499
+ });
2500
+ }
2501
+ const result = diagnostics.length > 0 ? {
2502
+ ok: false,
2503
+ failure: { diagnostics }
2504
+ } : {
2505
+ ok: true,
2506
+ value
2507
+ };
2508
+ return Object.freeze(result);
2509
+ } catch (error) {
2510
+ if (segment.abandonedAt !== null) {
2511
+ abandoned = true;
2512
+ return ABANDONED_OUTCOME;
2513
+ }
2514
+ return { [computeExceptionKey]: error };
2515
+ } finally {
2516
+ if (--segment.nesting === 0 && segment.abandonedAt !== null) {
2517
+ segment.recordedTarget = segment.abandonedAt;
2518
+ segment.abandonedAt = null;
2519
+ }
2520
+ if (this !== currentNode) this.depsTail = void 0;
2521
+ else if (abandoned) {
2522
+ const links = this;
2523
+ links.flags |= ALIEN_DIRTY;
2524
+ let last = links.depsTail ?? links.deps;
2525
+ if (last !== void 0) {
2526
+ while (last.nextDep !== void 0) last = last.nextDep;
2527
+ links.depsTail = last;
2528
+ }
2529
+ }
2530
+ if (this === currentNode) {
2531
+ --inProgress;
2532
+ cachedAbandoned = abandoned;
2533
+ if (!abandoned) linksCompleted = true;
2534
+ }
2535
+ }
2536
+ }
2537
+ /**
2538
+ * An evaluation abandoned before running `compute` (see {@link evaluate}): leaves the computed dirty with its
2539
+ * links (see `keepAbandoned`) and yields an abandoned outcome.
2540
+ */
2541
+ function abandonAtStart(target) {
2542
+ cachedAbandoned = true;
2543
+ keepAbandoned(target);
2544
+ return ABANDONED_OUTCOME;
2545
+ }
2546
+ /**
2547
+ * Records `candidate` as the current computed's node if none is recorded yet (the first evaluation after a
2548
+ * replacement); returns whether it is now the current one.
2549
+ */
2550
+ function claimCurrentNode(candidate) {
2551
+ if (currentNode !== null) return false;
2552
+ currentNode = candidate;
2553
+ return true;
2554
+ }
2555
+ let resultComputed = computed(evaluate);
2556
+ /**
2557
+ * Replaces the result computed by a fresh one that has not evaluated yet. Used for a computed that has no
2558
+ * outcome at all (see `getResultWithInspectionPublish`), and for one whose cached outcome is abandoned while
2559
+ * an evaluation of it is still in progress further up the stack: code run during that evaluation reads this
2560
+ * Property again through the public surface (a `compute`, refinement or `validateArgs` reading by closure, or
2561
+ * an Event listener of an emit made by a Method a Property depends on; not supported, but recovered here.
2562
+ * Inspection listeners no longer run there). Making that computed evaluate again would re-enter an
2563
+ * evaluation alien-signals has not finished; the fresh one evaluates on its own instead, exactly as a
2564
+ * re-entrant read of a Property whose first evaluation is in progress always did. The replaced computed
2565
+ * finishes its evaluation in progress for its own readers and never evaluates again (see {@link evaluate}).
2566
+ */
2567
+ function replaceComputed() {
2568
+ inProgress = 0;
2569
+ cachedAbandoned = false;
2570
+ linksCompleted = false;
2571
+ currentNode = null;
2572
+ resultComputed = computed(evaluate);
2573
+ }
2574
+ /**
2575
+ * Makes the computed evaluate again although no dependency changed, for a cached engine stack overflow: it
2576
+ * depends on how deep the stack was when the evaluation ran, not on the compute's inputs. The write marks
2577
+ * this Property (and through it its dependents) stale; its propagation is held until the enclosing Runtime
2578
+ * operation leaves, like any write made while an evaluation may run. A computed no write reaches any more
2579
+ * is replaced instead (see {@link isUnreachable}; only reachable after an engine stack overflow; not covered
2580
+ * by a deterministic test).
2581
+ */
2582
+ function reevaluate() {
2583
+ if (isUnreachable()) replaceComputed();
2584
+ else {
2585
+ const signal = retrySignal;
2586
+ writeDeferringFlush(() => signal(++retries));
2587
+ }
2588
+ return resultComputed();
2589
+ }
2590
+ /**
2591
+ * Whether the current computed has no dependency link, so that the write that makes a computed evaluate
2592
+ * again would not reach it: an engine stack overflow at the very start of an evaluation (when alien-signals
2593
+ * calls the getter) leaves the computed marked clean, with its previous outcome and with every link purged
2594
+ * (`deps`, its alien-signals@3.2.1 dependency list, is empty), so nothing would ever evaluate it again.
2595
+ */
2596
+ function isUnreachable() {
2597
+ return currentNode?.deps === void 0;
2598
+ }
2599
+ /** See {@link EvaluationNode.attempt}. Runs inside the boundary's Runtime operation with no active subscriber. */
2600
+ function attempt() {
2601
+ const evaluationsBefore = evaluations;
2602
+ const result = resultComputed();
2603
+ if (result === void 0) {
2604
+ replaceComputed();
2605
+ return resultComputed();
2606
+ }
2607
+ if (computeExceptionKey in result && evaluations === evaluationsBefore) {
2608
+ if (result === ABANDONED_OUTCOME) return readAbandonedAgain();
2609
+ if (isEngineStackOverflow(result[computeExceptionKey])) return reevaluate();
2610
+ }
2611
+ return result;
2612
+ }
2613
+ /**
2614
+ * A boundary read's own Property, read with no active subscriber: attempted, completed by the driver loop
2615
+ * when abandoned, and only then read once more by `subscriber` (when there is one) to link it, so that a
2616
+ * running subscriber is linked to the outcome the read completed, never to an abandoned one. The link read
2617
+ * evaluates nothing unless foreign code changed this Property after it completed; that evaluation is driven
2618
+ * like the first.
2619
+ *
2620
+ * A completed result not published yet is published here, still inside the boundary's Runtime operation, so
2621
+ * that its delivery is queued behind the completions this read produced and runs when the outermost
2622
+ * operation leaves (see `publishInspectionCompletion`), never from the caller's frame after it returned.
2623
+ */
2624
+ function readAtBoundary(subscriber) {
2625
+ const evaluationsBefore = evaluations;
2626
+ let outcome = resultComputed();
2627
+ if (outcome === void 0 || computeExceptionKey in outcome) outcome = completeBoundaryOutcome(outcome, evaluationsBefore);
2628
+ if (subscriber !== void 0) outcome = linkSubscriber(subscriber, outcome);
2629
+ if (outcome !== lastPublishedResult && !(computeExceptionKey in outcome)) {
2630
+ lastPublishedResult = outcome;
2631
+ publishInspectionCompletion();
2632
+ }
2633
+ return outcome;
1918
2634
  }
1919
- const resultComputed = computed(() => {
1920
- const collector = createOperationCollector();
1921
- const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => collector.addFinalizedDiagnostic(diagnostic, dedupe) };
1922
- const ctx = {
1923
- widget: params.selfNode,
1924
- blueprint: params.blueprintView,
1925
- deps: params.deps,
1926
- ...params.buildConfigFragment(),
1927
- addDiagnostic: collector.addDiagnostic,
1928
- hasAnyDiagnostic: collector.hasAnyDiagnostic
1929
- };
1930
- const value = context.withActiveCollector(sink, () => params.definition.compute(ctx));
1931
- assertSyncValue(value, `Property "${params.name}"'s compute`);
1932
- const diagnostics = collector.finalize((input) => buildPropertyResultDiagnostic(params.widgetId, params.name, value, input));
1933
- writeDeferringFlush(() => diagnosticsSignal(toDiagnosticSnapshot(diagnostics)));
1934
- const result = diagnostics.length > 0 ? {
1935
- ok: false,
1936
- failure: { diagnostics }
1937
- } : {
1938
- ok: true,
1939
- value
1940
- };
1941
- return Object.freeze(result);
1942
- });
1943
2635
  /**
1944
- * Reads the computed result through the exact same call every existing consumer already makes, then
1945
- * publishes the inspection fact only *after* that call has returned.
2636
+ * Whether the current computed, whose cached outcome is abandoned, would not evaluate again when read,
2637
+ * although an abandoned computed is left dirty (see `keepAbandoned`): its evaluation is still in progress
2638
+ * further up the stack (code run by that evaluation reads this Property again, see {@link replaceComputed};
2639
+ * alien-signals returns the cached outcome of a
2640
+ * computed it is evaluating), or, only reachable after an engine stack overflow and not covered by a
2641
+ * deterministic test, an overflow inside alien-signals' own bookkeeping left it marked clean.
2642
+ */
2643
+ function abandonedWithoutReevaluation() {
2644
+ return inProgress > 0 || ((currentNode?.flags ?? 0) & ALIEN_DIRTY) === 0;
2645
+ }
2646
+ /**
2647
+ * A read found a cached abandonment it did not produce, and evaluated nothing (see
2648
+ * {@link abandonedWithoutReevaluation}): the computed is replaced (see {@link replaceComputed}), and the
2649
+ * fresh one read.
2650
+ */
2651
+ function readAbandonedAgain() {
2652
+ replaceComputed();
2653
+ return resultComputed();
2654
+ }
2655
+ /**
2656
+ * The outcome of a boundary read's first read that is not a completed result: no outcome at all, an engine
2657
+ * stack overflow this read did not produce, or an abandonment, each completed as {@link attempt} and the
2658
+ * driver loop do; a compute exception is returned as it is.
2659
+ */
2660
+ function completeBoundaryOutcome(outcome, evaluationsBefore) {
2661
+ if (outcome === void 0) {
2662
+ replaceComputed();
2663
+ outcome = resultComputed();
2664
+ } else if (evaluations === evaluationsBefore) {
2665
+ if (outcome === ABANDONED_OUTCOME) outcome = readAbandonedAgain();
2666
+ else if (isEngineStackOverflow(outcome[computeExceptionKey])) outcome = reevaluate();
2667
+ }
2668
+ return outcome === ABANDONED_OUTCOME ? driveAbandonedRead(node) : outcome;
2669
+ }
2670
+ /**
2671
+ * Links `subscriber` to the computed whose `outcome` the boundary read just produced, by reading it once more
2672
+ * with `subscriber` active (see {@link readAtBoundary}).
2673
+ */
2674
+ function linkSubscriber(subscriber, outcome) {
2675
+ for (let rounds = 0;; rounds++) {
2676
+ setActiveSub(subscriber);
2677
+ let linked;
2678
+ try {
2679
+ linked = resultComputed();
2680
+ } finally {
2681
+ setActiveSub(void 0);
2682
+ }
2683
+ if (linked === outcome) return outcome;
2684
+ if (linked !== void 0 && linked !== ABANDONED_OUTCOME) return linked;
2685
+ if (outcome !== ABANDONED_OUTCOME && computeExceptionKey in outcome) return outcome;
2686
+ if (rounds >= MAX_DRIVE_STALLS) throw new Error("widget-core: internal error — a Property read made no progress.");
2687
+ outcome = attempt();
2688
+ if (outcome === ABANDONED_OUTCOME) outcome = driveAbandonedRead(node);
2689
+ }
2690
+ }
2691
+ /**
2692
+ * The boundary read (see {@link segment}): starts a new segment, reads the computed result through the
2693
+ * exact same call every existing consumer already makes — completing it in the driver loop when its
2694
+ * evaluation was abandoned (see {@link driveAbandonedRead}) — then publishes the inspection fact only after
2695
+ * that call has returned (in {@link readAtBoundary}, still inside this read's Runtime operation). Publishing
2696
+ * commits the fact; its listeners are notified once the outermost Runtime operation has left (see
2697
+ * `publishInspectionCompletion`): for a top-level read, when this read's own operation leaves.
1946
2698
  *
1947
2699
  * In pinned alien-signals@3.2.1 a computed's cache assignment happens as `c.value = c.getter(...)`:
1948
2700
  * the getter runs to completion *before* the assignment to `c.value` takes effect. Publishing from
@@ -1956,25 +2708,111 @@ function createPropertyPrimitive(context, params) {
1956
2708
  * made. Every actual recompute produces a brand-new frozen `ExecutionResult` literal (see above), so
1957
2709
  * comparing by reference — never by value — still notifies twice for two equal-value completions while
1958
2710
  * never re-publishing a merely-re-read, already-cached result.
2711
+ *
2712
+ * A cached {@link ComputeException} is rethrown here, after the computed read has linked the caller
2713
+ * (an enclosing evaluation or a subscription effect) to this Property, and is never published.
2714
+ *
2715
+ * Three outcomes are not kept, because they depend on the stack depth of an earlier read rather than on
2716
+ * the Property's inputs, and a later read from a shallower stack must be able to succeed:
2717
+ *
2718
+ * - a cached engine stack overflow that this read did not just produce is evaluated again (see
2719
+ * {@link reevaluate}); one this read produced is thrown, since retrying at the same depth would only
2720
+ * overflow again. The engine's own overflow stays the last line of defence, for example when the host
2721
+ * itself calls from an already deep stack;
2722
+ * - a cached abandonment (see {@link evaluate}) that this read did not just produce is evaluated again
2723
+ * too (its computed is dirty): an evaluation alien-signals started on its own during a flush (an effect's
2724
+ * dirty check) can be abandoned with no driver above it. One this read produced is completed by the
2725
+ * driver loop;
2726
+ * - a computed with no outcome at all: the stack ran out inside alien-signals' own bookkeeping or at the
2727
+ * very start of the first evaluation, so the exception escaped the computed and left it marked clean
2728
+ * without a value. Nothing ever linked to a computed whose evaluation never completed (alien-signals
2729
+ * links the reader only after a read returns), so it is replaced by a fresh one.
1959
2730
  */
1960
2731
  function getResultWithInspectionPublish() {
1961
- const result = runRuntimeOperation(resultComputed);
2732
+ const subscriber = getActiveSub();
2733
+ if (subscriber !== void 0) setActiveSub(void 0);
2734
+ const savedNesting = segment.nesting;
2735
+ const savedAbandonedAt = segment.abandonedAt;
2736
+ const outerTarget = savedNesting === 0 ? null : segment.recordedTarget;
2737
+ segment.nesting = 0;
2738
+ segment.abandonedAt = null;
2739
+ segment.recordedTarget = null;
2740
+ let result;
2741
+ try {
2742
+ result = runRuntimeOperation(readAtBoundary, subscriber);
2743
+ } finally {
2744
+ segment.nesting = savedNesting;
2745
+ segment.abandonedAt = savedAbandonedAt;
2746
+ segment.recordedTarget = outerTarget;
2747
+ if (subscriber !== void 0) setActiveSub(subscriber);
2748
+ }
2749
+ if (computeExceptionKey in result) throw result[computeExceptionKey];
2750
+ return result;
2751
+ }
2752
+ /**
2753
+ * {@link getResultWithInspectionPublish} for a Property's own dependency callable, nested in the reading
2754
+ * Property's evaluation on the same segment. An abandoned outcome is thrown as the internal
2755
+ * {@link ABANDONMENT}, through the reader's `compute`, to the reader's evaluation. A cached abandonment is
2756
+ * evaluated again by the read itself (the computed is dirty, see `keepAbandoned`), unless it would not be
2757
+ * (see {@link abandonedWithoutReevaluation}): it is then replaced first (see {@link replaceComputed}), rather
2758
+ * than abandoning the reader and being replaced only when the driver loop attempts it.
2759
+ */
2760
+ function readFromProperty() {
2761
+ if (cachedAbandoned && abandonedWithoutReevaluation()) replaceComputed();
2762
+ let result;
2763
+ if (hasCompletedLinks(currentNode)) {
2764
+ const evaluationsBefore = evaluations;
2765
+ const read = resultComputed;
2766
+ result = runRuntimeOperation(read);
2767
+ if (result !== void 0) {
2768
+ if (computeExceptionKey in result && evaluations === evaluationsBefore && isEngineStackOverflow(result[computeExceptionKey])) result = runRuntimeOperation(reevaluate);
2769
+ else if (resultComputed !== read) result = runRuntimeOperation(resultComputed);
2770
+ return finishReadFromProperty(result);
2771
+ }
2772
+ replaceComputed();
2773
+ }
2774
+ const reader = setActiveSub(void 0);
2775
+ try {
2776
+ const evaluationsBefore = evaluations;
2777
+ result = runRuntimeOperation(resultComputed);
2778
+ if (result === void 0) {
2779
+ replaceComputed();
2780
+ result = runRuntimeOperation(resultComputed);
2781
+ } else if (computeExceptionKey in result && evaluations === evaluationsBefore && isEngineStackOverflow(result[computeExceptionKey])) result = runRuntimeOperation(reevaluate);
2782
+ } finally {
2783
+ setActiveSub(reader);
2784
+ }
2785
+ if (result !== ABANDONED_OUTCOME) result = runRuntimeOperation(resultComputed);
2786
+ return finishReadFromProperty(result);
2787
+ }
2788
+ /** Throws an abandonment or a compute exception, or publishes a completed result unless already published. */
2789
+ function finishReadFromProperty(result) {
2790
+ if (result === ABANDONED_OUTCOME) {
2791
+ segment.abandonedAt ??= segment.recordedTarget ?? node;
2792
+ throw ABANDONMENT;
2793
+ }
2794
+ if (computeExceptionKey in result) throw result[computeExceptionKey];
1962
2795
  if (result !== lastPublishedResult) {
1963
2796
  lastPublishedResult = result;
1964
- publishInspectionCompletion(result);
2797
+ publishInspectionCompletion();
1965
2798
  }
1966
2799
  return result;
1967
2800
  }
1968
2801
  const internal = {
1969
2802
  getResult: getResultWithInspectionPublish,
2803
+ readFromProperty,
1970
2804
  getDiagnostics: () => diagnosticsSignal(),
1971
2805
  inspection: {
1972
- getSnapshot: () => inspectionSnapshot,
2806
+ getSnapshot: readInspectionSnapshot,
1973
2807
  subscribe: (listener) => {
1974
- const entry = { listener };
2808
+ const entry = {
2809
+ listener,
2810
+ active: true
2811
+ };
1975
2812
  if (inspectionListeners === null) inspectionListeners = [];
1976
2813
  inspectionListeners.push(entry);
1977
2814
  return () => {
2815
+ entry.active = false;
1978
2816
  if (inspectionListeners === null) return;
1979
2817
  const index = inspectionListeners.indexOf(entry);
1980
2818
  if (index !== -1) inspectionListeners.splice(index, 1);
@@ -1982,6 +2820,14 @@ function createPropertyPrimitive(context, params) {
1982
2820
  }
1983
2821
  }
1984
2822
  };
2823
+ /**
2824
+ * Creates a subscription to this Property's result. Called inside a Runtime operation (see `subscribe`): the
2825
+ * subscription's first read can evaluate Properties, and the inspection completions it produces must reach
2826
+ * their listeners after the subscription exists (see `createTrackedSubscription`).
2827
+ */
2828
+ function subscribeWithinOperation(listener) {
2829
+ return createTrackedSubscription(context, internal.getResult, listener, "Property", params);
2830
+ }
1985
2831
  return {
1986
2832
  internal,
1987
2833
  public: {
@@ -1991,7 +2837,7 @@ function createPropertyPrimitive(context, params) {
1991
2837
  },
1992
2838
  subscribe(listener) {
1993
2839
  context.assertActive();
1994
- return createTrackedSubscription(context, internal.getResult, listener);
2840
+ return runRuntimeOperation(subscribeWithinOperation, listener);
1995
2841
  },
1996
2842
  getDiagnostics() {
1997
2843
  context.assertActive();
@@ -1999,68 +2845,184 @@ function createPropertyPrimitive(context, params) {
1999
2845
  },
2000
2846
  subscribeDiagnostics(listener) {
2001
2847
  context.assertActive();
2002
- return createTrackedSubscription(context, internal.getDiagnostics, listener);
2848
+ return createTrackedSubscription(context, internal.getDiagnostics, listener, "the diagnostics of Property", params);
2003
2849
  }
2004
2850
  }
2005
2851
  };
2006
2852
  }
2007
2853
  //#endregion
2008
2854
  //#region src/runtime/state.ts
2855
+ function createStateLedger(stateCount) {
2856
+ return {
2857
+ dirty: new Uint32Array(stateCount + 31 >>> 5),
2858
+ states: []
2859
+ };
2860
+ }
2861
+ /**
2862
+ * Restores the captured initialization outcome of the State members whose ordinals lie in
2863
+ * `[first, end)` and that may have changed since — the shared implementation of
2864
+ * `WidgetSystemRuntime.resetState()` (every State) and `RuntimeWidget.resetState()` (one widget's
2865
+ * contiguous range). `validate` does not run again, all writes form one batch so dependents recompute and
2866
+ * subscribers are notified once, and Property/Method diagnostic snapshots are left untouched.
2867
+ *
2868
+ * Called from outside every Runtime operation, alien batch and reactive scope, the scan only visits the
2869
+ * set bits: restoring a State nothing wrote is then a no-op nobody can observe. In ascending ordinal order,
2870
+ * i.e. the order a scan over every State would restore them in, it re-reads the bitset word at every step,
2871
+ * so a State a listener writes during the reset is restored exactly when the scan has not passed it yet.
2872
+ * From anywhere else (a listener, a `compute`, a Method, an open batch) every State of the range is
2873
+ * restored, in order, because a restore also reads the State's signal: that read is tracked by an active
2874
+ * computed or effect and commits a value an enclosing write has not committed yet. Such a restore leaves
2875
+ * the marks set, since its own write may still be uncommitted when it returns; the next top-level reset
2876
+ * visits those States again, exactly as a full scan would, and clears the marks.
2877
+ *
2878
+ * Like `set()`, a restore made while another Runtime operation is in progress does not flush on its own: the
2879
+ * outermost operation notifies the subscribers (see `runRuntimeWrite`).
2880
+ */
2881
+ function restoreInitialState(context, ledger, first, end) {
2882
+ context.assertActive();
2883
+ const writtenOnly = isRuntimeIdle();
2884
+ runRuntimeWrite(() => {
2885
+ startBatch();
2886
+ try {
2887
+ const { dirty, states } = ledger;
2888
+ let ordinal = first;
2889
+ if (!writtenOnly) {
2890
+ for (; ordinal < end; ordinal++) states[ordinal].restoreInitial(false);
2891
+ return;
2892
+ }
2893
+ while (ordinal < end) {
2894
+ const remaining = dirty[ordinal >>> 5] >>> (ordinal & 31);
2895
+ if (remaining === 0) {
2896
+ ordinal = (ordinal | 31) + 1;
2897
+ continue;
2898
+ }
2899
+ ordinal += 31 - Math.clz32(remaining & -remaining);
2900
+ if (ordinal >= end) break;
2901
+ states[ordinal].restoreInitial(true);
2902
+ ++ordinal;
2903
+ }
2904
+ } finally {
2905
+ endBatch();
2906
+ }
2907
+ });
2908
+ }
2909
+ /**
2910
+ * Clears the dirty bit of `ordinal`, now that its initial outcome was captured or is being restored. Writing NaN
2911
+ * over NaN counts as a change, so restoring a NaN initial value notifies even an unwritten State: that bit
2912
+ * stays set.
2913
+ */
2914
+ function markCleanUnlessNaN(dirty, ordinal, initialValue) {
2915
+ if (Number.isNaN(initialValue)) dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2916
+ else dirty[ordinal >>> 5] &= ~(1 << (ordinal & 31));
2917
+ }
2009
2918
  function createStatePrimitive(context, params) {
2919
+ const { dirty, states } = params.ledger;
2920
+ const ordinal = states.length;
2010
2921
  const valueSignal = signal(null);
2011
2922
  const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2012
- let inspectionSnapshot = Object.freeze({ value: null });
2923
+ let inspectionValue = null;
2924
+ let inspectionSnapshot = null;
2013
2925
  let inspectionListeners = null;
2926
+ function readInspectionSnapshot() {
2927
+ return inspectionSnapshot ??= Object.freeze({ value: inspectionValue });
2928
+ }
2014
2929
  function publishInspectionSnapshot(value) {
2015
- inspectionSnapshot = Object.freeze({ value });
2930
+ inspectionValue = value;
2931
+ inspectionSnapshot = null;
2016
2932
  if (inspectionListeners === null) return;
2017
2933
  const listenersSnapshot = inspectionListeners.slice();
2018
- for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, inspectionSnapshot);
2934
+ for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, readInspectionSnapshot());
2019
2935
  }
2020
2936
  /**
2021
2937
  * The value write below is what makes the whole dependent Property graph recompute, and those
2022
2938
  * recomputes commit their own diagnostic snapshots from inside their evaluators. Wrapping the pipeline in
2023
- * `runRuntimeOperation` is only what tells `writeDeferringFlush` when those evaluators are all back
2939
+ * `runRuntimeWrite` is only what tells `writeDeferringFlush` when those evaluators are all back
2024
2940
  * out of the graph, so the propagations they deferred are released here: still inside the very `set()`
2025
2941
  * call that caused them, before its `ExecutionResult` reaches the caller.
2026
2942
  */
2943
+ let committedDiagnostics = EMPTY_DIAGNOSTICS;
2944
+ function commitDiagnostics(next) {
2945
+ if (next === committedDiagnostics) return;
2946
+ committedDiagnostics = next;
2947
+ writeDeferringFlush(() => {
2948
+ diagnosticsSignal(next);
2949
+ params.onDiagnosticsCommitted();
2950
+ });
2951
+ }
2027
2952
  function attemptSet(candidate) {
2028
- return runRuntimeOperation(() => attemptSetWithinOperation(candidate));
2953
+ return runRuntimeWrite(attemptSetWithinOperation, candidate);
2029
2954
  }
2955
+ /**
2956
+ * A rejected attempt changes the diagnostic snapshot, so every attempt marks the State: on entry, and once
2957
+ * more after its last mutation, because that mutation flushes listeners that may reset the State
2958
+ * (clearing its mark) before the attempt has finished writing.
2959
+ */
2030
2960
  function attemptSetWithinOperation(candidate) {
2961
+ dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2962
+ try {
2963
+ return attemptSetUnmarked(candidate);
2964
+ } finally {
2965
+ dirty[ordinal >>> 5] |= 1 << (ordinal & 31);
2966
+ }
2967
+ }
2968
+ function attemptSetUnmarked(candidate) {
2031
2969
  const collector = createOperationCollector();
2032
2970
  const ctx = {
2033
2971
  ...params.buildConfigFragment(),
2034
2972
  addDiagnostic: collector.addDiagnostic,
2035
2973
  hasAnyDiagnostic: collector.hasAnyDiagnostic
2036
2974
  };
2037
- const isValid = params.definition.validate(candidate, ctx);
2038
- assertSyncValue(isValid, `State "${params.key}"'s validate`);
2039
- if (!isValid || collector.hasAnyDiagnostic()) {
2975
+ let isValid;
2976
+ let hasDiagnostic;
2977
+ const previousOwner = callbackScope.owner;
2978
+ callbackScope.owner = null;
2979
+ try {
2980
+ isValid = params.definition.validate(candidate, ctx);
2981
+ assertSyncValue(isValid, "State", params.key, "validate");
2982
+ hasDiagnostic = collector.hasAnyDiagnostic();
2983
+ } finally {
2984
+ callbackScope.owner = previousOwner;
2985
+ collector.close();
2986
+ }
2987
+ if (!isValid || hasDiagnostic) {
2040
2988
  const finalized = collector.finalize((input) => buildStateValidationDiagnostic(params.widgetId, params.key, candidate, input));
2041
2989
  const diagnostics = finalized.length > 0 ? finalized : freezeDiagnosticSnapshot([buildDefaultStateValidationDiagnostic(params.widgetId, params.key, candidate)]);
2042
- writeDeferringFlush(() => diagnosticsSignal(diagnostics));
2990
+ commitDiagnostics(diagnostics);
2043
2991
  return {
2044
2992
  ok: false,
2045
2993
  failure: { diagnostics }
2046
2994
  };
2047
2995
  }
2048
- assertSyncValue(candidate, `State "${params.key}"'s value`);
2996
+ assertSyncValue(candidate, "State", params.key, "value");
2049
2997
  const previous = valueSignal();
2050
2998
  valueSignal(candidate);
2051
- writeDeferringFlush(() => diagnosticsSignal(EMPTY_DIAGNOSTICS));
2999
+ commitDiagnostics(EMPTY_DIAGNOSTICS);
2052
3000
  if (candidate !== previous) publishInspectionSnapshot(candidate);
2053
3001
  return {
2054
3002
  ok: true,
2055
3003
  value: candidate
2056
3004
  };
2057
3005
  }
3006
+ let initialValue = null;
3007
+ let initialDiagnostics = EMPTY_DIAGNOSTICS;
2058
3008
  const internal = {
3009
+ captureInitial() {
3010
+ initialValue = valueSignal();
3011
+ initialDiagnostics = committedDiagnostics;
3012
+ markCleanUnlessNaN(dirty, ordinal, initialValue);
3013
+ },
3014
+ restoreInitial(clearMark) {
3015
+ if (clearMark) markCleanUnlessNaN(dirty, ordinal, initialValue);
3016
+ const previous = valueSignal();
3017
+ valueSignal(initialValue);
3018
+ commitDiagnostics(initialDiagnostics);
3019
+ if (initialValue !== previous) publishInspectionSnapshot(initialValue);
3020
+ },
2059
3021
  get: () => valueSignal(),
2060
3022
  getDiagnostics: () => diagnosticsSignal(),
2061
3023
  attemptSet,
2062
3024
  inspection: {
2063
- getSnapshot: () => inspectionSnapshot,
3025
+ getSnapshot: readInspectionSnapshot,
2064
3026
  subscribe: (listener) => {
2065
3027
  const entry = { listener };
2066
3028
  if (inspectionListeners === null) inspectionListeners = [];
@@ -2073,77 +3035,100 @@ function createStatePrimitive(context, params) {
2073
3035
  }
2074
3036
  }
2075
3037
  };
3038
+ const publicState = {
3039
+ get() {
3040
+ context.assertActive();
3041
+ return internal.get();
3042
+ },
3043
+ set(value) {
3044
+ context.assertActive();
3045
+ return internal.attemptSet(value);
3046
+ },
3047
+ subscribe(listener) {
3048
+ context.assertActive();
3049
+ return createTrackedSubscription(context, internal.get, listener, "State", params);
3050
+ },
3051
+ getDiagnostics() {
3052
+ context.assertActive();
3053
+ return internal.getDiagnostics();
3054
+ },
3055
+ subscribeDiagnostics(listener) {
3056
+ context.assertActive();
3057
+ return createTrackedSubscription(context, internal.getDiagnostics, listener, "the diagnostics of State", params);
3058
+ }
3059
+ };
3060
+ states.push(internal);
2076
3061
  return {
2077
3062
  internal,
2078
- public: {
2079
- get() {
2080
- context.assertActive();
2081
- return internal.get();
2082
- },
2083
- set(value) {
2084
- context.assertActive();
2085
- return internal.attemptSet(value);
2086
- },
2087
- subscribe(listener) {
2088
- context.assertActive();
2089
- return createTrackedSubscription(context, internal.get, listener);
2090
- },
2091
- getDiagnostics() {
2092
- context.assertActive();
2093
- return internal.getDiagnostics();
2094
- },
2095
- subscribeDiagnostics(listener) {
2096
- context.assertActive();
2097
- return createTrackedSubscription(context, internal.getDiagnostics, listener);
2098
- }
2099
- }
3063
+ public: publicState
2100
3064
  };
2101
3065
  }
2102
3066
  //#endregion
2103
3067
  //#region src/runtime/widget.ts
2104
- function buildRuntimeWidget(context, node, entry) {
2105
- const diagnosticsAggregate = createRuntimeWidgetDiagnosticsAggregate(context, entry);
3068
+ /** `stateStart` and `stateEnd` bound the ledger ordinals of this widget's State members. */
3069
+ function buildRuntimeWidget(context, node, entry, ledger, stateStart, stateEnd) {
3070
+ const diagnosticsAggregate = createRuntimeWidgetDiagnosticsAggregate(context, entry, node.id);
2106
3071
  const widget = {
2107
3072
  id: node.id,
2108
3073
  type: node.type,
2109
- blueprint: node.publicNode,
3074
+ blueprintNode: node.publicNode,
2110
3075
  getDiagnostics: diagnosticsAggregate.getDiagnostics,
2111
3076
  subscribeDiagnostics: diagnosticsAggregate.subscribeDiagnostics
2112
3077
  };
2113
3078
  const definition = readWidgetPluginDefinition(node.plugin);
2114
3079
  if (definition.state !== null) {
2115
3080
  const stateSurface = Object.create(null);
2116
- for (const [key, primitive] of entry.state) stateSurface[key] = primitive.public;
3081
+ for (const key of entry.state.keys()) stateSurface[key] = entry.state.get(key).public;
2117
3082
  widget.state = Object.freeze(stateSurface);
3083
+ widget.resetState = () => restoreInitialState(context, ledger, stateStart, stateEnd);
2118
3084
  }
2119
3085
  if (definition.properties !== null) {
2120
3086
  const propertiesSurface = Object.create(null);
2121
- for (const [name, primitive] of entry.properties) propertiesSurface[name] = primitive.public;
3087
+ for (const name of entry.properties.keys()) propertiesSurface[name] = entry.properties.get(name).public;
2122
3088
  widget.properties = Object.freeze(propertiesSurface);
2123
3089
  }
2124
3090
  if (definition.methods !== null) {
2125
3091
  const methodsSurface = Object.create(null);
2126
- for (const [name, primitive] of entry.methods) methodsSurface[name] = primitive.public;
3092
+ for (const name of entry.methods.keys()) methodsSurface[name] = entry.methods.get(name).public;
2127
3093
  widget.methods = Object.freeze(methodsSurface);
2128
3094
  }
2129
3095
  if (definition.events !== null) {
2130
3096
  const eventsSurface = Object.create(null);
2131
- for (const [name, primitive] of entry.events) eventsSurface[name] = primitive.public;
3097
+ for (const name of entry.events.keys()) eventsSurface[name] = entry.events.get(name).public;
2132
3098
  widget.events = Object.freeze(eventsSurface);
2133
3099
  }
2134
3100
  return Object.freeze(widget);
2135
3101
  }
2136
3102
  //#endregion
2137
3103
  //#region src/runtime/index.ts
3104
+ /**
3105
+ * Adds `key` to `record` as an own, enumerable, writable, configurable data property. Plain assignment
3106
+ * does exactly that unless the key exists on `Object.prototype` (`__proto__` is a setter there), so only
3107
+ * those keys pay for `defineProperty`.
3108
+ */
3109
+ function defineOwnValue(record, key, value) {
3110
+ if (key in Object.prototype) Object.defineProperty(record, key, {
3111
+ value,
3112
+ enumerable: true,
3113
+ writable: true,
3114
+ configurable: true
3115
+ });
3116
+ else record[key] = value;
3117
+ }
2138
3118
  function createWidgetSystemRuntime(blueprint, options) {
2139
3119
  const compiled = readCompiledBlueprint(blueprint);
2140
3120
  const context = createRuntimeContext();
2141
3121
  const blueprintView = buildBlueprintView(blueprint);
2142
3122
  const registry = /* @__PURE__ */ new Map();
2143
- function buildConfigFragmentFor(node) {
2144
- if (readWidgetPluginDefinition(node.plugin).config === null) return () => ({});
2145
- return () => ({ config: node.config });
2146
- }
3123
+ const overrideResolution = resolveStateOverrides(compiled, options?.overrideStateDefaults);
3124
+ const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
3125
+ const commitHooks = [];
3126
+ const configFragments = [];
3127
+ let stateCount = 0;
3128
+ for (const node of compiled.nodes) if (node !== void 0 && node.resolved) stateCount += node.state.size;
3129
+ const stateLedger = createStateLedger(stateCount);
3130
+ const stateStart = [];
3131
+ const stateEnd = [];
2147
3132
  for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2148
3133
  const node = compiled.nodes[nodeId];
2149
3134
  if (node === void 0 || !node.resolved) continue;
@@ -2156,26 +3141,35 @@ function createWidgetSystemRuntime(blueprint, options) {
2156
3141
  registry.set(nodeId, entry);
2157
3142
  const definition = readWidgetPluginDefinition(node.plugin);
2158
3143
  if (definition.events !== null) for (const name of definition.events.keys()) entry.events.set(name, createEventPrimitive(context));
2159
- const buildConfigFragment = buildConfigFragmentFor(node);
2160
- for (const [key, member] of node.state) {
3144
+ const fragment = definition.config === null ? Object.freeze({}) : Object.freeze({ config: node.config });
3145
+ const buildConfigFragment = () => fragment;
3146
+ configFragments[nodeId] = buildConfigFragment;
3147
+ const onDiagnosticsCommitted = aggregate.commitHookFor(nodeId);
3148
+ commitHooks[nodeId] = onDiagnosticsCommitted;
3149
+ stateStart[nodeId] = stateLedger.states.length;
3150
+ for (const member of node.state.values()) {
3151
+ const { key } = member;
2161
3152
  const primitive = createStatePrimitive(context, {
2162
3153
  widgetId: node.id,
2163
3154
  key,
2164
3155
  definition: member.definition,
2165
- buildConfigFragment
3156
+ buildConfigFragment,
3157
+ onDiagnosticsCommitted,
3158
+ ledger: stateLedger
2166
3159
  });
2167
3160
  entry.state.set(key, primitive);
2168
3161
  }
3162
+ stateEnd[nodeId] = stateLedger.states.length;
2169
3163
  }
2170
- const overrideResolution = resolveStateOverrides(compiled, options?.overrideStateDefaults);
2171
3164
  for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2172
3165
  const node = compiled.nodes[nodeId];
2173
3166
  if (node === void 0 || !node.resolved) continue;
2174
3167
  const entry = registry.get(nodeId);
2175
3168
  if (entry === void 0) continue;
2176
- const buildConfigFragment = buildConfigFragmentFor(node);
3169
+ const buildConfigFragment = configFragments[nodeId];
2177
3170
  const overrides = overrideResolution.candidatesByNodeId.get(nodeId);
2178
- for (const [key, member] of node.state) {
3171
+ for (const member of node.state.values()) {
3172
+ const { key } = member;
2179
3173
  const primitive = entry.state.get(key);
2180
3174
  if (primitive === void 0) continue;
2181
3175
  let hasCandidate = false;
@@ -2184,11 +3178,18 @@ function createWidgetSystemRuntime(blueprint, options) {
2184
3178
  candidate = overrides.get(key);
2185
3179
  hasCandidate = true;
2186
3180
  } else if (member.definition.default) {
2187
- candidate = member.definition.default(buildConfigFragment());
2188
- assertSyncValue(candidate, `State "${key}"'s default`);
3181
+ const previousOwner = callbackScope.owner;
3182
+ callbackScope.owner = null;
3183
+ try {
3184
+ candidate = member.definition.default({ ...buildConfigFragment() });
3185
+ } finally {
3186
+ callbackScope.owner = previousOwner;
3187
+ }
3188
+ assertSyncValue(candidate, "State", key, "default");
2189
3189
  hasCandidate = true;
2190
3190
  }
2191
3191
  if (hasCandidate) primitive.internal.attemptSet(candidate);
3192
+ primitive.internal.captureInitial();
2192
3193
  }
2193
3194
  }
2194
3195
  for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
@@ -2196,17 +3197,12 @@ function createWidgetSystemRuntime(blueprint, options) {
2196
3197
  if (node === void 0 || !node.resolved) continue;
2197
3198
  const entry = registry.get(nodeId);
2198
3199
  if (entry === void 0) continue;
2199
- const buildConfigFragment = buildConfigFragmentFor(node);
2200
- const emitFragment = readWidgetPluginDefinition(node.plugin).events === null ? Object.freeze({}) : Object.freeze({ emit: buildEventEmitter(entry.events) });
2201
- for (const [name, member] of node.properties) {
2202
- const deps = materializeDependencyTree(member.deps, {
2203
- consumer: "property",
2204
- ownerWidgetId: node.id,
2205
- ownerName: name,
2206
- registry,
2207
- nodes: compiled.nodes,
2208
- context
2209
- });
3200
+ const buildConfigFragment = configFragments[nodeId];
3201
+ const onDiagnosticsCommitted = commitHooks[nodeId];
3202
+ const definition = readWidgetPluginDefinition(node.plugin);
3203
+ for (const member of node.properties.values()) {
3204
+ const { name } = member;
3205
+ const owner = createCallbackOwner(null, null);
2210
3206
  const primitive = createPropertyPrimitive(context, {
2211
3207
  widgetId: node.id,
2212
3208
  name,
@@ -2214,19 +3210,17 @@ function createWidgetSystemRuntime(blueprint, options) {
2214
3210
  buildConfigFragment,
2215
3211
  selfNode: node.publicNode,
2216
3212
  blueprintView,
2217
- deps
2218
- });
2219
- entry.properties.set(name, primitive);
2220
- }
2221
- for (const [name, member] of node.methods) {
2222
- const deps = materializeDependencyTree(member.deps, {
2223
- consumer: "method",
2224
- ownerWidgetId: node.id,
2225
- ownerName: name,
3213
+ depsTree: member.deps,
2226
3214
  registry,
2227
3215
  nodes: compiled.nodes,
2228
- context
3216
+ owner,
3217
+ onDiagnosticsCommitted
2229
3218
  });
3219
+ entry.properties.set(name, primitive);
3220
+ }
3221
+ for (const member of node.methods.values()) {
3222
+ const { name } = member;
3223
+ const owner = createCallbackOwner(node.id, name, member.definition.emits);
2230
3224
  const primitive = createMethodPrimitive(context, {
2231
3225
  widgetId: node.id,
2232
3226
  name,
@@ -2234,22 +3228,28 @@ function createWidgetSystemRuntime(blueprint, options) {
2234
3228
  buildConfigFragment,
2235
3229
  selfNode: node.publicNode,
2236
3230
  blueprintView,
2237
- deps,
2238
- emitFragment
3231
+ depsTree: member.deps,
3232
+ registry,
3233
+ nodes: compiled.nodes,
3234
+ pluginType: node.type,
3235
+ eventDefinitions: definition.events,
3236
+ events: definition.events === null ? null : entry.events,
3237
+ owner,
3238
+ onDiagnosticsCommitted
2239
3239
  });
2240
3240
  entry.methods.set(name, primitive);
2241
3241
  }
2242
3242
  }
2243
3243
  const runtimeWidgetsByNodeId = /* @__PURE__ */ new Map();
2244
3244
  const nodeIdByRuntimeWidget = /* @__PURE__ */ new Map();
2245
- for (const [nodeId, entry] of registry) {
3245
+ for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2246
3246
  const node = compiled.nodes[nodeId];
2247
- if (node === void 0 || !node.resolved) continue;
2248
- const runtimeWidget = buildRuntimeWidget(context, node, entry);
3247
+ const entry = registry.get(nodeId);
3248
+ if (node === void 0 || !node.resolved || entry === void 0) continue;
3249
+ const runtimeWidget = buildRuntimeWidget(context, node, entry, stateLedger, stateStart[nodeId], stateEnd[nodeId]);
2249
3250
  runtimeWidgetsByNodeId.set(nodeId, runtimeWidget);
2250
3251
  nodeIdByRuntimeWidget.set(runtimeWidget, nodeId);
2251
3252
  }
2252
- const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
2253
3253
  function getWidget(id) {
2254
3254
  context.assertActive();
2255
3255
  const publicNode = blueprint.getWidget(id);
@@ -2258,14 +3258,36 @@ function createWidgetSystemRuntime(blueprint, options) {
2258
3258
  if (nodeId === void 0) return null;
2259
3259
  return runtimeWidgetsByNodeId.get(nodeId) ?? null;
2260
3260
  }
3261
+ function resetState() {
3262
+ restoreInitialState(context, stateLedger, 0, stateLedger.states.length);
3263
+ }
3264
+ function snapshotState() {
3265
+ context.assertActive();
3266
+ const snapshot = {};
3267
+ for (const nodeId of compiled.semanticOrder) {
3268
+ const node = compiled.nodes[nodeId];
3269
+ const entry = registry.get(nodeId);
3270
+ if (node === void 0 || !node.resolved || entry === void 0) continue;
3271
+ let values = null;
3272
+ for (const key of entry.state.keys()) {
3273
+ const value = entry.state.get(key).internal.get();
3274
+ if (value !== null) defineOwnValue(values ??= {}, key, value);
3275
+ }
3276
+ if (values !== null) defineOwnValue(snapshot, node.id, values);
3277
+ }
3278
+ return snapshot;
3279
+ }
2261
3280
  const runtime = {
2262
3281
  blueprint,
2263
3282
  get isDisposed() {
2264
3283
  return context.isDisposed();
2265
3284
  },
2266
3285
  getWidget,
3286
+ resetState,
3287
+ snapshotState,
2267
3288
  getDiagnostics: aggregate.getDiagnostics,
2268
3289
  subscribeDiagnostics: aggregate.subscribeDiagnostics,
3290
+ subscribeDisposal: context.subscribeDisposal,
2269
3291
  dispose: () => context.dispose()
2270
3292
  };
2271
3293
  runtime[runtimeInternals] = {
@@ -2295,12 +3317,13 @@ function readDepExpression(expression) {
2295
3317
  return expression[depExpressionBrand];
2296
3318
  }
2297
3319
  function createDepExpression(internals, readable) {
2298
- const expression = { [depExpressionBrand]: internals };
2299
- if (readable) expression.validate = (refinement) => createDepExpression({
2300
- reference: internals.reference,
2301
- refinements: [...internals.refinements, refinement]
2302
- }, true);
2303
- return expression;
3320
+ return readable ? {
3321
+ validate: (refinement) => createDepExpression({
3322
+ reference: internals.reference,
3323
+ refinements: [...internals.refinements, refinement]
3324
+ }, true),
3325
+ [depExpressionBrand]: internals
3326
+ } : { [depExpressionBrand]: internals };
2304
3327
  }
2305
3328
  function createTargetOperations(target) {
2306
3329
  const leaf = (operation, readable) => createDepExpression({
@@ -2360,13 +3383,27 @@ function createDependencyBuilder() {
2360
3383
  }
2361
3384
  //#endregion
2362
3385
  //#region src/blueprint/diagnostics.ts
3386
+ /**
3387
+ * A compile-time callback's collector. `close()` ends its plugin-facing lifetime once the callback has
3388
+ * returned or thrown; a later `addDiagnostic` / `hasAnyDiagnostic` call then throws.
3389
+ */
2363
3390
  function createCollector() {
2364
3391
  const items = [];
3392
+ let closed = false;
2365
3393
  return {
2366
3394
  items,
2367
3395
  collector: {
2368
- addDiagnostic: (diagnostic) => items.push(diagnostic),
2369
- hasAnyDiagnostic: () => items.length > 0
3396
+ addDiagnostic: (diagnostic) => {
3397
+ if (closed) throwClosedCollector("addDiagnostic");
3398
+ items.push(diagnostic);
3399
+ },
3400
+ hasAnyDiagnostic: () => {
3401
+ if (closed) throwClosedCollector("hasAnyDiagnostic");
3402
+ return items.length > 0;
3403
+ }
3404
+ },
3405
+ close: () => {
3406
+ closed = true;
2370
3407
  }
2371
3408
  };
2372
3409
  }
@@ -2379,6 +3416,20 @@ function widgetLocation(node) {
2379
3416
  node
2380
3417
  };
2381
3418
  }
3419
+ const sharedWidgetLocations = /* @__PURE__ */ new WeakMap();
3420
+ /**
3421
+ * The one frozen `widget` location of a node, for `related` lists that mention many nodes (duplicate ids and
3422
+ * ambiguous dependency targets build K lists of K-1 locations each). Every list that names the node holds this
3423
+ * same object, so a location is built and frozen once per node instead of once per list entry.
3424
+ */
3425
+ function sharedWidgetLocation(node) {
3426
+ let location = sharedWidgetLocations.get(node);
3427
+ if (location === void 0) {
3428
+ location = Object.freeze(widgetLocation(node));
3429
+ sharedWidgetLocations.set(node, location);
3430
+ }
3431
+ return location;
3432
+ }
2382
3433
  function slotLocation(node, slot) {
2383
3434
  return {
2384
3435
  type: "slot",
@@ -2408,23 +3459,9 @@ function methodLocation(node, name) {
2408
3459
  name
2409
3460
  };
2410
3461
  }
2411
- function definitionCode(message, path) {
2412
- if (path === void 0) return "invalid-widget-definition";
2413
- const first = path[0];
2414
- if (first === "id") return "invalid-widget-id";
2415
- if (first === "type") return message.startsWith("Unknown plugin type") ? "unknown-widget-type" : "invalid-widget-type";
2416
- if (first === "config") return message.includes("no config capability") ? "unexpected-widget-config" : "invalid-widget-definition";
2417
- if (first === "slots") {
2418
- if (message.includes("not declared")) return "undeclared-widget-slot";
2419
- if (message.includes("must be an array")) return "invalid-widget-slot";
2420
- if (message.includes("no slots capability")) return "unexpected-widget-slots";
2421
- return "invalid-widget-slots";
2422
- }
2423
- return "invalid-widget-definition";
2424
- }
2425
- function definitionDiagnostic(node, message, path, related) {
3462
+ function definitionDiagnostic(node, code, message, path, related) {
2426
3463
  return {
2427
- code: definitionCode(message, path),
3464
+ code,
2428
3465
  location: widgetLocation(node),
2429
3466
  message,
2430
3467
  ...path === void 0 ? {} : { path },
@@ -2449,20 +3486,10 @@ function structureDiagnostic(node, message, slot, index, related, reason) {
2449
3486
  ...reason === void 0 ? {} : { reason }
2450
3487
  };
2451
3488
  }
2452
- function dependencyCode(message) {
2453
- if (message.includes("ambiguous")) return "ambiguous-dependency-target";
2454
- if (message.includes("could not be resolved")) return "unresolved-dependency-target";
2455
- if (message.includes("does not exist")) return "missing-dependency-target";
2456
- if (message.includes("no state capability") || message.includes("no properties capability") || message.includes("no methods capability")) return "missing-dependency-capability";
2457
- if (message.includes("no state member") || message.includes("no property") || message.includes("no method")) return "missing-dependency-member";
2458
- if (message.includes("invokes writeful")) return "property-dependency-has-write-effects";
2459
- return "property-evaluation-cycle";
2460
- }
2461
- function dependencyDiagnostic(node, member, message, dependency, related) {
2462
- const location = member.type === "property" ? propertyLocation(node, member.name) : methodLocation(node, member.name);
3489
+ function dependencyDiagnostic(node, member, code, message, dependency, related) {
2463
3490
  return {
2464
- code: dependencyCode(message),
2465
- location,
3491
+ code,
3492
+ location: member.type === "property" ? propertyLocation(node, member.name) : methodLocation(node, member.name),
2466
3493
  message,
2467
3494
  ...dependency === void 0 ? {} : { dependency },
2468
3495
  ...toNonEmpty(related ?? []) === void 0 ? {} : { related: toNonEmpty(related ?? []) }
@@ -2482,28 +3509,42 @@ function dedupeBy(items, key) {
2482
3509
  }
2483
3510
  //#endregion
2484
3511
  //#region src/blueprint/deps.ts
3512
+ function createMemberIds(nodes, semanticOrder) {
3513
+ const offsetsByDefinition = /* @__PURE__ */ new Map();
3514
+ const baseByNodeId = [];
3515
+ const offsetsByNodeId = [];
3516
+ let count = 0;
3517
+ for (const nodeId of semanticOrder) {
3518
+ const node = nodes[nodeId];
3519
+ if (!node.resolved || node.plugin === null) continue;
3520
+ const definition = readWidgetPluginDefinition(node.plugin);
3521
+ let offsets = offsetsByDefinition.get(definition);
3522
+ if (offsets === void 0) {
3523
+ const properties = /* @__PURE__ */ new Map();
3524
+ const methods = /* @__PURE__ */ new Map();
3525
+ let size = 0;
3526
+ for (const name of definition.properties?.keys() ?? []) properties.set(name, size++);
3527
+ for (const name of definition.methods?.keys() ?? []) methods.set(name, size++);
3528
+ offsets = {
3529
+ properties,
3530
+ methods,
3531
+ size
3532
+ };
3533
+ offsetsByDefinition.set(definition, offsets);
3534
+ }
3535
+ baseByNodeId[nodeId] = count;
3536
+ offsetsByNodeId[nodeId] = offsets;
3537
+ count += offsets.size;
3538
+ }
3539
+ return {
3540
+ baseByNodeId,
3541
+ offsetsByNodeId,
3542
+ count
3543
+ };
3544
+ }
2485
3545
  function configFragment$1(node) {
2486
3546
  return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
2487
3547
  }
2488
- /**
2489
- * `WidgetMemberKey = string` is an arbitrary finite string domain (member names may themselves
2490
- * contain `:` / `->`), so naive template-literal concatenation of the six identity components is not
2491
- * injective: e.g. a from-name of `"a->method:0:b"` paired with a to-name of `"c"` serializes to the
2492
- * same string as a from-name of `"a"` paired with a to-name of `"b->property:0:c"`. `JSON.stringify`
2493
- * of the component tuple is injective over strings/numbers (it round-trips exactly through
2494
- * `JSON.parse`), so two distinct tuples can never collide regardless of what characters member names
2495
- * contain.
2496
- */
2497
- function edgeKey(fromKind, fromNodeId, fromName, toKind, toNodeId, toName) {
2498
- return JSON.stringify([
2499
- fromKind,
2500
- fromNodeId,
2501
- fromName,
2502
- toKind,
2503
- toNodeId,
2504
- toName
2505
- ]);
2506
- }
2507
3548
  function walkDeps(value, resolveLeaf) {
2508
3549
  if (isDepExpression(value)) return resolveLeaf(value);
2509
3550
  if (Array.isArray(value)) return Object.freeze(value.map((item) => walkDeps(item, resolveLeaf)));
@@ -2521,25 +3562,34 @@ function describeMissingTarget(target) {
2521
3562
  default: return "Dependency target does not exist.";
2522
3563
  }
2523
3564
  }
2524
- function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds) {
2525
- const { reference, refinements } = readDepExpression(leaf);
2526
- const { target, operation } = reference;
2527
- const owner = nodes[ownerNodeId];
2528
- const ownerPublicNode = owner.publicNode;
2529
- if (operation.type === "state-set" && member.type === "property") throw new TypeError("registerDeps() produced a state-set dependency owned by a Property; Property members must remain side-effect free. This is a plugin implementation bug.");
2530
- const absent = () => ({
2531
- [compiledDependencyBrand]: true,
3565
+ function absentDependency(reference, refinements) {
3566
+ return {
2532
3567
  status: "absent",
2533
3568
  reference,
2534
- refinements
2535
- });
2536
- const invalid = (targetNodeId) => ({
2537
- [compiledDependencyBrand]: true,
3569
+ refinements,
3570
+ [compiledDependencyBrand]: true
3571
+ };
3572
+ }
3573
+ function invalidDependency(reference, refinements, targetNodeId) {
3574
+ return targetNodeId === void 0 ? {
2538
3575
  status: "invalid",
2539
3576
  reference,
2540
3577
  refinements,
2541
- ...targetNodeId === void 0 ? {} : { targetNodeId }
2542
- });
3578
+ [compiledDependencyBrand]: true
3579
+ } : {
3580
+ status: "invalid",
3581
+ reference,
3582
+ refinements,
3583
+ targetNodeId,
3584
+ [compiledDependencyBrand]: true
3585
+ };
3586
+ }
3587
+ function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, ownerMemberId, member, leaf, finalDiagnostics, memberIds, edges, edgeKeys, directWriteSeeds) {
3588
+ const { reference, refinements } = readDepExpression(leaf);
3589
+ const { target, operation } = reference;
3590
+ const owner = nodes[ownerNodeId];
3591
+ const ownerPublicNode = owner.publicNode;
3592
+ if (operation.type === "state-set" && member.type === "property") throw new TypeError("registerDeps() produced a state-set dependency owned by a Property; Property members must remain side-effect free. This is a plugin implementation bug.");
2543
3593
  let candidateIds;
2544
3594
  switch (target.type) {
2545
3595
  case "self":
@@ -2554,84 +3604,99 @@ function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member,
2554
3604
  case "widget": candidateIds = nodeIdsByWidgetId.get(target.widgetId) ?? [];
2555
3605
  }
2556
3606
  if (candidateIds.length === 0) {
2557
- if ((target.type === "parent" || target.type === "widget") && target.optional) return absent();
2558
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, describeMissingTarget(target), reference));
2559
- return invalid();
3607
+ if ((target.type === "parent" || target.type === "widget") && target.optional) return absentDependency(reference, refinements);
3608
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-target", describeMissingTarget(target), reference));
3609
+ return invalidDependency(reference, refinements);
2560
3610
  }
2561
3611
  if (candidateIds.length > 1) {
2562
- const related = candidateIds.map((id) => widgetLocation(nodes[id].publicNode));
2563
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target is ambiguous: multiple widgets share that id.", reference, related));
2564
- return invalid();
3612
+ const related = candidateIds.map((id) => sharedWidgetLocation(nodes[id].publicNode));
3613
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "ambiguous-dependency-target", "Dependency target is ambiguous: multiple widgets share that id.", reference, related));
3614
+ return invalidDependency(reference, refinements);
2565
3615
  }
2566
3616
  const targetNodeId = candidateIds[0];
2567
3617
  const targetWorking = nodes[targetNodeId];
2568
3618
  if (!targetWorking.resolved) {
2569
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target could not be resolved to a widget.", reference, [widgetLocation(targetWorking.publicNode)]));
2570
- return invalid(targetNodeId);
3619
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "unresolved-dependency-target", "Dependency target could not be resolved to a widget.", reference, [widgetLocation(targetWorking.publicNode)]));
3620
+ return invalidDependency(reference, refinements, targetNodeId);
2571
3621
  }
2572
3622
  const targetDefinition = readWidgetPluginDefinition(targetWorking.plugin);
2573
3623
  const targetPublicNode = targetWorking.publicNode;
2574
3624
  if (operation.type === "state-get" || operation.type === "state-set") {
2575
3625
  if (targetDefinition.state === null) {
2576
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no state capability.", reference, [widgetLocation(targetPublicNode)]));
2577
- return invalid(targetNodeId);
3626
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no state capability.", reference, [widgetLocation(targetPublicNode)]));
3627
+ return invalidDependency(reference, refinements, targetNodeId);
2578
3628
  }
2579
3629
  if (!targetDefinition.state.has(operation.key)) {
2580
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no state member "${operation.key}".`, reference, [widgetLocation(targetPublicNode)]));
2581
- return invalid(targetNodeId);
3630
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no state member "${operation.key}".`, reference, [widgetLocation(targetPublicNode)]));
3631
+ return invalidDependency(reference, refinements, targetNodeId);
2582
3632
  }
2583
3633
  if (operation.type === "state-set" && member.type === "method") directWriteSeeds.add(`${ownerNodeId}:${member.name}`);
2584
3634
  } else if (operation.type === "property-get") {
2585
3635
  if (targetDefinition.properties === null) {
2586
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no properties capability.", reference, [widgetLocation(targetPublicNode)]));
2587
- return invalid(targetNodeId);
3636
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no properties capability.", reference, [widgetLocation(targetPublicNode)]));
3637
+ return invalidDependency(reference, refinements, targetNodeId);
2588
3638
  }
2589
3639
  if (!targetDefinition.properties.has(operation.name)) {
2590
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no property "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2591
- return invalid(targetNodeId);
2592
- }
2593
- const key = edgeKey(member.type, ownerNodeId, member.name, "property", targetNodeId, operation.name);
2594
- if (!edges.has(key)) edges.set(key, {
2595
- fromKind: member.type,
2596
- fromNodeId: ownerNodeId,
2597
- fromName: member.name,
2598
- toKind: "property",
2599
- toNodeId: targetNodeId,
2600
- toName: operation.name,
2601
- reference
2602
- });
3640
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no property "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
3641
+ return invalidDependency(reference, refinements, targetNodeId);
3642
+ }
3643
+ const toId = memberIds.baseByNodeId[targetNodeId] + memberIds.offsetsByNodeId[targetNodeId].properties.get(operation.name);
3644
+ const key = ownerMemberId * memberIds.count + toId;
3645
+ if (!edgeKeys.has(key)) {
3646
+ edgeKeys.add(key);
3647
+ edges.push({
3648
+ fromKind: member.type,
3649
+ fromNodeId: ownerNodeId,
3650
+ fromName: member.name,
3651
+ fromId: ownerMemberId,
3652
+ toKind: "property",
3653
+ toNodeId: targetNodeId,
3654
+ toName: operation.name,
3655
+ toId,
3656
+ reference
3657
+ });
3658
+ }
2603
3659
  } else {
2604
3660
  if (targetDefinition.methods === null) {
2605
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no methods capability.", reference, [widgetLocation(targetPublicNode)]));
2606
- return invalid(targetNodeId);
3661
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-capability", "Dependency target has no methods capability.", reference, [widgetLocation(targetPublicNode)]));
3662
+ return invalidDependency(reference, refinements, targetNodeId);
2607
3663
  }
2608
3664
  if (!targetDefinition.methods.has(operation.name)) {
2609
- finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no method "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2610
- return invalid(targetNodeId);
2611
- }
2612
- const key = edgeKey(member.type, ownerNodeId, member.name, "method", targetNodeId, operation.name);
2613
- if (!edges.has(key)) edges.set(key, {
2614
- fromKind: member.type,
2615
- fromNodeId: ownerNodeId,
2616
- fromName: member.name,
2617
- toKind: "method",
2618
- toNodeId: targetNodeId,
2619
- toName: operation.name,
2620
- reference
2621
- });
3665
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "missing-dependency-member", `Dependency target has no method "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
3666
+ return invalidDependency(reference, refinements, targetNodeId);
3667
+ }
3668
+ const toId = memberIds.baseByNodeId[targetNodeId] + memberIds.offsetsByNodeId[targetNodeId].methods.get(operation.name);
3669
+ const key = ownerMemberId * memberIds.count + toId;
3670
+ if (!edgeKeys.has(key)) {
3671
+ edgeKeys.add(key);
3672
+ edges.push({
3673
+ fromKind: member.type,
3674
+ fromNodeId: ownerNodeId,
3675
+ fromName: member.name,
3676
+ fromId: ownerMemberId,
3677
+ toKind: "method",
3678
+ toNodeId: targetNodeId,
3679
+ toName: operation.name,
3680
+ toId,
3681
+ reference
3682
+ });
3683
+ }
2622
3684
  }
2623
3685
  return {
2624
- [compiledDependencyBrand]: true,
2625
3686
  status: "resolved",
2626
3687
  targetNodeId,
2627
3688
  reference,
2628
- refinements
3689
+ refinements,
3690
+ [compiledDependencyBrand]: true
2629
3691
  };
2630
3692
  }
2631
3693
  function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics) {
2632
- const edges = /* @__PURE__ */ new Map();
3694
+ const memberIds = createMemberIds(nodes, semanticOrder);
3695
+ const edges = [];
3696
+ const edgeKeys = /* @__PURE__ */ new Set();
2633
3697
  const directWriteSeeds = /* @__PURE__ */ new Set();
2634
- const resolve = (ownerNodeId, member, leaf) => resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds);
3698
+ const directEmitSeeds = /* @__PURE__ */ new Set();
3699
+ const resolve = (ownerNodeId, ownerMemberId, member, leaf) => resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, ownerMemberId, member, leaf, finalDiagnostics, memberIds, edges, edgeKeys, directWriteSeeds);
2635
3700
  for (const nodeId of semanticOrder) {
2636
3701
  const node = nodes[nodeId];
2637
3702
  if (!node.resolved || node.plugin === null) continue;
@@ -2639,13 +3704,12 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2639
3704
  if (definition.properties === null) continue;
2640
3705
  const configFrag = configFragment$1(node);
2641
3706
  for (const [name, propertyDefinition] of definition.properties) {
2642
- const dep = createDependencyBuilder();
2643
3707
  let rawDeps = {};
2644
3708
  if (propertyDefinition.registerDeps !== void 0) {
2645
3709
  rawDeps = propertyDefinition.registerDeps({
2646
3710
  widget: compileFacade.facadeForNodeId(nodeId),
2647
3711
  blueprint: compileFacade.view,
2648
- dep,
3712
+ dep: createDependencyBuilder(),
2649
3713
  ...configFrag
2650
3714
  });
2651
3715
  assertSyncValue(rawDeps, `Property "${name}"'s registerDeps`);
@@ -2654,7 +3718,8 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2654
3718
  type: "property",
2655
3719
  name
2656
3720
  };
2657
- const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
3721
+ const ownerMemberId = memberIds.baseByNodeId[nodeId] + memberIds.offsetsByNodeId[nodeId].properties.get(name);
3722
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, ownerMemberId, member, leaf));
2658
3723
  node.properties.set(name, {
2659
3724
  name,
2660
3725
  definition: propertyDefinition,
@@ -2669,13 +3734,12 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2669
3734
  if (definition.methods === null) continue;
2670
3735
  const configFrag = configFragment$1(node);
2671
3736
  for (const [name, methodDefinition] of definition.methods) {
2672
- const dep = createDependencyBuilder();
2673
3737
  let rawDeps = {};
2674
3738
  if (methodDefinition.registerDeps !== void 0) {
2675
3739
  rawDeps = methodDefinition.registerDeps({
2676
3740
  widget: compileFacade.facadeForNodeId(nodeId),
2677
3741
  blueprint: compileFacade.view,
2678
- dep,
3742
+ dep: createDependencyBuilder(),
2679
3743
  ...configFrag
2680
3744
  });
2681
3745
  assertSyncValue(rawDeps, `Method "${name}"'s registerDeps`);
@@ -2684,115 +3748,197 @@ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId
2684
3748
  type: "method",
2685
3749
  name
2686
3750
  };
2687
- const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
3751
+ const ownerMemberId = memberIds.baseByNodeId[nodeId] + memberIds.offsetsByNodeId[nodeId].methods.get(name);
3752
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, ownerMemberId, member, leaf));
2688
3753
  node.methods.set(name, {
2689
3754
  name,
2690
3755
  definition: methodDefinition,
2691
3756
  deps,
2692
- transitivelyWrites: false
3757
+ transitivelyWrites: false,
3758
+ transitivelyEmits: false
2693
3759
  });
3760
+ if (methodDefinition.emits !== void 0 && methodDefinition.emits.length > 0) directEmitSeeds.add(`${nodeId}:${name}`);
2694
3761
  }
2695
3762
  }
2696
3763
  return {
2697
3764
  edges,
2698
- directWriteSeeds
3765
+ memberCount: memberIds.count,
3766
+ directWriteSeeds,
3767
+ directEmitSeeds
2699
3768
  };
2700
3769
  }
2701
3770
  //#endregion
2702
3771
  //#region src/blueprint/graph.ts
2703
- function memberKey(kind, nodeId, name) {
2704
- return `${kind}:${nodeId}:${name}`;
2705
- }
2706
3772
  function memberLocation(nodes, ref) {
2707
3773
  const node = nodes[ref.nodeId].publicNode;
2708
3774
  return ref.kind === "property" ? propertyLocation(node, ref.name) : methodLocation(node, ref.name);
2709
3775
  }
3776
+ /** The effects a Method can have, as flags: it writes State, it emits an Event. */
3777
+ const WRITES = 1;
3778
+ const EMITS = 2;
2710
3779
  /**
2711
- * Runs the write-effect fixed point over Method->Method edges, marking transitively-writeful methods
2712
- * on each node's already-built `CompiledMethodMember` map.
3780
+ * Propagates effects over Method->Method edges: a Method writes when it directly writes State or invokes a
3781
+ * Method that writes, and emits when it declares an Event in `emits` or invokes a Method that emits.
3782
+ * One work list over a callee->callers adjacency built once; a caller is revisited only when it gains a
3783
+ * flag, so each Method is queued at most twice. Marks `transitivelyWrites` / `transitivelyEmits` on each
3784
+ * node's already-built `CompiledMethodMember` map and returns the flags by `${nodeId}:${name}` key.
2713
3785
  */
2714
- function computeWritefulMethods(nodes, edges, directWriteSeeds) {
2715
- const writeful = new Set(directWriteSeeds);
2716
- const methodEdges = [...edges.values()].filter((edge) => edge.fromKind === "method" && edge.toKind === "method");
2717
- let changed = true;
2718
- while (changed) {
2719
- changed = false;
2720
- for (const edge of methodEdges) {
2721
- const fromKey = `${edge.fromNodeId}:${edge.fromName}`;
2722
- const toKey = `${edge.toNodeId}:${edge.toName}`;
2723
- if (writeful.has(toKey) && !writeful.has(fromKey)) {
2724
- writeful.add(fromKey);
2725
- changed = true;
3786
+ function computeMethodEffects(nodes, edges, directWriteSeeds, directEmitSeeds) {
3787
+ const effects = /* @__PURE__ */ new Map();
3788
+ for (const key of directWriteSeeds) effects.set(key, WRITES);
3789
+ for (const key of directEmitSeeds) effects.set(key, (effects.get(key) ?? 0) | EMITS);
3790
+ const callersOf = /* @__PURE__ */ new Map();
3791
+ for (const edge of edges) {
3792
+ if (edge.fromKind !== "method" || edge.toKind !== "method") continue;
3793
+ const toKey = `${edge.toNodeId}:${edge.toName}`;
3794
+ const fromKey = `${edge.fromNodeId}:${edge.fromName}`;
3795
+ const callers = callersOf.get(toKey);
3796
+ if (callers === void 0) callersOf.set(toKey, [fromKey]);
3797
+ else callers.push(fromKey);
3798
+ }
3799
+ const workList = [...effects.keys()];
3800
+ for (let index = 0; index < workList.length; index++) {
3801
+ const callee = workList[index];
3802
+ const calleeEffects = effects.get(callee);
3803
+ for (const caller of callersOf.get(callee) ?? []) {
3804
+ const callerEffects = effects.get(caller) ?? 0;
3805
+ if ((callerEffects | calleeEffects) !== callerEffects) {
3806
+ effects.set(caller, callerEffects | calleeEffects);
3807
+ workList.push(caller);
2726
3808
  }
2727
3809
  }
2728
3810
  }
2729
3811
  for (const node of nodes) {
2730
3812
  if (!node.resolved) continue;
2731
- for (const [name, member] of node.methods) if (writeful.has(`${node.nodeId}:${name}`) && !member.transitivelyWrites) node.methods.set(name, {
2732
- ...member,
2733
- transitivelyWrites: true
2734
- });
3813
+ for (const [name, member] of node.methods) {
3814
+ const flags = effects.get(`${node.nodeId}:${name}`) ?? 0;
3815
+ if (flags !== 0) node.methods.set(name, {
3816
+ ...member,
3817
+ transitivelyWrites: (flags & WRITES) !== 0,
3818
+ transitivelyEmits: (flags & EMITS) !== 0
3819
+ });
3820
+ }
2735
3821
  }
2736
- return writeful;
2737
- }
2738
- function emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics) {
2739
- for (const edge of edges.values()) {
3822
+ return effects;
3823
+ }
3824
+ /** What the diagnostic message says about the invoked Method, by effect flags. */
3825
+ const effectWording = [
3826
+ "",
3827
+ "writes State",
3828
+ "emits an Event",
3829
+ "writes State and emits an Event"
3830
+ ];
3831
+ function emitPurityDiagnostics(nodes, edges, methodEffects, finalDiagnostics) {
3832
+ for (const edge of edges) {
2740
3833
  if (edge.fromKind !== "property" || edge.toKind !== "method") continue;
2741
- if (!writefulMethods.has(`${edge.toNodeId}:${edge.toName}`)) continue;
3834
+ const flags = methodEffects.get(`${edge.toNodeId}:${edge.toName}`) ?? 0;
3835
+ if (flags === 0) continue;
2742
3836
  const ownerNode = nodes[edge.fromNodeId].publicNode;
2743
3837
  const targetNode = nodes[edge.toNodeId].publicNode;
2744
3838
  finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
2745
3839
  type: "property",
2746
3840
  name: edge.fromName
2747
- }, `Property "${edge.fromName}" invokes writeful method "${edge.toName}".`, edge.reference, [methodLocation(targetNode, edge.toName)]));
3841
+ }, "property-dependency-has-side-effects", `Property "${edge.fromName}" invokes method "${edge.toName}", which ${effectWording[flags]} (itself or through the Methods it invokes).`, edge.reference, [methodLocation(targetNode, edge.toName)]));
2748
3842
  }
2749
3843
  }
2750
3844
  /**
2751
- * Tarjan's strongly-connected-components algorithm over the evaluation graph, visiting adjacency in
2752
- * `memberOrder` for determinism.
3845
+ * Evaluation-graph adjacency in compressed form: the targets of member `id` are
3846
+ * `targets[offsets[id]]` to `targets[offsets[id + 1] - 1]`, in edge-insertion order.
3847
+ */
3848
+ function buildAdjacency(edges, memberCount) {
3849
+ const offsets = new Int32Array(memberCount + 1);
3850
+ for (const edge of edges) offsets[edge.fromId + 1]++;
3851
+ for (let id = 0; id < memberCount; id++) offsets[id + 1] += offsets[id];
3852
+ const targets = new Int32Array(edges.length);
3853
+ const next = offsets.slice(0, memberCount);
3854
+ for (const edge of edges) targets[next[edge.fromId]++] = edge.toId;
3855
+ return {
3856
+ offsets,
3857
+ targets
3858
+ };
3859
+ }
3860
+ /**
3861
+ * Tarjan's strongly-connected-components algorithm over the evaluation graph, started from each member
3862
+ * in member order and visiting adjacency in edge-insertion order for determinism. Returns only the
3863
+ * cyclic components (more than one member, or one member with a self-loop), in the order Tarjan
3864
+ * completes them. A member without outgoing edges is a trivial component of its own and can never
3865
+ * take part in a cycle, so it is neither started from nor entered.
2753
3866
  */
2754
- function findStronglyConnectedComponents(memberOrder, adjacency) {
2755
- const indexOf = /* @__PURE__ */ new Map();
2756
- let indexCounter = 0;
2757
- const lowlink = /* @__PURE__ */ new Map();
2758
- const onStack = /* @__PURE__ */ new Set();
2759
- const stack = [];
3867
+ function findCyclicComponents(memberCount, offsets, targets) {
3868
+ const visitOrder = new Int32Array(memberCount);
3869
+ const lowlink = new Int32Array(memberCount);
3870
+ const onStack = new Uint8Array(memberCount);
3871
+ const hasSelfLoop = new Uint8Array(memberCount);
3872
+ const stack = new Int32Array(memberCount);
3873
+ const callStack = new Int32Array(memberCount);
3874
+ const cursor = new Int32Array(memberCount);
3875
+ let stackSize = 0;
3876
+ let visited = 0;
2760
3877
  const components = [];
2761
- function strongConnect(key) {
2762
- indexOf.set(key, indexCounter);
2763
- lowlink.set(key, indexCounter);
2764
- indexCounter++;
2765
- stack.push(key);
2766
- onStack.add(key);
2767
- for (const next of adjacency.get(key) ?? []) if (!indexOf.has(next)) {
2768
- strongConnect(next);
2769
- lowlink.set(key, Math.min(lowlink.get(key), lowlink.get(next)));
2770
- } else if (onStack.has(next)) lowlink.set(key, Math.min(lowlink.get(key), indexOf.get(next)));
2771
- if (lowlink.get(key) === indexOf.get(key)) {
2772
- const component = [];
2773
- let member;
2774
- do {
2775
- member = stack.pop();
2776
- onStack.delete(member);
2777
- component.push(member);
2778
- } while (member !== key);
2779
- components.push(component);
2780
- }
2781
- }
2782
- for (const key of memberOrder) if (!indexOf.has(key)) strongConnect(key);
3878
+ for (let root = 0; root < memberCount; root++) {
3879
+ if (visitOrder[root] !== 0 || offsets[root + 1] === offsets[root]) continue;
3880
+ let depth = 0;
3881
+ callStack[depth++] = root;
3882
+ visitOrder[root] = lowlink[root] = ++visited;
3883
+ cursor[root] = offsets[root];
3884
+ stack[stackSize++] = root;
3885
+ onStack[root] = 1;
3886
+ while (depth > 0) {
3887
+ const id = callStack[depth - 1];
3888
+ if (cursor[id] < offsets[id + 1]) {
3889
+ const next = targets[cursor[id]++];
3890
+ if (next === id) hasSelfLoop[id] = 1;
3891
+ if (visitOrder[next] === 0) {
3892
+ if (offsets[next + 1] === offsets[next]) continue;
3893
+ callStack[depth++] = next;
3894
+ visitOrder[next] = lowlink[next] = ++visited;
3895
+ cursor[next] = offsets[next];
3896
+ stack[stackSize++] = next;
3897
+ onStack[next] = 1;
3898
+ } else if (onStack[next] === 1) lowlink[id] = Math.min(lowlink[id], visitOrder[next]);
3899
+ continue;
3900
+ }
3901
+ depth--;
3902
+ if (lowlink[id] === visitOrder[id]) {
3903
+ const component = [];
3904
+ let member;
3905
+ do {
3906
+ member = stack[--stackSize];
3907
+ onStack[member] = 0;
3908
+ component.push(member);
3909
+ } while (member !== id);
3910
+ if (component.length > 1 || hasSelfLoop[id] === 1) components.push(component);
3911
+ }
3912
+ if (depth > 0) {
3913
+ const parent = callStack[depth - 1];
3914
+ lowlink[parent] = Math.min(lowlink[parent], lowlink[id]);
3915
+ }
3916
+ }
3917
+ }
2783
3918
  return components;
2784
3919
  }
2785
- function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics) {
2786
- const refByKey = /* @__PURE__ */ new Map();
2787
- for (const ref of memberOrder) refByKey.set(memberKey(ref.kind, ref.nodeId, ref.name), ref);
2788
- const orderIndex = /* @__PURE__ */ new Map();
2789
- memberOrderKeys.forEach((key, index) => orderIndex.set(key, index));
2790
- const components = findStronglyConnectedComponents(memberOrderKeys, adjacency);
3920
+ function emitCycleDiagnostics(nodes, semanticOrder, memberCount, edges, finalDiagnostics) {
3921
+ const { offsets, targets } = buildAdjacency(edges, memberCount);
3922
+ const components = findCyclicComponents(memberCount, offsets, targets);
3923
+ if (components.length === 0) return [];
3924
+ const memberOrder = [];
3925
+ for (const nodeId of semanticOrder) {
3926
+ const node = nodes[nodeId];
3927
+ if (!node.resolved) continue;
3928
+ for (const name of node.properties.keys()) memberOrder.push({
3929
+ nodeId,
3930
+ kind: "property",
3931
+ name
3932
+ });
3933
+ for (const name of node.methods.keys()) memberOrder.push({
3934
+ nodeId,
3935
+ kind: "method",
3936
+ name
3937
+ });
3938
+ }
2791
3939
  const invalidCycles = [];
2792
3940
  for (const component of components) {
2793
- const hasSelfLoop = component.length === 1 && (adjacency.get(component[0]) ?? []).includes(component[0]);
2794
- if (!(component.length > 1 || hasSelfLoop)) continue;
2795
- const refs = component.map((key) => refByKey.get(key)).sort((a, b) => orderIndex.get(memberKey(a.kind, a.nodeId, a.name)) - orderIndex.get(memberKey(b.kind, b.nodeId, b.name)));
3941
+ const refs = component.sort((a, b) => a - b).map((id) => memberOrder[id]);
2796
3942
  const properties = refs.filter((ref) => ref.kind === "property");
2797
3943
  if (properties.length === 0) continue;
2798
3944
  invalidCycles.push(refs.map((ref) => ({
@@ -2802,47 +3948,23 @@ function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, fi
2802
3948
  name: ref.name
2803
3949
  }
2804
3950
  })));
3951
+ const related = Object.freeze(refs.map((ref) => Object.freeze(memberLocation(nodes, ref))));
2805
3952
  for (const property of properties) {
2806
3953
  const ownerNode = nodes[property.nodeId].publicNode;
2807
- const related = refs.filter((ref) => ref !== property).map((ref) => memberLocation(nodes, ref));
2808
3954
  finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
2809
3955
  type: "property",
2810
3956
  name: property.name
2811
- }, `Property "${property.name}" participates in an evaluation cycle.`, void 0, related));
3957
+ }, "property-evaluation-cycle", `Property "${property.name}" participates in an evaluation cycle.`, void 0, related));
2812
3958
  }
2813
3959
  }
2814
3960
  return invalidCycles;
2815
3961
  }
2816
- function runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics) {
2817
- const writefulMethods = computeWritefulMethods(nodes, edges, directWriteSeeds);
2818
- emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics);
2819
- const memberOrder = [];
2820
- for (const nodeId of semanticOrder) {
2821
- const node = nodes[nodeId];
2822
- if (!node.resolved) continue;
2823
- for (const name of node.properties.keys()) memberOrder.push({
2824
- nodeId,
2825
- kind: "property",
2826
- name
2827
- });
2828
- for (const name of node.methods.keys()) memberOrder.push({
2829
- nodeId,
2830
- kind: "method",
2831
- name
2832
- });
2833
- }
2834
- const memberOrderKeys = memberOrder.map((ref) => memberKey(ref.kind, ref.nodeId, ref.name));
2835
- const adjacency = /* @__PURE__ */ new Map();
2836
- for (const edge of edges.values()) {
2837
- const fromKey = memberKey(edge.fromKind, edge.fromNodeId, edge.fromName);
2838
- const toKey = memberKey(edge.toKind, edge.toNodeId, edge.toName);
2839
- const list = adjacency.get(fromKey);
2840
- if (list === void 0) adjacency.set(fromKey, [toKey]);
2841
- else list.push(toKey);
2842
- }
3962
+ function runGraphAnalysis(nodes, semanticOrder, edges, memberCount, directWriteSeeds, directEmitSeeds, finalDiagnostics) {
3963
+ const methodEffects = computeMethodEffects(nodes, edges, directWriteSeeds, directEmitSeeds);
3964
+ emitPurityDiagnostics(nodes, edges, methodEffects, finalDiagnostics);
2843
3965
  return {
2844
- writefulMethods,
2845
- invalidCycles: emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics)
3966
+ methodEffects,
3967
+ invalidCycles: emitCycleDiagnostics(nodes, semanticOrder, memberCount, edges, finalDiagnostics)
2846
3968
  };
2847
3969
  }
2848
3970
  //#endregion
@@ -2885,6 +4007,14 @@ function readOwnEnumerableStringKeys(object) {
2885
4007
  return null;
2886
4008
  }
2887
4009
  }
4010
+ /** The own keys of an authored widget node; `meta` is the reserved, uninterpreted extension key. */
4011
+ const RECOGNIZED_WIDGET_FIELDS = /* @__PURE__ */ new Set([
4012
+ "id",
4013
+ "type",
4014
+ "config",
4015
+ "slots",
4016
+ "meta"
4017
+ ]);
2888
4018
  function readArrayInfo(value) {
2889
4019
  try {
2890
4020
  if (!Array.isArray(value)) return {
@@ -2915,25 +4045,35 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
2915
4045
  diagnostics: EMPTY_DIAGNOSTICS
2916
4046
  };
2917
4047
  const publicNode = shell;
4048
+ const location = Object.freeze(placement.kind === "root" ? { type: "root" } : placement.kind === "slot" ? {
4049
+ type: "slot",
4050
+ parent: parentPublicNode,
4051
+ slot: placement.slot,
4052
+ index: placement.index
4053
+ } : {
4054
+ type: "raw-slot",
4055
+ parent: parentPublicNode,
4056
+ slot: placement.slot,
4057
+ index: placement.index
4058
+ });
4059
+ const sourcePath = Object.freeze(placement.kind === "root" ? [] : [
4060
+ ...ctx.nodes[parentNodeId].sourcePath,
4061
+ "slots",
4062
+ placement.slot,
4063
+ placement.index
4064
+ ]);
2918
4065
  const working = {
2919
4066
  nodeId,
2920
4067
  parentNodeId,
2921
4068
  source: rawValue,
2922
4069
  rawSlots: [],
2923
- location: Object.freeze(placement.kind === "root" ? { type: "root" } : placement.kind === "slot" ? {
2924
- type: "slot",
2925
- parent: parentPublicNode,
2926
- slot: placement.slot,
2927
- index: placement.index
2928
- } : {
2929
- type: "raw-slot",
2930
- parent: parentPublicNode,
2931
- slot: placement.slot,
2932
- index: placement.index
2933
- }),
4070
+ location,
4071
+ sourcePath,
2934
4072
  resolved: false,
2935
4073
  id: null,
2936
4074
  type: null,
4075
+ typeHint: null,
4076
+ repeatsAncestor: false,
2937
4077
  plugin: null,
2938
4078
  rawConfig: null,
2939
4079
  config: null,
@@ -2948,34 +4088,42 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
2948
4088
  const localDiagnostics = [];
2949
4089
  const raw = isRecoverableObject(rawValue) ? rawValue : null;
2950
4090
  if (raw === null) {
2951
- localDiagnostics.push(definitionDiagnostic(publicNode, "Widget definition must be a plain object."));
4091
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-definition", "Widget definition must be a plain object."));
2952
4092
  finalizeShell(shell, working);
2953
4093
  flushDiagnostics(ctx, localDiagnostics);
2954
4094
  return nodeId;
2955
4095
  }
2956
- if (ctx.activeSourceObjects.has(raw)) {
2957
- localDiagnostics.push(definitionDiagnostic(publicNode, "Widget definition contains a cyclic source reference."));
2958
- finalizeShell(shell, working);
2959
- flushDiagnostics(ctx, localDiagnostics);
2960
- return nodeId;
2961
- }
2962
- ctx.activeSourceObjects.add(raw);
2963
4096
  const idProperty = readOwnDataProperty(raw, "id");
2964
4097
  const rawId = idProperty.accessible ? idProperty.value : void 0;
2965
4098
  const hasValidId = idProperty.found && idProperty.accessible && typeof rawId === "string";
2966
- if (!hasValidId) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"id\" is missing or is not a string.", ["id"]));
2967
4099
  const typeProperty = readOwnDataProperty(raw, "type");
2968
4100
  const rawType = typeProperty.accessible ? typeProperty.value : void 0;
2969
4101
  const hasValidTypeShape = typeProperty.found && typeProperty.accessible && typeof rawType === "string";
4102
+ working.id = hasValidId ? rawId : null;
4103
+ working.typeHint = hasValidTypeShape ? rawType : null;
4104
+ if (sourcePath.length >= 256) {
4105
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-definition", `Widget definition is nested deeper than the maximum supported depth (256).`));
4106
+ finalizeShell(shell, working);
4107
+ flushDiagnostics(ctx, localDiagnostics);
4108
+ return nodeId;
4109
+ }
4110
+ if (ctx.activeSourceObjects.has(raw)) {
4111
+ working.repeatsAncestor = true;
4112
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-definition", "Widget definition contains a cyclic source reference."));
4113
+ finalizeShell(shell, working);
4114
+ flushDiagnostics(ctx, localDiagnostics);
4115
+ return nodeId;
4116
+ }
4117
+ ctx.activeSourceObjects.add(raw);
4118
+ if (!hasValidId) localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-id", "Widget \"id\" is missing or is not a string.", ["id"]));
2970
4119
  let plugin = null;
2971
- if (!hasValidTypeShape) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"type\" is missing or is not a string.", ["type"]));
4120
+ if (!hasValidTypeShape) localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-type", "Widget \"type\" is missing or is not a string.", ["type"]));
2972
4121
  else {
2973
4122
  plugin = ctx.pluginsByType.get(rawType) ?? null;
2974
- if (plugin === null) localDiagnostics.push(definitionDiagnostic(publicNode, `Unknown plugin type "${rawType}".`, ["type"]));
4123
+ if (plugin === null) localDiagnostics.push(definitionDiagnostic(publicNode, "unknown-widget-type", `Unknown plugin type "${rawType}".`, ["type"]));
2975
4124
  }
2976
4125
  const resolved = hasValidId && hasValidTypeShape && plugin !== null;
2977
4126
  working.resolved = resolved;
2978
- working.id = hasValidId ? rawId : null;
2979
4127
  if (resolved) {
2980
4128
  working.type = rawType;
2981
4129
  working.plugin = plugin;
@@ -2992,7 +4140,7 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
2992
4140
  working.config = resolved;
2993
4141
  } else {
2994
4142
  const rawConfigValue = configProperty.found ? configProperty.value : null;
2995
- const { collector, items } = createCollector();
4143
+ const { collector, items, close } = createCollector();
2996
4144
  let ok = false;
2997
4145
  try {
2998
4146
  const rawValidateResult = definition.config.validate(rawConfigValue, collector);
@@ -3002,6 +4150,8 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3002
4150
  finalizeShell(shell, working);
3003
4151
  flushDiagnostics(ctx, localDiagnostics);
3004
4152
  throw error;
4153
+ } finally {
4154
+ close();
3005
4155
  }
3006
4156
  if (ok && items.length === 0) {
3007
4157
  const resolved = definition.config.resolve(rawConfigValue);
@@ -3017,7 +4167,7 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3017
4167
  working.config = resolved;
3018
4168
  }
3019
4169
  }
3020
- } else if (configProperty.found) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"config\" but its plugin has no config capability.", ["config"]));
4170
+ } else if (configProperty.found) localDiagnostics.push(definitionDiagnostic(publicNode, "unexpected-widget-config", "Widget declares \"config\" but its plugin has no config capability.", ["config"]));
3021
4171
  }
3022
4172
  if (resolved && plugin !== null) {
3023
4173
  const definition = readWidgetPluginDefinition(plugin);
@@ -3027,6 +4177,10 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3027
4177
  });
3028
4178
  }
3029
4179
  recoverSlots(ctx, working, raw, resolved ? working.plugin : null, localDiagnostics);
4180
+ const ownKeys = readOwnEnumerableStringKeys(raw);
4181
+ if (ownKeys !== null) {
4182
+ for (const key of ownKeys) if (!RECOGNIZED_WIDGET_FIELDS.has(key)) localDiagnostics.push(definitionDiagnostic(publicNode, "unexpected-widget-field", `Widget field "${key}" is not recognized; extension data belongs under "meta".`, [key]));
4183
+ }
3030
4184
  ctx.activeSourceObjects.delete(raw);
3031
4185
  finalizeShell(shell, working);
3032
4186
  flushDiagnostics(ctx, localDiagnostics);
@@ -3043,6 +4197,9 @@ function finalizeShell(shell, working) {
3043
4197
  shell.config = working.config;
3044
4198
  }
3045
4199
  shell.slots = {};
4200
+ } else {
4201
+ shell.id = working.id;
4202
+ shell.type = working.typeHint;
3046
4203
  }
3047
4204
  }
3048
4205
  /**
@@ -3062,30 +4219,30 @@ function recoverSlots(ctx, working, raw, plugin, localDiagnostics) {
3062
4219
  return;
3063
4220
  }
3064
4221
  if (!slotsProperty.accessible) {
3065
- localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" could not be inspected safely.", ["slots"]));
4222
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-slots", "Widget \"slots\" could not be inspected safely.", ["slots"]));
3066
4223
  fillMissingDeclaredSlots();
3067
4224
  return;
3068
4225
  }
3069
4226
  const rawSlotsValue = slotsProperty.value;
3070
4227
  if (!isRecoverableObject(rawSlotsValue)) {
3071
- localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" must be a plain object.", ["slots"]));
4228
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-slots", "Widget \"slots\" must be a plain object.", ["slots"]));
3072
4229
  fillMissingDeclaredSlots();
3073
4230
  return;
3074
4231
  }
3075
- if (plugin !== null && declaredSlots === null) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"slots\" but its plugin has no slots capability.", ["slots"]));
4232
+ if (plugin !== null && declaredSlots === null) localDiagnostics.push(definitionDiagnostic(publicNode, "unexpected-widget-slots", "Widget declares \"slots\" but its plugin has no slots capability.", ["slots"]));
3076
4233
  const slotNames = readOwnEnumerableStringKeys(rawSlotsValue);
3077
4234
  if (slotNames === null) {
3078
- localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" could not be inspected safely.", ["slots"]));
4235
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-slots", "Widget \"slots\" could not be inspected safely.", ["slots"]));
3079
4236
  fillMissingDeclaredSlots();
3080
4237
  return;
3081
4238
  }
3082
4239
  for (const slotName of slotNames) {
3083
4240
  const slotProperty = readOwnDataProperty(rawSlotsValue, slotName);
3084
4241
  const isDeclared = declaredSlots !== null && declaredSlots.has(slotName);
3085
- if (declaredSlots !== null && !isDeclared) localDiagnostics.push(definitionDiagnostic(publicNode, `Widget slot "${slotName}" is not declared by its plugin.`, ["slots", slotName]));
4242
+ if (declaredSlots !== null && !isDeclared) localDiagnostics.push(definitionDiagnostic(publicNode, "undeclared-widget-slot", `Widget slot "${slotName}" is not declared by its plugin.`, ["slots", slotName]));
3086
4243
  const slotArray = readArrayInfo(slotProperty.value);
3087
4244
  if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
3088
- localDiagnostics.push(definitionDiagnostic(publicNode, `Widget slot "${slotName}" must be an array.`, ["slots", slotName]));
4245
+ localDiagnostics.push(definitionDiagnostic(publicNode, "invalid-widget-slot", `Widget slot "${slotName}" must be an array.`, ["slots", slotName]));
3089
4246
  continue;
3090
4247
  }
3091
4248
  const childNodeIds = [];
@@ -3108,8 +4265,12 @@ function recoverSlots(ctx, working, raw, plugin, localDiagnostics) {
3108
4265
  }
3109
4266
  fillMissingDeclaredSlots();
3110
4267
  }
4268
+ /**
4269
+ * One push per diagnostic, never `push(...diagnostics)`: a node with very many unknown keys produces more
4270
+ * diagnostics than an engine accepts as call arguments.
4271
+ */
3111
4272
  function flushDiagnostics(ctx, diagnostics) {
3112
- ctx.finalDiagnostics.push(...diagnostics);
4273
+ for (const diagnostic of diagnostics) ctx.finalDiagnostics.push(diagnostic);
3113
4274
  }
3114
4275
  /**
3115
4276
  * Fills in every resolved node's `.slots` public field from its (by-then complete) children and
@@ -3129,7 +4290,7 @@ function finalizeSlots(ctx) {
3129
4290
  function computeWidgetIdIndex(ctx) {
3130
4291
  const index = /* @__PURE__ */ new Map();
3131
4292
  for (const node of ctx.nodes) {
3132
- if (node.id === null) continue;
4293
+ if (node.id === null || node.repeatsAncestor) continue;
3133
4294
  const list = index.get(node.id);
3134
4295
  if (list === void 0) index.set(node.id, [node.nodeId]);
3135
4296
  else list.push(node.nodeId);
@@ -3139,10 +4300,11 @@ function computeWidgetIdIndex(ctx) {
3139
4300
  function emitDuplicateIdDiagnostics(ctx, index) {
3140
4301
  for (const ids of index.values()) {
3141
4302
  if (ids.length < 2) continue;
3142
- for (const nodeId of ids) {
4303
+ const locations = ids.map((id) => sharedWidgetLocation(ctx.nodes[id].publicNode));
4304
+ for (const [position, nodeId] of ids.entries()) {
3143
4305
  const node = ctx.nodes[nodeId];
3144
- const related = ids.filter((otherId) => otherId !== nodeId).map((otherId) => widgetLocation(ctx.nodes[otherId].publicNode));
3145
- ctx.finalDiagnostics.push(definitionDiagnostic(node.publicNode, `Duplicate widget id "${node.id}".`, ["id"], related));
4306
+ const related = locations.filter((_, otherPosition) => otherPosition !== position);
4307
+ ctx.finalDiagnostics.push(definitionDiagnostic(node.publicNode, "duplicate-widget-id", `Duplicate widget id "${node.id}".`, ["id"], related));
3146
4308
  }
3147
4309
  }
3148
4310
  }
@@ -3197,6 +4359,36 @@ function recoverBlueprint(system, definition) {
3197
4359
  }
3198
4360
  //#endregion
3199
4361
  //#region src/blueprint/structure.ts
4362
+ /**
4363
+ * A structure validator that reports a location absent from the Blueprint being compiled (an index outside
4364
+ * the slot, an undeclared slot, a node of another Blueprint) violates the callback contract, exactly like
4365
+ * the other callback-contract escapes (`blueprint/deps.ts`): it is an implementation bug, not an Issue.
4366
+ */
4367
+ function structureLocationViolation(scope, field, detail) {
4368
+ return /* @__PURE__ */ new TypeError(`${scope} reported a structure diagnostic whose ${field} ${detail}; this is a plugin implementation bug.`);
4369
+ }
4370
+ function assertSlotIndex(scope, field, index, childCount) {
4371
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= childCount) throw structureLocationViolation(scope, field, `is not an existing child index (the slot has ${childCount} children)`);
4372
+ }
4373
+ function assertDeclaredSlot(scope, field, node, slot) {
4374
+ if (typeof slot !== "string" || !node.resolved || !node.semanticSlots.has(slot)) throw structureLocationViolation(scope, field, "is not a slot declared by the widget's plugin");
4375
+ }
4376
+ /**
4377
+ * Validates one system-level location (`location` or a `related` entry) against the Blueprint being compiled.
4378
+ * `field` names the offending field path, e.g. `location` or `related[1]`.
4379
+ */
4380
+ function assertSystemLocation(nodes, resolveNodeId, field, location) {
4381
+ const scope = "System-level validateStructure";
4382
+ if (typeof location !== "object" || location === null) throw structureLocationViolation(scope, field, "is not a location object");
4383
+ const { type, node: locationNode, slot, index } = location;
4384
+ if (type !== "widget" && type !== "slot" && type !== "slot-child") throw structureLocationViolation(scope, `${field}.type`, "is not \"widget\", \"slot\" or \"slot-child\"");
4385
+ const nodeId = resolveNodeId(locationNode);
4386
+ if (nodeId === void 0) throw structureLocationViolation(scope, `${field}.node`, "is not a node of the Blueprint being compiled");
4387
+ if (type === "widget") return;
4388
+ const node = nodes[nodeId];
4389
+ assertDeclaredSlot(scope, `${field}.slot`, node, slot);
4390
+ if (type === "slot-child") assertSlotIndex(scope, `${field}.index`, index, node.semanticSlots.get(slot).length);
4391
+ }
3200
4392
  function configFragment(node) {
3201
4393
  return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
3202
4394
  }
@@ -3281,49 +4473,73 @@ function runStructureValidation(system, nodes, semanticOrder, compileFacade, fin
3281
4473
  if (!node.resolved || node.plugin === null) continue;
3282
4474
  const definition = readWidgetPluginDefinition(node.plugin);
3283
4475
  const publicNode = node.publicNode;
3284
- const widgetFacade = compileFacade.facadeForNodeId(nodeId);
3285
4476
  if (definition.slots !== null) for (const [slotName, slotDefinition] of definition.slots) {
3286
4477
  if (slotDefinition.validateStructure === void 0) continue;
3287
4478
  const children = (node.semanticSlots.get(slotName) ?? []).map((id) => compileFacade.facadeForNodeId(id));
3288
- const { collector, items } = createCollector();
3289
- assertSyncValue(slotDefinition.validateStructure({
3290
- widget: widgetFacade,
3291
- slot: slotName,
3292
- children,
3293
- blueprint: compileFacade.view,
3294
- ...configFragment(node),
3295
- ...collector
3296
- }), `Slot "${slotName}"'s validateStructure`);
3297
- for (const item of items) finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slotName, item.index));
4479
+ const { collector, items, close } = createCollector();
4480
+ try {
4481
+ const result = slotDefinition.validateStructure({
4482
+ widget: compileFacade.facadeForNodeId(nodeId),
4483
+ slot: slotName,
4484
+ children,
4485
+ blueprint: compileFacade.view,
4486
+ ...configFragment(node),
4487
+ ...collector
4488
+ });
4489
+ assertSyncValue(result, `Slot "${slotName}"'s validateStructure`);
4490
+ } finally {
4491
+ close();
4492
+ }
4493
+ for (const item of items) {
4494
+ if (item.index !== void 0) assertSlotIndex(`Slot "${slotName}"'s validateStructure`, "index", item.index, children.length);
4495
+ finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slotName, item.index, void 0, item.reason));
4496
+ }
3298
4497
  }
3299
4498
  if (definition.validateStructure !== null) {
3300
- const { collector, items } = createCollector();
3301
- assertSyncValue(definition.validateStructure({
3302
- widget: widgetFacade,
3303
- blueprint: compileFacade.view,
3304
- ...configFragment(node),
3305
- ...collector
3306
- }), `Plugin "${node.type}"'s validateStructure`);
4499
+ const { collector, items, close } = createCollector();
4500
+ try {
4501
+ const result = definition.validateStructure({
4502
+ widget: compileFacade.facadeForNodeId(nodeId),
4503
+ blueprint: compileFacade.view,
4504
+ ...configFragment(node),
4505
+ ...collector
4506
+ });
4507
+ assertSyncValue(result, `Plugin "${node.type}"'s validateStructure`);
4508
+ } finally {
4509
+ close();
4510
+ }
3307
4511
  for (const item of items) {
3308
4512
  const slot = "slot" in item ? item.slot : void 0;
3309
4513
  const index = "index" in item ? item.index : void 0;
3310
- finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slot, index));
4514
+ const scope = `Plugin "${node.type}"'s validateStructure`;
4515
+ if (slot !== void 0) {
4516
+ assertDeclaredSlot(scope, "slot", node, slot);
4517
+ if (index !== void 0) assertSlotIndex(scope, "index", index, node.semanticSlots.get(slot).length);
4518
+ } else if (index !== void 0) throw structureLocationViolation(scope, "index", "has no slot to be an index of");
4519
+ finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slot, index, void 0, item.reason));
3311
4520
  }
3312
4521
  }
3313
4522
  }
3314
4523
  if (system.validateStructure !== null) {
3315
- const { collector, items } = createCollector();
3316
- assertSyncValue(system.validateStructure({
3317
- blueprint: compileFacade.view,
3318
- ...collector
3319
- }), "System-level validateStructure");
4524
+ const { collector, items, close } = createCollector();
4525
+ try {
4526
+ const result = system.validateStructure({
4527
+ blueprint: compileFacade.view,
4528
+ ...collector
4529
+ });
4530
+ assertSyncValue(result, "System-level validateStructure");
4531
+ } finally {
4532
+ close();
4533
+ }
3320
4534
  const semanticOrderIndex = /* @__PURE__ */ new Map();
3321
4535
  semanticOrder.forEach((nodeId, index) => semanticOrderIndex.set(nodeId, index));
3322
4536
  for (const item of items) {
3323
4537
  const { location, related } = item;
4538
+ assertSystemLocation(nodes, compileFacade.resolveNodeId, "location", location);
4539
+ related?.forEach((relatedLocation, relatedIndex) => assertSystemLocation(nodes, compileFacade.resolveNodeId, `related[${relatedIndex}]`, relatedLocation));
3324
4540
  const nodeId = compileFacade.resolveNodeId(location.node);
3325
4541
  const realNode = nodeId !== void 0 ? nodes[nodeId].publicNode : location.node;
3326
- finalDiagnostics.push(structureDiagnostic(realNode, item.message, location.type === "widget" ? void 0 : location.slot, location.type === "slot-child" ? location.index : void 0, normalizeRelated(nodes, semanticOrderIndex, compileFacade.resolveNodeId, related)));
4542
+ finalDiagnostics.push(structureDiagnostic(realNode, item.message, location.type === "widget" ? void 0 : location.slot, location.type === "slot-child" ? location.index : void 0, normalizeRelated(nodes, semanticOrderIndex, compileFacade.resolveNodeId, related), item.reason));
3327
4543
  }
3328
4544
  }
3329
4545
  }
@@ -3356,6 +4572,11 @@ function createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeI
3356
4572
  if (nodeId === void 0) return null;
3357
4573
  return nodes[nodeId].location;
3358
4574
  },
4575
+ getSourcePath(node) {
4576
+ const nodeId = nodeIdByPublicNode.get(node);
4577
+ if (nodeId === void 0) return null;
4578
+ return nodes[nodeId].sourcePath;
4579
+ },
3359
4580
  getChildren(node) {
3360
4581
  const nodeId = nodeIdByPublicNode.get(node);
3361
4582
  if (nodeId === void 0) return EMPTY_CHILDREN;
@@ -3400,6 +4621,9 @@ function createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootN
3400
4621
  const slots = Object.create(null);
3401
4622
  for (const [slotName, childIds] of working.semanticSlots) slots[slotName] = Object.freeze(childIds.map((childId) => facadeForNodeId(childId)));
3402
4623
  shell.slots = Object.freeze(slots);
4624
+ } else {
4625
+ shell.id = working.id;
4626
+ shell.type = working.typeHint;
3403
4627
  }
3404
4628
  const facade = Object.freeze(shell);
3405
4629
  facadeByNodeId.set(nodeId, facade);
@@ -3494,13 +4718,15 @@ function buildCompiledNodes(nodes, diagnosticsByNode) {
3494
4718
  source: node.source,
3495
4719
  parentNodeId: node.parentNodeId,
3496
4720
  location: node.location,
4721
+ sourcePath: node.sourcePath,
3497
4722
  rawSlots: Object.freeze(node.rawSlots),
3498
4723
  diagnostics
3499
4724
  };
3500
4725
  if (!node.resolved) return {
3501
4726
  ...base,
3502
4727
  resolved: false,
3503
- id: node.id
4728
+ id: node.id,
4729
+ type: node.typeHint
3504
4730
  };
3505
4731
  return {
3506
4732
  ...base,
@@ -3517,20 +4743,31 @@ function buildCompiledNodes(nodes, diagnosticsByNode) {
3517
4743
  };
3518
4744
  });
3519
4745
  }
3520
- function compileBlueprint(system, definition) {
4746
+ /**
4747
+ * `sourceJsonProven` is set only for a value Core itself produced with `JSON.parse` (no reviver): such a
4748
+ * value can only leave the JSON domain through a non-finite number (`1e400`), so a cheap scan replaces the
4749
+ * full `inspectJsonValue` inspection and the result stays equivalent to `createBlueprint(JSON.parse(text))`.
4750
+ *
4751
+ * Compile-time plugin callbacks (config, structure, `registerDeps`) own no dependency or `emit` callables,
4752
+ * so a Blueprint compiled while a Method runs must not let them use that Method's (see `callbackScope`).
4753
+ */
4754
+ function compileBlueprint(system, definition, sourceJsonProven = false) {
4755
+ return runOutsideCallbacks(() => compileBlueprintOutsideCallbacks(system, definition, sourceJsonProven));
4756
+ }
4757
+ function compileBlueprintOutsideCallbacks(system, definition, sourceJsonProven) {
3521
4758
  const { nodes, rootNodeId, nodeIdByPublicNode, nodeIdsByWidgetId, finalDiagnostics, diagnosticsByNode } = recoverBlueprint(system, definition);
3522
- const jsonInspection = inspectJsonValue(definition);
4759
+ const jsonInspection = sourceJsonProven ? inspectParsedJsonValue(definition) : inspectJsonValue(definition);
3523
4760
  const sourceJsonCompatible = jsonInspection.compatible;
3524
- finalDiagnostics.push(...jsonInspection.diagnostics);
4761
+ for (const diagnostic of jsonInspection.diagnostics) finalDiagnostics.push(diagnostic);
3525
4762
  const semanticOrder = computeSemanticOrder(nodes, rootNodeId);
3526
4763
  const navigator = createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3527
4764
  const compileFacade = createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3528
4765
  runStructureValidation(system, nodes, semanticOrder, compileFacade, finalDiagnostics);
3529
- const { edges, directWriteSeeds } = resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics);
3530
- const analysis = runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics);
4766
+ const { edges, memberCount, directWriteSeeds, directEmitSeeds } = resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics);
4767
+ const analysis = runGraphAnalysis(nodes, semanticOrder, edges, memberCount, directWriteSeeds, directEmitSeeds, finalDiagnostics);
3531
4768
  finalizeDiagnosticsByNode(nodeIdByPublicNode, finalDiagnostics, diagnosticsByNode);
3532
- for (const list of diagnosticsByNode.values()) freezeDiagnosticSnapshot(list);
3533
4769
  freezeDiagnosticSnapshot(finalDiagnostics);
4770
+ for (const list of diagnosticsByNode.values()) Object.freeze(list);
3534
4771
  for (const node of nodes) {
3535
4772
  const shell = node.publicNode;
3536
4773
  shell.diagnostics = diagnosticsByNode.get(node.nodeId) ?? EMPTY_DIAGNOSTICS;
@@ -3562,6 +4799,7 @@ function compileBlueprint(system, definition) {
3562
4799
  getWidget: validNavigator.getWidget,
3563
4800
  getParent: validNavigator.getParent,
3564
4801
  getLocation: validNavigator.getLocation,
4802
+ getSourcePath: validNavigator.getSourcePath,
3565
4803
  getChildren: validNavigator.getChildren,
3566
4804
  getChildrenAt: validNavigator.getChildrenAt,
3567
4805
  diagnostics: EMPTY_DIAGNOSTICS,
@@ -3582,6 +4820,7 @@ function compileBlueprint(system, definition) {
3582
4820
  getWidget: jsonInvalidNavigator.getWidget,
3583
4821
  getParent: jsonInvalidNavigator.getParent,
3584
4822
  getLocation: jsonInvalidNavigator.getLocation,
4823
+ getSourcePath: jsonInvalidNavigator.getSourcePath,
3585
4824
  getChildren: jsonInvalidNavigator.getChildren,
3586
4825
  getChildrenAt: jsonInvalidNavigator.getChildrenAt,
3587
4826
  diagnostics: finalDiagnostics,
@@ -3597,6 +4836,7 @@ function compileBlueprint(system, definition) {
3597
4836
  getWidget: invalidNavigator.getWidget,
3598
4837
  getParent: invalidNavigator.getParent,
3599
4838
  getLocation: invalidNavigator.getLocation,
4839
+ getSourcePath: invalidNavigator.getSourcePath,
3600
4840
  getChildren: invalidNavigator.getChildren,
3601
4841
  getChildrenAt: invalidNavigator.getChildrenAt,
3602
4842
  diagnostics: finalDiagnostics,
@@ -3614,9 +4854,13 @@ function attachInternalsAndFreeze(blueprint, compiled) {
3614
4854
  //#endregion
3615
4855
  //#region src/system.ts
3616
4856
  /**
3617
- * Thrown by `createWidgetSystem` for an invalid plugin registration. Discriminate by class and `code`;
3618
- * `message` is not protocol.
4857
+ * Thrown by `createWidgetSystem` for invalid options or an invalid plugin registration. Discriminate by
4858
+ * class and `code`; `message` is not protocol. The options shape is checked first, then the plugin
4859
+ * entries in tuple order.
3619
4860
  *
4861
+ * - `invalid-options`: `options` is not an object, `options.plugins` is not an array, or
4862
+ * `options.validateStructure` is present (neither `undefined` nor `null`) but not a function.
4863
+ * `pluginIndex`, `pluginType` and `firstPluginIndex` are `null`.
3620
4864
  * - `foreign-plugin`: the entry at `pluginIndex` was not completed by this loaded module instance
3621
4865
  * (another module instance or a structural look-alike). `pluginType` is its `type` when a string,
3622
4866
  * else `null`. `firstPluginIndex` is `null`.
@@ -3629,7 +4873,7 @@ var WidgetSystemConfigurationError = class extends Error {
3629
4873
  pluginType;
3630
4874
  firstPluginIndex;
3631
4875
  name = "WidgetSystemConfigurationError";
3632
- constructor(code, pluginIndex, pluginType, firstPluginIndex = null, message = code === "foreign-plugin" ? `The widget plugin at index ${pluginIndex} was not created by this widget core instance.` : `Duplicate widget plugin type "${pluginType}" at index ${pluginIndex} (first registered at index ${firstPluginIndex}).`) {
4876
+ constructor(code, pluginIndex, pluginType, firstPluginIndex = null, message = code === "invalid-options" ? "The createWidgetSystem options are malformed." : code === "foreign-plugin" ? `The widget plugin at index ${pluginIndex} was not created by this widget core instance.` : `Duplicate widget plugin type "${pluginType}" at index ${pluginIndex} (first registered at index ${firstPluginIndex}).`) {
3633
4877
  super(message);
3634
4878
  this.code = code;
3635
4879
  this.pluginIndex = pluginIndex;
@@ -3637,6 +4881,21 @@ var WidgetSystemConfigurationError = class extends Error {
3637
4881
  this.firstPluginIndex = firstPluginIndex;
3638
4882
  }
3639
4883
  };
4884
+ function describeOptionValue(value) {
4885
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
4886
+ }
4887
+ function invalidOptions(problem) {
4888
+ return new WidgetSystemConfigurationError("invalid-options", null, null, null, `Invalid createWidgetSystem options: ${problem}.`);
4889
+ }
4890
+ /**
4891
+ * Checks the options shape before any plugin entry is inspected.
4892
+ */
4893
+ function assertWidgetSystemOptions(options) {
4894
+ if (typeof options !== "object" || options === null) throw invalidOptions(`expected an options object, got ${describeOptionValue(options)}`);
4895
+ const { plugins, validateStructure } = options;
4896
+ if (!Array.isArray(plugins)) throw invalidOptions(`"plugins" must be an array of widget plugins, got ${describeOptionValue(plugins)}`);
4897
+ if (validateStructure !== void 0 && validateStructure !== null && typeof validateStructure !== "function") throw invalidOptions(`"validateStructure" must be a function when provided, got ${describeOptionValue(validateStructure)}`);
4898
+ }
3640
4899
  /**
3641
4900
  * Best-effort read of a foreign entry's `type`; a throwing accessor must not leak as an uncoded failure.
3642
4901
  */
@@ -3649,9 +4908,11 @@ function readForeignPluginType(entry) {
3649
4908
  }
3650
4909
  }
3651
4910
  /**
3652
- * Creates an instance-scoped, immutable widget system. Duplicate `plugin.type` is rejected.
4911
+ * Creates an instance-scoped, immutable widget system. Malformed options, foreign plugins and duplicate
4912
+ * `plugin.type` are rejected with a `WidgetSystemConfigurationError`.
3653
4913
  */
3654
4914
  function createWidgetSystem(options) {
4915
+ assertWidgetSystemOptions(options);
3655
4916
  const plugins = Object.freeze([...options.plugins]);
3656
4917
  const pluginsByType = /* @__PURE__ */ new Map();
3657
4918
  const firstIndexByType = /* @__PURE__ */ new Map();
@@ -3675,14 +4936,15 @@ function createWidgetSystem(options) {
3675
4936
  plugins,
3676
4937
  validateStructure: options.validateStructure ?? null,
3677
4938
  catalog,
3678
- getPlugin(type) {
3679
- return pluginsByType.get(type);
3680
- },
4939
+ getPlugin: ((type) => pluginsByType.get(type) ?? null),
3681
4940
  createBlueprint(definition) {
3682
4941
  return compileBlueprint(system, definition);
4942
+ },
4943
+ createBlueprintFromJson(text) {
4944
+ return compileBlueprint(system, JSON.parse(text), true);
3683
4945
  }
3684
4946
  };
3685
4947
  return Object.freeze(system);
3686
4948
  }
3687
4949
  //#endregion
3688
- export { EMPTY_DIAGNOSTICS, WIDGET_CONFIG_JSON_SCHEMA_DIALECT, WidgetSystemConfigurationError, WidgetSystemRuntimeDisposedError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, createWidgetValueContract, normalizeSeparatedWidgetSource, separateWidgetSource };
4950
+ export { EMPTY_DIAGNOSTICS, MAX_JSON_DEPTH, WIDGET_CONFIG_JSON_SCHEMA_DIALECT, WidgetSystemConfigurationError, WidgetSystemRuntimeDisposedError, WidgetSystemRuntimeReentrancyError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, createWidgetValueContract, isJsonValue, normalizeSeparatedWidgetSource, separateWidgetSource, setIsolatedErrorHandler };