schema-truth 0.7.0 → 0.8.2

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.
Files changed (36) hide show
  1. package/dist/{ajv-DTP2FXRr.js → ajv-DS9gtNZC.js} +1 -1
  2. package/dist/ajv.d.ts +1 -1
  3. package/dist/ajv.js +1 -1
  4. package/dist/{arktype-BdvvaBQX.js → arktype-CBV4bg-0.js} +179 -75
  5. package/dist/arktype.d.ts +3 -3
  6. package/dist/arktype.js +1 -1
  7. package/dist/cli/ajv.js +2 -2
  8. package/dist/cli/arktype.js +2 -2
  9. package/dist/cli/effect.js +2 -2
  10. package/dist/cli/typebox.js +2 -2
  11. package/dist/cli/valibot.js +2 -2
  12. package/dist/cli/yup.js +2 -2
  13. package/dist/cli/zod.js +2 -2
  14. package/dist/{cli-CL2mSark.js → cli-CB9GJ7qa.js} +2 -2
  15. package/dist/{effect-mUknRPv_.js → effect-D9pvwi_6.js} +91 -31
  16. package/dist/effect.d.ts +3 -3
  17. package/dist/effect.js +1 -1
  18. package/dist/{helper-Cfvb5UDq.js → helper-S7SSsYwh.js} +777 -40
  19. package/dist/{index-C2L8Ty0-.d.ts → index-EK43HM_z.d.ts} +29 -25
  20. package/dist/{index-DbV3dEmN.d.ts → index-G7UqNQ4w.d.ts} +54 -2
  21. package/dist/index.d.ts +63 -25
  22. package/dist/index.js +9 -9
  23. package/dist/{typebox-BdWJv3ND.js → typebox-DGGKJLdP.js} +82 -42
  24. package/dist/typebox.d.ts +3 -3
  25. package/dist/typebox.js +1 -1
  26. package/dist/{utils-WNBq1HR0.js → utils-Bky98UmP.js} +160 -31
  27. package/dist/{valibot-CaJIynCH.js → valibot-B6y4VQFF.js} +107 -36
  28. package/dist/valibot.d.ts +3 -3
  29. package/dist/valibot.js +1 -1
  30. package/dist/{yup-CM2TSFig.js → yup-DuqQwHUv.js} +2 -2
  31. package/dist/yup.d.ts +2 -2
  32. package/dist/yup.js +1 -1
  33. package/dist/{zod-BsXLZfwK.js → zod-CXo9NFuF.js} +192 -115
  34. package/dist/zod.d.ts +3 -3
  35. package/dist/zod.js +1 -1
  36. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { c as normalizeTypes, s as makeSafeKey } from "./utils-WNBq1HR0.js";
1
+ import { c as normalizeTypes, s as makeSafeKey } from "./utils-Bky98UmP.js";
2
2
  //#region src/generator/ajv/integer.ts
3
3
  /**
4
4
  * Reconstruct a draft-07 integer schema. `minimum` is the only numeric keyword
package/dist/ajv.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as JSONSchema } from "./index-DbV3dEmN.js";
1
+ import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
2
  //#region src/generator/ajv/index.d.ts
3
3
  /**
4
4
  * Convert a JSON Schema document to Ajv TypeScript: a reconstructed draft-07
package/dist/ajv.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToAjv } from "./ajv-DTP2FXRr.js";
1
+ export { t as schemaToAjv } from "./ajv-DS9gtNZC.js";
@@ -1,34 +1,75 @@
1
- import { $ as DEFINITION_REF_PREFIXES, B as isSchemaObject, D as isComposite, E as isArktypeDefinition, H as isStringWireLocation, I as isQuoted, M as isNullable, N as isObjectPrototypeProperty, O as isDeepLocalPointer, Ot as UNSAFE_GENERATED_MARKER, R as isRootRef, S as hasFixedLength, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, bt as QUOTE_OR_BACKSLASH_PATTERN, c as normalizeTypes, ft as NUMBER_RANGES, j as isNullTypeMember, l as resolveOpenAPIRef, o as issueMessageExpression, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-WNBq1HR0.js";
2
- import { A as emitOptionsOf, B as arktypePreprocess, C as formatPattern, F as schemaNamer, H as findCodeExtensionKeysInSchema, M as planDocument, P as rootNameOf, S as wireNullText, V as arktypeWrap, _ as ownProperties, a as regexLiteral, b as unionPrimitiveTypes, c as parameterReaders, g as isPrimitiveUnion, h as isNullTextRead, j as missingDefinitionComment, l as withoutParameterSerialization, m as isNullMatchedFirst, p as impliedWireType, s as hasParameterSerialization, u as notPredicate, v as stringboolPattern, w as regexSource, x as wireArrayOnce, y as stringboolTruthyPattern, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
1
+ import { $ as DEFINITION_REF_PREFIXES, At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, D as isComposite, E as isArktypeDefinition, H as isStringWireLocation, I as isQuoted, M as isNullable, N as isObjectPrototypeProperty, O as isDeepLocalPointer, R as isRootRef, S as hasFixedLength, St as QUOTE_OR_BACKSLASH_PATTERN, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, c as normalizeTypes, j as isNullTypeMember, l as resolveOpenAPIRef, o as issueMessageExpression, pt as NUMBER_RANGES, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
2
+ import { $ as callbackReturn, A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, G as schemaNamer, H as planDocument, K as discriminatedMembers, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as arktypeWrap, S as isNullTextRead, T as ownProperties, V as missingDefinitionComment, W as rootNameOf, X as itemsSchemaOf, Z as arktypePreprocess, at as foldAllOfMembers, b as integerWirePattern, c as withPolymorphicBases, ct as regexLiteral, d as propertyEmitOptions, et as callbackType, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, it as constraintPredicate, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, ot as isKeywordOnlyMember, p as isBigintFormat, r as evaluatedProperties, rt as constraintMessage, tt as findCodeExtensionKeysInSchema, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-S7SSsYwh.js";
3
3
  //#region src/generator/arktype/number.ts
4
- /** The DSL comparators of a numeric node: `>= 1`, `< 5`, `% 2`. */
4
+ /** The comparators of a numeric node: `>= 1`, `< 5`, `% 2`. */
5
5
  function numericConstraints(schema) {
6
6
  return [
7
7
  (() => {
8
- if (schema.minimum !== void 0) return schema.exclusiveMinimum === true ? `> ${schema.minimum}` : `>= ${schema.minimum}`;
9
- if (typeof schema.exclusiveMinimum === "number") return `> ${schema.exclusiveMinimum}`;
8
+ if (schema.minimum !== void 0) return schema.exclusiveMinimum === true ? {
9
+ op: ">",
10
+ value: String(schema.minimum)
11
+ } : {
12
+ op: ">=",
13
+ value: String(schema.minimum)
14
+ };
15
+ if (typeof schema.exclusiveMinimum === "number") return {
16
+ op: ">",
17
+ value: String(schema.exclusiveMinimum)
18
+ };
10
19
  })(),
11
20
  (() => {
12
- if (schema.maximum !== void 0) return schema.exclusiveMaximum === true ? `< ${schema.maximum}` : `<= ${schema.maximum}`;
13
- if (typeof schema.exclusiveMaximum === "number") return `< ${schema.exclusiveMaximum}`;
21
+ if (schema.maximum !== void 0) return schema.exclusiveMaximum === true ? {
22
+ op: "<",
23
+ value: String(schema.maximum)
24
+ } : {
25
+ op: "<=",
26
+ value: String(schema.maximum)
27
+ };
28
+ if (typeof schema.exclusiveMaximum === "number") return {
29
+ op: "<",
30
+ value: String(schema.exclusiveMaximum)
31
+ };
14
32
  })(),
15
- schema.multipleOf !== void 0 ? `% ${schema.multipleOf}` : void 0
16
- ].filter((v) => v !== void 0);
33
+ schema.multipleOf !== void 0 ? {
34
+ op: "%",
35
+ value: String(schema.multipleOf)
36
+ } : void 0
37
+ ].filter(isNumericBound);
38
+ }
39
+ function isNumericBound(bound) {
40
+ return bound !== void 0;
17
41
  }
18
42
  /** The range comparators of a fixed-width numeric `format`, if it has one. */
19
43
  function rangeConstraints(format) {
20
44
  const range = format === void 0 ? void 0 : NUMBER_RANGES[format];
21
45
  if (range === void 0) return [];
22
- return [`>= ${range.minimum}`, `<= ${range.maximum}`];
46
+ return [{
47
+ op: ">=",
48
+ value: range.minimum
49
+ }, {
50
+ op: "<=",
51
+ value: range.maximum
52
+ }];
23
53
  }
24
54
  /**
25
55
  * A numeric keyword with its comparators as one quoted definition:
26
56
  * `"number.integer >= 1 & number.integer <= 5"`. One definition, not an `.and()` chain
27
57
  * of them, so a morph can validate its output against it with `.to()`.
28
58
  */
29
- function constraintDefinition(base, constraints) {
30
- if (constraints.length === 0) return `"${base}"`;
31
- return `"${constraints.map((c) => `${base} ${c}`).join(" & ")}"`;
59
+ function constraintDefinition(base, bounds) {
60
+ if (bounds.length === 0) return `"${base}"`;
61
+ return `"${bounds.map((bound) => `${base} ${bound.op} ${bound.value}`).join(" & ")}"`;
62
+ }
63
+ /** Whether a bound's literal is exponent notation, which the ArkType string parser rejects. */
64
+ function usesExponent(bounds) {
65
+ return bounds.some((bound) => /[eE]/.test(bound.value));
66
+ }
67
+ /**
68
+ * Bounds as methods on `type("number")`: a JavaScript number literal, so `1e+21` and the
69
+ * float32 limits never enter the string parser.
70
+ */
71
+ function methodChain(base, bounds) {
72
+ return `type("${base}")${bounds.map(boundMethod).join("")}`;
32
73
  }
33
74
  /**
34
75
  * The `.narrow(...)` chain of a numeric node whose bounds carry their own messages: the
@@ -82,12 +123,12 @@ function hasPerKeywordMessage(schema) {
82
123
  ].some(Boolean);
83
124
  }
84
125
  /**
85
- * A morph reading the text of a wire parameter with `Number`, guarded by `guard`: what
86
- * every other generator reads, where ArkType's own `string.numeric.parse` refuses `1e3`,
87
- * `1.0`, `007` and `-0`.
126
+ * A morph reading wire text into a number. The text has to match the integer or JSON
127
+ * number grammar before `Number` sees it: `Number` accepts `""`, `" "`, `"0x10"` and,
128
+ * for an integer, `"1e3"`.
88
129
  */
89
130
  function numberMorph(guard, expected) {
90
- return `type("string").pipe((data, ctx) => { const value = Number(data); return Number.${guard}(value) ? value : ctx.error(${JSON.stringify(expected)}) })`;
131
+ return `type("string").pipe((data, ctx) => { const value = ${guard === "isSafeInteger" ? integerWirePattern() : numberWirePattern()}.test(data) ? Number(data) : Number.NaN; return Number.${guard}(value) ? value : ctx.error(${JSON.stringify(expected)}) })`;
91
132
  }
92
133
  /**
93
134
  * The ArkType definition of a number node: the `number` keyword with its comparators,
@@ -97,13 +138,17 @@ function numberMorph(guard, expected) {
97
138
  function number(schema) {
98
139
  const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
99
140
  const describe = errorMessage ? `.describe(${JSON.stringify(errorMessage)})` : "";
100
- const isFloat32 = schema.format === "float" || schema.format === "float32";
101
- const constraints = [...rangeConstraints(isFloat32 ? "float32" : void 0), ...numericConstraints(schema)];
102
- if (hasPerKeywordMessage(schema)) return `type(${constraintDefinition("number", rangeConstraints(isFloat32 ? "float32" : void 0))})${numericNarrows(schema, errorMessage)}${describe}`;
141
+ const range = rangeConstraints(schema.format === "float" || schema.format === "float32" ? "float32" : void 0);
142
+ const constraints = [...range, ...numericConstraints(schema)];
143
+ if (hasPerKeywordMessage(schema)) return `${usesExponent(range) ? methodChain("number", range) : `type(${constraintDefinition("number", range)})`}${numericNarrows(schema, errorMessage)}${describe}`;
144
+ if (usesExponent(constraints)) return `${methodChain("number", constraints)}${describe}`;
103
145
  const definition = constraintDefinition("number", constraints);
104
146
  if (errorMessage) return `type(${definition})${describe}`;
105
147
  return definition;
106
148
  }
149
+ function boundMethod(bound) {
150
+ return `.${bound.op === ">=" ? "atLeast" : bound.op === ">" ? "moreThan" : bound.op === "<=" ? "atMost" : bound.op === "<" ? "lessThan" : "divisibleBy"}(${bound.value})`;
151
+ }
107
152
  //#endregion
108
153
  //#region src/generator/arktype/integer.ts
109
154
  /** Whether a node is a 64-bit integer: a value beyond 2^53 that is read as a bigint. */
@@ -149,8 +194,10 @@ function integer(schema, options) {
149
194
  }
150
195
  if (isInt64(schema)) return `${bigintMorph(options?.wire === true)}${bigintNarrows(schema, (n) => `${n}n`)}${describe}`;
151
196
  const range = rangeConstraints(schema.format);
152
- if (hasPerKeywordMessage(schema)) return `type(${constraintDefinition("number.integer", range)})${numericNarrows(schema, errorMessage)}${describe}`;
153
- const definition = constraintDefinition("number.integer", [...range, ...numericConstraints(schema)]);
197
+ const constraints = [...range, ...numericConstraints(schema)];
198
+ if (hasPerKeywordMessage(schema)) return `${usesExponent(range) ? methodChain("number.integer", range) : `type(${constraintDefinition("number.integer", range)})`}${numericNarrows(schema, errorMessage)}${describe}`;
199
+ if (usesExponent(constraints)) return `${methodChain("number.integer", constraints)}${describe}`;
200
+ const definition = constraintDefinition("number.integer", constraints);
154
201
  if (errorMessage) return `type(${definition})${describe}`;
155
202
  return definition;
156
203
  }
@@ -189,12 +236,13 @@ function _enum(schema) {
189
236
  }
190
237
  //#endregion
191
238
  //#region src/generator/arktype/object.ts
192
- function composeNarrows(base, narrows) {
193
- return narrows.length === 0 ? base : narrows.reduce((acc, n) => `${acc}.narrow(${n})`, base);
194
- }
195
- /** Wrap a raw arktype expression with `type(...)` if it's a bare quoted string. */
196
- function ensureRuntime(s) {
197
- return isQuoted(s) ? `type(${s})` : s;
239
+ /**
240
+ * An object definition with its narrows. Inside a scope they stay in definition syntax
241
+ * (`[def, ":", fn]`), which the scope resolves; outside, they chain on `type(def)`.
242
+ */
243
+ function composeNarrows(definition, narrows, scopeMode) {
244
+ if (scopeMode) return narrows.reduce((acc, n) => `[${acc},":",${n}]`, definition);
245
+ return narrows.reduce((acc, n) => `${acc}.narrow(${n})`, `type(${definition})`);
198
246
  }
199
247
  /**
200
248
  * Compose a `.narrow(...)` argument with an optional error message.
@@ -202,7 +250,7 @@ function ensureRuntime(s) {
202
250
  * - Without message: `(data) => predicate`
203
251
  */
204
252
  function narrowPredicate(predicate, message) {
205
- return message ? `(data, ctx) => ${predicate} || ctx.mustBe(${JSON.stringify(message)})` : `(data) => ${predicate}`;
253
+ return message ? callbackReturn("(data, ctx)", `${predicate} || ctx.mustBe(${JSON.stringify(message)})`) : callbackReturn("(data)", predicate);
206
254
  }
207
255
  /**
208
256
  * Generate an Arktype object schema for a JSON Schema object node.
@@ -230,28 +278,34 @@ function object(schema, rootName, isArktype, options) {
230
278
  return "";
231
279
  };
232
280
  const patternPropertiesNarrows = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
233
- const s = ensureRuntime(arktype(propSchema, rootName, isArktype, options));
281
+ const s = callbackType(arktype(propSchema, rootName, isArktype, options), isArktype);
234
282
  return narrowPredicate(`Object.entries(data).every(([key, value]) => !new RegExp(${JSON.stringify(pattern)}).test(key) || ${s}.allows(value))`, patternPropsMessage);
235
283
  }) : [];
236
- if (typeof schema.additionalProperties === "object") {
284
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) {
237
285
  const innerLiteral = `{"[string]":${arktype(schema.additionalProperties, rootName, isArktype, options)}}`;
238
- const narrows = [propertyNamesNarrow(), ...patternPropertiesNarrows()].filter((a) => a !== "");
239
- if (narrows.length > 0) return composeNarrows(`type(${innerLiteral})`, narrows);
286
+ const narrows = [propertyNamesNarrow()].filter((a) => a !== "");
287
+ if (narrows.length > 0) return composeNarrows(innerLiteral, narrows, isArktype);
240
288
  return isArktype ? innerLiteral : `type(${innerLiteral})`;
241
289
  }
290
+ const properties = schema.properties ?? {};
291
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
242
292
  if (!schema.properties) {
243
293
  if (schema.additionalProperties === true) return "\"unknown\"";
244
- return isArktype ? "{}" : "type({})";
294
+ if (!(undeclaredRequired.length > 0 || schema.patternProperties !== void 0 || schema.additionalProperties === false || schema.unevaluatedProperties !== void 0)) return isArktype ? "{}" : "type({})";
245
295
  }
246
- const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false ? "reject" : void 0;
296
+ const isEvaluated = isEvaluatedKeyExpression({
297
+ names: Object.keys(properties),
298
+ patterns: Object.keys(schema.patternProperties ?? {})
299
+ }, "key");
300
+ const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false && schema.patternProperties === void 0 ? "reject" : void 0;
247
301
  const required = new Set(schema.required);
248
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
249
- const parsed = arktype(propSchema, rootName, isArktype, options);
302
+ const props = [...Object.entries(properties).map(([key, propSchema]) => {
303
+ const parsed = arktype(propSchema, rootName, isArktype, propertyEmitOptions(key, propSchema, options) ?? options);
250
304
  if (!parsed) return null;
251
305
  const isRequired = required.has(key);
252
306
  const baseSafeKey = makeSafeKey(key);
253
307
  return `${isRequired ? baseSafeKey : baseSafeKey.startsWith("\"") ? JSON.stringify(`${key}?`) : `"${key}?"`}:${parsed}`;
254
- }).filter((p) => p !== null);
308
+ }).filter((p) => p !== null), ...undeclaredRequired.map((key) => `${makeSafeKey(key)}:"unknown"`)];
255
309
  const additionalProp = additionalMode ? `"+":"${additionalMode}"` : void 0;
256
310
  const innerLiteral = `{${[...props, additionalProp].filter((p) => p !== void 0).join(",")}}`;
257
311
  const minPropertiesNarrow = typeof schema.minProperties === "number" ? narrowPredicate(`Object.keys(data).length >= ${schema.minProperties}`, minimumMessage) : "";
@@ -260,22 +314,25 @@ function object(schema, rootName, isArktype, options) {
260
314
  return narrowPredicate(`!('${key}' in data) || (${deps.map((d) => `'${d}' in data`).join(" && ")})`, depReqMessage);
261
315
  }) : [];
262
316
  const dependentSchemasNarrows = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
263
- return narrowPredicate(`!('${key}' in data) || ${ensureRuntime(arktype(subSchema, rootName, isArktype, options))}.allows(data)`, depSchMessage);
317
+ return narrowPredicate(`!('${key}' in data) || ${callbackType(arktype(subSchema, rootName, isArktype, options), isArktype)}.allows(data)`, depSchMessage);
264
318
  }) : [];
265
- const additionalPropertiesNarrow = schema.additionalProperties === false && addlPropsMessage ? narrowPredicate(`Object.keys(data).every((key) => ${JSON.stringify(Object.keys(schema.properties))}.includes(key))`, addlPropsMessage) : "";
319
+ const additionalPropertiesNarrow = schema.additionalProperties === false && (addlPropsMessage !== void 0 || schema.patternProperties !== void 0) ? narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, addlPropsMessage) : "";
266
320
  const unevaluatedPropertiesNarrow = (() => {
267
- const u = schema.unevaluatedProperties;
321
+ const u = typeof schema.additionalProperties === "object" ? schema.additionalProperties : schema.unevaluatedProperties;
268
322
  if (u === void 0 || u === true) return "";
269
- const declaredKeys = JSON.stringify(Object.keys(schema.properties ?? {}));
270
- if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${declaredKeys}.includes(key))`, unevalPropsRawMessage);
271
- if (typeof u === "object") return narrowPredicate(`Object.entries(data).filter(([key]) => !${declaredKeys}.includes(key)).every(([, value]) => ${ensureRuntime(arktype(u, rootName, isArktype, options))}.allows(value))`, unevalPropsRawMessage);
323
+ const message = typeof schema.additionalProperties === "object" ? addlPropsMessage : unevalPropsRawMessage;
324
+ if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, message);
325
+ if (typeof u === "object") {
326
+ const s = callbackType(arktype(u, rootName, isArktype, options), isArktype);
327
+ return narrowPredicate(`Object.entries(data).every(([key, value]) => ${isEvaluated} || ${s}.allows(value))`, message);
328
+ }
272
329
  return "";
273
330
  })();
274
331
  const ifThenElseNarrows = (() => {
275
332
  if (!schema.if) return [];
276
- const ifS = ensureRuntime(arktype(schema.if, rootName, isArktype, options));
277
- const thenS = schema.then ? ensureRuntime(arktype(schema.then, rootName, isArktype, options)) : void 0;
278
- const elseS = schema.else ? ensureRuntime(arktype(schema.else, rootName, isArktype, options)) : void 0;
333
+ const ifS = callbackType(arktype(schema.if, rootName, isArktype, options), isArktype);
334
+ const thenS = schema.then ? callbackType(arktype(schema.then, rootName, isArktype, options), isArktype) : void 0;
335
+ const elseS = schema.else ? callbackType(arktype(schema.else, rootName, isArktype, options), isArktype) : void 0;
279
336
  if (!thenS && !elseS) return [];
280
337
  const ifMessage = schema["x-if-message"];
281
338
  const thenMessage = schema["x-then-message"] ?? ifMessage;
@@ -296,13 +353,14 @@ function object(schema, rootName, isArktype, options) {
296
353
  unevaluatedPropertiesNarrow,
297
354
  ...ifThenElseNarrows
298
355
  ].filter((a) => a !== "");
299
- const baseExpr = narrows.length > 0 ? composeNarrows(`type(${innerLiteral})`, narrows) : isArktype ? innerLiteral : `type(${innerLiteral})`;
356
+ const baseExpr = narrows.length > 0 ? composeNarrows(innerLiteral, narrows, isArktype) : isArktype ? innerLiteral : `type(${innerLiteral})`;
300
357
  const propsMessage = schema["x-properties-message"];
301
358
  const described = (() => {
302
359
  if (typeof propsMessage !== "string") return baseExpr;
303
- return `${baseExpr.startsWith("{") ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
360
+ if (isArktype && isArktypeDefinition(baseExpr)) return `[${baseExpr},"@",${JSON.stringify(propsMessage)}]`;
361
+ return `${isArktypeDefinition(baseExpr) ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
304
362
  })();
305
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
363
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
306
364
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? `${arktypePreprocess([ownProperties("data")], described, "object")}.pipe((data) => ({ ...data }))` : described;
307
365
  }
308
366
  //#endregion
@@ -452,6 +510,13 @@ function wireNumeric(morph, inner) {
452
510
  function stringbool() {
453
511
  return `type(${stringboolPattern()}).pipe((data) => ${stringboolTruthyPattern()}.test(data))`;
454
512
  }
513
+ /** A keyword-only `allOf` member: the keywords apply when the value has their type. */
514
+ function keywordConstraint(schema) {
515
+ const body = constraintPredicate(schema, "data");
516
+ const message = constraintMessage(schema);
517
+ if (message === void 0) return `type("unknown").narrow((data) => ${body})`;
518
+ return `type("unknown").narrow((data, ctx) => (${body}) || ctx.mustBe(${JSON.stringify(message)}))`;
519
+ }
455
520
  function formatConst(value, isBigint) {
456
521
  if (typeof value === "string") return `"'${value}'"`;
457
522
  if (typeof value === "number" && isBigint) return `"${value}n"`;
@@ -463,6 +528,28 @@ function formatConst(value, isBigint) {
463
528
  function isNumericMember(schema) {
464
529
  return (schema.type === "number" || schema.type === "integer") && schema.$ref === void 0 && !hasCombinator(schema) && schema.enum === void 0 && schema.const === void 0 && !isInt64(schema) && schema.format !== "bigint";
465
530
  }
531
+ /** An ArkType regex index-signature key for `source`, its slashes escaped. */
532
+ function indexKey(source) {
533
+ return JSON.stringify(`[/${source.replaceAll("/", "\\/")}/]`);
534
+ }
535
+ /**
536
+ * The members an `allOf` gains from `patternProperties` and `unevaluatedProperties` beside
537
+ * it: a regex index signature per pattern, holding the keys it matches to its schema, and
538
+ * one matching every key no member evaluates (no listed name, no pattern matching anywhere
539
+ * in it), holding it to `unevaluatedProperties`. An index signature can name a scope alias,
540
+ * which a `.narrow()` callback cannot.
541
+ */
542
+ function objectKeysMembers(schema, rootName, isArktype, options) {
543
+ const patternMembers = Object.entries(schema.patternProperties ?? {}).map(([pattern, propSchema]) => `{${indexKey(pattern)}:${arktype(propSchema, rootName, isArktype, options)}}`);
544
+ const unevaluated = schema.unevaluatedProperties;
545
+ if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return patternMembers;
546
+ const evaluated = evaluatedProperties(schema, options?.definitions);
547
+ if (evaluated === void 0) return patternMembers;
548
+ const value = unevaluated === false ? "\"never\"" : arktype(unevaluated, rootName, isArktype, options);
549
+ const names = evaluated.names.map((name) => name.replaceAll(/[\\^$.*+?()[\]{}|]/gu, "\\$&"));
550
+ const exclusions = [...names.length === 0 ? [] : [`(?!(?:${names.join("|")})$)`], ...evaluated.patterns.map((pattern) => `(?![\\s\\S]*?(?:${pattern}))`)];
551
+ return [...patternMembers, `{${indexKey(`^${exclusions.join("")}`)}:${value}}`];
552
+ }
466
553
  /**
467
554
  * Generate ArkType schema code from JSON Schema.
468
555
  *
@@ -494,7 +581,7 @@ function node(schema, rootName, isArktype, options) {
494
581
  const literalInput = (values) => {
495
582
  if (values.every((v) => typeof v === "number")) {
496
583
  if (isInt64(schema)) return bigintMorph(isWireCoerced);
497
- if (isWireCoerced) return numberMorph("isFinite", "a number");
584
+ if (isWireCoerced) return wireNumericKind(schema, values) === "integer" ? numberMorph("isSafeInteger", "an integer") : numberMorph("isFinite", "a number");
498
585
  }
499
586
  if (isWireCoerced && values.every((v) => typeof v === "boolean")) return stringbool();
500
587
  };
@@ -533,7 +620,14 @@ function node(schema, rootName, isArktype, options) {
533
620
  }, rootName, isArktype, options);
534
621
  if (schema.oneOf) {
535
622
  if (schema.oneOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
536
- return arktypeWrap$1(unionOf(schema.oneOf.map((s) => arktype(s, rootName, isArktype, options)), schema["x-oneOf-message"]), schema);
623
+ const discriminated = discriminatedMembers(schema, schema.oneOf);
624
+ return arktypeWrap$1(unionOf(schema.oneOf.map((s, i) => {
625
+ const member = arktype(s, rootName, isArktype, options);
626
+ const values = discriminated?.members[i]?.values;
627
+ if (discriminated === void 0 || values === void 0) return member;
628
+ const literal = values.map((value) => `'${value.replaceAll(/['\\]/gu, "\\$&")}'`).join(" | ");
629
+ return intersectionStr([member, `{${JSON.stringify(discriminated.propertyName)}:${JSON.stringify(literal)}}`], isArktype);
630
+ }), schema["x-oneOf-message"]), schema);
537
631
  }
538
632
  if (schema.anyOf) {
539
633
  if (schema.anyOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
@@ -542,25 +636,26 @@ function node(schema, rootName, isArktype, options) {
542
636
  if (schema.allOf) {
543
637
  if (schema.allOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
544
638
  const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
545
- const members = schema.allOf.filter((s) => !isShapelessMember(s));
639
+ const members = foldAllOfMembers(schema.allOf.filter((s) => !isShapelessMember(s)), isWireCoerced);
546
640
  if (isWireCoerced && members.length > 0 && members.every(isNumericMember)) {
547
641
  const definitions = members.map((s) => s.type === "integer" ? integer(s) : number(s));
548
- if (definitions.every(isQuoted)) {
549
- const isInteger = members.some((s) => s.type === "integer");
642
+ const isInteger = members.some((s) => s.type === "integer");
643
+ return arktypeWrap$1(wireNumeric(isInteger ? numberMorph("isSafeInteger", "an integer") : numberMorph("isFinite", "a number"), definitions.every(isQuoted) ? (() => {
550
644
  const parts = definitions.map((d) => d.slice(1, -1)).filter((d) => d !== "number" && d !== "number.integer");
551
- const merged = parts.length === 0 ? isInteger ? "\"number.integer\"" : "\"number\"" : `"${parts.join(" & ")}"`;
552
- return arktypeWrap$1(wireNumeric(isInteger ? numberMorph("isSafeInteger", "an integer") : numberMorph("isFinite", "a number"), merged), {
553
- ...schema,
554
- nullable
555
- });
556
- }
645
+ if (parts.length === 0) return isInteger ? "\"number.integer\"" : "\"number\"";
646
+ return `"${parts.join(" & ")}"`;
647
+ })() : definitions.length === 1 ? definitions[0] : intersectionStr(definitions, isArktype)), {
648
+ ...schema,
649
+ nullable
650
+ });
557
651
  }
558
- const schemas = members.map((s) => arktype(s, rootName, isArktype, options));
652
+ const schemas = members.map((s) => isKeywordOnlyMember(s) ? keywordConstraint(s) : arktype(s, rootName, isArktype, options));
559
653
  if (schemas.length === 0) return arktypeWrap$1("\"unknown\"", {
560
654
  ...schema,
561
655
  nullable
562
656
  });
563
- return arktypeWrap$1(schemas.length === 1 ? schemas[0] : intersectionStr(schemas, isArktype), {
657
+ const intersected = [...schemas, ...objectKeysMembers(schema, rootName, isArktype, options)];
658
+ return arktypeWrap$1(intersected.length === 1 ? intersected[0] : intersectionStr(intersected, isArktype), {
564
659
  ...schema,
565
660
  nullable
566
661
  });
@@ -570,9 +665,10 @@ function node(schema, rootName, isArktype, options) {
570
665
  if (typeof inner !== "object" || inner === null) return arktypeWrap$1("\"unknown\"", schema);
571
666
  const notMessage = schema["x-not-message"];
572
667
  const predicate = (() => {
573
- const shared = notPredicate(inner, "data", "data: unknown");
668
+ const bigint = isBigintFormat(withoutNot);
669
+ const shared = notPredicate(inner, "data", "data: unknown", bigint);
574
670
  if (shared !== void 0) return shared;
575
- if (Array.isArray(inner.enum)) return `(data: unknown) => !${JSON.stringify(inner.enum)}.includes(data as never)`;
671
+ if (Array.isArray(inner.enum)) return `(data: unknown) => !${valueListLiteral(inner.enum, bigint)}.includes(data as never)`;
576
672
  })();
577
673
  if (withoutNot.type !== void 0) {
578
674
  const base = arktype(withoutNot, rootName, isArktype, options);
@@ -674,13 +770,13 @@ function node(schema, rootName, isArktype, options) {
674
770
  const uniqueExpr = schema.uniqueItems === true ? narrowWith(lengthExpr, `(data: unknown[], ctx) => new Set(data).size === data.length${uniqueItemsMessage ? ` || ctx.mustBe(${JSON.stringify(uniqueItemsMessage)})` : ""}`) : lengthExpr;
675
771
  return arktypeWrap$1(wireArray(describeWithMessage((() => {
676
772
  if (!schema.contains) return [];
677
- const containsRt = asRuntime(arktype(schema.contains, rootName, isArktype, options));
773
+ const containsRt = callbackType(arktype(schema.contains, rootName, isArktype, options), isArktype);
678
774
  const minC = schema.minContains;
679
775
  const maxC = schema.maxContains;
680
- if (minC === void 0 && maxC === void 0) return [`.narrow((data: unknown[], ctx) => data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")}))`];
776
+ if (minC === void 0 && maxC === void 0) return [callbackReturn("(data: unknown[], ctx)", `data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")})`)];
681
777
  const effectiveMin = minC ?? 1;
682
- return [effectiveMin > 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length >= ${effectiveMin} || ctx.mustBe(${JSON.stringify(minContainsMessage ?? `must contain at least ${effectiveMin} matching items`)}))` : void 0, maxC !== void 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length <= ${maxC} || ctx.mustBe(${JSON.stringify(maxContainsMessage ?? `must contain at most ${maxC} matching items`)}))` : void 0].filter((v) => v !== void 0);
683
- })().reduce((acc, narrow) => `${asRuntime(acc)}${narrow}`, uniqueExpr), schema["x-items-message"])), schema);
778
+ return [effectiveMin > 0 ? callbackReturn("(data: unknown[], ctx)", `data.filter((item) => ${containsRt}.allows(item)).length >= ${effectiveMin} || ctx.mustBe(${JSON.stringify(minContainsMessage ?? `must contain at least ${effectiveMin} matching items`)})`) : void 0, maxC !== void 0 ? callbackReturn("(data: unknown[], ctx)", `data.filter((item) => ${containsRt}.allows(item)).length <= ${maxC} || ctx.mustBe(${JSON.stringify(maxContainsMessage ?? `must contain at most ${maxC} matching items`)})`) : void 0].filter((v) => v !== void 0);
779
+ })().reduce((acc, narrow) => isArktype && isArktypeDefinition(acc) ? `[${acc},":",${narrow}]` : `${asRuntime(acc)}.narrow(${narrow})`, uniqueExpr), schema["x-items-message"])), schema);
684
780
  }
685
781
  if (types.includes("object")) return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
686
782
  if (types.includes("date")) {
@@ -688,6 +784,7 @@ function node(schema, rootName, isArktype, options) {
688
784
  return arktypeWrap$1("\"Date\"", schema);
689
785
  }
690
786
  if (types.length === 1 && types[0] === "null") return arktypeWrap$1("\"null\"", schema);
787
+ if (typeof schema.additionalProperties === "object") return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
691
788
  return arktypeWrap$1("\"unknown\"", schema);
692
789
  }
693
790
  //#endregion
@@ -697,12 +794,18 @@ function node(schema, rootName, isArktype, options) {
697
794
  * a `scope({...}).export()` so members can name one another; one without is a bare
698
795
  * `type(...)` export.
699
796
  */
700
- function schemaToArktype(schema, options) {
797
+ function schemaToArktype(input, options) {
798
+ const schema = withPolymorphicBases(hoistNestedRefs(input));
701
799
  const exportType = options?.exportType ?? true;
702
- const emitOptions = emitOptionsOf(options);
703
- const prefix = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
704
- const toName = schemaNamer(emitOptions.openapi);
800
+ const baseOptions = emitOptionsOf(options);
801
+ const prefix = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
802
+ const toName = schemaNamer(baseOptions.openapi);
705
803
  const plan = planDocument(schema, rootNameOf(schema, toName));
804
+ const definitions = definitionsOf(baseOptions, plan.definitions);
805
+ const emitOptions = definitions === void 0 ? baseOptions : {
806
+ ...baseOptions,
807
+ definitions
808
+ };
706
809
  const { rootName } = plan;
707
810
  if (plan.hasDefinitions) {
708
811
  const defEntries = plan.orderedNames.map((name) => {
@@ -711,8 +814,9 @@ function schemaToArktype(schema, options) {
711
814
  const pc = toName(name);
712
815
  return `${pc}:${arktype(def, pc, true, emitOptions)}`;
713
816
  });
714
- const scopeBody = `const types = scope({${(plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",")}}).export()`;
715
- const usesType = /\btype[(.]/u.test(scopeBody);
817
+ const entries = (plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",");
818
+ const scopeBody = entries.includes("$.type(") ? `const $ = scope({${entries}})\n\nconst types = $.export()` : `const types = scope({${entries}}).export()`;
819
+ const usesType = /(?<![\w$.])type[(.]/u.test(scopeBody);
716
820
  return [
717
821
  ...prefix,
718
822
  `import { scope${usesType ? ", type" : ""} } from "arktype"`,
package/dist/arktype.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { r as JSONSchema } from "./index-DbV3dEmN.js";
2
- import { n as GenerateOptions } from "./index-C2L8Ty0-.js";
1
+ import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
+ import { n as GenerateOptions } from "./index-EK43HM_z.js";
3
3
  //#region src/generator/arktype/index.d.ts
4
4
  /**
5
5
  * A whole JSON Schema document as an ArkType module. A document with definitions becomes
6
6
  * a `scope({...}).export()` so members can name one another; one without is a bare
7
7
  * `type(...)` export.
8
8
  */
9
- export declare function schemaToArktype(schema: JSONSchema, options?: GenerateOptions): string;
9
+ export declare function schemaToArktype(input: JSONSchema, options?: GenerateOptions): string;
10
10
  //#endregion
package/dist/arktype.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToArktype } from "./arktype-BdvvaBQX.js";
1
+ export { t as schemaToArktype } from "./arktype-CBV4bg-0.js";
package/dist/cli/ajv.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToAjv } from "../ajv-DTP2FXRr.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToAjv } from "../ajv-DS9gtNZC.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToArktype } from "../arktype-BdvvaBQX.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToArktype } from "../arktype-CBV4bg-0.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToEffect } from "../effect-mUknRPv_.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToEffect } from "../effect-D9pvwi_6.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToTypebox } from "../typebox-BdWJv3ND.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToTypebox } from "../typebox-DGGKJLdP.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToValibot } from "../valibot-CaJIynCH.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToValibot } from "../valibot-B6y4VQFF.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
package/dist/cli/yup.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToYup } from "../yup-CM2TSFig.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToYup } from "../yup-DuqQwHUv.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
package/dist/cli/zod.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToZod } from "../zod-BsXLZfwK.js";
3
- import { n as version, t as cli } from "../cli-CL2mSark.js";
2
+ import { t as schemaToZod } from "../zod-CXo9NFuF.js";
3
+ import { n as version, t as cli } from "../cli-CB9GJ7qa.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -1,4 +1,4 @@
1
- import { L as isRecord } from "./utils-WNBq1HR0.js";
1
+ import { L as isRecord } from "./utils-Bky98UmP.js";
2
2
  import { i as fmt, n as parseSchemaFile } from "./parser-CyJ2auea.js";
3
3
  import * as Effect from "effect/Effect";
4
4
  import path from "node:path";
@@ -9,7 +9,7 @@ import * as Stdio from "effect/Stdio";
9
9
  import "@effect/platform-node/NodeFileSystem";
10
10
  import * as FileSystem from "effect/FileSystem";
11
11
  //#region package.json
12
- var version = "0.7.0";
12
+ var version = "0.8.2";
13
13
  //#endregion
14
14
  //#region src/file/index.ts
15
15
  /** Creates the directory and its parents. An existing directory is not an error. */