@atscript/typescript 0.1.109 → 0.2.0

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,3717 @@
1
+ import { p as stageEnds, t as uniqueName } from "./unique-name-hg1CyPIs.mjs";
2
+ import path from "path";
3
+ import { DEFAULT_FORMAT, MERGE_TOO_COMPLEX, NAV_PROP_ANNOTATIONS, SemanticGroup, andExprs, componentOf, components, defPosition, documentsEpoch, entryParts, flatDefinitions, forEachAnnotationSpec, getRelPath, hasMutatingAnnotates, hasNavPropAnnotation, isAnnotate, isArray, isAsView, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isNull, isPhantomNode, isPrimitive, isQueryLogical, isRef, isStructure, isTuple, moduleId, pastViews, resolveAtscriptFromPath, unshell } from "@atscript/core";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+ import { readFileSync } from "fs";
6
+ import { fileURLToPath } from "url";
7
+
8
+ //#region packages/typescript/src/codegen/code-printer.ts
9
+ function _define_property$5(obj, key, value) {
10
+ if (key in obj) Object.defineProperty(obj, key, {
11
+ value,
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true
15
+ });
16
+ else obj[key] = value;
17
+ return obj;
18
+ }
19
+ var CodePrinter = class {
20
+ /**
21
+ * Write text with NO automatic newline.
22
+ * If current line is empty, we prepend indentation.
23
+ */ write(...text) {
24
+ if (!this.currentLine) this.currentLine = this.indentString();
25
+ this.currentLine += text.join("");
26
+ return this;
27
+ }
28
+ /**
29
+ * Write text and then finalize this line with a newline.
30
+ * Implemented by calling `write(...)` + push line + reset `currentLine`.
31
+ */ writeln(...text) {
32
+ this.write(...text);
33
+ this.lines.push(this.currentLine);
34
+ this.currentLine = "";
35
+ return this;
36
+ }
37
+ /**
38
+ * Open a block with an opening/closing pair, e.g. "{}" or "()".
39
+ * By default, places the opening delimiter on the current line (no extra newline).
40
+ */ block(pair) {
41
+ return this.doBlock(pair, false);
42
+ }
43
+ /**
44
+ * Same as `block()`, but adds a newline after writing the opening delimiter.
45
+ */ blockln(pair) {
46
+ return this.doBlock(pair, true);
47
+ }
48
+ /**
49
+ * Close the most recent block. By default, closing delimiter goes on the current line.
50
+ */ pop() {
51
+ return this.doPop(false);
52
+ }
53
+ /**
54
+ * Same as `pop()`, but puts the closing delimiter on a new line.
55
+ */ popln() {
56
+ return this.doPop(true);
57
+ }
58
+ /**
59
+ * Increase indentation by one level.
60
+ */ indent() {
61
+ this.indentLevel++;
62
+ return this;
63
+ }
64
+ /**
65
+ * Decrease indentation by one level (never below 0).
66
+ */ unindent() {
67
+ this.indentLevel = Math.max(0, this.indentLevel - 1);
68
+ return this;
69
+ }
70
+ render() {
71
+ return this.toString();
72
+ }
73
+ /** What `fn` prints, captured (not added to the output), from indentation 0. */ capture(fn) {
74
+ const saved = [
75
+ this.lines,
76
+ this.currentLine,
77
+ this.indentLevel,
78
+ this.blockStack
79
+ ];
80
+ this.lines = [];
81
+ this.currentLine = "";
82
+ this.indentLevel = 0;
83
+ this.blockStack = [];
84
+ try {
85
+ fn();
86
+ if (this.currentLine) this.lines.push(this.currentLine);
87
+ return this.lines.join("\n");
88
+ } finally {
89
+ [this.lines, this.currentLine, this.indentLevel, this.blockStack] = saved;
90
+ }
91
+ }
92
+ /**
93
+ * Return the entire code as a string. Removes any half-finished current line if empty.
94
+ */ toString() {
95
+ if (this.currentLine.trim() !== "") this.lines.push(this.currentLine);
96
+ else if (this.currentLine.length > 0) this.lines.push(this.currentLine);
97
+ return this.lines.join("\n");
98
+ }
99
+ doBlock(pair, withNewLine) {
100
+ if (pair.length < 2) throw new Error(`Block pair must have at least 2 chars, e.g. "{}" or "()". Got "${pair}"`);
101
+ const opening = pair[0];
102
+ const closing = pair[pair.length - 1];
103
+ this.write(opening);
104
+ this.blockStack.push(closing);
105
+ if (withNewLine) this.writeln();
106
+ this.indent();
107
+ return this;
108
+ }
109
+ doPop(withNewLine) {
110
+ if (this.blockStack.length === 0) throw new Error("No block to pop (stack is empty).");
111
+ const closing = this.blockStack.pop();
112
+ this.unindent();
113
+ if (withNewLine) this.writeln(closing);
114
+ else this.write(closing);
115
+ return this;
116
+ }
117
+ indentString() {
118
+ return " ".repeat(this.indentLevel * this.indentSize);
119
+ }
120
+ constructor() {
121
+ _define_property$5(this, "lines", []);
122
+ _define_property$5(this, "currentLine", "");
123
+ _define_property$5(this, "indentLevel", 0);
124
+ _define_property$5(this, "indentSize", 2);
125
+ _define_property$5(this, "blockStack", []);
126
+ }
127
+ };
128
+
129
+ //#endregion
130
+ //#region packages/typescript/src/codegen/base-renderer.ts
131
+ function _define_property$4(obj, key, value) {
132
+ if (key in obj) Object.defineProperty(obj, key, {
133
+ value,
134
+ enumerable: true,
135
+ configurable: true,
136
+ writable: true
137
+ });
138
+ else obj[key] = value;
139
+ return obj;
140
+ }
141
+ var BaseRenderer = class extends CodePrinter {
142
+ get unused() {
143
+ return this._unused ?? (this._unused = new Set(this.doc.getUnusedTokens().map((t) => t.text)));
144
+ }
145
+ pre() {}
146
+ post() {}
147
+ render() {
148
+ this.pre();
149
+ for (const node of this.doc.nodes) this.renderNode(node);
150
+ this.post();
151
+ return this.toString();
152
+ }
153
+ renderInterface(node) {}
154
+ renderType(node) {}
155
+ renderAnnotate(node) {}
156
+ transformFromPath(path) {
157
+ return `${path}.as`;
158
+ }
159
+ renderImport(node) {
160
+ const def = node.getDefinition();
161
+ const refs = [];
162
+ const from = this.transformFromPath(node.token("path").text);
163
+ let isUnusedImport = true;
164
+ if (isGroup(def)) {
165
+ for (const child of def.unwrap()) if (isRef(child) && !this.unused.has(child.id)) {
166
+ const node = child;
167
+ refs.push(node.id);
168
+ isUnusedImport = false;
169
+ }
170
+ } else if (isRef(def) && !this.unused.has(def.id)) {
171
+ refs.push(def.id);
172
+ isUnusedImport = false;
173
+ }
174
+ if (!isUnusedImport) {
175
+ const line = `import { ${refs.join(", ")} } from "${from}"`;
176
+ this.writeln(line);
177
+ this.importKept(node, refs, line);
178
+ }
179
+ }
180
+ /** An import the rendered module keeps (`names`: those it uses; `line`: its statement). */ importKept(_node, _names, _line) {}
181
+ renderNode(node) {
182
+ switch (node.entity) {
183
+ case "interface":
184
+ this.renderInterface(node);
185
+ break;
186
+ case "type":
187
+ this.renderType(node);
188
+ break;
189
+ case "import":
190
+ this.renderImport(node);
191
+ break;
192
+ case "annotate":
193
+ this.renderAnnotate(node);
194
+ break;
195
+ default: break;
196
+ }
197
+ }
198
+ constructor(doc) {
199
+ super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
200
+ }
201
+ };
202
+
203
+ //#endregion
204
+ //#region packages/typescript/src/codegen/import-cycles.ts
205
+ /**
206
+ * Whether `doc` is on an import cycle with mutating annotates (in any of its modules), by the
207
+ * imports the generated modules keep (`imports`: those whose names they use, and the ones they
208
+ * add). A cycle of the `.as` files only (an import whose names the module does not use, dropped
209
+ * from its generated module) is not one: those modules are evaluated in import order. Found for
210
+ * every module of the cycle at once (`cache`).
211
+ */ function findImportCycle(doc, imports, cache) {
212
+ const known = cache.get(doc);
213
+ if (known !== void 0) return known;
214
+ let cycle = false;
215
+ const candidates = sccOf(doc);
216
+ if (candidates.size > 1 && componentHasBlocks(candidates)) {
217
+ const docs = generatedCycle(doc, candidates, imports);
218
+ if (docs.length > 1 && docs.some(hasMutatingAnnotates)) {
219
+ for (const d of docs) cache.set(d, true);
220
+ cycle = true;
221
+ }
222
+ }
223
+ cache.set(doc, cycle);
224
+ return cycle;
225
+ }
226
+ /** The strongly connected component of each document's imports (see {@link sccOf}). */ const componentMemo = /* @__PURE__ */ new WeakMap();
227
+ /**
228
+ * The documents `doc` imports (directly or not) that import it (directly or not), and `doc`: its
229
+ * strongly connected component of the import graph — found for every document reached at once,
230
+ * memoized until a document changes (components found already are not entered again: a build
231
+ * checking each module of a large graph is linear, not quadratic).
232
+ */ function sccOf(doc) {
233
+ const epoch = documentsEpoch();
234
+ const known = componentMemo.get(doc);
235
+ if (known?.epoch === epoch) return known.docs;
236
+ const found = components([doc], (d) => [...d.dependencies].filter((to) => componentMemo.get(to)?.epoch !== epoch));
237
+ const sets = /* @__PURE__ */ new Map();
238
+ for (const [d, c] of found) {
239
+ let docs = sets.get(c);
240
+ if (!docs) sets.set(c, docs = new Set(c));
241
+ componentMemo.set(d, {
242
+ epoch,
243
+ docs
244
+ });
245
+ }
246
+ return componentMemo.get(doc).docs;
247
+ }
248
+ /** Whether a component (see {@link sccOf}) has mutating annotates, found once. */ const componentBlocks = /* @__PURE__ */ new WeakMap();
249
+ function componentHasBlocks(docs) {
250
+ let has = componentBlocks.get(docs);
251
+ if (has === void 0) {
252
+ has = [...docs].some(hasMutatingAnnotates);
253
+ componentBlocks.set(docs, has);
254
+ }
255
+ return has;
256
+ }
257
+ /** The modules of `candidates` on a cycle of generated imports through `doc` (and `doc`). */ function generatedCycle(doc, candidates, imports) {
258
+ const forward = /* @__PURE__ */ new Map();
259
+ const backward = /* @__PURE__ */ new Map();
260
+ for (const d of candidates) for (const to of imports(d)) if (candidates.has(to) && to !== d) {
261
+ forward.set(d, [...forward.get(d) ?? [], to]);
262
+ backward.set(to, [...backward.get(to) ?? [], d]);
263
+ }
264
+ const reach = (edges) => {
265
+ const out = new Set([doc]);
266
+ const queue = [doc];
267
+ for (const d of queue) for (const next of edges.get(d) ?? []) if (!out.has(next)) {
268
+ out.add(next);
269
+ queue.push(next);
270
+ }
271
+ return out;
272
+ };
273
+ const imported = reach(forward);
274
+ return [...reach(backward)].filter((d) => imported.has(d));
275
+ }
276
+
277
+ //#endregion
278
+ //#region packages/typescript/src/codegen/utils.ts
279
+ const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
280
+ /**
281
+ * Wraps a property name in double quotes if it's not a valid identifier (contains special chars, etc.).
282
+ *
283
+ * Examples:
284
+ * - "validName" => "validName"
285
+ * - "some-prop" => "\"some-prop\""
286
+ */ function wrapProp(name) {
287
+ if (!validIdentifier.test(name)) return `"${escapeQuotes(name)}"`;
288
+ return name;
289
+ }
290
+ function escapeQuotes(str) {
291
+ return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
292
+ }
293
+
294
+ //#endregion
295
+ //#region packages/typescript/src/codegen/js-renderer.ts
296
+ function _define_property$3(obj, key, value) {
297
+ if (key in obj) Object.defineProperty(obj, key, {
298
+ value,
299
+ enumerable: true,
300
+ configurable: true,
301
+ writable: true
302
+ });
303
+ else obj[key] = value;
304
+ return obj;
305
+ }
306
+ const QUERY_OP_MAP = {
307
+ "=": "$eq",
308
+ "!=": "$ne",
309
+ ">": "$gt",
310
+ ">=": "$gte",
311
+ "<": "$lt",
312
+ "<=": "$lte",
313
+ "in": "$in",
314
+ "not in": "$nin",
315
+ "matches": "$regex",
316
+ "exists": "$exists",
317
+ "not exists": "$exists"
318
+ };
319
+ const UTILS_IMPORT_MARKER = "/*@@atscript-utils-import@@*/";
320
+ const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
321
+ /** Phase-1 placeholders of a class's bundled JSON schema (see `JsRenderer.render`). */ const schemaMarker = (id) => `/*@@atscript-schema:${id}@@*/{}`;
322
+ const accountedMarker = (id) => `/*@@atscript-accounted:${id}@@*/`;
323
+ const MARKERS = /\/\*@@atscript-(schema|accounted):([^@]+)@@\*\/(?:\{\})?/g;
324
+ /**
325
+ * Phase-1 placeholders of the compiled checks' registrations and of their helper in the utils
326
+ * import (see `JsRenderer.render`).
327
+ */ const CHECKS_MARKER = "/*@@atscript-compiled-checks@@*/";
328
+ const CHECKS_IMPORT_MARKER = "/*@@atscript-compiled-checks-import@@*/";
329
+ /**
330
+ * The accounted blocks of a bundled schema whose realm failed (the module throws when loaded):
331
+ * never what the runtime applied, so the runtime's schema is used.
332
+ */ const REALM_FAILED = "!realm";
333
+ /**
334
+ * The `@atscript/typescript/utils` helpers generated code uses (in import order), with the
335
+ * local name each prefers (see `JsRenderer.util`).
336
+ */ const UTILS = {
337
+ defineAnnotatedType: "$",
338
+ annotate: "$a",
339
+ buildJsonSchema: "$$",
340
+ createDataFromAnnotatedType: "$e",
341
+ throwFeatureDisabled: "$d",
342
+ registerCompiledCheck: "$cv",
343
+ lazyJsonSchema: "$jl",
344
+ $f: "$f",
345
+ $ft: "$ft",
346
+ $fc: "$fc",
347
+ $alias: "$al",
348
+ $blk: "$blk",
349
+ $q: "$q",
350
+ $end: "$end",
351
+ $sh: "$sh",
352
+ bundledSchemaOf: "$jbm",
353
+ $ps: "$ps",
354
+ $ak: "$ak",
355
+ $nr: "$nk"
356
+ };
357
+ const LITERAL_IDENTIFIERS = new Set([
358
+ "true",
359
+ "false",
360
+ "null",
361
+ "undefined"
362
+ ]);
363
+ /**
364
+ * The JS source of an argument of an annotation without a spec
365
+ * (`unknownAnnotation: 'allow'` / `'warn'`): nothing says what it means, so it is kept as
366
+ * written — a string, a number, `true` / `false` / `null` / `undefined`, and any other
367
+ * identifier (`Name`, `Name.field`) or backtick argument as the string of its source; an
368
+ * argument left empty (`@a , 'x'`) is `undefined`. (An identifier emitted as is would be an
369
+ * undeclared variable at module load, a backtick one an empty argument.)
370
+ */ function unknownArg(token, doc) {
371
+ switch (token.type) {
372
+ case "text": return `"${escapeQuotes(token.text)}"`;
373
+ case "number": return token.text;
374
+ case "identifier": return LITERAL_IDENTIFIERS.has(token.text) ? token.text : JSON.stringify(token.text);
375
+ case "query": return JSON.stringify(backtickSource(token, doc));
376
+ default: return "undefined";
377
+ }
378
+ }
379
+ /** The source between the backticks of a backtick argument. */ function backtickSource(token, doc) {
380
+ const { start, end } = token.range;
381
+ const lines = doc.text.split("\n");
382
+ const offset = (pos) => {
383
+ let n = pos.character;
384
+ for (let i = 0; i < pos.line && i < lines.length; i++) n += lines[i].length + 1;
385
+ return n;
386
+ };
387
+ let text = doc.text.slice(offset(start), offset(end));
388
+ if (text.startsWith("`")) text = text.slice(1);
389
+ return text.endsWith("`") ? text.slice(0, -1) : text;
390
+ }
391
+ var JsRenderer = class extends BaseRenderer {
392
+ /**
393
+ * The local name of helper `name` (marked used): its preferred one, suffixed when the module
394
+ * declares or imports that name (`$m` → `$m_1`).
395
+ */ util(name) {
396
+ let local = this.utils.get(name);
397
+ if (local === void 0) {
398
+ local = this.allocAlias(UTILS[name], this.getSynthTaken());
399
+ this.utils.set(name, local);
400
+ }
401
+ return local;
402
+ }
403
+ /** `defineAnnotatedType` (see {@link util}). */ get $() {
404
+ return this.util("defineAnnotatedType");
405
+ }
406
+ /**
407
+ * Relative imports get the configured `moduleExtension`; bare specifiers
408
+ * always keep `.as` — they resolve through the package's `exports` map.
409
+ */ transformFromPath(path) {
410
+ return isBareSpecifier(path) ? `${path}.as` : `${path}${this.opts?.moduleExtension ?? ".as"}`;
411
+ }
412
+ /**
413
+ * The declaration `name` names in document `origin` (where a reference or an annotation
414
+ * argument was written), when this module needs a binding of its own for it: declared in
415
+ * another module (not a primitive) and not bound to it here under that name.
416
+ */ foreignOwner(name, origin) {
417
+ const theirs = this.resolveOwner(origin, name);
418
+ if (!theirs?.node || theirs.doc === this.doc || isPrimitive(theirs.node)) return;
419
+ const mine = this.resolveOwner(this.doc, name);
420
+ return mine?.doc === theirs.doc && mine.node === theirs.node ? void 0 : {
421
+ doc: theirs.doc,
422
+ node: theirs.node
423
+ };
424
+ }
425
+ getSynthTaken() {
426
+ if (!this._synthTaken) {
427
+ this._synthTaken = new Set(this.doc.registry.definitions.keys());
428
+ for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
429
+ }
430
+ return this._synthTaken;
431
+ }
432
+ getSynthPath(ownerDoc) {
433
+ if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
434
+ return this._synthPathCache.get(ownerDoc);
435
+ }
436
+ synthBinding(name, ownerInfo) {
437
+ const synthPath = this.getSynthPath(ownerInfo.doc);
438
+ if (!synthPath) return;
439
+ const allocKey = `${synthPath}::${name}`;
440
+ let info = this._synthAllocated.get(allocKey);
441
+ if (!info) {
442
+ info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
443
+ this._synthAllocated.set(allocKey, info);
444
+ }
445
+ return info;
446
+ }
447
+ /**
448
+ * Binding for a type name used by an annotation argument (`ref` / qualified
449
+ * query field refs). An annotation inherited from another document (chain ref
450
+ * or `extends`) carries names that only that document imports, so when the
451
+ * name does not resolve here to the same declaration, a synthesized import is
452
+ * allocated (lazily, spliced into the header by `render()`).
453
+ */ annotationTypeName(typeName, origin) {
454
+ const owner = origin && origin !== this.doc ? this.foreignOwner(typeName, origin) : void 0;
455
+ return (owner && this.synthBinding(typeName, owner)?.alias) ?? typeName;
456
+ }
457
+ resolveOwner(fromDoc, refId) {
458
+ const key = `${fromDoc.id}::${refId}`;
459
+ let v = this._ownerCache.get(key);
460
+ if (v === void 0 && !this._ownerCache.has(key)) {
461
+ v = fromDoc.getDeclarationOwnerNode(refId);
462
+ this._ownerCache.set(key, v);
463
+ }
464
+ return v;
465
+ }
466
+ allocateSynthInfo(refId, synthPath, ownerInfo, taken) {
467
+ const ownerDoc = ownerInfo.doc;
468
+ const ownerNode = ownerInfo.node;
469
+ if (this.doc.importedDefs.get(refId)?.text === synthPath && !this.unused.has(refId)) return {
470
+ alias: refId,
471
+ ownerDoc,
472
+ ownerNode
473
+ };
474
+ const alias = this.allocAlias(refId, taken);
475
+ let group = this._synthImports.get(synthPath);
476
+ if (!group) {
477
+ group = [];
478
+ this._synthImports.set(synthPath, group);
479
+ }
480
+ group.push({
481
+ name: refId,
482
+ alias
483
+ });
484
+ this.synthDocs.set(synthPath, ownerDoc);
485
+ this.importedDocs.add(ownerDoc);
486
+ return {
487
+ alias,
488
+ ownerDoc,
489
+ ownerNode
490
+ };
491
+ }
492
+ /** `name`, suffixed (`_1`, `_2`, …) when `taken`; the result is taken from now on. */ allocAlias(name, taken) {
493
+ const alias = uniqueName(name, (n) => taken.has(n), "_");
494
+ taken.add(alias);
495
+ return alias;
496
+ }
497
+ computeSynthPath(ownerDoc) {
498
+ if (isBareId(ownerDoc.id)) return ownerDoc.id.slice(5, -3);
499
+ if (!ownerDoc.id.startsWith("file://")) return;
500
+ return getRelPath(this.doc.id, ownerDoc.id);
501
+ }
502
+ importKept(node, names, line) {
503
+ const path = node.token("path")?.text;
504
+ const imported = path && this.doc.dependenciesMap.get(this.doc.resolveImportId(resolveAtscriptFromPath(path, this.doc.id)));
505
+ this.realmImports.push({
506
+ line,
507
+ doc: imported || void 0,
508
+ names: names.map((n) => [n, n])
509
+ });
510
+ if (imported) this.importedDocs.add(imported);
511
+ }
512
+ pre() {
513
+ this.writeln("// prettier-ignore-start");
514
+ this.writeln("/* eslint-disable */");
515
+ this.writeln("/* oxlint-disable */");
516
+ const nodesByName = /* @__PURE__ */ new Map();
517
+ for (const node of this.doc.nodes) if (node.__typeId !== null && node.__typeId !== void 0 && node.id) {
518
+ const name = node.id;
519
+ if (!nodesByName.has(name)) nodesByName.set(name, []);
520
+ nodesByName.get(name).push(node);
521
+ }
522
+ for (const [name, nodes] of nodesByName) if (nodes.length === 1) this.typeIds.set(nodes[0], name);
523
+ else for (let i = 0; i < nodes.length; i++) this.typeIds.set(nodes[i], `${name}__${i + 1}`);
524
+ this.writeln(UTILS_IMPORT_MARKER);
525
+ this.writeln(SYNTH_IMPORTS_MARKER);
526
+ }
527
+ /**
528
+ * The import of the `@atscript/typescript/utils` helpers: those the rendered body used, and
529
+ * those every module of its kind imports.
530
+ */ utilsImport() {
531
+ const always = ["defineAnnotatedType"];
532
+ if (this.opts?.exampleData) always.push("createDataFromAnnotatedType");
533
+ if (this.jsonSchemaMode === false) always.push("throwFeatureDisabled");
534
+ always.forEach((name) => this.util(name));
535
+ const names = Object.keys(UTILS).filter((name) => this.utils.has(name)).map((name) => [name, this.utils.get(name)]);
536
+ const line = `import { ${names.map(([name, local]) => name === "registerCompiledCheck" ? CHECKS_IMPORT_MARKER : `, ${name} as ${local}`).join("").slice(2)} } from "${this.utilsEntry}"`;
537
+ this.realmImports.push({
538
+ line,
539
+ names: names.filter(([name]) => name !== "registerCompiledCheck")
540
+ });
541
+ return line;
542
+ }
543
+ /**
544
+ * The generated module: phase 1 (see {@link renderModule}), then the view payloads spliced in
545
+ * (phase 2), built by the runtime from the realm's objects (see `realm.ts`): each bundled JSON
546
+ * schema, and the compiled validator checks (see `compiledCheckRegistrations`).
547
+ */ render() {
548
+ const module = this.phase1();
549
+ if (this.bundledSchemas.length === 0 && !this.compiles) return module.text;
550
+ const realm = this.realm();
551
+ const text = this.compiles ? this.spliceCompiledChecks(module.text, realm) : module.text;
552
+ if (this.bundledSchemas.length === 0) return text;
553
+ const views = /* @__PURE__ */ new Map();
554
+ const viewOf = (id) => {
555
+ let view = views.get(id);
556
+ if (!view) {
557
+ let schema = "{}";
558
+ let accounted = [REALM_FAILED];
559
+ try {
560
+ const type = realm.classOf(this.doc, id);
561
+ schema = JSON.stringify(realm.rt.buildJsonSchema(type));
562
+ accounted = this.accountedFor(realm, type);
563
+ } catch {}
564
+ view = {
565
+ schema,
566
+ accounted: accounted.length > 0 ? `, ${JSON.stringify(accounted)}` : ""
567
+ };
568
+ views.set(id, view);
569
+ }
570
+ return view;
571
+ };
572
+ return text.replace(MARKERS, (_, kind, id) => kind === "schema" ? viewOf(id).schema : viewOf(id).accounted);
573
+ }
574
+ /** `text` (phase 1) with the compiled checks' registrations, built in `realm`. */ spliceCompiledChecks(text, realm) {
575
+ let registrations = [];
576
+ try {
577
+ registrations = realm.rt.compiledCheckRegistrations({
578
+ classes: realm.classesOf(this.doc),
579
+ compiled: this.compiledChecks,
580
+ allClasses: realm.classTypes()
581
+ });
582
+ } catch {}
583
+ const cv = this.util("registerCompiledCheck");
584
+ const checks = registrations.map((args) => `${cv}(${args})\n`).join("");
585
+ return text.replace(CHECKS_IMPORT_MARKER, () => checks ? `, registerCompiledCheck as ${cv}` : "").replace(`${CHECKS_MARKER}\n`, () => checks ? `// Compiled validator checks\n${checks}\n` : "");
586
+ }
587
+ /**
588
+ * {@link renderModule}, once: phase 2 (see {@link render}) reads what it recorded; a module that
589
+ * fails to render fails every time with its error.
590
+ */ phase1() {
591
+ if (!this.phase1Out) try {
592
+ this.phase1Out = { module: this.renderModule() };
593
+ } catch (error) {
594
+ this.phase1Out = { error };
595
+ }
596
+ if ("error" in this.phase1Out) throw this.phase1Out.error;
597
+ return this.phase1Out.module;
598
+ }
599
+ /**
600
+ * Phase 1: the generated module without view payloads (a bundled JSON schema is a placeholder,
601
+ * see {@link render}), with what the realm needs to evaluate it (see `TRealmModule`).
602
+ */ renderModule() {
603
+ const out = super.render();
604
+ const lines = [];
605
+ for (const [synthPath, names] of this._synthImports) {
606
+ const line = `import { ${names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ")} } from "${this.transformFromPath(synthPath)}"`;
607
+ lines.push(line);
608
+ this.realmImports.push({
609
+ line,
610
+ doc: this.synthDocs.get(synthPath),
611
+ names: names.map((n) => [n.name, n.alias])
612
+ });
613
+ }
614
+ const text = out.replace(UTILS_IMPORT_MARKER, () => this.utilsImport()).replace(`${SYNTH_IMPORTS_MARKER}\n`, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
615
+ const at = new Map(this.realmImports.map((i) => [i, text.indexOf(i.line)]));
616
+ return {
617
+ text,
618
+ imports: [...this.realmImports].sort((a, b) => at.get(a) - at.get(b)),
619
+ exports: [...this.exportedClasses],
620
+ classes: [...this.declaredClasses]
621
+ };
622
+ }
623
+ /**
624
+ * Where the `$cv(Class, …)` registrations go (one per compiled class, after every chain and
625
+ * mutating annotate of the module ran: the compiled check binds on first use): a placeholder
626
+ * phase 2 fills from the realm (see `render`).
627
+ */ renderCompiledChecks() {
628
+ if (this.compiles) {
629
+ this.util("registerCompiledCheck");
630
+ this.writeln(CHECKS_MARKER);
631
+ }
632
+ }
633
+ renderClassStatics(node) {
634
+ this.writeln("static __is_atscript_annotated_type = true");
635
+ this.writeln(`static type = ${this.classTypeInit(node)}`);
636
+ this.writeln("static metadata = new Map()");
637
+ const typeId = this.typeIds.get(node);
638
+ if (typeId) this.writeln(`static id = "${typeId}"`);
639
+ this.renderJsonSchemaMethod(node);
640
+ this.renderExampleDataMethod(node);
641
+ this.renderDimMeasure(node);
642
+ }
643
+ renderInterface(node) {
644
+ this.renderDefinitionClass(node);
645
+ }
646
+ renderType(node) {
647
+ this.renderDefinitionClass(node);
648
+ }
649
+ renderAnnotate(node) {
650
+ if (!node.isMutating && this.doc.unwindType(node.targetName)?.def) this.renderDefinitionClass(node);
651
+ }
652
+ renderDefinitionClass(node) {
653
+ this.writeln();
654
+ const exported = node.token("export")?.text === "export";
655
+ if (exported) this.exportedClasses.push(node.id);
656
+ this.declaredClasses.push(node.id);
657
+ this.write(exported ? "export " : "");
658
+ this.write(`class ${node.id} `);
659
+ this.blockln("{}");
660
+ this.renderClassStatics(node);
661
+ this.popln();
662
+ this.writeln();
663
+ }
664
+ /**
665
+ * `static toJsonSchema()`: lazy (built by the runtime) or disabled; a bundled schema is the
666
+ * structure printer's (see `js-next.ts`).
667
+ */ renderJsonSchemaMethod(_node) {
668
+ if (this.jsonSchemaMode === "lazy") {
669
+ this.writeln("static toJsonSchema() {");
670
+ this.indent().writeln(`return ${this.util("lazyJsonSchema")}(this)`);
671
+ this.unindent();
672
+ this.writeln("}");
673
+ } else {
674
+ this.writeln("static toJsonSchema() {");
675
+ const disabled = this.util("throwFeatureDisabled");
676
+ this.indent().writeln(`${disabled}("JSON Schema", "jsonSchema", "emit.jsonSchema")`);
677
+ this.unindent();
678
+ this.writeln("}");
679
+ }
680
+ }
681
+ renderExampleDataMethod(_node) {
682
+ if (this.opts?.exampleData) {
683
+ this.writeln("static toExampleData() {");
684
+ const create = this.util("createDataFromAnnotatedType");
685
+ this.indent().writeln(`return ${create}(this, { mode: "example" })`).unindent();
686
+ this.writeln("}");
687
+ }
688
+ }
689
+ renderDimMeasure(node) {
690
+ if (!isInterface(node)) return;
691
+ const interfaceNode = node;
692
+ if (!isDbEntityNode(interfaceNode)) return;
693
+ let struct;
694
+ /** Whether a block on a parent (directly or not) writes annotation `key` on prop `name`. */ let parentBlock = (_name, _key) => false;
695
+ if (interfaceNode.hasExtends) {
696
+ struct = this.doc.resolveInterfaceExtends(interfaceNode);
697
+ const m = this.doc.structure();
698
+ const parents = /* @__PURE__ */ new Set();
699
+ const add = (d) => {
700
+ for (const p of m.extendsOf(d).map((x) => m.plainTarget(x))) if (!parents.has(p)) {
701
+ parents.add(p);
702
+ add(p);
703
+ }
704
+ };
705
+ const self = m.declOfNode(interfaceNode);
706
+ if (self) {
707
+ add(self);
708
+ parents.delete(self);
709
+ }
710
+ parentBlock = (name, key) => [...parents].some((p) => m.layersAt(p, [name]).some((l) => l.entry.ref.annotations?.some((a) => a.name === key)));
711
+ }
712
+ if (!struct) struct = interfaceNode.getDefinition();
713
+ if (!struct || !isStructure(struct)) return;
714
+ const structNode = struct;
715
+ const dims = [];
716
+ const measures = [];
717
+ for (const [name, prop] of structNode.props) {
718
+ if (prop.token("identifier")?.pattern) continue;
719
+ if (prop.countAnnotations("db.column.dimension") > 0 || parentBlock(name, "db.column.dimension")) dims.push(name);
720
+ if (prop.countAnnotations("db.column.measure") > 0 || parentBlock(name, "db.column.measure")) measures.push(name);
721
+ }
722
+ if (dims.length > 0) this.writeln(`static dimensions = [${dims.map((d) => `'${escapeQuotes(d)}'`).join(", ")}]`);
723
+ if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
724
+ }
725
+ defineConst(node) {
726
+ const t = node.token("identifier")?.type;
727
+ const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
728
+ this.writeln(`.designType("${escapeQuotes(designType)}")`);
729
+ this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
730
+ return this;
731
+ }
732
+ definePrimitive(node, name) {
733
+ this.renderPrimitiveDef(node.id === "never" ? "never" : node.config.type, name);
734
+ this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
735
+ return this;
736
+ }
737
+ /** Emits a primitive's builder chain. */ renderPrimitiveDef(def, name) {
738
+ const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
739
+ const final = (designType) => {
740
+ this.writeln(`${this.$}(${d()}).designType("${designType}")`);
741
+ };
742
+ if (!def) return final("any");
743
+ if (typeof def === "string") return final(def === "void" ? "undefined" : def);
744
+ switch (def.kind) {
745
+ case "final": return final(def.value === "void" ? "undefined" : def.value);
746
+ case "union":
747
+ case "intersection":
748
+ case "tuple":
749
+ this.writeln(`${this.$}(${d(def.kind)})`);
750
+ this.indent();
751
+ for (const itemDef of def.items) {
752
+ this.write(`.item(`);
753
+ this.indent();
754
+ this.renderPrimitiveDef(itemDef);
755
+ this.writeln(".$type");
756
+ this.unindent();
757
+ this.write(`)`);
758
+ }
759
+ this.unindent();
760
+ return;
761
+ case "array":
762
+ this.writeln(`${this.$}(${d("array")})`);
763
+ this.indent();
764
+ this.write(".of(");
765
+ this.indent();
766
+ this.renderPrimitiveDef(def.of);
767
+ this.writeln(`.$type`);
768
+ this.unindent();
769
+ this.writeln(`)`);
770
+ this.unindent();
771
+ return;
772
+ case "object": {
773
+ this.writeln(`${this.$}(${d("object")})`);
774
+ this.indent();
775
+ const props = [...Object.entries(def.props).map(([k, p]) => [
776
+ k,
777
+ p,
778
+ false
779
+ ]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
780
+ k,
781
+ p,
782
+ true
783
+ ])];
784
+ for (const [key, propDef, isPattern] of props) {
785
+ const optional = typeof propDef === "object" && propDef.optional;
786
+ this.writeln(isPattern ? `.propPattern(` : `.prop(`);
787
+ this.indent();
788
+ this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
789
+ this.renderPrimitiveDef(propDef);
790
+ if (optional) this.writeln(".optional()");
791
+ this.writeln(".$type");
792
+ this.unindent();
793
+ this.write(`)`);
794
+ }
795
+ this.unindent();
796
+ return;
797
+ }
798
+ default: return final("any");
799
+ }
800
+ }
801
+ /** Writes annotation `an` of `node`. */ resolveAnnotationValue(node, an) {
802
+ const { value, multiple } = this.computeAnnotationValue(node, an);
803
+ if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
804
+ else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
805
+ }
806
+ emitRefValue(text, origin) {
807
+ const dotIdx = text.indexOf(".");
808
+ if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
809
+ return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
810
+ }
811
+ emitArgValue(aSpec, argToken, origin) {
812
+ if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
813
+ if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
814
+ if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
815
+ if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
816
+ return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
817
+ }
818
+ emitExprNode(node, origin) {
819
+ switch (node.entity) {
820
+ case "query-expr-number": return String(node.value);
821
+ case "query-expr-binary": {
822
+ const { op, left, right } = node;
823
+ return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
824
+ }
825
+ case "query-expr-unary": {
826
+ const { op, operand } = node;
827
+ return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
828
+ }
829
+ case "query-expr-call": {
830
+ const { fn, args } = node;
831
+ return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
832
+ }
833
+ default: return this.emitQueryFieldRef(node, origin);
834
+ }
835
+ }
836
+ emitQueryTree(queryNode, origin) {
837
+ return this.emitQueryExpr(queryNode.expression, origin);
838
+ }
839
+ emitQueryExpr(node, origin) {
840
+ if (isQueryLogical(node)) return this.emitQueryLogical(node, origin);
841
+ return this.emitQueryComparison(node, origin);
842
+ }
843
+ emitQueryLogical(node, origin) {
844
+ if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
845
+ return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
846
+ }
847
+ emitQueryComparison(node, origin) {
848
+ const left = this.emitQueryFieldRef(node.left, origin);
849
+ const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
850
+ const parts = [`left: ${left}`, `op: "${mappedOp}"`];
851
+ if (node.right) {
852
+ if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
853
+ else if ("values" in node.right && node.right.values) {
854
+ const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
855
+ parts.push(`right: [${values}]`);
856
+ } else if ("valueToken" in node.right) parts.push(`right: ${this.emitQueryLiteral(node.right)}`);
857
+ } else if (node.operator === "exists") parts.push("right: true");
858
+ else if (node.operator === "not exists") parts.push("right: false");
859
+ return `{ ${parts.join(", ")} }`;
860
+ }
861
+ emitQueryFieldRef(node, origin) {
862
+ const parts = [];
863
+ if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
864
+ parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
865
+ return `{ ${parts.join(", ")} }`;
866
+ }
867
+ emitQueryLiteral(node) {
868
+ const token = node.valueToken;
869
+ switch (token.type) {
870
+ case "text": return `"${escapeQuotes(token.text)}"`;
871
+ case "number": return token.text;
872
+ case "regexp": {
873
+ const match = /^\/(.*)\/[a-z]*$/.exec(token.text);
874
+ return `"${escapeQuotes(match ? match[1] : token.text)}"`;
875
+ }
876
+ case "identifier":
877
+ if (token.text === "true" || token.text === "false") return token.text;
878
+ if (token.text === "null" || token.text === "undefined") return "null";
879
+ return token.text;
880
+ default: return token.text;
881
+ }
882
+ }
883
+ /** The JS source of an annotation's value, and whether the annotation is a list. */ computeAnnotationValue(node, an) {
884
+ const origin = this.doc.annotationOrigin(an);
885
+ const spec = this.doc.resolveAnnotation(an.name);
886
+ let targetValue = "true";
887
+ let multiple = false;
888
+ if (spec) {
889
+ multiple = spec.config.multiple;
890
+ const length = spec.arguments.length;
891
+ if (length !== 0) {
892
+ if (Array.isArray(spec.config.argument)) {
893
+ targetValue = "{ ";
894
+ let i = 0;
895
+ for (const aSpec of spec.arguments) {
896
+ if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
897
+ i++;
898
+ }
899
+ targetValue += "}";
900
+ } else if (an.args[0]) {
901
+ const aSpec = spec.arguments[0];
902
+ targetValue = this.emitArgValue(aSpec, an.args[0], origin);
903
+ }
904
+ }
905
+ } else {
906
+ multiple = (an.token.parentNode ?? node).countAnnotations(an.name) > 1 || an.args.length > 1;
907
+ if (an.args.length > 0) targetValue = unknownArg(an.args[0], origin ?? this.doc);
908
+ }
909
+ return {
910
+ value: targetValue,
911
+ multiple: !!multiple
912
+ };
913
+ }
914
+ constructor(doc, opts, compileMode) {
915
+ super(doc), _define_property$3(this, "opts", void 0), _define_property$3(this, "compileMode", void 0), _define_property$3(this, "typeIds", void 0), _define_property$3(this, "_synthImports", void 0), _define_property$3(this, "_synthTaken", void 0), _define_property$3(this, "_synthAllocated", void 0), _define_property$3(this, "_synthPathCache", void 0), _define_property$3(this, "_ownerCache", void 0), _define_property$3(this, "importedDocs", void 0), _define_property$3(this, "exportedClasses", void 0), _define_property$3(this, "declaredClasses", void 0), _define_property$3(this, "realmImports", void 0), _define_property$3(this, "synthDocs", void 0), _define_property$3(this, "bundledSchemas", void 0), _define_property$3(this, "jsonSchemaMode", void 0), _define_property$3(this, "compiledClasses", void 0), _define_property$3(this, "compiles", void 0), _define_property$3(this, "compiledChecks", void 0), _define_property$3(this, "utils", void 0), _define_property$3(this, "utilsEntry", void 0), _define_property$3(this, "phase1Out", void 0), this.opts = opts, this.compileMode = compileMode, this.typeIds = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map(), this.importedDocs = /* @__PURE__ */ new Set(), this.exportedClasses = [], this.declaredClasses = [], this.realmImports = [], this.synthDocs = /* @__PURE__ */ new Map(), this.bundledSchemas = [], this.compiledChecks = [], this.utils = /* @__PURE__ */ new Map(), this.utilsEntry = "@atscript/typescript/utils";
916
+ this.jsonSchemaMode = resolveJsonSchemaMode(opts);
917
+ if (compileMode === "annotated") {
918
+ this.compiledClasses = /* @__PURE__ */ new Set();
919
+ for (const node of doc.nodes) if (node.id && node.countAnnotations("emit.compiledValidator") > 0) this.compiledClasses.add(node.id);
920
+ }
921
+ this.compiles = compileMode === "all" || !!this.compiledClasses && this.compiledClasses.size > 0;
922
+ }
923
+ };
924
+
925
+ //#endregion
926
+ //#region packages/typescript/src/codegen/realm.ts
927
+ function _define_property$2(obj, key, value) {
928
+ if (key in obj) Object.defineProperty(obj, key, {
929
+ value,
930
+ enumerable: true,
931
+ configurable: true,
932
+ writable: true
933
+ });
934
+ else obj[key] = value;
935
+ return obj;
936
+ }
937
+ let runtimeSource;
938
+ /** This module's directory (dist: where `realm-runtime.js` is). */ function moduleDir() {
939
+ if (typeof __dirname === "string") return __dirname;
940
+ try {
941
+ return path.dirname(fileURLToPath(import.meta.url));
942
+ } catch {
943
+ return;
944
+ }
945
+ }
946
+ /**
947
+ * The text of the realm runtime: `$ATSCRIPT_REALM_RUNTIME` (a file: the test suite and tools
948
+ * running the sources build it), else `realm-runtime.js` next to this module (the package's
949
+ * `dist`).
950
+ */ function realmRuntimeSource() {
951
+ if (runtimeSource === void 0) {
952
+ const dir = moduleDir();
953
+ const tried = [process.env.ATSCRIPT_REALM_RUNTIME, dir && path.join(dir, "realm-runtime.js")];
954
+ for (const file of tried) if (file) try {
955
+ runtimeSource = readFileSync(file, "utf8");
956
+ break;
957
+ } catch {}
958
+ if (runtimeSource === void 0) throw new Error(`@atscript/typescript: the build-time runtime (realm-runtime.js) was not found (${tried.filter(Boolean).join(", ")})`);
959
+ }
960
+ return runtimeSource;
961
+ }
962
+ let runtimeFactory;
963
+ /**
964
+ * A fresh instance of the runtime (see {@link realmRuntimeSource}): its IIFE run again (compiled
965
+ * once), so the instance's module state is new.
966
+ */ function freshRuntime() {
967
+ runtimeFactory ?? (runtimeFactory = new Function(`${realmRuntimeSource()}\n;return __atscriptRealm`));
968
+ return runtimeFactory();
969
+ }
970
+ /** `error`'s message, quoted. */ const errorText = (error) => JSON.stringify(String(error?.message ?? error).split("\n")[0]);
971
+ /** Getters of `names` (`[name, local]`) reading `read(name)`, on a null-prototype object. */ function getters(names, read) {
972
+ const out = Object.create(null);
973
+ for (const [name, local] of names) Object.defineProperty(out, local, {
974
+ get: () => read(name),
975
+ enumerable: true
976
+ });
977
+ return out;
978
+ }
979
+ /** An object literal of getters of `names` (source). */ const gettersSource = (names) => `{ ${names.map((n) => typeof n === "string" ? [n, n] : n).map(([n, local]) => `get ${n}() { return ${local} }`).join(", ")} }`;
980
+ /**
981
+ * The function evaluating module `m`: `__scope` holds its imports, `__module(exports, classes)`
982
+ * gets getters of its exported classes and of all its classes before its body runs.
983
+ */ function moduleFunction(m) {
984
+ let body = m.text;
985
+ for (const { line } of m.imports) body = body.replace(`${line}\n`, () => "");
986
+ for (const name of m.exports) body = body.replace(`export class ${name} `, () => `class ${name} `);
987
+ const aliases = (m.aliases ?? []).map((a) => [a.name, a.local]);
988
+ for (const { line } of m.aliases ?? []) body = body.replace(`${line}\n`, () => "");
989
+ return new Function("__scope", "__module", `with (__scope) { return (function () { "use strict";\n__module(${gettersSource([...m.exports, ...aliases])}, ${gettersSource([...m.classes, ...aliases])});\n${body}\n})() }`);
990
+ }
991
+ var Realm = class {
992
+ /** Module `doc`'s `$q`: the runtime's, recording each statement with its module. */ queueOf(doc) {
993
+ const rt = this.rt;
994
+ return (fn, own) => {
995
+ const rec = {
996
+ doc,
997
+ fn,
998
+ done: false
999
+ };
1000
+ this.statements.push(rec);
1001
+ rt.$q(() => {
1002
+ try {
1003
+ const out = fn();
1004
+ rec.done = true;
1005
+ return out;
1006
+ } catch (error) {
1007
+ if (!rt.isWait(error)) rec.error = error;
1008
+ throw error;
1009
+ }
1010
+ }, own);
1011
+ };
1012
+ }
1013
+ /**
1014
+ * Evaluates every module (roots by module id; see the file comment). A module that throws
1015
+ * fails, and so do the modules importing it (as in ESM); the others are evaluated.
1016
+ */ load() {
1017
+ const roots = [...this.modules.keys()].map((doc) => ({
1018
+ doc,
1019
+ id: moduleId(doc)
1020
+ })).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
1021
+ for (const { doc } of roots) try {
1022
+ this.evaluate(doc);
1023
+ } catch {}
1024
+ return this;
1025
+ }
1026
+ /**
1027
+ * Evaluates `doc`'s module as the entry (with what it imports, as a loader would); what failed
1028
+ * is recorded (see {@link statements}, {@link failures}).
1029
+ */ loadFrom(doc) {
1030
+ try {
1031
+ this.evaluate(doc);
1032
+ } catch {}
1033
+ return this;
1034
+ }
1035
+ /**
1036
+ * What failed to load, by module (MODEL CYCLE-GUARD-8): its statements that never ran or threw,
1037
+ * and its own body's throw (one of its statements' error thrown on: theirs only).
1038
+ */ loadErrors() {
1039
+ const out = /* @__PURE__ */ new Map();
1040
+ const add = (doc, text) => {
1041
+ const xs = out.get(doc) ?? [];
1042
+ out.set(doc, xs);
1043
+ xs.push(text.replace(/\s+/g, " ").slice(0, 160));
1044
+ };
1045
+ const errors = /* @__PURE__ */ new Set();
1046
+ for (const st of this.statements) {
1047
+ if (st.done) continue;
1048
+ if (st.error === void 0) add(st.doc, `never ran: ${String(st.fn)}`);
1049
+ else {
1050
+ errors.add(st.error);
1051
+ add(st.doc, `threw ${errorText(st.error)}: ${String(st.fn)}`);
1052
+ }
1053
+ }
1054
+ for (const [doc, error] of this.failures) if (!errors.has(error)) add(doc, `threw ${errorText(error)}`);
1055
+ return out;
1056
+ }
1057
+ /** Class `name` of `doc`'s module (evaluated). */ classOf(doc, name) {
1058
+ const state = this.loaded.get(doc);
1059
+ if (!state?.classes || state.error) throw state?.error ?? /* @__PURE__ */ new Error(`realm: ${doc.id} was not evaluated`);
1060
+ return state.classes[name];
1061
+ }
1062
+ /** The classes of `doc`'s module (evaluated), by name. */ classesOf(doc) {
1063
+ const names = this.modules.get(doc)?.classes ?? [];
1064
+ return new Map(names.map((name) => [name, this.classOf(doc, name)]));
1065
+ }
1066
+ /** The types of every class of the realm's modules (evaluated). */ classTypes() {
1067
+ if (!this._classTypes) {
1068
+ this._classTypes = /* @__PURE__ */ new Set();
1069
+ for (const [doc, m] of this.modules) for (const name of m.classes) try {
1070
+ this._classTypes.add(this.classOf(doc, name)?.type);
1071
+ } catch {}
1072
+ }
1073
+ return this._classTypes;
1074
+ }
1075
+ evaluate(doc) {
1076
+ if (this.loaded.has(doc)) return;
1077
+ const state = {};
1078
+ this.loaded.set(doc, state);
1079
+ const m = this.modules.get(doc);
1080
+ if (!m) {
1081
+ state.error = /* @__PURE__ */ new Error(`realm: ${doc.id} was not rendered`);
1082
+ throw state.error;
1083
+ }
1084
+ for (const { doc: from } of m.imports) if (from) {
1085
+ try {
1086
+ this.evaluate(from);
1087
+ } catch (error) {
1088
+ state.error = error;
1089
+ throw error;
1090
+ }
1091
+ const failed = this.loaded.get(from)?.error;
1092
+ if (failed) {
1093
+ state.error = failed;
1094
+ throw failed;
1095
+ }
1096
+ }
1097
+ const scope = Object.create(null);
1098
+ const q = this.queueOf(doc);
1099
+ for (const { doc: from, names } of m.imports) {
1100
+ const read = from ? (name) => {
1101
+ const exported = this.loaded.get(from)?.exports;
1102
+ if (!exported) throw new ReferenceError(`Cannot access '${name}' before initialization`);
1103
+ return exported[name];
1104
+ } : (name) => name === "$q" ? q : this.rt[name];
1105
+ Object.defineProperties(scope, Object.getOwnPropertyDescriptors(getters(names, read)));
1106
+ }
1107
+ try {
1108
+ let fn = this.compiled.get(m);
1109
+ if (!fn) {
1110
+ fn = moduleFunction(m);
1111
+ this.compiled.set(m, fn);
1112
+ }
1113
+ fn(scope, (exported, classes) => {
1114
+ state.exports = exported;
1115
+ state.classes = classes;
1116
+ });
1117
+ } catch (error) {
1118
+ state.error = error;
1119
+ this.failures.set(doc, error);
1120
+ throw error;
1121
+ }
1122
+ }
1123
+ constructor(modules, compiled = /* @__PURE__ */ new Map()) {
1124
+ _define_property$2(this, "modules", void 0);
1125
+ _define_property$2(this, "compiled", void 0);
1126
+ /** The realm's runtime instance. */ _define_property$2(this, "rt", void 0);
1127
+ _define_property$2(this, "loaded", void 0);
1128
+ /**
1129
+ * The statements the modules queued (`$q`), each with its module (the build's load check,
1130
+ * MODEL CYCLE-GUARD-8): `done` once it ran; `error`: the error it failed with (not a wait).
1131
+ */ _define_property$2(this, "statements", void 0);
1132
+ /** The modules whose own body threw (not an import's failure), with the error. */ _define_property$2(this, "failures", void 0);
1133
+ _define_property$2(this, "_classTypes", void 0);
1134
+ this.modules = modules;
1135
+ this.compiled = compiled;
1136
+ this.rt = freshRuntime();
1137
+ this.loaded = /* @__PURE__ */ new Map();
1138
+ this.statements = [];
1139
+ this.failures = /* @__PURE__ */ new Map();
1140
+ }
1141
+ };
1142
+ /** The realms of each component (a component is the documents' epoch's), by render options. */ const realms = /* @__PURE__ */ new WeakMap();
1143
+ /**
1144
+ * The realm of `doc`'s import component (see `componentOf`) for the render options `key`, loaded:
1145
+ * one per component and options until a document changes (see `documentsEpoch`).
1146
+ * `moduleOf` renders a document's phase-1 module (a module that failed to evaluate throws on
1147
+ * `classOf`).
1148
+ */ function realmOf(doc, key, moduleOf) {
1149
+ const component = componentOf(doc);
1150
+ let byKey = realms.get(component);
1151
+ if (!byKey) realms.set(component, byKey = /* @__PURE__ */ new Map());
1152
+ const docs = component.docs;
1153
+ let realm = byKey.get(key);
1154
+ if (!realm) {
1155
+ const modules = /* @__PURE__ */ new Map();
1156
+ for (const d of docs) try {
1157
+ modules.set(d, moduleOf(d));
1158
+ } catch {}
1159
+ realm = new Realm(modules).load();
1160
+ byKey.set(key, realm);
1161
+ }
1162
+ return realm;
1163
+ }
1164
+
1165
+ //#endregion
1166
+ //#region packages/typescript/src/codegen/js-next.ts
1167
+ /**
1168
+ * The generated JS: the module prints the final structure core's `StructureModel` computes, and
1169
+ * the runtime adds nothing but metadata layers (`runtime/layers.ts`) and the helpers of
1170
+ * `runtime/blocks.ts`.
1171
+ *
1172
+ * - a reference is a thin node over its target (`$().ref(T)`); a bare plain alias IS its target
1173
+ * (`export { T as P }`), an annotated alias / an `annotate T as X` copy is `$alias(P, T)`;
1174
+ * - each distinct merge is one hidden class per module (`$M<n>`), whose single-contributor fields
1175
+ * are the contributor's node (`$f(Root, …path)`) and whose merged fields are own nodes layered
1176
+ * over their contributors (later first); a named merge / an interface with `extends` is printed
1177
+ * the same way under its own name;
1178
+ * - statements of a module in an import cycle run through `$q` (queued until the cycle's classes
1179
+ * are there) and the module ends with `$end()`; one in no cycle whose statements wait for each
1180
+ * other lists them (`$q(…, $Q)`) and ends with `$end($Q)`, which throws if one of them never
1181
+ * ran. A build loads every generated module, and every import cycle from each of its modules,
1182
+ * and fails on any load error (see `cycleLoadError`).
1183
+ */ function _define_property$1(obj, key, value) {
1184
+ if (key in obj) Object.defineProperty(obj, key, {
1185
+ value,
1186
+ enumerable: true,
1187
+ configurable: true,
1188
+ writable: true
1189
+ });
1190
+ else obj[key] = value;
1191
+ return obj;
1192
+ }
1193
+ var _globalThis, _Symbol_for;
1194
+ /** Builder chains longer than this are split into statements (see `chainOf`). */ const MAX_CHAIN = 500;
1195
+ /** A statement's text; one starting with `(` (a split chain) must not continue the previous line. */ const stmt = (text) => text.startsWith("(") ? `;${text}` : text;
1196
+ /** Whether a declaration is exported from its module. */ function isExported(d) {
1197
+ return d.node.token("export")?.text === "export";
1198
+ }
1199
+ const str = (s) => `"${escapeQuotes(s)}"`;
1200
+ /** `m`'s value at `k`, made by `make` and set when absent. */ function getOrSet(m, k, make) {
1201
+ let v = m.get(k);
1202
+ if (v === void 0) m.set(k, v = make());
1203
+ return v;
1204
+ }
1205
+ /** Whether steps `a` and `b` are the same. */ function samePath(a, b) {
1206
+ return a.length === b.length && a.every((x, i) => x === b[i]);
1207
+ }
1208
+ /**
1209
+ * Builder chain `c` (`$()…` / `$("kind")…`, helper name `$`) re-rooted to build `target` (a class,
1210
+ * a node read) in place: `$("", target)…` / `$("kind", target)…`.
1211
+ */ function inPlace($, c, target) {
1212
+ return c.startsWith(`${$}()`) ? `${$}("", ${target})${c.slice($.length + 2)}` : c.replace(new RegExp(`^\\${$}\\("([a-z]*)"\\)`), (_, kind) => `${$}("${kind}", ${target})`);
1213
+ }
1214
+ /**
1215
+ * The statement filling a placeholder at model path `q` of unit `U` (see `expr`); `item`: the
1216
+ * item of the `X | null` written there (the model's step passes through it to X, the read does
1217
+ * not: it is another node).
1218
+ */ const fillId = (U, q, item = false) => `chain:${U}:${q.join(".")}${item ? "|" : ""}`;
1219
+ /** A runtime path as a map key. */ const pathKey = (steps) => steps.join("\0");
1220
+ /** A scalar written type's identity: its primitive / literal node, or the alias it references. */ const scalarKey = (e) => e.k === "scalar" ? e.node : e.k === "ref" ? e.decl : void 0;
1221
+ /** `[step, kind], …`: the `$blk` / `$sh` data of runtime steps. */ const stepsText = (steps) => steps.map(([s, k]) => `[${str(s)}, ${k}]`).join(", ");
1222
+ /** The written expression one step (`|i`, `[]`, a prop name) below `e`. */ function exprStep(e, s) {
1223
+ if (s.startsWith("|")) return e.k === "uni" || e.k === "tup" ? e.items[Number(s.slice(1))] : void 0;
1224
+ if (s === "[]") return e.k === "arr" ? e.of : void 0;
1225
+ return e.k === "obj" ? e.props.find((p) => p.name === s)?.type : void 0;
1226
+ }
1227
+ const flagKeysMemo = /* @__PURE__ */ new WeakMap();
1228
+ /**
1229
+ * The keys layers read specially, from every spec of an annotations tree (core and plugins, not
1230
+ * only those a module writes: a raw or plugin write reads the same): `append` (multiple,
1231
+ * `mergeStrategy: 'append'`) and `notReferred` (`passedWhenReferred: false`). Sorted, memoized.
1232
+ */ function flagKeys(tree) {
1233
+ if (!tree) return {
1234
+ append: [],
1235
+ notReferred: []
1236
+ };
1237
+ let out = flagKeysMemo.get(tree);
1238
+ if (!out) {
1239
+ const append = /* @__PURE__ */ new Set();
1240
+ const notReferred = /* @__PURE__ */ new Set();
1241
+ forEachAnnotationSpec(tree, (name, spec) => {
1242
+ if (spec.config.multiple && spec.config.mergeStrategy === "append") append.add(name);
1243
+ if (spec.config.passedWhenReferred === false) notReferred.add(name);
1244
+ });
1245
+ flagKeysMemo.set(tree, out = {
1246
+ append: [...append].sort(),
1247
+ notReferred: [...notReferred].sort()
1248
+ });
1249
+ }
1250
+ return out;
1251
+ }
1252
+ /**
1253
+ * The binding of an in-place merge operand of declaration `d` at `steps` (`…&i`): a module-level
1254
+ * `let`, exported with an exported declaration (another module's merge may have its fields as
1255
+ * contributors: a merge operand is flattened into its operands).
1256
+ */ function inPlaceName(d, steps) {
1257
+ return uniqueName(`$i_${d.name}_${steps.map((s) => s.replace(/[^\w$]/g, (c) => c === "&" ? "" : "_")).join("_")}`, (n) => d.doc.registry.definitions.has(n) || d.doc.importedDefs.has(n), "_");
1258
+ }
1259
+ const hiddenExports = /* @__PURE__ */ new WeakMap();
1260
+ /**
1261
+ * The reserved names module `doc` exports its hidden merge classes under (like its
1262
+ * in-place operands, kept out of the `.d.ts`): `$h_<Decl>_<steps>` of the first place holding
1263
+ * each, breadth first from the module's declarations in source order through its own defs (a
1264
+ * shell def and the def it shells both). Computed from the module's own structure, so the module
1265
+ * and every module importing one of its hidden classes name it alike.
1266
+ */ function hiddenExportNames(model, doc) {
1267
+ let byDoc = hiddenExports.get(model);
1268
+ if (!byDoc) hiddenExports.set(model, byDoc = /* @__PURE__ */ new Map());
1269
+ let out = byDoc.get(doc);
1270
+ if (out) return out;
1271
+ out = /* @__PURE__ */ new Map();
1272
+ byDoc.set(doc, out);
1273
+ const names = /* @__PURE__ */ new Set();
1274
+ const own = (t) => t.kind === "merge" || t.kind === "umerge" ? t.module === doc : t.kind !== "view" && !!t.unit && model.declById(t.unit)?.doc === doc;
1275
+ const queue = [...model.decls.filter((d) => d.doc === doc && d.kind !== "as").map((decl) => ({
1276
+ decl,
1277
+ steps: [],
1278
+ def: model.defAt(decl, [])
1279
+ })), ...model.mergeRoots().filter((r) => r.mod === doc).map((r) => ({
1280
+ decl: r.decl,
1281
+ steps: r.path,
1282
+ def: r.def
1283
+ }))];
1284
+ const seen = /* @__PURE__ */ new Set();
1285
+ for (const { decl, steps, def } of queue) {
1286
+ if (!def || !own(def) || seen.has(def.key)) continue;
1287
+ seen.add(def.key);
1288
+ if (def.kind === "shell" && def.base) queue.push({
1289
+ decl,
1290
+ steps,
1291
+ def: def.base
1292
+ });
1293
+ if (def.kind === "merge" || def.kind === "umerge") {
1294
+ const name = uniqueName(`$h_${[decl.name, ...steps.map((s) => s.replace(/[^\w$]/g, "_"))].join("_")}`, (n) => names.has(n) || doc.registry.definitions.has(n) || doc.importedDefs.has(n), "_");
1295
+ names.add(name);
1296
+ out.set(def.key, name);
1297
+ }
1298
+ for (const k of def.names?.() ?? []) queue.push({
1299
+ decl,
1300
+ steps: [...steps, k],
1301
+ def: def.slot(k)?.def
1302
+ });
1303
+ for (let b = 0; b < (def.size ?? 0); b++) queue.push({
1304
+ decl,
1305
+ steps: [...steps, `|${b}`],
1306
+ def: def.branch?.(b)
1307
+ });
1308
+ }
1309
+ return out;
1310
+ }
1311
+ /** Whether a module is in an import cycle of `.as` modules. */ const inCycle = (doc) => sccOf(doc).size > 1;
1312
+ var JsNextRenderer = class extends JsRenderer {
1313
+ /**
1314
+ * The statement reads the structure of `d`: its statement runs first, and so does its
1315
+ * target's when `d` is an alias (its def is its target's, built by the target's statement).
1316
+ */ needStructure(d, seen = /* @__PURE__ */ new Set()) {
1317
+ if (seen.has(d)) return;
1318
+ seen.add(d);
1319
+ this.needs.add(d.id);
1320
+ const e = d.kind === "type" ? this.model.declExpr(d) : void 0;
1321
+ const target = d.kind === "as" ? this.model.asTarget(d) : e?.k === "ref" || e?.k === "chain" ? e.decl : void 0;
1322
+ if (target) this.needStructure(target, seen);
1323
+ }
1324
+ needUnit(unit) {
1325
+ const d = unit.startsWith("m:") ? void 0 : this.model.declById(unit);
1326
+ if (d) this.needStructure(d);
1327
+ else this.needs.add(unit);
1328
+ }
1329
+ /** Records guard `text` (`read`: the read it codes) of the statement being printed. */ guard(text, printed = true, read) {
1330
+ const key = printed ? text : `#${text}`;
1331
+ if (!this.guards.has(key)) this.guards.set(key, {
1332
+ text,
1333
+ printed,
1334
+ read
1335
+ });
1336
+ return text;
1337
+ }
1338
+ /**
1339
+ * `$f(name, …steps)` (`$ft` / `$fc` for `mode` 1 / 2): a read of the node at runtime `steps` of
1340
+ * class `name`, a guard of the statement being printed (`printed`: see {@link TGuard.printed}).
1341
+ */ read(mode, name, steps, printed = true) {
1342
+ const text = `${this.util(mode === 0 ? "$f" : mode === 1 ? "$ft" : "$fc")}(${[name, ...steps.map(str)].join(", ")})`;
1343
+ const read = {
1344
+ mode,
1345
+ name,
1346
+ steps
1347
+ };
1348
+ this.readsByText.set(text, read);
1349
+ return this.guard(text, printed, read);
1350
+ }
1351
+ /** Runs `fn` for a statement of its own (its needs and guards). */ statement(builds, fn) {
1352
+ const saved = [
1353
+ this.needs,
1354
+ this.guards,
1355
+ this.fillReads
1356
+ ];
1357
+ this.needs = /* @__PURE__ */ new Set();
1358
+ this.guards = /* @__PURE__ */ new Map();
1359
+ this.fillReads = [];
1360
+ try {
1361
+ const text = fn();
1362
+ this.statements.push({
1363
+ text,
1364
+ builds,
1365
+ needs: this.needs,
1366
+ guards: this.guards,
1367
+ fillReads: this.fillReads
1368
+ });
1369
+ } finally {
1370
+ [this.needs, this.guards, this.fillReads] = saved;
1371
+ }
1372
+ }
1373
+ decl(node) {
1374
+ return this.model.declOfNode(node);
1375
+ }
1376
+ /** A bare plain alias (no annotations of its own): the module exports its target. */ isBare(d) {
1377
+ return d.kind === "type" && this.model.bareTarget(d) !== d;
1378
+ }
1379
+ /**
1380
+ * A class whose def is another node's (an annotated alias, a chain ref, an `as` copy: its
1381
+ * `$alias` installs it): declared with `type = null`, so a read before then waits (`$q`).
1382
+ */ isReplacing(d) {
1383
+ if (d.kind === "as") return true;
1384
+ const e = d.kind === "type" ? this.model.declExpr(d) : void 0;
1385
+ return e?.k === "ref" && !this.isBare(d) || e?.k === "chain";
1386
+ }
1387
+ classTypeInit(node) {
1388
+ const d = this.decl(node);
1389
+ return d && (this.isReplacing(d) || this.defShared(d)) ? "null" : "{}";
1390
+ }
1391
+ /**
1392
+ * A `type X = A & B` class whose builder takes another node's def (`$("", X).ref(…)` /
1393
+ * `.type(…)`: a merge collapsing to one class or a hidden class, a scalar merge that is a
1394
+ * reference): declared with `type = null` too — a reference to it reads its def once it is
1395
+ * built, also from the other module of an import cycle.
1396
+ */ defShared(d) {
1397
+ const e = d.kind === "type" ? this.model.declExpr(d) : void 0;
1398
+ if (e?.k !== "and" || this.model.shapeAt(d, [])?.k === "never") return false;
1399
+ const def = this.model.declDef(d);
1400
+ if (def?.kind === "class" && def.unit === d.id) return false;
1401
+ return def ? true : isRef(this.doc.mergeIntersection(e.node));
1402
+ }
1403
+ /** `$a(P.metadata, …)` writes of a class's own annotations (after its `$alias`). */ annotateCalls(name, node) {
1404
+ let out = "";
1405
+ for (const an of node.annotations ?? []) {
1406
+ const { value, multiple } = this.computeAnnotationValue(node, an);
1407
+ out += `\n${this.util("annotate")}(${name}.metadata, ${str(an.name)}, ${value}${multiple ? ", true" : ""})`;
1408
+ }
1409
+ return out;
1410
+ }
1411
+ /**
1412
+ * A bundled JSON schema (`$jbm`): the literal while the applied block modules are
1413
+ * those the build accounted.
1414
+ */ renderJsonSchemaMethod(node) {
1415
+ if (node.countAnnotations("emit.jsonSchema") === 0 && this.jsonSchemaMode !== "bundle") {
1416
+ super.renderJsonSchemaMethod(node);
1417
+ return;
1418
+ }
1419
+ this.bundledSchemas.push(node.id);
1420
+ this.writeln("static toJsonSchema() {");
1421
+ this.indent().writeln(`return ${this.util("bundledSchemaOf")}(this, () => {`);
1422
+ this.indent().writeln(`return ${schemaMarker(node.id)}`).unindent();
1423
+ this.writeln(`}${accountedMarker(node.id)})`).unindent();
1424
+ this.writeln("}");
1425
+ }
1426
+ /** The block modules the build's realm applied (`$jbm` compares the runtime's with them). */ accountedFor(realm) {
1427
+ return [...realm.rt.appliedBlockModules()].sort();
1428
+ }
1429
+ realm() {
1430
+ return moduleRealm(this.doc, this.opts, this.compileMode);
1431
+ }
1432
+ renderType(node) {
1433
+ const d = this.decl(node);
1434
+ if (d && this.isBare(d)) return;
1435
+ super.renderType(node);
1436
+ }
1437
+ renderModule() {
1438
+ const errors = this.doc.structureErrors();
1439
+ if (errors.length > 0) throw new Error(`${this.doc.id}: ${errors[0].message}`);
1440
+ const diag = this.doc.getDiagMessages().find((m) => m.severity === 1);
1441
+ if (diag) throw new Error(`${this.doc.id}: ${diag.message}`);
1442
+ const module = super.renderModule();
1443
+ if (this.model.tooComplexIn(this.doc)) throw new Error(`${this.doc.id}: ${MERGE_TOO_COMPLEX}`);
1444
+ return {
1445
+ ...module,
1446
+ aliases: [...this.aliasExports]
1447
+ };
1448
+ }
1449
+ /**
1450
+ * The local name of declaration `d`'s class: a bare alias's is its target's; another module's
1451
+ * is the binding of its import (synthesized when the module does not import it).
1452
+ */ nameOf(d) {
1453
+ if (d.doc === this.doc) {
1454
+ if (this.isBare(d)) return this.nameOf(this.model.aliasStep(d));
1455
+ return d.name;
1456
+ }
1457
+ const mine = this.boundHere(d);
1458
+ if (!mine && !isExported(d)) {
1459
+ const via = this.hiddenDeclRef(d);
1460
+ if (via) return via;
1461
+ throw new Error(`${this.doc.id}: Type "${d.name}" (declared in ${d.doc.id}) is not exported but is required here — export it`);
1462
+ }
1463
+ const name = mine && !this.unused.has(d.name) ? d.name : this.synthBinding(d.name, {
1464
+ doc: d.doc,
1465
+ node: d.node
1466
+ })?.alias ?? d.name;
1467
+ this.read(0, name, []);
1468
+ return name;
1469
+ }
1470
+ /** Whether declaration `d` (of another module) is bound here under its own name. */ boundHere(d) {
1471
+ const mine = this.resolveOwner(this.doc, d.name);
1472
+ return mine?.doc === d.doc && mine.node === d.node;
1473
+ }
1474
+ /**
1475
+ * Whether the chain ref at (U, q) is printed as a placeholder its own statement fills: every
1476
+ * chain into this module or another module of its import cycle (a chain reaching a later
1477
+ * declaration, or one whose target holds a chain back, `P.q?: Q.x` with `Q.x: P.x`, cannot be
1478
+ * read by U's builder in every order — nor in every evaluation order of the cycle's modules).
1479
+ */ fillsLater(t, U, q) {
1480
+ return this.nearDoc(t.doc) && U.doc === this.doc && q.length > 0 && !q.some((s) => s.startsWith("&"));
1481
+ }
1482
+ /** Module `doc` is this one or another module of its import cycle. */ nearDoc(doc) {
1483
+ return doc === this.doc || this.importers().has(doc);
1484
+ }
1485
+ fillLater(U, q, text, item = false) {
1486
+ this.fillOnce(fillId(U.id, q, item), U.id, text);
1487
+ }
1488
+ /** The fill statement `id` (once), of declaration `decl`'s node when it is one's. */ fillOnce(id, decl, text) {
1489
+ if (!this.chainFills.has(id)) {
1490
+ this.chainFills.add(id);
1491
+ if (decl) this.fillDecls.add(decl);
1492
+ this.statement(id, text);
1493
+ }
1494
+ }
1495
+ /**
1496
+ * A declaration another module does not export (a merge here reads its class): through a
1497
+ * reference to it an exported declaration of that module holds — `$f(E, …).ref.type()` —,
1498
+ * breadth first; undefined when none (the module fails: export it).
1499
+ */ hiddenDeclRef(d) {
1500
+ if (this.hiddenDecls.has(d)) return this.hiddenDecls.get(d);
1501
+ let out;
1502
+ const queue = this.model.decls.filter((x) => x.doc === d.doc && x !== d && x.kind !== "as" && isExported(x)).map((decl) => ({
1503
+ decl,
1504
+ steps: []
1505
+ }));
1506
+ const seen = /* @__PURE__ */ new Set();
1507
+ for (let i = 0; i < queue.length && !out; i++) {
1508
+ const { decl, steps } = queue[i];
1509
+ if (steps.length > 0) {
1510
+ const branch = steps.at(-1).startsWith("|");
1511
+ const ends = branch ? void 0 : this.model.slotAt(decl, steps)?.ends;
1512
+ const e = branch ? this.exprAt(decl, steps) : ends?.length === 1 ? ends[0] : void 0;
1513
+ if (e?.k === "ref" && this.model.bareTarget(e.decl) === d) {
1514
+ out = `${this.pathRef(decl, steps)}.ref.type()`;
1515
+ break;
1516
+ }
1517
+ }
1518
+ const def = this.model.defAt(decl, steps);
1519
+ if (!def || seen.has(`${decl.id}:${def.key}`)) continue;
1520
+ seen.add(`${decl.id}:${def.key}`);
1521
+ for (const k of def.names?.() ?? []) queue.push({
1522
+ decl,
1523
+ steps: [...steps, k]
1524
+ });
1525
+ for (let b = 0; b < (def.size ?? 0); b++) queue.push({
1526
+ decl,
1527
+ steps: [...steps, `|${b}`]
1528
+ });
1529
+ }
1530
+ this.hiddenDecls.set(d, out);
1531
+ return out;
1532
+ }
1533
+ /** The class a unit id names (a declaration, or a hidden class `m:<key>`). */ unitName(unit) {
1534
+ if (unit.startsWith("m:")) return this.hiddenName(this.model.defByKey(unit));
1535
+ return this.nameOf(this.model.declById(unit));
1536
+ }
1537
+ /** Another module's hidden class: the binding of its export (see {@link hiddenExportNames}). */ importedHidden(def, mod) {
1538
+ const exported = hiddenExportNames(this.model, mod).get(def.key);
1539
+ if (!exported) throw new Error(`atscript next format: hidden class ${def.key} has no place in ${mod.id}`);
1540
+ const name = this.synthBinding(exported, { doc: mod })?.alias ?? exported;
1541
+ this.read(0, name, []);
1542
+ return name;
1543
+ }
1544
+ /** The hidden class of merge def `def` (printed on first use). */ hiddenName(def) {
1545
+ if (def.module && def.module !== this.doc) return this.importedHidden(def, def.module);
1546
+ let h = this.hidden.get(def.key);
1547
+ if (!h) {
1548
+ h = {
1549
+ name: this.allocAlias(`$M${this.hidden.size}`, this.getSynthTaken()),
1550
+ def
1551
+ };
1552
+ this.hidden.set(def.key, h);
1553
+ const exported = hiddenExportNames(this.model, this.doc).get(def.key);
1554
+ if (exported) this.aliasExports.push({
1555
+ line: `export { ${h.name} as ${exported} }`,
1556
+ name: exported,
1557
+ local: h.name
1558
+ });
1559
+ this.printHidden(h.name, def);
1560
+ }
1561
+ return h.name;
1562
+ }
1563
+ /**
1564
+ * The runtime steps below `prefix` of declaration `d` for model `steps`: a `X | null` the model
1565
+ * passes through is a union node at runtime (`|i`: its non-null item). `defNode`: down to the
1566
+ * node typed by the def at `steps` — the non-null item of `X | null` written there. The alias
1567
+ * unions passed (`type N = X | null`) are built first: the statement's needs, or `aliases`'.
1568
+ */ runtimePath(d, prefix, steps, defNode = false, aliases) {
1569
+ const mk = prefix.length === 0 ? `${d.id}\0${defNode}\0${pathKey(steps)}` : void 0;
1570
+ let hit = mk === void 0 ? void 0 : this.runtimePaths.get(mk);
1571
+ if (!hit) {
1572
+ hit = {
1573
+ steps: [],
1574
+ aliases: /* @__PURE__ */ new Set()
1575
+ };
1576
+ const { steps: out, aliases: passed } = hit;
1577
+ const root = this.model.structureRoot(d);
1578
+ const itemsAt = (at, below) => at.length > 0 ? this.slotNullItems(this.model.slotAt(d, at), passed, below) : root?.kind === "type" ? this.nullItems(this.model.declExpr(root), passed, below) : [];
1579
+ for (let i = 0; i < steps.length; i++) {
1580
+ for (const item of itemsAt([...prefix, ...steps.slice(0, i)], true)) out.push(`|${item}`);
1581
+ out.push(steps[i]);
1582
+ }
1583
+ if (defNode) for (const item of itemsAt([...prefix, ...steps], false)) out.push(`|${item}`);
1584
+ if (mk !== void 0) this.runtimePaths.set(mk, hit);
1585
+ }
1586
+ this.passAliases(hit.aliases, aliases);
1587
+ return hit.steps;
1588
+ }
1589
+ /** Alias unions `passed` on the way of a read: into `to`, else built before the statement. */ passAliases(passed, to) {
1590
+ for (const a of passed) if (to) to.add(a);
1591
+ else this.needStructure(a);
1592
+ }
1593
+ /**
1594
+ * The written expression at `steps` of declaration `d` (props, `[]`, `|i`, `&i`: the i-th
1595
+ * operand of an intersection, flattened as the model does).
1596
+ */ exprAt(d, steps) {
1597
+ let e = d.kind === "interface" ? {
1598
+ k: "obj",
1599
+ node: d.node,
1600
+ props: this.model.ownProps(d)
1601
+ } : this.model.declExpr(d);
1602
+ for (const s of steps) {
1603
+ while (e?.k === "nul") e = e.of;
1604
+ if (!e) return;
1605
+ e = s.startsWith("&") ? andExprs(e)[Number(s.slice(1))] : exprStep(e, s);
1606
+ }
1607
+ return e;
1608
+ }
1609
+ /** The runtime steps of model `steps` below written expression `e` (see {@link runtimePath}). */ exprPath(e, steps) {
1610
+ const out = [];
1611
+ for (const s of steps) {
1612
+ if (e?.k === "nul") {
1613
+ for (const at of this.nullItemsNeeded(e)) out.push(`|${at}`);
1614
+ e = e.of;
1615
+ }
1616
+ out.push(s);
1617
+ e = e && exprStep(e, s);
1618
+ }
1619
+ return out;
1620
+ }
1621
+ /**
1622
+ * The runtime items a model step passes through at a node written `e`: `X | null` is a union
1623
+ * node (its non-null item), and so is an alias of one (`type N = X | null`; `N | null`: two).
1624
+ * `below`: a step below the node — through a chain ref to a field typed so too (`p: T.v`: the
1625
+ * node is T.v's, `$alias`), whose own node is not an item.
1626
+ */ nullItems(e0, aliases, below = true) {
1627
+ const out = [];
1628
+ let e = e0;
1629
+ const seen = /* @__PURE__ */ new Set();
1630
+ while (e) if (e.k === "nul") {
1631
+ const at = this.nonNullItem(e, this.doc);
1632
+ out.push(at);
1633
+ e = this.model.exprOf(this.doc, e.node.unwrap()[at]);
1634
+ } else if (e.k === "ref" && e.decl.kind === "type" && !seen.has(e.decl)) {
1635
+ seen.add(e.decl);
1636
+ const x = this.model.declExpr(e.decl);
1637
+ if (x.k === "nul" || x.k === "ref" || x.k === "and" || x.k === "chain") {
1638
+ aliases.add(e.decl);
1639
+ e = x;
1640
+ } else e = void 0;
1641
+ } else if (below && e.k === "ref" && e.decl.kind === "as" && !seen.has(e.decl)) {
1642
+ seen.add(e.decl);
1643
+ const t = this.model.asTarget(e.decl);
1644
+ if (t) {
1645
+ aliases.add(e.decl);
1646
+ e = {
1647
+ k: "ref",
1648
+ decl: t,
1649
+ node: t.node
1650
+ };
1651
+ } else e = void 0;
1652
+ } else if (below && e.k === "chain" && !seen.has(e.node)) {
1653
+ seen.add(e.node);
1654
+ const slot = this.model.slotAt(e.decl, e.path);
1655
+ if (slot?.ends.length === 1) e = slot.ends[0];
1656
+ else {
1657
+ out.push(...this.mergedNullItem(slot));
1658
+ e = void 0;
1659
+ }
1660
+ } else if (e.k === "and" && this.model.nullableExpr(e)) {
1661
+ out.push(0);
1662
+ e = void 0;
1663
+ } else e = void 0;
1664
+ return out;
1665
+ }
1666
+ /** {@link nullItems} of a read of the statement being printed: the alias unions built first. */ nullItemsNeeded(e) {
1667
+ const aliases = /* @__PURE__ */ new Set();
1668
+ const out = this.nullItems(e, aliases);
1669
+ this.passAliases(aliases);
1670
+ return out;
1671
+ }
1672
+ /** The runtime items a model step passes through at node `slot` (see {@link nullItems}). */ slotNullItems(slot, aliases, below = true) {
1673
+ return slot?.ends.length === 1 ? this.nullItems(slot.ends[0], aliases, below) : this.mergedNullItem(slot);
1674
+ }
1675
+ /** A merged node every contributor of which is nullable: its type is item 0 (see `slotNode`). */ mergedNullItem(slot) {
1676
+ return slot?.contributors && this.model.nullableSlot(slot) && !this.model.nullSlot(slot) ? [0] : [];
1677
+ }
1678
+ /** The non-null item of a written `X | null` (the model passes through it), else undefined. */ nonNullItem(e, doc) {
1679
+ if (e.k !== "nul") return;
1680
+ const at = e.node.unwrap().findIndex((n) => !isNull(this.model.exprOf(doc, n)));
1681
+ return at < 0 ? 0 : at;
1682
+ }
1683
+ /** A `$f(…)` read of a node whose def is captured: `$ft(…)` (its final def), a guard too. */ typed(ref) {
1684
+ const r = this.readsByText.get(ref);
1685
+ if (r?.mode === 0) return this.read(1, r.name, r.steps);
1686
+ const f = `${this.util("$f")}(`;
1687
+ return ref.startsWith(f) ? this.guard(`${this.util("$ft")}(${ref.slice(f.length)}`) : ref;
1688
+ }
1689
+ /** The statement reads `d`'s nodes along `steps`: the classes whose defs they walk are built first. */ needPath(d, steps) {
1690
+ for (let i = 0; i < steps.length; i++) {
1691
+ const at = this.model.defAt(d, steps.slice(0, i));
1692
+ for (let def = at; def; def = def.kind === "view" ? def.base : void 0) {
1693
+ def = unshell(def);
1694
+ if (def.kind === "merge" || def.kind === "umerge") this.needs.add(def.key);
1695
+ else if (def.unit && !def.unit.startsWith("m:")) this.needUnit(def.unit);
1696
+ else if (def.kind === "view" && def.src?.[0]?.k === "ref") this.needStructure(def.src[0].decl);
1697
+ }
1698
+ }
1699
+ }
1700
+ /**
1701
+ * The statement reads the nodes along model `path` of `d`: a placeholder a statement of its own
1702
+ * fills (see `expr`) at any node the read passes — in whichever class it is reached (see
1703
+ * {@link reached}), and below every shell on the way (a shell's def is the def of the node it
1704
+ * is over) — is filled first. `shell`: a shell stage, which reads the defs on the way but only
1705
+ * the identity of the node at the end (its shell reads that node's def when used). `steps`:
1706
+ * the runtime steps read, when they are not `path`'s (an item stage's: the items after it).
1707
+ */ needFills(d, path, shell = false, steps) {
1708
+ const r = this.reads(d, steps ?? this.runtimePath(d, [], path));
1709
+ this.passAliases(r.needs);
1710
+ this.fillReads.push({
1711
+ reached: r.out,
1712
+ shell
1713
+ });
1714
+ }
1715
+ /** The fills statement `st` needs (see {@link needFills}): of the classes with fills. */ fillNeeds(st) {
1716
+ for (const { reached, shell } of st.fillReads) for (const r of reached) {
1717
+ if (!this.fillDecls.has(r.decl.id)) continue;
1718
+ let at;
1719
+ r.marks.forEach((k, j) => {
1720
+ const node = k ?? at;
1721
+ if (node !== void 0 && j >= r.from && (!shell || j < r.steps.length - 1)) st.needs.add(fillId(r.decl.id, r.m.slice(0, node), k === void 0));
1722
+ at = k;
1723
+ });
1724
+ }
1725
+ }
1726
+ /** `Decl, [steps]` of a chain ref (`.ref`, `$alias`): its `$f` read is a guard too. */ chainArgs(d, path) {
1727
+ this.needPath(d, path);
1728
+ this.needFills(d, path);
1729
+ const name = this.nameOf(d);
1730
+ const steps = this.runtimePath(d, [], path);
1731
+ this.read(1, name, steps);
1732
+ return `${name}, [${steps.map(str).join(", ")}]`;
1733
+ }
1734
+ /** `$f(Decl, …steps)` (the declaration's class itself without steps). */ pathRef(d, steps, defNode = false) {
1735
+ this.needStructure(d);
1736
+ this.needPath(d, steps);
1737
+ const path = this.runtimePath(d, [], steps, defNode);
1738
+ if (path.length === 0) return this.nameOf(d);
1739
+ this.util("$f");
1740
+ return this.read(0, this.nameOf(d), path);
1741
+ }
1742
+ /**
1743
+ * The node a slot's owner names: `$f(Root, …path)`; a path through an in-place merge operand
1744
+ * (`&i`) starts at that operand's node.
1745
+ */ nodeRef(owner, defNode = false) {
1746
+ const at = owner.path.findLastIndex((s) => s.startsWith("&"));
1747
+ if (at >= 0) {
1748
+ const key = `${owner.unit}:${owner.path.slice(0, at + 1).join("/")}`;
1749
+ let name = this.inPlace.get(key);
1750
+ const d = this.model.declById(owner.unit);
1751
+ if (!name && d?.doc === this.doc) {
1752
+ const q = owner.path.slice(0, at);
1753
+ let e = this.exprAt(d, q);
1754
+ while (e?.k === "nul") e = e.of;
1755
+ if (e?.k === "and") {
1756
+ this.printInPlaceOperands(e, d, q);
1757
+ name = this.inPlace.get(key);
1758
+ }
1759
+ }
1760
+ if (name && d?.doc === this.doc) this.needs.add(`const:${name}`);
1761
+ if (!name && d && d.doc !== this.doc) {
1762
+ const exported = inPlaceName(d, owner.path.slice(0, at + 1));
1763
+ name = this.synthBinding(exported, {
1764
+ doc: d.doc,
1765
+ node: d.node
1766
+ })?.alias ?? exported;
1767
+ this.needUnit(owner.unit);
1768
+ }
1769
+ if (!name) throw new Error(`atscript next format: in-place operand ${key} is not printed`);
1770
+ const rest = owner.path.slice(at + 1);
1771
+ const prefix = owner.path.slice(0, at + 1);
1772
+ const operand = this.exprAt(d, prefix);
1773
+ const steps = !operand ? rest : defNode ? this.exprPath(operand, [...rest, ""]).slice(0, -1) : this.exprPath(operand, rest);
1774
+ return this.read(0, name, steps);
1775
+ }
1776
+ const root = this.unitName(owner.unit);
1777
+ const d = this.model.declById(owner.unit);
1778
+ const path = d ? this.runtimePath(d, [], owner.path, defNode) : owner.path;
1779
+ if (path.length === 0) return root;
1780
+ this.needUnit(owner.unit);
1781
+ return this.read(0, root, path);
1782
+ }
1783
+ /** `.annotate(…)` calls of annotations `anns` of `node`. */ annotations(node, anns) {
1784
+ let out = "";
1785
+ for (const an of anns ?? []) {
1786
+ const { value, multiple } = this.computeAnnotationValue(node, an);
1787
+ out += `.annotate(${str(an.name)}, ${value}${multiple ? ", true" : ""})`;
1788
+ }
1789
+ return out;
1790
+ }
1791
+ /**
1792
+ * The annotations a node of `holder` (a prop, a declaration) writes itself: its own when its
1793
+ * type is a class (a reference, a chain, a merge: the rest comes through its layers), else its
1794
+ * evaluated ones (a primitive's built-ins included).
1795
+ */ ownAnnotations(holder, e) {
1796
+ const layered = e.k === "ref" || e.k === "chain" || e.k === "and" || e.k === "uni" && isRef(e.node);
1797
+ const anns = layered ? holder.annotations : this.doc.evalAnnotationsForNode(holder);
1798
+ const out = this.annotations(holder, anns);
1799
+ return !layered && holder.entity === "type" ? out + this.intrinsicMarks(anns) : out;
1800
+ }
1801
+ /**
1802
+ * A primitive extension's own `passedWhenReferred: false` annotations are part of
1803
+ * the type: marked (`.intrinsic(…)`) on a declaration's node, they pass the reference layers over it.
1804
+ */ intrinsicMarks(anns) {
1805
+ const keys = [...new Map((anns ?? []).map((a) => [a.name, a])).values()].filter((a) => a.intrinsic && this.doc.resolveAnnotation(a.name)?.config.passedWhenReferred === false).map((a) => str(a.name));
1806
+ return keys.length > 0 ? `.intrinsic(${keys.join(", ")})` : "";
1807
+ }
1808
+ /** A primitive / literal node's chain (`member`: a union / tuple item or an array element). */ scalar(node, member) {
1809
+ return this.capture(() => {
1810
+ if (isPrimitive(node)) {
1811
+ this.definePrimitive(node);
1812
+ if (member && node.annotations?.length) {
1813
+ this.indent();
1814
+ for (const an of node.annotations) this.resolveAnnotationValue(node, an);
1815
+ this.unindent();
1816
+ }
1817
+ } else if (isConst(node)) {
1818
+ this.writeln(`${this.$}()`);
1819
+ this.indent().defineConst(node).unindent();
1820
+ } else this.writeln(this.scalarGroup(node, member));
1821
+ });
1822
+ }
1823
+ /**
1824
+ * What the scalar algebra gives besides a primitive / literal: a reference (to a scalar type),
1825
+ * a group of scalars kept as written (a union, an intersection both sides of which check
1826
+ * something, a tuple), an array of them.
1827
+ */ scalarGroup(node, member) {
1828
+ const $ = this.$;
1829
+ if (isRef(node)) {
1830
+ const e = this.model.exprOf(this.doc, node);
1831
+ if (e.k === "ref") return `${$}().ref(${this.refTarget(e.decl)})`;
1832
+ const field = (x) => {
1833
+ if (x.k !== "chain") return;
1834
+ this.needStructure(x.decl);
1835
+ return `${$}().ref(${this.chainArgs(x.decl, x.path)})`;
1836
+ };
1837
+ if (e.k === "uni" && e.items.every((x) => x.k === "chain")) return this.chainOf(`${$}("union")`, e.items.map((x) => `\n .item(${this.indentText(field(x))}.$type)`));
1838
+ return field(e) ?? (e.k === "scalar" ? this.scalar(e.node, member) : `${$}().designType("any")`);
1839
+ }
1840
+ if (isGroup(node) && node.op === "&") {
1841
+ const merged = this.doc.mergeIntersection(node);
1842
+ if (merged !== node && !(isGroup(merged) && merged.op === "&")) return this.scalar(merged, member).trimEnd();
1843
+ node = merged;
1844
+ }
1845
+ if (isGroup(node) && node.unwrap().length === 1) return this.scalar(node.unwrap()[0], member).trimEnd();
1846
+ if (isGroup(node) || isTuple(node)) {
1847
+ let out = `${$}("${isTuple(node) ? "tuple" : node.op === "&" ? "intersection" : "union"}")`;
1848
+ for (const item of node.unwrap()) out += `\n .item(${this.indentText(this.scalar(item, true))}.$type)`;
1849
+ return out;
1850
+ }
1851
+ if (isArray(node)) return `${$}("array").of(${this.indentText(this.scalar(node.getDefinition(), true))}.$type)`;
1852
+ return `${$}().designType("any")`;
1853
+ }
1854
+ /**
1855
+ * The chain building the node a written expression `e` gives at (U, q) (no `.$type`): a
1856
+ * reference, a builder written in place, a merge's hidden class.
1857
+ */ expr(e, U, q, member = false) {
1858
+ const $ = this.$;
1859
+ switch (e.k) {
1860
+ case "ref": {
1861
+ const target = this.isBare(e.decl) ? this.model.bareTarget(e.decl) : e.decl;
1862
+ if (this.isReplacing(target) && this.fillsLater(target, U, q)) {
1863
+ this.fillLater(U, q, () => {
1864
+ this.needs.add(target.id);
1865
+ return `${this.util("$alias")}(${this.pathRef(U, q, !!member)}, ${this.refTarget(target)}, [])`;
1866
+ }, member === "item");
1867
+ return `${$}()`;
1868
+ }
1869
+ return `${$}().ref(${this.refTarget(e.decl)})`;
1870
+ }
1871
+ case "chain":
1872
+ if (this.fillsLater(e.decl, U, q)) {
1873
+ this.fillLater(U, q, () => {
1874
+ this.needStructure(e.decl);
1875
+ return `${this.util("$alias")}(${this.pathRef(U, q, !!member)}, ${this.chainArgs(e.decl, e.path)})`;
1876
+ }, member === "item");
1877
+ return `${$}()`;
1878
+ }
1879
+ this.needStructure(e.decl);
1880
+ return `${$}().ref(${this.chainArgs(e.decl, e.path)})`;
1881
+ case "obj": return this.chainOf(`${$}("object")`, e.props.map((p) => `\n .${this.propCall(p.node, p.name)}${this.indentText(this.propNode(p.node, p.type, p.optional, U, [...q, p.name]))}.$type)`));
1882
+ case "arr": return `${$}("array").of(${this.indentText(this.expr(e.of, U, [...q, "[]"], true))}.$type)`;
1883
+ case "nul":
1884
+ case "uni":
1885
+ case "tup": {
1886
+ const group = e.node;
1887
+ const items = e.k === "nul" ? group.unwrap().map((n) => this.model.exprOf(this.doc, n)) : e.items;
1888
+ const kind = e.k === "tup" ? "tuple" : "union";
1889
+ return this.chainOf(`${$}("${kind}")`, items.map((x, i) => {
1890
+ const steps = e.k === "nul" ? q : [...q, `|${i}`];
1891
+ return `\n .item(${this.indentText(this.expr(x, U, steps, e.k === "nul" ? "item" : true))}.$type)`;
1892
+ }));
1893
+ }
1894
+ case "and": return this.mergeAt(e, U, q, member);
1895
+ case "scalar": return this.scalar(e.node, !!member);
1896
+ default: return `${$}().designType("any")`;
1897
+ }
1898
+ }
1899
+ /** The class a reference to `d` is built over (a bare alias: its target). */ refTarget(d) {
1900
+ const target = this.isBare(d) && d.doc === this.doc ? this.model.bareTarget(d) : d;
1901
+ const name = this.nameOf(target);
1902
+ if (target.doc === this.doc && this.replacing.has(target.id)) {
1903
+ this.needs.add(target.id);
1904
+ this.read(1, name, []);
1905
+ } else if (target.doc === this.doc && target.kind === "type" && this.model.shapeAt(target, [])?.k === "scalar") this.needs.add(target.id);
1906
+ return name;
1907
+ }
1908
+ /** `.prop("name", ` / `.propPattern(/re/, ` of prop `prop`. */ propCall(prop, name) {
1909
+ const pattern = prop.token("identifier")?.pattern;
1910
+ return pattern ? `propPattern(/${pattern.source}/${pattern.flags}, ` : `prop(${str(name)}, `;
1911
+ }
1912
+ /** A prop's own node (written in place): its type's chain, its annotations, `?`. */ propNode(prop, e, optional, U, q) {
1913
+ return `${this.expr(e, U, q)}${this.ownAnnotations(prop, e)}${optional ? ".optional()" : ""}`;
1914
+ }
1915
+ indentText(text) {
1916
+ return text.replaceAll("\n", "\n ");
1917
+ }
1918
+ /** An unmergeable merge's node: `never`, tagged as a written `never` is (0.1.110). */ never() {
1919
+ return `${this.$}().designType("never").tags("never")`;
1920
+ }
1921
+ /**
1922
+ * An intersection written at (U, q): the hidden class of its merge (`$().ref($Mn)`), a union of
1923
+ * them (a union operand distributes), the class it collapses to, or the scalar the algebra gives.
1924
+ */ mergeAt(e, U, q, member = false) {
1925
+ if (member !== true && andExprs(e).some((x) => x.k === "chain" && this.fillsLater(x.decl, U, q))) {
1926
+ this.fillLater(U, q, () => inPlace(this.$, this.mergeAt0(e, U, q), this.pathRef(U, q, !!member)), member === "item");
1927
+ return `${this.$}()`;
1928
+ }
1929
+ return this.mergeAt0(e, U, q);
1930
+ }
1931
+ mergeAt0(e, U, q) {
1932
+ this.printInPlaceOperands(e, U, q);
1933
+ const shape = this.model.shape(e).k;
1934
+ if (shape === "never" || shape === "mixed") return this.never();
1935
+ if (shape === "scalar") return this.defNode(void 0, e);
1936
+ const def = this.model.defOfExpr(U, q, e);
1937
+ const root = def && def.kind !== "class" && def.kind !== "merge" && def.kind !== "umerge" ? this.rootDefOf(def) : void 0;
1938
+ if (def?.kind === "merge" || def?.kind === "umerge" || def?.kind === "class" || root) {
1939
+ const cls = root ? this.nameOf(root) : def.kind === "class" ? this.unitName(def.unit) : this.hiddenName(def);
1940
+ const one = root ?? this.oneDecl(def);
1941
+ const id = one ? `.id(${str(one.name)})` : "";
1942
+ const bases = this.operandBases(e);
1943
+ const over = bases.length > 0 ? `.over([${bases.join(", ")}], true)` : "";
1944
+ return this.model.nullableExpr(e) ? `${this.nullUnion(`${this.$}().type(${cls})${id}${over}`)}${over}` : `${this.$}().type(${cls})${id}${over}`;
1945
+ }
1946
+ return this.defNode(def, e);
1947
+ }
1948
+ /** A node of type `null` (tagged as a written `null` is). */ nullNode() {
1949
+ return `${this.$}().designType("null").tags("null")`;
1950
+ }
1951
+ /** `$("union", Name?)` of `item` (a chain) and `null`: a merge every operand of which is nullable. */ nullUnion(item, name) {
1952
+ return `${this.$}("union"${name ? `, ${name}` : ""})\n .item(${this.indentText(item)}.$type)\n .item(${this.nullNode()}.$type)`;
1953
+ }
1954
+ /** The chain of a node whose def is `def` (`e`: what is written there, for scalars). */ defNode(def, e) {
1955
+ const $ = this.$;
1956
+ if (!def) {
1957
+ const merged = this.doc.mergeIntersection(e.node);
1958
+ return this.scalar(merged, true);
1959
+ }
1960
+ switch (def.kind) {
1961
+ case "merge":
1962
+ case "umerge": return `${$}().ref(${this.hiddenName(def)})`;
1963
+ case "class": return `${$}().ref(${this.unitName(def.unit)})`;
1964
+ default: return `${$}().designType("any")`;
1965
+ }
1966
+ }
1967
+ /** The in-place object / array operands of intersection `e` at (U, q), as module constants. */ printInPlaceOperands(e, U, q) {
1968
+ andExprs(e).forEach((x, i) => {
1969
+ if (x.k !== "obj" && x.k !== "arr" && x.k !== "uni") return;
1970
+ const steps = [...q, `&${i}`];
1971
+ const key = `${U.id}:${steps.join("/")}`;
1972
+ if (!this.inPlace.has(key)) {
1973
+ const name = inPlaceName(U, steps);
1974
+ this.getSynthTaken().add(name);
1975
+ this.inPlace.set(key, name);
1976
+ if (isExported(U)) this.aliasExports.push({
1977
+ line: `export { ${name} }`,
1978
+ name,
1979
+ local: name
1980
+ });
1981
+ this.statement(`const:${name}`, () => `${name} = ${this.expr(x, U, steps)}.$type`);
1982
+ this.needs.add(`const:${name}`);
1983
+ this.guard(name);
1984
+ this.inPlaceText.push(name);
1985
+ }
1986
+ });
1987
+ }
1988
+ /** A hidden merge class: its declaration and its builder statement. */ printHidden(name, def) {
1989
+ this.declaredClasses.push(name);
1990
+ this.statement(def.key, () => def.kind === "umerge" ? this.unionOfMerges(name, def) : this.isArrayDef(def) ? `${this.$}("array", ${name}).of(${this.indentText(this.slotNode((def.raw ?? def.slot)("[]"), def.key))})` : this.withFields(`${this.$}("object", ${name})${this.rootLayers(def.ops ?? [], true)}`, def, def.key));
1991
+ }
1992
+ /**
1993
+ * A distributed merged field's own union: branch `i` is the branch merge's
1994
+ * def, its metadata layered over what each contributor gives that branch, later first — a union
1995
+ * contributor's member there; another contributor's type as written (an annotated alias its
1996
+ * own node), the branch passing through it: not the contributor's node (its own
1997
+ * annotations and path overrides are the field's, which layers over it). A reference layer,
1998
+ * as the branch's `ref` was: `passedWhenReferred: false` keys do not pass.
1999
+ */ mergedUnion(def, contributors) {
2000
+ let out = `${this.$}("union")`;
2001
+ for (let i = 0; i < (def.size ?? 0); i++) {
2002
+ const b = def.branch(i);
2003
+ const d = b && this.rootDefOf(b);
2004
+ const item = b && (b.kind === "merge" || b.kind === "umerge") ? `${this.$}().type(${this.hiddenName(b)})` : d ? `${this.$}().type(${this.nameOf(d)}).id(${str(d.name)})` : b ? this.defNode(b, { k: "unknown" }) : this.scalarBranch(def, i);
2005
+ const bases = contributors.flatMap((c) => {
2006
+ const at = this.model.branchItem(def, i, c.def);
2007
+ if (!at || !c.owner) return this.writtenTypeNodes(c);
2008
+ const s = c.def && this.model.structItem(c.def, at);
2009
+ if (s) return this.operandBases(s);
2010
+ const cd = this.shelled(c.def);
2011
+ if (cd?.kind === "merge" || cd?.kind === "umerge") this.needs.add(cd.key);
2012
+ return [this.nodeRef({
2013
+ unit: c.owner.unit,
2014
+ path: [...c.owner.path, ...at.map((k) => `|${k}`)]
2015
+ })];
2016
+ });
2017
+ out += `\n .item(${this.indentText(`${item}.over([${bases.join(", ")}], true)`)}.$type)`;
2018
+ }
2019
+ return out;
2020
+ }
2021
+ /**
2022
+ * The nodes contributor `c`'s written type stands for (`p?: T`: T, an annotated alias its own
2023
+ * class; a chain ref: that field; a merge written there: its hidden class); an object written
2024
+ * in place has no metadata of its own: none.
2025
+ */ writtenTypeNodes(c) {
2026
+ return c.ends.flatMap((e0) => {
2027
+ let e = e0;
2028
+ while (e.k === "nul") e = e.of;
2029
+ if (e.k === "ref") return [this.refTarget(e.decl)];
2030
+ if (e.k === "chain") return [this.pathRef(e.decl, e.path)];
2031
+ const d = this.shelled(c.def);
2032
+ if (e.k === "and" && d?.kind === "merge") {
2033
+ this.needs.add(d.key);
2034
+ return [this.hiddenName(d)];
2035
+ }
2036
+ if (e.k === "and" && d?.kind === "class" && d.unit) return [this.unitName(d.unit)];
2037
+ return [];
2038
+ });
2039
+ }
2040
+ /** The one declaration a class def is, or a hidden merge's operands are (it gives the id). */ oneDecl(def) {
2041
+ return def?.kind === "class" && def.unit ? this.model.declById(def.unit) : def?.kind === "merge" ? this.mergeOfOne(def) : void 0;
2042
+ }
2043
+ /** The one declaration a hidden merge's operands are (shells looked through), if so. */ mergeOfOne(def) {
2044
+ const ds = (def.ops ?? []).map((op) => {
2045
+ const d = this.shelled(op);
2046
+ return d && this.rootDefOf(d);
2047
+ });
2048
+ return ds.length > 0 && ds[0] && ds.every((d) => d === ds[0]) ? ds[0] : void 0;
2049
+ }
2050
+ /** A def with its shells looked through (the def they shell). */ shelled(def) {
2051
+ return def && unshell(def);
2052
+ }
2053
+ /** `$("union", Name)` of a distributed merge's branches (each a merge's hidden class). */ unionOfMerges(name, def) {
2054
+ let out = `${this.$}("union", ${name})`;
2055
+ for (let i = 0; i < (def.size ?? 0); i++) {
2056
+ const b = def.branch(i);
2057
+ const d = b && this.rootDefOf(b);
2058
+ const item = b && (b.kind === "merge" || b.kind === "umerge") ? `${this.$}().ref(${this.hiddenName(b)})` : d ? `${this.$}().ref(${this.nameOf(d)})` : b ? this.defNode(b, { k: "unknown" }) : this.scalarBranch(def, i);
2059
+ out += `\n .item(${item}.$type)`;
2060
+ }
2061
+ return out;
2062
+ }
2063
+ /** The declaration whose root def `def` is (a class, a `type X = …` builder), if any. */ rootDefOf(def) {
2064
+ const d = def.unit && !def.unit.startsWith("m:") ? this.model.declById(def.unit) : void 0;
2065
+ return d && (this.model.declDef(d)?.key === def.key || def.key === `a:${d.id}`) ? d : void 0;
2066
+ }
2067
+ /** A def of an array (its only child is the element: an array merge, item-wise). */ isArrayDef(def) {
2068
+ const names = def.names?.() ?? [];
2069
+ return names.length === 1 && names[0] === "[]";
2070
+ }
2071
+ /** `.over([…])` of a merge root over its operands' classes (later first). */ rootLayers(ops, reference) {
2072
+ const bases = ops.map((o) => this.rootDefOf(o)).filter((d) => !!d).map((d) => this.nameOf(d)).reverse();
2073
+ return bases.length > 0 ? `.over([${bases.join(", ")}]${reference ? ", true" : ""})` : "";
2074
+ }
2075
+ /** The props of a merged def (`unit`: its owner): references, own merged nodes, own props. */ withFields(head, def, unit, own, U) {
2076
+ const members = [];
2077
+ for (const k of def.names?.() ?? []) {
2078
+ const s = (def.raw ?? def.slot)(k);
2079
+ if (!s) continue;
2080
+ const re = k === "*" ? "/./" : /^\/.*\/[a-z]*$/.test(k) ? k : void 0;
2081
+ members.push(`\n .${re ? `propPattern(${re}` : `prop(${str(k)}`}, ${this.indentText(this.slotNode(s, unit, own?.get(k), U))})`);
2082
+ }
2083
+ return this.chainOf(head, members);
2084
+ }
2085
+ /**
2086
+ * `head` and its chained `members` (`\n .prop(…)` / `.item(…)`): more than {@link MAX_CHAIN}
2087
+ * members are split into statements on the handle in a function called with `head` — a chain of
2088
+ * tens of thousands of calls is nested too deep for V8 to parse (as the legacy renderer's `chain`).
2089
+ */ chainOf(head, members) {
2090
+ if (members.length <= MAX_CHAIN) return head + members.join("");
2091
+ this.chainHandle ?? (this.chainHandle = this.allocAlias("$h", this.getSynthTaken()));
2092
+ const h = this.chainHandle;
2093
+ let out = `(${h} => {`;
2094
+ for (let i = 0; i < members.length; i += MAX_CHAIN) out += `\n ${h}${this.indentText(members.slice(i, i + MAX_CHAIN).join(""))}`;
2095
+ return `${out}\n return ${h}\n})(${head})`;
2096
+ }
2097
+ /** The node of slot `s` of a merged def owned by `unit` (with its `.$type`). */ slotNode(s, unit, prop, U) {
2098
+ if (!(!s.owner || s.owner.unit === unit && s.owner.path.length === 1)) return this.nodeRef(s.owner);
2099
+ if (prop && U) {
2100
+ const e = this.model.exprOf(this.doc, prop.def);
2101
+ return `${this.propNode(prop, e, s.optional, U, [prop.id])}.$type`;
2102
+ }
2103
+ if (s.owner && !s.def && this.scalarReadsLater(s)) {
2104
+ const { unit: u, path: q } = s.owner;
2105
+ const D = this.model.declById(u);
2106
+ this.fillOnce(fillId(u, q), D?.id, () => {
2107
+ if (!D) this.needs.add(u);
2108
+ const at = D ? this.pathRef(D, q) : this.read(0, this.hidden.get(u).name, q);
2109
+ return inPlace(this.$, this.mergedSlotNode(s), at);
2110
+ });
2111
+ return `${this.$}().$type`;
2112
+ }
2113
+ return `${this.mergedSlotNode(s)}.$type`;
2114
+ }
2115
+ /**
2116
+ * Whether merged scalar field `s` (a declaration's or a hidden merge class's own) reads, for its
2117
+ * type, a chain ref or a class another def replaces, into this module or its import cycle (as
2118
+ * `expr` prints them, see {@link fillsLater}): filled by a statement of its own (see
2119
+ * {@link slotNode}).
2120
+ */ scalarReadsLater(s) {
2121
+ const reads = (n) => {
2122
+ if (isRef(n)) {
2123
+ const e = this.model.exprOf(this.doc, n);
2124
+ const near = (x) => {
2125
+ const t = x.k === "ref" && this.isBare(x.decl) ? this.model.bareTarget(x.decl) : void 0;
2126
+ return x.k === "chain" ? this.nearDoc(x.decl.doc) : x.k === "uni" ? x.items.some(near) : x.k === "ref" && this.isReplacing(t ?? x.decl) && this.nearDoc((t ?? x.decl).doc);
2127
+ };
2128
+ return near(e);
2129
+ }
2130
+ return isGroup(n) || isTuple(n) ? n.unwrap().some(reads) : isArray(n) ? reads(n.getDefinition()) : false;
2131
+ };
2132
+ return reads(this.scalarMergeOf(s).merged);
2133
+ }
2134
+ /**
2135
+ * The type node of merged scalar field `s`: the core algebra's merge of the written types
2136
+ * (`scalarMerge`: of the contributors' with their `?` — an optional contributor passes `null`
2137
+ * when a required one may be `null`, as core merges props).
2138
+ */ scalarMergeOf(s) {
2139
+ let hit = this.scalarMerges.get(s);
2140
+ if (!hit) {
2141
+ hit = this.scalarMergeOf0(s);
2142
+ this.scalarMerges.set(s, hit);
2143
+ }
2144
+ return hit;
2145
+ }
2146
+ scalarMergeOf0(s) {
2147
+ const cs = s.contributors ?? [];
2148
+ if (cs.length > 1 && cs.every((c) => c.ends.length === 1 && c.ends[0].node)) return {
2149
+ merged: this.doc.mergeFieldTypes(cs.map((c) => ({
2150
+ def: c.ends[0].node,
2151
+ optional: c.optional
2152
+ }))),
2153
+ scalarMerge: true
2154
+ };
2155
+ const nodes = s.ends.map((x) => x.node).filter((n) => !!n);
2156
+ return {
2157
+ merged: nodes.length > 1 ? this.doc.mergeIntersection(new SemanticGroup(nodes, "&")) : nodes[0],
2158
+ scalarMerge: false
2159
+ };
2160
+ }
2161
+ /** {@link slotNode}'s merged field: a node of its own over its contributors (no `.$type`). */ mergedSlotNode(s) {
2162
+ const contributors = [...s.contributors ?? []].reverse();
2163
+ const bases = contributors.map((c) => this.nodeRef(c.owner));
2164
+ const end = s.ends[0] ?? { k: "unknown" };
2165
+ let type;
2166
+ let scalarMerge = false;
2167
+ let typeBase = [];
2168
+ if (this.model.slotShape(s).k === "never") type = this.never();
2169
+ else if (this.model.nullSlot(s)) type = this.nullNode();
2170
+ else if (s.def?.kind === "umerge") type = this.mergedUnion(s.def, contributors);
2171
+ else if (s.def?.kind === "merge") {
2172
+ const one = this.mergeOfOne(s.def);
2173
+ type = `${this.$}().type(${this.hiddenName(s.def)})${one ? `.id(${str(one.name)})` : ""}`;
2174
+ } else if (s.def && this.rootDefOf(s.def)) {
2175
+ const d = this.rootDefOf(s.def);
2176
+ type = `${this.$}().type(${this.nameOf(d)}).id(${str(d.name)})`;
2177
+ } else if (s.def) {
2178
+ const same = s.contributors?.find((c) => c.def?.key === s.def.key && c.owner);
2179
+ const shelled = this.shelled(s.def);
2180
+ const one = shelled && this.rootDefOf(shelled);
2181
+ type = same ? `${this.$}().type(${this.typed(this.nodeRef(same.owner, true))})${one ? `.id(${str(one.name)})` : ""}` : this.defNode(s.def, end);
2182
+ } else {
2183
+ const m = this.scalarMergeOf(s);
2184
+ type = this.scalar(m.merged, false);
2185
+ typeBase = this.scalarTypeBase(m.merged, s.ends);
2186
+ scalarMerge = m.scalarMerge;
2187
+ }
2188
+ if (!scalarMerge && this.model.nullableSlot(s) && !this.model.nullSlot(s) && type !== this.never()) {
2189
+ const items = [...contributors.map((c) => this.nodeRef(c.owner, true)), ...typeBase];
2190
+ type = this.nullUnion(`${type}.over([${items.join(", ")}])`);
2191
+ typeBase = [];
2192
+ }
2193
+ return `${type}.over([${[...bases, ...typeBase].join(", ")}])${s.optional ? ".optional()" : ""}`;
2194
+ }
2195
+ /**
2196
+ * A merged field's scalar type `merged` picked from a union member (no
2197
+ * contributor written as it: `string & (string.email | number)` is `string.email`) is a base of
2198
+ * the field, last — a node of it, as the union's branch item is, so its own annotations (an
2199
+ * annotated alias's, a primitive extension's intrinsic checks) are read as the type's. A
2200
+ * contributor written as that type carries them already, and a primitive / literal without
2201
+ * annotations has none: no base.
2202
+ */ scalarTypeBase(merged, ends) {
2203
+ const x = merged && this.model.exprOf(this.doc, merged);
2204
+ const k = x && scalarKey(x);
2205
+ if (!k || ends.some((e) => scalarKey(e) === k) || x.k === "scalar" && !x.node?.annotations?.length) return [];
2206
+ return [`${this.scalar(merged, true).trimEnd()}.$type`];
2207
+ }
2208
+ /** The builder statement of declaration `d` of this module. */ declStatement(d) {
2209
+ this.statement(d.id, () => this.declText(d));
2210
+ const stages = this.shellStatements(d);
2211
+ if (d.kind === "as") this.statement(`as:${d.id}`, () => {
2212
+ this.needs.add(d.id);
2213
+ for (const id of stages) this.needs.add(id);
2214
+ return this.asEntries(d);
2215
+ });
2216
+ }
2217
+ declText(d) {
2218
+ const name = this.nameOf(d);
2219
+ let text;
2220
+ if (d.kind === "as") {
2221
+ const node = d.node;
2222
+ const target = this.model.asTarget(d);
2223
+ this.replacing.add(d.id);
2224
+ if (target.doc === this.doc && this.defShared(target)) this.needs.add(target.id);
2225
+ text = `${this.util("$alias")}(${name}, ${this.refTarget(target)})${this.annotateCalls(name, node)}`;
2226
+ } else if (d.kind === "interface" && this.model.extendsOf(d).length === 0) {
2227
+ const props = this.model.ownProps(d);
2228
+ text = this.chainOf(`${this.$}("object", ${name})${this.annotations(d.node, d.node.annotations)}`, props.map((p) => `\n .${this.propCall(p.node, p.name)}${this.indentText(this.propNode(p.node, p.type, p.optional, d, [p.name]))}.$type)`));
2229
+ } else if (d.kind === "interface") {
2230
+ const def = this.model.declDef(d);
2231
+ const own = new Map(this.model.ownProps(d).map((p) => [p.name, p.node]));
2232
+ text = this.withFields(`${this.$}("object", ${name})${this.annotations(d.node, d.node.annotations)}`, def, d.id, own, d);
2233
+ } else {
2234
+ const e = this.model.declExpr(d);
2235
+ if (e.k === "ref") {
2236
+ this.replacing.add(d.id);
2237
+ this.needStructure(e.decl);
2238
+ text = `${this.util("$alias")}(${name}, ${this.refTarget(e.decl)}, [])${this.annotateCalls(name, d.node)}`;
2239
+ } else if (e.k === "chain") {
2240
+ this.replacing.add(d.id);
2241
+ this.needStructure(e.decl);
2242
+ text = `${this.util("$alias")}(${name}, ${this.chainArgs(e.decl, e.path)})${this.annotateCalls(name, d.node)}`;
2243
+ } else if (e.k === "and") {
2244
+ this.printInPlaceOperands(e, d, []);
2245
+ const shape = this.model.shapeAt(d, [])?.k;
2246
+ const def = shape === "scalar" ? void 0 : this.model.declDef(d);
2247
+ if (shape === "never") text = `${this.$}("", ${name}).designType("never").tags("never")${this.namedRootLayers(d)}${this.annotations(d.node, d.node.annotations)}`;
2248
+ else if (def?.kind === "class" && def.unit === d.id && def.uni) {
2249
+ text = `${this.$}("union", ${name})${this.namedRootLayers(d)}${this.annotations(d.node, d.node.annotations)}`;
2250
+ for (let i = 0; i < (def.size ?? 0); i++) {
2251
+ const b = this.shelled(def.branch(i));
2252
+ const bases = this.operandBases(this.branchExpr(def, i, e));
2253
+ const item = b && (b.kind === "merge" || b.kind === "umerge") && bases.length > 0 ? `${this.$}().type(${this.hiddenName(b)}).over([${bases.join(", ")}], true)` : b ? this.defNode(b, e) : this.scalarBranch(def, i);
2254
+ text += `\n .item(${this.indentText(item)}.$type)`;
2255
+ }
2256
+ const scalarNull = (i) => !def.branch?.(i) && (def.bsrc?.(i) ?? []).every(isNull);
2257
+ if (this.model.nullableExpr(e) && !Array.from({ length: def.size ?? 0 }, (_, i) => i).some(scalarNull)) text += `\n .item(${this.nullNode()}.$type)`;
2258
+ } else if (def?.kind === "class" && def.unit === d.id && this.isArrayDef(def)) text = `${this.$}("array", ${name})${this.namedRootLayers(d)}${this.annotations(d.node, d.node.annotations)}.of(${this.indentText(this.slotNode((def.raw ?? def.slot)("[]"), d.id))})`;
2259
+ else if (def?.kind === "class" && def.unit === d.id) text = this.model.nullableExpr(e) ? `${this.nullUnion(this.withFields(`${this.$}("object")${this.namedRootLayers(d)}`, def, d.id), name)}${this.namedRootLayers(d)}${this.annotations(d.node, d.node.annotations)}` : this.withFields(`${this.$}("object", ${name})${this.namedRootLayers(d)}${this.annotations(d.node, d.node.annotations)}`, def, d.id);
2260
+ else {
2261
+ text = this.namedNode(name, this.defNode(def, e), d, e);
2262
+ if (!def) text += this.intrinsicMarks(this.doc.mergeIntersection(e.node).annotations);
2263
+ }
2264
+ } else text = this.namedNode(name, this.expr(e, d, []), d, e);
2265
+ }
2266
+ return text;
2267
+ }
2268
+ /**
2269
+ * `.over([…], true)` of named merge `d`'s root: over its written operands' classes, later first
2270
+ * (an annotated alias operand is its own class, a bare one its target).
2271
+ */ namedRootLayers(d) {
2272
+ const bases = this.operandBases(this.model.declExpr(d));
2273
+ return bases.length > 0 ? `.over([${bases.join(", ")}], true)` : "";
2274
+ }
2275
+ /**
2276
+ * Branch `i` of a distributed merge `def` (written `e`): its members' written types (one member
2277
+ * of each union operand, the product's i-th surviving branch).
2278
+ */ branchExpr(def, i, e) {
2279
+ return {
2280
+ k: "and",
2281
+ node: e.node,
2282
+ items: def.bsrc?.(i) ?? []
2283
+ };
2284
+ }
2285
+ /** A distributed merge's branch of scalars only: the core algebra's merge of its members. */ scalarBranch(def, i) {
2286
+ const nodes = (def.bsrc?.(i) ?? []).map((x) => x.node).filter((n) => !!n);
2287
+ if (nodes.length === 0) return this.never();
2288
+ const merged = nodes.length > 1 ? this.doc.mergeIntersection(new SemanticGroup(nodes, "&")) : nodes[0];
2289
+ return this.scalar(merged, true);
2290
+ }
2291
+ /**
2292
+ * The nodes a merge's root reads through, priority order (each operand's node, later
2293
+ * first): a class; a chain ref's field node; `X | null` written there:
2294
+ * X's class; an alias of a nullable type (`type XN = X | null`): XN's own over X's class.
2295
+ */ operandBases(e) {
2296
+ const out = [];
2297
+ const nodeOf = (x) => {
2298
+ if (x.k === "chain") {
2299
+ this.needFills(x.decl, x.path);
2300
+ return this.pathRef(x.decl, x.path);
2301
+ }
2302
+ return x.k === "ref" ? this.refTarget(x.decl) : void 0;
2303
+ };
2304
+ const visit = (x) => {
2305
+ if (x.k === "chain" && x.rep) return;
2306
+ const one = x.k === "uni" || x.k === "ref" ? this.model.oneType(x) : void 0;
2307
+ if (x.k === "uni" && x.struct) {
2308
+ if (one) visit(one);
2309
+ } else if (x.k === "and") x.items.forEach(visit);
2310
+ else if (x.k === "nul") {
2311
+ const n = nodeOf(x.of);
2312
+ if (n) out.push(n);
2313
+ } else if (x.k === "ref") {
2314
+ const t = x.decl.kind === "type" ? this.model.declExpr(x.decl) : void 0;
2315
+ const inner = t?.k === "nul" ? nodeOf(t.of) : void 0;
2316
+ if (inner) out.push(inner);
2317
+ if (one) visit(one);
2318
+ out.push(this.refTarget(x.decl));
2319
+ } else {
2320
+ const n = nodeOf(x);
2321
+ if (n) out.push(n);
2322
+ }
2323
+ };
2324
+ visit(e);
2325
+ return [...new Set(out.reverse())];
2326
+ }
2327
+ /** A `type T = …` class built by an expression's chain: re-rooted on the class. */ namedNode(name, chain, d, e) {
2328
+ const $ = this.$;
2329
+ const reroot = (c) => inPlace($, c, name);
2330
+ const split = this.chainHandle && chain.startsWith(`(${this.chainHandle} => {`);
2331
+ const at = split ? chain.lastIndexOf("})(") + 3 : 0;
2332
+ return `${split ? `${chain.slice(0, at)}${reroot(chain.slice(at, -1))})` : reroot(chain)}${this.ownAnnotations(d.node, e)}`;
2333
+ }
2334
+ /** `$blk(null, 0, X, …)`: an `as` copy's entries (below every block). */ asEntries(d) {
2335
+ const block = this.model.blocks.find((b) => b.node === d.node);
2336
+ const data = block ? this.entriesData(block, this.model.asTarget(d)) : "";
2337
+ return data ? `${this.util("$blk")}(null, 0, ${this.nameOf(d)}, ${data})` : "";
2338
+ }
2339
+ /**
2340
+ * The entries of block `b` as `$blk` data (`runtime/blocks.ts`): `[annotations, ...paths]`, a
2341
+ * type-level entry (the block's own annotations) first with an empty path. `reads`: the
2342
+ * declaration whose structure the paths walk (an `as` copy's target; else the block's target).
2343
+ * The statement needs what the paths go through built (`$f` guards, needs).
2344
+ */ entriesData(b, reads) {
2345
+ const entries = [];
2346
+ const annotationsOf = (node) => (node.annotations ?? []).map((an) => {
2347
+ const { value, multiple } = this.computeAnnotationValue(node, an);
2348
+ return `[${str(an.name)}, ${value}${multiple ? ", 1" : ""}]`;
2349
+ });
2350
+ if (b.rank && b.node.annotations?.length) entries.push(`[[${annotationsOf(b.node).join(", ")}], []]`);
2351
+ for (const en of b.entries) {
2352
+ if (en.error || en.paths.length === 0) continue;
2353
+ const copy = reads !== b.target;
2354
+ const paths = en.paths.map((p, i) => `[${stepsText(this.stepsData(reads, p, en.kinds[i], false, copy))}]`);
2355
+ entries.push(`[[${annotationsOf(en.ref).join(", ")}], ${paths.join(", ")}]`);
2356
+ }
2357
+ return entries.length > 0 ? `[\n ${entries.join(",\n ")},\n]` : "";
2358
+ }
2359
+ /**
2360
+ * The runtime `[step, kind]`s of model path `p` of `reads` (an `as` copy's: its target's
2361
+ * structure), and its needs: the classes it walks are built first (a shell def clones a built
2362
+ * def).
2363
+ */ stepsData(reads, p, kinds, building = false, copy = false, items = false) {
2364
+ const steps = this.runtimeSteps(reads, p, kinds, {
2365
+ copy,
2366
+ items
2367
+ });
2368
+ const below = items ? steps[this.runtimeSteps(reads, p, kinds, {
2369
+ copy,
2370
+ pure: true
2371
+ }).length] : void 0;
2372
+ if (steps.length > 0) {
2373
+ if (!building) this.needStructure(reads);
2374
+ this.needFills(reads, p, building, items ? steps.map(([s]) => s) : void 0);
2375
+ for (let i = 1; i <= p.length; i++) {
2376
+ let slot = this.model.slotAt(reads, p.slice(0, i));
2377
+ while (slot?.owner?.unit === reads.id && slot.shell) slot = slot.shell;
2378
+ if (slot?.owner && slot.owner.unit !== reads.id) if (building) {
2379
+ const ref = this.nodeRef(slot.owner);
2380
+ if ((i < p.length ? kinds[i] : below?.[1]) === 2) this.typed(ref);
2381
+ } else this.needUnit(slot.owner.unit);
2382
+ const at = this.model.defAt(reads, p.slice(0, i - 1));
2383
+ const def = at && pastViews(at);
2384
+ if (def?.kind === "merge" || def?.kind === "umerge") this.needs.add(def.key);
2385
+ else if (def?.unit) this.needUnit(def.unit);
2386
+ if (building && kinds[i - 1] === 2 && def?.unit && def.unit !== reads.id) this.defRead(def);
2387
+ }
2388
+ if (building) steps.forEach(([, k], j) => {
2389
+ if (k === 2 && j > 0) {
2390
+ const at0 = steps.slice(0, j).map(([s]) => s);
2391
+ const rd = this.reads(reads, at0);
2392
+ this.passAliases(rd.needs);
2393
+ for (const r of rd.out.slice(1)) {
2394
+ const n = this.boundName(r.decl);
2395
+ if (n) this.read(2, n, r.steps, false);
2396
+ }
2397
+ }
2398
+ const read = k === 2 && j > 0 ? this.ownedRead(reads, steps.slice(0, j)) : void 0;
2399
+ if (read) this.read(2, this.nameOf(read[0]), read[1]);
2400
+ });
2401
+ if (!building) {
2402
+ const name = this.nameOf(reads);
2403
+ this.read(0, name, steps.map(([s]) => s));
2404
+ steps.forEach(([, k], j) => {
2405
+ if (k !== 2) return;
2406
+ this.read(2, name, steps.slice(0, j).map(([s]) => s));
2407
+ const read = j > 0 ? this.ownedRead(reads, steps.slice(0, j)) : void 0;
2408
+ if (read) this.read(2, this.nameOf(read[0]), read[1]);
2409
+ });
2410
+ }
2411
+ }
2412
+ return steps;
2413
+ }
2414
+ /**
2415
+ * `$sh(T, [path])` statements: every shell the build's blocks need in declaration `d` (a path
2416
+ * override is the referrer's own), one statement per path (each runs once what it shells is
2417
+ * built: a merge over one of T's shells and another shell of T through that merge do not wait
2418
+ * for each other). Returns the stages' statement ids.
2419
+ */ shellStatements(d) {
2420
+ const seen = /* @__PURE__ */ new Set();
2421
+ const ids = [];
2422
+ for (const b of this.model.blocks) {
2423
+ if (b.target !== d) continue;
2424
+ for (const en of b.entries) {
2425
+ if (en.error) continue;
2426
+ en.paths.forEach((path, i) => {
2427
+ const stage = (p, kinds, items) => {
2428
+ const key = JSON.stringify([
2429
+ p,
2430
+ kinds,
2431
+ items
2432
+ ]);
2433
+ if (seen.has(key)) return;
2434
+ seen.add(key);
2435
+ const id = `sh:${d.id}:${seen.size}`;
2436
+ ids.push(id);
2437
+ this.statement(id, () => {
2438
+ this.needStructure(d);
2439
+ const path = this.stepsData(d, p, kinds, true, false, items);
2440
+ const data = `[${stepsText(path)}]`;
2441
+ const name = this.nameOf(d);
2442
+ this.shellPaths.set(id, {
2443
+ decl: d.id,
2444
+ name,
2445
+ data,
2446
+ path
2447
+ });
2448
+ return `${this.util("$sh")}(${name}, [${data}])`;
2449
+ });
2450
+ };
2451
+ en.kinds[i].forEach((kind, j) => {
2452
+ if (kind === 0) return;
2453
+ for (let m = 0; m <= j; m++) {
2454
+ const p = path.slice(0, m);
2455
+ const kinds = en.kinds[i].slice(0, m);
2456
+ const all = this.runtimeSteps(d, p, kinds, {
2457
+ items: true,
2458
+ pure: true
2459
+ });
2460
+ const own = this.runtimeSteps(d, p, kinds, { pure: true }).length;
2461
+ if (all.slice(own).some(([, k]) => k !== 0)) stage(p, kinds, true);
2462
+ }
2463
+ stage(path.slice(0, j + 1), en.kinds[i].slice(0, j + 1), false);
2464
+ });
2465
+ });
2466
+ }
2467
+ }
2468
+ return ids;
2469
+ }
2470
+ /** A cloning read (`$fc`, a guard) of the node holding own def `def` of a declaration. */ defRead(def) {
2471
+ const owner = this.model.declById(def.unit);
2472
+ const at = defPosition(def);
2473
+ if (!owner || at === void 0 || at.includes("&")) return;
2474
+ const steps = at === "" ? [] : at.split(".");
2475
+ this.needStructure(owner);
2476
+ this.read(2, this.nameOf(owner), this.runtimePath(owner, [], steps));
2477
+ }
2478
+ /**
2479
+ * The `sh:<id>` statements statement `st` needs: those whose shells change a node its `$f`
2480
+ * guards read (a node replaced on the way, or a def cloned below it — `changedBy` at runtime).
2481
+ */ shellNeeds(st, cycle) {
2482
+ if (this.withShells().size === 0) return [];
2483
+ const out = /* @__PURE__ */ new Set();
2484
+ const reached = [];
2485
+ const modes = [
2486
+ this.util("$f"),
2487
+ this.util("$ft"),
2488
+ this.util("$fc")
2489
+ ];
2490
+ for (const { read, printed } of st.guards.values()) {
2491
+ const X = read && !/[,()]/.test(read.name) ? this.declNamed(read.name) : void 0;
2492
+ if (!read || !X) continue;
2493
+ const typed = read.mode;
2494
+ this.reached(X, read.steps).forEach((r, k) => {
2495
+ if (!this.withShells().has(r.decl)) return;
2496
+ const name = k === 0 ? read.name : this.boundName(r.decl);
2497
+ const hits = name ? this.stagesChanging(name, r.steps, typed) : [];
2498
+ for (const id of hits) if (id !== st.builds) out.add(id);
2499
+ const guardName = name ?? (this.ofCycle(r.decl) ? this.nameOf(r.decl) : void 0);
2500
+ if (cycle && k > 0 && printed && guardName && !hits.includes(st.builds)) reached.push({
2501
+ mode: typed,
2502
+ name: guardName,
2503
+ steps: r.steps
2504
+ });
2505
+ });
2506
+ }
2507
+ for (const r of reached) {
2508
+ const text = `${modes[r.mode]}(${[r.name, ...r.steps.map(str)].join(", ")})`;
2509
+ if (!st.guards.has(text)) st.guards.set(text, {
2510
+ text,
2511
+ printed: true,
2512
+ read: r
2513
+ });
2514
+ }
2515
+ return [...out];
2516
+ }
2517
+ /** Whether declaration `d` is of another module of this one's import cycle. */ ofCycle(d) {
2518
+ return d.doc !== this.doc && this.importers().has(d.doc);
2519
+ }
2520
+ /** The modules importing this one, directly or not. */ importers() {
2521
+ this.importersMemo ?? (this.importersMemo = this.doc.transitive("dependants"));
2522
+ return this.importersMemo;
2523
+ }
2524
+ /**
2525
+ * The declarations with shells of their own (blocks, `as` entries with paths): their module
2526
+ * registers them as pending (`$ps`) until its shell stages run.
2527
+ */ withShells() {
2528
+ this.withShellsMemo ?? (this.withShellsMemo = new Set(this.model.blocks.filter((b) => b.entries.some((e) => !e.error && e.paths.some((p) => p.length > 0))).map((b) => b.target)));
2529
+ return this.withShellsMemo;
2530
+ }
2531
+ /**
2532
+ * The shell stages of class `name` that change a read of `steps` (0 plain, 1 typed, 2 cloned:
2533
+ * the runtime's `changedBy`): a stage at a prefix of the read — a node replaced on the way —,
2534
+ * or, for a typed / cloning read, one step below it that clones its def; in build order.
2535
+ */ stagesChanging(name, steps, typed) {
2536
+ const idx = this.shellPathsOf(name);
2537
+ const hits = [];
2538
+ let at = "";
2539
+ for (let n = 0; n < steps.length; n++) {
2540
+ at = n === 0 ? steps[0] : `${at}\0${steps[n]}`;
2541
+ hits.push(...idx.at.get(at) ?? []);
2542
+ }
2543
+ for (const [seq, id, kind] of typed > 0 ? idx.below.get(pathKey(steps)) ?? [] : []) if (typed === 2 || kind === 2) hits.push([seq, id]);
2544
+ return hits.sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2545
+ }
2546
+ /**
2547
+ * The node at runtime path `steps` of `reads` as a read of the class it belongs to, when that is
2548
+ * another class (a reference, or the node `reads`' own shell is over): `[class, its path]`.
2549
+ */ ownedRead(reads, steps) {
2550
+ const model = steps.filter(([s]) => s[0] !== "|").map(([s]) => s);
2551
+ for (let i = model.length; i >= 1; i--) {
2552
+ let slot = this.model.slotAt(reads, model.slice(0, i));
2553
+ const def = slot?.def;
2554
+ const C = def?.kind === "class" && def.unit !== reads.id ? this.model.declById(def.unit) : void 0;
2555
+ if (C && steps[steps.length - 1][0][0] !== "|") {
2556
+ let r = 0;
2557
+ for (let seen = 0; r < steps.length && seen < i; r++) if (steps[r][0][0] !== "|") seen++;
2558
+ return [C, steps.slice(r).map(([s]) => s)];
2559
+ }
2560
+ while (slot?.owner?.unit === reads.id && slot.shell) slot = slot.shell;
2561
+ const o = slot?.owner;
2562
+ if (!o || o.unit === reads.id || o.unit.startsWith("m:") || o.path.some((x) => x[0] === "&")) continue;
2563
+ const Y = this.model.declById(o.unit);
2564
+ if (!Y) return;
2565
+ let r = 0;
2566
+ for (let seen = 0; r < steps.length && seen < i; r++) if (steps[r][0][0] !== "|") seen++;
2567
+ return [Y, [...this.runtimePath(Y, [], o.path), ...steps.slice(r).map(([s]) => s)]];
2568
+ }
2569
+ }
2570
+ /**
2571
+ * The shell stages of class `name` (see {@link shellPaths}) by their path (`at`) and by the
2572
+ * path above their last step (`below`, with that step's kind), each with its build order;
2573
+ * indexed once they are all known.
2574
+ */ shellPathsOf(name) {
2575
+ if (!this.shellIndex) {
2576
+ this.shellIndex = /* @__PURE__ */ new Map();
2577
+ let seq = 0;
2578
+ for (const [id, { name: n, path: p }] of this.shellPaths) {
2579
+ const x = this.shellIndex.get(n) ?? {
2580
+ at: /* @__PURE__ */ new Map(),
2581
+ below: /* @__PURE__ */ new Map()
2582
+ };
2583
+ this.shellIndex.set(n, x);
2584
+ const names = p.map(([s]) => s);
2585
+ for (const j of stageEnds(p)) {
2586
+ const kind = p[j][1];
2587
+ const at = pathKey(names.slice(0, j + 1));
2588
+ if (kind !== 0 && (j === p.length - 1 || !x.at.has(at))) {
2589
+ getOrSet(x.at, at, () => []).push([seq, id]);
2590
+ const up = pathKey(names.slice(0, j));
2591
+ getOrSet(x.below, up, () => []).push([
2592
+ seq,
2593
+ id,
2594
+ kind
2595
+ ]);
2596
+ }
2597
+ }
2598
+ seq++;
2599
+ }
2600
+ }
2601
+ return this.shellIndex.get(name) ?? {
2602
+ at: /* @__PURE__ */ new Map(),
2603
+ below: /* @__PURE__ */ new Map()
2604
+ };
2605
+ }
2606
+ /**
2607
+ * The nodes a read of runtime `steps` below declaration `X0`'s class passes, by the class each
2608
+ * is reached in: X0 itself first, then every class the read continues in — below a node whose
2609
+ * def is another declaration's own (a reference: `I1.next.work` with `next?: I1` reads
2610
+ * `I1.work`; a union branch: `U.|0.work` with `U = A | B` reads `A.work`, nested unions and
2611
+ * aliases alike), or at a node that is another class's (a reference slot, what X's own shell is
2612
+ * over). A shell stage of any of them changes what the read reaches, and a placeholder filled
2613
+ * there is read (see {@link shellNeeds}, {@link needFills}). Each node once, the first time.
2614
+ */ reached(X0, steps) {
2615
+ return this.reads(X0, steps).out;
2616
+ }
2617
+ /** {@link reached} with the alias unions the read passes (built before a statement making it). */ reads(X0, steps) {
2618
+ const mk = `${X0.id}\0${pathKey(steps)}`;
2619
+ let hit = this.reachedMemo.get(mk);
2620
+ if (!hit) {
2621
+ hit = this.walkReads(X0, steps);
2622
+ this.reachedMemo.set(mk, hit);
2623
+ }
2624
+ return hit;
2625
+ }
2626
+ walkReads(X0, steps) {
2627
+ const visiting = /* @__PURE__ */ new Map();
2628
+ let low = Infinity;
2629
+ const visit = (X1, st) => {
2630
+ let X = X1;
2631
+ while (X?.kind === "type" && this.isBare(X)) X = this.model.aliasStep(X);
2632
+ if (!X) return;
2633
+ const key = `${X.id}\0${pathKey(st)}`;
2634
+ const depth = visiting.get(key);
2635
+ if (depth !== void 0) {
2636
+ low = Math.min(low, depth);
2637
+ return;
2638
+ }
2639
+ let hit = this.visitsMemo.get(key);
2640
+ if (!hit) {
2641
+ const low0 = low;
2642
+ low = Infinity;
2643
+ const level = visiting.size;
2644
+ visiting.set(key, level);
2645
+ const r = {
2646
+ out: [],
2647
+ needs: /* @__PURE__ */ new Set()
2648
+ };
2649
+ const seen = /* @__PURE__ */ new Set();
2650
+ const add = (sub, fy) => {
2651
+ for (const [k, x] of (sub?.out ?? []).entries()) if (!seen.has(x.key)) {
2652
+ seen.add(x.key);
2653
+ r.out.push(k === 0 && x.from !== fy ? {
2654
+ ...x,
2655
+ from: fy
2656
+ } : x);
2657
+ }
2658
+ for (const a of sub?.needs ?? []) r.needs.add(a);
2659
+ };
2660
+ const at = {
2661
+ decl: X,
2662
+ steps: st,
2663
+ key,
2664
+ m: [],
2665
+ marks: [],
2666
+ from: 0
2667
+ };
2668
+ seen.add(key);
2669
+ r.out.push(at);
2670
+ this.visit0(at, r.needs, (Y, sy, fy) => add(visit(Y, sy), fy));
2671
+ visiting.delete(key);
2672
+ if (low >= level) this.visitsMemo.set(key, r);
2673
+ low = Math.min(low0, low);
2674
+ hit = r;
2675
+ }
2676
+ return hit;
2677
+ };
2678
+ return visit(X0, steps) ?? {
2679
+ out: [],
2680
+ needs: /* @__PURE__ */ new Set()
2681
+ };
2682
+ }
2683
+ /**
2684
+ * {@link walkReads}' node `at` (at runtime steps `at.steps` of class `at.decl`): its model path
2685
+ * and steps' marks, the alias unions passed (`needs`), and every node the read continues in
2686
+ * (`visit`). What a node continues in depends on the class and model path only
2687
+ * ({@link nodeRec}); the runtime steps pick the items it passes.
2688
+ */ visit0(at, needs, visit) {
2689
+ const { decl: X, steps: st, m } = at;
2690
+ let i = 0;
2691
+ const items = (xs) => {
2692
+ for (const x of xs) {
2693
+ if (st[i] !== `|${x}`) return false;
2694
+ at.marks.push(void 0);
2695
+ i++;
2696
+ }
2697
+ return true;
2698
+ };
2699
+ const cross = (c) => {
2700
+ if (!c) return;
2701
+ let j = i;
2702
+ for (const x of c.xs) {
2703
+ if (st[j] !== `|${x}`) return;
2704
+ j++;
2705
+ }
2706
+ if (j < st.length) {
2707
+ this.passAliases(c.via ?? [], needs);
2708
+ visit(c.decl, [...c.zs ?? [], ...st.slice(j)], c.zs ? c.zs.length - 1 : 0);
2709
+ }
2710
+ };
2711
+ const into = (r, passed) => {
2712
+ if (r.owner && passed) visit(r.owner[0], [...r.owner[1], ...st.slice(i)], r.owner[1].length);
2713
+ };
2714
+ const root = this.model.structureRoot(X);
2715
+ if (root?.kind === "type" && root !== X) visit(root, st, 0);
2716
+ let key = X.id;
2717
+ let r = this.nodeRec(X, m, key);
2718
+ this.passAliases(r.aliases, needs);
2719
+ cross(r.cross);
2720
+ into(r, items(r.items));
2721
+ while (i < st.length) {
2722
+ const s = st[i++];
2723
+ m.push(s);
2724
+ at.marks.push(m.length);
2725
+ key = `${key}\0${s}`;
2726
+ r = this.nodeRec(X, m, key);
2727
+ this.passAliases(r.aliases, needs);
2728
+ if (r.other) visit(r.other.Z, [...r.other.zs, ...st.slice(i)], r.other.zs.length - 1);
2729
+ cross(r.cross);
2730
+ into(r, items(r.items));
2731
+ }
2732
+ }
2733
+ /**
2734
+ * What {@link visit0} reads at model path `m` of class `X` (`key`: X's id and m, joined): a node
2735
+ * of another class (a reference slot, what X's own shell is over), where the items its written
2736
+ * type passes lead (`cross`: the items and the node there), the items, the declaration whose
2737
+ * own def it is (`owner`), and the alias unions passed on the way.
2738
+ */ nodeRec(X, m, key) {
2739
+ let rec = this.nodeRecs.get(key);
2740
+ if (rec) return rec;
2741
+ const aliases = /* @__PURE__ */ new Set();
2742
+ rec = {
2743
+ items: [],
2744
+ aliases
2745
+ };
2746
+ const crossOf = (e0) => {
2747
+ let e = e0;
2748
+ const xs = [];
2749
+ const bare = /* @__PURE__ */ new Set();
2750
+ while (e?.k === "nul") {
2751
+ const x = this.nonNullItem(e, this.doc) ?? 0;
2752
+ xs.push(x);
2753
+ e = this.model.exprOf(this.doc, e.node.unwrap()[x]);
2754
+ for (let to = e.k === "ref" && this.isBare(e.decl) ? this.model.aliasStep(e.decl) : void 0; to && e.k === "ref" && !bare.has(e.decl); to = this.isBare(to) ? this.model.aliasStep(to) : void 0) {
2755
+ bare.add(e.decl);
2756
+ e = {
2757
+ k: "ref",
2758
+ decl: to,
2759
+ node: e.node
2760
+ };
2761
+ }
2762
+ }
2763
+ if (e?.k === "ref" && e.decl.kind === "type") return {
2764
+ xs,
2765
+ decl: e.decl
2766
+ };
2767
+ if (e?.k === "chain") {
2768
+ const via = /* @__PURE__ */ new Set();
2769
+ return {
2770
+ xs,
2771
+ decl: e.decl,
2772
+ zs: this.runtimePath(e.decl, [], e.path, false, via),
2773
+ via
2774
+ };
2775
+ }
2776
+ };
2777
+ if (m.length === 0) {
2778
+ const root = this.model.structureRoot(X);
2779
+ if (root?.kind === "type" && root === X) rec.cross = crossOf(this.model.declExpr(root));
2780
+ if (root?.kind === "type") rec.items = this.nullItems(this.model.declExpr(root), aliases);
2781
+ rec.owner = this.ownerOfDef(X, m, this.model.defAt(X, m), aliases);
2782
+ } else {
2783
+ const slot = this.model.slotAt(X, m);
2784
+ if (!m[m.length - 1].startsWith("|")) {
2785
+ let base = slot;
2786
+ while (base?.owner?.unit === X.id && base.shell) base = base.shell;
2787
+ const o = base?.owner;
2788
+ if (o && (o.unit !== X.id || !samePath(o.path, m)) && !o.unit.startsWith("m:") && !o.path.some((x) => x.startsWith("&"))) {
2789
+ const Z = this.model.declById(o.unit);
2790
+ if (Z) rec.other = {
2791
+ Z,
2792
+ zs: this.runtimePath(Z, [], o.path, false, aliases)
2793
+ };
2794
+ }
2795
+ }
2796
+ rec.cross = crossOf(slot?.ends.length === 1 ? slot.ends[0] : void 0);
2797
+ rec.items = this.slotNullItems(slot, aliases);
2798
+ rec.owner = this.ownerOfDef(X, m, slot?.def, aliases);
2799
+ }
2800
+ this.nodeRecs.set(key, rec);
2801
+ return rec;
2802
+ }
2803
+ /**
2804
+ * {@link reached}'s step into the declaration whose own def `def` (at model path `m` of `X`)
2805
+ * is: below that node the read is in that declaration's structure, below its runtime steps
2806
+ * returned. X's own def at `m` is X's: none.
2807
+ */ ownerOfDef(X, m, def, aliases) {
2808
+ const v = def && unshell(def);
2809
+ if (v && isAsView(v)) {
2810
+ const copy = this.model.declById(v.key.slice(2));
2811
+ if (copy && (copy !== X || m.length > 0)) return [copy, this.runtimePath(copy, [], [], true, aliases)];
2812
+ }
2813
+ const u = v && pastViews(v);
2814
+ const pos = u && defPosition(u);
2815
+ const Y = u?.unit && !u.unit.startsWith("m:") ? this.model.declById(u.unit) : void 0;
2816
+ if (!Y || pos === void 0 || pos.includes(":") || pos.includes("&") || Y === X && pos === m.join(".")) return;
2817
+ return [Y, this.runtimePath(Y, [], pos === "" ? [] : pos.split("."), true, aliases)];
2818
+ }
2819
+ /** The declaration a class name of this module stands for (its own, or an imported one). */ declNamed(n) {
2820
+ if (this.declsNamed.has(n)) return this.declsNamed.get(n);
2821
+ const owner = () => {
2822
+ const o = this.resolveOwner(this.doc, n);
2823
+ return o?.node && this.model.declOfNode(o.node);
2824
+ };
2825
+ const d = this.model.decls.find((x) => x.doc === this.doc && this.nameOf(x) === n && !this.isBare(x)) ?? owner();
2826
+ this.declsNamed.set(n, d);
2827
+ return d;
2828
+ }
2829
+ /** The name class `X` is bound to in this module, without adding an import (none: undefined). */ boundName(X) {
2830
+ if (X.doc === this.doc) return this.nameOf(X);
2831
+ return this.boundHere(X) && !this.unused.has(X.name) ? X.name : void 0;
2832
+ }
2833
+ /** The module's blocks: `$blk($R, i, T, entries)`, `$R` = the module's static rank. */ blockStatements() {
2834
+ const blocks = this.model.blocks.filter((b) => b.doc === this.doc && b.rank);
2835
+ if (blocks.length === 0) return;
2836
+ const R = this.allocAlias("$R", this.getSynthTaken());
2837
+ for (const b of blocks) this.statement(`blk:${b.index}`, () => {
2838
+ const data = this.entriesData(b, b.target);
2839
+ if (!data) return "";
2840
+ this.needStructure(b.target);
2841
+ return `${this.util("$blk")}(${R}, ${b.index}, ${this.nameOf(b.target)}, ${data})`;
2842
+ });
2843
+ const rank = blocks[0].rank;
2844
+ return `const ${R} = [${rank.depth}, ${str(rank.id)}]`;
2845
+ }
2846
+ /** The layer registries (`$ak`, `$nr`: how layers read those keys), before any statement. */ registries() {
2847
+ const { append, notReferred } = flagKeys(this.doc.config.annotations);
2848
+ const out = [];
2849
+ if (append.length > 0) out.push(`${this.util("$ak")}(${append.map(str).join(", ")})`);
2850
+ if (notReferred.length > 0) out.push(`${this.util("$nr")}(${notReferred.map(str).join(", ")})`);
2851
+ return out;
2852
+ }
2853
+ /**
2854
+ * The runtime steps of a model path: a `X | null` union the model passes through is a union
2855
+ * node at runtime (its non-null item: `|i`, own when the union's holder is, else shelled).
2856
+ */ runtimeSteps(d, steps, kinds, { copy = false, items: withItems = false, pure = false } = {}) {
2857
+ const out = [];
2858
+ const aliases = /* @__PURE__ */ new Set();
2859
+ const rd = this.model.structureRoot(d);
2860
+ if (rd?.kind === "type" && (steps.length > 0 || withItems)) {
2861
+ const root = this.model.declExpr(rd);
2862
+ const own = !copy && rd === d && (root.k === "nul" || root.k === "and");
2863
+ this.nullItems(root, aliases).forEach((at, j) => out.push([`|${at}`, j === 0 && own ? 0 : 2]));
2864
+ }
2865
+ for (let i = 0; i < steps.length; i++) {
2866
+ out.push([steps[i], kinds[i]]);
2867
+ const slot = this.model.slotAt(d, steps.slice(0, i + 1));
2868
+ const items = this.slotNullItems(slot, aliases);
2869
+ if (i < steps.length - 1 || withItems) {
2870
+ const written = slot?.ends.length === 1 && slot.ends[0].k === "nul";
2871
+ items.forEach((at, j) => out.push([`|${at}`, j === 0 && written && kinds[i] === 0 ? 0 : 2]));
2872
+ }
2873
+ }
2874
+ if (!pure) this.passAliases(aliases);
2875
+ return out;
2876
+ }
2877
+ post() {
2878
+ const decls = this.model.decls.filter((d) => d.doc === this.doc);
2879
+ for (const d of decls) if (this.isBare(d) && isExported(d)) {
2880
+ const local = this.nameOf(d);
2881
+ const line = `export { ${local} as ${d.name} }`;
2882
+ this.aliasExports.push({
2883
+ line,
2884
+ name: d.name,
2885
+ local
2886
+ });
2887
+ }
2888
+ for (const d of decls) if (this.isReplacing(d)) this.replacing.add(d.id);
2889
+ for (const d of decls) if (!this.isBare(d)) {
2890
+ this.declStatement(d);
2891
+ if (this.compiles && (!this.compiledClasses || this.compiledClasses.has(d.name))) this.compiledChecks.push(this.nameOf(d));
2892
+ }
2893
+ const rank = this.blockStatements();
2894
+ for (const line of this.registries()) this.writeln(line);
2895
+ if (rank) this.writeln(rank);
2896
+ if (this.inPlaceText.length > 0) this.writeln(`let ${this.inPlaceText.join(", ")}`);
2897
+ for (const { name } of this.hidden.values()) this.writeln(`class ${name} { static __is_atscript_annotated_type = true; static type = {}; static metadata = new Map() }`);
2898
+ if (this.hidden.size > 0) this.writeln();
2899
+ for (const st of this.fillDecls.size > 0 ? this.statements : []) this.fillNeeds(st);
2900
+ const cycle = inCycle(this.doc);
2901
+ if (this.shellPaths.size > 0 || cycle) for (const st of this.statements) for (const n of this.shellNeeds(st, cycle)) st.needs.add(n);
2902
+ const { statements, queued } = this.order();
2903
+ if (queued && !cycle && this.shellPaths.size > 0) for (const st of this.statements) this.shellNeeds(st, true);
2904
+ if (cycle || queued) {
2905
+ const byDecl = /* @__PURE__ */ new Map();
2906
+ for (const { decl, name, data } of this.shellPaths.values()) {
2907
+ const x = byDecl.get(decl) ?? {
2908
+ name,
2909
+ datas: []
2910
+ };
2911
+ x.datas.push(data);
2912
+ byDecl.set(decl, x);
2913
+ }
2914
+ for (const { name, datas } of byDecl.values()) this.writeln(`${this.util("$ps")}(${name}, [\n ${datas.join(",\n ")},\n])`);
2915
+ }
2916
+ const own = queued && !cycle ? this.allocAlias("$Q", this.getSynthTaken()) : void 0;
2917
+ if (own) this.writeln(`const ${own} = []`);
2918
+ for (const { text, guards } of statements) {
2919
+ if (!text) continue;
2920
+ if (cycle || queued) {
2921
+ this.writeln(`${this.util("$q")}(() => {`);
2922
+ for (const g of guards.values()) if (g.printed) this.writeln(` ${g.text}`);
2923
+ this.writeln(` ${this.indentText(stmt(text))}`);
2924
+ this.writeln(own ? `}, ${own})` : "})");
2925
+ } else this.writeln(stmt(text));
2926
+ this.writeln();
2927
+ }
2928
+ for (const { line } of this.aliasExports) this.writeln(line);
2929
+ if (cycle || queued) this.writeln(`${this.util("$end")}(${own ?? ""})`);
2930
+ this.renderCompiledChecks();
2931
+ this.writeln("// prettier-ignore-end");
2932
+ }
2933
+ /**
2934
+ * The statements in an order where each runs after the statements building what it needs
2935
+ * (declaration order otherwise); those in a dependency cycle are queued (`$q`).
2936
+ */ order() {
2937
+ const byBuild = new Map(this.statements.map((s) => [s.builds, s]));
2938
+ const out = [];
2939
+ const state = /* @__PURE__ */ new Map();
2940
+ let queued = false;
2941
+ const visit = (s) => {
2942
+ const st = state.get(s);
2943
+ if (st === "done") return;
2944
+ if (st === "visiting") {
2945
+ queued = true;
2946
+ return;
2947
+ }
2948
+ state.set(s, "visiting");
2949
+ for (const n of s.needs) {
2950
+ const dep = byBuild.get(n);
2951
+ if (dep && dep !== s) visit(dep);
2952
+ }
2953
+ state.set(s, "done");
2954
+ out.push(s);
2955
+ };
2956
+ this.statements.forEach(visit);
2957
+ return {
2958
+ statements: out,
2959
+ queued
2960
+ };
2961
+ }
2962
+ constructor(doc, opts, mode) {
2963
+ super(doc, opts, mode), _define_property$1(this, "model", void 0), _define_property$1(this, "hidden", /* @__PURE__ */ new Map()), _define_property$1(this, "inPlace", /* @__PURE__ */ new Map()), _define_property$1(this, "inPlaceText", []), _define_property$1(this, "statements", []), _define_property$1(this, "aliasExports", []), _define_property$1(this, "replacing", /* @__PURE__ */ new Set()), _define_property$1(this, "needs", /* @__PURE__ */ new Set()), _define_property$1(this, "guards", /* @__PURE__ */ new Map()), _define_property$1(this, "fillReads", []), _define_property$1(this, "readsByText", /* @__PURE__ */ new Map()), _define_property$1(this, "hiddenDecls", /* @__PURE__ */ new Map()), _define_property$1(this, "chainFills", /* @__PURE__ */ new Set()), _define_property$1(this, "fillDecls", /* @__PURE__ */ new Set()), _define_property$1(this, "runtimePaths", /* @__PURE__ */ new Map()), _define_property$1(this, "chainHandle", void 0), _define_property$1(this, "scalarMerges", /* @__PURE__ */ new WeakMap()), _define_property$1(this, "shellPaths", /* @__PURE__ */ new Map()), _define_property$1(this, "importersMemo", void 0), _define_property$1(this, "withShellsMemo", void 0), _define_property$1(this, "shellIndex", void 0), _define_property$1(this, "reachedMemo", /* @__PURE__ */ new Map()), _define_property$1(this, "visitsMemo", /* @__PURE__ */ new Map()), _define_property$1(this, "nodeRecs", /* @__PURE__ */ new Map()), _define_property$1(this, "declsNamed", /* @__PURE__ */ new Map());
2964
+ this.model = doc.componentStructure().complete();
2965
+ }
2966
+ };
2967
+ /**
2968
+ * The renderers of a documents' epoch, by module and render options (see {@link rendererOf}): by
2969
+ * the document object — two repositories may hold documents of one id.
2970
+ */ const phase1 = {
2971
+ epoch: -1,
2972
+ renderers: /* @__PURE__ */ new WeakMap()
2973
+ };
2974
+ /**
2975
+ * `doc`'s renderer for the render options at the current documents' epoch: its phase 1 (see
2976
+ * `JsRenderer.phase1`) runs once, shared by its render and by the realms that load it (phase 2,
2977
+ * the build's load check) — a module is rendered once per build.
2978
+ */ function rendererOf(doc, opts, mode) {
2979
+ if (phase1.epoch !== documentsEpoch()) {
2980
+ phase1.epoch = documentsEpoch();
2981
+ phase1.renderers = /* @__PURE__ */ new WeakMap();
2982
+ }
2983
+ let byKey = phase1.renderers.get(doc);
2984
+ if (!byKey) phase1.renderers.set(doc, byKey = /* @__PURE__ */ new Map());
2985
+ const key = moduleKey(opts, mode);
2986
+ let renderer = byKey.get(key);
2987
+ if (!renderer) {
2988
+ renderer = new JsNextRenderer(doc, opts, mode);
2989
+ byKey.set(key, renderer);
2990
+ }
2991
+ return renderer;
2992
+ }
2993
+ /** The render options a phase-1 module depends on (see {@link rendererOf}). */ function moduleKey(opts, mode) {
2994
+ return JSON.stringify([
2995
+ resolveJsonSchemaMode(opts),
2996
+ !!opts?.exampleData,
2997
+ opts?.moduleExtension ?? ".as",
2998
+ mode
2999
+ ]);
3000
+ }
3001
+ /** `doc`'s phase-1 module (see `JsRenderer.phase1`), rendered once per documents' epoch. */ function moduleOf(doc, opts, mode) {
3002
+ return rendererOf(doc, opts, mode).phase1();
3003
+ }
3004
+ /**
3005
+ * {@link withLoadCheck}'s state: one per process (`Symbol.for` on `globalThis`), so that every
3006
+ * copy of this package — its ESM and CommonJS builds, the CLI's bundle — agrees.
3007
+ */ const loadChecks = (_globalThis = globalThis)[_Symbol_for = Symbol.for("atscript.typescript.loadCheck")] ?? (_globalThis[_Symbol_for] = new AsyncLocalStorage());
3008
+ /**
3009
+ * Runs `fn` — renders of a build (`BuildRepo.generate` / `write`, `AtscriptDoc.render`) — with
3010
+ * the build's load check (MODEL CYCLE-GUARD-6, -8): every generated JS module is loaded (each
3011
+ * import cycle from each of its modules), and a module that fails to load fails the render. The
3012
+ * CLI's build runs in it; a render's own `loadCheck` option wins (the bundler plugin sets it).
3013
+ */ function withLoadCheck(fn) {
3014
+ return loadChecks.run(true, fn);
3015
+ }
3016
+ /**
3017
+ * The build's load check of `doc`'s render (see {@link cycleLoadError}) when it is on: the
3018
+ * render's `loadCheck` option, else {@link withLoadCheck}'s (dev / HMR / LSP renders never load).
3019
+ * Throws the error of `doc`'s module.
3020
+ */ function assertLoads(doc, opts, mode, loadCheck) {
3021
+ const error = loadCheck ?? loadChecks.getStore() === true ? cycleLoadError(doc, opts, mode) : void 0;
3022
+ if (error) throw new Error(`${doc.id}: ${error}`);
3023
+ }
3024
+ /**
3025
+ * {@link cycleLoadError}s by the component's realm (see `moduleRealm`: one per component, documents'
3026
+ * epoch and render options).
3027
+ */ const cycleLoadErrors = /* @__PURE__ */ new WeakMap();
3028
+ /**
3029
+ * The build's check of loads (MODEL CYCLE-GUARD-6, -8): every generated module of `doc`'s
3030
+ * component is loaded once, and every import cycle of the generated modules from each of its
3031
+ * modules, each in a fresh realm; any load error — a statement left waiting, one that threw, a
3032
+ * module body that threw — is an internal code generation error, reported on the module it is
3033
+ * of. Once per component and documents' epoch.
3034
+ */ function cycleLoadError(doc, opts, mode) {
3035
+ const realm = moduleRealm(doc, opts, mode);
3036
+ let found = cycleLoadErrors.get(realm);
3037
+ if (!found) {
3038
+ const errors = /* @__PURE__ */ new Map();
3039
+ cycleLoadErrors.set(realm, found = errors);
3040
+ const report = (r, entry) => {
3041
+ for (const [d, xs] of r.loadErrors()) if (!errors.has(d)) {
3042
+ const how = entry ? `when "${entry.name}" is loaded first` : "when loaded";
3043
+ errors.set(d, `the generated code fails to load ${how} — an internal code generation error, please report it: ${xs.join(" | ")}`);
3044
+ }
3045
+ };
3046
+ report(realm);
3047
+ const { modules, compiled } = realm;
3048
+ const graph = (d) => (modules.get(d)?.imports ?? []).flatMap((i) => i.doc && modules.has(i.doc) ? [i.doc] : []);
3049
+ for (const [d, scc] of components(modules.keys(), graph)) if (scc.length > 1) report(new Realm(modules, compiled).loadFrom(d), d);
3050
+ }
3051
+ return found.get(doc);
3052
+ }
3053
+ /** The realm of `doc` for the render options (see `realm.ts`): the one `render` uses. */ function moduleRealm(doc, opts, mode) {
3054
+ return realmOf(doc, moduleKey(opts, mode), (d) => moduleOf(d, opts, mode));
3055
+ }
3056
+ /**
3057
+ * {@link generatedImports}, by document, with the epoch of the documents it was computed at
3058
+ * (valid while neither the document nor those it imports, directly or not, changed).
3059
+ */ const generatedImportsCache = /* @__PURE__ */ new WeakMap();
3060
+ /**
3061
+ * The documents whose generated modules the generated module of `doc` imports: those of the
3062
+ * imports whose names it uses, and those it adds (see `synthBinding`) — what it is evaluated
3063
+ * after (see {@link importCycle}). Computed by rendering it, again once it or a document it
3064
+ * imports (directly or not) changed (see `AtscriptDoc.changedSince`).
3065
+ */ function generatedImports(doc) {
3066
+ let cached = generatedImportsCache.get(doc);
3067
+ if (!cached || doc.changedSince(cached.epoch)) {
3068
+ const renderer = new JsNextRenderer(doc, { jsonSchema: false }, "none");
3069
+ renderer.renderModule();
3070
+ cached = {
3071
+ epoch: documentsEpoch(),
3072
+ docs: [...renderer.importedDocs]
3073
+ };
3074
+ generatedImportsCache.set(doc, cached);
3075
+ }
3076
+ return cached.docs;
3077
+ }
3078
+ /** {@link importCycle}, by document, with the epoch of the documents it was found at. */ const importCycles = /* @__PURE__ */ new WeakMap();
3079
+ /**
3080
+ * Whether `doc`'s generated module is on an import cycle of generated modules with mutating
3081
+ * annotates (see `findImportCycle`): `unplugin-atscript` keeps such a module's side effects (the
3082
+ * cycles of the generated modules' imports, which the structure model's import ranks do not see).
3083
+ */ function importCycle(doc) {
3084
+ const known = importCycles.get(doc);
3085
+ if (known && !doc.changedSince(known.epoch)) return known.cycle;
3086
+ const found = /* @__PURE__ */ new Map();
3087
+ const cycle = findImportCycle(doc, generatedImports, found);
3088
+ const epoch = documentsEpoch();
3089
+ for (const [d, c] of found) importCycles.set(d, {
3090
+ epoch,
3091
+ cycle: c
3092
+ });
3093
+ return cycle;
3094
+ }
3095
+
3096
+ //#endregion
3097
+ //#region packages/typescript/src/codegen/type-renderer.ts
3098
+ function _define_property(obj, key, value) {
3099
+ if (key in obj) Object.defineProperty(obj, key, {
3100
+ value,
3101
+ enumerable: true,
3102
+ configurable: true,
3103
+ writable: true
3104
+ });
3105
+ else obj[key] = value;
3106
+ return obj;
3107
+ }
3108
+ var TypeRenderer = class TypeRenderer extends BaseRenderer {
3109
+ pre() {
3110
+ this.writeln("// prettier-ignore-start");
3111
+ this.writeln("/* eslint-disable */");
3112
+ this.writeln("/* oxlint-disable */");
3113
+ this.writeln(`/// <reference path="./${this.doc.name}" />`);
3114
+ this.writeln("/**");
3115
+ this.writeln(" * 🪄 This file was generated by Atscript");
3116
+ this.writeln(" * Do not edit this file!");
3117
+ this.writeln(" */");
3118
+ this.writeln();
3119
+ this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TAtscriptField, TMetadataMap, Validator, TValidatorOptions } from \"@atscript/typescript/utils\"");
3120
+ }
3121
+ post() {
3122
+ this.writeln("// prettier-ignore-end");
3123
+ }
3124
+ renderTypeDefString(def) {
3125
+ const newThis = new TypeRenderer(this.doc, this.opts);
3126
+ newThis.renderTypeDef(def);
3127
+ return newThis.toString();
3128
+ }
3129
+ renderTypeDef(def) {
3130
+ if (!def) {
3131
+ this.write("unknown");
3132
+ return;
3133
+ }
3134
+ if (isStructure(def)) return this.renderStructure(def);
3135
+ if (isGroup(def)) {
3136
+ const tuple = def.entity === "tuple";
3137
+ const operator = tuple ? ", " : ` ${def.op} `;
3138
+ const children = def.unwrap();
3139
+ const isUnion = (c) => isGroup(c) && c.entity !== "tuple" && c.op === "|" || this.primitiveKind(c) === "union";
3140
+ const wrapUnions = !tuple && def.op === "&" && children.some(isUnion);
3141
+ const hasSubgroup = !tuple && !wrapUnions && children.some((c) => c.entity === "group");
3142
+ this.write(tuple ? "[" : hasSubgroup ? "(" : "");
3143
+ children.forEach((child, i) => {
3144
+ if (i > 0) this.write(operator);
3145
+ const wrap = wrapUnions && isUnion(child);
3146
+ this.write(wrap ? "(" : "");
3147
+ this.renderTypeDef(child);
3148
+ this.write(wrap ? ")" : "");
3149
+ });
3150
+ return this.write(tuple ? "]" : hasSubgroup ? ")" : "");
3151
+ }
3152
+ if (isConst(def)) {
3153
+ const name = def.token("identifier")?.type === "number" ? def.id : `"${escapeQuotes(def.id)}"`;
3154
+ return this.write(name);
3155
+ }
3156
+ if (isRef(def)) {
3157
+ const node = def;
3158
+ const unwound = this.doc.unwindRef(node);
3159
+ if (isPrimitive(unwound?.def)) {
3160
+ this.write(renderPrimitiveTypeDef(unwound.def.config.type));
3161
+ if (node.hasChain) this.write(` /* ${node.chain.map((c) => c.text).join(".")} */`);
3162
+ return;
3163
+ }
3164
+ let name = node.id;
3165
+ for (const c of node.chain) name = `TAtscriptField<${name}, "${escapeQuotes(c.text)}">`;
3166
+ return this.write(name);
3167
+ }
3168
+ if (isArray(def)) {
3169
+ const def2 = def.getDefinition();
3170
+ const kind = def2 && this.primitiveKind(def2);
3171
+ const isGrp = def2?.entity === "group" || kind === "union" || kind === "intersection";
3172
+ if (isGrp) this.write("(");
3173
+ this.renderTypeDef(def2);
3174
+ if (isGrp) this.write(")");
3175
+ return this.write("[]");
3176
+ }
3177
+ if (isPrimitive(def)) return this.write(renderPrimitiveTypeDef(def.config.type));
3178
+ }
3179
+ /** The kind of the type a reference to a primitive renders (`string | number`: `union`). */ primitiveKind(node) {
3180
+ const def = isRef(node) ? this.doc.unwindRef(node)?.def : void 0;
3181
+ const type = isPrimitive(def) ? def.config.type : void 0;
3182
+ return typeof type === "object" ? type.kind : void 0;
3183
+ }
3184
+ renderStructure(struct, asClass, interfaceNode, filterProps) {
3185
+ this.blockln("{}");
3186
+ const patterns = [];
3187
+ const propsDefs = /* @__PURE__ */ new Set();
3188
+ for (const prop of struct.props.values()) {
3189
+ if (filterProps?.has(prop.id)) continue;
3190
+ if (prop.token("identifier")?.pattern) {
3191
+ if (!filterProps) patterns.push(prop);
3192
+ continue;
3193
+ }
3194
+ const phantomType = this.phantomPropType(prop.getDefinition());
3195
+ if (phantomType) {
3196
+ this.writeln(`// ${prop.id}: ${phantomType}`);
3197
+ continue;
3198
+ }
3199
+ const optional = !!prop.token("optional");
3200
+ this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
3201
+ const renderedDef = this.renderTypeDefString(prop.getDefinition());
3202
+ propsDefs.add(renderedDef);
3203
+ renderedDef.split("\n").forEach((l) => this.writeln(l));
3204
+ }
3205
+ if (patterns.length > 0) {
3206
+ this.write(`[key: string]: `);
3207
+ for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
3208
+ const defs = Array.from(propsDefs);
3209
+ if (defs.length > 1) {
3210
+ this.indent();
3211
+ for (const def of defs) {
3212
+ this.writeln();
3213
+ this.write("| ");
3214
+ def.split("\n").forEach((l) => this.write(l.trim()));
3215
+ }
3216
+ this.unindent();
3217
+ this.writeln();
3218
+ } else defs[0].split("\n").forEach((l) => this.writeln(l));
3219
+ }
3220
+ if (asClass) this.renderStaticDeclarations(asClass, interfaceNode);
3221
+ this.pop();
3222
+ }
3223
+ renderStaticDeclarations(asClass, interfaceNode) {
3224
+ this.writeln("static __is_atscript_annotated_type: true");
3225
+ this.writeln(`static type: TAtscriptTypeObject<keyof ${asClass}, ${asClass}>`);
3226
+ this.writeln(`static metadata: TMetadataMap<AtscriptMetadata>`);
3227
+ this.writeln(`static validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${asClass}>`);
3228
+ if (resolveJsonSchemaMode(this.opts) === false) this.writeln("/** @deprecated JSON Schema support is disabled. Calling this method will throw a runtime error. To enable, set `jsonSchema: 'lazy'` or `jsonSchema: 'bundle'` in tsPlugin options, or add `@emit.jsonSchema` annotation to individual interfaces. */");
3229
+ this.writeln("static toJsonSchema: () => any");
3230
+ if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
3231
+ this.writeln("static toExampleData?: () => any");
3232
+ if (interfaceNode && isDbEntityNode(interfaceNode)) {
3233
+ this.renderFlatMaps(interfaceNode);
3234
+ this.renderNavProps(interfaceNode);
3235
+ this.renderPk(interfaceNode);
3236
+ this.renderDimMeasure(interfaceNode);
3237
+ }
3238
+ }
3239
+ renderInterface(node) {
3240
+ this.writeln();
3241
+ const exported = node.token("export")?.text === "export";
3242
+ this.renderJsDoc(node);
3243
+ this.write(exported ? "export declare " : "declare ");
3244
+ if (node.hasExtends) {
3245
+ const firstParent = node.extendsTokens[0].text;
3246
+ this.write(`class ${node.id} extends ${firstParent} `);
3247
+ const resolved = this.doc.resolveInterfaceExtends(node);
3248
+ if (resolved?.entity === "structure") {
3249
+ const firstParentUnwound = this.doc.unwindType(firstParent);
3250
+ let firstParentProps;
3251
+ if (firstParentUnwound?.def) {
3252
+ let fpDef = firstParentUnwound.def;
3253
+ if (isInterface(fpDef)) {
3254
+ if (fpDef.hasExtends) {
3255
+ const fpResolved = firstParentUnwound.doc.resolveInterfaceExtends(fpDef);
3256
+ if (fpResolved && isStructure(fpResolved)) firstParentProps = fpResolved.props;
3257
+ }
3258
+ if (!firstParentProps) fpDef = fpDef.getDefinition() || fpDef;
3259
+ }
3260
+ if (!firstParentProps && isStructure(fpDef)) firstParentProps = fpDef.props;
3261
+ }
3262
+ this.renderStructure(resolved, node.id, node, firstParentProps);
3263
+ } else this.writeln("{}");
3264
+ } else {
3265
+ this.write(`class ${node.id} `);
3266
+ const struct = node.getDefinition();
3267
+ if (struct?.entity === "structure") this.renderStructure(struct, node.id, node);
3268
+ else this.writeln("{}");
3269
+ }
3270
+ this.writeln();
3271
+ }
3272
+ renderType(node) {
3273
+ this.writeln();
3274
+ const exported = node.token("export")?.text === "export";
3275
+ this.renderJsDoc(node);
3276
+ this.write(exported ? "export " : "declare ");
3277
+ this.write(`type ${node.id} = `);
3278
+ this.renderTypeDef(node.getDefinition());
3279
+ this.writeln();
3280
+ this.renderTypeNamespace(node);
3281
+ }
3282
+ renderAnnotate(node) {
3283
+ if (node.isMutating) return;
3284
+ const targetName = node.targetName;
3285
+ this.writeln();
3286
+ const exported = node.token("export")?.text === "export";
3287
+ this.renderJsDoc(node);
3288
+ if (this.isTypeTarget(targetName)) {
3289
+ this.write(exported ? "export " : "declare ");
3290
+ this.write(`type ${node.id} = ${targetName}`);
3291
+ this.writeln();
3292
+ const unwound = this.doc.unwindType(targetName);
3293
+ this.renderTypeNamespaceFor(node.id, unwound?.def, this.namesFields(node, this.doc));
3294
+ } else {
3295
+ this.write(exported ? "export declare " : "declare ");
3296
+ this.writeln(`class ${node.id} extends ${targetName} {}`);
3297
+ }
3298
+ }
3299
+ renderTypeNamespace(node) {
3300
+ this.renderTypeNamespaceFor(node.id, node.getDefinition(), this.namesFields(node, this.doc));
3301
+ }
3302
+ /**
3303
+ * Whether declaration `node` (of `doc`) is a type path naming several fields — written there,
3304
+ * through plain aliases and `annotate … as` copies, or as the type of the one field a type path
3305
+ * names —: a union of them at runtime, whatever its structure (MODEL §15 STRUCT-N3-DTS).
3306
+ */ namesFields(node, doc, seen = /* @__PURE__ */ new Set()) {
3307
+ if (!node || seen.has(node)) return false;
3308
+ seen.add(node);
3309
+ if (isAnnotate(node)) {
3310
+ const target = doc.getDeclarationOwnerNode(node.targetName);
3311
+ return this.namesFields(target?.node, target?.doc ?? doc, seen);
3312
+ }
3313
+ let def = node.entity === "type" || node.entity === "prop" ? node.getDefinition() : void 0;
3314
+ while (isGroup(def) && !def.op && def.unwrap().length === 1) def = def.unwrap()[0];
3315
+ if (!isRef(def)) return false;
3316
+ if (def.hasChain) {
3317
+ const e = doc.componentStructure().complete().exprOf(doc, def);
3318
+ if (e.k === "uni" || e.k === "scalar") return e.k === "uni";
3319
+ const unwound = doc.unwindRef(def);
3320
+ return this.namesFields(unwound?.node, unwound?.doc ?? doc, seen);
3321
+ }
3322
+ const owner = doc.resolveRefOwner(def);
3323
+ return this.namesFields(owner?.node, owner?.doc ?? doc, seen);
3324
+ }
3325
+ /**
3326
+ * `fields`: the type is a type path naming several fields (see {@link namesFields}): its
3327
+ * descriptor is typed as the runtime holds it, a union (MODEL §15 STRUCT-N3-DTS).
3328
+ */ renderTypeNamespaceFor(name, inputDef, fields = false) {
3329
+ this.write(`declare namespace ${name} `);
3330
+ this.blockln("{}");
3331
+ let typeDef = "TAtscriptTypeDef";
3332
+ if (inputDef) {
3333
+ let realDef = inputDef;
3334
+ if (isRef(inputDef)) realDef = this.doc.unwindRef(inputDef)?.def || realDef;
3335
+ realDef = this.doc.mergeIntersection(realDef);
3336
+ if (fields) typeDef = `TAtscriptTypeComplex<${name}>`;
3337
+ else if (isStructure(realDef) || isInterface(realDef)) typeDef = `TAtscriptTypeObject<keyof ${name}, ${name}>`;
3338
+ else if (isGroup(realDef)) typeDef = `TAtscriptTypeComplex<${name}>`;
3339
+ else if (isArray(realDef)) typeDef = `TAtscriptTypeArray<${name}>`;
3340
+ else if (isPrimitive(realDef)) typeDef = `TAtscriptTypeFinal<${name}>`;
3341
+ }
3342
+ this.writeln(`const __is_atscript_annotated_type: true`);
3343
+ this.writeln(`const type: ${typeDef}`);
3344
+ this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
3345
+ this.writeln(`const validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${name}>`);
3346
+ if (resolveJsonSchemaMode(this.opts) === false) this.writeln("/** @deprecated JSON Schema support is disabled. Calling this method will throw a runtime error. To enable, set `jsonSchema: 'lazy'` or `jsonSchema: 'bundle'` in tsPlugin options, or add `@emit.jsonSchema` annotation to individual interfaces. */");
3347
+ this.writeln("const toJsonSchema: () => any");
3348
+ if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
3349
+ this.writeln("const toExampleData: (() => any) | undefined");
3350
+ this.popln();
3351
+ }
3352
+ /**
3353
+ * Renders the `static __flat` property — a map of all dot-notation paths to their TypeScript
3354
+ * value types — and `static __ownProps` — the table-owned paths only (no nav props).
3355
+ *
3356
+ * This enables type-safe autocomplete for filter keys and `$select`/`$sort`
3357
+ * paths when using `AtscriptDbTable`. The `FlatOf<T>` utility type extracts
3358
+ * this map at the type level.
3359
+ *
3360
+ * The paths are the runtime flatten's (`flattenAnnotatedType`, as the db layer flattens the
3361
+ * table) of the type's class in the build-time realm (see `realm.ts`); their TS types are the
3362
+ * types written at them (see `flatDefinitions`). A type whose module fails to evaluate in the
3363
+ * realm has neither (a comment in the output says so).
3364
+ */ renderFlatMaps(node) {
3365
+ let flat;
3366
+ try {
3367
+ const realm = moduleRealm(this.doc, this.opts, compileValidatorsMode("js", this.opts));
3368
+ const type = realm.classOf(this.doc, node.id);
3369
+ if (type?.type?.kind !== "object") throw new Error(`${node.id} not built`);
3370
+ flat = realm.rt.flattenAnnotatedType(type, { excludePhantomTypes: true });
3371
+ } catch {
3372
+ this.writeln("// __flat / __ownProps omitted: the type failed to evaluate at build time");
3373
+ return;
3374
+ }
3375
+ const defs = flatDefinitions(this.doc, node);
3376
+ this.renderFlatMap("__flat", flat, defs);
3377
+ this.renderFlatMap("__ownProps", flat, defs, {
3378
+ ownProps: true,
3379
+ leadingNewline: true,
3380
+ trailingNewline: true
3381
+ });
3382
+ }
3383
+ /**
3384
+ * Shared renderer for flat-map static properties (`__flat`, `__ownProps`): the paths of `flat`
3385
+ * (the runtime flatten) except the root and the sub-paths of `@db.json` fields (and, with
3386
+ * `ownProps`, nav props and their sub-paths).
3387
+ *
3388
+ * Special rendering rules:
3389
+ * - **Intermediate paths** (structures, arrays of complex elements, unions of complex
3390
+ * branches only) → `never`
3391
+ * - **`@db.json` fields** → `string` (stored as serialized JSON in DB)
3392
+ * - **Leaf fields** → their original TypeScript type
3393
+ * - **Optional paths** (the field or one it is in is optional) → `?` and, unless
3394
+ * intermediate, `<type> | null` — the DB layer treats optional as nullable in filters, so
3395
+ * `null` must be assignable to the path's type
3396
+ */ renderFlatMap(propName, flat, defs, opts) {
3397
+ const paths = [];
3398
+ for (const [path, type] of flat) {
3399
+ const optional = path ? flatPathOptional(flat, path, type, !!opts?.ownProps) : void 0;
3400
+ if (optional !== void 0) paths.push([
3401
+ path,
3402
+ type,
3403
+ optional
3404
+ ]);
3405
+ }
3406
+ if (paths.length === 0) return;
3407
+ if (opts?.leadingNewline) this.writeln();
3408
+ this.write(`static ${propName}: `);
3409
+ this.blockln("{}");
3410
+ for (const [path, type, optional] of paths) {
3411
+ this.write(`"${escapeQuotes(path)}"`);
3412
+ if (optional) this.write("?");
3413
+ this.write(": ");
3414
+ const nullable = optional ? " | null" : "";
3415
+ if (dbJson(type)) this.writeln(`string${nullable}`);
3416
+ else if (intermediatePath(type)) this.writeln("never");
3417
+ else {
3418
+ const lines = this.renderTypeDefString(flatTypeDef(defs(path))).split("\n");
3419
+ lines[lines.length - 1] += nullable;
3420
+ lines.forEach((l) => this.writeln(l));
3421
+ }
3422
+ }
3423
+ if (opts?.trailingNewline) this.popln();
3424
+ else this.pop();
3425
+ }
3426
+ /**
3427
+ * Renders the `static __navProps` property — a map of navigation property names
3428
+ * to their declared TypeScript types.
3429
+ *
3430
+ * This enables type-safe `$with` in queries: `name` is constrained to known
3431
+ * navigation property keys, and nested filter/controls are typed to the target entity.
3432
+ */ renderNavProps(node) {
3433
+ let struct;
3434
+ if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
3435
+ if (!struct) struct = node.getDefinition();
3436
+ if (!struct || !isStructure(struct)) return;
3437
+ const structNode = struct;
3438
+ const navProps = [];
3439
+ for (const [name, prop] of structNode.props) {
3440
+ if (prop.token("identifier")?.pattern) continue;
3441
+ if (hasNavPropAnnotation(prop)) navProps.push({
3442
+ name,
3443
+ prop
3444
+ });
3445
+ }
3446
+ if (navProps.length === 0) return;
3447
+ this.writeln();
3448
+ this.write("static __navProps: ");
3449
+ this.blockln("{}");
3450
+ for (const { name, prop } of navProps) {
3451
+ this.write(`"${escapeQuotes(name)}"`);
3452
+ if (prop.token("optional")) this.write("?");
3453
+ this.write(": ");
3454
+ const propDef = prop.getDefinition();
3455
+ if (propDef) this.renderTypeDefString(propDef).split("\n").forEach((l) => this.writeln(l));
3456
+ else this.writeln("unknown");
3457
+ }
3458
+ this.popln();
3459
+ }
3460
+ renderPk(node) {
3461
+ const isMongoCollection = !!node.annotations?.some((a) => a.name === "db.mongo.collection");
3462
+ let struct;
3463
+ if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
3464
+ if (!struct) struct = node.getDefinition();
3465
+ if (!struct || !isStructure(struct)) return;
3466
+ const structNode = struct;
3467
+ const pkProps = [];
3468
+ const uniqueByIndex = /* @__PURE__ */ new Map();
3469
+ for (const [name, prop] of structNode.props) {
3470
+ if (prop.token("identifier")?.pattern) continue;
3471
+ if (isMongoCollection && name === "_id") continue;
3472
+ if (prop.countAnnotations("meta.id") > 0) pkProps.push({
3473
+ name,
3474
+ prop
3475
+ });
3476
+ if (prop.annotations) {
3477
+ for (const ann of prop.annotations) if (ann.name === "db.index.unique") {
3478
+ const indexName = ann.args[0]?.text ?? name;
3479
+ let group = uniqueByIndex.get(indexName);
3480
+ if (!group) {
3481
+ group = [];
3482
+ uniqueByIndex.set(indexName, group);
3483
+ }
3484
+ group.push({
3485
+ name,
3486
+ prop
3487
+ });
3488
+ }
3489
+ }
3490
+ }
3491
+ const uniqueProps = [];
3492
+ const pkNames = new Set(pkProps.map((p) => p.name));
3493
+ for (const fields of uniqueByIndex.values()) if (fields.length === 1 && !pkNames.has(fields[0].name)) uniqueProps.push(fields[0]);
3494
+ if (pkProps.length === 0 && uniqueProps.length === 0 && !isMongoCollection) return;
3495
+ let mongoIdType;
3496
+ if (isMongoCollection) {
3497
+ const idProp = structNode.props.get("_id");
3498
+ if (idProp) mongoIdType = this.renderTypeDefString(idProp.getDefinition()).trim();
3499
+ mongoIdType ?? (mongoIdType = "string");
3500
+ }
3501
+ const uniqueTypes = [];
3502
+ const seenTypes = /* @__PURE__ */ new Set();
3503
+ for (const { prop } of uniqueProps) {
3504
+ const rendered = this.renderTypeDefString(prop.getDefinition()).trim();
3505
+ if (!seenTypes.has(rendered)) {
3506
+ seenTypes.add(rendered);
3507
+ uniqueTypes.push(rendered);
3508
+ }
3509
+ }
3510
+ this.writeln();
3511
+ const uniqueSuffix = uniqueTypes.length > 0 ? ` | ${uniqueTypes.join(" | ")}` : "";
3512
+ if (pkProps.length === 0 && !isMongoCollection) this.writeln(`static __pk: ${uniqueTypes.join(" | ")}`);
3513
+ else if (pkProps.length === 0) this.writeln(`static __pk: ${mongoIdType}${uniqueSuffix}`);
3514
+ else if (pkProps.length === 1) {
3515
+ this.write("static __pk: ");
3516
+ if (isMongoCollection) this.write(`${mongoIdType} | `);
3517
+ const renderedDef = this.renderTypeDefString(pkProps[0].prop.getDefinition()).trim();
3518
+ this.writeln(`${renderedDef}${uniqueSuffix}`);
3519
+ } else {
3520
+ this.write("static __pk: ");
3521
+ if (isMongoCollection) this.write(`${mongoIdType} | `);
3522
+ this.blockln("{}");
3523
+ for (const { name, prop } of pkProps) {
3524
+ this.write(wrapProp(name), ": ");
3525
+ this.renderTypeDefString(prop.getDefinition()).split("\n").forEach((l) => this.writeln(l));
3526
+ }
3527
+ this.pop();
3528
+ this.writeln(uniqueSuffix);
3529
+ }
3530
+ }
3531
+ renderDimMeasure(node) {
3532
+ let struct;
3533
+ if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
3534
+ if (!struct) struct = node.getDefinition();
3535
+ if (!struct || !isStructure(struct)) return;
3536
+ const structNode = struct;
3537
+ const dims = [];
3538
+ const measures = [];
3539
+ for (const [name, prop] of structNode.props) {
3540
+ if (prop.token("identifier")?.pattern) continue;
3541
+ if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
3542
+ if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
3543
+ }
3544
+ if (dims.length === 0 && measures.length === 0) return;
3545
+ this.writeln();
3546
+ if (dims.length > 0) this.writeln(`static __dim: ${dims.map((d) => `"${escapeQuotes(d)}"`).join(" | ")}`);
3547
+ if (measures.length > 0) this.writeln(`static __measure: ${measures.map((m) => `"${escapeQuotes(m)}"`).join(" | ")}`);
3548
+ }
3549
+ phantomPropType(def) {
3550
+ if (!def || !isPhantomNode(this.doc, def)) return;
3551
+ return isRef(def) ? entryParts(def).join(".") : def.id;
3552
+ }
3553
+ isTypeTarget(name, doc) {
3554
+ const decl = (doc || this.doc).getDeclarationOwnerNode(name);
3555
+ if (!decl?.node) return false;
3556
+ if (decl.node.entity === "type") return true;
3557
+ if (decl.node.entity === "interface") return false;
3558
+ if (decl.node.entity === "annotate") return this.isTypeTarget(decl.node.targetName, decl.doc);
3559
+ return false;
3560
+ }
3561
+ renderJsDoc(node) {
3562
+ const range = node.token("identifier")?.range;
3563
+ const rangeStr = range ? `:${range.start.line + 1}:${range.start.character + 1}` : "";
3564
+ this.writeln(`/**`);
3565
+ this.writeln(` * Atscript ${node.entity} **${node.id}**`);
3566
+ this.writeln(` * @see {@link ./${this.doc.name}${rangeStr}}`);
3567
+ this.writeln(` */`);
3568
+ }
3569
+ constructor(doc, opts) {
3570
+ super(doc), _define_property(this, "opts", void 0), this.opts = opts;
3571
+ }
3572
+ };
3573
+ /** Whether flattened `type` is a `@db.json` field: a leaf, stored as a JSON string. */ function dbJson(type) {
3574
+ return type.metadata.has("db.json");
3575
+ }
3576
+ /** Whether flattened `type` is a nav prop (see `NAV_PROP_ANNOTATIONS`). */ function navProp(type) {
3577
+ const metadata = type.metadata;
3578
+ return NAV_PROP_ANNOTATIONS.some((name) => metadata.has(name));
3579
+ }
3580
+ /**
3581
+ * Whether `path` (of `type`) of runtime flatten `flat` is optional (it or a path it is in is, see
3582
+ * {@link optionalPath}); `undefined` when it is not listed: below a `@db.json` field, or with
3583
+ * `ownProps` a nav prop or below one.
3584
+ */ function flatPathOptional(flat, path, type, ownProps) {
3585
+ let optional = false;
3586
+ for (let dot = path.indexOf("."); dot >= 0; dot = path.indexOf(".", dot + 1)) {
3587
+ const above = flat.get(path.slice(0, dot));
3588
+ if (above && (dbJson(above) || ownProps && navProp(above))) return;
3589
+ optional || (optional = !!above && optionalPath(above));
3590
+ }
3591
+ return ownProps && navProp(type) ? void 0 : optional || optionalPath(type);
3592
+ }
3593
+ /**
3594
+ * Whether the path of flattened `type` is optional: the field is, or (paths colliding into a
3595
+ * union of their types) one of the fields there is.
3596
+ */ function optionalPath(type) {
3597
+ return !!type.optional || type.type.kind === "union" && type.type.items.some((i) => i.optional);
3598
+ }
3599
+ /**
3600
+ * Whether the path of flattened `type` is intermediate (rendered `never`): an object, an array of
3601
+ * complex elements, a union (or tuple) of complex branches only (a mixed union is a leaf: its
3602
+ * scalar branches compare).
3603
+ */ function intermediatePath(type) {
3604
+ switch (type.type.kind) {
3605
+ case "object": return true;
3606
+ case "array": return complexType(type.type.of);
3607
+ case "union":
3608
+ case "tuple": {
3609
+ const { items } = type.type;
3610
+ return items.length > 0 && items.every((item) => complexType(item));
3611
+ }
3612
+ default: return false;
3613
+ }
3614
+ }
3615
+ /** Whether `type` has sub-paths: an object, an array, a complex type with a complex item. */ function complexType(type, seen = /* @__PURE__ */ new Set()) {
3616
+ const { kind } = type.type;
3617
+ if (kind === "object" || kind === "array") return true;
3618
+ if (kind === "" || seen.has(type.type)) return false;
3619
+ seen.add(type.type);
3620
+ return type.type.items.some((item) => complexType(item, seen));
3621
+ }
3622
+ /**
3623
+ * The definition rendered as the TS type of a leaf path written as `defs` (see
3624
+ * `flatDefinitions`): the prop's type as written (a named type stays named), its resolved
3625
+ * definition when that is a union or tuple of another declaration, the union of them when
3626
+ * several fields meet at the path.
3627
+ */ function flatTypeDef(defs) {
3628
+ if (defs.length > 1) return new SemanticGroup(defs.map((d) => d.def), "|");
3629
+ const [only] = defs;
3630
+ const written = only?.prop.getDefinition();
3631
+ return written && !(isGroup(only.def) && only.def !== written) ? written : only?.def;
3632
+ }
3633
+ function renderPrimitiveTypeDef(def) {
3634
+ if (!def) return "unknown";
3635
+ if (typeof def === "string") return def === "void" ? "undefined" : def;
3636
+ switch (def.kind) {
3637
+ case "final": return def.value === "void" ? "undefined" : def.value;
3638
+ case "union": return def.items.map(renderPrimitiveTypeDef).join(" | ");
3639
+ case "intersection": return def.items.map((item) => typeof item === "object" && item.kind === "union" ? `(${renderPrimitiveTypeDef(item)})` : renderPrimitiveTypeDef(item)).join(" & ");
3640
+ case "tuple": return `[${def.items.map(renderPrimitiveTypeDef).join(", ")}]`;
3641
+ case "array": {
3642
+ const of = renderPrimitiveTypeDef(def.of);
3643
+ return typeof def.of === "object" && (def.of.kind === "union" || def.of.kind === "intersection") ? `(${of})[]` : `${of}[]`;
3644
+ }
3645
+ case "object": return `{ ${Object.entries(def.props).map(([key, val]) => `${wrapProp(key)}${typeof val === "object" && val.optional ? "?" : ""}: ${renderPrimitiveTypeDef(val)}`).join("; ")} }`;
3646
+ default: return "unknown";
3647
+ }
3648
+ }
3649
+
3650
+ //#endregion
3651
+ //#region packages/typescript/src/plugin.ts
3652
+ /**
3653
+ * Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
3654
+ * (used by `unplugin-atscript`'s `compileValidators` option): `'js:compiled'` compiles
3655
+ * every type; `'js:interpreted'` compiles none — `@emit.compiledValidator` included (a
3656
+ * forced-interpreted build, e.g. a browser bundle).
3657
+ */ const JS_COMPILED_FORMAT = "js:compiled";
3658
+ const JS_INTERPRETED_FORMAT = "js:interpreted";
3659
+ /** The JS render formats, with the compiled-validator mode each one forces (if any). */ const JS_FORMATS = new Map([
3660
+ ["js", void 0],
3661
+ [JS_COMPILED_FORMAT, "all"],
3662
+ [JS_INTERPRETED_FORMAT, "none"]
3663
+ ]);
3664
+ /** The compiled-validator mode of a JS render `format` (see {@link TCompileValidatorsMode}). */ function compileValidatorsMode(format, opts) {
3665
+ return JS_FORMATS.get(format) ?? (opts?.compileValidators ? "all" : "annotated");
3666
+ }
3667
+ /**
3668
+ * Resolves the effective JSON schema mode from plugin options.
3669
+ */ function resolveJsonSchemaMode(opts) {
3670
+ if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
3671
+ return false;
3672
+ }
3673
+ /** A generated JS module of `doc`, checked to load in a build (see `assertLoads`). */ function renderJs(doc, opts, mode, loadCheck) {
3674
+ const content = rendererOf(doc, opts, mode).render();
3675
+ assertLoads(doc, opts, mode, loadCheck);
3676
+ return content;
3677
+ }
3678
+ const tsPlugin = (opts) => {
3679
+ return {
3680
+ name: "typescript",
3681
+ render(doc, format, options) {
3682
+ if (format === "dts" || format === DEFAULT_FORMAT) return [{
3683
+ fileName: `${doc.name}.d.ts`,
3684
+ content: new TypeRenderer(doc, opts).render()
3685
+ }];
3686
+ if (JS_FORMATS.has(format)) return [{
3687
+ fileName: `${doc.name}.js`,
3688
+ content: renderJs(doc, opts, compileValidatorsMode(format, opts), options?.loadCheck)
3689
+ }];
3690
+ },
3691
+ async buildEnd(output, format, repo) {
3692
+ if (format === "dts" || format === DEFAULT_FORMAT) {
3693
+ const annotations = await repo.getUsedAnnotations();
3694
+ const tags = await repo.getPrimitivesTags() || /* @__PURE__ */ new Set();
3695
+ const rendered = [];
3696
+ for (const [key, val] of Object.entries(annotations)) {
3697
+ const multiple = val.multiple;
3698
+ const typeLine = Array.from(val.types).map((t) => {
3699
+ if (t.type === "object" && "props" in t) return `{ ${Object.entries(t.props).map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
3700
+ else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
3701
+ }).join(" | ");
3702
+ rendered.push(`${wrapProp(key)}: ${multiple ? "(" : ""}${typeLine}${multiple ? ")[]" : ""}`);
3703
+ }
3704
+ const renderedTags = Array.from(tags).map((f) => `"${escapeQuotes(f)}"`).join(" | ");
3705
+ output.push({
3706
+ content: "// prettier-ignore-start\n/* eslint-disable */\n/* oxlint-disable */\n/**\n * 🪄 This file was generated by Atscript\n * It is generated based on annotations used in this project\n * Do not edit this file!\n *\n * Use `npx asc -f dts` command to re-generate this file\n */\nexport {}\n\ndeclare global {\n interface AtscriptMetadata {\n " + rendered.join("\n ") + "\n }\n type AtscriptPrimitiveTags = " + renderedTags + "\n}\n// prettier-ignore-end",
3707
+ fileName: "atscript.d.ts",
3708
+ source: "",
3709
+ target: path.join(repo.root, "atscript.d.ts")
3710
+ });
3711
+ }
3712
+ }
3713
+ };
3714
+ };
3715
+
3716
+ //#endregion
3717
+ export { withLoadCheck as a, importCycle as i, JS_INTERPRETED_FORMAT as n, tsPlugin as r, JS_COMPILED_FORMAT as t };