@atscript/typescript 0.1.109 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1644 +0,0 @@
1
- import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-CioBVi6F.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$3(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$3(this, "lines", []);
100
- _define_property$3(this, "currentLine", "");
101
- _define_property$3(this, "indentLevel", 0);
102
- _define_property$3(this, "indentSize", 2);
103
- _define_property$3(this, "blockStack", []);
104
- }
105
- };
106
-
107
- //#endregion
108
- //#region packages/typescript/src/codegen/base-renderer.ts
109
- function _define_property$2(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$2(this, "doc", void 0), _define_property$2(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$1(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$1(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/codegen/js-renderer.ts
638
- function _define_property(obj, key, value) {
639
- if (key in obj) Object.defineProperty(obj, key, {
640
- value,
641
- enumerable: true,
642
- configurable: true,
643
- writable: true
644
- });
645
- else obj[key] = value;
646
- return obj;
647
- }
648
- const QUERY_OP_MAP = {
649
- "=": "$eq",
650
- "!=": "$ne",
651
- ">": "$gt",
652
- ">=": "$gte",
653
- "<": "$lt",
654
- "<=": "$lte",
655
- "in": "$in",
656
- "not in": "$nin",
657
- "matches": "$regex",
658
- "exists": "$exists",
659
- "not exists": "$exists"
660
- };
661
- /** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
662
- "expect.min": "minValue",
663
- "expect.max": "maxValue",
664
- "expect.exclusiveMin": "exclusiveMinValue",
665
- "expect.exclusiveMax": "exclusiveMaxValue"
666
- };
667
- const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
668
- var JsRenderer = class extends BaseRenderer {
669
- /**
670
- * Relative imports get the configured `moduleExtension`; bare specifiers
671
- * always keep `.as` — they resolve through the package's `exports` map.
672
- */ transformFromPath(path) {
673
- return isBareSpecifier(path) ? `${path}.as` : `${path}${this.opts?.moduleExtension ?? ".as"}`;
674
- }
675
- /**
676
- * Override base `unused` to subtract symbols that the JS output references
677
- * transitively through `extends`-resolved parent prop trees. Without this,
678
- * cross-file `extends` strips the imports needed by inherited `.refTo()` calls.
679
- */ get unused() {
680
- if (this._unusedJs) return this._unusedJs;
681
- const base = new Set(this.doc.getUnusedTokens().map((t) => t.text));
682
- for (const ref of this.getExtendsRefs().keys()) if (ref.id) base.delete(ref.id);
683
- return this._unusedJs = base;
684
- }
685
- getExtendsRefs() {
686
- if (this._extendsRefs) return this._extendsRefs;
687
- const out = /* @__PURE__ */ new Map();
688
- const visitedInterfaces = /* @__PURE__ */ new Set();
689
- for (const node of this.doc.nodes) if (isInterface(node) && node.hasExtends) this.walkExtendsParents(node, this.doc, out, visitedInterfaces);
690
- return this._extendsRefs = out;
691
- }
692
- walkRefs(node, visited, visit) {
693
- if (!node || visited.has(node)) return;
694
- visited.add(node);
695
- if (isRef(node)) {
696
- visit(node);
697
- return;
698
- }
699
- if (isGroup(node)) {
700
- for (const item of node.unwrap()) this.walkRefs(item, visited, visit);
701
- return;
702
- }
703
- if (isArray(node) || isProp(node)) this.walkRefs(node.getDefinition(), visited, visit);
704
- }
705
- walkExtendsParents(iface, doc, out, visited) {
706
- if (visited.has(iface)) return;
707
- visited.add(iface);
708
- const visitedNodes = /* @__PURE__ */ new Set();
709
- for (const token of iface.extendsTokens) {
710
- const unwound = doc.unwindType(token.text);
711
- if (!unwound?.def || !isInterface(unwound.def)) continue;
712
- const parentInterface = unwound.def;
713
- const parentDoc = unwound.doc;
714
- this.walkRefs(parentInterface.getDefinition(), visitedNodes, (ref) => {
715
- if (!out.has(ref)) out.set(ref, parentDoc);
716
- });
717
- if (parentInterface.hasExtends) this.walkExtendsParents(parentInterface, parentDoc, out, visited);
718
- }
719
- }
720
- computeSynthesizedImports() {
721
- if (this._synthComputed) return;
722
- this._synthComputed = true;
723
- const refToOriginDoc = this.getExtendsRefs();
724
- if (refToOriginDoc.size === 0) return;
725
- for (const [refNode, originDoc] of refToOriginDoc) {
726
- const refId = refNode.id;
727
- if (!refId) continue;
728
- const ownerInfo = this.resolveOwner(originDoc, refId);
729
- if (!ownerInfo?.doc || ownerInfo.doc === this.doc) continue;
730
- if (ownerInfo.node && isPrimitive(ownerInfo.node)) continue;
731
- const info = this.synthBinding(refId, ownerInfo);
732
- if (!info) continue;
733
- this._refSynthInfo.set(refNode, info);
734
- }
735
- }
736
- getSynthTaken() {
737
- if (!this._synthTaken) {
738
- this._synthTaken = new Set(this.doc.registry.definitions.keys());
739
- for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
740
- }
741
- return this._synthTaken;
742
- }
743
- getSynthPath(ownerDoc) {
744
- if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
745
- return this._synthPathCache.get(ownerDoc);
746
- }
747
- synthBinding(name, ownerInfo) {
748
- const synthPath = this.getSynthPath(ownerInfo.doc);
749
- if (!synthPath) return;
750
- const allocKey = `${synthPath}::${name}`;
751
- let info = this._synthAllocated.get(allocKey);
752
- if (!info) {
753
- info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
754
- this._synthAllocated.set(allocKey, info);
755
- }
756
- return info;
757
- }
758
- /**
759
- * Binding for a type name used by an annotation argument (`ref` / qualified
760
- * query field refs). An annotation inherited from another document (chain ref
761
- * or `extends`) carries names that only that document imports, so when the
762
- * name does not resolve here to the same declaration, a synthesized import is
763
- * allocated (lazily, spliced into the header by `render()`).
764
- */ annotationTypeName(typeName, origin) {
765
- if (!origin || origin === this.doc) return typeName;
766
- const theirs = this.resolveOwner(origin, typeName);
767
- if (!theirs?.doc || !theirs.node || theirs.doc === this.doc || isPrimitive(theirs.node)) return typeName;
768
- const mine = this.resolveOwner(this.doc, typeName);
769
- if (mine?.doc === theirs.doc && mine.node === theirs.node) return typeName;
770
- return this.synthBinding(typeName, {
771
- doc: theirs.doc,
772
- node: theirs.node
773
- })?.alias ?? typeName;
774
- }
775
- resolveOwner(fromDoc, refId) {
776
- const key = `${fromDoc.id}::${refId}`;
777
- let v = this._ownerCache.get(key);
778
- if (v === void 0 && !this._ownerCache.has(key)) {
779
- v = fromDoc.getDeclarationOwnerNode(refId);
780
- this._ownerCache.set(key, v);
781
- }
782
- return v;
783
- }
784
- allocateSynthInfo(refId, synthPath, ownerInfo, taken) {
785
- const ownerDoc = ownerInfo.doc;
786
- const ownerNode = ownerInfo.node;
787
- if (this.doc.importedDefs.get(refId)?.text === synthPath) return {
788
- alias: refId,
789
- ownerDoc,
790
- ownerNode
791
- };
792
- const alias = this.allocAlias(refId, taken);
793
- let group = this._synthImports.get(synthPath);
794
- if (!group) {
795
- group = [];
796
- this._synthImports.set(synthPath, group);
797
- }
798
- group.push({
799
- name: refId,
800
- alias
801
- });
802
- return {
803
- alias,
804
- ownerDoc,
805
- ownerNode
806
- };
807
- }
808
- allocAlias(name, taken) {
809
- if (!taken.has(name)) {
810
- taken.add(name);
811
- return name;
812
- }
813
- let n = 1;
814
- while (taken.has(`${name}_${n}`)) n++;
815
- const alias = `${name}_${n}`;
816
- taken.add(alias);
817
- return alias;
818
- }
819
- computeSynthPath(ownerDoc) {
820
- if (isBareId(ownerDoc.id)) return ownerDoc.id.slice(5, -3);
821
- if (!ownerDoc.id.startsWith("file://")) return;
822
- return getRelPath(this.doc.id, ownerDoc.id);
823
- }
824
- pre() {
825
- this.writeln("// prettier-ignore-start");
826
- this.writeln("/* eslint-disable */");
827
- this.writeln("/* oxlint-disable */");
828
- let hasMutatingAnnotate = false;
829
- const nodesByName = /* @__PURE__ */ new Map();
830
- for (const node of this.doc.nodes) {
831
- if (node.entity === "annotate" && node.isMutating) hasMutatingAnnotate = true;
832
- if (node.__typeId !== null && node.__typeId !== void 0 && node.id) {
833
- const name = node.id;
834
- if (!nodesByName.has(name)) nodesByName.set(name, []);
835
- nodesByName.get(name).push(node);
836
- }
837
- }
838
- for (const [name, nodes] of nodesByName) if (nodes.length === 1) this.typeIds.set(nodes[0], name);
839
- else for (let i = 0; i < nodes.length; i++) this.typeIds.set(nodes[i], `${name}__${i + 1}`);
840
- const imports = ["defineAnnotatedType as $", "annotate as $a"];
841
- if (hasMutatingAnnotate) imports.push("cloneRefProp as $c");
842
- const jsonSchemaMode = resolveJsonSchemaMode(this.opts);
843
- if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
844
- if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
845
- if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
846
- this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
847
- this.computeSynthesizedImports();
848
- this.writeln(SYNTH_IMPORTS_MARKER);
849
- }
850
- render() {
851
- const out = super.render();
852
- const lines = [];
853
- for (const [synthPath, names] of this._synthImports) {
854
- const list = names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ");
855
- lines.push(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
856
- }
857
- const marker = `${SYNTH_IMPORTS_MARKER}\n`;
858
- return out.replace(marker, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
859
- }
860
- buildAdHocMap(annotateNodes) {
861
- const map = /* @__PURE__ */ new Map();
862
- for (const annotateNode of annotateNodes) for (const entry of annotateNode.entries) {
863
- const path = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)].join(".") : entry.id;
864
- const anns = entry.annotations || [];
865
- if (anns.length > 0) {
866
- const existing = map.get(path);
867
- if (existing) existing.push(...anns);
868
- else map.set(path, [...anns]);
869
- }
870
- }
871
- return map.size > 0 ? map : null;
872
- }
873
- /**
874
- * Checks if any ad-hoc annotation path extends beyond the current _propPath,
875
- * meaning annotations target properties inside a referenced type.
876
- */ hasAdHocAnnotationsThroughRef() {
877
- if (!this._adHocAnnotations || this._propPath.length === 0) return false;
878
- const prefix = `${this._propPath.join(".")}.`;
879
- for (const key of this._adHocAnnotations.keys()) if (key.startsWith(prefix)) return true;
880
- return false;
881
- }
882
- post() {
883
- for (const node of this.postAnnotate) if (node.entity === "annotate") {
884
- const annotateNode = node;
885
- if (annotateNode.isMutating) this.renderMutatingAnnotateNode(annotateNode);
886
- else {
887
- const unwound = this.doc.unwindType(annotateNode.targetName);
888
- if (unwound?.def) {
889
- let def = this.doc.mergeIntersection(unwound.def);
890
- if (isInterface(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
891
- else def = def.getDefinition() || def;
892
- this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
893
- this.annotateType(def, node.id);
894
- this._adHocAnnotations = null;
895
- this.indent();
896
- this.defineMetadataForAnnotateAlias(annotateNode);
897
- this.unindent();
898
- this.writeln();
899
- }
900
- }
901
- } else {
902
- let def = node.getDefinition();
903
- if (isInterface(node) && node.hasExtends) {
904
- const resolved = this.doc.resolveInterfaceExtends(node);
905
- if (resolved) def = resolved;
906
- }
907
- this.annotateType(def, node.id);
908
- this.indent().defineMetadata(node).unindent();
909
- this.writeln();
910
- }
911
- this.writeln("// prettier-ignore-end");
912
- super.post();
913
- }
914
- renderClassStatics(node) {
915
- this.writeln("static __is_atscript_annotated_type = true");
916
- this.writeln("static type = {}");
917
- this.writeln("static metadata = new Map()");
918
- const typeId = this.typeIds.get(node);
919
- if (typeId) this.writeln(`static id = "${typeId}"`);
920
- this.renderJsonSchemaMethod(node);
921
- this.renderExampleDataMethod(node);
922
- this.renderDimMeasure(node);
923
- }
924
- renderInterface(node) {
925
- this.renderDefinitionClass(node);
926
- }
927
- renderType(node) {
928
- this.renderDefinitionClass(node);
929
- }
930
- renderAnnotate(node) {
931
- if (node.isMutating) {
932
- this.postAnnotate.push(node);
933
- return;
934
- }
935
- if (!this.doc.unwindType(node.targetName)?.def) return;
936
- this.renderDefinitionClass(node);
937
- }
938
- renderDefinitionClass(node) {
939
- this.writeln();
940
- const exported = node.token("export")?.text === "export";
941
- this.write(exported ? "export " : "");
942
- this.write(`class ${node.id} `);
943
- this.blockln("{}");
944
- this.renderClassStatics(node);
945
- this.popln();
946
- this.postAnnotate.push(node);
947
- this.writeln();
948
- }
949
- renderJsonSchemaMethod(node) {
950
- const mode = resolveJsonSchemaMode(this.opts);
951
- if (node.countAnnotations("emit.jsonSchema") > 0 || mode === "bundle") {
952
- const schema = JSON.stringify(buildJsonSchema(this.toAnnotatedType(node)));
953
- this.writeln("static toJsonSchema() {");
954
- this.indent().writeln(`return ${schema}`).unindent();
955
- this.writeln("}");
956
- } else if (mode === "lazy") {
957
- this.writeln("static toJsonSchema() {");
958
- this.indent().writeln("return this._jsonSchema ?? (this._jsonSchema = $$(this))").unindent();
959
- this.writeln("}");
960
- } else {
961
- this.writeln("static toJsonSchema() {");
962
- this.indent().writeln("$d(\"JSON Schema\", \"jsonSchema\", \"emit.jsonSchema\")").unindent();
963
- this.writeln("}");
964
- }
965
- }
966
- renderExampleDataMethod(_node) {
967
- if (this.opts?.exampleData) {
968
- this.writeln("static toExampleData() {");
969
- this.indent().writeln("return $e(this, { mode: \"example\" })").unindent();
970
- this.writeln("}");
971
- }
972
- }
973
- renderDimMeasure(node) {
974
- if (!isInterface(node)) return;
975
- const interfaceNode = node;
976
- if (!isDbEntityNode(interfaceNode)) return;
977
- let struct;
978
- if (interfaceNode.hasExtends) struct = this.doc.resolveInterfaceExtends(interfaceNode);
979
- if (!struct) struct = interfaceNode.getDefinition();
980
- if (!struct || !isStructure(struct)) return;
981
- const structNode = struct;
982
- const dims = [];
983
- const measures = [];
984
- for (const [name, prop] of structNode.props) {
985
- if (prop.token("identifier")?.pattern) continue;
986
- if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
987
- if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
988
- }
989
- if (dims.length > 0) this.writeln(`static dimensions = [${dims.map((d) => `'${escapeQuotes(d)}'`).join(", ")}]`);
990
- if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
991
- }
992
- toAnnotatedType(node) {
993
- return this.toAnnotatedHandle(node).$type;
994
- }
995
- toAnnotatedHandle(node, skipAnnotations = false) {
996
- if (!node) return defineAnnotatedType();
997
- switch (node.entity) {
998
- case "interface":
999
- case "type": {
1000
- let def = node.getDefinition();
1001
- if (isInterface(node) && node.hasExtends) {
1002
- const resolved = this.doc.resolveInterfaceExtends(node);
1003
- if (resolved) def = resolved;
1004
- }
1005
- const handle = this.toAnnotatedHandle(def, true);
1006
- const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
1007
- if (typeId) handle.id(typeId);
1008
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1009
- }
1010
- case "prop": {
1011
- const prop = node;
1012
- const def = prop.getDefinition();
1013
- const handle = this.toAnnotatedHandle(def, true);
1014
- if (!skipAnnotations) {
1015
- this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(prop));
1016
- if (prop.token("optional")) handle.optional();
1017
- }
1018
- return handle;
1019
- }
1020
- case "ref": {
1021
- const ref = node;
1022
- const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1023
- const handle = this.toAnnotatedHandle(decl, true);
1024
- if (skipAnnotations) return handle;
1025
- const own = this.doc.evalAnnotationsForNode(node);
1026
- const referred = this.refTargetAnnotations(ref, decl);
1027
- return this.applyExpectAnnotations(handle, referred ? this.doc.mergeNodesAnnotations(referred, own) : own);
1028
- }
1029
- case "primitive": {
1030
- const prim = node;
1031
- const handle = defineAnnotatedType();
1032
- handle.designType(prim.id === "never" ? "never" : prim.config.type);
1033
- if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1034
- return handle;
1035
- }
1036
- case "const": {
1037
- const c = node;
1038
- const handle = defineAnnotatedType();
1039
- const t = c.token("identifier")?.type;
1040
- handle.designType(t === "number" ? "number" : "string");
1041
- handle.value(t === "number" ? Number(c.id) : c.id);
1042
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1043
- }
1044
- case "structure": {
1045
- const struct = node;
1046
- const handle = defineAnnotatedType("object");
1047
- for (const prop of Array.from(struct.props.values())) {
1048
- const propHandle = this.toAnnotatedHandle(prop);
1049
- const pattern = prop.token("identifier")?.pattern;
1050
- if (pattern) handle.propPattern(pattern, propHandle.$type);
1051
- else handle.prop(prop.id, propHandle.$type);
1052
- }
1053
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1054
- }
1055
- case "group": {
1056
- const group = node;
1057
- const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection");
1058
- for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1059
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1060
- }
1061
- case "tuple": {
1062
- const group = node;
1063
- const handle = defineAnnotatedType("tuple");
1064
- for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
1065
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1066
- }
1067
- case "array": {
1068
- const arr = node;
1069
- const handle = defineAnnotatedType("array");
1070
- handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
1071
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1072
- }
1073
- default: {
1074
- const handle = defineAnnotatedType();
1075
- return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
1076
- }
1077
- }
1078
- }
1079
- applyExpectAnnotations(handle, annotations) {
1080
- annotations?.forEach((a) => {
1081
- switch (a.name) {
1082
- case "expect.minLength":
1083
- case "expect.maxLength":
1084
- if (a.args[0]) handle.annotate(a.name, {
1085
- length: Number(a.args[0].text),
1086
- message: a.args[1]?.text
1087
- });
1088
- break;
1089
- case "expect.min":
1090
- case "expect.max":
1091
- case "expect.exclusiveMin":
1092
- case "expect.exclusiveMax":
1093
- if (a.args[0]) handle.annotate(a.name, {
1094
- [NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
1095
- message: a.args[1]?.text
1096
- });
1097
- break;
1098
- case "expect.pattern":
1099
- handle.annotate(a.name, {
1100
- pattern: a.args[0]?.text || "",
1101
- flags: a.args[1]?.text,
1102
- message: a.args[2]?.text
1103
- }, true);
1104
- break;
1105
- case "expect.int":
1106
- case "meta.required":
1107
- handle.annotate(a.name, true);
1108
- break;
1109
- case "expect.array.uniqueItems":
1110
- case "expect.array.key":
1111
- handle.annotate(a.name, { message: a.args[0]?.text });
1112
- break;
1113
- default:
1114
- }
1115
- });
1116
- return handle;
1117
- }
1118
- annotateType(_node, name) {
1119
- if (!_node) return this;
1120
- const node = this.doc.mergeIntersection(_node);
1121
- let kind = node.entity;
1122
- switch (node.entity) {
1123
- case "ref": {
1124
- const ref = node;
1125
- const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
1126
- const primitive = this.inlinedPrimitive(ref, decl);
1127
- if (primitive) {
1128
- this.annotateType(primitive, name);
1129
- return this;
1130
- }
1131
- if (this._adHocAnnotations && this.hasAdHocAnnotationsThroughRef()) {
1132
- let resolved = decl ? this.doc.mergeIntersection(decl) : void 0;
1133
- if (resolved && isInterface(resolved)) resolved = resolved.getDefinition() || resolved;
1134
- if (resolved) {
1135
- this.annotateType(resolved, name);
1136
- return this;
1137
- }
1138
- }
1139
- const chain = ref.hasChain ? `, [${ref.chain.map((c) => `"${escapeQuotes(c.text)}"`).join(", ")}]` : "";
1140
- const synth = this._refSynthInfo.get(ref);
1141
- const ownerDecl = synth ? {
1142
- doc: synth.ownerDoc,
1143
- node: synth.ownerNode
1144
- } : this.resolveOwner(this.doc, ref.id);
1145
- const refName = synth?.alias ?? ref.id;
1146
- const refExpr = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false) ? `() => ${refName}` : refName;
1147
- this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
1148
- if (!ref.hasChain) {
1149
- if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
1150
- this.resolveAnnotationValue(ownerDecl.node, an);
1151
- });
1152
- }
1153
- this.unindent();
1154
- return this;
1155
- }
1156
- case "primitive":
1157
- this.definePrimitive(node, name);
1158
- return this;
1159
- case "const":
1160
- this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
1161
- return this;
1162
- case "structure":
1163
- this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
1164
- return this;
1165
- case "group":
1166
- kind = node.op === "|" ? "union" : "intersection";
1167
- this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1168
- return this;
1169
- case "tuple":
1170
- this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
1171
- return this;
1172
- case "array":
1173
- this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
1174
- return this;
1175
- default: return this;
1176
- }
1177
- }
1178
- defineConst(node) {
1179
- const t = node.token("identifier")?.type;
1180
- const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
1181
- this.writeln(`.designType("${escapeQuotes(designType)}")`);
1182
- this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
1183
- return this;
1184
- }
1185
- definePrimitive(node, name) {
1186
- this.renderPrimitiveDef(node.id === "never" ? "never" : node.config.type, name);
1187
- this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
1188
- return this;
1189
- }
1190
- renderPrimitiveDef(def, name) {
1191
- const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
1192
- if (!def) return this.writeln(`$(${d()}).designType("any")`);
1193
- if (typeof def === "string") return this.writeln(`$(${d()}).designType("${def === "void" ? "undefined" : def}")`);
1194
- switch (def.kind) {
1195
- case "final": return this.writeln(`$(${d()}).designType("${def.value === "void" ? "undefined" : def.value}")`);
1196
- case "union":
1197
- case "intersection":
1198
- case "tuple":
1199
- this.writeln(`$(${d(def.kind)})`);
1200
- this.indent();
1201
- for (const itemDef of def.items) {
1202
- this.write(`.item(`);
1203
- this.indent();
1204
- this.renderPrimitiveDef(itemDef);
1205
- this.writeln(".$type");
1206
- this.unindent();
1207
- this.write(`)`);
1208
- }
1209
- this.unindent();
1210
- return;
1211
- case "array":
1212
- this.writeln(`$(${d("array")})`);
1213
- this.indent();
1214
- this.write(".of(");
1215
- this.indent();
1216
- this.renderPrimitiveDef(def.of);
1217
- this.writeln(`.$type`);
1218
- this.unindent();
1219
- this.writeln(`)`);
1220
- this.unindent();
1221
- return;
1222
- case "object":
1223
- this.writeln(`$(${d("object")})`);
1224
- this.indent();
1225
- for (const [key, propDef] of Object.entries(def.props)) {
1226
- const optional = typeof propDef === "object" && propDef.optional;
1227
- this.writeln(`.prop(`);
1228
- this.indent();
1229
- this.writeln(`"${escapeQuotes(key)}",`);
1230
- this.renderPrimitiveDef(propDef);
1231
- if (optional) this.writeln(".optional()");
1232
- this.writeln(".$type");
1233
- this.unindent();
1234
- this.write(`)`);
1235
- }
1236
- for (const [key, propDef] of Object.entries(def.propsPatterns)) {
1237
- const optional = typeof propDef === "object" && propDef.optional;
1238
- this.writeln(`.propPattern(`);
1239
- this.indent();
1240
- this.writeln(`${key},`);
1241
- this.renderPrimitiveDef(propDef);
1242
- if (optional) this.writeln(".optional()");
1243
- this.writeln(".$type");
1244
- this.unindent();
1245
- this.write(`)`);
1246
- }
1247
- this.unindent();
1248
- return;
1249
- default: return this.writeln(`$(${d()}).designType("any")`);
1250
- }
1251
- }
1252
- defineObject(node) {
1253
- const props = Array.from(node.props.values());
1254
- for (const prop of props) {
1255
- const pattern = prop.token("identifier")?.pattern;
1256
- const optional = !!prop.token("optional");
1257
- this._propPath.push(prop.id);
1258
- if (pattern) {
1259
- this.writeln(`.propPattern(`);
1260
- this.indent();
1261
- this.writeln(`/${pattern.source}/${pattern.flags},`);
1262
- } else {
1263
- this.writeln(`.prop(`);
1264
- this.indent();
1265
- this.writeln(`"${escapeQuotes(prop.id)}",`);
1266
- }
1267
- this.annotateType(prop.getDefinition());
1268
- this.indent().defineMetadata(prop).unindent();
1269
- if (optional) this.writeln(" .optional()");
1270
- this.writeln(" .$type");
1271
- this.unindent();
1272
- this.write(`)`);
1273
- this._propPath.pop();
1274
- }
1275
- this.writeln();
1276
- return this;
1277
- }
1278
- defineGroup(node) {
1279
- const items = node.unwrap();
1280
- for (const item of items) this.write(".item(").indent().annotateType(item).defineInlinePrimitiveMetadata(item).write(" .$type").writeln(`)`).unindent();
1281
- return this;
1282
- }
1283
- defineArray(node) {
1284
- const of = node.getDefinition();
1285
- this.write(".of(").indent().annotateType(of).defineInlinePrimitiveMetadata(of).write(" .$type").writeln(`)`).unindent();
1286
- return this;
1287
- }
1288
- /**
1289
- * A built-in primitive extension used directly as a union / tuple member or array
1290
- * element (`number.int | null`, `string.email[]`) is inlined by `annotateType` without
1291
- * its built-in annotations (`expect.int`, the email pattern, …) — a prop gets them
1292
- * through `defineMetadata`, a member has no prop to carry them, so emit them here.
1293
- */ defineInlinePrimitiveMetadata(node) {
1294
- const primitive = node && this.inlinedPrimitive(node);
1295
- if (primitive?.annotations?.length) {
1296
- this.indent();
1297
- for (const an of primitive.annotations) this.resolveAnnotationValue(primitive, an);
1298
- this.unindent();
1299
- }
1300
- return this;
1301
- }
1302
- /**
1303
- * The built-in primitive a ref is inlined as by `annotateType` — not a named alias that
1304
- * resolves to one (`type MyString = string`), which is emitted as a `refTo`.
1305
- */ inlinedPrimitive(node, decl = isRef(node) ? this.doc.unwindType(node.id, node.chain)?.def : void 0) {
1306
- if (!isRef(node) || !isPrimitive(decl)) return;
1307
- const ownerDecl = this.resolveOwner(this.doc, node.id);
1308
- if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) return;
1309
- return decl;
1310
- }
1311
- /** Annotations a ref inherits from its target (see `annotateType`'s ref case). */ refTargetAnnotations(ref, decl) {
1312
- const primitive = this.inlinedPrimitive(ref, decl);
1313
- if (primitive) return primitive.annotations;
1314
- if (ref.hasChain) return;
1315
- const ownerDecl = this.resolveOwner(this.doc, ref.id);
1316
- return ownerDecl?.node ? ownerDecl.doc.evalReferredAnnotations(ownerDecl.node) : void 0;
1317
- }
1318
- defineMetadata(node) {
1319
- let annotations;
1320
- const nodeDef = node.getDefinition?.();
1321
- if (nodeDef && isRef(nodeDef)) {
1322
- const refNode = nodeDef;
1323
- if (!refNode.hasChain) {
1324
- const resolved = this.doc.unwindType(refNode.id, refNode.chain)?.def;
1325
- if (resolved && !isPrimitive(resolved)) annotations = node.annotations ?? [];
1326
- else if (resolved && isPrimitive(resolved)) {
1327
- const ownerDecl = this.doc.getDeclarationOwnerNode(refNode.id);
1328
- if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) annotations = node.annotations ?? [];
1329
- }
1330
- }
1331
- }
1332
- if (annotations === void 0) annotations = this.doc.evalAnnotationsForNode(node);
1333
- if (this._adHocAnnotations && this._propPath.length > 0) {
1334
- const path = this._propPath.join(".");
1335
- const adHoc = this._adHocAnnotations.get(path);
1336
- if (adHoc) annotations = this.doc.mergeNodesAnnotations(annotations, adHoc);
1337
- }
1338
- annotations?.forEach((an) => {
1339
- this.resolveAnnotationValue(node, an);
1340
- });
1341
- return this;
1342
- }
1343
- /**
1344
- * For non-mutating annotate aliases: merge the target's type-level annotations
1345
- * with the annotate block's own annotations (annotate's take priority).
1346
- */ defineMetadataForAnnotateAlias(annotateNode) {
1347
- const annotateAnnotations = this.doc.evalAnnotationsForNode(annotateNode);
1348
- const targetDecl = this.doc.getDeclarationOwnerNode(annotateNode.targetName);
1349
- const targetAnnotations = targetDecl?.node ? targetDecl.doc.evalAnnotationsForNode(targetDecl.node) : void 0;
1350
- this.doc.mergeNodesAnnotations(targetAnnotations, annotateAnnotations).forEach((an) => {
1351
- this.resolveAnnotationValue(annotateNode, an);
1352
- });
1353
- return this;
1354
- }
1355
- resolveAnnotationValue(node, an) {
1356
- const { value, multiple } = this.computeAnnotationValue(node, an);
1357
- if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
1358
- else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
1359
- }
1360
- emitRefValue(text, origin) {
1361
- const dotIdx = text.indexOf(".");
1362
- if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
1363
- return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1364
- }
1365
- emitArgValue(aSpec, argToken, origin) {
1366
- if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
1367
- if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
1368
- if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
1369
- if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
1370
- return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
1371
- }
1372
- emitExprNode(node, origin) {
1373
- switch (node.entity) {
1374
- case "query-expr-number": return String(node.value);
1375
- case "query-expr-binary": {
1376
- const { op, left, right } = node;
1377
- return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
1378
- }
1379
- case "query-expr-unary": {
1380
- const { op, operand } = node;
1381
- return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
1382
- }
1383
- case "query-expr-call": {
1384
- const { fn, args } = node;
1385
- return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
1386
- }
1387
- default: return this.emitQueryFieldRef(node, origin);
1388
- }
1389
- }
1390
- emitQueryTree(queryNode, origin) {
1391
- return this.emitQueryExpr(queryNode.expression, origin);
1392
- }
1393
- emitQueryExpr(node, origin) {
1394
- if (isQueryLogical(node)) return this.emitQueryLogical(node, origin);
1395
- return this.emitQueryComparison(node, origin);
1396
- }
1397
- emitQueryLogical(node, origin) {
1398
- if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
1399
- return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
1400
- }
1401
- emitQueryComparison(node, origin) {
1402
- const left = this.emitQueryFieldRef(node.left, origin);
1403
- const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
1404
- const parts = [`left: ${left}`, `op: "${mappedOp}"`];
1405
- if (node.right) {
1406
- if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
1407
- else if ("values" in node.right && node.right.values) {
1408
- const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
1409
- parts.push(`right: [${values}]`);
1410
- } else if ("valueToken" in node.right) parts.push(`right: ${this.emitQueryLiteral(node.right)}`);
1411
- } else if (node.operator === "exists") parts.push("right: true");
1412
- else if (node.operator === "not exists") parts.push("right: false");
1413
- return `{ ${parts.join(", ")} }`;
1414
- }
1415
- emitQueryFieldRef(node, origin) {
1416
- const parts = [];
1417
- if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
1418
- parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
1419
- return `{ ${parts.join(", ")} }`;
1420
- }
1421
- emitQueryLiteral(node) {
1422
- const token = node.valueToken;
1423
- switch (token.type) {
1424
- case "text": return `"${escapeQuotes(token.text)}"`;
1425
- case "number": return token.text;
1426
- case "regexp": {
1427
- const match = /^\/(.*)\/[a-z]*$/.exec(token.text);
1428
- return `"${escapeQuotes(match ? match[1] : token.text)}"`;
1429
- }
1430
- case "identifier":
1431
- if (token.text === "true" || token.text === "false") return token.text;
1432
- if (token.text === "null" || token.text === "undefined") return "null";
1433
- return token.text;
1434
- default: return token.text;
1435
- }
1436
- }
1437
- computeAnnotationValue(node, an) {
1438
- const origin = this.doc.annotationOrigin(an);
1439
- const spec = this.doc.resolveAnnotation(an.name);
1440
- let targetValue = "true";
1441
- let multiple = false;
1442
- if (spec) {
1443
- multiple = spec.config.multiple;
1444
- const length = spec.arguments.length;
1445
- if (length !== 0) if (Array.isArray(spec.config.argument)) {
1446
- targetValue = "{ ";
1447
- let i = 0;
1448
- for (const aSpec of spec.arguments) {
1449
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1450
- i++;
1451
- }
1452
- targetValue += "}";
1453
- } else {
1454
- const aSpec = spec.arguments[0];
1455
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
1456
- }
1457
- } else {
1458
- multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
1459
- if (an.args.length > 0) targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
1460
- }
1461
- return {
1462
- value: targetValue,
1463
- multiple: !!multiple
1464
- };
1465
- }
1466
- renderMutatingAnnotateNode(node) {
1467
- const targetName = node.targetName;
1468
- const targetDef = this.resolveTargetDef(targetName);
1469
- this.writeln("// Ad-hoc annotations for ", targetName);
1470
- const allClones = [];
1471
- const entryAccessors = [];
1472
- for (const entry of node.entries) {
1473
- const anns = entry.annotations;
1474
- if (!anns || anns.length === 0) continue;
1475
- const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
1476
- const { accessors, clones } = this.buildMutatingAccessors(targetName, targetDef, parts);
1477
- allClones.push(...clones);
1478
- entryAccessors.push({
1479
- entry,
1480
- accessors
1481
- });
1482
- }
1483
- const cloneKeys = /* @__PURE__ */ new Set();
1484
- for (const clone of allClones) {
1485
- const key = `${clone.parentPath}|${clone.propName}`;
1486
- if (!cloneKeys.has(key)) {
1487
- cloneKeys.add(key);
1488
- this.writeln(`$c(${clone.parentPath}, "${escapeQuotes(clone.propName)}")`);
1489
- }
1490
- }
1491
- for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor);
1492
- const topAnnotations = node.annotations;
1493
- if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, targetName);
1494
- this.writeln();
1495
- }
1496
- emitMutatingAnnotations(node, annotations, accessor) {
1497
- const cleared = /* @__PURE__ */ new Set();
1498
- for (const an of annotations) {
1499
- const { value, multiple } = this.computeAnnotationValue(node, an);
1500
- if (multiple) {
1501
- if (!cleared.has(an.name)) {
1502
- const spec = this.doc.resolveAnnotation(an.name);
1503
- if (!spec || spec.config.mergeStrategy !== "append") this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
1504
- cleared.add(an.name);
1505
- }
1506
- this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
1507
- } else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
1508
- }
1509
- }
1510
- resolveTargetDef(targetName) {
1511
- const unwound = this.doc.unwindType(targetName);
1512
- if (!unwound?.def) return;
1513
- let def = unwound.def;
1514
- if (isInterface(def)) def = def.getDefinition() || def;
1515
- return def;
1516
- }
1517
- /**
1518
- * Builds the runtime accessor paths for mutating annotate entries.
1519
- * Computes exact paths at compile time by walking the AST,
1520
- * so the generated JS accesses props directly without runtime search.
1521
- * Returns multiple paths when a property appears in multiple union branches.
1522
- */ buildMutatingAccessors(targetName, targetDef, parts) {
1523
- let accessors = [{
1524
- prefix: `${targetName}.type`,
1525
- def: targetDef
1526
- }];
1527
- const clones = [];
1528
- for (let i = 0; i < parts.length; i++) {
1529
- const nextAccessors = [];
1530
- for (const { prefix, def } of accessors) {
1531
- const results = this.buildPropPaths(def, parts[i]);
1532
- if (results.length > 0) for (const result of results) if (i < parts.length - 1) {
1533
- if (result.propDef && isRef(result.propDef)) clones.push({
1534
- parentPath: prefix,
1535
- propName: parts[i]
1536
- });
1537
- nextAccessors.push({
1538
- prefix: `${prefix}${result.path}?.type`,
1539
- def: result.propDef
1540
- });
1541
- } else nextAccessors.push({
1542
- prefix: `${prefix}${result.path}?`,
1543
- def: result.propDef
1544
- });
1545
- else {
1546
- const suffix = `.props.get("${escapeQuotes(parts[i])}")${i < parts.length - 1 ? "?.type" : "?"}`;
1547
- nextAccessors.push({
1548
- prefix: `${prefix}${suffix}`,
1549
- def: void 0
1550
- });
1551
- }
1552
- }
1553
- accessors = nextAccessors;
1554
- }
1555
- return {
1556
- accessors: accessors.map((a) => a.prefix),
1557
- clones
1558
- };
1559
- }
1560
- /**
1561
- * Finds a property in a type tree at compile time, returning all
1562
- * matching runtime path strings and prop definitions for further chaining.
1563
- * Returns multiple results when the same property appears in different union branches.
1564
- */ buildPropPaths(def, propName) {
1565
- if (!def) return [];
1566
- def = this.doc.mergeIntersection(def);
1567
- if (isRef(def)) {
1568
- const ref = def;
1569
- const unwound = this.doc.unwindType(ref.id, ref.chain)?.def;
1570
- return this.buildPropPaths(unwound, propName);
1571
- }
1572
- if (isInterface(def)) return this.buildPropPaths(def.getDefinition(), propName);
1573
- if (isStructure(def)) {
1574
- const prop = def.props.get(propName);
1575
- if (prop) return [{
1576
- path: `.props.get("${escapeQuotes(propName)}")`,
1577
- propDef: prop.getDefinition()
1578
- }];
1579
- return [];
1580
- }
1581
- if (isGroup(def)) {
1582
- const items = def.unwrap();
1583
- const results = [];
1584
- for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
1585
- path: `.items[${i}].type${result.path}`,
1586
- propDef: result.propDef
1587
- });
1588
- return results;
1589
- }
1590
- return [];
1591
- }
1592
- constructor(doc, opts) {
1593
- 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), 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();
1594
- }
1595
- };
1596
-
1597
- //#endregion
1598
- //#region packages/typescript/src/plugin.ts
1599
- /**
1600
- * Resolves the effective JSON schema mode from plugin options.
1601
- */ function resolveJsonSchemaMode(opts) {
1602
- if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
1603
- return false;
1604
- }
1605
- const tsPlugin = (opts) => {
1606
- return {
1607
- name: "typescript",
1608
- render(doc, format) {
1609
- if (format === "dts" || format === DEFAULT_FORMAT) return [{
1610
- fileName: `${doc.name}.d.ts`,
1611
- content: new TypeRenderer(doc, opts).render()
1612
- }];
1613
- if (format === "js") return [{
1614
- fileName: `${doc.name}.js`,
1615
- content: new JsRenderer(doc, opts).render()
1616
- }];
1617
- },
1618
- async buildEnd(output, format, repo) {
1619
- if (format === "dts" || format === DEFAULT_FORMAT) {
1620
- const annotations = await repo.getUsedAnnotations();
1621
- const tags = await repo.getPrimitivesTags() || /* @__PURE__ */ new Set();
1622
- const rendered = [];
1623
- for (const [key, val] of Object.entries(annotations)) {
1624
- const multiple = val.multiple;
1625
- const typeLine = Array.from(val.types).map((t) => {
1626
- if (t.type === "object" && "props" in t) return `{ ${Object.entries(t.props).map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
1627
- else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
1628
- }).join(" | ");
1629
- rendered.push(`${wrapProp(key)}: ${multiple ? "(" : ""}${typeLine}${multiple ? ")[]" : ""}`);
1630
- }
1631
- const renderedTags = Array.from(tags).map((f) => `"${escapeQuotes(f)}"`).join(" | ");
1632
- output.push({
1633
- 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",
1634
- fileName: "atscript.d.ts",
1635
- source: "",
1636
- target: path.join(repo.root, "atscript.d.ts")
1637
- });
1638
- }
1639
- }
1640
- };
1641
- };
1642
-
1643
- //#endregion
1644
- export { tsPlugin as t };