#!/usr/bin/env node
import{fileURLToPath as ln}from"node:url";import R from"node:path";import oe from"node:process";import ye from"node:fs/promises";import E from"node:path";function le(e,n){let t={typingImports:new Set,pydanticImports:new Set(["BaseModel"]),needsUUID:!1,needsDate:!1,needsDatetime:!1,regexConstants:new Map,regexOrder:[],warnings:n.warnings??[],renderedPaths:new Set,pathNameMap:new Map,nameCounts:new Map,enumClasses:new Map,enumClassesToRender:[],enumStyle:n.enumStyle??"enum",enumBaseType:n.enumBaseType??"str"},i=de(e,n.name,t,[]),r=$e(t),o=Ee(t),s=Ce(t);return[r,o,s,i].filter(Boolean).join(`

`)}function ce(e,n){if(e.type!=="enum")throw new Error("Root schema must be an enum to generate Pydantic Enum class.");if((n.enumStyle??"enum")==="literal"){let o=e.values.map(s=>C(s));return["from typing import Literal","",`type ${P(n.name)} = Literal[${o.join(", ")}]`].join(`
`)}let i=P(n.name);return["from enum import Enum","",me(i,e.values,n.enumBaseType??"str")].join(`
`)}function de(e,n,t,i){if(e.type!=="object")throw new Error(`Cannot render non-object node as class "${n}"`);let r=B(i.join(".")||n,n,t,i),o=[];for(let[c,l]of Object.entries(e.fields))I(l,[...i,c],(m,d)=>{let p=d.join(".");if(t.renderedPaths.has(p))return;t.renderedPaths.add(p);let v=B(p,d[d.length-1]??"Model",t,d,n);o.push(de(m,v,t,d))});let s=[];for(let[c,l]of Object.entries(e.fields))s.push(be(c,l,t,[...i,c],n));let a=c=>c.length===0?"":`    ${c}`,u=[];for(let c of[...o,...s.length?s:["pass"]])c.includes(`
`)?u.push(...c.split(`
`).map(a)):u.push(a(c));return[`class ${r}(BaseModel):`,...u].join(`
`)}function be(e,n,t,i,r){let{annotation:o,defaultCode:s,optional:a}=G(n,t,i,r),{name:u,alias:c}=je(e),l=s;return c&&(l=Pe(l,c,a??!1),t.pydanticImports.add("Field")),l!==void 0?`${u}: ${o} = ${l}`:`${u}: ${o}`}function G(e,n,t,i){let{inner:r,optional:o,nullable:s,defaultValue:a}=pe(e),u=xe(r,n,t,i),c=u.annotation;s&&(n.typingImports.add("Optional"),c=`Optional[${c}]`),o&&(n.typingImports.add("Optional"),c=`Optional[${c}]`);let l={annotation:c};return a!==void 0?(l.defaultCode=ke(a,n),l):o?(l.defaultCode="None",l):(u.defaultCode!==void 0&&(l.defaultCode=u.defaultCode),l.optional=o,l)}function xe(e,n,t,i){switch(e.type){case"string":{let r=e.constraints;if(r){n.pydanticImports.add("constr");let o=[];if(r.length!==void 0?o.push(`min_length=${r.length}`,`max_length=${r.length}`):(r.minLength!==void 0&&o.push(`min_length=${r.minLength}`),r.maxLength!==void 0&&o.push(`max_length=${r.maxLength}`)),r.regex!==void 0){let s=Se(r.regex,t,n);o.push(`pattern=${s}`)}return{annotation:`constr(${o.join(", ")})`}}return{annotation:"str"}}case"number":{let r=e.constraints;return r?(n.pydanticImports.add("confloat"),{annotation:`confloat(${ae(r).join(", ")})`}):{annotation:"float"}}case"int":{let r=e.constraints;n.pydanticImports.add("conint");let o=r?ae(r):[];return{annotation:o.length?`conint(${o.join(", ")})`:"conint()"}}case"boolean":return{annotation:"bool"};case"date":return n.needsDate=!0,{annotation:"date"};case"datetime":return n.needsDatetime=!0,{annotation:"datetime"};case"uuid":return n.needsUUID=!0,{annotation:"UUID"};case"enum":{if(n.enumStyle==="literal")return n.typingImports.add("Literal"),{annotation:`Literal[${e.values.map(m=>C(m)).join(", ")}]`};let r=e.values.slice().sort().join("|"),o=n.enumClasses.get(r);if(o)return{annotation:o.name};let s=t.length>0?`${t.join(".")}.Enum`:"Enum",a=t[t.length-1],u=B(s,a?`${P(a)}Enum`:"Enum",n,[...t,"Enum"],i),c={name:u,values:e.values,baseType:n.enumBaseType};return n.enumClasses.set(r,c),n.enumClassesToRender.push(c),{annotation:u}}case"literal":return n.typingImports.add("Literal"),{annotation:`Literal[${C(e.value)}]`};case"array":{n.typingImports.add("List");let r=G(e.element,n,[...t,"[item]"],i),o={annotation:`List[${r.annotation}]`};return r.defaultCode!==void 0&&(o.defaultCode=r.defaultCode),o}case"union":return n.typingImports.add("Union"),{annotation:`Union[${e.options.map((o,s)=>G(o,n,[...t,`option${s}`],i).annotation).join(", ")}]`};case"object":return{annotation:B(t.join("."),t[t.length-1]??i,n,t,i)};case"any":case"unknown":return n.typingImports.add("Any"),{annotation:"Any"};case"reference":return{annotation:e.name};default:return n.typingImports.add("Any"),{annotation:"Any"}}}function ae(e){let n=[];return e.min&&n.push(`${e.min.inclusive?"ge":"gt"}=${e.min.value}`),e.max&&n.push(`${e.max.inclusive?"le":"lt"}=${e.max.value}`),e.positive&&!e.min&&n.push("gt=0"),e.nonnegative&&!e.min&&n.push("ge=0"),n}function pe(e){let n=e,t=!1,i=!1,r;for(;;){if(n.type==="optional"){t=!0,n=n.inner;continue}if(n.type==="nullish"){t=!0,i=!0,n=n.inner;continue}if(n.type==="nullable"){i=!0,n=n.inner;continue}if(n.type==="default"){r=n.defaultValue,n=n.inner;continue}break}return{inner:n,optional:t,nullable:i,defaultValue:r}}function ke(e,n){return n.pydanticImports.add("Field"),Array.isArray(e)?"Field(default_factory=list)":e&&typeof e=="object"?"Field(default_factory=dict)":`Field(default=${C(e)})`}function Se(e,n,t){let i=Te(e),r=t.regexConstants.get(i);if(r)return r;if(typeof e=="object"&&e instanceof RegExp){let a=["i","m","s"],u=e.flags.split("").filter(c=>!a.includes(c)&&c!=="u"&&c!=="g");u.length>0&&t.warnings.push({code:"unsupported_effect",path:n,message:`Regex flags "${u.join("")}" are not mapped to Python. Only i/m/s are embedded inline; u is default in Python, g is irrelevant.`})}let s=`${Oe([...n].pop()??"pattern")}_REGEX`;return t.regexConstants.set(i,s),t.regexOrder.push(i),s}function Te(e){return typeof e=="string"?e:`/${e.source}/${e.flags}`}function Ne(e){if(typeof e=="string")return ue(e);let n=e.flags.split("").map(i=>{switch(i){case"i":return"i";case"m":return"m";case"s":return"s";default:return""}}).join(""),t=n?`(?${n})`:"";return ue(t+e.source)}function Ee(e){return e.regexOrder.length?e.regexOrder.map(t=>{let i=e.regexConstants.get(t);if(!i)throw new Error(`Missing regex constant for key: ${t}`);return`${i} = ${Ne(t.startsWith("/")?new RegExp(t.slice(1,t.lastIndexOf("/")),t.slice(t.lastIndexOf("/")+1)):t)}`}).join(`
`):""}function $e(e){let n=[],t=Array.from(e.pydanticImports).sort();t.length&&n.push(`from pydantic import ${t.join(", ")}`);let i=Array.from(e.typingImports).sort();i.length&&n.push(`from typing import ${i.join(", ")}`),e.enumClassesToRender.length>0&&n.push("from enum import Enum");let r=[];return e.needsDate&&r.push("date"),e.needsDatetime&&r.push("datetime"),r.length&&n.push(`from datetime import ${r.join(", ")}`),e.needsUUID&&n.push("from uuid import UUID"),n.join(`
`)}function me(e,n,t){let i=n.map(r=>{let o=Fe(r),s=L(r);return`    ${o} = ${s}`});return[`class ${e}(${t}, Enum):`,...i].join(`
`)}function Ce(e){return e.enumClassesToRender.length===0?"":e.enumClassesToRender.map(n=>me(n.name,n.values,n.baseType)).join(`

`)}function Fe(e){return e.toUpperCase().replace(/[^A-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"VALUE"}function C(e){switch(typeof e){case"string":return L(e);case"number":return Number.isFinite(e)?e.toString():"None";case"boolean":return e?"True":"False";case"undefined":return"None";case"object":return e===null?"None":Array.isArray(e)?`[${e.map(n=>C(n)).join(", ")}]`:"{"+Object.entries(e).map(([n,t])=>`${L(n)}: ${C(t)}`).join(", ")+"}";default:return"None"}}function L(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ue(e){return`r"${e.replace(/"/g,'\\"')}"`}function je(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?{name:e}:{name:e.replace(/[^A-Za-z0-9_]/g,"_").replace(/^[^A-Za-z_]+/,i=>`_${i}`).replace(/_+/g,"_")||"_field",alias:e}}function Pe(e,n,t){let i=`alias=${L(n)}`;if(e?.startsWith("Field(")){let r=e.slice(6,e.length-1).trim();return`Field(${(r?[i,r]:[i]).join(", ")})`}return e!==void 0?`Field(${i}, default=${e})`:t?`Field(${i}, default=None)`:`Field(${i}, default=...)`}function B(e,n,t,i,r){let o=t.pathNameMap.get(e);if(o)return o;let s=Ze(i,n,r),a=t.nameCounts.get(s)??0,u=a===0?s:`${s}${a+1}`;return t.nameCounts.set(s,a+1),t.pathNameMap.set(e,u),u}function Ze(e,n,t){let i=e.filter(Boolean).map(r=>r==="[item]"?"Item":(/^option\d+$/i.test(r),r)).filter(r=>r!=="");return i.length===0?P(n||t||"Model"):P(i.join(" "))}function P(e){return e.split(/[^a-zA-Z0-9]/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")||"Model"}function Oe(e){return e.replace(/[^a-zA-Z0-9]+/g,"_").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()}function I(e,n,t){let{inner:i}=pe(e);if(i.type==="object"){t(i,n);for(let[r,o]of Object.entries(i.fields))I(o,[...n,r],t);return}if(i.type==="array"){I(i.element,[...n,"[item]"],t);return}i.type==="union"&&i.options.forEach((r,o)=>I(r,[...n,`option${o}`],t))}function fe(e,n){let t={renderedPaths:new Set,warnings:n.warnings??[],exportNameOverrides:new Map(Object.entries(n.exportNameOverrides??{})),pathNameMap:new Map,nameCounts:new Map};if(e.type==="enum")return H(e,n);if(e.type!=="object")throw new Error("Root schema must be a Zod object or enum to generate TypeScript definitions.");return J(e,n.name,t,[])}function H(e,n){if(e.type!=="enum")throw new Error("Root schema must be an enum to generate TypeScript enum type.");let t=X(n.name),r=e.values.map(o=>Z(o)).join(" | ");return`export type ${t} = ${r};`}function J(e,n,t,i){if(e.type!=="object")throw new Error(`Cannot render non-object node as interface "${n}"`);let r=U(i.join(".")||n,n,t,i),o=[];for(let[d,p]of Object.entries(e.fields)){let{inner:v}=Q(p);if(v.type==="object"){let h=[...i,d],g=h.join(".");if(!t.renderedPaths.has(g)){t.renderedPaths.add(g);let f=U(h.join("."),d,t,h,r);o.push(J(v,f,t,h))}}else z(p,[...i,d],(h,g)=>{let f=g.join(".");if(t.renderedPaths.has(f))return;t.renderedPaths.add(f);let y=U(f,g[g.length-1]??"Model",t,g,r);o.push(J(h,y,t,g))})}let s=[];for(let[d,p]of Object.entries(e.fields))s.push(_e(d,p,t,[...i,d],r));let a=d=>d.length===0?"":`  ${d}`,u=[];for(let d of s.length?s:[])u.push(a(d));let c=u.length>0?` {
${u.join(`
`)}
}`:" {}",l=`export interface ${r}${c}`;return[...o,l].join(`

`)}function _e(e,n,t,i,r){let{typeAnnotation:o,isOptional:s}=K(n,t,i,r,!0),a=s?"?":"";return`${Me(e)}${a}: ${o};`}function K(e,n,t,i,r){let{inner:o,optional:s,nullable:a,nullish:u}=Q(e),c=Re(o,n,t,i),l=c,m=!1;return r?u?(m=!0,l=`${c} | null`):s&&a?(m=!0,l=`${c} | null`):s?(m=!0,l=c):a&&(l=`${c} | null`):u?l=`${c} | null | undefined`:s&&a?l=`${c} | null | undefined`:s?l=`${c} | undefined`:a&&(l=`${c} | null`),{typeAnnotation:l,isOptional:m}}function Re(e,n,t,i){switch(e.type){case"string":return"string";case"number":case"int":return"number";case"boolean":return"boolean";case"date":return"Date";case"datetime":return"string";case"uuid":return"string";case"enum":return e.values.map(o=>Z(o)).join(" | ");case"literal":return Z(e.value);case"array":{let r=K(e.element,n,[...t,"[item]"],i,!1);return`${r.typeAnnotation.includes(" | ")?`(${r.typeAnnotation})`:r.typeAnnotation}[]`}case"union":return e.options.map((o,s)=>K(o,n,[...t,`option${s}`],i,!1)).map(o=>o.typeAnnotation).join(" | ");case"object":{let r=t.join(".");return n.exportNameOverrides.get(r)??U(t.join("."),t[t.length-1]??i,n,t,i)}case"any":return"any";case"unknown":return"unknown";case"reference":return e.name;default:return"any"}}function Q(e){let n=e,t=!1,i=!1,r=!1;for(;;){if(n.type==="optional"){t=!0,n=n.inner;continue}if(n.type==="nullish"){r=!0,t=!0,i=!0,n=n.inner;continue}if(n.type==="nullable"){i=!0,n=n.inner;continue}if(n.type==="default"){n=n.inner;continue}break}return{inner:n,optional:t,nullable:i,nullish:r}}function Z(e){switch(typeof e){case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)?e.toString():"null";case"boolean":return e?"true":"false";case"undefined":return"undefined";case"object":return e===null?"null":Array.isArray(e)?`[${e.map(n=>Z(n)).join(", ")}]`:"{ "+Object.entries(e).map(([n,t])=>`${JSON.stringify(n)}: ${Z(t)}`).join(", ")+" }";default:return"any"}}function X(e){return e.split(/[^a-zA-Z0-9]/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")||"Model"}function Me(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function U(e,n,t,i,r){let o=t.exportNameOverrides.get(e);if(o)return t.pathNameMap.set(e,o),o;let s=t.pathNameMap.get(e);if(s)return s;let a=Ae(i,n,r),u=t.nameCounts.get(a)??0,c=u===0?a:`${a}${u+1}`;return t.nameCounts.set(a,u+1),t.pathNameMap.set(e,c),c}function Ae(e,n,t){let i=e.filter(Boolean).map(r=>r==="[item]"?"Item":(/^option\d+$/i.test(r),r)).filter(r=>r!=="");return i.length===0?X(n||t||"Model"):X(i.join(" "))}function z(e,n,t){let{inner:i}=Q(e);if(i.type==="object"){t(i,n);for(let[r,o]of Object.entries(i.fields))z(o,[...n,r],t);return}if(i.type==="array"){z(i.element,[...n,"[item]"],t);return}i.type==="union"&&i.options.forEach((r,o)=>z(r,[...n,`option${o}`],t))}function Y(e,n=[]){let t=[];return{node:x(e,n,t),warnings:t}}function x(e,n,t){let i=Le(e);if(!i||typeof i!="object")throw new Error("Invalid Zod schema definition");let r=i,o=Be(r);switch(o){case"optional":case"ZodOptional":{let s=r.innerType;return{type:"optional",inner:x(s,n,t)}}case"nullable":case"ZodNullable":{let s=r.innerType;return{type:"nullable",inner:x(s,n,t)}}case"nullish":case"ZodNullish":{let s=r.innerType;return{type:"nullish",inner:x(s,n,t)}}case"default":case"ZodDefault":{let s=r.innerType;return{type:"default",defaultValue:typeof r.defaultValue=="function"?r.defaultValue():r.defaultValue,inner:x(s,n,t)}}case"effects":case"ZodEffects":{let s=r.effect?.type??r.effects?.[0]?.type;t.push({code:"unsupported_effect",path:n,message:`Encountered Zod effect${s?` "${s}"`:""}; using base schema shape.`});let a=r.schema??r.innerType;return x(a,n,t)}case"pipe":{t.push({code:"unsupported_effect",path:n,message:"Encountered Zod pipeline; using input schema shape."});let s=r.in??r.schema;return x(s,n,t)}}switch(o){case"string":case"ZodString":{let{constraints:s,inferredType:a}=Ue(r);return a==="uuid"?{type:"uuid"}:a==="date"?{type:"date"}:a==="datetime"?{type:"datetime"}:s?{type:"string",constraints:s}:{type:"string"}}case"number":case"ZodNumber":{let{constraints:s,isInt:a}=ze(r);return a?s?{type:"int",constraints:s}:{type:"int"}:s?{type:"number",constraints:s}:{type:"number"}}case"boolean":case"ZodBoolean":return{type:"boolean"};case"date":case"ZodDate":return{type:"date"};case"uuid":return{type:"uuid"};case"enum":case"ZodEnum":return{type:"enum",values:r.values??(r.entries?Object.values(r.entries):void 0)??[]};case"literal":case"ZodLiteral":{let s="value"in r?r.value:void 0,a="values"in r&&Array.isArray(r.values)?r.values[0]:void 0,u="values"in r&&r.values instanceof Set?r.values.values().next().value:void 0;return{type:"literal",value:s??a??u}}case"null":case"ZodNull":return{type:"literal",value:null};case"object":case"ZodObject":{let s=r.shape,a=typeof s=="function"?s():s,u={};for(let[c,l]of Object.entries(a))u[c]=x(l,[...n,c],t);return{type:"object",fields:u}}case"array":case"ZodArray":{let s=r.element??(r.type!=="array"?r.type:void 0)??r.elementType??r.items;if(!s)throw new Error("Array schema missing element type");return{type:"array",element:x(s,[...n,"[element]"],t)}}case"union":case"ZodUnion":return{type:"union",options:(r.options||[]).map((a,u)=>x(a,[...n,`option${u}`],t))};case"ZodDiscriminatedUnion":{let s=r.options??r.optionsMap;return{type:"union",options:(s?Array.from(s.values()):[]).map((u,c)=>x(u,[...n,`option${c}`],t))}}case"any":case"ZodAny":return{type:"any"};case"unknown":case"ZodUnknown":return{type:"unknown"};default:return t.push({code:"unknown_type",path:n,message:`Unknown or unsupported Zod schema type "${String(o)}"; defaulting to 'any'.`}),{type:"any"}}}function Ie(e){return typeof e=="object"&&e!==null&&"_zod"in e}function Le(e){return Ie(e)?e._zod.def:e._def}function Be(e){let n=typeof e.type=="string"?e.type:void 0;if(n)return n;let t=typeof e.typeName=="string"?e.typeName:typeof e.typeName=="symbol"?e.typeName.description:void 0;if(t)return t.startsWith("Symbol(")&&t.endsWith(")")?t.slice(7,-1):t}function Ue(e){let n=e.checks||[],t={},i;for(let o of n){let s=De(o);if(s)switch(s.kind){case"min":t.minLength=s.value;break;case"max":t.maxLength=s.value;break;case"length":t.length=s.value;break;case"regex":t.regex=s.regex;break;case"uuid":i="uuid";break;case"datetime":i="datetime";break;case"date":i="date";break}}let r={};return Object.keys(t).length>0&&(r.constraints=t),i!==void 0&&(r.inferredType=i),r}function ze(e){let n=e.checks||[],t={},i=!1;for(let o of n){let s=We(o);if(s)switch(s.kind){case"min":t.min={value:s.value,inclusive:s.inclusive??!0},t.min.value===0&&t.min.inclusive===!1&&(t.positive=!0),t.min.value===0&&t.min.inclusive===!0&&(t.nonnegative=!0);break;case"max":t.max={value:s.value,inclusive:s.inclusive??!0};break;case"int":i=!0;break}}let r={isInt:i};return Object.keys(t).length>0&&(r.constraints=t),r}function De(e){if(!e||typeof e!="object")return null;if("kind"in e){let i=e;switch(i.kind){case"min":return{kind:"min",value:i.value};case"max":return{kind:"max",value:i.value};case"length":return{kind:"length",value:i.value};case"regex":return{kind:"regex",regex:i.regex};case"uuid":return{kind:"uuid"};case"datetime":return{kind:"datetime"};case"date":return{kind:"date"}}}let n=e._zod?.def??e.def;if(!n)return null;switch(n.check){case"min_length":return{kind:"min",value:n.minimum};case"max_length":return{kind:"max",value:n.maximum};case"length_equals":return{kind:"length",value:n.length};case"string_format":{let i=n.format;return i==="regex"&&n.pattern?{kind:"regex",regex:n.pattern}:i==="uuid"?{kind:"uuid"}:i==="datetime"?{kind:"datetime"}:i==="date"?{kind:"date"}:null}default:return null}}function We(e){if(!e||typeof e!="object")return null;if("kind"in e){let r=e;switch(r.kind){case"min":{let o={kind:"min",value:r.value};return r.inclusive!==void 0&&(o.inclusive=r.inclusive),o}case"max":{let o={kind:"max",value:r.value};return r.inclusive!==void 0&&(o.inclusive=r.inclusive),o}case"int":return{kind:"int"};case"positive":return{kind:"min",value:0,inclusive:!1};case"nonnegative":return{kind:"min",value:0,inclusive:!0}}}let n=e._zod?.def,t=e.def,i=n??t??void 0;if(i)switch(i.check){case"greater_than":return{kind:"min",value:i.value,inclusive:i.inclusive};case"less_than":return{kind:"max",value:i.value,inclusive:i.inclusive};case"number_format":{let o=i.format;if(o==="int"||o==="safeint")return{kind:"int"};break}}return e.isInt===!0?{kind:"int"}:null}import{pathToFileURL as Ve}from"node:url";import S from"node:path";import ee from"node:fs/promises";import N from"typescript";var k=class extends Error{constructor(n){super(n),this.name="SchemaLoadError"}};async function ne(e){let n=S.resolve(e.file);e.registerTsLoader&&await qe();let{warnings:t,dependencies:i}=await Je(n,{...e.tsconfigPath!==void 0&&{tsconfigPath:e.tsconfigPath},...e.allowUnresolved!==void 0&&{allowUnresolved:e.allowUnresolved}}),r;try{r=await import(Ve(n).href)}catch(s){let a=s instanceof Error?s.message:String(s);throw new k(`Failed to import schema module "${n}": ${a}`)}if(!(e.exportName in r)){let s=Object.keys(r).filter(a=>a!=="default");throw new k(`Export "${e.exportName}" not found in "${n}". Available exports: ${s.join(", ")||"(none)"}`)}let o=r[e.exportName];if(!Ge(o))throw new k(`Export "${e.exportName}" in "${n}" is not a Zod schema.`);return{schema:o,warnings:t,dependencies:i}}var O=null;async function qe(){if(O){await O;return}O=import("tsx/esm").catch(e=>{O=null;let n=e instanceof Error?e.message:String(e);throw new k(`Failed to register TypeScript loader (tsx). Install "tsx" as a dependency or precompile schemas. ${n}`)}),await O}function Ge(e){return!e||typeof e!="object"?!1:"_def"in e||"_zod"in e}async function Je(e,n){let t=new Set,i=[],r=[S.resolve(e)],o=n.tsconfigPath?await Ke(n.tsconfigPath):void 0;for(;r.length;){let s=r.pop();if(!s||t.has(s))continue;t.add(s);let a;try{a=await ee.readFile(s,"utf8")}catch{continue}let u=S.dirname(s),l=N.createSourceFile(s,a,N.ScriptTarget.Latest,!0).statements.filter(N.isImportDeclaration);for(let m of l){if(!m.moduleSpecifier||!N.isStringLiteral(m.moduleSpecifier))continue;let d=m.moduleSpecifier.text,p=await Xe(d,u,o);if(p!==null){if(!p){if(n.allowUnresolved){i.push(`Unresolved import "${d}" from ${s}`);continue}throw new k(`Failed to resolve import "${d}" from ${s}`)}r.push(p)}}}return{warnings:i,dependencies:Array.from(t)}}async function Ke(e){try{let n=await ee.readFile(e,"utf8"),t=N.parseConfigFileTextToJson(e,n);return t.error?void 0:N.parseJsonConfigFileContent(t.config,N.sys,S.dirname(e))}catch{return}}async function Xe(e,n,t){if(e.startsWith(".")||e.startsWith("/"))return await ge(S.resolve(n,e));if(t?.options.paths&&t.options.baseUrl){let i=He(e,t.options.baseUrl,t.options.paths);if(i){let r=await ge(i);if(r)return r}}return null}function He(e,n,t){for(let[i,r]of Object.entries(t)){let o=i.indexOf("*");if(o===-1){if(i===e&&r.length>0){let u=r[0];if(u)return S.resolve(n,u)}continue}let s=i.slice(0,o),a=i.slice(o+1);if(e.startsWith(s)&&e.endsWith(a)&&r.length>0){let u=r[0];if(u){let c=e.slice(s.length,e.length-a.length),l=u.replace("*",c);return S.resolve(n,l)}}}return null}async function ge(e){let n=["",".ts",".tsx",".mts",".cts",".js",".mjs",".cjs"],t=new Set;for(let r of n)t.add(e.endsWith(r)?e:e+r);let i=S.parse(e);if([".js",".mjs",".cjs"].includes(i.ext)){let r=S.join(i.dir,i.name);for(let o of n)t.add(r+o)}for(let r of t)try{if((await ee.stat(r)).isFile())return r}catch{continue}return null}import Qe from"node:fs/promises";import D from"node:path";import{pathToFileURL as Ye}from"node:url";async function te(e){let{sourceDir:n,extensions:t=[".ts",".tsx",".js",".mjs"],ignore:i=["node_modules",".git","dist","build","coverage"],registerTsLoader:r=!0,tsconfigPath:o,allowUnresolved:s=!1,exportNamePattern:a}=e,u=D.resolve(n),c=[],l=[],m=[];r&&await rn();let d=a!==void 0?sn(a):void 0,p=await en(u,t,i),v=new Set;for(let h of p)if(!v.has(h)){v.add(h);try{let g={registerTsLoader:!1,allowUnresolved:s};o!==void 0&&(g.tsconfigPath=o);let f=await nn(h,g),y=d!==void 0?f.filter(b=>d.test(b.exportName)):f;if(y.length===0){m.push(h);continue}c.push(...y)}catch(g){let f=g instanceof Error?g.message:String(g);if(s){l.push(`Failed to process ${h}: ${f}`),m.push(h);continue}throw g instanceof Error?g:new Error(f)}}return{schemas:c,warnings:l,skippedFiles:m}}async function en(e,n,t){let i=[],r=new Set(n);async function o(s){let a=await Qe.readdir(s,{withFileTypes:!0});for(let u of a){let c=D.join(s,u.name);if(!t.some(l=>u.name.includes(l))){if(u.isDirectory())await o(c);else if(u.isFile()){let l=D.extname(u.name);r.has(l)&&i.push(c)}}}}return await o(e),i}async function nn(e,n){let t=D.resolve(e),i=await import(Ye(t).href),r=[];for(let[o,s]of Object.entries(i))o!=="default"&&tn(s)&&r.push({file:t,exportName:o,schema:s});return r}function tn(e){return!e||typeof e!="object"?!1:"_def"in e||"_zod"in e}var _=null;async function rn(){if(_){await _;return}_=import("tsx/esm").catch(e=>{_=null;let n=e instanceof Error?e.message:String(e);throw new Error(`Failed to register TypeScript loader (tsx). Install "tsx" as a dependency. ${n}`)}),await _}function sn(e){let n=e.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`)}import F from"node:fs/promises";import w from"node:path";async function re(e){let{outDir:n,target:t,preserveStructure:i=!0,skipEmptyFiles:r=!0,generateInitFiles:o=!1,...s}=e,a=w.resolve(n);await F.mkdir(a,{recursive:!0});let u=await te(s),c=[...u.warnings],l=[...u.skippedFiles],m=[],d=new Map,p=new Map;for(let f of u.schemas){let y=f.exportName;if(!d.has(y))d.set(y,f),p.set(y,f.file);else{let b=p.get(y);if(!b){d.set(y,f),p.set(y,f.file);continue}if(w.basename(f.file)==="index.ts"||w.basename(f.file)==="index.js")continue;(w.basename(b)==="index.ts"||w.basename(b)==="index.js")&&(d.set(y,f),p.set(y,f.file))}}let v=new Map;for(let f of d.values()){let y=v.get(f.file)||[];y.push(f),v.set(f.file,y)}let h=new Map,g=new Set;for(let[f,y]of v.entries()){if(y.length===0)continue;let b=w.relative(s.sourceDir,f),$;if(i){let j=w.dirname(b),W=w.basename(f,w.extname(f));$=w.join(a,j,W)}else $=a;for(let j of y){let W=t==="all"?["pydantic","typescript"]:[t];for(let V of W)try{let T={preserveStructure:i,outputBasePath:$,sourceFile:f,outDir:a,usedNames:h};e.enumStyle!==void 0&&(T.enumStyle=e.enumStyle),e.enumBaseType!==void 0&&(T.enumBaseType=e.enumBaseType);let M=on(j,V,T),q=M.path,A=w.dirname(q);if(!g.has(A)&&(await F.mkdir(A,{recursive:!0}),g.add(A),o&&V==="pydantic")){let ve=w.join(A,"__init__.py");await F.writeFile(ve,"","utf8")}await F.writeFile(q,M.content,"utf8"),m.push({path:q,sourceFile:f,exportName:j.exportName,target:V})}catch(T){let M=T instanceof Error?T.message:String(T);c.push(`Failed to convert ${j.exportName} from ${f}: ${M}`)}}}if(o&&(t==="pydantic"||t==="all")){let f=w.join(a,"__init__.py");try{await F.access(f)}catch{await F.writeFile(f,"","utf8")}}return{files:m,warnings:c,skippedFiles:l}}function on(e,n,t){let{schema:i,exportName:r}=e,{preserveStructure:o,outputBasePath:s,outDir:a,usedNames:u,enumStyle:c,enumBaseType:l}=t,m=an(r),d=un(r),p=n==="pydantic"?".py":".d.ts",v=o?w.dirname(s):a,h=`${d}${p}`,g=w.join(v,h),f=u.get(g)??0;f>0&&(h=`${d}_${f}${p}`,g=w.join(v,h)),u.set(g,f+1);let y;o?y=w.join(w.dirname(s),h):y=w.join(a,h);let b={name:m,sourceModule:e.file};c!==void 0&&(b.enumStyle=c),l!==void 0&&(b.enumBaseType=l);let $=n==="pydantic"?ie(i,b):se(i,b);return{path:y,content:$}}function an(e){return e.split(/[^a-zA-Z0-9]/g).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")||"Model"}function un(e){return e.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase().replace(/^_+|_+$/g,"")}function ie(e,n){let{node:t,warnings:i}=Y(e),r={name:n.name,warnings:i};if(n.sourceModule!==void 0&&(r.sourceModule=n.sourceModule),n.enumStyle!==void 0&&(r.enumStyle=n.enumStyle),n.enumBaseType!==void 0&&(r.enumBaseType=n.enumBaseType),t.type==="enum")return ce(t,r);if(t.type!=="object")throw new Error("Root schema must be a Zod object or enum to generate Pydantic models.");return le(t,r)}function se(e,n){let{node:t,warnings:i}=Y(e),r={name:n.name,warnings:i};if(n.sourceModule!==void 0&&(r.sourceModule=n.sourceModule),n.exportNameOverrides!==void 0&&(r.exportNameOverrides=n.exportNameOverrides),t.type==="enum")return H(t,r);if(t.type!=="object")throw new Error("Root schema must be a Zod object or enum to generate TypeScript definitions.");return fe(t,r)}function he(e){let{schema:n,target:t,out:i,...r}=e,o=[],s=r.name,a=i?E.resolve(i):void 0,u=l=>l==="pydantic"?".py":".d.ts";if(t==="all"){if(a&&E.extname(a))return Promise.reject(new Error('When target is "all", --out must be a directory or omitted. Received a file path with extension.'));let l=a??process.cwd();o.push({target:"pydantic",path:E.join(l,`${s}${u("pydantic")}`)},{target:"typescript",path:E.join(l,`${s}${u("typescript")}`)})}else a?E.extname(a)?o.push({target:t,path:a}):o.push({target:t,path:`${a}${u(t)}`}):o.push({target:t,path:E.join(process.cwd(),`${s}${u(t)}`)});let c=o.map(async l=>{let m=l.target==="pydantic"?ie(n,r):se(n,r);return await ye.mkdir(E.dirname(l.path),{recursive:!0}),await ye.writeFile(l.path,m,"utf8"),{path:l.path,target:l.target}});return Promise.all(c)}var we=`
Usage:
  schemabridge convert zod <input-file> --export <schema-name> [--to pydantic|typescript|all] [--out <path>] [--allow-unresolved] [--enum-style enum|literal] [--enum-base-type str|int]
  schemabridge convert folder <source-dir> --out <output-dir> [--to pydantic|typescript|all] [--flat] [--init] [--export-pattern <pattern>] [--allow-unresolved] [--enum-style enum|literal] [--enum-base-type str|int]

Commands:
  convert zod    Convert a single Zod schema from a file
  convert folder Convert all Zod schemas in a folder recursively

Examples:
  # Convert single schema
  schemabridge convert zod input.ts --export enrichedTransactionSchema --to pydantic --out model.py
  
  # Convert standalone enum
  schemabridge convert zod enums.ts --export statusEnum --to pydantic --out status.py
  
  # Convert with enum options
  schemabridge convert zod input.ts --export schema --to pydantic --out model.py --enum-style literal --enum-base-type str
  
  # Convert all schemas in a folder (preserves structure)
  schemabridge convert folder ./src/schemas --out ./generated --to pydantic
  
  # Convert all schemas to flat output structure
  schemabridge convert folder ./src/schemas --out ./generated --to pydantic --flat
  
  # Generate __init__.py files for Python packages
  schemabridge convert folder ./src/schemas --out ./generated --to pydantic --init

  # Only convert exports whose names match a pattern (e.g. *Schema)
  schemabridge convert folder ./src/schemas --out ./generated --to pydantic --export-pattern '*Schema'
`.trim();async function cn(e=oe.argv.slice(2)){try{let n=dn(e);if(n.mode==="folder"){let s=await re({sourceDir:n.sourceDir,outDir:n.out,target:n.target,preserveStructure:!n.flat,generateInitFiles:n.generateInitFiles,registerTsLoader:!0,allowUnresolved:n.allowUnresolved,...n.exportNamePattern!==void 0&&{exportNamePattern:n.exportNamePattern},...n.tsconfigPath!==void 0&&{tsconfigPath:n.tsconfigPath},...n.enumStyle!==void 0&&{enumStyle:n.enumStyle},...n.enumBaseType!==void 0&&{enumBaseType:n.enumBaseType}});for(let a of s.warnings)console.warn(`Warning: ${a}`);s.skippedFiles.length>0&&console.warn(`Skipped ${s.skippedFiles.length} files (no schemas found)`);for(let a of s.files)console.log(`Wrote ${a.target}: ${a.path}`);return console.log(`
Converted ${s.files.length} schema(s) successfully.`),0}let{schema:t,warnings:i}=await ne({file:n.inputFile,exportName:n.exportName,registerTsLoader:!0,...n.tsconfigPath!==void 0&&{tsconfigPath:n.tsconfigPath},allowUnresolved:n.allowUnresolved});for(let s of i)console.warn(`Warning: ${s}`);let r={schema:t,name:n.exportName,target:n.target,allowUnresolved:n.allowUnresolved,sourceModule:n.inputFile};n.out!==void 0&&(r.out=n.out),n.enumStyle!==void 0&&(r.enumStyle=n.enumStyle),n.enumBaseType!==void 0&&(r.enumBaseType=n.enumBaseType);let o=await he(r);for(let s of o)console.log(`Wrote ${s.target}: ${s.path}`);return 0}catch(n){let t=n instanceof k||n instanceof Error?n.message:String(n);return console.error(`Error: ${t}`),console.error(we),1}}function dn(e){if(e.length===0||e.includes("--help")||e.includes("-h"))throw new Error(we);let[n,t,...i]=e;if(n!=="convert")throw new Error("Expected command: convert zod|folder ...");if(t==="folder")return mn(i);if(t!=="zod")throw new Error("Expected command: convert zod <input-file> or convert folder <source-dir>");return pn(i)}function pn(e){if(e.length===0)throw new Error("Missing <input-file>");let n=e[0];if(!n)throw new Error("Missing <input-file>");let t,i="pydantic",r,o=!1,s,a,u;for(let l=1;l<e.length;l++){let m=e[l];if(m)switch(m){case"--export":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--export requires a value: --export <schema-name>");t=d;break}case"--to":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--to requires a value: --to pydantic|typescript|all");if(d!=="pydantic"&&d!=="typescript"&&d!=="all")throw new Error('Invalid --to value. Expected "pydantic", "typescript", or "all".');i=d;break}case"--out":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--out requires a value: --out <path>");r=d;break}case"--allow-unresolved":o=!0;break;case"--tsconfig":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--tsconfig requires a value: --tsconfig <path>");s=d;break}case"--enum-style":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--enum-style requires a value: --enum-style enum|literal");if(d!=="enum"&&d!=="literal")throw new Error('Invalid --enum-style value. Expected "enum" or "literal".');a=d;break}case"--enum-base-type":{let d=e[++l];if(!d||d.startsWith("-"))throw new Error("--enum-base-type requires a value: --enum-base-type str|int");if(d!=="str"&&d!=="int")throw new Error('Invalid --enum-base-type value. Expected "str" or "int".');u=d;break}default:throw m.startsWith("-")?new Error(`Unknown option: ${m}`):new Error(`Unexpected argument: ${m}`)}}if(!t)throw new Error("Missing required --export <schema-name>");let c={mode:"file",inputFile:R.resolve(n),exportName:t,target:i,allowUnresolved:o,...s!==void 0&&{tsconfigPath:s},...a!==void 0&&{enumStyle:a},...u!==void 0&&{enumBaseType:u}};return r!==void 0&&(c.out=r),c}function mn(e){if(e.length===0)throw new Error("Missing <source-dir>");let n=e[0];if(!n)throw new Error("Missing <source-dir>");let t="pydantic",i,r=!1,o=!1,s=!1,a,u,c,l;for(let m=1;m<e.length;m++){let d=e[m];if(d)switch(d){case"--to":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--to requires a value: --to pydantic|typescript|all");if(p!=="pydantic"&&p!=="typescript"&&p!=="all")throw new Error('Invalid --to value. Expected "pydantic", "typescript", or "all".');t=p;break}case"--out":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--out requires a value: --out <output-dir>");i=p;break}case"--allow-unresolved":r=!0;break;case"--flat":o=!0;break;case"--init":s=!0;break;case"--export-pattern":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--export-pattern requires a value, e.g. --export-pattern '*Schema'");a=p;break}case"--tsconfig":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--tsconfig requires a value: --tsconfig <path>");u=p;break}case"--enum-style":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--enum-style requires a value: --enum-style enum|literal");if(p!=="enum"&&p!=="literal")throw new Error('Invalid --enum-style value. Expected "enum" or "literal".');c=p;break}case"--enum-base-type":{let p=e[++m];if(!p||p.startsWith("-"))throw new Error("--enum-base-type requires a value: --enum-base-type str|int");if(p!=="str"&&p!=="int")throw new Error('Invalid --enum-base-type value. Expected "str" or "int".');l=p;break}default:throw d.startsWith("-")?new Error(`Unknown option: ${d}`):new Error(`Unexpected argument: ${d}`)}}if(!i)throw new Error("Missing required --out <output-dir>");return{mode:"folder",sourceDir:R.resolve(n),out:R.resolve(i),target:t,allowUnresolved:r,flat:o,generateInitFiles:s,...a!==void 0&&{exportNamePattern:a},...u!==void 0&&{tsconfigPath:u},...c!==void 0&&{enumStyle:c},...l!==void 0&&{enumBaseType:l}}}R.resolve(ln(import.meta.url))===R.resolve(oe.argv[1]??"")&&cn().then(e=>{e!==0&&oe.exit(e)});export{cn as runCLI};
