@ahoo-wang/wow-generator 10.0.0-alpha.5 → 10.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs"),i=require("node:path");var a=`./wow-generator.config.json`,o={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},s=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return o[this.kind]}};function c(e){return e instanceof Error?e.message:String(e)}function l(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var u=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??l()}format(e,t,n){let r=this.decorate?`${e} `:t?`${t}: `:``;return`${this.level===`verbose`?`[${new Date().toTimeString().slice(0,8)}] `:``}${r}${n}`}debug(e,...t){this.level===`verbose`&&console.log(this.format(`ℹ️ `,``,e),...t)}info(e,...t){this.level!==`quiet`&&console.log(this.format(`✅`,``,e),...t)}warn(e,...t){console.warn(this.format(`⚠️ `,`warning`,e),...t)}error(e,...t){console.error(this.format(`❌`,`error`,e),...t)}},d=class{debug(){}info(){}warn(){}error(){}};function f(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var p=`types.ts`;function m(e){return f(e.path,p)}function h(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function g(e,t){let n=t.slice(1);try{n=decodeURIComponent(n)}catch{}if(n===``)return e;let r=e;for(let e of n.slice(1).split(`/`)){if(typeof r!=`object`||!r)return;let t=e.replace(/~1/g,`/`).replace(/~0/g,`~`);if(!Object.hasOwn(r,t))return;r=r[t]}return r}function ee(e){let t=[],n=new Set,r=(i,a)=>{if(typeof i!=`object`||!i||n.has(i))return;if(n.add(i),Array.isArray(i)){i.forEach((e,t)=>r(e,`${a}/${t}`));return}let o=i.$ref;typeof o==`string`&&o.startsWith(`#/components/`)&&g(e,o)===void 0&&t.push({ref:o,location:a||`/`});for(let[e,t]of Object.entries(i))r(t,`${a}/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`)};return r(e,``),t}var _=`#/components/`,te=`${_}parameters/`,ne=`${_}requestBodies/`,re=`${_}responses/`,ie=`${_}schemas/`;function ae(e){return e.$ref.split(`/`).pop()}function v(e,t,n){let r=new Set,i=e;for(;h(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new s(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function y(e,t){return v(e,t.schemas,ie)}function oe(e,t){return v(e,t.responses,re)}function se(e,t){return v(e,t.requestBodies,ne)}function ce(e,t){return v(e,t.parameters,te)}var le=new Intl.Collator(`en-US`);function b(e,t){return le.compare(e,t)}var ue=`application/json`,de=`text/event-stream`;function fe(e){return e.split(`;`)[0].trim().toLowerCase()}function pe(e){let t=fe(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function me(e){let t=fe(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function x(e,t,n=e=>fe(e)===t){if(!e)return;if(e[t])return e[t];let r=Object.keys(e).find(n);return r===void 0?void 0:e[r]}function he(e,t){if(t&&!h(t))return x(t.content,e)?.schema}function ge(e){if(e&&!h(e))return x(e.content,ue,pe)?.schema}function _e(e){return he(de,e)}function ve(e){return he(`*/*`,e)}function ye(e){return!e||h(e)?!1:Object.keys(e.content??{}).some(me)}function S(e){return Array.isArray(e.enum)&&e.enum.length>0}var be=`x-enum-text`;function xe(e){return e[be]}function Se(e){return e.type===`object`&&!!e.properties}function Ce(e){return e.type===`array`&&!!e.items}function we(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Te(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Ee(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function C(e){return we(e)||Te(e)||Ee(e)}function De(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Oe(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var ke=`x-map-key-schema`;function Ae(e){return e[ke]}function je(e){return e.readOnly===!0}function Me(e){if(Array.isArray(e))return e.map(e=>Me(e)).join(` | `);switch(e){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`any`}}function Ne(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),h(e))o(t&&y(e,t));else if(e.nullable||Array.isArray(e.type))a=!0;else{for(let t of e.required??[])r.add(t);for(let t of Object.keys(e.properties??{}))n.includes(t)||n.push(t);e.allOf?.forEach(o)}}};return o(e),a?[]:n.filter(e=>!r.has(e))}function Pe(e,t){return e.operation.operationId&&t.operation.operationId?b(e.operation.operationId,t.operation.operationId):e.path&&t.path?b(e.path,t.path):e.method&&t.method?b(e.method,t.method):0}function Fe(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=h(i)?n&&ce(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ie(e,t){let n=[];for(let[r,i]of Object.entries(e))Le(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Fe(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Pe)}function Le(e){return[{method:`get`,operation:e.get},{method:`put`,operation:e.put},{method:`post`,operation:e.post},{method:`delete`,operation:e.delete},{method:`options`,operation:e.options},{method:`head`,operation:e.head},{method:`patch`,operation:e.patch},{method:`trace`,operation:e.trace}].filter(({operation:e})=>e!==void 0)}function Re(e){let t=Object.keys(e.responses??{});if(t.includes(`200`))return`200`;let n=t.filter(e=>/^2\d\d$/.test(e)).sort();return n.length>0?n[0]:t.find(e=>e.toUpperCase()===`2XX`)}function ze(e,t){let n=Re(e),r=n?e.responses[n]:void 0;return t&&h(r)?oe(r,t):r}function Be(e,t){return(e.parameters??[]).map(e=>h(e)?ce(e,t):e).filter(e=>e!==void 0)}function Ve(e,t){let n=t=>{let n=e.indexOf(`{${t.name}}`);return n<0?2**53-1:n};return[...t].sort((e,t)=>n(e)-n(t))}var He=/[^\p{L}\p{N}$]+/u,Ue=new Set(`arguments.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.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(`.`));function w(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!Ue.has(e)}function We(e){return/^\p{N}/u.test(e)?`_${e}`:e}function T(e){if(w(e))return e;let t=We(O(e)||`_`);return Ue.has(t)?`${t}_`:t}function Ge(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&w(e)}function E(e){return We((Array.isArray(e)?e:[e]).map(e=>Ge(e)?e:D(e)).join(``)||`_`)}function Ke(e){return e.split(He)}function qe(e){return Array.isArray(e)?e.flatMap(e=>Je(Ke(e))):Je(Ke(e))}function Je(e){return e.flatMap(e=>{if(e.length===0)return[];let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=/[A-Z]/.test(i),o=r>0&&/[a-z]/.test(e[r-1]);a&&o&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function D(e){return e===``||e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>{let t=e.charAt(0),n=e.slice(1);return(/[a-zA-Z]/.test(t)?t.toUpperCase():t)+n.toLowerCase()}).join(``)}function O(e){let t=D(e);return t.charAt(0).toLowerCase()+t.slice(1)}function k(e){return e===``||Array.isArray(e)&&e.length===0?``:qe(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function A(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:j(e)}function Ye(e){return/^\d+$/.test(e)?`NUM_${e}`:k(e)||e}function j(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var Xe=`x-fetcher-method`;function Ze(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Qe(n))throw new s(`specification`,`${Xe} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=O(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Qe(e){return w(e)||/^[a-z]+$/.test(e)}function $e(e,t){let n=T(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function M(e){if(!e)return{name:``,path:`/`};let t=e.split(`.`),n=-1;for(let e=0;e<t.length;e++)if(t[e]&&/^[A-Z]/.test(t[e])){n=e;break}let r=t.slice(0,n),i=r.length>0?`/${r.join(`/`)}`:`/`;return{name:E(t.slice(n)),path:i}}function et(e,t){if(!e.$ref.startsWith(`#/components/schemas/`))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&y(e,t),M(ae(e))}var tt=[`httpRequest`,`attributes`];function nt(e,t,n){return new rt(e,t,n).clients()}var rt=class{document;config;warnings;constructor(e,t,n){this.document=e,this.config=t,this.warnings=n}clients(){let e=this.tags(),t=this.groupOperations(),n=new Map;return[...t.keys()].sort().map(r=>{let i=M(r),a=i;for(let e=2;n.has(N(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(N(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(N(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=f(t.path,it(r)),a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,methods:n.map(t=>this.method(e,r,t,a))}}method(e,t,n,r){let{operation:i}=n,a=this.methodName(e,t,n,r),o=new Set(tt),s=this.parameters(e,n,o),c=this.body(i,o),l=[...s.filter(({parameter:e})=>e.required),...s.filter(({parameter:e})=>!e.required)].filter(({description:e})=>e);return{name:a,httpMethod:n.method,path:n.path,parameters:s.map(({parameter:e})=>e),body:c,returns:this.returns(i),docs:[i.summary,i.description,`- operationId: \`${i.operationId}\``,`- path: \`${n.path}\``,...l.map(({parameter:e,description:t})=>`@param ${e.name} - ${t.replace(/\s*\n\s*/g,` `)}`)]}}methodName(e,t,n,r){let i=n.operation.operationId,a=Ze(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),o=r.get(a);if(o!==void 0)throw new s(`specification`,`Operations ${o} and ${i} of tag ${e.name} both generate the method ${t}.${a}(). Name one of them with apiClients["${e.name}"].methodNames in the generator configuration, or with the x-fetcher-method extension.`);return r.set(a,i),a}parameters(e,t,n){let r=Be(t.operation,this.document.components??{}),i=[];for(let a of[`path`,`query`,`header`]){let o=r.filter(e=>e.in===a);for(let r of a===`path`?Ve(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:$e(r.name,n),location:a,parameterName:r.name,schema:r.schema,required:a===`path`||r.required===!0},description:r.description})}let a=r.filter(e=>e.in===`cookie`);return a.length>0&&this.warnings.push(`${t.method.toUpperCase()} ${t.path} leaves out its cookie parameter(s) ${a.map(e=>e.name).join(`, `)}: the browser sends cookies, and fetch cannot set them.`),i}ignoresPathParameter(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters)?.includes(t)??!1}body(e,t){if(!e.requestBody)return;let n=h(e.requestBody)?se(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=x(i,ue,pe),o=$e(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Ne(a.schema,this.document.components)}}:x(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:x(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(me)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=ze(e,this.document.components);if(!t)return{kind:`response`};let n=ge(t),r=n||ve(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=_e(t);if(i){if(h(i)){let e=y(i,this.document.components);if(Ce(e)&&h(e.items)){let t=et(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return ye(t)?{kind:`text`}:{kind:`response`}}groupOperations(){let e=new Map;for(let t of this.document.endpoints){let n=`${t.method.toUpperCase()} ${t.path}`,r=t.operation.tags??[];if(r.length===0)this.warnings.push(`Skipping ${n}: it has no tag, and the tag names its API client.`);else if(!t.operation.operationId)this.warnings.push(`Skipping ${n}: it has no operationId, and the operationId names its method.`);else for(let n of r)e.has(n)||e.set(n,new Set),e.get(n).add(t)}return e}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{e.has(t)||e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>e.set(t.name,t)),e}};function it(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function N(e){return`${e.path}/${e.name}`.toLowerCase()}function at(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return ot(n),n.map(e=>{let n=t[e],r=M(e);return{key:e,info:r,file:m(r),schema:n}})}function ot(e){let t=new Map;for(let n of e){let e=M(n),r=`${e.path===`/`?``:e.path}/${e.name}`;t.set(r,[...t.get(r)??[],n])}let n=[...t].filter(([,e])=>e.length>1);if(n.length!==0)throw new s(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function st(e,t){let n=[];return{model:{models:at(e),apiClients:nt(e,t,n)},warnings:n}}var ct=class{declarations=new Map;add(e,t){let n=this.declarations.get(e);n||(n=[],this.declarations.set(e,n));for(let e of t)n.some(t=>t.name===e)||n.push({name:e});return n}apply(e){for(let{moduleSpecifier:t,name:n,alias:r}of e){let e=this.add(t,[n]).find(e=>e.name===n);r!==void 0&&(e.alias=r)}}entries(){return[...this.declarations].flatMap(([e,t])=>t.map(({name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n}))}localNames(e){return[...this.declarations.values()].flat().filter(t=>t!==e).map(e=>e.alias??e.name)}structures(){return[...this.declarations].map(([e,t])=>({moduleSpecifier:e,namedImports:t.map(({name:e,alias:t})=>t===void 0?e:{name:e,alias:t})}))}},lt=class{sourceFile;imports=new ct;statements=[];constructor(e){this.sourceFile=e}get directoryPath(){return this.sourceFile.getDirectoryPath()}add(e){return this.statements.push(e),e}build(){let t=[],n;for(let r of this.imports.structures())n={...r,kind:e.StructureKind.ImportDeclaration},t.push(n);for(let e of this.statements)n&&ft(n,e)&&t.push(dt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},ut=class{open;modules=new Map;constructor(e){this.open=e}module(e){let t=this.open(e),n=t.getFilePath(),r=this.modules.get(n);return r||(r=new lt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},dt=e=>{e.blankLineIfLastNot()};function ft(t,n){if(typeof n==`string`)return!1;switch(n.kind){case e.StructureKind.TypeAlias:case e.StructureKind.VariableStatement:return typeof t==`string`||t.kind!==n.kind;default:return!0}}function pt(e,t){return{name:`[key: string]`,type:e,docs:t}}var mt=`@`;function P(e,t,n){return e.imports.add(t,n)}function ht(e,n,r){return r.path.startsWith(mt)?r.path:F(e.directoryPath,(0,t.join)(n,r.path,p))}function F(e,n){let r=(0,t.relative)(e,n).split(t.sep).join(`/`);return r=r.endsWith(`.ts`)?r.replace(/\.ts$/,`.js`):`${r}/index.js`,r.startsWith(`.`)?r:`./${r}`}function gt(e,t=`
2
+ `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(_t);return n.length>0?n.join(t):void 0}function _t(e){return e.replace(/\*\//g,`*\\/`)}function I(e,t){let n=gt(t);n&&(e.docs=[...e.docs??[],n])}function L(e,t,n=!1){e=bt(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&xt(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),St(r,e,`default`),St(r,e,`example`),wt(r,e),Tt(r,e),Et(r,e),r}function vt(e,t,n){I(e,L(t,n))}function yt(e,t,n,r=!1){let i=L(t,n,!0);r&&Ct(i,`schema`,t),I(e,i)}function bt(e){for(let t of[`anyOf`,`oneOf`]){let n=e[t];if(!Array.isArray(n)||n.length<2)continue;let r=n.filter(e=>`$ref`in e||e.type!==`null`),[i]=r;if(r.length!==1||`$ref`in i)continue;let a={...i};for(let[n,r]of Object.entries(e))n!==t&&r!==void 0&&(a[n]=r);return a}return e}function xt(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function St(e,t,n){let r=t[n];r&&(typeof r==`object`?Ct(e,n,r):e.push(`- ${n}: \`${r}\``))}function Ct(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function wt(e,t){let n=[`- Numeric Constraints`];t.minimum!==void 0&&n.push(` - minimum: ${t.minimum}`),t.maximum!==void 0&&n.push(` - maximum: ${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(` - exclusiveMinimum: ${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(` - exclusiveMaximum: ${t.exclusiveMaximum}`),t.multipleOf!==void 0&&n.push(` - multipleOf: ${t.multipleOf}`),n.length!==1&&e.push(...n)}function Tt(e,t){let n=[`- String Constraints`];t.minLength!==void 0&&n.push(` - minLength: ${t.minLength}`),t.maxLength!==void 0&&n.push(` - maxLength: ${t.maxLength}`),t.pattern!==void 0&&n.push(` - pattern: ${t.pattern}`),n.length!==1&&e.push(...n)}function Et(e,t){let n=[`- Array Constraints`];t.minItems!==void 0&&n.push(` - minItems: ${t.minItems}`),t.maxItems!==void 0&&n.push(` - maxItems: ${t.maxItems}`),t.uniqueItems!==void 0&&n.push(` - uniqueItems: ${t.uniqueItems}`),n.length!==1&&e.push(...n)}function Dt(e,t){let n;return{components:e,modelOf:n=>t.ofReference(n,e),namesAt(r){if(!n){n=new Map;for(let r of Object.keys(e?.schemas??{})){let e=t.ofKey(r),i=n.get(e.path);i||(i=[],n.set(e.path,i)),i.push(e.name,`${e.name}EnumText`)}}return n.get(r)??[]}}}var Ot=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],kt=new Set([`string`,`number`,`boolean`]),At=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function jt(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function R(e,t,n=new Set){if(h(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=y(e,t);return r?R(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(Ee(e)&&e.type===void 0){let r=e.allOf.map(e=>R(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>jt(e,i))?i:void 0}if(!(C(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:Me(e.type)}}}function Mt(e,t,n){let r=R(t,n);if(typeof r!=`object`)return!1;let i=R(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Nt(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>Mt(e,n,t))}function Pt(e){return e.nullable!==!0||S(e)||!C(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(h))}function Ft(e,t){return t.type===void 0||e===null&&t.nullable?!0:[t.type].flat().some(t=>t===`null`?e===null:t===`array`?Array.isArray(e):t===`object`?typeof e==`object`&&!!e&&!Array.isArray(e):t===`integer`?typeof e==`number`&&Number.isInteger(e):typeof e===t)}function z(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>z(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${A(e)}: ${z(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var It=class{scope;entries;requested=[];constructor(e){this.scope=e,this.entries=e.imports.entries().map(e=>({...e}))}get components(){return this.scope.context.components}imports(){return this.requested.map(({moduleSpecifier:e,name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n})}request(e){this.requested.includes(e)||this.requested.push(e)}reference(e){let t=this.scope.context.modelOf(e),{owner:n}=this.scope;if(n.path===t.path)return t.name;let r=this.scope.specifierOf(t),i=this.entries.find(e=>e.moduleSpecifier===r&&e.name===t.name);if(i||(i={moduleSpecifier:r,name:t.name},this.entries.push(i)),this.request(i),i.alias)return i.alias;let a=new Set([...Ot,n.name,...n.path===void 0?[]:this.scope.context.namesAt(n.path),...this.entries.filter(e=>e!==i).map(e=>e.alias??e.name)]);if(!a.has(t.name))return t.name;let o=`_${t.name}`;for(;a.has(o);)o=`_${o}`;return i.alias=o,o}additionalProperties(e){return e.additionalProperties===!1||e.additionalProperties===void 0&&!e.required?.some(t=>!Object.hasOwn(e.properties??{},t))?``:e.additionalProperties===!0||e.additionalProperties===void 0?`[key: string]: any`:`[key: string]: ${this.additionalPropertyType(e)}`}additionalPropertyType(e){return this.type(typeof e.additionalProperties==`object`?e.additionalProperties:{})}requiredAdditionalPropertyType(e){return e.additionalProperties===!1?`never`:typeof e.additionalProperties==`object`?this.type(e.additionalProperties):`null | string | number | boolean | globalThis.Record<string, unknown> | readonly unknown[]`}propertyDefinitions(e){let{properties:t}=e;return Object.entries(t).map(([e,t])=>{let n=this.type(t),r=(je(t)?`readonly `:``)+A(e);if(!h(t)){let e=gt(L(t),`
3
+ * `);if(e)return`
4
+ /**
5
+ * ${e}
6
+ */
7
+ ${r}: ${n}
8
+ `}return`${r}: ${n}`})}objectType(e){let t=[];Se(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${A(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Oe(e)&&Ae(e)?this.mapType(e):Nt(e,this.components)?`globalThis.Record<string, ${this.additionalPropertyType(e)}>`:void 0,r=n?``:this.additionalProperties(e);if(r&&t.push(r),t.length===0)return`globalThis.Record<string, any>`;let i=`{\n ${t.join(`;
9
+ `)}; \n}`;return n?`(${i} & ${n})`:i}mapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?`any`:this.type(e.additionalProperties)}mapKeyType(e){let t=Ae(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>h(e)?this.components&&y(e,this.components):e,n=t(e),r=new Map,i=new Set,a=n?[n]:[];for(let e of a){if(r.has(e))continue;let n=[e.allOf,e.oneOf,e.anyOf].map(e=>e?.map(t)??[]);r.set(e,n);for(let e of n)for(let t of e)t&&!r.has(t)&&a.push(t);(e.type===`object`||e.type===`null`||Array.isArray(e.type)&&e.type.length>0&&e.type.every(e=>e===`object`||e===`null`))&&i.add(e)}let o=!0;for(;o;){o=!1;for(let[e,[t,n,a]]of r){if(i.has(e))continue;let r=e=>e!==void 0&&i.has(e);(t.some(r)||[n,a].some(e=>e.length>0&&e.every(r)))&&(i.add(e),o=!0)}}return n!==void 0&&i.has(n)}type(e){if(h(e))return this.reference(e);if(Array.isArray(e.type))return e.type.map(t=>{let n=this.type({...e,type:t});return/[|&]/.test(n)?`(${n})`:n}).join(` | `);if(Pt(e))return`(${this.type({...e,nullable:!1})}) | null`;if(C(e)){let t=this.simpleComposition(e);if(t!==void 0)return t;let n=[`allOf`,`oneOf`,`anyOf`].flatMap(t=>{let n=e[t];return n?.length?[`(${n.map(n=>{let r=this.memberType(e,t,n);return r===`any`?`unknown`:/[|&]/.test(r)?`(${r})`:r}).join(t===`allOf`?` & `:` | `)})`]:[]}),r=n.length===1?n[0]:`(${n.join(` & `)})`,i={...e,oneOf:void 0,anyOf:void 0,allOf:void 0},a=this.type(i),o=a===`any`?r:`(${r} & (${a}))`;return this.objectConstrained(e)?`globalThis.Exclude<${o}, string | number | boolean | readonly unknown[]> & ({ readonly [globalThis.Symbol.iterator]?: never } | null)`:o}if(e.const!==void 0){if(!Ft(e.const,e))return`never`;let t=z(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!S(e))return`(${this.type({...e,nullable:!1})}) | null`;if(S(e)){let t=e.enum.filter(t=>Ft(t,e)).map(e=>z(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||kt.has(n)?t:`(${t}) & (${n})`}return Oe(e)&&!e.required?.length?this.mapType(e):e.type===`array`?De(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?Me(e.type):e.required?.length||Object.keys(e.properties??{}).length>0?`(${this.objectType({...e,type:`object`,additionalProperties:e.additionalProperties??!0})} | null | string | number | boolean | readonly unknown[])`:`any`}simpleComposition(e){let t=[`allOf`,`oneOf`,`anyOf`].filter(t=>e[t]?.length);if(t.length!==1)return;let[n]=t;if(Object.keys(e).filter(e=>e!==n&&e!==`discriminator`&&!e.startsWith(`x-`)&&!At.has(e)).length>0)return;let r=e[n],i=e=>n!==`allOf`&&[e.type].flat().every(e=>e===`null`)&&e.type!==void 0&&Object.keys(e).every(e=>e===`type`||At.has(e));if(!r.every(e=>h(e)||i(e)))return;let a=r.map(t=>h(t)?this.memberType(e,n,t):`null`);return[...new Set(a)].join(n===`allOf`?` & `:` | `)}memberType(e,t,n){let r=this.type(n),i=e.discriminator;if(t===`allOf`||!i?.propertyName||!h(n))return r;let a=ae(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>j(e)).join(` | `);return`(${r} & { ${A(i.propertyName)}: ${s} })`}};function B(e,t){let n=new It(e);return{text:t(n),imports:n.imports()}}function Lt(e,t){return B(t,t=>t.type(e))}function Rt(e,t){return B(t,t=>t.additionalProperties(e))}function zt(e,t){return B(t,t=>t.additionalPropertyType(e))}function Bt(e,t){return B(t,t=>t.requiredAdditionalPropertyType(e))}function Vt(e,t){return B(t,t=>t.mapValueType(e))}var Ht=`@ahoo-wang/fetcher`,Ut=[`ContentTypeValues`,`ResultExtractors`],Wt=`@ahoo-wang/fetcher-decorator`,Gt=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Kt={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},qt={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Jt=`{
10
+ headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
+ resultExtractor: JsonEventStreamResultExtractor,
12
+ }`;function Yt(e){P(e,Ht,Ut)}function Xt(e){P(e,Wt,Gt)}function Zt(t,n,r=[],i=[],a){return n.add({kind:e.StructureKind.Class,name:t,isExported:!0,typeParameters:i,extends:a,decorators:[{name:`api`,arguments:r}]})}function Qt(t){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]})}function $t(e){return e===`delete`?`del`:e}var en=`@ahoo-wang/fetcher-eventstream`;function tn(e){P(e,en,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function nn(e,t){let n=t.modules.module(e.file);Yt(n),Xt(n),tn(n);let r=Zt(e.className,n);I(r,[e.description]),Qt(r);let i=rn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(an(t,i))}function rn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>ht(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=Lt(e,r);return t.imports.apply(n.imports),n.text}}}function an(e,t){let n=[],r=[];for(let i of e.parameters)(i.required?n:r).push({name:i.name,type:i.schema?t.resolveType(i.schema):`string`,hasQuestionToken:!i.required,decorators:[{name:i.location,arguments:[j(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:on(e.body,t),hasQuestionToken:!e.body.required,decorators:[{name:`body`,arguments:[]}]});let i=[...n,...r,{name:`httpRequest`,hasQuestionToken:!0,type:`ParameterRequest`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}],a=sn(e.returns,t),o=j(e.path),s={name:e.name,decorators:[{name:$t(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return I(s,[...e.docs]),s}function on(e,t){let{content:n}=e;switch(n.kind){case`json`:{let e=t.resolveType(n.schema),r=n.optionalFields;return r.length===0||/[|&]/.test(e)||e===`any`?e:(P(t.module,Ht,[`PartialBy`]),`PartialBy<${e}, ${r.map(j).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function sn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?qt:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Jt};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Jt}}case`text`:return qt;case`response`:return Kt}}function cn(e){return Dt(e,{ofKey:e=>M(e),ofReference:et})}function ln(e,t){new dn(e,t.modules.module(e.file),t).write()}function un(e){let t=new Set,n=new Map;for(let r of e){let e=Ye(r),i=[e];/^\d/.test(r)||i.push(r);let a=i.find(e=>!t.has(e));for(let n=2;a===void 0;n++)t.has(`${e}_${n}`)||(a=`${e}_${n}`);t.add(a),n.set(r,A(a))}return n}var dn=class{model;module;target;modelInfo;components;constructor(e,t,n){this.model=e,this.module=t,this.target=n,this.modelInfo=e.info,this.components=n.types.components,this.scope={context:n.types,owner:e.info,specifierOf:e=>ht(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&yt(e,this.model.schema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return h(e)?this.processTypeAlias(e):S(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||C(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Se(e)?this.processInterface(e):Oe(e)&&typeof e.additionalProperties==`object`&&!Ae(e)&&!e.required?.length?this.processIndexSignature(e):Ce(e)?this.processArray(e):C(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(Lt(e,this.scope))}processEnum(t){let n=xe(t);if(n){let t=un(Object.keys(n));this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name+`EnumText`,isExported:!0,members:[...t].map(([e,t])=>({name:t,initializer:z(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=un(r);return C(t)||t.const!==void 0||t.type!==void 0&&t.type!==`string`||t.enum.some(e=>typeof e!=`string`)?(r.length&&this.module.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:this.modelInfo.name,initializer:e=>{e.inlineBlock(()=>{for(let t of r)e.write(`${i.get(t)}: `).quote(t).write(`,`).newLine()}),e.write(` as const`)}}]}),this.processTypeAlias(t)):this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name,isExported:!0,members:r.map(e=>({name:i.get(e),initializer:z(e)}))})}addPropertyToInterface(e,t,n){let r={name:A(t),type:this.resolveType(n),isReadonly:je(n)};(e.properties??=[]).push(r),vt(r,n)}processInterface(t){if(Nt(t,this.components))return this.processTypeAlias(t);let n=[],r=this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:n}),i=t.properties||{};Object.entries(i).forEach(([e,t])=>{this.addPropertyToInterface(r,e,t)});for(let e of t.required??[])Object.hasOwn(i,e)||n.push({name:A(e),type:this.emit(Bt(t,this.scope))});return this.emit(Rt(t,this.scope))&&n.push(pt(this.emit(zt(t,this.scope)),[`Additional properties`])),r}processArray(t){let n=this.resolveType(t.items);return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:De(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[pt(this.emit(Vt(t,this.scope)))]})}processComposition(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}processTypeAlias(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}};function fn(e,t){e.models.forEach(e=>ln(e,t)),e.apiClients.forEach(e=>nn(e,t))}function pn(e,t){let n=[];return mn(e,t,n),n}function mn(e,t,n){let r=[];for(let t of e.getSourceFiles()){let e=t.getBaseName();e.endsWith(`.ts`)&&e!==`index.ts`&&r.push({specifier:`./${t.getBaseNameWithoutExtension()}.js`,exports:gn(t)})}for(let i of e.getDirectories()){let e=mn(i,t,n);e&&r.push({specifier:`./${i.getBaseName()}/index.js`,exports:e})}let i=e.getPath();return r.length===0?e.getProject().getSourceFile(`${i}/index.ts`)?new Map:void 0:hn(i,r,t,n)}function hn(e,t,n,r){let i=new Map;for(let e of t)for(let t of e.exports.keys())i.set(t,[...i.get(t)??[],e.specifier]);let a=[...i].filter(([,e])=>e.length>1).map(([e])=>e).sort();for(let t of a)r.push(`${t} is exported by both ${i.get(t).join(` and `)} in ${e}; its index leaves it out, so import it from its own module.`);let o=n(e);o.removeText();let s=new Map;for(let e of t){let t=[...e.exports].filter(([e])=>!a.includes(e)).sort(([e],[t])=>b(e,t));t.forEach(([e,t])=>s.set(e,t)),t.length===e.exports.size?o.addExportDeclaration({moduleSpecifier:e.specifier}):t.length>0&&o.addExportDeclaration({moduleSpecifier:e.specifier,namedExports:t.map(([e,t])=>({name:e,isTypeOnly:t}))})}return o.getStatements().length===0&&o.addStatements(`export {};`),s}function gn(t){let n=new Map;for(let[r,i]of t.getExportedDeclarations())n.set(r,i.every(t=>e.Node.isInterfaceDeclaration(t)||e.Node.isTypeAliasDeclaration(t)));return n}function _n(t){let n=t;for(let t=n.getParent();t;n=t,t=t.getParent())if(e.Node.isQualifiedName(t)){if(t.getLeft()!==n)return!1}else if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1}else{if(e.Node.isExpressionWithTypeArguments(t)){let n=t.getParent(),r=n?.getParent();return!(e.Node.isHeritageClause(n)&&n.getToken()===e.SyntaxKind.ExtendsKeyword&&(e.Node.isClassDeclaration(r)||e.Node.isClassExpression(r)))}return e.Node.isTypeNode(t)}return!1}function vn(t){let n=t.getImportDeclarations().filter(e=>!e.getDefaultImport()&&!e.getNamespaceImport()&&e.getNamedImports().length>0);if(n.length===0)return[];let r=new Set(n.flatMap(e=>e.getNamedImports().map(e=>(e.getAliasNode()??e.getNameNode()).getText()))),i=new Set;return t.forEachDescendant((t,n)=>{if(e.Node.isImportDeclaration(t))n.skip();else if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!_n(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>yn(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function yn(e,t){let n=e.getNamedImports(),r=n.map(t),i=r.every(Boolean);return()=>{n.forEach((e,t)=>{let n=!i&&r[t];e.isTypeOnly()!==n&&e.setIsTypeOnly(n)}),e.isTypeOnly()!==i&&e.setIsTypeOnly(i)}}function bn(e){let t=e.flatMap(vn);for(let e of t)e()}var xn=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function Sn(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!xn.has(t.getCode())||t.getSourceFile()!==r)continue;let i=e.ts.flattenDiagnosticMessageText(t.compilerObject.messageText,` `);n.push(`${r.getFilePath()}:${t.getLineNumber()??0} TS${t.getCode()} ${i}`)}if(n.length>0)throw Error(`The generated code does not compile; nothing was written. This is a wow-generator bug:\n${n.join(`
13
+ `)}`)}var Cn=`// Code generated by wow-generator. DO NOT EDIT.
14
+
15
+ `,wn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function Tn(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(wn),n.organizeImports(wn)}),bn(e),Sn(e);for(let t of e)t.insertText(0,Cn)}var En=3e4;function Dn(e){return/^https?:\/\//i.test(e)}function On(e,t={}){return Dn(e)?kn(e,t):jn(e)}async function kn(e,t={}){let n=t.timeoutMs??3e4,r;try{let i=AbortSignal.timeout(n);r=await fetch(e,{headers:t.headers,signal:t.signal?AbortSignal.any([t.signal,i]):i})}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no response within ${n} ms`:An(e);throw Error(t,{cause:e})}if(!r.ok){let e=[r.status,r.statusText].filter(Boolean).join(` `);throw Error(`HTTP ${e}`)}return await r.text()}function An(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error&&t.message?`${e.message} (${t.message})`:e.message}function jn(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Mn(e,t){let n;try{n=await On(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Pn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Nn(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new s(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new s(`input`,`${t} is a Swagger ${String(n.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`);if(typeof n.openapi!=`string`||!/^3\.\d+/.test(n.openapi))throw new s(`input`,`${t} is not an OpenAPI 3.x document: its "openapi" field is ${n.openapi===void 0?`missing`:JSON.stringify(n.openapi)}.`);if(typeof n.info!=`object`||n.info===null||Array.isArray(n.info))throw new s(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Pn(e){switch(Fn(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function Fn(e){let t=e.trimStart();if(t.startsWith(`{`)||t.startsWith(`[`))return`json`;if(t.startsWith(`-`)||t.startsWith(`%YAML`))return`yaml`;try{return JSON.parse(t),`json`}catch{if(t.length>0)return`yaml`}throw Error(`Unable to infer file format`)}async function In(e,t,n){if(e!==void 0)return{...await zn({path:e,explicit:!0},t,n),origin:V(e)};let r=await zn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:V(a)}}var Ln=[`apiClients`],Rn=[`ignorePathParameters`,`methodNames`];async function zn(e,t,n){let r=V(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await On(e.path,n)}catch(n){if(!e.explicit&&Bn(n)){t.debug(`No configuration file at ${r}`);return}throw new s(`configuration`,`Cannot read configuration ${r}: ${c(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Pn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Hn(a,r);return t.debug(`Configuration loaded from ${r}: ${Wn(o.config)}`),o}function V(e){return Dn(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Bn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function H(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vn(e,t,n,r,i){let a=Object.keys(r).filter(e=>!i.includes(e));a.length&&e.push(`Ignoring unknown ${n} option(s) in ${t}: ${a.join(`, `)}. Known option(s): ${i.join(`, `)}`)}function Hn(e,t){if(!U(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${H(e)}`);let n=[];return Vn(n,t,`configuration`,e,Ln),Un(e.apiClients,t,n),{config:e,warnings:n}}function Un(e,t,n){if(e!==void 0){if(!U(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${H(e)}`);for(let[r,i]of Object.entries(e)){if(!U(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${H(i)}`);Vn(n,t,`apiClients["${r}"]`,i,Rn);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new s(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${H(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!U(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${H(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!w(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Wn(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Gn=new Set,Kn=`#/$defs/`;function W(e){return e.startsWith(Kn)?e.slice(8):void 0}function qn(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.openapi===void 0&&t.swagger===void 0&&typeof t.format==`number`&&Array.isArray(t.contexts)}function G(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jn(e,t){let n=e;if(n.format!==1)throw new s(`input`,`${t} is a Wow Manifest of format ${n.format}; wow-generator reads format 1.`);let r=(n.requires??[]).filter(e=>!Gn.has(e));if(r.length>0)throw new s(`input`,`${t} requires ${r.join(`, `)}, which this wow-generator does not understand: generate with a newer one.`);let i=[];if(n.contexts.forEach((e,t)=>{!G(e)||typeof e.name!=`string`?i.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let r=`${e.name}.aggregates[${n}]`;!G(t)||typeof t.name!=`string`?i.push(`${r} has no name`):!G(t.state)||typeof t.state.schema!=`string`?i.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`a command of ${e.name}.${t.name} has no name or schema`)}),(t.events??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!G(n.$defs)&&i.push(`$defs is not an object`),i.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${i.join(`; `)}.`);return n}var Yn=new Set([`int64`,`bigint`,`decimal`]),Xn={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Zn=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),Qn=4;function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function $n(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>/ [|&] /.test(e)&&!e.startsWith(`{`)?`(${e})`:e).join(t)}function er(e){return typeof e==`string`?j(e):JSON.stringify(e)}var tr=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e){let t=new Set(e);for(let e=0;t.size>0;e++){let n=new Map;for(let r of t.keys()){let t=r.split(`.`),i=t[t.length-1].split(`$`),a=E([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?D(e):e));n.set(a,[...n.get(a)??[],r])}let r=new Set(this.names.values());for(let[i,a]of n){let n=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!r.has(i)?a:n;for(let e of o){let n=i;for(let e=2;r.has(n);e++)n=`${i}${e}`;r.add(n),this.names.set(e,n),t.delete(e)}}}}schemaOf(e){let t=this.defs[e];return K(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=W(n);if(r===void 0||t.has(r))return e;let i=this.schemaOf(r);return i?this.resolve(i,new Set([...t,r])):e}references(e,t=new Set){if(Array.isArray(e))e.forEach(e=>this.references(e,t));else if(K(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=W(r);e!==void 0&&t.add(e)}else n!==`enum`&&n!==`const`&&this.references(r,t);return t}namedReferences(e){let t=new Set;for(let n of this.references(e)){let e=this.schemaOf(n);e!==void 0&&this.inlined(n)?this.namedReferences(e).forEach(e=>t.add(e)):t.add(n)}return t}closure(e){let t=new Set,n=[...e];for(;n.length>0;){let e=n.pop();if(t.has(e))continue;t.add(e);let r=this.schemaOf(e);r&&n.push(...this.references(r))}return[...t]}refType(e,t){let n=this.schemaOf(e);if(n!==void 0&&this.inlined(e))return this.type(n,t);let r=this.names.get(e);return r!==void 0&&this.schemaOf(e)?r:(this.warnings.push(`${t} refers to the schema ${e}, which the Manifest's $defs does not hold; it is typed as unknown.`),`unknown`)}type(e,t){if(e===!0||e===void 0)return`unknown`;if(e===!1)return`never`;if(!K(e))return`unknown`;if(typeof e.$ref==`string`){let n=W(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return er(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:$n(e.enum.map(er),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return $n(i.map(e=>this.type(e,t)),r)}let n=q(e);return n.length===0?K(e.properties)?this.objectType(e,t):`unknown`:$n(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return typeof t.format==`string`&&Yn.has(t.format)?`string`:`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return/ [|&] /.test(e)?`(${e})[]`:`${e}[]`}case`object`:return this.objectType(t,n);default:return`unknown`}}objectType(e,t){let n=this.properties(e,t),r=this.additional(e,t);if(n.length===0)return`Record<string, ${r??`unknown`}>`;let i=n.map(e=>`${e.name}${e.optional?`?`:``}: ${e.type}`);return r!==void 0&&i.push(`[key: string]: unknown`),`{ ${i.join(`; `)} }`}properties(e,t){if(!K(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=K(r)?r.description:void 0;return{name:A(e),type:this.type(r,`${t}.${e}`),optional:!n.has(e),...typeof i==`string`?{description:i}:{}}})}additional(e,t){let n=e.additionalProperties;if(n!==void 0&&n!==!1)return this.type(n,t)}isInterface(e){let t=q(e);return K(e.properties)&&(t.length===0||t.length===1&&t[0]===`object`)&&e.$ref===void 0&&e.allOf===void 0&&e.oneOf===void 0&&e.anyOf===void 0}textNumbers(e,t=new Set){if(!K(e))return;let n=typeof e.$ref==`string`?W(e.$ref):void 0;if(n!==void 0){let e=this.schemaOf(n);return t.has(n)||e===void 0?void 0:this.textNumbers(e,new Set([...t,n]))}let r=[`oneOf`,`anyOf`,`allOf`].flatMap(t=>Array.isArray(e[t])?e[t]:[]).map(e=>this.textNumbers(e,t)).filter(e=>e!==void 0),i=q(e);(i.includes(`integer`)||i.includes(`number`))&&typeof e.format==`string`&&Yn.has(e.format)&&r.push(!0);let a={};if(K(e.properties))for(let[n,r]of Object.entries(e.properties)){let e=this.textNumbers(r,t);e!==void 0&&(a[n]=e)}let o=this.textNumbers(e.items,t)??this.textNumbers(e.additionalProperties,t);return o!==void 0&&(a[`*`]=o),Object.keys(a).length>0&&r.push(a),nr(r)}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?W(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!K(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<Qn&&K(r)&&(q(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function nr(e){if(e.length===0)return;let t=e.filter(e=>e!==!0);if(t.length===0)return!0;let n={};for(let e of t)for(let[t,r]of Object.entries(e))(n[t]??=[]).push(r);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,nr(t)]))}function rr(e,t){if(t===void 0)return!0;let n=e.resolve(t);return!Array.isArray(n.required)||n.required.length===0}function ir(e){return(e.commands??[]).filter(e=>e.system!==!0)}function ar(e){return(e.commands??[]).filter(e=>e.system===!0&&e.name.startsWith(`wow.lifecycle.`))}function or(e,t){return[t.state.schema,...ir(t).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(W).filter(e=>e!==void 0).concat(sr(e,t))}function sr(e,t){return ar(t).map(e=>e.name).filter(t=>Xn[t]!==void 0&&e.schemaOf(t))}function cr(e){let t=new tr(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=[...(e.aggregates??[]).flatMap(e=>or(t,e)),...(e.routes??[]).flatMap(e=>[...t.references(e.request),...t.references(e.response)])];for(let i of t.closure(n).sort(b))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(b));let a=i.map(e=>lr(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>b(e.file,t.file)||b(e.name,t.name)),o=n.map(e=>ur(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function lr(e,t,n){let r=e.schemaOf(t),i=e.names.get(t),a=typeof r.description==`string`?r.description:void 0,o=[...e.namedReferences(r)].map(t=>e.names.get(t)).filter(e=>e!==void 0&&e!==i),s={key:t,name:i,file:n,...a===void 0?{}:{description:a},references:[...new Set(o)].sort(b)};if(e.isInterface(r)){let n=e.additional(r,t);return{...s,properties:e.properties(r,t),...n===void 0?{}:{type:`unknown`}}}return{...s,type:e.type(r,t)}}function ur(e,t){return{name:t.name,...t.description?{description:t.description}:{},typeName:E(D(t.name)),constantName:k(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(b),aggregates:(t.aggregates??[]).map(n=>pr(e,t,n)),routes:(t.routes??[]).map(n=>{let r=`${t.name} route ${n.name}`;return{name:n.name,method:n.route.method,path:n.route.path,...n.description?{description:n.description}:{},deprecated:n.deprecated===!0,parameters:(n.parameters??[]).map(t=>({name:t.name,location:t.in===`path`?`path`:`query`,type:e.type(t.schema,`${r} ${t.name}`),required:t.required})),...n.request===void 0?{}:{requestType:e.type(n.request,`${r} body`)},...n.response===void 0?{}:{responseType:e.type(n.response,`${r} answer`)}}})}}function dr(e){return(e.routes??[]).map(e=>({method:e.method,path:e.path}))}function fr(e,t,n){let r=W(t);return r===void 0?`unknown`:e.refType(r,n)}function pr(e,t,n){let r=`${t.name}.${n.name}`,i=E(D(n.name)),a=n.idSource??`assigned`,o=a===`owner`,s=new Set(sr(e,n)),c=ar(n).filter(e=>Zn.has(e.name)).map(t=>{let n=t.name,i=n.split(`.`).pop(),a=e.schemaOf(n)?.description,c=T(O(i)),l=o&&(t.routes??[]).some(e=>!e.path.includes(`{id}`));return{name:n,member:k(i),method:c,routes:dr(t),...l?{ownMethod:`${c}Own`}:{},...s.has(n)?{bodyType:e.refType(n,r),bodyGenerated:!0}:Xn[n]?{bodyType:Xn[n]}:{},...typeof a==`string`?{description:a}:{}}}),l=new Set(c.flatMap(e=>[e.method,e.ownMethod??e.method])),u=ir(n).map(t=>{let n=T(O(t.name));(l.has(n)||n===`gateway`)&&(n=`${n}Command`),l.add(n);let i=(t.routes??[]).filter(e=>e.method===`POST`),a=i.find(e=>e.path.includes(`{id}`)),s=i.find(e=>!e.path.includes(`{id}`)),c;o&&a&&s&&!(t.mounted??!1)&&(c=`${n}Own`,l.has(c)&&(c=`${c}Command`),l.add(c));let u=W(t.schema);return{name:t.name,method:n,routes:dr(t),...a?{byIdPath:{path:a.path}}:{},...s?{unaddressedPath:{path:s.path}}:{},...c===void 0?{}:{ownMethod:c},bodyType:fr(e,t.schema,`${r}.${t.name}`),bodyOptional:rr(e,u===void 0?void 0:e.schemaOf(u)),creation:t.creation??`none`,mounted:t.mounted??!1,produces:t.produces??[],...t.description?{description:t.description}:{},...e.textNumbers({$ref:t.schema})===void 0?{}:{bodyNumbers:!0}}}),d=e.textNumbers({$ref:n.state.schema}),f=Object.fromEntries((n.events??[]).flatMap(r=>{let i=e.textNumbers({$ref:r.schema});return i===void 0?[]:[[mr(t,n,r.name),i]]})),p=Object.fromEntries(ir(n).flatMap(t=>{let n=e.textNumbers({$ref:t.schema});return n===void 0?[]:[[t.name,n]]})),m={...d===void 0?{}:{state:d},...Object.keys(f).length===0?{}:{events:f},...Object.keys(p).length===0?{}:{commands:p}},h=W(n.state.schema),g=h===void 0?void 0:e.schemaOf(h);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`owner`,idSource:a,snapshot:n.snapshot?.enabled??!0,stateType:fr(e,n.state.schema,`${r} state`),stateFields:g===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:u,events:(n.events??[]).map(i=>({name:i.name,wireName:mr(t,n,i.name),revision:i.revision??1,type:fr(e,i.schema,`${r}.${i.name}`)})),lifecycle:c,queryModels:(n.queries??[]).map(e=>e.model),...Object.keys(m).length===0?{}:{textNumbers:m}}}function mr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var J=`@ahoo-wang/wow-client`,hr=`@ahoo-wang/wow-client/routes`;function Y(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>_t(e).split(`
16
+ `));return n.length===0?``:n.length===1?`${t}/** ${n[0]} */\n`:`${t}/**\n${n.map(e=>`${t} * ${e}`.trimEnd()).join(`
17
+ `)}\n${t} */\n`}function X(e,t){e.add(`\n${t}`)}function Z(e){return e.length===0?`never`:e.join(` | `)}function Q(e,t,n,r,a){let o=new Map;for(let e of new Set(r)){let t=n.get(e);t!==void 0&&t!==a&&o.set(t,[...o.get(t)??[],e])}for(let[n,r]of o)e.imports.add(F(e.directoryPath,(0,i.join)(t,n)),r)}function gr(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)_r(t.module(i.file),i,r,n);for(let i of e.contexts){br(i,t,n);for(let e of i.aggregates)Dr(e,i,t,r,n),jr(e,i,t,r,n),Mr(e,t,r,n);xr(i,t),Sr(i,t,r,n),wr(i,t,n)}}function _r(e,t,n,r){Q(e,r,n,t.references,t.file);let i=Y([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){X(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${Y([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),X(e,`${i}export interface ${t.name} {\n${a.join(`
18
+ `)}\n}`)}function vr(e,t){let n=e.aggregates.map(t=>`${e.name}.${t.name}.`),r=t===void 0?`${e.name}.`:`${e.name}.${t.name}.`;return e.errors.filter(e=>t===void 0?!n.some(t=>e.code.startsWith(t)):e.code.startsWith(r)).map(e=>({member:k((e.code.startsWith(r)?e.code.slice(r.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,error:e}))}function yr(e,t){return e.length===0?``:`${t}Errors: {\n${e.map(({member:e,error:n})=>`${Y([`${n.status}: ${n.description??n.code}`],`${t} `)}${t} ${e}: ${j(n.code)},`).join(`
19
+ `)}\n${t}},\n`}function br(e,t,n){let r=t.module(`${e.directory}/contract.ts`),a=`${e.typeName}Contract`;r.imports.add(J,[`Hop`,`wait`]);for(let t of e.aggregates)r.imports.add(F(r.directoryPath,(0,i.join)(n,t.directory,`aggregate.ts`)),[`${t.typeName}Aggregate`]);let o=e.aggregates.map(e=>` ${e.typeName}: ${e.typeName}Aggregate,\n`);X(r,`${Y([`The bounded context \`${e.name}\`: its name, its error codes and its aggregates, as the Kotlin \`${a}\` names them. A problem's \`code\` is one of its \`Errors\`, or of an aggregate's.`,e.description])}export const ${a} = {\n NAME: ${j(e.name)},\n${yr(vr(e),` `)}${o.join(``)}} as const;`),X(r,`${Y([`An error code of \`${e.name}\`, of the context or of one of its aggregates.`])}export type ${e.typeName}ErrorCode = ${Z(e.errors.map(e=>j(e.code)))};`);let s=e.subscriptions.length>0;s&&X(r,`${Y([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${Z(e.subscriptions.map(j))};`);let c=`${a}.NAME`,l=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${c}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${c}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${c}),`];s&&l.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${c}),`),X(r,`${Y([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${O(e.name)}Wait = {\n${l.join(`
20
+ `)}\n} as const;`)}function xr(e,t){let n=t.module(`${e.directory}/manifest.ts`),r=`${e.typeName}Manifest`;n.imports.add(J,[`MANIFEST_FORMAT`,`RoutingManifest`]);let i=(e,t)=>` { name: ${j(e)}, routes: ${kr(t)} },`,a=e.aggregates.map(e=>{let t=[...e.commands.filter(e=>e.routes.length>0).map(e=>i(e.name,e.routes)),...e.lifecycle.map(e=>i(e.name,e.routes))];return` {\n name: ${j(e.name)},\n commands: [\n${t.join(`
21
+ `)}\n ],\n },`}),o=e.routes.map(e=>` { name: ${j(e.name)}, route: { method: ${j(e.method)}, path: ${j(e.path)} } },`),s=o.length===0?``:` routes: [\n${o.join(`
22
+ `)}\n ],\n`;X(n,`${Y([o.length===0?`The routes of \`${e.name}\`'s commands, as its Manifest lists them: what its command clients send by, with no Manifest fetched and no schema.`:`The routes of \`${e.name}\`'s commands and service routes, as its Manifest lists them: what its clients send by, with no Manifest fetched and no schema.`])}export const ${r}: RoutingManifest = {\n format: MANIFEST_FORMAT,\n contexts: [\n {\n name: ${j(e.name)},\n aggregates: [\n${a.join(`
23
+ `)}\n ],\n${s} },\n ],\n};`)}function Sr(e,t,n,r){if(e.routes.length===0)return;let i=t.module(`${e.directory}/routes.ts`),a=`${e.typeName}Routes`;i.imports.add(J,[`RequestOptions`,`WowClientOptions`]),i.imports.add(hr,[`ServiceRoutes`]),i.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]),Q(i,r,n,e.routes.flatMap(e=>[e.requestType,e.responseType,...e.parameters.map(e=>e.type)].filter(e=>e!==void 0).flatMap(e=>e.match(/[A-Za-z_$][A-Za-z0-9_$]*/g)??[])));let o=e.routes.map(t=>Cr(e,t));X(i,`${Y([`The service routes of \`${e.name}\`: routes whose handler is the service's own code, each called by its Manifest's name.`])}export class ${a} {\n /** Calls any route of the service by its name. */\n readonly routes: ServiceRoutes;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.routes = new ServiceRoutes(options, { manifest: ${e.typeName}Manifest });\n }\n\n${o.join(`
24
+
25
+ `)}\n}`)}function Cr(e,t){let n=t.parameters.filter(e=>e.location===`path`),r=t.parameters.filter(e=>e.location===`query`),i=n.map(e=>`${e.name}: ${e.type}`);if(t.requestType!==void 0&&i.push(`body: ${t.requestType}`),r.length>0){let e=r.map(e=>`readonly ${A(e.name)}${e.required?``:`?`}: ${e.type}`).join(`; `),t=r.some(e=>e.required);i.push(`query${t?``:`?`}: { ${e} }`)}i.push(`options?: RequestOptions`);let a=t.responseType??`void`,o=[...n.length===0?[]:[`path: { ${n.map(e=>A(e.name)).join(`, `)} }`],...t.requestType===void 0?[]:[`body`],...r.length===0?[]:[`query`]];return`${Y([t.description,`\`${t.method} ${t.path}\``,t.deprecated?`@deprecated The service deprecates this route.`:void 0],` `)} ${A(t.name)}(${i.join(`, `)}): Promise<${a}> {\n return this.routes.call(${j(e.name)}, ${j(t.name)}, { ${o.join(`, `)} }, options) as Promise<${a}>;\n }`}function wr(e,t,n){let r=t.module(`${e.directory}/client.ts`),a=`${e.typeName}Client`;r.imports.add(J,[`CommandClient`,`WowClientOptions`]),r.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]);let o=[],s=[];for(let t of e.aggregates){let e=t.typeName,a=e=>F(r.directoryPath,(0,i.join)(n,t.directory,e)),c=[[`commands`,`${e}CommandClient`]];t.queryModels.includes(`snapshot`)&&c.push([`snapshots`,`${e}SnapshotQueryClient`]),t.queryModels.includes(`events`)&&c.push([`events`,`${e}EventQueryClient`]),c.push([`state`,`${e}StateClient`]),r.imports.add(a(`commandClient.ts`),[`${e}CommandClient`]),r.imports.add(a(`queryClient.ts`),c.slice(1).map(([,e])=>e));let l=A(O(t.name));o.push(`${Y([`The clients of \`${t.context}.${t.name}\`.`],` `)} readonly ${l}: {\n${c.map(([e,t])=>` readonly ${e}: ${t};`).join(`
26
+ `)}\n };`),s.push(` this.${l} = {\n${c.map(([e,t])=>` ${e}: new ${t}(options),`).join(`
27
+ `)}\n };`)}e.routes.length>0&&(r.imports.add(`./routes.js`,[`${e.typeName}Routes`]),o.push(`${Y([`The service routes of \`${e.name}\`.`],` `)} readonly routes: ${e.typeName}Routes;`),s.push(` this.routes = new ${e.typeName}Routes(options);`)),X(r,`${Y([e.routes.length===0?`The clients of \`${e.name}\`: its command client, and per aggregate its command, query and state clients.`:`The clients of \`${e.name}\`: its command client, per aggregate its command, query and state clients, and its service routes.`])}export class ${a} {\n /** Sends any command of the service, by its Manifest's routes: \`send\`, \`wait\` and \`stream\`. */\n readonly commands: CommandClient;\n\n${o.join(`
28
+
29
+ `)}\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.commands = new CommandClient(options, { manifest: ${e.typeName}Manifest });\n${s.join(`
30
+ `)}\n }\n}`)}function Tr(e){return e===!0?`true`:`{ ${Object.entries(e).map(([e,t])=>`${A(e)}: ${Tr(t)}`).join(`, `)} }`}function Er(e){let t=e.textNumbers;return t===void 0?``:` textNumbers: {\n${[`state`,`events`,`commands`].flatMap(e=>{let n=t[e];return n===void 0?[]:e===`state`?[` state: ${Tr(n)},`]:[` ${e}: {\n${Object.entries(n).map(([e,t])=>` ${A(e)}: ${Tr(t)},`).join(`
31
+ `)}\n },`]}).join(`
32
+ `)}\n },\n`}function Dr(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;X(a,`${Y([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${j(t.name)},\n name: ${j(e.name)},\n path: ${j(`/${t.name}/${e.name}`)},\n ownership: ${j(e.ownership)},\n${e.idSource===`assigned`?``:` idSource: ${j(e.idSource)},\n`} snapshot: ${e.snapshot},\n${Er(e)}${yr(vr(t,e),` `)}} as const;`),X(a,`${Y([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${Z(e.stateFields.map(j))};`);let s=e.events.map(e=>`CommittedEvent<${j(e.wireName)}, ${e.type}>`);a.imports.add(J,s.length>0?[`CommittedEvent`,`SystemEvent`]:[`SystemEvent`]),X(a,`${Y([`The events of \`${e.name}\`, named as the server sends them, \`${e.context}.${e.name}.<Event>\` at its current revision (the \`events\` query upgrades older records), and the system events every aggregate has.`])}export type ${o}Event = ${Z([...s,`SystemEvent`])};`),Q(a,i,r,e.events.map(e=>e.type))}function Or(e,t){let n=(t===void 0?[e.byIdPath,e.unaddressedPath]:[t?e.unaddressedPath:e.byIdPath]).filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),r=e.creation===`required`?`Creates the aggregate.`:e.creation===`allowed`?`Creates the aggregate, or acts on the one that exists.`:void 0;return Y([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}${t===!0?`, to the caller's own aggregate, whose id is the caller's owner`:``}: ${n}.`,t===!1?"By id, for a caller with no owner; `"+e.ownMethod+"` sends it to the caller's own.":void 0,r,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function kr(e){return`[${e.map(e=>`{ method: ${j(e.method)}, path: ${j(e.path)} }`).join(`, `)}]`}function $(e,t,n,r){let i=e.bodyType===`unknown`?`object`:e.bodyType,a=e.bodyOptional?`body: ${i} = {}`:`body: ${i}`,o=n?`stream`:`wait`,s=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,c=r===!0?e.ownMethod:e.method,l=n?`${c}Stream`:c,u=n?Y([`\`${e.name}\`${r===!0?` to the caller's own aggregate`:``}, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):Or(e,r),d=j(`${t.context}.${t.name}.${e.name}`),f=e=>`{ ...options, command: ${d}, body${e} }`,p=r===void 0?e.byIdPath:!r,m=r===void 0?e.unaddressedPath:r,h=p&&m?`CreateCommandOptions`:`CommandOptions`,g=p&&!m?`id: string, `:``,ee=f(p&&!m?`, id`:``);return n?`${u} ${l}(${g}${a}, options?: ${h}): ${s} {\n return this.client.${o}(${ee});\n }`:Ar(u,l,`${g}${a}`,h,ee)}function Ar(e,t,n,r,i){return`${e} ${t}(${n?`${n}, `:``}options?: ${r}): Promise<CommandResult> {\n return this.client.wait(${i});\n }`}function jr(e,t,n,r,a){let o=n.module(`${e.directory}/commandClient.ts`),s=e.typeName,c=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),l=c.flatMap(t=>t.ownMethod===void 0?[$(t,e,!1),$(t,e,!0)]:[!1,!0].flatMap(n=>[$(t,e,!1,n),$(t,e,!0,n)])),u=[`CommandClient`,`CommandResult`,`WowClientOptions`];c.length>0&&u.push(`CommandResultStream`);let d=e=>e.byIdPath!==void 0&&e.unaddressedPath!==void 0&&e.ownMethod===void 0;c.some(d)&&u.push(`CreateCommandOptions`),(c.some(e=>!d(e))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let f=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?f:u).push(t.bodyType);let n=t.bodyType?`body: ${t.bodyType}`:``,r=n=>`{ ...options, command: LifecycleCommands.${t.member}, type: { context: ${j(e.context)}, name: ${j(e.name)} }${n?`, id`:``}${t.bodyType?`, body`:``} }`;l.push(Ar(Y([t.description,`The lifecycle command \`${t.name}\`.`,t.ownMethod===void 0?void 0:`By id, for a caller with no owner; \`${t.ownMethod}\` sends it to the caller's own.`],` `),t.method,n?`id: string, ${n}`:`id: string`,`CommandOptions`,r(!0))),t.ownMethod!==void 0&&l.push(Ar(Y([t.description,`The lifecycle command \`${t.name}\`, to the caller's own aggregate, whose id is the caller's owner.`],` `),t.ownMethod,n,`CommandOptions`,r(!1)))}let p=c.filter(e=>e.bodyNumbers);p.length>0&&o.imports.add(`./aggregate.js`,[`${s}Aggregate`]);let m=p.length?`, bodyNumbers: {\n${p.map(t=>` ${j(`${e.context}.${e.name}.${t.name}`)}: ${s}Aggregate.textNumbers.commands.${A(t.name)===t.name?t.name:`[${j(t.name)}]`},`).join(`
33
+ `)}\n }`:``,h=`${t.typeName}Manifest`;o.imports.add(F(o.directoryPath,(0,i.join)(a,t.directory,`manifest.ts`)),[h]),o.imports.add(J,[...new Set(u)].sort()),Q(o,a,r,[...c.map(e=>e.bodyType),...f]),X(o,`${Y([`Sends the commands of \`${e.context}.${e.name}\` by its service's routes (\`${h}\`). Each method answers the result its wait plan ends with, as \`CommandClient.wait\` does: the server's default plan unless the options give one, \`{ wait: WaitPlan.ACCEPTED }\` to answer once it is accepted. A rejected command rejects with a \`CommandRejectedError\`; anything else that did not succeed with a \`WowProblemError\`.`])}export class ${s}CommandClient {\n readonly client: CommandClient;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.client = new CommandClient(options, { manifest: ${h}${m} });\n }\n\n${l.join(`
34
+
35
+ `)}\n}`)}function Mr(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=e.idSource===`owner`,c=s?`OwnStateClient`:`StateClient`,l=[c,`WowClientOptions`],u=[`${a}Aggregate`,`${a}Event`],d=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(l.push(`SnapshotQueryClient`),u.push(`${a}StateField`),X(i,`${Y([`Queries the snapshots of \`${e.context}.${e.name}\`: \`POST /${e.context}/${e.name}/snapshot/query\`.`])}export class ${a}SnapshotQueryClient extends SnapshotQueryClient<${o}, ${a}StateField> {\n${d}\n}`)),e.queryModels.includes(`events`)&&(l.push(`EventQueryClient`),X(i,`${Y([`Queries the event streams of \`${e.context}.${e.name}\`, one record per commit: \`POST /${e.context}/${e.name}/events/query\`.`])}export class ${a}EventQueryClient extends EventQueryClient<${a}Event> {\n${d}\n}`)),X(i,`${Y([s?`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: the caller's own by no id (\`readOwn\`, \`getOwn\`, \`findOwn\`, \`traceOwn\`: \`GET /${e.context}/${e.name}/state\`), and by id for a caller with no owner (\`GET /${e.context}/${e.name}/{id}/state\`).`:`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: \`GET /${e.context}/${e.name}/{id}/state\`.`])}export class ${a}StateClient extends ${c}<${o}, ${a}Event> {\n${d}\n}`),i.imports.add(J,l.sort()),i.imports.add(`./aggregate.js`,u),Q(i,r,n,[o])}function Nr(e){return{openAPI:e,components:e.components,endpoints:Ie(e.paths,e.components)}}var Pr=`.wow-generator.json`,Fr=class e{project;outputPath;outputDir;previous;written=new Set;stale=new Set;constructor(e,t,n,r){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r}static open(n,r,i){let a=n.getFileSystem(),o=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Pr),l=new Map;if(a.fileExistsSync(c)){let e=Ir(c,a.readFileSync(c));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Br(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new s(`output`,`Invalid generated file entry in ${c}: ${n}`);l.set(e,i)}}let u=new Set([...i?.written??[],...l.keys()]);for(let e of n.getSourceFiles())u.has(e.getFilePath())&&e.forget();return new e(n,o,r,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=f(t,e);Br(t,n);let r=this.project.getSourceFile(n)??this.project.createSourceFile(n,``,{overwrite:!0}),i=r.getFilePath();return this.written.has(i)||(r.removeText(),this.written.add(i)),r}forgetStale(){for(let[e,t]of this.previous)!this.written.has(e)&&this.isUnchanged(e,t)&&this.stale.add(e);for(let e of this.project.getSourceFiles())this.stale.has(e.getFilePath())&&e.forget()}async commit(e){e?.throwIfAborted();let n=this.project.getFileSystem(),r=new Set([...this.written].map(e=>e.toLowerCase()));for(let e of this.stale)!this.written.has(e)&&r.has(e.toLowerCase())&&this.isUnchanged(e,this.previous.get(e))&&(await zr(`delete`,e,()=>n.delete(e)),this.stale.delete(e));let i=[...this.written].sort().map(e=>this.project.getSourceFileOrThrow(e));(await Promise.allSettled(i.map(e=>e.save()))).forEach((e,t)=>{if(e.status===`rejected`)throw Rr(`write`,i[t].getFilePath(),e.reason)}),e?.throwIfAborted();for(let e of this.stale)!this.written.has(e)&&this.isUnchanged(e,this.previous.get(e))&&await zr(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Pr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Lr(n.readFileSync(e.getFilePath()))]))},null,2)+`
36
+ `;await zr(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)})}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Br(n.realpathSync(this.outputDir),n.realpathSync(e)),Lr(n.readFileSync(e))===t):!1}};function Ir(e,t){let n=`delete it; without it this run cannot remove the stale files of the last run`,r;try{r=JSON.parse(t)}catch(t){throw new s(`output`,`Cannot parse the generation manifest ${e}: ${c(t)}. Resolve the merge conflict in it if it has one, or ${n}.`,{cause:t})}let i=r?.version;if(typeof i==`number`&&Number.isInteger(i)&&i>1)throw new s(`output`,`The generation manifest ${e} was written by a newer wow-generator (manifest version ${i}); this one reads version 1. Upgrade wow-generator.`);if(i!==1||!r.files||typeof r.files!=`object`||Array.isArray(r.files))throw new s(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function Lr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Rr(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function zr(e,t,n){try{await n()}catch(n){throw Rr(e,t,n)}}function Br(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),o=(0,t.relative)(i,a);if(o===``||o.startsWith(`..`)||(0,t.isAbsolute)(o))throw new s(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}var Vr=Symbol(`project`),Hr=Symbol(`signal`),Ur=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[Hr],this.project=t[Vr]??Wr(t.tsConfigFilePath),this.project.manipulationSettings.set({indentationText:e.IndentationText.TwoSpaces,quoteKind:e.QuoteKind.Single,useTrailingCommas:!0}),this.logger.debug(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}async generate(){let{logger:e,signal:t,options:n}=this,r=0,i=t=>{for(let n of t)r++,e.warn(n)};e.debug(`Starting code generation`),e.debug(`Work directory: ${process.cwd()}`),e.debug(`Input path: ${n.inputPath}`),e.debug(`Output directory: ${n.outputDir}`);let a={headers:n.headers,timeoutMs:n.timeoutMs,signal:t},o=await In(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await Mn(n.inputPath,a);if(t?.throwIfAborted(),qn(c))return this.generateFromManifest(Jn(c,n.inputPath),o.origin,i,()=>r);let l=Nn(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=ee(l);if(u.length>0)throw new s(`specification`,`${n.inputPath} has ${u.length} $ref(s) that point at nothing: ${u.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${u.length>10?`, …`:``}`);let d=Nr(l),f=Fr.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=st(d,o.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new ut(e=>f.claim(e));fn(p.model,{modules:m,outputDir:n.outputDir,types:cn(d.components),schemaDocs:n.schemaDocs??`summary`}),m.build(),e.debug(`Generated modules written`),f.forgetStale();let h=this.project.getDirectory(n.outputDir);return h?(e.debug(`Generating index files`),i(pn(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),Tn(h.getDescendantSourceFiles().filter(e=>f.files.has(e.getFilePath())),e),e.debug(`Source files optimized successfully`)):e.debug(`Output directory not found.`),e.debug(`Saving project to disk`),await f.commit(t),e.debug(`Code generation completed successfully`),{files:[...f.files].sort(),configPath:o.origin,warnings:r}}async generateFromManifest(e,t,n,r){let{logger:i,signal:a,options:o}=this,s=Fr.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=cr(e);n(c.warnings);let l=new ut(e=>s.claim(e));gr(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(pn(u,e=>s.claim(`index.ts`,e))),Tn(u.getDescendantSourceFiles().filter(e=>s.files.has(e.getFilePath())),i)),await s.commit(a),i.debug(`Code generation from the Manifest completed successfully`),{files:[...s.files].sort(),configPath:t,warnings:r()}}};function Wr(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new s(`configuration`,`Cannot read the TypeScript configuration ${t}: ${c(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Hr}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return En}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Ur}});
37
+ //# sourceMappingURL=codeGenerator-C0dKAKl6.cjs.map