UNPKG

@hey-api/openapi-ts

Version:

🌀 OpenAPI to TypeScript code generator. Generate API clients, SDKs, validators, and more.

2 lines 340 kB
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`@hey-api/codegen-core`),u=require(`ansi-colors`);u=c(u);let d=require(`node:fs`);d=c(d);let f=require(`node:path`);f=c(f);let p=require(`node:url`),m=require(`typescript`);m=c(m);let h=require(`node:os`),g=require(`semver`);g=c(g);let _=require(`@hey-api/json-schema-ref-parser`);const ee=(0,p.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),te=f.default.dirname(ee),ne=()=>{let e=te;for(;e!==f.default.dirname(e);){let t=d.default.readdirSync(e).filter(e=>e===`package.json`);if(t[0]){let n=f.default.join(e,t[0]);return JSON.parse(d.default.readFileSync(n,{encoding:`utf8`}))}e=f.default.dirname(e)}},re=()=>{let e=ne(),t={bugs:{url:``},name:``,version:``};return e&&typeof e==`object`&&(`name`in e&&typeof e.name==`string`&&(t.name=e.name),`version`in e&&typeof e.version==`string`&&(t.version=e.version),`bugs`in e&&e.bugs&&typeof e.bugs==`object`&&`url`in e.bugs&&typeof e.bugs.url==`string`&&(t.bugs.url=e.bugs.url,t.bugs.url&&!t.bugs.url.endsWith(`/`)&&(t.bugs.url+=`/`))),t},ie=e=>{if(e===null)return null;if(e){let t=f.default.isAbsolute(e)?e:f.default.resolve(te,e);return d.default.existsSync(t)?t:null}let t=te;for(;t!==f.default.dirname(t);){let e=d.default.readdirSync(t).filter(e=>e.startsWith(`tsconfig`)&&e.endsWith(`.json`)).sort(e=>e===`tsconfig.json`?-1:1);if(e[0])return f.default.join(t,e[0]);t=f.default.dirname(t)}return null},ae=e=>{if(!e)return null;let t=m.default.readConfigFile(e,m.default.sys.readFile);if(t.error)throw Error(`Couldn't read tsconfig from path: ${e}`);return m.default.parseJsonConfigFileContent(t.config,m.default.sys,f.default.dirname(e))},oe=e=>{d.default.existsSync(e)||d.default.mkdirSync(e,{recursive:!0})};var se=class extends Error{constructor(e){super(e),this.name=`ConfigError`}},ce=class extends Error{errors;constructor(e){super(`Found ${e.length} configuration ${e.length===1?`error`:`errors`}.`),this.name=`ConfigValidationError`,this.errors=e}},le=class extends Error{originalError;constructor(e,t){super(e),this.name=`JobError`,this.originalError=t}},ue=class extends Error{args;event;pluginName;constructor({args:e,error:t,event:n,name:r,pluginName:i}){let a=t instanceof Error?t.message:`Unknown error`;super(a),this.args=e,this.cause=t.cause,this.event=n,this.name=r||t.name,this.pluginName=i,this.stack=t.stack}};const de=(e,t)=>{if(e instanceof se||e instanceof ce)return;e instanceof le&&(e=e.originalError.error);let n=`openapi-ts-error-${Date.now()}.log`,r=f.default.resolve(process.cwd(),t);oe(r);let i=f.default.resolve(r,n),a=`[${new Date().toISOString()}] `;e instanceof ue&&(a+=`${e.name} during event "${e.event}"\n`,e.pluginName&&(a+=`Plugin: ${e.pluginName}\n`),a+=`Arguments: ${JSON.stringify(e.args,null,2)}\n\n`);let o=e instanceof Error?e.message:String(e),s=e instanceof Error?e.stack:void 0;return a+=`Error: ${o}\n`,s&&(a+=`Stack:\n${s}\n`),d.default.writeFileSync(i,a),i},fe=async e=>{let t=re();if(!t.bugs.url)return;e instanceof le&&(e=e.originalError.error);let n=``;e instanceof ue&&(e.pluginName&&(n+=`**Plugin**: \`${e.pluginName}\`\n`),n+=`**Event**: \`${e.event}\`\n`,n+=`**Arguments**:\n\`\`\`ts\n${JSON.stringify(e.args,null,2)}\n\`\`\`\n\n`);let r=e instanceof Error?e.message:String(e),i=e instanceof Error?e.stack:void 0;n+=`**Error**: \`${r}\`\n`,i&&(n+=`\n**Stack Trace**:\n\`\`\`\n${i}\n\`\`\``);let a=new URLSearchParams({body:n,labels:`bug 🔥`,title:`Crash Report`}),o=`${t.bugs.url}new?${a.toString()}`,s=(await import(`open`)).default;await s(o)},pe=({error:e,logPath:t})=>{if(e instanceof ce&&e.errors.length){let t=new Map;for(let{error:n,jobIndex:r}of e.errors)t.has(r)||t.set(r,[]),t.get(r).push(n);for(let[e,n]of t.entries()){let t=u.default.gray(`[Job ${e+1}] `),r=n.length,i=u.default.red(`Found ${r} configuration ${r===1?`error`:`errors`}:`);console.error(`${t}❗️ ${i}`),n.forEach((e,n)=>{let r=` [${n+1}] `,i=u.default.red(r);console.error(`${t}${i}${u.default.white(e.message)}`)})}}else{let t=u.default.gray(`[root] `);e instanceof le&&(t=u.default.gray(`[Job ${e.originalError.jobIndex+1}] `),e=e.originalError.error);let n=u.default.red(`Failed with the message:`);console.error(`${t}❌ ${n}`);let r=u.default.red(` `);console.error(`${t}${r}${typeof e==`string`?e:e instanceof Error?e.message:`Unknown error`}`)}if(t){let e=u.default.gray(`[root] `);console.error(`${e}${u.default.cyan(`📄 Crash log saved to:`)} ${u.default.gray(t)}`)}},me=async({error:e,isInteractive:t})=>!t||e instanceof se||e instanceof ce?!1:new Promise(e=>{let t=u.default.gray(`[root] `);console.log(`${t}${u.default.yellow(`📢 Open a GitHub issue with crash details? (y/N):`)}`),process.stdin.setEncoding(`utf8`),process.stdin.once(`data`,t=>{e(t.trim().toLowerCase()===`y`)})}),he=/^([\w-]+)\/([\w-]+)(?:\?([\w=&.-]*))?$/,ge=`https://get.heyapi.dev`,_e=(e,t,n)=>`${ge}/${e}/${t}${n?`?${n}`:``}`,ve=e=>{let t=e.organization,n=e.project,r;if(e.path){let i=e.path.match(he);if(!i)throw Error(`Invalid Hey API shorthand format. Expected "organization/project?queryParams" or "organization/project", received: ${e.path}`);t=i[1],n=i[2],r=i[3]}if(!t)throw Error(`The Hey API organization cannot be empty.`);if(!n)throw Error(`The Hey API project cannot be empty.`);return{organization:t,project:n,queryParams:r}},ye=e=>{let t=ve(e);return{path:_e(t.organization,t.project,t.queryParams),registry:`hey-api`}},be=/^(@([\w-]+)\/([\w\-.]+)#)?([\w-]+)$/,xe=e=>`https://dash.readme.com/api/v1/api-registry/${e}`,Se=`readme`,Ce=e=>{let t=e.match(be);if(!t)throw Error(`Invalid ReadMe shorthand format. Expected "${Se}:@organization/project#uuid" or "${Se}:uuid", received: ${Se}:${e}`);let[,,n,r,i]=t;if(!i)throw Error(`The ReadMe UUID cannot be empty.`);return{organization:n,project:r,uuid:i}},we=e=>{let t=Ce(e.slice(`${Se}:`.length));return{...t,path:xe(t.uuid),registry:`readme`}},Te=/^(@[\w-]+)\/([\w.-]+)$/,Ee=(e,t)=>`https://registry.scalar.com/${e}/apis/${t}/latest?format=json`,De=`scalar`,Oe=e=>{let t=e.match(Te);if(!t)throw Error(`Invalid Scalar shorthand format. Expected "${De}:@organization/project", received: ${De}:${e}`);let[,n,r]=t;if(!n)throw Error(`The Scalar organization cannot be empty.`);if(!r)throw Error(`The Scalar project cannot be empty.`);return{organization:n,project:r}},ke=e=>{let t=Oe(e.slice(`${De}:`.length));return{...t,path:Ee(t.organization,t.project),registry:`scalar`}},Ae=e=>{if(e.path.startsWith(`readme:`)){Object.assign(e,we(e.path));return}if(e.path.startsWith(`scalar:`)){Object.assign(e,ke(e.path));return}if(e.path.startsWith(`.`))return;if(e.path.startsWith(ge)){e.path=e.path.slice(23),Object.assign(e,ye(e));return}let t=e.path.split(`/`);if(t.length===2&&t.filter(Boolean).length===2){Object.assign(e,ye(e));return}},je={enabled:!1,interval:1e3,timeout:6e4},Me=e=>{let t={...je};return typeof e.path==`string`&&(typeof e.watch==`boolean`?t.enabled=e.watch:typeof e.watch==`number`?(t.enabled=!0,t.interval=e.watch):e.watch&&(t={...t,...e.watch})),t},Ne=e=>{let t=e.input instanceof Array?e.input:[e.input],n=[];for(let r of t){let t={path:``,watch:je};typeof r==`string`?t.path=r:r&&(r.path!==void 0||r.organization!==void 0)?(t={...t,path:ge,...r},t.watch!==void 0&&(t.watch=Me(t))):t={...t,path:r},typeof t.path==`string`&&Ae(t),e.watch!==void 0&&t.watch.enabled===je.enabled&&t.watch.interval===je.interval&&t.watch.timeout===je.timeout&&(t.watch=Me({path:t.path,watch:e.watch})),t.path&&n.push(t)}return n},Pe=e=>{let t={file:!0,level:`info`,path:process.cwd()};return typeof e?.logs==`string`?t.path=e.logs:t={...t,...e?.logs},t},Fe=(e,t)=>{let n=e||{},r=t||{};return{...n,...r}},Ie=(e,t)=>{let n=e||{},r=t||{},i={...n,...r};return typeof i.logs==`object`&&(i.logs=Fe(n.logs,r.logs)),i},Le=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e!=`function`,Re=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&r!==``&&(e[n]=r);return e},v=({defaultValue:e,mappers:t,value:n})=>{let r={...e};switch(typeof n){case`boolean`:if(t&&`boolean`in t){let e=t.boolean;r=Re(r,e(n))}break;case`function`:if(t&&`function`in t){let e=t.function;r=Re(r,e(n))}break;case`number`:if(t&&`number`in t){let e=t.number;r=Re(r,e(n))}break;case`string`:if(t&&`string`in t){let e=t.string;r=Re(r,e(n))}break;case`object`:if(Le(n))if(t&&`object`in t&&typeof t.object==`function`){let i=t.object;r=Re(r,i(n,e))}else r=Re(r,n);break}return r},ze=e=>{if(e.output instanceof Array)throw Error(`Unexpected array of outputs in user configuration. This should have been expanded already.`);let t=v({defaultValue:{clean:!0,fileName:{case:`preserve`,name:`{{name}}`,suffix:`.gen`},format:null,indexFile:!0,lint:null,path:``,preferExportAll:!1},mappers:{object:(e,t)=>({...e,fileName:v({defaultValue:{...t.fileName},mappers:{function:e=>({name:e}),string:e=>({name:e})},value:e.fileName})}),string:e=>({path:e})},value:e.output});return t.tsConfig=ae(ie(t.tsConfigPath)),t.importFileExtension===void 0&&(t.tsConfig?.options.moduleResolution===m.default.ModuleResolutionKind.NodeNext||t.tsConfig?.options.moduleResolution===m.default.ModuleResolutionKind.Node16)&&(t.importFileExtension=`.js`),t.importFileExtension&&!t.importFileExtension.startsWith(`.`)&&(t.importFileExtension=`.${t.importFileExtension}`),t},Be=e=>{let t=e?f.default.dirname(e):process.cwd();for(;t!==f.default.dirname(t);){let e=f.default.join(t,`package.json`);if(d.default.existsSync(e))try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));return{...t.dependencies,...t.devDependencies,...t.peerDependencies,...t.optionalDependencies}}catch{}let n=f.default.dirname(t);if(n===t)break;t=n}return{}},Ve=[`after`,`before`,`cursor`,`offset`,`page`,`start`],He=e=>v({defaultValue:{hooks:{},pagination:{keywords:Ve},transforms:{enums:{case:`PascalCase`,enabled:!1,mode:`root`,name:`{{name}}Enum`},propertiesRequiredByDefault:!1,readWrite:{enabled:!0,requests:{case:`preserve`,name:`{{name}}Writable`},responses:{case:`preserve`,name:`{{name}}`}}},validate_EXPERIMENTAL:!1},mappers:{object:(e,t)=>({...e,pagination:v({defaultValue:{...t.pagination},value:e.pagination}),transforms:v({defaultValue:{...t.transforms},mappers:{object:(e,t)=>({...e,enums:v({defaultValue:{...t.enums,enabled:e.enums===void 0?t.enums.enabled:!!e.enums},mappers:{boolean:e=>({enabled:e}),string:e=>({mode:e})},value:e.enums}),propertiesRequiredByDefault:e.propertiesRequiredByDefault===void 0?t.propertiesRequiredByDefault:e.propertiesRequiredByDefault,readWrite:v({defaultValue:{...t.readWrite,enabled:e.readWrite===void 0?t.readWrite.enabled:!!e.readWrite},mappers:{boolean:e=>({enabled:e}),object:(e,t)=>({...e,requests:v({defaultValue:{...t.requests},mappers:{function:e=>({name:e}),string:e=>({name:e})},value:e.requests}),responses:v({defaultValue:{...t.responses},mappers:{function:e=>({name:e}),string:e=>({name:e})},value:e.responses})})},value:e.readWrite})})},value:e.transforms}),validate_EXPERIMENTAL:e.validate_EXPERIMENTAL===!0?`warn`:e.validate_EXPERIMENTAL})},value:e.parser}),y=e=>t=>({...e,config:{...e.config,...t}}),b={boolean:e=>({enabled:e}),function:e=>({name:e}),string:e=>({name:e})},Ue=/[\p{Lu}]/u,We=/[\p{Ll}]/u,Ge=/([\p{Alpha}\p{N}_]|$)/u,Ke=/[_.:\- `\\[\]{}\\/]+/,qe=RegExp(`^${Ke.source}`),Je=RegExp(`${Ke.source}${Ge.source}`,`gu`),Ye=RegExp(`\\d+${Ge.source}`,`gu`),Xe=({case:e,string:t})=>{let n=!1,r=!1,i=!1,a=!1,o=e===`snake_case`||e===`SCREAMING_SNAKE_CASE`?`_`:`-`;for(let e=0;e<t.length;e++){let s=t[e];a=e>2?t[e-3]===o:!0;let c=e+1,l=t[c];for(Ke.lastIndex=0;l&&Ke.test(l);)c+=1,l=t[c];let u=c!==e+1;if(We.lastIndex=0,Ue.lastIndex=0,Ue.test(s)&&(n||l&&!u&&l!==`s`&&We.test(l)))t=`${t.slice(0,e)}${o}${t.slice(e)}`,e++,i=r,n=!1,r=!0;else if(r&&i&&We.test(s)&&!a&&!(s===`s`&&(!l||l.toLocaleLowerCase()!==l)))t=`${t.slice(0,e-1)}${o}${t.slice(e-1)}`,i=r,n=!0,r=!1;else{let e=s.toLocaleLowerCase(),t=s.toLocaleUpperCase();i=r,n=e===s&&t!==s,r=t===s&&e!==s}}return t},x=({case:e,stripLeadingSeparators:t=!0,value:n})=>{let r=n.trim();return r.length?!e||e===`preserve`?r:r.length===1?(Ke.lastIndex=0,Ke.test(r)?``:e===`PascalCase`||e===`SCREAMING_SNAKE_CASE`?r.toLocaleUpperCase():r.toLocaleLowerCase()):(r!==r.toLocaleLowerCase()&&(r=Xe({case:e,string:r})),(t||r[0]!==n[0])&&(r=r.replace(qe,``)),r=e===`SCREAMING_SNAKE_CASE`?r.toLocaleUpperCase():r.toLocaleLowerCase(),e===`PascalCase`&&(r=`${r.charAt(0).toLocaleUpperCase()}${r.slice(1)}`),e===`snake_case`||e===`SCREAMING_SNAKE_CASE`?(r=r.replaceAll(Je,(e,n,r)=>r===0&&!t?e:`_${n}`),r[r.length-1]===`_`&&(r=r.slice(0,r.length-1))):(Je.lastIndex=0,Ye.lastIndex=0,r=r.replaceAll(Ye,(e,t,n)=>[`_`,`-`,`.`].includes(r.charAt(n+e.length))?e:e.toLocaleUpperCase()),r=r.replaceAll(Je,(e,r,i)=>i===0&&!t&&e[0]&&n.startsWith(e[0])?e:r.toLocaleUpperCase())),r):``},S=({config:e,name:t})=>{if(typeof e.name==`function`)t=e.name(t);else if(e.name){let n=e.case===`preserve`?``:`-`;t=e.name.replace(`{{name}}`,`${n}${t}${n}`)}return x({case:e.case,value:t})},Ze=({context:e,parameter:t})=>{if(!t.pagination)return;if(t.pagination===!0)return t.schema;let n=t.schema;return n.$ref&&(n=e.resolveIrRef(n.$ref)),n.properties[t.pagination]},Qe=e=>{for(let t in e)if(e[t].required)return!0;return!1},$e=e=>e?!!(Qe(e.cookie)||Qe(e.header)||Qe(e.path)||Qe(e.query)):!1,et=({context:e,parameters:t})=>{if(t){for(let n in t.cookie){let r=t.cookie[n];if(r.pagination)return{in:r.location,name:r.pagination===!0?r.name:`${r.name}.${r.pagination}`,schema:Ze({context:e,parameter:r})}}for(let n in t.header){let r=t.header[n];if(r.pagination)return{in:r.location,name:r.pagination===!0?r.name:`${r.name}.${r.pagination}`,schema:Ze({context:e,parameter:r})}}for(let n in t.path){let r=t.path[n];if(r.pagination)return{in:r.location,name:r.pagination===!0?r.name:`${r.name}.${r.pagination}`,schema:Ze({context:e,parameter:r})}}for(let n in t.query){let r=t.query[n];if(r.pagination)return{in:r.location,name:r.pagination===!0?r.name:`${r.name}.${r.pagination}`,schema:Ze({context:e,parameter:r})}}}},C=({detectFormat:e=!0,schema:t})=>{if(!t.items)return t;let n=[],r=[];for(let i of t.items){if(!i.type&&i.items||t.type===`tuple`){n.push(i);continue}if(!i.type||i.type===`boolean`||i.type===`integer`||i.type===`null`||i.type===`number`||i.type===`string`||i.type===`unknown`||i.type===`void`){let t=i.const===void 0?``:`const-${i.const}`,a=i.format!==void 0&&e?`format-${i.format}`:``,o=[i.minLength===void 0?``:`minLength-${i.minLength}`,i.maxLength===void 0?``:`maxLength-${i.maxLength}`,i.minimum===void 0?``:`minimum-${i.minimum}`,i.maximum===void 0?``:`maximum-${i.maximum}`,i.exclusiveMinimum===void 0?``:`exclusiveMinimum-${i.exclusiveMinimum}`,i.exclusiveMaximum===void 0?``:`exclusiveMaximum-${i.exclusiveMaximum}`,i.minItems===void 0?``:`minItems-${i.minItems}`,i.maxItems===void 0?``:`maxItems-${i.maxItems}`,i.pattern===void 0?``:`pattern-${i.pattern}`].join(``),s=`${i.$ref??``}${i.type??``}${t}${a}${o}`;r.includes(s)||(r.push(s),n.push(i));continue}n.push(i)}let i={...t};if(i.items=n,i.items.length<=1&&i.type!==`array`&&i.type!==`enum`&&i.type!==`tuple`){let e=i.items[0];delete i.logicalOperator,delete i.items,i={...i,...e}}return i.type===`unknown`?{}:i},w=({items:e,logicalOperator:t=`or`,mutateSchemaOneItem:n=!1,schema:r})=>e.length?r.type===`tuple`?(r.items=e,r):e.length===1?n?(r={...r,...e[0]},r):(r.items=e,r):(r.items=e,r.logicalOperator=t,r):r,tt=e=>!!($e(e.parameters)||e.body?.required),T=({method:e,path:t})=>`${e.toUpperCase()} ${t}`,nt=({context:e,operation:t})=>{let n=t.body;if(!n||!n.pagination)return et({context:e,parameters:t.parameters});if(n.pagination===!0)return{in:`body`,name:`body`,schema:n.schema};let r=n.schema,i=r.$ref?e.resolveIrRef(r.$ref):r,a=(`schema`in i?i.schema:i)?.properties?.[n.pagination];return a?{in:`body`,name:n.pagination,schema:a}:et({context:e,parameters:t.parameters})},rt=({statusCode:e})=>{switch(e){case`1XX`:return`1XX`;case`2XX`:return`2XX`;case`3XX`:return`3XX`;case`4XX`:return`4XX`;case`5XX`:return`5XX`;case`default`:return`default`;default:return`${e[0]}XX`}},it=e=>{let t={};if(!e.responses)return t;let n={properties:{},type:`object`},r={properties:{},type:`object`},i;for(let t in e.responses){let a=e.responses[t];switch(rt({statusCode:t})){case`1XX`:case`3XX`:break;case`2XX`:r.properties[t]=a.schema;break;case`4XX`:case`5XX`:n.properties[t]=a.schema;break;case`default`:i=a;break}}if(i){let e=!1;Object.keys(r.properties).length||(r.properties.default=i.schema,e=!0);let t=(i.schema.description??``).toLocaleLowerCase(),a=(i.schema.$ref??``).toLocaleLowerCase();[`success`].some(e=>t.includes(e)||a.includes(e))&&(r.properties.default=i.schema,e=!0),[`error`,`problem`].some(e=>t.includes(e)||a.includes(e))&&(n.properties.default=i.schema,e=!0),e||(n.properties.default=i.schema)}let a=Object.keys(n.properties);if(a.length){n.required=a,t.errors=n;let e=w({items:Object.values(n.properties),mutateSchemaOneItem:!0,schema:{}});e=C({schema:e}),Object.keys(e).length&&e.type!==`unknown`&&(t.error=e)}let o=Object.keys(r.properties);if(o.length){r.required=o,t.responses=r;let e=w({items:Object.values(r.properties),mutateSchemaOneItem:!0,schema:{}});e=C({schema:e}),Object.keys(e).length&&e.type!==`unknown`&&(t.response=e)}return t},at=e=>e.replace(/^[^\p{ID_Start}]+/u,``).replace(/[^$\u200c\u200d\p{ID_Continue}]/gu,`-`).replace(/[$+]/g,`-`),ot=e=>{let t=E(e);return t.name===`@hey-api/client-axios`||t.name===`@hey-api/client-nuxt`?`baseURL`:`baseUrl`},E=e=>{for(let t of e.pluginOrder){let n=e.plugins[t];if(n?.tags?.includes(`client`))return n}return{config:{name:``},name:``}};var D=class{analyze(e){}exported;file;language=`typescript`;parent;root;symbol;toAst(e){}"~brand"=l.nodeBrand;$if(e,t,n){if(e){let n;try{n=t?.(this,e)}catch{}if(n===void 0)try{n=t?.(e)}catch{}if(n===void 0)try{n=t?.()}catch{}return n??this}if(n){let t;try{t=n?.(this,e)}catch{}if(t===void 0)try{t=n?.(e)}catch{}if(t===void 0)try{t=n?.()}catch{}return t??this}return this}$maybeId(e){return typeof e==`string`?m.default.factory.createIdentifier(e):e}$node(e,t){if(t!==void 0)return(0,l.isRef)(t)&&(t=(0,l.fromRef)(t)),(0,l.isSymbol)(t)?this.$maybeId(t.finalName):typeof t==`string`?this.$maybeId(t):t instanceof Array?t.map(t=>((0,l.isRef)(t)&&(t=(0,l.fromRef)(t)),this.unwrap(t,e))):this.unwrap(t,e)}$type(e,t,n){if(t!==void 0){if((0,l.isRef)(t)&&(t=(0,l.fromRef)(t)),(0,l.isSymbol)(t))return m.default.factory.createTypeReferenceNode(t.finalName,n);if(typeof t==`string`)return m.default.factory.createTypeReferenceNode(t,n);if(typeof t==`boolean`){let e=t?m.default.factory.createTrue():m.default.factory.createFalse();return m.default.factory.createLiteralTypeNode(e)}return typeof t==`number`?m.default.factory.createLiteralTypeNode(m.default.factory.createNumericLiteral(t)):t instanceof Array?t.map(t=>this.$type(e,t,n)):this.unwrap(t,e)}}unwrap(e,t){return(0,l.isNode)(e)?e.toAst(t):e}},st=class extends D{};const ct=D;var lt=class extends ct{"~dsl"=`IdTsDsl`;name;constructor(e){super(),this.name=e}analyze(e){super.analyze(e)}toAst(){return m.default.factory.createIdentifier(this.name)}},ut=class extends D{"~dsl"=`NewlineTsDsl`;analyze(e){super.analyze(e)}toAst(e){return this.$node(e,new lt(` `))}};function dt(e){class t extends e{_args=[];analyze(e){super.analyze(e);for(let t of this._args)e.analyze(t)}arg(e){return e!==void 0&&this._args.push((0,l.ref)(e)),this}args(...e){return this._args.push(...e.filter(e=>e!==void 0).map(e=>(0,l.ref)(e))),this}$args(e){return this.$node(e,this._args).map(t=>this.$node(e,t))}}return t}const ft=D;var pt=class extends ft{"~dsl"=`PrefixTsDsl`;_expr;_op;constructor(e,t){super(),this._expr=e,this._op=t}analyze(e){super.analyze(e),e.analyze(this._expr)}expr(e){return this._expr=e,this}neg(){return this._op=m.default.SyntaxKind.MinusToken,this}not(){return this._op=m.default.SyntaxKind.ExclamationToken,this}op(e){return this._op=e,this}toAst(e){if(!this._expr)throw Error(`Missing expression for prefix unary expression`);if(!this._op)throw Error(`Missing operator for prefix unary expression`);return m.default.factory.createPrefixUnaryExpression(this._op,this.$node(e,this._expr))}};function mt(e){let t,n=((...n)=>{if(!t)throw Error(`${e} factory not registered`);return t(...n)});return n.set=e=>{t=e},n}const O={as:mt(`as`),attr:mt(`attr`),await:mt(`await`),call:mt(`call`),return:mt(`return`),type:{expr:mt(`type.expr`),idx:mt(`type.idx`),operator:mt(`type.operator`),query:mt(`type.query`)},typeofExpr:mt(`typeofExpr`)};function ht(e){class t extends e{analyze(e){super.analyze(e)}as(...e){return O.as(this,...e)}}return t}const gt=ht(D);var k=class extends gt{"~dsl"=`LiteralTsDsl`;value;constructor(e){super(),this.value=e}analyze(e){super.analyze(e)}toAst(e){if(typeof this.value==`boolean`)return this.value?m.default.factory.createTrue():m.default.factory.createFalse();if(typeof this.value==`number`){let t=m.default.factory.createNumericLiteral(Math.abs(this.value));return this.value<0?this.$node(e,new pt(t).neg()):t}if(typeof this.value==`string`)return m.default.factory.createStringLiteral(this.value,!0);if(this.value===null)return m.default.factory.createNull();throw Error(`Unsupported literal: ${String(this.value)}`)}};const _t=/^[^$_\p{ID_Start}]+/u,vt=/^-?\d+(\.\d+)?$/,yt=/^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u,A={illegalStartCharacters:_t,number:vt,typeScriptIdentifier:yt},bt=[`document`,`history`,`location`,`navigator`,`window`],xt=[`console`,`Array`,`Date`,`Error`,`Function`,`JSON`,`Map`,`Math`,`Object`,`Promise`,`RegExp`,`Set`,`WeakMap`,`WeakSet`],St=`arguments.async.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.from.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`),Ct=[`global`,`process`,`Buffer`],wt=[`any`,`as`,`bigint`,`boolean`,`namespace`,`never`,`null`,`number`,`string`,`symbol`,`type`,`undefined`,`unknown`,`void`],Tt={browserGlobals:bt,javaScriptGlobals:xt,javaScriptKeywords:St,nodeGlobals:Ct,typeScriptKeywords:wt};var Et=class{_array;_set;constructor(e){this._array=e,this._set=new Set(e)}get"~values"(){return this._set}set(e){let t=typeof e==`function`?e(this._array):e;this._array=t,this._set=new Set(t)}};const Dt=new Et([...Tt.browserGlobals,...Tt.javaScriptGlobals,...Tt.javaScriptKeywords,...Tt.nodeGlobals,...Tt.typeScriptKeywords]),Ot=new Et([...Tt.javaScriptKeywords,...Tt.typeScriptKeywords]),kt={runtime:Dt,type:Ot},At=e=>(A.typeScriptIdentifier.lastIndex=0,A.typeScriptIdentifier.test(e)?new lt(e):new k(e)),jt=e=>(A.number.lastIndex=0,A.number.test(e)?e.startsWith(`-`)?new k(e):new k(Number(e)):(A.typeScriptIdentifier.lastIndex=0,A.typeScriptIdentifier.test(e)?new lt(e):new k(e))),Mt=(e,t)=>{let n=``,r,i=e[0];for(A.illegalStartCharacters.lastIndex=0,A.illegalStartCharacters.test(i)?(n+=`_`,r=0):(n+=i,r=1);r<e.length;){let t=e[r];n+=/^[\u200c\u200d\p{ID_Continue}]$/u.test(t)?t:`_`,r+=1}return t[`~values`].has(n)&&(n=`${n}_`),n||`_`},Nt=e=>Mt(e,kt.runtime),Pt=e=>Mt(e,kt.type),Ft=dt(D);var It=class extends Ft{"~dsl"=`DecoratorTsDsl`;name;constructor(e,...t){super(),this.name=(0,l.ref)(e),(0,l.isSymbol)(e)&&e.setNameSanitizer(Nt),this.args(...t)}analyze(e){super.analyze(e),e.analyze(this.name)}toAst(e){let t=this.$node(e,this.name),n=this.$args(e);return m.default.factory.createDecorator(n.length?m.default.factory.createCallExpression(t,void 0,n):t)}};function Lt(e){class t extends e{decorators=[];analyze(e){super.analyze(e);for(let t of this.decorators)e.analyze(t)}decorator(e,...t){return this.decorators.push(new It(e,...t)),this}$decorators(e){return this.$node(e,this.decorators)}}return t}var Rt=class extends D{"~dsl"=`DocTsDsl`;_lines=[];constructor(e,t){super(),e&&this.add(e),t?.(this)}analyze(e){super.analyze(e)}add(e){return this._lines.push(e),this}apply(e,t){let n=this._lines.reduce((t,n)=>{typeof n==`function`&&(n=n(e));for(let e of typeof n==`string`?[n]:n)(e||e===``)&&t.push(e);return t},[]);if(!n.length)return t;let r=n.map(e=>m.default.factory.createJSDocText(`${e}\n`)),i=m.default.factory.createJSDocComment(m.default.factory.createNodeArray(r),void 0),a=m.default.createPrinter().printNode(m.default.EmitHint.Unspecified,i,t.getSourceFile?.()??m.default.createSourceFile(``,``,m.default.ScriptTarget.Latest)).replace(`/*`,``).replace(`* */`,``);return m.default.addSyntheticLeadingComment(t,m.default.SyntaxKind.MultiLineCommentTrivia,a,!0),t}toAst(e){return this.$node(e,new lt(``))}};function j(e){class t extends e{_doc;analyze(e){super.analyze(e)}doc(e,t){return this._doc=new Rt(e,t),this}$docs(e,t){return this._doc?this._doc.apply(e,t):t}}return t}function M(e){class t extends e{modifiers=[];analyze(e){super.analyze(e)}_m(e,t){return t&&this.modifiers.push(m.default.factory.createModifier(e)),this}}return t}function zt(e){let t=M(e);class n extends t{abstract(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.AbstractKeyword,t)}}return n}function Bt(e){let t=M(e);class n extends t{async(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.AsyncKeyword,t)}}return n}function Vt(e){let t=M(e);class n extends t{const(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.ConstKeyword,t)}}return n}function Ht(e){let t=M(e);class n extends t{default(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.DefaultKeyword,t)}}return n}function Ut(e){let t=M(e);class n extends t{export(e){let t=arguments.length===0?!0:!!e;return this.exported=t,this.symbol&&this.symbol.setExported(t),this._m(m.default.SyntaxKind.ExportKeyword,t)}}return n}function Wt(e){let t=M(e);class n extends t{private(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.PrivateKeyword,t)}}return n}function Gt(e){let t=M(e);class n extends t{protected(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.ProtectedKeyword,t)}}return n}function Kt(e){let t=M(e);class n extends t{public(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.PublicKeyword,t)}}return n}function qt(e){let t=M(e);class n extends t{readonly(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.ReadonlyKeyword,t)}}return n}function Jt(e){let t=M(e);class n extends t{static(e){let t=arguments.length===0?!0:!!e;return this._m(m.default.SyntaxKind.StaticKeyword,t)}}return n}const Yt=D;var Xt=class extends Yt{"~dsl"=`TypeParamTsDsl`;constraint;defaultValue;name;constructor(e,t){super(),e&&(this.name=(0,l.ref)(e)),t?.(this)}analyze(e){super.analyze(e),e.analyze(this.name),e.analyze(this.constraint),e.analyze(this.defaultValue)}default(e){return this.defaultValue=(0,l.ref)(e),this}extends(e){return this.constraint=(0,l.ref)(e),this}toAst(e){if(!this.name)throw Error(`Missing type name`);return m.default.factory.createTypeParameterDeclaration(void 0,this.$node(e,this.name),this.$type(e,this.constraint),this.$type(e,this.defaultValue))}};function Zt(e){class t extends e{_generics=[];analyze(e){super.analyze(e);for(let t of this._generics)e.analyze(t)}generic(...e){let t=new Xt(...e);return this._generics.push(t),this}generics(...e){for(let t of e)(typeof t==`string`||(0,l.isSymbol)(t))&&(t=new Xt(t)),this._generics.push(t);return this}$generics(e){return this.$node(e,this._generics)}}return t}function Qt(e){class t extends e{_optional;analyze(e){super.analyze(e)}optional(e){return this._optional=arguments.length===0?!0:!!e,this}required(e){return this._optional=arguments.length===0?!1:!e,this}}return t}function $t(e){class t extends e{value;analyze(e){super.analyze(e),e.analyze(this.value)}assign(e){return this.value=e,this}$value(e){return this.$node(e,this.value)}}return t}var N=class extends D{"~dsl"=`TokenTsDsl`;_kind;kind(e){return this._kind=e,this}minus(){return this.kind(m.default.SyntaxKind.MinusToken)}optional(){return this.kind(m.default.SyntaxKind.QuestionToken)}plus(){return this.kind(m.default.SyntaxKind.PlusToken)}questionDot(){return this.kind(m.default.SyntaxKind.QuestionDotToken)}readonly(){return this.kind(m.default.SyntaxKind.ReadonlyKeyword)}spread(){return this.kind(m.default.SyntaxKind.DotDotDotToken)}toAst(){if(!this._kind)throw Error("Token missing `.kind(kind)`");return m.default.factory.createToken(this._kind)}};function en(e){class t extends e{_generics=[];analyze(e){super.analyze(e);for(let t of this._generics)e.analyze(t)}generic(e){return this._generics.push((0,l.ref)(e)),this}generics(...e){return this._generics.push(...e.map(e=>(0,l.ref)(e))),this}$generics(e){return this.$type(e,this._generics)}}return t}function tn(e){class t extends e{analyze(e){super.analyze(e)}idx(...e){return O.type.idx(this,...e)}keyof(){return O.type.operator().keyof(this)}readonly(){return O.type.operator().readonly(this)}returnType(...e){return O.type.expr(`ReturnType`).generic(O.type.query(this,...e))}typeofExpr(...e){return O.typeofExpr(this,...e)}typeofType(...e){return O.type.query(this,...e)}unique(){return O.type.operator().unique(this)}}return t}const nn=tn(D);var rn=class extends nn{"~dsl"=`TypeAttrTsDsl`;_base;_right;constructor(e,t){super(),t?(this.base(e),this.right(t)):(this.base(),this.right(e))}analyze(e){super.analyze(e),e.analyze(this._base),e.analyze(this._right)}base(e){return(0,l.isRef)(e)?this._base=e:this._base=e?(0,l.ref)(e):void 0,this}right(e){return this._right=(0,l.ref)(e),this}toAst(e){if(!this._base)throw Error(`TypeAttrTsDsl: missing base for qualified name`);let t=this.$node(e,this._base);if(!m.default.isEntityName(t))throw Error(`TypeAttrTsDsl: base must be an EntityName`);return m.default.factory.createQualifiedName(t,this.$node(e,this._right))}};const an=en(tn(D));var on=class extends an{"~dsl"=`TypeExprTsDsl`;_exprInput;constructor(e,t){super(),typeof e==`function`?e(this):(this._exprInput=e?(0,l.ref)(e):void 0,t?.(this))}analyze(e){super.analyze(e),e.analyze(this._exprInput)}attr(e){return this._exprInput=(0,l.isNode)(e)?(0,l.ref)(e.base(this._exprInput)):(0,l.ref)(new rn(this._exprInput,e)),this}toAst(e){if(!this._exprInput)throw Error(`TypeExpr must have an expression`);return m.default.factory.createTypeReferenceNode(this.$type(e,this._exprInput),this.$generics(e))}};O.type.expr.set((...e)=>new on(...e));const sn=Lt(j(Qt(Wt(Gt(Kt(qt(Jt($t(D)))))))));var cn=class extends sn{"~dsl"=`FieldTsDsl`;name;_type;constructor(e,t){super(),this.name=e,t?.(this)}analyze(e){super.analyze(e),e.analyze(this._type)}type(e){return this._type=e instanceof st?e:new on(e),this}toAst(e){let t=m.default.factory.createPropertyDeclaration([...this.$decorators(e),...this.modifiers],this.$node(e,this.name),this._optional?this.$node(e,new N().optional()):void 0,this.$type(e,this._type),this.$value(e));return this.$docs(e,t)}};const ln=D;var un=class extends ln{"~dsl"=`StmtTsDsl`;_inner;constructor(e){super(),this._inner=e}analyze(e){super.analyze(e),e.analyze(this._inner)}toAst(e){let t=this.$node(e,this._inner);return m.default.isStatement(t)?t:m.default.factory.createExpressionStatement(t)}};function dn(e){class t extends e{_do=[];analyze(e){super.analyze(e),e.pushScope();try{for(let t of this._do)e.analyze(t)}finally{e.popScope()}}do(...e){return this._do.push(...e),this}$do(e){return this.$node(e,this._do.map(e=>new un(e)))}}return t}const fn=D;var pn=class extends fn{"~dsl"=`PatternTsDsl`;pattern;_spread;analyze(e){super.analyze(e)}array(...e){return this.pattern={kind:`array`,values:e[0]instanceof Array?[...e[0]]:e},this}object(...e){let t={};for(let n of e)if(typeof n==`string`)t[n]=n;else if(n instanceof Array)for(let e of n)t[e]=e;else Object.assign(t,n);return this.pattern={kind:`object`,values:t},this}spread(e){return this._spread=e,this}toAst(e){if(!this.pattern)throw Error(`PatternTsDsl requires object() or array() pattern`);if(this.pattern.kind===`object`){let t=Object.entries(this.pattern.values).map(([e,t])=>e===t?m.default.factory.createBindingElement(void 0,void 0,e,void 0):m.default.factory.createBindingElement(void 0,e,t,void 0)),n=this.createSpread(e);return n&&t.push(n),m.default.factory.createObjectBindingPattern(t)}if(this.pattern.kind===`array`){let t=this.pattern.values.map(e=>m.default.factory.createBindingElement(void 0,void 0,e,void 0)),n=this.createSpread(e);return n&&t.push(n),m.default.factory.createArrayBindingPattern(t)}throw Error(`PatternTsDsl requires object() or array() pattern`)}createSpread(e){return this._spread?m.default.factory.createBindingElement(this.$node(e,new N().spread()),void 0,this.$node(e,new lt(this._spread))):void 0}};function mn(e){class t extends e{pattern;analyze(e){super.analyze(e),e.analyze(this.pattern)}array(...e){return(this.pattern??=new pn).array(...e),this}object(...e){return(this.pattern??=new pn).object(...e),this}spread(e){return(this.pattern??=new pn).spread(e),this}$pattern(e){if(this.pattern)return this.$node(e,this.pattern)}}return t}const hn=Lt(Qt(mn($t(D))));var gn=class extends hn{"~dsl"=`ParamTsDsl`;name;_type;constructor(e,t){super(),typeof e==`function`?e(this):(this.name=(0,l.ref)(e),t?.(this))}analyze(e){super.analyze(e),e.analyze(this.name),e.analyze(this._type)}type(e){return this._type=e instanceof st?e:new on(e),this}toAst(e){let t=this.$pattern(e);if(!t&&this.name&&(t=(0,l.isSymbolRef)(this.name)?(0,l.fromRef)(this.name).finalName:(0,l.fromRef)(this.name)),!t)throw Error(`Param must have either a name or a destructuring pattern`);return m.default.factory.createParameterDeclaration(this.$decorators(e),void 0,t,this._optional?this.$node(e,new N().optional()):void 0,this.$type(e,this._type),this.$value(e))}};function _n(e){class t extends e{_params=[];analyze(e){super.analyze(e);for(let t of this._params)e.analyze(t)}param(e,t){let n=new gn(e,t);return this._params.push(n),this}params(...e){return this._params.push(...e),this}$params(e){return this.$node(e,this._params)}}return t}function vn(e){class t extends e{static DEFAULT_THRESHOLD=3;layout;analyze(e){super.analyze(e)}auto(e=t.DEFAULT_THRESHOLD){return this.layout=e,this}inline(){return this.layout=!1,this}pretty(){return this.layout=!0,this}$multiline(e){return this.layout===void 0&&(this.layout=t.DEFAULT_THRESHOLD),e===0?!1:typeof this.layout==`number`?e>=this.layout:this.layout}}return t}const yn=dn(vn(D));var P=class extends yn{"~dsl"=`BlockTsDsl`;constructor(...e){super(),this.do(...e)}analyze(e){super.analyze(e)}toAst(e){let t=this.$do(e);return m.default.factory.createBlock(t,this.$multiline(t.length))}};const bn=Lt(dn(j(_n(Wt(Gt(Kt(D)))))));var xn=class extends bn{"~dsl"=`InitTsDsl`;constructor(e){super(),e?.(this)}analyze(e){e.pushScope();try{super.analyze(e)}finally{e.popScope()}}toAst(e){let t=m.default.factory.createConstructorDeclaration([...this.$decorators(e),...this.modifiers],this.$params(e),this.$node(e,new P(...this._do).pretty()));return this.$docs(e,t)}};function Sn(e){class t extends e{_returns;analyze(e){super.analyze(e),e.analyze(this._returns)}returns(e){return this._returns=e instanceof st?e:new on(e),this}$returns(e){return this.$type(e,this._returns)}}return t}const Cn=zt(Bt(Lt(dn(j(Qt(_n(Wt(Gt(Kt(Jt(Zt(Sn(D)))))))))))));var wn=class extends Cn{"~dsl"=`MethodTsDsl`;name;constructor(e,t){super(),this.name=e,t?.(this)}analyze(e){e.pushScope();try{super.analyze(e)}finally{e.popScope()}}toAst(e){let t=m.default.factory.createMethodDeclaration([...this.$decorators(e),...this.modifiers],void 0,this.name,this._optional?this.$node(e,new N().optional()):void 0,this.$generics(e),this.$params(e),this.$returns(e),this.$node(e,new P(...this._do).pretty()));return this.$docs(e,t)}};const Tn=zt(Lt(Ht(j(Ut(Zt(D))))));var En=class extends Tn{"~dsl"=`ClassTsDsl`;baseClass;body=[];name;constructor(e){super(),this.name=(0,l.ref)(e),(0,l.isSymbol)(e)&&(e.setKind(`class`),e.setNameSanitizer(Nt),e.setNode(this))}analyze(e){super.analyze(e),e.analyze(this.baseClass),e.analyze(this.name),e.pushScope();try{for(let t of this.body)e.analyze(t)}finally{e.popScope()}}do(...e){return this.body.push(...e),this}extends(e){return this.baseClass=e?(0,l.ref)(e):void 0,this}field(e,t){let n=new cn(e,t);return this.body.push(n),this}init(e){let t=new xn(e);return this.body.push(t),this}method(e,t){let n=new wn(e,t);return this.body.push(n),this}newline(){return this.body.push(new ut),this}toAst(e){let t=this.$node(e,this.body),n=m.default.factory.createClassDeclaration([...this.$decorators(e),...this.modifiers],this.$node(e,this.name),this.$generics(e),this._heritage(e),t);return this.$docs(e,n)}_heritage(e){let t=this.$node(e,this.baseClass);return t?[m.default.factory.createHeritageClause(m.default.SyntaxKind.ExtendsKeyword,[m.default.factory.createExpressionWithTypeArguments(t,void 0)])]:[]}};const Dn=j(D);var On=class extends Dn{"~dsl"=`EnumMemberTsDsl`;_name;_value;constructor(e,t){super(),this._name=e,typeof t==`function`?t(this):this.value(t)}analyze(e){super.analyze(e),e.analyze(this._value)}value(e){return this._value=e,this}toAst(e){let t=m.default.factory.createEnumMember(this.$node(e,At(this._name)),this.$node(e,this._value));return this.$docs(e,t)}};const kn=Vt(j(Ut(D)));var An=class extends kn{"~dsl"=`EnumTsDsl`;_members=[];_name;constructor(e,t){super(),this._name=(0,l.ref)(e),(0,l.isSymbol)(e)&&(e.setKind(`enum`),e.setNameSanitizer(Nt),e.setNode(this)),t?.(this)}analyze(e){super.analyze(e),e.analyze(this._name),e.pushScope();try{for(let t of this._members)e.analyze(t)}finally{e.popScope()}}member(e,t){let n=new On(e,t);return this._members.push(n),this}members(...e){return this._members.push(...e),this}toAst(e){let t=m.default.factory.createEnumDeclaration(this.modifiers,this.$node(e,this._name),this.$node(e,this._members));return this.$docs(e,t)}};const jn=zt(ht(Bt(Lt(dn(j(_n(Wt(Gt(Kt(Jt(Zt(Sn(D)))))))))))));var Mn=class extends jn{"~dsl"=`FuncTsDsl`;mode;name;constructor(e,t){super(),typeof e==`function`?(this.mode=`arrow`,e(this)):e&&(this.mode=`decl`,this.name=(0,l.ref)(e),(0,l.isSymbol)(e)&&(e.setKind(`function`),e.setNameSanitizer(Nt),e.setNode(this)),t?.(this))}analyze(e){e.pushScope();try{super.analyze(e),e.analyze(this.name)}finally{e.popScope()}}arrow(){return this.mode=`arrow`,this}decl(){return this.mode=`decl`,this}expr(){return this.mode=`expr`,this}toAst(e){let t=this.$node(e,new P(...this._do).pretty());if(this.mode===`decl`){if(!this.name)throw Error(`Function declaration requires a name`);let n=m.default.factory.createFunctionDeclaration([...this.$decorators(e),...this.modifiers],void 0,this.$node(e,this.name),this.$generics(e),this.$params(e),this.$returns(e),t);return this.$docs(e,n)}if(this.mode===`expr`){let n=m.default.factory.createFunctionExpression(this.modifiers,void 0,this.$node(e,this.name),this.$generics(e),this.$params(e),this.$returns(e),t);return this.$docs(e,n)}let n=m.default.factory.createArrowFunction(this.modifiers,this.$generics(e),this.$params(e),this.$returns(e),void 0,t.statements.length===1&&m.default.isReturnStatement(t.statements[0])&&t.statements[0].expression?t.statements[0].expression:t);return this.$docs(e,n)}};const Nn=Mn,Pn=zt(Bt(Lt(dn(j(_n(Wt(Gt(Kt(Jt(Sn(D)))))))))));var Fn=class extends Pn{"~dsl"=`GetterTsDsl`;name;constructor(e,t){super(),this.name=e,t?.(this)}analyze(e){e.pushScope();try{super.analyze(e)}finally{e.popScope()}}toAst(e){let t=m.default.factory.createGetAccessorDeclaration([...this.$decorators(e),...this.modifiers],this.name,this.$params(e),this.$returns(e),this.$node(e,new P(...this._do).pretty()));return this.$docs(e,t)}};const In=zt(Bt(Lt(dn(j(_n(Wt(Gt(Kt(Jt(D))))))))));var Ln=class extends In{"~dsl"=`SetterTsDsl`;name;constructor(e,t){super(),this.name=e,t?.(this)}analyze(e){e.pushScope();try{super.analyze(e)}finally{e.popScope()}}toAst(e){let t=m.default.factory.createSetAccessorDeclaration([...this.$decorators(e),...this.modifiers],this.name,this.$params(e),this.$node(e,new P(...this._do).pretty()));return this.$docs(e,t)}};const Rn=ht(vn(D));var zn=class extends Rn{"~dsl"=`ArrayTsDsl`;_elements=[];constructor(...e){super(),this.elements(...e)}analyze(e){super.analyze(e);for(let t of this._elements)e.analyze(t.expr)}element(e){let t=typeof e==`string`||typeof e==`number`||typeof e==`boolean`?new k(e):e;return this._elements.push({expr:t,kind:`element`}),this}elements(...e){for(let t of e)this.element(t);return this}spread(e){return this._elements.push({expr:e,kind:`spread`}),this}toAst(e){let t=this._elements.map(t=>{let n=this.$node(e,t.expr);return t.kind===`spread`?m.default.factory.createSpreadElement(n):n});return m.default.factory.createArrayLiteralExpression(t,this.$multiline(this._elements.length))}};function Bn(e){class t extends e{analyze(e){super.analyze(e)}attr(...e){return O.attr(this,...e)}await(){return O.await(this)}call(...e){return O.call(this,...e)}return(){return O.return(this)}}return t}const Vn=ht(Bn(D));var Hn=class extends Vn{"~dsl"=`AsTsDsl`;expr;type;constructor(e,t){super(),this.expr=(0,l.ref)(e),this.type=(0,l.ref)(t)}analyze(e){super.analyze(e),e.analyze(this.expr),e.analyze(this.type)}toAst(e){return m.default.factory.createAsExpression(this.$node(e,this.expr),this.$type(e,this.type))}};O.as.set((...e)=>new Hn(...e));const Un=ht(Bn(D));var F=class extends Un{"~dsl"=`BinaryTsDsl`;_base;_expr;_op;constructor(e,t,n){super(),this._base=(0,l.ref)(e),this._op=t,n&&(this._expr=(0,l.ref)(n))}analyze(e){super.analyze(e),e.analyze(this._base),e.analyze(this._expr)}and(e){return this.opAndExpr(`&&`,e)}assign(e){return this.opAndExpr(`=`,e)}coalesce(e){return this.opAndExpr(`??`,e)}div(e){return this.opAndExpr(`/`,e)}eq(e){return this.opAndExpr(`===`,e)}gt(e){return this.opAndExpr(`>`,e)}gte(e){return this.opAndExpr(`>=`,e)}looseEq(e){return this.opAndExpr(`==`,e)}looseNeq(e){return this.opAndExpr(`!=`,e)}lt(e){return this.opAndExpr(`<`,e)}lte(e){return this.opAndExpr(`<=`,e)}minus(e){return this.opAndExpr(`-`,e)}neq(e){return this.opAndExpr(`!==`,e)}nullishAssign(e){return this.opAndExpr(`??=`,e)}or(e){return this.opAndExpr(`||`,e)}plus(e){return this.opAndExpr(`+`,e)}times(e){return this.opAndExpr(`*`,e)}toAst(e){if(!this._op)throw Error(`BinaryTsDsl: missing operator`);let t=this.$node(e,this._expr);if(!t)throw Error(`BinaryTsDsl: missing right-hand expression`);let n=this.$node(e,this._base),r=typeof this._op==`string`?this.opToToken(this._op):this._op;return m.default.factory.createBinaryExpression(n,r,t)}opAndExpr(e,t){return this._expr=(0,l.ref)(t),this._op=e,this}opToToken(e){let t={"!=":m.default.SyntaxKind.ExclamationEqualsToken,"!==":m.default.SyntaxKind.ExclamationEqualsEqualsToken,"&&":m.default.SyntaxKind.AmpersandAmpersandToken,"*":m.default.SyntaxKind.AsteriskToken,"+":m.default.SyntaxKind.PlusToken,"-":m.default.SyntaxKind.MinusToken,"/":m.default.SyntaxKind.SlashToken,"<":m.default.SyntaxKind.LessThanToken,"<=":m.default.SyntaxKind.LessThanEqualsToken,"=":m.default.SyntaxKind.EqualsToken,"==":m.default.SyntaxKind.EqualsEqualsToken,"===":m.default.SyntaxKind.EqualsEqualsEqualsToken,">":m.default.SyntaxKind.GreaterThanToken,">=":m.default.SyntaxKind.GreaterThanEqualsToken,"??":m.default.SyntaxKind.QuestionQuestionToken,"??=":m.default.SyntaxKind.QuestionQuestionEqualsToken,"||":m.default.SyntaxKind.BarBarToken}[e];if(!t)throw Error(`Unsupported operator: ${e}`);return t}};function Wn(e){class t extends e{analyze(e){super.analyze(e)}and(e){return new F(this).and(e)}assign(e){return new F(this,`=`,e)}coalesce(e){return new F(this).coalesce(e)}div(e){return new F(this).div(e)}eq(e){return new F(this).eq(e)}gt(e){return new F(this).gt(e)}gte(e){return new F(this).gte(e)}looseEq(e){return new F(this).looseEq(e)}looseNeq(e){return new F(this).looseNeq(e)}lt(e){return new F(this).lt(e)}lte(e){return new F(this).lte(e)}minus(e){return new F(this).minus(e)}neq(e){return new F(this).neq(e)}nullishAssign(e){return new F(this).nullishAssign(e)}or(e){return new F(this).or(e)}plus(e){return new F(this).plus(e)}times(e){return new F(this).times(e)}}return t}const Gn=ht(Bn(Wn(Qt(D))));var Kn=class extends Gn{"~dsl"=`AttrTsDsl`;left;right;constructor(e,t){super(),this.left=(0,l.ref)(e),this.right=(0,l.ref)(t)}analyze(e){super.analyze(e),e.analyze(this.left),e.analyze(this.right)}toAst(e){let t=this.$node(e,this.left);return A.typeScriptIdentifier.lastIndex=0,typeof(0,l.fromRef)(this.right)==`number`||typeof(0,l.fromRef)(this.right)==`string`&&!A.typeScriptIdentifier.test((0,l.fromRef)(this.right))?this._optional?m.default.factory.createElementAccessChain(t,this.$node(e,new N().questionDot()),this.$node(e,new k((0,l.fromRef)(this.right)))):m.default.factory.createElementAccessExpression(t,this.$node(e,new k((0,l.fromRef)(this.right)))):this._optional?m.default.factory.createPropertyAccessChain(t,this.$node(e,new N().questionDot()),this.$node(e,this.right)):m.default.factory.createPropertyAccessExpression(t,this.$node(e,this.right))}};O.attr.set((...e)=>new Kn(...e));const qn=Bn(D);var Jn=class extends qn{"~dsl"=`AwaitTsDsl`;_awaitExpr;constructor(e){super(),this._awaitExpr=(0,l.ref)(e)}analyze(e){super.analyze(e),e.analyze(this._awaitExpr)}toAst(e){return m.default.factory.createAwaitExpression(this.$node(e,this._awaitExpr))}};O.await.set((...e)=>new Jn(...e));const Yn=dt(ht(Bn(en(D))));var Xn=class extends Yn{"~dsl"=`CallTsDsl`;_callee;constructor(e,...t){super(),this._callee=e,this.args(...t)}analyze(e){super.analyze(e),e.analyze(this._callee)}toAst(e){return m.default.factory.createCallExpression(this.$node(e,this._callee),this.$generics(e),this.$args(e))}};O.call.set((...e)=>new Xn(...e));const Zn=ht(Bn(Wn(tn(D))));var Qn=class extends Zn{"~dsl"=`ExprTsDsl`;_exprInput;constructor(e){super(),this._exprInput=(0,l.ref)(e)}analyze(e){super.analyze(e),e.analyze(this._exprInput)}toAst(e){return this.$node(e,this._exprInput)}},$n=class extends D{"~dsl"=`HintTsDsl`;_lines=[];constructor(e,t){super(),e&&this.add(e),t?.(this)}analyze(e){super.analyze(e)}add(e){return this._lines.push(e),this}apply(e,t){let n=this._lines.reduce((t,n)=>{typeof n==`function`&&(n=n(e));for(let e of typeof n==`string`?[n]:n)(e||e===``)&&t.push(e);return t},[]);if(!n.length)return t;for(let e of n)m.default.addSyntheticLeadingComment(t,m.default.SyntaxKind.SingleLineCommentTrivia,` ${e}`,!1);return t}toAst(e){return this.$node(e,new lt(``))}};function er(e){class t extends e{_hint;analyze(e){super.analyze(e)}hint(e,t){return this._hint=new $n(e,t),this}$hint(e,t){return this._hint?this._hint.apply(e,t):t}}return t}const tr=j(D);var nr=class extends tr{"~dsl"=`ObjectPropTsDsl`;_value;meta;constructor(e){super(),this.meta=e}analyze(e){super.analyze(e),e.analyze(this._value)}get isValid(){return this.missingRequiredCalls().length===0}value(e){return typeof e==`function`?e(this):this._value=(0,l.ref)(e),this}toAst(e){this.$validate();let t=this.$node(e,this._value);if(this.meta.kind===`spread`){if(m.default.isStatement(t))throw Error(`Invalid spread: object spread must be an expression, not a statement.`);let n=m.default.factory.createSpreadAssignment(t);return this.$docs(e,n)}if(this.meta.kind===`getter`){let n=new Fn(this.$node(e,jt(this.meta.name))).do(t),r=this.$node(e,n);return this.$docs(e,r)}if(this.meta.kind===`setter`){let n=new Ln(this.$node(e,jt(this.meta.name))).do(t),r=this.$node(e,n);return this.$docs(e,r)}if(m.default.isIdentifier(t)&&t.text===this.meta.name){let t=m.default.factory.createShorthandPropertyAssignment(this.meta.name);return this.$docs(e,t)}if(m.default.isStatement(t))throw Error(`Invalid property: object property value must be an expression, not a statement.`);let n=m.default.factory.createPropertyAssignment(this.meta.kind===`computed`?m.default.factory.createComputedPropertyName(this.$node(e,new lt(this.meta.name))):this.$node(e,jt(this.meta.name)),t);return this.$docs(e,n)}$validate(){let e=this.missingRequiredCalls();if(e.length!==0)throw Error(`Object property${this.meta.name?` "${this.meta.name}"`:``} missing ${e.join(` and `)}`)}missingRequiredCalls(){let e=[];return this._value||e.push(`.value()`),e}};const rr=ht(Bn(er(vn(D))));var ir=class extends rr{"~dsl"=`ObjectTsDsl`;_props=[];constructor(...e){super(),this.props(...e)}analyze(e){super.analyze(e);for(let t of this._props)e.analyze(t)}computed(e,t){return this._props.push(new nr({kind:`computed`,name:e}).value(t)),this}getter(e,t){return this._props.push(new nr({kind:`getter`,name:e}).value(t)),this}hasProps(){return this._props.length>0}get isEmpty(){return this._props.length===0}prop(e,t){return this._props.push(new nr({kind:`prop`,name:e}).value(t)),this}props(...e){return this._props.push(...e),this}setter(e,t){return this._props.push(new nr({kind:`setter`,name:e}).value(t)),this}spread(e){return this._props.push(new nr({kind:`spread`}).value(e)),this}toAst(e){let t=m.default.factory.createObjectLiteralExpression(this.$node(e,this._props),this.$multiline(this._props.length));return this.$hint(e,t)}};const ar=(e,t)=>{if((0,l.isNode)(e))return e;if(e===null||typeof e==`number`||typeof e==`boolean`||typeof e==`string`)return new k(e);if(e instanceof Array){let n=new zn(...e.map(e=>ar(e,t)));return t?.layout===`pretty`&&n.pretty(),n}if(typeof e==`object`){let n=new ir;for(let[r,i]of Object.entries(e)){let e=ar(i,t);n.prop(r,e)}return t?.layout===`pretty`&&n.pretty(),n}throw Error(`$.fromValue(): Unsupported input type ${String(e)}`)},or=dt(Bn(en(D)));var sr=class extends or{"~dsl"=`NewTsDsl`;classExpr;constructor(e,...t){super(),this.classExpr=(0,l.ref)(e),this.args(...t)}analyze(e){super.analyze(e),e.analyze(this.classExpr)}toAst(e){return m.default.factory.createNewExpression(this.$node(e,this.classExpr),this.$generics(e),this.$args(e))}};const cr=D;var lr=class extends