@histoire/protocol 0.0.0-stage → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bridge/catalog.d.ts +12 -0
  3. package/dist/bridge/catalog.d.ts.map +1 -0
  4. package/dist/bridge/envelope.d.ts +18 -0
  5. package/dist/bridge/envelope.d.ts.map +1 -0
  6. package/dist/bridge/events.d.ts +9 -0
  7. package/dist/bridge/events.d.ts.map +1 -0
  8. package/dist/bridge/handshake.d.ts +42 -0
  9. package/dist/bridge/handshake.d.ts.map +1 -0
  10. package/dist/bridge/limits.d.ts +41 -0
  11. package/dist/bridge/limits.d.ts.map +1 -0
  12. package/dist/bridge/payload.d.ts +9 -0
  13. package/dist/bridge/payload.d.ts.map +1 -0
  14. package/dist/bridge/project-test-collection.d.ts +5 -0
  15. package/dist/bridge/project-test-collection.d.ts.map +1 -0
  16. package/dist/bridge/results.d.ts +12 -0
  17. package/dist/bridge/results.d.ts.map +1 -0
  18. package/dist/bridge/size.d.ts +23 -0
  19. package/dist/bridge/size.d.ts.map +1 -0
  20. package/dist/bridge/snapshot.d.ts +27 -0
  21. package/dist/bridge/snapshot.d.ts.map +1 -0
  22. package/dist/bridge/source-descriptor.d.ts +5 -0
  23. package/dist/bridge/source-descriptor.d.ts.map +1 -0
  24. package/dist/bridge/string-size.d.ts +12 -0
  25. package/dist/bridge/string-size.d.ts.map +1 -0
  26. package/dist/bridge/test-execution.d.ts +4 -0
  27. package/dist/bridge/test-execution.d.ts.map +1 -0
  28. package/dist/bridge/types.d.ts +83 -0
  29. package/dist/bridge/types.d.ts.map +1 -0
  30. package/dist/bridge/validation.d.ts +14 -0
  31. package/dist/bridge/validation.d.ts.map +1 -0
  32. package/dist/channels.d.ts +42 -0
  33. package/dist/channels.d.ts.map +1 -0
  34. package/dist/geometry.d.ts +9 -0
  35. package/dist/geometry.d.ts.map +1 -0
  36. package/dist/helpers/matrix-numeric.d.ts +18 -0
  37. package/dist/helpers/matrix-numeric.d.ts.map +1 -0
  38. package/dist/helpers/matrix.d.ts +22 -0
  39. package/dist/helpers/matrix.d.ts.map +1 -0
  40. package/dist/helpers/meta.d.ts +26 -0
  41. package/dist/helpers/meta.d.ts.map +1 -0
  42. package/dist/helpers/story-route.d.ts +25 -0
  43. package/dist/helpers/story-route.d.ts.map +1 -0
  44. package/dist/index.d.ts +50 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +3288 -0
  47. package/dist/inspection/capabilities.d.ts +24 -0
  48. package/dist/inspection/capabilities.d.ts.map +1 -0
  49. package/dist/inspection/debug-buffer.d.ts +21 -0
  50. package/dist/inspection/debug-buffer.d.ts.map +1 -0
  51. package/dist/inspection/extensions.d.ts +5 -0
  52. package/dist/inspection/extensions.d.ts.map +1 -0
  53. package/dist/inspection/rows.d.ts +5 -0
  54. package/dist/inspection/rows.d.ts.map +1 -0
  55. package/dist/inspection/validation.d.ts +23 -0
  56. package/dist/inspection/validation.d.ts.map +1 -0
  57. package/dist/plugin-channels.d.ts +84 -0
  58. package/dist/plugin-channels.d.ts.map +1 -0
  59. package/dist/serialization/controls-revision.d.ts +12 -0
  60. package/dist/serialization/controls-revision.d.ts.map +1 -0
  61. package/dist/serialization/state.d.ts +12 -0
  62. package/dist/serialization/state.d.ts.map +1 -0
  63. package/dist/serialization/test-errors.d.ts +8 -0
  64. package/dist/serialization/test-errors.d.ts.map +1 -0
  65. package/dist/theme/color.d.ts +17 -0
  66. package/dist/theme/color.d.ts.map +1 -0
  67. package/dist/theme/semantic.d.ts +32 -0
  68. package/dist/theme/semantic.d.ts.map +1 -0
  69. package/dist/types/catalog.d.ts +161 -0
  70. package/dist/types/catalog.d.ts.map +1 -0
  71. package/dist/types/common.d.ts +59 -0
  72. package/dist/types/common.d.ts.map +1 -0
  73. package/dist/types/content.d.ts +34 -0
  74. package/dist/types/content.d.ts.map +1 -0
  75. package/dist/types/controls.d.ts +132 -0
  76. package/dist/types/controls.d.ts.map +1 -0
  77. package/dist/types/debug.d.ts +64 -0
  78. package/dist/types/debug.d.ts.map +1 -0
  79. package/dist/types/embed-presentation.d.ts +23 -0
  80. package/dist/types/embed-presentation.d.ts.map +1 -0
  81. package/dist/types/error.d.ts +23 -0
  82. package/dist/types/error.d.ts.map +1 -0
  83. package/dist/types/inspection-accessibility.d.ts +43 -0
  84. package/dist/types/inspection-accessibility.d.ts.map +1 -0
  85. package/dist/types/inspection-components.d.ts +69 -0
  86. package/dist/types/inspection-components.d.ts.map +1 -0
  87. package/dist/types/inspection.d.ts +221 -0
  88. package/dist/types/inspection.d.ts.map +1 -0
  89. package/dist/types/isolated-inspection.d.ts +69 -0
  90. package/dist/types/isolated-inspection.d.ts.map +1 -0
  91. package/dist/types/preview-message.d.ts +179 -0
  92. package/dist/types/preview-message.d.ts.map +1 -0
  93. package/dist/types/readonly.d.ts +5 -0
  94. package/dist/types/readonly.d.ts.map +1 -0
  95. package/dist/types/settings.d.ts +31 -0
  96. package/dist/types/settings.d.ts.map +1 -0
  97. package/dist/types/snapshot.d.ts +94 -0
  98. package/dist/types/snapshot.d.ts.map +1 -0
  99. package/dist/types/source-descriptor.d.ts +72 -0
  100. package/dist/types/source-descriptor.d.ts.map +1 -0
  101. package/dist/types/source-search.d.ts +20 -0
  102. package/dist/types/source-search.d.ts.map +1 -0
  103. package/dist/types/test.d.ts +208 -0
  104. package/dist/types/test.d.ts.map +1 -0
  105. package/dist/url/embed-origins.d.ts +16 -0
  106. package/dist/url/embed-origins.d.ts.map +1 -0
  107. package/dist/url/embed.d.ts +19 -0
  108. package/dist/url/embed.d.ts.map +1 -0
  109. package/dist/url/preview.d.ts +14 -0
  110. package/dist/url/preview.d.ts.map +1 -0
  111. package/package.json +32 -3
  112. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,3288 @@
1
+ // src/types/error.ts
2
+ /** Stable portable failure codes shared by SDK and Node adapters. */
3
+ var HISTOIRE_ERROR_CODES = [
4
+ "INVALID_ARGUMENT",
5
+ "INVALID_SELECTOR",
6
+ "RESULT_TOO_LARGE",
7
+ "BROWSER_REQUIRED",
8
+ "NOT_CONNECTED",
9
+ "DISPOSED",
10
+ "CAPABILITY_UNAVAILABLE",
11
+ "PROTOCOL_MISMATCH",
12
+ "ORIGIN_DENIED",
13
+ "BOOK_UNAVAILABLE",
14
+ "STORY_NOT_FOUND",
15
+ "STORY_AMBIGUOUS",
16
+ "VARIANT_NOT_FOUND",
17
+ "SELECTION_REQUIRED",
18
+ "PREVIEW_NOT_READY",
19
+ "RUNTIME_IN_USE",
20
+ "STALE_REVISION",
21
+ "RUNTIME_CHANGED",
22
+ "DOCS_NOT_FOUND",
23
+ "SOURCE_UNAVAILABLE",
24
+ "COLLECTION_FAILED",
25
+ "QUEUE_FULL",
26
+ "RATE_LIMITED",
27
+ "DEPENDENCY_MISSING",
28
+ "BROWSER_UNAVAILABLE",
29
+ "CANCELLED",
30
+ "TIMEOUT",
31
+ "INTERNAL_ERROR"
32
+ ];
33
+ /** Shared typed exception reconstructed at client boundary. */
34
+ var HistoireSdkError = class extends Error {
35
+ /** Stable failure code. */
36
+ code;
37
+ /** Optional bounded projected diagnostic data. */
38
+ details;
39
+ /** Constructs failure without importing platform/framework modules. */
40
+ constructor(code, message, details) {
41
+ super(message);
42
+ this.name = "HistoireSdkError";
43
+ this.code = code;
44
+ this.details = details;
45
+ }
46
+ };
47
+ // src/bridge/limits.ts
48
+ /** Hard traversal bounds for all untrusted payloads. */
49
+ var HISTOIRE_WIRE_LIMITS = {
50
+ metadata: 65536,
51
+ request: 1048576,
52
+ event: 65536,
53
+ catalog: 8388608,
54
+ state: 1048576,
55
+ error: 16384,
56
+ depth: 128,
57
+ containers: 1e5,
58
+ edges: 2e5
59
+ };
60
+ /** Per-test bound of plugin data attached to a test result (`HistoireTestCaseResult.data`). */
61
+ var HISTOIRE_TEST_DATA_LIMIT = 49152;
62
+ /** Specific limits override generic caps; catalog is never constrained to 1 MiB. */
63
+ function getHistoireWireLimit(policy) {
64
+ if (policy.kind === "error") return HISTOIRE_WIRE_LIMITS.error;
65
+ if (policy.kind === "metadata") return HISTOIRE_WIRE_LIMITS.metadata;
66
+ if (policy.kind === "descriptor" || policy.name === "view.sync" || policy.kind === "response" && [
67
+ "catalog.list",
68
+ "catalog.getStory",
69
+ "catalog.search"
70
+ ].includes(policy.name) || policy.kind === "event" && policy.name === "catalog.changed") return HISTOIRE_WIRE_LIMITS.catalog;
71
+ if ([
72
+ "channel.message",
73
+ "channel.post",
74
+ "plugin.message",
75
+ "plugin.post"
76
+ ].includes(policy.name)) return HISTOIRE_WIRE_LIMITS.event;
77
+ if (policy.kind === "event" && ["state.changed", "layout.changed"].includes(policy.name)) return HISTOIRE_WIRE_LIMITS.state;
78
+ return policy.kind === "event" ? HISTOIRE_WIRE_LIMITS.event : HISTOIRE_WIRE_LIMITS.request;
79
+ }
80
+ /**
81
+ * Bounds of story/variant `meta` published in the catalog. Per-meta bounds stop the copy early;
82
+ * catalog-wide bounds keep many valid metas from pushing the whole catalog past
83
+ * `HISTOIRE_WIRE_LIMITS.catalog` / `containers` / `edges`.
84
+ */
85
+ var HISTOIRE_META_LIMITS = {
86
+ /** JSON bytes of one `meta`. */
87
+ bytes: HISTOIRE_WIRE_LIMITS.metadata,
88
+ /** Nesting depth inside one `meta` (root is 0); deeper values are dropped. */
89
+ depth: 32,
90
+ /** JSON values (containers and leaves, each shared reference counted again) of one `meta`. */
91
+ nodes: 8192,
92
+ /** JSON bytes of all `meta` in one catalog. */
93
+ catalogBytes: 2097152,
94
+ /** JSON values of all `meta` in one catalog. */
95
+ catalogNodes: 4e4
96
+ };
97
+ // src/bridge/string-size.ts
98
+ /**
99
+ * Counts UTF-8 bytes of one string; JSON mode adds quotes and escapes, including
100
+ * well-formed `\uXXXX` escapes for lone surrogates.
101
+ * Stops as soon as the running count exceeds `limit`, so callers can reject oversized
102
+ * strings without scanning them fully. Any returned value above `limit` means "over budget".
103
+ * @param value String to count.
104
+ * @param json Whether JSON quoting/escaping applies.
105
+ * @param limit Remaining byte budget.
106
+ * @returns Exact byte count, or a partial count already greater than `limit`.
107
+ */
108
+ function countWireString(value, json, limit) {
109
+ let bytes = json ? 2 : 0;
110
+ const length = value.length;
111
+ for (let index = 0; index < length && bytes <= limit; index++) {
112
+ const code = value.charCodeAt(index);
113
+ if (code < 128) {
114
+ if (!json || code >= 32 && code !== 34 && code !== 92) bytes += 1;
115
+ else bytes += code === 34 || code === 92 || code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
116
+ } else if (code < 2048) bytes += 2;
117
+ else if (code >= 55296 && code <= 56319 && index + 1 < length && isLowSurrogate(value.charCodeAt(index + 1))) {
118
+ bytes += 4;
119
+ index++;
120
+ } else bytes += json && code >= 55296 && code <= 57343 ? 6 : 3;
121
+ }
122
+ return bytes;
123
+ }
124
+ /** Whether a UTF-16 code unit is a trailing surrogate. */
125
+ function isLowSurrogate(code) {
126
+ return code >= 56320 && code <= 57343;
127
+ }
128
+ // src/bridge/size.ts
129
+ /** Depth marker for a frame that releases its JSON ancestor after all children. */
130
+ var EXIT = -1;
131
+ /** Throws a typed failure without including untrusted oversized data. */
132
+ function fail(code, message) {
133
+ throw new HistoireSdkError(code, message);
134
+ }
135
+ /** Keys that could mutate prototypes when a receiver assigns them. */
136
+ function isPrototypeKey(key) {
137
+ return key === "__proto__" || key === "prototype" || key === "constructor";
138
+ }
139
+ /** Reads an own data field without ever evaluating accessors or toJSON. */
140
+ function readField(value, key) {
141
+ if (isPrototypeKey(key)) fail("INVALID_ARGUMENT", "Prototype-mutating keys are forbidden");
142
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
143
+ if (!descriptor || !("value" in descriptor)) fail("INVALID_ARGUMENT", "Accessors are forbidden in wire values");
144
+ return descriptor.value;
145
+ }
146
+ /** Exact `JSON.stringify(value).length` for a finite number, without allocating for safe integers. */
147
+ function jsonNumberLength(value) {
148
+ if (!Number.isSafeInteger(value)) return String(value).length;
149
+ let length = value < 0 ? 2 : 1;
150
+ for (let rest = Math.abs(value); rest >= 10; rest = Math.floor(rest / 10)) length++;
151
+ return length;
152
+ }
153
+ /** Rejects a negative or non-integer budget. */
154
+ function checkBound(bound) {
155
+ if (!Number.isSafeInteger(bound) || bound < 0) fail("INVALID_ARGUMENT", "Invalid wire budget");
156
+ }
157
+ /**
158
+ * Counts and validates one bounded wire value, stopping before expensive allocation.
159
+ * Traversal is iterative over two parallel stacks (value, depth) to avoid per-node frame
160
+ * objects; an `EXIT` depth marks where a JSON container leaves the ancestry.
161
+ */
162
+ function measureWireValue(value, options = {}) {
163
+ const json = options.mode !== "state";
164
+ const maxBytes = options.maxBytes ?? HISTOIRE_WIRE_LIMITS.request;
165
+ const maxDepth = options.maxDepth ?? HISTOIRE_WIRE_LIMITS.depth;
166
+ const maxContainers = options.maxContainers ?? HISTOIRE_WIRE_LIMITS.containers;
167
+ const maxEdges = options.maxEdges ?? HISTOIRE_WIRE_LIMITS.edges;
168
+ checkBound(maxBytes);
169
+ checkBound(maxDepth);
170
+ checkBound(maxContainers);
171
+ checkBound(maxEdges);
172
+ let bytes = 0;
173
+ let containers = 0;
174
+ let edges = 0;
175
+ const seen = /* @__PURE__ */ new Set();
176
+ const values = [value];
177
+ const depths = [0];
178
+ const fieldValues = [];
179
+ const fieldEnumerable = [];
180
+ /** Every increment checks budget before next traversal/allocation. */
181
+ const charge = (amount) => {
182
+ bytes += amount;
183
+ if (bytes > maxBytes) fail("RESULT_TOO_LARGE", "Wire byte limit exceeded");
184
+ };
185
+ /** Sparse slots count as edges even though no property descriptor exists. */
186
+ const chargeEdges = (amount) => {
187
+ edges += amount;
188
+ if (edges > maxEdges) fail("RESULT_TOO_LARGE", "Wire edge limit exceeded");
189
+ if (!json) charge(amount * 8);
190
+ };
191
+ /** Charges one string; counting stops once it cannot fit the remaining budget. */
192
+ const chargeString = (text, quoted) => {
193
+ charge(countWireString(text, quoted, maxBytes - bytes));
194
+ };
195
+ while (values.length) {
196
+ const current = values.pop();
197
+ const depth = depths.pop();
198
+ if (depth === EXIT) {
199
+ seen.delete(current);
200
+ continue;
201
+ }
202
+ if (depth > maxDepth) fail("RESULT_TOO_LARGE", "Wire depth limit exceeded");
203
+ if (typeof current === "string") {
204
+ chargeString(current, json);
205
+ continue;
206
+ }
207
+ if (current === null) {
208
+ charge(json ? 4 : 1);
209
+ continue;
210
+ }
211
+ if (typeof current === "boolean") {
212
+ charge(json ? current ? 4 : 5 : 1);
213
+ continue;
214
+ }
215
+ if (typeof current === "number") {
216
+ if (!Number.isFinite(current)) fail("INVALID_ARGUMENT", "Non-finite wire number");
217
+ charge(json ? jsonNumberLength(current) : 8);
218
+ continue;
219
+ }
220
+ if (current === void 0 && !json) {
221
+ charge(1);
222
+ continue;
223
+ }
224
+ if (typeof current === "bigint" && !json) {
225
+ charge(8);
226
+ const remaining = maxBytes - bytes;
227
+ const magnitude = current < 0n ? -current : current;
228
+ if (magnitude >> BigInt(remaining) * 8n !== 0n) fail("RESULT_TOO_LARGE", "Wire BigInt limit exceeded");
229
+ charge(magnitude === 0n ? 0 : Math.ceil(magnitude.toString(16).length / 2));
230
+ continue;
231
+ }
232
+ if (typeof current !== "object" || current === null) fail("INVALID_ARGUMENT", "Unsupported wire value");
233
+ const array = Array.isArray(current);
234
+ const prototype = Object.getPrototypeOf(current);
235
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) fail("INVALID_ARGUMENT", "Wire values must be plain containers");
236
+ if (seen.has(current)) {
237
+ if (json) fail("INVALID_ARGUMENT", "Cycles are forbidden in JSON DTOs");
238
+ continue;
239
+ }
240
+ if (++containers > maxContainers) fail("RESULT_TOO_LARGE", "Wire container limit exceeded");
241
+ seen.add(current);
242
+ if (array && current.length > maxEdges - edges) fail("RESULT_TOO_LARGE", "Wire edge limit exceeded");
243
+ const keys = Object.getOwnPropertyNames(current);
244
+ const names = keys.length;
245
+ if (names - (array ? 1 : 0) > maxEdges - edges) fail("RESULT_TOO_LARGE", "Wire edge limit exceeded");
246
+ let indexCount = 0;
247
+ for (let position = 0; position < names; position++) {
248
+ const key = keys[position];
249
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
250
+ if (!("value" in descriptor)) fail("INVALID_ARGUMENT", "Accessors are forbidden in wire values");
251
+ if (isPrototypeKey(key) || key === "toJSON" && typeof descriptor.value === "function") fail("INVALID_ARGUMENT", "Forbidden wire serialization key");
252
+ if (array && key === "length") indexCount = position;
253
+ fieldValues[position] = descriptor.value;
254
+ fieldEnumerable[position] = descriptor.enumerable;
255
+ }
256
+ if (json) {
257
+ values.push(current);
258
+ depths.push(EXIT);
259
+ charge(2);
260
+ } else charge(16);
261
+ const childDepth = depth + 1;
262
+ if (array) {
263
+ chargeEdges(current.length);
264
+ if (json && current.length) charge(current.length - 1);
265
+ if (json && indexCount < current.length) fail("INVALID_ARGUMENT", "Sparse arrays are forbidden in JSON DTOs");
266
+ for (let position = indexCount - 1; position >= 0; position--) {
267
+ values.push(fieldValues[position]);
268
+ depths.push(childDepth);
269
+ }
270
+ for (let position = indexCount + 1; position < names; position++) {
271
+ if (!fieldEnumerable[position]) continue;
272
+ if (json) fail("INVALID_ARGUMENT", "Extra array fields are forbidden in JSON DTOs");
273
+ chargeEdges(1);
274
+ chargeString(keys[position], false);
275
+ values.push(fieldValues[position]);
276
+ depths.push(childDepth);
277
+ }
278
+ } else {
279
+ let first = true;
280
+ for (let position = 0; position < names; position++) {
281
+ if (!fieldEnumerable[position]) continue;
282
+ chargeEdges(1);
283
+ if (json) {
284
+ charge(first ? 1 : 2);
285
+ first = false;
286
+ }
287
+ chargeString(keys[position], json);
288
+ values.push(fieldValues[position]);
289
+ depths.push(childDepth);
290
+ }
291
+ }
292
+ if (Object.getOwnPropertySymbols(current).length) fail("INVALID_ARGUMENT", "Symbol keys are forbidden in wire values");
293
+ }
294
+ return bytes;
295
+ }
296
+ /** Applies registry precedence; view.sync independently validates state/catalog fields. */
297
+ function validateWireValue(value, policy) {
298
+ const bytes = measureWireValue(value, {
299
+ mode: (policy.kind === "request" || policy.kind === "response" || policy.kind === "event") && (policy.name === "view.sync" || policy.name === "state.patch" || policy.name === "state.get" || policy.name === "state.reset" || policy.name === "state.changed") ? "state" : "json",
300
+ maxBytes: getHistoireWireLimit(policy)
301
+ });
302
+ if (policy.name === "view.sync" && value && typeof value === "object") {
303
+ const snapshot = value;
304
+ if (Object.hasOwn(snapshot, "catalog")) measureWireValue(readField(snapshot, "catalog"), { maxBytes: HISTOIRE_WIRE_LIMITS.catalog });
305
+ if (Object.hasOwn(snapshot, "state")) measureWireValue(readField(snapshot, "state"), {
306
+ mode: "state",
307
+ maxBytes: HISTOIRE_WIRE_LIMITS.state
308
+ });
309
+ }
310
+ return bytes;
311
+ }
312
+ // src/bridge/validation.ts
313
+ /** Throws typed validation failure without retaining untrusted payload. */
314
+ function invalid$1(message) {
315
+ throw new HistoireSdkError("INVALID_ARGUMENT", message);
316
+ }
317
+ /** Requires plain data record, rejecting accessors before any field reads. */
318
+ function wireRecord(value) {
319
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid$1("Expected wire object");
320
+ const prototype = Object.getPrototypeOf(value);
321
+ if (prototype !== null && prototype !== Object.prototype) return invalid$1("Expected plain wire object");
322
+ for (const key of Reflect.ownKeys(value)) {
323
+ if (typeof key !== "string" || [
324
+ "__proto__",
325
+ "constructor",
326
+ "prototype"
327
+ ].includes(key)) invalid$1("Forbidden wire key");
328
+ if (!("value" in Object.getOwnPropertyDescriptor(value, key))) invalid$1("Wire accessors are forbidden");
329
+ }
330
+ return value;
331
+ }
332
+ /** Nonempty bounded opaque identity, preserving exact contents. */
333
+ function wireId(value) {
334
+ return typeof value === "string" && value.length > 0 && value.length <= 4096;
335
+ }
336
+ /** Structured target input; no concatenated identity parsing. */
337
+ function validateHistoireTarget(value, optionalVariant = false) {
338
+ const input = wireRecord(value);
339
+ if (!wireId(input.storyId) || !(input.variantId === null || wireId(input.variantId) || optionalVariant && input.variantId === void 0)) invalid$1("Invalid story/variant target");
340
+ }
341
+ /** Exact additional HTTP(S) origin, rejecting paths, wildcards and opaque authority. */
342
+ function validateEmbedOrigin(value) {
343
+ if (typeof value !== "string") return invalid$1("Expected HTTP(S) origin");
344
+ let url;
345
+ try {
346
+ url = new URL(value);
347
+ } catch {
348
+ return invalid$1("Invalid HTTP(S) origin");
349
+ }
350
+ if (!["http:", "https:"].includes(url.protocol) || url.origin === "null" || url.username || url.password || url.pathname !== "/" || url.search || url.hash || value.includes("*") || value !== url.origin) invalid$1("Expected exact scheme/host/port origin");
351
+ return url.origin;
352
+ }
353
+ /** Validates host-owned settings before forwarding to any runtime. */
354
+ function validateSettingsPatch(value) {
355
+ measureWireValue(value);
356
+ const input = wireRecord(value);
357
+ const allowed = [
358
+ "responsiveWidth",
359
+ "responsiveHeight",
360
+ "rotate",
361
+ "backgroundColor",
362
+ "checkerboard",
363
+ "checkerboardTheme",
364
+ "textDirection",
365
+ "colorScheme",
366
+ "globals"
367
+ ];
368
+ if (Object.keys(input).some((key) => !allowed.includes(key))) invalid$1("Unknown preview setting");
369
+ for (const key of ["responsiveWidth", "responsiveHeight"]) {
370
+ const item = input[key];
371
+ if (item !== void 0 && !(key === "responsiveHeight" && item === null) && !(typeof item === "number" && Number.isFinite(item) && item > 0)) invalid$1("Invalid viewport size");
372
+ }
373
+ for (const key of ["rotate", "checkerboard"]) if (input[key] !== void 0 && typeof input[key] !== "boolean") invalid$1("Expected boolean setting");
374
+ if (input.backgroundColor !== void 0 && typeof input.backgroundColor !== "string") invalid$1("Expected background string");
375
+ if (input.checkerboardTheme !== void 0 && !["light", "dark"].includes(input.checkerboardTheme)) invalid$1("Invalid checkerboard theme");
376
+ if (input.textDirection !== void 0 && !["ltr", "rtl"].includes(input.textDirection)) invalid$1("Invalid text direction");
377
+ if (input.colorScheme !== void 0 && ![
378
+ "light",
379
+ "dark",
380
+ "auto"
381
+ ].includes(input.colorScheme)) invalid$1("Invalid color scheme");
382
+ if (input.globals !== void 0) {
383
+ const globals = wireRecord(input.globals);
384
+ if (Object.keys(globals).length > 32) invalid$1("Too many globals");
385
+ for (const [key, item] of Object.entries(globals)) {
386
+ if (!/^[A-Z][\w-]{0,63}$/i.test(key)) invalid$1("Invalid global key");
387
+ if (!(item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item) || typeof item === "string")) invalid$1("Invalid global value");
388
+ if (typeof item === "string" && measureWireValue(item, {
389
+ mode: "state",
390
+ maxBytes: 1024
391
+ }) > 1024) invalid$1("Global string too large");
392
+ }
393
+ }
394
+ return input;
395
+ }
396
+ // src/channels.ts
397
+ /** Validate and copy opt-in names; duplicate names confer no extra authority. */
398
+ function validateHostChannelNames(value) {
399
+ if (!Array.isArray(value) || value.length > 100 || value.some((name) => typeof name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(name))) invalid$1("Invalid host channel names");
400
+ return [...new Set(value)];
401
+ }
402
+ /** One canonical JSON traversal also limits UTF-8 wire bytes and rejects accessors. */
403
+ function validateHostChannelPayload(value, attributed = false) {
404
+ measureWireValue(value, { maxBytes: 65536 });
405
+ const input = wireRecord(value);
406
+ const fields = attributed ? [
407
+ "name",
408
+ "type",
409
+ "data",
410
+ "runtimeId",
411
+ "target"
412
+ ] : [
413
+ "name",
414
+ "type",
415
+ "data"
416
+ ];
417
+ if (Object.keys(input).some((key) => !fields.includes(key)) || !wireId(input.type) || !Object.hasOwn(input, "data")) invalid$1("Invalid host channel payload");
418
+ validateHostChannelNames([input.name]);
419
+ if (attributed) {
420
+ if (!wireId(input.runtimeId)) invalid$1("Invalid host channel runtime");
421
+ validateHistoireTarget(input.target);
422
+ if (input.target.variantId === null) invalid$1("Host channel needs a variant");
423
+ }
424
+ return input;
425
+ }
426
+ /** Bounded sliding window shared by each owner/direction; no timers or replay queue. */
427
+ function createHostChannelRateLimiter(now = Date.now) {
428
+ const accepted = [];
429
+ let dropped = 0;
430
+ return {
431
+ /** Count saturates, so hostile traffic cannot overflow portable integers. */
432
+ get droppedCount() {
433
+ return dropped;
434
+ },
435
+ /** Record local schema/callback failures as well as rate overflow. */
436
+ drop() {
437
+ dropped = Math.min(Number.MAX_SAFE_INTEGER, dropped + 1);
438
+ },
439
+ /** Admit at most 50 messages in any elapsed second across all names. */
440
+ accept() {
441
+ const time = now();
442
+ while (accepted.length && accepted[0] <= time - 1e3) accepted.shift();
443
+ if (accepted.length === 50) {
444
+ this.drop();
445
+ return false;
446
+ }
447
+ accepted.push(time);
448
+ return true;
449
+ },
450
+ /** A replacement document never inherits pending messages or old rate tokens. */
451
+ reset() {
452
+ accepted.length = 0;
453
+ dropped = 0;
454
+ }
455
+ };
456
+ }
457
+ // src/helpers/matrix-numeric.ts
458
+ /** Built-in samples for open numeric props; these are not complete prop domains. */
459
+ var HISTOIRE_MATRIX_NUMERIC_VALUES = Object.freeze([
460
+ 0,
461
+ 1,
462
+ 2,
463
+ 5,
464
+ 10
465
+ ]);
466
+ /** Validate a complete numeric list without silently dropping invalid members. */
467
+ function getHistoireNumericMatrixValues(input) {
468
+ if (!Array.isArray(input) || input.length > 64) return;
469
+ const items = Array.from(input);
470
+ if (items.some((value) => typeof value !== "number" || !Number.isFinite(value))) return;
471
+ const values = [...new Set(items.map((value) => value === 0 ? 0 : value))];
472
+ return values.length >= 2 ? values : void 0;
473
+ }
474
+ /** Exact integer coefficient and decimal scale for a finite number's canonical text. */
475
+ function decimal(value) {
476
+ const [mantissa, exponent = "0"] = String(value).toLowerCase().split("e");
477
+ const fraction = mantissa.split(".")[1]?.length ?? 0;
478
+ return {
479
+ coefficient: BigInt(mantissa.replace(".", "")),
480
+ scale: fraction - Number(exponent)
481
+ };
482
+ }
483
+ /** Expand decimal ranges exactly before converting each bounded result to Number. */
484
+ function getHistoireMatrixRangeValues(input) {
485
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
486
+ const { min, max, step } = input;
487
+ if ([
488
+ min,
489
+ max,
490
+ step
491
+ ].some((value) => typeof value !== "number" || !Number.isFinite(value)) || min > max || step <= 0) return;
492
+ const decimals = [
493
+ min,
494
+ max,
495
+ step
496
+ ].map(decimal);
497
+ const scale = Math.max(...decimals.map((value) => value.scale));
498
+ const [start, end, interval] = decimals.map((value) => value.coefficient * 10n ** BigInt(scale - value.scale));
499
+ const count = (end - start) / interval + 1n;
500
+ if (count > 64n) return;
501
+ const values = Array.from({ length: Number(count) }, (_, index) => Number(`${start + BigInt(index) * interval}e${-scale}`));
502
+ return [...new Set(values.map((value) => value === 0 ? 0 : value))];
503
+ }
504
+ /** Infer range inputs only if exact decimal expansion reproduces the entire domain. */
505
+ function getHistoireMatrixRange(input) {
506
+ if (!getHistoireNumericMatrixValues(input)) return;
507
+ const decimals = input.slice(0, 2).map(decimal);
508
+ const scale = Math.max(...decimals.map((value) => value.scale));
509
+ const [first, second] = decimals.map((value) => value.coefficient * 10n ** BigInt(scale - value.scale));
510
+ const range = {
511
+ min: input[0],
512
+ max: input[input.length - 1],
513
+ step: Number(`${second - first}e${-scale}`)
514
+ };
515
+ const values = getHistoireMatrixRangeValues(range);
516
+ return values?.length === input.length && values.every((value, index) => value === input[index]) ? range : void 0;
517
+ }
518
+ // src/helpers/matrix.ts
519
+ /** Matrix names never select internal controls or prototype properties. */
520
+ function isHistoireMatrixPropName(name) {
521
+ return Boolean(name) && !name.startsWith("_h") && ![
522
+ "__proto__",
523
+ "prototype",
524
+ "constructor"
525
+ ].includes(name);
526
+ }
527
+ /** Normalize bounded finite scalars without evaluating validators or source code. */
528
+ function getHistoireMatrixValues(value) {
529
+ if (!Array.isArray(value)) return;
530
+ const values = value.filter((item) => item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)).map((item) => item === 0 ? 0 : item);
531
+ return [...new Map(values.map((item) => [JSON.stringify([typeof item, item]), item])).values()].slice(0, 64);
532
+ }
533
+ /** Automatic domains must describe their complete finite set, never a sanitized subset. */
534
+ function getHistoireFiniteMatrixValues(value) {
535
+ if (!Array.isArray(value) || value.length > 64 || value.some((item) => getHistoireMatrixValues([item])?.length !== 1)) return;
536
+ return getHistoireMatrixValues(value);
537
+ }
538
+ /** Project untrusted declaration data to immutable portable catalog metadata. */
539
+ function normalizeHistoireMatrixHint(value) {
540
+ if (!value || typeof value !== "object") return;
541
+ const input = value.axes;
542
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
543
+ const axes = Object.fromEntries(Object.entries(input).filter(([name]) => isHistoireMatrixPropName(name)).map(([name, values]) => [name, Array.isArray(values) ? getHistoireMatrixValues(values) : getHistoireMatrixRangeValues(values)]).filter(([, values]) => Array.isArray(values) && values.length).slice(0, 32));
544
+ if (!Object.keys(axes).length) return;
545
+ for (const values of Object.values(axes)) Object.freeze(values);
546
+ return Object.freeze({ axes: Object.freeze(axes) });
547
+ }
548
+ // src/url/embed-origins.ts
549
+ /** Validates and deduplicates exact origins without silently accepting a partial list. */
550
+ function validateEmbedOrigins(value) {
551
+ if (!Array.isArray(value)) invalid$1("Expected embed.allowedOrigins array");
552
+ return [...new Set(value.map(validateEmbedOrigin))];
553
+ }
554
+ /** Resolves one document's policy; invalid present override permits own origin only. */
555
+ function resolveEmbedOrigins(baked, override) {
556
+ const configured = validateEmbedOrigins(baked);
557
+ if (!override?.present) return configured;
558
+ try {
559
+ return validateEmbedOrigins(override.value);
560
+ } catch {
561
+ return [];
562
+ }
563
+ }
564
+ /** Framing directive shares exact effective list used by bridge authorization. */
565
+ function createEmbedFrameAncestors(allowedOrigins) {
566
+ return ["frame-ancestors 'self'", ...validateEmbedOrigins(allowedOrigins)].join(" ");
567
+ }
568
+ /** Replaces only framing directive while preserving independent CSP policies/directives. */
569
+ function mergeEmbedFrameAncestors(existing, allowedOrigins) {
570
+ const directive = createEmbedFrameAncestors(allowedOrigins);
571
+ const merge = (policy) => [...policy.split(";").map((part) => part.trim()).filter((part) => part && !/^frame-ancestors(?:\s|$)/i.test(part)), directive].join("; ");
572
+ return Array.isArray(existing) ? existing.map(merge) : merge(existing ?? "");
573
+ }
574
+ // src/inspection/capabilities.ts
575
+ /** Source extension names remain separate from strict legacy capabilities. */
576
+ var HISTOIRE_INSPECTION_CAPABILITIES = [
577
+ "variant",
578
+ "dom",
579
+ "components",
580
+ "componentDetails",
581
+ "accessibilityAudit",
582
+ "highlight",
583
+ "componentHighlight",
584
+ "pick",
585
+ "highlightLease",
586
+ "diagnostics"
587
+ ];
588
+ /** Explicit operation-to-capability mapping; names need not be interchangeable. */
589
+ var HISTOIRE_INSPECTION_OPERATION_CAPABILITIES = {
590
+ variant: "variant",
591
+ dom: "dom",
592
+ components: "components",
593
+ component: "componentDetails",
594
+ componentForElement: "componentDetails",
595
+ accessibility: "accessibilityAudit",
596
+ highlight: "highlight",
597
+ pick: "pick",
598
+ highlightLease: "highlightLease",
599
+ highlightClear: "highlightLease",
600
+ debug: "diagnostics"
601
+ };
602
+ /** Validate every optional capability before projecting it to callers. */
603
+ function validateInspectionCapabilities(value) {
604
+ measureWireValue(value, { maxBytes: 4096 });
605
+ const input = wireRecord(value);
606
+ for (const [key, value] of Object.entries(input)) {
607
+ if (!HISTOIRE_INSPECTION_CAPABILITIES.includes(key)) invalid$1("Unknown inspection capability");
608
+ const capability = wireRecord(value);
609
+ if (Object.keys(capability).some((key) => !["available", "reason"].includes(key)) || typeof capability.available !== "boolean" || capability.reason !== void 0 && (typeof capability.reason !== "string" || capability.reason.length > 128)) invalid$1("Invalid inspection capability");
610
+ }
611
+ return input;
612
+ }
613
+ /** Absence and explicit false always deny; descriptors are only upper bounds. */
614
+ function hasInspectionCapability(value, key) {
615
+ return value?.[key]?.available === true;
616
+ }
617
+ /** Validate source-owned exact-origin policy, independently of legacy embed keys. */
618
+ function validateInspectionPolicy(value) {
619
+ measureWireValue(value, { maxBytes: 4096 });
620
+ const policy = wireRecord(value);
621
+ if (Object.keys(policy).some((key) => key !== "allowedOrigins")) invalid$1("Unknown inspection policy");
622
+ validateEmbedOrigins(policy.allowedOrigins);
623
+ }
624
+ // src/plugin-channels.ts
625
+ /** Byte budget of one plugin message, same as named host channels. */
626
+ var HISTOIRE_PLUGIN_CHANNEL_MAX_BYTES = 65536;
627
+ /** Plugin id grammar shared with `@histoire/plugin-kit` descriptors; `builtin` is reserved. */
628
+ var HISTOIRE_PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*$/;
629
+ /** Message types under this prefix are runtime notices; plugins can neither send nor observe them. */
630
+ var HISTOIRE_PLUGIN_NOTICE_PREFIX = "histoire:";
631
+ /** Frame runtime notices: actor attached after `attach` settled, actor detached, plugin failure. */
632
+ var HISTOIRE_PLUGIN_NOTICES = [
633
+ "histoire:attached",
634
+ "histoire:detached",
635
+ "histoire:error"
636
+ ];
637
+ /** Whether `type` names a runtime notice rather than plugin data. */
638
+ function isHistoirePluginNotice(type) {
639
+ return type.startsWith(HISTOIRE_PLUGIN_NOTICE_PREFIX);
640
+ }
641
+ /** Validates a plugin id against the shared grammar. */
642
+ function isHistoirePluginId(value) {
643
+ return typeof value === "string" && value.length <= 64 && value !== "builtin" && HISTOIRE_PLUGIN_ID_PATTERN.test(value);
644
+ }
645
+ /** Notice bodies are fixed: attach/detach carry nothing, failures a phase and bounded message. */
646
+ function validateNotice(type, data) {
647
+ if (!HISTOIRE_PLUGIN_NOTICES.includes(type)) invalid$1("Unknown plugin notice");
648
+ if (type !== "histoire:error") {
649
+ if (data !== null) invalid$1("Plugin notice carries no data");
650
+ return;
651
+ }
652
+ const error = wireRecord(data);
653
+ if (Object.keys(error).some((key) => key !== "phase" && key !== "message") || typeof error.phase !== "string" || error.phase.length > 64 || typeof error.message !== "string" || error.message.length > 2e3) invalid$1("Invalid plugin failure notice");
654
+ }
655
+ /**
656
+ * Validates one plugin message in a single bounded traversal.
657
+ * @param value Untrusted payload.
658
+ * @param attributed Frame-to-host publication: requires `target` and `runtimeId`.
659
+ * @param notices Admits runtime notices; only frame-to-host traffic carries them.
660
+ */
661
+ function validatePluginChannelPayload(value, attributed = false, notices = attributed) {
662
+ measureWireValue(value, { maxBytes: HISTOIRE_PLUGIN_CHANNEL_MAX_BYTES });
663
+ const input = wireRecord(value);
664
+ const fields = attributed ? [
665
+ "pluginId",
666
+ "actorId",
667
+ "type",
668
+ "data",
669
+ "target",
670
+ "runtimeId"
671
+ ] : [
672
+ "pluginId",
673
+ "actorId",
674
+ "type",
675
+ "data"
676
+ ];
677
+ if (Object.keys(input).some((key) => !fields.includes(key)) || !Object.hasOwn(input, "data") || input.data === void 0) invalid$1("Invalid plugin channel payload");
678
+ if (!isHistoirePluginId(input.pluginId) || !wireId(input.actorId) || !wireId(input.type)) invalid$1("Invalid plugin channel identity");
679
+ if (isHistoirePluginNotice(input.type)) {
680
+ if (!notices) invalid$1("Plugin message type is reserved");
681
+ validateNotice(input.type, input.data);
682
+ }
683
+ if (attributed) {
684
+ if (!wireId(input.runtimeId)) invalid$1("Invalid plugin channel runtime");
685
+ validateHistoireTarget(input.target);
686
+ if (input.target.variantId === null) invalid$1("Plugin channel needs a variant");
687
+ }
688
+ return input;
689
+ }
690
+ /**
691
+ * Validates the descriptor inventory of installed frame plugins: unique ids, integer versions,
692
+ * nothing but `{ id, apiVersion }` (never module paths).
693
+ */
694
+ function validateFramePluginInventory(value) {
695
+ if (!Array.isArray(value) || value.length > 256) return invalid$1("Invalid frame plugin inventory");
696
+ const seen = /* @__PURE__ */ new Set();
697
+ for (const entry of value) {
698
+ const plugin = wireRecord(entry);
699
+ if (Object.keys(plugin).some((key) => key !== "id" && key !== "apiVersion") || !isHistoirePluginId(plugin.id) || seen.has(plugin.id) || !Number.isSafeInteger(plugin.apiVersion) || plugin.apiVersion < 1) invalid$1("Invalid frame plugin entry");
700
+ seen.add(plugin.id);
701
+ }
702
+ return value;
703
+ }
704
+ /**
705
+ * Rate windows per plugin and direction, reusing the host-channel limiter: one plugin saturating
706
+ * its window never charges another. Owners create one per runtime document.
707
+ * @param now Clock, injectable for tests.
708
+ */
709
+ function createPluginChannelLimiters(now = Date.now) {
710
+ const plugins = /* @__PURE__ */ new Map();
711
+ return {
712
+ /** Limiter pair of one plugin, created on first use. */
713
+ get(pluginId) {
714
+ let limiters = plugins.get(pluginId);
715
+ if (!limiters) {
716
+ limiters = {
717
+ incoming: createHostChannelRateLimiter(now),
718
+ outgoing: createHostChannelRateLimiter(now)
719
+ };
720
+ plugins.set(pluginId, limiters);
721
+ }
722
+ return limiters;
723
+ },
724
+ /** Saturated drop count of one plugin across both directions. */
725
+ droppedCount(pluginId) {
726
+ const limiters = plugins.get(pluginId);
727
+ return limiters ? Math.min(Number.MAX_SAFE_INTEGER, limiters.incoming.droppedCount + limiters.outgoing.droppedCount) : 0;
728
+ },
729
+ /** Replacement documents never inherit rate tokens or counts. */
730
+ reset() {
731
+ plugins.clear();
732
+ }
733
+ };
734
+ }
735
+ // src/bridge/source-descriptor.ts
736
+ /** Strict same-base opaque reference; URL normalization must never hide traversal. */
737
+ function validateSourceAssetReference(value) {
738
+ if (typeof value !== "string" || !value || /[\\\0?#:%]/.test(value) || value.startsWith("/") || value.split("/").some((part) => !part || part === "." || part === "..")) invalid$1("Expected relative source asset reference");
739
+ return value;
740
+ }
741
+ /** Rejects unexpected projected keys before source configuration reaches UI code. */
742
+ function keys$1(input, allowed) {
743
+ if (Object.keys(input).some((key) => !allowed.includes(key))) invalid$1("Unknown source descriptor field");
744
+ }
745
+ /** Validates optional portable config/policy/lazy assets; legacy bare descriptors remain valid. */
746
+ function validateSourceDescriptorFields(input) {
747
+ if (input.framePlugins !== void 0) validateFramePluginInventory(input.framePlugins);
748
+ if (input.embed !== void 0) {
749
+ const policy = wireRecord(input.embed);
750
+ keys$1(policy, [
751
+ "allowedOrigins",
752
+ "allowOpenInEditor",
753
+ "allowServerTests"
754
+ ]);
755
+ validateEmbedOrigins(policy.allowedOrigins);
756
+ if (typeof policy.allowOpenInEditor !== "boolean" || typeof policy.allowServerTests !== "boolean") invalid$1("Invalid embed policy");
757
+ }
758
+ if (input.assets !== void 0) {
759
+ const assets = wireRecord(input.assets);
760
+ keys$1(assets, ["search", "content"]);
761
+ validateSourceAssetReference(assets.search);
762
+ if (!Array.isArray(assets.content)) invalid$1("Invalid source content inventory");
763
+ const seen = /* @__PURE__ */ new Set();
764
+ for (const value of assets.content) {
765
+ const entry = wireRecord(value);
766
+ keys$1(entry, [
767
+ "storyId",
768
+ "docs",
769
+ "rawSource"
770
+ ]);
771
+ if (!wireId(entry.storyId) || seen.has(entry.storyId)) invalid$1("Invalid source content target");
772
+ seen.add(entry.storyId);
773
+ if (entry.docs !== void 0) validateSourceAssetReference(entry.docs);
774
+ if (entry.rawSource !== void 0) validateSourceAssetReference(entry.rawSource);
775
+ }
776
+ }
777
+ if (input.config !== void 0) {
778
+ const config = wireRecord(input.config);
779
+ keys$1(config, [
780
+ "title",
781
+ "routerMode",
782
+ "matrix",
783
+ "theme",
784
+ "responsivePresets",
785
+ "backgroundPresets",
786
+ "autoApplyContrastColor",
787
+ "storyCollectTimeout",
788
+ "runTimeout",
789
+ "testMaxWorkers",
790
+ "globals",
791
+ "textDirection"
792
+ ]);
793
+ if (config.routerMode !== void 0 && !["history", "hash"].includes(config.routerMode)) invalid$1("Invalid source router mode");
794
+ if (config.matrix !== void 0) {
795
+ const matrix = wireRecord(config.matrix);
796
+ keys$1(matrix, ["numericValues"]);
797
+ if (!getHistoireNumericMatrixValues(matrix.numericValues)) invalid$1("Invalid matrix numeric values");
798
+ }
799
+ if (config.globals !== void 0) validateSettingsPatch({ globals: config.globals });
800
+ if (config.textDirection !== void 0) validateSettingsPatch({ textDirection: config.textDirection });
801
+ if (typeof config.title !== "string" || typeof config.autoApplyContrastColor !== "boolean") invalid$1("Invalid source config");
802
+ for (const key of ["storyCollectTimeout", "runTimeout"]) if (config[key] !== void 0 && (typeof config[key] !== "number" || !Number.isFinite(config[key]) || config[key] <= 0)) invalid$1("Invalid source deadline");
803
+ if (config.testMaxWorkers !== void 0 && (!Number.isSafeInteger(config.testMaxWorkers) || config.testMaxWorkers < 1)) invalid$1("Invalid source test worker limit");
804
+ const theme = wireRecord(config.theme);
805
+ keys$1(theme, [
806
+ "defaultColorScheme",
807
+ "darkClass",
808
+ "hideColorSchemeSwitch",
809
+ "colors"
810
+ ]);
811
+ validateSettingsPatch({ colorScheme: theme.defaultColorScheme });
812
+ if (typeof theme.darkClass !== "string" || theme.hideColorSchemeSwitch !== void 0 && typeof theme.hideColorSchemeSwitch !== "boolean") invalid$1("Invalid source theme");
813
+ if (theme.colors !== void 0) {
814
+ for (const shades of Object.values(wireRecord(theme.colors))) if (Object.values(wireRecord(shades)).some((value) => typeof value !== "string")) invalid$1("Invalid source colors");
815
+ }
816
+ if (!Array.isArray(config.responsivePresets) || !Array.isArray(config.backgroundPresets)) invalid$1("Invalid source presets");
817
+ for (const value of config.responsivePresets) {
818
+ const preset = wireRecord(value);
819
+ keys$1(preset, [
820
+ "label",
821
+ "width",
822
+ "height"
823
+ ]);
824
+ if (typeof preset.label !== "string" || typeof preset.width !== "number" || !Number.isFinite(preset.width) || preset.width <= 0 || preset.height != null && (typeof preset.height !== "number" || !Number.isFinite(preset.height) || preset.height <= 0)) invalid$1("Invalid responsive preset");
825
+ }
826
+ for (const value of config.backgroundPresets) {
827
+ const preset = wireRecord(value);
828
+ keys$1(preset, [
829
+ "label",
830
+ "color",
831
+ "contrastColor"
832
+ ]);
833
+ if (["label", "color"].some((key) => typeof preset[key] !== "string") || preset.contrastColor !== void 0 && typeof preset.contrastColor !== "string") invalid$1("Invalid background preset");
834
+ }
835
+ }
836
+ }
837
+ // src/bridge/catalog.ts
838
+ /** Finite advertised operation/surface keys. */
839
+ var operations = [
840
+ "catalog",
841
+ "search",
842
+ "docs",
843
+ "rawSource",
844
+ "dynamicSource",
845
+ "state",
846
+ "customControls",
847
+ "previewTests",
848
+ "serverTests",
849
+ "openInEditor",
850
+ "hostChannels"
851
+ ];
852
+ /** Optional operation keys; absent in legacy descriptors. */
853
+ var optionalOperations = ["framePlugins"];
854
+ var surfaces = [
855
+ "explorer",
856
+ "preview",
857
+ "tree",
858
+ "search",
859
+ "toolbar",
860
+ "controls",
861
+ "docs",
862
+ "source",
863
+ "events",
864
+ "tests"
865
+ ];
866
+ /** Validates complete availability maps before framework/UI code consumes them. */
867
+ function validateHistoireCapabilities(value) {
868
+ const input = wireRecord(value);
869
+ const views = wireRecord(input.surfaces);
870
+ for (const [record, keys] of [[input, operations], [views, surfaces]]) for (const key of keys) {
871
+ const capability = wireRecord(record[key]);
872
+ if (typeof capability.available !== "boolean" || capability.reason !== void 0 && typeof capability.reason !== "string") invalid$1("Invalid capability");
873
+ if (capability.channels !== void 0) {
874
+ if (key !== "hostChannels" || record !== input) invalid$1("Channel names require hostChannels capability");
875
+ validateHostChannelNames(capability.channels);
876
+ }
877
+ }
878
+ if (input.framePlugins !== void 0) {
879
+ const capability = wireRecord(input.framePlugins);
880
+ if (Object.keys(capability).some((key) => key !== "available" && key !== "reason") || typeof capability.available !== "boolean" || capability.reason !== void 0 && typeof capability.reason !== "string") invalid$1("Invalid capability");
881
+ }
882
+ if (Object.keys(input).some((key) => key !== "surfaces" && !operations.includes(key) && !optionalOperations.includes(key)) || Object.keys(views).some((key) => !surfaces.includes(key))) invalid$1("Unknown capability");
883
+ }
884
+ /** Relative display labels cannot expose Node paths or module identifiers. */
885
+ function validateRelativeLabel(value) {
886
+ if (value !== void 0 && (typeof value !== "string" || /^(?:\/|[a-z]:[\\/]|\\\\|\0)/i.test(value))) invalid$1("Expected relative file label");
887
+ }
888
+ /** Story/variant `meta` must be a JSON object within the per-meta bounds. */
889
+ function validateMeta(value) {
890
+ if (value === void 0) return;
891
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid$1("Invalid catalog metadata");
892
+ const { bytes, depth, nodes } = HISTOIRE_META_LIMITS;
893
+ measureWireValue(value, {
894
+ mode: "json",
895
+ maxBytes: bytes,
896
+ maxDepth: depth,
897
+ maxContainers: nodes,
898
+ maxEdges: nodes
899
+ });
900
+ }
901
+ /** Validates projected story/variant metadata without importing story modules. */
902
+ function validateHistoireCatalogStory(value) {
903
+ const input = wireRecord(value);
904
+ if (!wireId(input.id) || typeof input.title !== "string" || typeof input.docsOnly !== "boolean") invalid$1("Invalid catalog story");
905
+ if (!Array.isArray(input.path) || input.path.some((part) => typeof part !== "string")) invalid$1("Invalid story path");
906
+ if (!Array.isArray(input.variants)) invalid$1("Expected variants");
907
+ for (const value of input.variants) {
908
+ const variant = wireRecord(value);
909
+ if (!wireId(variant.id) || typeof variant.title !== "string" || variant.hasTests !== void 0 && typeof variant.hasTests !== "boolean") invalid$1("Invalid catalog variant");
910
+ if (variant.source !== void 0) {
911
+ const source = wireRecord(variant.source);
912
+ if (typeof source.raw !== "boolean" || typeof source.dynamic !== "boolean") invalid$1("Invalid source availability");
913
+ }
914
+ validateMeta(variant.meta);
915
+ }
916
+ validateMeta(input.meta);
917
+ const content = wireRecord(input.content);
918
+ if (typeof content.docs !== "boolean" || typeof content.rawSource !== "boolean") invalid$1("Invalid content availability");
919
+ for (const key of [
920
+ "group",
921
+ "icon",
922
+ "iconColor",
923
+ "supportPluginId"
924
+ ]) if (input[key] !== void 0 && typeof input[key] !== "string") invalid$1("Invalid catalog metadata");
925
+ validateRelativeLabel(input.relativePath);
926
+ if (input.fileOrigin !== void 0 && ![
927
+ "project",
928
+ "generated",
929
+ "external"
930
+ ].includes(input.fileOrigin)) invalid$1("Invalid story file origin");
931
+ if (input.runtimeRevision !== void 0 && (typeof input.runtimeRevision !== "string" || !/^[a-f0-9]{64}$/.test(input.runtimeRevision))) invalid$1("Invalid story runtime revision");
932
+ if (input.layoutExplicit !== void 0 && typeof input.layoutExplicit !== "boolean") invalid$1("Invalid layout provenance");
933
+ if (input.hasCustomControls !== void 0 && typeof input.hasCustomControls !== "boolean") invalid$1("Invalid custom controls availability");
934
+ if (input.layout !== void 0) {
935
+ const layout = wireRecord(input.layout);
936
+ if (!["single", "grid"].includes(layout.type)) invalid$1("Invalid story layout");
937
+ }
938
+ if (input.matrix !== void 0) {
939
+ const axes = wireRecord(wireRecord(input.matrix).axes);
940
+ if (Object.keys(axes).length > 32) invalid$1("Invalid matrix axes");
941
+ for (const [name, values] of Object.entries(axes)) {
942
+ const finite = getHistoireMatrixValues(values);
943
+ if (!isHistoireMatrixPropName(name) || !Array.isArray(values) || !finite || !values.length || values.length > 64 || finite.length !== new Set(values).size) invalid$1("Invalid matrix values");
944
+ }
945
+ }
946
+ return input;
947
+ }
948
+ /** Validates complete catalog tree and diagnostics at shared transport boundary. */
949
+ function validateHistoireCatalog(value) {
950
+ measureWireValue(value, { maxBytes: HISTOIRE_WIRE_LIMITS.catalog });
951
+ const input = wireRecord(value);
952
+ if (!Array.isArray(input.stories) || !Array.isArray(input.tree) || !Array.isArray(input.diagnostics)) invalid$1("Invalid catalog");
953
+ for (const story of input.stories) validateHistoireCatalogStory(story);
954
+ const queue = [...input.tree];
955
+ while (queue.length) {
956
+ const node = wireRecord(queue.pop());
957
+ if (typeof node.title !== "string") invalid$1("Invalid tree title");
958
+ if (node.kind === "story") {
959
+ if (!wireId(node.storyId)) invalid$1("Invalid tree story");
960
+ } else if (node.kind === "folder" || node.kind === "group") {
961
+ if (!Array.isArray(node.children) || node.id !== void 0 && !wireId(node.id)) invalid$1("Invalid tree folder");
962
+ for (const child of node.children) queue.push(child);
963
+ } else invalid$1("Unknown catalog tree node");
964
+ }
965
+ validateHistoireDiagnostics(input.diagnostics);
966
+ return input;
967
+ }
968
+ /** Validates diagnostics independently when projected alongside catalog in view snapshot. */
969
+ function validateHistoireDiagnostics(value) {
970
+ measureWireValue(value, { maxBytes: HISTOIRE_WIRE_LIMITS.catalog });
971
+ if (!Array.isArray(value)) invalid$1("Invalid diagnostics");
972
+ for (const entry of value) {
973
+ const diagnostic = wireRecord(entry);
974
+ if (!wireId(diagnostic.code) || typeof diagnostic.message !== "string" || !["warning", "error"].includes(diagnostic.severity)) invalid$1("Invalid diagnostic");
975
+ if (diagnostic.storyId !== void 0 && !wireId(diagnostic.storyId)) invalid$1("Invalid diagnostic target");
976
+ validateRelativeLabel(diagnostic.relativePath);
977
+ }
978
+ }
979
+ /** Handshake descriptor validation is data-only and shares catalog limits. */
980
+ function validateHistoireSourceDescriptor(value) {
981
+ measureWireValue(value, { maxBytes: HISTOIRE_WIRE_LIMITS.catalog });
982
+ const input = wireRecord(value);
983
+ if (input.descriptorVersion !== 1 || input.protocolVersion !== 1 || !wireId(input.sourceId) || !wireId(input.epoch) || !wireId(input.revision) || !["dev", "static"].includes(input.mode)) invalid$1("Invalid source descriptor");
984
+ validateHistoireCapabilities(input.capabilities);
985
+ if (input.inspection !== void 0) validateInspectionCapabilities(input.inspection);
986
+ if (input.inspectionPolicy !== void 0) validateInspectionPolicy(input.inspectionPolicy);
987
+ validateHistoireCatalog(input.catalog);
988
+ validateSourceDescriptorFields(input);
989
+ return input;
990
+ }
991
+ // src/inspection/extensions.ts
992
+ /** Strict extension records prevent silently exposing new fields. */
993
+ function record(value, fields) {
994
+ const input = wireRecord(value);
995
+ if (Object.keys(input).some((key) => !fields.includes(key))) invalid$1("Unknown inspection extension field");
996
+ return input;
997
+ }
998
+ /** Counts remain exact finite non-negative integers. */
999
+ function count(value) {
1000
+ if (!Number.isSafeInteger(value) || value < 0) invalid$1("Invalid inspection count");
1001
+ }
1002
+ /** Validate verified relative source metadata without granting editor access. */
1003
+ function source(value) {
1004
+ const input = record(value, [
1005
+ "relativePath",
1006
+ "line",
1007
+ "column"
1008
+ ]);
1009
+ if (typeof input.relativePath !== "string" || !input.relativePath || /[\\\0:?#%]/.test(input.relativePath) || input.relativePath.startsWith("/") || input.relativePath.split("/").some((part) => !part || part === "." || part === "..")) invalid$1("Invalid inspection source");
1010
+ for (const key of ["line", "column"]) if (input[key] !== void 0 && (!Number.isSafeInteger(input[key]) || input[key] < 1)) invalid$1("Invalid source position");
1011
+ }
1012
+ /** Instance identity is opaque and scoped to containing result owner. */
1013
+ function node(value) {
1014
+ const input = record(value, [
1015
+ "id",
1016
+ "parentId",
1017
+ "name",
1018
+ "framework",
1019
+ "source"
1020
+ ]);
1021
+ if (!wireId(input.id) || !(input.parentId === null || wireId(input.parentId)) || typeof input.name !== "string" || typeof input.framework !== "string") invalid$1("Invalid component node");
1022
+ if (input.source !== void 0) source(input.source);
1023
+ return input;
1024
+ }
1025
+ /** Selectors are bounded data, not executable callbacks. */
1026
+ function selectors(value) {
1027
+ if (!Array.isArray(value) || value.length > 100 || value.some((item) => typeof item !== "string" || !item || item.length > 512)) invalid$1("Invalid element selectors");
1028
+ }
1029
+ /** Validate framework tree or selected instance details after common JSON budget. */
1030
+ function validateComponentExtension(input, base) {
1031
+ const coverage = ["coverage", "limitations"];
1032
+ const limitations = [
1033
+ "fragment",
1034
+ "slot",
1035
+ "teleport",
1036
+ "async",
1037
+ "keep-alive",
1038
+ "framework-metadata",
1039
+ "source"
1040
+ ];
1041
+ if (!["complete", "partial"].includes(input.coverage) || !Array.isArray(input.limitations) || input.limitations.length > limitations.length || input.limitations.some((item) => !limitations.includes(item)) || new Set(input.limitations).size !== input.limitations.length || input.coverage === "complete" && input.limitations.length) invalid$1("Invalid component coverage");
1042
+ if (input.inspection === "components") {
1043
+ record(input, [
1044
+ ...base,
1045
+ ...coverage,
1046
+ "nodes",
1047
+ "omittedCount"
1048
+ ]);
1049
+ count(input.omittedCount);
1050
+ if (!Array.isArray(input.nodes) || input.nodes.length > 500) invalid$1("Invalid component tree");
1051
+ const seen = /* @__PURE__ */ new Set();
1052
+ const depth = /* @__PURE__ */ new Map();
1053
+ for (const value of input.nodes) {
1054
+ const current = node(value);
1055
+ if (seen.has(current.id) || current.parentId !== null && !seen.has(current.parentId)) invalid$1("Invalid component tree ownership");
1056
+ const level = current.parentId === null ? 0 : depth.get(current.parentId) + 1;
1057
+ if (level > 20) invalid$1("Component depth exceeded");
1058
+ seen.add(current.id);
1059
+ depth.set(current.id, level);
1060
+ }
1061
+ } else if (input.inspection === "componentForElement") {
1062
+ record(input, [
1063
+ ...base,
1064
+ ...coverage,
1065
+ "matched",
1066
+ "node",
1067
+ "unavailableReason"
1068
+ ]);
1069
+ if (typeof input.matched !== "boolean" || input.node !== null && !input.matched || input.unavailableReason !== void 0 && !["owner-unavailable", "outside-owned-root"].includes(input.unavailableReason) || input.node !== null && input.unavailableReason !== void 0 || input.matched && input.node === null && input.unavailableReason === void 0 || !input.matched && input.unavailableReason !== void 0) invalid$1("Invalid element ownership result");
1070
+ if (input.node !== null) node(input.node);
1071
+ } else {
1072
+ record(input, [
1073
+ ...base,
1074
+ ...coverage,
1075
+ "node",
1076
+ "props",
1077
+ "state",
1078
+ "selectors",
1079
+ "omittedValues"
1080
+ ]);
1081
+ node(input.node);
1082
+ wireRecord(input.props);
1083
+ if (input.state !== void 0) wireRecord(input.state);
1084
+ selectors(input.selectors);
1085
+ count(input.omittedValues);
1086
+ }
1087
+ }
1088
+ /** Bounded findings omit raw HTML and executable axe configuration. */
1089
+ function validateAccessibilityExtension(input, base) {
1090
+ record(input, [
1091
+ ...base,
1092
+ "matched",
1093
+ "engine",
1094
+ "engineVersion",
1095
+ "violations",
1096
+ "incomplete",
1097
+ "passesCount",
1098
+ "inapplicableCount",
1099
+ "droppedCount"
1100
+ ]);
1101
+ if (typeof input.matched !== "boolean" || input.engine !== "axe-core" || !wireId(input.engineVersion)) invalid$1("Invalid accessibility engine");
1102
+ for (const key of [
1103
+ "passesCount",
1104
+ "inapplicableCount",
1105
+ "droppedCount"
1106
+ ]) count(input[key]);
1107
+ let retained = 0;
1108
+ for (const key of ["violations", "incomplete"]) {
1109
+ const rows = input[key];
1110
+ if (!Array.isArray(rows) || rows.length > 500) invalid$1("Invalid accessibility findings");
1111
+ for (const value of rows) {
1112
+ const finding = record(value, [
1113
+ "id",
1114
+ "impact",
1115
+ "help",
1116
+ "helpUrl",
1117
+ "nodes"
1118
+ ]);
1119
+ if (!wireId(finding.id) || ![
1120
+ null,
1121
+ "minor",
1122
+ "moderate",
1123
+ "serious",
1124
+ "critical"
1125
+ ].includes(finding.impact) || typeof finding.help !== "string" || typeof finding.helpUrl !== "string") invalid$1("Invalid accessibility rule");
1126
+ let url;
1127
+ try {
1128
+ url = new URL(finding.helpUrl);
1129
+ } catch {
1130
+ return invalid$1("Invalid accessibility help URL");
1131
+ }
1132
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) invalid$1("Invalid accessibility help URL");
1133
+ if (!Array.isArray(finding.nodes)) invalid$1("Invalid accessibility nodes");
1134
+ for (const value of finding.nodes) {
1135
+ if (++retained > 500) invalid$1("Accessibility node limit exceeded");
1136
+ const item = record(value, [
1137
+ "selectors",
1138
+ "failureSummary",
1139
+ "accessibleName"
1140
+ ]);
1141
+ selectors(item.selectors);
1142
+ if (item.accessibleName !== void 0 && (typeof item.accessibleName !== "string" || item.accessibleName.length > 1024)) invalid$1("Invalid accessible name");
1143
+ if (item.failureSummary !== void 0 && (typeof item.failureSummary !== "string" || item.failureSummary.length > 4096)) invalid$1("Invalid accessibility summary");
1144
+ }
1145
+ }
1146
+ }
1147
+ if (!input.matched && (input.violations.length || input.incomplete.length)) invalid$1("Unmatched audit cannot contain findings");
1148
+ }
1149
+ // src/inspection/rows.ts
1150
+ /** Strict object keys prevent undeclared runtime data crossing the boundary. */
1151
+ function fields$1(input, names) {
1152
+ if (Object.keys(input).some((name) => !names.includes(name))) invalid$1("Unknown inspection row field");
1153
+ }
1154
+ /** Bounded descriptive text, allowing empty labels. */
1155
+ function text(input, maximum) {
1156
+ if (typeof input !== "string" || input.length > maximum) invalid$1("Invalid inspection text");
1157
+ }
1158
+ /** Validate component prop metadata after shared JSON graph validation. */
1159
+ function validateInspectionComponents(value) {
1160
+ if (!Array.isArray(value) || value.length > 100) invalid$1("Invalid component list");
1161
+ for (const item of value) {
1162
+ const component = wireRecord(item);
1163
+ fields$1(component, [
1164
+ "name",
1165
+ "index",
1166
+ "props"
1167
+ ]);
1168
+ text(component.name, 256);
1169
+ if (!Number.isSafeInteger(component.index) || component.index < 0 || !Array.isArray(component.props) || component.props.length > 100) invalid$1("Invalid component metadata");
1170
+ for (const item of component.props) {
1171
+ const prop = wireRecord(item);
1172
+ fields$1(prop, [
1173
+ "name",
1174
+ "types",
1175
+ "required",
1176
+ "default",
1177
+ "value",
1178
+ "values"
1179
+ ]);
1180
+ text(prop.name, 256);
1181
+ if (prop.required !== void 0 && typeof prop.required !== "boolean") invalid$1("Invalid prop requirement");
1182
+ if (prop.types !== void 0) {
1183
+ if (!Array.isArray(prop.types) || prop.types.length > 16) invalid$1("Invalid prop types");
1184
+ for (const type of prop.types) text(type, 128);
1185
+ }
1186
+ if (prop.values !== void 0 && (!Array.isArray(prop.values) || prop.values.length > 100)) invalid$1("Invalid prop values");
1187
+ }
1188
+ }
1189
+ }
1190
+ /** Validate preorder geometry and parents, rejecting impossible snapshot references. */
1191
+ function validateInspectionNodes(value) {
1192
+ if (!Array.isArray(value) || value.length > 500) invalid$1("Invalid DOM nodes");
1193
+ for (const [index, item] of value.entries()) {
1194
+ const node = wireRecord(item);
1195
+ fields$1(node, [
1196
+ "index",
1197
+ "parentIndex",
1198
+ "tag",
1199
+ "attributes",
1200
+ "text",
1201
+ "rect",
1202
+ "styles"
1203
+ ]);
1204
+ if (node.index !== index || (index === 0 ? node.parentIndex !== null : !Number.isInteger(node.parentIndex) || node.parentIndex < 0 || node.parentIndex >= index)) invalid$1("Invalid DOM parent");
1205
+ text(node.tag, 128);
1206
+ text(node.text, 1e3);
1207
+ for (const record of [node.attributes, node.styles]) for (const entry of Object.values(wireRecord(record))) text(entry, 512);
1208
+ const rect = wireRecord(node.rect);
1209
+ fields$1(rect, [
1210
+ "x",
1211
+ "y",
1212
+ "width",
1213
+ "height"
1214
+ ]);
1215
+ for (const name of [
1216
+ "x",
1217
+ "y",
1218
+ "width",
1219
+ "height"
1220
+ ]) if (typeof rect[name] !== "number" || !Number.isFinite(rect[name]) || ["width", "height"].includes(name) && rect[name] < 0) invalid$1("Invalid DOM geometry");
1221
+ }
1222
+ }
1223
+ // src/inspection/validation.ts
1224
+ /** Shared response budget leaves room for transport metadata. */
1225
+ var HISTOIRE_INSPECTION_LIMITS = {
1226
+ result: 61440,
1227
+ nodes: 500,
1228
+ depth: 20,
1229
+ selector: 512,
1230
+ pending: 4,
1231
+ timeout: 5e3
1232
+ };
1233
+ /** Reject extension fields rather than silently granting new behavior. */
1234
+ function keys(value, allowed) {
1235
+ if (Object.keys(value).some((key) => !allowed.includes(key))) invalid$1("Unknown inspection field");
1236
+ }
1237
+ /** An inspection target always names a rendered variant. */
1238
+ function validateInspectionTarget(value) {
1239
+ measureWireValue(value, {
1240
+ maxBytes: 16384,
1241
+ maxDepth: 32
1242
+ });
1243
+ const input = wireRecord(value);
1244
+ keys(input, ["storyId", "variantId"]);
1245
+ if (!wireId(input.storyId) || !wireId(input.variantId)) invalid$1("Exact inspection target required");
1246
+ return input;
1247
+ }
1248
+ /** Validate the entire tuple; caller-provided IDs never grant access. */
1249
+ function validateInspectionOwner(value) {
1250
+ measureWireValue(value, {
1251
+ maxBytes: 16384,
1252
+ maxDepth: 32
1253
+ });
1254
+ const input = wireRecord(value);
1255
+ keys(input, [
1256
+ "sourceId",
1257
+ "epoch",
1258
+ "revision",
1259
+ "runtimeId",
1260
+ "target"
1261
+ ]);
1262
+ for (const key of [
1263
+ "sourceId",
1264
+ "epoch",
1265
+ "revision",
1266
+ "runtimeId"
1267
+ ]) if (!wireId(input[key])) invalid$1("Invalid inspection owner");
1268
+ validateInspectionTarget(input.target);
1269
+ return input;
1270
+ }
1271
+ /** Compare structured IDs without ambiguous string concatenation. */
1272
+ function sameInspectionOwner(a, b) {
1273
+ return a.sourceId === b.sourceId && a.epoch === b.epoch && a.revision === b.revision && a.runtimeId === b.runtimeId && a.target.storyId === b.target.storyId && a.target.variantId === b.target.variantId;
1274
+ }
1275
+ /** Validate finite wire inputs. AbortSignal is intentionally absent. */
1276
+ function validateInspectionInput(kind, value) {
1277
+ measureWireValue(value, {
1278
+ maxBytes: 16384,
1279
+ maxDepth: 32
1280
+ });
1281
+ const input = wireRecord(value);
1282
+ const common = [
1283
+ "target",
1284
+ "expectedOwner",
1285
+ "correlationId"
1286
+ ];
1287
+ const fields = {
1288
+ debug: [
1289
+ "action",
1290
+ "observationId",
1291
+ "afterSequence"
1292
+ ],
1293
+ variant: [],
1294
+ dom: [
1295
+ "selector",
1296
+ "maxNodes",
1297
+ "maxDepth"
1298
+ ],
1299
+ components: [
1300
+ "rootId",
1301
+ "maxNodes",
1302
+ "maxDepth"
1303
+ ],
1304
+ component: ["componentId"],
1305
+ componentForElement: ["selector"],
1306
+ accessibility: ["selector"],
1307
+ highlight: [
1308
+ "selector",
1309
+ "componentId",
1310
+ "durationMs"
1311
+ ],
1312
+ pick: ["x", "y"],
1313
+ highlightLease: [
1314
+ "selector",
1315
+ "componentId",
1316
+ "durationMs"
1317
+ ],
1318
+ highlightClear: ["leaseId"]
1319
+ };
1320
+ if (!Object.hasOwn(fields, kind)) invalid$1("Unknown inspection operation");
1321
+ keys(input, [...common, ...fields[kind]]);
1322
+ if (input.target !== void 0) validateInspectionTarget(input.target);
1323
+ if (input.expectedOwner !== void 0) validateInspectionOwner(input.expectedOwner);
1324
+ for (const key of [
1325
+ "selector",
1326
+ "componentId",
1327
+ "rootId",
1328
+ "correlationId"
1329
+ ]) if (input[key] !== void 0 && (typeof input[key] !== "string" || !input[key] || input[key].length > (key === "selector" ? 512 : 128))) invalid$1("Invalid inspection locator or correlation");
1330
+ for (const [key, minimum, maximum] of [
1331
+ [
1332
+ "maxNodes",
1333
+ 1,
1334
+ 500
1335
+ ],
1336
+ [
1337
+ "maxDepth",
1338
+ 0,
1339
+ 20
1340
+ ],
1341
+ [
1342
+ "durationMs",
1343
+ 1,
1344
+ 5e3
1345
+ ]
1346
+ ]) if (input[key] !== void 0 && (!Number.isInteger(input[key]) || input[key] < minimum || input[key] > maximum)) invalid$1("Invalid inspection bound");
1347
+ if (kind === "debug" && (![
1348
+ "start",
1349
+ "read",
1350
+ "stop"
1351
+ ].includes(input.action) || !wireId(input.observationId) || input.afterSequence !== void 0 && (!Number.isSafeInteger(input.afterSequence) || input.afterSequence < 0))) invalid$1("Invalid diagnostic observation");
1352
+ if ((kind === "highlight" || kind === "highlightLease") && Number(input.selector !== void 0) + Number(input.componentId !== void 0) !== 1) invalid$1("One highlight locator required");
1353
+ if (kind === "component" && input.componentId === void 0) invalid$1("Component identity required");
1354
+ if (kind === "componentForElement" && input.selector === void 0) invalid$1("Component selector required");
1355
+ if (kind === "highlightClear" && (typeof input.leaseId !== "string" || !input.leaseId || input.leaseId.length > 128 || input.expectedOwner === void 0 || input.target === void 0)) invalid$1("Invalid highlight lease");
1356
+ if (kind === "pick" && ["x", "y"].some((key) => typeof input[key] !== "number" || !Number.isFinite(input[key]) || Math.abs(input[key]) > 1e6)) invalid$1("Invalid inspection point");
1357
+ measureWireValue(input, { maxBytes: 16384 });
1358
+ return input;
1359
+ }
1360
+ /** Strict JSON validation avoids coercing callbacks, unsupported values or accessors. */
1361
+ function assertInspectionJson(value, ancestors = /* @__PURE__ */ new Set()) {
1362
+ if (ancestors.size === 0) measureWireValue(value, {
1363
+ maxBytes: HISTOIRE_INSPECTION_LIMITS.result,
1364
+ maxDepth: 32
1365
+ });
1366
+ if (value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;
1367
+ if (!value || typeof value !== "object" || ancestors.has(value)) invalid$1("Inspection requires acyclic JSON");
1368
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) invalid$1("Inspection requires plain JSON objects");
1369
+ ancestors.add(value);
1370
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
1371
+ if (Array.isArray(value) && key === "length") continue;
1372
+ if (!("value" in descriptor) || [
1373
+ "__proto__",
1374
+ "constructor",
1375
+ "prototype"
1376
+ ].includes(key)) invalid$1("Unsafe inspection field");
1377
+ assertInspectionJson(descriptor.value, ancestors);
1378
+ }
1379
+ ancestors.delete(value);
1380
+ }
1381
+ /** Validate detached read result before exposing it outside the owning runtime. */
1382
+ function validateInspectionResult(value) {
1383
+ measureWireValue(value, {
1384
+ maxBytes: HISTOIRE_INSPECTION_LIMITS.result,
1385
+ maxDepth: 32
1386
+ });
1387
+ assertInspectionJson(value);
1388
+ const input = wireRecord(value);
1389
+ const base = [
1390
+ "mode",
1391
+ "owner",
1392
+ "observedAt",
1393
+ "durationMs",
1394
+ "truncated",
1395
+ "inspection"
1396
+ ];
1397
+ if (!["live", "isolated"].includes(input.mode) || typeof input.observedAt !== "string" || !Number.isFinite(Date.parse(input.observedAt)) || typeof input.durationMs !== "number" || !Number.isFinite(input.durationMs) || input.durationMs < 0 || typeof input.truncated !== "boolean") invalid$1("Invalid inspection metadata");
1398
+ validateInspectionOwner(input.owner);
1399
+ if (input.inspection === "variant") {
1400
+ keys(input, [
1401
+ ...base,
1402
+ "state",
1403
+ "components",
1404
+ "propsAvailable",
1405
+ "omittedValues"
1406
+ ]);
1407
+ wireRecord(input.state);
1408
+ validateInspectionComponents(input.components);
1409
+ if (!Array.isArray(input.components) || input.components.length > 100 || typeof input.propsAvailable !== "boolean" || !Number.isSafeInteger(input.omittedValues) || input.omittedValues < 0) invalid$1("Invalid variant inspection");
1410
+ } else if (input.inspection === "dom") {
1411
+ keys(input, [
1412
+ ...base,
1413
+ "matched",
1414
+ "nodes"
1415
+ ]);
1416
+ validateInspectionNodes(input.nodes);
1417
+ if (typeof input.matched !== "boolean" || !Array.isArray(input.nodes) || input.nodes.length > 500 || !input.matched && input.nodes.length > 0) invalid$1("Invalid DOM inspection");
1418
+ } else if (input.inspection === "components" || input.inspection === "component" || input.inspection === "componentForElement") validateComponentExtension(input, base);
1419
+ else if (input.inspection === "accessibility") validateAccessibilityExtension(input, base);
1420
+ else if (input.inspection === "debug") {
1421
+ keys(input, [
1422
+ ...base,
1423
+ "items",
1424
+ "nextSequence",
1425
+ "oldestSequence",
1426
+ "droppedCount",
1427
+ "gap"
1428
+ ]);
1429
+ if (!Array.isArray(input.items) || input.items.length > 200 || !Number.isSafeInteger(input.nextSequence) || input.nextSequence < 0 || !Number.isSafeInteger(input.droppedCount) || input.droppedCount < 0) invalid$1("Invalid diagnostic page");
1430
+ if (!Number.isSafeInteger(input.oldestSequence) || input.oldestSequence < 1 || typeof input.gap !== "boolean") invalid$1("Invalid diagnostic cursor");
1431
+ let previous = 0;
1432
+ for (const value of input.items) {
1433
+ const row = wireRecord(value);
1434
+ keys(row, [
1435
+ "sequence",
1436
+ "timestamp",
1437
+ "kind",
1438
+ "message",
1439
+ "level",
1440
+ "owner",
1441
+ "correlationId",
1442
+ "monotonicTimeMs",
1443
+ "requestId",
1444
+ "operationId",
1445
+ "outcome",
1446
+ "details"
1447
+ ]);
1448
+ if (!Number.isSafeInteger(row.sequence) || row.sequence < 1 || typeof row.timestamp !== "number" || !Number.isFinite(row.timestamp) || ![
1449
+ "console",
1450
+ "page-error",
1451
+ "unhandled-rejection",
1452
+ "sdk-request",
1453
+ "component-event",
1454
+ "state-patch",
1455
+ "lifecycle"
1456
+ ].includes(row.kind) || typeof row.message !== "string" || row.message.length > 2048) invalid$1("Invalid diagnostic entry");
1457
+ if (typeof row.monotonicTimeMs !== "number" || !Number.isFinite(row.monotonicTimeMs) || row.monotonicTimeMs < 0 || row.sequence <= previous || row.sequence > input.nextSequence || row.sequence < input.oldestSequence) invalid$1("Invalid diagnostic chronology");
1458
+ previous = row.sequence;
1459
+ measureWireValue(row, { maxBytes: 4096 });
1460
+ if (row.owner === void 0 && row.kind !== "lifecycle") invalid$1("Runtime diagnostics require owner");
1461
+ if (row.owner !== void 0) validateInspectionOwner(row.owner);
1462
+ for (const key of [
1463
+ "level",
1464
+ "correlationId",
1465
+ "requestId",
1466
+ "operationId",
1467
+ "outcome"
1468
+ ]) if (row[key] !== void 0 && (typeof row[key] !== "string" || row[key].length > 128)) invalid$1("Invalid diagnostic label");
1469
+ }
1470
+ } else throw new HistoireSdkError("INVALID_ARGUMENT", "Unknown inspection result");
1471
+ return input;
1472
+ }
1473
+ // src/bridge/snapshot.ts
1474
+ /** Ready visible variant geometry, finite and target-attributed. */
1475
+ function validateHistoireViewports(value) {
1476
+ if (!Array.isArray(value)) invalid$1("Expected runtime viewports");
1477
+ for (const entry of value) {
1478
+ const viewport = wireRecord(entry);
1479
+ validateHistoireTarget(viewport.target);
1480
+ for (const key of [
1481
+ "x",
1482
+ "y",
1483
+ "width",
1484
+ "height",
1485
+ "scale"
1486
+ ]) if (typeof viewport[key] !== "number" || !Number.isFinite(viewport[key]) || [
1487
+ "width",
1488
+ "height",
1489
+ "scale"
1490
+ ].includes(key) && viewport[key] <= 0) invalid$1("Invalid runtime geometry");
1491
+ const clip = wireRecord(viewport.visibleRect);
1492
+ for (const key of [
1493
+ "x",
1494
+ "y",
1495
+ "width",
1496
+ "height"
1497
+ ]) if (typeof clip[key] !== "number" || !Number.isFinite(clip[key]) || ["width", "height"].includes(key) && clip[key] <= 0) invalid$1("Invalid visible clip");
1498
+ }
1499
+ }
1500
+ /** Validates primary lifecycle before state/control/dynamic operations become ready. */
1501
+ function validateHistoireRuntimeSnapshot(value) {
1502
+ const input = wireRecord(value);
1503
+ if (![
1504
+ "absent",
1505
+ "mounting",
1506
+ "ready",
1507
+ "failed",
1508
+ "stale"
1509
+ ].includes(input.status)) invalid$1("Invalid runtime status");
1510
+ for (const key of ["mountId", "runtimeId"]) if (!(input[key] === null || wireId(input[key]))) invalid$1("Invalid runtime owner");
1511
+ validateHistoireViewports(input.viewports);
1512
+ if (input.viewport !== null) validateHistoireViewports([input.viewport]);
1513
+ if (input.inspection !== void 0) validateInspectionCapabilities(input.inspection);
1514
+ if (input.status === "ready" && (!wireId(input.mountId) || !wireId(input.runtimeId))) invalid$1("Ready runtime requires owner");
1515
+ return input;
1516
+ }
1517
+ /**
1518
+ * Cyclic cleaned state root remains structured-clone data and never runtime callbacks.
1519
+ * @param value Untrusted value.
1520
+ * @param measured Caller already measured `value` with the `state.changed` event policy
1521
+ * (identical to the `view.sync` state sub-budget).
1522
+ */
1523
+ function validateHistoireStateSnapshot(value, measured = false) {
1524
+ if (!measured) validateWireValue(value, {
1525
+ kind: "event",
1526
+ name: "state.changed"
1527
+ });
1528
+ const input = wireRecord(value);
1529
+ validateHistoireTarget(input.target);
1530
+ if (!wireId(input.runtimeId) || !input.value || typeof input.value !== "object") invalid$1("Invalid state snapshot");
1531
+ return input;
1532
+ }
1533
+ /**
1534
+ * Every event retains exact target/document ownership and finite chronology.
1535
+ * @param value Untrusted value.
1536
+ * @param measured Caller already measured an enclosing JSON value under a budget no larger
1537
+ * than the default request budget (e.g. the `events.appended` batch), which covers this payload.
1538
+ */
1539
+ function validateHistoireEvent(value, measured = false) {
1540
+ const input = wireRecord(value);
1541
+ validateHistoireTarget(input.target);
1542
+ if (!wireId(input.runtimeId) || !Number.isSafeInteger(input.sequence) || input.sequence < 0 || typeof input.timestamp !== "number" || !Number.isFinite(input.timestamp) || !Object.hasOwn(input, "payload")) invalid$1("Invalid story event");
1543
+ if (!measured) measureWireValue(input.payload);
1544
+ return input;
1545
+ }
1546
+ /**
1547
+ * Complete projected view snapshot; event history arrives in separate bounded batches.
1548
+ * @param value Untrusted value.
1549
+ * @param measured Caller already ran `validateWireValue(value, { kind: 'request', name: 'view.sync' })`,
1550
+ * which also measures the `catalog` and `state` sub-budgets.
1551
+ */
1552
+ function validateHistoireSnapshot(value, measured = false) {
1553
+ if (!measured) validateWireValue(value, {
1554
+ kind: "request",
1555
+ name: "view.sync"
1556
+ });
1557
+ const input = wireRecord(value);
1558
+ if (![
1559
+ "idle",
1560
+ "connecting",
1561
+ "ready",
1562
+ "restarting",
1563
+ "disconnected",
1564
+ "failed",
1565
+ "disposed"
1566
+ ].includes(input.status) || typeof input.stale !== "boolean") invalid$1("Invalid session lifecycle");
1567
+ if (input.source !== null) {
1568
+ const source = wireRecord(input.source);
1569
+ if (!wireId(source.sourceId) || !wireId(source.epoch) || !wireId(source.revision) || typeof source.url !== "string" || !["dev", "static"].includes(source.mode)) invalid$1("Invalid source identity");
1570
+ let url;
1571
+ try {
1572
+ url = new URL(source.url);
1573
+ } catch {
1574
+ return invalid$1("Invalid source URL");
1575
+ }
1576
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) invalid$1("Invalid source URL");
1577
+ }
1578
+ validateHistoireCatalog(input.catalog);
1579
+ validateHistoireDiagnostics(input.diagnostics);
1580
+ const diagnostics = wireRecord(input.catalog).diagnostics;
1581
+ if (!Array.isArray(input.diagnostics) || input.diagnostics.length !== diagnostics.length) invalid$1("Invalid snapshot diagnostics");
1582
+ if (input.selection !== null) validateHistoireTarget(input.selection);
1583
+ validateHistoireRuntimeSnapshot(input.runtime);
1584
+ if (input.state !== null) validateHistoireStateSnapshot(input.state, measured);
1585
+ const settings = validateSettingsPatch(input.settings);
1586
+ for (const key of [
1587
+ "responsiveWidth",
1588
+ "responsiveHeight",
1589
+ "rotate",
1590
+ "backgroundColor",
1591
+ "checkerboard",
1592
+ "textDirection",
1593
+ "colorScheme",
1594
+ "globals"
1595
+ ]) if (!Object.hasOwn(settings, key)) invalid$1("Incomplete session settings");
1596
+ validateHistoireCapabilities(input.capabilities);
1597
+ if (input.inspection !== void 0) validateInspectionCapabilities(input.inspection);
1598
+ const events = wireRecord(input.events);
1599
+ if (!Array.isArray(events.items) || events.items.length > 1e3 || !Number.isSafeInteger(events.droppedCount) || events.droppedCount < 0) invalid$1("Invalid event history");
1600
+ for (const event of events.items) validateHistoireEvent(event);
1601
+ return input;
1602
+ }
1603
+ // src/bridge/test-execution.ts
1604
+ /** Finite attribution DTO excludes callbacks, loaders, private paths and arbitrary metadata. */
1605
+ function validateHistoireTestExecution(value) {
1606
+ const input = wireRecord(value);
1607
+ if (Object.keys(input).some((key) => ![
1608
+ "runId",
1609
+ "mode",
1610
+ "target",
1611
+ "sourceId",
1612
+ "epoch",
1613
+ "revision",
1614
+ "runtimeId"
1615
+ ].includes(key))) invalid$1("Invalid test execution fields");
1616
+ if (!wireId(input.runId) || !["preview", "server"].includes(input.mode)) invalid$1("Invalid test execution identity");
1617
+ if (input.target !== void 0) validateHistoireTarget(input.target);
1618
+ const target = input.target;
1619
+ const source = [
1620
+ "sourceId",
1621
+ "epoch",
1622
+ "revision"
1623
+ ].filter((key) => input[key] !== void 0);
1624
+ if (source.length && source.length !== 3) invalid$1("Incomplete test source identity");
1625
+ for (const key of source) if (!wireId(input[key])) invalid$1("Invalid test source identity");
1626
+ if (input.mode === "preview" ? !wireId(input.runtimeId) || !target?.variantId || source.length !== 3 : input.runtimeId !== void 0) invalid$1("Invalid test runtime identity");
1627
+ }
1628
+ // src/bridge/results.ts
1629
+ /** JSON-safe bounded error; uncontrolled Error instances cannot enter callbacks. */
1630
+ function validateHistoireErrorData(value) {
1631
+ validateWireValue(value, {
1632
+ kind: "error",
1633
+ name: ""
1634
+ });
1635
+ const input = wireRecord(value);
1636
+ if (!HISTOIRE_ERROR_CODES.includes(input.code) || typeof input.message !== "string") invalid$1("Invalid bridge error");
1637
+ }
1638
+ /** Existing test-error representation with controlled portable fields. */
1639
+ function validateTestError(value) {
1640
+ if (typeof value === "string") return;
1641
+ const input = wireRecord(value);
1642
+ if (typeof input.message !== "string") invalid$1("Invalid test error");
1643
+ for (const key of [
1644
+ "name",
1645
+ "stack",
1646
+ "diff"
1647
+ ]) if (input[key] !== void 0 && typeof input[key] !== "string") invalid$1("Invalid test error field");
1648
+ }
1649
+ /** Plugin-keyed JSON attached to one test result, bounded per test. */
1650
+ function validateHistoireTestData(value) {
1651
+ wireRecord(value);
1652
+ measureWireValue(value, {
1653
+ mode: "json",
1654
+ maxBytes: HISTOIRE_TEST_DATA_LIMIT
1655
+ });
1656
+ }
1657
+ /** Existing wire-safe definition/summary fields retain names and assertion semantics. */
1658
+ function validateHistoireTestResult(value, summary) {
1659
+ const input = wireRecord(value);
1660
+ if (input.execution !== void 0) validateHistoireTestExecution(input.execution);
1661
+ if (!summary) {
1662
+ if (!Array.isArray(input.definitions)) invalid$1("Invalid test collection");
1663
+ for (const value of input.definitions) {
1664
+ const test = wireRecord(value);
1665
+ if (!wireId(test.id) || typeof test.name !== "string" || typeof test.fullName !== "string" || test.mode !== void 0 && ![
1666
+ "run",
1667
+ "skip",
1668
+ "only",
1669
+ "todo"
1670
+ ].includes(test.mode)) invalid$1("Invalid test definition");
1671
+ if (test.timeout !== void 0 && (typeof test.timeout !== "number" || !Number.isFinite(test.timeout) || test.timeout < 0)) invalid$1("Invalid test deadline");
1672
+ }
1673
+ if (input.error !== void 0 && input.error !== null) validateTestError(input.error);
1674
+ return;
1675
+ }
1676
+ if (typeof input.ok !== "boolean" || !Array.isArray(input.errors) || !Array.isArray(input.tests)) invalid$1("Invalid test run summary");
1677
+ for (const key of [
1678
+ "total",
1679
+ "passed",
1680
+ "failed",
1681
+ "skipped"
1682
+ ]) if (!Number.isSafeInteger(input[key]) || input[key] < 0) invalid$1("Invalid test count");
1683
+ for (const error of input.errors) validateTestError(error);
1684
+ for (const value of input.tests) {
1685
+ const test = wireRecord(value);
1686
+ if (!wireId(test.id) || typeof test.name !== "string" || typeof test.fullName !== "string" || ![
1687
+ "passed",
1688
+ "failed",
1689
+ "skipped"
1690
+ ].includes(test.state) || !Array.isArray(test.errors)) invalid$1("Invalid test case");
1691
+ for (const error of test.errors) validateTestError(error);
1692
+ if (test.data !== void 0) validateHistoireTestData(test.data);
1693
+ for (const key of ["storyId", "variantId"]) if (test[key] !== void 0 && !wireId(test[key])) invalid$1("Invalid test target");
1694
+ }
1695
+ if (input.uncollectedStories !== void 0) {
1696
+ if (!Array.isArray(input.uncollectedStories)) invalid$1("Invalid uncollected stories");
1697
+ for (const value of input.uncollectedStories) {
1698
+ const story = wireRecord(value);
1699
+ if (typeof story.relativePath !== "string" || typeof story.error !== "string") invalid$1("Invalid collection failure");
1700
+ }
1701
+ }
1702
+ }
1703
+ /** Lazy content has captured identity and finite origin/format semantics. */
1704
+ function validateHistoireContent(value, docs) {
1705
+ const input = wireRecord(value);
1706
+ if (!wireId(input.storyId) || !wireId(input.epoch) || !wireId(input.revision) || typeof input.body !== "string" || input.variantId !== void 0 && !wireId(input.variantId)) invalid$1("Invalid content identity/body");
1707
+ if (docs ? ![
1708
+ "sibling",
1709
+ "standalone",
1710
+ "inline",
1711
+ "collected"
1712
+ ].includes(input.origin) || !["html", "text"].includes(input.format) : ![
1713
+ "file",
1714
+ "virtual",
1715
+ "generated",
1716
+ "explicit",
1717
+ "slot"
1718
+ ].includes(input.origin) || !["raw", "dynamic"].includes(input.mode)) invalid$1("Invalid content kind");
1719
+ for (const key of ["relativePath", "language"]) if (input[key] !== void 0 && typeof input[key] !== "string") invalid$1("Invalid content label");
1720
+ }
1721
+ /** Correlated successful result must match requested command before observers see it. */
1722
+ function validateBridgeResult(command, value) {
1723
+ validateWireValue(value, {
1724
+ kind: "response",
1725
+ name: command
1726
+ });
1727
+ if ([
1728
+ "inspection.variant",
1729
+ "inspection.dom",
1730
+ "inspection.debug",
1731
+ "inspection.components",
1732
+ "inspection.component",
1733
+ "inspection.componentForElement",
1734
+ "inspection.accessibility"
1735
+ ].includes(command)) {
1736
+ const result = validateInspectionResult(value);
1737
+ if (result.inspection !== command.slice(11) || result.mode !== "live") invalid$1("Mismatched inspection result");
1738
+ } else if (command === "inspection.highlight") {
1739
+ const result = wireRecord(value);
1740
+ if (Object.keys(result).some((key) => !["owner", "observedAt"].includes(key)) || typeof result.observedAt !== "string" || !Number.isFinite(Date.parse(result.observedAt))) invalid$1("Invalid highlight result");
1741
+ validateInspectionOwner(result.owner);
1742
+ } else if (command === "inspection.pick") {
1743
+ const result = wireRecord(value);
1744
+ if (Object.keys(result).some((key) => ![
1745
+ "owner",
1746
+ "observedAt",
1747
+ "matched",
1748
+ "selector"
1749
+ ].includes(key)) || typeof result.observedAt !== "string" || !Number.isFinite(Date.parse(result.observedAt)) || typeof result.matched !== "boolean" || (result.matched ? typeof result.selector !== "string" || !result.selector || result.selector.length > 512 : result.selector !== void 0)) invalid$1("Invalid inspection pick result");
1750
+ validateInspectionOwner(result.owner);
1751
+ } else if (command === "inspection.highlightLease") {
1752
+ const result = wireRecord(value);
1753
+ if (Object.keys(result).some((key) => ![
1754
+ "owner",
1755
+ "observedAt",
1756
+ "leaseId"
1757
+ ].includes(key)) || typeof result.observedAt !== "string" || !Number.isFinite(Date.parse(result.observedAt)) || typeof result.leaseId !== "string" || !result.leaseId || result.leaseId.length > 128) invalid$1("Invalid highlight lease result");
1758
+ validateInspectionOwner(result.owner);
1759
+ } else if (command === "inspection.highlightClear") {
1760
+ const result = wireRecord(value);
1761
+ if (Object.keys(result).some((key) => !["owner", "cleared"].includes(key)) || typeof result.cleared !== "boolean") invalid$1("Invalid highlight clear result");
1762
+ validateInspectionOwner(result.owner);
1763
+ } else if (command === "inspection.cancel") {
1764
+ const result = wireRecord(value);
1765
+ if (Object.keys(result).some((key) => !["requestId", "cancelled"].includes(key)) || !wireId(result.requestId) || result.cancelled !== true) invalid$1("Invalid inspection cancellation acknowledgment");
1766
+ } else if (command === "catalog.list") {
1767
+ if (!Array.isArray(value)) invalid$1("Expected catalog stories");
1768
+ for (const story of value) validateHistoireCatalogStory(story);
1769
+ } else if (command === "catalog.getStory") validateHistoireCatalogStory(value);
1770
+ else if (command === "catalog.search") {
1771
+ if (!Array.isArray(value)) invalid$1("Expected search results");
1772
+ for (const entry of value) {
1773
+ const result = wireRecord(entry);
1774
+ validateHistoireTarget(result.target);
1775
+ if (![
1776
+ "story",
1777
+ "variant",
1778
+ "docs"
1779
+ ].includes(result.kind) || typeof result.title !== "string" || typeof result.rank !== "number" || !Number.isFinite(result.rank)) invalid$1("Invalid search result");
1780
+ if (result.match !== void 0) {
1781
+ const match = wireRecord(result.match);
1782
+ if (!["literal", "fuzzy"].includes(match.mode) || typeof match.score !== "number" || !Number.isFinite(match.score) || match.score < 0) invalid$1("Invalid search matching evidence");
1783
+ }
1784
+ for (const key of ["excerpt", "anchor"]) if (result[key] !== void 0 && typeof result[key] !== "string") invalid$1("Invalid search excerpt");
1785
+ }
1786
+ } else if ([
1787
+ "state.get",
1788
+ "state.patch",
1789
+ "state.reset"
1790
+ ].includes(command)) {
1791
+ if (value !== null || command === "state.get") validateHistoireStateSnapshot(value);
1792
+ } else if (command === "docs.get" || command === "source.get") validateHistoireContent(value, command === "docs.get");
1793
+ else if (command === "tests.collect" || command === "tests.run") validateHistoireTestResult(value, command === "tests.run");
1794
+ else if (command === "tests.cancel") {
1795
+ const result = wireRecord(value);
1796
+ if (Object.keys(result).some((key) => !["requestId", "cancelled"].includes(key)) || !wireId(result.requestId) || result.cancelled !== true) invalid$1("Invalid test cancellation acknowledgment");
1797
+ } else if (command === "controls.preset") {
1798
+ const input = wireRecord(value);
1799
+ if (Object.keys(input).some((key) => !["items", "selectedId"].includes(key)) || !Array.isArray(input.items) || input.items.length > 1e3 || input.selectedId !== void 0 && !wireId(input.selectedId)) invalid$1("Invalid preset result");
1800
+ for (const value of input.items) {
1801
+ const item = wireRecord(value);
1802
+ if (Object.keys(item).some((key) => !["id", "label"].includes(key)) || !wireId(item.id) || typeof item.label !== "string" || item.label.length > 120) invalid$1("Invalid preset option");
1803
+ }
1804
+ } else if (value !== null) invalid$1("Expected null acknowledgment");
1805
+ }
1806
+ // src/bridge/events.ts
1807
+ /** Finite controls schemas carry presentation only, never arbitrary runtime values. */
1808
+ function fields(input, allowed) {
1809
+ if (Object.keys(input).some((key) => !allowed.includes(key))) invalid$1("Unknown controls event field");
1810
+ }
1811
+ /** Finite overlay labels/IDs/rectangles; values and callbacks stay runtime-local. */
1812
+ function validateOverlay(input, closing) {
1813
+ fields(input, closing ? ["id"] : [
1814
+ "id",
1815
+ "anchor",
1816
+ "overlay"
1817
+ ]);
1818
+ if (!wireId(input.id)) invalid$1("Invalid overlay identity");
1819
+ if (closing) return;
1820
+ const anchor = wireRecord(input.anchor);
1821
+ fields(anchor, [
1822
+ "x",
1823
+ "y",
1824
+ "width",
1825
+ "height"
1826
+ ]);
1827
+ for (const key of [
1828
+ "x",
1829
+ "y",
1830
+ "width",
1831
+ "height"
1832
+ ]) if (typeof anchor[key] !== "number" || !Number.isFinite(anchor[key]) || ["width", "height"].includes(key) && anchor[key] < 0) invalid$1("Invalid overlay anchor");
1833
+ const overlay = wireRecord(input.overlay);
1834
+ if (overlay.kind === "select") {
1835
+ fields(overlay, [
1836
+ "kind",
1837
+ "items",
1838
+ "label",
1839
+ "selectedId"
1840
+ ]);
1841
+ if (!Array.isArray(overlay.items) || overlay.label !== void 0 && typeof overlay.label !== "string" || overlay.selectedId !== void 0 && !wireId(overlay.selectedId)) invalid$1("Invalid select overlay");
1842
+ for (const value of overlay.items) {
1843
+ const item = wireRecord(value);
1844
+ fields(item, [
1845
+ "id",
1846
+ "label",
1847
+ "disabled"
1848
+ ]);
1849
+ if (!wireId(item.id) || typeof item.label !== "string" || item.disabled !== void 0 && typeof item.disabled !== "boolean") invalid$1("Invalid overlay option");
1850
+ }
1851
+ } else if (overlay.kind === "tooltip") {
1852
+ fields(overlay, [
1853
+ "kind",
1854
+ "content",
1855
+ "placement",
1856
+ "distance"
1857
+ ]);
1858
+ if (typeof overlay.content !== "string" || overlay.placement !== void 0 && ![
1859
+ "top",
1860
+ "bottom",
1861
+ "left",
1862
+ "right"
1863
+ ].includes(overlay.placement) || overlay.distance !== void 0 && (typeof overlay.distance !== "number" || !Number.isFinite(overlay.distance))) invalid$1("Invalid tooltip overlay");
1864
+ } else invalid$1("Unknown overlay kind");
1865
+ }
1866
+ /**
1867
+ * Validates every finite publication before parent observers/framework rendering.
1868
+ * @param event Publication discriminator.
1869
+ * @param value Untrusted payload.
1870
+ * @param measured Caller already ran `validateWireValue(value, { kind: 'event', name: event })`.
1871
+ */
1872
+ function validateBridgeEventPayload(event, value, measured = false) {
1873
+ const input = wireRecord(value);
1874
+ if (event === "catalog.changed") validateHistoireSourceDescriptor(input.descriptor);
1875
+ else if (event === "content.changed") {
1876
+ if (!Array.isArray(input.storyIds) || input.storyIds.some((id) => !wireId(id))) invalid$1("Invalid changed-content targets");
1877
+ } else if (event === "selection.changed") {
1878
+ if (input.target !== null) validateHistoireTarget(input.target);
1879
+ } else if (event === "settings.changed") validateSettingsPatch(input);
1880
+ else if (event === "state.changed") validateHistoireStateSnapshot(input, measured);
1881
+ else if (event === "layout.changed") validateHistoireViewports(input.viewports);
1882
+ else if (event === "events.appended") {
1883
+ if (!Array.isArray(input.items) || input.items.length > 1e3 || input.reset !== void 0 && typeof input.reset !== "boolean" || input.droppedCount !== void 0 && (!Number.isSafeInteger(input.droppedCount) || input.droppedCount < 0)) invalid$1("Invalid event batch");
1884
+ for (const entry of input.items) validateHistoireEvent(entry, measured);
1885
+ } else if (event === "readiness.changed") validateHistoireRuntimeSnapshot(input.runtime);
1886
+ else if (event === "source.disconnected") {
1887
+ if (input.reason !== void 0) validateHistoireErrorData(input.reason);
1888
+ } else if (event === "tests.progress") {
1889
+ if (!wireId(input.runId) || ![
1890
+ "collecting",
1891
+ "running",
1892
+ "completed",
1893
+ "cancelled",
1894
+ "failed"
1895
+ ].includes(input.status)) invalid$1("Invalid test progress");
1896
+ for (const key of ["completed", "total"]) if (input[key] !== void 0 && (!Number.isSafeInteger(input[key]) || input[key] < 0)) invalid$1("Invalid test progress count");
1897
+ if (input.summary !== void 0) validateHistoireTestResult(input.summary, true);
1898
+ if (input.error !== void 0) validateHistoireErrorData(input.error);
1899
+ } else if ([
1900
+ "overlay.open",
1901
+ "overlay.update",
1902
+ "overlay.close"
1903
+ ].includes(event)) validateOverlay(input, event === "overlay.close");
1904
+ else if (event === "overlay.result") {
1905
+ fields(input, [
1906
+ "id",
1907
+ "restoreFocus",
1908
+ "itemId",
1909
+ "focusDirection"
1910
+ ]);
1911
+ if (!wireId(input.id) || typeof input.restoreFocus !== "boolean" || input.itemId !== void 0 && !wireId(input.itemId) || input.focusDirection !== void 0 && !["next", "previous"].includes(input.focusDirection)) invalid$1("Invalid overlay result");
1912
+ } else if (event === "controls.height") {
1913
+ fields(input, ["height", "hasControls"]);
1914
+ if (typeof input.height !== "number" || !Number.isFinite(input.height) || input.height < 0 || input.hasControls !== void 0 && typeof input.hasControls !== "boolean") invalid$1("Invalid controls height");
1915
+ } else if (event === "focus.changed") {
1916
+ fields(input, [
1917
+ "focused",
1918
+ "direction",
1919
+ "action"
1920
+ ]);
1921
+ if (typeof input.focused !== "boolean" || input.direction !== void 0 && !["next", "previous"].includes(input.direction) || input.action !== void 0 && ![
1922
+ "search",
1923
+ "toggle-ui",
1924
+ "show-ui"
1925
+ ].includes(input.action) || input.action !== void 0 && input.direction !== void 0) invalid$1("Invalid focus state");
1926
+ } else if (event === "channel.message") validateHostChannelPayload(input, true);
1927
+ else if (event === "plugin.message") validatePluginChannelPayload(input, true);
1928
+ }
1929
+ // src/bridge/types.ts
1930
+ /** Initial portable descriptor and bridge versions. */
1931
+ var HISTOIRE_PROTOCOL_VERSION = 1;
1932
+ var HISTOIRE_DESCRIPTOR_VERSION = 1;
1933
+ /** Finite request registry; no arbitrary plugin/code/URL execution. */
1934
+ var HISTOIRE_BRIDGE_COMMANDS = [
1935
+ "catalog.list",
1936
+ "catalog.getStory",
1937
+ "catalog.search",
1938
+ "selection.select",
1939
+ "state.get",
1940
+ "state.patch",
1941
+ "state.reset",
1942
+ "settings.update",
1943
+ "events.clear",
1944
+ "docs.get",
1945
+ "source.get",
1946
+ "tests.collect",
1947
+ "tests.run",
1948
+ "tests.cancel",
1949
+ "openInEditor",
1950
+ "subscriptions.add",
1951
+ "subscriptions.remove",
1952
+ "view.sync",
1953
+ "controls.configure",
1954
+ "controls.preset",
1955
+ "channel.post",
1956
+ "plugin.post",
1957
+ "inspection.variant",
1958
+ "inspection.dom",
1959
+ "inspection.highlight",
1960
+ "inspection.debug",
1961
+ "inspection.components",
1962
+ "inspection.component",
1963
+ "inspection.componentForElement",
1964
+ "inspection.accessibility",
1965
+ "inspection.pick",
1966
+ "inspection.highlightLease",
1967
+ "inspection.highlightClear",
1968
+ "inspection.cancel"
1969
+ ];
1970
+ /** Finite publication registry. */
1971
+ var HISTOIRE_BRIDGE_EVENTS = [
1972
+ "catalog.changed",
1973
+ "content.changed",
1974
+ "selection.changed",
1975
+ "state.changed",
1976
+ "settings.changed",
1977
+ "events.appended",
1978
+ "readiness.changed",
1979
+ "layout.changed",
1980
+ "tests.progress",
1981
+ "source.disconnected",
1982
+ "overlay.open",
1983
+ "overlay.update",
1984
+ "overlay.close",
1985
+ "overlay.result",
1986
+ "controls.height",
1987
+ "focus.changed",
1988
+ "channel.message",
1989
+ "plugin.message"
1990
+ ];
1991
+ // src/bridge/payload.ts
1992
+ /**
1993
+ * Validates finite command arguments; transport signals never cross wire.
1994
+ * @param command Request command.
1995
+ * @param value Untrusted arguments.
1996
+ * @param measured Caller already ran `validateWireValue(value, { kind: 'request', name: command })`.
1997
+ */
1998
+ function validateBridgePayload(command, value, measured = false) {
1999
+ const input = wireRecord(value);
2000
+ if (command === "inspection.cancel") {
2001
+ if (Object.keys(input).some((key) => key !== "requestId") || !wireId(input.requestId)) invalid$1("Exact inspection request identity required");
2002
+ return;
2003
+ }
2004
+ if (command.startsWith("inspection.")) {
2005
+ validateInspectionInput(command.slice(11), value);
2006
+ return;
2007
+ }
2008
+ const allowed = {
2009
+ "catalog.list": [],
2010
+ "catalog.getStory": ["storyId"],
2011
+ "catalog.search": ["query"],
2012
+ "selection.select": ["storyId", "variantId"],
2013
+ "state.get": [],
2014
+ "state.reset": [],
2015
+ "events.clear": [],
2016
+ "docs.get": ["storyId"],
2017
+ "source.get": [
2018
+ "storyId",
2019
+ "variantId",
2020
+ "mode"
2021
+ ],
2022
+ "tests.collect": [],
2023
+ "tests.run": ["mode"],
2024
+ "tests.cancel": ["requestId"],
2025
+ "openInEditor": ["storyId", "variantId"],
2026
+ "subscriptions.add": ["subscriptionId", "streams"],
2027
+ "subscriptions.remove": ["subscriptionId"],
2028
+ "channel.post": [
2029
+ "name",
2030
+ "type",
2031
+ "data"
2032
+ ],
2033
+ "plugin.post": [
2034
+ "pluginId",
2035
+ "actorId",
2036
+ "type",
2037
+ "data"
2038
+ ],
2039
+ "controls.configure": ["customOnly"],
2040
+ "controls.preset": [
2041
+ "action",
2042
+ "id",
2043
+ "label"
2044
+ ]
2045
+ }[command];
2046
+ if (allowed && Object.keys(input).some((key) => !allowed.includes(key))) invalid$1("Unknown command argument");
2047
+ if (["catalog.getStory", "docs.get"].includes(command) && !wireId(input.storyId)) invalid$1("Expected story ID");
2048
+ if (command === "catalog.search" && typeof input.query !== "string") invalid$1("Expected search query");
2049
+ if (command === "selection.select") validateHistoireTarget(input, true);
2050
+ if (command === "state.patch") {
2051
+ if (Object.hasOwn(input, "_hPropDefs")) invalid$1("Derived controls metadata is runtime-owned");
2052
+ }
2053
+ if (command === "settings.update") validateSettingsPatch(input);
2054
+ if (command === "source.get") {
2055
+ if (!wireId(input.storyId) || input.variantId !== void 0 && !wireId(input.variantId) || !["raw", "dynamic"].includes(input.mode)) invalid$1("Invalid source request");
2056
+ }
2057
+ if (command === "tests.run" && !["preview", "server"].includes(input.mode)) invalid$1("Explicit test execution mode required");
2058
+ if (command === "tests.cancel" && !wireId(input.requestId)) invalid$1("Exact test request identity required");
2059
+ if (command === "openInEditor") validateHistoireTarget(input);
2060
+ if (command.startsWith("subscriptions.")) {
2061
+ if (!wireId(input.subscriptionId)) invalid$1("Expected subscription identity");
2062
+ if (command === "subscriptions.add" && (!Array.isArray(input.streams) || input.streams.some((stream) => !HISTOIRE_BRIDGE_EVENTS.includes(stream)))) invalid$1("Invalid subscription stream");
2063
+ }
2064
+ if (command === "channel.post") validateHostChannelPayload(input);
2065
+ if (command === "plugin.post") validatePluginChannelPayload(input);
2066
+ if (command === "view.sync") validateHistoireSnapshot(value, measured);
2067
+ if (command === "controls.configure" && typeof input.customOnly !== "boolean") invalid$1("Controls presentation must be boolean");
2068
+ if (command === "controls.preset") {
2069
+ if (![
2070
+ "list",
2071
+ "save",
2072
+ "apply",
2073
+ "delete",
2074
+ "rename"
2075
+ ].includes(input.action)) invalid$1("Invalid preset action");
2076
+ const id = [
2077
+ "apply",
2078
+ "delete",
2079
+ "rename"
2080
+ ].includes(input.action);
2081
+ const label = ["save", "rename"].includes(input.action);
2082
+ if (id ? !wireId(input.id) : input.id !== void 0) invalid$1("Invalid preset identity");
2083
+ if (label ? typeof input.label !== "string" || !input.label.trim() || input.label.length > 120 : input.label !== void 0) invalid$1("Invalid preset label");
2084
+ }
2085
+ }
2086
+ // src/bridge/envelope.ts
2087
+ /** Runtime-only request groups; data bridge must never execute stories implicitly. */
2088
+ var runtimeCommands = [
2089
+ "state.get",
2090
+ "state.patch",
2091
+ "state.reset",
2092
+ "tests.collect",
2093
+ "controls.preset",
2094
+ "channel.post",
2095
+ "plugin.post"
2096
+ ];
2097
+ /** Commands bound to an inspected runtime target; cancellation uses its captured owner. */
2098
+ var inspectionCommands = [
2099
+ "inspection.variant",
2100
+ "inspection.dom",
2101
+ "inspection.highlight",
2102
+ "inspection.debug",
2103
+ "inspection.components",
2104
+ "inspection.component",
2105
+ "inspection.componentForElement",
2106
+ "inspection.accessibility",
2107
+ "inspection.pick",
2108
+ "inspection.highlightLease",
2109
+ "inspection.highlightClear"
2110
+ ];
2111
+ /** Gates role authority before dispatch, independently of advertised capability checks. */
2112
+ function validateRole(role, command, payload, direction) {
2113
+ if (command.startsWith("inspection.")) {
2114
+ if (direction === "parent-to-child" ? role !== "primary" : !["primary", "view"].includes(role)) invalid$1("Inspection requires primary runtime or view intent");
2115
+ return;
2116
+ }
2117
+ if (command === "controls.configure") {
2118
+ if (role !== "controls" || direction !== "parent-to-child") invalid$1("Controls presentation requires parent controls port");
2119
+ return;
2120
+ }
2121
+ if (command === "controls.preset") {
2122
+ if (direction === "parent-to-child" ? role !== "primary" : !["primary", "controls"].includes(role)) invalid$1("Preset action requires primary runtime or controls intent");
2123
+ return;
2124
+ }
2125
+ if (command === "view.sync") {
2126
+ if (direction !== "parent-to-child") invalid$1("View sync is parent-to-view only");
2127
+ if (role === "data") invalid$1("View sync requires surface port");
2128
+ return;
2129
+ }
2130
+ if (direction === "child-to-parent" && role !== "data") {
2131
+ if (role === "controls" && ![
2132
+ "state.patch",
2133
+ "state.reset",
2134
+ "subscriptions.add",
2135
+ "subscriptions.remove"
2136
+ ].includes(command)) invalid$1("Controls port command unavailable");
2137
+ return;
2138
+ }
2139
+ if (role === "data" && (runtimeCommands.includes(command) || command === "source.get" && payload.mode === "dynamic" || command === "tests.run" && payload.mode === "preview")) invalid$1("Data port cannot execute runtime commands");
2140
+ if (role === "view") invalid$1("View port cannot execute runtime commands");
2141
+ if (role === "controls" && ![
2142
+ "state.patch",
2143
+ "subscriptions.add",
2144
+ "subscriptions.remove",
2145
+ "view.sync"
2146
+ ].includes(command)) invalid$1("Controls port command unavailable");
2147
+ }
2148
+ /**
2149
+ * Validates envelope before use; expected response command comes from pending request.
2150
+ * Metadata and body are each traversed once; `metadataOnly` stops after owner/identity checks
2151
+ * so callers can gate (rate, correlation) before running {@link validateBridgeEnvelopeBody}.
2152
+ */
2153
+ function validateBridgeEnvelope(value, owner, role, responseCommand, direction = "parent-to-child", metadataOnly = false) {
2154
+ const input = validateBridgeEnvelopeMetadata(value, owner, direction);
2155
+ return metadataOnly ? input : validateBridgeEnvelopeBody(input, role, responseCommand, direction);
2156
+ }
2157
+ /**
2158
+ * Validates owner identity, kind discriminators and bounded metadata size.
2159
+ * @returns Envelope record; payload/result remain unchecked.
2160
+ */
2161
+ function validateBridgeEnvelopeMetadata(value, owner, direction) {
2162
+ const input = wireRecord(value);
2163
+ if (input.kind === "request" && inspectionCommands.includes(input.command) && !wireId(owner.runtimeId)) invalid$1("Inspection requires an owned runtime");
2164
+ const keys = [
2165
+ "protocolVersion",
2166
+ "sessionId",
2167
+ "connectionId",
2168
+ "mountId",
2169
+ "sourceId",
2170
+ "epoch",
2171
+ "revision"
2172
+ ];
2173
+ const allowed = [
2174
+ ...keys,
2175
+ "runtimeId",
2176
+ "target",
2177
+ "selectionVersion",
2178
+ "kind",
2179
+ ...input.kind === "request" ? [
2180
+ "requestId",
2181
+ "command",
2182
+ "payload",
2183
+ "selectionRequestId"
2184
+ ] : input.kind === "response" ? [
2185
+ "requestId",
2186
+ "ok",
2187
+ "result",
2188
+ "error"
2189
+ ] : [
2190
+ "event",
2191
+ "sequence",
2192
+ "payload"
2193
+ ]
2194
+ ];
2195
+ if (Object.keys(input).some((key) => !allowed.includes(key))) invalid$1("Unknown bridge envelope field");
2196
+ const publication = input.kind === "event" && ["catalog.changed", "content.changed"].includes(input.event);
2197
+ const metadata = {};
2198
+ for (const key of keys) {
2199
+ metadata[key] = input[key];
2200
+ if (key === "protocolVersion" ? !Number.isSafeInteger(input[key]) || input[key] < 1 || input[key] !== owner[key] : !wireId(input[key]) || !(key === "revision" && publication) && input[key] !== owner[key]) invalid$1("Mismatched bridge owner/version");
2201
+ }
2202
+ if (input.runtimeId !== void 0) {
2203
+ if (!wireId(input.runtimeId) || owner.runtimeId !== void 0 && input.runtimeId !== owner.runtimeId) invalid$1("Mismatched runtime owner");
2204
+ metadata.runtimeId = input.runtimeId;
2205
+ } else if (owner.runtimeId !== void 0) invalid$1("Missing runtime owner");
2206
+ if (input.target !== void 0) {
2207
+ validateHistoireTarget(input.target);
2208
+ metadata.target = input.target;
2209
+ const target = input.target;
2210
+ if (!(input.kind === "request" && inspectionCommands.includes(input.command)) && owner.target && (target.storyId !== owner.target.storyId || target.variantId !== owner.target.variantId)) invalid$1("Mismatched runtime target");
2211
+ } else if (owner.target !== void 0) invalid$1("Missing runtime target");
2212
+ if (input.selectionVersion !== void 0) {
2213
+ if (!Number.isSafeInteger(input.selectionVersion) || input.selectionVersion < 0) invalid$1("Invalid selection generation");
2214
+ metadata.selectionVersion = input.selectionVersion;
2215
+ if (input.kind !== "event" && owner.selectionVersion !== void 0 && input.selectionVersion !== owner.selectionVersion) invalid$1("Mismatched selection generation");
2216
+ } else if (input.kind === "request" && inspectionCommands.includes(input.command) && owner.selectionVersion !== void 0) invalid$1("Missing selection generation");
2217
+ else if (input.kind === "request" && input.command === "selection.select" && direction === "child-to-parent" && owner.selectionVersion !== void 0) invalid$1("Missing selection generation");
2218
+ metadata.kind = input.kind;
2219
+ if (input.kind === "request") {
2220
+ if (!wireId(input.requestId) || !HISTOIRE_BRIDGE_COMMANDS.includes(input.command)) invalid$1("Invalid bridge request");
2221
+ metadata.requestId = input.requestId;
2222
+ metadata.command = input.command;
2223
+ if (input.selectionRequestId !== void 0) {
2224
+ if (!wireId(input.selectionRequestId) || input.command !== "view.sync" || direction !== "parent-to-child") invalid$1("Selection acknowledgment requires parent view sync");
2225
+ metadata.selectionRequestId = input.selectionRequestId;
2226
+ }
2227
+ } else if (input.kind === "response") {
2228
+ if (!wireId(input.requestId) || typeof input.ok !== "boolean") invalid$1("Invalid bridge response");
2229
+ metadata.requestId = input.requestId;
2230
+ metadata.ok = input.ok;
2231
+ } else if (input.kind === "event") {
2232
+ if (!HISTOIRE_BRIDGE_EVENTS.includes(input.event) || !Number.isSafeInteger(input.sequence) || input.sequence < 0) invalid$1("Invalid bridge event");
2233
+ metadata.event = input.event;
2234
+ metadata.sequence = input.sequence;
2235
+ } else invalid$1("Unknown bridge envelope kind");
2236
+ validateWireValue(metadata, {
2237
+ kind: "metadata",
2238
+ name: ""
2239
+ });
2240
+ return input;
2241
+ }
2242
+ /**
2243
+ * Validates payload/result/error and role authority of an envelope whose metadata
2244
+ * already passed `validateBridgeEnvelope(..., metadataOnly = true)` for the same object.
2245
+ * Each payload is measured once here; nested validators receive `measured` so they skip
2246
+ * re-measuring the same subtree under an identical or looser budget.
2247
+ */
2248
+ function validateBridgeEnvelopeBody(value, role, responseCommand, direction = "parent-to-child") {
2249
+ const input = wireRecord(value);
2250
+ if (input.kind === "request") {
2251
+ const command = input.command;
2252
+ validateWireValue(input.payload, {
2253
+ kind: "request",
2254
+ name: command
2255
+ });
2256
+ validateBridgePayload(command, input.payload, true);
2257
+ validateRole(role, command, wireRecord(input.payload), direction);
2258
+ if (inspectionCommands.includes(command)) {
2259
+ const target = wireRecord(input.target);
2260
+ const requested = wireRecord(wireRecord(input.payload).target);
2261
+ if (!wireId(input.runtimeId) || !wireId(target.variantId) || target.storyId !== requested.storyId || target.variantId !== requested.variantId) invalid$1("Inspection target does not match request");
2262
+ if (command === "inspection.highlightClear") {
2263
+ const expected = wireRecord(wireRecord(input.payload).expectedOwner);
2264
+ const expectedTarget = wireRecord(expected.target);
2265
+ if ([
2266
+ "sourceId",
2267
+ "epoch",
2268
+ "revision",
2269
+ "runtimeId"
2270
+ ].some((key) => expected[key] !== input[key]) || target.storyId !== expectedTarget.storyId || target.variantId !== expectedTarget.variantId) invalid$1("Highlight lease owner does not match request");
2271
+ }
2272
+ }
2273
+ } else if (input.kind === "response") {
2274
+ if (responseCommand?.startsWith("inspection.")) measureWireValue(input, { maxBytes: 65536 });
2275
+ if (input.ok) {
2276
+ if (!responseCommand) invalid$1("Successful response requires captured command");
2277
+ validateBridgeResult(responseCommand, input.result);
2278
+ if (inspectionCommands.includes(responseCommand)) {
2279
+ const resultOwner = wireRecord(wireRecord(input.result).owner);
2280
+ const target = wireRecord(input.target);
2281
+ const resultTarget = wireRecord(resultOwner.target);
2282
+ if ([
2283
+ "sourceId",
2284
+ "epoch",
2285
+ "revision",
2286
+ "runtimeId"
2287
+ ].some((key) => resultOwner[key] !== input[key]) || target.storyId !== resultTarget.storyId || target.variantId !== resultTarget.variantId) invalid$1("Mismatched inspection result owner");
2288
+ }
2289
+ } else validateHistoireErrorData(input.error);
2290
+ } else validateBridgeEventBody(input, role, direction);
2291
+ return input;
2292
+ }
2293
+ /** Event payload schema plus role/direction authority for one publication. */
2294
+ function validateBridgeEventBody(input, role, direction) {
2295
+ const event = input.event;
2296
+ validateWireValue(input.payload, {
2297
+ kind: "event",
2298
+ name: event
2299
+ });
2300
+ validateBridgeEventPayload(event, input.payload, true);
2301
+ if (event === "channel.message" || event === "plugin.message") {
2302
+ const payload = wireRecord(input.payload);
2303
+ const target = wireRecord(payload.target);
2304
+ if (role !== "primary" || direction !== "child-to-parent" || !wireId(input.runtimeId) || payload.runtimeId !== input.runtimeId || !input.target || target.storyId !== wireRecord(input.target).storyId) invalid$1("Application channel event requires exact primary document and story");
2305
+ }
2306
+ if (event === "focus.changed" && role === "primary") {
2307
+ if (direction !== "child-to-parent" || wireRecord(input.payload).direction !== void 0) invalid$1("Primary focus must come from owned document");
2308
+ } else if (event.startsWith("overlay.") || event === "controls.height" || event === "focus.changed") {
2309
+ if (role !== "controls") invalid$1("Controls event requires controls port");
2310
+ if (event === "overlay.result" !== (direction === "parent-to-child")) invalid$1("Controls event direction unavailable");
2311
+ }
2312
+ if (event === "catalog.changed") {
2313
+ const descriptor = wireRecord(wireRecord(input.payload).descriptor);
2314
+ for (const key of [
2315
+ "sourceId",
2316
+ "epoch",
2317
+ "revision"
2318
+ ]) if (descriptor[key] !== input[key]) invalid$1("Catalog publication identity mismatch");
2319
+ }
2320
+ }
2321
+ // src/bridge/handshake.ts
2322
+ /** Requires finite positive supported protocol interval. */
2323
+ function validateHistoireProtocolRange(value) {
2324
+ const input = wireRecord(value);
2325
+ if (Object.keys(input).some((key) => !["min", "max"].includes(key)) || !Number.isSafeInteger(input.min) || !Number.isSafeInteger(input.max) || input.min < 1 || input.max < input.min) invalid$1("Invalid protocol range");
2326
+ return input;
2327
+ }
2328
+ /** Chooses highest common version, with both ranges in typed failure. */
2329
+ function negotiateHistoireProtocol(host, book) {
2330
+ validateHistoireProtocolRange(host);
2331
+ validateHistoireProtocolRange(book);
2332
+ const version = Math.min(host.max, book.max);
2333
+ if (version < Math.max(host.min, book.min)) throw new HistoireSdkError("PROTOCOL_MISMATCH", `Host protocol ${host.min}–${host.max}; book protocol ${book.min}–${book.max}`);
2334
+ return version;
2335
+ }
2336
+ /** Validates bounded hello before accessing any untrusted bootstrap fields. */
2337
+ function validateHistoireHello(value) {
2338
+ validateWireValue(value, {
2339
+ kind: "metadata",
2340
+ name: ""
2341
+ });
2342
+ const input = wireRecord(value);
2343
+ if (Object.keys(input).some((key) => ![
2344
+ "kind",
2345
+ "protocolRange",
2346
+ "nonce",
2347
+ "sessionId",
2348
+ "mountId",
2349
+ "parentOrigin",
2350
+ "role"
2351
+ ].includes(key)) || input.kind !== "histoire:hello" || ![
2352
+ "data",
2353
+ "primary",
2354
+ "controls",
2355
+ "view"
2356
+ ].includes(input.role)) invalid$1("Invalid handshake hello");
2357
+ for (const key of [
2358
+ "nonce",
2359
+ "sessionId",
2360
+ "mountId"
2361
+ ]) if (!wireId(input[key])) invalid$1("Invalid handshake identity");
2362
+ validateHistoireProtocolRange(input.protocolRange);
2363
+ validateEmbedOrigin(input.parentOrigin);
2364
+ return input;
2365
+ }
2366
+ /** Validates descriptor separately from small handshake metadata. */
2367
+ function validateHistoireAck(value, hello) {
2368
+ const input = wireRecord(value);
2369
+ if (Object.keys(input).some((key) => ![
2370
+ "kind",
2371
+ "nonce",
2372
+ "protocolRange",
2373
+ "ok",
2374
+ "owner",
2375
+ "descriptor",
2376
+ "error"
2377
+ ].includes(key)) || input.kind !== "histoire:ack" || input.nonce !== hello.nonce || typeof input.ok !== "boolean") invalid$1("Invalid handshake acknowledgment");
2378
+ const range = validateHistoireProtocolRange(input.protocolRange);
2379
+ if (!input.ok) validateHistoireErrorData(input.error);
2380
+ else {
2381
+ const owner = wireRecord(input.owner);
2382
+ const version = negotiateHistoireProtocol(hello.protocolRange, range);
2383
+ if (owner.protocolVersion !== version || owner.sessionId !== hello.sessionId || owner.mountId !== hello.mountId) invalid$1("Mismatched handshake owner/version");
2384
+ for (const key of [
2385
+ "connectionId",
2386
+ "sourceId",
2387
+ "epoch",
2388
+ "revision"
2389
+ ]) if (!wireId(owner[key])) invalid$1("Invalid handshake owner");
2390
+ if (owner.selectionVersion !== void 0 && (!Number.isSafeInteger(owner.selectionVersion) || owner.selectionVersion < 0)) invalid$1("Invalid handshake selection generation");
2391
+ if (Object.keys(owner).some((key) => ![
2392
+ "protocolVersion",
2393
+ "sessionId",
2394
+ "mountId",
2395
+ "connectionId",
2396
+ "sourceId",
2397
+ "epoch",
2398
+ "revision",
2399
+ "selectionVersion"
2400
+ ].includes(key))) invalid$1("Unknown handshake owner field");
2401
+ const descriptor = validateHistoireSourceDescriptor(input.descriptor);
2402
+ for (const key of [
2403
+ "sourceId",
2404
+ "epoch",
2405
+ "revision"
2406
+ ]) if (owner[key] !== descriptor[key]) invalid$1("Mismatched handshake descriptor");
2407
+ if (descriptor.protocolVersion !== version) invalid$1("Mismatched descriptor protocol");
2408
+ }
2409
+ validateWireValue({
2410
+ kind: input.kind,
2411
+ nonce: input.nonce,
2412
+ protocolRange: input.protocolRange,
2413
+ ok: input.ok,
2414
+ ...input.ok ? { owner: input.owner } : { error: input.error }
2415
+ }, {
2416
+ kind: "metadata",
2417
+ name: ""
2418
+ });
2419
+ return input;
2420
+ }
2421
+ // src/types/common.ts
2422
+ /** All independently mountable first-party surfaces. */
2423
+ var HISTOIRE_SURFACES = [
2424
+ "explorer",
2425
+ "preview",
2426
+ "tree",
2427
+ "search",
2428
+ "toolbar",
2429
+ "controls",
2430
+ "docs",
2431
+ "source",
2432
+ "events",
2433
+ "tests"
2434
+ ];
2435
+ /** Injective tuple encoding; never parse separator-concatenated IDs. */
2436
+ function getHistoireTargetKey(target) {
2437
+ return JSON.stringify([target.storyId, target.variantId]);
2438
+ }
2439
+ // src/bridge/project-test-collection.ts
2440
+ /** Validate bounded collection evidence, optionally requiring the complete admitted target inventory. */
2441
+ function validateProjectTestCollection(value, targets) {
2442
+ validateWireValue(value, {
2443
+ kind: "response",
2444
+ name: "tests.collect"
2445
+ });
2446
+ const input = wireRecord(value);
2447
+ validateHistoireTestExecution(input.execution);
2448
+ if (input.execution.mode !== "server") invalid$1("Invalid project collection engine");
2449
+ if (!Array.isArray(input.variants)) invalid$1("Invalid project test collection");
2450
+ const seen = /* @__PURE__ */ new Set();
2451
+ for (const item of input.variants) {
2452
+ const entry = wireRecord(item);
2453
+ validateHistoireTarget(entry.target);
2454
+ const target = entry.target;
2455
+ if (target.variantId === null) invalid$1("Project collection requires variant identity");
2456
+ const key = getHistoireTargetKey(target);
2457
+ if (seen.has(key)) invalid$1("Duplicate project collection target");
2458
+ seen.add(key);
2459
+ validateHistoireTestResult(entry.collection, false);
2460
+ }
2461
+ if (targets) {
2462
+ const admitted = new Set(targets.map(getHistoireTargetKey));
2463
+ if (seen.size !== admitted.size || [...seen].some((key) => !admitted.has(key))) invalid$1("Test discovery target inventory changed");
2464
+ }
2465
+ }
2466
+ // src/geometry.ts
2467
+ /** Positive intersection; fully clipped content has no published viewport. */
2468
+ function intersectRuntimeRects(left, right) {
2469
+ const x = Math.max(left.x, right.x);
2470
+ const y = Math.max(left.y, right.y);
2471
+ const width = Math.min(left.x + left.width, right.x + right.width) - x;
2472
+ const height = Math.min(left.y + left.height, right.y + right.height) - y;
2473
+ return width > 0 && height > 0 ? {
2474
+ x,
2475
+ y,
2476
+ width,
2477
+ height
2478
+ } : null;
2479
+ }
2480
+ /** Compose sandbox offsets/scales into source surface padding-box coordinates. */
2481
+ function mapRuntimeViewport(viewport, frame, logical, clip) {
2482
+ const scaleX = frame.width / logical.width;
2483
+ const scaleY = frame.height / logical.height;
2484
+ /** Transform one rectangle through iframe rendered dimensions. */
2485
+ function map(rect) {
2486
+ return {
2487
+ x: frame.x + rect.x * scaleX,
2488
+ y: frame.y + rect.y * scaleY,
2489
+ width: rect.width * scaleX,
2490
+ height: rect.height * scaleY
2491
+ };
2492
+ }
2493
+ const visibleRect = intersectRuntimeRects(map(viewport.visibleRect), clip);
2494
+ return visibleRect ? {
2495
+ ...map(viewport),
2496
+ target: viewport.target,
2497
+ scale: viewport.scale * scaleX,
2498
+ visibleRect
2499
+ } : null;
2500
+ }
2501
+ // src/helpers/meta.ts
2502
+ /** Keys never copied: they could poison prototypes of consumers merging metadata. */
2503
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set([
2504
+ "__proto__",
2505
+ "prototype",
2506
+ "constructor"
2507
+ ]);
2508
+ /** Thrown inside the copy once a budget is exceeded, unwinding the recursion at once. */
2509
+ var OVER_BUDGET = Symbol("over budget");
2510
+ /**
2511
+ * Whether a value is an object literal (or `Object.create(null)`); class instances, dates,
2512
+ * components and arrays are excluded.
2513
+ * @param value Candidate.
2514
+ */
2515
+ function isPlainObject(value) {
2516
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2517
+ const prototype = Object.getPrototypeOf(value);
2518
+ return prototype === Object.prototype || prototype === null;
2519
+ }
2520
+ /**
2521
+ * Adds JSON bytes to the copy, abandoning it past the per-meta byte bound.
2522
+ * @param budget Running totals.
2523
+ * @param amount Bytes to add.
2524
+ */
2525
+ function charge(budget, amount) {
2526
+ budget.bytes += amount;
2527
+ if (budget.bytes > HISTOIRE_META_LIMITS.bytes) throw OVER_BUDGET;
2528
+ }
2529
+ /**
2530
+ * Counts one copied JSON value, abandoning the copy past the per-meta node bound.
2531
+ * @param budget Running totals.
2532
+ */
2533
+ function countNode(budget) {
2534
+ if (++budget.nodes > HISTOIRE_META_LIMITS.nodes) throw OVER_BUDGET;
2535
+ }
2536
+ /**
2537
+ * Deep-copies one value keeping only JSON data. Returns `undefined` for values JSON cannot
2538
+ * carry (functions, symbols, non-finite numbers, class instances), for cyclic references and
2539
+ * for values deeper than `HISTOIRE_META_LIMITS.depth`. Shared references are copied (and
2540
+ * charged) once per occurrence, like `JSON.stringify` would, so DAGs hit the node bound early.
2541
+ * @param value Collected value.
2542
+ * @param depth Nesting depth of `value` (root is 0).
2543
+ * @param budget Running totals; throws {@link OVER_BUDGET} when exceeded.
2544
+ */
2545
+ function copyJson(value, depth, budget) {
2546
+ if (depth > HISTOIRE_META_LIMITS.depth || typeof value === "number" && !Number.isFinite(value)) return;
2547
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
2548
+ countNode(budget);
2549
+ charge(budget, typeof value === "string" ? countWireString(value, true, HISTOIRE_META_LIMITS.bytes - budget.bytes) : String(value).length);
2550
+ return value;
2551
+ }
2552
+ if (!value || typeof value !== "object" || budget.ancestors.has(value)) return;
2553
+ if (!Array.isArray(value) && !isPlainObject(value)) return;
2554
+ countNode(budget);
2555
+ const container = value;
2556
+ budget.ancestors.add(container);
2557
+ charge(budget, 2);
2558
+ let result;
2559
+ if (Array.isArray(container)) {
2560
+ const items = [];
2561
+ for (const item of container) {
2562
+ const copy = copyJson(item, depth + 1, budget);
2563
+ if (copy === void 0) continue;
2564
+ charge(budget, 1);
2565
+ items.push(copy);
2566
+ }
2567
+ result = Object.freeze(items);
2568
+ } else {
2569
+ const record = {};
2570
+ for (const [key, item] of Object.entries(container)) {
2571
+ if (UNSAFE_KEYS.has(key)) continue;
2572
+ const copy = copyJson(item, depth + 1, budget);
2573
+ if (copy === void 0) continue;
2574
+ charge(budget, countWireString(key, true, HISTOIRE_META_LIMITS.bytes - budget.bytes) + 2);
2575
+ record[key] = copy;
2576
+ }
2577
+ result = Object.freeze(record);
2578
+ }
2579
+ budget.ancestors.delete(container);
2580
+ return result;
2581
+ }
2582
+ /**
2583
+ * Projects collected `meta` to immutable JSON data without evaluating it. Non-JSON entries
2584
+ * (callbacks, components), cycles and values deeper than `HISTOIRE_META_LIMITS.depth` are
2585
+ * dropped; an empty or non-object result has no `meta`. The copy stops as soon as it exceeds
2586
+ * `HISTOIRE_META_LIMITS` bytes or nodes and reports `tooLarge`, so callers can warn.
2587
+ * @param value Story or variant `meta` as collected.
2588
+ */
2589
+ function normalizeHistoireMeta(value) {
2590
+ if (!isPlainObject(value)) return {};
2591
+ const budget = {
2592
+ bytes: 0,
2593
+ nodes: 0,
2594
+ ancestors: /* @__PURE__ */ new Set()
2595
+ };
2596
+ let copy;
2597
+ try {
2598
+ copy = copyJson(value, 0, budget);
2599
+ } catch (error) {
2600
+ if (error === OVER_BUDGET) return { tooLarge: true };
2601
+ throw error;
2602
+ }
2603
+ return Object.keys(copy).length ? {
2604
+ meta: copy,
2605
+ bytes: budget.bytes,
2606
+ nodes: budget.nodes
2607
+ } : {};
2608
+ }
2609
+ // src/helpers/story-route.ts
2610
+ /** Resolve exact route identity, preferring normal path over dot-ID query fallback. */
2611
+ function resolveStoryRouteId(params, query) {
2612
+ if (typeof params.storyId === "string" && params.storyId) return params.storyId;
2613
+ return typeof query.storyId === "string" && /^\.+$/.test(query.storyId) ? query.storyId : void 0;
2614
+ }
2615
+ /** Decode URL query once without collapsing bare `?variantId` into an empty string. */
2616
+ function parseStoryRouteQuery(search) {
2617
+ const query = Object.create(null);
2618
+ for (const pair of search.replace(/^\?/, "").split("&")) {
2619
+ if (!pair) continue;
2620
+ new URLSearchParams(pair).forEach((decoded, key) => {
2621
+ const value = pair.includes("=") ? decoded : null;
2622
+ const previous = query[key];
2623
+ if (previous === void 0) query[key] = value;
2624
+ else if (previous === null) query[key] = [null, value];
2625
+ else if (typeof previous === "string") query[key] = [previous, value];
2626
+ else query[key] = [...previous, value];
2627
+ });
2628
+ }
2629
+ return query;
2630
+ }
2631
+ /** Resolve shared path/query identity and keep omitted variants distinct from explicit null. */
2632
+ function resolveStoryRouteSelection(params, query) {
2633
+ const storyId = resolveStoryRouteId(params, query);
2634
+ if (!storyId) return;
2635
+ const variantId = query.variantId;
2636
+ if (variantId === null) return {
2637
+ storyId,
2638
+ variantId: null
2639
+ };
2640
+ return {
2641
+ storyId,
2642
+ ...typeof variantId === "string" ? { variantId } : {}
2643
+ };
2644
+ }
2645
+ /** Hash routes support both normal path IDs and dot-only query identities. */
2646
+ function isStoryRouteHash(hash) {
2647
+ return /^#\/story(?:[/?]|$)/.test(hash);
2648
+ }
2649
+ /** Named story route supports safe query selection for dot-only identities. */
2650
+ var STORY_ROUTE_PATH = "/story/:storyId?";
2651
+ // src/inspection/debug-buffer.ts
2652
+ /** Bounded detached timeline; sequence numbers also account for omitted entries. */
2653
+ function createDebugBuffer(options = {}) {
2654
+ const rows = [];
2655
+ const encoder = new TextEncoder();
2656
+ const maxEntries = options.maxEntries ?? 1e3;
2657
+ const maxBytes = options.maxBytes ?? 1048576;
2658
+ let sequence = 0;
2659
+ let bytes = 0;
2660
+ let droppedCount = 0;
2661
+ /** Measure serialized UTF-8 including escaped strings and metadata. */
2662
+ function size(value) {
2663
+ return encoder.encode(JSON.stringify(value)).byteLength;
2664
+ }
2665
+ return {
2666
+ /** Latest allocated sequence including dropped observations. */
2667
+ cursor() {
2668
+ return sequence;
2669
+ },
2670
+ /** Add only detached complete entries within the per-entry bound. */
2671
+ add(value) {
2672
+ const entry = {
2673
+ ...value,
2674
+ sequence: ++sequence,
2675
+ message: value.message.slice(0, 2048)
2676
+ };
2677
+ while (size(entry) > 4096 && entry.message.length) entry.message = entry.message.slice(0, Math.floor(entry.message.length / 2));
2678
+ const length = size(entry);
2679
+ if (length > 4096 || length > maxBytes) {
2680
+ droppedCount++;
2681
+ return;
2682
+ }
2683
+ rows.push({
2684
+ entry: structuredClone(entry),
2685
+ bytes: length
2686
+ });
2687
+ bytes += length;
2688
+ while (rows.length > maxEntries || bytes > maxBytes) {
2689
+ bytes -= rows.shift().bytes;
2690
+ droppedCount++;
2691
+ }
2692
+ },
2693
+ /** Count observations omitted before retention and reserve their sequence numbers. */
2694
+ drop(count = 1) {
2695
+ if (!Number.isSafeInteger(count) || count < 0 || !Number.isSafeInteger(sequence + count)) throw new Error("Invalid diagnostic loss count");
2696
+ sequence += count;
2697
+ droppedCount += count;
2698
+ },
2699
+ /** Return a complete bounded page with loss and continuation metadata. */
2700
+ read(input = {}) {
2701
+ const after = input.afterSequence ?? 0;
2702
+ const limit = input.limit ?? 100;
2703
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("Invalid diagnostic cursor or limit");
2704
+ const oldestSequence = rows[0]?.entry.sequence ?? sequence + 1;
2705
+ const items = [];
2706
+ let cursor = after;
2707
+ let gap = false;
2708
+ for (const row of rows) {
2709
+ if (row.entry.sequence <= after) continue;
2710
+ if (items.length >= limit) break;
2711
+ const candidate = [...items, row.entry];
2712
+ const candidateGap = gap || row.entry.sequence > cursor + 1;
2713
+ if (size({
2714
+ items: candidate,
2715
+ nextSequence: row.entry.sequence,
2716
+ oldestSequence,
2717
+ droppedCount,
2718
+ gap: candidateGap
2719
+ }) > 45056) break;
2720
+ gap = candidateGap;
2721
+ cursor = row.entry.sequence;
2722
+ items.push(row.entry);
2723
+ }
2724
+ if (!items.length && sequence > after) {
2725
+ gap = true;
2726
+ cursor = sequence;
2727
+ }
2728
+ return structuredClone({
2729
+ items,
2730
+ nextSequence: cursor,
2731
+ oldestSequence,
2732
+ droppedCount,
2733
+ gap
2734
+ });
2735
+ },
2736
+ /** Discard retained rows without recycling identities or hiding their loss. */
2737
+ clear() {
2738
+ droppedCount += rows.length;
2739
+ rows.length = 0;
2740
+ bytes = 0;
2741
+ }
2742
+ };
2743
+ }
2744
+ // src/serialization/controls-revision.ts
2745
+ /** One controls document owns revision counter; source wrapper keeps admitted watermark. */
2746
+ function createControlsStateRevision() {
2747
+ let revision = 0;
2748
+ /** Optional field (primary frames omit it); present revisions must be finite counters. */
2749
+ function valid(value) {
2750
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2751
+ }
2752
+ return {
2753
+ /** Last captured local edit or admitted child edit for this document only. */
2754
+ get current() {
2755
+ return revision;
2756
+ },
2757
+ /** Stamp edit before asynchronous postMessage can cross wrapper boundary. */
2758
+ capture() {
2759
+ if (revision === Number.MAX_SAFE_INTEGER) throw new HistoireSdkError("INVALID_ARGUMENT", "Controls revision exhausted");
2760
+ return ++revision;
2761
+ },
2762
+ /** Admit each child edit once, rejecting replay and malformed counters. */
2763
+ receive(value) {
2764
+ if (value === void 0) return true;
2765
+ if (!valid(value) || value <= revision) return false;
2766
+ revision = value;
2767
+ return true;
2768
+ },
2769
+ /** New typing already captured locally makes older acknowledgment inapplicable. */
2770
+ accept(value) {
2771
+ return value === void 0 || valid(value) && value === revision;
2772
+ }
2773
+ };
2774
+ }
2775
+ // src/serialization/state.ts
2776
+ /** Returns whether a value can contain fields that need reconciliation. */
2777
+ function isContainer(value) {
2778
+ return value !== null && typeof value === "object";
2779
+ }
2780
+ /**
2781
+ * Applies serializable fields without replacing runtime-owned objects or callbacks.
2782
+ * Unlike local applyState, the source has lost functions and prototypes in transit:
2783
+ * assigning a whole nested object or array would erase those values in the iframe.
2784
+ * Returns whether any reactive field changed, so an unchanged snapshot arms no echo guard.
2785
+ * Reset additionally prunes added serializable fields while retaining opaque owners.
2786
+ */
2787
+ function applySerializedState(target, source, reset = false) {
2788
+ const seen = /* @__PURE__ */ new WeakMap();
2789
+ let changed = false;
2790
+ /** Non-enumerable/symbol keys are absent from wire projection and remain local. */
2791
+ function hasHiddenOwner(value) {
2792
+ return Reflect.ownKeys(value).some((key) => typeof key === "symbol" || key !== "length" && !Object.getOwnPropertyDescriptor(value, key)?.enumerable);
2793
+ }
2794
+ /** Detect protected descendants before pruning so cyclic ownership remains intact. */
2795
+ function hasOpaque(value, visited = /* @__PURE__ */ new WeakSet()) {
2796
+ if (typeof value === "function" || typeof value === "symbol") return true;
2797
+ if (!isContainer(value) || visited.has(value)) return false;
2798
+ visited.add(value);
2799
+ const prototype = Object.getPrototypeOf(value);
2800
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return true;
2801
+ if (hasHiddenOwner(value)) return true;
2802
+ return Object.values(value).some((child) => hasOpaque(child, visited));
2803
+ }
2804
+ /** Reset may remove added serializable data, but cannot remove nested live owners. */
2805
+ function retainOpaque(container, key, visited = /* @__PURE__ */ new WeakSet()) {
2806
+ const value = container[key];
2807
+ if (typeof value === "function" || typeof value === "symbol") return true;
2808
+ if (isContainer(value)) {
2809
+ const prototype = Object.getPrototypeOf(value);
2810
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return true;
2811
+ if (visited.has(value)) return hasOpaque(value);
2812
+ visited.add(value);
2813
+ let retained = hasHiddenOwner(value);
2814
+ for (const child of Object.keys(value).reverse()) if (retainOpaque(value, child, visited)) retained = true;
2815
+ else try {
2816
+ if (Array.isArray(value) && /^\d+$/.test(child)) value.splice(Number(child), 1);
2817
+ else delete value[child];
2818
+ changed = true;
2819
+ } catch {
2820
+ retained = true;
2821
+ }
2822
+ return retained;
2823
+ }
2824
+ return false;
2825
+ }
2826
+ /** Writes one field, preserving the existing tolerance for readonly story state. */
2827
+ function assign(container, key, value) {
2828
+ if (Object.is(container[key], value)) return;
2829
+ try {
2830
+ container[key] = value;
2831
+ changed = true;
2832
+ } catch {}
2833
+ }
2834
+ /** Reconciles one field, retaining the target's local identity and prototype. */
2835
+ function mergeField(container, key, value, replaceMissing) {
2836
+ const current = container[key];
2837
+ if (typeof current === "function" || typeof current === "symbol") return;
2838
+ const prototype = isContainer(current) ? Object.getPrototypeOf(current) : void 0;
2839
+ if (isContainer(current) && !Array.isArray(current) && prototype !== Object.prototype && prototype !== null && (!isContainer(value) || Array.isArray(value) || seen.has(value))) return;
2840
+ if (!isContainer(value)) {
2841
+ assign(container, key, value);
2842
+ return;
2843
+ }
2844
+ if (seen.has(value)) {
2845
+ assign(container, key, seen.get(value));
2846
+ return;
2847
+ }
2848
+ const compatible = isContainer(current) && Array.isArray(current) === Array.isArray(value);
2849
+ const next = compatible ? current : Array.isArray(value) ? [] : {};
2850
+ merge(next, value, replaceMissing);
2851
+ if (!compatible) assign(container, key, next);
2852
+ }
2853
+ /** Walks a snapshot once, including cycles and arrays containing omitted functions. */
2854
+ function merge(current, incoming, replaceMissing = false) {
2855
+ seen.set(incoming, current);
2856
+ if (Array.isArray(current) && Array.isArray(incoming)) {
2857
+ const positions = current.flatMap((value, index) => typeof value === "function" ? [] : [index]);
2858
+ for (let index = 0; index < incoming.length; index++) mergeField(current, positions[index] ?? current.length, incoming[index], true);
2859
+ for (const index of positions.slice(incoming.length).reverse()) {
2860
+ if (reset && retainOpaque(current, index)) continue;
2861
+ current.splice(index, 1);
2862
+ changed = true;
2863
+ }
2864
+ return;
2865
+ }
2866
+ for (const key of Object.keys(incoming)) {
2867
+ if (reset && key === "_hPropDefs") continue;
2868
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
2869
+ mergeField(current, key, incoming[key], replaceMissing || key.startsWith("_h"));
2870
+ }
2871
+ if (replaceMissing) for (const key of Object.keys(current)) {
2872
+ if (Object.hasOwn(incoming, key) || typeof current[key] === "function" || reset && (key === "_hPropDefs" || retainOpaque(current, key))) continue;
2873
+ try {
2874
+ if (delete current[key]) changed = true;
2875
+ } catch {}
2876
+ }
2877
+ }
2878
+ if (isContainer(target) && isContainer(source)) merge(target, source, reset);
2879
+ return changed;
2880
+ }
2881
+ // src/serialization/test-errors.ts
2882
+ /** Narrows runtime exception-like values before explicit projection. */
2883
+ function hasProperty(value, key) {
2884
+ return !!value && typeof value === "object" && key in value;
2885
+ }
2886
+ /** Coerces an arbitrary value to a structured-clone / JSON-safe form so it can cross postMessage/WS boundaries. */
2887
+ function toSerializableRaw(value) {
2888
+ if (value === void 0) return void 0;
2889
+ try {
2890
+ return JSON.parse(JSON.stringify(value));
2891
+ } catch {
2892
+ try {
2893
+ return String(value);
2894
+ } catch {
2895
+ return;
2896
+ }
2897
+ }
2898
+ }
2899
+ /** Projects runtime error while omitting absent fields required by JSON DTOs. */
2900
+ function serializeTestError(error) {
2901
+ if (error instanceof Error) {
2902
+ const payload = error;
2903
+ const raw = toSerializableRaw(payload.cause);
2904
+ return {
2905
+ name: payload.name || "Error",
2906
+ message: payload.message || error.toString(),
2907
+ ...payload.stack === void 0 ? {} : { stack: payload.stack },
2908
+ ...typeof payload.diff === "string" ? { diff: payload.diff } : {},
2909
+ ...raw === void 0 ? {} : { raw }
2910
+ };
2911
+ }
2912
+ if (error === null || error === void 0) return { message: "Unknown error" };
2913
+ if (typeof error === "string") return { message: error };
2914
+ if (hasProperty(error, "message")) {
2915
+ const rawMessage = String(hasProperty(error, "message") ? error.message : "");
2916
+ const name = hasProperty(error, "name") ? String(error.name) : void 0;
2917
+ const stack = hasProperty(error, "stack") ? String(error.stack ?? "") || void 0 : void 0;
2918
+ const diff = hasProperty(error, "diff") ? String(error.diff ?? "") || void 0 : void 0;
2919
+ const raw = toSerializableRaw(error.raw);
2920
+ return {
2921
+ message: rawMessage || "Unknown error",
2922
+ ...name === void 0 ? {} : { name },
2923
+ ...stack === void 0 ? {} : { stack },
2924
+ ...diff === void 0 ? {} : { diff },
2925
+ ...raw === void 0 ? {} : { raw }
2926
+ };
2927
+ }
2928
+ return { message: String(error) };
2929
+ }
2930
+ /** Applies same projection to every lifecycle/assertion error. */
2931
+ function serializeTestErrors(errors) {
2932
+ return errors.map(serializeTestError);
2933
+ }
2934
+ var ANSI_PATTERN = /\u001B\[\d*(?:;\d+)*m/g;
2935
+ /** Removes ANSI color escapes — node-side Vitest colorizes diffs for TTYs. */
2936
+ function stripAnsi(value) {
2937
+ return value.replace(ANSI_PATTERN, "");
2938
+ }
2939
+ /** Renders transported failure text while stripping terminal-only color escapes. */
2940
+ function formatTestError(error) {
2941
+ if (typeof error === "string") return stripAnsi(error);
2942
+ return [
2943
+ error.message,
2944
+ error.stack,
2945
+ error.diff
2946
+ ].filter(Boolean).map((part) => stripAnsi(String(part))).join("\n\n");
2947
+ }
2948
+ // src/theme/color.ts
2949
+ var value = "[+-]?(?:\\d+|\\d*\\.\\d+)%?";
2950
+ var separator = "(?:\\s*,\\s*|\\s+)";
2951
+ var alpha = `(?:\\s*[,/]\\s*(${value}))?`;
2952
+ var rgb = new RegExp(`^rgba?\\(\\s*(${value})${separator}(${value})${separator}(${value})${alpha}\\s*\\)$`, "i");
2953
+ var hsl = new RegExp(`^hsla?\\(\\s*([+-]?(?:\\d+|\\d*\\.\\d+)(?:deg|rad|grad|turn)?)${separator}(${value})${separator}(${value})${alpha}\\s*\\)$`, "i");
2954
+ /** Dependency-free CSS color parser shared by Node theme output and native providers. */
2955
+ function parseColor(input) {
2956
+ if (typeof input !== "string") return null;
2957
+ const text = input.trim();
2958
+ if (text.toLowerCase() === "transparent") return {
2959
+ mode: "rgb",
2960
+ color: [
2961
+ "0",
2962
+ "0",
2963
+ "0"
2964
+ ],
2965
+ alpha: "0"
2966
+ };
2967
+ const hex = (/^#[a-f\d]{3,4}$/i.test(text) ? `#${[...text.slice(1)].map((value) => value + value).join("")}` : text).match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i);
2968
+ if (hex) return {
2969
+ mode: "rgb",
2970
+ color: hex.slice(1, 4).map((part) => Number.parseInt(part, 16).toString()),
2971
+ alpha: hex[4] ? (Number.parseInt(hex[4], 16) / 255).toString() : void 0
2972
+ };
2973
+ const matched = text.match(rgb) ?? text.match(hsl);
2974
+ if (!matched) return null;
2975
+ return {
2976
+ mode: /^rgb/i.test(text) ? "rgb" : "hsl",
2977
+ color: matched.slice(1, 4),
2978
+ alpha: matched[4]
2979
+ };
2980
+ }
2981
+ /** Convert HSL/percent RGB to numeric RGB channels; CSS alpha remains independent of utility opacity. */
2982
+ function getHistoireColorChannels(parsed) {
2983
+ const opacity = parsed.alpha === void 0 ? 1 : Number.parseFloat(parsed.alpha) / (parsed.alpha.endsWith("%") ? 100 : 1);
2984
+ let channels;
2985
+ if (parsed.mode === "rgb") channels = parsed.color.map((value) => Number.parseFloat(value) * (value.endsWith("%") ? 2.55 : 1));
2986
+ else {
2987
+ const hue = parsed.color[0];
2988
+ const unit = hue.match(/(?:deg|rad|grad|turn)$/i)?.[0].toLowerCase();
2989
+ const normalizedHue = (Number.parseFloat(hue) * (unit === "rad" ? 180 / Math.PI : unit === "grad" ? .9 : unit === "turn" ? 360 : 1) % 360 + 360) % 360 / 60;
2990
+ const saturation = Math.max(0, Math.min(1, Number.parseFloat(parsed.color[1]) / 100));
2991
+ const lightness = Math.max(0, Math.min(1, Number.parseFloat(parsed.color[2]) / 100));
2992
+ const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
2993
+ const secondary = chroma * (1 - Math.abs(normalizedHue % 2 - 1));
2994
+ const offset = lightness - chroma / 2;
2995
+ channels = [
2996
+ [
2997
+ chroma,
2998
+ secondary,
2999
+ 0
3000
+ ],
3001
+ [
3002
+ secondary,
3003
+ chroma,
3004
+ 0
3005
+ ],
3006
+ [
3007
+ 0,
3008
+ chroma,
3009
+ secondary
3010
+ ],
3011
+ [
3012
+ 0,
3013
+ secondary,
3014
+ chroma
3015
+ ],
3016
+ [
3017
+ secondary,
3018
+ 0,
3019
+ chroma
3020
+ ],
3021
+ [
3022
+ chroma,
3023
+ 0,
3024
+ secondary
3025
+ ]
3026
+ ][Math.floor(normalizedHue)].map((value) => (value + offset) * 255);
3027
+ }
3028
+ return {
3029
+ channels: channels.map((value) => String(Math.round(Math.max(0, Math.min(255, value)) * 1e3) / 1e3)).join(" "),
3030
+ alpha: String(Math.max(0, Math.min(1, opacity)))
3031
+ };
3032
+ }
3033
+ // src/theme/semantic.ts
3034
+ /** Default source neutral palette, distinct from authored C1 semantic surfaces. */
3035
+ var histoireDefaultNeutralColors = {
3036
+ 50: "#fafafa",
3037
+ 100: "#f4f4f5",
3038
+ 200: "#e4e4e7",
3039
+ 300: "#d4d4d8",
3040
+ 400: "#a1a1aa",
3041
+ 500: "#71717a",
3042
+ 600: "#52525b",
3043
+ 700: "#3f3f46",
3044
+ 750: "#323238",
3045
+ 800: "#27272a",
3046
+ 850: "#1f1f21",
3047
+ 900: "#18181b",
3048
+ 950: "#101012"
3049
+ };
3050
+ /** Default source accent palette used by utility colors and project overrides. */
3051
+ var histoireDefaultAccentColors = {
3052
+ 50: "#ecfdf5",
3053
+ 100: "#d1fae5",
3054
+ 200: "#a7f3d0",
3055
+ 300: "#6ee7b7",
3056
+ 400: "#34d399",
3057
+ 500: "#10b981",
3058
+ 600: "#059669",
3059
+ 700: "#047857",
3060
+ 800: "#065f46",
3061
+ 900: "#064e3b"
3062
+ };
3063
+ /** Source shade mapping shared by native providers and generated workbench CSS. */
3064
+ var lightShades = {
3065
+ primary: {
3066
+ "accent": "500",
3067
+ "accent-soft": "50",
3068
+ "accent-text": "800",
3069
+ "accent-link": "700"
3070
+ },
3071
+ gray: {
3072
+ canvas: "100",
3073
+ home: "50",
3074
+ surface: "50",
3075
+ border: "200",
3076
+ chip: "100",
3077
+ input: "50",
3078
+ text: "900",
3079
+ body: "700",
3080
+ muted: "500"
3081
+ }
3082
+ };
3083
+ /** Dark soft accents retain C1's authored twelve-percent tint. */
3084
+ var darkShades = {
3085
+ primary: {
3086
+ "accent": "400",
3087
+ "accent-soft": "400",
3088
+ "accent-link": "400"
3089
+ },
3090
+ gray: {
3091
+ canvas: "950",
3092
+ home: "950",
3093
+ surface: "900",
3094
+ border: "800",
3095
+ chip: "850",
3096
+ input: "950",
3097
+ text: "200",
3098
+ body: "300",
3099
+ muted: "400"
3100
+ }
3101
+ };
3102
+ /** Emit customized shades only; resolved default source colors must not replace C1 defaults. */
3103
+ function getHistoireSemanticThemeOverrides(colors = {}, dark = false) {
3104
+ const variables = {};
3105
+ const shades = dark ? darkShades : lightShades;
3106
+ for (const color of ["primary", "gray"]) {
3107
+ const defaults = color === "primary" ? histoireDefaultAccentColors : histoireDefaultNeutralColors;
3108
+ for (const [semantic, shade] of Object.entries(shades[color])) {
3109
+ const input = colors[color]?.[shade];
3110
+ if (!input || !parseColor(input) || input === defaults[shade]) continue;
3111
+ variables[`--histoire-${semantic}-rgb`] = `var(--_histoire-color-${color}-${shade})`;
3112
+ if (semantic !== "accent-soft" || !dark) variables[`--histoire-${semantic}-alpha`] = `var(--_histoire-color-${color}-${shade}-alpha, 1)`;
3113
+ }
3114
+ }
3115
+ return variables;
3116
+ }
3117
+ // src/types/catalog.ts
3118
+ /** Legacy descriptors omitted provenance and represented ordinary project stories. */
3119
+ function isHistoireProjectFileOrigin(origin) {
3120
+ return origin === void 0 || origin === "project";
3121
+ }
3122
+ // src/types/controls.ts
3123
+ /** Message names shared by the controls sandbox and its host overlay layer. */
3124
+ var CONTROLS_APPEARANCE = "__histoire:controls-appearance";
3125
+ var CONTROLS_OVERLAY = "__histoire:controls-overlay";
3126
+ var CONTROLS_OVERLAY_RESULT = "__histoire:controls-overlay-result";
3127
+ var CONTROLS_OVERLAY_REFRESH = "__histoire:controls-overlay-refresh";
3128
+ /** Finite traversal request when cross-origin boundary prevents local DOM access. */
3129
+ var CONTROLS_FOCUS = "__histoire:controls-focus";
3130
+ // src/types/embed-presentation.ts
3131
+ /** Panels available in a scoped story or variant embed. */
3132
+ var HISTOIRE_EMBED_PANELS = [
3133
+ "controls",
3134
+ "docs",
3135
+ "source",
3136
+ "events"
3137
+ ];
3138
+ // src/types/inspection.ts
3139
+ /** Finite operations independent of transport or UI framework. */
3140
+ var HISTOIRE_INSPECTION_KINDS = [
3141
+ "variant",
3142
+ "dom",
3143
+ "components",
3144
+ "component",
3145
+ "componentForElement",
3146
+ "accessibility",
3147
+ "highlight",
3148
+ "pick",
3149
+ "highlightLease",
3150
+ "highlightClear"
3151
+ ];
3152
+ // src/types/preview-message.ts
3153
+ /**
3154
+ * Message types of the host <-> preview iframe postMessage protocol.
3155
+ *
3156
+ * Declared here rather than app-side because both ends read them: the app
3157
+ * imports them directly, and the generated preview runtime imports the app's
3158
+ * re-export. The payload types below are the only compiler check the protocol
3159
+ * gets — the preview side is generated JavaScript.
3160
+ */
3161
+ var STATE_SYNC = "__histoire:state-sync";
3162
+ var SANDBOX_READY = "__histoire:sandbox-ready";
3163
+ var EVENT_SEND = "__histoire:event";
3164
+ var PREVIEW_SETTINGS_SYNC = "__histoire:preview-settings-sync";
3165
+ var VARIANT_READY = "__histoire:variant-ready";
3166
+ var PREVIEW_SYNC = "__histoire:preview-sync";
3167
+ var CONTROLS_READY = "__histoire:controls-ready";
3168
+ var CONTROLS_RESIZE = "__histoire:controls-resize";
3169
+ var COLLECT_TESTS = "__histoire:collect-tests";
3170
+ var RUN_TESTS = "__histoire:run-tests";
3171
+ var RUN_TEST_CASE = "__histoire:run-test-case";
3172
+ var TEST_DEFINITIONS = "__histoire:test-definitions";
3173
+ var TEST_RESULT = "__histoire:test-result";
3174
+ var TEST_CASE_RESULT = "__histoire:test-case-result";
3175
+ var RUNTIME_REQUEST = "__histoire:runtime-request";
3176
+ var RUNTIME_RESULT = "__histoire:runtime-result";
3177
+ var RUNTIME_FAILED = "__histoire:runtime-failed";
3178
+ var RUNTIME_LAYOUT = "__histoire:runtime-layout";
3179
+ var RUNTIME_FOCUS = "__histoire:runtime-focus";
3180
+ /** Application channel messages retain existing sandbox identity/origin guards. */
3181
+ var HOST_CHANNEL_MESSAGE = "__histoire:host-channel";
3182
+ // src/types/settings.ts
3183
+ /** Fresh defaults prevent globals shared between sessions. */
3184
+ function createDefaultHistoireSettings() {
3185
+ return {
3186
+ responsiveWidth: 720,
3187
+ responsiveHeight: null,
3188
+ rotate: false,
3189
+ backgroundColor: "transparent",
3190
+ checkerboard: false,
3191
+ checkerboardTheme: "light",
3192
+ textDirection: "ltr",
3193
+ colorScheme: "auto",
3194
+ globals: {}
3195
+ };
3196
+ }
3197
+ // src/url/preview.ts
3198
+ /** Canonical deployment base must remain on the current origin. */
3199
+ function normalizePreviewBase(value) {
3200
+ const base = value.endsWith("/") ? value : `${value}/`;
3201
+ const segments = base.split("/").map((segment) => segment.replace(/%2e/gi, "."));
3202
+ if (!base.startsWith("/") || base.startsWith("//") || /[?#\\\0]/.test(base) || !base.isWellFormed() || segments.some((segment) => segment === "." || segment === "..")) throw new Error("Preview base must be a same-origin absolute path");
3203
+ return base;
3204
+ }
3205
+ /** Build a relative sandbox URL with exact identities in query parameters. */
3206
+ function getSandboxRelativeUrl(options) {
3207
+ const query = new URLSearchParams({
3208
+ storyId: options.storyId,
3209
+ variantId: options.variantId
3210
+ });
3211
+ return `${normalizePreviewBase(options.base)}__sandbox.html?${query}`;
3212
+ }
3213
+ // src/url/embed.ts
3214
+ /** Reject malformed presentation without widening visible capabilities. */
3215
+ function invalid(message) {
3216
+ throw new HistoireSdkError("INVALID_ARGUMENT", message);
3217
+ }
3218
+ /** Normalize panels once for URL, SDK, and native composition. */
3219
+ function validateEmbedPanels(value = ["controls"]) {
3220
+ if (!Array.isArray(value) || value.some((panel) => !HISTOIRE_EMBED_PANELS.includes(panel))) invalid("Unsupported embed panel");
3221
+ return HISTOIRE_EMBED_PANELS.filter((panel) => value.includes(panel));
3222
+ }
3223
+ /** Validate untyped SDK options before a surface reserves runtime ownership. */
3224
+ function validateEmbedPresentation(value) {
3225
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid("Expected embed presentation");
3226
+ const input = value;
3227
+ if (input.type !== "embed" || !["story", "variant"].includes(input.scope)) invalid("Unsupported embed presentation");
3228
+ return {
3229
+ type: "embed",
3230
+ scope: input.scope,
3231
+ panels: validateEmbedPanels(input.panels)
3232
+ };
3233
+ }
3234
+ /** Repeated routing values cannot silently become another target or composition. */
3235
+ function hint(query, key) {
3236
+ const values = query.getAll(key);
3237
+ if (values.length > 1) invalid(`Repeated embed ${key}`);
3238
+ return values[0];
3239
+ }
3240
+ /** Read explicitly empty panels separately from omitted default panels. */
3241
+ function panels(query) {
3242
+ const value = hint(query, "panels");
3243
+ return validateEmbedPanels(value === void 0 ? void 0 : value === "" ? [] : value.split(","));
3244
+ }
3245
+ /** Parse SDK surface presentation independently from parent handshake identity. */
3246
+ function parseEmbedPresentation(query) {
3247
+ const type = hint(query, "presentation");
3248
+ if (type === void 0) return;
3249
+ return validateEmbedPresentation({
3250
+ type,
3251
+ scope: hint(query, "scope"),
3252
+ panels: panels(query)
3253
+ });
3254
+ }
3255
+ /** Serialize only validated cosmetic hints; selection still comes from parent session. */
3256
+ function writeEmbedPresentation(query, input) {
3257
+ const value = validateEmbedPresentation(input);
3258
+ query.set("presentation", value.type);
3259
+ query.set("scope", value.scope);
3260
+ query.set("panels", value.panels.join(","));
3261
+ }
3262
+ /** Validate exact public target IDs, retaining byte-for-byte query identity. */
3263
+ function parseEmbedDocumentOptions(query) {
3264
+ const storyId = targetId(hint(query, "storyId"));
3265
+ const variantId = hint(query, "variantId");
3266
+ return {
3267
+ storyId,
3268
+ ...variantId === void 0 ? {} : { variantId: targetId(variantId) },
3269
+ panels: panels(query)
3270
+ };
3271
+ }
3272
+ /** Reject coercion and surrogate replacement before URLSearchParams encodes IDs. */
3273
+ function targetId(value) {
3274
+ if (typeof value !== "string" || !value || !value.isWellFormed()) invalid("Expected exact embed story and variant IDs");
3275
+ return value;
3276
+ }
3277
+ /** Build deployment-relative direct embed link without standalone route or runtime hints. */
3278
+ function getEmbedRelativeUrl(options) {
3279
+ const query = new URLSearchParams({
3280
+ view: "embed",
3281
+ storyId: targetId(options.storyId)
3282
+ });
3283
+ if (options.variantId !== void 0) query.set("variantId", targetId(options.variantId));
3284
+ query.set("panels", validateEmbedPanels(options.panels).join(","));
3285
+ parseEmbedDocumentOptions(query);
3286
+ return `${normalizePreviewBase(options.base)}__embed.html?${query}`;
3287
+ }
3288
+ export { COLLECT_TESTS, CONTROLS_APPEARANCE, CONTROLS_FOCUS, CONTROLS_OVERLAY, CONTROLS_OVERLAY_REFRESH, CONTROLS_OVERLAY_RESULT, CONTROLS_READY, CONTROLS_RESIZE, EVENT_SEND, HISTOIRE_BRIDGE_COMMANDS, HISTOIRE_BRIDGE_EVENTS, HISTOIRE_DESCRIPTOR_VERSION, HISTOIRE_EMBED_PANELS, HISTOIRE_ERROR_CODES, HISTOIRE_INSPECTION_CAPABILITIES, HISTOIRE_INSPECTION_KINDS, HISTOIRE_INSPECTION_LIMITS, HISTOIRE_INSPECTION_OPERATION_CAPABILITIES, HISTOIRE_MATRIX_NUMERIC_VALUES, HISTOIRE_META_LIMITS, HISTOIRE_PLUGIN_CHANNEL_MAX_BYTES, HISTOIRE_PLUGIN_ID_PATTERN, HISTOIRE_PLUGIN_NOTICES, HISTOIRE_PLUGIN_NOTICE_PREFIX, HISTOIRE_PROTOCOL_VERSION, HISTOIRE_SURFACES, HISTOIRE_TEST_DATA_LIMIT, HISTOIRE_WIRE_LIMITS, HOST_CHANNEL_MESSAGE, HistoireSdkError, PREVIEW_SETTINGS_SYNC, PREVIEW_SYNC, RUNTIME_FAILED, RUNTIME_FOCUS, RUNTIME_LAYOUT, RUNTIME_REQUEST, RUNTIME_RESULT, RUN_TESTS, RUN_TEST_CASE, SANDBOX_READY, STATE_SYNC, STORY_ROUTE_PATH, TEST_CASE_RESULT, TEST_DEFINITIONS, TEST_RESULT, VARIANT_READY, applySerializedState, assertInspectionJson, createControlsStateRevision, createDebugBuffer, createDefaultHistoireSettings, createEmbedFrameAncestors, createHostChannelRateLimiter, createPluginChannelLimiters, formatTestError, getEmbedRelativeUrl, getHistoireColorChannels, getHistoireFiniteMatrixValues, getHistoireMatrixRange, getHistoireMatrixRangeValues, getHistoireMatrixValues, getHistoireNumericMatrixValues, getHistoireSemanticThemeOverrides, getHistoireTargetKey, getHistoireWireLimit, getSandboxRelativeUrl, hasInspectionCapability, histoireDefaultAccentColors, histoireDefaultNeutralColors, intersectRuntimeRects, isHistoireMatrixPropName, isHistoirePluginId, isHistoirePluginNotice, isHistoireProjectFileOrigin, isStoryRouteHash, mapRuntimeViewport, measureWireValue, mergeEmbedFrameAncestors, negotiateHistoireProtocol, normalizeHistoireMatrixHint, normalizeHistoireMeta, normalizePreviewBase, parseColor, parseEmbedDocumentOptions, parseEmbedPresentation, parseStoryRouteQuery, resolveEmbedOrigins, resolveStoryRouteId, resolveStoryRouteSelection, sameInspectionOwner, serializeTestError, serializeTestErrors, validateBridgeEnvelope, validateBridgeEnvelopeBody, validateBridgeEventPayload, validateBridgePayload, validateBridgeResult, validateEmbedOrigin, validateEmbedOrigins, validateEmbedPanels, validateEmbedPresentation, validateFramePluginInventory, validateHistoireAck, validateHistoireCapabilities, validateHistoireCatalog, validateHistoireCatalogStory, validateHistoireContent, validateHistoireDiagnostics, validateHistoireErrorData, validateHistoireEvent, validateHistoireHello, validateHistoireProtocolRange, validateHistoireRuntimeSnapshot, validateHistoireSnapshot, validateHistoireSourceDescriptor, validateHistoireStateSnapshot, validateHistoireTarget, validateHistoireTestData, validateHistoireTestExecution, validateHistoireTestResult, validateHistoireViewports, validateHostChannelNames, validateHostChannelPayload, validateInspectionCapabilities, validateInspectionInput, validateInspectionOwner, validateInspectionPolicy, validateInspectionResult, validateInspectionTarget, validatePluginChannelPayload, validateProjectTestCollection, validateSettingsPatch, validateWireValue, wireRecord, writeEmbedPresentation };