to-json-schema.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import { globalRegistry } from "./registries.js";
  2. // function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
  3. // return {
  4. // processor: inputs.processor,
  5. // metadataRegistry: inputs.metadata ?? globalRegistry,
  6. // target: inputs.target ?? "draft-2020-12",
  7. // unrepresentable: inputs.unrepresentable ?? "throw",
  8. // };
  9. // }
  10. export function initializeContext(params) {
  11. // Normalize target: convert old non-hyphenated versions to hyphenated versions
  12. let target = params?.target ?? "draft-2020-12";
  13. if (target === "draft-4")
  14. target = "draft-04";
  15. if (target === "draft-7")
  16. target = "draft-07";
  17. return {
  18. processors: params.processors ?? {},
  19. metadataRegistry: params?.metadata ?? globalRegistry,
  20. target,
  21. unrepresentable: params?.unrepresentable ?? "throw",
  22. override: params?.override ?? (() => { }),
  23. io: params?.io ?? "output",
  24. counter: 0,
  25. seen: new Map(),
  26. cycles: params?.cycles ?? "ref",
  27. reused: params?.reused ?? "inline",
  28. external: params?.external ?? undefined,
  29. };
  30. }
  31. export function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
  32. var _a;
  33. const def = schema._zod.def;
  34. // check for schema in seens
  35. const seen = ctx.seen.get(schema);
  36. if (seen) {
  37. seen.count++;
  38. // check if cycle
  39. const isCycle = _params.schemaPath.includes(schema);
  40. if (isCycle) {
  41. seen.cycle = _params.path;
  42. }
  43. return seen.schema;
  44. }
  45. // initialize
  46. const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
  47. ctx.seen.set(schema, result);
  48. // custom method overrides default behavior
  49. const overrideSchema = schema._zod.toJSONSchema?.();
  50. if (overrideSchema) {
  51. result.schema = overrideSchema;
  52. }
  53. else {
  54. const params = {
  55. ..._params,
  56. schemaPath: [..._params.schemaPath, schema],
  57. path: _params.path,
  58. };
  59. if (schema._zod.processJSONSchema) {
  60. schema._zod.processJSONSchema(ctx, result.schema, params);
  61. }
  62. else {
  63. const _json = result.schema;
  64. const processor = ctx.processors[def.type];
  65. if (!processor) {
  66. throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
  67. }
  68. processor(schema, ctx, _json, params);
  69. }
  70. const parent = schema._zod.parent;
  71. if (parent) {
  72. // Also set ref if processor didn't (for inheritance)
  73. if (!result.ref)
  74. result.ref = parent;
  75. process(parent, ctx, params);
  76. ctx.seen.get(parent).isParent = true;
  77. }
  78. }
  79. // metadata
  80. const meta = ctx.metadataRegistry.get(schema);
  81. if (meta)
  82. Object.assign(result.schema, meta);
  83. if (ctx.io === "input" && isTransforming(schema)) {
  84. // examples/defaults only apply to output type of pipe
  85. delete result.schema.examples;
  86. delete result.schema.default;
  87. }
  88. // set prefault as default
  89. if (ctx.io === "input" && result.schema._prefault)
  90. (_a = result.schema).default ?? (_a.default = result.schema._prefault);
  91. delete result.schema._prefault;
  92. // pulling fresh from ctx.seen in case it was overwritten
  93. const _result = ctx.seen.get(schema);
  94. return _result.schema;
  95. }
  96. export function extractDefs(ctx, schema
  97. // params: EmitParams
  98. ) {
  99. // iterate over seen map;
  100. const root = ctx.seen.get(schema);
  101. if (!root)
  102. throw new Error("Unprocessed schema. This is a bug in Zod.");
  103. // Track ids to detect duplicates across different schemas
  104. const idToSchema = new Map();
  105. for (const entry of ctx.seen.entries()) {
  106. const id = ctx.metadataRegistry.get(entry[0])?.id;
  107. if (id) {
  108. const existing = idToSchema.get(id);
  109. if (existing && existing !== entry[0]) {
  110. throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
  111. }
  112. idToSchema.set(id, entry[0]);
  113. }
  114. }
  115. // returns a ref to the schema
  116. // defId will be empty if the ref points to an external schema (or #)
  117. const makeURI = (entry) => {
  118. // comparing the seen objects because sometimes
  119. // multiple schemas map to the same seen object.
  120. // e.g. lazy
  121. // external is configured
  122. const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
  123. if (ctx.external) {
  124. const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
  125. // check if schema is in the external registry
  126. const uriGenerator = ctx.external.uri ?? ((id) => id);
  127. if (externalId) {
  128. return { ref: uriGenerator(externalId) };
  129. }
  130. // otherwise, add to __shared
  131. const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
  132. entry[1].defId = id; // set defId so it will be reused if needed
  133. return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
  134. }
  135. if (entry[1] === root) {
  136. return { ref: "#" };
  137. }
  138. // self-contained schema
  139. const uriPrefix = `#`;
  140. const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
  141. const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
  142. return { defId, ref: defUriPrefix + defId };
  143. };
  144. // stored cached version in `def` property
  145. // remove all properties, set $ref
  146. const extractToDef = (entry) => {
  147. // if the schema is already a reference, do not extract it
  148. if (entry[1].schema.$ref) {
  149. return;
  150. }
  151. const seen = entry[1];
  152. const { ref, defId } = makeURI(entry);
  153. seen.def = { ...seen.schema };
  154. // defId won't be set if the schema is a reference to an external schema
  155. // or if the schema is the root schema
  156. if (defId)
  157. seen.defId = defId;
  158. // wipe away all properties except $ref
  159. const schema = seen.schema;
  160. for (const key in schema) {
  161. delete schema[key];
  162. }
  163. schema.$ref = ref;
  164. };
  165. // throw on cycles
  166. // break cycles
  167. if (ctx.cycles === "throw") {
  168. for (const entry of ctx.seen.entries()) {
  169. const seen = entry[1];
  170. if (seen.cycle) {
  171. throw new Error("Cycle detected: " +
  172. `#/${seen.cycle?.join("/")}/<root>` +
  173. '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
  174. }
  175. }
  176. }
  177. // extract schemas into $defs
  178. for (const entry of ctx.seen.entries()) {
  179. const seen = entry[1];
  180. // convert root schema to # $ref
  181. if (schema === entry[0]) {
  182. extractToDef(entry); // this has special handling for the root schema
  183. continue;
  184. }
  185. // extract schemas that are in the external registry
  186. if (ctx.external) {
  187. const ext = ctx.external.registry.get(entry[0])?.id;
  188. if (schema !== entry[0] && ext) {
  189. extractToDef(entry);
  190. continue;
  191. }
  192. }
  193. // extract schemas with `id` meta
  194. const id = ctx.metadataRegistry.get(entry[0])?.id;
  195. if (id) {
  196. extractToDef(entry);
  197. continue;
  198. }
  199. // break cycles
  200. if (seen.cycle) {
  201. // any
  202. extractToDef(entry);
  203. continue;
  204. }
  205. // extract reused schemas
  206. if (seen.count > 1) {
  207. if (ctx.reused === "ref") {
  208. extractToDef(entry);
  209. // biome-ignore lint:
  210. continue;
  211. }
  212. }
  213. }
  214. }
  215. export function finalize(ctx, schema) {
  216. const root = ctx.seen.get(schema);
  217. if (!root)
  218. throw new Error("Unprocessed schema. This is a bug in Zod.");
  219. // flatten refs - inherit properties from parent schemas
  220. const flattenRef = (zodSchema) => {
  221. const seen = ctx.seen.get(zodSchema);
  222. // already processed
  223. if (seen.ref === null)
  224. return;
  225. const schema = seen.def ?? seen.schema;
  226. const _cached = { ...schema };
  227. const ref = seen.ref;
  228. seen.ref = null; // prevent infinite recursion
  229. if (ref) {
  230. flattenRef(ref);
  231. const refSeen = ctx.seen.get(ref);
  232. const refSchema = refSeen.schema;
  233. // merge referenced schema into current
  234. if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
  235. // older drafts can't combine $ref with other properties
  236. schema.allOf = schema.allOf ?? [];
  237. schema.allOf.push(refSchema);
  238. }
  239. else {
  240. Object.assign(schema, refSchema);
  241. }
  242. // restore child's own properties (child wins)
  243. Object.assign(schema, _cached);
  244. const isParentRef = zodSchema._zod.parent === ref;
  245. // For parent chain, child is a refinement - remove parent-only properties
  246. if (isParentRef) {
  247. for (const key in schema) {
  248. if (key === "$ref" || key === "allOf")
  249. continue;
  250. if (!(key in _cached)) {
  251. delete schema[key];
  252. }
  253. }
  254. }
  255. // When ref was extracted to $defs, remove properties that match the definition
  256. if (refSchema.$ref && refSeen.def) {
  257. for (const key in schema) {
  258. if (key === "$ref" || key === "allOf")
  259. continue;
  260. if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
  261. delete schema[key];
  262. }
  263. }
  264. }
  265. }
  266. // If parent was extracted (has $ref), propagate $ref to this schema
  267. // This handles cases like: readonly().meta({id}).describe()
  268. // where processor sets ref to innerType but parent should be referenced
  269. const parent = zodSchema._zod.parent;
  270. if (parent && parent !== ref) {
  271. // Ensure parent is processed first so its def has inherited properties
  272. flattenRef(parent);
  273. const parentSeen = ctx.seen.get(parent);
  274. if (parentSeen?.schema.$ref) {
  275. schema.$ref = parentSeen.schema.$ref;
  276. // De-duplicate with parent's definition
  277. if (parentSeen.def) {
  278. for (const key in schema) {
  279. if (key === "$ref" || key === "allOf")
  280. continue;
  281. if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
  282. delete schema[key];
  283. }
  284. }
  285. }
  286. }
  287. }
  288. // execute overrides
  289. ctx.override({
  290. zodSchema: zodSchema,
  291. jsonSchema: schema,
  292. path: seen.path ?? [],
  293. });
  294. };
  295. for (const entry of [...ctx.seen.entries()].reverse()) {
  296. flattenRef(entry[0]);
  297. }
  298. const result = {};
  299. if (ctx.target === "draft-2020-12") {
  300. result.$schema = "https://json-schema.org/draft/2020-12/schema";
  301. }
  302. else if (ctx.target === "draft-07") {
  303. result.$schema = "http://json-schema.org/draft-07/schema#";
  304. }
  305. else if (ctx.target === "draft-04") {
  306. result.$schema = "http://json-schema.org/draft-04/schema#";
  307. }
  308. else if (ctx.target === "openapi-3.0") {
  309. // OpenAPI 3.0 schema objects should not include a $schema property
  310. }
  311. else {
  312. // Arbitrary string values are allowed but won't have a $schema property set
  313. }
  314. if (ctx.external?.uri) {
  315. const id = ctx.external.registry.get(schema)?.id;
  316. if (!id)
  317. throw new Error("Schema is missing an `id` property");
  318. result.$id = ctx.external.uri(id);
  319. }
  320. Object.assign(result, root.def ?? root.schema);
  321. // build defs object
  322. const defs = ctx.external?.defs ?? {};
  323. for (const entry of ctx.seen.entries()) {
  324. const seen = entry[1];
  325. if (seen.def && seen.defId) {
  326. defs[seen.defId] = seen.def;
  327. }
  328. }
  329. // set definitions in result
  330. if (ctx.external) {
  331. }
  332. else {
  333. if (Object.keys(defs).length > 0) {
  334. if (ctx.target === "draft-2020-12") {
  335. result.$defs = defs;
  336. }
  337. else {
  338. result.definitions = defs;
  339. }
  340. }
  341. }
  342. try {
  343. // this "finalizes" this schema and ensures all cycles are removed
  344. // each call to finalize() is functionally independent
  345. // though the seen map is shared
  346. const finalized = JSON.parse(JSON.stringify(result));
  347. Object.defineProperty(finalized, "~standard", {
  348. value: {
  349. ...schema["~standard"],
  350. jsonSchema: {
  351. input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
  352. output: createStandardJSONSchemaMethod(schema, "output", ctx.processors),
  353. },
  354. },
  355. enumerable: false,
  356. writable: false,
  357. });
  358. return finalized;
  359. }
  360. catch (_err) {
  361. throw new Error("Error converting schema to JSON.");
  362. }
  363. }
  364. function isTransforming(_schema, _ctx) {
  365. const ctx = _ctx ?? { seen: new Set() };
  366. if (ctx.seen.has(_schema))
  367. return false;
  368. ctx.seen.add(_schema);
  369. const def = _schema._zod.def;
  370. if (def.type === "transform")
  371. return true;
  372. if (def.type === "array")
  373. return isTransforming(def.element, ctx);
  374. if (def.type === "set")
  375. return isTransforming(def.valueType, ctx);
  376. if (def.type === "lazy")
  377. return isTransforming(def.getter(), ctx);
  378. if (def.type === "promise" ||
  379. def.type === "optional" ||
  380. def.type === "nonoptional" ||
  381. def.type === "nullable" ||
  382. def.type === "readonly" ||
  383. def.type === "default" ||
  384. def.type === "prefault") {
  385. return isTransforming(def.innerType, ctx);
  386. }
  387. if (def.type === "intersection") {
  388. return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
  389. }
  390. if (def.type === "record" || def.type === "map") {
  391. return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
  392. }
  393. if (def.type === "pipe") {
  394. return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
  395. }
  396. if (def.type === "object") {
  397. for (const key in def.shape) {
  398. if (isTransforming(def.shape[key], ctx))
  399. return true;
  400. }
  401. return false;
  402. }
  403. if (def.type === "union") {
  404. for (const option of def.options) {
  405. if (isTransforming(option, ctx))
  406. return true;
  407. }
  408. return false;
  409. }
  410. if (def.type === "tuple") {
  411. for (const item of def.items) {
  412. if (isTransforming(item, ctx))
  413. return true;
  414. }
  415. if (def.rest && isTransforming(def.rest, ctx))
  416. return true;
  417. return false;
  418. }
  419. return false;
  420. }
  421. /**
  422. * Creates a toJSONSchema method for a schema instance.
  423. * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
  424. */
  425. export const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
  426. const ctx = initializeContext({ ...params, processors });
  427. process(schema, ctx);
  428. extractDefs(ctx, schema);
  429. return finalize(ctx, schema);
  430. };
  431. export const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
  432. const { libraryOptions, target } = params ?? {};
  433. const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });
  434. process(schema, ctx);
  435. extractDefs(ctx, schema);
  436. return finalize(ctx, schema);
  437. };