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