@deviltea/widget-core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,3891 @@
1
+ import { a as isCompiledDependency, i as compiledDependencyBrand, n as runtimeInternals, o as readCompiledBlueprint, r as blueprintInternals } from "./internals-DXFEmv8H.mjs";
2
+ import { computed, effect, endBatch, setActiveSub, signal, startBatch } from "alien-signals";
3
+ //#region src/diagnostic.ts
4
+ const EMPTY_DIAGNOSTICS = Object.freeze([]);
5
+ var WidgetSystemRuntimeDisposedError = class extends Error {
6
+ name = "WidgetSystemRuntimeDisposedError";
7
+ code = "runtime-disposed";
8
+ constructor(message = "The widget system runtime has been disposed.") {
9
+ super(message);
10
+ }
11
+ };
12
+ //#endregion
13
+ //#region src/runtime/adapter.ts
14
+ /**
15
+ * Invokes `listener(value)` with no active alien subscriber (restoring the previous one afterward) and
16
+ * isolates a synchronous throw so it cannot escape into the current alien-signals flush. Baseline
17
+ * reporting for an isolated exception is a queued microtask rethrow.
18
+ */
19
+ function invokeListenerIsolated(listener, value) {
20
+ const previous = setActiveSub(void 0);
21
+ try {
22
+ listener(value);
23
+ } catch (error) {
24
+ queueMicrotask(() => {
25
+ throw error;
26
+ });
27
+ } finally {
28
+ setActiveSub(previous);
29
+ }
30
+ }
31
+ /**
32
+ * Nesting depth of the calls that can drive an `alien-signals` evaluation/flush and therefore have to be
33
+ * back out of the reactive graph before a deferred propagation is safe to release: `RuntimeState`'s
34
+ * `attemptSet`, `RuntimeMethod`'s `invoke` and the tracked read of a Property's result computed. Purely
35
+ * local bookkeeping for {@link writeDeferringFlush}, not a semantic boundary of its own.
36
+ */
37
+ let operationDepth = 0;
38
+ /** Number of `startBatch()` calls {@link writeDeferringFlush} has opened and not yet closed. */
39
+ let deferredFlushDepth = 0;
40
+ /**
41
+ * Closes every batch level {@link writeDeferringFlush} left open, letting alien-signals flush the
42
+ * notifications it already queued.
43
+ *
44
+ * The loop condition is re-tested after every `endBatch()`: that flush can run an effect whose Property
45
+ * recompute commits its own diagnostic snapshot, which opens a fresh level this same drain must then close.
46
+ * A recompute that throws inside one of those flushes must not leave alien-signals permanently batched
47
+ * (every later flush in the Runtime's life would be silently suspended), so the remaining levels are
48
+ * closed before the throw is rethrown.
49
+ */
50
+ function releaseDeferredFlushes() {
51
+ while (deferredFlushDepth > 0) {
52
+ --deferredFlushDepth;
53
+ try {
54
+ endBatch();
55
+ } catch (error) {
56
+ releaseDeferredFlushes();
57
+ throw error;
58
+ }
59
+ }
60
+ }
61
+ /**
62
+ * Tracks one nesting level of the calls that can drive an evaluation, and releases every flush
63
+ * {@link writeDeferringFlush} deferred inside it once the outermost level is leaving.
64
+ *
65
+ * The release runs while the depth is still `1`, so a listener that the release's own flush invokes and
66
+ * that re-enters the Runtime cannot re-enter the drain loop. The decrement is unconditional: a Property
67
+ * recompute that throws inside the release's flush (`createTrackedSubscription` isolates the external
68
+ * listener, never the tracked read) must not leave the depth pinned above `0`, or every later call would
69
+ * look nested and no release would ever run again.
70
+ */
71
+ function runRuntimeOperation(fn) {
72
+ ++operationDepth;
73
+ try {
74
+ return fn();
75
+ } finally {
76
+ try {
77
+ if (operationDepth === 1) releaseDeferredFlushes();
78
+ } finally {
79
+ --operationDepth;
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Performs a signal write whose propagation must not be flushed while a computed may still be
85
+ * mid-evaluation, by holding an alien batch open until the outermost {@link runRuntimeOperation} frame on
86
+ * the stack is leaving — i.e. until nothing that could still be evaluating remains.
87
+ *
88
+ * Why this is required in pinned alien-signals@3.2.1 (`esm/index.mjs` / `esm/system.mjs`):
89
+ *
90
+ * - `signalOper` ends a changed write with `propagate(subs, ...)` followed by `if (!batchDepth) flush()`.
91
+ * A write performed from inside a computed's own evaluator therefore starts a *nested* flush that runs
92
+ * the effects the outer propagation had already queued — while the computed that queued them is still
93
+ * mid-`updateComputed`.
94
+ * - `updateComputed` sets `c.flags = 1 | 4` (`Mutable | RecursedCheck`) and only assigns
95
+ * `c.value = c.getter(...)` after the getter returns, so during that window the computed carries
96
+ * neither `Dirty` (16) nor `Pending` (32) and still holds its previous value.
97
+ * - `checkDirty` has no `RecursedCheck` branch: a queued effect whose dependency chain passes through
98
+ * that computed hits none of its `(1 | 16)` / `(1 | 32)` cases, concludes `dirty === false`, and then
99
+ * clears its own intermediate's `Pending` flag (`sub.flags &= ~32`). The intermediate is now marked
100
+ * clean while still holding a stale cached value, so the later `shallowPropagate` — which only
101
+ * upgrades subscribers that are still `Pending` — skips it for good: the effect never runs again and
102
+ * even an untracked `.get()` returns the stale cache.
103
+ *
104
+ * Keeping `batchDepth > 0` for the write removes the nested flush entirely: `propagate` still marks and
105
+ * queues every watcher through alien-signals' own bookkeeping, and the queue is drained later — by the
106
+ * flush that is already running (it re-reads the shared queue length) or by
107
+ * {@link runRuntimeOperation}'s release. Nothing here re-implements propagation, ordering or dedupe.
108
+ *
109
+ * The write itself is unconditional and immediate, so a snapshot is committed exactly where it was
110
+ * before: `pendingValue` is written synchronously and every later read commits it (`signalOper`'s read
111
+ * path runs `updateSignal` when the signal is `Dirty`), which keeps "the snapshot is committed by the
112
+ * time the operation's `ExecutionResult` is observable" true. Only the *notification* moves — never past
113
+ * the end of the operation that produced it.
114
+ *
115
+ * One consequence of using an alien batch as the deferral mechanism, rather than a normative rule about
116
+ * Runtime operations: while a level is open, alien-signals coalesces as it does inside any batch, so two
117
+ * writes to the *same* signal before the release notify its subscribers once, with the final value. This
118
+ * is not a new Runtime semantic — it is the ordinary behavior of the batching alien-signals already owns,
119
+ * already observable inside `RuntimeMethod.invoke`'s batch. Every actual completed recompute still
120
+ * notifies each of its own subscribers exactly once; alien-signals, not this module, decides which
121
+ * recomputes happen.
122
+ */
123
+ function writeDeferringFlush(write) {
124
+ if (operationDepth === 0) {
125
+ write();
126
+ return;
127
+ }
128
+ startBatch();
129
+ ++deferredFlushDepth;
130
+ write();
131
+ }
132
+ /**
133
+ * Creates a Runtime-owned public subscription: an alien `effect()` that tracks `read()`, skips the
134
+ * bootstrap run, and invokes `listener` through {@link invokeListenerIsolated} on every actual
135
+ * subsequent run. Returns an idempotent unsubscribe function registered with the Runtime's disposal
136
+ * bookkeeping.
137
+ */
138
+ function createTrackedSubscription(context, read, listener) {
139
+ let isBootstrap = true;
140
+ const rawDispose = effect(() => {
141
+ const value = read();
142
+ if (isBootstrap) {
143
+ isBootstrap = false;
144
+ return;
145
+ }
146
+ invokeListenerIsolated(listener, value);
147
+ });
148
+ return context.registerSubscription(rawDispose);
149
+ }
150
+ //#endregion
151
+ //#region src/json.ts
152
+ function jsonDiagnostic(path, reason) {
153
+ return {
154
+ code: "json-incompatible-value",
155
+ location: { type: "source" },
156
+ path: [...path],
157
+ reason,
158
+ message: `Authored source is outside the JSON domain (${reason}).`
159
+ };
160
+ }
161
+ function accessDiagnostic(path) {
162
+ return {
163
+ code: "source-access-failed",
164
+ location: { type: "source" },
165
+ path: [...path],
166
+ message: "Authored source could not be safely inspected."
167
+ };
168
+ }
169
+ function inspectJsonValueAt(value, path, active, diagnostics) {
170
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
171
+ if (typeof value === "number") {
172
+ if (!Number.isFinite(value)) diagnostics.push(jsonDiagnostic(path, "non-finite-number"));
173
+ return;
174
+ }
175
+ if (typeof value === "undefined") {
176
+ diagnostics.push(jsonDiagnostic(path, "undefined"));
177
+ return;
178
+ }
179
+ if (typeof value === "bigint") {
180
+ diagnostics.push(jsonDiagnostic(path, "bigint"));
181
+ return;
182
+ }
183
+ if (typeof value === "symbol") {
184
+ diagnostics.push(jsonDiagnostic(path, "symbol"));
185
+ return;
186
+ }
187
+ if (typeof value === "function") {
188
+ diagnostics.push(jsonDiagnostic(path, "function"));
189
+ return;
190
+ }
191
+ if (typeof value !== "object") return;
192
+ let isArray;
193
+ try {
194
+ isArray = Array.isArray(value);
195
+ } catch {
196
+ diagnostics.push(accessDiagnostic(path));
197
+ return;
198
+ }
199
+ if (active.has(value)) {
200
+ diagnostics.push(jsonDiagnostic(path, "cyclic-reference"));
201
+ return;
202
+ }
203
+ active.add(value);
204
+ try {
205
+ let prototype;
206
+ try {
207
+ prototype = Object.getPrototypeOf(value);
208
+ } catch {
209
+ diagnostics.push(accessDiagnostic(path));
210
+ return;
211
+ }
212
+ if (prototype !== (isArray ? Array.prototype : Object.prototype) && !(prototype === null && !isArray)) {
213
+ diagnostics.push(jsonDiagnostic(path, "unsupported-object-prototype"));
214
+ return;
215
+ }
216
+ let keys;
217
+ try {
218
+ keys = Reflect.ownKeys(value);
219
+ } catch {
220
+ diagnostics.push(accessDiagnostic(path));
221
+ return;
222
+ }
223
+ if (isArray) {
224
+ let length;
225
+ try {
226
+ const descriptor = Object.getOwnPropertyDescriptor(value, "length");
227
+ if (descriptor === void 0 || !("value" in descriptor) || typeof descriptor.value !== "number") {
228
+ diagnostics.push(accessDiagnostic(path));
229
+ return;
230
+ }
231
+ length = descriptor.value;
232
+ } catch {
233
+ diagnostics.push(accessDiagnostic(path));
234
+ return;
235
+ }
236
+ for (const key of keys) {
237
+ if (typeof key === "symbol") {
238
+ diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
239
+ continue;
240
+ }
241
+ if (key === "length") continue;
242
+ if (/^(?:0|[1-9]\d*)$/.test(key) && Number(key) < length) continue;
243
+ diagnostics.push(jsonDiagnostic([...path, key], "array-extra-property"));
244
+ }
245
+ for (let index = 0; index < length; index++) {
246
+ let descriptor;
247
+ try {
248
+ descriptor = Object.getOwnPropertyDescriptor(value, String(index));
249
+ } catch {
250
+ diagnostics.push(accessDiagnostic([...path, index]));
251
+ continue;
252
+ }
253
+ if (descriptor === void 0) {
254
+ diagnostics.push(jsonDiagnostic([...path, index], "sparse-array"));
255
+ continue;
256
+ }
257
+ if (!("value" in descriptor)) {
258
+ diagnostics.push(jsonDiagnostic([...path, index], "accessor-property"));
259
+ continue;
260
+ }
261
+ inspectJsonValueAt(descriptor.value, [...path, index], active, diagnostics);
262
+ }
263
+ return;
264
+ }
265
+ for (const key of keys) {
266
+ if (typeof key === "symbol") {
267
+ diagnostics.push(jsonDiagnostic([...path, key], "symbol-key"));
268
+ continue;
269
+ }
270
+ let descriptor;
271
+ try {
272
+ descriptor = Object.getOwnPropertyDescriptor(value, key);
273
+ } catch {
274
+ diagnostics.push(accessDiagnostic([...path, key]));
275
+ continue;
276
+ }
277
+ if (descriptor === void 0) {
278
+ diagnostics.push(accessDiagnostic([...path, key]));
279
+ continue;
280
+ }
281
+ if (!("value" in descriptor)) {
282
+ diagnostics.push(jsonDiagnostic([...path, key], "accessor-property"));
283
+ continue;
284
+ }
285
+ inspectJsonValueAt(descriptor.value, [...path, key], active, diagnostics);
286
+ }
287
+ } finally {
288
+ active.delete(value);
289
+ }
290
+ }
291
+ /**
292
+ * Inspect the complete authored candidate without invoking authored accessors/arbitrary behavior.
293
+ * Diagnostics are deterministic, source-rooted facts; unsafe fragments stop locally while safe
294
+ * siblings continue to aggregate.
295
+ */
296
+ function inspectJsonValue(value) {
297
+ const diagnostics = [];
298
+ inspectJsonValueAt(value, [], /* @__PURE__ */ new Set(), diagnostics);
299
+ return {
300
+ compatible: diagnostics.length === 0,
301
+ diagnostics
302
+ };
303
+ }
304
+ function isJsonValue(value) {
305
+ return inspectJsonValue(value).compatible;
306
+ }
307
+ /** JSON-domain equality used by RFC6902 `test` and by SourcePatch no-op detection. */
308
+ function jsonEqual(left, right, seen = /* @__PURE__ */ new Set()) {
309
+ if (Object.is(left, right)) return true;
310
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false;
311
+ if (!isJsonValue(left) || !isJsonValue(right)) return false;
312
+ if (seen.has(left) || seen.has(right)) return false;
313
+ seen.add(left);
314
+ seen.add(right);
315
+ try {
316
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
317
+ if (Array.isArray(left) && Array.isArray(right)) {
318
+ if (left.length !== right.length) return false;
319
+ for (let index = 0; index < left.length; index++) if (!jsonEqual(left[index], right[index], seen)) return false;
320
+ return true;
321
+ }
322
+ const leftObject = left;
323
+ const rightObject = right;
324
+ const leftKeys = Object.keys(leftObject);
325
+ const rightKeys = Object.keys(rightObject);
326
+ if (leftKeys.length !== rightKeys.length) return false;
327
+ for (const key of leftKeys) if (!Object.hasOwn(rightObject, key) || !jsonEqual(leftObject[key], rightObject[key], seen)) return false;
328
+ return true;
329
+ } finally {
330
+ seen.delete(left);
331
+ seen.delete(right);
332
+ }
333
+ }
334
+ //#endregion
335
+ //#region src/source-patch.ts
336
+ const PATCH_ERROR_MESSAGES = {
337
+ "invalid-path": "The SourcePath is malformed.",
338
+ "path-not-found": "The SourcePath does not identify an existing location.",
339
+ "path-not-traversable": "The SourcePath passes through a non-traversable value.",
340
+ "invalid-array-index": "The SourcePath contains an invalid Array index.",
341
+ "invalid-move-target": "The move destination is invalid relative to its source.",
342
+ "test-failed": "The test operation did not match the addressed value.",
343
+ "source-access-failed": "The source could not be inspected safely."
344
+ };
345
+ function failure(code, message = PATCH_ERROR_MESSAGES[code]) {
346
+ return {
347
+ ok: false,
348
+ error: {
349
+ code,
350
+ message
351
+ }
352
+ };
353
+ }
354
+ function parsePath(path) {
355
+ if (typeof path === "string") {
356
+ if (path === "") return {
357
+ ok: true,
358
+ value: {
359
+ segments: [],
360
+ append: false,
361
+ pointer: true
362
+ }
363
+ };
364
+ if (!path.startsWith("/")) return failure("invalid-path");
365
+ const rawSegments = path.slice(1).split("/");
366
+ const segments = [];
367
+ for (const rawSegment of rawSegments) {
368
+ let segment = "";
369
+ for (let index = 0; index < rawSegment.length; index++) {
370
+ const character = rawSegment[index];
371
+ if (character !== "~") {
372
+ segment += character;
373
+ continue;
374
+ }
375
+ const escape = rawSegment[++index];
376
+ if (escape === "0") segment += "~";
377
+ else if (escape === "1") segment += "/";
378
+ else return failure("invalid-path");
379
+ }
380
+ segments.push(segment);
381
+ }
382
+ return {
383
+ ok: true,
384
+ value: {
385
+ segments,
386
+ append: segments.at(-1) === "-",
387
+ pointer: true
388
+ }
389
+ };
390
+ }
391
+ if (!Array.isArray(path)) return failure("invalid-path");
392
+ const segments = [];
393
+ for (const segment of path) if (typeof segment === "string") segments.push(segment);
394
+ else if (typeof segment === "number" && Number.isFinite(segment)) segments.push(segment);
395
+ else return failure("invalid-path");
396
+ return {
397
+ ok: true,
398
+ value: {
399
+ segments,
400
+ append: false,
401
+ pointer: false
402
+ }
403
+ };
404
+ }
405
+ function inspectStructuralContainer(value) {
406
+ if (typeof value !== "object" || value === null) return {
407
+ ok: true,
408
+ value: "opaque"
409
+ };
410
+ try {
411
+ if (Array.isArray(value)) return {
412
+ ok: true,
413
+ value: "array"
414
+ };
415
+ const prototype = Object.getPrototypeOf(value);
416
+ return {
417
+ ok: true,
418
+ value: prototype === Object.prototype || prototype === null ? "object" : "opaque"
419
+ };
420
+ } catch {
421
+ return failure("source-access-failed");
422
+ }
423
+ }
424
+ function isCanonicalArrayIndex(key) {
425
+ return /^(?:0|[1-9]\d*)$/.test(key) && Number(key) < 4294967295;
426
+ }
427
+ function getArrayIndex(path, segment, allowAppend = false) {
428
+ const key = String(segment);
429
+ if (!path.pointer && typeof segment === "string" && !isCanonicalArrayIndex(key)) return {
430
+ ok: true,
431
+ value: null
432
+ };
433
+ if (key === "-" && allowAppend) return {
434
+ ok: true,
435
+ value: null
436
+ };
437
+ if (key === "-" || !isCanonicalArrayIndex(key)) return failure("invalid-array-index");
438
+ return {
439
+ ok: true,
440
+ value: Number(key)
441
+ };
442
+ }
443
+ function ownDescriptor(container, key) {
444
+ try {
445
+ return {
446
+ ok: true,
447
+ value: Object.getOwnPropertyDescriptor(container, key)
448
+ };
449
+ } catch {
450
+ return failure("source-access-failed");
451
+ }
452
+ }
453
+ function readOwn(container, key) {
454
+ const descriptor = ownDescriptor(container, key);
455
+ if (!descriptor.ok) return descriptor;
456
+ if (descriptor.value === void 0) return failure("path-not-found");
457
+ if (!("value" in descriptor.value)) return failure("path-not-traversable", "The addressed source property is accessor-backed.");
458
+ return {
459
+ ok: true,
460
+ value: {
461
+ descriptor: descriptor.value,
462
+ value: descriptor.value.value
463
+ }
464
+ };
465
+ }
466
+ function readArrayLength(array) {
467
+ const descriptor = ownDescriptor(array, "length");
468
+ if (!descriptor.ok) return descriptor;
469
+ if (descriptor.value === void 0 || !("value" in descriptor.value) || typeof descriptor.value.value !== "number") return failure("source-access-failed");
470
+ return {
471
+ ok: true,
472
+ value: descriptor.value.value
473
+ };
474
+ }
475
+ function readAt(source, path) {
476
+ let current = source;
477
+ for (let index = 0; index < path.segments.length; index++) {
478
+ const segment = path.segments[index];
479
+ const key = String(segment);
480
+ const container = inspectStructuralContainer(current);
481
+ if (!container.ok) return container;
482
+ if (container.value === "opaque") return failure("path-not-traversable");
483
+ if (container.value === "array") {
484
+ const indexResult = getArrayIndex(path, segment);
485
+ if (!indexResult.ok) return indexResult;
486
+ const length = readArrayLength(current);
487
+ if (!length.ok) return length;
488
+ if (indexResult.value !== null && indexResult.value >= length.value) return failure("invalid-array-index");
489
+ }
490
+ const result = readOwn(current, key);
491
+ if (!result.ok) return result;
492
+ current = result.value.value;
493
+ }
494
+ return {
495
+ ok: true,
496
+ value: current
497
+ };
498
+ }
499
+ function ownEntries(container) {
500
+ try {
501
+ const entries = [];
502
+ for (const key of Reflect.ownKeys(container)) {
503
+ const descriptor = Object.getOwnPropertyDescriptor(container, key);
504
+ if (descriptor === void 0) return failure("source-access-failed");
505
+ entries.push([key, descriptor]);
506
+ }
507
+ return {
508
+ ok: true,
509
+ value: entries
510
+ };
511
+ } catch {
512
+ return failure("source-access-failed");
513
+ }
514
+ }
515
+ function define(target, key, descriptor) {
516
+ try {
517
+ Object.defineProperty(target, key, descriptor);
518
+ return {
519
+ ok: true,
520
+ value: void 0
521
+ };
522
+ } catch {
523
+ return failure("source-access-failed");
524
+ }
525
+ }
526
+ function createContainer(source, lengthDelta = 0) {
527
+ try {
528
+ if (Array.isArray(source)) {
529
+ const array = [];
530
+ array.length = source.length + lengthDelta;
531
+ return {
532
+ ok: true,
533
+ value: array
534
+ };
535
+ }
536
+ return {
537
+ ok: true,
538
+ value: Object.create(Object.getPrototypeOf(source))
539
+ };
540
+ } catch {
541
+ return failure("source-access-failed");
542
+ }
543
+ }
544
+ function rebuildObject(container, segment, action, value, pointer = true, allowArrayAppend = false) {
545
+ const entries = ownEntries(container);
546
+ if (!entries.ok) return entries;
547
+ const containerKind = inspectStructuralContainer(container);
548
+ if (!containerKind.ok) return containerKind;
549
+ const isArray = containerKind.value === "array";
550
+ const arrayLength = isArray ? readArrayLength(container) : {
551
+ ok: true,
552
+ value: 0
553
+ };
554
+ if (!arrayLength.ok) return arrayLength;
555
+ const key = String(segment);
556
+ const append = isArray && pointer && segment === "-" && allowArrayAppend;
557
+ const effectiveKey = append ? String(arrayLength.value) : key;
558
+ const arrayIndexResult = isArray ? getArrayIndex({
559
+ segments: [],
560
+ append: false,
561
+ pointer
562
+ }, segment, allowArrayAppend) : {
563
+ ok: true,
564
+ value: null
565
+ };
566
+ if (!arrayIndexResult.ok) return arrayIndexResult;
567
+ const arrayIndex = append ? arrayLength.value : arrayIndexResult.value;
568
+ if (isArray && pointer && segment === "-" && !allowArrayAppend) return failure("invalid-array-index");
569
+ if (isArray && arrayIndex !== null) {
570
+ if (action === "add" && arrayIndex > arrayLength.value) return failure("invalid-array-index");
571
+ if (action !== "add" && arrayIndex >= arrayLength.value) return failure("invalid-array-index");
572
+ }
573
+ const exists = entries.value.some(([entryKey]) => entryKey === effectiveKey);
574
+ if (action !== "add" && !exists) return failure("path-not-found");
575
+ const target = createContainer(container, isArray && arrayIndex !== null ? action === "add" ? 1 : -1 : 0);
576
+ if (!target.ok) return target;
577
+ for (const [entryKey, descriptor] of entries.value) {
578
+ if (entryKey === "length" && isArray) continue;
579
+ if (action !== "add" && entryKey === effectiveKey) continue;
580
+ let outputKey = entryKey;
581
+ if (isArray && typeof entryKey === "string" && arrayIndex !== null && isCanonicalArrayIndex(entryKey)) {
582
+ const entryIndex = Number(entryKey);
583
+ if (action === "add" && entryIndex >= arrayIndex) outputKey = String(entryIndex + 1);
584
+ else if (action === "remove" && entryIndex > arrayIndex) outputKey = String(entryIndex - 1);
585
+ else if (action === "remove" && entryIndex === arrayIndex) continue;
586
+ }
587
+ const result = define(target.value, outputKey, descriptor);
588
+ if (!result.ok) return result;
589
+ }
590
+ if (action !== "remove") {
591
+ const result = define(target.value, isArray && arrayIndex !== null && action === "add" ? String(arrayIndex) : effectiveKey, {
592
+ value,
593
+ enumerable: true,
594
+ writable: true,
595
+ configurable: true
596
+ });
597
+ if (!result.ok) return result;
598
+ }
599
+ return {
600
+ ok: true,
601
+ value: target.value
602
+ };
603
+ }
604
+ function modifyAt(source, path, modify) {
605
+ if (path.segments.length === 0) return modify({ value: source }, "value");
606
+ function visit(container, index) {
607
+ const containerKind = inspectStructuralContainer(container);
608
+ if (!containerKind.ok) return containerKind;
609
+ if (containerKind.value === "opaque") return failure("path-not-traversable");
610
+ const segment = path.segments[index];
611
+ const key = String(segment);
612
+ if (index === path.segments.length - 1) return modify(container, segment);
613
+ if (containerKind.value === "array") {
614
+ const indexResult = getArrayIndex(path, segment);
615
+ if (!indexResult.ok) return indexResult;
616
+ const length = readArrayLength(container);
617
+ if (!length.ok) return length;
618
+ if (indexResult.value !== null && indexResult.value >= length.value) return failure("invalid-array-index");
619
+ }
620
+ const child = readOwn(container, key);
621
+ if (!child.ok) return child;
622
+ const next = visit(child.value.value, index + 1);
623
+ if (!next.ok) return next;
624
+ return rebuildObject(container, segment, "replace", next.value, path.pointer);
625
+ }
626
+ return visit(source, 0);
627
+ }
628
+ function modifyRoot(source, value) {
629
+ return {
630
+ ok: true,
631
+ value
632
+ };
633
+ }
634
+ function copyValue(value) {
635
+ if (value === null || typeof value !== "object") return {
636
+ ok: true,
637
+ value
638
+ };
639
+ const containerKind = inspectStructuralContainer(value);
640
+ if (!containerKind.ok) return containerKind;
641
+ if (containerKind.value === "opaque") return {
642
+ ok: true,
643
+ value
644
+ };
645
+ const seen = /* @__PURE__ */ new WeakMap();
646
+ function clone(current) {
647
+ const previous = seen.get(current);
648
+ if (previous !== void 0) return {
649
+ ok: true,
650
+ value: previous
651
+ };
652
+ const result = createContainer(current);
653
+ if (!result.ok) return result;
654
+ seen.set(current, result.value);
655
+ const entries = ownEntries(current);
656
+ if (!entries.ok) return entries;
657
+ const currentKind = inspectStructuralContainer(current);
658
+ if (!currentKind.ok) return currentKind;
659
+ for (const [key, descriptor] of entries.value) {
660
+ if (key === "length" && currentKind.value === "array") continue;
661
+ if (!("value" in descriptor)) return failure("path-not-traversable", "Accessor-backed source properties cannot be copied.");
662
+ const child = descriptor.value;
663
+ let copied = {
664
+ ok: true,
665
+ value: child
666
+ };
667
+ if (child !== null && typeof child === "object") {
668
+ const childKind = inspectStructuralContainer(child);
669
+ if (!childKind.ok) return childKind;
670
+ if (childKind.value !== "opaque") copied = clone(child);
671
+ }
672
+ if (!copied.ok) return copied;
673
+ const defined = define(result.value, key, {
674
+ ...descriptor,
675
+ value: copied.value
676
+ });
677
+ if (!defined.ok) return defined;
678
+ }
679
+ return result;
680
+ }
681
+ return clone(value);
682
+ }
683
+ function structurallyEqual(left, right) {
684
+ const matched = /* @__PURE__ */ new WeakMap();
685
+ function equal(currentLeft, currentRight) {
686
+ if (Object.is(currentLeft, currentRight)) return true;
687
+ if (typeof currentLeft !== "object" || currentLeft === null || typeof currentRight !== "object" || currentRight === null) return false;
688
+ const leftKind = inspectStructuralContainer(currentLeft);
689
+ const rightKind = inspectStructuralContainer(currentRight);
690
+ if (!leftKind.ok || !rightKind.ok) return false;
691
+ if (leftKind.value === "opaque" || rightKind.value === "opaque") return false;
692
+ const previous = matched.get(currentLeft);
693
+ if (previous !== void 0) return previous === currentRight;
694
+ matched.set(currentLeft, currentRight);
695
+ try {
696
+ if (Object.getPrototypeOf(currentLeft) !== Object.getPrototypeOf(currentRight)) return false;
697
+ const leftKeys = Reflect.ownKeys(currentLeft);
698
+ const rightKeys = Reflect.ownKeys(currentRight);
699
+ if (leftKeys.length !== rightKeys.length) return false;
700
+ for (const key of leftKeys) {
701
+ if (!Object.hasOwn(currentRight, key)) return false;
702
+ const leftDescriptor = Object.getOwnPropertyDescriptor(currentLeft, key);
703
+ const rightDescriptor = Object.getOwnPropertyDescriptor(currentRight, key);
704
+ if (leftDescriptor === void 0 || rightDescriptor === void 0) return false;
705
+ const leftData = "value" in leftDescriptor;
706
+ if (leftData !== "value" in rightDescriptor) return false;
707
+ if (leftData) {
708
+ if (!equal(leftDescriptor.value, rightDescriptor.value)) return false;
709
+ } else if (leftDescriptor.get !== rightDescriptor.get || leftDescriptor.set !== rightDescriptor.set) return false;
710
+ }
711
+ return true;
712
+ } catch {
713
+ return false;
714
+ }
715
+ }
716
+ return equal(left, right);
717
+ }
718
+ function samePathSegment(left, right) {
719
+ return String(left) === String(right);
720
+ }
721
+ function isPrefix(prefix, value) {
722
+ return prefix.length < value.length && prefix.every((segment, index) => samePathSegment(segment, value[index]));
723
+ }
724
+ function samePath(left, right) {
725
+ return left.length === right.length && left.every((segment, index) => samePathSegment(segment, right[index]));
726
+ }
727
+ function operationError(index, error) {
728
+ return Object.freeze({
729
+ code: error.code,
730
+ operationIndex: index,
731
+ message: error.message
732
+ });
733
+ }
734
+ function applySourcePatch(source, patch) {
735
+ if (!Array.isArray(patch)) return {
736
+ ok: false,
737
+ failure: operationError(0, {
738
+ code: "invalid-path",
739
+ message: "SourcePatch must be an array."
740
+ })
741
+ };
742
+ let working = source;
743
+ for (let operationIndex = 0; operationIndex < patch.length; operationIndex++) {
744
+ const operation = patch[operationIndex];
745
+ if (typeof operation !== "object" || operation === null || !("op" in operation)) return {
746
+ ok: false,
747
+ failure: operationError(operationIndex, {
748
+ code: "invalid-path",
749
+ message: "SourcePatch operation is malformed."
750
+ })
751
+ };
752
+ const op = operation.op;
753
+ const pathResult = parsePath(operation.path);
754
+ if (!pathResult.ok) return {
755
+ ok: false,
756
+ failure: operationError(operationIndex, pathResult.error)
757
+ };
758
+ const path = pathResult.value;
759
+ let next;
760
+ switch (op) {
761
+ case "add":
762
+ case "replace": {
763
+ const value = operation.value;
764
+ if (!isJsonValue(value)) return {
765
+ ok: false,
766
+ failure: operationError(operationIndex, {
767
+ code: "source-access-failed",
768
+ message: "SourcePatch operands must be JsonValue."
769
+ })
770
+ };
771
+ const copied = copyValue(value);
772
+ if (!copied.ok) return {
773
+ ok: false,
774
+ failure: operationError(operationIndex, copied.error)
775
+ };
776
+ if (path.segments.length === 0) next = modifyRoot(working, copied.value);
777
+ else next = modifyAt(working, path, (container, segment) => rebuildObject(container, segment, op, copied.value, path.pointer, op === "add" && path.append));
778
+ break;
779
+ }
780
+ case "remove":
781
+ if (path.segments.length === 0) return {
782
+ ok: false,
783
+ failure: operationError(operationIndex, {
784
+ code: "invalid-path",
785
+ message: PATCH_ERROR_MESSAGES["invalid-path"]
786
+ })
787
+ };
788
+ else next = modifyAt(working, path, (container, segment) => rebuildObject(container, segment, "remove", void 0, path.pointer));
789
+ break;
790
+ case "test": {
791
+ const value = operation.value;
792
+ if (!isJsonValue(value)) return {
793
+ ok: false,
794
+ failure: operationError(operationIndex, {
795
+ code: "source-access-failed",
796
+ message: "SourcePatch operands must be JsonValue."
797
+ })
798
+ };
799
+ const actual = readAt(working, path);
800
+ if (!actual.ok) return {
801
+ ok: false,
802
+ failure: operationError(operationIndex, actual.error)
803
+ };
804
+ if (!jsonEqual(actual.value, value)) return {
805
+ ok: false,
806
+ failure: operationError(operationIndex, {
807
+ code: "test-failed",
808
+ message: PATCH_ERROR_MESSAGES["test-failed"]
809
+ })
810
+ };
811
+ next = {
812
+ ok: true,
813
+ value: working
814
+ };
815
+ break;
816
+ }
817
+ case "copy":
818
+ case "move": {
819
+ const fromResult = parsePath(operation.from);
820
+ if (!fromResult.ok) return {
821
+ ok: false,
822
+ failure: operationError(operationIndex, fromResult.error)
823
+ };
824
+ const from = fromResult.value;
825
+ if (op === "move" && isPrefix(from.segments, path.segments)) return {
826
+ ok: false,
827
+ failure: operationError(operationIndex, {
828
+ code: "invalid-move-target",
829
+ message: PATCH_ERROR_MESSAGES["invalid-move-target"]
830
+ })
831
+ };
832
+ const sourceValue = readAt(working, from);
833
+ if (!sourceValue.ok) return {
834
+ ok: false,
835
+ failure: operationError(operationIndex, sourceValue.error)
836
+ };
837
+ if (op === "move" && samePath(from.segments, path.segments)) {
838
+ next = {
839
+ ok: true,
840
+ value: working
841
+ };
842
+ break;
843
+ }
844
+ const copied = copyValue(sourceValue.value);
845
+ if (!copied.ok) return {
846
+ ok: false,
847
+ failure: operationError(operationIndex, copied.error)
848
+ };
849
+ if (op === "copy") {
850
+ next = path.segments.length === 0 ? modifyRoot(working, copied.value) : modifyAt(working, path, (container, segment) => rebuildObject(container, segment, "add", copied.value, path.pointer, path.append));
851
+ break;
852
+ }
853
+ const removed = from.segments.length === 0 ? failure("invalid-path") : modifyAt(working, from, (container, segment) => rebuildObject(container, segment, "remove", void 0, from.pointer));
854
+ if (!removed.ok) return {
855
+ ok: false,
856
+ failure: operationError(operationIndex, removed.error)
857
+ };
858
+ next = path.segments.length === 0 ? modifyRoot(removed.value, copied.value) : modifyAt(removed.value, path, (container, segment) => rebuildObject(container, segment, "add", copied.value, path.pointer, path.append));
859
+ break;
860
+ }
861
+ default: return {
862
+ ok: false,
863
+ failure: operationError(operationIndex, {
864
+ code: "invalid-path",
865
+ message: "SourcePatch operation is malformed."
866
+ })
867
+ };
868
+ }
869
+ if (!next.ok) return {
870
+ ok: false,
871
+ failure: operationError(operationIndex, next.error)
872
+ };
873
+ working = next.value;
874
+ }
875
+ return {
876
+ ok: true,
877
+ value: {
878
+ changed: !structurallyEqual(source, working),
879
+ source: working
880
+ }
881
+ };
882
+ }
883
+ //#endregion
884
+ //#region src/document.ts
885
+ function createWidgetDocument(options) {
886
+ let blueprint = options.system.createBlueprint(options.source);
887
+ let snapshot = Object.freeze({
888
+ revision: 0,
889
+ blueprint
890
+ });
891
+ let phase = "idle";
892
+ const subscribers = [];
893
+ function getSnapshot() {
894
+ return snapshot;
895
+ }
896
+ function applyPatch(patch, applyOptions) {
897
+ if (phase !== "idle") return {
898
+ ok: false,
899
+ failure: Object.freeze({
900
+ code: "reentrant-apply",
901
+ message: "WidgetDocument.applyPatch() cannot be called while the Document is applying or notifying."
902
+ })
903
+ };
904
+ if (applyOptions !== void 0 && applyOptions.expectedRevision !== snapshot.revision) return {
905
+ ok: false,
906
+ failure: Object.freeze({
907
+ code: "document-revision-conflict",
908
+ expectedRevision: applyOptions.expectedRevision,
909
+ actualRevision: snapshot.revision,
910
+ message: "WidgetDocument revision does not match expectedRevision."
911
+ })
912
+ };
913
+ phase = "applying";
914
+ try {
915
+ const result = applySourcePatch(blueprint.source, patch);
916
+ if (!result.ok) return {
917
+ ok: false,
918
+ failure: result.failure
919
+ };
920
+ if (!result.value.changed) return {
921
+ ok: true,
922
+ changed: false
923
+ };
924
+ const nextBlueprint = options.system.createBlueprint(result.value.source);
925
+ blueprint = nextBlueprint;
926
+ snapshot = Object.freeze({
927
+ revision: snapshot.revision + 1,
928
+ blueprint: nextBlueprint
929
+ });
930
+ phase = "notifying";
931
+ const audience = subscribers.slice();
932
+ for (const subscriber of audience) invokeListenerIsolated(subscriber.listener, snapshot);
933
+ return {
934
+ ok: true,
935
+ changed: true
936
+ };
937
+ } finally {
938
+ phase = "idle";
939
+ }
940
+ }
941
+ function subscribe(listener) {
942
+ const subscriber = { listener };
943
+ subscribers.push(subscriber);
944
+ let active = true;
945
+ return () => {
946
+ if (!active) return;
947
+ active = false;
948
+ const index = subscribers.indexOf(subscriber);
949
+ if (index >= 0) subscribers.splice(index, 1);
950
+ };
951
+ }
952
+ return Object.freeze({
953
+ getSnapshot,
954
+ applyPatch,
955
+ subscribe
956
+ });
957
+ }
958
+ //#endregion
959
+ //#region src/readonly-map.ts
960
+ /** Creates a map-shaped, runtime immutable projection without exposing mutating Map methods. */
961
+ function createReadonlyMap(entries) {
962
+ const map = new Map(entries);
963
+ const result = {
964
+ get size() {
965
+ return map.size;
966
+ },
967
+ get(key) {
968
+ return map.get(key);
969
+ },
970
+ has(key) {
971
+ return map.has(key);
972
+ },
973
+ keys() {
974
+ return map.keys();
975
+ },
976
+ values() {
977
+ return map.values();
978
+ },
979
+ entries() {
980
+ return map.entries();
981
+ },
982
+ forEach(callbackfn, thisArg) {
983
+ map.forEach((value, key) => callbackfn.call(thisArg, value, key, result));
984
+ },
985
+ [Symbol.iterator]() {
986
+ return map[Symbol.iterator]();
987
+ }
988
+ };
989
+ return Object.freeze(result);
990
+ }
991
+ //#endregion
992
+ //#region src/plugin.ts
993
+ /**
994
+ * Framework-private brand carrying the plugin's phantom interfaces and its erased definition record.
995
+ */
996
+ const widgetPluginBrand = Symbol("@deviltea/widget-core:widget-plugin");
997
+ /**
998
+ * Reads the erased definition record of a plugin.
999
+ */
1000
+ function readWidgetPluginDefinition(plugin) {
1001
+ return plugin[widgetPluginBrand].definition;
1002
+ }
1003
+ /**
1004
+ * Builds the section keyed-chain object.
1005
+ *
1006
+ * Declared member keys exist only at the type level, so every string member access resolves to a
1007
+ * consuming function; the returned chain object is the same object by identity.
1008
+ */
1009
+ function createSection(sink) {
1010
+ const section = new Proxy({}, { get(_target, key) {
1011
+ if (typeof key !== "string") return void 0;
1012
+ return (definition) => {
1013
+ sink.set(key, definition);
1014
+ return section;
1015
+ };
1016
+ } });
1017
+ return section;
1018
+ }
1019
+ /**
1020
+ * Starts the plugin builder for one plugin `type`.
1021
+ *
1022
+ * Phase order is `interfaces -> config? -> slots? -> state? -> properties? -> methods? -> done()`;
1023
+ * a phase exists only when its capability is declared.
1024
+ */
1025
+ function createWidgetPlugin(type) {
1026
+ const draft = {
1027
+ description: "",
1028
+ config: null,
1029
+ slots: null,
1030
+ validateStructure: null,
1031
+ state: null,
1032
+ properties: null,
1033
+ methods: null
1034
+ };
1035
+ const builder = {
1036
+ description(description) {
1037
+ draft.description = description;
1038
+ return builder;
1039
+ },
1040
+ interfaces: () => builder,
1041
+ config(definition) {
1042
+ draft.config = definition;
1043
+ return builder;
1044
+ },
1045
+ slots(definitions, validateStructure) {
1046
+ draft.slots = new Map(Object.entries(definitions));
1047
+ draft.validateStructure = validateStructure ?? null;
1048
+ return builder;
1049
+ },
1050
+ state(build) {
1051
+ const members = /* @__PURE__ */ new Map();
1052
+ draft.state = members;
1053
+ build(createSection(members));
1054
+ return builder;
1055
+ },
1056
+ properties(build) {
1057
+ const members = /* @__PURE__ */ new Map();
1058
+ draft.properties = members;
1059
+ build(createSection(members));
1060
+ return builder;
1061
+ },
1062
+ methods(build) {
1063
+ const members = /* @__PURE__ */ new Map();
1064
+ draft.methods = members;
1065
+ build(createSection(members));
1066
+ return builder;
1067
+ },
1068
+ done() {
1069
+ const definition = Object.freeze({
1070
+ type,
1071
+ description: draft.description,
1072
+ config: draft.config,
1073
+ slots: draft.slots,
1074
+ validateStructure: draft.validateStructure,
1075
+ state: draft.state,
1076
+ properties: draft.properties,
1077
+ methods: draft.methods
1078
+ });
1079
+ const capabilities = Object.freeze({
1080
+ config: definition.config !== null,
1081
+ slots: definition.slots !== null,
1082
+ state: definition.state !== null,
1083
+ properties: definition.properties !== null,
1084
+ methods: definition.methods !== null
1085
+ });
1086
+ const descriptions = Object.freeze({
1087
+ config: definition.config?.description ?? null,
1088
+ slots: definition.slots === null ? null : createReadonlyMap([...definition.slots].map(([key, slot]) => [key, slot.description]))
1089
+ });
1090
+ return Object.freeze({
1091
+ type,
1092
+ description: draft.description,
1093
+ capabilities,
1094
+ descriptions,
1095
+ [widgetPluginBrand]: Object.freeze({ definition })
1096
+ });
1097
+ }
1098
+ };
1099
+ return builder;
1100
+ }
1101
+ //#endregion
1102
+ //#region src/separated-source.ts
1103
+ function readDataProperty(value, key) {
1104
+ try {
1105
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1106
+ if (descriptor === void 0) return {
1107
+ found: false,
1108
+ accessible: true
1109
+ };
1110
+ if (!("value" in descriptor)) return {
1111
+ found: true,
1112
+ accessible: false
1113
+ };
1114
+ return {
1115
+ found: true,
1116
+ accessible: true,
1117
+ value: descriptor.value
1118
+ };
1119
+ } catch {
1120
+ return {
1121
+ found: true,
1122
+ accessible: false
1123
+ };
1124
+ }
1125
+ }
1126
+ function isPlainObject(value) {
1127
+ if (typeof value !== "object" || value === null) return false;
1128
+ try {
1129
+ if (Array.isArray(value)) return false;
1130
+ const prototype = Object.getPrototypeOf(value);
1131
+ return prototype === Object.prototype || prototype === null;
1132
+ } catch {
1133
+ return false;
1134
+ }
1135
+ }
1136
+ function ownStringKeys(value) {
1137
+ try {
1138
+ return Reflect.ownKeys(value).filter((key) => typeof key === "string");
1139
+ } catch {
1140
+ return null;
1141
+ }
1142
+ }
1143
+ function readArrayInfo$1(value) {
1144
+ try {
1145
+ if (!Array.isArray(value)) return {
1146
+ isArray: false,
1147
+ accessible: true
1148
+ };
1149
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
1150
+ if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || typeof lengthDescriptor.value !== "number" || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) return {
1151
+ isArray: true,
1152
+ accessible: false
1153
+ };
1154
+ return {
1155
+ isArray: true,
1156
+ accessible: true,
1157
+ length: lengthDescriptor.value
1158
+ };
1159
+ } catch {
1160
+ return {
1161
+ isArray: true,
1162
+ accessible: false
1163
+ };
1164
+ }
1165
+ }
1166
+ function freezeLocation(location) {
1167
+ if ("path" in location && location.path !== void 0) return Object.freeze({
1168
+ ...location,
1169
+ path: Object.freeze([...location.path])
1170
+ });
1171
+ return Object.freeze({ ...location });
1172
+ }
1173
+ function freezeDiagnostic(code, location, message, fields = {}) {
1174
+ return Object.freeze({
1175
+ code,
1176
+ location: freezeLocation(location),
1177
+ message,
1178
+ ...fields
1179
+ });
1180
+ }
1181
+ function cloneJsonValue(value) {
1182
+ if (value === null || typeof value !== "object") return value;
1183
+ if (Array.isArray(value)) {
1184
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
1185
+ if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || typeof lengthDescriptor.value !== "number") throw new TypeError("A valid JsonValue array must have an accessible length.");
1186
+ const copy = [];
1187
+ copy.length = lengthDescriptor.value;
1188
+ for (let index = 0; index < lengthDescriptor.value; index++) {
1189
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
1190
+ if (descriptor === void 0 || !("value" in descriptor)) throw new TypeError("A valid JsonValue array cannot contain an accessor property.");
1191
+ Object.defineProperty(copy, String(index), {
1192
+ value: cloneJsonValue(descriptor.value),
1193
+ enumerable: descriptor.enumerable,
1194
+ writable: true,
1195
+ configurable: true
1196
+ });
1197
+ }
1198
+ return Object.freeze(copy);
1199
+ }
1200
+ const copy = Object.create(null);
1201
+ for (const key of Reflect.ownKeys(value)) {
1202
+ if (typeof key !== "string") throw new TypeError("A valid JsonValue object cannot contain a symbol property.");
1203
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1204
+ if (descriptor === void 0 || !("value" in descriptor)) throw new TypeError("A valid JsonValue cannot contain an accessor property.");
1205
+ Object.defineProperty(copy, key, {
1206
+ value: cloneJsonValue(descriptor.value),
1207
+ enumerable: descriptor.enumerable,
1208
+ writable: true,
1209
+ configurable: true
1210
+ });
1211
+ }
1212
+ return Object.freeze(copy);
1213
+ }
1214
+ function copyRecoveryValue(value) {
1215
+ try {
1216
+ return isJsonValue(value) ? cloneJsonValue(value) : value;
1217
+ } catch {
1218
+ return;
1219
+ }
1220
+ }
1221
+ function diagnosticPath(path, key) {
1222
+ return [...path, key];
1223
+ }
1224
+ /**
1225
+ * Projects canonical nested authored source into the explicit separated representation.
1226
+ * Projection preserves nested slot order and emits flat data in deterministic depth-first order.
1227
+ */
1228
+ function separateWidgetSource(source) {
1229
+ const widgets = [];
1230
+ function projectNode(node) {
1231
+ const value = node;
1232
+ const id = value.id;
1233
+ const data = {
1234
+ id,
1235
+ type: value.type
1236
+ };
1237
+ if (Object.hasOwn(value, "config")) data.config = cloneJsonValue(value.config);
1238
+ widgets.push(Object.freeze(data));
1239
+ const structure = { id };
1240
+ if (Object.hasOwn(value, "slots")) {
1241
+ const slotsValue = value.slots;
1242
+ const slots = Object.create(null);
1243
+ const slotNames = ownStringKeys(slotsValue);
1244
+ if (slotNames === null) throw new TypeError("WidgetSource slots could not be inspected safely.");
1245
+ for (const slot of slotNames) {
1246
+ const children = slotsValue[slot];
1247
+ slots[slot] = Object.freeze(children.map(projectNode));
1248
+ }
1249
+ structure.slots = slots;
1250
+ }
1251
+ return Object.freeze(structure);
1252
+ }
1253
+ const structure = projectNode(source);
1254
+ return Object.freeze({
1255
+ structure,
1256
+ widgets: Object.freeze(widgets)
1257
+ });
1258
+ }
1259
+ /**
1260
+ * Normalizes an explicitly supplied separated representation into a best-effort nested source.
1261
+ *
1262
+ * Normalization is deterministic and non-destructive: the first flat entry for an ID wins;
1263
+ * missing data creates a partial node; unused data is never guessed into the tree; and repeated
1264
+ * structural occurrences retain their available data/subtree while omitting the repeated ID.
1265
+ */
1266
+ function normalizeSeparatedWidgetSource(input) {
1267
+ const diagnostics = [];
1268
+ const dataById = /* @__PURE__ */ new Map();
1269
+ const usedData = /* @__PURE__ */ new Set();
1270
+ const addDiagnostic = (code, location, message, fields) => {
1271
+ diagnostics.push(freezeDiagnostic(code, location, message, fields));
1272
+ };
1273
+ const envelope = isPlainObject(input) ? input : null;
1274
+ const structureProperty = envelope === null ? {
1275
+ found: false,
1276
+ accessible: false
1277
+ } : readDataProperty(envelope, "structure");
1278
+ const widgetsProperty = envelope === null ? {
1279
+ found: false,
1280
+ accessible: false
1281
+ } : readDataProperty(envelope, "widgets");
1282
+ if (envelope === null || !structureProperty.found || !structureProperty.accessible) addDiagnostic("invalid-separated-source", {
1283
+ area: "structure",
1284
+ path: []
1285
+ }, " separated source must contain an accessible structure root.", { reason: "missing-structure" });
1286
+ const widgetsArray = readArrayInfo$1(widgetsProperty.value);
1287
+ if (!widgetsProperty.found || !widgetsProperty.accessible || !widgetsArray.isArray || !widgetsArray.accessible) addDiagnostic("invalid-separated-source", {
1288
+ area: "widgets",
1289
+ index: 0
1290
+ }, " separated source widgets must be an Array.", { reason: "invalid-widgets" });
1291
+ if (widgetsArray.isArray && widgetsArray.accessible) {
1292
+ const widgets = widgetsProperty.value;
1293
+ for (let index = 0; index < widgetsArray.length; index++) {
1294
+ const location = {
1295
+ area: "widgets",
1296
+ index
1297
+ };
1298
+ const entryProperty = readDataProperty(widgets, String(index));
1299
+ if (!entryProperty.found || !entryProperty.accessible || !isPlainObject(entryProperty.value)) {
1300
+ addDiagnostic("invalid-separated-widget", location, "flat Widget data entry must be a data object.", { reason: "invalid-entry" });
1301
+ continue;
1302
+ }
1303
+ const entry = entryProperty.value;
1304
+ const idProperty = readDataProperty(entry, "id");
1305
+ if (!idProperty.found || !idProperty.accessible || typeof idProperty.value !== "string") {
1306
+ addDiagnostic("invalid-separated-widget", {
1307
+ ...location,
1308
+ path: ["id"]
1309
+ }, "flat Widget data entry must have a string id.", { reason: "invalid-id" });
1310
+ continue;
1311
+ }
1312
+ const typeProperty = readDataProperty(entry, "type");
1313
+ if (!typeProperty.found || !typeProperty.accessible || typeof typeProperty.value !== "string") addDiagnostic("invalid-separated-widget", {
1314
+ ...location,
1315
+ path: ["type"]
1316
+ }, "flat Widget data entry must have a string type.", { reason: "invalid-type" });
1317
+ const id = idProperty.value;
1318
+ if (dataById.has(id)) {
1319
+ addDiagnostic("duplicate-widget-id", location, `flat Widget data id "${id}" occurs more than once.`, { widgetId: id });
1320
+ continue;
1321
+ }
1322
+ dataById.set(id, {
1323
+ index,
1324
+ value: entry
1325
+ });
1326
+ }
1327
+ }
1328
+ const seenStructureIds = /* @__PURE__ */ new Set();
1329
+ const activeStructureNodes = /* @__PURE__ */ new Set();
1330
+ function normalizeNode(value, path) {
1331
+ if (!isPlainObject(value)) {
1332
+ addDiagnostic("invalid-separated-structure", {
1333
+ area: "structure",
1334
+ path
1335
+ }, "structure entry must be an object.", { reason: "invalid-node" });
1336
+ return value;
1337
+ }
1338
+ const objectValue = value;
1339
+ if (activeStructureNodes.has(objectValue)) {
1340
+ addDiagnostic("invalid-separated-structure", {
1341
+ area: "structure",
1342
+ path
1343
+ }, "structure contains a cyclic reference; the repeated node was omitted.", { reason: "invalid-node" });
1344
+ return Object.create(null);
1345
+ }
1346
+ activeStructureNodes.add(objectValue);
1347
+ try {
1348
+ const idProperty = readDataProperty(value, "id");
1349
+ const rawId = idProperty.accessible ? idProperty.value : void 0;
1350
+ const hasStringId = idProperty.found && idProperty.accessible && typeof rawId === "string";
1351
+ const repeated = hasStringId && seenStructureIds.has(rawId);
1352
+ if (hasStringId && !repeated) seenStructureIds.add(rawId);
1353
+ const output = Object.create(null);
1354
+ if (repeated) addDiagnostic("duplicate-structure-id", {
1355
+ area: "structure",
1356
+ path: diagnosticPath(path, "id")
1357
+ }, `structure id "${rawId}" occurs more than once; the later occurrence is de-identified.`, { widgetId: rawId });
1358
+ else if (idProperty.found && idProperty.accessible) {
1359
+ output.id = copyRecoveryValue(rawId);
1360
+ if (!hasStringId) addDiagnostic("invalid-separated-structure", {
1361
+ area: "structure",
1362
+ path: diagnosticPath(path, "id")
1363
+ }, "structure entry id must be a string.", { reason: "invalid-node" });
1364
+ } else if (!idProperty.found || !idProperty.accessible) addDiagnostic("invalid-separated-structure", {
1365
+ area: "structure",
1366
+ path: diagnosticPath(path, "id")
1367
+ }, "structure entry must have an accessible string id.", { reason: "invalid-node" });
1368
+ if (hasStringId) {
1369
+ const data = dataById.get(rawId);
1370
+ if (data === void 0) {
1371
+ if (!repeated) addDiagnostic("missing-widget-data", {
1372
+ area: "structure",
1373
+ path: diagnosticPath(path, "id")
1374
+ }, `no flat Widget data exists for structure id "${rawId}".`, { widgetId: rawId });
1375
+ } else {
1376
+ usedData.add(data.index);
1377
+ const typeProperty = readDataProperty(data.value, "type");
1378
+ if (typeProperty.found && typeProperty.accessible) output.type = copyRecoveryValue(typeProperty.value);
1379
+ const configProperty = readDataProperty(data.value, "config");
1380
+ if (configProperty.found && configProperty.accessible) output.config = copyRecoveryValue(configProperty.value);
1381
+ else if (configProperty.found && !configProperty.accessible) addDiagnostic("invalid-separated-widget", {
1382
+ area: "widgets",
1383
+ index: data.index,
1384
+ path: ["config"]
1385
+ }, "flat Widget data config could not be inspected safely.", { reason: "invalid-entry" });
1386
+ }
1387
+ }
1388
+ const slotsProperty = readDataProperty(value, "slots");
1389
+ if (slotsProperty.found && !slotsProperty.accessible) addDiagnostic("invalid-separated-structure", {
1390
+ area: "structure",
1391
+ path: diagnosticPath(path, "slots")
1392
+ }, "structure slots could not be inspected safely.", { reason: "invalid-slots" });
1393
+ else if (slotsProperty.found && slotsProperty.accessible) if (!isPlainObject(slotsProperty.value)) {
1394
+ output.slots = copyRecoveryValue(slotsProperty.value);
1395
+ addDiagnostic("invalid-separated-structure", {
1396
+ area: "structure",
1397
+ path: diagnosticPath(path, "slots")
1398
+ }, "structure slots must be an object.", { reason: "invalid-slots" });
1399
+ } else {
1400
+ const outputSlots = Object.create(null);
1401
+ const slots = ownStringKeys(slotsProperty.value);
1402
+ if (slots === null) addDiagnostic("invalid-separated-structure", {
1403
+ area: "structure",
1404
+ path: diagnosticPath(path, "slots")
1405
+ }, "structure slots could not be inspected safely.", { reason: "invalid-slots" });
1406
+ else {
1407
+ for (const slot of slots) {
1408
+ const slotProperty = readDataProperty(slotsProperty.value, slot);
1409
+ const slotPath = diagnosticPath(diagnosticPath(path, "slots"), slot);
1410
+ const slotArray = readArrayInfo$1(slotProperty.value);
1411
+ if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
1412
+ if (slotProperty.found && slotProperty.accessible) outputSlots[slot] = copyRecoveryValue(slotProperty.value);
1413
+ addDiagnostic("invalid-separated-structure", {
1414
+ area: "structure",
1415
+ path: slotPath
1416
+ }, "structure slot must be an Array.", { reason: "invalid-slot-children" });
1417
+ continue;
1418
+ }
1419
+ const children = [];
1420
+ const childArray = slotProperty.value;
1421
+ for (let index = 0; index < slotArray.length; index++) {
1422
+ const childProperty = readDataProperty(childArray, String(index));
1423
+ children.push(childProperty.found && childProperty.accessible ? normalizeNode(childProperty.value, [...slotPath, index]) : void 0);
1424
+ if (!childProperty.found || !childProperty.accessible) addDiagnostic("invalid-separated-structure", {
1425
+ area: "structure",
1426
+ path: [...slotPath, index]
1427
+ }, "structure child could not be inspected safely.", { reason: "invalid-slot-children" });
1428
+ }
1429
+ outputSlots[slot] = children;
1430
+ }
1431
+ output.slots = outputSlots;
1432
+ }
1433
+ }
1434
+ return output;
1435
+ } finally {
1436
+ activeStructureNodes.delete(objectValue);
1437
+ }
1438
+ }
1439
+ const normalizedSource = structureProperty.found && structureProperty.accessible ? normalizeNode(structureProperty.value, []) : void 0;
1440
+ for (const [widgetId, data] of dataById) if (!usedData.has(data.index)) addDiagnostic("unused-widget-data", {
1441
+ area: "widgets",
1442
+ index: data.index
1443
+ }, `flat Widget data id "${widgetId}" is not referenced by structure.`, { widgetId });
1444
+ return Object.freeze({
1445
+ source: normalizedSource,
1446
+ diagnostics: Object.freeze(diagnostics)
1447
+ });
1448
+ }
1449
+ //#endregion
1450
+ //#region src/runtime/diagnostics.ts
1451
+ function toDiagnosticSnapshot(diagnostics) {
1452
+ return diagnostics.length === 0 ? EMPTY_DIAGNOSTICS : Object.freeze(diagnostics);
1453
+ }
1454
+ function freezeArray(value) {
1455
+ if (Array.isArray(value)) Object.freeze(value);
1456
+ }
1457
+ function freezeObject(value) {
1458
+ if (typeof value === "object" && value !== null) Object.freeze(value);
1459
+ }
1460
+ function freezeRelated(related) {
1461
+ if (!Array.isArray(related)) return;
1462
+ for (const item of related) freezeObject(item);
1463
+ Object.freeze(related);
1464
+ }
1465
+ function freezeDependency(dependency) {
1466
+ if (typeof dependency !== "object" || dependency === null) return;
1467
+ const record = dependency;
1468
+ freezeObject(record.target);
1469
+ freezeObject(record.operation);
1470
+ Object.freeze(dependency);
1471
+ }
1472
+ /** Freeze the framework-owned diagnostic record without executing or freezing arbitrary payload objects. */
1473
+ function deepFreezeDiagnostic(diagnostic) {
1474
+ if (typeof diagnostic !== "object" || diagnostic === null) return diagnostic;
1475
+ const record = diagnostic;
1476
+ freezeObject(record.location);
1477
+ freezeArray(record.path);
1478
+ freezeRelated(record.related);
1479
+ freezeDependency(record.dependency);
1480
+ if (record.cause !== void 0) deepFreezeDiagnostic(record.cause);
1481
+ Object.freeze(diagnostic);
1482
+ return diagnostic;
1483
+ }
1484
+ function freezeDiagnosticSnapshot(diagnostics) {
1485
+ for (const diagnostic of diagnostics) deepFreezeDiagnostic(diagnostic);
1486
+ return Object.freeze(diagnostics);
1487
+ }
1488
+ function stateLocation(widgetId, key) {
1489
+ return {
1490
+ type: "state",
1491
+ widgetId,
1492
+ key
1493
+ };
1494
+ }
1495
+ function propertyLocation$1(widgetId, name) {
1496
+ return {
1497
+ type: "property",
1498
+ widgetId,
1499
+ name
1500
+ };
1501
+ }
1502
+ function methodLocation$1(widgetId, name) {
1503
+ return {
1504
+ type: "method",
1505
+ widgetId,
1506
+ name
1507
+ };
1508
+ }
1509
+ function buildStateValidationDiagnostic(widgetId, key, candidate, input) {
1510
+ return {
1511
+ code: "invalid-state-value",
1512
+ location: stateLocation(widgetId, key),
1513
+ candidate,
1514
+ message: input.message,
1515
+ ...input.path === void 0 ? {} : { path: input.path },
1516
+ ...input.reason === void 0 ? {} : { reason: input.reason }
1517
+ };
1518
+ }
1519
+ function buildDefaultStateValidationDiagnostic(widgetId, key, candidate) {
1520
+ return buildStateValidationDiagnostic(widgetId, key, candidate, { message: "The candidate value failed state validation." });
1521
+ }
1522
+ function buildPropertyResultDiagnostic(widgetId, name, result, input) {
1523
+ return {
1524
+ code: "invalid-property-result",
1525
+ location: propertyLocation$1(widgetId, name),
1526
+ result,
1527
+ message: input.message,
1528
+ ...input.path === void 0 ? {} : { path: input.path },
1529
+ ...input.reason === void 0 ? {} : { reason: input.reason }
1530
+ };
1531
+ }
1532
+ function buildMethodArgsDiagnostic(widgetId, name, args, input) {
1533
+ return {
1534
+ code: "invalid-method-arguments",
1535
+ location: methodLocation$1(widgetId, name),
1536
+ args,
1537
+ message: input.message,
1538
+ ...input.path === void 0 ? {} : { path: input.path },
1539
+ ...input.reason === void 0 ? {} : { reason: input.reason }
1540
+ };
1541
+ }
1542
+ function buildDefaultMethodArgsDiagnostic(widgetId, name, args) {
1543
+ return buildMethodArgsDiagnostic(widgetId, name, args, { message: "The method arguments failed validation." });
1544
+ }
1545
+ function buildMethodResultDiagnostic(widgetId, name, result, input) {
1546
+ return {
1547
+ code: "invalid-method-result",
1548
+ location: methodLocation$1(widgetId, name),
1549
+ result,
1550
+ message: input.message,
1551
+ ...input.path === void 0 ? {} : { path: input.path },
1552
+ ...input.reason === void 0 ? {} : { reason: input.reason }
1553
+ };
1554
+ }
1555
+ function buildPropertyDependencyDiagnostic(params) {
1556
+ const base = {
1557
+ location: propertyLocation$1(params.widgetId, params.name),
1558
+ dependency: params.dependency,
1559
+ related: [params.related],
1560
+ message: params.message
1561
+ };
1562
+ if (params.received !== void 0) return {
1563
+ ...base,
1564
+ code: "dependency-value-rejected",
1565
+ received: params.received.value
1566
+ };
1567
+ return {
1568
+ ...base,
1569
+ code: "dependency-target-failed",
1570
+ cause: params.cause
1571
+ };
1572
+ }
1573
+ function buildMethodDependencyDiagnostic(params) {
1574
+ const base = {
1575
+ location: methodLocation$1(params.widgetId, params.name),
1576
+ dependency: params.dependency,
1577
+ related: [params.related],
1578
+ message: params.message
1579
+ };
1580
+ if (params.received !== void 0) return {
1581
+ ...base,
1582
+ code: "dependency-value-rejected",
1583
+ received: params.received.value
1584
+ };
1585
+ return {
1586
+ ...base,
1587
+ code: "dependency-target-failed",
1588
+ cause: params.cause
1589
+ };
1590
+ }
1591
+ function buildTopLevelStateOverrideDiagnostic(message) {
1592
+ return {
1593
+ code: "invalid-state-overrides",
1594
+ location: { type: "runtime" },
1595
+ message
1596
+ };
1597
+ }
1598
+ function buildWidgetStateOverrideDiagnostic(widgetId, message) {
1599
+ return {
1600
+ code: "unknown-state-override-widget",
1601
+ location: { type: "runtime" },
1602
+ path: [widgetId],
1603
+ message
1604
+ };
1605
+ }
1606
+ function buildUnsupportedStateOverrideDiagnostic(widgetId, message) {
1607
+ return {
1608
+ code: "unsupported-state-override-target",
1609
+ location: { type: "runtime" },
1610
+ path: [widgetId],
1611
+ message
1612
+ };
1613
+ }
1614
+ function buildInvalidStateOverrideFragmentDiagnostic(widgetId, message) {
1615
+ return {
1616
+ code: "invalid-state-override-fragment",
1617
+ location: { type: "runtime" },
1618
+ path: [widgetId],
1619
+ message
1620
+ };
1621
+ }
1622
+ function buildKeyStateOverrideDiagnostic(widgetId, key, message) {
1623
+ return {
1624
+ code: "unknown-state-override-member",
1625
+ location: { type: "runtime" },
1626
+ path: [widgetId, key],
1627
+ message
1628
+ };
1629
+ }
1630
+ //#endregion
1631
+ //#region src/runtime/aggregate.ts
1632
+ const widgetSnapshotCache = /* @__PURE__ */ new WeakMap();
1633
+ /**
1634
+ * One `RuntimeWidget`'s own aggregate snapshot: only diagnostics owned by that widget's primitives, never
1635
+ * Runtime-level diagnostics even when their source mentions the same `widgetId`. Reuses the canonical empty
1636
+ * snapshot identity when the widget currently owns no diagnostic (no capability, or every primitive
1637
+ * currently succeeds).
1638
+ */
1639
+ function buildWidgetDiagnosticSnapshot(entry) {
1640
+ const primitiveSnapshots = [
1641
+ ...Array.from(entry.state.values(), (primitive) => primitive.internal.getDiagnostics()),
1642
+ ...Array.from(entry.properties.values(), (primitive) => primitive.internal.getDiagnostics()),
1643
+ ...Array.from(entry.methods.values(), (primitive) => primitive.getDiagnostics())
1644
+ ];
1645
+ const previous = widgetSnapshotCache.get(entry);
1646
+ if (previous !== void 0 && previous.primitiveSnapshots.length === primitiveSnapshots.length && primitiveSnapshots.every((snapshot, index) => snapshot === previous.primitiveSnapshots[index])) return previous.snapshot;
1647
+ const result = toDiagnosticSnapshot(primitiveSnapshots.flat());
1648
+ widgetSnapshotCache.set(entry, {
1649
+ primitiveSnapshots,
1650
+ snapshot: result
1651
+ });
1652
+ return result;
1653
+ }
1654
+ /**
1655
+ * Builds the live-gated `getDiagnostics`/`subscribeDiagnostics` pair one `RuntimeWidget` exposes, composing
1656
+ * {@link buildWidgetDiagnosticSnapshot} the same way {@link createRuntimeAggregate} composes it for every
1657
+ * widget at the Runtime level.
1658
+ */
1659
+ function createRuntimeWidgetDiagnosticsAggregate(context, entry) {
1660
+ const snapshot = () => buildWidgetDiagnosticSnapshot(entry);
1661
+ return {
1662
+ getDiagnostics() {
1663
+ context.assertActive();
1664
+ return snapshot();
1665
+ },
1666
+ subscribeDiagnostics(listener) {
1667
+ context.assertActive();
1668
+ return createTrackedSubscription(context, snapshot, listener);
1669
+ }
1670
+ };
1671
+ }
1672
+ function createRuntimeAggregate(context, compiled, registry, runtimeLevelDiagnostics) {
1673
+ let previousChildren;
1674
+ let previousSnapshot;
1675
+ const snapshot = () => {
1676
+ const children = compiled.semanticOrder.map((nodeId) => registry.get(nodeId)).filter((entry) => entry !== void 0).map((entry) => buildWidgetDiagnosticSnapshot(entry));
1677
+ if (previousSnapshot !== void 0 && previousChildren !== void 0 && previousChildren.length === children.length && previousChildren.every((child, index) => child === children[index])) return previousSnapshot;
1678
+ const result = [...runtimeLevelDiagnostics];
1679
+ for (const child of children) result.push(...child);
1680
+ previousChildren = children;
1681
+ previousSnapshot = toDiagnosticSnapshot(result);
1682
+ return previousSnapshot;
1683
+ };
1684
+ return {
1685
+ getDiagnostics() {
1686
+ context.assertActive();
1687
+ return snapshot();
1688
+ },
1689
+ subscribeDiagnostics(listener) {
1690
+ context.assertActive();
1691
+ return createTrackedSubscription(context, snapshot, listener);
1692
+ }
1693
+ };
1694
+ }
1695
+ //#endregion
1696
+ //#region src/runtime/blueprint-view.ts
1697
+ function buildBlueprintView(blueprint) {
1698
+ const view = {
1699
+ root: blueprint.root,
1700
+ getWidget: (id) => blueprint.getWidget(id),
1701
+ getParent: (node) => blueprint.getParent(node),
1702
+ getLocation: (node) => blueprint.getLocation(node),
1703
+ getChildren: (node) => blueprint.getChildren(node),
1704
+ getChildrenAt: (node, slot) => blueprint.getChildrenAt(node, slot)
1705
+ };
1706
+ return Object.freeze(view);
1707
+ }
1708
+ //#endregion
1709
+ //#region src/runtime/context.ts
1710
+ function createRuntimeContext() {
1711
+ let disposed = false;
1712
+ let activeCollector = null;
1713
+ const owned = /* @__PURE__ */ new Set();
1714
+ function assertActive() {
1715
+ if (disposed) throw new WidgetSystemRuntimeDisposedError();
1716
+ }
1717
+ return {
1718
+ isDisposed: () => disposed,
1719
+ assertActive,
1720
+ withActiveCollector(collector, fn) {
1721
+ const previous = activeCollector;
1722
+ activeCollector = collector;
1723
+ try {
1724
+ return fn();
1725
+ } finally {
1726
+ activeCollector = previous;
1727
+ }
1728
+ },
1729
+ getActiveCollector: () => activeCollector,
1730
+ registerSubscription(rawDispose) {
1731
+ let unsubscribed = false;
1732
+ const handle = () => {
1733
+ if (unsubscribed) return;
1734
+ unsubscribed = true;
1735
+ owned.delete(handle);
1736
+ rawDispose();
1737
+ };
1738
+ owned.add(handle);
1739
+ return handle;
1740
+ },
1741
+ dispose() {
1742
+ if (disposed) return;
1743
+ disposed = true;
1744
+ for (const handle of [...owned]) handle();
1745
+ owned.clear();
1746
+ }
1747
+ };
1748
+ }
1749
+ //#endregion
1750
+ //#region src/runtime/sync.ts
1751
+ /**
1752
+ * Synchronous semantic-boundary guard.
1753
+ *
1754
+ * Normative source: diagnostic #10 amendment "synchronous core boundary and future async seams" /
1755
+ * consolidated handoff §16: a semantic callback returning a thenable is an implementation-contract
1756
+ * violation, not a Blueprint/Runtime Diagnostic and not an `ExecutionResult.failure`, so it throws.
1757
+ *
1758
+ * `PromiseLike` is a structural (duck-typed) contract, not a nominal one, and its `then` method may
1759
+ * live on an object *or* on a callable (a function value with a `.then` property is still thenable).
1760
+ * Checking `typeof value === 'object'` alone misses that callable case, so both representations are
1761
+ * treated as thenable candidates before inspecting `.then`.
1762
+ */
1763
+ function assertSyncValue(value, description) {
1764
+ 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.`);
1765
+ }
1766
+ //#endregion
1767
+ //#region src/runtime/deps.ts
1768
+ function consumerDependencyDiagnostic(params, dependency, message, received, related, cause) {
1769
+ const base = {
1770
+ widgetId: params.ownerWidgetId,
1771
+ name: params.ownerName,
1772
+ dependency,
1773
+ ...received === void 0 ? {} : { received },
1774
+ ...cause === void 0 ? {} : { cause },
1775
+ related,
1776
+ message
1777
+ };
1778
+ return params.consumer === "property" ? buildPropertyDependencyDiagnostic(base) : buildMethodDependencyDiagnostic(base);
1779
+ }
1780
+ function reportDependencyDiagnostic(params, diagnostic, dedupe) {
1781
+ params.context.getActiveCollector()?.addFinalizedDiagnostic(diagnostic, dedupe);
1782
+ }
1783
+ /**
1784
+ * Per-dependency-leaf unique id, assigned once when a leaf's callable is materialized and closed over
1785
+ * for the callable's lifetime. Combined with a raw failure-identity anchor to dedupe repeated insertion
1786
+ * of the same dependency failure into one execution scope's collector (diagnostic #10 §12: "repeated reads
1787
+ * of the same failing dependency ... avoid duplicating the same dependency diagnostic insertion").
1788
+ */
1789
+ let nextLeafId = 0;
1790
+ /**
1791
+ * Builds the dedupe descriptor for one dependency-leaf failure.
1792
+ *
1793
+ * `scope` identifies the dependency *leaf* only (`leafId`) — never the failure's `message`. Message is
1794
+ * human-readable-only per diagnostic #10 ("`message` is human-readable only, never a machine protocol") and
1795
+ * must not participate in identity/machine logic; stuffing it into `scope` would make two occurrences
1796
+ * of literally the same failure fail to dedupe if the message text ever varied, and — more subtly —
1797
+ * would never actually help distinguish genuinely different failures either, since that job already
1798
+ * belongs entirely to `anchor`.
1799
+ *
1800
+ * `anchor` is passed through to the collector as the *raw* value (never stringified): the collector
1801
+ * compares it via `Set` SameValueZero membership, which is collision-free for every JS value —
1802
+ * including two distinct `Symbol`s that share a description, which a `typeof`+`String()` encoding would
1803
+ * incorrectly conflate.
1804
+ */
1805
+ function dependencyDedupeDescriptor(leafId, failureAnchor) {
1806
+ return {
1807
+ scope: `${leafId}`,
1808
+ anchor: failureAnchor
1809
+ };
1810
+ }
1811
+ /**
1812
+ * Applies `.validate()` refinements, in order, to a successfully-produced value. Returns the refined
1813
+ * ok value or a rejection carrying the offending `received` value.
1814
+ *
1815
+ * `.validate()` is a semantic callback like every other framework-owned predicate, so its return value
1816
+ * is captured as `unknown` and passed through the sync-boundary guard *before* being interpreted as a
1817
+ * boolean — a `Promise.resolve(false)` escape hatch is truthy and would otherwise make a rejection look
1818
+ * like an accepted refinement.
1819
+ */
1820
+ function applyRefinements(value, refinements) {
1821
+ for (const refine of refinements) {
1822
+ const accepted = refine(value);
1823
+ assertSyncValue(accepted, "A dependency .validate() refinement");
1824
+ if (!accepted) return {
1825
+ ok: false,
1826
+ received: value
1827
+ };
1828
+ }
1829
+ return {
1830
+ ok: true,
1831
+ value
1832
+ };
1833
+ }
1834
+ function locationOf(operation, widgetId) {
1835
+ switch (operation.type) {
1836
+ case "state-get":
1837
+ case "state-set": return {
1838
+ type: "state",
1839
+ widgetId,
1840
+ key: operation.key
1841
+ };
1842
+ case "property-get": return {
1843
+ type: "property",
1844
+ widgetId,
1845
+ name: operation.name
1846
+ };
1847
+ case "method-invoke": return {
1848
+ type: "method",
1849
+ widgetId,
1850
+ name: operation.name
1851
+ };
1852
+ }
1853
+ }
1854
+ function resolveTargetWidgetId(nodes, nodeId) {
1855
+ const node = nodes[nodeId];
1856
+ if (node === void 0 || !node.resolved) throw new Error(`widget-core: internal error — dependency target node ${nodeId} is not a resolved node.`);
1857
+ return node.id;
1858
+ }
1859
+ function materializeAbsentLeaf(operation) {
1860
+ switch (operation.type) {
1861
+ case "state-set": return (candidate) => ({
1862
+ ok: true,
1863
+ value: candidate
1864
+ });
1865
+ case "method-invoke": return (..._args) => ({
1866
+ ok: true,
1867
+ value: null
1868
+ });
1869
+ case "state-get":
1870
+ case "property-get": return () => ({
1871
+ ok: true,
1872
+ value: null
1873
+ });
1874
+ }
1875
+ }
1876
+ function missingRegistryEntry(targetNodeId) {
1877
+ throw new Error(`widget-core: internal error — dependency target node ${targetNodeId} has no primitive registry entry.`);
1878
+ }
1879
+ /**
1880
+ * Looks up the target node's registry entry. Called lazily, inside each returned callable, never while
1881
+ * building the callable: the registry is populated progressively while the Runtime is constructed, so
1882
+ * a target node's own entry (and the primitive inside it) may not exist yet at materialization time —
1883
+ * only by the time the callable is actually invoked, after `createRuntime()` has finished.
1884
+ */
1885
+ function resolveEntry(params, targetNodeId) {
1886
+ return params.registry.get(targetNodeId) ?? missingRegistryEntry(targetNodeId);
1887
+ }
1888
+ function materializeResolvedLeaf(leaf, params) {
1889
+ const { reference } = leaf;
1890
+ const { operation } = reference;
1891
+ const related = locationOf(operation, resolveTargetWidgetId(params.nodes, leaf.targetNodeId));
1892
+ const leafId = nextLeafId++;
1893
+ switch (operation.type) {
1894
+ case "state-get": return () => {
1895
+ const target = resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1896
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved state-get target "${operation.key}" is missing.`);
1897
+ const refined = applyRefinements(target.internal.get(), leaf.refinements);
1898
+ if (!refined.ok) {
1899
+ const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
1900
+ const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
1901
+ reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
1902
+ return {
1903
+ ok: false,
1904
+ failure: { diagnostics }
1905
+ };
1906
+ }
1907
+ return {
1908
+ ok: true,
1909
+ value: refined.value
1910
+ };
1911
+ };
1912
+ case "state-set": return (candidate) => {
1913
+ const target = resolveEntry(params, leaf.targetNodeId).state.get(operation.key);
1914
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved state-set target "${operation.key}" is missing.`);
1915
+ const result = target.internal.attemptSet(candidate);
1916
+ if (result.ok) return {
1917
+ ok: true,
1918
+ value: candidate
1919
+ };
1920
+ return {
1921
+ ok: false,
1922
+ failure: { diagnostics: wrapTargetFailure(params, reference, result.failure.diagnostics, related, leafId) }
1923
+ };
1924
+ };
1925
+ case "property-get": return () => {
1926
+ const target = resolveEntry(params, leaf.targetNodeId).properties.get(operation.name);
1927
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved property-get target "${operation.name}" is missing.`);
1928
+ const targetResult = target.internal.getResult();
1929
+ if (!targetResult.ok) return {
1930
+ ok: false,
1931
+ failure: { diagnostics: wrapTargetFailure(params, reference, targetResult.failure.diagnostics, related, leafId) }
1932
+ };
1933
+ const refined = applyRefinements(targetResult.value, leaf.refinements);
1934
+ if (!refined.ok) {
1935
+ const diagnostic = consumerDependencyDiagnostic(params, reference, "The dependency value failed validation.", { value: refined.received }, related);
1936
+ const diagnostics = freezeDiagnosticSnapshot([deepFreezeDiagnostic(diagnostic)]);
1937
+ reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, refined.received));
1938
+ return {
1939
+ ok: false,
1940
+ failure: { diagnostics }
1941
+ };
1942
+ }
1943
+ return {
1944
+ ok: true,
1945
+ value: refined.value
1946
+ };
1947
+ };
1948
+ case "method-invoke": return (...args) => {
1949
+ const target = resolveEntry(params, leaf.targetNodeId).methods.get(operation.name);
1950
+ if (target === void 0) throw new Error(`widget-core: internal error — resolved method-invoke target "${operation.name}" is missing.`);
1951
+ const targetResult = target.public(...args);
1952
+ if (!targetResult.ok) return {
1953
+ ok: false,
1954
+ failure: { diagnostics: wrapTargetFailure(params, reference, targetResult.failure.diagnostics, related, leafId) }
1955
+ };
1956
+ const refined = applyRefinements(targetResult.value, 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
+ }
1966
+ return {
1967
+ ok: true,
1968
+ value: refined.value
1969
+ };
1970
+ };
1971
+ }
1972
+ }
1973
+ function wrapTargetFailure(params, reference, targetDiagnostics, related, leafId) {
1974
+ const pairs = targetDiagnostics.map((targetDiagnostic) => {
1975
+ const diagnostic = consumerDependencyDiagnostic(params, reference, targetDiagnostic.message, void 0, related, targetDiagnostic);
1976
+ deepFreezeDiagnostic(diagnostic);
1977
+ return {
1978
+ diagnostic,
1979
+ targetDiagnostic
1980
+ };
1981
+ });
1982
+ const wrapped = pairs.map((pair) => pair.diagnostic);
1983
+ freezeDiagnosticSnapshot(wrapped);
1984
+ for (const { diagnostic, targetDiagnostic } of pairs) reportDependencyDiagnostic(params, diagnostic, dependencyDedupeDescriptor(leafId, targetDiagnostic));
1985
+ return wrapped;
1986
+ }
1987
+ function materializeLeaf(leaf, params) {
1988
+ if (leaf.status === "absent") return materializeAbsentLeaf(leaf.reference.operation);
1989
+ 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.");
1990
+ return materializeResolvedLeaf(leaf, params);
1991
+ }
1992
+ function materializeDependencyTree(tree, params) {
1993
+ if (isCompiledDependency(tree)) return materializeLeaf(tree, params);
1994
+ if (Array.isArray(tree)) return tree.map((item) => materializeDependencyTree(item, params));
1995
+ const result = Object.create(null);
1996
+ for (const key of Object.keys(tree)) result[key] = materializeDependencyTree(tree[key], params);
1997
+ return result;
1998
+ }
1999
+ //#endregion
2000
+ //#region src/runtime/collector.ts
2001
+ function createOperationCollector() {
2002
+ const entries = [];
2003
+ const seenAnchorsByScope = /* @__PURE__ */ new Map();
2004
+ return {
2005
+ addDiagnostic(input) {
2006
+ entries.push({
2007
+ kind: "relative",
2008
+ input
2009
+ });
2010
+ },
2011
+ addFinalizedDiagnostic(diagnostic, dedupe) {
2012
+ if (dedupe !== void 0) {
2013
+ let seenAnchors = seenAnchorsByScope.get(dedupe.scope);
2014
+ if (seenAnchors === void 0) {
2015
+ seenAnchors = /* @__PURE__ */ new Set();
2016
+ seenAnchorsByScope.set(dedupe.scope, seenAnchors);
2017
+ }
2018
+ if (seenAnchors.has(dedupe.anchor)) return;
2019
+ seenAnchors.add(dedupe.anchor);
2020
+ }
2021
+ entries.push({
2022
+ kind: "final",
2023
+ diagnostic
2024
+ });
2025
+ },
2026
+ hasAnyDiagnostic() {
2027
+ return entries.length > 0;
2028
+ },
2029
+ finalize(toFinalDiagnostic) {
2030
+ return freezeDiagnosticSnapshot(entries.map((entry) => entry.kind === "relative" ? toFinalDiagnostic(entry.input) : entry.diagnostic));
2031
+ }
2032
+ };
2033
+ }
2034
+ //#endregion
2035
+ //#region src/runtime/method.ts
2036
+ function createMethodPrimitive(context, params) {
2037
+ const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2038
+ function invoke(...args) {
2039
+ context.assertActive();
2040
+ return runRuntimeOperation(() => invokeWithinOperation(...args));
2041
+ }
2042
+ function invokeWithinOperation(...args) {
2043
+ startBatch();
2044
+ try {
2045
+ const argsCollector = createOperationCollector();
2046
+ const argsCtx = {
2047
+ ...params.buildConfigFragment(),
2048
+ addDiagnostic: argsCollector.addDiagnostic,
2049
+ hasAnyDiagnostic: argsCollector.hasAnyDiagnostic
2050
+ };
2051
+ const validArgs = params.definition.validateArgs(args, argsCtx);
2052
+ assertSyncValue(validArgs, `Method "${params.name}"'s validateArgs`);
2053
+ if (!validArgs || argsCollector.hasAnyDiagnostic()) {
2054
+ const finalized = argsCollector.finalize((input) => buildMethodArgsDiagnostic(params.widgetId, params.name, args, input));
2055
+ const diagnostics = finalized.length > 0 ? finalized : freezeDiagnosticSnapshot([buildDefaultMethodArgsDiagnostic(params.widgetId, params.name, args)]);
2056
+ writeDeferringFlush(() => diagnosticsSignal(diagnostics));
2057
+ return Object.freeze({
2058
+ ok: false,
2059
+ failure: { diagnostics }
2060
+ });
2061
+ }
2062
+ const execCollector = createOperationCollector();
2063
+ const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => execCollector.addFinalizedDiagnostic(diagnostic, dedupe) };
2064
+ const executeCtx = {
2065
+ args,
2066
+ widget: params.selfNode,
2067
+ blueprint: params.blueprintView,
2068
+ deps: params.deps,
2069
+ ...params.buildConfigFragment(),
2070
+ addDiagnostic: execCollector.addDiagnostic,
2071
+ hasAnyDiagnostic: execCollector.hasAnyDiagnostic
2072
+ };
2073
+ const value = context.withActiveCollector(sink, () => params.definition.execute(executeCtx));
2074
+ assertSyncValue(value, `Method "${params.name}"'s execute`);
2075
+ const diagnostics = execCollector.finalize((input) => buildMethodResultDiagnostic(params.widgetId, params.name, value, input));
2076
+ writeDeferringFlush(() => diagnosticsSignal(toDiagnosticSnapshot(diagnostics)));
2077
+ const result = diagnostics.length > 0 ? {
2078
+ ok: false,
2079
+ failure: { diagnostics }
2080
+ } : {
2081
+ ok: true,
2082
+ value
2083
+ };
2084
+ return Object.freeze(result);
2085
+ } finally {
2086
+ endBatch();
2087
+ }
2088
+ }
2089
+ const callable = ((...args) => invoke(...args));
2090
+ Object.assign(callable, {
2091
+ getDiagnostics() {
2092
+ context.assertActive();
2093
+ return diagnosticsSignal();
2094
+ },
2095
+ subscribeDiagnostics(listener) {
2096
+ context.assertActive();
2097
+ return createTrackedSubscription(context, () => diagnosticsSignal(), listener);
2098
+ }
2099
+ });
2100
+ return {
2101
+ getDiagnostics: () => diagnosticsSignal(),
2102
+ public: callable
2103
+ };
2104
+ }
2105
+ //#endregion
2106
+ //#region src/runtime/override.ts
2107
+ function isPlainRecord(value) {
2108
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2109
+ }
2110
+ function resolveStateOverrides(compiled, overrideStateDefaults) {
2111
+ const runtimeLevelDiagnostics = [];
2112
+ const candidatesByNodeId = /* @__PURE__ */ new Map();
2113
+ if (overrideStateDefaults === void 0) return {
2114
+ runtimeLevelDiagnostics: freezeDiagnosticSnapshot(runtimeLevelDiagnostics),
2115
+ candidatesByNodeId
2116
+ };
2117
+ if (!isPlainRecord(overrideStateDefaults)) {
2118
+ runtimeLevelDiagnostics.push(buildTopLevelStateOverrideDiagnostic("The \"overrideStateDefaults\" option is not a usable override record."));
2119
+ return {
2120
+ runtimeLevelDiagnostics: freezeDiagnosticSnapshot(runtimeLevelDiagnostics),
2121
+ candidatesByNodeId
2122
+ };
2123
+ }
2124
+ for (const widgetId of Object.keys(overrideStateDefaults)) {
2125
+ const fragment = overrideStateDefaults[widgetId];
2126
+ const nodeId = compiled.nodeIdsByWidgetId.get(widgetId)?.[0];
2127
+ const node = nodeId === void 0 ? void 0 : compiled.nodes[nodeId];
2128
+ if (node === void 0 || !node.resolved) {
2129
+ runtimeLevelDiagnostics.push(buildWidgetStateOverrideDiagnostic(widgetId, `Unknown widget id "${widgetId}" in "overrideStateDefaults".`));
2130
+ continue;
2131
+ }
2132
+ if (readWidgetPluginDefinition(node.plugin).state === null) {
2133
+ runtimeLevelDiagnostics.push(buildUnsupportedStateOverrideDiagnostic(widgetId, `Widget "${widgetId}" has no state capability.`));
2134
+ continue;
2135
+ }
2136
+ if (!isPlainRecord(fragment)) {
2137
+ runtimeLevelDiagnostics.push(buildInvalidStateOverrideFragmentDiagnostic(widgetId, `The override fragment for widget "${widgetId}" is not a usable state-member record.`));
2138
+ continue;
2139
+ }
2140
+ const perWidget = /* @__PURE__ */ new Map();
2141
+ for (const key of Object.keys(fragment)) {
2142
+ if (!node.state.has(key)) {
2143
+ runtimeLevelDiagnostics.push(buildKeyStateOverrideDiagnostic(widgetId, key, `Unknown state member "${key}" on widget "${widgetId}".`));
2144
+ continue;
2145
+ }
2146
+ perWidget.set(key, fragment[key]);
2147
+ }
2148
+ if (perWidget.size > 0) candidatesByNodeId.set(nodeId, perWidget);
2149
+ }
2150
+ return {
2151
+ runtimeLevelDiagnostics: freezeDiagnosticSnapshot(runtimeLevelDiagnostics),
2152
+ candidatesByNodeId
2153
+ };
2154
+ }
2155
+ //#endregion
2156
+ //#region src/runtime/property.ts
2157
+ /** The frozen singleton every Property inspection channel starts at and returns to before first evaluation. */
2158
+ const NEVER_EVALUATED_SNAPSHOT = Object.freeze({ status: "never-evaluated" });
2159
+ function createPropertyPrimitive(context, params) {
2160
+ const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2161
+ let inspectionSnapshot = NEVER_EVALUATED_SNAPSHOT;
2162
+ let inspectionListeners = null;
2163
+ let lastPublishedResult = null;
2164
+ function publishInspectionCompletion(result) {
2165
+ inspectionSnapshot = Object.freeze({
2166
+ status: "completed",
2167
+ result
2168
+ });
2169
+ if (inspectionListeners === null) return;
2170
+ const listenersSnapshot = inspectionListeners.slice();
2171
+ for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, inspectionSnapshot);
2172
+ }
2173
+ const resultComputed = computed(() => {
2174
+ const collector = createOperationCollector();
2175
+ const sink = { addFinalizedDiagnostic: (diagnostic, dedupe) => collector.addFinalizedDiagnostic(diagnostic, dedupe) };
2176
+ const ctx = {
2177
+ widget: params.selfNode,
2178
+ blueprint: params.blueprintView,
2179
+ deps: params.deps,
2180
+ ...params.buildConfigFragment(),
2181
+ addDiagnostic: collector.addDiagnostic,
2182
+ hasAnyDiagnostic: collector.hasAnyDiagnostic
2183
+ };
2184
+ const value = context.withActiveCollector(sink, () => params.definition.compute(ctx));
2185
+ assertSyncValue(value, `Property "${params.name}"'s compute`);
2186
+ const diagnostics = collector.finalize((input) => buildPropertyResultDiagnostic(params.widgetId, params.name, value, input));
2187
+ writeDeferringFlush(() => diagnosticsSignal(toDiagnosticSnapshot(diagnostics)));
2188
+ const result = diagnostics.length > 0 ? {
2189
+ ok: false,
2190
+ failure: { diagnostics }
2191
+ } : {
2192
+ ok: true,
2193
+ value
2194
+ };
2195
+ return Object.freeze(result);
2196
+ });
2197
+ /**
2198
+ * Reads the computed result through the exact same call every existing consumer already makes, then
2199
+ * publishes the inspection fact only *after* that call has returned.
2200
+ *
2201
+ * In pinned alien-signals@3.2.1 a computed's cache assignment happens as `c.value = c.getter(...)`:
2202
+ * the getter runs to completion *before* the assignment to `c.value` takes effect. Publishing from
2203
+ * inside the getter body (as an earlier revision did) therefore ran before alien-signals had committed
2204
+ * the fresh result to its own cache — a synchronous inspection listener that read the same Property
2205
+ * back through the ordinary `.get()`/computed path during that window could observe the *previous*
2206
+ * cached result (or an inconsistent one on the very first evaluation). Reading `resultComputed()` to
2207
+ * completion here first, and only then comparing/publishing, means the cache is already committed by
2208
+ * the time any listener runs. This is not a second alien-signals effect and creates no new tracked
2209
+ * read: it is a plain post-return identity check on the same synchronous call `getResult()` already
2210
+ * made. Every actual recompute produces a brand-new frozen `ExecutionResult` literal (see above), so
2211
+ * comparing by reference — never by value — still notifies twice for two equal-value completions while
2212
+ * never re-publishing a merely-re-read, already-cached result.
2213
+ */
2214
+ function getResultWithInspectionPublish() {
2215
+ const result = runRuntimeOperation(resultComputed);
2216
+ if (result !== lastPublishedResult) {
2217
+ lastPublishedResult = result;
2218
+ publishInspectionCompletion(result);
2219
+ }
2220
+ return result;
2221
+ }
2222
+ const internal = {
2223
+ getResult: getResultWithInspectionPublish,
2224
+ getDiagnostics: () => diagnosticsSignal(),
2225
+ inspection: {
2226
+ getSnapshot: () => inspectionSnapshot,
2227
+ subscribe: (listener) => {
2228
+ const entry = { listener };
2229
+ if (inspectionListeners === null) inspectionListeners = [];
2230
+ inspectionListeners.push(entry);
2231
+ return () => {
2232
+ if (inspectionListeners === null) return;
2233
+ const index = inspectionListeners.indexOf(entry);
2234
+ if (index !== -1) inspectionListeners.splice(index, 1);
2235
+ };
2236
+ }
2237
+ }
2238
+ };
2239
+ return {
2240
+ internal,
2241
+ public: {
2242
+ get() {
2243
+ context.assertActive();
2244
+ return internal.getResult();
2245
+ },
2246
+ subscribe(listener) {
2247
+ context.assertActive();
2248
+ return createTrackedSubscription(context, internal.getResult, listener);
2249
+ },
2250
+ getDiagnostics() {
2251
+ context.assertActive();
2252
+ return internal.getDiagnostics();
2253
+ },
2254
+ subscribeDiagnostics(listener) {
2255
+ context.assertActive();
2256
+ return createTrackedSubscription(context, internal.getDiagnostics, listener);
2257
+ }
2258
+ }
2259
+ };
2260
+ }
2261
+ //#endregion
2262
+ //#region src/runtime/state.ts
2263
+ function createStatePrimitive(context, params) {
2264
+ const valueSignal = signal(null);
2265
+ const diagnosticsSignal = signal(EMPTY_DIAGNOSTICS);
2266
+ let inspectionSnapshot = Object.freeze({ value: null });
2267
+ let inspectionListeners = null;
2268
+ function publishInspectionSnapshot(value) {
2269
+ inspectionSnapshot = Object.freeze({ value });
2270
+ if (inspectionListeners === null) return;
2271
+ const listenersSnapshot = inspectionListeners.slice();
2272
+ for (const entry of listenersSnapshot) invokeListenerIsolated(entry.listener, inspectionSnapshot);
2273
+ }
2274
+ /**
2275
+ * The value write below is what makes the whole dependent Property graph recompute, and those
2276
+ * recomputes commit their own diagnostic snapshots from inside their evaluators. Wrapping the pipeline in
2277
+ * `runRuntimeOperation` is only what tells `writeDeferringFlush` when those evaluators are all back
2278
+ * out of the graph, so the propagations they deferred are released here: still inside the very `set()`
2279
+ * call that caused them, before its `ExecutionResult` reaches the caller.
2280
+ */
2281
+ function attemptSet(candidate) {
2282
+ return runRuntimeOperation(() => attemptSetWithinOperation(candidate));
2283
+ }
2284
+ function attemptSetWithinOperation(candidate) {
2285
+ const collector = createOperationCollector();
2286
+ const ctx = {
2287
+ ...params.buildConfigFragment(),
2288
+ addDiagnostic: collector.addDiagnostic,
2289
+ hasAnyDiagnostic: collector.hasAnyDiagnostic
2290
+ };
2291
+ const isValid = params.definition.validate(candidate, ctx);
2292
+ assertSyncValue(isValid, `State "${params.key}"'s validate`);
2293
+ if (!isValid || collector.hasAnyDiagnostic()) {
2294
+ const finalized = collector.finalize((input) => buildStateValidationDiagnostic(params.widgetId, params.key, candidate, input));
2295
+ const diagnostics = finalized.length > 0 ? finalized : freezeDiagnosticSnapshot([buildDefaultStateValidationDiagnostic(params.widgetId, params.key, candidate)]);
2296
+ writeDeferringFlush(() => diagnosticsSignal(diagnostics));
2297
+ return {
2298
+ ok: false,
2299
+ failure: { diagnostics }
2300
+ };
2301
+ }
2302
+ assertSyncValue(candidate, `State "${params.key}"'s value`);
2303
+ const previous = valueSignal();
2304
+ valueSignal(candidate);
2305
+ writeDeferringFlush(() => diagnosticsSignal(EMPTY_DIAGNOSTICS));
2306
+ if (candidate !== previous) publishInspectionSnapshot(candidate);
2307
+ return {
2308
+ ok: true,
2309
+ value: candidate
2310
+ };
2311
+ }
2312
+ const internal = {
2313
+ get: () => valueSignal(),
2314
+ getDiagnostics: () => diagnosticsSignal(),
2315
+ attemptSet,
2316
+ inspection: {
2317
+ getSnapshot: () => inspectionSnapshot,
2318
+ subscribe: (listener) => {
2319
+ const entry = { listener };
2320
+ if (inspectionListeners === null) inspectionListeners = [];
2321
+ inspectionListeners.push(entry);
2322
+ return () => {
2323
+ if (inspectionListeners === null) return;
2324
+ const index = inspectionListeners.indexOf(entry);
2325
+ if (index !== -1) inspectionListeners.splice(index, 1);
2326
+ };
2327
+ }
2328
+ }
2329
+ };
2330
+ return {
2331
+ internal,
2332
+ public: {
2333
+ get() {
2334
+ context.assertActive();
2335
+ return internal.get();
2336
+ },
2337
+ set(value) {
2338
+ context.assertActive();
2339
+ return internal.attemptSet(value);
2340
+ },
2341
+ subscribe(listener) {
2342
+ context.assertActive();
2343
+ return createTrackedSubscription(context, internal.get, listener);
2344
+ },
2345
+ getDiagnostics() {
2346
+ context.assertActive();
2347
+ return internal.getDiagnostics();
2348
+ },
2349
+ subscribeDiagnostics(listener) {
2350
+ context.assertActive();
2351
+ return createTrackedSubscription(context, internal.getDiagnostics, listener);
2352
+ }
2353
+ }
2354
+ };
2355
+ }
2356
+ //#endregion
2357
+ //#region src/runtime/widget.ts
2358
+ function buildRuntimeWidget(context, node, entry) {
2359
+ const diagnosticsAggregate = createRuntimeWidgetDiagnosticsAggregate(context, entry);
2360
+ const widget = {
2361
+ id: node.id,
2362
+ type: node.type,
2363
+ blueprint: node.publicNode,
2364
+ getDiagnostics: diagnosticsAggregate.getDiagnostics,
2365
+ subscribeDiagnostics: diagnosticsAggregate.subscribeDiagnostics
2366
+ };
2367
+ const definition = readWidgetPluginDefinition(node.plugin);
2368
+ if (definition.state !== null) {
2369
+ const stateSurface = Object.create(null);
2370
+ for (const [key, primitive] of entry.state) stateSurface[key] = primitive.public;
2371
+ widget.state = Object.freeze(stateSurface);
2372
+ }
2373
+ if (definition.properties !== null) {
2374
+ const propertiesSurface = Object.create(null);
2375
+ for (const [name, primitive] of entry.properties) propertiesSurface[name] = primitive.public;
2376
+ widget.properties = Object.freeze(propertiesSurface);
2377
+ }
2378
+ if (definition.methods !== null) {
2379
+ const methodsSurface = Object.create(null);
2380
+ for (const [name, primitive] of entry.methods) methodsSurface[name] = primitive.public;
2381
+ widget.methods = Object.freeze(methodsSurface);
2382
+ }
2383
+ return Object.freeze(widget);
2384
+ }
2385
+ //#endregion
2386
+ //#region src/runtime/index.ts
2387
+ function createWidgetSystemRuntime(blueprint, options) {
2388
+ const compiled = readCompiledBlueprint(blueprint);
2389
+ const context = createRuntimeContext();
2390
+ const blueprintView = buildBlueprintView(blueprint);
2391
+ const registry = /* @__PURE__ */ new Map();
2392
+ function buildConfigFragmentFor(node) {
2393
+ if (readWidgetPluginDefinition(node.plugin).config === null) return () => ({});
2394
+ return () => ({ config: node.config });
2395
+ }
2396
+ for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2397
+ const node = compiled.nodes[nodeId];
2398
+ if (node === void 0 || !node.resolved) continue;
2399
+ const entry = {
2400
+ state: /* @__PURE__ */ new Map(),
2401
+ properties: /* @__PURE__ */ new Map(),
2402
+ methods: /* @__PURE__ */ new Map()
2403
+ };
2404
+ registry.set(nodeId, entry);
2405
+ const buildConfigFragment = buildConfigFragmentFor(node);
2406
+ for (const [key, member] of node.state) {
2407
+ const primitive = createStatePrimitive(context, {
2408
+ widgetId: node.id,
2409
+ key,
2410
+ definition: member.definition,
2411
+ buildConfigFragment
2412
+ });
2413
+ entry.state.set(key, primitive);
2414
+ }
2415
+ }
2416
+ const overrideResolution = resolveStateOverrides(compiled, options?.overrideStateDefaults);
2417
+ for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2418
+ const node = compiled.nodes[nodeId];
2419
+ if (node === void 0 || !node.resolved) continue;
2420
+ const entry = registry.get(nodeId);
2421
+ if (entry === void 0) continue;
2422
+ const buildConfigFragment = buildConfigFragmentFor(node);
2423
+ const overrides = overrideResolution.candidatesByNodeId.get(nodeId);
2424
+ for (const [key, member] of node.state) {
2425
+ const primitive = entry.state.get(key);
2426
+ if (primitive === void 0) continue;
2427
+ let hasCandidate = false;
2428
+ let candidate;
2429
+ if (overrides?.has(key)) {
2430
+ candidate = overrides.get(key);
2431
+ hasCandidate = true;
2432
+ } else if (member.definition.default) {
2433
+ candidate = member.definition.default(buildConfigFragment());
2434
+ assertSyncValue(candidate, `State "${key}"'s default`);
2435
+ hasCandidate = true;
2436
+ }
2437
+ if (hasCandidate) primitive.internal.attemptSet(candidate);
2438
+ }
2439
+ }
2440
+ for (let nodeId = 0; nodeId < compiled.nodes.length; nodeId++) {
2441
+ const node = compiled.nodes[nodeId];
2442
+ if (node === void 0 || !node.resolved) continue;
2443
+ const entry = registry.get(nodeId);
2444
+ if (entry === void 0) continue;
2445
+ const buildConfigFragment = buildConfigFragmentFor(node);
2446
+ for (const [name, member] of node.properties) {
2447
+ const deps = materializeDependencyTree(member.deps, {
2448
+ consumer: "property",
2449
+ ownerWidgetId: node.id,
2450
+ ownerName: name,
2451
+ registry,
2452
+ nodes: compiled.nodes,
2453
+ context
2454
+ });
2455
+ const primitive = createPropertyPrimitive(context, {
2456
+ widgetId: node.id,
2457
+ name,
2458
+ definition: member.definition,
2459
+ buildConfigFragment,
2460
+ selfNode: node.publicNode,
2461
+ blueprintView,
2462
+ deps
2463
+ });
2464
+ entry.properties.set(name, primitive);
2465
+ }
2466
+ for (const [name, member] of node.methods) {
2467
+ const deps = materializeDependencyTree(member.deps, {
2468
+ consumer: "method",
2469
+ ownerWidgetId: node.id,
2470
+ ownerName: name,
2471
+ registry,
2472
+ nodes: compiled.nodes,
2473
+ context
2474
+ });
2475
+ const primitive = createMethodPrimitive(context, {
2476
+ widgetId: node.id,
2477
+ name,
2478
+ definition: member.definition,
2479
+ buildConfigFragment,
2480
+ selfNode: node.publicNode,
2481
+ blueprintView,
2482
+ deps
2483
+ });
2484
+ entry.methods.set(name, primitive);
2485
+ }
2486
+ }
2487
+ const runtimeWidgetsByNodeId = /* @__PURE__ */ new Map();
2488
+ for (const [nodeId, entry] of registry) {
2489
+ const node = compiled.nodes[nodeId];
2490
+ if (node === void 0 || !node.resolved) continue;
2491
+ runtimeWidgetsByNodeId.set(nodeId, buildRuntimeWidget(context, node, entry));
2492
+ }
2493
+ const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
2494
+ function getWidget(id) {
2495
+ context.assertActive();
2496
+ const publicNode = blueprint.getWidget(id);
2497
+ if (publicNode === null) return null;
2498
+ const nodeId = compiled.nodeIdByPublicNode.get(publicNode);
2499
+ if (nodeId === void 0) return null;
2500
+ return runtimeWidgetsByNodeId.get(nodeId) ?? null;
2501
+ }
2502
+ const runtime = {
2503
+ blueprint,
2504
+ get isDisposed() {
2505
+ return context.isDisposed();
2506
+ },
2507
+ getWidget,
2508
+ getDiagnostics: aggregate.getDiagnostics,
2509
+ subscribeDiagnostics: aggregate.subscribeDiagnostics,
2510
+ dispose: () => context.dispose()
2511
+ };
2512
+ runtime[runtimeInternals] = {
2513
+ context,
2514
+ registry
2515
+ };
2516
+ return runtime;
2517
+ }
2518
+ //#endregion
2519
+ //#region src/dep.ts
2520
+ /**
2521
+ * Framework-private brand of a dependency expression leaf.
2522
+ *
2523
+ * Plugin code must never construct an expression manually or read its internals; leaves are opaque
2524
+ * and are only produced by the fluent `dep` builder.
2525
+ */
2526
+ const depExpressionBrand = Symbol("@deviltea/widget-core:dep-expression");
2527
+ function isDepExpression(value) {
2528
+ return typeof value === "object" && value !== null && depExpressionBrand in value;
2529
+ }
2530
+ /**
2531
+ * Reads the framework-internal payload of a branded dependency leaf.
2532
+ */
2533
+ function readDepExpression(expression) {
2534
+ return expression[depExpressionBrand];
2535
+ }
2536
+ function createDepExpression(internals, readable) {
2537
+ const expression = { [depExpressionBrand]: internals };
2538
+ if (readable) expression.validate = (refinement) => createDepExpression({
2539
+ reference: internals.reference,
2540
+ refinements: [...internals.refinements, refinement]
2541
+ }, true);
2542
+ return expression;
2543
+ }
2544
+ function createTargetOperations(target) {
2545
+ const leaf = (operation, readable) => createDepExpression({
2546
+ reference: {
2547
+ target,
2548
+ operation
2549
+ },
2550
+ refinements: []
2551
+ }, readable);
2552
+ return {
2553
+ state: {
2554
+ get: (key) => leaf({
2555
+ type: "state-get",
2556
+ key
2557
+ }, true),
2558
+ set: (key) => leaf({
2559
+ type: "state-set",
2560
+ key
2561
+ }, false)
2562
+ },
2563
+ properties: { get: (name) => leaf({
2564
+ type: "property-get",
2565
+ name
2566
+ }, true) },
2567
+ methods: { invoke: (name) => leaf({
2568
+ type: "method-invoke",
2569
+ name
2570
+ }, true) }
2571
+ };
2572
+ }
2573
+ function createOptionalizableTarget(target) {
2574
+ return {
2575
+ ...createTargetOperations(target(false)),
2576
+ optional: () => createTargetOperations(target(true))
2577
+ };
2578
+ }
2579
+ /**
2580
+ * Creates the `dep` grammar object handed to `registerDeps`.
2581
+ *
2582
+ * The consumer kind only narrows the public type surface (`state.set` is invisible to Property
2583
+ * consumers); the runtime object is consumer-agnostic.
2584
+ */
2585
+ function createDependencyBuilder() {
2586
+ return {
2587
+ self: createTargetOperations({ type: "self" }),
2588
+ root: createTargetOperations({ type: "root" }),
2589
+ parent: createOptionalizableTarget((optional) => ({
2590
+ type: "parent",
2591
+ optional
2592
+ })),
2593
+ widget: (widgetId) => createOptionalizableTarget((optional) => ({
2594
+ type: "widget",
2595
+ widgetId,
2596
+ optional
2597
+ }))
2598
+ };
2599
+ }
2600
+ //#endregion
2601
+ //#region src/blueprint/diagnostics.ts
2602
+ function createCollector() {
2603
+ const items = [];
2604
+ return {
2605
+ items,
2606
+ collector: {
2607
+ addDiagnostic: (diagnostic) => items.push(diagnostic),
2608
+ hasAnyDiagnostic: () => items.length > 0
2609
+ }
2610
+ };
2611
+ }
2612
+ function toNonEmpty(items) {
2613
+ return items.length === 0 ? void 0 : items;
2614
+ }
2615
+ function widgetLocation(node) {
2616
+ return {
2617
+ type: "widget",
2618
+ node
2619
+ };
2620
+ }
2621
+ function slotLocation(node, slot) {
2622
+ return {
2623
+ type: "slot",
2624
+ node,
2625
+ slot
2626
+ };
2627
+ }
2628
+ function slotChildLocation(node, slot, index) {
2629
+ return {
2630
+ type: "slot-child",
2631
+ node,
2632
+ slot,
2633
+ index
2634
+ };
2635
+ }
2636
+ function propertyLocation(node, name) {
2637
+ return {
2638
+ type: "property",
2639
+ node,
2640
+ name
2641
+ };
2642
+ }
2643
+ function methodLocation(node, name) {
2644
+ return {
2645
+ type: "method",
2646
+ node,
2647
+ name
2648
+ };
2649
+ }
2650
+ function definitionCode(message, path) {
2651
+ if (path === void 0) return "invalid-widget-definition";
2652
+ const first = path[0];
2653
+ if (first === "id") return "invalid-widget-id";
2654
+ if (first === "type") return message.startsWith("Unknown plugin type") ? "unknown-widget-type" : "invalid-widget-type";
2655
+ if (first === "config") return message.includes("no config capability") ? "unexpected-widget-config" : "invalid-widget-definition";
2656
+ if (first === "slots") {
2657
+ if (message.includes("not declared")) return "undeclared-widget-slot";
2658
+ if (message.includes("must be an array")) return "invalid-widget-slot";
2659
+ if (message.includes("no slots capability")) return "unexpected-widget-slots";
2660
+ return "invalid-widget-slots";
2661
+ }
2662
+ return "invalid-widget-definition";
2663
+ }
2664
+ function definitionDiagnostic(node, message, path, related) {
2665
+ return {
2666
+ code: definitionCode(message, path),
2667
+ location: widgetLocation(node),
2668
+ message,
2669
+ ...path === void 0 ? {} : { path },
2670
+ ...toNonEmpty(related ?? []) === void 0 ? {} : { related: toNonEmpty(related ?? []) }
2671
+ };
2672
+ }
2673
+ function configDiagnostic(node, message, path, reason) {
2674
+ return {
2675
+ code: "invalid-widget-config",
2676
+ location: widgetLocation(node),
2677
+ message,
2678
+ ...path === void 0 ? {} : { path },
2679
+ ...reason === void 0 ? {} : { reason }
2680
+ };
2681
+ }
2682
+ function structureDiagnostic(node, message, slot, index, related, reason) {
2683
+ return {
2684
+ code: "invalid-widget-structure",
2685
+ location: slot === void 0 ? widgetLocation(node) : index === void 0 ? slotLocation(node, slot) : slotChildLocation(node, slot, index),
2686
+ message,
2687
+ ...toNonEmpty(related ?? []) === void 0 ? {} : { related: toNonEmpty(related ?? []) },
2688
+ ...reason === void 0 ? {} : { reason }
2689
+ };
2690
+ }
2691
+ function dependencyCode(message) {
2692
+ if (message.includes("ambiguous")) return "ambiguous-dependency-target";
2693
+ if (message.includes("could not be resolved")) return "unresolved-dependency-target";
2694
+ if (message.includes("does not exist")) return "missing-dependency-target";
2695
+ if (message.includes("no state capability") || message.includes("no properties capability") || message.includes("no methods capability")) return "missing-dependency-capability";
2696
+ if (message.includes("no state member") || message.includes("no property") || message.includes("no method")) return "missing-dependency-member";
2697
+ if (message.includes("invokes writeful")) return "property-dependency-has-write-effects";
2698
+ return "property-evaluation-cycle";
2699
+ }
2700
+ function dependencyDiagnostic(node, member, message, dependency, related) {
2701
+ const location = member.type === "property" ? propertyLocation(node, member.name) : methodLocation(node, member.name);
2702
+ return {
2703
+ code: dependencyCode(message),
2704
+ location,
2705
+ message,
2706
+ ...dependency === void 0 ? {} : { dependency },
2707
+ ...toNonEmpty(related ?? []) === void 0 ? {} : { related: toNonEmpty(related ?? []) }
2708
+ };
2709
+ }
2710
+ function dedupeBy(items, key) {
2711
+ const seen = /* @__PURE__ */ new Set();
2712
+ const result = [];
2713
+ for (const item of items) {
2714
+ const itemKey = key(item);
2715
+ if (!seen.has(itemKey)) {
2716
+ seen.add(itemKey);
2717
+ result.push(item);
2718
+ }
2719
+ }
2720
+ return result;
2721
+ }
2722
+ //#endregion
2723
+ //#region src/blueprint/deps.ts
2724
+ function configFragment$1(node) {
2725
+ return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
2726
+ }
2727
+ /**
2728
+ * `WidgetMemberKey = string` is an arbitrary finite string domain (member names may themselves
2729
+ * contain `:` / `->`), so naive template-literal concatenation of the six identity components is not
2730
+ * injective: e.g. a from-name of `"a->method:0:b"` paired with a to-name of `"c"` serializes to the
2731
+ * same string as a from-name of `"a"` paired with a to-name of `"b->property:0:c"`. `JSON.stringify`
2732
+ * of the component tuple is injective over strings/numbers (it round-trips exactly through
2733
+ * `JSON.parse`), so two distinct tuples can never collide regardless of what characters member names
2734
+ * contain.
2735
+ */
2736
+ function edgeKey(fromKind, fromNodeId, fromName, toKind, toNodeId, toName) {
2737
+ return JSON.stringify([
2738
+ fromKind,
2739
+ fromNodeId,
2740
+ fromName,
2741
+ toKind,
2742
+ toNodeId,
2743
+ toName
2744
+ ]);
2745
+ }
2746
+ function walkDeps(value, resolveLeaf) {
2747
+ if (isDepExpression(value)) return resolveLeaf(value);
2748
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => walkDeps(item, resolveLeaf)));
2749
+ if (typeof value === "object" && value !== null) {
2750
+ const result = Object.create(null);
2751
+ for (const key of Object.keys(value)) result[key] = walkDeps(value[key], resolveLeaf);
2752
+ return Object.freeze(result);
2753
+ }
2754
+ throw new TypeError("registerDeps() returned a value that is neither a dependency expression nor a container of one; this is a plugin implementation bug.");
2755
+ }
2756
+ function describeMissingTarget(target) {
2757
+ switch (target.type) {
2758
+ case "parent": return "Dependency target (parent) does not exist.";
2759
+ case "widget": return `Dependency target widget "${target.widgetId}" does not exist.`;
2760
+ default: return "Dependency target does not exist.";
2761
+ }
2762
+ }
2763
+ function resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds) {
2764
+ const { reference, refinements } = readDepExpression(leaf);
2765
+ const { target, operation } = reference;
2766
+ const owner = nodes[ownerNodeId];
2767
+ const ownerPublicNode = owner.publicNode;
2768
+ 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.");
2769
+ const absent = () => ({
2770
+ [compiledDependencyBrand]: true,
2771
+ status: "absent",
2772
+ reference,
2773
+ refinements
2774
+ });
2775
+ const invalid = (targetNodeId) => ({
2776
+ [compiledDependencyBrand]: true,
2777
+ status: "invalid",
2778
+ reference,
2779
+ refinements,
2780
+ ...targetNodeId === void 0 ? {} : { targetNodeId }
2781
+ });
2782
+ let candidateIds;
2783
+ switch (target.type) {
2784
+ case "self":
2785
+ candidateIds = [ownerNodeId];
2786
+ break;
2787
+ case "root":
2788
+ candidateIds = [rootNodeId];
2789
+ break;
2790
+ case "parent":
2791
+ candidateIds = owner.parentNodeId === null ? [] : [owner.parentNodeId];
2792
+ break;
2793
+ case "widget": candidateIds = nodeIdsByWidgetId.get(target.widgetId) ?? [];
2794
+ }
2795
+ if (candidateIds.length === 0) {
2796
+ if ((target.type === "parent" || target.type === "widget") && target.optional) return absent();
2797
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, describeMissingTarget(target), reference));
2798
+ return invalid();
2799
+ }
2800
+ if (candidateIds.length > 1) {
2801
+ const related = candidateIds.map((id) => widgetLocation(nodes[id].publicNode));
2802
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target is ambiguous: multiple widgets share that id.", reference, related));
2803
+ return invalid();
2804
+ }
2805
+ const targetNodeId = candidateIds[0];
2806
+ const targetWorking = nodes[targetNodeId];
2807
+ if (!targetWorking.resolved) {
2808
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target could not be resolved to a widget.", reference, [widgetLocation(targetWorking.publicNode)]));
2809
+ return invalid(targetNodeId);
2810
+ }
2811
+ const targetDefinition = readWidgetPluginDefinition(targetWorking.plugin);
2812
+ const targetPublicNode = targetWorking.publicNode;
2813
+ if (operation.type === "state-get" || operation.type === "state-set") {
2814
+ if (targetDefinition.state === null) {
2815
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no state capability.", reference, [widgetLocation(targetPublicNode)]));
2816
+ return invalid(targetNodeId);
2817
+ }
2818
+ if (!targetDefinition.state.has(operation.key)) {
2819
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no state member "${operation.key}".`, reference, [widgetLocation(targetPublicNode)]));
2820
+ return invalid(targetNodeId);
2821
+ }
2822
+ if (operation.type === "state-set" && member.type === "method") directWriteSeeds.add(`${ownerNodeId}:${member.name}`);
2823
+ } else if (operation.type === "property-get") {
2824
+ if (targetDefinition.properties === null) {
2825
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no properties capability.", reference, [widgetLocation(targetPublicNode)]));
2826
+ return invalid(targetNodeId);
2827
+ }
2828
+ if (!targetDefinition.properties.has(operation.name)) {
2829
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no property "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2830
+ return invalid(targetNodeId);
2831
+ }
2832
+ const key = edgeKey(member.type, ownerNodeId, member.name, "property", targetNodeId, operation.name);
2833
+ if (!edges.has(key)) edges.set(key, {
2834
+ fromKind: member.type,
2835
+ fromNodeId: ownerNodeId,
2836
+ fromName: member.name,
2837
+ toKind: "property",
2838
+ toNodeId: targetNodeId,
2839
+ toName: operation.name,
2840
+ reference
2841
+ });
2842
+ } else {
2843
+ if (targetDefinition.methods === null) {
2844
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, "Dependency target has no methods capability.", reference, [widgetLocation(targetPublicNode)]));
2845
+ return invalid(targetNodeId);
2846
+ }
2847
+ if (!targetDefinition.methods.has(operation.name)) {
2848
+ finalDiagnostics.push(dependencyDiagnostic(ownerPublicNode, member, `Dependency target has no method "${operation.name}".`, reference, [widgetLocation(targetPublicNode)]));
2849
+ return invalid(targetNodeId);
2850
+ }
2851
+ const key = edgeKey(member.type, ownerNodeId, member.name, "method", targetNodeId, operation.name);
2852
+ if (!edges.has(key)) edges.set(key, {
2853
+ fromKind: member.type,
2854
+ fromNodeId: ownerNodeId,
2855
+ fromName: member.name,
2856
+ toKind: "method",
2857
+ toNodeId: targetNodeId,
2858
+ toName: operation.name,
2859
+ reference
2860
+ });
2861
+ }
2862
+ return {
2863
+ [compiledDependencyBrand]: true,
2864
+ status: "resolved",
2865
+ targetNodeId,
2866
+ reference,
2867
+ refinements
2868
+ };
2869
+ }
2870
+ function resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics) {
2871
+ const edges = /* @__PURE__ */ new Map();
2872
+ const directWriteSeeds = /* @__PURE__ */ new Set();
2873
+ const resolve = (ownerNodeId, member, leaf) => resolveLeaf(nodes, nodeIdsByWidgetId, rootNodeId, ownerNodeId, member, leaf, finalDiagnostics, edges, directWriteSeeds);
2874
+ for (const nodeId of semanticOrder) {
2875
+ const node = nodes[nodeId];
2876
+ if (!node.resolved || node.plugin === null) continue;
2877
+ const definition = readWidgetPluginDefinition(node.plugin);
2878
+ if (definition.properties === null) continue;
2879
+ const configFrag = configFragment$1(node);
2880
+ for (const [name, propertyDefinition] of definition.properties) {
2881
+ const dep = createDependencyBuilder();
2882
+ let rawDeps = {};
2883
+ if (propertyDefinition.registerDeps !== void 0) {
2884
+ rawDeps = propertyDefinition.registerDeps({
2885
+ widget: compileFacade.facadeForNodeId(nodeId),
2886
+ blueprint: compileFacade.view,
2887
+ dep,
2888
+ ...configFrag
2889
+ });
2890
+ assertSyncValue(rawDeps, `Property "${name}"'s registerDeps`);
2891
+ }
2892
+ const member = {
2893
+ type: "property",
2894
+ name
2895
+ };
2896
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
2897
+ node.properties.set(name, {
2898
+ name,
2899
+ definition: propertyDefinition,
2900
+ deps
2901
+ });
2902
+ }
2903
+ }
2904
+ for (const nodeId of semanticOrder) {
2905
+ const node = nodes[nodeId];
2906
+ if (!node.resolved || node.plugin === null) continue;
2907
+ const definition = readWidgetPluginDefinition(node.plugin);
2908
+ if (definition.methods === null) continue;
2909
+ const configFrag = configFragment$1(node);
2910
+ for (const [name, methodDefinition] of definition.methods) {
2911
+ const dep = createDependencyBuilder();
2912
+ let rawDeps = {};
2913
+ if (methodDefinition.registerDeps !== void 0) {
2914
+ rawDeps = methodDefinition.registerDeps({
2915
+ widget: compileFacade.facadeForNodeId(nodeId),
2916
+ blueprint: compileFacade.view,
2917
+ dep,
2918
+ ...configFrag
2919
+ });
2920
+ assertSyncValue(rawDeps, `Method "${name}"'s registerDeps`);
2921
+ }
2922
+ const member = {
2923
+ type: "method",
2924
+ name
2925
+ };
2926
+ const deps = walkDeps(rawDeps, (leaf) => resolve(nodeId, member, leaf));
2927
+ node.methods.set(name, {
2928
+ name,
2929
+ definition: methodDefinition,
2930
+ deps,
2931
+ transitivelyWrites: false
2932
+ });
2933
+ }
2934
+ }
2935
+ return {
2936
+ edges,
2937
+ directWriteSeeds
2938
+ };
2939
+ }
2940
+ //#endregion
2941
+ //#region src/blueprint/graph.ts
2942
+ function memberKey(kind, nodeId, name) {
2943
+ return `${kind}:${nodeId}:${name}`;
2944
+ }
2945
+ function memberLocation(nodes, ref) {
2946
+ const node = nodes[ref.nodeId].publicNode;
2947
+ return ref.kind === "property" ? propertyLocation(node, ref.name) : methodLocation(node, ref.name);
2948
+ }
2949
+ /**
2950
+ * Runs the write-effect fixed point over Method->Method edges, marking transitively-writeful methods
2951
+ * on each node's already-built `CompiledMethodMember` map.
2952
+ */
2953
+ function computeWritefulMethods(nodes, edges, directWriteSeeds) {
2954
+ const writeful = new Set(directWriteSeeds);
2955
+ const methodEdges = [...edges.values()].filter((edge) => edge.fromKind === "method" && edge.toKind === "method");
2956
+ let changed = true;
2957
+ while (changed) {
2958
+ changed = false;
2959
+ for (const edge of methodEdges) {
2960
+ const fromKey = `${edge.fromNodeId}:${edge.fromName}`;
2961
+ const toKey = `${edge.toNodeId}:${edge.toName}`;
2962
+ if (writeful.has(toKey) && !writeful.has(fromKey)) {
2963
+ writeful.add(fromKey);
2964
+ changed = true;
2965
+ }
2966
+ }
2967
+ }
2968
+ for (const node of nodes) {
2969
+ if (!node.resolved) continue;
2970
+ for (const [name, member] of node.methods) if (writeful.has(`${node.nodeId}:${name}`) && !member.transitivelyWrites) node.methods.set(name, {
2971
+ ...member,
2972
+ transitivelyWrites: true
2973
+ });
2974
+ }
2975
+ return writeful;
2976
+ }
2977
+ function emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics) {
2978
+ for (const edge of edges.values()) {
2979
+ if (edge.fromKind !== "property" || edge.toKind !== "method") continue;
2980
+ if (!writefulMethods.has(`${edge.toNodeId}:${edge.toName}`)) continue;
2981
+ const ownerNode = nodes[edge.fromNodeId].publicNode;
2982
+ const targetNode = nodes[edge.toNodeId].publicNode;
2983
+ finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
2984
+ type: "property",
2985
+ name: edge.fromName
2986
+ }, `Property "${edge.fromName}" invokes writeful method "${edge.toName}".`, edge.reference, [methodLocation(targetNode, edge.toName)]));
2987
+ }
2988
+ }
2989
+ /**
2990
+ * Tarjan's strongly-connected-components algorithm over the evaluation graph, visiting adjacency in
2991
+ * `memberOrder` for determinism.
2992
+ */
2993
+ function findStronglyConnectedComponents(memberOrder, adjacency) {
2994
+ const indexOf = /* @__PURE__ */ new Map();
2995
+ let indexCounter = 0;
2996
+ const lowlink = /* @__PURE__ */ new Map();
2997
+ const onStack = /* @__PURE__ */ new Set();
2998
+ const stack = [];
2999
+ const components = [];
3000
+ function strongConnect(key) {
3001
+ indexOf.set(key, indexCounter);
3002
+ lowlink.set(key, indexCounter);
3003
+ indexCounter++;
3004
+ stack.push(key);
3005
+ onStack.add(key);
3006
+ for (const next of adjacency.get(key) ?? []) if (!indexOf.has(next)) {
3007
+ strongConnect(next);
3008
+ lowlink.set(key, Math.min(lowlink.get(key), lowlink.get(next)));
3009
+ } else if (onStack.has(next)) lowlink.set(key, Math.min(lowlink.get(key), indexOf.get(next)));
3010
+ if (lowlink.get(key) === indexOf.get(key)) {
3011
+ const component = [];
3012
+ let member;
3013
+ do {
3014
+ member = stack.pop();
3015
+ onStack.delete(member);
3016
+ component.push(member);
3017
+ } while (member !== key);
3018
+ components.push(component);
3019
+ }
3020
+ }
3021
+ for (const key of memberOrder) if (!indexOf.has(key)) strongConnect(key);
3022
+ return components;
3023
+ }
3024
+ function emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics) {
3025
+ const refByKey = /* @__PURE__ */ new Map();
3026
+ for (const ref of memberOrder) refByKey.set(memberKey(ref.kind, ref.nodeId, ref.name), ref);
3027
+ const orderIndex = /* @__PURE__ */ new Map();
3028
+ memberOrderKeys.forEach((key, index) => orderIndex.set(key, index));
3029
+ const components = findStronglyConnectedComponents(memberOrderKeys, adjacency);
3030
+ const invalidCycles = [];
3031
+ for (const component of components) {
3032
+ const hasSelfLoop = component.length === 1 && (adjacency.get(component[0]) ?? []).includes(component[0]);
3033
+ if (!(component.length > 1 || hasSelfLoop)) continue;
3034
+ 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)));
3035
+ const properties = refs.filter((ref) => ref.kind === "property");
3036
+ if (properties.length === 0) continue;
3037
+ invalidCycles.push(refs.map((ref) => ({
3038
+ nodeId: ref.nodeId,
3039
+ member: {
3040
+ type: ref.kind,
3041
+ name: ref.name
3042
+ }
3043
+ })));
3044
+ for (const property of properties) {
3045
+ const ownerNode = nodes[property.nodeId].publicNode;
3046
+ const related = refs.filter((ref) => ref !== property).map((ref) => memberLocation(nodes, ref));
3047
+ finalDiagnostics.push(dependencyDiagnostic(ownerNode, {
3048
+ type: "property",
3049
+ name: property.name
3050
+ }, `Property "${property.name}" participates in an evaluation cycle.`, void 0, related));
3051
+ }
3052
+ }
3053
+ return invalidCycles;
3054
+ }
3055
+ function runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics) {
3056
+ const writefulMethods = computeWritefulMethods(nodes, edges, directWriteSeeds);
3057
+ emitPurityDiagnostics(nodes, edges, writefulMethods, finalDiagnostics);
3058
+ const memberOrder = [];
3059
+ for (const nodeId of semanticOrder) {
3060
+ const node = nodes[nodeId];
3061
+ if (!node.resolved) continue;
3062
+ for (const name of node.properties.keys()) memberOrder.push({
3063
+ nodeId,
3064
+ kind: "property",
3065
+ name
3066
+ });
3067
+ for (const name of node.methods.keys()) memberOrder.push({
3068
+ nodeId,
3069
+ kind: "method",
3070
+ name
3071
+ });
3072
+ }
3073
+ const memberOrderKeys = memberOrder.map((ref) => memberKey(ref.kind, ref.nodeId, ref.name));
3074
+ const adjacency = /* @__PURE__ */ new Map();
3075
+ for (const edge of edges.values()) {
3076
+ const fromKey = memberKey(edge.fromKind, edge.fromNodeId, edge.fromName);
3077
+ const toKey = memberKey(edge.toKind, edge.toNodeId, edge.toName);
3078
+ const list = adjacency.get(fromKey);
3079
+ if (list === void 0) adjacency.set(fromKey, [toKey]);
3080
+ else list.push(toKey);
3081
+ }
3082
+ return {
3083
+ writefulMethods,
3084
+ invalidCycles: emitCycleDiagnostics(nodes, memberOrder, memberOrderKeys, adjacency, finalDiagnostics)
3085
+ };
3086
+ }
3087
+ //#endregion
3088
+ //#region src/blueprint/recovery.ts
3089
+ function isRecoverableObject(value) {
3090
+ if (typeof value !== "object" || value === null) return false;
3091
+ try {
3092
+ return !Array.isArray(value);
3093
+ } catch {
3094
+ return false;
3095
+ }
3096
+ }
3097
+ function readOwnDataProperty(object, key) {
3098
+ try {
3099
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
3100
+ if (descriptor === void 0) return {
3101
+ found: false,
3102
+ accessible: true
3103
+ };
3104
+ if (!("value" in descriptor)) return {
3105
+ found: true,
3106
+ accessible: false
3107
+ };
3108
+ return {
3109
+ found: true,
3110
+ accessible: true,
3111
+ value: descriptor.value
3112
+ };
3113
+ } catch {
3114
+ return {
3115
+ found: true,
3116
+ accessible: false
3117
+ };
3118
+ }
3119
+ }
3120
+ function readOwnEnumerableStringKeys(object) {
3121
+ try {
3122
+ return Object.keys(object);
3123
+ } catch {
3124
+ return null;
3125
+ }
3126
+ }
3127
+ function readArrayInfo(value) {
3128
+ try {
3129
+ if (!Array.isArray(value)) return {
3130
+ isArray: false,
3131
+ accessible: true
3132
+ };
3133
+ const descriptor = Object.getOwnPropertyDescriptor(value, "length");
3134
+ if (descriptor === void 0 || !("value" in descriptor) || typeof descriptor.value !== "number") return {
3135
+ isArray: true,
3136
+ accessible: false
3137
+ };
3138
+ return {
3139
+ isArray: true,
3140
+ accessible: true,
3141
+ length: descriptor.value
3142
+ };
3143
+ } catch {
3144
+ return {
3145
+ isArray: true,
3146
+ accessible: false
3147
+ };
3148
+ }
3149
+ }
3150
+ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3151
+ const nodeId = ctx.nodes.length;
3152
+ const shell = {
3153
+ source: rawValue,
3154
+ diagnostics: EMPTY_DIAGNOSTICS
3155
+ };
3156
+ const publicNode = shell;
3157
+ const working = {
3158
+ nodeId,
3159
+ parentNodeId,
3160
+ source: rawValue,
3161
+ rawSlots: [],
3162
+ location: Object.freeze(placement.kind === "root" ? { type: "root" } : placement.kind === "slot" ? {
3163
+ type: "slot",
3164
+ parent: parentPublicNode,
3165
+ slot: placement.slot,
3166
+ index: placement.index
3167
+ } : {
3168
+ type: "raw-slot",
3169
+ parent: parentPublicNode,
3170
+ slot: placement.slot,
3171
+ index: placement.index
3172
+ }),
3173
+ resolved: false,
3174
+ id: null,
3175
+ type: null,
3176
+ plugin: null,
3177
+ rawConfig: null,
3178
+ config: null,
3179
+ semanticSlots: /* @__PURE__ */ new Map(),
3180
+ state: /* @__PURE__ */ new Map(),
3181
+ properties: /* @__PURE__ */ new Map(),
3182
+ methods: /* @__PURE__ */ new Map(),
3183
+ publicNode
3184
+ };
3185
+ ctx.nodes.push(working);
3186
+ ctx.nodeIdByPublicNode.set(publicNode, nodeId);
3187
+ const localDiagnostics = [];
3188
+ const raw = isRecoverableObject(rawValue) ? rawValue : null;
3189
+ if (raw === null) {
3190
+ localDiagnostics.push(definitionDiagnostic(publicNode, "Widget definition must be a plain object."));
3191
+ finalizeShell(shell, working);
3192
+ flushDiagnostics(ctx, localDiagnostics);
3193
+ return nodeId;
3194
+ }
3195
+ if (ctx.activeSourceObjects.has(raw)) {
3196
+ localDiagnostics.push(definitionDiagnostic(publicNode, "Widget definition contains a cyclic source reference."));
3197
+ finalizeShell(shell, working);
3198
+ flushDiagnostics(ctx, localDiagnostics);
3199
+ return nodeId;
3200
+ }
3201
+ ctx.activeSourceObjects.add(raw);
3202
+ const idProperty = readOwnDataProperty(raw, "id");
3203
+ const rawId = idProperty.accessible ? idProperty.value : void 0;
3204
+ const hasValidId = idProperty.found && idProperty.accessible && typeof rawId === "string";
3205
+ if (!hasValidId) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"id\" is missing or is not a string.", ["id"]));
3206
+ const typeProperty = readOwnDataProperty(raw, "type");
3207
+ const rawType = typeProperty.accessible ? typeProperty.value : void 0;
3208
+ const hasValidTypeShape = typeProperty.found && typeProperty.accessible && typeof rawType === "string";
3209
+ let plugin = null;
3210
+ if (!hasValidTypeShape) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"type\" is missing or is not a string.", ["type"]));
3211
+ else {
3212
+ plugin = ctx.pluginsByType.get(rawType) ?? null;
3213
+ if (plugin === null) localDiagnostics.push(definitionDiagnostic(publicNode, `Unknown plugin type "${rawType}".`, ["type"]));
3214
+ }
3215
+ const resolved = hasValidId && hasValidTypeShape && plugin !== null;
3216
+ working.resolved = resolved;
3217
+ working.id = hasValidId ? rawId : null;
3218
+ if (resolved) {
3219
+ working.type = rawType;
3220
+ working.plugin = plugin;
3221
+ }
3222
+ if (resolved && plugin !== null) {
3223
+ const definition = readWidgetPluginDefinition(plugin);
3224
+ const configProperty = readOwnDataProperty(raw, "config");
3225
+ if (definition.config !== null) if (!configProperty.found) {
3226
+ const resolved = definition.config.resolve(null);
3227
+ assertSyncValue(resolved, "config.resolve");
3228
+ working.rawConfig = null;
3229
+ working.config = resolved;
3230
+ } else if (!configProperty.accessible) {
3231
+ localDiagnostics.push(configDiagnostic(publicNode, "Widget config could not be inspected safely."));
3232
+ const resolved = definition.config.resolve(null);
3233
+ assertSyncValue(resolved, "config.resolve");
3234
+ working.rawConfig = null;
3235
+ working.config = resolved;
3236
+ } else {
3237
+ const rawConfigValue = configProperty.value;
3238
+ const { collector, items } = createCollector();
3239
+ let ok = false;
3240
+ try {
3241
+ const rawValidateResult = definition.config.validate(rawConfigValue, collector);
3242
+ assertSyncValue(rawValidateResult, "config.validate");
3243
+ ok = rawValidateResult;
3244
+ } catch (error) {
3245
+ finalizeShell(shell, working);
3246
+ flushDiagnostics(ctx, localDiagnostics);
3247
+ throw error;
3248
+ }
3249
+ if (ok && items.length === 0) {
3250
+ const resolved = definition.config.resolve(rawConfigValue);
3251
+ assertSyncValue(resolved, "config.resolve");
3252
+ working.rawConfig = rawConfigValue;
3253
+ working.config = resolved;
3254
+ } else {
3255
+ if (items.length === 0) items.push({ message: "Invalid config." });
3256
+ for (const item of items) localDiagnostics.push(configDiagnostic(publicNode, item.message, item.path, item.reason));
3257
+ const resolved = definition.config.resolve(null);
3258
+ assertSyncValue(resolved, "config.resolve");
3259
+ working.rawConfig = null;
3260
+ working.config = resolved;
3261
+ }
3262
+ }
3263
+ else if (configProperty.found) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"config\" but its plugin has no config capability.", ["config"]));
3264
+ }
3265
+ if (resolved && plugin !== null) {
3266
+ const definition = readWidgetPluginDefinition(plugin);
3267
+ if (definition.state !== null) for (const [key, memberDefinition] of definition.state) working.state.set(key, {
3268
+ key,
3269
+ definition: memberDefinition
3270
+ });
3271
+ }
3272
+ recoverSlots(ctx, working, raw, resolved ? working.plugin : null, localDiagnostics);
3273
+ ctx.activeSourceObjects.delete(raw);
3274
+ finalizeShell(shell, working);
3275
+ flushDiagnostics(ctx, localDiagnostics);
3276
+ return nodeId;
3277
+ }
3278
+ function finalizeShell(shell, working) {
3279
+ shell.resolved = working.resolved;
3280
+ if (working.resolved) {
3281
+ shell.id = working.id;
3282
+ shell.type = working.type;
3283
+ shell.plugin = working.plugin;
3284
+ if (working.plugin !== null && readWidgetPluginDefinition(working.plugin).config !== null) {
3285
+ shell.rawConfig = working.rawConfig;
3286
+ shell.config = working.config;
3287
+ }
3288
+ shell.slots = {};
3289
+ }
3290
+ }
3291
+ /**
3292
+ * Recovers a node's raw `slots` fragment (topology only) and, for a resolved node, projects it onto
3293
+ * the plugin's declared semantic slots. Independent of plugin resolution for the raw-topology part.
3294
+ */
3295
+ function recoverSlots(ctx, working, raw, plugin, localDiagnostics) {
3296
+ const publicNode = working.publicNode;
3297
+ const declaredSlots = (plugin !== null ? readWidgetPluginDefinition(plugin) : null)?.slots ?? null;
3298
+ function fillMissingDeclaredSlots() {
3299
+ if (declaredSlots === null) return;
3300
+ for (const slotName of declaredSlots.keys()) if (!working.semanticSlots.has(slotName)) working.semanticSlots.set(slotName, []);
3301
+ }
3302
+ const slotsProperty = readOwnDataProperty(raw, "slots");
3303
+ if (!slotsProperty.found) {
3304
+ fillMissingDeclaredSlots();
3305
+ return;
3306
+ }
3307
+ if (!slotsProperty.accessible) {
3308
+ localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" could not be inspected safely.", ["slots"]));
3309
+ fillMissingDeclaredSlots();
3310
+ return;
3311
+ }
3312
+ const rawSlotsValue = slotsProperty.value;
3313
+ if (!isRecoverableObject(rawSlotsValue)) {
3314
+ localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" must be a plain object.", ["slots"]));
3315
+ fillMissingDeclaredSlots();
3316
+ return;
3317
+ }
3318
+ if (plugin !== null && declaredSlots === null) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"slots\" but its plugin has no slots capability.", ["slots"]));
3319
+ const slotNames = readOwnEnumerableStringKeys(rawSlotsValue);
3320
+ if (slotNames === null) {
3321
+ localDiagnostics.push(definitionDiagnostic(publicNode, "Widget \"slots\" could not be inspected safely.", ["slots"]));
3322
+ fillMissingDeclaredSlots();
3323
+ return;
3324
+ }
3325
+ for (const slotName of slotNames) {
3326
+ const slotProperty = readOwnDataProperty(rawSlotsValue, slotName);
3327
+ const isDeclared = declaredSlots !== null && declaredSlots.has(slotName);
3328
+ if (declaredSlots !== null && !isDeclared) localDiagnostics.push(definitionDiagnostic(publicNode, `Widget slot "${slotName}" is not declared by its plugin.`, ["slots", slotName]));
3329
+ const slotArray = readArrayInfo(slotProperty.value);
3330
+ if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
3331
+ localDiagnostics.push(definitionDiagnostic(publicNode, `Widget slot "${slotName}" must be an array.`, ["slots", slotName]));
3332
+ continue;
3333
+ }
3334
+ const childNodeIds = [];
3335
+ const placementKind = isDeclared ? "slot" : "raw-slot";
3336
+ const slotValue = slotProperty.value;
3337
+ for (let index = 0; index < slotArray.length; index++) {
3338
+ const childProperty = readOwnDataProperty(slotValue, String(index));
3339
+ const childId = buildNode(ctx, childProperty.found && childProperty.accessible ? childProperty.value : void 0, working.nodeId, publicNode, {
3340
+ kind: placementKind,
3341
+ slot: slotName,
3342
+ index
3343
+ });
3344
+ childNodeIds.push(childId);
3345
+ }
3346
+ working.rawSlots.push({
3347
+ slot: slotName,
3348
+ childNodeIds
3349
+ });
3350
+ if (isDeclared) working.semanticSlots.set(slotName, childNodeIds);
3351
+ }
3352
+ fillMissingDeclaredSlots();
3353
+ }
3354
+ function flushDiagnostics(ctx, diagnostics) {
3355
+ ctx.finalDiagnostics.push(...diagnostics);
3356
+ }
3357
+ /**
3358
+ * Fills in every resolved node's `.slots` public field from its (by-then complete) children and
3359
+ * freezes every public node. Runs once, after the whole tree has been recovered.
3360
+ */
3361
+ function finalizeSlots(ctx) {
3362
+ for (const node of ctx.nodes) {
3363
+ const shell = node.publicNode;
3364
+ if (node.resolved) {
3365
+ const slots = Object.create(null);
3366
+ for (const [slotName, childIds] of node.semanticSlots) slots[slotName] = Object.freeze(childIds.map((id) => ctx.nodes[id].publicNode));
3367
+ shell.slots = Object.freeze(slots);
3368
+ }
3369
+ Object.freeze(node.rawSlots);
3370
+ }
3371
+ }
3372
+ function computeWidgetIdIndex(ctx) {
3373
+ const index = /* @__PURE__ */ new Map();
3374
+ for (const node of ctx.nodes) {
3375
+ if (node.id === null) continue;
3376
+ const list = index.get(node.id);
3377
+ if (list === void 0) index.set(node.id, [node.nodeId]);
3378
+ else list.push(node.nodeId);
3379
+ }
3380
+ return index;
3381
+ }
3382
+ function emitDuplicateIdDiagnostics(ctx, index) {
3383
+ for (const ids of index.values()) {
3384
+ if (ids.length < 2) continue;
3385
+ for (const nodeId of ids) {
3386
+ const node = ctx.nodes[nodeId];
3387
+ const related = ids.filter((otherId) => otherId !== nodeId).map((otherId) => widgetLocation(ctx.nodes[otherId].publicNode));
3388
+ ctx.finalDiagnostics.push(definitionDiagnostic(node.publicNode, `Duplicate widget id "${node.id}".`, ["id"], related));
3389
+ }
3390
+ }
3391
+ }
3392
+ /**
3393
+ * Deterministic semantic traversal order used for diagnostic/aggregate ordering (COMMENT 13): declared
3394
+ * slots in plugin declaration order for resolved nodes, falling back to recovered raw-topology order
3395
+ * for unresolved nodes and for any raw-only child left over from an undeclared slot.
3396
+ */
3397
+ function computeSemanticOrder(nodes, rootNodeId) {
3398
+ const visited = /* @__PURE__ */ new Set();
3399
+ const order = [];
3400
+ function visit(nodeId) {
3401
+ if (visited.has(nodeId)) return;
3402
+ visited.add(nodeId);
3403
+ order.push(nodeId);
3404
+ const node = nodes[nodeId];
3405
+ if (node.resolved) {
3406
+ for (const childIds of node.semanticSlots.values()) for (const childId of childIds) visit(childId);
3407
+ for (const rawSlot of node.rawSlots) {
3408
+ if (node.semanticSlots.has(rawSlot.slot)) continue;
3409
+ for (const childId of rawSlot.childNodeIds) visit(childId);
3410
+ }
3411
+ } else for (const rawSlot of node.rawSlots) for (const childId of rawSlot.childNodeIds) visit(childId);
3412
+ }
3413
+ visit(rootNodeId);
3414
+ for (let id = 0; id < nodes.length; id++) visit(id);
3415
+ return order;
3416
+ }
3417
+ function recoverBlueprint(system, definition) {
3418
+ const pluginsByType = /* @__PURE__ */ new Map();
3419
+ for (const plugin of system.plugins) pluginsByType.set(plugin.type, plugin);
3420
+ const ctx = {
3421
+ pluginsByType,
3422
+ nodes: [],
3423
+ finalDiagnostics: [],
3424
+ diagnosticsByNode: /* @__PURE__ */ new Map(),
3425
+ nodeIdByPublicNode: /* @__PURE__ */ new Map(),
3426
+ activeSourceObjects: /* @__PURE__ */ new Set()
3427
+ };
3428
+ const rootNodeId = buildNode(ctx, definition, null, null, { kind: "root" });
3429
+ finalizeSlots(ctx);
3430
+ const nodeIdsByWidgetId = computeWidgetIdIndex(ctx);
3431
+ emitDuplicateIdDiagnostics(ctx, nodeIdsByWidgetId);
3432
+ return {
3433
+ nodes: ctx.nodes,
3434
+ rootNodeId,
3435
+ nodeIdByPublicNode: ctx.nodeIdByPublicNode,
3436
+ nodeIdsByWidgetId,
3437
+ finalDiagnostics: ctx.finalDiagnostics,
3438
+ diagnosticsByNode: ctx.diagnosticsByNode
3439
+ };
3440
+ }
3441
+ //#endregion
3442
+ //#region src/blueprint/structure.ts
3443
+ function configFragment(node) {
3444
+ return node.plugin !== null && readWidgetPluginDefinition(node.plugin).config !== null ? { config: node.config } : {};
3445
+ }
3446
+ /**
3447
+ * Declaration-order index of one slot name within a resolved node's plugin. Used only to make
3448
+ * system-level `related` ordering deterministic; `0` for a node/slot combination that cannot be
3449
+ * resolved (defensive fallback, never expected on a legitimate location).
3450
+ */
3451
+ function slotDeclarationIndex(node, slot) {
3452
+ if (node.plugin === null) return 0;
3453
+ const declaredSlots = readWidgetPluginDefinition(node.plugin).slots;
3454
+ if (declaredSlots === null) return 0;
3455
+ let index = 0;
3456
+ for (const slotName of declaredSlots.keys()) {
3457
+ if (slotName === slot) return index;
3458
+ index++;
3459
+ }
3460
+ return 0;
3461
+ }
3462
+ /**
3463
+ * Semantic identity key for one `related` location, used to deduplicate independently-authored
3464
+ * duplicates (same node + same discriminator) before finalizing. `location.node` is a compile-time
3465
+ * facade node (from `compileFacade.view`'s queries), resolved back to its internal node id via
3466
+ * `compileFacade.resolveNodeId`.
3467
+ */
3468
+ function locationKey(resolveNodeId, location) {
3469
+ const nodeId = resolveNodeId(location.node) ?? -1;
3470
+ const slot = location.type === "widget" ? "" : location.slot;
3471
+ const index = location.type === "slot-child" ? location.index : -1;
3472
+ return `${location.type}:${nodeId}:${slot}:${index}`;
3473
+ }
3474
+ const locationRank = {
3475
+ "widget": 0,
3476
+ "slot": 1,
3477
+ "slot-child": 2
3478
+ };
3479
+ /**
3480
+ * Orders `related` locations deterministically by semantic traversal order (the node's position in
3481
+ * `semanticOrder`), then discriminator refinement (widget -> slot -> slot-child), then slot
3482
+ * declaration order, then child index — never by authoring/hash/timing order.
3483
+ */
3484
+ function compareLocations(nodes, semanticOrderIndex, resolveNodeId, a, b) {
3485
+ const nodeIdA = resolveNodeId(a.node);
3486
+ const nodeIdB = resolveNodeId(b.node);
3487
+ const orderA = nodeIdA !== void 0 ? semanticOrderIndex.get(nodeIdA) ?? Number.MAX_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
3488
+ const orderB = nodeIdB !== void 0 ? semanticOrderIndex.get(nodeIdB) ?? Number.MAX_SAFE_INTEGER : Number.MAX_SAFE_INTEGER;
3489
+ if (orderA !== orderB) return orderA - orderB;
3490
+ const rankA = locationRank[a.type];
3491
+ const rankB = locationRank[b.type];
3492
+ if (rankA !== rankB) return rankA - rankB;
3493
+ if (a.type !== "widget" && b.type !== "widget" && nodeIdA !== void 0) {
3494
+ const slotIndexA = slotDeclarationIndex(nodes[nodeIdA], a.slot);
3495
+ const slotIndexB = slotDeclarationIndex(nodes[nodeIdA], b.slot);
3496
+ if (slotIndexA !== slotIndexB) return slotIndexA - slotIndexB;
3497
+ }
3498
+ if (a.type === "slot-child" && b.type === "slot-child") return a.index - b.index;
3499
+ return 0;
3500
+ }
3501
+ /**
3502
+ * Deduplicates and deterministically orders a system-level `validateStructure` author's `related`
3503
+ * input, then converts it to the framework-owned finalized location shape (real nodes, not facades).
3504
+ * `undefined` in, and `undefined` out for an empty result (a `related` field is never
3505
+ * present-but-empty).
3506
+ */
3507
+ function normalizeRelated(nodes, semanticOrderIndex, resolveNodeId, related) {
3508
+ if (related === void 0 || related.length === 0) return void 0;
3509
+ const deduped = dedupeBy(related, (location) => locationKey(resolveNodeId, location));
3510
+ deduped.sort((a, b) => compareLocations(nodes, semanticOrderIndex, resolveNodeId, a, b));
3511
+ if (deduped.length === 0) return void 0;
3512
+ return Object.freeze(deduped.map((location) => {
3513
+ const nodeId = resolveNodeId(location.node);
3514
+ const realNode = nodeId !== void 0 ? nodes[nodeId].publicNode : location.node;
3515
+ return {
3516
+ ...location,
3517
+ node: realNode
3518
+ };
3519
+ }));
3520
+ }
3521
+ function runStructureValidation(system, nodes, semanticOrder, compileFacade, finalDiagnostics) {
3522
+ for (const nodeId of semanticOrder) {
3523
+ const node = nodes[nodeId];
3524
+ if (!node.resolved || node.plugin === null) continue;
3525
+ const definition = readWidgetPluginDefinition(node.plugin);
3526
+ const publicNode = node.publicNode;
3527
+ const widgetFacade = compileFacade.facadeForNodeId(nodeId);
3528
+ if (definition.slots !== null) for (const [slotName, slotDefinition] of definition.slots) {
3529
+ if (slotDefinition.validateStructure === void 0) continue;
3530
+ const children = (node.semanticSlots.get(slotName) ?? []).map((id) => compileFacade.facadeForNodeId(id));
3531
+ const { collector, items } = createCollector();
3532
+ assertSyncValue(slotDefinition.validateStructure({
3533
+ widget: widgetFacade,
3534
+ slot: slotName,
3535
+ children,
3536
+ blueprint: compileFacade.view,
3537
+ ...configFragment(node),
3538
+ ...collector
3539
+ }), `Slot "${slotName}"'s validateStructure`);
3540
+ for (const item of items) finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slotName, item.index));
3541
+ }
3542
+ if (definition.validateStructure !== null) {
3543
+ const { collector, items } = createCollector();
3544
+ assertSyncValue(definition.validateStructure({
3545
+ widget: widgetFacade,
3546
+ blueprint: compileFacade.view,
3547
+ ...configFragment(node),
3548
+ ...collector
3549
+ }), `Plugin "${node.type}"'s validateStructure`);
3550
+ for (const item of items) {
3551
+ const slot = "slot" in item ? item.slot : void 0;
3552
+ const index = "index" in item ? item.index : void 0;
3553
+ finalDiagnostics.push(structureDiagnostic(publicNode, item.message, slot, index));
3554
+ }
3555
+ }
3556
+ }
3557
+ if (system.validateStructure !== null) {
3558
+ const { collector, items } = createCollector();
3559
+ assertSyncValue(system.validateStructure({
3560
+ blueprint: compileFacade.view,
3561
+ ...collector
3562
+ }), "System-level validateStructure");
3563
+ const semanticOrderIndex = /* @__PURE__ */ new Map();
3564
+ semanticOrder.forEach((nodeId, index) => semanticOrderIndex.set(nodeId, index));
3565
+ for (const item of items) {
3566
+ const { location, related } = item;
3567
+ const nodeId = compileFacade.resolveNodeId(location.node);
3568
+ const realNode = nodeId !== void 0 ? nodes[nodeId].publicNode : location.node;
3569
+ 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)));
3570
+ }
3571
+ }
3572
+ }
3573
+ //#endregion
3574
+ //#region src/blueprint/view.ts
3575
+ const EMPTY_CHILDREN = Object.freeze([]);
3576
+ const EMPTY_FACADE_CHILDREN = Object.freeze([]);
3577
+ /**
3578
+ * The real navigator, over full public nodes. Not exposed to plugin callbacks directly — only used to
3579
+ * assemble the finalized Blueprint's own navigation methods.
3580
+ */
3581
+ function createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId) {
3582
+ return {
3583
+ get root() {
3584
+ return nodes[rootNodeId].publicNode;
3585
+ },
3586
+ getWidget(id) {
3587
+ const ids = nodeIdsByWidgetId.get(id);
3588
+ if (ids === void 0 || ids.length !== 1) return null;
3589
+ return nodes[ids[0]].publicNode;
3590
+ },
3591
+ getParent(node) {
3592
+ const nodeId = nodeIdByPublicNode.get(node);
3593
+ if (nodeId === void 0) return null;
3594
+ const parentNodeId = nodes[nodeId].parentNodeId;
3595
+ return parentNodeId === null ? null : nodes[parentNodeId].publicNode;
3596
+ },
3597
+ getLocation(node) {
3598
+ const nodeId = nodeIdByPublicNode.get(node);
3599
+ if (nodeId === void 0) return null;
3600
+ return nodes[nodeId].location;
3601
+ },
3602
+ getChildren(node) {
3603
+ const nodeId = nodeIdByPublicNode.get(node);
3604
+ if (nodeId === void 0) return EMPTY_CHILDREN;
3605
+ const working = nodes[nodeId];
3606
+ const children = [];
3607
+ for (const rawSlot of working.rawSlots) for (const childId of rawSlot.childNodeIds) children.push(nodes[childId].publicNode);
3608
+ return Object.freeze(children);
3609
+ },
3610
+ getChildrenAt(node, slot) {
3611
+ const nodeId = nodeIdByPublicNode.get(node);
3612
+ if (nodeId === void 0) return EMPTY_CHILDREN;
3613
+ const entry = nodes[nodeId].rawSlots.find((rawSlot) => rawSlot.slot === slot);
3614
+ if (entry === void 0) return EMPTY_CHILDREN;
3615
+ return Object.freeze(entry.childNodeIds.map((childId) => nodes[childId].publicNode));
3616
+ }
3617
+ };
3618
+ }
3619
+ /**
3620
+ * Builds a real, restricted compile-time facade: node facades never physically carry `diagnostics`, a
3621
+ * resolved facade's `.slots` children are themselves facades, `getLocation()`'s `parent` is a facade,
3622
+ * and the returned navigator object is frozen (readonly navigation, per {@link BlueprintCompileView}).
3623
+ */
3624
+ function createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId) {
3625
+ const facadeByNodeId = /* @__PURE__ */ new Map();
3626
+ const nodeIdByFacade = /* @__PURE__ */ new Map();
3627
+ const facadeLocationByNodeId = /* @__PURE__ */ new Map();
3628
+ function facadeForNodeId(nodeId) {
3629
+ const cached = facadeByNodeId.get(nodeId);
3630
+ if (cached !== void 0) return cached;
3631
+ const working = nodes[nodeId];
3632
+ const shell = Object.create(null);
3633
+ shell.source = working.source;
3634
+ shell.resolved = working.resolved;
3635
+ if (working.resolved) {
3636
+ shell.id = working.id;
3637
+ shell.type = working.type;
3638
+ shell.plugin = working.plugin;
3639
+ if (working.plugin !== null && readWidgetPluginDefinition(working.plugin).config !== null) {
3640
+ shell.rawConfig = working.rawConfig;
3641
+ shell.config = working.config;
3642
+ }
3643
+ const slots = Object.create(null);
3644
+ for (const [slotName, childIds] of working.semanticSlots) slots[slotName] = Object.freeze(childIds.map((childId) => facadeForNodeId(childId)));
3645
+ shell.slots = Object.freeze(slots);
3646
+ }
3647
+ const facade = Object.freeze(shell);
3648
+ facadeByNodeId.set(nodeId, facade);
3649
+ nodeIdByFacade.set(facade, nodeId);
3650
+ return facade;
3651
+ }
3652
+ function resolveNodeId(node) {
3653
+ const viaFacade = nodeIdByFacade.get(node);
3654
+ if (viaFacade !== void 0) return viaFacade;
3655
+ return nodeIdByPublicNode.get(node);
3656
+ }
3657
+ function facadeLocationForNodeId(nodeId) {
3658
+ const cached = facadeLocationByNodeId.get(nodeId);
3659
+ if (cached !== void 0) return cached;
3660
+ const location = nodes[nodeId].location;
3661
+ let facadeLocation;
3662
+ if (location.type === "root") facadeLocation = Object.freeze({ type: "root" });
3663
+ else {
3664
+ const parentNodeId = nodeIdByPublicNode.get(location.parent);
3665
+ facadeLocation = parentNodeId === void 0 ? null : Object.freeze({
3666
+ type: location.type,
3667
+ parent: facadeForNodeId(parentNodeId),
3668
+ slot: location.slot,
3669
+ index: location.index
3670
+ });
3671
+ }
3672
+ facadeLocationByNodeId.set(nodeId, facadeLocation);
3673
+ return facadeLocation;
3674
+ }
3675
+ const view = {
3676
+ get root() {
3677
+ return facadeForNodeId(rootNodeId);
3678
+ },
3679
+ getWidget(id) {
3680
+ const ids = nodeIdsByWidgetId.get(id);
3681
+ if (ids === void 0 || ids.length !== 1) return null;
3682
+ return facadeForNodeId(ids[0]);
3683
+ },
3684
+ getParent(node) {
3685
+ const nodeId = resolveNodeId(node);
3686
+ if (nodeId === void 0) return null;
3687
+ const parentNodeId = nodes[nodeId].parentNodeId;
3688
+ return parentNodeId === null ? null : facadeForNodeId(parentNodeId);
3689
+ },
3690
+ getLocation(node) {
3691
+ const nodeId = resolveNodeId(node);
3692
+ if (nodeId === void 0) return null;
3693
+ return facadeLocationForNodeId(nodeId);
3694
+ },
3695
+ getChildren(node) {
3696
+ const nodeId = resolveNodeId(node);
3697
+ if (nodeId === void 0) return EMPTY_FACADE_CHILDREN;
3698
+ const working = nodes[nodeId];
3699
+ const children = [];
3700
+ for (const rawSlot of working.rawSlots) for (const childId of rawSlot.childNodeIds) children.push(facadeForNodeId(childId));
3701
+ return Object.freeze(children);
3702
+ },
3703
+ getChildrenAt(node, slot) {
3704
+ const nodeId = resolveNodeId(node);
3705
+ if (nodeId === void 0) return EMPTY_FACADE_CHILDREN;
3706
+ const entry = nodes[nodeId].rawSlots.find((rawSlot) => rawSlot.slot === slot);
3707
+ if (entry === void 0) return EMPTY_FACADE_CHILDREN;
3708
+ return Object.freeze(entry.childNodeIds.map((childId) => facadeForNodeId(childId)));
3709
+ }
3710
+ };
3711
+ Object.freeze(view);
3712
+ return {
3713
+ view,
3714
+ facadeForNodeId: (nodeId) => facadeForNodeId(nodeId),
3715
+ resolveNodeId
3716
+ };
3717
+ }
3718
+ //#endregion
3719
+ //#region src/blueprint/index.ts
3720
+ function finalizeDiagnosticsByNode(nodeIdByPublicNode, finalDiagnostics, diagnosticsByNode) {
3721
+ for (const diagnostic of finalDiagnostics) {
3722
+ if (diagnostic.code === "json-incompatible-value" || diagnostic.code === "source-access-failed") continue;
3723
+ const node = diagnostic.location.node;
3724
+ const nodeId = nodeIdByPublicNode.get(node);
3725
+ if (nodeId === void 0) continue;
3726
+ const list = diagnosticsByNode.get(nodeId);
3727
+ if (list === void 0) diagnosticsByNode.set(nodeId, [diagnostic]);
3728
+ else list.push(diagnostic);
3729
+ }
3730
+ }
3731
+ function buildCompiledNodes(nodes, diagnosticsByNode) {
3732
+ return nodes.map((node) => {
3733
+ const diagnostics = diagnosticsByNode.get(node.nodeId) ?? EMPTY_DIAGNOSTICS;
3734
+ const base = {
3735
+ nodeId: node.nodeId,
3736
+ publicNode: node.publicNode,
3737
+ source: node.source,
3738
+ parentNodeId: node.parentNodeId,
3739
+ location: node.location,
3740
+ rawSlots: Object.freeze(node.rawSlots),
3741
+ diagnostics
3742
+ };
3743
+ if (!node.resolved) return {
3744
+ ...base,
3745
+ resolved: false,
3746
+ id: node.id
3747
+ };
3748
+ return {
3749
+ ...base,
3750
+ resolved: true,
3751
+ id: node.id,
3752
+ type: node.type,
3753
+ plugin: node.plugin,
3754
+ rawConfig: node.rawConfig,
3755
+ config: node.config,
3756
+ semanticSlots: node.semanticSlots,
3757
+ state: node.state,
3758
+ properties: node.properties,
3759
+ methods: node.methods
3760
+ };
3761
+ });
3762
+ }
3763
+ function compileBlueprint(system, definition) {
3764
+ const { nodes, rootNodeId, nodeIdByPublicNode, nodeIdsByWidgetId, finalDiagnostics, diagnosticsByNode } = recoverBlueprint(system, definition);
3765
+ const jsonInspection = inspectJsonValue(definition);
3766
+ const sourceJsonCompatible = jsonInspection.compatible;
3767
+ finalDiagnostics.push(...jsonInspection.diagnostics);
3768
+ const semanticOrder = computeSemanticOrder(nodes, rootNodeId);
3769
+ const navigator = createNavigator(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3770
+ const compileFacade = createCompileFacade(nodes, nodeIdByPublicNode, nodeIdsByWidgetId, rootNodeId);
3771
+ runStructureValidation(system, nodes, semanticOrder, compileFacade, finalDiagnostics);
3772
+ const { edges, directWriteSeeds } = resolveDependencies(nodes, semanticOrder, rootNodeId, nodeIdsByWidgetId, compileFacade, finalDiagnostics);
3773
+ const analysis = runGraphAnalysis(nodes, semanticOrder, edges, directWriteSeeds, finalDiagnostics);
3774
+ finalizeDiagnosticsByNode(nodeIdByPublicNode, finalDiagnostics, diagnosticsByNode);
3775
+ for (const list of diagnosticsByNode.values()) freezeDiagnosticSnapshot(list);
3776
+ freezeDiagnosticSnapshot(finalDiagnostics);
3777
+ for (const node of nodes) {
3778
+ const shell = node.publicNode;
3779
+ shell.diagnostics = diagnosticsByNode.get(node.nodeId) ?? EMPTY_DIAGNOSTICS;
3780
+ Object.freeze(shell);
3781
+ }
3782
+ const canCreateRuntime = (finalDiagnostics.length === 0 ? "valid" : "invalid") === "valid" && sourceJsonCompatible;
3783
+ const compiledNodes = buildCompiledNodes(nodes, diagnosticsByNode);
3784
+ const compiled = {
3785
+ system,
3786
+ source: definition,
3787
+ sourceJsonCompatible,
3788
+ status: canCreateRuntime ? "valid" : "invalid",
3789
+ rootNodeId,
3790
+ nodes: compiledNodes,
3791
+ nodeIdByPublicNode,
3792
+ nodeIdsByWidgetId,
3793
+ semanticOrder,
3794
+ diagnostics: finalDiagnostics,
3795
+ analysis
3796
+ };
3797
+ if (canCreateRuntime) {
3798
+ const validNavigator = navigator;
3799
+ const blueprint = {
3800
+ system,
3801
+ source: definition,
3802
+ sourceJsonCompatible: true,
3803
+ status: "valid",
3804
+ root: validNavigator.root,
3805
+ getWidget: validNavigator.getWidget,
3806
+ getParent: validNavigator.getParent,
3807
+ getLocation: validNavigator.getLocation,
3808
+ getChildren: validNavigator.getChildren,
3809
+ getChildrenAt: validNavigator.getChildrenAt,
3810
+ diagnostics: EMPTY_DIAGNOSTICS,
3811
+ recompile: (next) => system.createBlueprint(next),
3812
+ createRuntime: (options) => createWidgetSystemRuntime(blueprint, options)
3813
+ };
3814
+ return attachInternalsAndFreeze(blueprint, compiled);
3815
+ }
3816
+ const invalidNavigator = navigator;
3817
+ if (sourceJsonCompatible) {
3818
+ const jsonInvalidNavigator = invalidNavigator;
3819
+ return attachInternalsAndFreeze({
3820
+ system,
3821
+ source: definition,
3822
+ sourceJsonCompatible: true,
3823
+ status: "invalid",
3824
+ root: jsonInvalidNavigator.root,
3825
+ getWidget: jsonInvalidNavigator.getWidget,
3826
+ getParent: jsonInvalidNavigator.getParent,
3827
+ getLocation: jsonInvalidNavigator.getLocation,
3828
+ getChildren: jsonInvalidNavigator.getChildren,
3829
+ getChildrenAt: jsonInvalidNavigator.getChildrenAt,
3830
+ diagnostics: finalDiagnostics,
3831
+ recompile: (next) => system.createBlueprint(next)
3832
+ }, compiled);
3833
+ }
3834
+ return attachInternalsAndFreeze({
3835
+ system,
3836
+ source: definition,
3837
+ sourceJsonCompatible: false,
3838
+ status: "invalid",
3839
+ root: invalidNavigator.root,
3840
+ getWidget: invalidNavigator.getWidget,
3841
+ getParent: invalidNavigator.getParent,
3842
+ getLocation: invalidNavigator.getLocation,
3843
+ getChildren: invalidNavigator.getChildren,
3844
+ getChildrenAt: invalidNavigator.getChildrenAt,
3845
+ diagnostics: finalDiagnostics,
3846
+ recompile: (next) => system.createBlueprint(next)
3847
+ }, compiled);
3848
+ }
3849
+ /**
3850
+ * Attaches the compiled internal model under the private `blueprintInternals` symbol (not part of the
3851
+ * published Blueprint contract) and freezes the public Blueprint object.
3852
+ */
3853
+ function attachInternalsAndFreeze(blueprint, compiled) {
3854
+ blueprint[blueprintInternals] = compiled;
3855
+ return Object.freeze(blueprint);
3856
+ }
3857
+ //#endregion
3858
+ //#region src/system.ts
3859
+ /**
3860
+ * Creates an instance-scoped, immutable widget system. Duplicate `plugin.type` is rejected.
3861
+ */
3862
+ function createWidgetSystem(options) {
3863
+ const plugins = Object.freeze([...options.plugins]);
3864
+ const pluginsByType = /* @__PURE__ */ new Map();
3865
+ for (const plugin of plugins) {
3866
+ if (pluginsByType.has(plugin.type)) throw new Error(`Duplicate widget plugin type: "${plugin.type}".`);
3867
+ pluginsByType.set(plugin.type, plugin);
3868
+ }
3869
+ const catalog = Object.freeze({ widgets: Object.freeze(plugins.map((plugin) => Object.freeze({
3870
+ type: plugin.type,
3871
+ description: plugin.description,
3872
+ descriptions: Object.freeze({
3873
+ config: plugin.descriptions.config,
3874
+ slots: plugin.descriptions.slots === null ? null : createReadonlyMap(plugin.descriptions.slots)
3875
+ })
3876
+ }))) });
3877
+ const system = {
3878
+ plugins,
3879
+ validateStructure: options.validateStructure ?? null,
3880
+ catalog,
3881
+ getPlugin(type) {
3882
+ return pluginsByType.get(type);
3883
+ },
3884
+ createBlueprint(definition) {
3885
+ return compileBlueprint(system, definition);
3886
+ }
3887
+ };
3888
+ return Object.freeze(system);
3889
+ }
3890
+ //#endregion
3891
+ export { EMPTY_DIAGNOSTICS, WidgetSystemRuntimeDisposedError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, normalizeSeparatedWidgetSource, separateWidgetSource };