@amritk/validation 0.6.0 → 0.6.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.
- package/README.md +18 -34
- package/dist/parsers/generators/generate-parser-function.js +9 -9
- package/dist/parsers/generators/generate-schema-checks.js +3 -3
- package/dist/parsers/generators/generate-strict-assertion.js +5 -5
- package/dist/parsers/generators/generate-type-checks.js +2 -2
- package/dist/parsers/generators/generate-validation-expression.js +3 -3
- package/dist/parsers/generators/subschema-match.js +4 -4
- package/dist/parsers/generators/unevaluated-match.js +2 -2
- package/dist/parsers/helpers/collect-imports.js +8 -8
- package/dist/validators/generators/generate-validator-function.js +96 -35
- package/dist/validators/generators/unevaluated-match.js +2 -2
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -211,35 +211,22 @@ document has to clone it first. `coerceX` returns a new value that shares
|
|
|
211
211
|
everything it did not touch, or the input itself when nothing needed coercing.
|
|
212
212
|
|
|
213
213
|
**It is faster where the input has to survive.** Against Ajv cloning first, so
|
|
214
|
-
both leave the caller's document alone
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
valid document is the common case and the widest gap: `coerceX` answers it with
|
|
231
|
-
`isX` and hands the input straight back, without walking it. `isX` builds
|
|
232
|
-
nothing — no error, no path — and stops at the first failure, answering a
|
|
233
|
-
`$ref` with the target's own `isX`; it calls `validateX` only for a schema that
|
|
234
|
-
folds to a constant. On valid input Ajv rewrites nothing, so it can
|
|
235
|
-
also be timed without the clone; `coerceX` is still ahead there on these
|
|
236
|
-
schemas, by 1.2–3.3×, but not on every one: on a large, union-heavy document
|
|
237
|
-
that the caller lets Ajv coerce in place, Ajv can come out modestly ahead. The
|
|
238
|
-
gap above is the clone, so it is real exactly where the caller cannot let Ajv
|
|
239
|
-
mutate its input.
|
|
240
|
-
The config case is the shape `--coerce` exists for: every coercible scalar sits
|
|
241
|
-
inside a union reached through `$ref`, and every union branch is tested by a
|
|
242
|
-
named function rather than a closure built per call.</sub>
|
|
214
|
+
both leave the caller's document alone, `coerceX` comes out ahead on every
|
|
215
|
+
schema in the bench, on both Bun and Node, whether the input is valid, needs
|
|
216
|
+
coercing, or cannot be coerced (`bun run bench:validators:coerce`, or
|
|
217
|
+
`bench:validators:coerce:node`). A valid document is the common case and the
|
|
218
|
+
widest gap: `coerceX` answers it with `isX` and hands the input straight back,
|
|
219
|
+
without walking it. `isX` builds nothing — no error, no path — and stops at the
|
|
220
|
+
first failure, answering a `$ref` with the target's own `isX`; it calls
|
|
221
|
+
`validateX` only for a schema that folds to a constant. On valid input Ajv
|
|
222
|
+
rewrites nothing, so it can also be timed without the clone; `coerceX` is still
|
|
223
|
+
ahead there on the bench schemas, but not on every one: on a large, union-heavy
|
|
224
|
+
document that the caller lets Ajv coerce in place, Ajv can come out modestly
|
|
225
|
+
ahead. Much of the gap is the clone, so it is real exactly where the caller
|
|
226
|
+
cannot let Ajv mutate its input. The bench's `config` case is the shape
|
|
227
|
+
`--coerce` exists for: every coercible scalar sits inside a union reached
|
|
228
|
+
through `$ref`, and every union branch is tested by a named function rather
|
|
229
|
+
than a closure built per call.
|
|
243
230
|
|
|
244
231
|
The errors differ in one way worth knowing if you key diagnostics on
|
|
245
232
|
`path + keyword + params`: an `additionalProperties` error points **at the
|
|
@@ -315,18 +302,15 @@ made. `bun run bench` measures it anyway, and the deltas wander either side of
|
|
|
315
302
|
zero between runs, which is what process-level variance looks like when there is
|
|
316
303
|
no underlying difference.
|
|
317
304
|
|
|
318
|
-
What does change is
|
|
305
|
+
What does change is what a build that reaches every mode emits:
|
|
319
306
|
|
|
320
307
|
| | before (both engines directly) | after |
|
|
321
308
|
|:---|:---|:---|
|
|
322
|
-
| codegen for the whole matrix | 2.9 ms | 2.7 ms |
|
|
323
|
-
| emitted bytes | 46.0 KiB | 45.8 KiB |
|
|
324
309
|
| files | 7 | 6 |
|
|
325
310
|
| declarations of `Order` | **2** | **1** |
|
|
326
|
-
| per-mode codegen | — | equal or slightly lower |
|
|
327
311
|
| per-mode bytes | — | identical |
|
|
328
312
|
|
|
329
|
-
The one that matters is the
|
|
313
|
+
The one that matters is the declarations row. Reaching every mode
|
|
330
314
|
used to mean running both generators yourself and shipping two trees for one
|
|
331
315
|
schema, including two declarations of the same type — structurally
|
|
332
316
|
interchangeable, but two things to keep in step. Now there is one.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { generateTypeDefinition } from "@amritk/helpers/generate-type-definition";
|
|
3
3
|
import { getDefaultValue } from "@amritk/helpers/get-default-value";
|
|
4
4
|
import { quoteJsString } from "@amritk/helpers/quote-js-string";
|
|
@@ -1418,12 +1418,12 @@ const generateStrictCombinedParser = (schema, typeName, functionName, propertyLi
|
|
|
1418
1418
|
const loopLines = [` if (${knownKeyCheck.isKnown("key")}) continue;`];
|
|
1419
1419
|
if (refPattern) {
|
|
1420
1420
|
const parserName = generateParserName(refToName(refPattern[1].$ref, suffix));
|
|
1421
|
-
loopLines.push(` if (${
|
|
1421
|
+
loopLines.push(` if (${regexTest(refPattern[0], "key")}) {`);
|
|
1422
1422
|
loopLines.push(` ${safeResultAssign("key", `${parserName}(input[key])`)}`);
|
|
1423
1423
|
loopLines.push(` continue;`);
|
|
1424
1424
|
loopLines.push(` }`);
|
|
1425
1425
|
}
|
|
1426
|
-
const keepConditions = patterns.filter(([p]) => !(refPattern && p === refPattern[0])).map(([p]) =>
|
|
1426
|
+
const keepConditions = patterns.filter(([p]) => !(refPattern && p === refPattern[0])).map(([p]) => regexTest(p, "key"));
|
|
1427
1427
|
if (keepConditions.length > 0) {
|
|
1428
1428
|
loopLines.push(` if (${keepConditions.join(" || ")}) {`);
|
|
1429
1429
|
loopLines.push(` ${safeResultAssign("key", "input[key]")}`);
|
|
@@ -1482,7 +1482,7 @@ const generateCombinedObjectParser = (schema, typeName, useRefImports, suffix, l
|
|
|
1482
1482
|
const ref = patternSchema.$ref;
|
|
1483
1483
|
const parserName = generateParserName(refToName(ref, suffix));
|
|
1484
1484
|
const assignmentCode = `(result as Record<string, unknown>)[key] = ${parserName}(value);`;
|
|
1485
|
-
const
|
|
1485
|
+
const patternTest = regexTest(pattern, "key");
|
|
1486
1486
|
const inputSpread = " ...input,";
|
|
1487
1487
|
let objectProperties = inputSpread;
|
|
1488
1488
|
if (propertyLines.length > 0) {
|
|
@@ -1500,7 +1500,7 @@ ${notObjectBranch}
|
|
|
1500
1500
|
${objectProperties}
|
|
1501
1501
|
} as unknown as ${typeName};
|
|
1502
1502
|
for (const key in input) {
|
|
1503
|
-
if (${
|
|
1503
|
+
if (${patternTest}) {
|
|
1504
1504
|
const value = input[key];
|
|
1505
1505
|
${assignmentCode}
|
|
1506
1506
|
}
|
|
@@ -1604,19 +1604,19 @@ const generatePatternPropertiesParser = (schema, typeName, useRefImports, suffix
|
|
|
1604
1604
|
patternAssignment = "";
|
|
1605
1605
|
patternValueExpr = null;
|
|
1606
1606
|
}
|
|
1607
|
-
const
|
|
1607
|
+
const patternTest = regexTest(pattern, "key");
|
|
1608
1608
|
const notObjectBranch = strict ? ` throw new Error(\`[${typeName}] expected object, got \${input === null ? "null" : typeof input}\`);` : ` return {} as unknown as ${typeName};`;
|
|
1609
1609
|
const keywordPrelude = strict ? strictObjectKeywordPrelude(schema, typeName, context) : "";
|
|
1610
1610
|
const strictKeys = hasAdditionalProperties(schema) && schema.additionalProperties === false;
|
|
1611
1611
|
if (strictKeys) {
|
|
1612
|
-
const loopLines = [` if (${
|
|
1612
|
+
const loopLines = [` if (${patternTest}) {`];
|
|
1613
1613
|
if (patternValueExpr) {
|
|
1614
1614
|
loopLines.push(` const value = input[key];`);
|
|
1615
1615
|
loopLines.push(` ${safeResultAssign("key", patternValueExpr)}`);
|
|
1616
1616
|
}
|
|
1617
1617
|
loopLines.push(` continue;`);
|
|
1618
1618
|
loopLines.push(` }`);
|
|
1619
|
-
const keepConditions = patterns.slice(1).map(([p]) =>
|
|
1619
|
+
const keepConditions = patterns.slice(1).map(([p]) => regexTest(p, "key"));
|
|
1620
1620
|
if (keepConditions.length > 0) {
|
|
1621
1621
|
loopLines.push(` if (${keepConditions.join(" || ")}) {`);
|
|
1622
1622
|
loopLines.push(` ${safeResultAssign("key", "input[key]")}`);
|
|
@@ -1644,7 +1644,7 @@ ${notObjectBranch}
|
|
|
1644
1644
|
...input,
|
|
1645
1645
|
} as unknown as ${typeName};
|
|
1646
1646
|
for (const key in input) {
|
|
1647
|
-
if (${
|
|
1647
|
+
if (${patternTest}) {
|
|
1648
1648
|
const value = input[key];
|
|
1649
1649
|
${patternAssignment}
|
|
1650
1650
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { getMjstInstanceOf, getMjstPrimitive } from "@amritk/helpers/mjst-extension";
|
|
3
3
|
import { multipleOfPassExpr } from "@amritk/helpers/multiple-of-check";
|
|
4
4
|
import { boundPassExpr } from "@amritk/helpers/numeric-bound-check";
|
|
@@ -95,7 +95,7 @@ const generateInferredChecks = (accessor, schema, type) => {
|
|
|
95
95
|
case "string":
|
|
96
96
|
checks.push(`typeof ${accessor} === "string"`);
|
|
97
97
|
if (hasPattern(schema)) {
|
|
98
|
-
checks.push(
|
|
98
|
+
checks.push(regexTest(schema.pattern, accessor));
|
|
99
99
|
}
|
|
100
100
|
if (hasMinLength(schema)) {
|
|
101
101
|
checks.push(minLengthPassExpr(accessor, schema.minLength));
|
|
@@ -175,7 +175,7 @@ const generateSchemaChecks = (accessor, schema) => {
|
|
|
175
175
|
case "string": {
|
|
176
176
|
checks.push(`typeof ${accessor} === "string"`);
|
|
177
177
|
if (hasPattern(schema)) {
|
|
178
|
-
checks.push(
|
|
178
|
+
checks.push(regexTest(schema.pattern, accessor));
|
|
179
179
|
}
|
|
180
180
|
if (hasMinLength(schema)) {
|
|
181
181
|
checks.push(minLengthPassExpr(accessor, schema.minLength));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { getMjstInstanceOf, getMjstPrimitive } from "@amritk/helpers/mjst-extension";
|
|
3
3
|
import { multipleOfFailExpr } from "@amritk/helpers/multiple-of-check";
|
|
4
4
|
import { boundFailExpr } from "@amritk/helpers/numeric-bound-check";
|
|
@@ -144,8 +144,8 @@ const generateConstraintChecks = (acc, propSchema, field, context = {}) => {
|
|
|
144
144
|
const lines = [];
|
|
145
145
|
if (t === "string") {
|
|
146
146
|
if (hasPattern(propSchema)) {
|
|
147
|
-
const
|
|
148
|
-
lines.push(` if (typeof ${acc} === "string" && !${
|
|
147
|
+
const patternTest = regexTest(propSchema.pattern, acc);
|
|
148
|
+
lines.push(` if (typeof ${acc} === "string" && !${patternTest}) ${throwError(`${field} must match pattern ${propSchema.pattern}`)};`);
|
|
149
149
|
}
|
|
150
150
|
if (hasMinLength(propSchema)) {
|
|
151
151
|
lines.push(` if (typeof ${acc} === "string" && ${minLengthFailExpr(acc, propSchema.minLength)}) ${throwError(`${field} must have at least ${propSchema.minLength} characters`)};`);
|
|
@@ -389,7 +389,7 @@ const generateKeyedValueChecks = (obj, schema, label, context = {}) => {
|
|
|
389
389
|
const additionalMatch = additional !== void 0 && typeof additional !== "boolean" ? subschemaMatchExpr("_v", additional, matchContext(context)) : null;
|
|
390
390
|
const lines = [];
|
|
391
391
|
for (const [pattern, match] of patternEntries) {
|
|
392
|
-
lines.push(` if (${
|
|
392
|
+
lines.push(` if (${regexTest(pattern, "_k")} && !(${match})) ${throwError(`${label} invalid value for property `, "_k")};`);
|
|
393
393
|
}
|
|
394
394
|
if (additionalMatch !== null && additionalMatch !== "true") {
|
|
395
395
|
const declared = hasProperties(schema) ? Object.keys(schema.properties) : [];
|
|
@@ -397,7 +397,7 @@ const generateKeyedValueChecks = (obj, schema, label, context = {}) => {
|
|
|
397
397
|
if (declared.length > 0)
|
|
398
398
|
guards.push(`!${JSON.stringify(declared)}.includes(_k)`);
|
|
399
399
|
for (const pattern of allPatterns)
|
|
400
|
-
guards.push(`!${
|
|
400
|
+
guards.push(`!${regexTest(pattern, "_k")}`);
|
|
401
401
|
const prefix = guards.length > 0 ? `${guards.join(" && ")} && ` : "";
|
|
402
402
|
lines.push(` if (${prefix}!(${additionalMatch})) ${throwError(`${label} invalid value for property `, "_k")};`);
|
|
403
403
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { multipleOfPassExpr } from "@amritk/helpers/multiple-of-check";
|
|
3
3
|
import { refToName } from "@amritk/helpers/ref-to-name";
|
|
4
4
|
import { resolveRef } from "@amritk/helpers/resolve-ref";
|
|
@@ -186,7 +186,7 @@ const generatePropertyTypeCheck = (varName, schema, useRefImports, suffix) => {
|
|
|
186
186
|
case "string": {
|
|
187
187
|
checks.push(`typeof ${varName} === "string"`);
|
|
188
188
|
if (hasPattern(schema))
|
|
189
|
-
checks.push(
|
|
189
|
+
checks.push(regexTest(schema.pattern, varName));
|
|
190
190
|
if (hasMinLength(schema))
|
|
191
191
|
checks.push(minLengthPassExpr(varName, schema.minLength));
|
|
192
192
|
if (hasMaxLength(schema))
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { getDefaultValue } from "@amritk/helpers/get-default-value";
|
|
3
3
|
import { getMjstInstanceOf, getMjstPrimitive } from "@amritk/helpers/mjst-extension";
|
|
4
4
|
import { multipleOfPassExpr } from "@amritk/helpers/multiple-of-check";
|
|
@@ -120,7 +120,7 @@ const getTypeArray = (schema) => {
|
|
|
120
120
|
const stringBoundChecks = (valueExpr, schema) => {
|
|
121
121
|
const checks = [];
|
|
122
122
|
if (hasPattern(schema))
|
|
123
|
-
checks.push(
|
|
123
|
+
checks.push(regexTest(schema.pattern, valueExpr));
|
|
124
124
|
if (hasMinLength(schema))
|
|
125
125
|
checks.push(minLengthPassExpr(valueExpr, schema.minLength));
|
|
126
126
|
if (hasMaxLength(schema))
|
|
@@ -285,7 +285,7 @@ const generateValidationExpression = (key, schema, defaultValue, isRequired, roo
|
|
|
285
285
|
case "string": {
|
|
286
286
|
checks.push(`typeof ${accessor} === "string"`);
|
|
287
287
|
if (hasPattern(schema)) {
|
|
288
|
-
checks.push(
|
|
288
|
+
checks.push(regexTest(schema.pattern, accessor));
|
|
289
289
|
}
|
|
290
290
|
if (hasMinLength(schema)) {
|
|
291
291
|
checks.push(minLengthPassExpr(accessor, schema.minLength));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { multipleOfPassExpr } from "@amritk/helpers/multiple-of-check";
|
|
3
3
|
import { resolveRef } from "@amritk/helpers/resolve-ref";
|
|
4
4
|
import { hasOwnCheck, missingCheck, safeAccessor } from "@amritk/helpers/safe-accessor";
|
|
@@ -83,7 +83,7 @@ const patternEntriesOf = (schema) => {
|
|
|
83
83
|
const stringConstraints = (acc, schema) => {
|
|
84
84
|
const c = [];
|
|
85
85
|
if (hasPattern(schema))
|
|
86
|
-
c.push(
|
|
86
|
+
c.push(regexTest(schema.pattern, acc));
|
|
87
87
|
if (hasMinLength(schema))
|
|
88
88
|
c.push(minLengthPassExpr(acc, schema.minLength));
|
|
89
89
|
if (hasMaxLength(schema))
|
|
@@ -245,7 +245,7 @@ const keyWalkTerms = (keyVar, valueVar, schema, ctx) => {
|
|
|
245
245
|
return null;
|
|
246
246
|
if (match === "true")
|
|
247
247
|
continue;
|
|
248
|
-
terms.push({ expr: `(!${
|
|
248
|
+
terms.push({ expr: `(!${regexTest(pattern, keyVar)} || ${match})`, usesValue: true });
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
251
|
const additional = schema["additionalProperties"];
|
|
@@ -255,7 +255,7 @@ const keyWalkTerms = (keyVar, valueVar, schema, ctx) => {
|
|
|
255
255
|
guards.push(`!${JSON.stringify(declared)}.includes(${keyVar})`);
|
|
256
256
|
if (patterns)
|
|
257
257
|
for (const [pattern] of patterns)
|
|
258
|
-
guards.push(`!${
|
|
258
|
+
guards.push(`!${regexTest(pattern, keyVar)}`);
|
|
259
259
|
const unclaimed = guards.length > 0 ? guards.join(" && ") : null;
|
|
260
260
|
if (additional === false) {
|
|
261
261
|
terms.push({ expr: unclaimed === null ? "false" : `!(${unclaimed})`, usesValue: false });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { resolveRef } from "@amritk/helpers/resolve-ref";
|
|
3
3
|
import { isSchemaObject } from "@amritk/helpers/schema-guards";
|
|
4
4
|
const NONE = { all: false, terms: [] };
|
|
@@ -29,7 +29,7 @@ const ownPropertyCoverage = (schema, keyVar, ignoreOwnUnevaluated) => {
|
|
|
29
29
|
const patterns = schema["patternProperties"];
|
|
30
30
|
if (typeof patterns === "object" && patterns !== null && !Array.isArray(patterns)) {
|
|
31
31
|
for (const pattern of Object.keys(patterns)) {
|
|
32
|
-
terms.push(
|
|
32
|
+
terms.push(regexTest(pattern, keyVar));
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
return { all: false, terms };
|
|
@@ -113,12 +113,12 @@ const collectImportTargets = (schema, options) => {
|
|
|
113
113
|
collectRefsFromValue(record.additionalProperties);
|
|
114
114
|
return;
|
|
115
115
|
}
|
|
116
|
-
if (record
|
|
116
|
+
if (record["type"] === "array" && hasItems(record) && !Array.isArray(record.items) && hasRef(record.items)) {
|
|
117
117
|
collectRefsFromValue(record.items);
|
|
118
118
|
return;
|
|
119
119
|
}
|
|
120
|
-
if (Object.hasOwn(record, "properties") && typeof record
|
|
121
|
-
for (const value2 of Object.values(record
|
|
120
|
+
if (Object.hasOwn(record, "properties") && typeof record["properties"] === "object" && record["properties"] !== null) {
|
|
121
|
+
for (const value2 of Object.values(record["properties"])) {
|
|
122
122
|
collectRefsFromValue(value2);
|
|
123
123
|
}
|
|
124
124
|
}
|
|
@@ -145,19 +145,19 @@ const collectImportTargets = (schema, options) => {
|
|
|
145
145
|
if (hasAdditionalProperties(record)) {
|
|
146
146
|
collectRefsFromValue(record.additionalProperties);
|
|
147
147
|
}
|
|
148
|
-
if (Object.hasOwn(record, "patternProperties") && typeof record
|
|
149
|
-
for (const value2 of Object.values(record
|
|
148
|
+
if (Object.hasOwn(record, "patternProperties") && typeof record["patternProperties"] === "object" && record["patternProperties"] !== null) {
|
|
149
|
+
for (const value2 of Object.values(record["patternProperties"])) {
|
|
150
150
|
collectRefsFromValue(value2);
|
|
151
151
|
}
|
|
152
152
|
}
|
|
153
153
|
if (Object.hasOwn(record, "if")) {
|
|
154
|
-
collectRefsFromValue(record
|
|
154
|
+
collectRefsFromValue(record["if"]);
|
|
155
155
|
}
|
|
156
156
|
if (Object.hasOwn(record, "then")) {
|
|
157
|
-
collectRefsFromValue(record
|
|
157
|
+
collectRefsFromValue(record["then"]);
|
|
158
158
|
}
|
|
159
159
|
if (Object.hasOwn(record, "else")) {
|
|
160
|
-
collectRefsFromValue(record
|
|
160
|
+
collectRefsFromValue(record["else"]);
|
|
161
161
|
}
|
|
162
162
|
};
|
|
163
163
|
if (typeof schema === "object" && schema !== null && hasRef(schema)) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { regexFlagsFor,
|
|
1
|
+
import { literalPattern, regexFlagsFor, regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { getMjstInstanceOf, getMjstPrimitive, MJST_EXTENSION_KEY } from "@amritk/helpers/mjst-extension";
|
|
3
3
|
import { multipleOfFailExpr, multipleOfPassExpr } from "@amritk/helpers/multiple-of-check";
|
|
4
4
|
import { boundFailExpr, boundOperator, boundPassExpr } from "@amritk/helpers/numeric-bound-check";
|
|
@@ -185,12 +185,20 @@ const generateStrictKeyChecks = (schema, ctx) => {
|
|
|
185
185
|
let patternGuard = "";
|
|
186
186
|
if (patterns.length > 0) {
|
|
187
187
|
const patternsName = `${hoistPrefix(ctx)}_patterns${ctx.hoisted.length}`;
|
|
188
|
-
const compiled =
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
188
|
+
const compiled = [];
|
|
189
|
+
const terms = patterns.map((p) => {
|
|
190
|
+
if (literalPattern(p) !== null)
|
|
191
|
+
return regexTest(p, `_key${d}`);
|
|
192
|
+
compiled.push(`new RegExp(${JSON.stringify(p)}, ${JSON.stringify(regexFlagsFor(p))})`);
|
|
193
|
+
return `${patternsName}[${compiled.length - 1}].test(_key${d})`;
|
|
193
194
|
});
|
|
195
|
+
patternGuard = ` && !(${terms.join(" || ")})`;
|
|
196
|
+
if (compiled.length > 0) {
|
|
197
|
+
ctx.hoisted.push({
|
|
198
|
+
declaration: `const ${patternsName} = [${compiled.join(", ")}]`,
|
|
199
|
+
reference: patternGuard
|
|
200
|
+
});
|
|
201
|
+
}
|
|
194
202
|
}
|
|
195
203
|
return [
|
|
196
204
|
` for (const _key${d} in ${ctx.objVar}) {`,
|
|
@@ -215,7 +223,7 @@ const generateMissingRequiredChecks = (schema, ctx) => {
|
|
|
215
223
|
}
|
|
216
224
|
return lines;
|
|
217
225
|
};
|
|
218
|
-
const generatePropertyChecks = (key, index, propSchema, isRequired, suffix, ctx) => {
|
|
226
|
+
const generatePropertyChecks = (key, index, propSchema, isRequired, suffix, ctx, dispatched) => {
|
|
219
227
|
if (propSchema === false) {
|
|
220
228
|
const path = `\`${ctx.pathPrefix}/${pointerSegment(key)}\``;
|
|
221
229
|
const parentPath = ctx.depth === 0 ? "_path" : `\`${ctx.pathPrefix}\``;
|
|
@@ -246,7 +254,59 @@ const generatePropertyChecks = (key, index, propSchema, isRequired, suffix, ctx)
|
|
|
246
254
|
];
|
|
247
255
|
if (!readsBinding(raw, lines.join("\n")))
|
|
248
256
|
return lines;
|
|
249
|
-
return [` const ${raw} = ${propertyRead(ctx.objVar, key)}`, ...lines];
|
|
257
|
+
return [` const ${raw} = ${dispatched ?? propertyRead(ctx.objVar, key)}`, ...lines];
|
|
258
|
+
};
|
|
259
|
+
const KEY_DISPATCH_MIN_OPTIONAL = 8;
|
|
260
|
+
const planKeyDispatch = (properties, required, depth) => {
|
|
261
|
+
const locals = /* @__PURE__ */ new Map();
|
|
262
|
+
let optional = 0;
|
|
263
|
+
for (const [index, [key, propSchema]] of Object.entries(properties).entries()) {
|
|
264
|
+
if (PROTOTYPE_MEMBERS.has(key) || propSchema === false)
|
|
265
|
+
continue;
|
|
266
|
+
locals.set(key, `_dv${depth}_${index}`);
|
|
267
|
+
if (!required.has(key))
|
|
268
|
+
optional++;
|
|
269
|
+
}
|
|
270
|
+
if (optional < KEY_DISPATCH_MIN_OPTIONAL)
|
|
271
|
+
return null;
|
|
272
|
+
return { locals, extra: `_dx${depth}`, keyVar: `_dk${depth}` };
|
|
273
|
+
};
|
|
274
|
+
const renderKeyDispatch = (plan, objVar, body, sweep) => {
|
|
275
|
+
const read = [...plan.locals].filter(([, local]) => readsBinding(local, body));
|
|
276
|
+
if (read.length === 0 && !sweep)
|
|
277
|
+
return [];
|
|
278
|
+
const unread = sweep ? [...plan.locals].filter(([, local]) => !readsBinding(local, body)) : [];
|
|
279
|
+
const declarations = [...read.map(([, local]) => `${local}: unknown`), ...sweep ? [`${plan.extra} = false`] : []];
|
|
280
|
+
return [
|
|
281
|
+
` let ${declarations.join(", ")}`,
|
|
282
|
+
` for (const ${plan.keyVar} in ${objVar}) {`,
|
|
283
|
+
` switch (${plan.keyVar}) {`,
|
|
284
|
+
...read.flatMap(([key, local]) => [
|
|
285
|
+
` case ${JSON.stringify(key)}:`,
|
|
286
|
+
` ${local} = ${objVar}[${plan.keyVar}]`,
|
|
287
|
+
` break`
|
|
288
|
+
]),
|
|
289
|
+
...unread.length > 0 ? [...unread.map(([key]) => ` case ${JSON.stringify(key)}:`), ` break`] : [],
|
|
290
|
+
...sweep ? [` default:`, ` ${plan.extra} = true`] : [],
|
|
291
|
+
` }`,
|
|
292
|
+
` }`
|
|
293
|
+
];
|
|
294
|
+
};
|
|
295
|
+
const generatePropertiesBlock = (properties, required, suffix, ctx) => {
|
|
296
|
+
const dispatch = planKeyDispatch(properties, required, ctx.depth);
|
|
297
|
+
const lines = [];
|
|
298
|
+
for (const [index, [key, propSchema]] of Object.entries(properties).entries()) {
|
|
299
|
+
lines.push(...generatePropertyChecks(key, index, propSchema, required.has(key), suffix, ctx, dispatch?.locals.get(key)));
|
|
300
|
+
}
|
|
301
|
+
return { lines, dispatch };
|
|
302
|
+
};
|
|
303
|
+
const gatedStrictKeyChecks = (sweep, dispatch) => dispatch === null || sweep.length === 0 ? sweep : [` if (${dispatch.extra}) {`, ...sweep.map((line) => ` ${line}`), ` }`];
|
|
304
|
+
const assembleObjectLines = (dispatch, objVar, propertyLines, sweep, rest, afterSweep) => {
|
|
305
|
+
const gated = gatedStrictKeyChecks(sweep, dispatch);
|
|
306
|
+
const lines = [...propertyLines, ...rest, ...gated, ...afterSweep];
|
|
307
|
+
if (dispatch === null)
|
|
308
|
+
return lines;
|
|
309
|
+
return [...renderKeyDispatch(dispatch, objVar, lines.join("\n"), gated !== sweep), ...lines];
|
|
250
310
|
};
|
|
251
311
|
const singleIfBlock = (lines) => {
|
|
252
312
|
if (lines.length < 3)
|
|
@@ -374,9 +434,8 @@ const generateConstraintChecks = (key, raw, path, propSchema, suffix, ctx) => {
|
|
|
374
434
|
}
|
|
375
435
|
if (hasPattern(propSchema) || hasMinLength(propSchema) || hasMaxLength(propSchema)) {
|
|
376
436
|
if (hasPattern(propSchema)) {
|
|
377
|
-
const re = regexLiteral(propSchema.pattern);
|
|
378
437
|
const msg = JSON.stringify(`must match pattern ${propSchema.pattern}`);
|
|
379
|
-
lines.push(` if (typeof ${raw} === 'string' && !${
|
|
438
|
+
lines.push(` if (typeof ${raw} === 'string' && !${regexTest(propSchema.pattern, raw)}) {`);
|
|
380
439
|
lines.push(` ${pushError(ctx.sink, msg, path, "pattern", JSON.stringify({ pattern: propSchema.pattern }))}`);
|
|
381
440
|
lines.push(` }`);
|
|
382
441
|
}
|
|
@@ -819,7 +878,7 @@ const generatePatternAndAdditionalChecks = (schema, suffix, ctx) => {
|
|
|
819
878
|
const valueChecks = valueChecksFor(sub);
|
|
820
879
|
if (valueChecks.length === 0)
|
|
821
880
|
continue;
|
|
822
|
-
body.push(` if (${
|
|
881
|
+
body.push(` if (${regexTest(pattern, kv)}) {`);
|
|
823
882
|
body.push(...valueChecks.map((line) => ` ${line}`));
|
|
824
883
|
body.push(` }`);
|
|
825
884
|
}
|
|
@@ -836,7 +895,7 @@ const generatePatternAndAdditionalChecks = (schema, suffix, ctx) => {
|
|
|
836
895
|
body.push(` if (${knownTest}) continue`);
|
|
837
896
|
}
|
|
838
897
|
for (const pattern of patterns) {
|
|
839
|
-
body.push(` if (${
|
|
898
|
+
body.push(` if (${regexTest(pattern, kv)}) continue`);
|
|
840
899
|
}
|
|
841
900
|
body.push(...valueChecks.map((line) => ` ${line}`));
|
|
842
901
|
}
|
|
@@ -867,20 +926,21 @@ const generateInlineObjectChecks = (key, propSchema, raw, suffix, ctx) => {
|
|
|
867
926
|
};
|
|
868
927
|
const required = new Set(hasRequired(propSchema) ? propSchema.required : []);
|
|
869
928
|
const properties = hasProperties(propSchema) ? propSchema.properties : {};
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
929
|
+
const { lines: declaredLines, dispatch } = generatePropertiesBlock(properties, required, suffix, child);
|
|
930
|
+
const rest = [
|
|
931
|
+
...generateMissingRequiredChecks(propSchema, child),
|
|
932
|
+
...generatePatternAndAdditionalChecks(propSchema, suffix, child)
|
|
933
|
+
];
|
|
934
|
+
const sweep = generateStrictKeyChecks(propSchema, child);
|
|
935
|
+
const afterSweep = [];
|
|
936
|
+
afterSweep.push(...generateDependentRequiredChecks(propSchema, child));
|
|
937
|
+
afterSweep.push(...generateDependentSchemasChecks(propSchema, suffix, child));
|
|
938
|
+
afterSweep.push(...generateDependenciesChecks(propSchema, suffix, child));
|
|
939
|
+
afterSweep.push(...generateMinMaxPropertiesChecks(propSchema, child));
|
|
881
940
|
if (hasPropertyNames(propSchema)) {
|
|
882
|
-
|
|
941
|
+
afterSweep.push(...generatePropertyNameChecks(propSchema.propertyNames, suffix, child));
|
|
883
942
|
}
|
|
943
|
+
const innerLines = assembleObjectLines(dispatch, child.objVar, declaredLines, sweep, rest, afterSweep);
|
|
884
944
|
if (innerLines.length === 0)
|
|
885
945
|
return [];
|
|
886
946
|
return [
|
|
@@ -1196,16 +1256,16 @@ const generateObjectValidator = (schema, typeName, suffix, rootSchema, unknownKe
|
|
|
1196
1256
|
const required = new Set(hasRequired(schema) ? schema.required : []);
|
|
1197
1257
|
const properties = hasProperties(schema) ? schema.properties : {};
|
|
1198
1258
|
const ctx = createRootContext(rootSchema, formats, branchErrors, failFast);
|
|
1259
|
+
const { lines: declaredLines, dispatch } = generatePropertiesBlock(properties, required, suffix, ctx);
|
|
1260
|
+
const rest = [
|
|
1261
|
+
// Required keys with no `properties` entry still need a presence check.
|
|
1262
|
+
...generateMissingRequiredChecks(schema, ctx),
|
|
1263
|
+
// patternProperties values and a schema-form additionalProperties are
|
|
1264
|
+
// validated here (the `false` form is handled by generateStrictKeyChecks).
|
|
1265
|
+
...generatePatternAndAdditionalChecks(schema, suffix, ctx)
|
|
1266
|
+
];
|
|
1267
|
+
const sweep = generateStrictKeyChecks(schema, ctx);
|
|
1199
1268
|
const propertyLines = [];
|
|
1200
|
-
for (const [index, [key, propSchema]] of Object.entries(properties).entries()) {
|
|
1201
|
-
const checks = generatePropertyChecks(key, index, propSchema, required.has(key), suffix, ctx);
|
|
1202
|
-
if (checks.length > 0) {
|
|
1203
|
-
propertyLines.push(...checks);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
propertyLines.push(...generateMissingRequiredChecks(schema, ctx));
|
|
1207
|
-
propertyLines.push(...generatePatternAndAdditionalChecks(schema, suffix, ctx));
|
|
1208
|
-
propertyLines.push(...generateStrictKeyChecks(schema, ctx));
|
|
1209
1269
|
propertyLines.push(...generateDependentRequiredChecks(schema, ctx));
|
|
1210
1270
|
propertyLines.push(...generateDependentSchemasChecks(schema, suffix, ctx));
|
|
1211
1271
|
propertyLines.push(...generateDependenciesChecks(schema, suffix, ctx));
|
|
@@ -1219,7 +1279,8 @@ const generateObjectValidator = (schema, typeName, suffix, rootSchema, unknownKe
|
|
|
1219
1279
|
propertyLines.push(` const _root: unknown = input`);
|
|
1220
1280
|
propertyLines.push(...objectCombinators);
|
|
1221
1281
|
}
|
|
1222
|
-
const
|
|
1282
|
+
const objectLines = assembleObjectLines(dispatch, ctx.objVar, declaredLines, sweep, rest, propertyLines);
|
|
1283
|
+
const body = objectLines.length > 0 ? "\n" + objectLines.join("\n") + "\n" : "";
|
|
1223
1284
|
const guard = guardObjectConditions(schema, "input", "obj", createGuardContext(unknownKeys, formats));
|
|
1224
1285
|
const objBinding = readsObjBinding(body) ? [` const obj = input as Record<string, unknown>`] : [];
|
|
1225
1286
|
const collectBody = (name, exported) => [
|
|
@@ -1318,7 +1379,7 @@ const booleanLeafExpr = (schema, acc, ctx) => {
|
|
|
1318
1379
|
if (formatPass !== null)
|
|
1319
1380
|
parts.push(formatPass);
|
|
1320
1381
|
if (hasPattern(schema))
|
|
1321
|
-
parts.push(
|
|
1382
|
+
parts.push(regexTest(schema.pattern, acc));
|
|
1322
1383
|
if (hasMinLength(schema))
|
|
1323
1384
|
parts.push(minLengthPassExpr(acc, schema.minLength));
|
|
1324
1385
|
if (hasMaxLength(schema))
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { regexTest } from "@amritk/helpers/escape-regex-pattern";
|
|
2
2
|
import { declaresKey, readKey } from "@amritk/helpers/read-key";
|
|
3
3
|
import { resolveRef } from "@amritk/helpers/resolve-ref";
|
|
4
4
|
import { isSchemaObject } from "@amritk/helpers/schema-guards";
|
|
@@ -37,7 +37,7 @@ const ownPropertyCoverage = (schema, keyVar, ignoreOwnUnevaluated) => {
|
|
|
37
37
|
const patterns = readKey(schema, "patternProperties");
|
|
38
38
|
if (typeof patterns === "object" && patterns !== null && !Array.isArray(patterns)) {
|
|
39
39
|
for (const pattern of Object.keys(patterns)) {
|
|
40
|
-
terms.push(
|
|
40
|
+
terms.push(regexTest(pattern, keyVar));
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
return { all: false, terms };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/validation",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"description": "One generator surface over mjst's types, validators, coercers, repairers and parsers.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -73,20 +73,20 @@
|
|
|
73
73
|
}
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
|
-
"@amritk/helpers": "^0.
|
|
77
|
-
"json-schema-typed": "^
|
|
76
|
+
"@amritk/helpers": "^0.26.1",
|
|
77
|
+
"json-schema-typed": "^9.0.0"
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
80
|
"@amritk/runtime-validators": "^0.15.2",
|
|
81
81
|
"@ryoppippi/unplugin-typia": "^2.6.5",
|
|
82
|
-
"@scalar/openapi-parser": "^0.
|
|
82
|
+
"@scalar/openapi-parser": "^0.29.27",
|
|
83
83
|
"@sinclair/typebox": "^0.34.49",
|
|
84
84
|
"ajv": "^8.17.1",
|
|
85
85
|
"ajv-formats": "^3.0.1",
|
|
86
86
|
"benny": "^3.7.1",
|
|
87
|
-
"esbuild": "^0.28.
|
|
87
|
+
"esbuild": "^0.28.2",
|
|
88
88
|
"typescript": "^5.9.3",
|
|
89
|
-
"typia": "^
|
|
90
|
-
"zod": "^4.
|
|
89
|
+
"typia": "^15.4.1",
|
|
90
|
+
"zod": "^4.6.7"
|
|
91
91
|
}
|
|
92
92
|
}
|