Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion scripts/generate-zod.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { preprocessSpec, rewriteUnionsAsDiscriminated } from './lib/preprocess.mjs';
import { preprocessSpec, rewriteUnionsAsDiscriminated, relaxResponseStrict } from './lib/preprocess.mjs';
import { generateZodClientFromOpenAPI } from 'openapi-zod-client';

const __dirname = dirname(fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -192,6 +192,9 @@ async function main() {
// Post-process: convert `z.union([...])` → `z.discriminatedUnion("type", [...])`
// for hierarchies the preprocessor inlined.
clean = rewriteUnionsAsDiscriminated(clean, inlinedDiscriminators);
// Post-process: relax `.strict()` → `.passthrough()` on response-shape DTOs
// so new API fields don't break surfaces built against an older spec.
clean = relaxResponseStrict(clean);
writeFileSync(OUTPUT_PATH, clean, 'utf8');

const schemaCount = (clean.match(/^const /gm) || []).length;
Expand Down
40 changes: 40 additions & 0 deletions scripts/lib/preprocess.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,43 @@ export function rewriteUnionsAsDiscriminated(source, unions) {
return `z.discriminatedUnion("${disc}", [${memberList.join(', ')}])`;
});
}

/**
* Rewrite `.strict()` → `.passthrough()` on response-shape DTO declarations
* so surfaces tolerate new fields added to the API after the surface was built.
* Request schemas keep `.strict()` to catch typos in user input.
*/
export function relaxResponseStrict(source) {
const declRe = /^const\s+(\w+)\b/gm;
const strictRe = /\.strict\(\)/g;

function isResponseShape(name) {
if (/^[a-z]/.test(name)) return false;
if (/(Request|Params)$/.test(name)) return false;
return (
/(Dto|Response)$/.test(name) ||
/^(SingleValueResponse|TableValueResult|CursorPage)/.test(name)
);
}

const declarations = [];
let match;
while ((match = declRe.exec(source)) !== null) {
declarations.push({ start: match.index, name: match[1] });
}
if (declarations.length === 0) return source;

let out = source.slice(0, declarations[0].start);
for (let i = 0; i < declarations.length; i++) {
const { start, name } = declarations[i];
const end =
i + 1 < declarations.length ? declarations[i + 1].start : source.length;
const body = source.slice(start, end);
if (isResponseShape(name)) {
out += body.replace(strictRe, '.passthrough()');
} else {
out += body;
}
}
return out;
}
Loading
Loading