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