openapi-sync 2.1.10 → 2.1.12

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.
@@ -1,6 +1,7 @@
1
- import { Method } from "axios";
2
- export type IOpenApiSpec = Record<"openapi", string> & Record<string, any>;
3
- export type IOpenApSchemaSpec = {
1
+ import { Method } from 'axios';
2
+
3
+ type IOpenApiSpec = Record<"openapi", string> & Record<string, any>;
4
+ type IOpenApSchemaSpec = {
4
5
  nullable?: boolean;
5
6
  type: "string" | "integer" | "number" | "array" | "object" | "boolean" | "null" | any[];
6
7
  example?: any;
@@ -16,7 +17,7 @@ export type IOpenApSchemaSpec = {
16
17
  oneOf?: IOpenApSchemaSpec[];
17
18
  allOf?: IOpenApSchemaSpec[];
18
19
  };
19
- export type IOpenApiParameterSpec = {
20
+ type IOpenApiParameterSpec = {
20
21
  $ref?: string;
21
22
  name: string;
22
23
  in: string;
@@ -32,28 +33,28 @@ export type IOpenApiParameterSpec = {
32
33
  example?: any;
33
34
  examples?: any[];
34
35
  };
35
- export type IOpenApiMediaTypeSpec = {
36
+ type IOpenApiMediaTypeSpec = {
36
37
  schema?: IOpenApSchemaSpec;
37
38
  example?: any;
38
39
  examples?: any[];
39
40
  encoding?: any;
40
41
  };
41
- export type IOpenApiRequestBodySpec = {
42
+ type IOpenApiRequestBodySpec = {
42
43
  description?: string;
43
44
  required?: boolean;
44
45
  content: Record<string, IOpenApiMediaTypeSpec>;
45
46
  };
46
- export type IOpenApiResponseSpec = Record<string, IOpenApiRequestBodySpec>;
47
- export type IConfigReplaceWord = {
47
+ type IOpenApiResponseSpec = Record<string, IOpenApiRequestBodySpec>;
48
+ type IConfigReplaceWord = {
48
49
  /** string and regular expression as a string*/
49
50
  replace: string;
50
51
  with: string;
51
52
  };
52
- export type IConfigDoc = {
53
+ type IConfigDoc = {
53
54
  disable?: boolean;
54
55
  showCurl?: boolean;
55
56
  };
56
- export type IConfigExclude = {
57
+ type IConfigExclude = {
57
58
  /** Exclude/Include endpoints by tags */
58
59
  tags?: string[];
59
60
  /** Exclude/Include individual endpoints by path and method */
@@ -66,13 +67,30 @@ export type IConfigExclude = {
66
67
  method?: Method;
67
68
  }>;
68
69
  };
69
- export interface IConfigInclude extends IConfigExclude {
70
+ interface IConfigInclude extends IConfigExclude {
70
71
  }
71
- export type IConfig = {
72
+ type IConfigFolderSplit = {
73
+ /** Split folders by tags - creates folders named after each tag */
74
+ byTags?: boolean;
75
+ /** Custom function to determine folder name for each endpoint */
76
+ customFolder?: (data: {
77
+ method: Method;
78
+ path: string;
79
+ summary?: string;
80
+ operationId?: string;
81
+ tags?: string[];
82
+ parameters?: IOpenApiParameterSpec[];
83
+ requestBody?: IOpenApiRequestBodySpec;
84
+ responses?: IOpenApiResponseSpec;
85
+ }) => string | null;
86
+ };
87
+ type IConfig = {
72
88
  refetchInterval?: number;
73
89
  folder?: string;
74
90
  api: Record<string, string>;
75
91
  server?: number | string;
92
+ /** Configuration for splitting generated code into folders */
93
+ folderSplit?: IConfigFolderSplit;
76
94
  /** Configuration for excluding endpoints from code generation */
77
95
  types?: {
78
96
  name?: {
@@ -111,7 +129,7 @@ export type IConfig = {
111
129
  include?: IConfigInclude;
112
130
  };
113
131
  };
114
- export type IOpenApiSecuritySchemes = {
132
+ type IOpenApiSecuritySchemes = {
115
133
  [key: string]: {
116
134
  type: "http" | "apiKey" | "oauth2" | "openIdConnect" | "mutualTLS";
117
135
  scheme?: "bearer" | "basic";
@@ -130,3 +148,25 @@ export type IOpenApiSecuritySchemes = {
130
148
  name?: string;
131
149
  };
132
150
  };
151
+
152
+ declare const isJson: (value: any) => boolean;
153
+ declare const isYamlString: (fileContent: string) => boolean;
154
+ declare const yamlStringToJson: (fileContent: string) => any;
155
+ declare const capitalize: (text: string) => string;
156
+ declare const getEndpointDetails: (path: string, method: string) => {
157
+ name: string;
158
+ variables: string[];
159
+ pathParts: string[];
160
+ };
161
+ declare const JSONStringify: (obj: Record<string, any>, indent?: number) => string;
162
+ declare const renderTypeRefMD: (typeRef: string, indent?: number) => string;
163
+ declare function getNestedValue<T>(obj: object, path: string): T | undefined;
164
+
165
+ declare const variableName: RegExp;
166
+ declare const variableNameChar: RegExp;
167
+
168
+ declare const Init: (options?: {
169
+ refetchInterval?: number;
170
+ }) => Promise<void>;
171
+
172
+ export { type IConfig, type IConfigDoc, type IConfigExclude, type IConfigFolderSplit, type IConfigInclude, type IConfigReplaceWord, type IOpenApSchemaSpec, type IOpenApiMediaTypeSpec, type IOpenApiParameterSpec, type IOpenApiRequestBodySpec, type IOpenApiResponseSpec, type IOpenApiSecuritySchemes, type IOpenApiSpec, Init, JSONStringify, capitalize, getEndpointDetails, getNestedValue, isJson, isYamlString, renderTypeRefMD, variableName, variableNameChar, yamlStringToJson };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,172 @@
1
- export * from "./types";
2
- export * from "./helpers";
3
- export * from "./regex";
4
- export declare const Init: (options?: {
1
+ import { Method } from 'axios';
2
+
3
+ type IOpenApiSpec = Record<"openapi", string> & Record<string, any>;
4
+ type IOpenApSchemaSpec = {
5
+ nullable?: boolean;
6
+ type: "string" | "integer" | "number" | "array" | "object" | "boolean" | "null" | any[];
7
+ example?: any;
8
+ enum?: string[];
9
+ format?: string;
10
+ items?: IOpenApSchemaSpec;
11
+ required?: string[];
12
+ description?: string;
13
+ $ref?: string;
14
+ properties?: Record<string, IOpenApSchemaSpec>;
15
+ additionalProperties?: IOpenApSchemaSpec;
16
+ anyOf?: IOpenApSchemaSpec[];
17
+ oneOf?: IOpenApSchemaSpec[];
18
+ allOf?: IOpenApSchemaSpec[];
19
+ };
20
+ type IOpenApiParameterSpec = {
21
+ $ref?: string;
22
+ name: string;
23
+ in: string;
24
+ enum?: string[];
25
+ description?: string;
26
+ required?: boolean;
27
+ deprecated?: boolean;
28
+ allowEmptyValue?: boolean;
29
+ style?: string;
30
+ explode?: boolean;
31
+ allowReserved?: boolean;
32
+ schema?: IOpenApSchemaSpec;
33
+ example?: any;
34
+ examples?: any[];
35
+ };
36
+ type IOpenApiMediaTypeSpec = {
37
+ schema?: IOpenApSchemaSpec;
38
+ example?: any;
39
+ examples?: any[];
40
+ encoding?: any;
41
+ };
42
+ type IOpenApiRequestBodySpec = {
43
+ description?: string;
44
+ required?: boolean;
45
+ content: Record<string, IOpenApiMediaTypeSpec>;
46
+ };
47
+ type IOpenApiResponseSpec = Record<string, IOpenApiRequestBodySpec>;
48
+ type IConfigReplaceWord = {
49
+ /** string and regular expression as a string*/
50
+ replace: string;
51
+ with: string;
52
+ };
53
+ type IConfigDoc = {
54
+ disable?: boolean;
55
+ showCurl?: boolean;
56
+ };
57
+ type IConfigExclude = {
58
+ /** Exclude/Include endpoints by tags */
59
+ tags?: string[];
60
+ /** Exclude/Include individual endpoints by path and method */
61
+ endpoints?: Array<{
62
+ /** Exact path match (regex will be ignore when provided)*/
63
+ path?: string;
64
+ /** Regular expression pattern for path matching */
65
+ regex?: string;
66
+ /** Don't specify method to exclude all methods */
67
+ method?: Method;
68
+ }>;
69
+ };
70
+ interface IConfigInclude extends IConfigExclude {
71
+ }
72
+ type IConfigFolderSplit = {
73
+ /** Split folders by tags - creates folders named after each tag */
74
+ byTags?: boolean;
75
+ /** Custom function to determine folder name for each endpoint */
76
+ customFolder?: (data: {
77
+ method: Method;
78
+ path: string;
79
+ summary?: string;
80
+ operationId?: string;
81
+ tags?: string[];
82
+ parameters?: IOpenApiParameterSpec[];
83
+ requestBody?: IOpenApiRequestBodySpec;
84
+ responses?: IOpenApiResponseSpec;
85
+ }) => string | null;
86
+ };
87
+ type IConfig = {
88
+ refetchInterval?: number;
89
+ folder?: string;
90
+ api: Record<string, string>;
91
+ server?: number | string;
92
+ /** Configuration for splitting generated code into folders */
93
+ folderSplit?: IConfigFolderSplit;
94
+ /** Configuration for excluding endpoints from code generation */
95
+ types?: {
96
+ name?: {
97
+ prefix?: string;
98
+ useOperationId?: boolean;
99
+ format?: (source: "shared" | "endpoint", data: {
100
+ name?: string;
101
+ type?: "response" | "dto" | "query";
102
+ code?: string;
103
+ method?: Method;
104
+ path?: string;
105
+ summary?: string;
106
+ operationId?: string;
107
+ }, defaultName: string) => string | null | undefined;
108
+ };
109
+ doc?: IConfigDoc;
110
+ };
111
+ endpoints?: {
112
+ value?: {
113
+ replaceWords?: IConfigReplaceWord[];
114
+ includeServer?: boolean;
115
+ type?: "string" | "object";
116
+ };
117
+ name?: {
118
+ format?: (data: {
119
+ method: Method;
120
+ path: string;
121
+ summary: string;
122
+ operationId: string;
123
+ }, defaultName: string) => string | null;
124
+ prefix?: string;
125
+ useOperationId?: boolean;
126
+ };
127
+ doc?: IConfigDoc;
128
+ exclude?: IConfigExclude;
129
+ include?: IConfigInclude;
130
+ };
131
+ };
132
+ type IOpenApiSecuritySchemes = {
133
+ [key: string]: {
134
+ type: "http" | "apiKey" | "oauth2" | "openIdConnect" | "mutualTLS";
135
+ scheme?: "bearer" | "basic";
136
+ in?: "query" | "header" | "cookie";
137
+ flows?: {
138
+ authorizationCode: {
139
+ authorizationUrl: "https://example.com/auth";
140
+ tokenUrl: "https://example.com/token";
141
+ scopes: {
142
+ "read:data": "Grants read access";
143
+ };
144
+ };
145
+ };
146
+ bearerFormat?: "JWT";
147
+ openIdConnectUrl?: string;
148
+ name?: string;
149
+ };
150
+ };
151
+
152
+ declare const isJson: (value: any) => boolean;
153
+ declare const isYamlString: (fileContent: string) => boolean;
154
+ declare const yamlStringToJson: (fileContent: string) => any;
155
+ declare const capitalize: (text: string) => string;
156
+ declare const getEndpointDetails: (path: string, method: string) => {
157
+ name: string;
158
+ variables: string[];
159
+ pathParts: string[];
160
+ };
161
+ declare const JSONStringify: (obj: Record<string, any>, indent?: number) => string;
162
+ declare const renderTypeRefMD: (typeRef: string, indent?: number) => string;
163
+ declare function getNestedValue<T>(obj: object, path: string): T | undefined;
164
+
165
+ declare const variableName: RegExp;
166
+ declare const variableNameChar: RegExp;
167
+
168
+ declare const Init: (options?: {
5
169
  refetchInterval?: number;
6
170
  }) => Promise<void>;
171
+
172
+ export { type IConfig, type IConfigDoc, type IConfigExclude, type IConfigFolderSplit, type IConfigInclude, type IConfigReplaceWord, type IOpenApSchemaSpec, type IOpenApiMediaTypeSpec, type IOpenApiParameterSpec, type IOpenApiRequestBodySpec, type IOpenApiResponseSpec, type IOpenApiSecuritySchemes, type IOpenApiSpec, Init, JSONStringify, capitalize, getEndpointDetails, getNestedValue, isJson, isYamlString, renderTypeRefMD, variableName, variableNameChar, yamlStringToJson };
package/dist/index.js CHANGED
@@ -1,86 +1,56 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.Init = void 0;
30
- const Openapi_sync_1 = __importDefault(require("./Openapi-sync"));
31
- const path_1 = __importDefault(require("path"));
32
- const fs_1 = __importDefault(require("fs"));
33
- const state_1 = require("./Openapi-sync/state");
34
- // Re-export modules for user consumption
35
- __exportStar(require("./types"), exports);
36
- __exportStar(require("./helpers"), exports);
37
- __exportStar(require("./regex"), exports);
38
- const rootUsingCwd = process.cwd();
39
- const Init = (options) => __awaiter(void 0, void 0, void 0, function* () {
40
- // Load config file
41
- let configJS;
42
- // Register TypeScript loader before requiring the file
43
- try {
44
- require("esbuild-register");
45
- }
46
- catch (registerError) {
47
- throw registerError;
48
- }
49
- const jsConfigPath = path_1.default.join(rootUsingCwd, "openapi.sync.js");
50
- const tsConfigPath = path_1.default.join(rootUsingCwd, "openapi.sync.ts");
51
- const jsonConfigPath = path_1.default.join(rootUsingCwd, "openapi.sync.json");
52
- const configPaths = [jsConfigPath, tsConfigPath, jsonConfigPath];
53
- try {
54
- for (const configPath of configPaths) {
55
- if (fs_1.default.existsSync(configPath)) {
56
- configJS = require(configPath);
57
- if (Object.keys(configJS).length === 1 && configJS.default) {
58
- configJS = configJS.default;
59
- }
60
- }
61
- }
62
- }
63
- catch (e) {
64
- console.log(e);
65
- }
66
- if (typeof configJS === "function") {
67
- configJS = configJS();
68
- }
69
- const config = configJS;
70
- if (!config) {
71
- throw new Error("No config found");
72
- }
73
- const apiNames = Object.keys(config.api);
74
- const refetchInterval = options &&
75
- "refetchInterval" in options &&
76
- !isNaN(options === null || options === void 0 ? void 0 : options.refetchInterval)
77
- ? options.refetchInterval
78
- : config.refetchInterval;
79
- (0, state_1.resetState)();
80
- for (let i = 0; i < apiNames.length; i += 1) {
81
- const apiName = apiNames[i];
82
- const apiUrl = config.api[apiName];
83
- (0, Openapi_sync_1.default)(apiUrl, apiName, config, refetchInterval);
84
- }
85
- });
86
- exports.Init = Init;
1
+ "use strict";var Ot=Object.create;var oe=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var bt=Object.getOwnPropertyNames;var jt=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var xt=(n,i)=>{for(var e in i)oe(n,e,{get:i[e],enumerable:!0})},ge=(n,i,e,j)=>{if(i&&typeof i=="object"||typeof i=="function")for(let O of bt(i))!Ct.call(n,O)&&O!==e&&oe(n,O,{get:()=>i[O],enumerable:!(j=It(i,O))||j.enumerable});return n};var q=(n,i,e)=>(e=n!=null?Ot(jt(n)):{},ge(i||!n||!n.__esModule?oe(e,"default",{value:n,enumerable:!0}):e,n)),At=n=>ge(oe({},"__esModule",{value:!0}),n);var ae=(n,i,e)=>new Promise((j,O)=>{var x=C=>{try{c(e.next(C))}catch(f){O(f)}},E=C=>{try{c(e.throw(C))}catch(f){O(f)}},c=C=>C.done?j(C.value):Promise.resolve(C.value).then(x,E);c((e=e.apply(n,i)).next())});var wt={};xt(wt,{Init:()=>St,JSONStringify:()=>Z,capitalize:()=>V,getEndpointDetails:()=>he,getNestedValue:()=>Tt,isJson:()=>$e,isYamlString:()=>et,renderTypeRefMD:()=>ee,variableName:()=>Et,variableNameChar:()=>ye,yamlStringToJson:()=>fe});module.exports=At(wt);var P=q(require("fs")),F=q(require("path"));var Et=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ye=/[A-Za-z0-9_$]/;var g=q(require("js-yaml")),$e=n=>["object"].includes(typeof n)&&!(n instanceof Blob),et=n=>{try{return g.load(n),!0}catch(i){let e=i;if(e instanceof g.YAMLException)return!1;throw e}},fe=n=>{if(et(n)){let i=g.load(n),e=JSON.stringify(i,null,2);return JSON.parse(e)}},V=n=>n.substring(0,1).toUpperCase()+n.substring(1),he=(n,i)=>{let e=n.split("/"),j=`${V(i)}`,O=[];return e.forEach(x=>{if(x[0]==="{"&&x[x.length-1]==="}"){let c=x.replace(/{/,"").replace(/}/,"");O.push(c),x=`$${c}`}else if(x[0]==="<"&&x[x.length-1]===">"){let c=x.replace(/</,"").replace(/>/,"");O.push(c),x=`$${c}`}else if(x[0]===":"){let c=x.replace(/:/,"");O.push(c),x=`$${c}`}let E="";x.split("").forEach(c=>{let C=c;ye.test(c)||(C="/"),E+=C}),E.split("/").forEach(c=>{j+=V(c)})}),{name:j,variables:O,pathParts:e}},Z=(n,i=1)=>{let e="{",j=Object.keys(n);for(let O=0;O<j.length;O++){let x=j[O],E=n[x];if(e+=`
2
+ `+" ".repeat(i)+x+": ",Array.isArray(E)){e+="[";for(let c=0;c<E.length;c++){let C=E[c];typeof C=="object"&&C!==null?e+=Z(C,i+1):e+=typeof C=="string"?`"${C}"`:C,c<E.length-1&&(e+=", ")}e+="]"}else typeof E=="object"&&E!==null?e+=""+Z(E,i+1):e+=E.split(`
3
+ `).filter(c=>c.trim()!=="").join(`
4
+ ${" ".repeat(i)}`);O<j.length-1&&(e+=", ")}return e+=`
5
+ ${" ".repeat(i-1)}}`,e},ee=(n,i=1)=>`
6
+ \`\`\`typescript
7
+ ${" ".repeat(i)} ${n.split(`
8
+ `).filter(e=>e.trim()!=="").join(`
9
+ ${" ".repeat(i)} `)}
10
+ \`\`\``;function Tt(n,i){return i.split(".").reduce((j,O)=>j&&j[O]!==void 0?j[O]:void 0,n)}var at=q(require("lodash.isequal")),Ie=q(require("lodash.get")),it=q(require("axios")),lt=q(require("axios-retry")),pe=require("@redocly/openapi-core");var tt=q(require("path")),ie=q(require("fs")),le=tt.default.join(__dirname,"../","../db.json");ie.default.existsSync(le)||ie.default.writeFileSync(le,"{}");var ce={};try{ce=require(le)}catch(n){ce={}}var te=ce||{},rt=n=>{ie.default.writeFileSync(le,JSON.stringify(n))},st=(n,i)=>{te[n]=i,rt(te)},nt=n=>te[n],ot=()=>{te={},rt(te)};var pt=require("curl-generator");var re=process.cwd(),Oe={},mt=it.default.create({timeout:6e4});(0,lt.default)(mt,{retries:20,retryCondition:n=>n.code==="ECONNABORTED"||n.message.includes("Network Error"),retryDelay:n=>n*1e3});var dt=(n,i,e,j)=>ae(null,null,function*(){var Ae,Ee,Te,Se,we,Ne;let O=yield mt.get(n),x=yield(0,pe.createConfig)({extends:["minimal"]}),E=JSON.stringify($e(O.data)?O.data:fe(O.data)),c=yield(0,pe.bundleFromString)({source:E,config:x}),C=F.default.join((e==null?void 0:e.folder)||"",i),f=c.bundle.parsed,B={},de=s=>{var r,I;if((r=e==null?void 0:e.folderSplit)!=null&&r.customFolder){let $=e.folderSplit.customFolder(s);if($)return $}return(I=e==null?void 0:e.folderSplit)!=null&&I.byTags&&s.tags&&s.tags.length>0?s.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},je=typeof(e==null?void 0:e.server)=="string"?e==null?void 0:e.server:((Ee=(Ae=f==null?void 0:f.servers)==null?void 0:Ae[(e==null?void 0:e.server)||0])==null?void 0:Ee.url)||"",L=typeof((Se=(Te=e==null?void 0:e.types)==null?void 0:Te.name)==null?void 0:Se.prefix)=="string"?e==null?void 0:e.types.name.prefix:"I",$t=typeof((Ne=(we=e==null?void 0:e.endpoints)==null?void 0:we.name)==null?void 0:Ne.prefix)=="string"?e==null?void 0:e.endpoints.name.prefix:"",Ce=(s,r)=>{var $,o;let I=V(s);if((o=($=e==null?void 0:e.types)==null?void 0:$.name)!=null&&o.format){let p=e==null?void 0:e.types.name.format("shared",{name:s},I);if(p)return`${L}${p}`}return`${L}${I}`},U=(s,r,I,$,o,p=0)=>{let h="",a="",l="";if(r){if(r.$ref)if(r.$ref[0]==="#"){let m=(r.$ref||"").split("/");m.shift(),[...m].pop();let w=(0,Ie.default)(s,m,null);if(w){w!=null&&w.name&&(h=w.name),a=m[m.length-1];let N=Ce(a);N.includes(".")&&(N=N.split(".").map((z,Y)=>Y===0?z:`["${z}"]`).join("")),l+=`${o!=null&&o.noSharedImport?"":"Shared."}${N}`}}else l+="";else if(r.anyOf)l+=`(${r.anyOf.map(m=>U(s,m,"",$,o)).filter(m=>!!m).join("|")})`;else if(r.oneOf)l+=`(${r.oneOf.map(m=>U(s,m,"",$,o)).filter(m=>!!m).join("|")})`;else if(r.allOf)l+=`(${r.allOf.map(m=>U(s,m,"",$,o)).filter(m=>!!m).join("&")})`;else if(r.items)l+=`${U(s,r.items,"",!1,o)}[]`;else if(r.properties){let m=Object.keys(r.properties),b=r.required||[],S="";m.forEach(w=>{var X,z,Y,Q,se,D;let N="";!((z=(X=e==null?void 0:e.types)==null?void 0:X.doc)!=null&&z.disable)&&((Q=(Y=r.properties)==null?void 0:Y[w])!=null&&Q.description)&&(N=" * "+((se=r.properties)==null?void 0:se[w].description.split(`
11
+ `).filter(ne=>ne.trim()!=="").join(`
12
+ *${" ".repeat(1)}`))),S+=(N?`/**
13
+ ${N}
14
+ */
15
+ `:"")+`${U(s,(D=r.properties)==null?void 0:D[w],w,b.includes(w),o,p+1)}`}),S.length>0?l+=`{
16
+ ${" ".repeat(p)}${S}${" ".repeat(p)}}`:l+="{[k: string]: any}"}else if(r.enum&&r.enum.length>0)r.enum.length>1&&(l+="("),r.enum.map(m=>JSON.stringify(m)).filter(m=>!!m).forEach((m,b)=>{l+=`${b===0?"":"|"}${m}`}),r.enum.length>1&&(l+=")");else if(r.type){let m=b=>{let S="";if(typeof b=="string")["string","integer","number","array","boolean","null"].includes(b)?["integer","number"].includes(b)?S+="number":b==="array"?S+="any[]":S+=b:b==="object"&&(r.additionalProperties?S+=`{[k: string]: ${U(s,r.additionalProperties,"",!0,o)||"any"}}`:S+="{[k: string]: any}");else if(Array.isArray(b)){let w=b.map(N=>m(N));w.filter(N=>N!==""),w.length>1&&(S+="("+w.join("|")+")")}else S+="any";return S};l=m(r.type)}}else l="string";let u=h||I;o!=null&&o.useComponentName&&!u&&(u=a);let T=u?` "${u}"${$?"":"?"}: `:"",t=r!=null&&r.nullable?" | null":"";return l.length>0?`${T}${l}${t}${u?`;
17
+ `:""}`:""},W=(s,r)=>{let I="",$="",o="";if(r){if(r.$ref)if(r.$ref[0]==="#"){let p=(r.$ref||"").split("/");p.shift();let a=(0,Ie.default)(s,p,null);a&&(a!=null&&a.name&&(I=a.name),$=p[p.length-1],o+=W(s,a))}else o+="";else if(r.anyOf)o+=W(s,r.anyOf[0]);else if(r.oneOf)o+=W(s,r.oneOf[0]);else if(r.allOf)o+=`{${r.allOf.map(p=>`...(${W(s,p)})`).join(",")}}`;else if(r.items)o+=`[${W(s,r.items)}]`;else if(r.properties){let a=Object.keys(r.properties).map(l=>{var u;return` "${l}": ${W(s,(u=r.properties)==null?void 0:u[l])}`}).join(`,
18
+ `);a.length>0?o+=`{
19
+ ${a}
20
+ }`:o+="{}"}else if(r.enum&&r.enum.length>0)r.enum.length>1&&(o+=r.enum[0]);else if(r.type)if(r.example)o+=JSON.stringify(r.example);else{let p=h=>{let a="";if(typeof h=="string")["string","integer","number","array","boolean","null"].includes(h)?["integer","number"].includes(h)?a+="123":h==="array"?a+="[]":h==="boolean"?a+="true":h==="null"?a+="null":a+=`"${h}"`:h==="object"&&(a+="{}");else if(Array.isArray(h)){let l=h.map(u=>p(u));l.filter(u=>u!==""),l.length>1&&(a+=l.join("|"))}else a+="any";return a};o=p(r.type)}}else o="string";return o};j&&!isNaN(j)&&j>0&&(process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||(Oe[i]&&clearTimeout(Oe[i]),Oe[i]=setTimeout(()=>dt(n,i,e,j),j)));let ft=nt(i);if((0,at.default)(ft,f))return;st(i,f);let ue="",H="",G={};f.components&&Object.keys(f.components).forEach(s=>{if(["schemas","responses","parameters","examples","requestBodies","headers","links","callbacks"].includes(s)){let r=f.components[s],I={},$={};Object.keys(r).forEach(p=>{var l;let h=(l=r[p])!=null&&l.schema?r[p].schema:r[p],a=`${U(f,h,"",!0,{noSharedImport:!0,useComponentName:["parameters"].includes(s)})}`;if(a){let u=p.split("."),T=I,t=$;for(let m=0;m<u.length;m++){let b=u[m];m<u.length-1?(b in T||(T[b]={},t[b]={}),T=T[b],t=t[b]):(T[b]=a,t[b]=h)}}}),Object.keys(I).forEach(p=>{var u,T,t,m;let h=Ce(p),a=I[p],l="";!((T=(u=e==null?void 0:e.types)==null?void 0:u.doc)!=null&&T.disable)&&p in r&&((t=r[p])!=null&&t.description)&&(l=" * "+r[p].description.split(`
21
+ `).filter(b=>b.trim()!=="").join(`
22
+ *${" ".repeat(1)}`)),G[p]=((m=G[p])!=null?m:"")+(l?`/**
23
+ ${l}
24
+ */
25
+ `:"")+"export type "+h+" = "+(typeof a=="string"?a:Z(a))+`;
26
+ `})}});let xe=s=>{let r="";if(s.content){let I=Object.keys(s.content);I[0]&&s.content[I[0]].schema&&(r+=`${U(f,s.content[I[0]].schema,"")}`)}return r},ht=s=>{var r,I,$,o,p;if((I=(r=e==null?void 0:e.endpoints)==null?void 0:r.value)!=null&&I.replaceWords&&Array.isArray(e==null?void 0:e.endpoints.value.replaceWords)){let h=s;return(p=(o=($=e==null?void 0:e.endpoints)==null?void 0:$.value)==null?void 0:o.replaceWords)==null||p.forEach((a,l)=>{let u=new RegExp(a.replace,"g");h=h.replace(u,a.with||"")}),h}else return s},ct=(s,r,I=[])=>{var p,h;let $=(p=e==null?void 0:e.endpoints)==null?void 0:p.exclude,o=(h=e==null?void 0:e.endpoints)==null?void 0:h.include;if(o){let a=o.tags&&o.tags.length>0?I.some(u=>o.tags.includes(u)):!0,l=o.endpoints&&o.endpoints.length>0?o.endpoints.some(u=>{let T=!u.method||u.method.toLowerCase()===r.toLowerCase();return u.path?s===u.path&&T:u.regex?new RegExp(u.regex).test(s)&&T:!1}):!0;if(!a||!l)return!0}return!!($&&($.tags&&$.tags.length>0&&I.some(l=>$.tags.includes(l))||$.endpoints&&$.endpoints.length>0&&$.endpoints.some(l=>{let u=!l.method||l.method.toLowerCase()===r.toLowerCase();return l.path?s===l.path&&u:l.regex?new RegExp(l.regex).test(s)&&u:!1})))};if(Object.keys(f.paths||{}).forEach(s=>{let r=f.paths[s];Object.keys(r).forEach($=>{var ne,Re,ve,Fe,ke,qe,Pe,Be,Je,Me,Ue,Le,ze,Ke,Ve,We,Ye,Ge,Qe,Ze,He,Xe,De,_e;let o=$,p=he(s,o),h=((ne=r[o])==null?void 0:ne.tags)||[];if(ct(s,o,h))return;let a=r[o],l=de({method:o,path:s,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId,tags:h,parameters:a==null?void 0:a.parameters,requestBody:a==null?void 0:a.requestBody,responses:a==null?void 0:a.responses});B[l]||(B[l]={endpoints:"",types:""});let u=((ve=(Re=e==null?void 0:e.endpoints)==null?void 0:Re.value)!=null&&ve.includeServer?je:"")+p.pathParts.map(y=>(y[0]==="{"&&y[y.length-1]==="}"?y=`\${${y.replace(/{/,"").replace(/}/,"")}}`:y[0]==="<"&&y[y.length-1]===">"?y=`\${${y.replace(/</,"").replace(/>/,"")}}`:y[0]===":"&&(y=`\${${y.replace(/:/,"")}}`),y)).join("/"),T=`"${u}"`;p.variables.length>0&&(T=`(${p.variables.map(d=>`${d}:string`).join(",")})=> \`${u}\``),T=ht(T);let t=r[o],m="";if(t!=null&&t.parameters&&((t==null?void 0:t.parameters).forEach((d,R)=>{(d.$ref||d.in==="query"&&d.name)&&(m+=`${U(f,d.$ref?d:d.schema,d.name||"",d.required)}`)}),m)){m=`{
27
+ ${m}}`;let d=`${p.name}Query`;if((ke=(Fe=e==null?void 0:e.types)==null?void 0:Fe.name)!=null&&ke.useOperationId&&(t!=null&&t.operationId)&&(d=`${t.operationId}Query`),d=V(`${L}${d}`),(Pe=(qe=e==null?void 0:e.types)==null?void 0:qe.name)!=null&&Pe.format){let J=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"query",method:o,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},d);J&&(d=`${L}${J}`)}let R=`export type ${d} = ${m};
28
+ `;e!=null&&e.folderSplit?B[l].types+=R:H+=R}let b=t==null?void 0:t.requestBody,S="";if(b&&(S=xe(b),S)){let y=`${p.name}DTO`;if((Je=(Be=e==null?void 0:e.types)==null?void 0:Be.name)!=null&&Je.useOperationId&&(t!=null&&t.operationId)&&(y=`${t.operationId}DTO`),y=V(`${L}${y}`),(Ue=(Me=e==null?void 0:e.types)==null?void 0:Me.name)!=null&&Ue.format){let R=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"dto",method:o,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},y);R&&(y=`${L}${R}`)}let d=`export type ${y} = ${S};
29
+ `;e!=null&&e.folderSplit?B[l].types+=d:H+=d}let w={},N="";if(t!=null&&t.responses){let y=t==null?void 0:t.responses;Object.keys(y).forEach(R=>{var J,M,v,k;if(N=xe(y[R]),w[R]=N,N){let A=`${p.name}${R}Response`;if((M=(J=e==null?void 0:e.types)==null?void 0:J.name)!=null&&M.useOperationId&&(t!=null&&t.operationId)&&(A=`${t.operationId}${R}Response`),A=V(`${L}${A}`),(k=(v=e==null?void 0:e.types)==null?void 0:v.name)!=null&&k.format){let _=e==null?void 0:e.types.name.format("endpoint",{code:R,type:"response",method:o,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},A);_&&(A=`${L}${_}`)}let K=`export type ${A} = ${N};
30
+ `;e!=null&&e.folderSplit?B[l].types+=K:H+=K}})}let X=y=>!y||!y.length?"":y.map(d=>Object.entries(d).map(([J,M])=>{let v=J,k="";return Array.isArray(M)&&M.length&&(k=`
31
+ - Scopes: [\`${M.join("`, `")}\`]`,v=`**${v}**`),`
32
+ - ${v}${k}`}).join("")).join(`
33
+ `),z=t!=null&&t.security?X(t.security):"",Y="";if(!((ze=(Le=e==null?void 0:e.endpoints)==null?void 0:Le.doc)!=null&&ze.disable)){let y="";if((Ve=(Ke=e==null?void 0:e.endpoints)==null?void 0:Ke.doc)!=null&&Ve.showCurl){let d={},R="",J="";(We=t.requestBody)!=null&&We.content&&Object.keys(t.requestBody.content).forEach(k=>{let A=t.requestBody.content[k].schema;if(A){Array.isArray(d["Content-type"])?d["Content-type"].push(k):d["Content-type"]=[k];let K=W(f,A);K&&(R=K)}}),t!=null&&t.security&&t.security.forEach(v=>{Object.keys(v).forEach(k=>{var K,_;let A=(_=(K=f.components)==null?void 0:K.securitySchemes)==null?void 0:_[k];A&&(A.type==="mutualTLS"?J+=`
34
+ --cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:A.type==="apiKey"?d[(A==null?void 0:A.name)||"X-API-KEY"]="{API_KEY_VALUE}":d.Authorization=`${(A==null?void 0:A.scheme)==="basic"?"Basic":"Bearer"} {${(A==null?void 0:A.scheme)==="basic"?"VALUE":"TOKEN"}}`)})});let M={};Object.keys(d).forEach(v=>{Array.isArray(d[v])?M[v]=d[v].join("; "):M[v]=d[v]}),y=`
35
+ \`\`\`bash
36
+ ${(0,pt.CurlGenerator)({url:je+s,method:o.toUpperCase(),headers:M,body:R})}${J}
37
+ \`\`\``}Y=`/**${t!=null&&t.description?`
38
+ * ${t==null?void 0:t.description} `:""}
39
+ * **Method**: \`${o.toUpperCase()}\`
40
+ * **Summary**: ${(t==null?void 0:t.summary)||""}
41
+ * **Tags**: [${((Ye=t==null?void 0:t.tags)==null?void 0:Ye.join(", "))||""}]
42
+ * **OperationId**: ${(t==null?void 0:t.operationId)||""} ${m?`
43
+ * **Query**: ${ee(m)} `:""}${S?`
44
+ * **DTO**: ${ee(S)} `:""}${N?`
45
+ * **Response**: ${Object.entries(w).map(([d,R])=>`
46
+ - **${d}**: ${ee(R,2)} `).join("")}`:""}${z?`
47
+ * **Security**: ${z}
48
+ `:""}${y}
49
+ */
50
+ `}let Q=(Qe=(Ge=e==null?void 0:e.endpoints)==null?void 0:Ge.name)!=null&&Qe.useOperationId&&((Ze=t==null?void 0:t.operationId)==null?void 0:Ze.length)>0?t.operationId:`${p.name}`;if((Xe=(He=e==null?void 0:e.endpoints)==null?void 0:He.name)!=null&&Xe.format){let y=e==null?void 0:e.endpoints.name.format({method:o,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},Q);y&&(Q=y)}let se={method:`"${o}"`,operationId:`"${t==null?void 0:t.operationId}"`,url:T,tags:(t==null?void 0:t.tags)||[]},D=`${Y}export const ${$t}${Q} = ${((_e=(De=e==null?void 0:e.endpoints)==null?void 0:De.value)==null?void 0:_e.type)==="object"?Z(se):T};
51
+ `;e!=null&&e.folderSplit?B[l].endpoints+=D:ue+=D})}),e!=null&&e.folderSplit){for(let[s,r]of Object.entries(B))if(r.endpoints||r.types){let I=F.default.join(C,s);if(r.endpoints){let $=F.default.join(re,I,"endpoints.ts");yield P.default.promises.mkdir(F.default.dirname($),{recursive:!0}),yield P.default.promises.writeFile($,r.endpoints)}if(r.types){let $=F.default.join(re,I,"types.ts");yield P.default.promises.mkdir(F.default.dirname($),{recursive:!0});let o=Object.values(G).length>0?`import * as Shared from "../shared";
52
+
53
+ ${r.types}`:r.types;yield P.default.promises.writeFile($,o)}}}if(ue.length>0){let s=F.default.join(re,C,"endpoints.ts");yield P.default.promises.mkdir(F.default.dirname(s),{recursive:!0}),yield P.default.promises.writeFile(s,ue)}if(Object.values(G).length>0){let s=F.default.join(re,C,e!=null&&e.folderSplit?"":"types","shared.ts");yield P.default.promises.mkdir(F.default.dirname(s),{recursive:!0}),yield P.default.promises.writeFile(s,Object.values(G).join(`
54
+ `))}if(H.length>0){let s=F.default.join(re,C,"types","index.ts");yield P.default.promises.mkdir(F.default.dirname(s),{recursive:!0}),yield P.default.promises.writeFile(s,`${Object.values(G).length>0?`import * as Shared from "./shared";
55
+
56
+ `:""}${H}`)}}),ut=dt;var me=q(require("path")),yt=q(require("fs"));var be=process.cwd(),St=n=>ae(null,null,function*(){let i;try{require("esbuild-register")}catch(f){throw f}let e=me.default.join(be,"openapi.sync.js"),j=me.default.join(be,"openapi.sync.ts"),O=me.default.join(be,"openapi.sync.json"),x=[e,j,O];try{for(let f of x)yt.default.existsSync(f)&&(i=require(f),Object.keys(i).length===1&&i.default&&(i=i.default))}catch(f){}typeof i=="function"&&(i=i());let E=i;if(!E)throw new Error("No config found");let c=Object.keys(E.api),C=n&&"refetchInterval"in n&&!isNaN(n==null?void 0:n.refetchInterval)?n.refetchInterval:E.refetchInterval;ot();for(let f=0;f<c.length;f+=1){let B=c[f],de=E.api[B];ut(de,B,E,C)}});0&&(module.exports={Init,JSONStringify,capitalize,getEndpointDetails,getNestedValue,isJson,isYamlString,renderTypeRefMD,variableName,variableNameChar,yamlStringToJson});
package/dist/index.mjs ADDED
@@ -0,0 +1,56 @@
1
+ var D=(a=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(a,{get:(m,e)=>(typeof require!="undefined"?require:m)[e]}):a)(function(a){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ne=(a,m,e)=>new Promise((x,A)=>{var j=b=>{try{c(e.next(b))}catch(f){A(f)}},E=b=>{try{c(e.throw(b))}catch(f){A(f)}},c=b=>b.done?x(b.value):Promise.resolve(b.value).then(j,E);c((e=e.apply(a,m)).next())});import J from"fs";import F from"path";var Ot=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ge=/[A-Za-z0-9_$]/;import*as g from"js-yaml";var Qe=a=>["object"].includes(typeof a)&&!(a instanceof Blob),lt=a=>{try{return g.load(a),!0}catch(m){let e=m;if(e instanceof g.YAMLException)return!1;throw e}},Ze=a=>{if(lt(a)){let m=g.load(a),e=JSON.stringify(m,null,2);return JSON.parse(e)}},W=a=>a.substring(0,1).toUpperCase()+a.substring(1),He=(a,m)=>{let e=a.split("/"),x=`${W(m)}`,A=[];return e.forEach(j=>{if(j[0]==="{"&&j[j.length-1]==="}"){let c=j.replace(/{/,"").replace(/}/,"");A.push(c),j=`$${c}`}else if(j[0]==="<"&&j[j.length-1]===">"){let c=j.replace(/</,"").replace(/>/,"");A.push(c),j=`$${c}`}else if(j[0]===":"){let c=j.replace(/:/,"");A.push(c),j=`$${c}`}let E="";j.split("").forEach(c=>{let b=c;Ge.test(c)||(b="/"),E+=b}),E.split("/").forEach(c=>{x+=W(c)})}),{name:x,variables:A,pathParts:e}},_=(a,m=1)=>{let e="{",x=Object.keys(a);for(let A=0;A<x.length;A++){let j=x[A],E=a[j];if(e+=`
2
+ `+" ".repeat(m)+j+": ",Array.isArray(E)){e+="[";for(let c=0;c<E.length;c++){let b=E[c];typeof b=="object"&&b!==null?e+=_(b,m+1):e+=typeof b=="string"?`"${b}"`:b,c<E.length-1&&(e+=", ")}e+="]"}else typeof E=="object"&&E!==null?e+=""+_(E,m+1):e+=E.split(`
3
+ `).filter(c=>c.trim()!=="").join(`
4
+ ${" ".repeat(m)}`);A<x.length-1&&(e+=", ")}return e+=`
5
+ ${" ".repeat(m-1)}}`,e},oe=(a,m=1)=>`
6
+ \`\`\`typescript
7
+ ${" ".repeat(m)} ${a.split(`
8
+ `).filter(e=>e.trim()!=="").join(`
9
+ ${" ".repeat(m)} `)}
10
+ \`\`\``;function jt(a,m){return m.split(".").reduce((x,A)=>x&&x[A]!==void 0?x[A]:void 0,a)}import mt from"lodash.isequal";import et from"lodash.get";import dt from"axios";import ut from"axios-retry";import{bundleFromString as yt,createConfig as $t}from"@redocly/openapi-core";import pt from"path";import pe from"fs";var ae=pt.join(__dirname,"../","../db.json");pe.existsSync(ae)||pe.writeFileSync(ae,"{}");var me={};try{me=D(ae)}catch(a){me={}}var ee=me||{},Xe=a=>{pe.writeFileSync(ae,JSON.stringify(a))},De=(a,m)=>{ee[a]=m,Xe(ee)},_e=a=>ee[a],ge=()=>{ee={},Xe(ee)};import{CurlGenerator as ft}from"curl-generator";var te=process.cwd(),de={},tt=dt.create({timeout:6e4});ut(tt,{retries:20,retryCondition:a=>a.code==="ECONNABORTED"||a.message.includes("Network Error"),retryDelay:a=>a*1e3});var rt=(a,m,e,x)=>ne(null,null,function*(){var ce,Oe,Ie,be,je,Ce;let A=yield tt.get(a),j=yield $t({extends:["minimal"]}),E=JSON.stringify(Qe(A.data)?A.data:Ze(A.data)),c=yield yt({source:E,config:j}),b=F.join((e==null?void 0:e.folder)||"",m),f=c.bundle.parsed,q={},ie=s=>{var r,O;if((r=e==null?void 0:e.folderSplit)!=null&&r.customFolder){let $=e.folderSplit.customFolder(s);if($)return $}return(O=e==null?void 0:e.folderSplit)!=null&&O.byTags&&s.tags&&s.tags.length>0?s.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},$e=typeof(e==null?void 0:e.server)=="string"?e==null?void 0:e.server:((Oe=(ce=f==null?void 0:f.servers)==null?void 0:ce[(e==null?void 0:e.server)||0])==null?void 0:Oe.url)||"",U=typeof((be=(Ie=e==null?void 0:e.types)==null?void 0:Ie.name)==null?void 0:be.prefix)=="string"?e==null?void 0:e.types.name.prefix:"I",nt=typeof((Ce=(je=e==null?void 0:e.endpoints)==null?void 0:je.name)==null?void 0:Ce.prefix)=="string"?e==null?void 0:e.endpoints.name.prefix:"",fe=(s,r)=>{var $,n;let O=W(s);if((n=($=e==null?void 0:e.types)==null?void 0:$.name)!=null&&n.format){let l=e==null?void 0:e.types.name.format("shared",{name:s},O);if(l)return`${U}${l}`}return`${U}${O}`},M=(s,r,O,$,n,l=0)=>{let h="",o="",i="";if(r){if(r.$ref)if(r.$ref[0]==="#"){let p=(r.$ref||"").split("/");p.shift(),[...p].pop();let w=et(s,p,null);if(w){w!=null&&w.name&&(h=w.name),o=p[p.length-1];let N=fe(o);N.includes(".")&&(N=N.split(".").map((L,V)=>V===0?L:`["${L}"]`).join("")),i+=`${n!=null&&n.noSharedImport?"":"Shared."}${N}`}}else i+="";else if(r.anyOf)i+=`(${r.anyOf.map(p=>M(s,p,"",$,n)).filter(p=>!!p).join("|")})`;else if(r.oneOf)i+=`(${r.oneOf.map(p=>M(s,p,"",$,n)).filter(p=>!!p).join("|")})`;else if(r.allOf)i+=`(${r.allOf.map(p=>M(s,p,"",$,n)).filter(p=>!!p).join("&")})`;else if(r.items)i+=`${M(s,r.items,"",!1,n)}[]`;else if(r.properties){let p=Object.keys(r.properties),I=r.required||[],S="";p.forEach(w=>{var Z,L,V,G,re,H;let N="";!((L=(Z=e==null?void 0:e.types)==null?void 0:Z.doc)!=null&&L.disable)&&((G=(V=r.properties)==null?void 0:V[w])!=null&&G.description)&&(N=" * "+((re=r.properties)==null?void 0:re[w].description.split(`
11
+ `).filter(se=>se.trim()!=="").join(`
12
+ *${" ".repeat(1)}`))),S+=(N?`/**
13
+ ${N}
14
+ */
15
+ `:"")+`${M(s,(H=r.properties)==null?void 0:H[w],w,I.includes(w),n,l+1)}`}),S.length>0?i+=`{
16
+ ${" ".repeat(l)}${S}${" ".repeat(l)}}`:i+="{[k: string]: any}"}else if(r.enum&&r.enum.length>0)r.enum.length>1&&(i+="("),r.enum.map(p=>JSON.stringify(p)).filter(p=>!!p).forEach((p,I)=>{i+=`${I===0?"":"|"}${p}`}),r.enum.length>1&&(i+=")");else if(r.type){let p=I=>{let S="";if(typeof I=="string")["string","integer","number","array","boolean","null"].includes(I)?["integer","number"].includes(I)?S+="number":I==="array"?S+="any[]":S+=I:I==="object"&&(r.additionalProperties?S+=`{[k: string]: ${M(s,r.additionalProperties,"",!0,n)||"any"}}`:S+="{[k: string]: any}");else if(Array.isArray(I)){let w=I.map(N=>p(N));w.filter(N=>N!==""),w.length>1&&(S+="("+w.join("|")+")")}else S+="any";return S};i=p(r.type)}}else i="string";let u=h||O;n!=null&&n.useComponentName&&!u&&(u=o);let T=u?` "${u}"${$?"":"?"}: `:"",t=r!=null&&r.nullable?" | null":"";return i.length>0?`${T}${i}${t}${u?`;
17
+ `:""}`:""},K=(s,r)=>{let O="",$="",n="";if(r){if(r.$ref)if(r.$ref[0]==="#"){let l=(r.$ref||"").split("/");l.shift();let o=et(s,l,null);o&&(o!=null&&o.name&&(O=o.name),$=l[l.length-1],n+=K(s,o))}else n+="";else if(r.anyOf)n+=K(s,r.anyOf[0]);else if(r.oneOf)n+=K(s,r.oneOf[0]);else if(r.allOf)n+=`{${r.allOf.map(l=>`...(${K(s,l)})`).join(",")}}`;else if(r.items)n+=`[${K(s,r.items)}]`;else if(r.properties){let o=Object.keys(r.properties).map(i=>{var u;return` "${i}": ${K(s,(u=r.properties)==null?void 0:u[i])}`}).join(`,
18
+ `);o.length>0?n+=`{
19
+ ${o}
20
+ }`:n+="{}"}else if(r.enum&&r.enum.length>0)r.enum.length>1&&(n+=r.enum[0]);else if(r.type)if(r.example)n+=JSON.stringify(r.example);else{let l=h=>{let o="";if(typeof h=="string")["string","integer","number","array","boolean","null"].includes(h)?["integer","number"].includes(h)?o+="123":h==="array"?o+="[]":h==="boolean"?o+="true":h==="null"?o+="null":o+=`"${h}"`:h==="object"&&(o+="{}");else if(Array.isArray(h)){let i=h.map(u=>l(u));i.filter(u=>u!==""),i.length>1&&(o+=i.join("|"))}else o+="any";return o};n=l(r.type)}}else n="string";return n};x&&!isNaN(x)&&x>0&&(process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||(de[m]&&clearTimeout(de[m]),de[m]=setTimeout(()=>rt(a,m,e,x),x)));let ot=_e(m);if(mt(ot,f))return;De(m,f);let le="",Q="",Y={};f.components&&Object.keys(f.components).forEach(s=>{if(["schemas","responses","parameters","examples","requestBodies","headers","links","callbacks"].includes(s)){let r=f.components[s],O={},$={};Object.keys(r).forEach(l=>{var i;let h=(i=r[l])!=null&&i.schema?r[l].schema:r[l],o=`${M(f,h,"",!0,{noSharedImport:!0,useComponentName:["parameters"].includes(s)})}`;if(o){let u=l.split("."),T=O,t=$;for(let p=0;p<u.length;p++){let I=u[p];p<u.length-1?(I in T||(T[I]={},t[I]={}),T=T[I],t=t[I]):(T[I]=o,t[I]=h)}}}),Object.keys(O).forEach(l=>{var u,T,t,p;let h=fe(l),o=O[l],i="";!((T=(u=e==null?void 0:e.types)==null?void 0:u.doc)!=null&&T.disable)&&l in r&&((t=r[l])!=null&&t.description)&&(i=" * "+r[l].description.split(`
21
+ `).filter(I=>I.trim()!=="").join(`
22
+ *${" ".repeat(1)}`)),Y[l]=((p=Y[l])!=null?p:"")+(i?`/**
23
+ ${i}
24
+ */
25
+ `:"")+"export type "+h+" = "+(typeof o=="string"?o:_(o))+`;
26
+ `})}});let he=s=>{let r="";if(s.content){let O=Object.keys(s.content);O[0]&&s.content[O[0]].schema&&(r+=`${M(f,s.content[O[0]].schema,"")}`)}return r},at=s=>{var r,O,$,n,l;if((O=(r=e==null?void 0:e.endpoints)==null?void 0:r.value)!=null&&O.replaceWords&&Array.isArray(e==null?void 0:e.endpoints.value.replaceWords)){let h=s;return(l=(n=($=e==null?void 0:e.endpoints)==null?void 0:$.value)==null?void 0:n.replaceWords)==null||l.forEach((o,i)=>{let u=new RegExp(o.replace,"g");h=h.replace(u,o.with||"")}),h}else return s},it=(s,r,O=[])=>{var l,h;let $=(l=e==null?void 0:e.endpoints)==null?void 0:l.exclude,n=(h=e==null?void 0:e.endpoints)==null?void 0:h.include;if(n){let o=n.tags&&n.tags.length>0?O.some(u=>n.tags.includes(u)):!0,i=n.endpoints&&n.endpoints.length>0?n.endpoints.some(u=>{let T=!u.method||u.method.toLowerCase()===r.toLowerCase();return u.path?s===u.path&&T:u.regex?new RegExp(u.regex).test(s)&&T:!1}):!0;if(!o||!i)return!0}return!!($&&($.tags&&$.tags.length>0&&O.some(i=>$.tags.includes(i))||$.endpoints&&$.endpoints.length>0&&$.endpoints.some(i=>{let u=!i.method||i.method.toLowerCase()===r.toLowerCase();return i.path?s===i.path&&u:i.regex?new RegExp(i.regex).test(s)&&u:!1})))};if(Object.keys(f.paths||{}).forEach(s=>{let r=f.paths[s];Object.keys(r).forEach($=>{var se,xe,Ae,Ee,Te,Se,we,Ne,Re,ve,Fe,ke,qe,Pe,Be,Je,Me,Ue,Le,ze,Ke,Ve,We,Ye;let n=$,l=He(s,n),h=((se=r[n])==null?void 0:se.tags)||[];if(it(s,n,h))return;let o=r[n],i=ie({method:n,path:s,summary:o==null?void 0:o.summary,operationId:o==null?void 0:o.operationId,tags:h,parameters:o==null?void 0:o.parameters,requestBody:o==null?void 0:o.requestBody,responses:o==null?void 0:o.responses});q[i]||(q[i]={endpoints:"",types:""});let u=((Ae=(xe=e==null?void 0:e.endpoints)==null?void 0:xe.value)!=null&&Ae.includeServer?$e:"")+l.pathParts.map(y=>(y[0]==="{"&&y[y.length-1]==="}"?y=`\${${y.replace(/{/,"").replace(/}/,"")}}`:y[0]==="<"&&y[y.length-1]===">"?y=`\${${y.replace(/</,"").replace(/>/,"")}}`:y[0]===":"&&(y=`\${${y.replace(/:/,"")}}`),y)).join("/"),T=`"${u}"`;l.variables.length>0&&(T=`(${l.variables.map(d=>`${d}:string`).join(",")})=> \`${u}\``),T=at(T);let t=r[n],p="";if(t!=null&&t.parameters&&((t==null?void 0:t.parameters).forEach((d,R)=>{(d.$ref||d.in==="query"&&d.name)&&(p+=`${M(f,d.$ref?d:d.schema,d.name||"",d.required)}`)}),p)){p=`{
27
+ ${p}}`;let d=`${l.name}Query`;if((Te=(Ee=e==null?void 0:e.types)==null?void 0:Ee.name)!=null&&Te.useOperationId&&(t!=null&&t.operationId)&&(d=`${t.operationId}Query`),d=W(`${U}${d}`),(we=(Se=e==null?void 0:e.types)==null?void 0:Se.name)!=null&&we.format){let P=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"query",method:n,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},d);P&&(d=`${U}${P}`)}let R=`export type ${d} = ${p};
28
+ `;e!=null&&e.folderSplit?q[i].types+=R:Q+=R}let I=t==null?void 0:t.requestBody,S="";if(I&&(S=he(I),S)){let y=`${l.name}DTO`;if((Re=(Ne=e==null?void 0:e.types)==null?void 0:Ne.name)!=null&&Re.useOperationId&&(t!=null&&t.operationId)&&(y=`${t.operationId}DTO`),y=W(`${U}${y}`),(Fe=(ve=e==null?void 0:e.types)==null?void 0:ve.name)!=null&&Fe.format){let R=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"dto",method:n,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},y);R&&(y=`${U}${R}`)}let d=`export type ${y} = ${S};
29
+ `;e!=null&&e.folderSplit?q[i].types+=d:Q+=d}let w={},N="";if(t!=null&&t.responses){let y=t==null?void 0:t.responses;Object.keys(y).forEach(R=>{var P,B,v,k;if(N=he(y[R]),w[R]=N,N){let C=`${l.name}${R}Response`;if((B=(P=e==null?void 0:e.types)==null?void 0:P.name)!=null&&B.useOperationId&&(t!=null&&t.operationId)&&(C=`${t.operationId}${R}Response`),C=W(`${U}${C}`),(k=(v=e==null?void 0:e.types)==null?void 0:v.name)!=null&&k.format){let X=e==null?void 0:e.types.name.format("endpoint",{code:R,type:"response",method:n,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},C);X&&(C=`${U}${X}`)}let z=`export type ${C} = ${N};
30
+ `;e!=null&&e.folderSplit?q[i].types+=z:Q+=z}})}let Z=y=>!y||!y.length?"":y.map(d=>Object.entries(d).map(([P,B])=>{let v=P,k="";return Array.isArray(B)&&B.length&&(k=`
31
+ - Scopes: [\`${B.join("`, `")}\`]`,v=`**${v}**`),`
32
+ - ${v}${k}`}).join("")).join(`
33
+ `),L=t!=null&&t.security?Z(t.security):"",V="";if(!((qe=(ke=e==null?void 0:e.endpoints)==null?void 0:ke.doc)!=null&&qe.disable)){let y="";if((Be=(Pe=e==null?void 0:e.endpoints)==null?void 0:Pe.doc)!=null&&Be.showCurl){let d={},R="",P="";(Je=t.requestBody)!=null&&Je.content&&Object.keys(t.requestBody.content).forEach(k=>{let C=t.requestBody.content[k].schema;if(C){Array.isArray(d["Content-type"])?d["Content-type"].push(k):d["Content-type"]=[k];let z=K(f,C);z&&(R=z)}}),t!=null&&t.security&&t.security.forEach(v=>{Object.keys(v).forEach(k=>{var z,X;let C=(X=(z=f.components)==null?void 0:z.securitySchemes)==null?void 0:X[k];C&&(C.type==="mutualTLS"?P+=`
34
+ --cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:C.type==="apiKey"?d[(C==null?void 0:C.name)||"X-API-KEY"]="{API_KEY_VALUE}":d.Authorization=`${(C==null?void 0:C.scheme)==="basic"?"Basic":"Bearer"} {${(C==null?void 0:C.scheme)==="basic"?"VALUE":"TOKEN"}}`)})});let B={};Object.keys(d).forEach(v=>{Array.isArray(d[v])?B[v]=d[v].join("; "):B[v]=d[v]}),y=`
35
+ \`\`\`bash
36
+ ${ft({url:$e+s,method:n.toUpperCase(),headers:B,body:R})}${P}
37
+ \`\`\``}V=`/**${t!=null&&t.description?`
38
+ * ${t==null?void 0:t.description} `:""}
39
+ * **Method**: \`${n.toUpperCase()}\`
40
+ * **Summary**: ${(t==null?void 0:t.summary)||""}
41
+ * **Tags**: [${((Me=t==null?void 0:t.tags)==null?void 0:Me.join(", "))||""}]
42
+ * **OperationId**: ${(t==null?void 0:t.operationId)||""} ${p?`
43
+ * **Query**: ${oe(p)} `:""}${S?`
44
+ * **DTO**: ${oe(S)} `:""}${N?`
45
+ * **Response**: ${Object.entries(w).map(([d,R])=>`
46
+ - **${d}**: ${oe(R,2)} `).join("")}`:""}${L?`
47
+ * **Security**: ${L}
48
+ `:""}${y}
49
+ */
50
+ `}let G=(Le=(Ue=e==null?void 0:e.endpoints)==null?void 0:Ue.name)!=null&&Le.useOperationId&&((ze=t==null?void 0:t.operationId)==null?void 0:ze.length)>0?t.operationId:`${l.name}`;if((Ve=(Ke=e==null?void 0:e.endpoints)==null?void 0:Ke.name)!=null&&Ve.format){let y=e==null?void 0:e.endpoints.name.format({method:n,path:s,summary:t==null?void 0:t.summary,operationId:t==null?void 0:t.operationId},G);y&&(G=y)}let re={method:`"${n}"`,operationId:`"${t==null?void 0:t.operationId}"`,url:T,tags:(t==null?void 0:t.tags)||[]},H=`${V}export const ${nt}${G} = ${((Ye=(We=e==null?void 0:e.endpoints)==null?void 0:We.value)==null?void 0:Ye.type)==="object"?_(re):T};
51
+ `;e!=null&&e.folderSplit?q[i].endpoints+=H:le+=H})}),e!=null&&e.folderSplit){for(let[s,r]of Object.entries(q))if(r.endpoints||r.types){let O=F.join(b,s);if(r.endpoints){let $=F.join(te,O,"endpoints.ts");yield J.promises.mkdir(F.dirname($),{recursive:!0}),yield J.promises.writeFile($,r.endpoints)}if(r.types){let $=F.join(te,O,"types.ts");yield J.promises.mkdir(F.dirname($),{recursive:!0});let n=Object.values(Y).length>0?`import * as Shared from "../shared";
52
+
53
+ ${r.types}`:r.types;yield J.promises.writeFile($,n)}}}if(le.length>0){let s=F.join(te,b,"endpoints.ts");yield J.promises.mkdir(F.dirname(s),{recursive:!0}),yield J.promises.writeFile(s,le)}if(Object.values(Y).length>0){let s=F.join(te,b,e!=null&&e.folderSplit?"":"types","shared.ts");yield J.promises.mkdir(F.dirname(s),{recursive:!0}),yield J.promises.writeFile(s,Object.values(Y).join(`
54
+ `))}if(Q.length>0){let s=F.join(te,b,"types","index.ts");yield J.promises.mkdir(F.dirname(s),{recursive:!0}),yield J.promises.writeFile(s,`${Object.values(Y).length>0?`import * as Shared from "./shared";
55
+
56
+ `:""}${Q}`)}}),st=rt;import ue from"path";import ht from"fs";var ye=process.cwd(),Wt=a=>ne(null,null,function*(){let m;try{D("esbuild-register")}catch(f){throw f}let e=ue.join(ye,"openapi.sync.js"),x=ue.join(ye,"openapi.sync.ts"),A=ue.join(ye,"openapi.sync.json"),j=[e,x,A];try{for(let f of j)ht.existsSync(f)&&(m=D(f),Object.keys(m).length===1&&m.default&&(m=m.default))}catch(f){}typeof m=="function"&&(m=m());let E=m;if(!E)throw new Error("No config found");let c=Object.keys(E.api),b=a&&"refetchInterval"in a&&!isNaN(a==null?void 0:a.refetchInterval)?a.refetchInterval:E.refetchInterval;ge();for(let f=0;f<c.length;f+=1){let q=c[f],ie=E.api[q];st(ie,q,E,b)}});export{Wt as Init,_ as JSONStringify,W as capitalize,He as getEndpointDetails,jt as getNestedValue,Qe as isJson,lt as isYamlString,oe as renderTypeRefMD,Ot as variableName,Ge as variableNameChar,Ze as yamlStringToJson};
package/package.json CHANGED
@@ -1,31 +1,9 @@
1
1
  {
2
2
  "name": "openapi-sync",
3
- "version": "2.1.10",
3
+ "version": "2.1.12",
4
4
  "description": "A developer-friendly tool designed to keep your API up-to-date by leveraging OpenAPI schemas. It automates the generation of endpoint URIs and type definitions, including shared types, directly from your OpenAPI specification.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "require": "./dist/index.js",
11
- "import": "./dist/index.js"
12
- },
13
- "./types": {
14
- "types": "./dist/types.d.ts",
15
- "require": "./dist/types.js",
16
- "import": "./dist/types.js"
17
- },
18
- "./helpers": {
19
- "types": "./dist/helpers.d.ts",
20
- "require": "./dist/helpers.js",
21
- "import": "./dist/helpers.js"
22
- },
23
- "./regex": {
24
- "types": "./dist/regex.d.ts",
25
- "require": "./dist/regex.js",
26
- "import": "./dist/regex.js"
27
- }
28
- },
29
7
  "bin": {
30
8
  "openapi-sync": "./bin/cli.js"
31
9
  },
@@ -59,16 +37,17 @@
59
37
  "url": "https://github.com/akintomiwa-fisayo/openapi-sync/issues"
60
38
  },
61
39
  "scripts": {
62
- "test": "echo \"Error: no test specified\"",
63
- "build": "rm -rf dist && tsc",
64
- "publish-package": "npm run build && npm publish",
65
- "start": "npm run build && openapi-sync"
40
+ "build-tsc": "rm -rf dist && tsc",
41
+ "build": "rm -rf dist && tsup",
42
+ "publish-package": "npm run build && npm publish"
66
43
  },
67
44
  "author": "P-Technologies",
68
45
  "license": "ISC",
69
46
  "devDependencies": {
70
47
  "@types/js-yaml": "^4.0.9",
71
48
  "@types/lodash": "^4.17.7",
49
+ "@types/lodash.get": "^4.4.9",
50
+ "@types/lodash.isequal": "^4.5.8",
72
51
  "@types/node": "^22.1.0",
73
52
  "typescript": "^5.5.4"
74
53
  },
@@ -76,10 +55,12 @@
76
55
  "@redocly/openapi-core": "^1.19.0",
77
56
  "axios": "^1.7.3",
78
57
  "axios-retry": "^4.5.0",
79
- "esbuild-register": "^3.6.0",
80
58
  "curl-generator": "^0.4.2",
59
+ "esbuild-register": "^3.6.0",
81
60
  "js-yaml": "^4.1.0",
82
- "lodash": "^4.17.21",
61
+ "lodash.get": "^4.4.2",
62
+ "lodash.isequal": "^4.5.0",
63
+ "tsup": "^8.5.0",
83
64
  "yargs": "^17.7.2"
84
65
  }
85
- }
66
+ }