diff --git a/README.md b/README.md index 9294209..aec0659 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Each `new Validator(schema)` in your code whose schema the build can read become It also compiles JSON Schema files into self-contained modules with TypeScript declarations. Such a module imports nothing; a small schema compiles to about 1.3 KB gzipped and a ten-field one to about 2.6 KB, full error detail included, on ata-validator 1.36.0. It exports `validate`, `isValid` and the inferred type, and runs anywhere plain JavaScript runs. Schemas can be authored as `.json`, `.js` or `.ts`. +A form that validates with react-hook-form's `zodResolver(schema)` is compiled the same way, without changing the form: where the build can read the schema, zod leaves the page (a Next.js form page went from 43.5 to 15.3 KB gzipped). This is on by default. `zodResolver: false` turns it off, and `npx @ata-project/unplugin scan` shows which calls a build would compile, and why not the others, before you add the plugin. See [react-hook-form with zod](#react-hook-form-with-zod-zodresolverschema). + ## Install ```bash @@ -229,9 +231,9 @@ build with the plugin would compile away, and for each of the others, why not: ``` zodResolver: 2 of 6 calls would be compiled at build time; zod leaves the files where every call is. - app/signup/Form.tsx:10 zodResolver(schema): `schema` is not a constant written at the top of the file (a schema made inside a component is built on every render and cannot be read) - app/signup/Form.tsx:14 zodResolver(passwords): the schema has a function in it (a refine, a transform or a message function), which the build does not carry - app/profile/Form.tsx:9 zodResolver(tags): tags: an array is not carried yet + app/signup/Form.tsx:10 zodResolver(schema): the schema uses `t`, which is not zod or a constant of the file (a prop, a translation function and the like cannot be read) + app/signup/Form.tsx:14 zodResolver(passwords): a refine reads `minLength` from outside its own argument, which the build does not carry + app/profile/Form.tsx:9 zodResolver(profile): contact: a union is not carried yet app/links/Form.jsx:12 zodResolver(formSchema): site: url() is not carried (zod does not check it with a pattern) 3 files read. Nothing was written. ``` @@ -411,8 +413,9 @@ beyond the home page, gzipped: 43.5 KB as written and 15.3 KB through the plugin under Turbopack, 37.3 KB and 15.8 KB under webpack. react-hook-form alone is 12.3 KB. -The schema can be a constant of the file, built from zod and other constants -of the file, or written in the call itself. It can also come from another module of the project, imported by +The schema can be a constant of the file, at the top or inside the component, +built from zod and other constants of the file, or written in the call itself. +One built from a prop or a translation function cannot be read. It can also come from another module of the project, imported by name (`import { formSchema } from '@/lib/schemas'`). That module is read as text and never run: it has to import zod under one name and build the schema from zod and its own constants. A module that builds it from another module's diff --git a/src/compile-away.js b/src/compile-away.js index f5658f1..84a31d3 100644 --- a/src/compile-away.js +++ b/src/compile-away.js @@ -1080,7 +1080,7 @@ export function compileAway(code, id, ata, options) { zodKeep(call, why.why !== undefined ? why.why : name === null || zodFile.consts.has(name) ? (zodFile.zod ? 'zod was not found from this file' : 'zod is not imported under one name (`import { z } from \'zod\'`)') : named.has(name) ? 'the schema is imported and the build has no resolver for it here' - : `\`${name}\` is not a constant written at the top of the file (a schema made inside a component is built on every render and cannot be read)`) + : `\`${name}\` is not a constant the build can read (a \`const\` of one name, at the top of the file or in a function)`) continue } let plan = null; let ir = null diff --git a/src/zod-resolver.js b/src/zod-resolver.js index 38572a2..bc7a702 100644 --- a/src/zod-resolver.js +++ b/src/zod-resolver.js @@ -381,6 +381,16 @@ export function readZodFile (ast, needResolver = true) { else if (!stmt.source) for (const sp of stmt.specifiers) if (sp.type === 'ExportSpecifier' && sp.exportKind !== 'type' && sp.local.type === 'Identifier') { exports.set(sp.exported.name || sp.exported.value, sp.local.name); const c = consts.get(sp.local.name); if (c) c.exported = true } } } + // A constant declared inside a function, a component's body say: read like + // one at the top of the file where the file declares that name once (the + // caller checks). Its source still may name nothing but zod and constants, + // so one built from a prop or a translation function is not read. + walk(ast.program, (n, up) => { + if (n.type !== 'VariableDeclaration' || !up || up[0].type === 'Program' || up[0].type === 'ExportNamedDeclaration') return + if (up[0].type !== 'BlockStatement' || n.kind !== 'const' || n.declarations.length !== 1 || n.declarations[0].id.type !== 'Identifier' || !n.declarations[0].init) return + const name = n.declarations[0].id.name + if (!consts.has(name)) consts.set(name, { stmt: n, init: n.declarations[0].init, exported: false, local: true }) + }) // `export { x }` written before the constant it names. for (const local of exports.values()) { const c = consts.get(local); if (c) c.exported = true } return resolver || !needResolver ? { zod, resolver, consts, exports } : null @@ -420,7 +430,7 @@ export function schemaSource (name, info, code, exportedToo = false, out = {}) { // Nothing but zod's own methods by name: no computed member, and none // of the names that reach a function constructor. if ((n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') && (n.computed || /^(?:constructor|prototype|__proto__|call|apply|bind)$/.test(n.property.name))) { ok = fail('the schema reads a member the build does not follow'); return } - if (n.type === 'Identifier' && isName(n, up) && n.name !== info.zod.local && n.name !== 'undefined') { if (!info.consts.has(n.name)) ok = fail(`the schema uses \`${n.name}\`, which is not zod or a constant written at the top of the file`); else if (!visit(n.name)) ok = false } + if (n.type === 'Identifier' && isName(n, up) && n.name !== info.zod.local && n.name !== 'undefined') { if (!info.consts.has(n.name)) ok = fail(`the schema uses \`${n.name}\`, which is not zod or a constant of the file (a prop, a translation function and the like cannot be read)`); else if (!visit(n.name)) ok = false } }) return ok } @@ -430,7 +440,7 @@ export function schemaSource (name, info, code, exportedToo = false, out = {}) { const c = info.consts.get(nm) // In the file of the call an exported constant has readers the build // does not see, so it cannot be taken out and is not read. - if (!c) return fail(`\`${nm}\` is not a constant written at the top of the file`) + if (!c) return fail(`\`${nm}\` is not a constant the build can read`) if (c.exported && !exportedToo) return fail(`\`${nm}\` is exported, so other files may read it and it cannot leave this one`) if (!readable(c.init)) return false order.push(nm) diff --git a/test/scan.test.js b/test/scan.test.js index 1a8ed3c..3dc32a8 100644 --- a/test/scan.test.js +++ b/test/scan.test.js @@ -43,7 +43,7 @@ export const e = zodResolver(loginSchema, undefined, { raw: true }) const reasons = Object.fromEntries(r.zod.kept.map((k) => [/zodResolver\(([^)]*)\)/.exec(k.reason)[1] + '@' + k.line, k.reason])) assert.equal(r.zod.kept.length, 6) for (const k of r.zod.kept) assert.equal(k.file, path.join('app', 'mixed.ts')) - assert.match(reasons['schema@8'], /not a constant written at the top of the file/) + assert.match(reasons['schema@8'], /the schema uses `min`, which is not zod or a constant of the file/) assert.match(reasons['passwords@9'], /a refine reads `limit` from outside its own argument/) assert.match(reasons['tags@10'], /profile\.tags\.\*: a union is not carried yet/) assert.match(reasons['site@11'], /site: url\(\) is not carried/) diff --git a/test/zod-resolver.test.js b/test/zod-resolver.test.js index 9147e8a..4aad369 100644 --- a/test/zod-resolver.test.js +++ b/test/zod-resolver.test.js @@ -211,6 +211,12 @@ describe('zodResolver compiled away: a build', () => { assert.doesNotMatch(kept.text, /__ataZodResolver/) assert.match(kept.text, HAS_ZOD) }) + it('reads a schema declared inside the component, where it is made of zod alone', async () => { + const { text, mod } = await build('inside.js', `import { zodResolver } from '@hookform/resolvers/zod'\nimport { z } from 'zod'\nexport function useResolver() {\n const formSchema = z.object({\n ${FIELDS}\n })\n return zodResolver(formSchema)\n}\nexport function useOther(t) {\n const other = z.object({ name: z.string().min(2, t('short')) })\n return zodResolver(other)\n}\n`) + assert.equal((text.match(/__ataZodResolver\(/g) || []).length, 1, 'the one made of zod alone, not the one that calls t()') + assert.match(text, HAS_ZOD, 'the second schema still needs zod') + await same(mod.useResolver()) + }) it('keeps the type a TypeScript file infers from the schema', async () => { const { text, mod } = await build('typed.ts', `import { zodResolver } from '@hookform/resolvers/zod'\nimport { z } from 'zod'\nconst formSchema = z.object({\n ${FIELDS}\n})\nexport type FormValues = z.infer\nexport const resolver = zodResolver(formSchema)\nexport const first = (v: FormValues): string => v.username\n`) assert.doesNotMatch(text, HAS_ZOD, 'zod is still in the bundle')