@atscript/typescript 0.2.9 → 0.2.10

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/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_user_text = require('./user-text-C9ov-aSv.cjs');
2
+ const require_user_text = require('./user-text-BrP_qD3T.cjs');
3
3
 
4
4
  //#region packages/typescript/src/runtime/copy-on-change.ts
5
5
  /**
@@ -772,6 +772,338 @@ function collectLeaves(items, out) {
772
772
  return result === NO_MATCH ? input : result;
773
773
  }
774
774
 
775
+ //#endregion
776
+ //#region packages/typescript/src/runtime/json-schema-strict.ts
777
+ /** The keywords every provider takes: the shape of the schema, its notes and literals. */ const BASE_KEYWORDS = {
778
+ type: true,
779
+ properties: true,
780
+ required: true,
781
+ additionalProperties: true,
782
+ items: true,
783
+ anyOf: true,
784
+ $ref: true,
785
+ $defs: true,
786
+ enum: true,
787
+ const: true,
788
+ title: true,
789
+ description: true
790
+ };
791
+ /** The string formats both providers list. */ const FORMATS = new Set([
792
+ "date-time",
793
+ "time",
794
+ "date",
795
+ "duration",
796
+ "email",
797
+ "hostname",
798
+ "ipv4",
799
+ "ipv6",
800
+ "uuid"
801
+ ]);
802
+ /**
803
+ * OpenAI Structured Outputs / `strict: true` function calling: every property required
804
+ * (optional ones nullable), objects closed, an object root, no `allOf`; patterns without
805
+ * lookaround, backreferences or modifier groups, numeric bounds and `minItems` / `maxItems`
806
+ * kept; string lengths, `uniqueItems` and key counts dropped. Recursion is allowed.
807
+ */ const OPENAI_STRICT = {
808
+ name: "openai",
809
+ keywords: {
810
+ ...BASE_KEYWORDS,
811
+ pattern: (value) => decodablePattern(value),
812
+ format: (value) => FORMATS.has(value),
813
+ minimum: true,
814
+ maximum: true,
815
+ exclusiveMinimum: true,
816
+ exclusiveMaximum: true,
817
+ multipleOf: true,
818
+ minItems: true,
819
+ maxItems: true
820
+ },
821
+ requireAll: true,
822
+ collapseAllOf: true,
823
+ describeDropped: true,
824
+ allowRecursion: true,
825
+ objectRoot: true
826
+ };
827
+ /**
828
+ * Anthropic strict tool use / structured outputs: objects closed, an object root (a tool's
829
+ * `input_schema`), no recursion; simple patterns kept (no lookaround, backreferences, word
830
+ * boundaries or large `{n,m}`), `minItems` only `0` / `1`; numeric bounds, string lengths,
831
+ * `maxItems`, `uniqueItems` and key counts dropped. `allOf` is allowed
832
+ * except with a `$ref` (collapsed). Optional properties stay optional.
833
+ */ const ANTHROPIC_STRICT = {
834
+ name: "anthropic",
835
+ keywords: {
836
+ ...BASE_KEYWORDS,
837
+ allOf: true,
838
+ pattern: (value) => simplePattern(value),
839
+ format: (value) => FORMATS.has(value) || value === "uri",
840
+ minItems: (value) => value === 0 || value === 1
841
+ },
842
+ requireAll: false,
843
+ collapseAllOf: true,
844
+ describeDropped: true,
845
+ allowRecursion: false,
846
+ objectRoot: true
847
+ };
848
+ /** The largest `{n,m}` bound a simple pattern has (see {@link simplePattern}). */ const SIMPLE_BOUND = 100;
849
+ /**
850
+ * A pattern without lookaround, backreferences, word boundaries, Unicode property escapes,
851
+ * modifier groups or `{n,m}` bounds above {@link SIMPLE_BOUND} (Anthropic's simple patterns).
852
+ * Named groups are fine; `\b` in a class is a backspace.
853
+ */ function simplePattern(pattern) {
854
+ return scanPattern(pattern, true);
855
+ }
856
+ /** A pattern without lookaround, backreferences or modifier groups (OpenAI). */ function decodablePattern(pattern) {
857
+ return scanPattern(pattern, false);
858
+ }
859
+ /** {@link simplePattern} (`simple`), else {@link decodablePattern}. */ function scanPattern(pattern, simple) {
860
+ let inClass = false;
861
+ for (let i = 0; i < pattern.length; i++) {
862
+ const c = pattern[i];
863
+ if (c === "\\") {
864
+ const next = pattern[++i];
865
+ if (next === void 0 || /[1-9k]/.test(next)) return false;
866
+ if (simple && (/[pPB]/.test(next) || next === "b" && !inClass)) return false;
867
+ } else if (inClass) inClass = c !== "]";
868
+ else if (c === "[") inClass = true;
869
+ else if (c === "(" && pattern[i + 1] === "?") {
870
+ const kind = pattern[i + 2];
871
+ const named = kind === "<" && pattern[i + 3] !== "=" && pattern[i + 3] !== "!";
872
+ if (kind !== ":" && !named) return false;
873
+ } else if (simple && c === "{") {
874
+ const bounds = /^\{(\d+)(?:,(\d*))?\}/.exec(pattern.slice(i));
875
+ if (bounds && (Number(bounds[1]) > SIMPLE_BOUND || Number(bounds[2] || 0) > SIMPLE_BOUND)) return false;
876
+ }
877
+ }
878
+ return true;
879
+ }
880
+ /** The `$defs` name a `$ref` this builder writes points to. */ function refName(ref) {
881
+ return ref.slice(8);
882
+ }
883
+ /** The `$defs` names `schema` refers to (through any keyword but `$defs`). */ function refsOf(schema, out = /* @__PURE__ */ new Set()) {
884
+ if (Array.isArray(schema)) for (const item of schema) refsOf(item, out);
885
+ else if (schema && typeof schema === "object") {
886
+ for (const [key, value] of Object.entries(schema)) if (key === "$ref" && typeof value === "string") out.add(refName(value));
887
+ else if (key !== "$defs") refsOf(value, out);
888
+ }
889
+ return out;
890
+ }
891
+ /** The refs of each `$defs` entry, by name. */ function edgesOf(defs) {
892
+ return new Map(Object.entries(defs).map(([name, def]) => [name, refsOf(def)]));
893
+ }
894
+ /** The `$defs` names reachable from `from` through `edges`. */ function reachable(from, edges) {
895
+ const seen = /* @__PURE__ */ new Set();
896
+ const stack = [...from];
897
+ for (let name = stack.pop(); name !== void 0; name = stack.pop()) if (!seen.has(name)) {
898
+ seen.add(name);
899
+ stack.push(...edges.get(name) ?? []);
900
+ }
901
+ return seen;
902
+ }
903
+ /** The first `$defs` entry that refers to itself, through any others; `undefined`: none. */ function recursiveDef(defs) {
904
+ const edges = edgesOf(defs);
905
+ return [...edges.keys()].find((name) => reachable(edges.get(name), edges).has(name));
906
+ }
907
+ /** `n` `one`(s): `1 item`, `2 items`. */ function count(n, one, many = `${one}s`) {
908
+ return `${n} ${n === 1 ? one : many}`;
909
+ }
910
+ /** A dropped keyword in plain words (`pattern` `\S`: the `@meta.required` check). */ function describe(keyword, value) {
911
+ switch (keyword) {
912
+ case "minLength": return `At least ${count(value, "character")}.`;
913
+ case "maxLength": return `At most ${count(value, "character")}.`;
914
+ case "pattern": return value === "\\S" ? "Must not be blank." : `Must match the pattern ${JSON.stringify(value)}.`;
915
+ case "format": return `Format: ${value}.`;
916
+ case "minimum": return `Minimum ${value}.`;
917
+ case "maximum": return `Maximum ${value}.`;
918
+ case "exclusiveMinimum": return `Greater than ${value}.`;
919
+ case "exclusiveMaximum": return `Less than ${value}.`;
920
+ case "multipleOf": return `A multiple of ${value}.`;
921
+ case "minItems": return `At least ${count(value, "item")}.`;
922
+ case "maxItems": return `At most ${count(value, "item")}.`;
923
+ case "uniqueItems": return value ? "Items must be unique." : "";
924
+ case "minProperties": return `At least ${count(value, "property", "properties")}.`;
925
+ case "maxProperties": return `At most ${count(value, "property", "properties")}.`;
926
+ default: return `${keyword}: ${JSON.stringify(value)}.`;
927
+ }
928
+ }
929
+ /** A schema `type` of objects (`'object'`, or a type list with it: an optional object). */ function isObjectType(type) {
930
+ return type === "object" || Array.isArray(type) && type.includes("object");
931
+ }
932
+ /** Whether `schema` accepts `null` as it is (a `null` type, value or `anyOf` member). */ function acceptsNull$1(schema) {
933
+ if ("const" in schema) return schema.const === null;
934
+ if (Array.isArray(schema.enum)) return schema.enum.includes(null);
935
+ if (schema.type !== void 0) return schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null");
936
+ return Array.isArray(schema.anyOf) && schema.anyOf.some(acceptsNull$1);
937
+ }
938
+ /**
939
+ * `schema` also accepting `null`: `type: [t, 'null']` for a plain typed schema, else an `anyOf`
940
+ * with a `null` member (the title / description stay beside it).
941
+ */ function orNull(schema) {
942
+ if (acceptsNull$1(schema)) return schema;
943
+ if (schema.type !== void 0 && !("const" in schema) && schema.enum === void 0) return {
944
+ ...schema,
945
+ type: [schema.type, "null"].flat()
946
+ };
947
+ const { title, description, ...body } = schema;
948
+ const notes = {};
949
+ if (title !== void 0) notes.title = title;
950
+ if (description !== void 0) notes.description = description;
951
+ return {
952
+ anyOf: [...Object.keys(body).length === 1 && Array.isArray(body.anyOf) ? body.anyOf : [body], { type: "null" }],
953
+ ...notes
954
+ };
955
+ }
956
+ /**
957
+ * Object schema `out` with every property required (`requireAll`): those not in `required`
958
+ * (optional) made nullable.
959
+ */ function requireAll(out, required) {
960
+ const properties = out.properties ?? {};
961
+ const keys = Object.keys(properties);
962
+ const requiredKeys = new Set(required);
963
+ for (const key of keys) if (!requiredKeys.has(key)) properties[key] = orNull(properties[key]);
964
+ if (keys.length > 0) out.required = keys;
965
+ else delete out.required;
966
+ }
967
+ /** Whether `schema` carries the `@meta.required` check of a string (the pattern `\S`). */ function hasBlankCheck(schema) {
968
+ return schema.pattern === "\\S" || Array.isArray(schema.allOf) && schema.allOf.some((item) => item.pattern === "\\S");
969
+ }
970
+ /**
971
+ * `out` with the `dropped` keywords described in its `description` (`blank`: it has the
972
+ * `@meta.required` check, kept or described, which says what its `minLength: 1` would). A lone
973
+ * `$ref` takes no keywords beside it: it moves into an `anyOf` of its own.
974
+ */ function described(out, dropped, blank) {
975
+ const notes = dropped.filter(([key, value]) => !(blank && key === "minLength" && value === 1)).map(([key, value]) => describe(key, value)).filter(Boolean).join(" ");
976
+ if (!notes) return out;
977
+ let schema = out;
978
+ if (schema.$ref !== void 0) {
979
+ const { $ref, ...rest } = schema;
980
+ schema = {
981
+ anyOf: [{ $ref }],
982
+ ...rest
983
+ };
984
+ }
985
+ schema.description = schema.description ? `${schema.description}\n\n${notes}` : notes;
986
+ return schema;
987
+ }
988
+ /**
989
+ * `schema` (built closed by {@link buildJsonSchema}) rewritten to `profile` (see
990
+ * {@link TStrictProfile}). Throws for a shape the profile can't take.
991
+ */ function strictSchema(schema, profile) {
992
+ const fail = (what) => {
993
+ throw new Error(`buildJsonSchema (strict: ${profile.name}): ${what}`);
994
+ };
995
+ const defs = schema.$defs ?? {};
996
+ if (!profile.allowRecursion) {
997
+ const recursive = recursiveDef(defs);
998
+ if (recursive !== void 0) fail(`recursive type "${recursive}" is not supported`);
999
+ }
1000
+ if (profile.objectRoot && schema.type !== "object") fail("the root must be an object type");
1001
+ const allowed = (keyword, value) => {
1002
+ const rule = profile.keywords[keyword];
1003
+ return rule === true || rule !== void 0 && rule(value);
1004
+ };
1005
+ /** `$defs` entries being inlined (a use of an entry inside itself stays a reference). */ const inlining = /* @__PURE__ */ new Set();
1006
+ /**
1007
+ * `s` rewritten; the constraints it drops are described on it. `part`: a subschema of an
1008
+ * `allOf` (a constraint of the schema it sits in, no type of its own).
1009
+ */ const rewrite = (s, at, part = false) => {
1010
+ /** The dropped keywords and their values (described at the end). */ const dropped = [];
1011
+ /** The `$defs` entries inlined here (see `collapse`). */ const entered = [];
1012
+ let source = profile.collapseAllOf ? collapse(s, dropped, entered) : s;
1013
+ if (source.oneOf && !profile.keywords.oneOf) {
1014
+ const { oneOf, discriminator: _, ...rest } = source;
1015
+ source = {
1016
+ ...rest,
1017
+ anyOf: oneOf
1018
+ };
1019
+ }
1020
+ const where = at || "the root";
1021
+ if (Array.isArray(source.items)) fail(`a tuple (at ${where}) has no strict schema`);
1022
+ if (source.patternProperties !== void 0) fail(`a record (at ${where}) has no strict schema; use an array of key/value objects`);
1023
+ if (!part && source.type === void 0 && source.anyOf === void 0 && source.allOf === void 0 && source.$ref === void 0 && source.not === void 0 && !("const" in source) && source.enum === void 0) fail(`a value of any type (at ${where}) has no strict schema`);
1024
+ const out = {};
1025
+ for (const [key, value] of Object.entries(source)) {
1026
+ if (key === "discriminator" && !profile.keywords.discriminator) continue;
1027
+ if (!allowed(key, value)) {
1028
+ if (key === "allOf" || key === "not") fail(`${key === "allOf" ? "an intersection" : "an impossible type"} (at ${where}) has no strict schema`);
1029
+ dropped.push([key, value]);
1030
+ continue;
1031
+ }
1032
+ out[key] = rewriteValue(key, value, at);
1033
+ }
1034
+ for (const name of entered) inlining.delete(name);
1035
+ if (isObjectType(out.type)) {
1036
+ out.additionalProperties = false;
1037
+ if (profile.requireAll) requireAll(out, source.required);
1038
+ }
1039
+ return profile.describeDropped && dropped.length > 0 ? described(out, dropped, hasBlankCheck(s) || hasBlankCheck(source)) : out;
1040
+ };
1041
+ /** The value of keyword `key` rewritten (its subschemas). */ const rewriteValue = (key, value, at) => {
1042
+ switch (key) {
1043
+ case "properties": return Object.fromEntries(Object.entries(value).map(([name, p]) => [name, rewrite(p, at ? `${at}.${name}` : name)]));
1044
+ case "items": return rewrite(value, `${at}[]`);
1045
+ case "anyOf": return value.map((item) => rewrite(item, at));
1046
+ case "allOf": return value.map((item) => rewrite(item, at, true));
1047
+ case "$defs": return Object.fromEntries(Object.entries(value).map(([name, d]) => {
1048
+ inlining.add(name);
1049
+ const entry = rewrite(d, `$defs.${name}`);
1050
+ inlining.delete(name);
1051
+ return [name, entry];
1052
+ }));
1053
+ default: return value;
1054
+ }
1055
+ };
1056
+ /**
1057
+ * `s` with its `allOf` collapsed (see `collapseAllOf`): what it drops in `dropped`, the
1058
+ * `$defs` entries it inlines in `entered` (and `inlining`, until `s` is rewritten).
1059
+ */ const collapse = (s, dropped, entered) => {
1060
+ if (!Array.isArray(s.allOf)) return s;
1061
+ const { allOf, ...rest } = s;
1062
+ const ref = allOf.length === 1 && Object.keys(allOf[0]).length === 1 ? allOf[0].$ref : void 0;
1063
+ if (typeof ref === "string") {
1064
+ const name = refName(ref);
1065
+ const target = defs[name];
1066
+ if (target === void 0 || inlining.has(name)) return {
1067
+ anyOf: [{ $ref: ref }],
1068
+ ...rest
1069
+ };
1070
+ inlining.add(name);
1071
+ entered.push(name);
1072
+ return collapse({
1073
+ ...target,
1074
+ ...rest
1075
+ }, dropped, entered);
1076
+ }
1077
+ if (!allOf.every((item) => Object.keys(item).length === 1 && "pattern" in item)) return s;
1078
+ if (profile.keywords.allOf) {
1079
+ const kept = allOf.filter((item) => {
1080
+ if (allowed("pattern", item.pattern)) return true;
1081
+ dropped.push(["pattern", item.pattern]);
1082
+ return false;
1083
+ });
1084
+ if (kept.length > 1 || kept.length === 1 && rest.pattern !== void 0) return {
1085
+ ...rest,
1086
+ allOf: kept
1087
+ };
1088
+ return kept.length === 1 ? {
1089
+ ...rest,
1090
+ pattern: kept[0].pattern
1091
+ } : rest;
1092
+ }
1093
+ const out = { ...rest };
1094
+ for (const { pattern } of allOf) if (out.pattern === void 0 && allowed("pattern", pattern)) out.pattern = pattern;
1095
+ else dropped.push(["pattern", pattern]);
1096
+ return out;
1097
+ };
1098
+ const out = rewrite(schema, "");
1099
+ if (out.$defs) {
1100
+ const used = reachable(refsOf(out), edgesOf(out.$defs));
1101
+ for (const name of Object.keys(out.$defs)) if (!used.has(name)) delete out.$defs[name];
1102
+ if (Object.keys(out.$defs).length === 0) delete out.$defs;
1103
+ }
1104
+ return out;
1105
+ }
1106
+
775
1107
  //#endregion
776
1108
  //#region packages/typescript/src/runtime/traverse.ts
777
1109
  /**
@@ -840,6 +1172,11 @@ function collectLeaves(items, out) {
840
1172
  * @param opts - {@link TJsonSchemaOptions}.
841
1173
  * @returns A JSON Schema object.
842
1174
  */ function buildJsonSchema(type, opts) {
1175
+ if (opts?.strict) return strictSchema(buildJsonSchema(type, {
1176
+ ...opts,
1177
+ strict: void 0,
1178
+ closed: true
1179
+ }), opts.strict);
843
1180
  const closed = opts?.closed === true;
844
1181
  const annotations = opts?.annotations !== false;
845
1182
  const enums = opts?.enums !== false;
@@ -1689,6 +2026,91 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1689
2026
  return out;
1690
2027
  }
1691
2028
 
2029
+ //#endregion
2030
+ //#region packages/typescript/src/runtime/drop-optional-nulls.ts
2031
+ /**
2032
+ * What `value` looks like without the `null` values the model sends for fields it leaves out under
2033
+ * a `requireAll` profile (`OPENAI_STRICT`), before it goes to the validator. The validator
2034
+ * takes a missing optional field, but not `null` on an optional `@meta.required` one.
2035
+ *
2036
+ * A `null` is dropped only from an optional field whose type does not accept `null`: for
2037
+ * `x?: string | null` it stays (`null` and a missing field mean different things, e.g. "clear"
2038
+ * and "keep" in a patch). In a union, the branch its discriminator picks applies; else every
2039
+ * branch does, and a key is dropped only when every branch (and, in an intersection, every part)
2040
+ * that declares it has it optional and not accepting `null`: one that needs the `null` keeps it.
2041
+ *
2042
+ * Copy-on-change: `value` is never mutated (a frozen one works); the same reference comes back
2043
+ * when nothing is dropped, else a copy with the changed objects and arrays rebuilt.
2044
+ */ function dropOptionalNulls(type, value) {
2045
+ return dropNulls([type], value);
2046
+ }
2047
+ /** The discriminator of a union, found once per union type. */ const discriminators = /* @__PURE__ */ new WeakMap();
2048
+ function discriminatorOf(union) {
2049
+ let disc = discriminators.get(union);
2050
+ if (disc === void 0) {
2051
+ disc = require_user_text.detectDiscriminator(union.items);
2052
+ discriminators.set(union, disc);
2053
+ }
2054
+ return disc;
2055
+ }
2056
+ /**
2057
+ * The defs `value` is checked against, unions and intersections expanded: the branch a
2058
+ * discriminator picks, else every branch.
2059
+ */ function expand(defs, value, out) {
2060
+ for (const def of defs) {
2061
+ const type = def.type;
2062
+ if (type.kind === "union" || type.kind === "intersection") {
2063
+ const union = type;
2064
+ const isObject = value !== null && typeof value === "object" && !Array.isArray(value);
2065
+ const disc = type.kind === "union" && isObject ? discriminatorOf(union) : null;
2066
+ const picked = disc ? disc.indexMapping[String(value[disc.propertyName])] : void 0;
2067
+ expand(picked === void 0 ? union.items : [union.items[picked]], value, out);
2068
+ } else out.push(def);
2069
+ }
2070
+ }
2071
+ /** {@link dropOptionalNulls} of `value` as every one of `defs` (alternatives or parts). */ function dropNulls(defs, value) {
2072
+ if (value === null || typeof value !== "object") return value;
2073
+ const leaves = [];
2074
+ expand(defs, value, leaves);
2075
+ if (Array.isArray(value)) return dropNullsOfArray(leaves, value);
2076
+ let out;
2077
+ for (const key of Object.keys(value)) {
2078
+ const current = value[key];
2079
+ if (current !== null && typeof current !== "object") continue;
2080
+ const declared = [];
2081
+ for (const leaf of leaves) {
2082
+ const prop = leaf.type.kind === "object" ? leaf.type.props.get(key) : void 0;
2083
+ if (prop !== void 0 && !require_user_text.isPhantomType(prop)) declared.push(prop);
2084
+ }
2085
+ if (declared.length === 0) continue;
2086
+ if (current === null) {
2087
+ if (declared.every((prop) => prop.optional && !require_user_text.acceptsNull(prop))) {
2088
+ out ?? (out = { ...value });
2089
+ delete out[key];
2090
+ }
2091
+ continue;
2092
+ }
2093
+ const next = dropNulls(declared, current);
2094
+ if (next !== current) {
2095
+ out ?? (out = { ...value });
2096
+ out[key] = next;
2097
+ }
2098
+ }
2099
+ return out ?? value;
2100
+ }
2101
+ /** {@link dropNulls} of an array `value`: the items of every array and tuple among `leaves`. */ function dropNullsOfArray(leaves, value) {
2102
+ return mapList(value, (item, i) => {
2103
+ if (item === null || typeof item !== "object") return item;
2104
+ const declared = [];
2105
+ for (const leaf of leaves) {
2106
+ const type = leaf.type;
2107
+ if (type.kind === "array") declared.push(type.of);
2108
+ else if (type.kind === "tuple" && i < type.items.length) declared.push(type.items[i]);
2109
+ }
2110
+ return dropNulls(declared, item);
2111
+ });
2112
+ }
2113
+
1692
2114
  //#endregion
1693
2115
  //#region packages/typescript/src/runtime/default-value.ts
1694
2116
  /**
@@ -2636,6 +3058,26 @@ function* deserializeTypeDef(t, resolved) {
2636
3058
  texts
2637
3059
  };
2638
3060
  }
3061
+ /**
3062
+ * Translates the value of one metadata key (live, as a compiled type holds it — not serialized)
3063
+ * with `t`, by the rules {@link translateServed} applies to serialized metadata, so a client
3064
+ * translating compiled types reads one catalogue with the server: a text key's string (each item
3065
+ * of a `multiple` list; the named fields of a value object, e.g. `message` of `meta.required`) is
3066
+ * replaced by `t(text)` — except a primitive's built-in format message, which is reported by its
3067
+ * code. Returns `value` itself when the key holds no user text or nothing is translated; it is
3068
+ * never changed.
3069
+ *
3070
+ * Expressions are left as they are: their string literals are translated in a served type's
3071
+ * `texts`, and a client translates what an expression returns (by exact match), not its source.
3072
+ *
3073
+ * @example
3074
+ * ```ts
3075
+ * const label = translateUserText('meta.label', 'Street', text => dict[text]) // dict['Street']
3076
+ * ```
3077
+ */ function translateUserText(key, value, t) {
3078
+ const mode = require_user_text.userTextOf(key);
3079
+ return mode === void 0 ? value : walk(value, mode, { t });
3080
+ }
2639
3081
  /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2640
3082
  if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2641
3083
  if (typeof value === "string") {
@@ -2644,6 +3086,7 @@ function* deserializeTypeDef(t, resolved) {
2644
3086
  return value;
2645
3087
  }
2646
3088
  if (typeof value !== "object" || value === null) return value;
3089
+ if (ctx.texts === void 0 && typeof mode !== "object") return value;
2647
3090
  return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2648
3091
  }
2649
3092
  /**
@@ -2658,10 +3101,12 @@ function* deserializeTypeDef(t, resolved) {
2658
3101
  const out = ctx.t(text);
2659
3102
  return typeof out === "string" ? out : void 0;
2660
3103
  }
2661
- /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2662
- for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
3104
+ /** Adds the translated string literals of expression `source` to `ctx.texts` (a served type only). */ function collectLiterals(source, ctx) {
3105
+ const { texts } = ctx;
3106
+ if (!texts) return;
3107
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(texts, literal)) {
2663
3108
  const translated = translate(literal, ctx);
2664
- if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
3109
+ if (translated !== void 0 && translated !== literal) texts[literal] = translated;
2665
3110
  }
2666
3111
  }
2667
3112
  /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
@@ -2829,7 +3274,9 @@ exports.$ps = require_user_text.$ps;
2829
3274
  exports.$q = require_user_text.$q;
2830
3275
  exports.$sh = require_user_text.$sh;
2831
3276
  exports.$ut = require_user_text.$ut;
3277
+ exports.ANTHROPIC_STRICT = ANTHROPIC_STRICT;
2832
3278
  exports.LayerMap = require_user_text.LayerMap;
3279
+ exports.OPENAI_STRICT = OPENAI_STRICT;
2833
3280
  exports.SERIALIZE_VERSION = SERIALIZE_VERSION;
2834
3281
  exports.VALIDATOR_ERROR_CODES = require_user_text.VALIDATOR_ERROR_CODES;
2835
3282
  exports.VALIDATOR_MESSAGES = require_user_text.VALIDATOR_MESSAGES;
@@ -2846,6 +3293,7 @@ exports.createDataFromAnnotatedType = createDataFromAnnotatedType;
2846
3293
  exports.defineAnnotatedType = require_user_text.defineAnnotatedType;
2847
3294
  exports.deserializeAnnotatedType = deserializeAnnotatedType;
2848
3295
  exports.detectDiscriminator = require_user_text.detectDiscriminator;
3296
+ exports.dropOptionalNulls = dropOptionalNulls;
2849
3297
  exports.flattenAnnotatedType = flattenAnnotatedType;
2850
3298
  exports.forAnnotatedType = forAnnotatedType;
2851
3299
  exports.formatValidatorMessage = require_user_text.formatValidatorMessage;
@@ -2866,6 +3314,7 @@ exports.registerUserText = require_user_text.registerUserText;
2866
3314
  exports.serializeAnnotatedType = serializeAnnotatedType;
2867
3315
  exports.throwFeatureDisabled = throwFeatureDisabled;
2868
3316
  exports.translateServed = translateServed;
3317
+ exports.translateUserText = translateUserText;
2869
3318
  exports.typeHasNormalizers = typeHasNormalizers;
2870
3319
  exports.unionDiscriminator = require_user_text.unionDiscriminator;
2871
3320
  exports.userTextKeys = require_user_text.userTextKeys;
package/dist/utils.d.ts CHANGED
@@ -322,7 +322,10 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
322
322
  private builtin;
323
323
  /** {@link fail} of a type mismatch of `def`: its `@expect.message` replaces the message. */
324
324
  private mismatch;
325
- /** The `@meta.required` error of `def` (custom message or the type's default). */
325
+ /**
326
+ * The `@meta.required` error of `def`: its message, else its `@expect.message`, else the code's
327
+ * default.
328
+ */
326
329
  private required;
327
330
  /**
328
331
  * Adds `error`, already made, to the errors of the current level (as {@link error} does);
@@ -351,6 +354,12 @@ declare class Validator<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedTyp
351
354
  private get shortcuts();
352
355
  /** Validates `value` against `def` (after `replace`, `optional` and the plugins). */
353
356
  protected validateSafe(def: TAtscriptAnnotatedType, value: any): boolean;
357
+ /**
358
+ * A missing value (`undefined`, or `null`) of a `@meta.required` `def`: when `def` rejects it,
359
+ * the `@meta.required` error replaces the type error the walk reports (the same verdict). A
360
+ * bare `@meta.required` keeps the `@expect.message` text the type error had.
361
+ */
362
+ private missing;
354
363
  /**
355
364
  * What {@link validateSafe} decides of `def` (replaced) before its own validation: an
356
365
  * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
@@ -747,6 +756,56 @@ declare function normalizeForType<T = unknown>(def: TAtscriptAnnotatedType, valu
747
756
  */
748
757
  declare function typeHasNormalizers(def: TAtscriptAnnotatedType): boolean;
749
758
 
759
+ /**
760
+ * What a strict tool / structured-output schema of an LLM provider accepts (the `strict` option
761
+ * of {@link buildJsonSchema}): the schema is built closed (`additionalProperties: false` on every
762
+ * object), then rewritten to the profile. Constraints the profile drops are not enforced by the
763
+ * provider: validate the model's output with the atscript validator.
764
+ */
765
+ interface TStrictProfile {
766
+ /** The provider's name, in the errors of a shape it can't take. */
767
+ name: string;
768
+ /**
769
+ * The keywords the provider accepts (an allow-list): `true`, or a check of the keyword's value
770
+ * (`false`: the keyword is dropped there). Every other keyword is dropped.
771
+ */
772
+ keywords: Readonly<Record<string, true | ((value: unknown) => boolean)>>;
773
+ /**
774
+ * Every property in `required`, the optional ones nullable: the model sends `null` for an
775
+ * optional field it leaves out. The validator rejects `null` on an optional `@meta.required`
776
+ * field: drop those values first (see `dropOptionalNulls`).
777
+ */
778
+ requireAll: boolean;
779
+ /**
780
+ * Rewrites the `allOf` the schema builder writes: a `$ref` with notes beside it (a field's
781
+ * title, description, key counts) → the referenced schema inlined with them; several patterns
782
+ * → the first one (the rest dropped) when `allOf` itself is not allowed. Any other `allOf`
783
+ * the profile does not allow throws.
784
+ */
785
+ collapseAllOf: boolean;
786
+ /** Appends each dropped constraint to the schema's `description`, in plain words. */
787
+ describeDropped: boolean;
788
+ /** Recursive types (a `$defs` entry that refers to itself); `false`: throws. */
789
+ allowRecursion: boolean;
790
+ /** The root must be an object schema; else throws. */
791
+ objectRoot: boolean;
792
+ }
793
+ /**
794
+ * OpenAI Structured Outputs / `strict: true` function calling: every property required
795
+ * (optional ones nullable), objects closed, an object root, no `allOf`; patterns without
796
+ * lookaround, backreferences or modifier groups, numeric bounds and `minItems` / `maxItems`
797
+ * kept; string lengths, `uniqueItems` and key counts dropped. Recursion is allowed.
798
+ */
799
+ declare const OPENAI_STRICT: TStrictProfile;
800
+ /**
801
+ * Anthropic strict tool use / structured outputs: objects closed, an object root (a tool's
802
+ * `input_schema`), no recursion; simple patterns kept (no lookaround, backreferences, word
803
+ * boundaries or large `{n,m}`), `minItems` only `0` / `1`; numeric bounds, string lengths,
804
+ * `maxItems`, `uniqueItems` and key counts dropped. `allOf` is allowed
805
+ * except with a `$ref` (collapsed). Optional properties stay optional.
806
+ */
807
+ declare const ANTHROPIC_STRICT: TStrictProfile;
808
+
750
809
  /** A JSON Schema object (draft-compatible). */
751
810
  type TJsonSchema = Record<string, any>;
752
811
  /** Options of {@link buildJsonSchema} (and of the `jsonSchemaOptions` plugin option). */
@@ -767,6 +826,14 @@ interface TJsonSchemaOptions {
767
826
  * `anyOf` of `const` schemas. *(default: `true`)*
768
827
  */
769
828
  enums?: boolean;
829
+ /**
830
+ * Targets a strict LLM tool / structured-output schema: `OPENAI_STRICT`, `ANTHROPIC_STRICT` or
831
+ * a profile of your own (see {@link TStrictProfile}). The schema is built `closed`, then keeps
832
+ * only the keywords the profile allows (the dropped constraints described in `description`);
833
+ * a shape the profile can't take throws. The provider does not enforce what was dropped:
834
+ * validate the model's output with the type's validator. Runtime only (not a plugin option).
835
+ */
836
+ strict?: TStrictProfile;
770
837
  }
771
838
  /**
772
839
  * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
@@ -827,6 +894,22 @@ declare function mergeJsonSchemas(types: TAtscriptAnnotatedType[], opts?: TJsonS
827
894
  $defs: Record<string, TJsonSchema>;
828
895
  };
829
896
 
897
+ /**
898
+ * What `value` looks like without the `null` values the model sends for fields it leaves out under
899
+ * a `requireAll` profile (`OPENAI_STRICT`), before it goes to the validator. The validator
900
+ * takes a missing optional field, but not `null` on an optional `@meta.required` one.
901
+ *
902
+ * A `null` is dropped only from an optional field whose type does not accept `null`: for
903
+ * `x?: string | null` it stays (`null` and a missing field mean different things, e.g. "clear"
904
+ * and "keep" in a patch). In a union, the branch its discriminator picks applies; else every
905
+ * branch does, and a key is dropped only when every branch (and, in an intersection, every part)
906
+ * that declares it has it optional and not accepting `null`: one that needs the `null` keeps it.
907
+ *
908
+ * Copy-on-change: `value` is never mutated (a frozen one works); the same reference comes back
909
+ * when nothing is dropped, else a copy with the changed objects and arrays rebuilt.
910
+ */
911
+ declare function dropOptionalNulls<T>(type: TAtscriptAnnotatedType, value: T): T;
912
+
830
913
  /**
831
914
  * Describes a discriminator property shared by all variants of a union.
832
915
  *
@@ -1328,6 +1411,24 @@ declare function translateServed<T>(json: T, t: (text: string) => string | undef
1328
1411
  value: T;
1329
1412
  texts: Record<string, string>;
1330
1413
  };
1414
+ /**
1415
+ * Translates the value of one metadata key (live, as a compiled type holds it — not serialized)
1416
+ * with `t`, by the rules {@link translateServed} applies to serialized metadata, so a client
1417
+ * translating compiled types reads one catalogue with the server: a text key's string (each item
1418
+ * of a `multiple` list; the named fields of a value object, e.g. `message` of `meta.required`) is
1419
+ * replaced by `t(text)` — except a primitive's built-in format message, which is reported by its
1420
+ * code. Returns `value` itself when the key holds no user text or nothing is translated; it is
1421
+ * never changed.
1422
+ *
1423
+ * Expressions are left as they are: their string literals are translated in a served type's
1424
+ * `texts`, and a client translates what an expression returns (by exact match), not its source.
1425
+ *
1426
+ * @example
1427
+ * ```ts
1428
+ * const label = translateUserText('meta.label', 'Street', text => dict[text]) // dict['Street']
1429
+ * ```
1430
+ */
1431
+ declare function translateUserText(key: string, value: unknown, t: (text: string) => string | undefined): unknown;
1331
1432
 
1332
1433
  /**
1333
1434
  * Metadata layers: the runtime's one metadata mechanism.
@@ -1551,5 +1652,5 @@ type NavPropsOf<T> = T extends {
1551
1652
  __navProps: infer N extends Record<string, unknown>;
1552
1653
  } ? N : Record<string, never>;
1553
1654
 
1554
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1555
- export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };
1655
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, ANTHROPIC_STRICT, LayerMap, OPENAI_STRICT, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, dropOptionalNulls, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, translateUserText, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
1656
+ export type { AtscriptExprNode, AtscriptOrderItem, AtscriptQueryComparison, AtscriptQueryFieldRef, AtscriptQueryNode, AtscriptRef, FlatOf, InferDataType, NavPropsOf, OwnPropsOf, PrimaryKeyOf, TAnnotatedTypeHandle, TAtscriptAnnotatedType, TAtscriptAnnotatedTypeConstructor, TAtscriptDataType, TAtscriptField, TAtscriptTypeArray, TAtscriptTypeComplex, TAtscriptTypeDef, TAtscriptTypeFinal, TAtscriptTypeObject, TCreateDataOptions, TError, TErrorInfo, TFlattenOptions, TJsonSchema, TJsonSchemaOptions, TMetadataMap, TProcessAnnotationContext, TSerializeOptions, TSerializedAnnotatedType, TSerializedAnnotatedTypeInner, TSerializedTypeArray, TSerializedTypeComplex, TSerializedTypeDef, TSerializedTypeFinal, TSerializedTypeObject, TStrictProfile, TUnionDiscriminator, TUserTextFields, TValidatorDiscriminator, TValidatorErrorCode, TValidatorOptions, TValidatorPlugin, TValidatorPluginContext, TValidatorTranslate, TValueResolver };