@ahoo-wang/fetcher-generator 2.3.6 → 2.5.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 +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +18 -17
- package/dist/cli.js.map +1 -1
- package/dist/client/apiClientGenerator.d.ts +97 -0
- package/dist/client/apiClientGenerator.d.ts.map +1 -0
- package/dist/client/clientGenerator.d.ts +4 -3
- package/dist/client/clientGenerator.d.ts.map +1 -1
- package/dist/client/commandClientGenerator.d.ts +3 -4
- package/dist/client/commandClientGenerator.d.ts.map +1 -1
- package/dist/client/decorators.d.ts +54 -0
- package/dist/client/decorators.d.ts.map +1 -0
- package/dist/client/index.d.ts +5 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/queryClientGenerator.d.ts +3 -3
- package/dist/client/queryClientGenerator.d.ts.map +1 -1
- package/dist/client/utils.d.ts +1 -0
- package/dist/client/utils.d.ts.map +1 -1
- package/dist/{baseCodeGenerator.d.ts → generateContext.d.ts} +13 -10
- package/dist/generateContext.d.ts.map +1 -0
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +864 -398
- package/dist/index.js.map +1 -1
- package/dist/model/modelGenerator.d.ts +5 -3
- package/dist/model/modelGenerator.d.ts.map +1 -1
- package/dist/model/modelInfo.d.ts +2 -0
- package/dist/model/modelInfo.d.ts.map +1 -1
- package/dist/types.d.ts +17 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/clis.d.ts.map +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/naming.d.ts.map +1 -1
- package/dist/utils/{openAPIParser.d.ts → parsers.d.ts} +3 -1
- package/dist/utils/parsers.d.ts.map +1 -0
- package/dist/utils/responses.d.ts +5 -2
- package/dist/utils/responses.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/baseCodeGenerator.d.ts.map +0 -1
- package/dist/utils/openAPIParser.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`):void 0}function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@ahoo-wang/fetcher"),S=require("ts-morph"),q=require("@ahoo-wang/fetcher-wow"),z=require("yaml"),ie=require("fs"),M=require("path");function ae(o){const e=o.split(".");return e.length!=2||e[0].length===0||e[1].length===0?null:e}function ce(o){const e=ae(o.name);return e?{tag:o,contextAlias:e[0],aggregateName:e[1]}:null}function ge(o){const e=o?.map(n=>ce(n)).filter(n=>n!==null);if(!e)return new Map;const t=new Map;return e.forEach(n=>{t.set(n.tag.name,{aggregate:n,commands:new Map,events:new Map})}),t}function le(o){if(!o)return null;const e=o.split(".");return e.length!=3?null:e[2]}function P(o){return o.$ref.split("/").pop()}function w(o,e){const t=P(o);return e.schemas?.[t]}function B(o,e){const t=P(o);return e.requestBodies?.[t]}function pe(o,e){const t=P(o);return e.parameters?.[t]}function T(o,e){return{key:P(o),schema:w(o,e)}}const j=/[-_\s.]+/;function k(o){return Array.isArray(o)?o.flatMap(e=>G(e.split(j))):G(o.split(j))}function G(o){return o.flatMap(e=>{if(e.length===0)return[];const t=[];let n="";for(let r=0;r<e.length;r++){const s=e[r],i=/[A-Z]/.test(s),a=r>0&&/[a-z]/.test(e[r-1]);i&&a&&n?(t.push(n),n=s):n+=s}return n&&t.push(n),t})}function C(o){return o===""||o.length===0?"":k(o).filter(t=>t.length>0).map(t=>{const n=t.charAt(0),r=t.slice(1);return(/[a-zA-Z]/.test(n)?n.toUpperCase():n)+r.toLowerCase()}).join("")}function y(o){const e=C(o);return e.charAt(0).toLowerCase()+e.slice(1)}function ue(o){return o===""||Array.isArray(o)&&o.length===0?"":k(o).filter(t=>t.length>0).map(t=>t.toUpperCase()).join("_")}function L(o){return o.startsWith("http://")||o.startsWith("https://")?de(o):me(o)}async function de(o){return await(await fetch(o)).text()}function me(o){return new Promise((e,t)=>{ie.readFile(o,"utf-8",(n,r)=>{n?t(n):e(r)})})}async function fe(o){const e=await L(o);switch(Q(e)){case"json":return JSON.parse(e);case"yaml":return z.parse(e);default:throw new Error(`Unsupported file format: ${o}`)}}async function he(o){const e=await L(o);switch(Q(e)){case"json":return JSON.parse(e);case"yaml":return z.parse(e);default:throw new Error(`Unsupported file format: ${o}`)}}function Q(o){const e=o.trimStart();if(e.startsWith("{")||e.startsWith("["))return"json";if(e.startsWith("-")||e.startsWith("%YAML"))return"yaml";try{return JSON.parse(e),"json"}catch{if(e.length>0)return"yaml"}throw new Error("Unable to infer file format")}function l(o){return!!(o&&typeof o=="object"&&"$ref"in o)}function N(o,e){if(e&&!l(e)&&e.content)return e.content[o]?.schema}function U(o){return N(h.ContentTypeValues.APPLICATION_JSON,o)}function ye(o){return N(h.ContentTypeValues.TEXT_EVENT_STREAM,o)}function xe(o){return N("*/*",o)}function V(o){return[{method:"get",operation:o.get},{method:"put",operation:o.put},{method:"post",operation:o.post},{method:"delete",operation:o.delete},{method:"options",operation:o.options},{method:"head",operation:o.head},{method:"patch",operation:o.patch},{method:"trace",operation:o.trace}].filter(({operation:e})=>e!==void 0)}function D(o){return o.responses[200]}function F(o){const e=D(o);return U(e)}const Ae=["string","number","integer","boolean","null"];function J(o){return Array.isArray(o)?!0:Ae.includes(o)}function v(o){return o.type==="array"}function Ce(o){return Array.isArray(o.enum)&&o.enum.length>0}function K(o){return Array.isArray(o.anyOf)&&o.anyOf.length>0}function H(o){return Array.isArray(o.oneOf)&&o.oneOf.length>0}function $e(o){return K(o)||H(o)}function Pe(o){return Array.isArray(o.allOf)&&o.allOf.length>0}function _(o){return K(o)||H(o)||Pe(o)}function W(o){return o.includes("|")||o.includes("&")?`(${o})[]`:`${o}[]`}function Te(o){return o.type!=="object"?!1:o.properties?Object.keys(o.properties).length===0:!0}function R(o){if(Array.isArray(o))return o.map(e=>R(e)).join(" | ");switch(o){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";default:return"any"}}const X="types.ts",Ie="@";function Se(o){return h.combineURLs(o.path,X)}function Y(o,e,t){const n=h.combineURLs(e,t),r=o.getSourceFile(n);return r||o.createSourceFile(n,"",{overwrite:!0})}function E(o,e,t){let n=o.getImportDeclaration(r=>r.getModuleSpecifierValue()===e);n||(n=o.addImportDeclaration({moduleSpecifier:e})),t.forEach(r=>{n.getNamedImports().some(i=>i.getName()===r)||n.addNamedImport(r)})}function f(o,e,t){if(t.path.startsWith(Ie)){E(o,t.path,[t.name]);return}const n=o.getDirectoryPath(),r=M.join(e,t.path,X);let s=M.relative(n,r);s=s.replace(/\.ts$/,""),s.startsWith(".")||(s="./"+s),E(o,s,[t.name])}function I(o,e,t,n){o.path!==n.path&&f(e,t,n)}function we(o,e){const t=[o,e].filter(n=>n!==void 0&&n.length>0);return t.length>0?t.join(`
|
|
2
|
+
`):void 0}function A(o,e,t){const n=we(e,t);n&&o.addJsDoc({description:n})}const Re="#/components/responses/wow.CommandOk",Ee="#/components/parameters/wow.id";class ve{constructor(e){this.openAPI=e,this.aggregates=ge(e.tags),this.build()}aggregates;build(){for(const[e,t]of Object.entries(this.openAPI.paths)){const n=V(t);for(const r of n)this.commands(e,r),this.state(r.operation),this.events(r.operation),this.fields(r.operation)}}resolve(){const e=new Map;for(const t of this.aggregates.values()){if(!t.state||!t.fields)continue;const n=t.aggregate.contextAlias;let r=e.get(n);r||(r=new Set,e.set(n,r)),r.add(t)}return e}commands(e,t){const n=t.operation;if(n.operationId==="wow.command.send")return;const r=le(n.operationId);if(!r)return;const s=D(n);if(!s||!l(s)||s.$ref!==Re||!n.requestBody)return;const i=n.parameters??[],a=i.filter(d=>l(d)&&d.$ref===Ee).at(0),c=i.filter(d=>!l(d)&&d.in==="path");if(a){const d=pe(a,this.openAPI.components);c.push(d)}const u=n.requestBody.content[h.ContentTypeValues.APPLICATION_JSON].schema,p=T(u,this.openAPI.components);p.schema.title=p.schema.title||n.summary,p.schema.description=p.schema.description||n.description;const se={name:r,method:t.method,path:e,pathParameters:c,summary:n.summary,description:n.description,schema:p,operation:n};n.tags?.forEach(d=>{const b=this.aggregates.get(d);b&&b.commands.set(r,se)})}state(e){if(!e.operationId?.endsWith(".snapshot_state.single"))return;const t=F(e);if(!l(t))return;const n=T(t,this.openAPI.components);e.tags?.forEach(r=>{const s=this.aggregates.get(r);s&&(s.state=n)})}events(e){if(!this.openAPI.components||!e.operationId?.endsWith(".event.list_query"))return;const t=F(e);if(l(t))return;const n=t?.items;if(!l(n))return;const s=w(n,this.openAPI.components).properties.body.items.anyOf.map(i=>{const a=i.title,c=i.properties.name.const,g=i.properties.body,u=T(g,this.openAPI.components);return u.schema.title=u.schema.title||i.title,{title:a,name:c,schema:u}});e.tags?.forEach(i=>{const a=this.aggregates.get(i);a&&s.forEach(c=>{a.events.set(c.name,c)})})}fields(e){if(!this.openAPI.components||!e.operationId?.endsWith(".snapshot.count"))return;const n=B(e.requestBody,this.openAPI.components).content[h.ContentTypeValues.APPLICATION_JSON].schema,s=w(n,this.openAPI.components).properties?.field,i=T(s,this.openAPI.components);e.tags?.forEach(a=>{const c=this.aggregates.get(a);c&&(c.fields=i)})}}const $="@ahoo-wang/fetcher-wow",Oe={"wow.command.CommandResult":"CommandResult","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.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.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 m(o){if(!o)return{name:"",path:"/"};const e=Oe[o];if(e)return{name:e,path:$};const t=o.split(".");let n=-1;for(let c=0;c<t.length;c++)if(t[c]&&/^[A-Z]/.test(t[c])){n=c;break}if(n===-1)return{name:o,path:"/"};const r=t.slice(0,n),s=r.length>0?`/${r.join("/")}`:"/",i=t.slice(n);return{name:C(i),path:s}}function x(o){const e=P(o);return m(e)}class Ne{constructor(e){this.context=e}getOrCreateSourceFile(e){const t=Se(e);return this.context.getOrCreateSourceFile(t)}generate(){const e=this.context.openAPI.components?.schemas;if(!e){this.context.logger.info("No schemas found in OpenAPI specification");return}const t=this.stateAggregatedTypeNames(),n=this.filterSchemas(e,t);this.context.logger.progress(`Generating models for ${n.length} schemas`),n.forEach((r,s)=>{this.context.logger.progressWithCount(s+1,n.length,`Processing schema: ${r.key}`,2),this.generateKeyedSchema(r)}),this.context.logger.success("Model generation completed")}filterSchemas(e,t){return Object.entries(e).map(([n,r])=>({key:n,schema:r})).filter(n=>!this.isWowSchema(n.key,t))}isWowSchema(e,t){if(e.startsWith("wow.")||e.endsWith("AggregatedCondition")||e.endsWith("AggregatedDomainEventStream")||e.endsWith("AggregatedDomainEventStreamPagedList")||e.endsWith("AggregatedDomainEventStreamServerSentEventNonNullData")||e.endsWith("AggregatedListQuery")||e.endsWith("AggregatedPagedQuery")||e.endsWith("AggregatedSingleQuery"))return!0;const n=m(e);return t.has(n.name)}aggregatedSchemaSuffix=["MaterializedSnapshot","MaterializedSnapshotPagedList","MaterializedSnapshotServerSentEventNonNullData","PagedList","ServerSentEventNonNullData","Snapshot","StateEvent"];stateAggregatedTypeNames(){const e=new Set;for(const t of this.context.contextAggregates.values())for(const n of t)this.aggregatedSchemaSuffix.forEach(r=>{const s=m(n.state.key),i=C(s.name)+r;e.add(i)});return e}generateKeyedSchema({key:e,schema:t}){const n=m(e),r=this.getOrCreateSourceFile(n),s=this.process(n,r,t);s&&A(s,t.title,t.description)}process(e,t,n){if(Ce(n))return t.addEnum({name:e.name,isExported:!0,members:n.enum.filter(s=>typeof s=="string"&&s.length>0).map(s=>({name:ue(s),initializer:`'${s}'`}))});if(v(n)&&l(n.items)){const s=x(n.items);return I(e,t,this.context.outputDir,s),t.addTypeAlias({name:e.name,type:W(s.name),isExported:!0})}const r=t.addInterface({name:e.name,isExported:!0});return n.type==="object"&&n.properties?this.processInterface(t,e,n,r):(_(n)&&(n.anyOf||n.oneOf||n.allOf).forEach(i=>{if(l(i)){const a=x(i);I(e,t,this.context.outputDir,a),r.addExtends(a.name);return}this.processInterface(t,e,i,r)}),r)}processObject(e,t,n){const r=e.addInterface({name:t.name,isExported:!0});return this.processInterface(e,t,n,r)}processInterface(e,t,n,r){for(const[s,i]of Object.entries(n.properties)){const a=this.resolvePropertyType(t,e,s,i);let c=r.getProperty(s);c?c.setType(a):c=r.addProperty({name:s,type:a}),l(i)||A(c,i.title,i.description)}return r}resolvePropertyType(e,t,n,r){if(l(r)){const s=x(r);return I(e,t,this.context.outputDir,s),s.name}if(r.const)return`'${r.const}'`;if(v(r)){const s=this.resolvePropertyType(e,t,n,r.items);return W(s)}if(r.type&&J(r.type))return R(r.type);if(_(r))return this.resolvePropertyCompositionType(e,t,r);if(r.type==="object"&&r.properties){const s={path:e.path,name:`${e.name}${C(n)}`},i=this.processObject(t,s,r);return A(i,r.title,r.description),s.name}return"any"}resolvePropertyCompositionType(e,t,n){const r=n.anyOf||n.oneOf||n.allOf,s=new Set;r.forEach(a=>{if(l(a)){const c=x(a);I(e,t,this.context.outputDir,c),s.add(c.name);return}s.add(R(a.type??"string"))});const i=$e(n)?"|":"&";return Array.from(s).join(i)}}function De(o){let e=0,t=0;return o.commands.forEach(n=>{n.path.startsWith(q.ResourceAttributionPathSpec.TENANT)&&(e+=1),n.path.startsWith(q.ResourceAttributionPathSpec.OWNER)&&(t+=1)}),e===0&&t===0?"ResourceAttributionPathSpec.NONE":e>t?"ResourceAttributionPathSpec.TENANT":"ResourceAttributionPathSpec.OWNER"}function Z(o,e,t,n){const r=`${t.contextAlias}/${t.aggregateName}/${n}.ts`;return Y(o,e,r)}function be(o,e){return`${C(o.aggregateName)}${e}`}function O(o){return o==="delete"?"del":o}class qe{constructor(e){this.context=e}generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((n,r)=>n+r.size,0);this.context.logger.info("--- Generating Query Clients ---"),this.context.logger.progress(`Generating query clients for ${e} aggregates`);let t=0;for(const[,n]of this.context.contextAggregates)n.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing query client for aggregate: ${r.aggregate.aggregateName}`),this.processQueryClient(r)});this.context.logger.success("Query client generation completed")}createClientFilePath(e,t){return Z(this.context.project,this.context.outputDir,e,t)}processQueryClient(e){const t=this.createClientFilePath(e.aggregate,"queryClient");this.context.logger.info(`Processing query client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`),this.context.logger.info(`Adding imports from ${$}: QueryClientFactory, QueryClientOptions, ResourceAttributionPathSpec`),t.addImportDeclaration({moduleSpecifier:$,namedImports:["QueryClientFactory","QueryClientOptions","ResourceAttributionPathSpec"]});const n="DEFAULT_QUERY_CLIENT_OPTIONS";this.context.logger.info(`Creating default query client options: ${n}`),t.addVariableStatement({declarationKind:S.VariableDeclarationKind.Const,declarations:[{name:n,type:"QueryClientOptions",initializer:`{
|
|
3
3
|
contextAlias: '${e.aggregate.contextAlias}',
|
|
4
4
|
aggregateName: '${e.aggregate.aggregateName}',
|
|
5
|
-
resourceAttribution: ${
|
|
6
|
-
}`}],isExported:!1});const r=[];this.logger.info(`Processing ${e.events.size} domain events for aggregate: ${e.aggregate.aggregateName}`);for(const u of e.events.values()){const
|
|
7
|
-
basePath: '${e.aggregate.contextAlias}'
|
|
8
|
-
}`}],isExported:!1}),this.logger.info(`Adding imports from ${A}: CommandRequest, CommandResult, CommandResultEventStream, DeleteAggregate, RecoverAggregate`),t.addImportDeclaration({moduleSpecifier:A,namedImports:["CommandRequest","CommandResult","CommandResultEventStream","DeleteAggregate","RecoverAggregate"],isTypeOnly:!0}),this.logger.info("Adding import from @ahoo-wang/fetcher-eventstream: JsonEventStreamResultExtractor"),t.addImportDeclaration({moduleSpecifier:"@ahoo-wang/fetcher-eventstream",namedImports:["JsonEventStreamResultExtractor"]}),this.logger.info("Adding import from @ahoo-wang/fetcher: ContentTypeValues"),x(t,"@ahoo-wang/fetcher",["ContentTypeValues"]),this.logger.info("Adding imports from @ahoo-wang/fetcher-decorator: ApiMetadata types and decorators"),x(t,"@ahoo-wang/fetcher-decorator",["type ApiMetadata","type ApiMetadataCapable","api","post","put","patch","del","request","attribute","path","autoGeneratedError"]),this.logger.info("Generating standard command client class"),this.processCommandClient(t,e),this.logger.info("Generating stream command client class"),this.processCommandClient(t,e,!0),this.logger.success(`Command client generation completed for aggregate: ${e.aggregate.aggregateName}`)}processCommandEndpointPaths(e,t){this.logger.info(`Creating command endpoint paths enum: ${this.commandEndpointPathsName}`);const n=e.addEnum({name:this.commandEndpointPathsName});t.commands.forEach(r=>{this.logger.info(`Adding command endpoint: ${r.name.toUpperCase()} = '${r.path}'`),n.addMember({name:r.name.toUpperCase(),initializer:`'${r.path}'`})}),this.logger.success(`Command endpoint paths enum created with ${t.commands.size} entries`)}getEndpointPath(e){return`${this.commandEndpointPathsName}.${e.name.toUpperCase()}`}processCommandClient(e,t,n=!1){let r="CommandClient",s={name:"api",arguments:[]},i="Promise<CommandResult>";n&&(r="Stream"+r,s={name:"api",arguments:["''",`{
|
|
5
|
+
resourceAttribution: ${De(e)},
|
|
6
|
+
}`}],isExported:!1});const r=[];this.context.logger.info(`Processing ${e.events.size} domain events for aggregate: ${e.aggregate.aggregateName}`);for(const u of e.events.values()){const p=m(u.schema.key);this.context.logger.info(`Adding import for event model: ${p.name} from path: ${p.path}`),f(t,this.context.outputDir,p),r.push(p)}const s="DOMAIN_EVENT_TYPES",i=r.map(u=>u.name).join(" | ");this.context.logger.info(`Creating domain event types union: ${s} = ${i}`),t.addTypeAlias({name:s,type:i});const a=`${y(e.aggregate.aggregateName)}QueryClientFactory`,c=m(e.state.key),g=m(e.fields.key);this.context.logger.info(`Adding import for state model: ${c.name} from path: ${c.path}`),f(t,this.context.outputDir,c),this.context.logger.info(`Adding import for fields model: ${g.name} from path: ${g.path}`),f(t,this.context.outputDir,g),this.context.logger.info(`Creating query client factory: ${a}`),t.addVariableStatement({declarationKind:S.VariableDeclarationKind.Const,declarations:[{name:a,initializer:`new QueryClientFactory<${c.name}, ${g.name} | string, ${s}>(${n})`}],isExported:!0}),this.context.logger.success(`Query client generation completed for aggregate: ${e.aggregate.aggregateName}`)}}const Me="@ahoo-wang/fetcher-decorator",je=["type ApiMetadata","type ApiMetadataCapable","api","post","put","patch","del","request","attribute","path","autoGeneratedError"],ee=`{
|
|
9
7
|
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
10
8
|
resultExtractor: JsonEventStreamResultExtractor,
|
|
11
|
-
}
|
|
9
|
+
}`;function te(o){E(o,Me,je)}function ne(o,e,t=[]){return e.addClass({name:o,isExported:!0,decorators:[{name:"api",arguments:t}]})}function oe(o,e){o.addImplements("ApiMetadataCapable"),o.addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",hasQuestionToken:e===void 0,scope:S.Scope.Public,isReadonly:!0,initializer:e}]})}class Ge{constructor(e){this.context=e}commandEndpointPathsName="COMMAND_ENDPOINT_PATHS";defaultCommandClientOptionsName="DEFAULT_COMMAND_CLIENT_OPTIONS";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((n,r)=>n+r.size,0);this.context.logger.info("--- Generating Command Clients ---"),this.context.logger.progress(`Generating command clients for ${e} aggregates`);let t=0;for(const[,n]of this.context.contextAggregates)n.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing command client for aggregate: ${r.aggregate.aggregateName}`),this.processAggregate(r)});this.context.logger.success("Command client generation completed")}processAggregate(e){this.context.logger.info(`Processing command client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`);const t=Z(this.context.project,this.context.outputDir,e.aggregate,"commandClient");this.context.logger.info(`Processing command endpoint paths for ${e.commands.size} commands`),this.processCommandEndpointPaths(t,e),this.context.logger.info(`Creating default command client options: ${this.defaultCommandClientOptionsName}`),t.addVariableStatement({declarationKind:S.VariableDeclarationKind.Const,declarations:[{name:this.defaultCommandClientOptionsName,type:"ApiMetadata",initializer:`{
|
|
10
|
+
basePath: '${e.aggregate.contextAlias}'
|
|
11
|
+
}`}],isExported:!1}),this.context.logger.info(`Adding imports from ${$}: CommandRequest, CommandResult, CommandResultEventStream, DeleteAggregate, RecoverAggregate`),t.addImportDeclaration({moduleSpecifier:$,namedImports:["CommandRequest","CommandResult","CommandResultEventStream","DeleteAggregate","RecoverAggregate"],isTypeOnly:!0}),this.context.logger.info("Adding import from @ahoo-wang/fetcher-eventstream: JsonEventStreamResultExtractor"),t.addImportDeclaration({moduleSpecifier:"@ahoo-wang/fetcher-eventstream",namedImports:["JsonEventStreamResultExtractor"]}),this.context.logger.info("Adding import from @ahoo-wang/fetcher: ContentTypeValues"),E(t,"@ahoo-wang/fetcher",["ContentTypeValues"]),this.context.logger.info("Adding imports from @ahoo-wang/fetcher-decorator: ApiMetadata types and decorators"),te(t),this.context.logger.info("Generating standard command client class"),this.processCommandClient(t,e),this.context.logger.info("Generating stream command client class"),this.processCommandClient(t,e,!0),this.context.logger.success(`Command client generation completed for aggregate: ${e.aggregate.aggregateName}`)}processCommandEndpointPaths(e,t){this.context.logger.info(`Creating command endpoint paths enum: ${this.commandEndpointPathsName}`);const n=e.addEnum({name:this.commandEndpointPathsName});t.commands.forEach(r=>{this.context.logger.info(`Adding command endpoint: ${r.name.toUpperCase()} = '${r.path}'`),n.addMember({name:r.name.toUpperCase(),initializer:`'${r.path}'`})}),this.context.logger.success(`Command endpoint paths enum created with ${t.commands.size} entries`)}getEndpointPath(e){return`${this.commandEndpointPathsName}.${e.name.toUpperCase()}`}processCommandClient(e,t,n=!1){let r="CommandClient",s=[],i="Promise<CommandResult>";n&&(r="Stream"+r,s=["''",ee],i="Promise<CommandResultEventStream>");const a=be(t.aggregate,r),c=ne(a,e,s);oe(c,this.defaultCommandClientOptionsName),t.commands.forEach(g=>{this.processCommandMethod(e,c,g,i)})}processCommandMethod(e,t,n,r){const s=m(n.schema.key);this.context.logger.info(`Adding import for command model: ${s.name} from path: ${s.path}`),f(e,this.context.outputDir,s),this.context.logger.info(`Generating command method: ${y(n.name)} for command: ${n.name}`),this.context.logger.info(`Command method details: HTTP ${n.method}, path: ${n.path}, return type: ${r}`);const i=n.pathParameters.map(c=>(this.context.logger.info(`Adding path parameter: ${c.name} (type: string)`),{name:c.name,type:"string",hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${c.name}'`]}]}));this.context.logger.info(`Adding command request parameter: commandRequest (type: CommandRequest<${s.name}>)`),i.push({name:"commandRequest",hasQuestionToken:Te(n.schema.schema),type:`CommandRequest<${s.name}>`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: attributes (type: Record<string, any>)"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]});const a=t.addMethod({name:y(n.name),decorators:[{name:O(n.method),arguments:[`${this.getEndpointPath(n)}`]}],parameters:i,returnType:r,statements:[`throw autoGeneratedError(${i.map(c=>c.name).join(",")});`]});(n.summary||n.description)&&this.context.logger.info(`Adding JSDoc documentation for method: ${y(n.name)}`),A(a,n.summary,n.description),this.context.logger.success(`Command method generated: ${y(n.name)}`)}}class Fe{constructor(e){this.context=e,this.apiMetadataCtorInitializer=this.context.currentContextAlias?`{basePath:'${this.context.currentContextAlias}'}`:void 0}defaultParameterRequestType="ParameterRequest";defaultReturnType={type:"Promise<any>"};apiMetadataCtorInitializer;generate(){this.context.logger.info("Starting API client generation");const e=this.resolveApiTags();this.context.logger.info(`Resolved ${e.size} API client tags: ${Array.from(e.keys()).join(", ")}`);const t=this.groupOperations(e);this.context.logger.info(`Grouped operations into ${t.size} tag groups`),this.generateApiClients(e,t),this.context.logger.success("API client generation completed")}generateApiClients(e,t){this.context.logger.info(`Generating ${t.size} API client classes`);let n=0;for(const[r,s]of t){n++,this.context.logger.progressWithCount(n,t.size,`Generating API client for tag: ${r}`);const i=e.get(r);this.generateApiClient(i,s)}}createApiClientFile(e){let t=e.path;return this.context.currentContextAlias&&(t=h.combineURLs(this.context.currentContextAlias,t)),t=h.combineURLs(t,`${e.name}ApiClient.ts`),this.context.logger.info(`Creating API client file: ${t}`),this.context.getOrCreateSourceFile(t)}generateApiClient(e,t){const n=m(e.name);this.context.logger.info(`Generating API client class: ${n.name}ApiClient with ${t.size} operations`);const r=this.createApiClientFile(n);te(r);const s=ne(n.name+"ApiClient",r);A(s,e.description),oe(s,this.apiMetadataCtorInitializer),this.context.logger.info(`Processing ${t.size} operations for ${n.name}ApiClient`),t.forEach(i=>{this.processOperation(e,r,s,i)}),this.context.logger.success(`Completed API client: ${n.name}ApiClient`)}getMethodName(e,t){const n=t.operationId.split(".");for(let r=n.length-1;r>=0;r--){const s=y(n.slice(r));if(!e.getMethod(s))return s}return y(n)}resolveRequestType(e,t){if(!t.requestBody)return this.context.logger.info(`No request body found for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;let n;if(l(t.requestBody)?(this.context.logger.info(`Extracting request body from reference for operation: ${t.operationId}`),n=B(t.requestBody,this.context.openAPI.components)):n=t.requestBody,!n)return this.context.logger.info(`Request body extraction failed for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;if(n.content["multipart/form-data"])return this.context.logger.info(`Detected multipart/form-data content for operation ${t.operationId}, using ParameterRequest<FormData>`),"ParameterRequest<FormData>";if(n.content["application/json"]){const r=n.content["application/json"].schema;if(l(r)){const s=x(r);this.context.logger.info(`Adding import for request body model: ${s.name} from ${s.path}`),f(e,this.context.outputDir,s);const i=`ParameterRequest<${s.name}>`;return this.context.logger.info(`Resolved request type for operation ${t.operationId}: ${i}`),i}}return this.context.logger.info(`Using default request type for operation ${t.operationId}: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType}resolveParameters(e,t,n){if(!n.parameters)return this.context.logger.info(`No parameters found for operation ${n.operationId}`),[];const r=n.parameters?.filter(a=>!l(a)&&a.in==="path"&&!this.context.isIgnoreApiClientPathParameters(e.name,a.name))??[];this.context.logger.info(`Found ${r.length} path parameters for operation ${n.operationId}`);const s=r.map(a=>(this.context.logger.info(`Adding path parameter: ${a.name} (type: string)`),{name:a.name,type:"string",hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${a.name}'`]}]})),i=this.resolveRequestType(t,n);return this.context.logger.info(`Adding httpRequest parameter: ${i}`),s.push({name:"httpRequest",hasQuestionToken:i===this.defaultParameterRequestType,type:`${i}`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: Record<string, any>"),s.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),s}resolveSchemaReturnType(e,t){if(l(t)){const n=x(t);this.context.logger.info(`Adding import for response model: ${n.name} from ${n.path}`),f(e,this.context.outputDir,n);const r=`Promise<${n.name}>`;return this.context.logger.info(`Resolved reference return type: ${r}`),r}if(!t.type)return this.context.logger.info(`Schema has no type, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType.type;if(J(t.type)){const r=`Promise<${R(t.type)}>`;return this.context.logger.info(`Resolved primitive return type: ${r}`),r}return this.context.logger.info(`Using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType.type}resolveReturnType(e,t){const n=D(t);if(!n)return this.context.logger.info(`No OK response found for operation ${t.operationId}, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType;const r=U(n);if(r){const a=this.resolveSchemaReturnType(e,r);return this.context.logger.info(`Resolved JSON response return type for operation ${t.operationId}: ${a}`),{stream:!1,type:a}}const s=ye(n);if(s){if(l(s)){const c=w(s,this.context.openAPI.components);if(v(c)&&l(c.items)){const g=x(c.items);this.context.logger.info(`Adding import for event stream model: ${g.name} from ${g.path}`),f(e,this.context.outputDir,g);const p=`Promise<JsonServerSentEventStream<${g.name.includes("ServerSentEvent")?`${g.name}['data']`:g.name}>>`;return this.context.logger.info(`Resolved event stream return type for operation ${t.operationId}: ${p}`),{stream:!0,type:p}}}const a="Promise<JsonServerSentEventStream<any>>";return this.context.logger.info(`Resolved generic event stream return type for operation ${t.operationId}: ${a}`),{stream:!0,type:a}}const i=xe(n);if(i){const a=this.resolveSchemaReturnType(e,i);return this.context.logger.info(`Resolved wildcard response return type for operation ${t.operationId}: ${a}`),{type:a}}return this.context.logger.info(`Using default return type for operation ${t.operationId}: ${this.defaultReturnType.type}`),this.defaultReturnType}processOperation(e,t,n,r){this.context.logger.info(`Processing operation: ${r.operation.operationId} (${r.method} ${r.path})`);const s=this.getMethodName(n,r.operation);this.context.logger.info(`Generated method name: ${s}`);const i=this.resolveParameters(e,t,r.operation),a=this.resolveReturnType(t,r.operation),c=a.stream?{name:O(r.method),arguments:[`'${r.path}'`,ee]}:{name:O(r.method),arguments:[`'${r.path}'`]};this.context.logger.info(`Creating method with ${i.length} parameters, return type: ${a.type}, stream: ${a.stream||!1}`);const g=n.addMethod({name:s,decorators:[c],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(u=>u.name).join(",")});`]});A(g,r.operation.summary,r.operation.description),this.context.logger.success(`Operation method generated: ${s}`)}groupOperations(e){this.context.logger.info("Grouping operations by API client tags");const t=new Map;let n=0;for(const[r,s]of Object.entries(this.context.openAPI.paths)){const i=V(s).filter(a=>{if(!a.operation.operationId)return!1;const c=a.operation.tags;return!c||c.length==0?!1:c.every(g=>e.has(g))});this.context.logger.info(`Path ${r}: found ${i.length} valid operations`);for(const a of i)a.operation.tags.forEach(c=>{const g={...a,path:r};t.has(c)||t.set(c,new Set),t.get(c).add(g),n++})}return this.context.logger.info(`Grouped ${n} operations into ${t.size} tag groups`),t}resolveApiTags(){this.context.logger.info("Resolving API client tags from OpenAPI specification");const e=new Map,t=this.context.openAPI.tags?.length||0;let n=0;return this.context.openAPI.tags?.forEach(r=>{r.name!="wow"&&r.name!="Actuator"&&!this.isAggregateTag(r)?(e.set(r.name,r),n++,this.context.logger.info(`Included API client tag: ${r.name}`)):this.context.logger.info(`Excluded tag: ${r.name} (wow/Actuator/aggregate)`)}),this.context.logger.info(`Resolved ${n} API client tags from ${t} total tags`),e}isAggregateTag(e){for(const t of this.context.contextAggregates.values())for(const n of t)if(n.aggregate.tag.name===e.name)return!0;return!1}}class _e{constructor(e){this.context=e,this.queryClientGenerator=new qe(e),this.commandClientGenerator=new Ge(e),this.apiClientGenerator=new Fe(e)}queryClientGenerator;commandClientGenerator;apiClientGenerator;generate(){this.context.logger.info("--- Generating Clients ---"),this.context.logger.progress(`Generating clients for ${this.context.contextAggregates.size} bounded contexts`);let e=0;for(const[t]of this.context.contextAggregates)e++,this.context.logger.progressWithCount(e,this.context.contextAggregates.size,`Processing bounded context: ${t}`,1),this.processBoundedContext(t);this.queryClientGenerator.generate(),this.commandClientGenerator.generate(),this.apiClientGenerator.generate(),this.context.logger.success("Client generation completed")}processBoundedContext(e){const t=`${e}/boundedContext.ts`;this.context.logger.info(`Creating bounded context file: ${t}`);const n=this.context.getOrCreateSourceFile(t);this.context.logger.info(`Adding bounded context alias constant: BOUNDED_CONTEXT_ALIAS = '${e}'`),n.addStatements(`export const BOUNDED_CONTEXT_ALIAS = '${e}';`),this.context.logger.success(`Bounded context file created successfully: ${t}`)}}class We{project;openAPI;outputDir;contextAggregates;logger;config;defaultIgnorePathParameters=["tenantId","ownerId"];currentContextAlias;constructor(e){this.project=e.project,this.openAPI=e.openAPI,this.outputDir=e.outputDir,this.contextAggregates=e.contextAggregates,this.logger=e.logger,this.config=e.config??{},this.currentContextAlias=this.openAPI.info["x-wow-context-alias"]}getOrCreateSourceFile(e){return Y(this.project,this.outputDir,e)}isIgnoreApiClientPathParameters(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters??this.defaultIgnorePathParameters).includes(t)}}const re="./fetcher-generator.config.json";class ze{constructor(e){this.options=e,this.project=e.project,this.options.logger.info("CodeGenerator instance created")}project;async generate(){this.options.logger.info("Starting code generation from OpenAPI specification"),this.options.logger.info(`Input path: ${this.options.inputPath}`),this.options.logger.info(`Output directory: ${this.options.outputDir}`),this.options.logger.info("Parsing OpenAPI specification");const e=await fe(this.options.inputPath);this.options.logger.info("OpenAPI specification parsed successfully"),this.options.logger.info("Resolving bounded context aggregates");const n=new ve(e).resolve();this.options.logger.info(`Resolved ${n.size} bounded context aggregates`);const r=this.options.configPath??re;let s={};try{this.options.logger.info("Parsing configuration file:",r),s=await he(r)}catch(g){this.options.logger.info("Configuration file parsing failed ",g)}const i=new We({openAPI:e,project:this.project,outputDir:this.options.outputDir,contextAggregates:n,logger:this.options.logger,config:s});this.options.logger.info("Generating models"),new Ne(i).generate(),this.options.logger.info("Models generated successfully"),this.options.logger.info("Generating clients"),new _e(i).generate(),this.options.logger.info("Clients generated successfully"),this.options.logger.info("Generating index files"),this.generateIndex(),this.options.logger.info("Index files generated successfully"),this.options.logger.info("Optimizing source files"),this.optimizeSourceFiles(),this.options.logger.info("Source files optimized successfully"),this.options.logger.info("Saving project to disk"),await this.project.save(),this.options.logger.info("Code generation completed successfully")}generateIndex(){this.options.logger.info(`Generating index files for output directory: ${this.options.outputDir}`);const e=this.project.getDirectory(this.options.outputDir);if(!e){this.options.logger.info("Output directory not found, skipping index generation");return}this.processDirectory(e),this.generateIndexForDirectory(e),this.options.logger.info("Index file generation completed")}processDirectory(e){const t=e.getDirectories();this.options.logger.info(`Processing ${t.length} subdirectories`);for(const n of t)this.options.logger.info(`Processing subdirectory: ${n.getPath()}`),this.generateIndexForDirectory(n),this.processDirectory(n)}generateIndexForDirectory(e){const t=e.getPath();this.options.logger.info(`Generating index for directory: ${t}`);const n=e.getSourceFiles().filter(a=>a.getBaseName().endsWith(".ts")&&a.getBaseName()!=="index.ts"),r=e.getDirectories();if(this.options.logger.info(`Found ${n.length} TypeScript files and ${r.length} subdirectories in ${t}`),n.length===0&&r.length===0){this.options.logger.info(`No files or subdirectories to export in ${t}, skipping index generation`);return}const s=`${t}/index.ts`;this.options.logger.info(`Creating/updating index file: ${s}`);const i=this.project.getSourceFile(s)||this.project.createSourceFile(s,"",{overwrite:!0});i.removeText();for(const a of n){const c=`./${a.getBaseNameWithoutExtension()}`;this.options.logger.info(`Adding export for file: ${c}`),i.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}for(const a of r){const c=`./${a.getBaseName()}`;this.options.logger.info(`Adding export for subdirectory: ${c}`),i.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}this.options.logger.info(`Index file generated for ${t} with ${n.length+r.length} exports`)}optimizeSourceFiles(){const e=this.project.getSourceFiles();this.options.logger.info(`Optimizing ${e.length} source files`),e.forEach((t,n)=>{this.options.logger.info(`Optimizing file ${n+1}/${e.length}`),t.formatText(),t.organizeImports(),t.fixMissingImports()}),this.options.logger.info("All source files optimized")}}exports.CodeGenerator=ze;exports.DEFAULT_CONFIG_PATH=re;
|
|
12
12
|
//# sourceMappingURL=index.cjs.map
|