@deviltea/widget-core 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
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";
1
+ import { a as runRuntimeOperation, i as invokeListenerIsolated, n as createEventPrimitive, o as writeDeferringFlush, r as createTrackedSubscription, t as buildEventEmitter } from "./event-BMif_vRJ.mjs";
2
+ import { a as createWidgetPlugin, c as readWidgetPluginDefinition, i as WIDGET_CONFIG_JSON_SCHEMA_DIALECT, l as createReadonlyMap, o as createWidgetValueContract, r as runtimeInternals, s as isCoreWidgetPlugin } from "./internals-L391flXY.mjs";
3
+ import { a as readCompiledBlueprint, n as compiledDependencyBrand, r as isCompiledDependency, t as blueprintInternals } from "./contract-CRpMqCY2.mjs";
4
+ import { computed, endBatch, signal, startBatch } from "alien-signals";
3
5
  //#region src/diagnostic.ts
4
6
  const EMPTY_DIAGNOSTICS = Object.freeze([]);
5
7
  var WidgetSystemRuntimeDisposedError = class extends Error {
@@ -10,144 +12,6 @@ var WidgetSystemRuntimeDisposedError = class extends Error {
10
12
  }
11
13
  };
12
14
  //#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
15
  //#region src/json.ts
152
16
  function jsonDiagnostic(path, reason) {
153
17
  return {
@@ -304,7 +168,7 @@ function inspectJsonValue(value) {
304
168
  function isJsonValue(value) {
305
169
  return inspectJsonValue(value).compatible;
306
170
  }
307
- /** JSON-domain equality used by RFC6902 `test` and by SourcePatch no-op detection. */
171
+ /** JSON-domain equality used by the RFC6902 `test` operation. (SourcePatch no-op detection uses `structurallyEqual` in `source-patch.ts`.) */
308
172
  function jsonEqual(left, right, seen = /* @__PURE__ */ new Set()) {
309
173
  if (Object.is(left, right)) return true;
310
174
  if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false;
@@ -882,6 +746,15 @@ function applySourcePatch(source, patch) {
882
746
  }
883
747
  //#endregion
884
748
  //#region src/document.ts
749
+ /**
750
+ * Creates a revisioned source + Blueprint coordinator.
751
+ *
752
+ * Ownership: `options.source` is retained by reference as revision 0's `blueprint.source`, and Core
753
+ * never mutates it. Handing it over transfers ownership, so it must not be mutated afterwards. Patches
754
+ * are copy-on-write: each new revision shares untouched subtrees with the previous one, so any revision
755
+ * can share structure with this original input, and mutating the input corrupts later revisions too.
756
+ * A host that keeps its own editable model should pass a copy (for example `structuredClone`).
757
+ */
885
758
  function createWidgetDocument(options) {
886
759
  let blueprint = options.system.createBlueprint(options.source);
887
760
  let snapshot = Object.freeze({
@@ -956,149 +829,6 @@ function createWidgetDocument(options) {
956
829
  });
957
830
  }
958
831
  //#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
832
  //#region src/separated-source.ts
1103
833
  function readDataProperty(value, key) {
1104
834
  try {
@@ -1390,45 +1120,47 @@ function normalizeSeparatedWidgetSource(input) {
1390
1120
  area: "structure",
1391
1121
  path: diagnosticPath(path, "slots")
1392
1122
  }, "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" });
1123
+ else if (slotsProperty.found && slotsProperty.accessible) {
1124
+ if (!isPlainObject(slotsProperty.value)) {
1125
+ output.slots = copyRecoveryValue(slotsProperty.value);
1126
+ addDiagnostic("invalid-separated-structure", {
1127
+ area: "structure",
1128
+ path: diagnosticPath(path, "slots")
1129
+ }, "structure slots must be an object.", { reason: "invalid-slots" });
1130
+ } else {
1131
+ const outputSlots = Object.create(null);
1132
+ const slots = ownStringKeys(slotsProperty.value);
1133
+ if (slots === null) addDiagnostic("invalid-separated-structure", {
1134
+ area: "structure",
1135
+ path: diagnosticPath(path, "slots")
1136
+ }, "structure slots could not be inspected safely.", { reason: "invalid-slots" });
1137
+ else {
1138
+ for (const slot of slots) {
1139
+ const slotProperty = readDataProperty(slotsProperty.value, slot);
1140
+ const slotPath = diagnosticPath(diagnosticPath(path, "slots"), slot);
1141
+ const slotArray = readArrayInfo$1(slotProperty.value);
1142
+ if (!slotProperty.found || !slotProperty.accessible || !slotArray.isArray || !slotArray.accessible) {
1143
+ if (slotProperty.found && slotProperty.accessible) outputSlots[slot] = copyRecoveryValue(slotProperty.value);
1144
+ addDiagnostic("invalid-separated-structure", {
1145
+ area: "structure",
1146
+ path: slotPath
1147
+ }, "structure slot must be an Array.", { reason: "invalid-slot-children" });
1148
+ continue;
1149
+ }
1150
+ const children = [];
1151
+ const childArray = slotProperty.value;
1152
+ for (let index = 0; index < slotArray.length; index++) {
1153
+ const childProperty = readDataProperty(childArray, String(index));
1154
+ children.push(childProperty.found && childProperty.accessible ? normalizeNode(childProperty.value, [...slotPath, index]) : void 0);
1155
+ if (!childProperty.found || !childProperty.accessible) addDiagnostic("invalid-separated-structure", {
1156
+ area: "structure",
1157
+ path: [...slotPath, index]
1158
+ }, "structure child could not be inspected safely.", { reason: "invalid-slot-children" });
1159
+ }
1160
+ outputSlots[slot] = children;
1428
1161
  }
1429
- outputSlots[slot] = children;
1162
+ output.slots = outputSlots;
1430
1163
  }
1431
- output.slots = outputSlots;
1432
1164
  }
1433
1165
  }
1434
1166
  return output;
@@ -2066,6 +1798,7 @@ function createMethodPrimitive(context, params) {
2066
1798
  widget: params.selfNode,
2067
1799
  blueprint: params.blueprintView,
2068
1800
  deps: params.deps,
1801
+ ...params.emitFragment,
2069
1802
  ...params.buildConfigFragment(),
2070
1803
  addDiagnostic: execCollector.addDiagnostic,
2071
1804
  hasAnyDiagnostic: execCollector.hasAnyDiagnostic
@@ -2380,6 +2113,11 @@ function buildRuntimeWidget(context, node, entry) {
2380
2113
  for (const [name, primitive] of entry.methods) methodsSurface[name] = primitive.public;
2381
2114
  widget.methods = Object.freeze(methodsSurface);
2382
2115
  }
2116
+ if (definition.events !== null) {
2117
+ const eventsSurface = Object.create(null);
2118
+ for (const [name, primitive] of entry.events) eventsSurface[name] = primitive.public;
2119
+ widget.events = Object.freeze(eventsSurface);
2120
+ }
2383
2121
  return Object.freeze(widget);
2384
2122
  }
2385
2123
  //#endregion
@@ -2399,9 +2137,12 @@ function createWidgetSystemRuntime(blueprint, options) {
2399
2137
  const entry = {
2400
2138
  state: /* @__PURE__ */ new Map(),
2401
2139
  properties: /* @__PURE__ */ new Map(),
2402
- methods: /* @__PURE__ */ new Map()
2140
+ methods: /* @__PURE__ */ new Map(),
2141
+ events: /* @__PURE__ */ new Map()
2403
2142
  };
2404
2143
  registry.set(nodeId, entry);
2144
+ const definition = readWidgetPluginDefinition(node.plugin);
2145
+ if (definition.events !== null) for (const name of definition.events.keys()) entry.events.set(name, createEventPrimitive(context));
2405
2146
  const buildConfigFragment = buildConfigFragmentFor(node);
2406
2147
  for (const [key, member] of node.state) {
2407
2148
  const primitive = createStatePrimitive(context, {
@@ -2443,6 +2184,7 @@ function createWidgetSystemRuntime(blueprint, options) {
2443
2184
  const entry = registry.get(nodeId);
2444
2185
  if (entry === void 0) continue;
2445
2186
  const buildConfigFragment = buildConfigFragmentFor(node);
2187
+ const emitFragment = readWidgetPluginDefinition(node.plugin).events === null ? Object.freeze({}) : Object.freeze({ emit: buildEventEmitter(entry.events) });
2446
2188
  for (const [name, member] of node.properties) {
2447
2189
  const deps = materializeDependencyTree(member.deps, {
2448
2190
  consumer: "property",
@@ -2479,16 +2221,20 @@ function createWidgetSystemRuntime(blueprint, options) {
2479
2221
  buildConfigFragment,
2480
2222
  selfNode: node.publicNode,
2481
2223
  blueprintView,
2482
- deps
2224
+ deps,
2225
+ emitFragment
2483
2226
  });
2484
2227
  entry.methods.set(name, primitive);
2485
2228
  }
2486
2229
  }
2487
2230
  const runtimeWidgetsByNodeId = /* @__PURE__ */ new Map();
2231
+ const nodeIdByRuntimeWidget = /* @__PURE__ */ new Map();
2488
2232
  for (const [nodeId, entry] of registry) {
2489
2233
  const node = compiled.nodes[nodeId];
2490
2234
  if (node === void 0 || !node.resolved) continue;
2491
- runtimeWidgetsByNodeId.set(nodeId, buildRuntimeWidget(context, node, entry));
2235
+ const runtimeWidget = buildRuntimeWidget(context, node, entry);
2236
+ runtimeWidgetsByNodeId.set(nodeId, runtimeWidget);
2237
+ nodeIdByRuntimeWidget.set(runtimeWidget, nodeId);
2492
2238
  }
2493
2239
  const aggregate = createRuntimeAggregate(context, compiled, registry, overrideResolution.runtimeLevelDiagnostics);
2494
2240
  function getWidget(id) {
@@ -2511,7 +2257,9 @@ function createWidgetSystemRuntime(blueprint, options) {
2511
2257
  };
2512
2258
  runtime[runtimeInternals] = {
2513
2259
  context,
2514
- registry
2260
+ registry,
2261
+ compiled,
2262
+ nodeIdByRuntimeWidget
2515
2263
  };
2516
2264
  return runtime;
2517
2265
  }
@@ -3222,45 +2970,46 @@ function buildNode(ctx, rawValue, parentNodeId, parentPublicNode, placement) {
3222
2970
  if (resolved && plugin !== null) {
3223
2971
  const definition = readWidgetPluginDefinition(plugin);
3224
2972
  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);
2973
+ if (definition.config !== null) {
2974
+ if (!configProperty.found) {
2975
+ const resolved = definition.config.resolve(null);
3251
2976
  assertSyncValue(resolved, "config.resolve");
3252
- working.rawConfig = rawConfigValue;
2977
+ working.rawConfig = null;
3253
2978
  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));
2979
+ } else if (!configProperty.accessible) {
2980
+ localDiagnostics.push(configDiagnostic(publicNode, "Widget config could not be inspected safely."));
3257
2981
  const resolved = definition.config.resolve(null);
3258
2982
  assertSyncValue(resolved, "config.resolve");
3259
2983
  working.rawConfig = null;
3260
2984
  working.config = resolved;
2985
+ } else {
2986
+ const rawConfigValue = configProperty.value;
2987
+ const { collector, items } = createCollector();
2988
+ let ok = false;
2989
+ try {
2990
+ const rawValidateResult = definition.config.validate(rawConfigValue, collector);
2991
+ assertSyncValue(rawValidateResult, "config.validate");
2992
+ ok = rawValidateResult;
2993
+ } catch (error) {
2994
+ finalizeShell(shell, working);
2995
+ flushDiagnostics(ctx, localDiagnostics);
2996
+ throw error;
2997
+ }
2998
+ if (ok && items.length === 0) {
2999
+ const resolved = definition.config.resolve(rawConfigValue);
3000
+ assertSyncValue(resolved, "config.resolve");
3001
+ working.rawConfig = rawConfigValue;
3002
+ working.config = resolved;
3003
+ } else {
3004
+ if (items.length === 0) items.push({ message: "Invalid config." });
3005
+ for (const item of items) localDiagnostics.push(configDiagnostic(publicNode, item.message, item.path, item.reason));
3006
+ const resolved = definition.config.resolve(null);
3007
+ assertSyncValue(resolved, "config.resolve");
3008
+ working.rawConfig = null;
3009
+ working.config = resolved;
3010
+ }
3261
3011
  }
3262
- }
3263
- else if (configProperty.found) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"config\" but its plugin has no config capability.", ["config"]));
3012
+ } else if (configProperty.found) localDiagnostics.push(definitionDiagnostic(publicNode, "Widget declares \"config\" but its plugin has no config capability.", ["config"]));
3264
3013
  }
3265
3014
  if (resolved && plugin !== null) {
3266
3015
  const definition = readWidgetPluginDefinition(plugin);
@@ -3857,18 +3606,58 @@ function attachInternalsAndFreeze(blueprint, compiled) {
3857
3606
  //#endregion
3858
3607
  //#region src/system.ts
3859
3608
  /**
3609
+ * Thrown by `createWidgetSystem` for an invalid plugin registration. Discriminate by class and `code`;
3610
+ * `message` is not protocol.
3611
+ *
3612
+ * - `foreign-plugin`: the entry at `pluginIndex` was not completed by this loaded module instance
3613
+ * (another module instance or a structural look-alike). `pluginType` is its `type` when a string,
3614
+ * else `null`. `firstPluginIndex` is `null`.
3615
+ * - `duplicate-plugin-type`: the entry at `pluginIndex` repeats `pluginType`, first registered at
3616
+ * `firstPluginIndex`.
3617
+ */
3618
+ var WidgetSystemConfigurationError = class extends Error {
3619
+ code;
3620
+ pluginIndex;
3621
+ pluginType;
3622
+ firstPluginIndex;
3623
+ name = "WidgetSystemConfigurationError";
3624
+ constructor(code, pluginIndex, pluginType, firstPluginIndex = null, message = code === "foreign-plugin" ? `The widget plugin at index ${pluginIndex} was not created by this widget core instance.` : `Duplicate widget plugin type "${pluginType}" at index ${pluginIndex} (first registered at index ${firstPluginIndex}).`) {
3625
+ super(message);
3626
+ this.code = code;
3627
+ this.pluginIndex = pluginIndex;
3628
+ this.pluginType = pluginType;
3629
+ this.firstPluginIndex = firstPluginIndex;
3630
+ }
3631
+ };
3632
+ /**
3633
+ * Best-effort read of a foreign entry's `type`; a throwing accessor must not leak as an uncoded failure.
3634
+ */
3635
+ function readForeignPluginType(entry) {
3636
+ try {
3637
+ const type = entry?.type;
3638
+ return typeof type === "string" ? type : null;
3639
+ } catch {
3640
+ return null;
3641
+ }
3642
+ }
3643
+ /**
3860
3644
  * Creates an instance-scoped, immutable widget system. Duplicate `plugin.type` is rejected.
3861
3645
  */
3862
3646
  function createWidgetSystem(options) {
3863
3647
  const plugins = Object.freeze([...options.plugins]);
3864
3648
  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}".`);
3649
+ const firstIndexByType = /* @__PURE__ */ new Map();
3650
+ for (const [index, plugin] of plugins.entries()) {
3651
+ if (!isCoreWidgetPlugin(plugin)) throw new WidgetSystemConfigurationError("foreign-plugin", index, readForeignPluginType(plugin));
3652
+ const firstIndex = firstIndexByType.get(plugin.type);
3653
+ if (firstIndex !== void 0) throw new WidgetSystemConfigurationError("duplicate-plugin-type", index, plugin.type, firstIndex);
3654
+ firstIndexByType.set(plugin.type, index);
3867
3655
  pluginsByType.set(plugin.type, plugin);
3868
3656
  }
3869
3657
  const catalog = Object.freeze({ widgets: Object.freeze(plugins.map((plugin) => Object.freeze({
3870
3658
  type: plugin.type,
3871
3659
  description: plugin.description,
3660
+ config: plugin.config,
3872
3661
  descriptions: Object.freeze({
3873
3662
  config: plugin.descriptions.config,
3874
3663
  slots: plugin.descriptions.slots === null ? null : createReadonlyMap(plugin.descriptions.slots)
@@ -3888,4 +3677,4 @@ function createWidgetSystem(options) {
3888
3677
  return Object.freeze(system);
3889
3678
  }
3890
3679
  //#endregion
3891
- export { EMPTY_DIAGNOSTICS, WidgetSystemRuntimeDisposedError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, normalizeSeparatedWidgetSource, separateWidgetSource };
3680
+ export { EMPTY_DIAGNOSTICS, WIDGET_CONFIG_JSON_SCHEMA_DIALECT, WidgetSystemConfigurationError, WidgetSystemRuntimeDisposedError, createWidgetDocument, createWidgetPlugin, createWidgetSystem, createWidgetValueContract, normalizeSeparatedWidgetSource, separateWidgetSource };