@wireweave/core 4.0.0-beta.13 → 4.0.0-beta.14

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.
@@ -0,0 +1,2145 @@
1
+ 'use strict';
2
+
3
+ var chunkIMUVIIJR_cjs = require('./chunk-IMUVIIJR.cjs');
4
+ var chunkZPHNXJRY_cjs = require('./chunk-ZPHNXJRY.cjs');
5
+ var chunkETV4XYOV_cjs = require('./chunk-ETV4XYOV.cjs');
6
+
7
+ // src/ast/expand-variants.ts
8
+ function cloneNode(value) {
9
+ if (Array.isArray(value)) return value.map(cloneNode);
10
+ if (value === null || typeof value !== "object") return value;
11
+ const source = value;
12
+ const result = {};
13
+ for (const [key, item] of Object.entries(source)) {
14
+ result[key] = key === "loc" ? item : cloneNode(item);
15
+ }
16
+ return result;
17
+ }
18
+ function variantNames(page) {
19
+ const declared = page.variants;
20
+ if (!Array.isArray(declared)) return [];
21
+ const seen = /* @__PURE__ */ new Set();
22
+ const names = [];
23
+ for (const raw of declared) {
24
+ if (typeof raw !== "string") continue;
25
+ const name = raw.trim();
26
+ if (name.length === 0 || seen.has(name)) continue;
27
+ seen.add(name);
28
+ names.push(name);
29
+ }
30
+ return names;
31
+ }
32
+ function hasVariants(document) {
33
+ return document.children.some((child) => child.type === "Page" && variantNames(child).length > 0);
34
+ }
35
+ function expandVariants(document) {
36
+ if (!hasVariants(document)) return chunkZPHNXJRY_cjs.filterUnscopedPages(document);
37
+ return {
38
+ ...document,
39
+ children: document.children.flatMap((child) => {
40
+ if (child.type !== "Page") return [child];
41
+ const names = variantNames(child);
42
+ if (names.length === 0) {
43
+ const filtered = chunkZPHNXJRY_cjs.filterVariantScope(child.children, void 0);
44
+ return [filtered === child.children ? child : { ...child, children: filtered }];
45
+ }
46
+ return names.map((variant, position) => {
47
+ const clone = cloneNode(child);
48
+ delete clone.variants;
49
+ clone.variant = variant;
50
+ if (position > 0) delete clone.states;
51
+ clone.children = chunkZPHNXJRY_cjs.filterVariantScope(clone.children, variant);
52
+ return clone;
53
+ });
54
+ })
55
+ };
56
+ }
57
+
58
+ // src/app/v4.ts
59
+ var bundleBrand = /* @__PURE__ */ Symbol("AppBundle");
60
+ var linkedBrand = /* @__PURE__ */ Symbol("LinkedApp");
61
+ var bundles = /* @__PURE__ */ new WeakMap();
62
+ var links = /* @__PURE__ */ new WeakMap();
63
+ var identifiers = /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/;
64
+ var uuids = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
65
+ var containers = new Set(
66
+ "page header main footer sidebar section row col stack relative card modal drawer accordion popover form tab nav-group list-item annotation-item".split(
67
+ " "
68
+ )
69
+ );
70
+ function textValue(value) {
71
+ if (typeof value === "string") return value;
72
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
73
+ return value === void 0 || value === null ? "" : jcs(value);
74
+ }
75
+ function object(value) {
76
+ return value !== null && typeof value === "object" && !Array.isArray(value);
77
+ }
78
+ function isArray(value) {
79
+ return Array.isArray(value);
80
+ }
81
+ function diagnostic(code, messageKey, source, details = {}, phase = "link", path = "") {
82
+ var _a, _b, _c;
83
+ return {
84
+ severity: "error",
85
+ code,
86
+ phase,
87
+ sourceId: (_a = source == null ? void 0 : source.sourceId) != null ? _a : "app",
88
+ start: (_b = source == null ? void 0 : source.start) != null ? _b : 0,
89
+ end: (_c = source == null ? void 0 : source.end) != null ? _c : 0,
90
+ path,
91
+ messageKey,
92
+ details,
93
+ related: []
94
+ };
95
+ }
96
+ function failed(diagnostics) {
97
+ const sorted = diagnostics.slice().sort(
98
+ (a, b) => (a.sourceId < b.sourceId ? -1 : a.sourceId > b.sourceId ? 1 : 0) || a.start - b.start || (a.phase < b.phase ? -1 : a.phase > b.phase ? 1 : 0) || (a.code < b.code ? -1 : a.code > b.code ? 1 : 0)
99
+ );
100
+ if (sorted.length > 1e3) {
101
+ const omitted = sorted.length - 999;
102
+ sorted.length = 999;
103
+ sorted.push(diagnostic("WW_DIAGNOSTIC_LIMIT", "app.diagnostic-limit", void 0, { omitted }));
104
+ }
105
+ return { ok: false, value: null, html: null, diagnostics: sorted };
106
+ }
107
+ function jcs(value, depth = 0, ancestors = /* @__PURE__ */ new Set()) {
108
+ if (depth > 512) throw new TypeError("JSON nesting limit");
109
+ if (value === null || typeof value === "boolean" || typeof value === "string")
110
+ return JSON.stringify(value);
111
+ if (typeof value === "number") {
112
+ if (!Number.isFinite(value)) throw new TypeError("Non-finite JSON number");
113
+ return JSON.stringify(value);
114
+ }
115
+ if (typeof value !== "object" || value === null || ancestors.has(value))
116
+ throw new TypeError("Invalid or cyclic JSON value");
117
+ ancestors.add(value);
118
+ try {
119
+ if (Array.isArray(value))
120
+ return `[${value.map((item) => jcs(item, depth + 1, ancestors)).join(",")}]`;
121
+ if (Object.prototype.toString.call(value) !== "[object Object]")
122
+ throw new TypeError("Invalid JSON object");
123
+ return `{${Object.keys(value).sort().map(
124
+ (key) => `${JSON.stringify(key)}:${jcs(value[key], depth + 1, ancestors)}`
125
+ ).join(",")}}`;
126
+ } finally {
127
+ ancestors.delete(value);
128
+ }
129
+ }
130
+ function freeze(value) {
131
+ const stack = [value];
132
+ while (stack.length > 0) {
133
+ const current = stack.pop();
134
+ if (current !== null && typeof current === "object" && !Object.isFrozen(current)) {
135
+ for (const child of Object.values(current)) stack.push(child);
136
+ Object.freeze(current);
137
+ }
138
+ }
139
+ return value;
140
+ }
141
+ function dsl(value) {
142
+ if (Array.isArray(value)) return `[${value.map(dsl).join(",")}]`;
143
+ if (object(value))
144
+ return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}=${dsl(item)}`).join(",")}}`;
145
+ return JSON.stringify(value);
146
+ }
147
+ function plain(value) {
148
+ return JSON.parse(jcs(value));
149
+ }
150
+ function sourceId(value) {
151
+ var _a;
152
+ return (_a = value.split(/[\\/]/).filter(Boolean).at(-1)) != null ? _a : "source.wf";
153
+ }
154
+ function sourceOf(value, fallback) {
155
+ var _a;
156
+ const found = (_a = chunkIMUVIIJR_cjs.getV4SourceSpan(value)) != null ? _a : fallback;
157
+ return found === void 0 ? { sourceId: "app", start: 0, end: 0, startLine: 1, startColumn: 1, endLine: 1, endColumn: 1 } : { ...found, sourceId: sourceId(found.sourceId) };
158
+ }
159
+ function createAppBundle(documents, options) {
160
+ if (!isArray(documents) || !object(options) || !object(options.moduleSources))
161
+ throw new TypeError("Parsed documents and explicit bundle options are required");
162
+ const diagnostics = [];
163
+ const modules = [];
164
+ const sourceByPath = /* @__PURE__ */ new Map();
165
+ try {
166
+ jcs(options);
167
+ if (!identifiers.test(options.id))
168
+ return failed([diagnostic("WW_SCHEMA", "app.invalid-id", void 0, {}, "schema")]);
169
+ const configuration = chunkIMUVIIJR_cjs.parseV4(
170
+ `app ${options.id} entry=${dsl(options.entry)} profile=${dsl(options.profile)} states=${dsl(options.states)} registry=${dsl(options.registry)} fixtures=${dsl(options.fixtures)} {}`,
171
+ { languageVersion: "4.0.0", sourceId: "app" }
172
+ );
173
+ for (const document of documents) {
174
+ if (document.languageVersion !== "4.0.0" || document.schemaVersion !== "1.0.0" || !isArray(document.modules)) {
175
+ diagnostics.push(
176
+ diagnostic("WW_UNSUPPORTED_VERSION", "app.document-version", void 0, {}, "schema")
177
+ );
178
+ continue;
179
+ }
180
+ for (const module of document.modules) {
181
+ const bytes = options.moduleSources[module.id];
182
+ if (modules.some((prior) => prior.id === module.id)) {
183
+ diagnostics.push(
184
+ diagnostic("WW_DUPLICATE_ID", "app.duplicate-module", sourceOf(module), {
185
+ id: module.id
186
+ })
187
+ );
188
+ continue;
189
+ }
190
+ if (typeof bytes !== "string") {
191
+ diagnostics.push(
192
+ diagnostic(
193
+ "WW_IMPORT",
194
+ "app.missing-source-bytes",
195
+ sourceOf(module),
196
+ { id: module.id },
197
+ "import"
198
+ )
199
+ );
200
+ continue;
201
+ }
202
+ const reparsed = chunkIMUVIIJR_cjs.parseV4(bytes, { languageVersion: "4.0.0", sourceId: `${module.id}.wf` });
203
+ if (chunkIMUVIIJR_cjs.digestV4(bytes) !== module.sourceDigest || reparsed.modules.length !== 1 || jcs(reparsed.modules[0]) !== jcs(module)) {
204
+ diagnostics.push(
205
+ diagnostic(
206
+ "WW_IMPORT",
207
+ "app.source-content-mismatch",
208
+ sourceOf(module),
209
+ { id: module.id },
210
+ "import"
211
+ )
212
+ );
213
+ continue;
214
+ }
215
+ const stack = [
216
+ { value: reparsed.modules[0], path: module.id, fallback: sourceOf(reparsed.modules[0]) }
217
+ ];
218
+ while (stack.length > 0) {
219
+ const item = stack.pop();
220
+ if (item.value !== null && typeof item.value === "object") {
221
+ const span = sourceOf(item.value, item.fallback);
222
+ sourceByPath.set(item.path, span);
223
+ for (const [key, value] of Object.entries(item.value))
224
+ stack.push({ value, path: `${item.path}/${key}`, fallback: span });
225
+ }
226
+ }
227
+ modules.push(plain(module));
228
+ }
229
+ }
230
+ if (modules.length === 0 || modules.length > 256)
231
+ diagnostics.push(diagnostic("WW_LIMIT", "app.module-count", void 0, {}, "schema"));
232
+ for (const id of Object.keys(options.moduleSources))
233
+ if (!modules.some((module) => module.id === id)) {
234
+ diagnostics.push(
235
+ diagnostic("WW_IMPORT", "app.unselected-source", void 0, { id }, "import")
236
+ );
237
+ }
238
+ if (diagnostics.length > 0) return failed(diagnostics);
239
+ const candidate = {
240
+ [bundleBrand]: true,
241
+ schemaVersion: "1.0.0",
242
+ languageVersion: "4.0.0",
243
+ id: configuration.app.id,
244
+ entry: configuration.app.entry,
245
+ profile: configuration.app.profile,
246
+ states: configuration.states,
247
+ registry: configuration.registry,
248
+ fixtures: configuration.fixtures,
249
+ modules
250
+ };
251
+ if (new TextEncoder().encode(jcs(candidate)).byteLength > 64 * 1024 * 1024)
252
+ return failed([diagnostic("WW_LIMIT", "app.bundle-byte-limit")]);
253
+ const bundle = freeze(candidate);
254
+ bundles.set(bundle, { sourceByPath });
255
+ return { ok: true, value: bundle, diagnostics: [] };
256
+ } catch (error) {
257
+ if (error instanceof chunkIMUVIIJR_cjs.V4ParseError)
258
+ return failed(error.diagnostics.map((item) => ({ ...item, phase: "schema" })));
259
+ if (error instanceof TypeError)
260
+ return failed([diagnostic("WW_SCHEMA", "app.invalid-json", void 0, {}, "schema")]);
261
+ throw error;
262
+ }
263
+ }
264
+ var Linker = class {
265
+ constructor(bundle, data) {
266
+ chunkETV4XYOV_cjs.__publicField(this, "bundle", bundle);
267
+ chunkETV4XYOV_cjs.__publicField(this, "data", data);
268
+ chunkETV4XYOV_cjs.__publicField(this, "diagnostics", []);
269
+ chunkETV4XYOV_cjs.__publicField(this, "owners", /* @__PURE__ */ new Map());
270
+ chunkETV4XYOV_cjs.__publicField(this, "moduleById", /* @__PURE__ */ new Map());
271
+ chunkETV4XYOV_cjs.__publicField(this, "ownerByNode", /* @__PURE__ */ new WeakMap());
272
+ chunkETV4XYOV_cjs.__publicField(this, "pathByNode", /* @__PURE__ */ new WeakMap());
273
+ chunkETV4XYOV_cjs.__publicField(this, "expanded", []);
274
+ chunkETV4XYOV_cjs.__publicField(this, "screens", []);
275
+ chunkETV4XYOV_cjs.__publicField(this, "shells", []);
276
+ chunkETV4XYOV_cjs.__publicField(this, "moduleEdges", /* @__PURE__ */ new Map());
277
+ chunkETV4XYOV_cjs.__publicField(this, "definitionEdges", /* @__PURE__ */ new Map());
278
+ chunkETV4XYOV_cjs.__publicField(this, "registry", /* @__PURE__ */ new Map());
279
+ chunkETV4XYOV_cjs.__publicField(this, "expandedCount", 0);
280
+ chunkETV4XYOV_cjs.__publicField(this, "domIds", /* @__PURE__ */ new Set());
281
+ }
282
+ source(node) {
283
+ var _a, _b;
284
+ return (_b = this.data.sourceByPath.get((_a = this.pathByNode.get(node)) != null ? _a : "")) != null ? _b : sourceOf(node);
285
+ }
286
+ error(code, key, node, details = {}) {
287
+ var _a;
288
+ this.diagnostics.push(
289
+ diagnostic(
290
+ code,
291
+ key,
292
+ node === void 0 ? void 0 : this.source(node),
293
+ details,
294
+ code === "WW_IMPORT" ? "import" : "link",
295
+ node === void 0 ? "" : (_a = this.pathByNode.get(node)) != null ? _a : ""
296
+ )
297
+ );
298
+ }
299
+ key(namespace, kind, id) {
300
+ return `${namespace}/${kind}/${id}`;
301
+ }
302
+ walk(root, visit, rootPath) {
303
+ const stack = [{ node: root, path: rootPath }];
304
+ while (stack.length > 0) {
305
+ const { node, path } = stack.pop();
306
+ visit(node, path);
307
+ if (node.kind === "use") {
308
+ for (let i = node.fills.length - 1; i >= 0; i--)
309
+ for (let j = node.fills[i].children.length - 1; j >= 0; j--)
310
+ stack.push({
311
+ node: node.fills[i].children[j],
312
+ path: `${path}/fills/${i}/children/${j}`
313
+ });
314
+ } else if ("children" in node)
315
+ for (let i = node.children.length - 1; i >= 0; i--)
316
+ stack.push({ node: node.children[i], path: `${path}/children/${i}` });
317
+ }
318
+ }
319
+ index() {
320
+ const namespaces = /* @__PURE__ */ new Set();
321
+ for (const module of this.bundle.modules) {
322
+ this.pathByNode.set(module, module.id);
323
+ this.moduleById.set(module.id, module);
324
+ if (namespaces.has(module.namespace))
325
+ this.error("WW_DUPLICATE_ID", "app.duplicate-namespace", module, {
326
+ namespace: module.namespace
327
+ });
328
+ namespaces.add(module.namespace);
329
+ for (const [index, definition] of module.definitions.entries()) {
330
+ const id = definition.id;
331
+ if (id === void 0) {
332
+ this.error("WW_REFERENCE", "app.page-id-required", module);
333
+ continue;
334
+ }
335
+ const key = this.key(module.namespace, definition.kind, id);
336
+ const owner = { module, definition, key };
337
+ this.walk(
338
+ definition,
339
+ (node, path) => {
340
+ this.ownerByNode.set(node, owner);
341
+ this.pathByNode.set(node, path);
342
+ },
343
+ `${module.id}/definitions/${index}`
344
+ );
345
+ if (this.owners.has(key))
346
+ this.error("WW_DUPLICATE_ID", "app.duplicate-definition", definition, { id });
347
+ else this.owners.set(key, owner);
348
+ const localIds = /* @__PURE__ */ new Set();
349
+ this.walk(
350
+ definition,
351
+ (node) => {
352
+ if ("id" in node && node.id !== void 0) {
353
+ if (localIds.has(node.id))
354
+ this.error("WW_DUPLICATE_ID", "app.duplicate-local-id", node, { id: node.id });
355
+ localIds.add(node.id);
356
+ }
357
+ },
358
+ ""
359
+ );
360
+ }
361
+ }
362
+ }
363
+ resolve(owner, kind, id, alias, node = owner.definition) {
364
+ let namespace = owner.module.namespace;
365
+ if (alias !== void 0) {
366
+ const imported = owner.module.imports.find((item) => item.namespace === alias);
367
+ const target2 = imported === void 0 ? void 0 : this.moduleById.get(imported.moduleId);
368
+ if (target2 === void 0 || imported === void 0 || !imported.symbols.some((symbol) => symbol.kind === kind && symbol.id === id)) {
369
+ this.error("WW_REFERENCE", "app.unimported-symbol", node, { kind, id, namespace: alias });
370
+ return void 0;
371
+ }
372
+ namespace = target2.namespace;
373
+ }
374
+ const target = this.owners.get(this.key(namespace, kind, id));
375
+ if (target === void 0)
376
+ this.error("WW_REFERENCE", "app.missing-symbol", node, { kind, id, namespace });
377
+ return target;
378
+ }
379
+ imports() {
380
+ for (const module of this.bundle.modules) {
381
+ const aliases = /* @__PURE__ */ new Set();
382
+ const edges = [];
383
+ for (const [index, imported] of module.imports.entries()) {
384
+ this.pathByNode.set(imported, `${module.id}/imports/${index}`);
385
+ if (aliases.has(imported.namespace))
386
+ this.error("WW_DUPLICATE_ID", "app.duplicate-import-alias", imported);
387
+ aliases.add(imported.namespace);
388
+ const target = this.moduleById.get(imported.moduleId);
389
+ if (target === void 0 || target.sourceDigest !== imported.digest) {
390
+ this.error("WW_IMPORT", "app.import-digest-or-module", imported);
391
+ continue;
392
+ }
393
+ edges.push(target.id);
394
+ const selected = /* @__PURE__ */ new Set();
395
+ for (const symbol of imported.symbols) {
396
+ const key = `${symbol.kind}/${symbol.id}`;
397
+ if (selected.has(key))
398
+ this.error("WW_DUPLICATE_ID", "app.duplicate-import-symbol", imported);
399
+ selected.add(key);
400
+ if (!target.exports.some((entry) => entry.kind === symbol.kind && entry.id === symbol.id))
401
+ this.error("WW_IMPORT", "app.unexported-symbol", imported, { symbol: key });
402
+ }
403
+ }
404
+ const exports = /* @__PURE__ */ new Set();
405
+ for (const item of module.exports) {
406
+ const key = this.key(module.namespace, item.kind, item.id);
407
+ if (exports.has(key)) this.error("WW_DUPLICATE_ID", "app.duplicate-export", module);
408
+ exports.add(key);
409
+ if (!this.owners.has(key))
410
+ this.error("WW_IMPORT", "app.missing-export", module, { id: item.id });
411
+ }
412
+ this.moduleEdges.set(module.id, edges);
413
+ }
414
+ this.cycles(this.moduleEdges, 64);
415
+ }
416
+ cycles(edges, depthLimit) {
417
+ var _a, _b, _c;
418
+ const colors = /* @__PURE__ */ new Map();
419
+ for (const start of edges.keys()) {
420
+ if (colors.has(start)) continue;
421
+ const frames = [{ id: start, cursor: 0 }];
422
+ colors.set(start, 1);
423
+ while (frames.length > 0) {
424
+ const current = frames[frames.length - 1];
425
+ const neighbors = (_a = edges.get(current.id)) != null ? _a : [];
426
+ if (current.cursor === neighbors.length) {
427
+ colors.set(current.id, 2);
428
+ frames.pop();
429
+ continue;
430
+ }
431
+ const next = neighbors[current.cursor++];
432
+ if (colors.get(next) === 1) {
433
+ this.error(
434
+ "WW_CYCLE",
435
+ "app.dependency-cycle",
436
+ (_c = (_b = this.owners.get(current.id)) == null ? void 0 : _b.definition) != null ? _c : this.moduleById.get(current.id),
437
+ { from: current.id, to: next }
438
+ );
439
+ continue;
440
+ }
441
+ if (colors.has(next)) continue;
442
+ if (frames.length >= depthLimit) {
443
+ this.error("WW_LIMIT", "app.dependency-depth", void 0, { id: next });
444
+ continue;
445
+ }
446
+ colors.set(next, 1);
447
+ frames.push({ id: next, cursor: 0 });
448
+ }
449
+ }
450
+ }
451
+ references() {
452
+ for (const owner of this.owners.values()) {
453
+ const edges = [];
454
+ const slots = /* @__PURE__ */ new Set();
455
+ this.walk(
456
+ owner.definition,
457
+ (node) => {
458
+ var _a;
459
+ if (node.kind === "use") {
460
+ const target = this.resolve(owner, "component", node.name, node.namespace, node);
461
+ if (target !== void 0) edges.push(target.key);
462
+ }
463
+ if (node.kind === "slot") {
464
+ const name = (_a = node.name) != null ? _a : "";
465
+ if (slots.has(name)) this.error("WW_SLOT", "app.duplicate-slot", node);
466
+ slots.add(name);
467
+ if (owner.definition.kind === "component" && name === "")
468
+ this.error("WW_SLOT", "app.component-slot-name", node);
469
+ }
470
+ },
471
+ ""
472
+ );
473
+ if (owner.definition.kind === "layout" && (slots.size !== 1 || !slots.has("")))
474
+ this.error("WW_SLOT", "app.layout-slot-cardinality", owner.definition);
475
+ const uses = owner.definition.attributes.uses;
476
+ if (typeof uses === "string") {
477
+ if (owner.definition.kind !== "page")
478
+ this.error("WW_REFERENCE", "app.layout-nesting", owner.definition);
479
+ const [alias, id] = uses.includes("::") ? uses.split("::") : [void 0, uses];
480
+ const target = this.resolve(owner, "layout", id, alias);
481
+ if (target !== void 0) edges.push(target.key);
482
+ }
483
+ this.definitionEdges.set(owner.key, edges);
484
+ }
485
+ this.cycles(this.definitionEdges, 1e4);
486
+ }
487
+ registryChecks() {
488
+ const entries = this.bundle.registry.entries;
489
+ const sorted = entries.slice().sort((a, b) => {
490
+ const left = `${textValue(a.kind)}\0${textValue(a.namespace)}\0${textValue(a.id)}`;
491
+ const right = `${textValue(b.kind)}\0${textValue(b.namespace)}\0${textValue(b.id)}`;
492
+ return left < right ? -1 : left > right ? 1 : 0;
493
+ });
494
+ if (jcs(entries) !== jcs(sorted) || chunkIMUVIIJR_cjs.digestV4(jcs(entries)) !== this.bundle.registry.digest)
495
+ this.error("WW_REGISTRY", "app.registry-digest");
496
+ for (const entry of entries) {
497
+ if (typeof entry.id !== "string" || !uuids.test(entry.id) || typeof entry.namespace !== "string" || !["Requirement", "ImplementationObligation"].includes(textValue(entry.kind))) {
498
+ this.error("WW_REGISTRY", "app.registry-identity");
499
+ continue;
500
+ }
501
+ if (this.registry.has(entry.id))
502
+ this.error("WW_REGISTRY", "app.duplicate-registry-id", void 0, { id: entry.id });
503
+ this.registry.set(entry.id, entry);
504
+ if (typeof entry.title !== "string" || entry.title.length === 0 || !Array.isArray(entry.acceptance) || entry.acceptance.length === 0)
505
+ this.error("WW_REGISTRY", "app.incomplete-requirement", void 0, { id: entry.id });
506
+ if (entry.kind === "ImplementationObligation") {
507
+ for (const field of ["trigger", "authority"])
508
+ if (typeof entry[field] !== "string" || entry[field].length === 0)
509
+ this.error("WW_REGISTRY", "app.incomplete-obligation", void 0, {
510
+ id: entry.id,
511
+ field
512
+ });
513
+ for (const field of ["preconditions", "success", "failureCases", "requirementRefs"])
514
+ if (!Array.isArray(entry[field]) || field !== "preconditions" && entry[field].length === 0)
515
+ this.error("WW_REGISTRY", "app.incomplete-obligation", void 0, {
516
+ id: entry.id,
517
+ field
518
+ });
519
+ for (const field of ["request", "response"])
520
+ if (!object(entry[field]) || !["schema", "not-applicable"].includes(textValue(entry[field].mode)))
521
+ this.error("WW_REGISTRY", "app.incomplete-obligation", void 0, {
522
+ id: entry.id,
523
+ field
524
+ });
525
+ }
526
+ }
527
+ for (const entry of entries) {
528
+ for (const ref of Array.isArray(entry.requirementRefs) ? entry.requirementRefs : []) {
529
+ const target = object(ref) ? this.registry.get(textValue(ref.id)) : void 0;
530
+ if ((target == null ? void 0 : target.kind) !== "Requirement" || !object(ref) || ref.namespace !== target.namespace || ref.kind !== "Requirement")
531
+ this.error("WW_REGISTRY", "app.obligation-requirement-reference");
532
+ }
533
+ }
534
+ for (const owner of this.owners.values())
535
+ this.walk(
536
+ owner.definition,
537
+ (node) => {
538
+ if (!("attributes" in node)) return;
539
+ this.registryRefs(node.attributes, node);
540
+ for (const handler of asObjects(node.attributes.on))
541
+ for (const operation of asObjects(handler.operations))
542
+ this.registryRefs(operation, node);
543
+ },
544
+ ""
545
+ );
546
+ }
547
+ registryRefs(value, node) {
548
+ var _a;
549
+ for (const [field, kind] of [
550
+ ["requirementRefs", "Requirement"],
551
+ ["obligationRefs", "ImplementationObligation"]
552
+ ]) {
553
+ for (const id of Array.isArray(value[field]) ? value[field] : []) {
554
+ if (typeof id !== "string" || ((_a = this.registry.get(id)) == null ? void 0 : _a.kind) !== kind)
555
+ this.error("WW_REGISTRY", "app.unresolved-registry-reference", node, { field, id });
556
+ }
557
+ }
558
+ }
559
+ binding(value) {
560
+ if (!object(value)) {
561
+ this.error("WW_REGISTRY", "app.invalid-source-binding");
562
+ return;
563
+ }
564
+ if (value.scope === "instance" && (!object(value.instanceRoot) || !Array.isArray(value.instancePath))) {
565
+ this.error("WW_REGISTRY", "app.invalid-instance-binding");
566
+ return;
567
+ }
568
+ if (!["module", "definition", "instance", "app-state"].includes(textValue(value.scope))) {
569
+ this.error("WW_REGISTRY", "app.invalid-source-binding");
570
+ return;
571
+ }
572
+ if (value.scope === "app-state") {
573
+ if (value.appId !== this.bundle.id || !this.bundle.states.some((state) => `app:${textValue(state.id)}` === value.stateRef))
574
+ this.error("WW_REGISTRY", "app.unresolved-source-binding");
575
+ return;
576
+ }
577
+ const module = this.moduleById.get(textValue(value.moduleId));
578
+ if (module === void 0) {
579
+ this.error("WW_REGISTRY", "app.unresolved-source-binding");
580
+ return;
581
+ }
582
+ if (value.scope === "module") return;
583
+ const owner = this.owners.get(
584
+ this.key(module.namespace, textValue(value.definitionKind), textValue(value.definitionId))
585
+ );
586
+ if (owner === void 0) {
587
+ this.error("WW_REGISTRY", "app.unresolved-source-binding");
588
+ return;
589
+ }
590
+ if (value.scope === "instance" && (value.appId !== this.bundle.id || !this.expanded.some(
591
+ (entry) => entry.owner === owner && jcs(entry.identity.instanceRoot) === jcs(value.instanceRoot) && jcs(entry.identity.instancePath) === jcs(value.instancePath) && (!["element", "operation"].includes(textValue(value.targetKind)) || entry.node.id === value.elementId)
592
+ )))
593
+ this.error("WW_REGISTRY", "app.unresolved-instance-binding");
594
+ if (value.targetKind === "definition") return;
595
+ if (value.targetKind === "variant") {
596
+ if (!Array.isArray(owner.definition.attributes.variants) || !owner.definition.attributes.variants.includes(value.variantId))
597
+ this.error("WW_REGISTRY", "app.unresolved-source-binding");
598
+ return;
599
+ }
600
+ if (value.targetKind === "state") {
601
+ const scope = owner.definition.kind === "page" ? "screen" : owner.definition.kind === "layout" ? "shell" : "component";
602
+ if (!asObjects(owner.definition.attributes.states).some(
603
+ (state) => value.stateRef === `${scope}:${textValue(state.id)}`
604
+ ))
605
+ this.error("WW_REGISTRY", "app.unresolved-source-binding");
606
+ return;
607
+ }
608
+ let found = false;
609
+ this.walk(
610
+ owner.definition,
611
+ (node) => {
612
+ if (!("id" in node) || node.id !== value.elementId || !("attributes" in node)) return;
613
+ found = value.targetKind === "element" || asObjects(node.attributes.on).some(
614
+ (handler) => asObjects(handler.operations).some((operation) => operation.id === value.operationId)
615
+ );
616
+ },
617
+ ""
618
+ );
619
+ if (!found) this.error("WW_REGISTRY", "app.unresolved-source-binding");
620
+ }
621
+ route(reference, node, code = "WW_REFERENCE") {
622
+ const target = this.owners.get(this.key(reference.namespace, "page", reference.id));
623
+ if (target === void 0 || reference.variant !== void 0 && (!Array.isArray(target.definition.attributes.variants) || !target.definition.attributes.variants.includes(reference.variant))) {
624
+ this.error(code, "app.unresolved-route", node, {
625
+ namespace: reference.namespace,
626
+ id: reference.id
627
+ });
628
+ return void 0;
629
+ }
630
+ return target;
631
+ }
632
+ frame(owner) {
633
+ var _a;
634
+ const attrs2 = owner.definition.attributes;
635
+ const { width, height } = this.bundle.profile;
636
+ const pair = attrs2.viewport === void 0 ? null : /^(\d+)(?:x(\d+))?$/.exec(textValue(attrs2.viewport));
637
+ const presets = {
638
+ "desktop-sm": [1280, 800],
639
+ desktop: [1440, 900],
640
+ "desktop-lg": [1920, 1080],
641
+ "desktop-xl": [2560, 1440],
642
+ ipad: [1024, 768],
643
+ "ipad-portrait": [768, 1024],
644
+ "ipad-pro": [1366, 1024],
645
+ "ipad-pro-portrait": [1024, 1366],
646
+ "iphone-se": [375, 667],
647
+ iphone14: [390, 844],
648
+ "iphone14-pro": [393, 852],
649
+ "iphone14-pro-max": [430, 932],
650
+ android: [360, 800],
651
+ "android-lg": [412, 915]
652
+ };
653
+ const device = presets[textValue(attrs2.device)];
654
+ if (attrs2.viewport !== void 0 && (pair === null || Number(pair[1]) !== width || Number((_a = pair[2]) != null ? _a : 900) !== height) || attrs2.device !== void 0 && (!device || device[0] !== width || device[1] !== height) || ["w", "width"].some(
655
+ (key) => attrs2[key] !== void 0 && attrs2[key] !== width && attrs2[key] !== "screen" && attrs2[key] !== "full"
656
+ ) || ["h", "height"].some(
657
+ (key) => attrs2[key] !== void 0 && attrs2[key] !== height && attrs2[key] !== "screen" && attrs2[key] !== "full"
658
+ ))
659
+ this.error("WW_VIEWPORT", "app.incompatible-frame", owner.definition);
660
+ }
661
+ expandAll() {
662
+ var _a;
663
+ this.route(this.bundle.entry, void 0, "WW_ROUTE");
664
+ const pages = [...this.owners.values()].filter((owner) => owner.definition.kind === "page");
665
+ if (pages.length === 0 || pages.length > 2e3) this.error("WW_LIMIT", "app.screen-count");
666
+ for (const owner of pages) {
667
+ this.frame(owner);
668
+ const screen = {
669
+ owner,
670
+ route: { namespace: owner.module.namespace, id: owner.definition.id },
671
+ children: []
672
+ };
673
+ const root = { kind: "screen", ...screen.route };
674
+ const uses = owner.definition.attributes.uses;
675
+ if (typeof uses === "string") {
676
+ const [alias, id] = uses.includes("::") ? uses.split("::") : [void 0, uses];
677
+ const layout = this.resolve(owner, "layout", id, alias);
678
+ if (layout !== void 0) {
679
+ screen.shell = layout.key;
680
+ if (!this.shells.some((shell) => shell.owner === layout)) {
681
+ this.frame(layout);
682
+ const shellRoot = {
683
+ kind: "shell",
684
+ namespace: layout.module.namespace,
685
+ id: layout.definition.id,
686
+ profileDigest: chunkIMUVIIJR_cjs.digestV4(jcs(this.bundle.profile))
687
+ };
688
+ const children = this.expandChildren([layout.definition], {
689
+ owner: layout,
690
+ root: shellRoot,
691
+ path: [],
692
+ bindings: {},
693
+ fills: /* @__PURE__ */ new Map(),
694
+ invocationSources: [],
695
+ depth: 0
696
+ });
697
+ const slot = this.expanded.find((node) => node.slot && node.owner === layout);
698
+ this.shells.push({ owner: layout, children, slotId: (_a = slot == null ? void 0 : slot.renderedId) != null ? _a : "" });
699
+ }
700
+ }
701
+ }
702
+ screen.children = this.expandChildren([owner.definition], {
703
+ owner,
704
+ root,
705
+ path: [],
706
+ bindings: {},
707
+ fills: /* @__PURE__ */ new Map(),
708
+ invocationSources: [],
709
+ depth: 0
710
+ });
711
+ this.screens.push(screen);
712
+ if (this.expandedCount > 1e6) break;
713
+ }
714
+ }
715
+ expandChildren(nodes, context) {
716
+ var _a, _b, _c, _d, _e;
717
+ const result = [];
718
+ for (const node of nodes) {
719
+ if (++this.expandedCount > 1e6 || context.depth > 128) {
720
+ this.error("WW_LIMIT", "app.expansion-limit", node);
721
+ break;
722
+ }
723
+ if (node.kind === "use") {
724
+ const target = this.resolve(context.owner, "component", node.name, node.namespace, node);
725
+ if (target === void 0 || target.definition.kind !== "component") continue;
726
+ if (this.bundle.profile.id === "neutral-app" && this.source(node).authoredId === false)
727
+ this.error("WW_REFERENCE", "app.invocation-id-required", node);
728
+ const bindings = {};
729
+ const parameters = target.definition.parameters;
730
+ for (const name of Object.keys(node.inputs))
731
+ if (!parameters.some((parameter) => parameter.id === name))
732
+ this.error("WW_PARAMETER", "app.unknown-argument", node, { name });
733
+ for (const parameter of parameters) {
734
+ const input = node.inputs[parameter.id];
735
+ const value = input === void 0 ? parameter.default : "literal" in input ? input.literal : context.bindings[input.param];
736
+ if (!matchesType(value, parameter.type))
737
+ this.error("WW_PARAMETER", "app.argument-type", node, {
738
+ name: parameter.id,
739
+ type: parameter.type
740
+ });
741
+ else Object.defineProperty(bindings, parameter.id, { value, enumerable: true });
742
+ }
743
+ const slots = /* @__PURE__ */ new Set();
744
+ this.walk(
745
+ target.definition,
746
+ (child) => {
747
+ var _a2;
748
+ if (child.kind === "slot") slots.add((_a2 = child.name) != null ? _a2 : "");
749
+ },
750
+ ""
751
+ );
752
+ const fills = /* @__PURE__ */ new Map();
753
+ for (const fill of node.fills) {
754
+ if (!slots.has(fill.name))
755
+ this.error("WW_SLOT", "app.unknown-fill", node, { name: fill.name });
756
+ if (fills.has(fill.name))
757
+ this.error("WW_SLOT", "app.duplicate-fill", node, { name: fill.name });
758
+ fills.set(fill.name, { nodes: fill.children, context });
759
+ }
760
+ if (this.diagnostics.length > 0) continue;
761
+ const children = this.expandChildren(target.definition.children, {
762
+ ...context,
763
+ owner: target,
764
+ bindings,
765
+ fills,
766
+ path: [...context.path, { kind: "use", id: node.id }],
767
+ invocationSources: [...context.invocationSources, this.source(node)],
768
+ depth: context.depth + 1
769
+ });
770
+ for (const child of children) result.push(child);
771
+ } else if (node.kind === "repeat") {
772
+ if (this.bundle.profile.id === "neutral-app" && node.id === void 0)
773
+ this.error("WW_REFERENCE", "app.repeat-id-required", node);
774
+ if (node.count > 0 && node.count * node.children.length + this.expandedCount > 1e6) {
775
+ this.error("WW_LIMIT", "app.expansion-limit", node);
776
+ continue;
777
+ }
778
+ for (let index = 0; index < node.count; index++) {
779
+ const children = this.expandChildren(node.children, {
780
+ ...context,
781
+ path: [
782
+ ...context.path,
783
+ { kind: "repeat", id: (_a = node.id) != null ? _a : `_repeat_${this.source(node).start}`, index }
784
+ ],
785
+ depth: context.depth + 1
786
+ });
787
+ for (const child of children) result.push(child);
788
+ if (this.expandedCount > 1e6) break;
789
+ }
790
+ } else if (node.kind === "slot" && context.owner.definition.kind === "component") {
791
+ const fill = context.fills.get((_b = node.name) != null ? _b : "");
792
+ if (fill !== void 0) {
793
+ const children = this.expandChildren(fill.nodes, {
794
+ ...fill.context,
795
+ root: context.root,
796
+ path: context.path,
797
+ invocationSources: context.invocationSources,
798
+ depth: context.depth + 1
799
+ });
800
+ for (const child of children) result.push(child);
801
+ }
802
+ } else {
803
+ if (node.kind === "component" || node.kind === "layout" && node !== context.owner.definition) {
804
+ this.error("WW_SCHEMA", "app.nested-definition", node);
805
+ continue;
806
+ }
807
+ const slot = node.kind === "slot";
808
+ const source = this.source(node);
809
+ const replacement = (value) => context.owner.definition.kind === "component" ? substitute(
810
+ value,
811
+ context.bindings,
812
+ (name) => this.error("WW_PARAMETER", "app.unbound-parameter", node, { name })
813
+ ) : value;
814
+ const authored = node;
815
+ const primitive = slot ? { kind: "section", attributes: {}, children: [] } : {
816
+ ...authored,
817
+ ...node.kind === "layout" ? { kind: "section" } : {},
818
+ attributes: plain(replacement(authored.attributes)),
819
+ ...authored.label === void 0 ? {} : { label: replacement(authored.label) },
820
+ children: []
821
+ };
822
+ this.pathByNode.set(primitive, (_c = this.pathByNode.get(node)) != null ? _c : "");
823
+ if (context.owner.definition.kind === "component") this.checkSubstituted(primitive, node);
824
+ const identity = {
825
+ namespace: context.owner.module.namespace,
826
+ definitionKind: context.owner.definition.kind,
827
+ definitionId: context.owner.definition.id,
828
+ instanceRoot: context.root,
829
+ instancePath: context.path,
830
+ localId: (_e = primitive.id) != null ? _e : slot ? "_slot" : `_node_${chunkIMUVIIJR_cjs.digestV4((_d = this.pathByNode.get(node)) != null ? _d : textValue(source.start)).slice(7)}`
831
+ };
832
+ const renderedId = `wf-${chunkIMUVIIJR_cjs.digestV4(jcs({ identity, projectionId: this.bundle.profile.id })).slice(7)}`;
833
+ if (this.domIds.has(renderedId))
834
+ this.error("WW_DUPLICATE_ID", "app.rendered-identity-collision", node);
835
+ this.domIds.add(renderedId);
836
+ const expanded = {
837
+ node: primitive,
838
+ owner: context.owner,
839
+ identity,
840
+ renderedId,
841
+ source,
842
+ invocationSources: context.invocationSources,
843
+ children: [],
844
+ stateBindings: {},
845
+ ...slot ? { slot: true } : {}
846
+ };
847
+ this.expanded.push(expanded);
848
+ if (!slot && "children" in node) {
849
+ expanded.children = this.expandChildren(node.children, {
850
+ ...context,
851
+ depth: context.depth + 1
852
+ });
853
+ for (const child of expanded.children) child.parent = expanded;
854
+ }
855
+ result.push(expanded);
856
+ }
857
+ }
858
+ return result;
859
+ }
860
+ checkSubstituted(node, source) {
861
+ const name = node.kind === "nav-item" || node.kind === "dropdown-item" || node.kind === "list-item" || node.kind === "annotation-item" ? "item" : node.kind === "nav-group" ? "group" : node.kind;
862
+ const label = node.label === void 0 ? "" : ` ${dsl(node.label)}`;
863
+ let snippet = `${name}${node.number === void 0 ? "" : ` ${node.number}`}${label} ${attrsDsl(node.attributes)}${containers.has(node.kind) ? " {}" : ""}`;
864
+ if (node.kind === "table") snippet = `table ${attrsDsl(node.attributes)} {}`;
865
+ const parent = {
866
+ "nav-item": "nav",
867
+ "nav-group": "nav",
868
+ "dropdown-item": "dropdown",
869
+ "list-item": "list",
870
+ tab: "tabs",
871
+ option: "select",
872
+ "annotation-item": "annotations"
873
+ }[node.kind];
874
+ if (parent !== void 0) snippet = `${parent} { ${snippet} }`;
875
+ try {
876
+ chunkIMUVIIJR_cjs.parseV4(`page { ${snippet} }`, { languageVersion: "4.0.0" });
877
+ } catch (error) {
878
+ if (error instanceof chunkIMUVIIJR_cjs.V4ParseError)
879
+ this.error("WW_PARAMETER", "app.substituted-attribute-domain", source);
880
+ else throw error;
881
+ }
882
+ }
883
+ state(ref, expanded) {
884
+ var _a, _b, _c;
885
+ const [scope, id] = ref.split(":");
886
+ let declarations = [];
887
+ if (scope === "app") declarations = this.bundle.states;
888
+ else if (scope === "component" && expanded.owner.definition.kind === "component")
889
+ declarations = asObjects(expanded.owner.definition.attributes.states);
890
+ else if (scope === "screen" && expanded.identity.instanceRoot.kind === "screen") {
891
+ const root = expanded.identity.instanceRoot;
892
+ const owner = this.owners.get(this.key(root.namespace, "page", root.id));
893
+ declarations = asObjects(owner == null ? void 0 : owner.definition.attributes.states);
894
+ } else if (scope === "shell") {
895
+ const root = expanded.identity.instanceRoot;
896
+ const screen = root.kind === "screen" ? this.screens.find(
897
+ (screen2) => screen2.route.namespace === root.namespace && screen2.route.id === root.id
898
+ ) : void 0;
899
+ const owner = root.kind === "shell" ? this.owners.get(this.key(root.namespace, "layout", root.id)) : this.owners.get((_a = screen == null ? void 0 : screen.shell) != null ? _a : "");
900
+ declarations = asObjects(owner == null ? void 0 : owner.definition.attributes.states);
901
+ }
902
+ const state = declarations.find((state2) => state2.id === id);
903
+ if (state === void 0) this.error("WW_STATE", "app.unresolved-state", expanded.node, { ref });
904
+ else {
905
+ const root = expanded.identity.instanceRoot;
906
+ const shellOwner = root.kind === "shell" ? this.owners.get(this.key(root.namespace, "layout", root.id)) : this.owners.get(
907
+ (_c = (_b = this.screens.find(
908
+ (screen) => screen.route.namespace === root.namespace && screen.route.id === root.id
909
+ )) == null ? void 0 : _b.shell) != null ? _c : ""
910
+ );
911
+ const stateRoot = scope === "app" ? "app" : scope === "shell" ? `shell/${shellOwner == null ? void 0 : shellOwner.module.namespace}/${shellOwner == null ? void 0 : shellOwner.definition.id}` : `${root.kind}/${root.namespace}/${root.id}`;
912
+ const key = scope === "app" ? ref : scope === "component" ? `${expanded.owner.key}/${jcs(root)}/${jcs(componentPath(expanded.identity.instancePath))}/${id}` : scope === "screen" ? `screen/${root.namespace}/${root.id}/${id}` : `${stateRoot}/${id}`;
913
+ expanded.stateBindings[ref] = {
914
+ key,
915
+ initial: state.initial,
916
+ type: textValue(state.type),
917
+ lifetime: state.lifetime === "mount" ? "mount" : "session",
918
+ sensitive: state.sensitive === true,
919
+ root: stateRoot
920
+ };
921
+ }
922
+ return state;
923
+ }
924
+ semantics() {
925
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
926
+ for (const entry of this.bundle.registry.entries)
927
+ for (const binding of Array.isArray(entry.bindings) ? entry.bindings : [])
928
+ this.binding(binding);
929
+ if (asObjects(this.bundle.profile.assets).length > 0 || this.bundle.profile.fontAssetId !== void 0)
930
+ this.error("WW_ASSET", "app.asset-decoder-unavailable");
931
+ const scopes = [
932
+ { node: void 0, states: this.bundle.states, app: true },
933
+ ...[...this.owners.values()].map((owner) => ({
934
+ node: owner.definition,
935
+ states: asObjects(owner.definition.attributes.states),
936
+ app: false
937
+ }))
938
+ ];
939
+ for (const scope of scopes) {
940
+ const ids = /* @__PURE__ */ new Set();
941
+ for (const state of scope.states) {
942
+ const id = textValue(state.id);
943
+ if (!matchesType(state.initial, textValue(state.type)))
944
+ this.error("WW_STATE", "app.state-initial-type", scope.node);
945
+ if (ids.has(id)) this.error("WW_DUPLICATE_ID", "app.duplicate-state", scope.node, { id });
946
+ ids.add(id);
947
+ if (scope.app && state.lifetime !== "session")
948
+ this.error("WW_STATE", "app.app-state-lifetime", scope.node);
949
+ }
950
+ }
951
+ const fixtureIds = /* @__PURE__ */ new Set();
952
+ for (const fixture of this.bundle.fixtures) {
953
+ const id = textValue(fixture.id);
954
+ if (fixtureIds.has(id))
955
+ this.error("WW_DUPLICATE_ID", "app.duplicate-fixture", void 0, { id });
956
+ fixtureIds.add(id);
957
+ }
958
+ for (const expanded of this.expanded) {
959
+ const { node, owner } = expanded;
960
+ const attrs2 = node.attributes;
961
+ const strict = this.bundle.profile.id === "neutral-app";
962
+ if (["row", "col", "stack"].includes(node.kind) && ["left", "right", "justify"].includes(textValue(attrs2.align)))
963
+ this.error("WW_LAYOUT", "app.container-alignment", node);
964
+ if (attrs2.src !== void 0 && attrs2.src !== true)
965
+ this.error("WW_ASSET", "app.unresolved-asset", node);
966
+ const interactive = [
967
+ "input",
968
+ "textarea",
969
+ "select",
970
+ "checkbox",
971
+ "radio",
972
+ "switch",
973
+ "slider",
974
+ "button",
975
+ "link",
976
+ "nav-item",
977
+ "dropdown-item"
978
+ ];
979
+ const descendants = (root) => {
980
+ const result = [], pending = [...root.children];
981
+ while (pending.length) {
982
+ const child = pending.pop();
983
+ result.push(child);
984
+ pending.push(...child.children);
985
+ }
986
+ return result;
987
+ };
988
+ const descend = ["form", "card", "tooltip"].includes(node.kind) || attrs2.initialFocus !== void 0 || attrs2.order !== void 0 ? descendants(expanded) : [];
989
+ if (node.kind === "form") {
990
+ if (descend.some((child) => child.node.kind === "form"))
991
+ this.error("WW_FORM", "app.nested-form", node);
992
+ const names = /* @__PURE__ */ new Map();
993
+ for (const child of descend.filter(
994
+ (child2) => ["input", "textarea", "select", "checkbox", "radio", "switch", "slider"].includes(
995
+ child2.node.kind
996
+ )
997
+ )) {
998
+ const name = textValue((_a = child.node.attributes.name) != null ? _a : child.node.id);
999
+ const previous = names.get(name);
1000
+ if (previous && !(previous.node.kind === "radio" && child.node.kind === "radio" && jcs(previous.node.attributes.bind) === jcs(child.node.attributes.bind) && jcs(previous.node.attributes.value) !== jcs(child.node.attributes.value)))
1001
+ this.error("WW_FORM", "app.duplicate-field-name", child.node, { name });
1002
+ names.set(name, child);
1003
+ }
1004
+ }
1005
+ if (node.kind === "card" && (attrs2.on !== void 0 || attrs2.navigate !== void 0) && descend.some((child) => interactive.includes(child.node.kind)))
1006
+ this.error("WW_ACCESSIBILITY", "app.nested-interactive-card", node);
1007
+ if (attrs2.role !== void 0) {
1008
+ const natural = {
1009
+ button: ["button"],
1010
+ link: ["link"],
1011
+ image: ["img"],
1012
+ alert: ["alert", "status"],
1013
+ toast: ["status", "alert"],
1014
+ spinner: ["status"],
1015
+ section: ["region"]
1016
+ };
1017
+ if (!((_b = natural[node.kind]) != null ? _b : []).includes(textValue(attrs2.role)))
1018
+ this.error("WW_ACCESSIBILITY", "app.incompatible-role", node);
1019
+ }
1020
+ if (attrs2.initialFocus !== void 0 && !descend.some(
1021
+ (child) => child.node.id === attrs2.initialFocus && interactive.includes(child.node.kind) && child.node.attributes.disabled !== true
1022
+ ))
1023
+ this.error("WW_ACCESSIBILITY", "app.invalid-initial-focus", node);
1024
+ if (node.kind === "tooltip" && (expanded.children.length !== 1 || descend.slice(1).some((child) => interactive.includes(child.node.kind))))
1025
+ this.error("WW_ACCESSIBILITY", "app.tooltip-trigger", node);
1026
+ if (node.kind === "tabs" && (typeof attrs2.active === "boolean" || Number((_c = attrs2.active) != null ? _c : 0) >= expanded.children.filter((child) => child.node.kind === "tab").length || ((_e = expanded.children.filter((child) => child.node.kind === "tab")[Number((_d = attrs2.active) != null ? _d : 0)]) == null ? void 0 : _e.node.attributes.disabled) === true))
1027
+ this.error("WW_ACCESSIBILITY", "app.tab-selection", node);
1028
+ if (attrs2.order !== void 0 && attrs2.order !== 0 && (interactive.includes(node.kind) || descend.some((child) => interactive.includes(child.node.kind))))
1029
+ this.error("WW_ACCESSIBILITY", "app.visual-focus-order", node);
1030
+ for (const key of ["p", "px", "py", "pt", "pr", "pb", "pl", "gap"])
1031
+ if (attrs2[key] === "auto" || (typeof attrs2[key] === "number" ? Number(attrs2[key]) < 0 : object(attrs2[key]) && Number(attrs2[key].value) < 0))
1032
+ this.error("WW_LAYOUT", "app.invalid-spacing", node, { key });
1033
+ for (const key of ["m", "my", "mt", "mr", "mb", "ml"])
1034
+ if (attrs2[key] === "auto") this.error("WW_LAYOUT", "app.invalid-spacing", node, { key });
1035
+ for (const [minimum, maximum] of [
1036
+ ["minW", "maxW"],
1037
+ ["minH", "maxH"],
1038
+ ["minLength", "maxLength"],
1039
+ ["min", "max"]
1040
+ ])
1041
+ if (typeof attrs2[minimum] === "number" && typeof attrs2[maximum] === "number" && Number(attrs2[minimum]) > Number(attrs2[maximum]))
1042
+ this.error("WW_LAYOUT", "app.inverted-bounds", node, { minimum, maximum });
1043
+ for (const key of ["minW", "maxW", "minH", "maxH"])
1044
+ if (typeof attrs2[key] === "string")
1045
+ this.error("WW_LAYOUT", "app.bound-keyword", node, { key });
1046
+ if (attrs2.h === "fit" || typeof attrs2.flex === "number" && attrs2.flex < 0 || typeof attrs2.step === "number" && attrs2.step <= 0)
1047
+ this.error("WW_LAYOUT", "app.invalid-layout-value", node);
1048
+ if (attrs2.bold === true && attrs2.weight !== void 0 && attrs2.weight !== "bold" || attrs2.primary === true && attrs2.secondary === true || attrs2.outline === true && attrs2.ghost === true)
1049
+ this.error("WW_LAYOUT", "app.conflicting-presentation", node);
1050
+ if (node.kind !== "page" && (attrs2.x !== void 0 || attrs2.y !== void 0 || attrs2.anchor !== void 0)) {
1051
+ let parent = expanded.parent;
1052
+ while (parent && parent.node.kind !== "relative") parent = parent.parent;
1053
+ if (!parent) this.error("WW_LAYOUT", "app.missing-relative-container", node);
1054
+ }
1055
+ if (object(attrs2.h) && attrs2.h.unit === "%") {
1056
+ const height = (_h = (_f = expanded.parent) == null ? void 0 : _f.node.attributes.h) != null ? _h : (_g = expanded.parent) == null ? void 0 : _g.node.attributes.height;
1057
+ if (((_i = expanded.parent) == null ? void 0 : _i.node.kind) !== "page" && (height === void 0 || height === "auto"))
1058
+ this.error("WW_LAYOUT", "app.indefinite-percentage-height", node);
1059
+ }
1060
+ if (strict && ["input", "textarea", "select", "checkbox", "radio", "switch", "slider", "button"].includes(
1061
+ node.kind
1062
+ ) && ![node.label, attrs2.label, attrs2.aria, attrs2["aria-label"]].some(
1063
+ (label) => typeof label === "string" && label.trim().length > 0
1064
+ ))
1065
+ this.error("WW_ACCESSIBILITY", "app.missing-control-name", node);
1066
+ if (attrs2.aria !== void 0 && attrs2["aria-label"] !== void 0 && attrs2.aria !== attrs2["aria-label"])
1067
+ this.error("WW_ACCESSIBILITY", "app.conflicting-name", node);
1068
+ if (node.kind === "button" && (attrs2.buttonType === "submit" || attrs2.action === "submit" || attrs2.form !== void 0)) {
1069
+ let target = expanded.parent;
1070
+ if (typeof attrs2.form === "string")
1071
+ target = this.element(
1072
+ {
1073
+ scope: owner.definition.kind === "component" ? "component" : owner.definition.kind === "layout" ? "shell" : "screen",
1074
+ id: attrs2.form
1075
+ },
1076
+ expanded
1077
+ );
1078
+ else while (target !== void 0 && target.node.kind !== "form") target = target.parent;
1079
+ if ((target == null ? void 0 : target.node.kind) !== "form" || target.node.id === void 0)
1080
+ this.error("WW_REFERENCE", "app.missing-form", node);
1081
+ else expanded.formTarget = target.renderedId;
1082
+ if (attrs2.action === "submit" && attrs2.buttonType !== void 0 && attrs2.buttonType !== "submit")
1083
+ this.error("WW_EVENT", "app.conflicting-submit-button", node);
1084
+ }
1085
+ if (strict && node.id === void 0 && ["on", "bind", "navigate", "opens", "toggles", "action"].some(
1086
+ (key) => attrs2[key] !== void 0
1087
+ ))
1088
+ this.error("WW_REFERENCE", "app.addressed-id-required", node);
1089
+ if (attrs2.navigate !== void 0) {
1090
+ if (typeof attrs2.navigate !== "string" || !attrs2.navigate.includes("::") && /^[A-Za-z][A-Za-z0-9+.-]*:/.test(attrs2.navigate))
1091
+ this.error("WW_REFERENCE", "app.explicit-url-required", node);
1092
+ else {
1093
+ const [alias, id] = attrs2.navigate.includes("::") ? attrs2.navigate.split("::") : [void 0, attrs2.navigate];
1094
+ const target = this.resolve(owner, "page", id, alias, node);
1095
+ if (target !== void 0)
1096
+ expanded.route = { namespace: target.module.namespace, id: target.definition.id };
1097
+ }
1098
+ }
1099
+ if (typeof attrs2.href === "string" && !safeUrl(attrs2.href))
1100
+ this.error("WW_REFERENCE", "app.unsafe-url", node);
1101
+ if (attrs2.action !== void 0 && !["back", "close", "submit"].includes(textValue(attrs2.action)))
1102
+ this.error("WW_REFERENCE", "app.unknown-action", node);
1103
+ const shorthand = ["navigate", "opens", "toggles"].filter((key) => attrs2[key] !== void 0);
1104
+ if (attrs2.action === "back" || attrs2.action === "close") shorthand.push("action");
1105
+ if (shorthand.length > 1 || shorthand.length > 0 && asObjects(attrs2.on).some((handler) => handler.event === "click"))
1106
+ this.error("WW_EVENT", "app.competing-click-handlers", node);
1107
+ if (shorthand.length === 1) {
1108
+ let effect;
1109
+ if (expanded.route)
1110
+ effect = {
1111
+ kind: "navigate",
1112
+ target: { kind: "screen", screen: { ...expanded.route } },
1113
+ history: "push"
1114
+ };
1115
+ else if (attrs2.action === "back") effect = { kind: "navigateBack" };
1116
+ else {
1117
+ const scope = owner.definition.kind === "component" ? "component" : owner.definition.kind === "layout" ? "shell" : "screen";
1118
+ let id = textValue((_j = attrs2.opens) != null ? _j : attrs2.toggles);
1119
+ if (attrs2.action === "close") {
1120
+ let parent = expanded.parent;
1121
+ while (parent && !["modal", "drawer", "popover", "dropdown"].includes(parent.node.kind))
1122
+ parent = parent.parent;
1123
+ if (!(parent == null ? void 0 : parent.node.id)) this.error("WW_REFERENCE", "app.missing-owning-overlay", node);
1124
+ else id = parent.node.id;
1125
+ }
1126
+ if (id)
1127
+ effect = {
1128
+ kind: attrs2.action === "close" ? "close" : attrs2.toggles === void 0 ? "open" : "toggleOverlay",
1129
+ target: { scope, id }
1130
+ };
1131
+ }
1132
+ if (effect)
1133
+ attrs2.on = [
1134
+ ...asObjects(attrs2.on),
1135
+ {
1136
+ id: "shorthand_click",
1137
+ event: "click",
1138
+ concurrency: "drop",
1139
+ operations: [
1140
+ {
1141
+ id: "primary_click",
1142
+ executionClass: "executable",
1143
+ effect,
1144
+ after: [],
1145
+ onFailure: "stop",
1146
+ obligationRefs: []
1147
+ }
1148
+ ]
1149
+ }
1150
+ ];
1151
+ }
1152
+ const declarationScope = owner.definition.kind === "component" ? "component" : owner.definition.kind === "layout" ? "shell" : "screen";
1153
+ for (const declaration of asObjects(owner.definition.attributes.states))
1154
+ this.state(`${declarationScope}:${textValue(declaration.id)}`, expanded);
1155
+ const stack = [attrs2];
1156
+ while (stack.length > 0) {
1157
+ const value = stack.pop();
1158
+ if (Array.isArray(value)) {
1159
+ for (const item of value) stack.push(item);
1160
+ continue;
1161
+ }
1162
+ if (!object(value)) continue;
1163
+ if (typeof value.state === "string") this.state(value.state, expanded);
1164
+ for (const key of ["resultState", "statusState", "errorState", "source", "target"])
1165
+ if (typeof value[key] === "string" && /^(app|shell|screen|component):/.test(value[key]))
1166
+ this.state(value[key], expanded);
1167
+ if (object(value.read) && Array.isArray(value.read.path) && value.read.path.some(
1168
+ (part) => ["__proto__", "constructor", "prototype"].includes(textValue(part))
1169
+ ))
1170
+ this.error("WW_EFFECT", "app.unsafe-read-path", node);
1171
+ for (const [key, child] of Object.entries(value))
1172
+ if (!["literal", "initial", "states", "options"].includes(key)) stack.push(child);
1173
+ }
1174
+ if (object(attrs2.bind)) {
1175
+ const state = this.state(textValue(attrs2.bind.state), expanded);
1176
+ if (state !== void 0 && (attrs2.bind.property === "checked" && state.type !== "boolean" || attrs2.bind.property === "value" && !["number", "string", "boolean"].includes(textValue(state.type))))
1177
+ this.error("WW_STATE", "app.binding-type", node);
1178
+ }
1179
+ if (object(attrs2.data) && typeof attrs2.data.state === "string") {
1180
+ const state = this.state(attrs2.data.state, expanded);
1181
+ if (state !== void 0) {
1182
+ const rows = state.initial;
1183
+ const columns = Array.isArray(attrs2.columns) ? attrs2.columns : [];
1184
+ if (!Array.isArray(rows) || node.kind === "table" && rows.some(
1185
+ (row) => !object(row) || columns.some(
1186
+ (column) => typeof column !== "string" || !Object.hasOwn(row, column) || row[column] !== null && !["string", "number", "boolean"].includes(typeof row[column])
1187
+ )
1188
+ ))
1189
+ this.error("WW_STATE", "app.bound-data-shape", node);
1190
+ }
1191
+ }
1192
+ const handlerIds = /* @__PURE__ */ new Set(), events = /* @__PURE__ */ new Set(), operationIds = /* @__PURE__ */ new Set();
1193
+ for (const handler of asObjects(attrs2.on)) {
1194
+ const event = `${textValue(handler.event)}/${textValue((_k = handler.key) != null ? _k : "")}`;
1195
+ if (handlerIds.has(textValue(handler.id)) || events.has(event))
1196
+ this.error("WW_DUPLICATE_ID", "app.duplicate-handler", node);
1197
+ handlerIds.add(textValue(handler.id));
1198
+ events.add(event);
1199
+ const lifecycleOwner = node.kind === "page" || owner.definition.kind === "layout" && node.id === owner.definition.id;
1200
+ if (["enter", "exit"].includes(textValue(handler.event)) && !lifecycleOwner || handler.event === "submit" && node.kind !== "form")
1201
+ this.error("WW_EVENT", "app.event-owner", node);
1202
+ const previous = /* @__PURE__ */ new Set();
1203
+ for (const operation of asObjects(handler.operations)) {
1204
+ const id = textValue(operation.id);
1205
+ if (operationIds.has(id)) this.error("WW_DUPLICATE_ID", "app.duplicate-operation", node);
1206
+ operationIds.add(id);
1207
+ for (const dependency of Array.isArray(operation.after) ? operation.after : [])
1208
+ if (!previous.has(textValue(dependency)))
1209
+ this.error("WW_EFFECT", "app.operation-dependency", node, { id });
1210
+ previous.add(id);
1211
+ const effect = object(operation.effect) ? operation.effect : {};
1212
+ if (object(effect.target) && ["open", "close", "toggleOverlay", "focus", "validate"].includes(textValue(effect.kind))) {
1213
+ const target = this.element(effect.target, expanded);
1214
+ if (target === void 0 || effect.kind === "validate" && target.node.kind !== "form" || ["open", "close", "toggleOverlay"].includes(textValue(effect.kind)) && !["modal", "drawer", "popover", "dropdown", "tooltip"].includes(target.node.kind))
1215
+ this.error("WW_REFERENCE", "app.invalid-effect-target", node);
1216
+ else {
1217
+ (_l = expanded.effectTargets) != null ? _l : expanded.effectTargets = {};
1218
+ expanded.effectTargets[`${textValue(effect.target.scope)}:${textValue(effect.target.id)}`] = target.renderedId;
1219
+ }
1220
+ }
1221
+ if (handler.event === "exit" && (operation.executionClass !== "executable" || !["set", "reset", "toggle", "filter", "sort", "close"].includes(
1222
+ textValue(effect.kind)
1223
+ )))
1224
+ this.error("WW_EVENT", "app.exit-effect", node);
1225
+ if (effect.kind === "simulate") {
1226
+ const fixture = this.bundle.fixtures.find((fixture2) => fixture2.id === effect.fixtureRef);
1227
+ if (!fixtureIds.has(textValue(effect.fixtureRef)))
1228
+ this.error("WW_EFFECT", "app.missing-fixture", node);
1229
+ const result = expanded.stateBindings[textValue(effect.resultState)], status = expanded.stateBindings[textValue(effect.statusState)], error = expanded.stateBindings[textValue(effect.errorState)];
1230
+ if (!result || !status || !error || (/* @__PURE__ */ new Set([result.key, status.key, error.key])).size !== 3 || status.type !== "string" || status.initial !== "idle" || error.type !== "record" || jcs(error.initial) !== "{}")
1231
+ this.error("WW_EFFECT", "app.fixture-output-contract", node);
1232
+ else if (asObjects(fixture == null ? void 0 : fixture.steps).some(
1233
+ (step) => step.outcome === "success" && !matchesType(step.value, result.type)
1234
+ ))
1235
+ this.error("WW_EFFECT", "app.fixture-result-type", node);
1236
+ }
1237
+ if (effect.kind === "navigate" && object(effect.target)) {
1238
+ if (effect.target.kind === "screen" && object(effect.target.screen))
1239
+ this.route(effect.target.screen, node);
1240
+ if (effect.target.kind === "url" && !safeUrl(textValue(effect.target.url)))
1241
+ this.error("WW_REFERENCE", "app.unsafe-url", node);
1242
+ }
1243
+ }
1244
+ }
1245
+ }
1246
+ const stateKeys = new Set(this.bundle.states.map((state) => `app:${textValue(state.id)}`));
1247
+ for (const entry of this.expanded)
1248
+ for (const state of Object.values(entry.stateBindings)) stateKeys.add(state.key);
1249
+ if (stateKeys.size > 4096) this.error("WW_LIMIT", "app.state-count");
1250
+ for (const screen of this.screens) {
1251
+ const active = this.expanded.filter(
1252
+ (entry) => entry.identity.instanceRoot.kind === "screen" ? entry.identity.instanceRoot.namespace === screen.route.namespace && entry.identity.instanceRoot.id === screen.route.id : entry.owner.key === screen.shell
1253
+ );
1254
+ if (active.filter((entry) => entry.node.kind === "main").length > 1)
1255
+ this.error("WW_ACCESSIBILITY", "app.multiple-main-landmarks", (_m = screen.children[0]) == null ? void 0 : _m.node);
1256
+ }
1257
+ }
1258
+ element(ref, source) {
1259
+ const kind = ref.scope === "screen" ? "page" : ref.scope === "shell" ? "layout" : "component";
1260
+ const candidates = this.expanded.filter(
1261
+ (entry) => entry.node.id === ref.id && entry.owner.definition.kind === kind && (kind === "component" ? entry.owner === source.owner : true) && jcs(entry.identity.instanceRoot) === jcs(source.identity.instanceRoot) && entry.identity.instancePath.length <= source.identity.instancePath.length && entry.identity.instancePath.every(
1262
+ (step, index) => jcs(step) === jcs(source.identity.instancePath[index])
1263
+ )
1264
+ );
1265
+ candidates.sort((a, b) => b.identity.instancePath.length - a.identity.instancePath.length);
1266
+ return candidates[0];
1267
+ }
1268
+ };
1269
+ function matchesType(value, type) {
1270
+ return type === "record" ? object(value) : type === "list" ? Array.isArray(value) : typeof value === type;
1271
+ }
1272
+ function componentPath(path) {
1273
+ for (let index = path.length - 1; index >= 0; index--)
1274
+ if (path[index].kind === "use") return path.slice(0, index + 1);
1275
+ return [];
1276
+ }
1277
+ function substitute(value, bindings, missing) {
1278
+ if (typeof value === "string") {
1279
+ if (value.startsWith("$$")) return value.slice(1);
1280
+ const match = /^\$([A-Za-z_][A-Za-z0-9_-]*)$/.exec(value);
1281
+ if (match === null) return value;
1282
+ if (!Object.hasOwn(bindings, match[1])) {
1283
+ missing(match[1]);
1284
+ return value;
1285
+ }
1286
+ return bindings[match[1]];
1287
+ }
1288
+ if (Array.isArray(value)) return value.map((item) => substitute(item, bindings, missing));
1289
+ if (object(value)) {
1290
+ if (typeof value.param === "string" && Object.keys(value).length === 1) {
1291
+ if (!Object.hasOwn(bindings, value.param)) {
1292
+ missing(value.param);
1293
+ return value;
1294
+ }
1295
+ return { literal: bindings[value.param] };
1296
+ }
1297
+ return Object.fromEntries(
1298
+ Object.entries(value).map(([key, item]) => [key, substitute(item, bindings, missing)])
1299
+ );
1300
+ }
1301
+ return value;
1302
+ }
1303
+ function attrsDsl(attrs2) {
1304
+ return Object.entries(attrs2).map(([key, value]) => `${key}=${dsl(value)}`).join(" ");
1305
+ }
1306
+ function safeUrl(value) {
1307
+ if ([...value].some((character) => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127))
1308
+ return false;
1309
+ try {
1310
+ const url = new URL(value);
1311
+ return ["https:", "http:", "mailto:", "tel:"].includes(url.protocol) && !url.username && !url.password;
1312
+ } catch {
1313
+ return false;
1314
+ }
1315
+ }
1316
+ function asObjects(value) {
1317
+ return Array.isArray(value) ? value.filter(object) : [];
1318
+ }
1319
+ function linkAppV4(bundle) {
1320
+ const data = typeof bundle === "object" && bundle !== null ? bundles.get(bundle) : void 0;
1321
+ if (data === void 0) return failed([diagnostic("WW_SCHEMA", "app.untrusted-bundle")]);
1322
+ const linker = new Linker(bundle, data);
1323
+ linker.index();
1324
+ linker.imports();
1325
+ linker.references();
1326
+ linker.registryChecks();
1327
+ if (linker.diagnostics.length > 0) return failed(linker.diagnostics);
1328
+ linker.expandAll();
1329
+ linker.semantics();
1330
+ if (linker.diagnostics.length > 0) return failed(linker.diagnostics);
1331
+ const sourceMap = linker.expanded.map((entry) => ({
1332
+ renderedId: entry.renderedId,
1333
+ identity: entry.identity,
1334
+ moduleId: entry.owner.module.id,
1335
+ source: entry.source,
1336
+ invocationSources: entry.invocationSources,
1337
+ requirementRefs: stringArray(entry.node.attributes.requirementRefs),
1338
+ obligationRefs: stringArray(entry.node.attributes.obligationRefs),
1339
+ operationIds: asObjects(entry.node.attributes.on).flatMap(
1340
+ (handler) => asObjects(handler.operations).map((operation) => textValue(operation.id))
1341
+ )
1342
+ }));
1343
+ const linked = freeze({
1344
+ [linkedBrand]: true,
1345
+ kind: "LinkedApp",
1346
+ languageVersion: "4.0.0",
1347
+ id: bundle.id,
1348
+ digest: chunkIMUVIIJR_cjs.digestV4(jcs(bundle)),
1349
+ sourceMap
1350
+ });
1351
+ links.set(linked, {
1352
+ bundle,
1353
+ screens: linker.screens,
1354
+ shells: linker.shells,
1355
+ nodes: linker.expanded,
1356
+ sourceMap
1357
+ });
1358
+ return { ok: true, value: linked, diagnostics: [] };
1359
+ }
1360
+ function stringArray(value) {
1361
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1362
+ }
1363
+ function getLinkedAppData(linked) {
1364
+ return typeof linked === "object" && linked !== null ? links.get(linked) : void 0;
1365
+ }
1366
+
1367
+ // src/renderer/site/styles.ts
1368
+ function generateSiteStyles(prefix) {
1369
+ return `
1370
+ /* ===== Site composition (renderSite) ===== */
1371
+
1372
+ .${prefix}-site {
1373
+ display: flex;
1374
+ justify-content: center;
1375
+ align-items: flex-start;
1376
+ }
1377
+
1378
+ /* A shell and a standalone screen are both top-level frames: exactly one of
1379
+ them is on at a time. Screens inside a shell switch within it. */
1380
+ .${prefix}-site > .${prefix}-shell,
1381
+ .${prefix}-site > .${prefix}-screen {
1382
+ display: none;
1383
+ }
1384
+
1385
+ .${prefix}-site > .${prefix}-shell.${prefix}-on {
1386
+ display: flex;
1387
+ flex-direction: column;
1388
+ }
1389
+
1390
+ .${prefix}-site > .${prefix}-screen.${prefix}-on {
1391
+ display: block;
1392
+ }
1393
+
1394
+ /* A site document is a running prototype, not a canvas thumbnail. The page
1395
+ renderer sizes a page to its authored viewport and clips what runs past it
1396
+ with an inline \`overflow: hidden\` \u2014 right for a thumbnail, where a page is a
1397
+ picture, and wrong here, where it is a screen someone is using: a settings
1398
+ page authored 14x taller than its viewport would keep 93% of itself
1399
+ unreachable. The frame stays exactly as authored and only the overflow
1400
+ becomes reachable. \`!important\` is unavoidable and confined to this rule:
1401
+ the declaration being overridden is inline. */
1402
+ .${prefix}-site .${prefix}-page {
1403
+ overflow: auto !important;
1404
+ }
1405
+
1406
+ /* The slot is where a layout hands its frame over to page content, so it takes
1407
+ the space a page's own root would have taken. */
1408
+ .${prefix}-site .${prefix}-slot {
1409
+ display: flex;
1410
+ flex-direction: column;
1411
+ flex: 1;
1412
+ min-height: 0;
1413
+ }
1414
+
1415
+ .${prefix}-site .${prefix}-slot > .${prefix}-screen {
1416
+ display: none;
1417
+ }
1418
+
1419
+ .${prefix}-site .${prefix}-slot > .${prefix}-screen.${prefix}-on {
1420
+ display: flex;
1421
+ flex-direction: column;
1422
+ flex: 1;
1423
+ min-height: 0;
1424
+ }
1425
+
1426
+ /* Page-root layout rules key off \`.${prefix}-page > \u2026\`. A screen composed into
1427
+ a shell is one level further in, so the same rules are restated for it \u2014
1428
+ otherwise a sidebar row would stop filling its frame the moment a page
1429
+ started using a layout. */
1430
+ .${prefix}-site .${prefix}-screen > .${prefix}-col {
1431
+ flex: 1;
1432
+ min-height: 0;
1433
+ }
1434
+
1435
+ .${prefix}-site .${prefix}-screen > .${prefix}-row:has(.${prefix}-sidebar),
1436
+ .${prefix}-site .${prefix}-screen > .${prefix}-row:has(.${prefix}-main),
1437
+ .${prefix}-site .${prefix}-screen > .${prefix}-col > .${prefix}-row:has(.${prefix}-sidebar),
1438
+ .${prefix}-site .${prefix}-screen > .${prefix}-col > .${prefix}-row:has(.${prefix}-main) {
1439
+ flex: 1;
1440
+ min-height: 0;
1441
+ align-items: stretch;
1442
+ }
1443
+
1444
+ /* Overlays something opens start closed; overlays nothing opens are part of
1445
+ the screen as drawn and never get this class. Two class selectors so the
1446
+ rule outranks \`.${prefix}-modal-backdrop\` / \`.${prefix}-drawer\` on
1447
+ specificity, not only on order. */
1448
+ .${prefix}-site .${prefix}-closed {
1449
+ display: none;
1450
+ }
1451
+
1452
+ /* State guards use the native hidden/disabled semantics. Component display
1453
+ rules can be more specific than the browser stylesheet, so hidden is held at
1454
+ the site boundary explicitly. */
1455
+ .${prefix}-site [hidden] {
1456
+ display: none !important;
1457
+ }
1458
+ `;
1459
+ }
1460
+
1461
+ // src/renderer/site/runtime.ts
1462
+ var ID_SCOPE_ATTR = "data-id-scope";
1463
+ var [NAVIGATE_ATTR, OPENS_ATTR, TOGGLES_ATTR, ACTION_ATTR] = chunkZPHNXJRY_cjs.INTERACTIVE_ATTR_NAMES;
1464
+ function embedJson(value) {
1465
+ return JSON.stringify(value).replace(/</g, "\\u003C");
1466
+ }
1467
+ function siteRuntime(registry, prefix) {
1468
+ return `(function () {
1469
+ 'use strict';
1470
+ var P = ${embedJson(prefix)};
1471
+ var R = ${embedJson(registry)};
1472
+ var ON = P + '-on';
1473
+ var CLOSED = P + '-closed';
1474
+ var NAV_ACTIVE = P + '-nav-link-active';
1475
+ var site = document.querySelector('.' + P + '-site');
1476
+ if (!site) return;
1477
+
1478
+ var screens = {};
1479
+ var order = [];
1480
+ var shellOf = {};
1481
+ var hosts = site.querySelectorAll('[data-screen]');
1482
+ for (var i = 0; i < hosts.length; i++) {
1483
+ var key = hosts[i].getAttribute('data-screen');
1484
+ // First-wins: two pages can share a name, and the model already decided
1485
+ // which one that name resolves to. The DOM must not disagree with it.
1486
+ if (!Object.prototype.hasOwnProperty.call(screens, key)) {
1487
+ screens[key] = hosts[i];
1488
+ order.push(key);
1489
+ shellOf[key] = shellFor(hosts[i]);
1490
+ }
1491
+ }
1492
+ var shells = site.querySelectorAll('.' + P + '-shell');
1493
+ var state = {};
1494
+ var initial = {};
1495
+ var stateTypes = {};
1496
+ for (var st = 0; st < R.states.length; st++) {
1497
+ var declaration = R.states[st];
1498
+ state[declaration.name] = declaration.initial;
1499
+ initial[declaration.name] = declaration.initial;
1500
+ stateTypes[declaration.name] = declaration.valueType;
1501
+ }
1502
+
1503
+ function diagnostic(code, detail) {
1504
+ site.setAttribute('data-wf-runtime-diagnostic', code + ':' + detail);
1505
+ }
1506
+
1507
+ function hasState(name) {
1508
+ return Object.prototype.hasOwnProperty.call(state, name);
1509
+ }
1510
+
1511
+ function guardPasses(guard) {
1512
+ return !guard || (hasState(guard.state) && state[guard.state] === guard.equals);
1513
+ }
1514
+
1515
+ function valueMatches(name, value) {
1516
+ return hasState(name) && typeof value === stateTypes[name];
1517
+ }
1518
+
1519
+ function parseJson(value, fallback) {
1520
+ if (!value) return fallback;
1521
+ try {
1522
+ return JSON.parse(value);
1523
+ } catch (e) {
1524
+ return fallback;
1525
+ }
1526
+ }
1527
+
1528
+ function handlerId(signature) {
1529
+ for (var i = 0; i < R.handlers.length; i++) {
1530
+ if (JSON.stringify(R.handlers[i]) === signature) return i;
1531
+ }
1532
+ return -1;
1533
+ }
1534
+
1535
+ function contains(ids, id) {
1536
+ for (var i = 0; i < ids.length; i++) if (ids[i] === id) return true;
1537
+ return false;
1538
+ }
1539
+
1540
+ function shellHandlersFor(key) {
1541
+ var shell = shellOf[key];
1542
+ if (!shell) return [];
1543
+ return R.shellHandlers[shell.getAttribute('data-layout')] || [];
1544
+ }
1545
+
1546
+ function interactionFor(key, element, signature) {
1547
+ var id = handlerId(signature);
1548
+ if (id < 0) return null;
1549
+ var ids = isChrome(element) ? shellHandlersFor(key) : R.screenHandlers[String(key)] || [];
1550
+ return contains(ids, id) ? R.handlers[id] : null;
1551
+ }
1552
+
1553
+ function routeAllowed(key, target) {
1554
+ var groups = [R.screenHandlers[String(key)] || [], shellHandlersFor(key)];
1555
+ for (var i = 0; i < groups.length; i++) {
1556
+ for (var j = 0; j < groups[i].length; j++) {
1557
+ var handler = R.handlers[groups[i][j]];
1558
+ if (!handler || !guardPasses(handler.guard)) continue;
1559
+ for (var e = 0; e < handler.effects.length; e++) {
1560
+ var effect = handler.effects[e];
1561
+ if (effect.kind === 'navigate' && effect.target === target) return true;
1562
+ }
1563
+ }
1564
+ }
1565
+ return false;
1566
+ }
1567
+
1568
+ /** The shell a screen is hosted in, or null when it stands alone. */
1569
+ function shellFor(node) {
1570
+ var el = node.parentNode;
1571
+ while (el && el !== site) {
1572
+ if (el.classList && el.classList.contains(P + '-shell')) return el;
1573
+ el = el.parentNode;
1574
+ }
1575
+ return null;
1576
+ }
1577
+
1578
+ /** True for an element that belongs to a shell's own chrome, not to a screen. */
1579
+ function isChrome(el) {
1580
+ return !(el.closest && el.closest('[data-screen]'));
1581
+ }
1582
+
1583
+ /**
1584
+ * The id prefix a container namespaces its contents under.
1585
+ *
1586
+ * Read from the document rather than rebuilt from the scheme that produced
1587
+ * it: the renderer decides how scopes are spelled, and a second spelling in
1588
+ * here could disagree with the first without anything noticing.
1589
+ */
1590
+ function scopeOf(el) {
1591
+ return (el && el.getAttribute(${embedJson(ID_SCOPE_ATTR)})) || '';
1592
+ }
1593
+
1594
+ /** Match one id exactly, whatever characters an author put in it. */
1595
+ function idSelector(id) {
1596
+ return '[id="' + String(id).replace(/["\\\\]/g, '\\\\$&') + '"]';
1597
+ }
1598
+
1599
+ /** Screen key for a navigate target or a fragment, or null. */
1600
+ function resolve(target) {
1601
+ if (target === null || target === undefined) return null;
1602
+ var name = String(target).trim();
1603
+ if (name === '') return null;
1604
+ if (Object.prototype.hasOwnProperty.call(R.names, name)) return String(R.names[name]);
1605
+ return Object.prototype.hasOwnProperty.call(screens, name) ? name : null;
1606
+ }
1607
+
1608
+ /**
1609
+ * The overlay an intent addresses, from the point of view of one screen.
1610
+ *
1611
+ * An overlay id is scoped to the thing that declares it, and composition gives
1612
+ * a screen two declaring contexts: the page itself, and the shell it is hosted
1613
+ * in. A \`drawer\` written into a layout belongs to every screen that uses that
1614
+ * layout, so the screen is searched first and its shell second \u2014 nearest
1615
+ * declaration wins, and a page can shadow a shell's overlay with its own.
1616
+ *
1617
+ * The shell is searched for chrome only. Its hosted screens are descendants of
1618
+ * it, so an unfiltered query there would let one screen's trigger reach into
1619
+ * another screen that happens to reuse the id.
1620
+ *
1621
+ * The two searches use two different selectors, because the two contexts
1622
+ * namespace their ids separately: the authored name is composed with the
1623
+ * scope each container publishes. The trigger's attribute is never rewritten
1624
+ * \u2014 \`opens="confirm"\` means the \`confirm\` its author could see, and which
1625
+ * element that is depends on where the search is standing.
1626
+ */
1627
+ function overlayFor(key, id) {
1628
+ if (!id) return null;
1629
+
1630
+ var screen = screens[key];
1631
+ if (screen) {
1632
+ var own = screen.querySelector(idSelector(scopeOf(screen) + id));
1633
+ if (own) return own;
1634
+ }
1635
+
1636
+ var shell = shellOf[key];
1637
+ if (shell) {
1638
+ var candidates = shell.querySelectorAll(idSelector(scopeOf(shell) + id));
1639
+ for (var i = 0; i < candidates.length; i++) {
1640
+ if (isChrome(candidates[i])) return candidates[i];
1641
+ }
1642
+ }
1643
+ return null;
1644
+ }
1645
+
1646
+ /** Every element that opens or toggles something, from one screen's view. */
1647
+ function triggersFor(key) {
1648
+ var selector = '[' + ${embedJson(OPENS_ATTR)} + '],[' + ${embedJson(TOGGLES_ATTR)} + ']';
1649
+ var found = [];
1650
+ var i;
1651
+
1652
+ var screen = screens[key];
1653
+ if (screen) {
1654
+ var own = screen.querySelectorAll(selector);
1655
+ for (i = 0; i < own.length; i++) found.push(own[i]);
1656
+ }
1657
+
1658
+ var shell = shellOf[key];
1659
+ if (shell) {
1660
+ var chrome = shell.querySelectorAll(selector);
1661
+ for (i = 0; i < chrome.length; i++) {
1662
+ if (isChrome(chrome[i])) found.push(chrome[i]);
1663
+ }
1664
+ }
1665
+ return found;
1666
+ }
1667
+
1668
+ /**
1669
+ * Close every overlay something points at, from one screen's point of view.
1670
+ *
1671
+ * An overlay nothing points at is left visible: a wireframe that draws a
1672
+ * modal in order to describe it is not waiting for a click.
1673
+ */
1674
+ function closeOverlays(key) {
1675
+ var triggers = triggersFor(key);
1676
+ for (var i = 0; i < triggers.length; i++) {
1677
+ var id =
1678
+ triggers[i].getAttribute(${embedJson(OPENS_ATTR)}) ||
1679
+ triggers[i].getAttribute(${embedJson(TOGGLES_ATTR)});
1680
+ var overlay = overlayFor(key, id);
1681
+ if (overlay) overlay.classList.add(CLOSED);
1682
+ }
1683
+ }
1684
+
1685
+ function initOverlays() {
1686
+ for (var i = 0; i < order.length; i++) closeOverlays(order[i]);
1687
+ }
1688
+
1689
+ function applyOutcomes() {
1690
+ var visible = site.querySelectorAll('[' + ${embedJson(chunkZPHNXJRY_cjs.VISIBLE_GUARD_ATTR)} + ']');
1691
+ for (var i = 0; i < visible.length; i++) {
1692
+ var visibleGuard = parseJson(visible[i].getAttribute(${embedJson(chunkZPHNXJRY_cjs.VISIBLE_GUARD_ATTR)}), null);
1693
+ if (guardPasses(visibleGuard)) visible[i].removeAttribute('hidden');
1694
+ else visible[i].setAttribute('hidden', 'hidden');
1695
+ }
1696
+
1697
+ var enabled = site.querySelectorAll('[' + ${embedJson(chunkZPHNXJRY_cjs.ENABLED_GUARD_ATTR)} + ']');
1698
+ for (var j = 0; j < enabled.length; j++) {
1699
+ var enabledGuard = parseJson(enabled[j].getAttribute(${embedJson(chunkZPHNXJRY_cjs.ENABLED_GUARD_ATTR)}), null);
1700
+ if (guardPasses(enabledGuard)) {
1701
+ enabled[j].removeAttribute('disabled');
1702
+ enabled[j].removeAttribute('aria-disabled');
1703
+ } else {
1704
+ enabled[j].setAttribute('disabled', 'disabled');
1705
+ enabled[j].setAttribute('aria-disabled', 'true');
1706
+ }
1707
+ }
1708
+ }
1709
+
1710
+ function applyVariantScopes() {
1711
+ var screen = current === null ? null : screens[current];
1712
+ var variant = screen ? screen.getAttribute('data-wf-variant') : null;
1713
+ var scoped = site.querySelectorAll('[' + ${embedJson(chunkZPHNXJRY_cjs.VARIANT_SCOPE_ATTR)} + ']');
1714
+ for (var i = 0; i < scoped.length; i++) {
1715
+ var names = parseJson(scoped[i].getAttribute(${embedJson(chunkZPHNXJRY_cjs.VARIANT_SCOPE_ATTR)}), []);
1716
+ var visible = variant !== null && names.indexOf(variant) >= 0;
1717
+ if (visible) scoped[i].removeAttribute('hidden');
1718
+ else scoped[i].setAttribute('hidden', 'hidden');
1719
+ }
1720
+ }
1721
+
1722
+ function applyEffects(handler) {
1723
+ for (var i = 0; i < handler.effects.length; i++) {
1724
+ var effect = handler.effects[i];
1725
+ if (effect.kind === 'navigate') {
1726
+ var route = resolve(effect.target);
1727
+ if (route !== null) show(route, true);
1728
+ else diagnostic('unknown-route', effect.target);
1729
+ } else if (effect.kind === 'set') {
1730
+ if (valueMatches(effect.state, effect.value)) state[effect.state] = effect.value;
1731
+ else diagnostic('invalid-set', effect.state);
1732
+ } else if (effect.kind === 'reset') {
1733
+ if (hasState(effect.state)) state[effect.state] = initial[effect.state];
1734
+ else diagnostic('unknown-state', effect.state);
1735
+ } else if (effect.kind === 'toggle') {
1736
+ if (stateTypes[effect.state] === 'boolean') state[effect.state] = !state[effect.state];
1737
+ else diagnostic('invalid-toggle', effect.state);
1738
+ } else if (effect.kind === 'open') {
1739
+ var opened = overlayFor(current, effect.target);
1740
+ if (opened) opened.classList.remove(CLOSED);
1741
+ else diagnostic('unknown-overlay', effect.target);
1742
+ } else if (effect.kind === 'close') {
1743
+ var closed = overlayFor(current, effect.target);
1744
+ if (closed) closed.classList.add(CLOSED);
1745
+ else diagnostic('unknown-overlay', effect.target);
1746
+ }
1747
+ }
1748
+ applyOutcomes();
1749
+ }
1750
+
1751
+ var current = null;
1752
+
1753
+ /**
1754
+ * The one place \`active\` is decided.
1755
+ *
1756
+ * Every shell nav item carries its own \`navigate\` target, including the item
1757
+ * for the screen being shown, and the class is applied to whichever of them
1758
+ * resolves to the current screen. Authoring it by hand is what produced items
1759
+ * marked active while pointing somewhere else; there is nothing to author
1760
+ * here, so there is nothing to get wrong.
1761
+ *
1762
+ * Only the shell's own chrome is derived. Links inside a screen belong to
1763
+ * that screen's content, where an authored \`active\` still means what its
1764
+ * author meant.
1765
+ */
1766
+ function markActive(key) {
1767
+ for (var i = 0; i < shells.length; i++) {
1768
+ var links = shells[i].querySelectorAll('[' + ${embedJson(NAVIGATE_ATTR)} + ']');
1769
+ for (var j = 0; j < links.length; j++) {
1770
+ if (!isChrome(links[j])) continue;
1771
+ // An external target names no screen, so it can never be the current
1772
+ // one. Same marker, same skip: the registry is not consulted.
1773
+ if (links[j].hasAttribute(${embedJson(chunkZPHNXJRY_cjs.EXTERNAL_NAVIGATE_ATTR)})) continue;
1774
+ var target = resolve(links[j].getAttribute(${embedJson(NAVIGATE_ATTR)}));
1775
+ if (target === key) links[j].classList.add(NAV_ACTIVE);
1776
+ else links[j].classList.remove(NAV_ACTIVE);
1777
+ }
1778
+ }
1779
+ }
1780
+
1781
+ function show(key, writeFragment) {
1782
+ var screen = screens[key];
1783
+ if (!screen) return false;
1784
+ if (key === current) return true;
1785
+
1786
+ for (var i = 0; i < order.length; i++) {
1787
+ var k = order[i];
1788
+ if (k === key) screens[k].classList.add(ON);
1789
+ else screens[k].classList.remove(ON);
1790
+ }
1791
+ var shell = shellOf[key];
1792
+ for (var s = 0; s < shells.length; s++) {
1793
+ if (shells[s] === shell) shells[s].classList.add(ON);
1794
+ else shells[s].classList.remove(ON);
1795
+ }
1796
+
1797
+ // Which screen is current is *state*; \`data-screen\` is the *identity* of a
1798
+ // screen host. Writing the state under the identity attribute makes the site
1799
+ // root answer \`[data-screen]\` and shadow every host below it, which is
1800
+ // precisely the conflation this feature exists to remove.
1801
+ site.setAttribute('data-current-screen', key);
1802
+ current = key;
1803
+ closeOverlays(key);
1804
+ markActive(key);
1805
+ applyVariantScopes();
1806
+ applyOutcomes();
1807
+
1808
+ if (writeFragment) {
1809
+ var fragment = R.fragments[Number(key)] || key;
1810
+ // The resulting hashchange re-enters show() with the key already current,
1811
+ // which returns early \u2014 the fragment and the screen cannot fight.
1812
+ if (location.hash.slice(1) !== fragment) location.hash = fragment;
1813
+ }
1814
+ return true;
1815
+ }
1816
+
1817
+ function fromFragment() {
1818
+ var raw = location.hash.slice(1);
1819
+ if (raw === '') return null;
1820
+ var decoded = raw;
1821
+ try {
1822
+ decoded = decodeURIComponent(raw);
1823
+ } catch (e) {
1824
+ decoded = raw;
1825
+ }
1826
+ return resolve(decoded);
1827
+ }
1828
+
1829
+ document.addEventListener('click', function (event) {
1830
+ var typed = event.target.closest ? event.target.closest('[' + ${embedJson(chunkZPHNXJRY_cjs.TYPED_INTERACTION_ATTR)} + ']') : null;
1831
+ if (typed) {
1832
+ var signatures = parseJson(typed.getAttribute(${embedJson(chunkZPHNXJRY_cjs.TYPED_INTERACTION_ATTR)}), []);
1833
+ var matched = false;
1834
+ for (var typedIndex = 0; typedIndex < signatures.length; typedIndex++) {
1835
+ var normalized = interactionFor(current, typed, signatures[typedIndex]);
1836
+ if (!normalized) continue;
1837
+ matched = true;
1838
+ if (guardPasses(normalized.guard)) applyEffects(normalized);
1839
+ }
1840
+ if (matched) {
1841
+ event.preventDefault();
1842
+ return;
1843
+ }
1844
+ }
1845
+
1846
+ var mover = event.target.closest ? event.target.closest('[' + ${embedJson(NAVIGATE_ATTR)} + ']') : null;
1847
+ // The marker is a decision the renderer already made, not a hint to check.
1848
+ // Reading it here \u2014 rather than re-deriving "is this a URL" from the string \u2014
1849
+ // is what keeps that rule in one place; a second copy in generated JS is a
1850
+ // drift surface, and the two disagreeing is how a runtime ends up hunting
1851
+ // for a screen named "https://\u2026". Marked elements skip the registry
1852
+ // entirely: the lookup is not attempted, not merely discarded.
1853
+ if (mover && !mover.hasAttribute(${embedJson(chunkZPHNXJRY_cjs.EXTERNAL_NAVIGATE_ATTR)})) {
1854
+ var navigateTarget = mover.getAttribute(${embedJson(NAVIGATE_ATTR)});
1855
+ var key = routeAllowed(current, navigateTarget) ? resolve(navigateTarget) : null;
1856
+ if (key !== null) {
1857
+ event.preventDefault();
1858
+ show(key, true);
1859
+ return;
1860
+ }
1861
+ }
1862
+
1863
+ var opener = event.target.closest ? event.target.closest('[' + ${embedJson(OPENS_ATTR)} + ']') : null;
1864
+ if (opener) {
1865
+ var opened = overlayFor(current, opener.getAttribute(${embedJson(OPENS_ATTR)}));
1866
+ if (opened) {
1867
+ event.preventDefault();
1868
+ opened.classList.remove(CLOSED);
1869
+ return;
1870
+ }
1871
+ }
1872
+
1873
+ var toggler = event.target.closest ? event.target.closest('[' + ${embedJson(TOGGLES_ATTR)} + ']') : null;
1874
+ if (toggler) {
1875
+ var toggled = overlayFor(current, toggler.getAttribute(${embedJson(TOGGLES_ATTR)}));
1876
+ if (toggled) {
1877
+ event.preventDefault();
1878
+ toggled.classList.toggle(CLOSED);
1879
+ return;
1880
+ }
1881
+ }
1882
+
1883
+ var actor = event.target.closest ? event.target.closest('[' + ${embedJson(ACTION_ATTR)} + ']') : null;
1884
+ if (actor) {
1885
+ // Only the two structural actions are the runtime's business. Every other
1886
+ // value is an opaque handler id the wireframe never promised to run.
1887
+ var action = (actor.getAttribute(${embedJson(ACTION_ATTR)}) || '').trim();
1888
+ if (action === 'close' || action === 'back') {
1889
+ event.preventDefault();
1890
+ closeOverlays(current);
1891
+ return;
1892
+ }
1893
+ if (action !== '') diagnostic('unknown-action', action);
1894
+ }
1895
+
1896
+ // Clicking a modal's own backdrop dismisses it, the way a real one does.
1897
+ var backdrop = event.target;
1898
+ if (backdrop && backdrop.classList && backdrop.classList.contains(P + '-modal-backdrop')) {
1899
+ backdrop.classList.add(CLOSED);
1900
+ }
1901
+
1902
+ // Every branch above cancels the default only when it RESOLVES an intent,
1903
+ // which is right for them \u2014 an unresolved intent must not silently look
1904
+ // handled. But that leaves the anchors the renderer marked as having no
1905
+ // destination at all, and a wireframe is mostly those: nav labels, tabs,
1906
+ // breadcrumbs, placeholder links. Their default action is a navigation, and
1907
+ // in the \`srcdoc\` frame every consumer mounts this output in, the inert
1908
+ // \`href\` resolves against the EMBEDDER's URL \u2014 so the click walks the frame
1909
+ // out of the wireframe and loads the host app inside itself, refetching its
1910
+ // assets. Measured on a 20-screen demo: 44 such anchors, frame URL
1911
+ // \`about:srcdoc\` -> \`<host page>#\`.
1912
+ //
1913
+ // The test is the renderer's own statement (\`INERT_HREF\`), read back, not a
1914
+ // guess about what the string means: an authored \`href\`, and a URL-shaped
1915
+ // \`navigate\` moved into one, are real destinations and are left alone. An
1916
+ // authored fragment link is left alone too \u2014 the hashchange handler below is
1917
+ // how that is supposed to work.
1918
+ var link = event.target.closest ? event.target.closest('a[href]') : null;
1919
+ if (link && link.getAttribute('href') === ${embedJson(chunkZPHNXJRY_cjs.INERT_HREF)}) event.preventDefault();
1920
+ });
1921
+
1922
+ document.addEventListener('keydown', function (event) {
1923
+ if (event.key === 'Escape' && current !== null) closeOverlays(current);
1924
+ });
1925
+
1926
+ window.addEventListener('hashchange', function () {
1927
+ var key = fromFragment();
1928
+ if (key !== null) show(key, false);
1929
+ });
1930
+
1931
+ initOverlays();
1932
+ var start = fromFragment();
1933
+ if (start === null) start = String(R.entry);
1934
+ if (!show(start, false)) show(String(R.entry), false);
1935
+ })();`;
1936
+ }
1937
+
1938
+ // src/renderer/site/index.ts
1939
+ var DEFAULT_PREFIX = "wf";
1940
+ var screenScope = (index) => `s${index}-`;
1941
+ var shellScope = (index) => `l${index}-`;
1942
+ function escapeAttr(value) {
1943
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1944
+ }
1945
+ function escapeText(value) {
1946
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1947
+ }
1948
+ function attrs(pairs) {
1949
+ return pairs.filter((pair) => pair[1] !== void 0).map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("");
1950
+ }
1951
+ function renderHostedScreen(screen, shell, make, prefix) {
1952
+ const { width, height } = chunkZPHNXJRY_cjs.resolvePageDimensions(screen.page);
1953
+ const conflict = width !== shell.width || height !== shell.height ? `${width}x${height}` : void 0;
1954
+ const scope = screenScope(screen.index);
1955
+ const marks = attrs([
1956
+ ["data-screen", String(screen.index)],
1957
+ ["data-screen-name", screen.name],
1958
+ ["data-wf-variant", screen.variant],
1959
+ [ID_SCOPE_ATTR, scope],
1960
+ ["data-wf-viewport-conflict", conflict]
1961
+ ]);
1962
+ const content = make(scope).renderFragment(screen.page.children);
1963
+ return `<div class="${prefix}-screen"${marks}>
1964
+ ${content}
1965
+ </div>`;
1966
+ }
1967
+ function renderStandaloneScreen(screen, make, prefix) {
1968
+ var _a, _b;
1969
+ const scope = screenScope(screen.index);
1970
+ const marks = attrs([
1971
+ ["data-screen", String(screen.index)],
1972
+ ["data-screen-name", screen.name],
1973
+ ["data-wf-variant", screen.variant],
1974
+ [ID_SCOPE_ATTR, scope],
1975
+ ["data-wf-uses-unresolved", (_a = screen.miss) == null ? void 0 : _a.uses],
1976
+ ["data-wf-uses-reason", (_b = screen.miss) == null ? void 0 : _b.reason]
1977
+ ]);
1978
+ const page = make(scope).render({ type: "Document", children: [screen.page] }).html;
1979
+ return `<div class="${prefix}-screen"${marks}>
1980
+ ${page}
1981
+ </div>`;
1982
+ }
1983
+ function renderShell(shell, index, make, prefix) {
1984
+ const hosted = shell.screens.map((screen) => renderHostedScreen(screen, shell, make, prefix)).join("\n");
1985
+ const scope = shellScope(index);
1986
+ const style = `position: relative; width: ${shell.width}px; height: ${shell.height}px; overflow: hidden`;
1987
+ const marks = attrs([
1988
+ ["data-layout", shell.name],
1989
+ [ID_SCOPE_ATTR, scope],
1990
+ ["data-viewport-width", String(shell.width)],
1991
+ ["data-viewport-height", String(shell.height)]
1992
+ ]);
1993
+ const body = make(scope).renderFragment(shell.layout.children, hosted);
1994
+ return `<div class="${prefix}-page ${prefix}-shell" style="${style}"${marks}>
1995
+ ${body}
1996
+ </div>`;
1997
+ }
1998
+ function resolveEntry(model, options) {
1999
+ var _a;
2000
+ const fallback = Math.max(model.entry, 0);
2001
+ const requested = (_a = options.entry) == null ? void 0 : _a.trim();
2002
+ if (requested === void 0 || requested.length === 0) return { index: fallback };
2003
+ const index = model.names.get(requested);
2004
+ if (index === void 0) return { index: fallback, unresolved: requested };
2005
+ return { index };
2006
+ }
2007
+ function resolveTitle(model, options, entry) {
2008
+ var _a, _b;
2009
+ if (options.title !== void 0) return options.title;
2010
+ const page = (_a = model.screens[entry]) == null ? void 0 : _a.page;
2011
+ const title = (_b = page == null ? void 0 : page.title) == null ? void 0 : _b.trim();
2012
+ return title !== void 0 && title.length > 0 ? title : "Wireframe";
2013
+ }
2014
+ function compactRuntimeInteractions(model, interactions) {
2015
+ var _a;
2016
+ const handlers = [];
2017
+ const handlerIds = /* @__PURE__ */ new Map();
2018
+ const screenHandlers = {};
2019
+ const shellHandlers = {};
2020
+ const intern = (signature, handler) => {
2021
+ const existing = handlerIds.get(signature);
2022
+ if (existing !== void 0) return existing;
2023
+ const id = handlers.length;
2024
+ handlerIds.set(signature, id);
2025
+ handlers.push(handler);
2026
+ return id;
2027
+ };
2028
+ const add = (owner, key, id) => {
2029
+ var _a2;
2030
+ const ids = (_a2 = owner[key]) != null ? _a2 : owner[key] = [];
2031
+ if (!ids.includes(id)) ids.push(id);
2032
+ };
2033
+ for (const interaction of interactions) {
2034
+ const id = intern(interaction.signature, interaction.handler);
2035
+ if (interaction.source === "screen") {
2036
+ add(screenHandlers, String(interaction.screenIndex), id);
2037
+ continue;
2038
+ }
2039
+ const shell = (_a = model.screens[interaction.screenIndex]) == null ? void 0 : _a.shell;
2040
+ if (shell !== void 0) add(shellHandlers, shell, id);
2041
+ }
2042
+ return { handlers, screenHandlers, shellHandlers };
2043
+ }
2044
+ function renderSite(document, options = {}) {
2045
+ var _a;
2046
+ const prefix = (_a = options.classPrefix) != null ? _a : DEFAULT_PREFIX;
2047
+ document = chunkZPHNXJRY_cjs.expandRepeats(expandVariants(document));
2048
+ const model = chunkZPHNXJRY_cjs.buildSiteModel(document);
2049
+ const interactionModel = chunkZPHNXJRY_cjs.collectInteractions(document);
2050
+ const make = (idScope) => new chunkZPHNXJRY_cjs.HtmlRenderer({
2051
+ theme: options.theme,
2052
+ classPrefix: prefix,
2053
+ background: options.background,
2054
+ annotationStyle: options.annotationStyle,
2055
+ includeStyles: false,
2056
+ idScope
2057
+ });
2058
+ const shells = model.shells.map((shell, index) => renderShell(shell, index, make, prefix)).join("\n");
2059
+ const standalone = model.screens.filter((screen) => screen.shell === void 0).map((screen) => renderStandaloneScreen(screen, make, prefix)).join("\n");
2060
+ const theme = options.theme === "dark" ? chunkZPHNXJRY_cjs.darkTheme : chunkZPHNXJRY_cjs.defaultTheme;
2061
+ const css = chunkZPHNXJRY_cjs.generateStyles(theme, prefix, options.annotationStyle) + generateSiteStyles(prefix);
2062
+ const entry = resolveEntry(model, options);
2063
+ const fragments = model.screens.map((screen) => {
2064
+ var _a2;
2065
+ return (_a2 = screen.name) != null ? _a2 : String(screen.index);
2066
+ });
2067
+ const runtimeInteractions = compactRuntimeInteractions(model, interactionModel.interactions);
2068
+ const runtime = siteRuntime(
2069
+ {
2070
+ names: Object.fromEntries(model.names),
2071
+ fragments,
2072
+ entry: entry.index,
2073
+ states: interactionModel.states,
2074
+ ...runtimeInteractions,
2075
+ diagnostics: interactionModel.diagnostics
2076
+ },
2077
+ prefix
2078
+ );
2079
+ const body = [shells, standalone].filter((part) => part.length > 0).join("\n");
2080
+ const siteAttrs = attrs([
2081
+ ["data-screen-count", String(model.screens.length)],
2082
+ ["data-shell-count", String(model.shells.length)],
2083
+ ["data-wf-entry-unresolved", entry.unresolved],
2084
+ ["data-wf-diagnostic-count", String(interactionModel.diagnostics.length)]
2085
+ ]);
2086
+ return `<!DOCTYPE html>
2087
+ <html lang="en">
2088
+ <head>
2089
+ <meta charset="UTF-8">
2090
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2091
+ <title>${escapeText(resolveTitle(model, options, entry.index))}</title>
2092
+ <style>
2093
+ html, body {
2094
+ margin: 0;
2095
+ padding: 0;
2096
+ min-height: 100vh;
2097
+ background: #f4f4f5;
2098
+ }
2099
+ /* The gutter is breathing room *around* a board, so it may never come out of
2100
+ the width the board is laid out in.
2101
+
2102
+ \`body\` is a block box: its \`width: auto\` resolves to the space available in
2103
+ the viewport minus its own horizontal padding, so \`padding: 24px\` made the
2104
+ containing block 1440 - 24*2 = 1392px. \`box-sizing\` does not undo that \u2014
2105
+ it only reinterprets an *explicit* width, and there is none here. A board
2106
+ authored at the 1440px desktop viewport is 1440px of \`.wf-page\` that must
2107
+ not shrink (\`flex-shrink: 0\`, the fixed-layout invariant), so it overhung
2108
+ its 1392px parent by 24px on each side and the document scrolled sideways.
2109
+
2110
+ The gutter therefore moves off the horizontal axis, where it competes with
2111
+ the board for the viewport, and stays only on the vertical one, where it
2112
+ costs nothing: a document scrolls down by nature, so leading above and
2113
+ below a board is free, while every horizontal pixel it takes is a pixel the
2114
+ board must give back. A board authored at exactly the viewport width now
2115
+ fills it edge to edge, as authored, and anything wider scrolls by its own
2116
+ overflow rather than by the gutter's. */
2117
+ body {
2118
+ padding: 24px 0;
2119
+ }
2120
+ ${css}
2121
+ </style>
2122
+ </head>
2123
+ <body>
2124
+ <div class="${prefix}-site"${siteAttrs}>
2125
+ ${body}
2126
+ </div>
2127
+ <script>
2128
+ ${runtime}
2129
+ </script>
2130
+ </body>
2131
+ </html>`;
2132
+ }
2133
+
2134
+ exports.asObjects = asObjects;
2135
+ exports.createAppBundle = createAppBundle;
2136
+ exports.diagnostic = diagnostic;
2137
+ exports.expandVariants = expandVariants;
2138
+ exports.failed = failed;
2139
+ exports.freeze = freeze;
2140
+ exports.getLinkedAppData = getLinkedAppData;
2141
+ exports.jcs = jcs;
2142
+ exports.linkAppV4 = linkAppV4;
2143
+ exports.object = object;
2144
+ exports.renderSite = renderSite;
2145
+ exports.textValue = textValue;