@atscript/typescript 0.1.98 → 0.1.100

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,4 +1,4 @@
1
- import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-Cka8ETxe.mjs";
1
+ import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-BogNt-9w.mjs";
2
2
  import path from "path";
3
3
  import { DEFAULT_FORMAT, flattenInterfaceNode, getRelPath, hasNavPropAnnotation, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isPrimitive, isProp, isQueryLogical, isRef, isStructure } from "@atscript/core";
4
4
 
@@ -658,6 +658,7 @@ const QUERY_OP_MAP = {
658
658
  "exists": "$exists",
659
659
  "not exists": "$exists"
660
660
  };
661
+ const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
661
662
  var JsRenderer = class extends BaseRenderer {
662
663
  /**
663
664
  * Relative imports get the configured `moduleExtension`; bare specifiers
@@ -715,32 +716,56 @@ var JsRenderer = class extends BaseRenderer {
715
716
  this._synthComputed = true;
716
717
  const refToOriginDoc = this.getExtendsRefs();
717
718
  if (refToOriginDoc.size === 0) return;
718
- const taken = new Set(this.doc.registry.definitions.keys());
719
- const allocated = /* @__PURE__ */ new Map();
720
- const synthPathCache = /* @__PURE__ */ new Map();
721
719
  for (const [refNode, originDoc] of refToOriginDoc) {
722
720
  const refId = refNode.id;
723
721
  if (!refId) continue;
724
722
  const ownerInfo = this.resolveOwner(originDoc, refId);
725
723
  if (!ownerInfo?.doc || ownerInfo.doc === this.doc) continue;
726
724
  if (ownerInfo.node && isPrimitive(ownerInfo.node)) continue;
727
- const ownerDoc = ownerInfo.doc;
728
- let synthPath;
729
- if (synthPathCache.has(ownerDoc)) synthPath = synthPathCache.get(ownerDoc);
730
- else {
731
- synthPath = this.computeSynthPath(ownerDoc);
732
- synthPathCache.set(ownerDoc, synthPath);
733
- }
734
- if (!synthPath) continue;
735
- const allocKey = `${synthPath}::${refId}`;
736
- let info = allocated.get(allocKey);
737
- if (!info) {
738
- info = this.allocateSynthInfo(refId, synthPath, ownerInfo, taken);
739
- allocated.set(allocKey, info);
740
- }
725
+ const info = this.synthBinding(refId, ownerInfo);
726
+ if (!info) continue;
741
727
  this._refSynthInfo.set(refNode, info);
742
728
  }
743
729
  }
730
+ getSynthTaken() {
731
+ if (!this._synthTaken) {
732
+ this._synthTaken = new Set(this.doc.registry.definitions.keys());
733
+ for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
734
+ }
735
+ return this._synthTaken;
736
+ }
737
+ getSynthPath(ownerDoc) {
738
+ if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
739
+ return this._synthPathCache.get(ownerDoc);
740
+ }
741
+ synthBinding(name, ownerInfo) {
742
+ const synthPath = this.getSynthPath(ownerInfo.doc);
743
+ if (!synthPath) return;
744
+ const allocKey = `${synthPath}::${name}`;
745
+ let info = this._synthAllocated.get(allocKey);
746
+ if (!info) {
747
+ info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
748
+ this._synthAllocated.set(allocKey, info);
749
+ }
750
+ return info;
751
+ }
752
+ /**
753
+ * Binding for a type name used by an annotation argument (`ref` / qualified
754
+ * query field refs). An annotation inherited from another document (chain ref
755
+ * or `extends`) carries names that only that document imports, so when the
756
+ * name does not resolve here to the same declaration, a synthesized import is
757
+ * allocated (lazily, spliced into the header by `render()`).
758
+ */ annotationTypeName(typeName, origin) {
759
+ if (!origin || origin === this.doc) return typeName;
760
+ const theirs = this.resolveOwner(origin, typeName);
761
+ if (!theirs?.doc || !theirs.node || theirs.doc === this.doc || isPrimitive(theirs.node)) return typeName;
762
+ const mine = this.resolveOwner(this.doc, typeName);
763
+ if (mine?.doc === theirs.doc && mine.node === theirs.node) return typeName;
764
+ return this.synthBinding(typeName, {
765
+ doc: theirs.doc,
766
+ node: theirs.node
767
+ })?.alias ?? typeName;
768
+ }
744
769
  resolveOwner(fromDoc, refId) {
745
770
  const key = `${fromDoc.id}::${refId}`;
746
771
  let v = this._ownerCache.get(key);
@@ -814,10 +839,17 @@ var JsRenderer = class extends BaseRenderer {
814
839
  if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
815
840
  this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
816
841
  this.computeSynthesizedImports();
842
+ this.writeln(SYNTH_IMPORTS_MARKER);
843
+ }
844
+ render() {
845
+ const out = super.render();
846
+ const lines = [];
817
847
  for (const [synthPath, names] of this._synthImports) {
818
848
  const list = names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ");
819
- this.writeln(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
849
+ lines.push(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
820
850
  }
851
+ const marker = `${SYNTH_IMPORTS_MARKER}\n`;
852
+ return out.replace(marker, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
821
853
  }
822
854
  buildAdHocMap(annotateNodes) {
823
855
  const map = /* @__PURE__ */ new Map();
@@ -1289,33 +1321,53 @@ var JsRenderer = class extends BaseRenderer {
1289
1321
  if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
1290
1322
  else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
1291
1323
  }
1292
- emitRefValue(text) {
1324
+ emitRefValue(text, origin) {
1293
1325
  const dotIdx = text.indexOf(".");
1294
- if (dotIdx === -1) return `() => ${text}`;
1295
- return `{ type: () => ${text.slice(0, dotIdx)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1296
- }
1297
- emitArgValue(aSpec, argToken) {
1298
- if (aSpec.type === "ref") return this.emitRefValue(argToken.text);
1299
- if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode);
1326
+ if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
1327
+ return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1328
+ }
1329
+ emitArgValue(aSpec, argToken, origin) {
1330
+ if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
1331
+ if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
1332
+ if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
1333
+ if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
1300
1334
  return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
1301
1335
  }
1302
- emitQueryTree(queryNode) {
1303
- return this.emitQueryExpr(queryNode.expression);
1336
+ emitExprNode(node, origin) {
1337
+ switch (node.entity) {
1338
+ case "query-expr-number": return String(node.value);
1339
+ case "query-expr-binary": {
1340
+ const { op, left, right } = node;
1341
+ return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
1342
+ }
1343
+ case "query-expr-unary": {
1344
+ const { op, operand } = node;
1345
+ return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
1346
+ }
1347
+ case "query-expr-call": {
1348
+ const { fn, args } = node;
1349
+ return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
1350
+ }
1351
+ default: return this.emitQueryFieldRef(node, origin);
1352
+ }
1353
+ }
1354
+ emitQueryTree(queryNode, origin) {
1355
+ return this.emitQueryExpr(queryNode.expression, origin);
1304
1356
  }
1305
- emitQueryExpr(node) {
1306
- if (isQueryLogical(node)) return this.emitQueryLogical(node);
1307
- return this.emitQueryComparison(node);
1357
+ emitQueryExpr(node, origin) {
1358
+ if (isQueryLogical(node)) return this.emitQueryLogical(node, origin);
1359
+ return this.emitQueryComparison(node, origin);
1308
1360
  }
1309
- emitQueryLogical(node) {
1310
- if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0])} }`;
1311
- return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op)).join(", ")}] }`;
1361
+ emitQueryLogical(node, origin) {
1362
+ if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
1363
+ return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
1312
1364
  }
1313
- emitQueryComparison(node) {
1314
- const left = this.emitQueryFieldRef(node.left);
1365
+ emitQueryComparison(node, origin) {
1366
+ const left = this.emitQueryFieldRef(node.left, origin);
1315
1367
  const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
1316
1368
  const parts = [`left: ${left}`, `op: "${mappedOp}"`];
1317
1369
  if (node.right) {
1318
- if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right)}`);
1370
+ if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
1319
1371
  else if ("values" in node.right && node.right.values) {
1320
1372
  const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
1321
1373
  parts.push(`right: [${values}]`);
@@ -1324,9 +1376,9 @@ var JsRenderer = class extends BaseRenderer {
1324
1376
  else if (node.operator === "not exists") parts.push("right: false");
1325
1377
  return `{ ${parts.join(", ")} }`;
1326
1378
  }
1327
- emitQueryFieldRef(node) {
1379
+ emitQueryFieldRef(node, origin) {
1328
1380
  const parts = [];
1329
- if (node.typeRef) parts.push(`type: () => ${node.typeRef.text}`);
1381
+ if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
1330
1382
  parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
1331
1383
  return `{ ${parts.join(", ")} }`;
1332
1384
  }
@@ -1347,6 +1399,7 @@ var JsRenderer = class extends BaseRenderer {
1347
1399
  }
1348
1400
  }
1349
1401
  computeAnnotationValue(node, an) {
1402
+ const origin = this.doc.annotationOrigin(an);
1350
1403
  const spec = this.doc.resolveAnnotation(an.name);
1351
1404
  let targetValue = "true";
1352
1405
  let multiple = false;
@@ -1357,13 +1410,13 @@ var JsRenderer = class extends BaseRenderer {
1357
1410
  targetValue = "{ ";
1358
1411
  let i = 0;
1359
1412
  for (const aSpec of spec.arguments) {
1360
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i])}${i === length - 1 ? "" : ", "} `;
1413
+ if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1361
1414
  i++;
1362
1415
  }
1363
1416
  targetValue += "}";
1364
1417
  } else {
1365
1418
  const aSpec = spec.arguments[0];
1366
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0]) : "true";
1419
+ targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
1367
1420
  }
1368
1421
  } else {
1369
1422
  multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
@@ -1501,7 +1554,7 @@ var JsRenderer = class extends BaseRenderer {
1501
1554
  return [];
1502
1555
  }
1503
1556
  constructor(doc, opts) {
1504
- 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, "_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._ownerCache = /* @__PURE__ */ new Map();
1557
+ 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();
1505
1558
  }
1506
1559
  };
1507
1560
 
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_plugin = require('./plugin-dcd-XTR-.cjs');
2
+ const require_plugin = require('./plugin-Cu6Nez-H.cjs');
3
3
  let path = require("path");
4
4
  path = require_plugin.__toESM(path);
5
5
  let _atscript_core = require("@atscript/core");
@@ -1,4 +1,4 @@
1
- import { t as tsPlugin } from "./plugin-BDjZ2rOT.mjs";
1
+ import { t as tsPlugin } from "./plugin-DG3jlbSN.mjs";
2
2
  import path from "path";
3
3
  import { build } from "@atscript/core";
4
4
  import { readFileSync, writeFileSync } from "fs";
package/dist/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_json_schema = require('./json-schema-CZo482nY.cjs');
2
+ const require_json_schema = require('./json-schema-CtQ_rzJn.cjs');
3
3
 
4
4
  //#region packages/typescript/src/runtime/coerce.ts
5
5
  /**
@@ -406,6 +406,16 @@ function flattenAnnotatedType(type, options) {
406
406
 
407
407
  //#endregion
408
408
  //#region packages/typescript/src/runtime/serialize.ts
409
+ function _define_property(obj, key, value) {
410
+ if (key in obj) Object.defineProperty(obj, key, {
411
+ value,
412
+ enumerable: true,
413
+ configurable: true,
414
+ writable: true
415
+ });
416
+ else obj[key] = value;
417
+ return obj;
418
+ }
409
419
  /** Current serialization format version. Bumped on breaking changes to the serialized shape. */ const SERIALIZE_VERSION = 2;
410
420
  /**
411
421
  * Converts a runtime {@link TAtscriptAnnotatedType} into a plain JSON-safe object.
@@ -425,41 +435,135 @@ function flattenAnnotatedType(type, options) {
425
435
  * @param options - Optional filtering/transformation for annotations.
426
436
  * @returns A versioned, JSON-safe representation of the type.
427
437
  */ function serializeAnnotatedType(type, options) {
428
- const result = serializeNode(type, [], options, /* @__PURE__ */ new Set());
438
+ const result = serializeNode(type, [], options, new Visited());
429
439
  result.$v = SERIALIZE_VERSION;
430
440
  return result;
431
441
  }
432
- function serializeNode(def, path, options, visited) {
433
- if (def.id && visited.has(def.id)) return {
434
- type: {
435
- kind: "$ref",
436
- id: def.id
437
- },
438
- metadata: {},
439
- ...def.optional ? { optional: true } : {},
440
- id: def.id
441
- };
442
- if (def.id) visited.add(def.id);
443
- const result = {
444
- type: serializeTypeDef(def, path, options, visited),
445
- metadata: serializeMetadata(def.metadata, path, def.type.kind, options)
446
- };
447
- if (def.optional) result.optional = true;
448
- if (def.id) result.id = def.id;
442
+ /**
443
+ * Named types serialized so far. `own` keeps, per id, the first node serialized under it (and
444
+ * the `refDepth` it was serialized at); a later reference is compared against it, by a
445
+ * fingerprint of what it carries (metadata, `optional` and `ref`), to tell a reference that adds
446
+ * nothing from one whose prop annotations or FK target differ. The first node's key is computed
447
+ * only when a revisit needs it, and memoized.
448
+ */ let Visited = class Visited extends Set {
449
+ /** Whether `def` (revisiting its id at `refDepth`) carries something other than the first node. */ differsFromFirst(def, refDepth) {
450
+ const id = def.id;
451
+ let first = this.firstKeys.get(id);
452
+ if (first === void 0) {
453
+ const { def: firstDef, refDepth: firstDepth } = this.own.get(id);
454
+ first = ownKey(firstDef, this, firstDepth);
455
+ this.firstKeys.set(id, first);
456
+ }
457
+ return first !== ownKey(def, this, refDepth);
458
+ }
459
+ /** Stable per-run identity of a function / class instance (compared by reference). */ identity(value) {
460
+ let id = this.identities.get(value);
461
+ if (id === void 0) {
462
+ id = ++this.nextId;
463
+ this.identities.set(value, id);
464
+ }
465
+ return id;
466
+ }
467
+ constructor(...args) {
468
+ super(...args), _define_property(this, "own", /* @__PURE__ */ new Map()), _define_property(this, "firstKeys", /* @__PURE__ */ new Map()), _define_property(this, "identities", /* @__PURE__ */ new WeakMap()), _define_property(this, "nextId", 0);
469
+ }
470
+ };
471
+ /**
472
+ * A stable, cycle-safe, BigInt-tolerant comparison key of raw annotation values. Plain objects
473
+ * and arrays compare structurally; a type reference (a getter or an annotated type) by the type it
474
+ * resolves to, so equal targets collapse and different ones do not; other functions and objects by
475
+ * identity.
476
+ */ function fingerprint(value, visited, ancestors = /* @__PURE__ */ new Set()) {
477
+ switch (typeof value) {
478
+ case "bigint": return `${value}n`;
479
+ case "string": return JSON.stringify(value);
480
+ case "function": {
481
+ const target = resolveAnnotationTarget(value);
482
+ if (target) return targetKey(target, visited);
483
+ return `fn#${visited.identity(value)}`;
484
+ }
485
+ case "object": {
486
+ if (value === null) return "null";
487
+ const target = resolveAnnotationTarget(value);
488
+ if (target) return targetKey(target, visited);
489
+ if (!isPlainOrArray(value)) return `obj#${visited.identity(value)}`;
490
+ if (ancestors.has(value)) return "[circular]";
491
+ ancestors.add(value);
492
+ const body = Array.isArray(value) ? value.map((v) => fingerprint(v, visited, ancestors)).join(",") : Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited, ancestors)}`).join(",");
493
+ ancestors.delete(value);
494
+ return `[${body}]`;
495
+ }
496
+ default: return String(value);
497
+ }
498
+ }
499
+ /** A plain object or an array (as opposed to a class instance), the shapes compared structurally. */ function isPlainOrArray(value) {
500
+ const proto = Object.getPrototypeOf(value);
501
+ return Array.isArray(value) || proto === Object.prototype || proto === null;
502
+ }
503
+ /** Comparison key of a resolved annotation target: its id, else its identity. */ function targetKey(target, visited) {
504
+ return target.id ? `ref#${target.id}` : `ref@${visited.identity(target)}`;
505
+ }
506
+ /** What a node carries of its own (metadata, optionality, FK target), as a comparison key. */ function ownKey(def, visited, refDepth) {
507
+ const entries = [...def.metadata.entries()].map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited)}`);
508
+ const refTarget = refDepth > 0 ? def.ref?.type() : void 0;
509
+ const ref = def.ref && refTarget ? `${refTarget.id ?? ""}.${def.ref.field}` : "";
510
+ return `${entries.join(",")}|${def.optional ? 1 : 0}|${ref}`;
511
+ }
512
+ function serializeRef(def, options, visited) {
449
513
  const refDepth = options?.refDepth ?? 0;
450
514
  if (refDepth > 0 && def.ref) {
451
515
  const refTarget = def.ref.type();
452
- if (refTarget) result.ref = {
516
+ if (refTarget) return {
453
517
  field: def.ref.field,
454
- type: refDepth < 1 && isHalfStep(refDepth) ? {
455
- id: refTarget.id ?? "",
456
- metadata: serializeMetadata(refTarget.metadata, [], refTarget.type.kind, options)
457
- } : serializeNode(refTarget, [], {
518
+ type: refDepth < 1 && isHalfStep(refDepth) ? shallowTarget(refTarget, options, {
519
+ visited,
520
+ depth: 1
521
+ }, true) : serializeNode(refTarget, [], {
458
522
  ...options,
459
523
  refDepth: refDepth - 1
460
524
  }, visited)
461
525
  };
462
526
  }
527
+ }
528
+ function serializeNode(def, path, options, visited) {
529
+ const refDepth = options?.refDepth ?? 0;
530
+ const metadata = () => serializeMetadata(def.metadata, {
531
+ path,
532
+ kind: def.type.kind
533
+ }, options, {
534
+ visited,
535
+ depth: 0
536
+ });
537
+ if (def.id && visited.has(def.id)) {
538
+ const differs = visited.differsFromFirst(def, refDepth);
539
+ const ref = differs ? serializeRef(def, options, visited) : void 0;
540
+ return {
541
+ type: {
542
+ kind: "$ref",
543
+ id: def.id,
544
+ ...differs ? { own: true } : {}
545
+ },
546
+ metadata: differs ? metadata() : {},
547
+ ...def.optional ? { optional: true } : {},
548
+ id: def.id,
549
+ ...ref ? { ref } : {}
550
+ };
551
+ }
552
+ if (def.id) {
553
+ visited.add(def.id);
554
+ visited.own.set(def.id, {
555
+ def,
556
+ refDepth
557
+ });
558
+ }
559
+ const result = {
560
+ type: serializeTypeDef(def, path, options, visited),
561
+ metadata: metadata()
562
+ };
563
+ if (def.optional) result.optional = true;
564
+ if (def.id) result.id = def.id;
565
+ const ref = serializeRef(def, options, visited);
566
+ if (ref) result.ref = ref;
463
567
  return result;
464
568
  }
465
569
  function isHalfStep(refDepth) {
@@ -529,7 +633,61 @@ function serializeTypeDef(def, path, options, visited) {
529
633
  }
530
634
  });
531
635
  }
532
- function serializeMetadata(metadata, path, kind, options) {
636
+ /**
637
+ * Resolves a type reference held in an annotation value: an annotated type itself (same-file
638
+ * refs) or the getter generated for a cross-file ref. Generated getters are zero-arity, plain
639
+ * synchronous arrow functions (no `prototype`, `Function` constructor); that is the only shape
640
+ * invoked. Classes, `function` expressions, async/generator functions and any other function
641
+ * are never called, so serializing never runs user code.
642
+ */ function resolveAnnotationTarget(value) {
643
+ if (require_json_schema.isAnnotatedType(value)) return value;
644
+ if (typeof value === "function" && value.length === 0 && !Object.prototype.hasOwnProperty.call(value, "prototype") && value.constructor === Function) {
645
+ const fn = value;
646
+ try {
647
+ const target = fn();
648
+ return require_json_schema.isAnnotatedType(target) ? target : void 0;
649
+ } catch {
650
+ return;
651
+ }
652
+ }
653
+ }
654
+ /**
655
+ * `{ id }` for a referenced type, plus its metadata (serialized at the next depth, so every
656
+ * nested reference collapses to `{ id }`) when `withMetadata`.
657
+ */ function shallowTarget(target, options, state, withMetadata) {
658
+ return {
659
+ id: target.id ?? "",
660
+ ...withMetadata ? { metadata: serializeMetadata(target.metadata, {
661
+ path: [],
662
+ kind: target.type.kind
663
+ }, options, state) } : {}
664
+ };
665
+ }
666
+ /**
667
+ * Makes an annotation value JSON-safe: type references (a getter or a class, as emitted for `ref`
668
+ * arguments and qualified query field refs) become shallow targets `{ id, metadata }`
669
+ * (`refDepth > 0`) or `{ id }` (`refDepth` 0). Inside a shallow target's own metadata (`depth` >= 1)
670
+ * every reference is `{ id }`, so the output is bounded and cycle-free. Plain objects and arrays
671
+ * recurse; other values pass unchanged.
672
+ */ function serializeAnnotationValue(value, options, state) {
673
+ var _state;
674
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
675
+ const target = resolveAnnotationTarget(value);
676
+ if (target) return shallowTarget(target, options, {
677
+ visited: state.visited,
678
+ depth: state.depth + 1
679
+ }, state.depth === 0 && (options?.refDepth ?? 0) > 0);
680
+ if (typeof value === "function") return value;
681
+ if (!isPlainOrArray(value)) return value;
682
+ const ancestors = (_state = state).ancestors ?? (_state.ancestors = /* @__PURE__ */ new Set());
683
+ if (ancestors.has(value)) return "[Circular]";
684
+ ancestors.add(value);
685
+ const out = Array.isArray(value) ? value.map((item) => serializeAnnotationValue(item, options, state)) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, serializeAnnotationValue(v, options, state)]));
686
+ ancestors.delete(value);
687
+ return out;
688
+ }
689
+ function serializeMetadata(metadata, site, options, state) {
690
+ const { path, kind } = site;
533
691
  const result = {};
534
692
  const ignoreSet = options?.ignoreAnnotations ? new Set(options.ignoreAnnotations) : void 0;
535
693
  for (const [key, value] of metadata.entries()) {
@@ -542,10 +700,10 @@ function serializeMetadata(metadata, path, kind, options) {
542
700
  kind
543
701
  });
544
702
  if (processed === void 0 || processed === null) continue;
545
- result[processed.key] = processed.value;
703
+ result[processed.key] = serializeAnnotationValue(processed.value, options, state);
546
704
  continue;
547
705
  }
548
- result[key] = value;
706
+ result[key] = serializeAnnotationValue(value, options, state);
549
707
  }
550
708
  return result;
551
709
  }
@@ -581,10 +739,41 @@ function emptyObjectTypeDef() {
581
739
  function toMetadataMap(record) {
582
740
  return new Map(Object.entries(record));
583
741
  }
742
+ function deserializeRef(data, resolved) {
743
+ if (!data.ref) return;
744
+ const refTargetData = data.ref.type;
745
+ if ("type" in refTargetData) {
746
+ const deserializedRefTarget = deserializeNode(refTargetData, resolved);
747
+ return {
748
+ type: () => deserializedRefTarget,
749
+ field: data.ref.field
750
+ };
751
+ }
752
+ const sentinel = require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
753
+ return {
754
+ type: () => sentinel,
755
+ field: data.ref.field
756
+ };
757
+ }
584
758
  function deserializeNode(data, resolved) {
585
759
  if (data.type.kind === "$ref") {
586
- const refId = data.type.id;
587
- return resolved.get(refId) || require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
760
+ const { id: refId, own } = data.type;
761
+ const target = resolved.get(refId);
762
+ if (!own) return target || require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
763
+ const node = require_json_schema.createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
764
+ id: refId,
765
+ optional: data.optional || void 0,
766
+ ref: deserializeRef(data, resolved)
767
+ });
768
+ if (target) Object.defineProperty(node, "type", {
769
+ get: () => target.type,
770
+ set: (v) => {
771
+ target.type = v;
772
+ },
773
+ enumerable: true,
774
+ configurable: true
775
+ });
776
+ return node;
588
777
  }
589
778
  const metadata = toMetadataMap(data.metadata);
590
779
  let result;
@@ -598,23 +787,7 @@ function deserializeNode(data, resolved) {
598
787
  resolved.set(data.id, result);
599
788
  }
600
789
  const type = deserializeTypeDef(data.type, resolved);
601
- let ref;
602
- if (data.ref) {
603
- const refTargetData = data.ref.type;
604
- if ("type" in refTargetData) {
605
- const deserializedRefTarget = deserializeNode(refTargetData, resolved);
606
- ref = {
607
- type: () => deserializedRefTarget,
608
- field: data.ref.field
609
- };
610
- } else {
611
- const sentinel = require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
612
- ref = {
613
- type: () => sentinel,
614
- field: data.ref.field
615
- };
616
- }
617
- }
790
+ const ref = deserializeRef(data, resolved);
618
791
  if (result) {
619
792
  result.type = type;
620
793
  if (ref) result.ref = ref;
package/dist/utils.d.ts CHANGED
@@ -515,6 +515,25 @@ type AtscriptQueryNode = AtscriptQueryComparison | {
515
515
  } | {
516
516
  $not: AtscriptQueryNode;
517
517
  };
518
+ /**
519
+ * Arithmetic expression tree (runtime shape of an `expr` annotation argument).
520
+ * Leaves are numeric literals or field references.
521
+ */
522
+ type AtscriptExprNode = number | AtscriptQueryFieldRef | {
523
+ op: '+' | '-' | '*' | '/';
524
+ args: [AtscriptExprNode, AtscriptExprNode];
525
+ } | {
526
+ op: 'neg';
527
+ args: [AtscriptExprNode];
528
+ } | {
529
+ op: 'coalesce';
530
+ args: AtscriptExprNode[];
531
+ };
532
+ /** One key of an ordering (runtime shape of an `order` annotation argument is an array of these). */
533
+ interface AtscriptOrderItem {
534
+ ref: AtscriptQueryFieldRef;
535
+ desc?: true;
536
+ }
518
537
 
519
538
  /** Current serialization format version. Bumped on breaking changes to the serialized shape. */
520
539
  declare const SERIALIZE_VERSION = 2;
@@ -571,6 +590,13 @@ interface TSerializedTypeComplex {
571
590
  interface TSerializedTypeRef {
572
591
  kind: '$ref';
573
592
  id: string;
593
+ /**
594
+ * The entry's `metadata` / `optional` belong to the referencing node (a prop's own
595
+ * annotations merged over the type's), not to the first node serialized under `id`.
596
+ * The deserializer then builds a node of its own over the shared type. The entry then also
597
+ * carries the use-site `ref` (FK target) when `refDepth` > 0 and the node has one.
598
+ */
599
+ own?: true;
574
600
  }
575
601
  type TSerializedTypeDef = TSerializedTypeFinal | TSerializedTypeObject | TSerializedTypeArray | TSerializedTypeComplex | TSerializedTypeRef;
576
602
  /** Context passed to {@link TSerializeOptions.processAnnotation} for each annotation entry. */
@@ -683,4 +709,4 @@ type NavPropsOf<T> = T extends {
683
709
  } ? N : Record<string, never>;
684
710
 
685
711
  export { SERIALIZE_VERSION, Validator, ValidatorError, annotate, buildJsonSchema, cloneRefProp, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, mergeJsonSchemas, serializeAnnotatedType, throwFeatureDisabled };
686
- export type { AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TFlattenOptions, TJsonSchema, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValueResolver };
712
+ export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TFlattenOptions, TJsonSchema, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValueResolver };