@ahoo-wang/wow-generator 9.9.0 → 10.0.0-alpha.4

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.
Files changed (81) hide show
  1. package/README.md +99 -62
  2. package/README.zh-CN.md +85 -48
  3. package/dist/analysis/analyze.d.cts +5 -8
  4. package/dist/analysis/analyze.d.ts +5 -8
  5. package/dist/analysis/apiClients.d.cts +3 -4
  6. package/dist/analysis/apiClients.d.ts +3 -4
  7. package/dist/analysis/clientNames.d.cts +0 -20
  8. package/dist/analysis/clientNames.d.ts +0 -20
  9. package/dist/analysis/model.d.cts +2 -102
  10. package/dist/analysis/model.d.ts +2 -102
  11. package/dist/analysis/modelInfo.d.cts +12 -3
  12. package/dist/analysis/modelInfo.d.ts +12 -3
  13. package/dist/analysis/models.d.cts +3 -11
  14. package/dist/analysis/models.d.ts +3 -11
  15. package/dist/api/configuration.d.cts +1 -5
  16. package/dist/api/configuration.d.ts +1 -5
  17. package/dist/cli/program.d.cts +0 -5
  18. package/dist/cli/program.d.ts +0 -5
  19. package/dist/cli.cjs +9 -1
  20. package/dist/cli.cjs.map +1 -1
  21. package/dist/cli.js +102 -3
  22. package/dist/cli.js.map +1 -1
  23. package/dist/codeGenerator-CU1TGcUI.js +2407 -0
  24. package/dist/codeGenerator-CU1TGcUI.js.map +1 -0
  25. package/dist/codeGenerator-DzI0zCgM.cjs +27 -0
  26. package/dist/codeGenerator-DzI0zCgM.cjs.map +1 -0
  27. package/dist/emit/imports.d.cts +0 -9
  28. package/dist/emit/imports.d.ts +0 -9
  29. package/dist/emitters/decorators.d.cts +3 -18
  30. package/dist/emitters/decorators.d.ts +3 -18
  31. package/dist/emitters/emit.d.cts +2 -3
  32. package/dist/emitters/emit.d.ts +2 -3
  33. package/dist/emitters/manifestClients.d.cts +15 -0
  34. package/dist/emitters/manifestClients.d.ts +15 -0
  35. package/dist/emitters/models.d.cts +1 -1
  36. package/dist/emitters/models.d.ts +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/input/configuration.d.cts +2 -4
  40. package/dist/input/configuration.d.ts +2 -4
  41. package/dist/input/parsers.d.cts +13 -0
  42. package/dist/input/parsers.d.ts +13 -0
  43. package/dist/manifest/analyze.d.cts +148 -0
  44. package/dist/manifest/analyze.d.ts +148 -0
  45. package/dist/manifest/document.d.cts +89 -0
  46. package/dist/manifest/document.d.ts +89 -0
  47. package/dist/naming/modelInfo.d.cts +1 -2
  48. package/dist/naming/modelInfo.d.ts +1 -2
  49. package/dist/naming/paths.d.cts +0 -5
  50. package/dist/naming/paths.d.ts +0 -5
  51. package/dist/output/outputStore.d.cts +2 -6
  52. package/dist/output/outputStore.d.ts +2 -6
  53. package/dist/pipeline/codeGenerator.d.cts +19 -11
  54. package/dist/pipeline/codeGenerator.d.ts +19 -11
  55. package/package.json +8 -8
  56. package/dist/analysis/aggregates.d.cts +0 -21
  57. package/dist/analysis/aggregates.d.ts +0 -21
  58. package/dist/codeGenerator-BMyiC0tW.cjs +0 -23
  59. package/dist/codeGenerator-BMyiC0tW.cjs.map +0 -1
  60. package/dist/codeGenerator-CsWf0pZy.js +0 -2572
  61. package/dist/codeGenerator-CsWf0pZy.js.map +0 -1
  62. package/dist/emitters/commandClients.d.cts +0 -14
  63. package/dist/emitters/commandClients.d.ts +0 -14
  64. package/dist/emitters/queryClients.d.cts +0 -11
  65. package/dist/emitters/queryClients.d.ts +0 -11
  66. package/dist/fetcherGeneratorCli.cjs +0 -3
  67. package/dist/fetcherGeneratorCli.cjs.map +0 -1
  68. package/dist/fetcherGeneratorCli.d.cts +0 -8
  69. package/dist/fetcherGeneratorCli.d.ts +0 -8
  70. package/dist/fetcherGeneratorCli.js +0 -6
  71. package/dist/fetcherGeneratorCli.js.map +0 -1
  72. package/dist/program-64WQvLq1.js +0 -103
  73. package/dist/program-64WQvLq1.js.map +0 -1
  74. package/dist/program-DWjbTSVJ.cjs +0 -10
  75. package/dist/program-DWjbTSVJ.cjs.map +0 -1
  76. package/dist/wow/conventions.d.cts +0 -154
  77. package/dist/wow/conventions.d.ts +0 -154
  78. package/dist/wow/model.d.cts +0 -116
  79. package/dist/wow/model.d.ts +0 -116
  80. package/dist/wow/resolveWowModel.d.cts +0 -21
  81. package/dist/wow/resolveWowModel.d.ts +0 -21
@@ -0,0 +1,27 @@
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 ee(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 te(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/`)&&ee(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 g=`#/components/`,ne=`${g}parameters/`,re=`${g}requestBodies/`,ie=`${g}responses/`,ae=`${g}schemas/`;function oe(e){return e.$ref.split(`/`).pop()}function _(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 v(e,t){return _(e,t.schemas,ae)}function se(e,t){return _(e,t.responses,ie)}function ce(e,t){return _(e,t.requestBodies,re)}function le(e,t){return _(e,t.parameters,ne)}var ue=new Intl.Collator(`en-US`);function y(e,t){return ue.compare(e,t)}var de=`application/json`,fe=`text/event-stream`;function pe(e){return e.split(`;`)[0].trim().toLowerCase()}function me(e){let t=pe(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function he(e){let t=pe(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function b(e,t,n=e=>pe(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 ge(e,t){if(t&&!h(t))return b(t.content,e)?.schema}function _e(e){if(e&&!h(e))return b(e.content,de,me)?.schema}function ve(e){return ge(fe,e)}function ye(e){return ge(`*/*`,e)}function be(e){return!e||h(e)?!1:Object.keys(e.content??{}).some(he)}function x(e){return Array.isArray(e.enum)&&e.enum.length>0}var xe=`x-enum-text`;function Se(e){return e[xe]}function Ce(e){return e.type===`object`&&!!e.properties}function we(e){return e.type===`array`&&!!e.items}function Te(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Ee(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function De(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function S(e){return Te(e)||Ee(e)||De(e)}function Oe(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function C(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var ke=`x-map-key-schema`;function w(e){return e[ke]}function Ae(e){return e.readOnly===!0}function T(e){if(Array.isArray(e))return e.map(e=>T(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 je(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&&v(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 Me(e,t){return e.operation.operationId&&t.operation.operationId?y(e.operation.operationId,t.operation.operationId):e.path&&t.path?y(e.path,t.path):e.method&&t.method?y(e.method,t.method):0}function Ne(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=h(i)?n&&le(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Pe(e,t){let n=[];for(let[r,i]of Object.entries(e))Fe(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Ne(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Me)}function Fe(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 Ie(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 Le(e,t){let n=Ie(e),r=n?e.responses[n]:void 0;return t&&h(r)?se(r,t):r}function Re(e,t){return(e.parameters??[]).map(e=>h(e)?le(e,t):e).filter(e=>e!==void 0)}function ze(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 Be=/[^\p{L}\p{N}$]+/u,Ve=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 E(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!Ve.has(e)}function He(e){return/^\p{N}/u.test(e)?`_${e}`:e}function D(e){if(E(e))return e;let t=He(A(e)||`_`);return Ve.has(t)?`${t}_`:t}function Ue(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&E(e)}function O(e){return He((Array.isArray(e)?e:[e]).map(e=>Ue(e)?e:k(e)).join(``)||`_`)}function We(e){return e.split(Be)}function Ge(e){return Array.isArray(e)?e.flatMap(e=>Ke(We(e))):Ke(We(e))}function Ke(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 k(e){return e===``||e.length===0?``:Ge(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 A(e){let t=k(e);return t.charAt(0).toLowerCase()+t.slice(1)}function j(e){return e===``||Array.isArray(e)&&e.length===0?``:Ge(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function M(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:N(e)}function qe(e){return/^\d+$/.test(e)?`NUM_${e}`:j(e)||e}function N(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var Je=`x-fetcher-method`;function Ye(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Xe(n))throw new s(`specification`,`${Je} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=A(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Xe(e){return E(e)||/^[a-z]+$/.test(e)}function Ze(e,t){let n=D(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function P(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:O(t.slice(n)),path:i}}function Qe(e,t){if(!e.$ref.startsWith(ae))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&v(e,t),P(oe(e))}var $e=[`httpRequest`,`attributes`];function et(e,t,n){return new tt(e,t,n).clients()}var tt=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=P(r),a=i;for(let e=2;n.has(F(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(F(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(F(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=f(t.path,nt(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($e),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=Ye(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=Re(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`?ze(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:Ze(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)?ce(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=b(i,de,me),o=Ze(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:je(a.schema,this.document.components)}}:b(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:b(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(he)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=Le(e,this.document.components);if(!t)return{kind:`response`};let n=_e(t),r=n||ye(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=ve(t);if(i){if(h(i)){let e=v(i,this.document.components);if(we(e)&&h(e.items)){let t=Qe(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return be(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 nt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function F(e){return`${e.path}/${e.name}`.toLowerCase()}function rt(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return it(n),n.map(e=>{let n=t[e],r=P(e);return{key:e,info:r,file:m(r),schema:n}})}function it(e){let t=new Map;for(let n of e){let e=P(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 at(e,t){let n=[];return{model:{models:rt(e),apiClients:et(e,t,n)},warnings:n}}var ot=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})}))}},st=class{sourceFile;imports=new ot;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&&ut(n,e)&&t.push(lt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},ct=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 st(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},lt=e=>{e.blankLineIfLastNot()};function ut(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 dt(e,t){return{name:`[key: string]`,type:e,docs:t}}var ft=`@`;function I(e,t,n){return e.imports.add(t,n)}function pt(e,n,r){return r.path.startsWith(ft)?r.path:mt(e.directoryPath,(0,t.join)(n,r.path,p))}function mt(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 ht(e,t=`
2
+ `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(gt);return n.length>0?n.join(t):void 0}function gt(e){return e.replace(/\*\//g,`*\\/`)}function L(e,t){let n=ht(t);n&&(e.docs=[...e.docs??[],n])}function R(e,t,n=!1){e=yt(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&bt(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),xt(r,e,`default`),xt(r,e,`example`),Ct(r,e),wt(r,e),Tt(r,e),r}function _t(e,t,n){L(e,R(t,n))}function vt(e,t,n,r=!1){let i=R(t,n,!0);r&&St(i,`schema`,t),L(e,i)}function yt(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 bt(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function xt(e,t,n){let r=t[n];r&&(typeof r==`object`?St(e,n,r):e.push(`- ${n}: \`${r}\``))}function St(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function Ct(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 wt(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 Tt(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 Et(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 Dt=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],Ot=new Set([`string`,`number`,`boolean`]),kt=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function At(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function z(e,t,n=new Set){if(h(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=v(e,t);return r?z(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(De(e)&&e.type===void 0){let r=e.allOf.map(e=>z(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>At(e,i))?i:void 0}if(!(S(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:T(e.type)}}}function jt(e,t,n){let r=z(t,n);if(typeof r!=`object`)return!1;let i=z(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Mt(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>jt(e,n,t))}function Nt(e){return e.nullable!==!0||x(e)||!S(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(h))}function Pt(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 B(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>B(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${M(e)}: ${B(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Ft=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([...Dt,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=(Ae(t)?`readonly `:``)+M(e);if(!h(t)){let e=ht(R(t),`
3
+ * `);if(e)return`
4
+ /**
5
+ * ${e}
6
+ */
7
+ ${r}: ${n}
8
+ `}return`${r}: ${n}`})}objectType(e){let t=[];Ce(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${M(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=C(e)&&w(e)?this.mapType(e):Mt(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=w(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&&v(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(Nt(e))return`(${this.type({...e,nullable:!1})}) | null`;if(S(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(!Pt(e.const,e))return`never`;let t=B(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!x(e))return`(${this.type({...e,nullable:!1})}) | null`;if(x(e)){let t=e.enum.filter(t=>Pt(t,e)).map(e=>B(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||Ot.has(n)?t:`(${t}) & (${n})`}return C(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Oe(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?T(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-`)&&!kt.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`||kt.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=oe(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>N(e)).join(` | `);return`(${r} & { ${M(i.propertyName)}: ${s} })`}};function V(e,t){let n=new Ft(e);return{text:t(n),imports:n.imports()}}function It(e,t){return V(t,t=>t.type(e))}function Lt(e,t){return V(t,t=>t.additionalProperties(e))}function Rt(e,t){return V(t,t=>t.additionalPropertyType(e))}function zt(e,t){return V(t,t=>t.requiredAdditionalPropertyType(e))}function Bt(e,t){return V(t,t=>t.mapValueType(e))}var Vt=`@ahoo-wang/fetcher`,Ht=[`ContentTypeValues`,`ResultExtractors`],Ut=`@ahoo-wang/fetcher-decorator`,Wt=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Gt={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Kt={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},qt=`{
10
+ headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
+ resultExtractor: JsonEventStreamResultExtractor,
12
+ }`;function Jt(e){I(e,Vt,Ht)}function Yt(e){I(e,Ut,Wt)}function Xt(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 Zt(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 Qt(e){return e===`delete`?`del`:e}var $t=`@ahoo-wang/fetcher-eventstream`;function en(e){I(e,$t,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function tn(e,t){let n=t.modules.module(e.file);Jt(n),Yt(n),en(n);let r=Xt(e.className,n);L(r,[e.description]),Zt(r);let i=nn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(rn(t,i))}function nn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>pt(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=It(e,r);return t.imports.apply(n.imports),n.text}}}function rn(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:[N(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:an(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=on(e.returns,t),o=N(e.path),s={name:e.name,decorators:[{name:Qt(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return L(s,[...e.docs]),s}function an(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:(I(t.module,Vt,[`PartialBy`]),`PartialBy<${e}, ${r.map(N).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function on(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Kt:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:qt};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:qt}}case`text`:return Kt;case`response`:return Gt}}function sn(e){return Et(e,{ofKey:e=>P(e),ofReference:Qe})}function cn(e,t){new un(e,t.modules.module(e.file),t).write()}function ln(e){let t=new Set,n=new Map;for(let r of e){let e=qe(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,M(a))}return n}var un=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=>pt(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&vt(e,this.model.schema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return h(e)?this.processTypeAlias(e):x(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||S(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Ce(e)?this.processInterface(e):C(e)&&typeof e.additionalProperties==`object`&&!w(e)&&!e.required?.length?this.processIndexSignature(e):we(e)?this.processArray(e):S(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(It(e,this.scope))}processEnum(t){let n=Se(t);if(n){let t=ln(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:B(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=ln(r);return S(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:B(e)}))})}addPropertyToInterface(e,t,n){let r={name:M(t),type:this.resolveType(n),isReadonly:Ae(n)};(e.properties??=[]).push(r),_t(r,n)}processInterface(t){if(Mt(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:M(e),type:this.emit(zt(t,this.scope))});return this.emit(Lt(t,this.scope))&&n.push(dt(this.emit(Rt(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:Oe(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[dt(this.emit(Bt(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 dn(e,t){e.models.forEach(e=>cn(e,t)),e.apiClients.forEach(e=>tn(e,t))}function fn(e,t){let n=[];return pn(e,t,n),n}function pn(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:hn(t)})}for(let i of e.getDirectories()){let e=pn(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:mn(i,r,t,n)}function mn(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])=>y(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 hn(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 gn(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 _n(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())&&!gn(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>vn(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function vn(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 yn(e){let t=e.flatMap(_n);for(let e of t)e()}var bn=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function xn(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!bn.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 Sn=`// Code generated by wow-generator. DO NOT EDIT.
14
+
15
+ `,Cn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function wn(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(Cn),n.organizeImports(Cn)}),yn(e),xn(e);for(let t of e)t.insertText(0,Sn)}var Tn=3e4;function En(e){return/^https?:\/\//i.test(e)}function Dn(e,t={}){return En(e)?On(e,t):An(e)}async function On(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`:kn(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 kn(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 An(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function jn(e,t){let n;try{n=await Dn(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Nn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Mn(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 Nn(e){switch(Pn(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function Pn(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 Fn(e,t,n){if(e!==void 0)return{...await Rn({path:e,explicit:!0},t,n),origin:H(e)};let r=await Rn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:H(a)}}var In=[`apiClients`],Ln=[`ignorePathParameters`,`methodNames`];async function Rn(e,t,n){let r=H(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await Dn(e.path,n)}catch(n){if(!e.explicit&&zn(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=Nn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Vn(a,r);return t.debug(`Configuration loaded from ${r}: ${Un(o.config)}`),o}function H(e){return En(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function zn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function U(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bn(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 Vn(e,t){if(!W(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${U(e)}`);let n=[];return Bn(n,t,`configuration`,e,In),Hn(e.apiClients,t,n),{config:e,warnings:n}}function Hn(e,t,n){if(e!==void 0){if(!W(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${U(e)}`);for(let[r,i]of Object.entries(e)){if(!W(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${U(i)}`);Bn(n,t,`apiClients["${r}"]`,i,Ln);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 ${U(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!W(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${U(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!E(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Un(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Wn=`#/$defs/`;function G(e){return e.startsWith(Wn)?e.slice(8):void 0}function Gn(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 K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kn(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=[];if(n.contexts.forEach((e,t)=>{!K(e)||typeof e.name!=`string`?r.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let i=`${e.name}.aggregates[${n}]`;!K(t)||typeof t.name!=`string`?r.push(`${i} has no name`):!K(t.state)||typeof t.state.schema!=`string`?r.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&r.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`)&&r.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!K(n.$defs)&&r.push(`$defs is not an object`),r.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${r.join(`; `)}.`);return n}var qn=new Set([`int64`,`bigint`,`decimal`]),q={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Jn=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),Yn=4;function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function Xn(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 Zn(e){return typeof e==`string`?N(e):JSON.stringify(e)}var Qn=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=O([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?k(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 J(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=G(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(J(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=G(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(!J(e))return`unknown`;if(typeof e.$ref==`string`){let n=G(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return Zn(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:Xn(e.enum.map(Zn),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return Xn(i.map(e=>this.type(e,t)),r)}let n=Y(e);return n.length===0?J(e.properties)?this.objectType(e,t):`unknown`:Xn(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`&&qn.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(!J(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=J(r)?r.description:void 0;return{name:M(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=Y(e);return J(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(!J(e))return;let n=typeof e.$ref==`string`?G(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=Y(e);(i.includes(`integer`)||i.includes(`number`))&&typeof e.format==`string`&&qn.has(e.format)&&r.push(!0);let a={};if(J(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),$n(r)}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?G(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!J(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<Yn&&J(r)&&(Y(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function $n(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,$n(t)]))}function er(e,t){if(t===void 0)return!0;let n=e.resolve(t);return!Array.isArray(n.required)||n.required.length===0}function tr(e,t){return[t.state.schema,...(t.commands??[]).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(G).filter(e=>e!==void 0).concat(nr(e,t))}function nr(e,t){return(t.lifecycle??[]).filter(t=>q[t]!==void 0&&e.schemaOf(t))}function rr(e){let t=new Qn(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=(e.aggregates??[]).flatMap(e=>tr(t,e));for(let i of t.closure(n).sort(y))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(y));let a=i.map(e=>ir(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>y(e.file,t.file)||y(e.name,t.name)),o=n.map(e=>ar(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function ir(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(y)};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 ar(e,t){let n=`${t.name}.`;return{name:t.name,...t.description?{description:t.description}:{},typeName:O(k(t.name)),constantName:j(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({member:j((e.code.startsWith(n)?e.code.slice(n.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(y),aggregates:(t.aggregates??[]).map(n=>sr(e,t,n))}}function or(e,t,n){let r=G(t);return r===void 0?`unknown`:e.refType(r,n)}function sr(e,t,n){let r=`${t.name}.${n.name}`,i=O(k(n.name)),a=new Set(nr(e,n)),o=(n.lifecycle??[]).filter(e=>Jn.has(e)).map(t=>{let n=t.split(`.`).pop(),i=e.schemaOf(t)?.description;return{name:t,member:j(n),method:D(A(n)),...a.has(t)?{bodyType:e.refType(t,r),bodyGenerated:!0}:q[t]?{bodyType:q[t]}:{},...typeof i==`string`?{description:i}:{}}}),s=new Set(o.map(e=>e.method)),c=(n.commands??[]).map(t=>{let n=D(A(t.name));(s.has(n)||n===`gateway`)&&(n=`${n}Command`),s.add(n);let i=j(t.name),a=(t.routes??[]).filter(e=>e.method===`POST`),o=a.find(e=>e.path.includes(`{id}`)),c=a.find(e=>!e.path.includes(`{id}`)),l=G(t.schema);return{name:t.name,method:n,...o?{byIdPath:{member:i,path:o.path}}:{},...c?{unaddressedPath:{member:o?`${i}_WITHOUT_ID`:i,path:c.path}}:{},bodyType:or(e,t.schema,`${r}.${t.name}`),bodyOptional:er(e,l===void 0?void 0:e.schemaOf(l)),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}}}),l=e.textNumbers({$ref:n.state.schema}),u=Object.fromEntries((n.events??[]).flatMap(r=>{let i=e.textNumbers({$ref:r.schema});return i===void 0?[]:[[cr(t,n,r.name),i]]})),d=Object.fromEntries((n.commands??[]).flatMap(t=>{let n=e.textNumbers({$ref:t.schema});return n===void 0?[]:[[t.name,n]]})),f={...l===void 0?{}:{state:l},...Object.keys(u).length===0?{}:{events:u},...Object.keys(d).length===0?{}:{commands:d}},p=G(n.state.schema),m=p===void 0?void 0:e.schemaOf(p);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`OWNER`,snapshot:n.snapshot?.enabled??!0,stateType:or(e,n.state.schema,`${r} state`),stateFields:m===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:c,events:(n.events??[]).map(i=>({name:i.name,wireName:cr(t,n,i.name),revision:i.revision??1,type:or(e,i.schema,`${r}.${i.name}`)})),lifecycle:o,queryModels:(n.queries??[]).map(e=>e.model),...Object.keys(f).length===0?{}:{textNumbers:f}}}function cr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var X=`@ahoo-wang/wow-client`;function Z(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>gt(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 Q(e,t){e.add(`\n${t}`)}function lr(e){return e.length===0?`never`:e.join(` | `)}function $(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(mt(e.directoryPath,(0,i.join)(t,n)),r)}function ur(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)dr(t.module(i.file),i,r,n);for(let i of e.contexts){fr(i,t);for(let e of i.aggregates)hr(e,i,t,r,n),vr(e,t,r,n),yr(e,t,r,n)}}function dr(e,t,n,r){$(e,r,n,t.references,t.file);let i=Z([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){Q(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${Z([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),Q(e,`${i}export interface ${t.name} {\n${a.join(`
18
+ `)}\n}`)}function fr(e,t){let n=t.module(`${e.directory}/boundedContext.ts`),r=`${e.constantName}_BOUNDED_CONTEXT`;n.imports.add(X,[`Hop`,`wait`]),Q(n,`${Z([`The bounded context \`${e.name}\`.`,e.description])}export const ${r} = ${N(e.name)};`);let i=e.errors.map(e=>`${Z([`${e.status}: ${e.description??e.code}`],` `)} ${e.member}: ${N(e.code)},`);Q(n,`${Z([`The domain error codes of \`${e.name}\`, each a problem's \`code\` with the status the Manifest gives it.`])}export const ${e.typeName}ErrorCodes = {\n${i.join(`
19
+ `)}\n} as const;`),Q(n,`${Z([`A {@link ${e.typeName}ErrorCodes} value.`])}export type ${e.typeName}ErrorCode = (typeof ${e.typeName}ErrorCodes)[keyof typeof ${e.typeName}ErrorCodes];`);let a=e.subscriptions.length>0;a&&Q(n,`${Z([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${lr(e.subscriptions.map(N))};`);let o=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${r}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${r}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${r}),`];a&&o.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${r}),`),Q(n,`${Z([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${A(e.name)}Wait = {\n${o.join(`
20
+ `)}\n} as const;`)}function pr(e){return e===!0?`true`:`{ ${Object.entries(e).map(([e,t])=>`${M(e)}: ${pr(t)}`).join(`, `)} }`}function mr(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: ${pr(n)},`]:[` ${e}: {\n${Object.entries(n).map(([e,t])=>` ${M(e)}: ${pr(t)},`).join(`
21
+ `)}\n },`]}).join(`
22
+ `)}\n },\n`}function hr(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;Q(a,`${Z([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${N(t.name)},\n name: ${N(e.name)},\n path: ${N(`/${t.name}/${e.name}`)},\n ownership: ${N(e.ownership)},\n snapshot: ${e.snapshot},\n${mr(e)}} as const;`),Q(a,`${Z([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${lr(e.stateFields.map(N))};`);let s=e.events.map(e=>`EventView<${N(e.wireName)}, ${e.type}>`);a.imports.add(X,s.length>0?[`EventView`,`SystemEvent`]:[`SystemEvent`]),Q(a,`${Z([`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 = ${lr([...s,`SystemEvent`])};`),$(a,i,r,e.events.map(e=>e.type))}function gr(e){let t=[e.byIdPath,e.unaddressedPath].filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),n=e.creation===`REQUIRED`?`Creates the aggregate.`:e.creation===`ALLOWED`?`Creates the aggregate, or acts on the one that exists.`:void 0;return Z([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}: ${t}.`,n,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function _r(e,t,n,r){let i=e.bodyNumbers?`, bodyNumbers: ${r}.textNumbers.commands.${M(e.name)===e.name?e.name:`[${N(e.name)}]`}`:``,a=e.bodyType===`unknown`?`object`:e.bodyType,o=e.bodyOptional?`body: ${a} = {}`:`body: ${a}`,s=n?`stream`:`send`,c=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,l=n?`${e.method}Stream`:e.method,u=n?Z([`\`${e.name}\`, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):gr(e),d=e.byIdPath,f=e.unaddressedPath;return d&&f?`${u} ${l}(${o}, options?: CreateCommandOptions): ${c} {\n return this.gateway.${s}(options?.id === undefined ? ${t}.${f.member} : ${t}.${d.member}, body, ${i?`{ ...options${i} }`:`options`});\n }`:d?`${u} ${l}(id: string, ${o}, options?: CommandOptions): ${c} {\n return this.gateway.${s}(${t}.${d.member}, body, { ...options, id${i} });\n }`:`${u} ${l}(${o}, options?: CommandOptions): ${c} {\n return this.gateway.${s}(${t}.${f.member}, body, ${i?`{ ...options${i} }`:`options`});\n }`}function vr(e,t,n,r){let i=t.module(`${e.directory}/commandClient.ts`),a=e.typeName,o=`${a}CommandPaths`,s=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),c=s.flatMap(e=>[e.byIdPath,e.unaddressedPath].filter(e=>e!==void 0).map(e=>` ${e.member}: ${N(e.path)},`));Q(i,`${Z([`The command routes of \`${e.context}.${e.name}\`.`])}export const ${o} = {\n${c.join(`
23
+ `)}\n} as const;`);let l=s.flatMap(e=>[_r(e,o,!1,`${a}Aggregate`),_r(e,o,!0,`${a}Aggregate`)]),u=[`CommandGateway`,`CommandResult`,`WowClientOptions`];s.length>0&&u.push(`CommandResultStream`),s.some(e=>e.byIdPath&&e.unaddressedPath)&&u.push(`CreateCommandOptions`),(s.some(e=>!(e.byIdPath&&e.unaddressedPath))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let d=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?d:u).push(t.bodyType);let e=t.bodyType?`id: string, body: ${t.bodyType}, options?: CommandOptions`:`id: string, options?: CommandOptions`;l.push(`${Z([t.description,`The lifecycle command \`${t.name}\`.`],` `)} ${t.method}(${e}): Promise<CommandResult> {\n return this.gateway.lifecycle(${a}Aggregate.path, id, LifecycleCommands.${t.member}, ${t.bodyType?`body`:`undefined`}, options);\n }`)}(e.lifecycle.length>0||s.some(e=>e.bodyNumbers))&&i.imports.add(`./aggregate.js`,[`${a}Aggregate`]),i.imports.add(X,[...new Set(u)].sort()),$(i,r,n,[...s.map(e=>e.bodyType),...d]),Q(i,`${Z([`Sends the commands of \`${e.context}.${e.name}\`; a command that did not succeed rejects with a \`WowProblemError\` holding its result.`])}export class ${a}CommandClient {\n readonly gateway: CommandGateway;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.gateway = new CommandGateway(options);\n }\n\n${l.join(`
24
+
25
+ `)}\n}`)}function yr(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=[`StateClient`,`WowClientOptions`],c=[`${a}Aggregate`,`${a}Event`],l=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(s.push(`SnapshotQueryClient`),c.push(`${a}StateField`),Q(i,`${Z([`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${l}\n}`)),e.queryModels.includes(`events`)&&(s.push(`EventQueryClient`),Q(i,`${Z([`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${l}\n}`)),Q(i,`${Z([`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 StateClient<${o}, ${a}Event> {\n${l}\n}`),i.imports.add(X,s.sort()),i.imports.add(`./aggregate.js`,c),$(i,r,n,[o])}function br(e){return{openAPI:e,components:e.components,endpoints:Pe(e.paths,e.components)}}var xr=`.wow-generator.json`,Sr=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,xr),l=new Map;if(a.fileExistsSync(c)){let e=Cr(c,a.readFileSync(c));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Dr(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);Dr(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 Er(`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 Tr(`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 Er(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,xr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),wr(n.readFileSync(e.getFilePath()))]))},null,2)+`
26
+ `;await Er(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)})}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Dr(n.realpathSync(this.outputDir),n.realpathSync(e)),wr(n.readFileSync(e))===t):!1}};function Cr(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 wr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Tr(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function Er(e,t,n){try{await n()}catch(n){throw Tr(e,t,n)}}function Dr(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 Or=Symbol(`project`),kr=Symbol(`signal`),Ar=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[kr],this.project=t[Or]??jr(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 Fn(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await jn(n.inputPath,a);if(t?.throwIfAborted(),Gn(c))return this.generateFromManifest(Kn(c,n.inputPath),o.origin,i,()=>r);let l=Mn(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=te(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=br(l),f=Sr.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=at(d,o.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new ct(e=>f.claim(e));dn(p.model,{modules:m,outputDir:n.outputDir,types:sn(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(fn(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),wn(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=Sr.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=rr(e);n(c.warnings);let l=new ct(e=>s.claim(e));ur(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(fn(u,e=>s.claim(`index.ts`,e))),wn(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 jr(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 kr}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Tn}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Ar}});
27
+ //# sourceMappingURL=codeGenerator-DzI0zCgM.cjs.map