-
-
Notifications
You must be signed in to change notification settings - Fork 35
Deep checks using toJSONSchema
#2589
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
020e156
hasNestedSchema() draft using z.toJSONSchema.
RobinTail 7008d1f
Switching hasUpload, hasRaw and hasForm to the new implementation.
RobinTail de53d57
Ref: no assert, throw.
RobinTail 485d69b
Migrating assertJsonCompatible() to new implementation.
RobinTail cddc54f
REF: changing it to findJsonIncompatible() and findNestedSchema(), so…
RobinTail 196e3e3
Tests for the new kind of error.
RobinTail 8d4b9d3
REF: replacing hasRaw in depictBody to content type condition.
RobinTail 1bff037
Merge branch 'make-v24' into deep-checks-using-json-schema
RobinTail 122705e
REF: replacing all has* functions with a single findRequestTypeDefini…
RobinTail File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,171 +1,81 @@ | ||
| import type { | ||
| $ZodArray, | ||
| $ZodCatch, | ||
| $ZodDefault, | ||
| $ZodDiscriminatedUnion, | ||
| $ZodInterface, | ||
| $ZodIntersection, | ||
| $ZodLazy, | ||
| $ZodNullable, | ||
| $ZodObject, | ||
| $ZodOptional, | ||
| $ZodPipe, | ||
| $ZodReadonly, | ||
| $ZodRecord, | ||
| $ZodTuple, | ||
| $ZodType, | ||
| $ZodUnion, | ||
| } from "@zod/core"; | ||
| import { fail } from "node:assert/strict"; // eslint-disable-line no-restricted-syntax -- acceptable | ||
| import { globalRegistry } from "zod"; | ||
| import type { $ZodType } from "@zod/core"; | ||
| import * as R from "ramda"; | ||
| import { globalRegistry, z } from "zod"; | ||
| import { ezDateInBrand } from "./date-in-schema"; | ||
| import { ezDateOutBrand } from "./date-out-schema"; | ||
| import { ezFileBrand } from "./file-schema"; | ||
| import { DeepCheckError } from "./errors"; | ||
| import { ezFormBrand } from "./form-schema"; | ||
| import { IOSchema } from "./io-schema"; | ||
| import { metaSymbol } from "./metadata"; | ||
| import { ProprietaryBrand } from "./proprietary-schemas"; | ||
| import { ezRawBrand } from "./raw-schema"; | ||
| import { | ||
| FirstPartyKind, | ||
| HandlingRules, | ||
| NextHandlerInc, | ||
| SchemaHandler, | ||
| } from "./schema-walker"; | ||
| import { FirstPartyKind } from "./schema-walker"; | ||
| import { ezUploadBrand } from "./upload-schema"; | ||
| import { ezRawBrand } from "./raw-schema"; | ||
|
|
||
| type CheckContext = { visited: WeakSet<object> }; | ||
| /** @desc Check is a schema handling rule returning boolean */ | ||
| type Check = SchemaHandler<boolean, CheckContext>; | ||
|
|
||
| const onSomeUnion: Check = ( | ||
| { _zod }: $ZodUnion | $ZodDiscriminatedUnion, | ||
| { next }, | ||
| ) => _zod.def.options.some(next); | ||
|
|
||
| const onIntersection: Check = ({ _zod }: $ZodIntersection, { next }) => | ||
| [_zod.def.left, _zod.def.right].some(next); | ||
|
|
||
| const onWrapped: Check = ( | ||
| { | ||
| _zod: { def }, | ||
| }: $ZodOptional | $ZodNullable | $ZodReadonly | $ZodDefault | $ZodCatch, | ||
| { next }, | ||
| ) => next(def.innerType); | ||
|
|
||
| const ioChecks: HandlingRules<boolean, CheckContext, FirstPartyKind> = { | ||
| object: ({ _zod }: $ZodObject, { next }) => | ||
| Object.values(_zod.def.shape).some(next), | ||
| interface: (int: $ZodInterface, { next, visited }) => | ||
| visited.has(int) | ||
| ? false | ||
| : visited.add(int) && Object.values(int._zod.def.shape).some(next), | ||
| union: onSomeUnion, | ||
| intersection: onIntersection, | ||
| optional: onWrapped, | ||
| nullable: onWrapped, | ||
| default: onWrapped, | ||
| record: ({ _zod }: $ZodRecord, { next }) => next(_zod.def.valueType), | ||
| array: ({ _zod }: $ZodArray, { next }) => next(_zod.def.element), | ||
| }; | ||
|
|
||
| interface NestedSchemaLookupProps extends Partial<CheckContext> { | ||
| condition?: (schema: $ZodType) => boolean; | ||
| rules?: HandlingRules< | ||
| boolean, | ||
| CheckContext, | ||
| FirstPartyKind | ProprietaryBrand | ||
| >; | ||
| maxDepth?: number; | ||
| depth?: number; | ||
| interface NestedSchemaLookupProps { | ||
| io: "input" | "output"; | ||
| condition: (zodSchema: $ZodType) => boolean; | ||
| } | ||
|
|
||
| /** @desc The optimized version of the schema walker for boolean checks */ | ||
| export const hasNestedSchema = ( | ||
| export const findNestedSchema = ( | ||
| subject: $ZodType, | ||
| { | ||
| condition, | ||
| rules = ioChecks, | ||
| depth = 1, | ||
| maxDepth = Number.POSITIVE_INFINITY, | ||
| visited = new WeakSet(), | ||
| }: NestedSchemaLookupProps, | ||
| ): boolean => { | ||
| if (condition?.(subject)) return true; | ||
| if (depth >= maxDepth) return false; | ||
| const { brand } = globalRegistry.get(subject)?.[metaSymbol] ?? {}; | ||
| const handler = | ||
| brand && brand in rules | ||
| ? rules[brand as keyof typeof rules] | ||
| : rules[subject._zod.def.type]; | ||
| if (handler) { | ||
| return handler(subject, { | ||
| visited, | ||
| next: (schema) => | ||
| hasNestedSchema(schema, { | ||
| condition, | ||
| rules, | ||
| maxDepth, | ||
| visited, | ||
| depth: depth + 1, | ||
| }), | ||
| } as CheckContext & NextHandlerInc<boolean>); | ||
| } | ||
| return false; | ||
| }; | ||
|
|
||
| export const hasUpload = (subject: IOSchema) => | ||
| hasNestedSchema(subject, { | ||
| condition: (schema) => | ||
| globalRegistry.get(schema)?.[metaSymbol]?.brand === ezUploadBrand, | ||
| rules: { | ||
| ...ioChecks, | ||
| [ezFormBrand]: ioChecks.object, | ||
| { io, condition }: NestedSchemaLookupProps, | ||
| ) => | ||
| R.tryCatch( | ||
| () => { | ||
| z.toJSONSchema(subject, { | ||
| io, | ||
| unrepresentable: "any", | ||
| override: ({ zodSchema }) => { | ||
| if (condition(zodSchema)) throw new DeepCheckError(zodSchema); // exits early | ||
| }, | ||
| }); | ||
| return undefined; | ||
| }, | ||
| }); | ||
| (err: DeepCheckError) => err.cause, | ||
| )(); | ||
|
|
||
| export const hasRaw = (subject: IOSchema) => | ||
| hasNestedSchema(subject, { | ||
| condition: (schema) => | ||
| globalRegistry.get(schema)?.[metaSymbol]?.brand === ezRawBrand, | ||
| maxDepth: 3, | ||
| export const findRequestTypeDefiningSchema = (subject: IOSchema) => | ||
| findNestedSchema(subject, { | ||
| condition: (schema) => { | ||
| const { brand } = globalRegistry.get(schema)?.[metaSymbol] || {}; | ||
| return ( | ||
| typeof brand === "symbol" && | ||
| [ezUploadBrand, ezRawBrand, ezFormBrand].includes(brand) | ||
| ); | ||
| }, | ||
| io: "input", | ||
| }); | ||
|
|
||
| export const hasForm = (subject: IOSchema) => | ||
| hasNestedSchema(subject, { | ||
| condition: (schema) => | ||
| globalRegistry.get(schema)?.[metaSymbol]?.brand === ezFormBrand, | ||
| maxDepth: 3, | ||
| }); | ||
| const unsupported: FirstPartyKind[] = [ | ||
| "nan", | ||
| "symbol", | ||
| "map", | ||
| "set", | ||
| "bigint", | ||
| "void", | ||
| "promise", | ||
| "never", | ||
| ]; | ||
|
|
||
| /** @throws AssertionError with incompatible schema constructor */ | ||
| export const assertJsonCompatible = (subject: $ZodType, dir: "in" | "out") => | ||
| hasNestedSchema(subject, { | ||
| maxDepth: 300, | ||
| rules: { | ||
| ...ioChecks, | ||
| readonly: onWrapped, | ||
| catch: onWrapped, | ||
| pipe: ({ _zod }: $ZodPipe, { next }) => next(_zod.def[dir]), | ||
| lazy: ({ _zod: { def } }: $ZodLazy, { next, visited }) => | ||
| visited.has(def.getter) | ||
| ? false | ||
| : visited.add(def.getter) && next(def.getter()), | ||
| tuple: ({ _zod: { def } }: $ZodTuple, { next }) => | ||
| [...def.items].concat(def.rest ?? []).some(next), | ||
| nan: () => fail("z.nan()"), | ||
| symbol: () => fail("z.symbol()"), | ||
| map: () => fail("z.map()"), | ||
| set: () => fail("z.set()"), | ||
| bigint: () => fail("z.bigint()"), | ||
| void: () => fail("z.void()"), | ||
| promise: () => fail("z.promise()"), | ||
| never: () => fail("z.never()"), | ||
| date: () => dir === "in" && fail("z.date()"), | ||
| [ezDateOutBrand]: () => dir === "in" && fail("ez.dateOut()"), | ||
| [ezDateInBrand]: () => dir === "out" && fail("ez.dateIn()"), | ||
| [ezRawBrand]: () => dir === "out" && fail("ez.raw()"), | ||
| [ezUploadBrand]: () => dir === "out" && fail("ez.upload()"), | ||
| [ezFileBrand]: () => false, | ||
| export const findJsonIncompatible = ( | ||
| subject: $ZodType, | ||
| io: "input" | "output", | ||
| ) => | ||
| findNestedSchema(subject, { | ||
| io, | ||
| condition: (zodSchema) => { | ||
| const { brand } = globalRegistry.get(zodSchema)?.[metaSymbol] || {}; | ||
| const { type } = zodSchema._zod.def; | ||
| if (unsupported.includes(type)) return true; | ||
| if (io === "input") { | ||
| if (type === "date") return true; | ||
| if (brand === ezDateOutBrand) return true; | ||
| } | ||
| if (io === "output") { | ||
| if (brand === ezDateInBrand) return true; | ||
| if (brand === ezRawBrand) return true; | ||
| if (brand === ezUploadBrand) return true; | ||
| } | ||
| return false; | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.