@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.
@@ -1,2483 +0,0 @@
1
- import { A as D_UNKNOWN, B as LAYOUT_VERSION, C as D_ARRAY, D as D_OBJECT_PATTERNS, E as D_OBJECT, F as F_PARTIAL_TOP, G as keySlots, H as STRING_BITS, I as F_STRIP, J as siteSlotCount, K as readKeys, L as F_TOP, M as F_ERROR, N as F_IN_UNION, O as D_TUPLE, P as F_PARTIAL_DEEP, R as INTERP, S as B_UNIQUE, T as D_INTERSECTION, U as childSites, V as NUMBER_BITS, W as hasRejectSlot, X as isValidatorKey, _ as getRegex, b as B_INT, d as defineAnnotatedType, j as EXT, k as D_UNION, o as annotate, q as siteBits, s as cloneRefProp, t as buildJsonSchema, w as D_FINAL, x as B_REQUIRED, y as ARRAY_BITS, z as ITEMS_KIND_CODES } from "./json-schema-BG1SEcjI.mjs";
2
- import path from "path";
3
- import { DEFAULT_FORMAT, flattenInterfaceNode, getRelPath, hasNavPropAnnotation, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isPrimitive, isProp, isQueryLogical, isRef, isStructure } from "@atscript/core";
4
-
5
- //#region packages/typescript/src/codegen/code-printer.ts
6
- function _define_property$5(obj, key, value) {
7
- if (key in obj) Object.defineProperty(obj, key, {
8
- value,
9
- enumerable: true,
10
- configurable: true,
11
- writable: true
12
- });
13
- else obj[key] = value;
14
- return obj;
15
- }
16
- var CodePrinter = class {
17
- /**
18
- * Write text with NO automatic newline.
19
- * If current line is empty, we prepend indentation.
20
- */ write(...text) {
21
- if (!this.currentLine) this.currentLine = this.indentString();
22
- this.currentLine += text.join("");
23
- return this;
24
- }
25
- /**
26
- * Write text and then finalize this line with a newline.
27
- * Implemented by calling `write(...)` + push line + reset `currentLine`.
28
- */ writeln(...text) {
29
- this.write(...text);
30
- this.lines.push(this.currentLine);
31
- this.currentLine = "";
32
- return this;
33
- }
34
- /**
35
- * Open a block with an opening/closing pair, e.g. "{}" or "()".
36
- * By default, places the opening delimiter on the current line (no extra newline).
37
- */ block(pair) {
38
- return this.doBlock(pair, false);
39
- }
40
- /**
41
- * Same as `block()`, but adds a newline after writing the opening delimiter.
42
- */ blockln(pair) {
43
- return this.doBlock(pair, true);
44
- }
45
- /**
46
- * Close the most recent block. By default, closing delimiter goes on the current line.
47
- */ pop() {
48
- return this.doPop(false);
49
- }
50
- /**
51
- * Same as `pop()`, but puts the closing delimiter on a new line.
52
- */ popln() {
53
- return this.doPop(true);
54
- }
55
- /**
56
- * Increase indentation by one level.
57
- */ indent() {
58
- this.indentLevel++;
59
- return this;
60
- }
61
- /**
62
- * Decrease indentation by one level (never below 0).
63
- */ unindent() {
64
- this.indentLevel = Math.max(0, this.indentLevel - 1);
65
- return this;
66
- }
67
- render() {
68
- return this.toString();
69
- }
70
- /**
71
- * Return the entire code as a string. Removes any half-finished current line if empty.
72
- */ toString() {
73
- if (this.currentLine.trim() !== "") this.lines.push(this.currentLine);
74
- else if (this.currentLine.length > 0) this.lines.push(this.currentLine);
75
- return this.lines.join("\n");
76
- }
77
- doBlock(pair, withNewLine) {
78
- if (pair.length < 2) throw new Error(`Block pair must have at least 2 chars, e.g. "{}" or "()". Got "${pair}"`);
79
- const opening = pair[0];
80
- const closing = pair[pair.length - 1];
81
- this.write(opening);
82
- this.blockStack.push(closing);
83
- if (withNewLine) this.writeln();
84
- this.indent();
85
- return this;
86
- }
87
- doPop(withNewLine) {
88
- if (this.blockStack.length === 0) throw new Error("No block to pop (stack is empty).");
89
- const closing = this.blockStack.pop();
90
- this.unindent();
91
- if (withNewLine) this.writeln(closing);
92
- else this.write(closing);
93
- return this;
94
- }
95
- indentString() {
96
- return " ".repeat(this.indentLevel * this.indentSize);
97
- }
98
- constructor() {
99
- _define_property$5(this, "lines", []);
100
- _define_property$5(this, "currentLine", "");
101
- _define_property$5(this, "indentLevel", 0);
102
- _define_property$5(this, "indentSize", 2);
103
- _define_property$5(this, "blockStack", []);
104
- }
105
- };
106
-
107
- //#endregion
108
- //#region packages/typescript/src/codegen/base-renderer.ts
109
- function _define_property$4(obj, key, value) {
110
- if (key in obj) Object.defineProperty(obj, key, {
111
- value,
112
- enumerable: true,
113
- configurable: true,
114
- writable: true
115
- });
116
- else obj[key] = value;
117
- return obj;
118
- }
119
- var BaseRenderer = class extends CodePrinter {
120
- get unused() {
121
- return this._unused ?? (this._unused = new Set(this.doc.getUnusedTokens().map((t) => t.text)));
122
- }
123
- pre() {}
124
- post() {}
125
- render() {
126
- this.pre();
127
- for (const node of this.doc.nodes) this.renderNode(node);
128
- this.post();
129
- return this.toString();
130
- }
131
- renderInterface(node) {}
132
- renderType(node) {}
133
- renderAnnotate(node) {}
134
- transformFromPath(path) {
135
- return `${path}.as`;
136
- }
137
- renderImport(node) {
138
- const def = node.getDefinition();
139
- const refs = [];
140
- const from = this.transformFromPath(node.token("path").text);
141
- let isUnusedImport = true;
142
- if (isGroup(def)) {
143
- for (const child of def.unwrap()) if (isRef(child) && !this.unused.has(child.id)) {
144
- const node = child;
145
- refs.push(node.id);
146
- isUnusedImport = false;
147
- }
148
- } else if (isRef(def) && !this.unused.has(def.id)) {
149
- refs.push(def.id);
150
- isUnusedImport = false;
151
- }
152
- if (!isUnusedImport) this.writeln(`import { ${refs.join(", ")} } from "${from}"`);
153
- }
154
- renderNode(node) {
155
- switch (node.entity) {
156
- case "interface":
157
- this.renderInterface(node);
158
- break;
159
- case "type":
160
- this.renderType(node);
161
- break;
162
- case "import":
163
- this.renderImport(node);
164
- break;
165
- case "annotate":
166
- this.renderAnnotate(node);
167
- break;
168
- default: break;
169
- }
170
- }
171
- constructor(doc) {
172
- super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
173
- }
174
- };
175
-
176
- //#endregion
177
- //#region packages/typescript/src/codegen/utils.ts
178
- const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
179
- /**
180
- * Wraps a property name in double quotes if it's not a valid identifier (contains special chars, etc.).
181
- *
182
- * Examples:
183
- * - "validName" => "validName"
184
- * - "some-prop" => "\"some-prop\""
185
- */ function wrapProp(name) {
186
- if (!validIdentifier.test(name)) return `"${escapeQuotes(name)}"`;
187
- return name;
188
- }
189
- function escapeQuotes(str) {
190
- return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
191
- }
192
-
193
- //#endregion
194
- //#region packages/typescript/src/codegen/type-renderer.ts
195
- function _define_property$3(obj, key, value) {
196
- if (key in obj) Object.defineProperty(obj, key, {
197
- value,
198
- enumerable: true,
199
- configurable: true,
200
- writable: true
201
- });
202
- else obj[key] = value;
203
- return obj;
204
- }
205
- var TypeRenderer = class TypeRenderer extends BaseRenderer {
206
- pre() {
207
- this.writeln("// prettier-ignore-start");
208
- this.writeln("/* eslint-disable */");
209
- this.writeln("/* oxlint-disable */");
210
- this.writeln(`/// <reference path="./${this.doc.name}" />`);
211
- this.writeln("/**");
212
- this.writeln(" * 🪄 This file was generated by Atscript");
213
- this.writeln(" * Do not edit this file!");
214
- this.writeln(" */");
215
- this.writeln();
216
- this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from \"@atscript/typescript/utils\"");
217
- }
218
- post() {
219
- this.writeln("// prettier-ignore-end");
220
- }
221
- renderTypeDefString(def) {
222
- const newThis = new TypeRenderer(this.doc, this.opts);
223
- newThis.renderTypeDef(def);
224
- return newThis.toString();
225
- }
226
- renderTypeDef(def) {
227
- if (!def) {
228
- this.write("unknown");
229
- return;
230
- }
231
- if (isStructure(def)) return this.renderStructure(def);
232
- if (isGroup(def)) {
233
- const tuple = def.entity === "tuple";
234
- const operator = tuple ? ", " : ` ${def.op} `;
235
- const children = def.unwrap();
236
- const hasSubgroup = !tuple && children.some((c) => c.entity === "group");
237
- this.write(tuple ? "[" : hasSubgroup ? "(" : "");
238
- this.renderTypeDef(def.first);
239
- for (const child of children.slice(1)) {
240
- this.write(operator);
241
- this.renderTypeDef(child);
242
- }
243
- return this.write(tuple ? "]" : hasSubgroup ? ")" : "");
244
- }
245
- if (isConst(def)) {
246
- const name = def.token("identifier")?.type === "number" ? def.id : `"${escapeQuotes(def.id)}"`;
247
- return this.write(name);
248
- }
249
- if (isRef(def)) {
250
- const node = def;
251
- const unwound = this.doc.unwindType(node.id, node.chain);
252
- if (isPrimitive(unwound?.def)) {
253
- this.write(renderPrimitiveTypeDef(unwound.def.config.type));
254
- if (node.hasChain) this.write(` /* ${node.chain.map((c) => c.text).join(".")} */`);
255
- return;
256
- }
257
- let name = node.id;
258
- for (const c of node.chain) name += `["${escapeQuotes(c.text)}"]`;
259
- return this.write(name);
260
- }
261
- if (isArray(def)) {
262
- const def2 = def.getDefinition();
263
- const isGrp = def2?.entity === "group";
264
- if (isGrp) this.write("(");
265
- this.renderTypeDef(def2);
266
- if (isGrp) this.write(")");
267
- return this.write("[]");
268
- }
269
- if (isPrimitive(def)) return this.write(renderPrimitiveTypeDef(def.config.type));
270
- }
271
- renderStructure(struct, asClass, interfaceNode, filterProps) {
272
- this.blockln("{}");
273
- const patterns = [];
274
- const propsDefs = /* @__PURE__ */ new Set();
275
- for (const prop of struct.props.values()) {
276
- if (filterProps?.has(prop.id)) continue;
277
- if (prop.token("identifier")?.pattern) {
278
- if (!filterProps) patterns.push(prop);
279
- continue;
280
- }
281
- const phantomType = this.phantomPropType(prop.getDefinition());
282
- if (phantomType) {
283
- this.writeln(`// ${prop.id}: ${phantomType}`);
284
- continue;
285
- }
286
- const optional = !!prop.token("optional");
287
- this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
288
- const renderedDef = this.renderTypeDefString(prop.getDefinition());
289
- propsDefs.add(renderedDef);
290
- renderedDef.split("\n").forEach((l) => this.writeln(l));
291
- }
292
- if (patterns.length > 0) {
293
- this.write(`[key: string]: `);
294
- for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
295
- const defs = Array.from(propsDefs);
296
- if (defs.length > 1) {
297
- this.indent();
298
- for (const def of defs) {
299
- this.writeln();
300
- this.write("| ");
301
- def.split("\n").forEach((l) => this.write(l.trim()));
302
- }
303
- this.unindent();
304
- this.writeln();
305
- } else defs[0].split("\n").forEach((l) => this.writeln(l));
306
- }
307
- if (asClass) this.renderStaticDeclarations(asClass, interfaceNode);
308
- this.pop();
309
- }
310
- renderStaticDeclarations(asClass, interfaceNode) {
311
- this.writeln("static __is_atscript_annotated_type: true");
312
- this.writeln(`static type: TAtscriptTypeObject<keyof ${asClass}, ${asClass}>`);
313
- this.writeln(`static metadata: TMetadataMap<AtscriptMetadata>`);
314
- this.writeln(`static validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${asClass}>`);
315
- 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. */");
316
- this.writeln("static toJsonSchema: () => any");
317
- if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
318
- this.writeln("static toExampleData?: () => any");
319
- if (interfaceNode && isDbEntityNode(interfaceNode)) {
320
- this.renderFlat(interfaceNode);
321
- this.renderOwnProps(interfaceNode);
322
- this.renderNavProps(interfaceNode);
323
- this.renderPk(interfaceNode);
324
- this.renderDimMeasure(interfaceNode);
325
- }
326
- }
327
- renderInterface(node) {
328
- this.writeln();
329
- const exported = node.token("export")?.text === "export";
330
- this.renderJsDoc(node);
331
- this.write(exported ? "export declare " : "declare ");
332
- if (node.hasExtends) {
333
- const firstParent = node.extendsTokens[0].text;
334
- this.write(`class ${node.id} extends ${firstParent} `);
335
- const resolved = this.doc.resolveInterfaceExtends(node);
336
- if (resolved?.entity === "structure") {
337
- const firstParentUnwound = this.doc.unwindType(firstParent);
338
- let firstParentProps;
339
- if (firstParentUnwound?.def) {
340
- let fpDef = firstParentUnwound.def;
341
- if (isInterface(fpDef)) {
342
- if (fpDef.hasExtends) {
343
- const fpResolved = firstParentUnwound.doc.resolveInterfaceExtends(fpDef);
344
- if (fpResolved && isStructure(fpResolved)) firstParentProps = fpResolved.props;
345
- }
346
- if (!firstParentProps) fpDef = fpDef.getDefinition() || fpDef;
347
- }
348
- if (!firstParentProps && isStructure(fpDef)) firstParentProps = fpDef.props;
349
- }
350
- this.renderStructure(resolved, node.id, node, firstParentProps);
351
- } else this.writeln("{}");
352
- } else {
353
- this.write(`class ${node.id} `);
354
- const struct = node.getDefinition();
355
- if (struct?.entity === "structure") this.renderStructure(struct, node.id, node);
356
- else this.writeln("{}");
357
- }
358
- this.writeln();
359
- }
360
- renderType(node) {
361
- this.writeln();
362
- const exported = node.token("export")?.text === "export";
363
- this.renderJsDoc(node);
364
- this.write(exported ? "export " : "declare ");
365
- this.write(`type ${node.id} = `);
366
- this.renderTypeDef(node.getDefinition());
367
- this.writeln();
368
- this.renderTypeNamespace(node);
369
- }
370
- renderAnnotate(node) {
371
- if (node.isMutating) return;
372
- const targetName = node.targetName;
373
- this.writeln();
374
- const exported = node.token("export")?.text === "export";
375
- this.renderJsDoc(node);
376
- if (this.isTypeTarget(targetName)) {
377
- this.write(exported ? "export " : "declare ");
378
- this.write(`type ${node.id} = ${targetName}`);
379
- this.writeln();
380
- const unwound = this.doc.unwindType(targetName);
381
- this.renderTypeNamespaceFor(node.id, unwound?.def);
382
- } else {
383
- this.write(exported ? "export declare " : "declare ");
384
- this.writeln(`class ${node.id} extends ${targetName} {}`);
385
- }
386
- }
387
- renderTypeNamespace(node) {
388
- this.renderTypeNamespaceFor(node.id, node.getDefinition());
389
- }
390
- renderTypeNamespaceFor(name, inputDef) {
391
- this.write(`declare namespace ${name} `);
392
- this.blockln("{}");
393
- let typeDef = "TAtscriptTypeDef";
394
- if (inputDef) {
395
- let realDef = inputDef;
396
- if (isRef(inputDef)) realDef = this.doc.unwindType(inputDef.id, inputDef.chain)?.def || realDef;
397
- realDef = this.doc.mergeIntersection(realDef);
398
- if (isStructure(realDef) || isInterface(realDef)) typeDef = `TAtscriptTypeObject<keyof ${name}, ${name}>`;
399
- else if (isGroup(realDef)) typeDef = `TAtscriptTypeComplex<${name}>`;
400
- else if (isArray(realDef)) typeDef = `TAtscriptTypeArray<${name}>`;
401
- else if (isPrimitive(realDef)) typeDef = `TAtscriptTypeFinal<${name}>`;
402
- }
403
- this.writeln(`const __is_atscript_annotated_type: true`);
404
- this.writeln(`const type: ${typeDef}`);
405
- this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
406
- this.writeln(`const validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${name}>`);
407
- 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. */");
408
- this.writeln("const toJsonSchema: () => any");
409
- if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
410
- this.writeln("const toExampleData: (() => any) | undefined");
411
- this.popln();
412
- }
413
- /**
414
- * Renders the `static __flat` property — a map of all dot-notation paths
415
- * to their TypeScript value types.
416
- *
417
- * This enables type-safe autocomplete for filter keys and `$select`/`$sort`
418
- * paths when using `AtscriptDbTable`. The `FlatOf<T>` utility type extracts
419
- * this map at the type level.
420
- *
421
- * Special rendering rules:
422
- * - **Intermediate paths** (structures, arrays of structures) → `never`
423
- * (prevents `$eq` comparisons, but allows `$select` and `$exists`)
424
- * - **`@db.json` fields** → `string` (stored as serialized JSON in DB,
425
- * not individually queryable)
426
- * - **Leaf fields** → their original TypeScript type
427
- */ renderFlat(node) {
428
- this.renderFlatMap("__flat", flattenInterfaceNode(this.doc, node));
429
- }
430
- /**
431
- * Renders the `static __ownProps` property — table-owned fields only (no nav props).
432
- */ renderOwnProps(node) {
433
- this.renderFlatMap("__ownProps", flattenInterfaceNode(this.doc, node, { skipNavProps: true }), {
434
- leadingNewline: true,
435
- trailingNewline: true
436
- });
437
- }
438
- /**
439
- * Shared renderer for flat-map static properties (`__flat`, `__ownProps`).
440
- *
441
- * Special rendering rules:
442
- * - **Intermediate paths** (structures, arrays of structures) → `never`
443
- * - **`@db.json` fields** → `string` (stored as serialized JSON in DB)
444
- * - **Leaf fields** → their original TypeScript type
445
- * - **Optional leaf / `@db.json` fields** → `<type> | null` — the DB layer treats
446
- * optional as nullable in filters, so `null` must be assignable to the path's type
447
- */ renderFlatMap(propName, flatMap, opts) {
448
- if (flatMap.size === 0) return;
449
- if (opts?.leadingNewline) this.writeln();
450
- this.write(`static ${propName}: `);
451
- this.blockln("{}");
452
- for (const [path, descriptor] of flatMap) {
453
- this.write(`"${escapeQuotes(path)}"`);
454
- if (descriptor.optional) this.write("?");
455
- this.write(": ");
456
- const nullable = descriptor.optional ? " | null" : "";
457
- if (descriptor.intermediate) this.writeln("never");
458
- else if (descriptor.dbJson) this.writeln(`string${nullable}`);
459
- else {
460
- const originalDef = descriptor.propNode?.getDefinition();
461
- const defToRender = originalDef && !(isGroup(descriptor.def) && descriptor.def !== originalDef) ? originalDef : descriptor.def;
462
- const lines = this.renderTypeDefString(defToRender).split("\n");
463
- lines[lines.length - 1] += nullable;
464
- lines.forEach((l) => this.writeln(l));
465
- }
466
- }
467
- if (opts?.trailingNewline) this.popln();
468
- else this.pop();
469
- }
470
- /**
471
- * Renders the `static __navProps` property — a map of navigation property names
472
- * to their declared TypeScript types.
473
- *
474
- * This enables type-safe `$with` in queries: `name` is constrained to known
475
- * navigation property keys, and nested filter/controls are typed to the target entity.
476
- */ renderNavProps(node) {
477
- let struct;
478
- if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
479
- if (!struct) struct = node.getDefinition();
480
- if (!struct || !isStructure(struct)) return;
481
- const structNode = struct;
482
- const navProps = [];
483
- for (const [name, prop] of structNode.props) {
484
- if (prop.token("identifier")?.pattern) continue;
485
- if (hasNavPropAnnotation(prop)) navProps.push({
486
- name,
487
- prop
488
- });
489
- }
490
- if (navProps.length === 0) return;
491
- this.writeln();
492
- this.write("static __navProps: ");
493
- this.blockln("{}");
494
- for (const { name, prop } of navProps) {
495
- this.write(`"${escapeQuotes(name)}"`);
496
- if (prop.token("optional")) this.write("?");
497
- this.write(": ");
498
- const propDef = prop.getDefinition();
499
- if (propDef) this.renderTypeDefString(propDef).split("\n").forEach((l) => this.writeln(l));
500
- else this.writeln("unknown");
501
- }
502
- this.popln();
503
- }
504
- renderPk(node) {
505
- const isMongoCollection = !!node.annotations?.some((a) => a.name === "db.mongo.collection");
506
- let struct;
507
- if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
508
- if (!struct) struct = node.getDefinition();
509
- if (!struct || !isStructure(struct)) return;
510
- const structNode = struct;
511
- const pkProps = [];
512
- const uniqueByIndex = /* @__PURE__ */ new Map();
513
- for (const [name, prop] of structNode.props) {
514
- if (prop.token("identifier")?.pattern) continue;
515
- if (isMongoCollection && name === "_id") continue;
516
- if (prop.countAnnotations("meta.id") > 0) pkProps.push({
517
- name,
518
- prop
519
- });
520
- if (prop.annotations) {
521
- for (const ann of prop.annotations) if (ann.name === "db.index.unique") {
522
- const indexName = ann.args[0]?.text ?? name;
523
- let group = uniqueByIndex.get(indexName);
524
- if (!group) {
525
- group = [];
526
- uniqueByIndex.set(indexName, group);
527
- }
528
- group.push({
529
- name,
530
- prop
531
- });
532
- }
533
- }
534
- }
535
- const uniqueProps = [];
536
- const pkNames = new Set(pkProps.map((p) => p.name));
537
- for (const fields of uniqueByIndex.values()) if (fields.length === 1 && !pkNames.has(fields[0].name)) uniqueProps.push(fields[0]);
538
- if (pkProps.length === 0 && uniqueProps.length === 0 && !isMongoCollection) return;
539
- let mongoIdType;
540
- if (isMongoCollection) {
541
- const idProp = structNode.props.get("_id");
542
- if (idProp) mongoIdType = this.renderTypeDefString(idProp.getDefinition()).trim();
543
- mongoIdType ?? (mongoIdType = "string");
544
- }
545
- const uniqueTypes = [];
546
- const seenTypes = /* @__PURE__ */ new Set();
547
- for (const { prop } of uniqueProps) {
548
- const rendered = this.renderTypeDefString(prop.getDefinition()).trim();
549
- if (!seenTypes.has(rendered)) {
550
- seenTypes.add(rendered);
551
- uniqueTypes.push(rendered);
552
- }
553
- }
554
- this.writeln();
555
- const uniqueSuffix = uniqueTypes.length > 0 ? ` | ${uniqueTypes.join(" | ")}` : "";
556
- if (pkProps.length === 0 && !isMongoCollection) this.writeln(`static __pk: ${uniqueTypes.join(" | ")}`);
557
- else if (pkProps.length === 0) this.writeln(`static __pk: ${mongoIdType}${uniqueSuffix}`);
558
- else if (pkProps.length === 1) {
559
- this.write("static __pk: ");
560
- if (isMongoCollection) this.write(`${mongoIdType} | `);
561
- const renderedDef = this.renderTypeDefString(pkProps[0].prop.getDefinition()).trim();
562
- this.writeln(`${renderedDef}${uniqueSuffix}`);
563
- } else {
564
- this.write("static __pk: ");
565
- if (isMongoCollection) this.write(`${mongoIdType} | `);
566
- this.blockln("{}");
567
- for (const { name, prop } of pkProps) {
568
- this.write(wrapProp(name), ": ");
569
- this.renderTypeDefString(prop.getDefinition()).split("\n").forEach((l) => this.writeln(l));
570
- }
571
- this.pop();
572
- this.writeln(uniqueSuffix);
573
- }
574
- }
575
- renderDimMeasure(node) {
576
- let struct;
577
- if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
578
- if (!struct) struct = node.getDefinition();
579
- if (!struct || !isStructure(struct)) return;
580
- const structNode = struct;
581
- const dims = [];
582
- const measures = [];
583
- for (const [name, prop] of structNode.props) {
584
- if (prop.token("identifier")?.pattern) continue;
585
- if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
586
- if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
587
- }
588
- if (dims.length === 0 && measures.length === 0) return;
589
- this.writeln();
590
- if (dims.length > 0) this.writeln(`static __dim: ${dims.map((d) => `"${escapeQuotes(d)}"`).join(" | ")}`);
591
- if (measures.length > 0) this.writeln(`static __measure: ${measures.map((m) => `"${escapeQuotes(m)}"`).join(" | ")}`);
592
- }
593
- phantomPropType(def) {
594
- if (!def) return;
595
- if (isPrimitive(def) && def.config.type === "phantom") return def.id;
596
- if (isRef(def)) {
597
- const ref = def;
598
- const unwound = this.doc.unwindType(ref.id, ref.chain)?.def;
599
- if (isPrimitive(unwound) && unwound.config.type === "phantom") return ref.hasChain ? `${ref.id}.${ref.chain.map((c) => c.text).join(".")}` : ref.id;
600
- }
601
- }
602
- isTypeTarget(name, doc) {
603
- const decl = (doc || this.doc).getDeclarationOwnerNode(name);
604
- if (!decl?.node) return false;
605
- if (decl.node.entity === "type") return true;
606
- if (decl.node.entity === "interface") return false;
607
- if (decl.node.entity === "annotate") return this.isTypeTarget(decl.node.targetName, decl.doc);
608
- return false;
609
- }
610
- renderJsDoc(node) {
611
- const range = node.token("identifier")?.range;
612
- const rangeStr = range ? `:${range.start.line + 1}:${range.start.character + 1}` : "";
613
- this.writeln(`/**`);
614
- this.writeln(` * Atscript ${node.entity} **${node.id}**`);
615
- this.writeln(` * @see {@link ./${this.doc.name}${rangeStr}}`);
616
- this.writeln(` */`);
617
- }
618
- constructor(doc, opts) {
619
- super(doc), _define_property$3(this, "opts", void 0), this.opts = opts;
620
- }
621
- };
622
- function renderPrimitiveTypeDef(def) {
623
- if (!def) return "unknown";
624
- if (typeof def === "string") return def === "void" ? "undefined" : def;
625
- switch (def.kind) {
626
- case "final": return def.value === "void" ? "undefined" : def.value;
627
- case "union": return def.items.map(renderPrimitiveTypeDef).join(" | ");
628
- case "intersection": return def.items.map(renderPrimitiveTypeDef).join(" & ");
629
- case "tuple": return `[${def.items.map(renderPrimitiveTypeDef).join(", ")}]`;
630
- case "array": return `${renderPrimitiveTypeDef(def.of)}[]`;
631
- case "object": return `{ ${Object.entries(def.props).map(([key, val]) => `${wrapProp(key)}${typeof val === "object" && val.optional ? "?" : ""}: ${renderPrimitiveTypeDef(val)}`).join("; ")} }`;
632
- default: return "unknown";
633
- }
634
- }
635
-
636
- //#endregion
637
- //#region packages/typescript/src/runtime/compiled-check/build-layout.ts
638
- /**
639
- * Build-time layout derivation (renderer and tests; not part of the runtime bundle).
640
- */
641
- /**
642
- * Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
643
- * once and referenced by index.
644
- */ function buildLayout(root, reader, classify) {
645
- const defs = [];
646
- const index = /* @__PURE__ */ new Map();
647
- let slots = 0;
648
- function describeDef(type) {
649
- switch (type.kind) {
650
- case "": return type.value === void 0 ? [D_FINAL, type.designType] : [
651
- D_FINAL,
652
- type.designType,
653
- type.value
654
- ];
655
- case "object": {
656
- if (type.propsPatterns.length > 0) return [D_OBJECT_PATTERNS];
657
- const props = [...type.props];
658
- return [
659
- D_OBJECT,
660
- props.map(([key]) => key),
661
- props.map(([, prop]) => site(prop))
662
- ];
663
- }
664
- case "array": return [D_ARRAY, site(type.of)];
665
- case "union":
666
- case "intersection":
667
- case "tuple": return [ITEMS_KIND_CODES[type.kind], type.items.map(site)];
668
- default: return [D_UNKNOWN, String(type.kind)];
669
- }
670
- }
671
- function site(node) {
672
- const type = node.type;
673
- const marker = classify?.(type);
674
- const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
675
- let d;
676
- let keys = {
677
- mask: 0,
678
- shape: ""
679
- };
680
- if (marker === "interp") d = INTERP;
681
- else if (marker === "ext") {
682
- d = EXT;
683
- keys = readKeys(node.metadata, siteBits(void 0, optional === 1), reader);
684
- } else {
685
- d = index.get(type) ?? -1;
686
- if (d < 0) {
687
- d = defs.length;
688
- defs.push([]);
689
- index.set(type, d);
690
- defs[d] = describeDef(type);
691
- }
692
- keys = readKeys(node.metadata, siteBits(type, optional === 1), reader);
693
- }
694
- const result = [
695
- optional,
696
- keys.mask,
697
- d,
698
- keys.shape,
699
- slots
700
- ];
701
- slots += siteSlotCount(result);
702
- return result;
703
- }
704
- return [
705
- defs,
706
- site(root),
707
- slots
708
- ];
709
- }
710
- /** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
711
- if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
712
- return literalSource(value);
713
- }
714
- /** JS source of a primitive literal. */ function literalSource(value) {
715
- if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
716
- if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
717
- if (value === void 0) return "undefined";
718
- return JSON.stringify(value);
719
- }
720
-
721
- //#endregion
722
- //#region packages/typescript/src/runtime/compiled-check/emit.ts
723
- /**
724
- * Emits the JS source of a compiled validator check factory from its layout.
725
- *
726
- * Build-time only (the renderer, and test code): the runtime never generates code. The
727
- * emitted factory `(K, H) => check` mirrors the interpreted pre-check
728
- * (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
729
- * FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
730
- * def and per def that closes a reference cycle, everything else inlined.
731
- *
732
- * Generated code conventions:
733
- * - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
734
- * see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
735
- * - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
736
- * union (where failures must visit everything the walk would) it records the failure and
737
- * jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
738
- * runtime flags tell. BAIL is always `return 2`.
739
- * - Annotation values are closure constants `k<slot>` read from `K` once per bind.
740
- */ function _define_property$2(obj, key, value) {
741
- if (key in obj) Object.defineProperty(obj, key, {
742
- value,
743
- enumerable: true,
744
- configurable: true,
745
- writable: true
746
- });
747
- else obj[key] = value;
748
- return obj;
749
- }
750
- const ROOT_CTX = {
751
- fail: "return 0",
752
- inUnionFail: "return 0",
753
- union: false,
754
- clearTop: false
755
- };
756
- /** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
757
- ["pk", /\bpk\./],
758
- ["ho", /\bho\.call\(/],
759
- ["dec", /\bdec\.test\(/],
760
- ["rn", /\brn\(/]
761
- ];
762
- /** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
763
- return new CheckEmitter(layout).emit();
764
- }
765
- let CheckEmitter = class CheckEmitter {
766
- emit() {
767
- const body = [];
768
- for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
769
- const root = this.layout[1];
770
- const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
771
- if (root[0] === 0 && this.fn[root[2]] && (rootDef === D_OBJECT || rootDef === D_OBJECT_PATTERNS || rootDef === D_TUPLE || rootDef === D_INTERSECTION)) body.push(`return d${root[2]}`);
772
- else {
773
- body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
774
- body.push("return r");
775
- }
776
- const code = body.join("\n");
777
- const head = [];
778
- const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
779
- if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
780
- const slots = [...new Set(Array.from(code.matchAll(/\bk(\d+)\b/g), (m) => Number(m[1])))].filter((k) => k < this.layout[2]).sort((a, b) => a - b);
781
- for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
782
- return [
783
- "(K, H) => {",
784
- ...indent([...head, ...body]),
785
- "}"
786
- ].join("\n");
787
- }
788
- /**
789
- * Object defs get a function each; so does every def a reference cycle passes through
790
- * (each back-edge target of a DFS), which keeps inlining finite.
791
- */ functionDefs() {
792
- const defs = this.defs;
793
- const fn = defs.map((def) => def[0] === D_OBJECT || def[0] === D_OBJECT_PATTERNS);
794
- const state = Array.from({ length: defs.length }).fill(0);
795
- const dfs = (d) => {
796
- state[d] = 1;
797
- for (const site of childSites(defs[d])) {
798
- const c = site[2];
799
- if (c < 0) continue;
800
- if (state[c] === 1) fn[c] = true;
801
- else if (state[c] === 0) dfs(c);
802
- }
803
- state[d] = 2;
804
- };
805
- for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
806
- return fn;
807
- }
808
- next(prefix) {
809
- return `${prefix}${this.uid++}`;
810
- }
811
- /** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
812
- const lines = body();
813
- const code = lines.join("\n");
814
- const locals = [];
815
- if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${F_IN_UNION}) === 0`);
816
- if (/\bt = /.test(code)) locals.push("let t");
817
- return [
818
- `function ${name}(v, f, o) {`,
819
- ...indent([...locals, ...lines]),
820
- "}"
821
- ];
822
- }
823
- defFunction(d) {
824
- const def = this.defs[d];
825
- return this.fnLines(`d${d}`, () => {
826
- switch (def[0]) {
827
- case D_OBJECT: return this.objectBody(def);
828
- case D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
829
- case D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
830
- case D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
831
- case D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
832
- case D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
833
- default: return ["return 2"];
834
- }
835
- });
836
- }
837
- /** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
838
- const sites = def[2];
839
- const props = def[1].map((key, i) => ({
840
- key,
841
- site: sites[i]
842
- })).filter((p) => !this.isPhantom(p.site));
843
- const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
844
- if (props.some((p) => p.site[0] === 0 || p.site[2] === INTERP)) {
845
- const top = F_PARTIAL_TOP | F_TOP;
846
- lines.push(`const sk = (f & ${F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
847
- }
848
- if (props.length > 0) lines.push("let r = 1");
849
- for (const { key, site } of props) {
850
- const p = this.next("P");
851
- const x = this.next("x");
852
- const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
853
- lines.push(`${p}: {`, ` const ${x} = ${access}`);
854
- if (site[0] === 0 || site[2] === INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
855
- const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
856
- lines.push(...indent(this.site(site, x, ctx)), "}");
857
- }
858
- if (props.length > 0) lines.push("if (r === 0) return 0");
859
- const known = props.map((p) => p.key);
860
- const onUnknown = `{ if ((f & ${F_ERROR}) !== 0) return 0; if ((f & ${F_TOP}) === 0) return 2; pk.push(k) }`;
861
- const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
862
- "for (const k in v) {",
863
- " switch (k) {",
864
- ...known.map((key) => ` case ${literalSource(key)}:`),
865
- " break",
866
- " default:",
867
- ` if (ho.call(v, k)) ${onUnknown}`,
868
- " }",
869
- "}"
870
- ];
871
- lines.push(`if ((f & ${F_ERROR | F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
872
- return lines;
873
- }
874
- isPhantom(site) {
875
- const d = site[2];
876
- return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "phantom";
877
- }
878
- isLiteralDef(d) {
879
- return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d].length > 2;
880
- }
881
- /** A required `never` union branch: it can never match (skipped). */ isNever(site) {
882
- const d = site[2];
883
- return site[0] === 0 && d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
884
- }
885
- /** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
886
- const [, , d, , slot] = site;
887
- if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
888
- return `k${d === INTERP ? slot + 1 : slot + (hasRejectSlot(site) ? 1 : 0) + 1}`;
889
- }
890
- /** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
891
- const [optional, mask, d, shape, slot] = site;
892
- if (d === INTERP) return this.call(`k${slot}`, x, ctx);
893
- let at = slot;
894
- const rej = hasRejectSlot(site) ? at++ : -1;
895
- const body = d === EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
896
- if (!optional) return body;
897
- if (rej < 0) return body.length > 0 ? [
898
- `if (${x} !== undefined && ${x} !== null) {`,
899
- ...indent(body),
900
- "}"
901
- ] : [];
902
- const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
903
- if (body.length > 0) lines.push("} else {", ...indent(body));
904
- lines.push("}");
905
- return lines;
906
- }
907
- /** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
908
- this.calls++;
909
- return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
910
- }
911
- def(d, mask, shape, at, x, ctx) {
912
- const def = this.defs[d];
913
- const kind = def[0];
914
- if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
915
- switch (kind) {
916
- case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
917
- case D_ARRAY: return [
918
- `if (!Array.isArray(${x})) ${ctx.fail}`,
919
- ...this.arrayConstraints(mask, keySlots(mask, shape, at), x, ctx.fail),
920
- ...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
921
- ];
922
- case D_UNION: {
923
- const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
924
- if (!this.fn[d]) return this.union(def[1], {
925
- mask,
926
- shape,
927
- at
928
- }, constraints, x, ctx);
929
- this.calls++;
930
- const lines = [
931
- `t = d${d}(${x}, ${flags(ctx)}, o)`,
932
- "if (t === 2) return 2",
933
- `if (t === 0) ${ctx.fail}`
934
- ];
935
- if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
936
- return lines;
937
- }
938
- case D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
939
- case D_TUPLE: return this.tuple(def[1], x, ctx);
940
- default: return ["return 2"];
941
- }
942
- }
943
- /** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
944
- const designType = def[1];
945
- if (designType === "phantom") return [];
946
- if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
947
- const ks = keySlots(mask, shape, at);
948
- switch (designType) {
949
- case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
950
- case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
951
- case "boolean": {
952
- const conds = [`typeof ${x} !== "boolean"`];
953
- if (mask & B_REQUIRED) conds.push(`${x} !== true`);
954
- return [`if (${conds.join(" || ")}) ${fail}`];
955
- }
956
- case "any": return [];
957
- case "never": return [fail];
958
- case "undefined": return [`if (${x} !== undefined) ${fail}`];
959
- case "null": return [`if (${x} !== null) ${fail}`];
960
- case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
961
- default: return ["return 2"];
962
- }
963
- }
964
- stringChecks(mask, shape, ks, x, fail, conds) {
965
- if (mask & B_REQUIRED) conds.push(`${x}.trim().length === 0`);
966
- if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
967
- if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
968
- const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
969
- let p = 0;
970
- for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
971
- else if (c === "s") {
972
- lines.push("return 2");
973
- break;
974
- }
975
- return lines;
976
- }
977
- numberChecks(mask, ks, x, fail, conds) {
978
- if (mask & B_INT) conds.push(`${x} % 1 !== 0`);
979
- if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
980
- if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
981
- if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
982
- if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
983
- return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
984
- }
985
- /** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
986
- const conds = [];
987
- if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
988
- if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
989
- const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
990
- if (mask & B_UNIQUE) lines.push("return 2");
991
- return lines;
992
- }
993
- /** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
994
- const ks = keySlots(mask, shape, at);
995
- const branches = [];
996
- if (mask & STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
997
- if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
998
- if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
999
- if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
1000
- const lines = [];
1001
- branches.forEach(([cond, body], i) => {
1002
- lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
1003
- });
1004
- if (lines.length > 0) lines.push("}");
1005
- return lines;
1006
- }
1007
- /**
1008
- * The union-level constraints after a non-literal branch passed. A required (non-optional)
1009
- * branch of a known primitive / array type fixes `typeof`: only that part applies.
1010
- */ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
1011
- const [optional, , d] = item;
1012
- const def = this.defs[d];
1013
- if (optional) return constraints;
1014
- const ks = keySlots(mask, shape, at);
1015
- if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
1016
- if (def[0] !== D_FINAL) return constraints;
1017
- switch (def[1]) {
1018
- case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
1019
- case "number": return this.numberChecks(mask, ks, x, fail, []);
1020
- case "boolean": return mask & B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
1021
- case "null":
1022
- case "undefined": return [];
1023
- default: return constraints;
1024
- }
1025
- }
1026
- /**
1027
- * Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
1028
- * FAIL breaks out of; `onMatch` ends a passing branch.
1029
- */ unionBranches(items, x, clearTop, onMatch) {
1030
- const lines = [];
1031
- for (const item of items) {
1032
- if (this.isNever(item)) continue;
1033
- const b = this.next("B");
1034
- const calls = this.calls;
1035
- const fail = `break ${b}`;
1036
- const body = this.site(item, x, {
1037
- fail,
1038
- inUnionFail: fail,
1039
- union: true,
1040
- clearTop
1041
- });
1042
- lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
1043
- if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
1044
- }
1045
- return lines;
1046
- }
1047
- /** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
1048
- const u = this.next("U");
1049
- const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
1050
- const lines = [];
1051
- const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
1052
- if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
1053
- else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
1054
- lines.push(`break ${u}`);
1055
- return lines;
1056
- });
1057
- return [
1058
- `${u}: {`,
1059
- ...indent([...branches, ctx.fail]),
1060
- "}"
1061
- ];
1062
- }
1063
- /** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
1064
- const y = this.next("y");
1065
- const a = this.next("a");
1066
- const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
1067
- if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
1068
- return [
1069
- `let ${a} = 1`,
1070
- `for (const ${y} of ${x}) {`,
1071
- ...indent(body),
1072
- "}",
1073
- `if (${a} === 0) ${ctx.inUnionFail}`
1074
- ];
1075
- }
1076
- /** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
1077
- const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
1078
- items.forEach((item, i) => {
1079
- const e = this.next("e");
1080
- lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
1081
- ...ctx,
1082
- clearTop: true
1083
- }));
1084
- });
1085
- return lines;
1086
- }
1087
- constructor(layout) {
1088
- _define_property$2(this, "layout", void 0);
1089
- _define_property$2(this, "defs", void 0);
1090
- /** Def index → emitted as its own function. */ _define_property$2(this, "fn", void 0);
1091
- _define_property$2(this, "uid", void 0);
1092
- /** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$2(this, "calls", void 0);
1093
- this.layout = layout;
1094
- this.uid = 0;
1095
- this.calls = 0;
1096
- this.defs = layout[0];
1097
- this.fn = this.functionDefs();
1098
- }
1099
- };
1100
- /**
1101
- * Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
1102
- * inside a union and leaves the check otherwise.
1103
- */ function recordingCtx(record, union, clearTop) {
1104
- const inUnionFail = `{ ${record} }`;
1105
- return {
1106
- fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
1107
- inUnionFail,
1108
- union,
1109
- clearTop
1110
- };
1111
- }
1112
- /** Flags passed to a callee. */ function flags(ctx) {
1113
- if (ctx.clearTop) return ctx.union ? `(f & ${~F_TOP}) | ${F_IN_UNION}` : `f & ${~F_TOP}`;
1114
- return ctx.union ? `f | ${F_IN_UNION}` : "f";
1115
- }
1116
- /** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
1117
- return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
1118
- }
1119
- /** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
1120
- return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
1121
- }
1122
- function notObject(x) {
1123
- return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
1124
- }
1125
- function indent(lines, n = 2) {
1126
- const pad = " ".repeat(n);
1127
- return lines.map((l) => pad + l);
1128
- }
1129
-
1130
- //#endregion
1131
- //#region packages/typescript/src/codegen/validation-model.ts
1132
- function _define_property$1(obj, key, value) {
1133
- if (key in obj) Object.defineProperty(obj, key, {
1134
- value,
1135
- enumerable: true,
1136
- configurable: true,
1137
- writable: true
1138
- });
1139
- else obj[key] = value;
1140
- return obj;
1141
- }
1142
- /** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
1143
- const INTERP_KIND = "#interp";
1144
- /**
1145
- * How the layout treats a model type: `'ext'` — another module's type referenced as a
1146
- * whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
1147
- * chained reference into another module's type, only known at runtime.
1148
- */ function classifyType(type) {
1149
- const kind = type?.kind;
1150
- return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
1151
- }
1152
- /**
1153
- * Build-time model of the runtime type trees a generated `.as.js` module builds, used to
1154
- * compile validator checks (`compileValidators`).
1155
- *
1156
- * The renderer drives it in lockstep with the builder chains it emits, through the real
1157
- * runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
1158
- * the same structure, the same type-def sharing (by identity) and the same validator
1159
- * annotations as the module after its initialisation. Only the annotations the validator
1160
- * pre-check reads are recorded. Types of other modules are opaque markers: a reference to
1161
- * one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
1162
- * runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
1163
- *
1164
- * Anything the model cannot follow marks it broken; nothing is compiled then. A model that
1165
- * nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
1166
- * the interpreted pre-check runs.
1167
- */ var ValidationModel = class {
1168
- /** Runs a model step; a throw marks the model broken. */ run(step) {
1169
- if (this.broken) return;
1170
- try {
1171
- return step();
1172
- } catch {
1173
- this.broken = true;
1174
- return;
1175
- }
1176
- }
1177
- /** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
1178
- this.classes.set(name, {
1179
- __is_atscript_annotated_type: true,
1180
- type: {},
1181
- metadata: /* @__PURE__ */ new Map(),
1182
- name
1183
- });
1184
- }
1185
- /** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
1186
- const cls = this.classes.get(name);
1187
- if (!cls) throw new Error(`${name} is not a class of this module`);
1188
- return cls;
1189
- }
1190
- /** `$(kind, name?)`. */ handle(kind, name) {
1191
- return this.run(() => defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
1192
- }
1193
- /** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
1194
- this.run(() => {
1195
- if (!handle) throw new Error("no chain");
1196
- if (imported) {
1197
- const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
1198
- handle.refTo(() => marker, chain);
1199
- } else handle.refTo(this.classBase(name), chain);
1200
- });
1201
- }
1202
- /** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
1203
- const key = `${name}${kind}`;
1204
- let marker = this.markers.get(key);
1205
- if (!marker) {
1206
- marker = {
1207
- __is_atscript_annotated_type: true,
1208
- type: { kind },
1209
- metadata: /* @__PURE__ */ new Map()
1210
- };
1211
- this.markers.set(key, marker);
1212
- }
1213
- return marker;
1214
- }
1215
- /** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
1216
- if (!isValidatorKey(key)) return;
1217
- this.run(() => {
1218
- if (!this.current) throw new Error("no chain");
1219
- this.current.annotate(key, value, multiple);
1220
- });
1221
- }
1222
- /** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
1223
- let cur = this.classes.get(name);
1224
- for (const step of steps) {
1225
- if (cur === void 0 || cur === null) return;
1226
- if (step === "type") {
1227
- cur = cur.type;
1228
- if (classifyType(cur) !== void 0) return;
1229
- } else if (step[0] === "props") cur = cur.props?.get(step[1]);
1230
- else cur = cur.items?.[step[1]];
1231
- }
1232
- return cur;
1233
- }
1234
- /** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
1235
- this.run(() => {
1236
- const parent = this.resolve(name, steps);
1237
- if (parent) cloneRefProp(parent, prop);
1238
- });
1239
- }
1240
- /** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
1241
- this.run(() => {
1242
- this.resolve(name, steps)?.metadata?.delete(key);
1243
- });
1244
- }
1245
- /** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
1246
- if (!isValidatorKey(key)) return;
1247
- this.run(() => {
1248
- annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
1249
- });
1250
- }
1251
- /**
1252
- * `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
1253
- * compiled (its root type is only known at runtime, or the model is broken).
1254
- */ registration(name) {
1255
- if (this.broken) return;
1256
- const cls = this.classes.get(name);
1257
- if (!cls) return;
1258
- let layout;
1259
- try {
1260
- layout = buildLayout(cls, { regex: getRegex }, classifyType);
1261
- } catch {
1262
- return;
1263
- }
1264
- const root = layout[1][2];
1265
- if (root === INTERP || root >= 0 && layout[0][root][0] === D_UNKNOWN) return;
1266
- return `$cv(${name}, ${LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
1267
- }
1268
- constructor() {
1269
- /** The model could not follow the emitted code: compile nothing. */ _define_property$1(this, "broken", false);
1270
- /** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$1(this, "current", void 0);
1271
- _define_property$1(this, "classes", /* @__PURE__ */ new Map());
1272
- _define_property$1(this, "markers", /* @__PURE__ */ new Map());
1273
- }
1274
- };
1275
- /**
1276
- * Runtime value of an annotation argument the emitted code writes as a raw expression
1277
- * (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
1278
- * compares only presence / truthiness and reads the real values at runtime.
1279
- */ function rawLiteralValue(text) {
1280
- switch (text) {
1281
- case "true": return true;
1282
- case "false": return false;
1283
- case "null": return null;
1284
- case "undefined": return;
1285
- default: {
1286
- const n = Number(text);
1287
- return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
1288
- }
1289
- }
1290
- }
1291
-
1292
- //#endregion
1293
- //#region packages/typescript/src/codegen/js-renderer.ts
1294
- function _define_property(obj, key, value) {
1295
- if (key in obj) Object.defineProperty(obj, key, {
1296
- value,
1297
- enumerable: true,
1298
- configurable: true,
1299
- writable: true
1300
- });
1301
- else obj[key] = value;
1302
- return obj;
1303
- }
1304
- const QUERY_OP_MAP = {
1305
- "=": "$eq",
1306
- "!=": "$ne",
1307
- ">": "$gt",
1308
- ">=": "$gte",
1309
- "<": "$lt",
1310
- "<=": "$lte",
1311
- "in": "$in",
1312
- "not in": "$nin",
1313
- "matches": "$regex",
1314
- "exists": "$exists",
1315
- "not exists": "$exists"
1316
- };
1317
- /** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
1318
- "expect.min": "minValue",
1319
- "expect.max": "maxValue",
1320
- "expect.exclusiveMin": "exclusiveMinValue",
1321
- "expect.exclusiveMax": "exclusiveMaxValue"
1322
- };
1323
- const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
1324
- /** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
1325
- return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
1326
- }
1327
- /**
1328
- * The runtime accessor of a mutating-annotate path: `Name` followed by the steps
1329
- * (`.type`, `.props.get("a")?`, `.items[0]`).
1330
- */ function accessorPath(targetName, steps) {
1331
- let path = targetName;
1332
- for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
1333
- return path;
1334
- }
1335
- var JsRenderer = class extends BaseRenderer {
1336
- /**
1337
- * Relative imports get the configured `moduleExtension`; bare specifiers
1338
- * always keep `.as` — they resolve through the package's `exports` map.
1339
- */ transformFromPath(path) {
1340
- return isBareSpecifier(path) ? `${path}.as` : `${path}${this.opts?.moduleExtension ?? ".as"}`;
1341
- }
1342
- /**
1343
- * Override base `unused` to subtract symbols that the JS output references
1344
- * transitively through `extends`-resolved parent prop trees. Without this,
1345
- * cross-file `extends` strips the imports needed by inherited `.refTo()` calls.
1346
- */ get unused() {
1347
- if (this._unusedJs) return this._unusedJs;
1348
- const base = new Set(this.doc.getUnusedTokens().map((t) => t.text));
1349
- for (const ref of this.getExtendsRefs().keys()) if (ref.id) base.delete(ref.id);
1350
- return this._unusedJs = base;
1351
- }
1352
- getExtendsRefs() {
1353
- if (this._extendsRefs) return this._extendsRefs;
1354
- const out = /* @__PURE__ */ new Map();
1355
- const visitedInterfaces = /* @__PURE__ */ new Set();
1356
- for (const node of this.doc.nodes) if (isInterface(node) && node.hasExtends) this.walkExtendsParents(node, this.doc, out, visitedInterfaces);
1357
- return this._extendsRefs = out;
1358
- }
1359
- walkRefs(node, visited, visit) {
1360
- if (!node || visited.has(node)) return;
1361
- visited.add(node);
1362
- if (isRef(node)) {
1363
- visit(node);
1364
- return;
1365
- }
1366
- if (isGroup(node)) {
1367
- for (const item of node.unwrap()) this.walkRefs(item, visited, visit);
1368
- return;
1369
- }
1370
- if (isArray(node) || isProp(node)) this.walkRefs(node.getDefinition(), visited, visit);
1371
- }
1372
- walkExtendsParents(iface, doc, out, visited) {
1373
- if (visited.has(iface)) return;
1374
- visited.add(iface);
1375
- const visitedNodes = /* @__PURE__ */ new Set();
1376
- for (const token of iface.extendsTokens) {
1377
- const unwound = doc.unwindType(token.text);
1378
- if (!unwound?.def || !isInterface(unwound.def)) continue;
1379
- const parentInterface = unwound.def;
1380
- const parentDoc = unwound.doc;
1381
- this.walkRefs(parentInterface.getDefinition(), visitedNodes, (ref) => {
1382
- if (!out.has(ref)) out.set(ref, parentDoc);
1383
- });
1384
- if (parentInterface.hasExtends) this.walkExtendsParents(parentInterface, parentDoc, out, visited);
1385
- }
1386
- }
1387
- computeSynthesizedImports() {
1388
- if (this._synthComputed) return;
1389
- this._synthComputed = true;
1390
- const refToOriginDoc = this.getExtendsRefs();
1391
- if (refToOriginDoc.size === 0) return;
1392
- for (const [refNode, originDoc] of refToOriginDoc) {
1393
- const refId = refNode.id;
1394
- if (!refId) continue;
1395
- const ownerInfo = this.resolveOwner(originDoc, refId);
1396
- if (!ownerInfo?.doc || ownerInfo.doc === this.doc) continue;
1397
- if (ownerInfo.node && isPrimitive(ownerInfo.node)) continue;
1398
- const info = this.synthBinding(refId, ownerInfo);
1399
- if (!info) continue;
1400
- this._refSynthInfo.set(refNode, info);
1401
- }
1402
- }
1403
- getSynthTaken() {
1404
- if (!this._synthTaken) {
1405
- this._synthTaken = new Set(this.doc.registry.definitions.keys());
1406
- for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
1407
- }
1408
- return this._synthTaken;
1409
- }
1410
- getSynthPath(ownerDoc) {
1411
- if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
1412
- return this._synthPathCache.get(ownerDoc);
1413
- }
1414
- synthBinding(name, ownerInfo) {
1415
- const synthPath = this.getSynthPath(ownerInfo.doc);
1416
- if (!synthPath) return;
1417
- const allocKey = `${synthPath}::${name}`;
1418
- let info = this._synthAllocated.get(allocKey);
1419
- if (!info) {
1420
- info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
1421
- this._synthAllocated.set(allocKey, info);
1422
- }
1423
- return info;
1424
- }
1425
- /**
1426
- * Binding for a type name used by an annotation argument (`ref` / qualified
1427
- * query field refs). An annotation inherited from another document (chain ref
1428
- * or `extends`) carries names that only that document imports, so when the
1429
- * name does not resolve here to the same declaration, a synthesized import is
1430
- * allocated (lazily, spliced into the header by `render()`).
1431
- */ annotationTypeName(typeName, origin) {
1432
- if (!origin || origin === this.doc) return typeName;
1433
- const theirs = this.resolveOwner(origin, typeName);
1434
- if (!theirs?.doc || !theirs.node || theirs.doc === this.doc || isPrimitive(theirs.node)) return typeName;
1435
- const mine = this.resolveOwner(this.doc, typeName);
1436
- if (mine?.doc === theirs.doc && mine.node === theirs.node) return typeName;
1437
- return this.synthBinding(typeName, {
1438
- doc: theirs.doc,
1439
- node: theirs.node
1440
- })?.alias ?? typeName;
1441
- }
1442
- resolveOwner(fromDoc, refId) {
1443
- const key = `${fromDoc.id}::${refId}`;
1444
- let v = this._ownerCache.get(key);
1445
- if (v === void 0 && !this._ownerCache.has(key)) {
1446
- v = fromDoc.getDeclarationOwnerNode(refId);
1447
- this._ownerCache.set(key, v);
1448
- }
1449
- return v;
1450
- }
1451
- allocateSynthInfo(refId, synthPath, ownerInfo, taken) {
1452
- const ownerDoc = ownerInfo.doc;
1453
- const ownerNode = ownerInfo.node;
1454
- if (this.doc.importedDefs.get(refId)?.text === synthPath) return {
1455
- alias: refId,
1456
- ownerDoc,
1457
- ownerNode
1458
- };
1459
- const alias = this.allocAlias(refId, taken);
1460
- let group = this._synthImports.get(synthPath);
1461
- if (!group) {
1462
- group = [];
1463
- this._synthImports.set(synthPath, group);
1464
- }
1465
- group.push({
1466
- name: refId,
1467
- alias
1468
- });
1469
- return {
1470
- alias,
1471
- ownerDoc,
1472
- ownerNode
1473
- };
1474
- }
1475
- allocAlias(name, taken) {
1476
- if (!taken.has(name)) {
1477
- taken.add(name);
1478
- return name;
1479
- }
1480
- let n = 1;
1481
- while (taken.has(`${name}_${n}`)) n++;
1482
- const alias = `${name}_${n}`;
1483
- taken.add(alias);
1484
- return alias;
1485
- }
1486
- computeSynthPath(ownerDoc) {
1487
- if (isBareId(ownerDoc.id)) return ownerDoc.id.slice(5, -3);
1488
- if (!ownerDoc.id.startsWith("file://")) return;
1489
- return getRelPath(this.doc.id, ownerDoc.id);
1490
- }
1491
- pre() {
1492
- this.writeln("// prettier-ignore-start");
1493
- this.writeln("/* eslint-disable */");
1494
- this.writeln("/* oxlint-disable */");
1495
- let hasMutatingAnnotate = false;
1496
- const nodesByName = /* @__PURE__ */ new Map();
1497
- for (const node of this.doc.nodes) {
1498
- if (node.entity === "annotate" && node.isMutating) hasMutatingAnnotate = true;
1499
- if (node.__typeId !== null && node.__typeId !== void 0 && node.id) {
1500
- const name = node.id;
1501
- if (!nodesByName.has(name)) nodesByName.set(name, []);
1502
- nodesByName.get(name).push(node);
1503
- }
1504
- }
1505
- for (const [name, nodes] of nodesByName) if (nodes.length === 1) this.typeIds.set(nodes[0], name);
1506
- else for (let i = 0; i < nodes.length; i++) this.typeIds.set(nodes[i], `${name}__${i + 1}`);
1507
- const imports = ["defineAnnotatedType as $", "annotate as $a"];
1508
- if (hasMutatingAnnotate) imports.push("cloneRefProp as $c");
1509
- const jsonSchemaMode = resolveJsonSchemaMode(this.opts);
1510
- if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
1511
- if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
1512
- if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
1513
- if (this.model) imports.push("registerCompiledCheck as $cv");
1514
- this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
1515
- this.computeSynthesizedImports();
1516
- this.writeln(SYNTH_IMPORTS_MARKER);
1517
- }
1518
- render() {
1519
- const out = super.render();
1520
- const lines = [];
1521
- for (const [synthPath, names] of this._synthImports) {
1522
- const list = names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ");
1523
- lines.push(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
1524
- }
1525
- const marker = `${SYNTH_IMPORTS_MARKER}\n`;
1526
- return out.replace(marker, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
1527
- }
1528
- buildAdHocMap(annotateNodes) {
1529
- const map = /* @__PURE__ */ new Map();
1530
- for (const annotateNode of annotateNodes) for (const entry of annotateNode.entries) {
1531
- const path = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)].join(".") : entry.id;
1532
- const anns = entry.annotations || [];
1533
- if (anns.length > 0) {
1534
- const existing = map.get(path);
1535
- if (existing) existing.push(...anns);
1536
- else map.set(path, [...anns]);
1537
- }
1538
- }
1539
- return map.size > 0 ? map : null;
1540
- }
1541
- /**
1542
- * Checks if any ad-hoc annotation path extends beyond the current _propPath,
1543
- * meaning annotations target properties inside a referenced type.
1544
- */ hasAdHocAnnotationsThroughRef() {
1545
- if (!this._adHocAnnotations || this._propPath.length === 0) return false;
1546
- const prefix = `${this._propPath.join(".")}.`;
1547
- for (const key of this._adHocAnnotations.keys()) if (key.startsWith(prefix)) return true;
1548
- return false;
1549
- }
1550
- post() {
1551
- for (const node of this.postAnnotate) if (node.entity === "annotate") {
1552
- const annotateNode = node;
1553
- if (annotateNode.isMutating) this.renderMutatingAnnotateNode(annotateNode);
1554
- else {
1555
- const unwound = this.doc.unwindType(annotateNode.targetName);
1556
- if (unwound?.def) {
1557
- let def = this.doc.mergeIntersection(unwound.def);
1558
- if (isInterface(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
1559
- else def = def.getDefinition() || def;
1560
- this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
1561
- this.modelClass(node.id, () => this.annotateType(def, node.id));
1562
- this._adHocAnnotations = null;
1563
- this.indent();
1564
- this.defineMetadataForAnnotateAlias(annotateNode);
1565
- this.unindent();
1566
- this.writeln();
1567
- }
1568
- }
1569
- } else {
1570
- let def = node.getDefinition();
1571
- if (isInterface(node) && node.hasExtends) {
1572
- const resolved = this.doc.resolveInterfaceExtends(node);
1573
- if (resolved) def = resolved;
1574
- }
1575
- this.modelClass(node.id, () => this.annotateType(def, node.id));
1576
- this.indent().defineMetadata(node).unindent();
1577
- this.writeln();
1578
- }
1579
- this.renderCompiledChecks();
1580
- this.writeln("// prettier-ignore-end");
1581
- super.post();
1582
- }
1583
- /**
1584
- * Emits class `name`'s chain; the validation model follows it (its handle stays the current
1585
- * chain, the target of the class-level annotations emitted next).
1586
- */ modelClass(name, emit) {
1587
- if (this.model) this.model.current = void 0;
1588
- emit();
1589
- if (this.model?.current) this.modelClasses.push(name);
1590
- }
1591
- /**
1592
- * `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
1593
- * mutating annotate of the module ran (the compiled check binds on first use).
1594
- */ renderCompiledChecks() {
1595
- if (!this.model) return;
1596
- const registrations = [];
1597
- for (const name of this.modelClasses) {
1598
- const registration = this.model.registration(name);
1599
- if (registration) registrations.push(registration);
1600
- }
1601
- if (registrations.length > 0) {
1602
- this.writeln("// Compiled validator checks");
1603
- for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
1604
- this.writeln();
1605
- }
1606
- }
1607
- renderClassStatics(node) {
1608
- this.writeln("static __is_atscript_annotated_type = true");
1609
- this.writeln("static type = {}");
1610
- this.writeln("static metadata = new Map()");
1611
- const typeId = this.typeIds.get(node);
1612
- if (typeId) this.writeln(`static id = "${typeId}"`);
1613
- this.renderJsonSchemaMethod(node);
1614
- this.renderExampleDataMethod(node);
1615
- this.renderDimMeasure(node);
1616
- }
1617
- renderInterface(node) {
1618
- this.renderDefinitionClass(node);
1619
- }
1620
- renderType(node) {
1621
- this.renderDefinitionClass(node);
1622
- }
1623
- renderAnnotate(node) {
1624
- if (node.isMutating) {
1625
- this.postAnnotate.push(node);
1626
- return;
1627
- }
1628
- if (!this.doc.unwindType(node.targetName)?.def) return;
1629
- this.renderDefinitionClass(node);
1630
- }
1631
- renderDefinitionClass(node) {
1632
- this.writeln();
1633
- const exported = node.token("export")?.text === "export";
1634
- this.write(exported ? "export " : "");
1635
- this.write(`class ${node.id} `);
1636
- this.blockln("{}");
1637
- this.model?.declare(node.id);
1638
- this.renderClassStatics(node);
1639
- this.popln();
1640
- this.postAnnotate.push(node);
1641
- this.writeln();
1642
- }
1643
- renderJsonSchemaMethod(node) {
1644
- const mode = resolveJsonSchemaMode(this.opts);
1645
- if (node.countAnnotations("emit.jsonSchema") > 0 || mode === "bundle") {
1646
- const schema = JSON.stringify(buildJsonSchema(this.toAnnotatedType(node)));
1647
- this.writeln("static toJsonSchema() {");
1648
- this.indent().writeln(`return ${schema}`).unindent();
1649
- this.writeln("}");
1650
- } else if (mode === "lazy") {
1651
- this.writeln("static toJsonSchema() {");
1652
- this.indent().writeln("return this._jsonSchema ?? (this._jsonSchema = $$(this))").unindent();
1653
- this.writeln("}");
1654
- } else {
1655
- this.writeln("static toJsonSchema() {");
1656
- this.indent().writeln("$d(\"JSON Schema\", \"jsonSchema\", \"emit.jsonSchema\")").unindent();
1657
- this.writeln("}");
1658
- }
1659
- }
1660
- renderExampleDataMethod(_node) {
1661
- if (this.opts?.exampleData) {
1662
- this.writeln("static toExampleData() {");
1663
- this.indent().writeln("return $e(this, { mode: \"example\" })").unindent();
1664
- this.writeln("}");
1665
- }
1666
- }
1667
- renderDimMeasure(node) {
1668
- if (!isInterface(node)) return;
1669
- const interfaceNode = node;
1670
- if (!isDbEntityNode(interfaceNode)) return;
1671
- let struct;
1672
- if (interfaceNode.hasExtends) struct = this.doc.resolveInterfaceExtends(interfaceNode);
1673
- if (!struct) struct = interfaceNode.getDefinition();
1674
- if (!struct || !isStructure(struct)) return;
1675
- const structNode = struct;
1676
- const dims = [];
1677
- const measures = [];
1678
- for (const [name, prop] of structNode.props) {
1679
- if (prop.token("identifier")?.pattern) continue;
1680
- if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
1681
- if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
1682
- }
1683
- if (dims.length > 0) this.writeln(`static dimensions = [${dims.map((d) => `'${escapeQuotes(d)}'`).join(", ")}]`);
1684
- if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
1685
- }
1686
- toAnnotatedType(node) {
1687
- return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
1688
- }
1689
- /**
1690
- * The build-time runtime type of an interface / type declaration (see `_declTypes`);
1691
- * `doc` is the document that declares it (where an alias's target name resolves).
1692
- */ declType(node, doc = this.doc) {
1693
- const known = this._declTypes.get(node);
1694
- if (known) return known;
1695
- let def = node.getDefinition();
1696
- if (isInterface(node) && node.hasExtends) {
1697
- const resolved = this.doc.resolveInterfaceExtends(node);
1698
- if (resolved) def = resolved;
1699
- }
1700
- const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1701
- let handle;
1702
- if (def && isRef(def)) {
1703
- const ref = def;
1704
- const decl = doc.unwindType(ref.id, ref.chain)?.def;
1705
- const target = this.refTarget(ref, decl, doc);
1706
- handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1707
- } else {
1708
- const base = {
1709
- __is_atscript_annotated_type: true,
1710
- type: {},
1711
- metadata: /* @__PURE__ */ new Map(),
1712
- id: typeId
1713
- };
1714
- this._declTypes.set(node, base);
1715
- if (def) this._declTypes.set(def, base);
1716
- handle = this.toAnnotatedHandle(def, true, base);
1717
- }
1718
- this._declTypes.set(node, handle.$type);
1719
- if (typeId) handle.id(typeId);
1720
- this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1721
- return handle.$type;
1722
- }
1723
- /**
1724
- * The declaration type a reference points at (see `declType`), or `undefined` when it is
1725
- * not a declaration (a chained reference into a prop, an unresolved name). A plain
1726
- * reference to a type alias points at the alias itself (its own type and id, like the
1727
- * runtime `$().refTo(Alias)`), not at what the alias unwinds to.
1728
- */ refTarget(ref, decl, doc = this.doc) {
1729
- if (!decl) return;
1730
- const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
1731
- if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
1732
- const known = this._declTypes.get(decl);
1733
- if (known) return known;
1734
- return isInterface(decl) ? this.declType(decl) : void 0;
1735
- }
1736
- /**
1737
- * The build-time runtime type of an expression node; with `base`, built into that object
1738
- * (a declaration's type, see `declType`).
1739
- */ toAnnotatedHandle(node, skipAnnotations = false, base) {
1740
- if (!node) return defineAnnotatedType(void 0, base);
1741
- switch (node.entity) {
1742
- case "interface":
1743
- case "type": return defineAnnotatedType().refTo(this.declType(node));
1744
- case "prop": {
1745
- const prop = node;
1746
- const def = prop.getDefinition();
1747
- const handle = this.toAnnotatedHandle(def, true);
1748
- if (!skipAnnotations) {
1749
- this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(prop));
1750
- if (prop.token("optional")) handle.optional();
1751
- }
1752
- return handle;
1753
- }
1754
- case "ref": {
1755
- const ref = node;
1756
- const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1757
- const target = this.refTarget(ref, decl);
1758
- const handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
1759
- if (skipAnnotations) return handle;
1760
- const own = this.doc.evalAnnotationsForNode(node);
1761
- const referred = this.refTargetAnnotations(ref, decl);
1762
- return this.applyExpectAnnotations(handle, referred ? this.doc.mergeNodesAnnotations(referred, own) : own);
1763
- }
1764
- case "primitive": {
1765
- const prim = node;
1766
- const handle = defineAnnotatedType(void 0, base);
1767
- handle.designType(prim.id === "never" ? "never" : prim.config.type);
1768
- if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1769
- return handle;
1770
- }
1771
- case "const": {
1772
- const c = node;
1773
- const handle = defineAnnotatedType(void 0, base);
1774
- const t = c.token("identifier")?.type;
1775
- handle.designType(t === "number" ? "number" : "string");
1776
- handle.value(t === "number" ? Number(c.id) : c.id);
1777
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1778
- }
1779
- case "structure": {
1780
- const struct = node;
1781
- const handle = defineAnnotatedType("object", base);
1782
- for (const prop of Array.from(struct.props.values())) {
1783
- const propHandle = this.toAnnotatedHandle(prop);
1784
- const pattern = prop.token("identifier")?.pattern;
1785
- if (pattern) handle.propPattern(pattern, propHandle.$type);
1786
- else handle.prop(prop.id, propHandle.$type);
1787
- }
1788
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1789
- }
1790
- case "group": {
1791
- const group = node;
1792
- const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
1793
- for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1794
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1795
- }
1796
- case "tuple": {
1797
- const group = node;
1798
- const handle = defineAnnotatedType("tuple", base);
1799
- for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1800
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1801
- }
1802
- case "array": {
1803
- const arr = node;
1804
- const handle = defineAnnotatedType("array", base);
1805
- handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
1806
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1807
- }
1808
- default: {
1809
- const handle = defineAnnotatedType(void 0, base);
1810
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1811
- }
1812
- }
1813
- }
1814
- applyExpectAnnotations(handle, annotations) {
1815
- annotations?.forEach((a) => {
1816
- switch (a.name) {
1817
- case "expect.minLength":
1818
- case "expect.maxLength":
1819
- if (a.args[0]) handle.annotate(a.name, {
1820
- length: Number(a.args[0].text),
1821
- message: a.args[1]?.text
1822
- });
1823
- break;
1824
- case "expect.min":
1825
- case "expect.max":
1826
- case "expect.exclusiveMin":
1827
- case "expect.exclusiveMax":
1828
- if (a.args[0]) handle.annotate(a.name, {
1829
- [NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
1830
- message: a.args[1]?.text
1831
- });
1832
- break;
1833
- case "expect.pattern":
1834
- handle.annotate(a.name, {
1835
- pattern: a.args[0]?.text || "",
1836
- flags: a.args[1]?.text,
1837
- message: a.args[2]?.text
1838
- }, true);
1839
- break;
1840
- case "expect.int":
1841
- case "meta.required":
1842
- handle.annotate(a.name, true);
1843
- break;
1844
- case "expect.array.uniqueItems":
1845
- case "expect.array.key":
1846
- handle.annotate(a.name, { message: a.args[0]?.text });
1847
- break;
1848
- default:
1849
- }
1850
- });
1851
- return handle;
1852
- }
1853
- annotateType(_node, name) {
1854
- if (!_node) return this;
1855
- const node = this.doc.mergeIntersection(_node);
1856
- let kind = node.entity;
1857
- switch (node.entity) {
1858
- case "ref": {
1859
- const ref = node;
1860
- const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1861
- const primitive = this.inlinedPrimitive(ref, decl);
1862
- if (primitive) {
1863
- this.annotateType(primitive, name);
1864
- return this;
1865
- }
1866
- if (this._adHocAnnotations && this.hasAdHocAnnotationsThroughRef()) {
1867
- let resolved = decl ? this.doc.mergeIntersection(decl) : void 0;
1868
- if (resolved && isInterface(resolved)) resolved = resolved.getDefinition() || resolved;
1869
- if (resolved) {
1870
- this.annotateType(resolved, name);
1871
- return this;
1872
- }
1873
- }
1874
- const chain = ref.hasChain ? `, [${ref.chain.map((c) => `"${escapeQuotes(c.text)}"`).join(", ")}]` : "";
1875
- const synth = this._refSynthInfo.get(ref);
1876
- const ownerDecl = synth ? {
1877
- doc: synth.ownerDoc,
1878
- node: synth.ownerNode
1879
- } : this.resolveOwner(this.doc, ref.id);
1880
- const refName = synth?.alias ?? ref.id;
1881
- const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
1882
- const refExpr = isImported ? `() => ${refName}` : refName;
1883
- this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
1884
- this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
1885
- if (!ref.hasChain) {
1886
- if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
1887
- this.resolveAnnotationValue(ownerDecl.node, an);
1888
- });
1889
- }
1890
- this.unindent();
1891
- return this;
1892
- }
1893
- case "primitive":
1894
- this.definePrimitive(node, name);
1895
- return this;
1896
- case "const":
1897
- this.modelHandle("", name);
1898
- this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
1899
- return this;
1900
- case "structure":
1901
- this.modelHandle("object", name);
1902
- this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
1903
- return this;
1904
- case "group":
1905
- kind = node.op === "|" ? "union" : "intersection";
1906
- this.modelHandle(kind, name);
1907
- this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1908
- return this;
1909
- case "tuple":
1910
- this.modelHandle("tuple", name);
1911
- this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1912
- return this;
1913
- case "array":
1914
- this.modelHandle("array", name);
1915
- this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
1916
- return this;
1917
- default: return this;
1918
- }
1919
- }
1920
- /** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
1921
- if (!this.model) return;
1922
- const h = this.model.handle(kind, name);
1923
- this.model.current = h;
1924
- return h;
1925
- }
1926
- /**
1927
- * The model handle of a nested chain (`emit` writes it and its annotations): `current`
1928
- * is cleared first so a chain that emits nothing breaks the model instead of leaving a
1929
- * stale handle, and restored to the parent chain afterwards.
1930
- */ modelChild(emit) {
1931
- if (!this.model) {
1932
- emit();
1933
- return;
1934
- }
1935
- const parent = this.model.current;
1936
- this.model.current = void 0;
1937
- emit();
1938
- const child = this.model.current;
1939
- this.model.current = parent;
1940
- if (!child) this.model.broken = true;
1941
- return child;
1942
- }
1943
- defineConst(node) {
1944
- const t = node.token("identifier")?.type;
1945
- const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
1946
- this.writeln(`.designType("${escapeQuotes(designType)}")`);
1947
- this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
1948
- if (this.model) {
1949
- const h = this.model.current;
1950
- this.model.run(() => {
1951
- h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
1952
- });
1953
- }
1954
- return this;
1955
- }
1956
- definePrimitive(node, name) {
1957
- this.renderPrimitiveDef(node.id === "never" ? "never" : node.config.type, name);
1958
- this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
1959
- return this;
1960
- }
1961
- /** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
1962
- const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
1963
- const final = (designType) => {
1964
- this.writeln(`$(${d()}).designType("${designType}")`);
1965
- const h = this.modelHandle("", name);
1966
- this.model?.run(() => h.designType(designType));
1967
- };
1968
- if (!def) return final("any");
1969
- if (typeof def === "string") return final(def === "void" ? "undefined" : def);
1970
- switch (def.kind) {
1971
- case "final": return final(def.value === "void" ? "undefined" : def.value);
1972
- case "union":
1973
- case "intersection":
1974
- case "tuple":
1975
- this.writeln(`$(${d(def.kind)})`);
1976
- this.modelHandle(def.kind, name);
1977
- this.indent();
1978
- for (const itemDef of def.items) {
1979
- this.write(`.item(`);
1980
- this.indent();
1981
- const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
1982
- this.writeln(".$type");
1983
- this.unindent();
1984
- this.write(`)`);
1985
- this.model?.run(() => this.model.current.item(child.$type));
1986
- }
1987
- this.unindent();
1988
- return;
1989
- case "array": {
1990
- this.writeln(`$(${d("array")})`);
1991
- this.modelHandle("array", name);
1992
- this.indent();
1993
- this.write(".of(");
1994
- this.indent();
1995
- const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
1996
- this.writeln(`.$type`);
1997
- this.unindent();
1998
- this.writeln(`)`);
1999
- this.unindent();
2000
- this.model?.run(() => this.model.current.of(child.$type));
2001
- return;
2002
- }
2003
- case "object": {
2004
- this.writeln(`$(${d("object")})`);
2005
- this.modelHandle("object", name);
2006
- this.indent();
2007
- const props = [...Object.entries(def.props).map(([k, p]) => [
2008
- k,
2009
- p,
2010
- false
2011
- ]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
2012
- k,
2013
- p,
2014
- true
2015
- ])];
2016
- for (const [key, propDef, isPattern] of props) {
2017
- const optional = typeof propDef === "object" && propDef.optional;
2018
- this.writeln(isPattern ? `.propPattern(` : `.prop(`);
2019
- this.indent();
2020
- this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
2021
- const child = this.modelChild(() => {
2022
- this.renderPrimitiveDef(propDef);
2023
- if (optional) {
2024
- this.writeln(".optional()");
2025
- this.model?.run(() => this.model.current.optional());
2026
- }
2027
- });
2028
- this.writeln(".$type");
2029
- this.unindent();
2030
- this.write(`)`);
2031
- this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
2032
- }
2033
- this.unindent();
2034
- return;
2035
- }
2036
- default: return final("any");
2037
- }
2038
- }
2039
- defineObject(node) {
2040
- const props = Array.from(node.props.values());
2041
- for (const prop of props) {
2042
- const pattern = prop.token("identifier")?.pattern;
2043
- const optional = !!prop.token("optional");
2044
- this._propPath.push(prop.id);
2045
- if (pattern) {
2046
- this.writeln(`.propPattern(`);
2047
- this.indent();
2048
- this.writeln(`/${pattern.source}/${pattern.flags},`);
2049
- } else {
2050
- this.writeln(`.prop(`);
2051
- this.indent();
2052
- this.writeln(`"${escapeQuotes(prop.id)}",`);
2053
- }
2054
- const child = this.modelChild(() => {
2055
- this.annotateType(prop.getDefinition());
2056
- this.indent().defineMetadata(prop).unindent();
2057
- });
2058
- if (optional) this.writeln(" .optional()");
2059
- this.writeln(" .$type");
2060
- this.unindent();
2061
- this.write(`)`);
2062
- this._propPath.pop();
2063
- this.model?.run(() => {
2064
- if (optional) child.optional();
2065
- if (pattern) this.model.current.propPattern(pattern, child.$type);
2066
- else this.model.current.prop(prop.id, child.$type);
2067
- });
2068
- }
2069
- this.writeln();
2070
- return this;
2071
- }
2072
- defineGroup(node) {
2073
- for (const item of node.unwrap()) {
2074
- this.write(".item(").indent();
2075
- const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
2076
- this.write(" .$type").writeln(`)`).unindent();
2077
- this.model?.run(() => this.model.current.item(child.$type));
2078
- }
2079
- return this;
2080
- }
2081
- defineArray(node) {
2082
- const of = node.getDefinition();
2083
- this.write(".of(").indent();
2084
- const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
2085
- this.write(" .$type").writeln(`)`).unindent();
2086
- this.model?.run(() => this.model.current.of(child.$type));
2087
- return this;
2088
- }
2089
- /**
2090
- * A built-in primitive extension used directly as a union / tuple member or array
2091
- * element (`number.int | null`, `string.email[]`) is inlined by `annotateType` without
2092
- * its built-in annotations (`expect.int`, the email pattern, …) — a prop gets them
2093
- * through `defineMetadata`, a member has no prop to carry them, so emit them here.
2094
- */ defineInlinePrimitiveMetadata(node) {
2095
- const primitive = node && this.inlinedPrimitive(node);
2096
- if (primitive?.annotations?.length) {
2097
- this.indent();
2098
- for (const an of primitive.annotations) this.resolveAnnotationValue(primitive, an);
2099
- this.unindent();
2100
- }
2101
- return this;
2102
- }
2103
- /**
2104
- * The built-in primitive a ref is inlined as by `annotateType` — not a named alias that
2105
- * resolves to one (`type MyString = string`), which is emitted as a `refTo`.
2106
- */ inlinedPrimitive(node, decl = isRef(node) ? this.doc.unwindType(node.id, node.chain)?.def : void 0) {
2107
- if (!isRef(node) || !isPrimitive(decl)) return;
2108
- const ownerDecl = this.resolveOwner(this.doc, node.id);
2109
- if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) return;
2110
- return decl;
2111
- }
2112
- /** Annotations a ref inherits from its target (see `annotateType`'s ref case). */ refTargetAnnotations(ref, decl) {
2113
- const primitive = this.inlinedPrimitive(ref, decl);
2114
- if (primitive) return primitive.annotations;
2115
- if (ref.hasChain) return;
2116
- const ownerDecl = this.resolveOwner(this.doc, ref.id);
2117
- return ownerDecl?.node ? ownerDecl.doc.evalReferredAnnotations(ownerDecl.node) : void 0;
2118
- }
2119
- defineMetadata(node) {
2120
- let annotations;
2121
- const nodeDef = node.getDefinition?.();
2122
- if (nodeDef && isRef(nodeDef)) {
2123
- const refNode = nodeDef;
2124
- if (!refNode.hasChain) {
2125
- const resolved = this.doc.unwindType(refNode.id, refNode.chain)?.def;
2126
- if (resolved && !isPrimitive(resolved)) annotations = node.annotations ?? [];
2127
- else if (resolved && isPrimitive(resolved)) {
2128
- const ownerDecl = this.doc.getDeclarationOwnerNode(refNode.id);
2129
- if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) annotations = node.annotations ?? [];
2130
- }
2131
- }
2132
- }
2133
- if (annotations === void 0) annotations = this.doc.evalAnnotationsForNode(node);
2134
- if (this._adHocAnnotations && this._propPath.length > 0) {
2135
- const path = this._propPath.join(".");
2136
- const adHoc = this._adHocAnnotations.get(path);
2137
- if (adHoc) annotations = this.doc.mergeNodesAnnotations(annotations, adHoc);
2138
- }
2139
- annotations?.forEach((an) => {
2140
- this.resolveAnnotationValue(node, an);
2141
- });
2142
- return this;
2143
- }
2144
- /**
2145
- * For non-mutating annotate aliases: merge the target's type-level annotations
2146
- * with the annotate block's own annotations (annotate's take priority).
2147
- */ defineMetadataForAnnotateAlias(annotateNode) {
2148
- const annotateAnnotations = this.doc.evalAnnotationsForNode(annotateNode);
2149
- const targetDecl = this.doc.getDeclarationOwnerNode(annotateNode.targetName);
2150
- const targetAnnotations = targetDecl?.node ? targetDecl.doc.evalAnnotationsForNode(targetDecl.node) : void 0;
2151
- this.doc.mergeNodesAnnotations(targetAnnotations, annotateAnnotations).forEach((an) => {
2152
- this.resolveAnnotationValue(annotateNode, an);
2153
- });
2154
- return this;
2155
- }
2156
- resolveAnnotationValue(node, an) {
2157
- const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
2158
- if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
2159
- else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
2160
- this.model?.annotate(an.name, runtime, multiple);
2161
- }
2162
- emitRefValue(text, origin) {
2163
- const dotIdx = text.indexOf(".");
2164
- if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
2165
- return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
2166
- }
2167
- emitArgValue(aSpec, argToken, origin) {
2168
- if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
2169
- if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
2170
- if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
2171
- if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
2172
- return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
2173
- }
2174
- emitExprNode(node, origin) {
2175
- switch (node.entity) {
2176
- case "query-expr-number": return String(node.value);
2177
- case "query-expr-binary": {
2178
- const { op, left, right } = node;
2179
- return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
2180
- }
2181
- case "query-expr-unary": {
2182
- const { op, operand } = node;
2183
- return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
2184
- }
2185
- case "query-expr-call": {
2186
- const { fn, args } = node;
2187
- return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
2188
- }
2189
- default: return this.emitQueryFieldRef(node, origin);
2190
- }
2191
- }
2192
- emitQueryTree(queryNode, origin) {
2193
- return this.emitQueryExpr(queryNode.expression, origin);
2194
- }
2195
- emitQueryExpr(node, origin) {
2196
- if (isQueryLogical(node)) return this.emitQueryLogical(node, origin);
2197
- return this.emitQueryComparison(node, origin);
2198
- }
2199
- emitQueryLogical(node, origin) {
2200
- if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
2201
- return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
2202
- }
2203
- emitQueryComparison(node, origin) {
2204
- const left = this.emitQueryFieldRef(node.left, origin);
2205
- const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
2206
- const parts = [`left: ${left}`, `op: "${mappedOp}"`];
2207
- if (node.right) {
2208
- if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
2209
- else if ("values" in node.right && node.right.values) {
2210
- const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
2211
- parts.push(`right: [${values}]`);
2212
- } else if ("valueToken" in node.right) parts.push(`right: ${this.emitQueryLiteral(node.right)}`);
2213
- } else if (node.operator === "exists") parts.push("right: true");
2214
- else if (node.operator === "not exists") parts.push("right: false");
2215
- return `{ ${parts.join(", ")} }`;
2216
- }
2217
- emitQueryFieldRef(node, origin) {
2218
- const parts = [];
2219
- if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
2220
- parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
2221
- return `{ ${parts.join(", ")} }`;
2222
- }
2223
- emitQueryLiteral(node) {
2224
- const token = node.valueToken;
2225
- switch (token.type) {
2226
- case "text": return `"${escapeQuotes(token.text)}"`;
2227
- case "number": return token.text;
2228
- case "regexp": {
2229
- const match = /^\/(.*)\/[a-z]*$/.exec(token.text);
2230
- return `"${escapeQuotes(match ? match[1] : token.text)}"`;
2231
- }
2232
- case "identifier":
2233
- if (token.text === "true" || token.text === "false") return token.text;
2234
- if (token.text === "null" || token.text === "undefined") return "null";
2235
- return token.text;
2236
- default: return token.text;
2237
- }
2238
- }
2239
- /**
2240
- * The JS source of an annotation's value, and (for the validation model, which only reads
2241
- * validator annotations: numbers, strings, flags) the runtime value it evaluates to;
2242
- * other argument kinds are opaque there.
2243
- */ computeAnnotationValue(node, an) {
2244
- const origin = this.doc.annotationOrigin(an);
2245
- const spec = this.doc.resolveAnnotation(an.name);
2246
- let targetValue = "true";
2247
- let runtime = true;
2248
- let multiple = false;
2249
- if (spec) {
2250
- multiple = spec.config.multiple;
2251
- const length = spec.arguments.length;
2252
- if (length !== 0) {
2253
- if (Array.isArray(spec.config.argument)) {
2254
- targetValue = "{ ";
2255
- const fields = {};
2256
- let i = 0;
2257
- for (const aSpec of spec.arguments) {
2258
- if (an.args[i]) {
2259
- targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
2260
- fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
2261
- }
2262
- i++;
2263
- }
2264
- targetValue += "}";
2265
- runtime = fields;
2266
- } else if (an.args[0]) {
2267
- const aSpec = spec.arguments[0];
2268
- targetValue = this.emitArgValue(aSpec, an.args[0], origin);
2269
- runtime = runtimeArg(aSpec.type, an.args[0]);
2270
- }
2271
- }
2272
- } else {
2273
- multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
2274
- if (an.args.length > 0) {
2275
- targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
2276
- runtime = runtimeArg(void 0, an.args[0]);
2277
- }
2278
- }
2279
- return {
2280
- value: targetValue,
2281
- multiple: !!multiple,
2282
- runtime
2283
- };
2284
- }
2285
- renderMutatingAnnotateNode(node) {
2286
- const targetName = node.targetName;
2287
- const targetDef = this.resolveTargetDef(targetName);
2288
- this.writeln("// Ad-hoc annotations for ", targetName);
2289
- const allClones = [];
2290
- const entryAccessors = [];
2291
- for (const entry of node.entries) {
2292
- const anns = entry.annotations;
2293
- if (!anns || anns.length === 0) continue;
2294
- const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
2295
- const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
2296
- allClones.push(...clones);
2297
- entryAccessors.push({
2298
- entry,
2299
- accessors
2300
- });
2301
- }
2302
- const cloneKeys = /* @__PURE__ */ new Set();
2303
- for (const clone of allClones) {
2304
- const parentPath = accessorPath(targetName, clone.parentSteps);
2305
- const key = `${parentPath}|${clone.propName}`;
2306
- if (!cloneKeys.has(key)) {
2307
- cloneKeys.add(key);
2308
- this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
2309
- this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
2310
- }
2311
- }
2312
- for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
2313
- const topAnnotations = node.annotations;
2314
- if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
2315
- this.writeln();
2316
- }
2317
- emitMutatingAnnotations(node, annotations, steps, targetName) {
2318
- const accessor = accessorPath(targetName, steps);
2319
- const cleared = /* @__PURE__ */ new Set();
2320
- for (const an of annotations) {
2321
- const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
2322
- if (multiple) {
2323
- if (!cleared.has(an.name)) {
2324
- const spec = this.doc.resolveAnnotation(an.name);
2325
- if (!spec || spec.config.mergeStrategy !== "append") {
2326
- this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
2327
- this.model?.deleteAnnotation(targetName, steps, an.name);
2328
- }
2329
- cleared.add(an.name);
2330
- }
2331
- this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
2332
- } else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
2333
- this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
2334
- }
2335
- }
2336
- resolveTargetDef(targetName) {
2337
- const unwound = this.doc.unwindType(targetName);
2338
- if (!unwound?.def) return;
2339
- let def = unwound.def;
2340
- if (isInterface(def)) def = def.getDefinition() || def;
2341
- return def;
2342
- }
2343
- /**
2344
- * Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
2345
- * Computes exact paths at compile time by walking the AST,
2346
- * so the generated JS accesses props directly without runtime search.
2347
- * Returns multiple paths when a property appears in multiple union branches.
2348
- */ buildMutatingAccessors(targetDef, parts) {
2349
- let accessors = [{
2350
- steps: ["type"],
2351
- def: targetDef
2352
- }];
2353
- const clones = [];
2354
- for (let i = 0; i < parts.length; i++) {
2355
- const last = i === parts.length - 1;
2356
- const nextAccessors = [];
2357
- for (const { steps, def } of accessors) {
2358
- const results = this.buildPropPaths(def, parts[i]);
2359
- const found = results.length > 0 ? results : [{
2360
- steps: [["props", parts[i]]],
2361
- propDef: void 0
2362
- }];
2363
- for (const result of found) {
2364
- if (!last && result.propDef && isRef(result.propDef)) clones.push({
2365
- parentSteps: steps,
2366
- propName: parts[i]
2367
- });
2368
- const next = [...steps, ...result.steps];
2369
- if (!last) next.push("type");
2370
- nextAccessors.push({
2371
- steps: next,
2372
- def: result.propDef
2373
- });
2374
- }
2375
- }
2376
- accessors = nextAccessors;
2377
- }
2378
- return {
2379
- accessors: accessors.map((a) => a.steps),
2380
- clones
2381
- };
2382
- }
2383
- /**
2384
- * Finds a property in a type tree at compile time, returning all
2385
- * matching accessor steps and prop definitions for further chaining.
2386
- * Returns multiple results when the same property appears in different union branches.
2387
- */ buildPropPaths(def, propName) {
2388
- if (!def) return [];
2389
- def = this.doc.mergeIntersection(def);
2390
- if (isRef(def)) {
2391
- const ref = def;
2392
- const unwound = this.doc.unwindType(ref.id, ref.chain)?.def;
2393
- return this.buildPropPaths(unwound, propName);
2394
- }
2395
- if (isInterface(def)) return this.buildPropPaths(def.getDefinition(), propName);
2396
- if (isStructure(def)) {
2397
- const prop = def.props.get(propName);
2398
- if (prop) return [{
2399
- steps: [["props", propName]],
2400
- propDef: prop.getDefinition()
2401
- }];
2402
- return [];
2403
- }
2404
- if (isGroup(def)) {
2405
- const items = def.unwrap();
2406
- const results = [];
2407
- for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
2408
- steps: [
2409
- ["items", i],
2410
- "type",
2411
- ...result.steps
2412
- ],
2413
- propDef: result.propDef
2414
- });
2415
- return results;
2416
- }
2417
- return [];
2418
- }
2419
- constructor(doc, opts) {
2420
- super(doc), _define_property(this, "opts", void 0), _define_property(this, "postAnnotate", void 0), _define_property(this, "_adHocAnnotations", void 0), _define_property(this, "_propPath", void 0), _define_property(this, "typeIds", void 0), _define_property(this, "_unusedJs", void 0), _define_property(this, "_extendsRefs", void 0), _define_property(this, "_refSynthInfo", void 0), _define_property(this, "_synthImports", void 0), _define_property(this, "_synthComputed", void 0), _define_property(this, "_synthTaken", void 0), _define_property(this, "_synthAllocated", void 0), _define_property(this, "_synthPathCache", void 0), _define_property(this, "_ownerCache", void 0), _define_property(this, "model", void 0), _define_property(this, "modelClasses", void 0), _define_property(this, "_declTypes", void 0), this.opts = opts, this.postAnnotate = [], this._adHocAnnotations = null, this._propPath = [], this.typeIds = /* @__PURE__ */ new Map(), this._refSynthInfo = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthComputed = false, this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map(), this.modelClasses = [], this._declTypes = /* @__PURE__ */ new Map();
2421
- if (opts?.compileValidators) this.model = new ValidationModel();
2422
- }
2423
- };
2424
-
2425
- //#endregion
2426
- //#region packages/typescript/src/plugin.ts
2427
- /**
2428
- * Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
2429
- * (used by `unplugin-atscript`'s `compileValidators` option).
2430
- */ const JS_COMPILED_FORMAT = "js:compiled";
2431
- const JS_INTERPRETED_FORMAT = "js:interpreted";
2432
- /**
2433
- * Resolves the effective JSON schema mode from plugin options.
2434
- */ function resolveJsonSchemaMode(opts) {
2435
- if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
2436
- return false;
2437
- }
2438
- const tsPlugin = (opts) => {
2439
- return {
2440
- name: "typescript",
2441
- render(doc, format) {
2442
- if (format === "dts" || format === DEFAULT_FORMAT) return [{
2443
- fileName: `${doc.name}.d.ts`,
2444
- content: new TypeRenderer(doc, opts).render()
2445
- }];
2446
- if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
2447
- const jsOpts = format === "js" ? opts : {
2448
- ...opts,
2449
- compileValidators: format === JS_COMPILED_FORMAT
2450
- };
2451
- return [{
2452
- fileName: `${doc.name}.js`,
2453
- content: new JsRenderer(doc, jsOpts).render()
2454
- }];
2455
- }
2456
- },
2457
- async buildEnd(output, format, repo) {
2458
- if (format === "dts" || format === DEFAULT_FORMAT) {
2459
- const annotations = await repo.getUsedAnnotations();
2460
- const tags = await repo.getPrimitivesTags() || /* @__PURE__ */ new Set();
2461
- const rendered = [];
2462
- for (const [key, val] of Object.entries(annotations)) {
2463
- const multiple = val.multiple;
2464
- const typeLine = Array.from(val.types).map((t) => {
2465
- if (t.type === "object" && "props" in t) return `{ ${Object.entries(t.props).map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
2466
- else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
2467
- }).join(" | ");
2468
- rendered.push(`${wrapProp(key)}: ${multiple ? "(" : ""}${typeLine}${multiple ? ")[]" : ""}`);
2469
- }
2470
- const renderedTags = Array.from(tags).map((f) => `"${escapeQuotes(f)}"`).join(" | ");
2471
- output.push({
2472
- 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",
2473
- fileName: "atscript.d.ts",
2474
- source: "",
2475
- target: path.join(repo.root, "atscript.d.ts")
2476
- });
2477
- }
2478
- }
2479
- };
2480
- };
2481
-
2482
- //#endregion
2483
- export { JS_INTERPRETED_FORMAT as n, tsPlugin as r, JS_COMPILED_FORMAT as t };