@atscript/typescript 0.1.109 → 0.1.110
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +1587 -189
- package/dist/index.cjs +5 -2
- package/dist/index.d.ts +53 -1
- package/dist/index.mjs +3 -3
- package/dist/{json-schema-CioBVi6F.mjs → json-schema-B3iAqkGQ.cjs} +919 -37
- package/dist/{json-schema-9OBvrg9D.cjs → json-schema-BG1SEcjI.mjs} +618 -120
- package/dist/{plugin-D3_BnRrI.mjs → plugin-DpzE8aJr.mjs} +955 -116
- package/dist/{plugin-6r27w6rG.cjs → plugin-mzTvme4k.cjs} +966 -115
- package/dist/test-utils.cjs +4 -4
- package/dist/test-utils.d.ts +53 -0
- package/dist/test-utils.mjs +4 -4
- package/dist/utils.cjs +14 -26
- package/dist/utils.d.ts +81 -2
- package/dist/utils.mjs +13 -27
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as D_UNKNOWN, B as LAYOUT_VERSION, C as D_ARRAY, D as D_OBJECT_PATTERNS, E as D_OBJECT, F as F_PARTIAL_TOP, G as keySlots, H as STRING_BITS, I as F_STRIP, J as siteSlotCount, K as readKeys, L as F_TOP, M as F_ERROR, N as F_IN_UNION, O as D_TUPLE, P as F_PARTIAL_DEEP, R as INTERP, S as B_UNIQUE, T as D_INTERSECTION, U as childSites, V as NUMBER_BITS, W as hasRejectSlot, X as isValidatorKey, _ as getRegex, b as B_INT, d as defineAnnotatedType, j as EXT, k as D_UNION, o as annotate, q as siteBits, s as cloneRefProp, t as buildJsonSchema, w as D_FINAL, x as B_REQUIRED, y as ARRAY_BITS, z as ITEMS_KIND_CODES } from "./json-schema-BG1SEcjI.mjs";
|
|
2
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
|
|
|
5
5
|
//#region packages/typescript/src/codegen/code-printer.ts
|
|
6
|
-
function _define_property$
|
|
6
|
+
function _define_property$5(obj, key, value) {
|
|
7
7
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
8
8
|
value,
|
|
9
9
|
enumerable: true,
|
|
@@ -96,17 +96,17 @@ var CodePrinter = class {
|
|
|
96
96
|
return " ".repeat(this.indentLevel * this.indentSize);
|
|
97
97
|
}
|
|
98
98
|
constructor() {
|
|
99
|
-
_define_property$
|
|
100
|
-
_define_property$
|
|
101
|
-
_define_property$
|
|
102
|
-
_define_property$
|
|
103
|
-
_define_property$
|
|
99
|
+
_define_property$5(this, "lines", []);
|
|
100
|
+
_define_property$5(this, "currentLine", "");
|
|
101
|
+
_define_property$5(this, "indentLevel", 0);
|
|
102
|
+
_define_property$5(this, "indentSize", 2);
|
|
103
|
+
_define_property$5(this, "blockStack", []);
|
|
104
104
|
}
|
|
105
105
|
};
|
|
106
106
|
|
|
107
107
|
//#endregion
|
|
108
108
|
//#region packages/typescript/src/codegen/base-renderer.ts
|
|
109
|
-
function _define_property$
|
|
109
|
+
function _define_property$4(obj, key, value) {
|
|
110
110
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
111
111
|
value,
|
|
112
112
|
enumerable: true,
|
|
@@ -169,7 +169,7 @@ var BaseRenderer = class extends CodePrinter {
|
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
constructor(doc) {
|
|
172
|
-
super(), _define_property$
|
|
172
|
+
super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
|
|
173
173
|
}
|
|
174
174
|
};
|
|
175
175
|
|
|
@@ -192,7 +192,7 @@ function escapeQuotes(str) {
|
|
|
192
192
|
|
|
193
193
|
//#endregion
|
|
194
194
|
//#region packages/typescript/src/codegen/type-renderer.ts
|
|
195
|
-
function _define_property$
|
|
195
|
+
function _define_property$3(obj, key, value) {
|
|
196
196
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
197
197
|
value,
|
|
198
198
|
enumerable: true,
|
|
@@ -616,7 +616,7 @@ var TypeRenderer = class TypeRenderer extends BaseRenderer {
|
|
|
616
616
|
this.writeln(` */`);
|
|
617
617
|
}
|
|
618
618
|
constructor(doc, opts) {
|
|
619
|
-
super(doc), _define_property$
|
|
619
|
+
super(doc), _define_property$3(this, "opts", void 0), this.opts = opts;
|
|
620
620
|
}
|
|
621
621
|
};
|
|
622
622
|
function renderPrimitiveTypeDef(def) {
|
|
@@ -633,6 +633,662 @@ function renderPrimitiveTypeDef(def) {
|
|
|
633
633
|
}
|
|
634
634
|
}
|
|
635
635
|
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region packages/typescript/src/runtime/compiled-check/build-layout.ts
|
|
638
|
+
/**
|
|
639
|
+
* Build-time layout derivation (renderer and tests; not part of the runtime bundle).
|
|
640
|
+
*/
|
|
641
|
+
/**
|
|
642
|
+
* Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
|
|
643
|
+
* once and referenced by index.
|
|
644
|
+
*/ function buildLayout(root, reader, classify) {
|
|
645
|
+
const defs = [];
|
|
646
|
+
const index = /* @__PURE__ */ new Map();
|
|
647
|
+
let slots = 0;
|
|
648
|
+
function describeDef(type) {
|
|
649
|
+
switch (type.kind) {
|
|
650
|
+
case "": return type.value === void 0 ? [D_FINAL, type.designType] : [
|
|
651
|
+
D_FINAL,
|
|
652
|
+
type.designType,
|
|
653
|
+
type.value
|
|
654
|
+
];
|
|
655
|
+
case "object": {
|
|
656
|
+
if (type.propsPatterns.length > 0) return [D_OBJECT_PATTERNS];
|
|
657
|
+
const props = [...type.props];
|
|
658
|
+
return [
|
|
659
|
+
D_OBJECT,
|
|
660
|
+
props.map(([key]) => key),
|
|
661
|
+
props.map(([, prop]) => site(prop))
|
|
662
|
+
];
|
|
663
|
+
}
|
|
664
|
+
case "array": return [D_ARRAY, site(type.of)];
|
|
665
|
+
case "union":
|
|
666
|
+
case "intersection":
|
|
667
|
+
case "tuple": return [ITEMS_KIND_CODES[type.kind], type.items.map(site)];
|
|
668
|
+
default: return [D_UNKNOWN, String(type.kind)];
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function site(node) {
|
|
672
|
+
const type = node.type;
|
|
673
|
+
const marker = classify?.(type);
|
|
674
|
+
const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
|
|
675
|
+
let d;
|
|
676
|
+
let keys = {
|
|
677
|
+
mask: 0,
|
|
678
|
+
shape: ""
|
|
679
|
+
};
|
|
680
|
+
if (marker === "interp") d = INTERP;
|
|
681
|
+
else if (marker === "ext") {
|
|
682
|
+
d = EXT;
|
|
683
|
+
keys = readKeys(node.metadata, siteBits(void 0, optional === 1), reader);
|
|
684
|
+
} else {
|
|
685
|
+
d = index.get(type) ?? -1;
|
|
686
|
+
if (d < 0) {
|
|
687
|
+
d = defs.length;
|
|
688
|
+
defs.push([]);
|
|
689
|
+
index.set(type, d);
|
|
690
|
+
defs[d] = describeDef(type);
|
|
691
|
+
}
|
|
692
|
+
keys = readKeys(node.metadata, siteBits(type, optional === 1), reader);
|
|
693
|
+
}
|
|
694
|
+
const result = [
|
|
695
|
+
optional,
|
|
696
|
+
keys.mask,
|
|
697
|
+
d,
|
|
698
|
+
keys.shape,
|
|
699
|
+
slots
|
|
700
|
+
];
|
|
701
|
+
slots += siteSlotCount(result);
|
|
702
|
+
return result;
|
|
703
|
+
}
|
|
704
|
+
return [
|
|
705
|
+
defs,
|
|
706
|
+
site(root),
|
|
707
|
+
slots
|
|
708
|
+
];
|
|
709
|
+
}
|
|
710
|
+
/** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
|
|
711
|
+
if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
|
|
712
|
+
return literalSource(value);
|
|
713
|
+
}
|
|
714
|
+
/** JS source of a primitive literal. */ function literalSource(value) {
|
|
715
|
+
if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
|
|
716
|
+
if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
717
|
+
if (value === void 0) return "undefined";
|
|
718
|
+
return JSON.stringify(value);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
//#endregion
|
|
722
|
+
//#region packages/typescript/src/runtime/compiled-check/emit.ts
|
|
723
|
+
/**
|
|
724
|
+
* Emits the JS source of a compiled validator check factory from its layout.
|
|
725
|
+
*
|
|
726
|
+
* Build-time only (the renderer, and test code): the runtime never generates code. The
|
|
727
|
+
* emitted factory `(K, H) => check` mirrors the interpreted pre-check
|
|
728
|
+
* (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
|
|
729
|
+
* FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
|
|
730
|
+
* def and per def that closes a reference cycle, everything else inlined.
|
|
731
|
+
*
|
|
732
|
+
* Generated code conventions:
|
|
733
|
+
* - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
|
|
734
|
+
* see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
|
|
735
|
+
* - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
|
|
736
|
+
* union (where failures must visit everything the walk would) it records the failure and
|
|
737
|
+
* jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
|
|
738
|
+
* runtime flags tell. BAIL is always `return 2`.
|
|
739
|
+
* - Annotation values are closure constants `k<slot>` read from `K` once per bind.
|
|
740
|
+
*/ function _define_property$2(obj, key, value) {
|
|
741
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
742
|
+
value,
|
|
743
|
+
enumerable: true,
|
|
744
|
+
configurable: true,
|
|
745
|
+
writable: true
|
|
746
|
+
});
|
|
747
|
+
else obj[key] = value;
|
|
748
|
+
return obj;
|
|
749
|
+
}
|
|
750
|
+
const ROOT_CTX = {
|
|
751
|
+
fail: "return 0",
|
|
752
|
+
inUnionFail: "return 0",
|
|
753
|
+
union: false,
|
|
754
|
+
clearTop: false
|
|
755
|
+
};
|
|
756
|
+
/** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
|
|
757
|
+
["pk", /\bpk\./],
|
|
758
|
+
["ho", /\bho\.call\(/],
|
|
759
|
+
["dec", /\bdec\.test\(/],
|
|
760
|
+
["rn", /\brn\(/]
|
|
761
|
+
];
|
|
762
|
+
/** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
|
|
763
|
+
return new CheckEmitter(layout).emit();
|
|
764
|
+
}
|
|
765
|
+
let CheckEmitter = class CheckEmitter {
|
|
766
|
+
emit() {
|
|
767
|
+
const body = [];
|
|
768
|
+
for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
|
|
769
|
+
const root = this.layout[1];
|
|
770
|
+
const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
|
|
771
|
+
if (root[0] === 0 && this.fn[root[2]] && (rootDef === D_OBJECT || rootDef === D_OBJECT_PATTERNS || rootDef === D_TUPLE || rootDef === D_INTERSECTION)) body.push(`return d${root[2]}`);
|
|
772
|
+
else {
|
|
773
|
+
body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
|
|
774
|
+
body.push("return r");
|
|
775
|
+
}
|
|
776
|
+
const code = body.join("\n");
|
|
777
|
+
const head = [];
|
|
778
|
+
const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
|
|
779
|
+
if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
|
|
780
|
+
const slots = [...new Set(Array.from(code.matchAll(/\bk(\d+)\b/g), (m) => Number(m[1])))].filter((k) => k < this.layout[2]).sort((a, b) => a - b);
|
|
781
|
+
for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
|
|
782
|
+
return [
|
|
783
|
+
"(K, H) => {",
|
|
784
|
+
...indent([...head, ...body]),
|
|
785
|
+
"}"
|
|
786
|
+
].join("\n");
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Object defs get a function each; so does every def a reference cycle passes through
|
|
790
|
+
* (each back-edge target of a DFS), which keeps inlining finite.
|
|
791
|
+
*/ functionDefs() {
|
|
792
|
+
const defs = this.defs;
|
|
793
|
+
const fn = defs.map((def) => def[0] === D_OBJECT || def[0] === D_OBJECT_PATTERNS);
|
|
794
|
+
const state = Array.from({ length: defs.length }).fill(0);
|
|
795
|
+
const dfs = (d) => {
|
|
796
|
+
state[d] = 1;
|
|
797
|
+
for (const site of childSites(defs[d])) {
|
|
798
|
+
const c = site[2];
|
|
799
|
+
if (c < 0) continue;
|
|
800
|
+
if (state[c] === 1) fn[c] = true;
|
|
801
|
+
else if (state[c] === 0) dfs(c);
|
|
802
|
+
}
|
|
803
|
+
state[d] = 2;
|
|
804
|
+
};
|
|
805
|
+
for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
|
|
806
|
+
return fn;
|
|
807
|
+
}
|
|
808
|
+
next(prefix) {
|
|
809
|
+
return `${prefix}${this.uid++}`;
|
|
810
|
+
}
|
|
811
|
+
/** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
|
|
812
|
+
const lines = body();
|
|
813
|
+
const code = lines.join("\n");
|
|
814
|
+
const locals = [];
|
|
815
|
+
if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${F_IN_UNION}) === 0`);
|
|
816
|
+
if (/\bt = /.test(code)) locals.push("let t");
|
|
817
|
+
return [
|
|
818
|
+
`function ${name}(v, f, o) {`,
|
|
819
|
+
...indent([...locals, ...lines]),
|
|
820
|
+
"}"
|
|
821
|
+
];
|
|
822
|
+
}
|
|
823
|
+
defFunction(d) {
|
|
824
|
+
const def = this.defs[d];
|
|
825
|
+
return this.fnLines(`d${d}`, () => {
|
|
826
|
+
switch (def[0]) {
|
|
827
|
+
case D_OBJECT: return this.objectBody(def);
|
|
828
|
+
case D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
|
|
829
|
+
case D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
|
|
830
|
+
case D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
|
|
831
|
+
case D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
|
|
832
|
+
case D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
|
|
833
|
+
default: return ["return 2"];
|
|
834
|
+
}
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
/** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
|
|
838
|
+
const sites = def[2];
|
|
839
|
+
const props = def[1].map((key, i) => ({
|
|
840
|
+
key,
|
|
841
|
+
site: sites[i]
|
|
842
|
+
})).filter((p) => !this.isPhantom(p.site));
|
|
843
|
+
const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
|
|
844
|
+
if (props.some((p) => p.site[0] === 0 || p.site[2] === INTERP)) {
|
|
845
|
+
const top = F_PARTIAL_TOP | F_TOP;
|
|
846
|
+
lines.push(`const sk = (f & ${F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
|
|
847
|
+
}
|
|
848
|
+
if (props.length > 0) lines.push("let r = 1");
|
|
849
|
+
for (const { key, site } of props) {
|
|
850
|
+
const p = this.next("P");
|
|
851
|
+
const x = this.next("x");
|
|
852
|
+
const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
|
|
853
|
+
lines.push(`${p}: {`, ` const ${x} = ${access}`);
|
|
854
|
+
if (site[0] === 0 || site[2] === INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
|
|
855
|
+
const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
|
|
856
|
+
lines.push(...indent(this.site(site, x, ctx)), "}");
|
|
857
|
+
}
|
|
858
|
+
if (props.length > 0) lines.push("if (r === 0) return 0");
|
|
859
|
+
const known = props.map((p) => p.key);
|
|
860
|
+
const onUnknown = `{ if ((f & ${F_ERROR}) !== 0) return 0; if ((f & ${F_TOP}) === 0) return 2; pk.push(k) }`;
|
|
861
|
+
const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
|
|
862
|
+
"for (const k in v) {",
|
|
863
|
+
" switch (k) {",
|
|
864
|
+
...known.map((key) => ` case ${literalSource(key)}:`),
|
|
865
|
+
" break",
|
|
866
|
+
" default:",
|
|
867
|
+
` if (ho.call(v, k)) ${onUnknown}`,
|
|
868
|
+
" }",
|
|
869
|
+
"}"
|
|
870
|
+
];
|
|
871
|
+
lines.push(`if ((f & ${F_ERROR | F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
|
|
872
|
+
return lines;
|
|
873
|
+
}
|
|
874
|
+
isPhantom(site) {
|
|
875
|
+
const d = site[2];
|
|
876
|
+
return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "phantom";
|
|
877
|
+
}
|
|
878
|
+
isLiteralDef(d) {
|
|
879
|
+
return d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d].length > 2;
|
|
880
|
+
}
|
|
881
|
+
/** A required `never` union branch: it can never match (skipped). */ isNever(site) {
|
|
882
|
+
const d = site[2];
|
|
883
|
+
return site[0] === 0 && d >= 0 && this.defs[d][0] === D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
|
|
884
|
+
}
|
|
885
|
+
/** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
|
|
886
|
+
const [, , d, , slot] = site;
|
|
887
|
+
if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
|
|
888
|
+
return `k${d === INTERP ? slot + 1 : slot + (hasRejectSlot(site) ? 1 : 0) + 1}`;
|
|
889
|
+
}
|
|
890
|
+
/** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
|
|
891
|
+
const [optional, mask, d, shape, slot] = site;
|
|
892
|
+
if (d === INTERP) return this.call(`k${slot}`, x, ctx);
|
|
893
|
+
let at = slot;
|
|
894
|
+
const rej = hasRejectSlot(site) ? at++ : -1;
|
|
895
|
+
const body = d === EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
|
|
896
|
+
if (!optional) return body;
|
|
897
|
+
if (rej < 0) return body.length > 0 ? [
|
|
898
|
+
`if (${x} !== undefined && ${x} !== null) {`,
|
|
899
|
+
...indent(body),
|
|
900
|
+
"}"
|
|
901
|
+
] : [];
|
|
902
|
+
const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
|
|
903
|
+
if (body.length > 0) lines.push("} else {", ...indent(body));
|
|
904
|
+
lines.push("}");
|
|
905
|
+
return lines;
|
|
906
|
+
}
|
|
907
|
+
/** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
|
|
908
|
+
this.calls++;
|
|
909
|
+
return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
|
|
910
|
+
}
|
|
911
|
+
def(d, mask, shape, at, x, ctx) {
|
|
912
|
+
const def = this.defs[d];
|
|
913
|
+
const kind = def[0];
|
|
914
|
+
if (this.fn[d] && kind !== D_ARRAY && kind !== D_UNION) return this.call(`d${d}`, x, ctx);
|
|
915
|
+
switch (kind) {
|
|
916
|
+
case D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
|
|
917
|
+
case D_ARRAY: return [
|
|
918
|
+
`if (!Array.isArray(${x})) ${ctx.fail}`,
|
|
919
|
+
...this.arrayConstraints(mask, keySlots(mask, shape, at), x, ctx.fail),
|
|
920
|
+
...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
|
|
921
|
+
];
|
|
922
|
+
case D_UNION: {
|
|
923
|
+
const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
|
|
924
|
+
if (!this.fn[d]) return this.union(def[1], {
|
|
925
|
+
mask,
|
|
926
|
+
shape,
|
|
927
|
+
at
|
|
928
|
+
}, constraints, x, ctx);
|
|
929
|
+
this.calls++;
|
|
930
|
+
const lines = [
|
|
931
|
+
`t = d${d}(${x}, ${flags(ctx)}, o)`,
|
|
932
|
+
"if (t === 2) return 2",
|
|
933
|
+
`if (t === 0) ${ctx.fail}`
|
|
934
|
+
];
|
|
935
|
+
if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
|
|
936
|
+
return lines;
|
|
937
|
+
}
|
|
938
|
+
case D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
|
|
939
|
+
case D_TUPLE: return this.tuple(def[1], x, ctx);
|
|
940
|
+
default: return ["return 2"];
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
/** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
|
|
944
|
+
const designType = def[1];
|
|
945
|
+
if (designType === "phantom") return [];
|
|
946
|
+
if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
|
|
947
|
+
const ks = keySlots(mask, shape, at);
|
|
948
|
+
switch (designType) {
|
|
949
|
+
case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
|
|
950
|
+
case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
|
|
951
|
+
case "boolean": {
|
|
952
|
+
const conds = [`typeof ${x} !== "boolean"`];
|
|
953
|
+
if (mask & B_REQUIRED) conds.push(`${x} !== true`);
|
|
954
|
+
return [`if (${conds.join(" || ")}) ${fail}`];
|
|
955
|
+
}
|
|
956
|
+
case "any": return [];
|
|
957
|
+
case "never": return [fail];
|
|
958
|
+
case "undefined": return [`if (${x} !== undefined) ${fail}`];
|
|
959
|
+
case "null": return [`if (${x} !== null) ${fail}`];
|
|
960
|
+
case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
|
|
961
|
+
default: return ["return 2"];
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
stringChecks(mask, shape, ks, x, fail, conds) {
|
|
965
|
+
if (mask & B_REQUIRED) conds.push(`${x}.trim().length === 0`);
|
|
966
|
+
if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
|
|
967
|
+
if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
|
|
968
|
+
const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
969
|
+
let p = 0;
|
|
970
|
+
for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
|
|
971
|
+
else if (c === "s") {
|
|
972
|
+
lines.push("return 2");
|
|
973
|
+
break;
|
|
974
|
+
}
|
|
975
|
+
return lines;
|
|
976
|
+
}
|
|
977
|
+
numberChecks(mask, ks, x, fail, conds) {
|
|
978
|
+
if (mask & B_INT) conds.push(`${x} % 1 !== 0`);
|
|
979
|
+
if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
|
|
980
|
+
if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
|
|
981
|
+
if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
|
|
982
|
+
if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
|
|
983
|
+
return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
984
|
+
}
|
|
985
|
+
/** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
|
|
986
|
+
const conds = [];
|
|
987
|
+
if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
|
|
988
|
+
if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
|
|
989
|
+
const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
990
|
+
if (mask & B_UNIQUE) lines.push("return 2");
|
|
991
|
+
return lines;
|
|
992
|
+
}
|
|
993
|
+
/** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
|
|
994
|
+
const ks = keySlots(mask, shape, at);
|
|
995
|
+
const branches = [];
|
|
996
|
+
if (mask & STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
|
|
997
|
+
if (mask & NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
|
|
998
|
+
if (mask & B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
|
|
999
|
+
if (mask & ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
|
|
1000
|
+
const lines = [];
|
|
1001
|
+
branches.forEach(([cond, body], i) => {
|
|
1002
|
+
lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
|
|
1003
|
+
});
|
|
1004
|
+
if (lines.length > 0) lines.push("}");
|
|
1005
|
+
return lines;
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* The union-level constraints after a non-literal branch passed. A required (non-optional)
|
|
1009
|
+
* branch of a known primitive / array type fixes `typeof`: only that part applies.
|
|
1010
|
+
*/ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
|
|
1011
|
+
const [optional, , d] = item;
|
|
1012
|
+
const def = this.defs[d];
|
|
1013
|
+
if (optional) return constraints;
|
|
1014
|
+
const ks = keySlots(mask, shape, at);
|
|
1015
|
+
if (def[0] === D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
|
|
1016
|
+
if (def[0] !== D_FINAL) return constraints;
|
|
1017
|
+
switch (def[1]) {
|
|
1018
|
+
case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
|
|
1019
|
+
case "number": return this.numberChecks(mask, ks, x, fail, []);
|
|
1020
|
+
case "boolean": return mask & B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
|
|
1021
|
+
case "null":
|
|
1022
|
+
case "undefined": return [];
|
|
1023
|
+
default: return constraints;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
|
|
1028
|
+
* FAIL breaks out of; `onMatch` ends a passing branch.
|
|
1029
|
+
*/ unionBranches(items, x, clearTop, onMatch) {
|
|
1030
|
+
const lines = [];
|
|
1031
|
+
for (const item of items) {
|
|
1032
|
+
if (this.isNever(item)) continue;
|
|
1033
|
+
const b = this.next("B");
|
|
1034
|
+
const calls = this.calls;
|
|
1035
|
+
const fail = `break ${b}`;
|
|
1036
|
+
const body = this.site(item, x, {
|
|
1037
|
+
fail,
|
|
1038
|
+
inUnionFail: fail,
|
|
1039
|
+
union: true,
|
|
1040
|
+
clearTop
|
|
1041
|
+
});
|
|
1042
|
+
lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
|
|
1043
|
+
if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
|
|
1044
|
+
}
|
|
1045
|
+
return lines;
|
|
1046
|
+
}
|
|
1047
|
+
/** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
|
|
1048
|
+
const u = this.next("U");
|
|
1049
|
+
const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
|
|
1050
|
+
const lines = [];
|
|
1051
|
+
const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
|
|
1052
|
+
if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
|
|
1053
|
+
else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
|
|
1054
|
+
lines.push(`break ${u}`);
|
|
1055
|
+
return lines;
|
|
1056
|
+
});
|
|
1057
|
+
return [
|
|
1058
|
+
`${u}: {`,
|
|
1059
|
+
...indent([...branches, ctx.fail]),
|
|
1060
|
+
"}"
|
|
1061
|
+
];
|
|
1062
|
+
}
|
|
1063
|
+
/** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
|
|
1064
|
+
const y = this.next("y");
|
|
1065
|
+
const a = this.next("a");
|
|
1066
|
+
const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
|
|
1067
|
+
if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
|
|
1068
|
+
return [
|
|
1069
|
+
`let ${a} = 1`,
|
|
1070
|
+
`for (const ${y} of ${x}) {`,
|
|
1071
|
+
...indent(body),
|
|
1072
|
+
"}",
|
|
1073
|
+
`if (${a} === 0) ${ctx.inUnionFail}`
|
|
1074
|
+
];
|
|
1075
|
+
}
|
|
1076
|
+
/** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
|
|
1077
|
+
const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
|
|
1078
|
+
items.forEach((item, i) => {
|
|
1079
|
+
const e = this.next("e");
|
|
1080
|
+
lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
|
|
1081
|
+
...ctx,
|
|
1082
|
+
clearTop: true
|
|
1083
|
+
}));
|
|
1084
|
+
});
|
|
1085
|
+
return lines;
|
|
1086
|
+
}
|
|
1087
|
+
constructor(layout) {
|
|
1088
|
+
_define_property$2(this, "layout", void 0);
|
|
1089
|
+
_define_property$2(this, "defs", void 0);
|
|
1090
|
+
/** Def index → emitted as its own function. */ _define_property$2(this, "fn", void 0);
|
|
1091
|
+
_define_property$2(this, "uid", void 0);
|
|
1092
|
+
/** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$2(this, "calls", void 0);
|
|
1093
|
+
this.layout = layout;
|
|
1094
|
+
this.uid = 0;
|
|
1095
|
+
this.calls = 0;
|
|
1096
|
+
this.defs = layout[0];
|
|
1097
|
+
this.fn = this.functionDefs();
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
/**
|
|
1101
|
+
* Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
|
|
1102
|
+
* inside a union and leaves the check otherwise.
|
|
1103
|
+
*/ function recordingCtx(record, union, clearTop) {
|
|
1104
|
+
const inUnionFail = `{ ${record} }`;
|
|
1105
|
+
return {
|
|
1106
|
+
fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
|
|
1107
|
+
inUnionFail,
|
|
1108
|
+
union,
|
|
1109
|
+
clearTop
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
/** Flags passed to a callee. */ function flags(ctx) {
|
|
1113
|
+
if (ctx.clearTop) return ctx.union ? `(f & ${~F_TOP}) | ${F_IN_UNION}` : `f & ${~F_TOP}`;
|
|
1114
|
+
return ctx.union ? `f | ${F_IN_UNION}` : "f";
|
|
1115
|
+
}
|
|
1116
|
+
/** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
|
|
1117
|
+
return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
|
|
1118
|
+
}
|
|
1119
|
+
/** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
|
|
1120
|
+
return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
|
|
1121
|
+
}
|
|
1122
|
+
function notObject(x) {
|
|
1123
|
+
return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
|
|
1124
|
+
}
|
|
1125
|
+
function indent(lines, n = 2) {
|
|
1126
|
+
const pad = " ".repeat(n);
|
|
1127
|
+
return lines.map((l) => pad + l);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
//#endregion
|
|
1131
|
+
//#region packages/typescript/src/codegen/validation-model.ts
|
|
1132
|
+
function _define_property$1(obj, key, value) {
|
|
1133
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
1134
|
+
value,
|
|
1135
|
+
enumerable: true,
|
|
1136
|
+
configurable: true,
|
|
1137
|
+
writable: true
|
|
1138
|
+
});
|
|
1139
|
+
else obj[key] = value;
|
|
1140
|
+
return obj;
|
|
1141
|
+
}
|
|
1142
|
+
/** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
|
|
1143
|
+
const INTERP_KIND = "#interp";
|
|
1144
|
+
/**
|
|
1145
|
+
* How the layout treats a model type: `'ext'` — another module's type referenced as a
|
|
1146
|
+
* whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
|
|
1147
|
+
* chained reference into another module's type, only known at runtime.
|
|
1148
|
+
*/ function classifyType(type) {
|
|
1149
|
+
const kind = type?.kind;
|
|
1150
|
+
return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Build-time model of the runtime type trees a generated `.as.js` module builds, used to
|
|
1154
|
+
* compile validator checks (`compileValidators`).
|
|
1155
|
+
*
|
|
1156
|
+
* The renderer drives it in lockstep with the builder chains it emits, through the real
|
|
1157
|
+
* runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
|
|
1158
|
+
* the same structure, the same type-def sharing (by identity) and the same validator
|
|
1159
|
+
* annotations as the module after its initialisation. Only the annotations the validator
|
|
1160
|
+
* pre-check reads are recorded. Types of other modules are opaque markers: a reference to
|
|
1161
|
+
* one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
|
|
1162
|
+
* runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
|
|
1163
|
+
*
|
|
1164
|
+
* Anything the model cannot follow marks it broken; nothing is compiled then. A model that
|
|
1165
|
+
* nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
|
|
1166
|
+
* the interpreted pre-check runs.
|
|
1167
|
+
*/ var ValidationModel = class {
|
|
1168
|
+
/** Runs a model step; a throw marks the model broken. */ run(step) {
|
|
1169
|
+
if (this.broken) return;
|
|
1170
|
+
try {
|
|
1171
|
+
return step();
|
|
1172
|
+
} catch {
|
|
1173
|
+
this.broken = true;
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
/** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
|
|
1178
|
+
this.classes.set(name, {
|
|
1179
|
+
__is_atscript_annotated_type: true,
|
|
1180
|
+
type: {},
|
|
1181
|
+
metadata: /* @__PURE__ */ new Map(),
|
|
1182
|
+
name
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
/** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
|
|
1186
|
+
const cls = this.classes.get(name);
|
|
1187
|
+
if (!cls) throw new Error(`${name} is not a class of this module`);
|
|
1188
|
+
return cls;
|
|
1189
|
+
}
|
|
1190
|
+
/** `$(kind, name?)`. */ handle(kind, name) {
|
|
1191
|
+
return this.run(() => defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
|
|
1192
|
+
}
|
|
1193
|
+
/** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
|
|
1194
|
+
this.run(() => {
|
|
1195
|
+
if (!handle) throw new Error("no chain");
|
|
1196
|
+
if (imported) {
|
|
1197
|
+
const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
|
|
1198
|
+
handle.refTo(() => marker, chain);
|
|
1199
|
+
} else handle.refTo(this.classBase(name), chain);
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
/** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
|
|
1203
|
+
const key = `${name}${kind}`;
|
|
1204
|
+
let marker = this.markers.get(key);
|
|
1205
|
+
if (!marker) {
|
|
1206
|
+
marker = {
|
|
1207
|
+
__is_atscript_annotated_type: true,
|
|
1208
|
+
type: { kind },
|
|
1209
|
+
metadata: /* @__PURE__ */ new Map()
|
|
1210
|
+
};
|
|
1211
|
+
this.markers.set(key, marker);
|
|
1212
|
+
}
|
|
1213
|
+
return marker;
|
|
1214
|
+
}
|
|
1215
|
+
/** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
|
|
1216
|
+
if (!isValidatorKey(key)) return;
|
|
1217
|
+
this.run(() => {
|
|
1218
|
+
if (!this.current) throw new Error("no chain");
|
|
1219
|
+
this.current.annotate(key, value, multiple);
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
/** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
|
|
1223
|
+
let cur = this.classes.get(name);
|
|
1224
|
+
for (const step of steps) {
|
|
1225
|
+
if (cur === void 0 || cur === null) return;
|
|
1226
|
+
if (step === "type") {
|
|
1227
|
+
cur = cur.type;
|
|
1228
|
+
if (classifyType(cur) !== void 0) return;
|
|
1229
|
+
} else if (step[0] === "props") cur = cur.props?.get(step[1]);
|
|
1230
|
+
else cur = cur.items?.[step[1]];
|
|
1231
|
+
}
|
|
1232
|
+
return cur;
|
|
1233
|
+
}
|
|
1234
|
+
/** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
|
|
1235
|
+
this.run(() => {
|
|
1236
|
+
const parent = this.resolve(name, steps);
|
|
1237
|
+
if (parent) cloneRefProp(parent, prop);
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
/** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
|
|
1241
|
+
this.run(() => {
|
|
1242
|
+
this.resolve(name, steps)?.metadata?.delete(key);
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
/** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
|
|
1246
|
+
if (!isValidatorKey(key)) return;
|
|
1247
|
+
this.run(() => {
|
|
1248
|
+
annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
|
|
1253
|
+
* compiled (its root type is only known at runtime, or the model is broken).
|
|
1254
|
+
*/ registration(name) {
|
|
1255
|
+
if (this.broken) return;
|
|
1256
|
+
const cls = this.classes.get(name);
|
|
1257
|
+
if (!cls) return;
|
|
1258
|
+
let layout;
|
|
1259
|
+
try {
|
|
1260
|
+
layout = buildLayout(cls, { regex: getRegex }, classifyType);
|
|
1261
|
+
} catch {
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
const root = layout[1][2];
|
|
1265
|
+
if (root === INTERP || root >= 0 && layout[0][root][0] === D_UNKNOWN) return;
|
|
1266
|
+
return `$cv(${name}, ${LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
|
|
1267
|
+
}
|
|
1268
|
+
constructor() {
|
|
1269
|
+
/** The model could not follow the emitted code: compile nothing. */ _define_property$1(this, "broken", false);
|
|
1270
|
+
/** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$1(this, "current", void 0);
|
|
1271
|
+
_define_property$1(this, "classes", /* @__PURE__ */ new Map());
|
|
1272
|
+
_define_property$1(this, "markers", /* @__PURE__ */ new Map());
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
/**
|
|
1276
|
+
* Runtime value of an annotation argument the emitted code writes as a raw expression
|
|
1277
|
+
* (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
|
|
1278
|
+
* compares only presence / truthiness and reads the real values at runtime.
|
|
1279
|
+
*/ function rawLiteralValue(text) {
|
|
1280
|
+
switch (text) {
|
|
1281
|
+
case "true": return true;
|
|
1282
|
+
case "false": return false;
|
|
1283
|
+
case "null": return null;
|
|
1284
|
+
case "undefined": return;
|
|
1285
|
+
default: {
|
|
1286
|
+
const n = Number(text);
|
|
1287
|
+
return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
636
1292
|
//#endregion
|
|
637
1293
|
//#region packages/typescript/src/codegen/js-renderer.ts
|
|
638
1294
|
function _define_property(obj, key, value) {
|
|
@@ -665,6 +1321,17 @@ const QUERY_OP_MAP = {
|
|
|
665
1321
|
"expect.exclusiveMax": "exclusiveMaxValue"
|
|
666
1322
|
};
|
|
667
1323
|
const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
|
|
1324
|
+
/** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
|
|
1325
|
+
return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
|
|
1326
|
+
}
|
|
1327
|
+
/**
|
|
1328
|
+
* The runtime accessor of a mutating-annotate path: `Name` followed by the steps
|
|
1329
|
+
* (`.type`, `.props.get("a")?`, `.items[0]`).
|
|
1330
|
+
*/ function accessorPath(targetName, steps) {
|
|
1331
|
+
let path = targetName;
|
|
1332
|
+
for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
|
|
1333
|
+
return path;
|
|
1334
|
+
}
|
|
668
1335
|
var JsRenderer = class extends BaseRenderer {
|
|
669
1336
|
/**
|
|
670
1337
|
* Relative imports get the configured `moduleExtension`; bare specifiers
|
|
@@ -843,6 +1510,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
843
1510
|
if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
|
|
844
1511
|
if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
|
|
845
1512
|
if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
|
|
1513
|
+
if (this.model) imports.push("registerCompiledCheck as $cv");
|
|
846
1514
|
this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
|
|
847
1515
|
this.computeSynthesizedImports();
|
|
848
1516
|
this.writeln(SYNTH_IMPORTS_MARKER);
|
|
@@ -890,7 +1558,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
890
1558
|
if (isInterface(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
|
|
891
1559
|
else def = def.getDefinition() || def;
|
|
892
1560
|
this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
|
|
893
|
-
this.annotateType(def, node.id);
|
|
1561
|
+
this.modelClass(node.id, () => this.annotateType(def, node.id));
|
|
894
1562
|
this._adHocAnnotations = null;
|
|
895
1563
|
this.indent();
|
|
896
1564
|
this.defineMetadataForAnnotateAlias(annotateNode);
|
|
@@ -904,13 +1572,38 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
904
1572
|
const resolved = this.doc.resolveInterfaceExtends(node);
|
|
905
1573
|
if (resolved) def = resolved;
|
|
906
1574
|
}
|
|
907
|
-
this.annotateType(def, node.id);
|
|
1575
|
+
this.modelClass(node.id, () => this.annotateType(def, node.id));
|
|
908
1576
|
this.indent().defineMetadata(node).unindent();
|
|
909
1577
|
this.writeln();
|
|
910
1578
|
}
|
|
1579
|
+
this.renderCompiledChecks();
|
|
911
1580
|
this.writeln("// prettier-ignore-end");
|
|
912
1581
|
super.post();
|
|
913
1582
|
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Emits class `name`'s chain; the validation model follows it (its handle stays the current
|
|
1585
|
+
* chain, the target of the class-level annotations emitted next).
|
|
1586
|
+
*/ modelClass(name, emit) {
|
|
1587
|
+
if (this.model) this.model.current = void 0;
|
|
1588
|
+
emit();
|
|
1589
|
+
if (this.model?.current) this.modelClasses.push(name);
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
|
|
1593
|
+
* mutating annotate of the module ran (the compiled check binds on first use).
|
|
1594
|
+
*/ renderCompiledChecks() {
|
|
1595
|
+
if (!this.model) return;
|
|
1596
|
+
const registrations = [];
|
|
1597
|
+
for (const name of this.modelClasses) {
|
|
1598
|
+
const registration = this.model.registration(name);
|
|
1599
|
+
if (registration) registrations.push(registration);
|
|
1600
|
+
}
|
|
1601
|
+
if (registrations.length > 0) {
|
|
1602
|
+
this.writeln("// Compiled validator checks");
|
|
1603
|
+
for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
|
|
1604
|
+
this.writeln();
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
914
1607
|
renderClassStatics(node) {
|
|
915
1608
|
this.writeln("static __is_atscript_annotated_type = true");
|
|
916
1609
|
this.writeln("static type = {}");
|
|
@@ -941,6 +1634,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
941
1634
|
this.write(exported ? "export " : "");
|
|
942
1635
|
this.write(`class ${node.id} `);
|
|
943
1636
|
this.blockln("{}");
|
|
1637
|
+
this.model?.declare(node.id);
|
|
944
1638
|
this.renderClassStatics(node);
|
|
945
1639
|
this.popln();
|
|
946
1640
|
this.postAnnotate.push(node);
|
|
@@ -990,23 +1684,63 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
990
1684
|
if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
|
|
991
1685
|
}
|
|
992
1686
|
toAnnotatedType(node) {
|
|
993
|
-
return this.toAnnotatedHandle(node).$type;
|
|
1687
|
+
return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* The build-time runtime type of an interface / type declaration (see `_declTypes`);
|
|
1691
|
+
* `doc` is the document that declares it (where an alias's target name resolves).
|
|
1692
|
+
*/ declType(node, doc = this.doc) {
|
|
1693
|
+
const known = this._declTypes.get(node);
|
|
1694
|
+
if (known) return known;
|
|
1695
|
+
let def = node.getDefinition();
|
|
1696
|
+
if (isInterface(node) && node.hasExtends) {
|
|
1697
|
+
const resolved = this.doc.resolveInterfaceExtends(node);
|
|
1698
|
+
if (resolved) def = resolved;
|
|
1699
|
+
}
|
|
1700
|
+
const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
|
|
1701
|
+
let handle;
|
|
1702
|
+
if (def && isRef(def)) {
|
|
1703
|
+
const ref = def;
|
|
1704
|
+
const decl = doc.unwindType(ref.id, ref.chain)?.def;
|
|
1705
|
+
const target = this.refTarget(ref, decl, doc);
|
|
1706
|
+
handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
|
|
1707
|
+
} else {
|
|
1708
|
+
const base = {
|
|
1709
|
+
__is_atscript_annotated_type: true,
|
|
1710
|
+
type: {},
|
|
1711
|
+
metadata: /* @__PURE__ */ new Map(),
|
|
1712
|
+
id: typeId
|
|
1713
|
+
};
|
|
1714
|
+
this._declTypes.set(node, base);
|
|
1715
|
+
if (def) this._declTypes.set(def, base);
|
|
1716
|
+
handle = this.toAnnotatedHandle(def, true, base);
|
|
1717
|
+
}
|
|
1718
|
+
this._declTypes.set(node, handle.$type);
|
|
1719
|
+
if (typeId) handle.id(typeId);
|
|
1720
|
+
this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1721
|
+
return handle.$type;
|
|
994
1722
|
}
|
|
995
|
-
|
|
996
|
-
|
|
1723
|
+
/**
|
|
1724
|
+
* The declaration type a reference points at (see `declType`), or `undefined` when it is
|
|
1725
|
+
* not a declaration (a chained reference into a prop, an unresolved name). A plain
|
|
1726
|
+
* reference to a type alias points at the alias itself (its own type and id, like the
|
|
1727
|
+
* runtime `$().refTo(Alias)`), not at what the alias unwinds to.
|
|
1728
|
+
*/ refTarget(ref, decl, doc = this.doc) {
|
|
1729
|
+
if (!decl) return;
|
|
1730
|
+
const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
|
|
1731
|
+
if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
|
|
1732
|
+
const known = this._declTypes.get(decl);
|
|
1733
|
+
if (known) return known;
|
|
1734
|
+
return isInterface(decl) ? this.declType(decl) : void 0;
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* The build-time runtime type of an expression node; with `base`, built into that object
|
|
1738
|
+
* (a declaration's type, see `declType`).
|
|
1739
|
+
*/ toAnnotatedHandle(node, skipAnnotations = false, base) {
|
|
1740
|
+
if (!node) return defineAnnotatedType(void 0, base);
|
|
997
1741
|
switch (node.entity) {
|
|
998
1742
|
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
|
-
}
|
|
1743
|
+
case "type": return defineAnnotatedType().refTo(this.declType(node));
|
|
1010
1744
|
case "prop": {
|
|
1011
1745
|
const prop = node;
|
|
1012
1746
|
const def = prop.getDefinition();
|
|
@@ -1020,7 +1754,8 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1020
1754
|
case "ref": {
|
|
1021
1755
|
const ref = node;
|
|
1022
1756
|
const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
|
|
1023
|
-
const
|
|
1757
|
+
const target = this.refTarget(ref, decl);
|
|
1758
|
+
const handle = target ? defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
|
|
1024
1759
|
if (skipAnnotations) return handle;
|
|
1025
1760
|
const own = this.doc.evalAnnotationsForNode(node);
|
|
1026
1761
|
const referred = this.refTargetAnnotations(ref, decl);
|
|
@@ -1028,14 +1763,14 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1028
1763
|
}
|
|
1029
1764
|
case "primitive": {
|
|
1030
1765
|
const prim = node;
|
|
1031
|
-
const handle = defineAnnotatedType();
|
|
1766
|
+
const handle = defineAnnotatedType(void 0, base);
|
|
1032
1767
|
handle.designType(prim.id === "never" ? "never" : prim.config.type);
|
|
1033
1768
|
if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1034
1769
|
return handle;
|
|
1035
1770
|
}
|
|
1036
1771
|
case "const": {
|
|
1037
1772
|
const c = node;
|
|
1038
|
-
const handle = defineAnnotatedType();
|
|
1773
|
+
const handle = defineAnnotatedType(void 0, base);
|
|
1039
1774
|
const t = c.token("identifier")?.type;
|
|
1040
1775
|
handle.designType(t === "number" ? "number" : "string");
|
|
1041
1776
|
handle.value(t === "number" ? Number(c.id) : c.id);
|
|
@@ -1043,7 +1778,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1043
1778
|
}
|
|
1044
1779
|
case "structure": {
|
|
1045
1780
|
const struct = node;
|
|
1046
|
-
const handle = defineAnnotatedType("object");
|
|
1781
|
+
const handle = defineAnnotatedType("object", base);
|
|
1047
1782
|
for (const prop of Array.from(struct.props.values())) {
|
|
1048
1783
|
const propHandle = this.toAnnotatedHandle(prop);
|
|
1049
1784
|
const pattern = prop.token("identifier")?.pattern;
|
|
@@ -1054,24 +1789,24 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1054
1789
|
}
|
|
1055
1790
|
case "group": {
|
|
1056
1791
|
const group = node;
|
|
1057
|
-
const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection");
|
|
1792
|
+
const handle = defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
|
|
1058
1793
|
for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
|
|
1059
1794
|
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1060
1795
|
}
|
|
1061
1796
|
case "tuple": {
|
|
1062
1797
|
const group = node;
|
|
1063
|
-
const handle = defineAnnotatedType("tuple");
|
|
1798
|
+
const handle = defineAnnotatedType("tuple", base);
|
|
1064
1799
|
for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
|
|
1065
1800
|
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1066
1801
|
}
|
|
1067
1802
|
case "array": {
|
|
1068
1803
|
const arr = node;
|
|
1069
|
-
const handle = defineAnnotatedType("array");
|
|
1804
|
+
const handle = defineAnnotatedType("array", base);
|
|
1070
1805
|
handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
|
|
1071
1806
|
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1072
1807
|
}
|
|
1073
1808
|
default: {
|
|
1074
|
-
const handle = defineAnnotatedType();
|
|
1809
|
+
const handle = defineAnnotatedType(void 0, base);
|
|
1075
1810
|
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1076
1811
|
}
|
|
1077
1812
|
}
|
|
@@ -1143,8 +1878,10 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1143
1878
|
node: synth.ownerNode
|
|
1144
1879
|
} : this.resolveOwner(this.doc, ref.id);
|
|
1145
1880
|
const refName = synth?.alias ?? ref.id;
|
|
1146
|
-
const
|
|
1881
|
+
const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
|
|
1882
|
+
const refExpr = isImported ? `() => ${refName}` : refName;
|
|
1147
1883
|
this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
|
|
1884
|
+
this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
|
|
1148
1885
|
if (!ref.hasChain) {
|
|
1149
1886
|
if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
|
|
1150
1887
|
this.resolveAnnotationValue(ownerDecl.node, an);
|
|
@@ -1157,29 +1894,63 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1157
1894
|
this.definePrimitive(node, name);
|
|
1158
1895
|
return this;
|
|
1159
1896
|
case "const":
|
|
1897
|
+
this.modelHandle("", name);
|
|
1160
1898
|
this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
|
|
1161
1899
|
return this;
|
|
1162
1900
|
case "structure":
|
|
1901
|
+
this.modelHandle("object", name);
|
|
1163
1902
|
this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
|
|
1164
1903
|
return this;
|
|
1165
1904
|
case "group":
|
|
1166
1905
|
kind = node.op === "|" ? "union" : "intersection";
|
|
1906
|
+
this.modelHandle(kind, name);
|
|
1167
1907
|
this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
|
|
1168
1908
|
return this;
|
|
1169
1909
|
case "tuple":
|
|
1910
|
+
this.modelHandle("tuple", name);
|
|
1170
1911
|
this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
|
|
1171
1912
|
return this;
|
|
1172
1913
|
case "array":
|
|
1914
|
+
this.modelHandle("array", name);
|
|
1173
1915
|
this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
|
|
1174
1916
|
return this;
|
|
1175
1917
|
default: return this;
|
|
1176
1918
|
}
|
|
1177
1919
|
}
|
|
1920
|
+
/** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
|
|
1921
|
+
if (!this.model) return;
|
|
1922
|
+
const h = this.model.handle(kind, name);
|
|
1923
|
+
this.model.current = h;
|
|
1924
|
+
return h;
|
|
1925
|
+
}
|
|
1926
|
+
/**
|
|
1927
|
+
* The model handle of a nested chain (`emit` writes it and its annotations): `current`
|
|
1928
|
+
* is cleared first so a chain that emits nothing breaks the model instead of leaving a
|
|
1929
|
+
* stale handle, and restored to the parent chain afterwards.
|
|
1930
|
+
*/ modelChild(emit) {
|
|
1931
|
+
if (!this.model) {
|
|
1932
|
+
emit();
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
const parent = this.model.current;
|
|
1936
|
+
this.model.current = void 0;
|
|
1937
|
+
emit();
|
|
1938
|
+
const child = this.model.current;
|
|
1939
|
+
this.model.current = parent;
|
|
1940
|
+
if (!child) this.model.broken = true;
|
|
1941
|
+
return child;
|
|
1942
|
+
}
|
|
1178
1943
|
defineConst(node) {
|
|
1179
1944
|
const t = node.token("identifier")?.type;
|
|
1180
1945
|
const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
|
|
1181
1946
|
this.writeln(`.designType("${escapeQuotes(designType)}")`);
|
|
1182
1947
|
this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
|
|
1948
|
+
if (this.model) {
|
|
1949
|
+
const h = this.model.current;
|
|
1950
|
+
this.model.run(() => {
|
|
1951
|
+
h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1183
1954
|
return this;
|
|
1184
1955
|
}
|
|
1185
1956
|
definePrimitive(node, name) {
|
|
@@ -1187,66 +1958,82 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1187
1958
|
this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
|
|
1188
1959
|
return this;
|
|
1189
1960
|
}
|
|
1190
|
-
renderPrimitiveDef(def, name) {
|
|
1961
|
+
/** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
|
|
1191
1962
|
const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
|
|
1192
|
-
|
|
1193
|
-
|
|
1963
|
+
const final = (designType) => {
|
|
1964
|
+
this.writeln(`$(${d()}).designType("${designType}")`);
|
|
1965
|
+
const h = this.modelHandle("", name);
|
|
1966
|
+
this.model?.run(() => h.designType(designType));
|
|
1967
|
+
};
|
|
1968
|
+
if (!def) return final("any");
|
|
1969
|
+
if (typeof def === "string") return final(def === "void" ? "undefined" : def);
|
|
1194
1970
|
switch (def.kind) {
|
|
1195
|
-
case "final": return
|
|
1971
|
+
case "final": return final(def.value === "void" ? "undefined" : def.value);
|
|
1196
1972
|
case "union":
|
|
1197
1973
|
case "intersection":
|
|
1198
1974
|
case "tuple":
|
|
1199
1975
|
this.writeln(`$(${d(def.kind)})`);
|
|
1976
|
+
this.modelHandle(def.kind, name);
|
|
1200
1977
|
this.indent();
|
|
1201
1978
|
for (const itemDef of def.items) {
|
|
1202
1979
|
this.write(`.item(`);
|
|
1203
1980
|
this.indent();
|
|
1204
|
-
this.renderPrimitiveDef(itemDef);
|
|
1981
|
+
const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
|
|
1205
1982
|
this.writeln(".$type");
|
|
1206
1983
|
this.unindent();
|
|
1207
1984
|
this.write(`)`);
|
|
1985
|
+
this.model?.run(() => this.model.current.item(child.$type));
|
|
1208
1986
|
}
|
|
1209
1987
|
this.unindent();
|
|
1210
1988
|
return;
|
|
1211
|
-
case "array":
|
|
1989
|
+
case "array": {
|
|
1212
1990
|
this.writeln(`$(${d("array")})`);
|
|
1991
|
+
this.modelHandle("array", name);
|
|
1213
1992
|
this.indent();
|
|
1214
1993
|
this.write(".of(");
|
|
1215
1994
|
this.indent();
|
|
1216
|
-
this.renderPrimitiveDef(def.of);
|
|
1995
|
+
const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
|
|
1217
1996
|
this.writeln(`.$type`);
|
|
1218
1997
|
this.unindent();
|
|
1219
1998
|
this.writeln(`)`);
|
|
1220
1999
|
this.unindent();
|
|
2000
|
+
this.model?.run(() => this.model.current.of(child.$type));
|
|
1221
2001
|
return;
|
|
1222
|
-
|
|
2002
|
+
}
|
|
2003
|
+
case "object": {
|
|
1223
2004
|
this.writeln(`$(${d("object")})`);
|
|
2005
|
+
this.modelHandle("object", name);
|
|
1224
2006
|
this.indent();
|
|
1225
|
-
|
|
2007
|
+
const props = [...Object.entries(def.props).map(([k, p]) => [
|
|
2008
|
+
k,
|
|
2009
|
+
p,
|
|
2010
|
+
false
|
|
2011
|
+
]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
|
|
2012
|
+
k,
|
|
2013
|
+
p,
|
|
2014
|
+
true
|
|
2015
|
+
])];
|
|
2016
|
+
for (const [key, propDef, isPattern] of props) {
|
|
1226
2017
|
const optional = typeof propDef === "object" && propDef.optional;
|
|
1227
|
-
this.writeln(`.prop(`);
|
|
2018
|
+
this.writeln(isPattern ? `.propPattern(` : `.prop(`);
|
|
1228
2019
|
this.indent();
|
|
1229
|
-
this.writeln(`"${escapeQuotes(key)}",`);
|
|
1230
|
-
this.
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
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()");
|
|
2020
|
+
this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
|
|
2021
|
+
const child = this.modelChild(() => {
|
|
2022
|
+
this.renderPrimitiveDef(propDef);
|
|
2023
|
+
if (optional) {
|
|
2024
|
+
this.writeln(".optional()");
|
|
2025
|
+
this.model?.run(() => this.model.current.optional());
|
|
2026
|
+
}
|
|
2027
|
+
});
|
|
1243
2028
|
this.writeln(".$type");
|
|
1244
2029
|
this.unindent();
|
|
1245
2030
|
this.write(`)`);
|
|
2031
|
+
this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
|
|
1246
2032
|
}
|
|
1247
2033
|
this.unindent();
|
|
1248
2034
|
return;
|
|
1249
|
-
|
|
2035
|
+
}
|
|
2036
|
+
default: return final("any");
|
|
1250
2037
|
}
|
|
1251
2038
|
}
|
|
1252
2039
|
defineObject(node) {
|
|
@@ -1264,25 +2051,39 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1264
2051
|
this.indent();
|
|
1265
2052
|
this.writeln(`"${escapeQuotes(prop.id)}",`);
|
|
1266
2053
|
}
|
|
1267
|
-
this.
|
|
1268
|
-
|
|
2054
|
+
const child = this.modelChild(() => {
|
|
2055
|
+
this.annotateType(prop.getDefinition());
|
|
2056
|
+
this.indent().defineMetadata(prop).unindent();
|
|
2057
|
+
});
|
|
1269
2058
|
if (optional) this.writeln(" .optional()");
|
|
1270
2059
|
this.writeln(" .$type");
|
|
1271
2060
|
this.unindent();
|
|
1272
2061
|
this.write(`)`);
|
|
1273
2062
|
this._propPath.pop();
|
|
2063
|
+
this.model?.run(() => {
|
|
2064
|
+
if (optional) child.optional();
|
|
2065
|
+
if (pattern) this.model.current.propPattern(pattern, child.$type);
|
|
2066
|
+
else this.model.current.prop(prop.id, child.$type);
|
|
2067
|
+
});
|
|
1274
2068
|
}
|
|
1275
2069
|
this.writeln();
|
|
1276
2070
|
return this;
|
|
1277
2071
|
}
|
|
1278
2072
|
defineGroup(node) {
|
|
1279
|
-
const
|
|
1280
|
-
|
|
2073
|
+
for (const item of node.unwrap()) {
|
|
2074
|
+
this.write(".item(").indent();
|
|
2075
|
+
const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
|
|
2076
|
+
this.write(" .$type").writeln(`)`).unindent();
|
|
2077
|
+
this.model?.run(() => this.model.current.item(child.$type));
|
|
2078
|
+
}
|
|
1281
2079
|
return this;
|
|
1282
2080
|
}
|
|
1283
2081
|
defineArray(node) {
|
|
1284
2082
|
const of = node.getDefinition();
|
|
1285
|
-
this.write(".of(").indent()
|
|
2083
|
+
this.write(".of(").indent();
|
|
2084
|
+
const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
|
|
2085
|
+
this.write(" .$type").writeln(`)`).unindent();
|
|
2086
|
+
this.model?.run(() => this.model.current.of(child.$type));
|
|
1286
2087
|
return this;
|
|
1287
2088
|
}
|
|
1288
2089
|
/**
|
|
@@ -1353,9 +2154,10 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1353
2154
|
return this;
|
|
1354
2155
|
}
|
|
1355
2156
|
resolveAnnotationValue(node, an) {
|
|
1356
|
-
const { value, multiple } = this.computeAnnotationValue(node, an);
|
|
2157
|
+
const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
|
|
1357
2158
|
if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
|
|
1358
2159
|
else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
|
|
2160
|
+
this.model?.annotate(an.name, runtime, multiple);
|
|
1359
2161
|
}
|
|
1360
2162
|
emitRefValue(text, origin) {
|
|
1361
2163
|
const dotIdx = text.indexOf(".");
|
|
@@ -1434,33 +2236,50 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1434
2236
|
default: return token.text;
|
|
1435
2237
|
}
|
|
1436
2238
|
}
|
|
1437
|
-
|
|
2239
|
+
/**
|
|
2240
|
+
* The JS source of an annotation's value, and (for the validation model, which only reads
|
|
2241
|
+
* validator annotations: numbers, strings, flags) the runtime value it evaluates to;
|
|
2242
|
+
* other argument kinds are opaque there.
|
|
2243
|
+
*/ computeAnnotationValue(node, an) {
|
|
1438
2244
|
const origin = this.doc.annotationOrigin(an);
|
|
1439
2245
|
const spec = this.doc.resolveAnnotation(an.name);
|
|
1440
2246
|
let targetValue = "true";
|
|
2247
|
+
let runtime = true;
|
|
1441
2248
|
let multiple = false;
|
|
1442
2249
|
if (spec) {
|
|
1443
2250
|
multiple = spec.config.multiple;
|
|
1444
2251
|
const length = spec.arguments.length;
|
|
1445
|
-
if (length !== 0)
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
2252
|
+
if (length !== 0) {
|
|
2253
|
+
if (Array.isArray(spec.config.argument)) {
|
|
2254
|
+
targetValue = "{ ";
|
|
2255
|
+
const fields = {};
|
|
2256
|
+
let i = 0;
|
|
2257
|
+
for (const aSpec of spec.arguments) {
|
|
2258
|
+
if (an.args[i]) {
|
|
2259
|
+
targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
|
|
2260
|
+
fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
|
|
2261
|
+
}
|
|
2262
|
+
i++;
|
|
2263
|
+
}
|
|
2264
|
+
targetValue += "}";
|
|
2265
|
+
runtime = fields;
|
|
2266
|
+
} else if (an.args[0]) {
|
|
2267
|
+
const aSpec = spec.arguments[0];
|
|
2268
|
+
targetValue = this.emitArgValue(aSpec, an.args[0], origin);
|
|
2269
|
+
runtime = runtimeArg(aSpec.type, an.args[0]);
|
|
1451
2270
|
}
|
|
1452
|
-
targetValue += "}";
|
|
1453
|
-
} else {
|
|
1454
|
-
const aSpec = spec.arguments[0];
|
|
1455
|
-
targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
|
|
1456
2271
|
}
|
|
1457
2272
|
} else {
|
|
1458
2273
|
multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
|
|
1459
|
-
if (an.args.length > 0)
|
|
2274
|
+
if (an.args.length > 0) {
|
|
2275
|
+
targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
|
|
2276
|
+
runtime = runtimeArg(void 0, an.args[0]);
|
|
2277
|
+
}
|
|
1460
2278
|
}
|
|
1461
2279
|
return {
|
|
1462
2280
|
value: targetValue,
|
|
1463
|
-
multiple: !!multiple
|
|
2281
|
+
multiple: !!multiple,
|
|
2282
|
+
runtime
|
|
1464
2283
|
};
|
|
1465
2284
|
}
|
|
1466
2285
|
renderMutatingAnnotateNode(node) {
|
|
@@ -1473,7 +2292,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1473
2292
|
const anns = entry.annotations;
|
|
1474
2293
|
if (!anns || anns.length === 0) continue;
|
|
1475
2294
|
const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
|
|
1476
|
-
const { accessors, clones } = this.buildMutatingAccessors(
|
|
2295
|
+
const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
|
|
1477
2296
|
allClones.push(...clones);
|
|
1478
2297
|
entryAccessors.push({
|
|
1479
2298
|
entry,
|
|
@@ -1482,29 +2301,36 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1482
2301
|
}
|
|
1483
2302
|
const cloneKeys = /* @__PURE__ */ new Set();
|
|
1484
2303
|
for (const clone of allClones) {
|
|
1485
|
-
const
|
|
2304
|
+
const parentPath = accessorPath(targetName, clone.parentSteps);
|
|
2305
|
+
const key = `${parentPath}|${clone.propName}`;
|
|
1486
2306
|
if (!cloneKeys.has(key)) {
|
|
1487
2307
|
cloneKeys.add(key);
|
|
1488
|
-
this.writeln(`$c(${
|
|
2308
|
+
this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
|
|
2309
|
+
this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
|
|
1489
2310
|
}
|
|
1490
2311
|
}
|
|
1491
|
-
for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor);
|
|
2312
|
+
for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
|
|
1492
2313
|
const topAnnotations = node.annotations;
|
|
1493
|
-
if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, targetName);
|
|
2314
|
+
if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
|
|
1494
2315
|
this.writeln();
|
|
1495
2316
|
}
|
|
1496
|
-
emitMutatingAnnotations(node, annotations,
|
|
2317
|
+
emitMutatingAnnotations(node, annotations, steps, targetName) {
|
|
2318
|
+
const accessor = accessorPath(targetName, steps);
|
|
1497
2319
|
const cleared = /* @__PURE__ */ new Set();
|
|
1498
2320
|
for (const an of annotations) {
|
|
1499
|
-
const { value, multiple } = this.computeAnnotationValue(node, an);
|
|
2321
|
+
const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
|
|
1500
2322
|
if (multiple) {
|
|
1501
2323
|
if (!cleared.has(an.name)) {
|
|
1502
2324
|
const spec = this.doc.resolveAnnotation(an.name);
|
|
1503
|
-
if (!spec || spec.config.mergeStrategy !== "append")
|
|
2325
|
+
if (!spec || spec.config.mergeStrategy !== "append") {
|
|
2326
|
+
this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
|
|
2327
|
+
this.model?.deleteAnnotation(targetName, steps, an.name);
|
|
2328
|
+
}
|
|
1504
2329
|
cleared.add(an.name);
|
|
1505
2330
|
}
|
|
1506
2331
|
this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
|
|
1507
2332
|
} else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
|
|
2333
|
+
this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
|
|
1508
2334
|
}
|
|
1509
2335
|
}
|
|
1510
2336
|
resolveTargetDef(targetName) {
|
|
@@ -1515,51 +2341,48 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1515
2341
|
return def;
|
|
1516
2342
|
}
|
|
1517
2343
|
/**
|
|
1518
|
-
* Builds the
|
|
2344
|
+
* Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
|
|
1519
2345
|
* Computes exact paths at compile time by walking the AST,
|
|
1520
2346
|
* so the generated JS accesses props directly without runtime search.
|
|
1521
2347
|
* Returns multiple paths when a property appears in multiple union branches.
|
|
1522
|
-
*/ buildMutatingAccessors(
|
|
2348
|
+
*/ buildMutatingAccessors(targetDef, parts) {
|
|
1523
2349
|
let accessors = [{
|
|
1524
|
-
|
|
2350
|
+
steps: ["type"],
|
|
1525
2351
|
def: targetDef
|
|
1526
2352
|
}];
|
|
1527
2353
|
const clones = [];
|
|
1528
2354
|
for (let i = 0; i < parts.length; i++) {
|
|
2355
|
+
const last = i === parts.length - 1;
|
|
1529
2356
|
const nextAccessors = [];
|
|
1530
|
-
for (const {
|
|
2357
|
+
for (const { steps, def } of accessors) {
|
|
1531
2358
|
const results = this.buildPropPaths(def, parts[i]);
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
2359
|
+
const found = results.length > 0 ? results : [{
|
|
2360
|
+
steps: [["props", parts[i]]],
|
|
2361
|
+
propDef: void 0
|
|
2362
|
+
}];
|
|
2363
|
+
for (const result of found) {
|
|
2364
|
+
if (!last && result.propDef && isRef(result.propDef)) clones.push({
|
|
2365
|
+
parentSteps: steps,
|
|
1535
2366
|
propName: parts[i]
|
|
1536
2367
|
});
|
|
2368
|
+
const next = [...steps, ...result.steps];
|
|
2369
|
+
if (!last) next.push("type");
|
|
1537
2370
|
nextAccessors.push({
|
|
1538
|
-
|
|
2371
|
+
steps: next,
|
|
1539
2372
|
def: result.propDef
|
|
1540
2373
|
});
|
|
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
2374
|
}
|
|
1552
2375
|
}
|
|
1553
2376
|
accessors = nextAccessors;
|
|
1554
2377
|
}
|
|
1555
2378
|
return {
|
|
1556
|
-
accessors: accessors.map((a) => a.
|
|
2379
|
+
accessors: accessors.map((a) => a.steps),
|
|
1557
2380
|
clones
|
|
1558
2381
|
};
|
|
1559
2382
|
}
|
|
1560
2383
|
/**
|
|
1561
2384
|
* Finds a property in a type tree at compile time, returning all
|
|
1562
|
-
* matching
|
|
2385
|
+
* matching accessor steps and prop definitions for further chaining.
|
|
1563
2386
|
* Returns multiple results when the same property appears in different union branches.
|
|
1564
2387
|
*/ buildPropPaths(def, propName) {
|
|
1565
2388
|
if (!def) return [];
|
|
@@ -1573,7 +2396,7 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1573
2396
|
if (isStructure(def)) {
|
|
1574
2397
|
const prop = def.props.get(propName);
|
|
1575
2398
|
if (prop) return [{
|
|
1576
|
-
|
|
2399
|
+
steps: [["props", propName]],
|
|
1577
2400
|
propDef: prop.getDefinition()
|
|
1578
2401
|
}];
|
|
1579
2402
|
return [];
|
|
@@ -1582,7 +2405,11 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1582
2405
|
const items = def.unwrap();
|
|
1583
2406
|
const results = [];
|
|
1584
2407
|
for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
|
|
1585
|
-
|
|
2408
|
+
steps: [
|
|
2409
|
+
["items", i],
|
|
2410
|
+
"type",
|
|
2411
|
+
...result.steps
|
|
2412
|
+
],
|
|
1586
2413
|
propDef: result.propDef
|
|
1587
2414
|
});
|
|
1588
2415
|
return results;
|
|
@@ -1590,13 +2417,19 @@ var JsRenderer = class extends BaseRenderer {
|
|
|
1590
2417
|
return [];
|
|
1591
2418
|
}
|
|
1592
2419
|
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();
|
|
2420
|
+
super(doc), _define_property(this, "opts", void 0), _define_property(this, "postAnnotate", void 0), _define_property(this, "_adHocAnnotations", void 0), _define_property(this, "_propPath", void 0), _define_property(this, "typeIds", void 0), _define_property(this, "_unusedJs", void 0), _define_property(this, "_extendsRefs", void 0), _define_property(this, "_refSynthInfo", void 0), _define_property(this, "_synthImports", void 0), _define_property(this, "_synthComputed", void 0), _define_property(this, "_synthTaken", void 0), _define_property(this, "_synthAllocated", void 0), _define_property(this, "_synthPathCache", void 0), _define_property(this, "_ownerCache", void 0), _define_property(this, "model", void 0), _define_property(this, "modelClasses", void 0), _define_property(this, "_declTypes", void 0), this.opts = opts, this.postAnnotate = [], this._adHocAnnotations = null, this._propPath = [], this.typeIds = /* @__PURE__ */ new Map(), this._refSynthInfo = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthComputed = false, this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map(), this.modelClasses = [], this._declTypes = /* @__PURE__ */ new Map();
|
|
2421
|
+
if (opts?.compileValidators) this.model = new ValidationModel();
|
|
1594
2422
|
}
|
|
1595
2423
|
};
|
|
1596
2424
|
|
|
1597
2425
|
//#endregion
|
|
1598
2426
|
//#region packages/typescript/src/plugin.ts
|
|
1599
2427
|
/**
|
|
2428
|
+
* Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
|
|
2429
|
+
* (used by `unplugin-atscript`'s `compileValidators` option).
|
|
2430
|
+
*/ const JS_COMPILED_FORMAT = "js:compiled";
|
|
2431
|
+
const JS_INTERPRETED_FORMAT = "js:interpreted";
|
|
2432
|
+
/**
|
|
1600
2433
|
* Resolves the effective JSON schema mode from plugin options.
|
|
1601
2434
|
*/ function resolveJsonSchemaMode(opts) {
|
|
1602
2435
|
if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
|
|
@@ -1610,10 +2443,16 @@ const tsPlugin = (opts) => {
|
|
|
1610
2443
|
fileName: `${doc.name}.d.ts`,
|
|
1611
2444
|
content: new TypeRenderer(doc, opts).render()
|
|
1612
2445
|
}];
|
|
1613
|
-
if (format === "js")
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
2446
|
+
if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
|
|
2447
|
+
const jsOpts = format === "js" ? opts : {
|
|
2448
|
+
...opts,
|
|
2449
|
+
compileValidators: format === JS_COMPILED_FORMAT
|
|
2450
|
+
};
|
|
2451
|
+
return [{
|
|
2452
|
+
fileName: `${doc.name}.js`,
|
|
2453
|
+
content: new JsRenderer(doc, jsOpts).render()
|
|
2454
|
+
}];
|
|
2455
|
+
}
|
|
1617
2456
|
},
|
|
1618
2457
|
async buildEnd(output, format, repo) {
|
|
1619
2458
|
if (format === "dts" || format === DEFAULT_FORMAT) {
|
|
@@ -1641,4 +2480,4 @@ const tsPlugin = (opts) => {
|
|
|
1641
2480
|
};
|
|
1642
2481
|
|
|
1643
2482
|
//#endregion
|
|
1644
|
-
export { tsPlugin as t };
|
|
2483
|
+
export { JS_INTERPRETED_FORMAT as n, tsPlugin as r, JS_COMPILED_FORMAT as t };
|