@ahoo-wang/wow-generator 9.7.0 → 9.8.0

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.
package/dist/cli.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-CXVxnY-Z.cjs");let t=require("path"),n=require("commander");var r=`9.7.0`;function i(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!0}return/^[a-z]:$/i.test(t.protocol)?!0:t.protocol===`http:`||t.protocol===`https:`}function a(t=[]){let n={};for(let r of t){let t=r.indexOf(`:`),i=t>0?r.slice(0,t).trim():``;if(!i)throw new e.s(`input`,`Invalid --header "${r}": expected "Name: value".`);n[i]=r.slice(t+1).trim()}return n}function o(t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new e.s(`input`,`Invalid --timeout "${t}": expected a positive number of milliseconds.`);return n}function s(t){if(t===void 0||t===`summary`)return`summary`;if(t===`full`)return`full`;throw new e.s(`input`,`Invalid --schema-docs "${t}": expected "summary" or "full".`)}function c(e){return e.verbose?`verbose`:e.quiet?`quiet`:`normal`}function l(t,n,r){if(n instanceof e.s)return t.error(n.message),r&&n.cause!==void 0&&t.error(`Caused by:`,n.cause),n.exitCode;let i=n instanceof Error?n.message:String(n);return t.error(`Code generation failed: ${i}`),r?t.error(``,n):t.error(`Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.`),e.o.internal}async function u(n,u=new e.i({level:c(n)}),d={}){if(!i(n.input))return u.error(`Invalid input "${n.input}": expected a file path or an http(s) URL.`),e.o.input;try{u.debug(`wow-generator v${r}`);let i={...d,inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,headers:a(n.header),timeoutMs:o(n.timeout),schemaDocs:s(n.schemaDocs),logger:u},c=await new e.t(i).generate(),l=c.warnings?`, ${c.warnings} warning${c.warnings===1?``:`s`}`:``,f=c.configPath?` with ${(0,t.relative)(process.cwd(),c.configPath)||c.configPath}`:``;return u.info(`Generated ${c.files.length} files into ${n.output}${f}${l}`),n.strict&&c.warnings>0?(u.error(`--strict: the run logged ${c.warnings} warning${c.warnings===1?``:`s`}.`),e.o.specification):e.o.success}catch(t){return d[e.n]?.aborted?e.o.interrupted:l(u,t,!!n.verbose)}}async function d(t){let n=new AbortController;process.once(`SIGINT`,()=>{console.error(`Generation interrupted by user`),n.abort()}),process.exitCode=await u(t,void 0,{[e.n]:n.signal})}function f(e,t=[]){return[...t,e]}function p(t=n.program){return t.exitOverride(),t.name(`wow-generator`).description(`OpenAPI Specification TypeScript code generator for Wow`).version(r,`-v, --version`),t.command(`generate`).description(`Generate TypeScript code from OpenAPI specification`).requiredOption(`-i, --input <file>`,`Input OpenAPI specification file path or URL (http/https)`).option(`-o, --output <path>`,`Output directory path`,`src/generated`).option(`-c, --config <file>`,`Configuration file path (default: ${e.c})`).option(`-t, --ts-config-file-path <file>`,`TypeScript configuration file path`).option(`-H, --header <header>`,`Request header for an http(s) input or configuration, as "Name: value"; repeatable`,f).option(`--timeout <ms>`,`Milliseconds before fetching an http(s) input is abandoned (default: ${e.r})`).option(`--schema-docs <mode>`,`What model doc comments carry: "summary" (title, description, constraints) or "full" (also the JSON schema)`,`summary`).option(`--strict`,`Exit with code 4 when the run logs a warning`).option(`--verbose`,`Log every step, and the stack trace of a failure`).option(`--quiet`,`Log only warnings and errors`).action(d),t}function m(t){return t.exitCode===0?e.o.success:e.o.input}async function h(e,t=p()){try{e===void 0?await t.parseAsync():await t.parseAsync(e,{from:`user`})}catch(e){if(!(e instanceof n.CommanderError))throw e;process.exitCode=m(e)}}h(),exports.collect=f,exports.runCLI=h,exports.setupCLI=p;
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-BMyiC0tW.cjs");let t=require("path"),n=require("commander");var r=`9.8.0`;function i(e){if(!e)return!1;let t;try{t=new URL(e)}catch{return!0}return/^[a-z]:$/i.test(t.protocol)?!0:t.protocol===`http:`||t.protocol===`https:`}function a(t=[]){let n={};for(let r of t){let t=r.indexOf(`:`),i=t>0?r.slice(0,t).trim():``;if(!i)throw new e.s(`input`,`Invalid --header "${r}": expected "Name: value".`);n[i]=r.slice(t+1).trim()}return n}function o(t){if(t===void 0)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw new e.s(`input`,`Invalid --timeout "${t}": expected a positive number of milliseconds.`);return n}function s(t){if(t===void 0||t===`summary`)return`summary`;if(t===`full`)return`full`;throw new e.s(`input`,`Invalid --schema-docs "${t}": expected "summary" or "full".`)}function c(e){return e.verbose?`verbose`:e.quiet?`quiet`:`normal`}function l(t,n,r){if(n instanceof e.s)return t.error(n.message),r&&n.cause!==void 0&&t.error(`Caused by:`,n.cause),n.exitCode;let i=n instanceof Error?n.message:String(n);return t.error(`Code generation failed: ${i}`),r?t.error(``,n):t.error(`Rerun with --verbose for the stack trace, and report it at https://github.com/Ahoo-Wang/Wow/issues if the input is valid.`),e.o.internal}async function u(n,u=new e.i({level:c(n)}),d={}){if(!i(n.input))return u.error(`Invalid input "${n.input}": expected a file path or an http(s) URL.`),e.o.input;try{u.debug(`wow-generator v${r}`);let i={...d,inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,headers:a(n.header),timeoutMs:o(n.timeout),schemaDocs:s(n.schemaDocs),logger:u},c=await new e.t(i).generate(),l=c.warnings?`, ${c.warnings} warning${c.warnings===1?``:`s`}`:``,f=c.configPath?` with ${(0,t.relative)(process.cwd(),c.configPath)||c.configPath}`:``;return u.info(`Generated ${c.files.length} files into ${n.output}${f}${l}`),n.strict&&c.warnings>0?(u.error(`--strict: the run logged ${c.warnings} warning${c.warnings===1?``:`s`}.`),e.o.specification):e.o.success}catch(t){return d[e.n]?.aborted?e.o.interrupted:l(u,t,!!n.verbose)}}async function d(t){let n=new AbortController;process.once(`SIGINT`,()=>{console.error(`Generation interrupted by user`),n.abort()}),process.exitCode=await u(t,void 0,{[e.n]:n.signal})}function f(e,t=[]){return[...t,e]}function p(t=n.program){return t.exitOverride(),t.name(`wow-generator`).description(`OpenAPI Specification TypeScript code generator for Wow`).version(r,`-v, --version`),t.command(`generate`).description(`Generate TypeScript code from OpenAPI specification`).requiredOption(`-i, --input <file>`,`Input OpenAPI specification file path or URL (http/https)`).option(`-o, --output <path>`,`Output directory path`,`src/generated`).option(`-c, --config <file>`,`Configuration file path (default: ${e.c})`).option(`-t, --ts-config-file-path <file>`,`TypeScript configuration file path`).option(`-H, --header <header>`,`Request header for an http(s) input or configuration, as "Name: value"; repeatable`,f).option(`--timeout <ms>`,`Milliseconds before fetching an http(s) input is abandoned (default: ${e.r})`).option(`--schema-docs <mode>`,`What model doc comments carry: "summary" (title, description, constraints) or "full" (also the JSON schema)`,`summary`).option(`--strict`,`Exit with code 4 when the run logs a warning`).option(`--verbose`,`Log every step, and the stack trace of a failure`).option(`--quiet`,`Log only warnings and errors`).action(d),t}function m(t){return t.exitCode===0?e.o.success:e.o.input}async function h(e,t=p()){try{e===void 0?await t.parseAsync():await t.parseAsync(e,{from:`user`})}catch(e){if(!(e instanceof n.CommanderError))throw e;process.exitCode=m(e)}}h(),exports.collect=f,exports.runCLI=h,exports.setupCLI=p;
3
3
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-DCYj0aYK.js";
2
+ import { c as e, i as t, n, o as r, r as i, s as a, t as o } from "./codeGenerator-CsWf0pZy.js";
3
3
  import { relative as s } from "path";
4
4
  import { CommanderError as c, program as l } from "commander";
5
5
  //#region src/version.ts
6
- var u = "9.7.0";
6
+ var u = "9.8.0";
7
7
  //#endregion
8
8
  //#region src/cli/runGenerate.ts
9
9
  function d(e) {
@@ -0,0 +1,23 @@
1
+ let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs");var i=`./wow-generator.config.json`,a={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},o=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return a[this.kind]}};function s(e){return e instanceof Error?e.message:String(e)}function c(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var l=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??c()}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)}},u=class{debug(){}info(){}warn(){}error(){}},d=/[^\p{L}\p{N}$]+/u,f=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 p(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!f.has(e)}function m(e){return/^\p{N}/u.test(e)?`_${e}`:e}function h(e){if(p(e))return e;let t=m(v(e)||`_`);return f.has(t)?`${t}_`:t}function ee(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&p(e)}function te(e){return m((Array.isArray(e)?e:[e]).map(e=>ee(e)?e:re(e)).join(``)||`_`)}function ne(e){return e.split(d)}function g(e){return Array.isArray(e)?e.flatMap(e=>_(ne(e))):_(ne(e))}function _(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 re(e){return e===``||e.length===0?``:g(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 v(e){let t=re(e);return t.charAt(0).toLowerCase()+t.slice(1)}function ie(e){return e===``||Array.isArray(e)&&e.length===0?``:g(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function y(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:b(e)}function ae(e){return/^\d+$/.test(e)?`NUM_${e}`:ie(e)||e}function b(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var oe=new Intl.Collator(`en-US`);function x(e,t){return oe.compare(e,t)}function S(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function se(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 ce(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/`)&&se(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 C=`#/components/`,le=`${C}parameters/`,ue=`${C}requestBodies/`,w=`${C}responses/`,de=`${C}schemas/`;function T(e){return e.$ref.split(`/`).pop()}function E(e,t,n){let r=new Set,i=e;for(;S(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new o(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function D(e,t){return E(e,t.schemas,de)}function fe(e,t){return E(e,t.responses,w)}function pe(e,t){return E(e,t.requestBodies,ue)}function me(e,t){return E(e,t.parameters,le)}function O(e,t){return{key:T(e),schema:D(e,t)}}var k=`application/json`,he=`text/event-stream`;function A(e){return e.split(`;`)[0].trim().toLowerCase()}function ge(e){let t=A(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function _e(e){let t=A(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function j(e,t,n=e=>A(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 ve(e,t){if(t&&!S(t))return j(t.content,e)?.schema}function ye(e){if(e&&!S(e))return j(e.content,k,ge)?.schema}function be(e){return ve(he,e)}function xe(e){return ve(`*/*`,e)}function Se(e){return!e||S(e)?!1:Object.keys(e.content??{}).some(_e)}var Ce=[`string`,`number`,`integer`,`boolean`,`null`];function we(e){return Array.isArray(e)?!0:Ce.includes(e)}function M(e){return Array.isArray(e.enum)&&e.enum.length>0}var Te=`x-enum-text`;function Ee(e){return e[Te]}function De(e){return e.type===`object`&&!!e.properties}function Oe(e){return e.type===`array`&&!!e.items}function ke(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Ae(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function je(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function N(e){return ke(e)||Ae(e)||je(e)}function Me(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Ne(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var Pe=`x-map-key-schema`;function Fe(e){return e[Pe]}function Ie(e){return e.type===`object`?!e.properties||Object.keys(e.properties).length===0:!1}function Le(e){return e.readOnly===!0}function P(e){if(Array.isArray(e))return e.map(e=>P(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 Re(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),S(e))o(t&&D(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 ze(e,t){return e.operation.operationId&&t.operation.operationId?x(e.operation.operationId,t.operation.operationId):e.path&&t.path?x(e.path,t.path):e.method&&t.method?x(e.method,t.method):0}function Be(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=S(i)?n&&me(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Ve(e,t){let n=[];for(let[r,i]of Object.entries(e))He(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Be(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(ze)}function He(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 Ue(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 F(e,t){let n=Ue(e),r=n?e.responses[n]:void 0;return t&&S(r)?fe(r,t):r}function We(e,t){return ye(F(e,t))}function Ge(e,t){return(e.parameters??[]).map(e=>S(e)?me(e,t):e).filter(e=>e!==void 0)}function Ke(e,t){return e.parameters?e.parameters.map(e=>S(e)?me(e,t):e).filter(e=>e?.in===`path`):[]}function qe(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 Je=`string`;function Ye(e){return!e.schema||S(e.schema)||!e.schema.type||!we(e.schema.type)?Je:P(e.schema.type)}var Xe=`8.10`,Ze=`x-wow-context-alias`;function Qe(e){return e.info[Ze]}function $e(e){let t=e.split(`.`);return t.length!=2||t[0].length===0||t[1].length===0?null:t}function et(e){let t=$e(e.name);return t?{tag:e,contextAlias:t[0],aggregateName:t[1]}:null}function tt(e){if(!e)return null;let t=e.split(`.`);return t.length==3?t[2]:null}var nt=`.snapshot_state.single`,rt=`.snapshot.count`,it=`x-wow-query-fields`,at=/^(?:\/tenant\/\{tenantId\})?(?:\/owner\/\{ownerId\})?\/(.+?)\/snapshot(?:\/|$)/,ot=[`MaterializedSnapshot`,`MaterializedSnapshotPagedList`,`MaterializedSnapshotCursorPage`,`MaterializedSnapshotServerSentEventNonNullData`,`PagedList`,`ServerSentEventNonNullData`,`Snapshot`,`StateEvent`];function st(e){return ot.map(t=>e+t)}function ct(e,t,n){return e!==`wow.api.query.PagedList`&&e.startsWith(`wow.api.query.`)&&e.endsWith(`PagedList`)||e.startsWith(`wow.api.query.Operator`)&&e.endsWith(`Map`)?!1:e.startsWith(`wow.`)||e.endsWith(`AggregatedCondition`)||e.endsWith(`AggregatedDomainEventStream`)||e.endsWith(`AggregatedDomainEventStreamPagedList`)||e.endsWith(`AggregatedDomainEventStreamCursorPage`)||e.endsWith(`AggregatedDomainEventStreamServerSentEventNonNullData`)||e.endsWith(`AggregatedListQuery`)||e.endsWith(`AggregatedPagedQuery`)||e.endsWith(`AggregatedSingleQuery`)?!0:n.has(t())}var I=`@ahoo-wang/wow-client`,lt=`@ahoo-wang/wow-client/legacy`,ut=new Set([`Condition`,`ConditionOptions`,`ListQuery`,`Operator`,`PagedQuery`]),dt={"wow.command.CommandResult":`CommandResult`,"wow.command.CommandResultArray":`CommandResultArray`,"wow.MessageHeaderSqlType":`MessageHeaderSqlType`,"wow.api.BindingError":`BindingError`,"wow.api.DefaultErrorInfo":`ErrorInfo`,"wow.api.RecoverableType":`RecoverableType`,"wow.api.command.DefaultDeleteAggregate":`DeleteAggregate`,"wow.api.command.DefaultRecoverAggregate":`RecoverAggregate`,"wow.api.abac.DefaultApplyResourceTags":`ApplyResourceTags`,"wow.api.messaging.FunctionInfoData":`FunctionInfo`,"wow.api.messaging.FunctionKind":`FunctionKind`,"wow.api.modeling.AggregateId":`AggregateId`,"wow.api.query.Condition":`Condition`,"wow.api.query.ConditionOptions":`ConditionOptions`,"wow.api.query.ListQuery":`ListQuery`,"wow.api.query.Operator":`Operator`,"wow.api.query.PagedQuery":`PagedQuery`,"wow.api.query.Pagination":`Pagination`,"wow.api.query.Projection":`Projection`,"wow.api.query.Sort":`FieldSort`,"wow.api.query.Sort.Direction":`SortDirection`,"wow.api.query.DynamicDocument":`DynamicDocument`,"wow.api.query.DynamicDocumentArray":`DynamicDocumentArray`,"wow.command.CommandStage":`CommandStage`,"wow.command.SimpleWaitSignal":`WaitSignal`,"wow.configuration.Aggregate":`Aggregate`,"wow.configuration.BoundedContext":`BoundedContext`,"wow.configuration.WowMetadata":`WowMetadata`,"wow.modeling.DomainEvent":`DomainEvent`,"wow.openapi.BatchResult":`BatchResult`,"wow.messaging.CompensationTarget":`CompensationTarget`};function ft(e,t){let n=dt[e];if(t&&`filter`in t&&(e===`wow.api.query.ListQuery`?n=`FilterListQuery`:e===`wow.api.query.PagedQuery`&&(n=`FilterPagedQuery`)),n)return{name:n,path:ut.has(n)?lt:I}}var pt=new Set([`wow`,`Actuator`]),mt=[`tenantId`,`ownerId`];function ht(e){let t=0,n=0;return e.commands.forEach(e=>{e.path.startsWith(`/tenant/{tenantId}`)&&(t+=1),e.path.startsWith(`/owner/{ownerId}`)&&(n+=1)}),t===0&&n===0?`ResourceAttributionPathSpec.NONE`:t>n?`ResourceAttributionPathSpec.TENANT`:`ResourceAttributionPathSpec.OWNER`}function gt(e,t){return`${e.contextAlias}/${e.aggregateName}/${t}.ts`}function L(e,t){return`${te(e.aggregateName)}${t}`}var _t=`x-fetcher-method`;function vt(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!yt(n))throw new o(`specification`,`${_t} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=v(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function yt(e){return p(e)||/^[a-z]+$/.test(e)}function bt(e,t){let n=h(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function R(e,t){if(!e)return{name:``,path:`/`};let n=ft(e,t?.properties);if(n)return n;let r=e.split(`.`),i=-1;for(let e=0;e<r.length;e++)if(r[e]&&/^[A-Z]/.test(r[e])){i=e;break}let a=r.slice(0,i),o=a.length>0?`/${a.join(`/`)}`:`/`;return{name:te(r.slice(i)),path:o}}function xt(e,t){if(!e.$ref.startsWith(de))throw new o(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return R(T(e),t?D(e,t):void 0)}function z(e){let t=`${ie(e)}_BOUNDED_CONTEXT_ALIAS`;return/^\p{N}/u.test(t)?`_${t}`:t}var St=`Command`;function Ct(e,t){return[...t.contexts.values()].flatMap(t=>[...t].map(t=>wt(e,t)))}function wt(e,t){let{contextAlias:n,aggregateName:r}=t.aggregate;return{contextAlias:n,aggregateName:r,context:{alias:n,constantName:z(n)},commandClient:Tt(e,t),queryClient:At(t)}}function Tt(e,t){let n=t.aggregate,r=Ot(t);return{file:gt(n,`commandClient`),endpointPathsName:L(n,`CommandEndpointPaths`),className:L(n,`CommandClient`),streamClassName:L(n,`StreamCommandClient`),commands:[...t.commands.values()].map(t=>{let n=R(t.schema.key),i=new Set([`commandRequest`,`attributes`]);return{path:t.path,endpointMember:r.get(t),httpMethod:t.method,methodName:kt(t),typeName:Et(n),body:n,bodyKey:t.schema.key,optionalFields:Re(t.schema.schema,e.components),requestOptional:Ie(t.schema.schema),pathParameters:qe(t.path,t.pathParameters).filter(e=>!mt.includes(e.name)).map(e=>({name:bt(e.name,i),pathName:e.name,type:Ye(e)})),docs:[t.summary,t.description,`- operationId: \`${t.operation.operationId}\``,`- path: \`${t.path}\``]}})}}function Et(e){return e.path===`@ahoo-wang/wow-client`?`${e.name}Command`:e.name.endsWith(St)?void 0:`${e.name}${St}`}function Dt(e,t){for(let n of e){let e=`/${n.contextAlias}/${n.aggregateName}`,r=new Map;for(let n of t)n.info.path===e&&r.set(n.info.name,{holder:`the model of schema ${n.key}`,key:n.key});for(let{body:e,bodyKey:t}of n.commandClient.commands)e.path!==`@ahoo-wang/wow-client`&&r.set(e.name,{holder:`the model of schema ${t}`,key:t});for(let e of n.commandClient.commands){let{typeName:t,bodyKey:i}=e;if(t===void 0||e.body.path===`@ahoo-wang/wow-client`)continue;let a=r.get(t);if(a!==void 0&&a.bodyKey!==i)throw new o(`specification`,`Command ${e.methodName}() of aggregate ${n.contextAlias}.${n.aggregateName} generates the type ${t} for its body ${i}, but ${a.holder} already has that name. Rename the schema ${i} or ${a.key} in the document.`);r.set(t,{holder:`the type of command ${e.methodName}()`,key:i,bodyKey:i})}}}function Ot(e){let t=new Map,n=new Set;for(let r of e.commands.values()){let e=r.name.toUpperCase().replace(/[^\p{L}\p{N}_$]/gu,`_`);(!e||/^\p{N}/u.test(e))&&(e=`_${e}`);let i=e;for(let t=2;n.has(i);t++)i=`${e}_${t}`;n.add(i),t.set(r,i)}return t}function kt(e){let t=v(e.name)||`_`;return/^\p{N}/u.test(t)?`_${t}`:t}function At(e){let t=e.aggregate,n=v(t.aggregateName)||`_`;return{file:gt(t,`queryClient`),resourceName:e.resourceName,resourceAttribution:ht(e),state:R(e.state.key),fields:R(e.fields.key),eventTitlesName:L(t,`DomainEventTypeMapTitle`),eventTypeName:L(t,`DomainEventType`),events:[...e.events.values()].map(e=>({memberName:y(e.name),title:e.title,body:R(e.schema.key)})),factoryName:`${/^\p{N}/u.test(n)?`_`:``}${n}QueryClientFactory`}}function B(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var jt=`types.ts`;function Mt(e){return B(e.path,jt)}function Nt(e){return`${e}/boundedContext.ts`}function Pt(e){return e.contextAlias!==void 0||e.aggregateTags.size>0}function Ft(e,t){return t?{...e,...t}:e}var It=[`httpRequest`,`attributes`];function Lt(e,t,n,r){return new Rt(e,t,n,r).clients()}var Rt=class{document;wow;config;warnings;basePath;wowDocument;constructor(e,t,n,r){this.document=e,this.wow=t,this.config=n,this.warnings=r,this.wowDocument=Pt(t),t.contextAlias&&(this.basePath={alias:t.contextAlias,constantName:z(t.contextAlias)})}clients(){let e=this.tags(),t=this.groupOperations(e),n=new Map;return[...t.keys()].sort().map(r=>{let i=R(r),a=i;for(let e=2;n.has(V(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(V(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(V(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=t.path;this.wow.contextAlias&&(i=B(this.wow.contextAlias,i)),i=B(i,zt(r));let a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,basePath:this.basePath,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(It),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=vt(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),s=r.get(a);if(s!==void 0)throw new o(`specification`,`Operations ${s} 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=Ge(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`?qe(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:bt(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??(this.wowDocument?mt:[])).includes(t)}body(e,t){if(!e.requestBody)return;let n=S(e.requestBody)?pe(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=j(i,k,ge),o=bt(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Re(a.schema,this.document.components)}}:j(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:j(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(_e)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=F(e,this.document.components);if(!t)return{kind:`response`};let n=ye(t),r=n||xe(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=be(t);if(i){if(S(i)){let e=D(i,this.document.components);if(Oe(e)&&S(e.items)){let t=xt(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return Se(t)?{kind:`text`}:{kind:`response`}}groupOperations(e){let t=new Map;for(let n of this.document.endpoints){let r=`${n.method.toUpperCase()} ${n.path}`,i=n.operation.tags??[];if(i.length===0){this.warnings.push(`Skipping ${r}: it has no tag, and the tag names its API client.`);continue}let a=i.filter(t=>e.has(t));if(!(a.length<i.length)){if(!n.operation.operationId)this.warnings.push(`Skipping ${r}: it has no operationId, and the operationId names its method.`);else for(let e of a)t.has(e)||t.set(e,new Set),t.get(e).add(n)}}return t}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{!this.ignoresTag(t)&&!e.has(t)&&e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>{this.ignoresTag(t.name)||e.set(t.name,t)}),e}ignoresTag(e){return pt.has(e)||this.wow.aggregateTags.has(e)}};function zt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function V(e){return`${e.path}/${e.name}`.toLowerCase()}function Bt(e){let t=new Set(e.contexts.keys());return e.contextAlias&&t.add(e.contextAlias),[...t].sort().map(e=>({alias:e,constantName:z(e),file:Nt(e)}))}function Vt(e,t){let n=e.components?.schemas;if(!n)return[];let r=Ut(t),i=Ht(e,t),a=Object.keys(n).filter(e=>!ct(e,()=>R(e).name,r)||!e.startsWith(`wow.`)&&i.has(e));Wt(a);let o=Gt(t);return a.map(e=>{let r=n[e],i=R(e);return{key:e,info:i,file:Mt(i),schema:r,docSchema:Ft(r,t.schemaDocOverrides.get(e)),emptyMessageBody:o.has(e)&&Kt(r)}})}function Ht(e,t){let n=new Set,r=new Set,i=e.components??{},a=e=>{if(typeof e!=`object`||!e||r.has(e))return;if(r.add(e),Array.isArray(e)){e.forEach(a);return}let{$ref:t}=e;if(typeof t==`string`&&t.startsWith(`#/components/`)){let[e,...r]=t.slice(C.length).split(`/`),o=r.join(`/`);e===`schemas`&&n.add(o),a(i[e]?.[o])}Object.values(e).forEach(a)};for(let{operation:n}of e.endpoints){let e=n.tags??[];e.length>0&&e.every(e=>!pt.has(e)&&!t.aggregateTags.has(e))&&a(n)}return n}function Ut(e){let t=new Set;for(let n of e.contexts.values())for(let e of n)st(R(e.state.key).name).forEach(e=>t.add(e));return t}function Wt(e){let t=new Map;for(let n of e){let e=R(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 o(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function Gt(e){return new Set([...e.contexts.values()].flatMap(e=>[...e].flatMap(e=>[...[...e.commands.values()].map(e=>e.schema.key),...[...e.events.values()].map(e=>e.schema.key)])))}function Kt(e){return!S(e)&&e.type===`object`&&Object.keys(e.properties??{}).length===0&&(e.additionalProperties===void 0||e.additionalProperties===!1)&&!e.required?.length&&!N(e)&&e.enum===void 0&&e.const===void 0}function qt(e,t,n){let r=[],i=Bt(t),a=Vt(e,t),o=Ct(e,t);return Dt(o,a),{model:{contexts:i,models:a,aggregates:o,apiClients:Lt(e,t,n,r)},warnings:r}}var Jt=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})}))}},Yt=class{sourceFile;imports=new Jt;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&&Qt(n,e)&&t.push(Zt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},Xt=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 Yt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},Zt=e=>{e.blankLineIfLastNot()};function Qt(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 $t(e){return e.map(e=>({...e,initializer:`${e.initializer},`}))}function en(e,t){return{name:`[key: string]`,type:e,docs:t}}var tn=`@`;function H(e,t,n){return e.imports.add(t,n)}function U(e,t,n){return H(e,W(e,t,n),[n.name])}function W(e,n,r){return r.path.startsWith(tn)?r.path:nn(e.directoryPath,(0,t.join)(n,r.path,jt))}function nn(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 G(e,n,r,i){return H(e,nn(e.directoryPath,(0,t.join)(n,Nt(r))),[i])}function rn(e,t=`
2
+ `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(an);return n.length>0?n.join(t):void 0}function an(e){return e.replace(/\*\//g,`*\\/`)}function K(e,t){let n=rn(t);n&&(e.docs=[...e.docs??[],n])}function on(e,t,n=!1){e=ln(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&un(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),dn(r,e,`default`),dn(r,e,`example`),pn(r,e),mn(r,e),hn(r,e),r}function sn(e,t,n){K(e,on(t,n))}function cn(e,t,n,r=!1){let i=on(t,n,!0);r&&fn(i,`schema`,t),K(e,i)}function ln(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 un(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function dn(e,t,n){let r=t[n];r&&(typeof r==`object`?fn(e,n,r):e.push(`- ${n}: \`${r}\``))}function fn(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function pn(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 mn(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 hn(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 gn(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 _n=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],vn=new Set([`string`,`number`,`boolean`]),yn=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function bn(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function q(e,t,n=new Set){if(S(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=D(e,t);return r?q(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(je(e)&&e.type===void 0){let r=e.allOf.map(e=>q(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>bn(e,i))?i:void 0}if(!(N(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:P(e.type)}}}function xn(e,t,n){let r=q(t,n);if(typeof r!=`object`)return!1;let i=q(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function Sn(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>xn(e,n,t))}function Cn(e){return e.nullable!==!0||M(e)||!N(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(S))}function wn(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 J(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>J(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${y(e)}: ${J(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var Tn=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([..._n,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=(Le(t)?`readonly `:``)+y(e);if(!S(t)){let e=rn(on(t),`
3
+ * `);if(e)return`
4
+ /**
5
+ * ${e}
6
+ */
7
+ ${r}: ${n}
8
+ `}return`${r}: ${n}`})}objectType(e){let t=[];De(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${y(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Ne(e)&&Fe(e)?this.mapType(e):Sn(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=Fe(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>S(e)?this.components&&D(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(S(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(Cn(e))return`(${this.type({...e,nullable:!1})}) | null`;if(N(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(!wn(e.const,e))return`never`;let t=J(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!M(e))return`(${this.type({...e,nullable:!1})}) | null`;if(M(e)){let t=e.enum.filter(t=>wn(t,e)).map(e=>J(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||vn.has(n)?t:`(${t}) & (${n})`}return Ne(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Me(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?P(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-`)&&!yn.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`||yn.has(e));if(!r.every(e=>S(e)||i(e)))return;let a=r.map(t=>S(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||!S(n))return r;let a=T(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>b(e)).join(` | `);return`(${r} & { ${y(i.propertyName)}: ${s} })`}};function Y(e,t){let n=new Tn(e);return{text:t(n),imports:n.imports()}}function En(e,t){return Y(t,t=>t.type(e))}function Dn(e,t){return Y(t,t=>t.additionalProperties(e))}function On(e,t){return Y(t,t=>t.additionalPropertyType(e))}function kn(e,t){return Y(t,t=>t.requiredAdditionalPropertyType(e))}function An(e,t){return Y(t,t=>t.mapValueType(e))}var jn=`@ahoo-wang/fetcher`,Mn=[`ContentTypeValues`,`ResultExtractors`],Nn=`@ahoo-wang/fetcher-decorator`,Pn=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Fn={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},In={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Ln=`{
10
+ headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
+ resultExtractor: JsonEventStreamResultExtractor,
12
+ }`,Rn=`COMMAND_STREAM_ENDPOINT`;function zn(e){H(e,jn,Mn)}function Bn(e){H(e,Nn,Pn)}function Vn(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 Hn(t,n){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],n===void 0?t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]}):(t.properties=[...t.properties??[],{name:`apiMetadata`,type:`ApiMetadata`,isReadonly:!0}],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0}],statements:`this.apiMetadata = { ${n}, ...apiMetadata };`,docs:["@param apiMetadata - Merged over the defaults, so passing only a `fetcher` keeps the base path."]}))}function Un(e){return e===`delete`?`del`:e}var Wn=`@ahoo-wang/fetcher-eventstream`;function Gn(e){H(e,Wn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function Kn(e,t){let n=t.modules.module(e.file);zn(n),Bn(n),Gn(n);let r=Vn(e.className,n);K(r,[e.description]);let i;e.basePath&&(G(n,t.outputDir,e.basePath.alias,e.basePath.constantName),i=`basePath: ${e.basePath.constantName}`),Hn(r,i);let a=qn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(Jn(t,a))}function qn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>W(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=En(e,r);return t.imports.apply(n.imports),n.text}}}function Jn(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:[b(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:Yn(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=Xn(e.returns,t),o=b(e.path),s={name:e.name,decorators:[{name:Un(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return K(s,[...e.docs]),s}function Yn(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:(H(t.module,jn,[`PartialBy`]),`PartialBy<${e}, ${r.map(b).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function Xn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?In:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Ln};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Ln}}case`text`:return In;case`response`:return Fn}}var Zn=`DEFAULT_COMMAND_CLIENT_OPTIONS`;function Qn(t,n){let r=t.commandClient;if(r.commands.length===0)return;let i=n.modules.module(r.file);i.add({kind:e.StructureKind.Enum,name:r.endpointPathsName,isExported:!0,members:$t(r.commands.map(e=>({name:e.endpointMember,initializer:b(e.path)})))});let a=new Set,o=r.commands.map(e=>$n(i,n.outputDir,e,a));G(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:Zn,type:`ApiMetadata`,initializer:`{
13
+ basePath: ${t.context.constantName}
14
+ }`}],isExported:!1}),H(i,I,[`CommandRequest`,`CommandResult`,`CommandResultEventStream`,`CommandBody`,Rn]),H(i,`@ahoo-wang/fetcher`,[`PartialBy`]),Bn(i);let s=Vn(r.className,i,[],[`R = CommandResult`]);Hn(s,`...${Zn}`);for(let[e,t]of r.commands.entries()){let n=er(t,o[e]),i={name:t.methodName,decorators:[{name:Un(t.httpMethod),arguments:[`${r.endpointPathsName}.${t.endpointMember}`]}],parameters:n,returnType:`Promise<R>`,statements:`throw autoGeneratedError(${n.map(e=>e.name).join(`,`)});`};(s.methods??=[]).push(i),K(i,[...t.docs])}Vn(r.streamClassName,i,[`''`,Rn],[],`${r.className}<CommandResultEventStream>`)}function $n(t,n,r,i){if(r.body.path===`@ahoo-wang/wow-client`)return H(t,I,[r.typeName]),r.typeName;U(t,n,r.body);let a=r.body.name,o=r.optionalFields.map(b).join(` | `);o!==``&&(a=`PartialBy<${a},${o}>`);let s=`CommandBody<${a}>`;return r.typeName===void 0?s:(i.has(r.typeName)||(i.add(r.typeName),t.add({kind:e.StructureKind.TypeAlias,name:r.typeName,type:s,isExported:!0})),r.typeName)}function er(e,t){return[...e.pathParameters.map(e=>({name:e.name,type:e.type,hasQuestionToken:!1,decorators:[{name:`path`,arguments:[b(e.pathName)]}]})),{name:`commandRequest`,hasQuestionToken:e.requestOptional,type:`CommandRequest<${t}>`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}]}function tr(e){return gn(e,{ofKey:e=>R(e),ofReference:xt})}function nr(t,n){let r=n.modules.module(t.file);t.emptyMessageBody?cn(r.add({kind:e.StructureKind.TypeAlias,name:t.info.name,type:`globalThis.Record<string, never>`,isExported:!0}),t.docSchema,t.key,n.schemaDocs===`full`):new ir(t,r,n).write()}function rr(e){let t=new Set,n=new Map;for(let r of e){let e=ae(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,y(a))}return n}var ir=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=>W(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&cn(e,this.model.docSchema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return S(e)?this.processTypeAlias(e):M(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||N(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):De(e)?this.processInterface(e):Ne(e)&&typeof e.additionalProperties==`object`&&!Fe(e)&&!e.required?.length?this.processIndexSignature(e):Oe(e)?this.processArray(e):N(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(En(e,this.scope))}processEnum(t){let n=Ee(t);if(n){let t=rr(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:J(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=rr(r);return N(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:J(e)}))})}addPropertyToInterface(e,t,n){let r={name:y(t),type:this.resolveType(n),isReadonly:Le(n)};(e.properties??=[]).push(r),sn(r,n)}processInterface(t){if(Sn(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:y(e),type:this.emit(kn(t,this.scope))});return this.emit(Dn(t,this.scope))&&n.push(en(this.emit(On(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:Me(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[en(this.emit(An(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})}},ar=`DEFAULT_QUERY_CLIENT_OPTIONS`;function or(t,n){let r=t.queryClient,i=n.modules.module(r.file);H(i,I,[`QueryClientFactory`,`QueryClientOptions`,`ResourceAttributionPathSpec`]),G(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:ar,type:`QueryClientOptions`,initializer:`{
15
+ contextAlias: ${t.context.constantName},
16
+ aggregateName: ${b(r.resourceName)},
17
+ resourceAttribution: ${r.resourceAttribution},
18
+ }`}],isExported:!1}),i.add({kind:e.StructureKind.Enum,name:r.eventTitlesName,isExported:!0,members:$t(r.events.map(e=>({name:e.memberName,initializer:b(e.title)})))});for(let e of r.events)U(i,n.outputDir,e.body);i.add({kind:e.StructureKind.TypeAlias,isExported:!0,name:r.eventTypeName,type:r.events.map(e=>e.body.name).join(` | `)||`never`}),U(i,n.outputDir,r.state),U(i,n.outputDir,r.fields),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:r.factoryName,initializer:`new QueryClientFactory<${r.state.name}, \`\${${r.fields.name}}\`, ${r.eventTypeName}>(${ar})`}],isExported:!0})}function sr(e,t){e.contexts.forEach(e=>cr(e,t)),e.models.forEach(e=>nr(e,t)),e.aggregates.forEach(e=>or(e,t)),e.aggregates.forEach(e=>Qn(e,t)),e.apiClients.forEach(e=>Kn(e,t))}function cr(e,t){t.modules.module(e.file).add(`export const ${e.constantName} = ${b(e.alias)};`)}function lr(e,t){let n=[];return ur(e,t,n),n}function ur(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:fr(t)})}for(let i of e.getDirectories()){let e=ur(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:dr(i,r,t,n)}function dr(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])=>x(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 fr(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 pr(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 mr(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())&&!pr(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>hr(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function hr(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 gr(e){let t=e.flatMap(mr);for(let e of t)e()}var _r=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function vr(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!_r.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(`
19
+ `)}`)}var yr=`// Code generated by wow-generator. DO NOT EDIT.
20
+
21
+ `,br={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function xr(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(br),n.organizeImports(br)}),gr(e),vr(e);for(let t of e)t.insertText(0,yr)}var Sr=3e4;function Cr(e){return/^https?:\/\//i.test(e)}function wr(e,t={}){return Cr(e)?Tr(e,t):Dr(e)}async function Tr(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`:Er(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 Er(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 Dr(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Or(e,t){let n;try{n=await wr(e,t)}catch(t){throw new o(`input`,`Cannot read the OpenAPI document ${e}: ${s(t)}`,{cause:t})}let r;try{r=Ar(n)}catch(t){throw new o(`input`,`Cannot parse the OpenAPI document ${e}: ${s(t)}`,{cause:t})}return kr(r,e)}function kr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new o(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new o(`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 o(`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 o(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Ar(e){switch(jr(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function jr(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`)}var Mr=`./fetcher-generator.config.json`;async function Nr(e,t,n){if(e!==void 0)return{...await Ir({path:e,explicit:!0},t,n),origin:X(e)};for(let e of[i,Mr]){let r=await Ir({path:e,explicit:!1},t,n);if(r===void 0)continue;let a=[...r.warnings];return e===`./fetcher-generator.config.json`&&a.push(`${X(e)} uses the deprecated name; rename it to ${i.slice(2)}. The old name is no longer read from v10.`),{config:r.config,origin:X(e),warnings:a}}return t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}}var Pr=[`apiClients`],Fr=[`ignorePathParameters`,`methodNames`];async function Ir(e,t,n){let r=X(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await wr(e.path,n)}catch(n){if(!e.explicit&&Lr(n)){t.debug(`No configuration file at ${r}`);return}throw new o(`configuration`,`Cannot read configuration ${r}: ${s(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Ar(i)}catch(e){throw new o(`configuration`,`Cannot parse configuration ${r}: ${s(e)}`,{cause:e})}let c=zr(a,r);return t.debug(`Configuration loaded from ${r}: ${Vr(c.config)}`),c}function X(e){return Cr(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Lr(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function Z(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rr(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 zr(e,t){if(!Q(e))throw new o(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${Z(e)}`);let n=[];return Rr(n,t,`configuration`,e,Pr),Br(e.apiClients,t,n),{config:e,warnings:n}}function Br(e,t,n){if(e!==void 0){if(!Q(e))throw new o(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${Z(e)}`);for(let[r,i]of Object.entries(e)){if(!Q(i))throw new o(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${Z(i)}`);Rr(n,t,`apiClients["${r}"]`,i,Fr);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new o(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${Z(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!Q(a))throw new o(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${Z(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!p(n))throw new o(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function Vr(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}function Hr(e){return{openAPI:e,components:e.components,endpoints:Ve(e.paths,e.components)}}var Ur=`.wow-generator.json`,Wr=`.fetcher-generator.json`,Gr=class e{project;outputPath;outputDir;previous;legacyManifest;written=new Set;stale=new Set;constructor(e,t,n,r,i){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r,this.legacyManifest=i}static open(n,r,i){let a=n.getFileSystem(),s=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,Wr),l=a.fileExistsSync(c)?c:void 0,u=(0,t.join)(r,Ur);!a.fileExistsSync(u)&&l&&(u=l);let d=new Map;if(a.fileExistsSync(u)){let e=Kr(u,a.readFileSync(u));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Yr(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new o(`output`,`Invalid generated file entry in ${u}: ${n}`);d.set(e,i)}}let f=new Set([...i?.written??[],...d.keys()]);for(let e of n.getSourceFiles())f.has(e.getFilePath())&&e.forget();return new e(n,s,r,d,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=B(t,e);Yr(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 $(`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 Jr(`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 $(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Ur),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),qr(n.readFileSync(e.getFilePath()))]))},null,2)+`
22
+ `;await $(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)});let s=this.legacyManifest;s&&n.fileExistsSync(s)&&await $(`delete`,s,()=>n.delete(s))}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Yr(n.realpathSync(this.outputDir),n.realpathSync(e)),qr(n.readFileSync(e))===t):!1}};function Kr(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 o(`output`,`Cannot parse the generation manifest ${e}: ${s(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 o(`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 o(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function qr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Jr(e,t,n){return n instanceof o?n:new o(`output`,`Cannot ${e} ${t}: ${s(n)}`,{cause:n})}async function $(e,t,n){try{await n()}catch(n){throw Jr(e,t,n)}}function Yr(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),s=(0,t.relative)(i,a);if(s===``||s.startsWith(`..`)||(0,t.isAbsolute)(s))throw new o(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}function Xr(e){let{openAPI:t,components:n,endpoints:r}=e,i=[],a=new Map,s=new Set,c=t.tags??[],l=new Set(c.map(e=>e.name)),u=new Set(r.flatMap(e=>e.operation.tags??[]).filter(e=>!l.has(e))),d=new Map;for(let e of[...c,...[...u].map(e=>({name:e}))]){let t=et(e);t&&d.set(e.name,{aggregate:t,commands:new Map,events:new Map})}let f=e=>(e.tags??[]).flatMap(e=>{let t=d.get(e);return t?(s.add(e),[t]):[]}),p=(e,t,n)=>{let r=a.get(e.key);r||(r={},a.set(e.key,r));let i=t in r?r[t]:e.schema[t];r[t]=i||n},m=(e,t)=>new o(`specification`,`Cannot read the Wow metadata of ${e.operationId}: ${t}. wow-generator reads documents from Wow ${Xe} or later.`),h=(e,t)=>{let n=at.exec(t)?.[1];n&&e.forEach(e=>{e.resourceName??=n})},ee=e=>{let{operation:t,path:r}=e;if(t.operationId===`wow.command.send`)return;let a=tt(t.operationId);if(!a)return;let s=F(t),c=new Set;for(;s&&S(s)&&s.$ref!==`#/components/responses/wow.CommandOk`;){if(!s.$ref.startsWith(w))return;if(c.has(s.$ref))throw new o(`specification`,`Cyclic component reference: ${s.$ref}`);c.add(s.$ref),s=n?.responses?.[s.$ref.slice(w.length)]}if(!s||!S(s)||s.$ref!==`#/components/responses/wow.CommandOk`)return;let l=f(t);if(!t.requestBody)return;let u=Ke(t,n??{}),d=(S(t.requestBody)?pe(t.requestBody,n??{}):t.requestBody)?.content?.[k]?.schema;if(!S(d)){l.length>0&&i.push(`Skipping command ${t.operationId} (${e.method.toUpperCase()} ${r}): its application/json request body is not a $ref to a component schema.`);return}let m=O(d,n??{});if(!m.schema)return;p(m,`title`,t.summary),p(m,`description`,t.description);let h={name:a,method:e.method,path:r,pathParameters:u,summary:t.summary,description:t.description,schema:m,operation:t};l.forEach(e=>{e.commands.set(a,h)})},te=({operation:e,path:t})=>{if(!e.operationId?.endsWith(`.snapshot_state.single`))return;let r=f(e);h(r,t);let i=We(e,n);if(!S(i)){if(r.length>0)throw m(e,`its 200 application/json response is not a $ref to the state schema`);return}let a=O(i,n);r.forEach(e=>{e.state=a})},ne=({operation:e})=>{if(!n||!e.operationId?.endsWith(`.event.list_query`))return;let t=f(e);if(t.length===0)return;let r=We(e,n);if(S(r))return;let i=r?.items;if(!S(i))throw m(e,`its 200 application/json response is not an array of a $ref to the event stream schema`);let a=Zr(D(i,n),[`properties`,`body`,`items`,`anyOf`]);if(!Array.isArray(a))throw m(e,`the event stream schema ${i.$ref} has no properties.body.items.anyOf listing the domain events`);let o=a.map((t,r)=>{let a=Zr(t,[`properties`,`name`,`const`]),o=Zr(t,[`properties`,`body`]);if(typeof a!=`string`||!S(o))throw m(e,`domain event ${r} of ${i.$ref} needs a properties.name.const and a properties.body that is a $ref to the event schema`);let s=O(o,n);return p(s,`title`,t.title),{title:t.title??a,name:a,schema:s}});t.forEach(e=>{o.forEach(t=>{e.events.set(t.name,t)})})},g=({operation:e,path:t})=>{if(!n||!e.operationId?.endsWith(`.snapshot.count`))return;let r=f(e);if(r.length===0)return;h(r,t);let i=e.requestBody?S(e.requestBody)?pe(e.requestBody,n):e.requestBody:void 0;if(!i)throw m(e,`it has no request body`);let a=i[it],o;if(a!==void 0){if(!S(a))throw m(e,`${it} must be a schema reference`);o=a}else{let t=i.content?.[k]?.schema,r=(S(t)?D(t,n):void 0)?.properties?.field;if(!S(r))throw m(e,`its request body has no ${it}, and its condition schema has no field $ref to read the query fields from`);o=r}let s=O(o,n);r.forEach(e=>{e.fields=s})};for(let e of r)ee(e),te(e),ne(e),g(e);let _=new Map;for(let[e,t]of d){if(!t.state||!t.fields){if(s.has(e)){let n=[t.state?void 0:`${e}${nt}`,t.fields?void 0:`${e}${rt}`].filter(Boolean);i.push(`Skipping aggregate ${e}: the document has no ${n.join(` or `)} operation, so it generates neither command nor query clients for it.`)}continue}let n=t.aggregate.contextAlias,r=_.get(n);r||(r=new Set,_.set(n,r)),r.add({...t,resourceName:t.resourceName??t.aggregate.aggregateName})}return{contextAlias:Qe(t),contexts:_,aggregateTags:s,schemaDocOverrides:a,warnings:i}}function Zr(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}var Qr=Symbol(`project`),$r=Symbol(`signal`),ei=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new l,this.signal=t[$r],this.project=t[Qr]??ti(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 from OpenAPI specification`),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},s=await Nr(n.configPath,e,a);i(s.warnings),t?.throwIfAborted(),e.debug(`Parsing OpenAPI specification`);let c=await Or(n.inputPath,a);t?.throwIfAborted(),e.debug(`OpenAPI specification parsed successfully`);let l=ce(c);if(l.length>0)throw new o(`specification`,`${n.inputPath} has ${l.length} $ref(s) that point at nothing: ${l.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${l.length>10?`, …`:``}`);let u=Hr(c);e.debug(`Resolving bounded context aggregates`);let d=Xr(u);i(d.warnings),e.debug(`Resolved ${d.contexts.size} bounded context aggregates`);let f=Gr.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=qt(u,d,s.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new Xt(e=>f.claim(e));sr(p.model,{modules:m,outputDir:n.outputDir,types:tr(u.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(lr(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),xr(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:s.origin,warnings:r}}};function ti(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new o(`configuration`,`Cannot read the TypeScript configuration ${t}: ${s(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $r}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Sr}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ei}});
23
+ //# sourceMappingURL=codeGenerator-BMyiC0tW.cjs.map