@bitstack/ng-query-codegen-openapi 0.0.31-alpha.4 → 0.0.31-alpha.5
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/lib/bin/cli.mjs +26 -26
- package/lib/bin/cli.mjs.map +1 -1
- package/lib/index.js +18 -18
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +18 -18
- package/lib/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/generators/common-types-generator.ts +1 -1
- package/src/generators/rtk-enhance-endpoints-generator.ts +4 -4
- package/src/generators/rtk-query-generator.ts +14 -13
package/lib/bin/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var I=Object.defineProperty;var
|
|
2
|
+
var I=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Q=(n,t)=>()=>(n&&(t=n(n=0)),t);var Re=(n,t)=>{for(var e in t)I(n,e,{get:t[e],enumerable:!0})},Se=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ae(t))!Ee.call(n,o)&&o!==e&&I(n,o,{get:()=>t[o],enumerable:!(r=Ne(t,o))||r.enumerable});return n};var qe=n=>Se(I({},"__esModule",{value:!0}),n);import{fileURLToPath as Fe}from"node:url";var we,l,c=Q(()=>{"use strict";we=()=>Fe(import.meta.url),l=we()});var ie={};Re(ie,{argumentMatches:()=>He,defaultIsDataResponse:()=>ze,getOperationName:()=>E,getOverrides:()=>K,getTags:()=>Le,operationMatches:()=>oe});import{getOperationName as Be}from"oazapfts/generate";function ze(n,t){if(t&&n==="default")return!0;let e=Number(n);return!Number.isNaN(e)&&e>=200&&e<300}function E({verb:n,path:t}){return Be(n,t,void 0)}function Le({verb:n,pathItem:t}){return n?t[n]?.tags||[]:[]}function ne(n){let t=Array.isArray(n)?n:[n];return function(r){return n?t.some(o=>typeof o=="string"?o===r:o?.test(r)):!0}}function oe(n){let t=typeof n=="function"?n:ne(n);return function(r){if(!n)return!0;let o=E(r);return t(o,r)}}function He(n){let t=typeof n=="function"?n:ne(n);return function(r){if(!n||r.in==="path")return!0;let o=r.name;return t(o,r)}}function K(n,t){return t?.find(e=>oe(e.pattern)(n))}var M=Q(()=>{"use strict";c()});c();import j from"commander";import{createRequire as ot}from"node:module";c();import je from"commander";import{createRequire as Ie}from"node:module";import{resolve as k}from"node:path";import{existsSync as G,rmSync as Ge,readdirSync as De,statSync as Ke,mkdirSync as Me}from"node:fs";import V from"node:path";var O=Ie(l);function Qe(n){let t=new Map;if(!G(n))return t;function e(r){try{let o=De(r);for(let s of o){let a=V.join(r,s);if(Ke(a).isDirectory())e(a);else if(s==="enhanceEndpoints.ts"){let u=O("node:fs").readFileSync(a);t.set(a,u)}}}catch{}}return e(n),t}function ke(n){for(let[t,e]of n)try{let r=V.dirname(t);G(r)||Me(r,{recursive:!0}),O("node:fs").writeFileSync(t,e)}catch(r){console.warn(`Failed to restore ${t}:`,r)}}function U(n){let t=["/","/usr","/etc","/var","/home","/Users",".",".."],e=k(n);if(t.some(r=>e===k(r))&&(console.error(`Dangerous path detected: ${e}. Refusing to delete.`),process.exit(1)),G(n)){console.log(`Cleaning output directory: ${n}`);let r=Qe(n);Ge(n,{recursive:!0,force:!0}),r.size>0&&(ke(r),console.log(`Protected ${r.size} enhanceEndpoints.ts file(s) from deletion`)),console.log(`Directory cleaned: ${n}`)}}function W(){try{if(O.resolve("esbuild")&&O.resolve("esbuild-runner"))return O("esbuild-runner/register"),!0}catch{}try{if(O.resolve("typescript")&&O.resolve("ts-node"))return O("ts-node").register({transpileOnly:!0,compilerOptions:{target:"es6",module:"commonjs"}}),!0}catch{}return!1}function _(n){(!n||!/\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(n))&&(console.error("Please provide a valid configuration file."),je.help())}function B(n,t){/\.[mc]?tsx?$/.test(n)&&!t&&(console.error("Encountered a TypeScript config file, but neither esbuild-runner nor ts-node are installed."),process.exit(1))}import{dirname as it,resolve as st}from"node:path";c();c();import F from"node:path";import he from"typescript";c();c();function P(n){return n.replace(n[0],n[0].toUpperCase())}c();import D from"node:fs";import Ve from"node:path";c();function z(n){try{new URL(n)}catch{return!1}return!0}async function L(n,t){if(!z(n))throw new Error(`remoteFile must be a valid URL: ${n}`);try{let e=Ve.dirname(t);D.existsSync(e)||await D.promises.mkdir(e,{recursive:!0});let r=await fetch(n);if(!r.ok)throw new Error(`Failed to download schema from ${n}: ${r.statusText}`);let o=await r.text();return await D.promises.writeFile(t,o,"utf-8"),console.log(`Schema downloaded from ${n} to ${t}`),t}catch(e){throw console.error(`Error downloading schema from ${n}:`,e),e}}c();c();var H=["get","put","post","delete","options","head","patch","trace"];function Z(n){return Object.entries(n.paths).flatMap(([t,e])=>e?Object.entries(e).filter(r=>H.includes(r[0])).map(([r,o])=>({path:t,verb:r,pathItem:e,operation:o})):[])}c();import Ue from"@apidevtools/swagger-parser";import We from"swagger2openapi";async function Y(n,t){let e=await Ue.bundle(n,{resolve:{http:t}});return"openapi"in e&&e.openapi.startsWith("3")?e:(await We.convertObj(e,{})).openapi}c();function J(n,t,e,r){return r?r(n,t):e?.type?e.type==="query":n==="get"}var $=class{docCache={};async getDocument(t,e){if(this.docCache[t])return this.docCache[t];let r=await Y(t,e);return this.docCache[t]=r,r}async downloadSchema(t,e){return L(t,e)}getPaths(t){return Object.keys(t.paths||{})}clearCache(){this.docCache={}}};c();import X from"lodash.camelcase";var N=class{groupPaths(t,e){let{groupKeyMatch:r,outputDir:o}=e,s=t.reduce((p,u)=>{let i=r(u),m=i?X(i):"_common";return p[m]||(p[m]=[]),p[m].push(u),p},{}),a={};for(let[p,u]of Object.entries(s))a[p]={groupKey:p,paths:u,outputPath:`${o}/${p}/query.service.ts`};return a}createGroupFilter(t,e){return(r,o)=>{let s=o.path,a=X(e.groupKeyMatch(s)||"");return a!==t&&(a||"_common")!==t?!1:e.filterEndpoint?e.filterEndpoint(r,s,t):!0}}};c();import re from"node:fs";import f from"node:path";c();import _e from"node:path";import ee from"node:fs";async function te(n){let t=_e.dirname(n);ee.existsSync(t)||await ee.promises.mkdir(t,{recursive:!0})}var A=class{async writeFile(t,e){try{let r=f.resolve(process.cwd(),t);return f.basename(r)==="enhanceEndpoints.ts"&&re.existsSync(r)?{path:r,success:!0}:(await te(r),re.writeFileSync(r,e),{path:r,success:!0})}catch(r){return{path:t,success:!1,error:r}}}async writeFiles(t){let e=[];for(let[r,o]of Object.entries(t)){let s=await this.writeFile(r,o);e.push(s)}return e}async writeGroupFiles(t,e){let r={};return e.types&&(r[f.join(t,"types.ts")]=e.types),e.queryService&&(r[f.join(t,"query.generated.ts")]=e.queryService),e.enhanceEndpoints&&(r[f.join(t,"enhanceEndpoints.ts")]=e.enhanceEndpoints),e.index&&(r[f.join(t,"index.ts")]=e.index),this.writeFiles(r)}async writeSharedFiles(t,e){let r={};return e.commonTypes&&(r[f.join(t,"common-types.ts")]=e.commonTypes),e.tagTypes&&(r[f.join(t,"tagTypes.ts")]=e.tagTypes),e.doNotModify&&(r[f.join(t,"DO_NOT_MODIFY.md")]=e.doNotModify),e.utils&&(r[f.join(t,"utils.ts")]=e.utils),this.writeFiles(r)}async writeSchemaFile(t,e){let r={};return r[f.join(t,"schema.ts")]=e,this.writeFiles(r)}};c();import Ze from"oazapfts/generate";var R=class{constructor(t,e){this.v3Doc=t;this.apiGen=new Ze(t,{unionUndefined:e.unionUndefined,mergeReadWriteOnly:e.mergeReadWriteOnly})}apiGen;initialize(){this.apiGen.spec.components?.schemas&&(Object.keys(this.apiGen.spec.components.schemas).forEach(t=>{let e=this.apiGen.spec.components.schemas[t];e&&typeof e=="object"&&"title"in e&&delete e.title}),this.apiGen.preprocessComponents(this.apiGen.spec.components.schemas),Object.keys(this.apiGen.spec.components.schemas).forEach(t=>{try{this.apiGen.getRefAlias({$ref:`#/components/schemas/${t}`})}catch{}}))}getOperationDefinitions(t){let{operationMatches:e}=(M(),qe(ie));return Z(this.v3Doc).filter(e(t))}getApiGenerator(){return this.apiGen}getDocument(){return this.v3Doc}getSchemaTypeNames(){return new Set}};c();function se(){return`/* eslint-disable */
|
|
3
3
|
// [Warning] Generated automatically - do not edit manually
|
|
4
4
|
|
|
5
5
|
export interface RequestOptions {
|
|
@@ -21,7 +21,7 @@ export interface IRequestConfig extends RequestOptions {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export type IRestFulEndpointsQueryReturn<TVariables> = TVariables extends void ?
|
|
24
|
-
(undefined | {fetchOptions?: IRequestConfig;}):
|
|
24
|
+
(undefined | {fetchOptions?: IRequestConfig;config?: QueryConfig;}):
|
|
25
25
|
{
|
|
26
26
|
variables: TVariables;
|
|
27
27
|
fetchOptions?: IRequestConfig;
|
|
@@ -51,7 +51,7 @@ ${r.join(`
|
|
|
51
51
|
\u9019\u4E9B\u6A94\u6848\u662F\u7531 @bitstack/ng-query-codegen-openapi \u7522\u751F\u5668\u6240\u5EFA\u7ACB\u3002
|
|
52
52
|
|
|
53
53
|
\u5982\u6709\u7591\u554F\uFF0C\u8ACB\u53C3\u8003\u5C08\u6848\u6587\u4EF6\u6216\u806F\u7E6B\u958B\u767C\u5718\u968A\u3002
|
|
54
|
-
`}c();import
|
|
54
|
+
`}c();import ge from"typescript";c();M();import{supportDeepObjects as Xe}from"oazapfts/generate";var S=class{constructor(t){this.options=t}extractEndpointInfos(t){return t.map(e=>this.extractSingleEndpointInfo(e))}extractSingleEndpointInfo(t){let{verb:e,path:r,operation:o}=t,{operationNameSuffix:s="",argSuffix:a="Req",responseSuffix:p="Res",queryMatch:u,endpointOverrides:i}=this.options,m=E({verb:e,path:r}),y=s?P(m+s):m,d=P(m+s+a),C=P(m+s+p),v=J(e,r,K(t,i),u),T=`${m.replace(/([A-Z])/g,"_$1").toUpperCase()}`,x=o.summary||`${e.toUpperCase()} ${r}`,{queryParams:Oe,pathParams:xe,isVoidArg:Ce,hasRequestBody:Te}=this.extractParameters(t),Pe=this.extractContentType(o),$e=Array.isArray(o.tags)?o.tags:[];return{operationName:y,argTypeName:d,responseTypeName:C,isQuery:v,verb:e.toUpperCase(),path:r,queryKeyName:T,queryParams:Oe,pathParams:xe,isVoidArg:Ce,summary:x,contentType:Pe,hasRequestBody:Te,tags:$e}}extractParameters(t){let{operation:e,pathItem:r}=t,o=this.resolveArray(e.parameters),s=this.resolveArray(r.parameters).filter(y=>!o.some(d=>d.name===y.name&&d.in===y.in)),a=Xe([...s,...o]).filter(y=>y.in!=="header"),p=a.filter(y=>y.in==="query"),u=a.filter(y=>y.in==="path"),i=!!e.requestBody,m=p.length===0&&u.length===0&&!e.requestBody;return{queryParams:p,pathParams:u,isVoidArg:m,hasRequestBody:i}}resolveArray(t){return t?Array.isArray(t)?t:[t]:[]}extractContentType(t){if(!t.requestBody)return"application/json";let e=t.requestBody.content;if(!e||typeof e!="object")return"application/json";let r=Object.keys(e);return r.length===0?"application/json":r[0]}};c();var et=n=>n.charAt(0).toUpperCase()+n.slice(1);function ue(n,t,e,r){let o={};e&&Object.keys(e).forEach(i=>{if(o[i]=i,i.endsWith("Vo")){let m=i.slice(0,-2)+"VO";o[m]=i}if(i.endsWith("Dto")){let m=i.slice(0,-3)+"DTO";o[m]=i}});let s=`/* eslint-disable */
|
|
55
55
|
// [Warning] Generated automatically - do not edit manually
|
|
56
56
|
|
|
57
57
|
`;e&&Object.keys(e).length>0&&(s+=`import * as Schema from "../schema";
|
|
@@ -61,34 +61,34 @@ ${r.join(`
|
|
|
61
61
|
|
|
62
62
|
`)}function tt(n,t,e={}){let r=[];n.queryParams&&n.queryParams.length>0&&n.queryParams.forEach(s=>{let a=s.required?"":"?",p=ce(s,e);r.push(` ${s.name}${a}: ${p};`)}),n.pathParams&&n.pathParams.length>0&&n.pathParams.forEach(s=>{let a=s.required?"":"?",p=ce(s,e);r.push(` ${s.name}${a}: ${p};`)});let o=t?.find(s=>s.operation?.operationId===n.operationName||s.operation?.operationId===n.operationName.toLowerCase()||s.verb===n.verb.toLowerCase()&&s.path===n.path);if(o?.operation?.requestBody){let a=o.operation.requestBody.content,p=a["application/json"]||a["*/*"],u=a["multipart/form-data"]||a["application/x-www-form-urlencoded"];if(p?.schema){let i=b(p.schema,e,1);r.push(` body: ${i};`)}else if(u?.schema){let i=b(u.schema,e,1);r.push(` body: ${i};`)}else{let i=Object.values(a)[0];if(i?.schema){let m=b(i.schema,e,1);r.push(` body: ${m};`)}else r.push(" body?: any; // Request body from OpenAPI")}}return r.length===0?"":r.join(`
|
|
63
63
|
`)}function rt(n,t,e={}){let r=[],o=t?.find(s=>s.operation?.operationId===n.operationName||s.operation?.operationId===n.operationName.toLowerCase()||s.verb===n.verb.toLowerCase()&&s.path===n.path);if(o?.operation?.responses){let s=o.operation.responses[200]||o.operation.responses[201];if(s?.content){let a=s.content["application/json"]||s.content["*/*"]||Object.values(s.content)[0];if(a?.schema){let p=nt(a.schema,e);r.push(...p)}else r.push(" // Success response from OpenAPI"),r.push(" data?: any;")}}return r.length===0?"":r.join(`
|
|
64
|
-
`)}function nt(n,t={}){let e=[];if(n.type==="object"&&n.properties){let r=n.required||[];Object.entries(n.properties).forEach(([o,s])=>{let p=r.includes(o)?"":"?",u=b(s,t,1),m=/[^a-zA-Z0-9_$]/.test(o)?`"${o}"`:o;s.description&&e.push(` /** ${s.description} */`),e.push(` ${m}${p}: ${u};`)})}return e}function b(n,t={},e=0){if(!n)return"any";if(n.$ref){let o=n.$ref;if(o.startsWith("#/components/schemas/")){let s=o.replace("#/components/schemas/",""),a=t[s]||s,u=`Schema.${et(a)}`;return n.nullable?`${u} | null`:u}}let r;switch(n.type){case"string":n.enum?r=n.enum.map(a=>`"${a}"`).join(" | "):n.format==="binary"?r="Blob":r="string";break;case"number":case"integer":r="number";break;case"boolean":r="boolean";break;case"array":let o=n.items?b(n.items,t,e):"any";r=o.includes("|")?`(${o})[]`:`${o}[]`;break;case"object":if(n.properties){let a=Object.entries(n.properties);if(a.length===0)n.additionalProperties?r=`Record<string, ${n.additionalProperties===!0?"any":b(n.additionalProperties,t,e)}>`:r="{}";else{let p=" ".repeat(e+1),u=" ".repeat(e),i=[];a.forEach(([m,y])=>{let
|
|
64
|
+
`)}function nt(n,t={}){let e=[];if(n.type==="object"&&n.properties){let r=n.required||[];Object.entries(n.properties).forEach(([o,s])=>{let p=r.includes(o)?"":"?",u=b(s,t,1),m=/[^a-zA-Z0-9_$]/.test(o)?`"${o}"`:o;s.description&&e.push(` /** ${s.description} */`),e.push(` ${m}${p}: ${u};`)})}return e}function b(n,t={},e=0){if(!n)return"any";if(n.$ref){let o=n.$ref;if(o.startsWith("#/components/schemas/")){let s=o.replace("#/components/schemas/",""),a=t[s]||s,u=`Schema.${et(a)}`;return n.nullable?`${u} | null`:u}}let r;switch(n.type){case"string":n.enum?r=n.enum.map(a=>`"${a}"`).join(" | "):n.format==="binary"?r="Blob":r="string";break;case"number":case"integer":r="number";break;case"boolean":r="boolean";break;case"array":let o=n.items?b(n.items,t,e):"any";r=o.includes("|")?`(${o})[]`:`${o}[]`;break;case"object":if(n.properties){let a=Object.entries(n.properties);if(a.length===0)n.additionalProperties?r=`Record<string, ${n.additionalProperties===!0?"any":b(n.additionalProperties,t,e)}>`:r="{}";else{let p=" ".repeat(e+1),u=" ".repeat(e),i=[];a.forEach(([m,y])=>{let C=(n.required||[]).includes(m)?"":"?",v=b(y,t,e+1),x=/[^a-zA-Z0-9_$]/.test(m)?`"${m}"`:m;y.description&&i.push(`${p}/** ${y.description} */`),i.push(`${p}${x}${C}: ${v};`)}),r=`{
|
|
65
65
|
${i.join(`
|
|
66
66
|
`)}
|
|
67
67
|
${u}}`}}else n.additionalProperties?r=`Record<string, ${n.additionalProperties===!0?"any":b(n.additionalProperties,t,e)}>`:r="any";break;default:r="any";break}return n.nullable?`${r} | null`:r}function ce(n,t={}){return n.schema?b(n.schema,t):"any"}c();function me(n,t){let{groupKey:e,refetchOnMountOrArgChange:r=60}=t,o=e?`${e.charAt(0).toUpperCase()+e.slice(1)}QueryService`:"QueryService",s=e?`${e.charAt(0).toUpperCase()+e.slice(1)}ApiService`:"ApiService",a=n.filter(i=>i.isQuery).map(i=>`
|
|
68
68
|
/**
|
|
69
69
|
* ${i.summary}
|
|
70
70
|
*/
|
|
71
|
-
${i.operationName}Query(
|
|
72
|
-
return this.ntkQuery.query<${i.responseTypeName}, ${i.
|
|
73
|
-
queryKey: [ECacheTagTypes.${i.queryKeyName}${i.
|
|
71
|
+
${i.operationName}Query(args: IRestFulEndpointsQueryReturn<${i.argTypeName}>): Observable<QueryState<${i.responseTypeName}>> {
|
|
72
|
+
return this.ntkQuery.query<${i.responseTypeName}, ${i.isVoidArg?"void":`IRestFulEndpointsQueryReturn<${i.argTypeName}>`}>({
|
|
73
|
+
queryKey: [ECacheTagTypes.${i.queryKeyName}${i.isVoidArg?"":", args.variables"}],
|
|
74
74
|
queryFn: () => {
|
|
75
|
-
return this.apiService.${i.operationName}(
|
|
75
|
+
return this.apiService.${i.operationName}(args);
|
|
76
76
|
},
|
|
77
77
|
fetchOptions: args?.fetchOptions,
|
|
78
78
|
config: args?.config,
|
|
79
|
-
})
|
|
79
|
+
})(args);
|
|
80
80
|
}`).join(""),p=n.filter(i=>!i.isQuery).map(i=>`
|
|
81
81
|
/**
|
|
82
82
|
* ${i.summary}
|
|
83
83
|
*/
|
|
84
84
|
${i.operationName}Mutation(): MutationResponse<${i.responseTypeName}, {
|
|
85
|
-
variables: ${i.
|
|
85
|
+
variables: ${i.isVoidArg?"void":i.argTypeName};
|
|
86
86
|
fetchOptions?: RequestOptions;
|
|
87
87
|
}, HttpErrorResponse> {
|
|
88
|
-
return this.ntkQuery.mutation<${i.responseTypeName}, ${i.
|
|
88
|
+
return this.ntkQuery.mutation<${i.responseTypeName}, ${i.isVoidArg?"void":`IRestFulEndpointsQueryReturn<${i.argTypeName}>`}, HttpErrorResponse>({
|
|
89
89
|
endpointName: '${i.operationName}',
|
|
90
|
-
mutationFn: (
|
|
91
|
-
return this.apiService.${i.operationName}(
|
|
90
|
+
mutationFn: (args) => {
|
|
91
|
+
return this.apiService.${i.operationName}(args);
|
|
92
92
|
},
|
|
93
93
|
});
|
|
94
94
|
}`).join(""),u=n.filter(i=>i.isQuery).map(i=>`
|
|
@@ -96,18 +96,18 @@ ${u}}`}}else n.additionalProperties?r=`Record<string, ${n.additionalProperties==
|
|
|
96
96
|
* ${i.summary}
|
|
97
97
|
*/
|
|
98
98
|
${i.operationName}LazyQuery(): {
|
|
99
|
-
trigger: (${i.
|
|
99
|
+
trigger: (${i.isVoidArg?"":`args: IRestFulEndpointsQueryReturn<${i.argTypeName}>, `}options?: { skipCache?: boolean }) => Observable<${i.responseTypeName}>
|
|
100
100
|
} {
|
|
101
101
|
return {
|
|
102
|
-
trigger: (${i.
|
|
102
|
+
trigger: (${i.isVoidArg?"":"args, "}options = {}) => {
|
|
103
103
|
const { skipCache = true } = options;
|
|
104
104
|
if (!skipCache) {
|
|
105
|
-
const cachedResult = this.ntkQuery.getQueryCache<${i.responseTypeName}>([ECacheTagTypes.${i.queryKeyName}${i.
|
|
105
|
+
const cachedResult = this.ntkQuery.getQueryCache<${i.responseTypeName}>([ECacheTagTypes.${i.queryKeyName}${i.isVoidArg?"":", args.variables"}]);
|
|
106
106
|
if (cachedResult) {
|
|
107
107
|
return cachedResult;
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
|
-
return this.apiService.${i.operationName}(
|
|
110
|
+
return this.apiService.${i.operationName}('args');
|
|
111
111
|
}
|
|
112
112
|
};
|
|
113
113
|
}`).join("");return`/* eslint-disable */
|
|
@@ -130,7 +130,7 @@ export class ${o} {
|
|
|
130
130
|
private ntkQuery = inject(NtkQueryService);
|
|
131
131
|
${a}${p}${u}
|
|
132
132
|
}
|
|
133
|
-
`}c();function
|
|
133
|
+
`}c();function le(n,t){let{apiConfiguration:e,httpClient:r,groupKey:o}=t,s=o?`${o.charAt(0).toUpperCase()+o.slice(1)}ApiService`:"ApiService";return`/* eslint-disable */
|
|
134
134
|
// [Warning] Generated automatically - do not edit manually
|
|
135
135
|
|
|
136
136
|
import { ${r.importReturnTypeName} } from '${r.file}';
|
|
@@ -148,23 +148,23 @@ export class ${s} {
|
|
|
148
148
|
private config = inject(${e.importName});
|
|
149
149
|
private http = inject(${r.importReturnTypeName});
|
|
150
150
|
|
|
151
|
-
${n.map(a=>{let p=a.verb.toUpperCase()==="GET",u
|
|
151
|
+
${n.map(a=>{let p=a.verb.toUpperCase()==="GET",u=!a.isVoidArg,i=a.hasRequestBody,m=v=>v.includes("{")&&u?`\`\${this.config.rootUrl}${v.replace(/\{([^}]+)\}/g,"${args.variables.$1}")}\``:`\`\${this.config.rootUrl}${v}\``,y=a.queryParams.length>0,d=!p&&u,C=()=>{let v="";return a.queryParams&&a.queryParams.length>0&&(v=`params: {${a.queryParams.map(x=>`${x.name}: args.variables.${x.name},`).join(`
|
|
152
152
|
`)}},`),`{
|
|
153
|
-
...args
|
|
154
|
-
headers: { 'Content-Type': '${a.contentType}', ...args
|
|
153
|
+
...args?.fetchOptions,
|
|
154
|
+
headers: { 'Content-Type': '${a.contentType}', ...args?.fetchOptions?.headers },
|
|
155
155
|
${v}${a.hasRequestBody?"body: args.variables.body,":""}
|
|
156
156
|
}`};return`
|
|
157
157
|
/**
|
|
158
158
|
* ${a.summary}
|
|
159
159
|
*/
|
|
160
160
|
${a.operationName}(
|
|
161
|
-
|
|
161
|
+
args: IRestFulEndpointsQueryReturn<${a.argTypeName}>,
|
|
162
162
|
): Observable<${a.responseTypeName}> {
|
|
163
163
|
const url = ${m(a.path)};
|
|
164
|
-
return this.http.request('${a.verb.toLowerCase()}', url, ${
|
|
164
|
+
return this.http.request('${a.verb.toLowerCase()}', url, ${C()});
|
|
165
165
|
}`}).join("")}
|
|
166
166
|
}
|
|
167
|
-
`}var q=class{constructor(t,e){this.parserService=t;this.options=e;this.infoExtractor=new S(e)}infoExtractor;async generate(){let t=this.parserService.getOperationDefinitions(this.options.filterEndpoints),e=this.infoExtractor.extractEndpointInfos(t);return this.generateRtkQueryCode(e)}generateRtkQueryCode(t){let e=this.generateTypes(t),r=me(t,this.options),o=
|
|
167
|
+
`}var q=class{constructor(t,e){this.parserService=t;this.options=e;this.infoExtractor=new S(e)}infoExtractor;async generate(){let t=this.parserService.getOperationDefinitions(this.options.filterEndpoints),e=this.infoExtractor.extractEndpointInfos(t);return this.generateRtkQueryCode(e)}generateRtkQueryCode(t){let e=this.generateTypes(t),r=me(t,this.options),o=le(t,this.options),s=this.generateIndex(),a=t.filter(i=>i.isQuery).map(i=>({operationName:i.operationName,queryKeyName:i.queryKeyName,groupKey:this.options.groupKey||"_common"})),p=t.map(i=>i.operationName),u=new Set;return t.forEach(i=>{i.tags&&Array.isArray(i.tags)&&i.tags.forEach(m=>u.add(m))}),{operationNames:p,tags:Array.from(u),files:{types:e,queryService:r,index:s,enhanceEndpoints:o,allEndpointCacheKeys:a}}}generateTypes(t){let e={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}},o=this.parserService.getApiGenerator().aliases.reduce((a,p)=>{if(ge.isInterfaceDeclaration(p)||ge.isTypeAliasDeclaration(p)){let u=p.name.text;return{...a,[u]:p}}return a},{}),s=this.parserService.getOperationDefinitions(this.options.filterEndpoints);return ue(t,e,o,s)}generateIndex(){let t=this.options.groupKey||"";return`/* eslint-disable */
|
|
168
168
|
// [Warning] Generated automatically - do not edit manually
|
|
169
169
|
|
|
170
170
|
export { default as ${t?`${t.charAt(0).toLowerCase()+t.slice(1)}Api`:"api"} } from "./enhanceEndpoints";
|
|
@@ -197,10 +197,10 @@ ${a}`}).join(`
|
|
|
197
197
|
}
|
|
198
198
|
|
|
199
199
|
export default ECacheTagTypes;
|
|
200
|
-
`}var w=class{_options;openApiService=new
|
|
200
|
+
`}var w=class{_options;openApiService=new $;groupService=new N;fileWriterService=new A;allEndpointCacheKeys=[];openApiDoc=null;parserService=null;schemaInterfaces={};actualSchemaFile="";generatedContent={groups:[],commonTypes:"",componentSchema:"",doNotModify:"",utils:"",tagTypes:""};allTags=new Set;constructor(t){this._options=t}async generateAll(){return await this.prepare(),await this.generateApi(),this.generateCommonTypesContent(),this.generateSchemaContent(),this.generateUtilsContent(),this.generateDoNotModifyContent(),this.generatECacheTagTypesContent(),await this.release()}async prepare(){this.actualSchemaFile=this._options.schemaFile,this._options.remoteFile&&(this.actualSchemaFile=await this.openApiService.downloadSchema(this._options.remoteFile,this._options.schemaFile)),this.openApiDoc=await this.openApiService.getDocument(this.actualSchemaFile,this._options.httpResolverOptions),this.parserService=new R(this.openApiDoc,this._options),this.parserService.initialize();let t=this.parserService.getApiGenerator();this.schemaInterfaces=t.aliases.reduce((e,r)=>{if(he.isInterfaceDeclaration(r)||he.isTypeAliasDeclaration(r)){let o=r.name.text;return{...e,[o]:r}}return e},{})}async generateApi(){if(!this.openApiDoc||!this.parserService)throw new Error("\u8ACB\u5148\u8ABF\u7528 prepare() \u65B9\u6CD5");let t=this.openApiService.getPaths(this.openApiDoc),e=this.groupService.groupPaths(t,this._options.outputFiles);for(let r of Object.values(e))try{let o=await this.generateApiGroupContent(this._options,r);o.operationNames.length>0&&(this.generatedContent.groups.push({groupKey:r.groupKey,outputPath:r.outputPath,content:o}),o.tags&&Array.isArray(o.tags)&&o.tags.forEach(s=>this.allTags.add(s)))}catch(o){throw new Error(`\u7FA4\u7D44 ${r.groupKey} \u751F\u6210\u5931\u6557: ${o}`)}}async generatECacheTagTypesContent(){this.generatedContent.tagTypes=fe(this.allEndpointCacheKeys)}async generateCommonTypesContent(){this.generatedContent.commonTypes=se()}async generateSchemaContent(){this.generatedContent.componentSchema=ae(this.schemaInterfaces)}async generateDoNotModifyContent(){this.generatedContent.doNotModify=pe()}async generateUtilsContent(){this.generatedContent.utils=ye()}async release(){let t=[],e=[],r=[];try{for(let p of this.generatedContent.groups)try{if(p.content?.files){let u=F.dirname(p.outputPath),i=await this.fileWriterService.writeGroupFiles(u,{types:p.content.files.types,queryService:p.content.files.queryService,enhanceEndpoints:p.content.files.enhanceEndpoints,index:p.content.files.index});t.push(...i),r.push(p.groupKey)}}catch(u){e.push(new Error(`\u5BEB\u5165\u7FA4\u7D44 ${p.groupKey} \u5931\u6557: ${u}`))}let o=this.generatedContent.groups[0]?F.dirname(F.dirname(this.generatedContent.groups[0].outputPath)):"./generated";if(this.generatedContent.tagTypes||this.generatedContent.commonTypes||this.generatedContent.doNotModify||this.generatedContent.utils){let p=await this.fileWriterService.writeSharedFiles(o,{tagTypes:this.generatedContent.tagTypes||void 0,commonTypes:this.generatedContent.commonTypes||void 0,doNotModify:this.generatedContent.doNotModify||void 0,utils:this.generatedContent.utils||void 0});t.push(...p)}if(this.generatedContent.componentSchema){let p=await this.fileWriterService.writeSchemaFile(o,this.generatedContent.componentSchema);t.push(...p)}let s=this.generateMainIndex(r),a=await this.fileWriterService.writeFile(F.join(o,"index.ts"),s);t.push(a)}catch(o){e.push(o)}return{success:e.length===0,writtenFiles:t,errors:e,generatedGroups:r}}async generateApiGroupContent(t,e){let{outputFiles:r,...o}=t,s={...o,schemaFile:this.actualSchemaFile,outputFile:e.outputPath,sharedTypesFile:`${r.outputDir}/common-types.ts`,filterEndpoints:this.groupService.createGroupFilter(e.groupKey,r),queryMatch:r.queryMatch,groupKey:e.groupKey};if(!this.openApiDoc||!this.parserService)throw new Error("OpenAPI \u6587\u6A94\u672A\u521D\u59CB\u5316\uFF0C\u8ACB\u5148\u8ABF\u7528 prepare()");let p=await new q(this.parserService,s).generate();if(p.files&&"allEndpointCacheKeys"in p.files){let u=p.files.allEndpointCacheKeys;this.allEndpointCacheKeys.push(...u)}return p}generateMainIndex(t){return`/* eslint-disable */
|
|
201
201
|
// [Warning] Generated automatically - do not edit manually
|
|
202
202
|
|
|
203
203
|
${t.map(r=>`export * from "./${r}";`).join(`
|
|
204
204
|
`)}
|
|
205
|
-
`}};async function ve(n){let e=await new w(n).generateAll();if(!e.success&&e.errors.length>0)throw e.errors[0]}var be=ot(
|
|
205
|
+
`}};async function ve(n){let e=await new w(n).generateAll();if(!e.success&&e.errors.length>0)throw e.errors[0]}var be=ot(l);async function at(n){let t=st(process.cwd(),n);process.chdir(it(t));let e=be(t),r=e.default??e;"outputFiles"in r||(console.error('Configuration must include "outputFiles" property. Single file output is no longer supported.'),process.exit(1)),r.outputFiles&&r.outputFiles.outputDir&&U(r.outputFiles.outputDir);try{console.log("Generating multiple outputs..."),await ve(r),console.log("Done")}catch(o){console.error("Generation failed:",o),process.exit(1)}}async function pt(){let n=be("../../package.json"),t=W();j.version(n.version).usage("<path/to/config.js>").parse(process.argv);let e=j.args[0];if(j.args.length===0){j.help();return}_(e),B(e,t),await at(e)}pt().catch(n=>{console.error("CLI execution failed:",n),process.exit(1)});export{at as runGeneration};
|
|
206
206
|
//# sourceMappingURL=cli.mjs.map
|