(
schema: T,
ctx: ToJSONSchemaContext,
_params: ProcessParams = { path: [], schemaPath: [] }
)
| 137 | } |
| 138 | |
| 139 | export function process<T extends schemas.$ZodType>( |
| 140 | schema: T, |
| 141 | ctx: ToJSONSchemaContext, |
| 142 | _params: ProcessParams = { path: [], schemaPath: [] } |
| 143 | ): JSONSchema.BaseSchema { |
| 144 | const def = schema._zod.def as schemas.$ZodTypes["_zod"]["def"]; |
| 145 | |
| 146 | // check for schema in seens |
| 147 | const seen = ctx.seen.get(schema); |
| 148 | |
| 149 | if (seen) { |
| 150 | seen.count++; |
| 151 | |
| 152 | // check if cycle |
| 153 | const isCycle = _params.schemaPath.includes(schema); |
| 154 | if (isCycle) { |
| 155 | seen.cycle = _params.path; |
| 156 | } |
| 157 | |
| 158 | return seen.schema; |
| 159 | } |
| 160 | |
| 161 | // initialize |
| 162 | const result: Seen = { schema: {}, count: 1, cycle: undefined, path: _params.path }; |
| 163 | ctx.seen.set(schema, result); |
| 164 | |
| 165 | // custom method overrides default behavior |
| 166 | const overrideSchema = schema._zod.toJSONSchema?.(); |
| 167 | if (overrideSchema) { |
| 168 | result.schema = overrideSchema as any; |
| 169 | } else { |
| 170 | const params = { |
| 171 | ..._params, |
| 172 | schemaPath: [..._params.schemaPath, schema], |
| 173 | path: _params.path, |
| 174 | }; |
| 175 | |
| 176 | if (schema._zod.processJSONSchema) { |
| 177 | schema._zod.processJSONSchema(ctx, result.schema, params); |
| 178 | } else { |
| 179 | const _json = result.schema; |
| 180 | const processor = ctx.processors[def.type]; |
| 181 | if (!processor) { |
| 182 | throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); |
| 183 | } |
| 184 | processor(schema, ctx, _json, params); |
| 185 | } |
| 186 | |
| 187 | const parent = schema._zod.parent as T; |
| 188 | |
| 189 | if (parent) { |
| 190 | // Also set ref if processor didn't (for inheritance) |
| 191 | if (!result.ref) result.ref = parent; |
| 192 | process(parent, ctx, params); |
| 193 | ctx.seen.get(parent)!.isParent = true; |
| 194 | } |
| 195 | } |
| 196 |
no test coverage detected