@ahoo-wang/wow-generator 9.6.0 → 9.6.2
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/api/options.d.cts +2 -2
- package/dist/api/options.d.ts +2 -2
- package/dist/cli.cjs +1 -1
- package/dist/cli.js +2 -2
- package/dist/codeGenerator-CXVxnY-Z.cjs +23 -0
- package/dist/codeGenerator-CXVxnY-Z.cjs.map +1 -0
- package/dist/{codeGenerator-kyY9eLML.js → codeGenerator-DCYj0aYK.js} +580 -563
- package/dist/codeGenerator-DCYj0aYK.js.map +1 -0
- package/dist/emit/jsdoc.d.cts +13 -1
- package/dist/emit/jsdoc.d.ts +13 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
- package/dist/codeGenerator-DpDTDC4o.cjs +0 -23
- package/dist/codeGenerator-DpDTDC4o.cjs.map +0 -1
- package/dist/codeGenerator-kyY9eLML.js.map +0 -1
package/dist/emit/jsdoc.d.cts
CHANGED
|
@@ -19,7 +19,19 @@ export declare function escapeJsDoc(text: string): string;
|
|
|
19
19
|
* description, after the ones it already has.
|
|
20
20
|
*/
|
|
21
21
|
export declare function addJSDoc(node: JSDocableNodeStructure, descriptions: (string | undefined)[]): void;
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* The doc comment lines of a schema.
|
|
24
|
+
*
|
|
25
|
+
* A nullable value written as `anyOf: [{type: null}, X]` (or `oneOf`) is
|
|
26
|
+
* documented from its non-null branch too, so its `format` and constraints
|
|
27
|
+
* are not lost; what the schema itself says comes first.
|
|
28
|
+
*
|
|
29
|
+
* @param schema - The schema
|
|
30
|
+
* @param key - The schema's component key, given for a model
|
|
31
|
+
* @param main - Whether the comment is a model's, which also lists the
|
|
32
|
+
* properties its schema requires
|
|
33
|
+
*/
|
|
34
|
+
export declare function schemaJSDoc(schema: Schema, key?: string, main?: boolean): (string | undefined)[];
|
|
23
35
|
/**
|
|
24
36
|
* Adds a JSDoc comment to a declaration based on the schema's title and description.
|
|
25
37
|
* @param node - The declaration to add the JSDoc comment to
|
package/dist/emit/jsdoc.d.ts
CHANGED
|
@@ -19,7 +19,19 @@ export declare function escapeJsDoc(text: string): string;
|
|
|
19
19
|
* description, after the ones it already has.
|
|
20
20
|
*/
|
|
21
21
|
export declare function addJSDoc(node: JSDocableNodeStructure, descriptions: (string | undefined)[]): void;
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* The doc comment lines of a schema.
|
|
24
|
+
*
|
|
25
|
+
* A nullable value written as `anyOf: [{type: null}, X]` (or `oneOf`) is
|
|
26
|
+
* documented from its non-null branch too, so its `format` and constraints
|
|
27
|
+
* are not lost; what the schema itself says comes first.
|
|
28
|
+
*
|
|
29
|
+
* @param schema - The schema
|
|
30
|
+
* @param key - The schema's component key, given for a model
|
|
31
|
+
* @param main - Whether the comment is a model's, which also lists the
|
|
32
|
+
* properties its schema requires
|
|
33
|
+
*/
|
|
34
|
+
export declare function schemaJSDoc(schema: Schema, key?: string, main?: boolean): (string | undefined)[];
|
|
23
35
|
/**
|
|
24
36
|
* Adds a JSDoc comment to a declaration based on the schema's title and description.
|
|
25
37
|
* @param node - The declaration to add the JSDoc comment to
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./codeGenerator-CXVxnY-Z.cjs");exports.CodeGenerator=e.t,exports.ConsoleLogger=e.i,exports.DEFAULT_CONFIG_PATH=e.c,exports.EXIT_CODES=e.o,exports.GeneratorError=e.s,exports.SilentLogger=e.a;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, c as t, i as n, o as r, s as i, t as a } from "./codeGenerator-
|
|
1
|
+
import { a as e, c as t, i as n, o as r, s as i, t as a } from "./codeGenerator-DCYj0aYK.js";
|
|
2
2
|
export { a as CodeGenerator, n as ConsoleLogger, t as DEFAULT_CONFIG_PATH, r as EXIT_CODES, i as GeneratorError, e as SilentLogger };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/wow-generator",
|
|
3
|
-
"version": "9.6.
|
|
3
|
+
"version": "9.6.2",
|
|
4
4
|
"description": "Generates TypeScript models, Fetcher decorator clients and Wow command and query clients from a local or remote OpenAPI 3 document. The Wow clients follow the CQRS model of the Wow DDD framework (https://github.com/Ahoo-Wang/Wow).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"wow",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"@ahoo-wang/fetcher": "^5.1.5 || ^6.0.0",
|
|
65
65
|
"@ahoo-wang/fetcher-decorator": "^5.1.5 || ^6.0.0",
|
|
66
66
|
"@ahoo-wang/fetcher-eventstream": "^5.1.5 || ^6.0.0",
|
|
67
|
-
"@ahoo-wang/wow-client": "~9.6.
|
|
67
|
+
"@ahoo-wang/wow-client": "~9.6.2"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
70
|
"ts-morph": "^28.0.0",
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
"vite": "8.3.3",
|
|
91
91
|
"vite-bundle-analyzer": "^1.3.9",
|
|
92
92
|
"vitest": "^4.1.11",
|
|
93
|
-
"@ahoo-wang/wow-client": "~9.6.
|
|
93
|
+
"@ahoo-wang/wow-client": "~9.6.2"
|
|
94
94
|
},
|
|
95
95
|
"scripts": {
|
|
96
96
|
"build": "vite build && pnpm test:package",
|
|
@@ -1,23 +0,0 @@
|
|
|
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 g(e){return e.split(d)}function ne(e){return Array.isArray(e)?e.flatMap(e=>_(g(e))):_(g(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?``:ne(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?``:ne(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/`,de=`${C}responses/`,fe=`${C}schemas/`;function pe(e){return e.$ref.split(`/`).pop()}function w(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 T(e,t){return w(e,t.schemas,fe)}function me(e,t){return w(e,t.responses,de)}function E(e,t){return w(e,t.requestBodies,ue)}function D(e,t){return w(e,t.parameters,le)}function O(e,t){return{key:pe(e),schema:T(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 P(e){return e[Pe]}function Fe(e){return e.type===`object`?!e.properties||Object.keys(e.properties).length===0:!1}function Ie(e){return e.readOnly===!0}function F(e){if(Array.isArray(e))return e.map(e=>F(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 Le(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&&T(e,t));return}if(e.nullable||Array.isArray(e.type)){a=!0;return}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 Re(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 ze(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=S(i)?n&&D(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function Be(e,t){let n=[];for(let[r,i]of Object.entries(e))Ve(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:ze(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Re)}function Ve(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 He(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 I(e,t){let n=He(e),r=n?e.responses[n]:void 0;return t&&S(r)?me(r,t):r}function Ue(e,t){return ye(I(e,t))}function We(e,t){return(e.parameters??[]).map(e=>S(e)?D(e,t):e).filter(e=>e!==void 0)}function Ge(e,t){return e.parameters?e.parameters.map(e=>S(e)?D(e,t):e).filter(e=>e?.in===`path`):[]}function Ke(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 qe=`string`;function Je(e){return!e.schema||S(e.schema)||!e.schema.type||!we(e.schema.type)?qe:F(e.schema.type)}var Ye=`8.10`,Xe=`x-wow-context-alias`;function Ze(e){return e.info[Xe]}function Qe(e){let t=e.split(`.`);return t.length!=2||t[0].length===0||t[1].length===0?null:t}function $e(e){let t=Qe(e.name);return t?{tag:e,contextAlias:t[0],aggregateName:t[1]}:null}function et(e){if(!e)return null;let t=e.split(`.`);return t.length==3?t[2]:null}var tt=`.snapshot_state.single`,nt=`.snapshot.count`,rt=`x-wow-query-fields`,it=/^(?:\/tenant\/\{tenantId\})?(?:\/owner\/\{ownerId\})?\/(.+?)\/snapshot(?:\/|$)/,at=[`MaterializedSnapshot`,`MaterializedSnapshotPagedList`,`MaterializedSnapshotCursorPage`,`MaterializedSnapshotServerSentEventNonNullData`,`PagedList`,`ServerSentEventNonNullData`,`Snapshot`,`StateEvent`];function ot(e){return at.map(t=>e+t)}function st(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 L=`@ahoo-wang/wow-client`,ct=`@ahoo-wang/wow-client/legacy`,lt=new Set([`Condition`,`ConditionOptions`,`ListQuery`,`Operator`,`PagedQuery`]),ut={"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 dt(e,t){let n=ut[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:lt.has(n)?ct:L}}var ft=new Set([`wow`,`Actuator`]),pt=[`tenantId`,`ownerId`];function mt(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 ht(e,t){return`${e.contextAlias}/${e.aggregateName}/${t}.ts`}function R(e,t){return`${te(e.aggregateName)}${t}`}var gt=`x-fetcher-method`;function _t(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!vt(n))throw new o(`specification`,`${gt} 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 vt(e){return p(e)||/^[a-z]+$/.test(e)}function yt(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 z(e,t){if(!e)return{name:``,path:`/`};let n=dt(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 bt(e,t){if(!e.$ref.startsWith(fe))throw new o(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return z(pe(e),t?T(e,t):void 0)}function B(e){let t=`${ie(e)}_BOUNDED_CONTEXT_ALIAS`;return/^\p{N}/u.test(t)?`_${t}`:t}var xt=`Command`;function St(e,t){return[...t.contexts.values()].flatMap(t=>[...t].map(t=>Ct(e,t)))}function Ct(e,t){let{contextAlias:n,aggregateName:r}=t.aggregate;return{contextAlias:n,aggregateName:r,context:{alias:n,constantName:B(n)},commandClient:wt(e,t),queryClient:kt(t)}}function wt(e,t){let n=t.aggregate,r=Dt(t);return{file:ht(n,`commandClient`),endpointPathsName:R(n,`CommandEndpointPaths`),className:R(n,`CommandClient`),streamClassName:R(n,`StreamCommandClient`),commands:[...t.commands.values()].map(t=>{let n=z(t.schema.key),i=new Set([`commandRequest`,`attributes`]);return{path:t.path,endpointMember:r.get(t),httpMethod:t.method,methodName:Ot(t),typeName:Tt(n),body:n,bodyKey:t.schema.key,optionalFields:Le(t.schema.schema,e.components),requestOptional:Fe(t.schema.schema),pathParameters:Ke(t.path,t.pathParameters).filter(e=>!pt.includes(e.name)).map(e=>({name:yt(e.name,i),pathName:e.name,type:Je(e)})),docs:[t.summary,t.description,`- operationId: \`${t.operation.operationId}\``,`- path: \`${t.path}\``]}})}}function Tt(e){return e.path===`@ahoo-wang/wow-client`?`${e.name}Command`:e.name.endsWith(xt)?void 0:`${e.name}${xt}`}function Et(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 Dt(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 Ot(e){let t=v(e.name)||`_`;return/^\p{N}/u.test(t)?`_${t}`:t}function kt(e){let t=e.aggregate,n=v(t.aggregateName)||`_`;return{file:ht(t,`queryClient`),resourceName:e.resourceName,resourceAttribution:mt(e),state:z(e.state.key),fields:z(e.fields.key),eventTitlesName:R(t,`DomainEventTypeMapTitle`),eventTypeName:R(t,`DomainEventType`),events:[...e.events.values()].map(e=>({memberName:y(e.name),title:e.title,body:z(e.schema.key)})),factoryName:`${/^\p{N}/u.test(n)?`_`:``}${n}QueryClientFactory`}}function V(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var At=`types.ts`;function jt(e){return V(e.path,At)}function Mt(e){return`${e}/boundedContext.ts`}function Nt(e){return e.contextAlias!==void 0||e.aggregateTags.size>0}function Pt(e,t){return t?{...e,...t}:e}var Ft=[`httpRequest`,`attributes`];function It(e,t,n,r){return new Lt(e,t,n,r).clients()}var Lt=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=Nt(t),t.contextAlias&&(this.basePath={alias:t.contextAlias,constantName:B(t.contextAlias)})}clients(){let e=this.tags(),t=this.groupOperations(e),n=new Map;return[...t.keys()].sort().map(r=>{let i=z(r),a=i;for(let e=2;n.has(H(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(H(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(H(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=V(this.wow.contextAlias,i)),i=V(i,Rt(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(Ft),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=_t(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=We(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`?Ke(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:yt(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?pt:[])).includes(t)}body(e,t){if(!e.requestBody)return;let n=S(e.requestBody)?E(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=j(i,k,ge),o=yt(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Le(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=I(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=T(i,this.document.components);if(Oe(e)&&S(e.items)){let t=bt(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.`);continue}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 ft.has(e)||this.wow.aggregateTags.has(e)}};function Rt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function H(e){return`${e.path}/${e.name}`.toLowerCase()}function zt(e){let t=new Set(e.contexts.keys());return e.contextAlias&&t.add(e.contextAlias),[...t].sort().map(e=>({alias:e,constantName:B(e),file:Mt(e)}))}function Bt(e,t){let n=e.components?.schemas;if(!n)return[];let r=Ht(t),i=Vt(e,t),a=Object.keys(n).filter(e=>!st(e,()=>z(e).name,r)||!e.startsWith(`wow.`)&&i.has(e));Ut(a);let o=Wt(t);return a.map(e=>{let r=n[e],i=z(e);return{key:e,info:i,file:jt(i),schema:r,docSchema:Pt(r,t.schemaDocOverrides.get(e)),emptyMessageBody:o.has(e)&&Gt(r)}})}function Vt(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=>!ft.has(e)&&!t.aggregateTags.has(e))&&a(n)}return n}function Ht(e){let t=new Set;for(let n of e.contexts.values())for(let e of n)ot(z(e.state.key).name).forEach(e=>t.add(e));return t}function Ut(e){let t=new Map;for(let n of e){let e=z(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 Wt(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 Gt(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 Kt(e,t,n){let r=[],i=zt(t),a=Bt(e,t),o=St(e,t);return Et(o,a),{model:{contexts:i,models:a,aggregates:o,apiClients:It(e,t,n,r)},warnings:r}}var qt=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})}))}},Jt=class{sourceFile;imports=new qt;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&&Zt(n,e)&&t.push(Xt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},Yt=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 Jt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},Xt=e=>{e.blankLineIfLastNot()};function Zt(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 Qt(e){return e.map(e=>({...e,initializer:`${e.initializer},`}))}function $t(e,t){return{name:`[key: string]`,type:e,docs:t}}var en=`@`;function U(e,t,n){return e.imports.add(t,n)}function W(e,t,n){return U(e,G(e,t,n),[n.name])}function G(e,n,r){return r.path.startsWith(en)?r.path:tn(e.directoryPath,(0,t.join)(n,r.path,At))}function tn(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 nn(e,n,r,i){return U(e,tn(e.directoryPath,(0,t.join)(n,Mt(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){let n=[e.title,e.description];return t&&n.push(`- key: ${t}`),e.format&&n.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),ln(n,e,`default`),ln(n,e,`example`),dn(n,e),fn(n,e),pn(n,e),n}function sn(e,t,n){K(e,on(t,n))}function cn(e,t,n,r=!1){let i=on(t,n);r&&un(i,`schema`,t),K(e,i)}function ln(e,t,n){let r=t[n];if(r){if(typeof r!=`object`){e.push(`- ${n}: \`${r}\``);return}un(e,n,r)}}function un(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function dn(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 fn(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 pn(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 mn(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 hn=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],gn=new Set([`string`,`number`,`boolean`]),_n=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function vn(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=T(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=>vn(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:F(e.type)}}}function yn(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 bn(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>yn(e,n,t))}function xn(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 Sn(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 Cn=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([...hn,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=(Ie(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)&&P(e)?this.mapType(e):bn(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=P(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&&T(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(xn(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(!Sn(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=>Sn(t,e)).map(e=>J(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||gn.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?F(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-`)&&!_n.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`||_n.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=pe(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 Cn(e);return{text:t(n),imports:n.imports()}}function wn(e,t){return Y(t,t=>t.type(e))}function Tn(e,t){return Y(t,t=>t.additionalProperties(e))}function En(e,t){return Y(t,t=>t.additionalPropertyType(e))}function Dn(e,t){return Y(t,t=>t.requiredAdditionalPropertyType(e))}function On(e,t){return Y(t,t=>t.mapValueType(e))}var kn=`@ahoo-wang/fetcher`,An=[`ContentTypeValues`,`ResultExtractors`],jn=`@ahoo-wang/fetcher-decorator`,Mn=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Nn={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Pn={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Fn=`{
|
|
10
|
-
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
11
|
-
resultExtractor: JsonEventStreamResultExtractor,
|
|
12
|
-
}`,In=`COMMAND_STREAM_ENDPOINT`;function Ln(e){U(e,kn,An)}function Rn(e){U(e,jn,Mn)}function zn(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 Bn(t,n){if(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}]});return}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 Vn(e){return e===`delete`?`del`:e}var Hn=`@ahoo-wang/fetcher-eventstream`;function Un(e){U(e,Hn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function Wn(e,t){let n=t.modules.module(e.file);Ln(n),Rn(n),Un(n);let r=zn(e.className,n);K(r,[e.description]);let i;e.basePath&&(nn(n,t.outputDir,e.basePath.alias,e.basePath.constantName),i=`basePath: ${e.basePath.constantName}`),Bn(r,i);let a=Gn(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(Kn(t,a))}function Gn(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>G(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=wn(e,r);return t.imports.apply(n.imports),n.text}}}function Kn(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:qn(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=Jn(e.returns,t),o=b(e.path),s={name:e.name,decorators:[{name:Vn(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 qn(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:(U(t.module,kn,[`PartialBy`]),`PartialBy<${e}, ${r.map(b).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function Jn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Pn:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Fn};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Fn}}case`text`:return Pn;case`response`:return Nn}}var Yn=`DEFAULT_COMMAND_CLIENT_OPTIONS`;function Xn(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:Qt(r.commands.map(e=>({name:e.endpointMember,initializer:b(e.path)})))});let a=new Set,o=r.commands.map(e=>Zn(i,n.outputDir,e,a));nn(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:Yn,type:`ApiMetadata`,initializer:`{
|
|
13
|
-
basePath: ${t.context.constantName}
|
|
14
|
-
}`}],isExported:!1}),U(i,L,[`CommandRequest`,`CommandResult`,`CommandResultEventStream`,`CommandBody`,In]),U(i,`@ahoo-wang/fetcher`,[`PartialBy`]),Rn(i);let s=zn(r.className,i,[],[`R = CommandResult`]);Bn(s,`...${Yn}`);for(let[e,t]of r.commands.entries()){let n=Qn(t,o[e]),i={name:t.methodName,decorators:[{name:Vn(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])}zn(r.streamClassName,i,[`''`,In],[],`${r.className}<CommandResultEventStream>`)}function Zn(t,n,r,i){if(r.body.path===`@ahoo-wang/wow-client`)return U(t,L,[r.typeName]),r.typeName;W(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)?r.typeName:(i.add(r.typeName),t.add({kind:e.StructureKind.TypeAlias,name:r.typeName,type:s,isExported:!0}),r.typeName)}function Qn(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 $n(e){return mn(e,{ofKey:e=>z(e),ofReference:bt})}function er(t,n){let r=n.modules.module(t.file);if(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`);return}new nr(t,r,n).write()}function tr(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 nr=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=>G(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`&&!P(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(wn(e,this.scope))}processEnum(t){let n=Ee(t);if(n){let t=tr(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=tr(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:Ie(n)};(e.properties??=[]).push(r),sn(r,n)}processInterface(t){if(bn(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(Dn(t,this.scope))});return this.emit(Tn(t,this.scope))&&n.push($t(this.emit(En(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:[$t(this.emit(On(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})}},rr=`DEFAULT_QUERY_CLIENT_OPTIONS`;function ir(t,n){let r=t.queryClient,i=n.modules.module(r.file);U(i,L,[`QueryClientFactory`,`QueryClientOptions`,`ResourceAttributionPathSpec`]),nn(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:rr,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:Qt(r.events.map(e=>({name:e.memberName,initializer:b(e.title)})))});for(let e of r.events)W(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`}),W(i,n.outputDir,r.state),W(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}>(${rr})`}],isExported:!0})}function ar(e,t){e.contexts.forEach(e=>or(e,t)),e.models.forEach(e=>er(e,t)),e.aggregates.forEach(e=>ir(e,t)),e.aggregates.forEach(e=>Xn(e,t)),e.apiClients.forEach(e=>Wn(e,t))}function or(e,t){t.modules.module(e.file).add(`export const ${e.constantName} = ${b(e.alias)};`)}function sr(e,t){let n=[];return cr(e,t,n),n}function cr(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:ur(t)})}for(let i of e.getDirectories()){let e=cr(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:lr(i,r,t,n)}function lr(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 ur(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 dr(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;continue}if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1;continue}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 fr(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();return}if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!dr(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>pr(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function pr(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 mr(e){let t=e.flatMap(fr);for(let e of t)e()}var hr=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function gr(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!hr.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 _r=`// Code generated by wow-generator. DO NOT EDIT.
|
|
20
|
-
|
|
21
|
-
`,vr={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function yr(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(vr),n.organizeImports(vr)}),mr(e),gr(e);for(let t of e)t.insertText(0,_r)}var br=3e4;function xr(e){return/^https?:\/\//i.test(e)}function Sr(e,t={}){return xr(e)?Cr(e,t):Tr(e)}async function Cr(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`:wr(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 wr(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 Tr(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Er(e,t){let n;try{n=await Sr(e,t)}catch(t){throw new o(`input`,`Cannot read the OpenAPI document ${e}: ${s(t)}`,{cause:t})}let r;try{r=Or(n)}catch(t){throw new o(`input`,`Cannot parse the OpenAPI document ${e}: ${s(t)}`,{cause:t})}return Dr(r,e)}function Dr(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 Or(e){switch(kr(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function kr(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 Ar=`./fetcher-generator.config.json`;async function jr(e,t,n){if(e!==void 0)return{...await Pr({path:e,explicit:!0},t,n),origin:X(e)};for(let e of[i,Ar]){let r=await Pr({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 Mr=[`apiClients`],Nr=[`ignorePathParameters`,`methodNames`];async function Pr(e,t,n){let r=X(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await Sr(e.path,n)}catch(n){if(!e.explicit&&Fr(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=Or(i)}catch(e){throw new o(`configuration`,`Cannot parse configuration ${r}: ${s(e)}`,{cause:e})}let c=Lr(a,r);return t.debug(`Configuration loaded from ${r}: ${zr(c.config)}`),c}function X(e){return xr(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Fr(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 Ir(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 Lr(e,t){if(!Q(e))throw new o(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${Z(e)}`);let n=[];return Ir(n,t,`configuration`,e,Mr),Rr(e.apiClients,t,n),{config:e,warnings:n}}function Rr(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)}`);Ir(n,t,`apiClients["${r}"]`,i,Nr);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 zr(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}function Br(e){return{openAPI:e,components:e.components,endpoints:Be(e.paths,e.components)}}var Vr=`.wow-generator.json`,Hr=`.fetcher-generator.json`,Ur=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,Hr),l=a.fileExistsSync(c)?c:void 0,u=(0,t.join)(r,Vr);!a.fileExistsSync(u)&&l&&(u=l);let d=new Map;if(a.fileExistsSync(u)){let e=Wr(u,a.readFileSync(u));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(qr(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=V(t,e);qr(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 Kr(`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,Vr),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Gr(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)?(qr(n.realpathSync(this.outputDir),n.realpathSync(e)),Gr(n.readFileSync(e))===t):!1}};function Wr(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 Gr(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Kr(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 Kr(e,t,n)}}function qr(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 Jr(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=$e(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 ${Ye} or later.`),h=(e,t)=>{let n=it.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=et(t.operationId);if(!a)return;let s=I(t),c=new Set;for(;s&&S(s)&&s.$ref!==`#/components/responses/wow.CommandOk`;){if(!s.$ref.startsWith(de))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(de.length)]}if(!s||!S(s)||s.$ref!==`#/components/responses/wow.CommandOk`)return;let l=f(t);if(!t.requestBody)return;let u=Ge(t,n??{}),d=(S(t.requestBody)?E(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=Ue(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})},g=({operation:e})=>{if(!n||!e.operationId?.endsWith(`.event.list_query`))return;let t=f(e);if(t.length===0)return;let r=Ue(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=Yr(T(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=Yr(t,[`properties`,`name`,`const`]),o=Yr(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)})})},ne=({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)?E(e.requestBody,n):e.requestBody:void 0;if(!i)throw m(e,`it has no request body`);let a=i[rt],o;if(a!==void 0){if(!S(a))throw m(e,`${rt} must be a schema reference`);o=a}else{let t=i.content?.[k]?.schema,r=(S(t)?T(t,n):void 0)?.properties?.field;if(!S(r))throw m(e,`its request body has no ${rt}, 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),g(e),ne(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}${tt}`,t.fields?void 0:`${e}${nt}`].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:Ze(t),contexts:_,aggregateTags:s,schemaDocOverrides:a,warnings:i}}function Yr(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}var Xr=Symbol(`project`),Zr=Symbol(`signal`),Qr=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new l,this.signal=t[Zr],this.project=t[Xr]??$r(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 jr(n.configPath,e,a);i(s.warnings),t?.throwIfAborted(),e.debug(`Parsing OpenAPI specification`);let c=await Er(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=Br(c);e.debug(`Resolving bounded context aggregates`);let d=Jr(u);i(d.warnings),e.debug(`Resolved ${d.contexts.size} bounded context aggregates`);let f=Ur.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=Kt(u,d,s.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new Yt(e=>f.claim(e));ar(p.model,{modules:m,outputDir:n.outputDir,types:$n(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(sr(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),yr(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 $r(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 Zr}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return br}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Qr}});
|
|
23
|
-
//# sourceMappingURL=codeGenerator-DpDTDC4o.cjs.map
|