@acrool/rtk-query-codegen-openapi 0.0.1

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/index.js ADDED
@@ -0,0 +1,877 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ generateEndpoints: () => generateEndpoints,
34
+ parseConfig: () => parseConfig
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_node_fs = __toESM(require("node:fs"));
38
+ var import_node_module = require("node:module");
39
+ var import_node_path3 = __toESM(require("node:path"));
40
+
41
+ // src/generate.ts
42
+ var import_node_path2 = __toESM(require("node:path"));
43
+ var import_generate3 = __toESM(require("oazapfts/generate"));
44
+ var import_typescript4 = __toESM(require("typescript"));
45
+
46
+ // src/utils/factory.ts
47
+ var import_typescript = __toESM(require("typescript"));
48
+ var import_semver = __toESM(require("semver"));
49
+ var originalFactory = import_typescript.default.factory;
50
+ function createImportSpecifier(propertyName, name) {
51
+ if (import_semver.default.satisfies(import_typescript.default.version, ">= 4.5"))
52
+ return originalFactory.createImportSpecifier(false, propertyName, name);
53
+ return originalFactory.createImportSpecifier(propertyName, name);
54
+ }
55
+ function createExportSpecifier(propertyName, name) {
56
+ if (import_semver.default.satisfies(import_typescript.default.version, ">= 4.5"))
57
+ return originalFactory.createExportSpecifier(false, propertyName, name);
58
+ return originalFactory.createExportSpecifier(propertyName, name);
59
+ }
60
+ var factory = {
61
+ ...originalFactory,
62
+ createImportSpecifier,
63
+ createExportSpecifier
64
+ };
65
+
66
+ // src/codegen.ts
67
+ var import_typescript2 = __toESM(require("typescript"));
68
+ var defaultEndpointBuilder = factory.createIdentifier("build");
69
+ function generateObjectProperties(obj) {
70
+ return Object.entries(obj).filter(([_, v]) => v).map(([k, v]) => factory.createPropertyAssignment(factory.createIdentifier(k), v));
71
+ }
72
+ function generateImportNode(pkg, namedImports, defaultImportName) {
73
+ return factory.createImportDeclaration(
74
+ void 0,
75
+ factory.createImportClause(
76
+ false,
77
+ defaultImportName !== void 0 ? factory.createIdentifier(defaultImportName) : void 0,
78
+ factory.createNamedImports(
79
+ Object.entries(namedImports).map(
80
+ ([propertyName, name]) => factory.createImportSpecifier(
81
+ name === propertyName ? void 0 : factory.createIdentifier(propertyName),
82
+ factory.createIdentifier(name)
83
+ )
84
+ )
85
+ )
86
+ ),
87
+ factory.createStringLiteral(pkg)
88
+ );
89
+ }
90
+ function generateCreateApiCall({
91
+ endpointBuilder = defaultEndpointBuilder,
92
+ endpointDefinitions,
93
+ tag
94
+ }) {
95
+ const injectEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(
96
+ generateObjectProperties({
97
+ endpoints: factory.createArrowFunction(
98
+ void 0,
99
+ void 0,
100
+ [factory.createParameterDeclaration(void 0, void 0, endpointBuilder, void 0, void 0, void 0)],
101
+ void 0,
102
+ factory.createToken(import_typescript2.default.SyntaxKind.EqualsGreaterThanToken),
103
+ factory.createParenthesizedExpression(endpointDefinitions)
104
+ ),
105
+ overrideExisting: factory.createFalse()
106
+ }),
107
+ true
108
+ );
109
+ if (tag) {
110
+ const enhanceEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(
111
+ [factory.createShorthandPropertyAssignment(factory.createIdentifier("addTagTypes"), void 0)],
112
+ true
113
+ );
114
+ return factory.createVariableStatement(
115
+ void 0,
116
+ factory.createVariableDeclarationList(
117
+ [
118
+ factory.createVariableDeclaration(
119
+ factory.createIdentifier("injectedRtkApi"),
120
+ void 0,
121
+ void 0,
122
+ factory.createCallExpression(
123
+ factory.createPropertyAccessExpression(
124
+ factory.createCallExpression(
125
+ factory.createPropertyAccessExpression(
126
+ factory.createIdentifier("api"),
127
+ factory.createIdentifier("enhanceEndpoints")
128
+ ),
129
+ void 0,
130
+ [enhanceEndpointsObjectLiteralExpression]
131
+ ),
132
+ factory.createIdentifier("injectEndpoints")
133
+ ),
134
+ void 0,
135
+ [injectEndpointsObjectLiteralExpression]
136
+ )
137
+ )
138
+ ],
139
+ import_typescript2.default.NodeFlags.Const
140
+ )
141
+ );
142
+ }
143
+ return factory.createVariableStatement(
144
+ void 0,
145
+ factory.createVariableDeclarationList(
146
+ [
147
+ factory.createVariableDeclaration(
148
+ factory.createIdentifier("injectedRtkApi"),
149
+ void 0,
150
+ void 0,
151
+ factory.createCallExpression(
152
+ factory.createPropertyAccessExpression(
153
+ factory.createIdentifier("api"),
154
+ factory.createIdentifier("injectEndpoints")
155
+ ),
156
+ void 0,
157
+ [injectEndpointsObjectLiteralExpression]
158
+ )
159
+ )
160
+ ],
161
+ import_typescript2.default.NodeFlags.Const
162
+ )
163
+ );
164
+ }
165
+ function generateEndpointDefinition({
166
+ operationName,
167
+ type,
168
+ Response,
169
+ QueryArg,
170
+ queryFn,
171
+ endpointBuilder = defaultEndpointBuilder,
172
+ extraEndpointsProps,
173
+ tags
174
+ }) {
175
+ const objectProperties = generateObjectProperties({ query: queryFn, ...extraEndpointsProps });
176
+ if (tags.length > 0) {
177
+ objectProperties.push(
178
+ factory.createPropertyAssignment(
179
+ factory.createIdentifier(type === "query" ? "providesTags" : "invalidatesTags"),
180
+ factory.createArrayLiteralExpression(
181
+ tags.map((tag) => factory.createStringLiteral(tag)),
182
+ false
183
+ )
184
+ )
185
+ );
186
+ }
187
+ return factory.createPropertyAssignment(
188
+ factory.createIdentifier(operationName),
189
+ factory.createCallExpression(
190
+ factory.createPropertyAccessExpression(endpointBuilder, factory.createIdentifier(type)),
191
+ [Response, QueryArg],
192
+ [factory.createObjectLiteralExpression(objectProperties, true)]
193
+ )
194
+ );
195
+ }
196
+ function generateTagTypes({ addTagTypes }) {
197
+ return factory.createVariableStatement(
198
+ [factory.createModifier(import_typescript2.default.SyntaxKind.ExportKeyword)],
199
+ factory.createVariableDeclarationList(
200
+ [
201
+ factory.createVariableDeclaration(
202
+ factory.createIdentifier("addTagTypes"),
203
+ void 0,
204
+ void 0,
205
+ factory.createAsExpression(
206
+ factory.createArrayLiteralExpression(
207
+ addTagTypes.map((tagType) => factory.createStringLiteral(tagType)),
208
+ true
209
+ ),
210
+ factory.createTypeReferenceNode(factory.createIdentifier("const"), void 0)
211
+ )
212
+ )
213
+ ],
214
+ import_typescript2.default.NodeFlags.Const
215
+ )
216
+ );
217
+ }
218
+
219
+ // src/generators/react-hooks.ts
220
+ var import_typescript3 = __toESM(require("typescript"));
221
+ var import_generate = require("oazapfts/generate");
222
+
223
+ // src/utils/capitalize.ts
224
+ function capitalize(str) {
225
+ return str.replace(str[0], str[0].toUpperCase());
226
+ }
227
+
228
+ // src/types.ts
229
+ var operationKeys = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
230
+
231
+ // src/utils/getOperationDefinitions.ts
232
+ function getOperationDefinitions(v3Doc) {
233
+ return Object.entries(v3Doc.paths).flatMap(
234
+ ([path4, pathItem]) => !pathItem ? [] : Object.entries(pathItem).filter(
235
+ (arg) => operationKeys.includes(arg[0])
236
+ ).map(([verb, operation]) => ({
237
+ path: path4,
238
+ verb,
239
+ pathItem,
240
+ operation
241
+ }))
242
+ );
243
+ }
244
+
245
+ // src/utils/getV3Doc.ts
246
+ var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"));
247
+ var import_swagger2openapi = __toESM(require("swagger2openapi"));
248
+ async function getV3Doc(spec, httpResolverOptions) {
249
+ const doc = await import_swagger_parser.default.bundle(spec, {
250
+ resolve: {
251
+ http: httpResolverOptions
252
+ }
253
+ });
254
+ const isOpenApiV3 = "openapi" in doc && doc.openapi.startsWith("3");
255
+ if (isOpenApiV3) {
256
+ return doc;
257
+ } else {
258
+ const result = await import_swagger2openapi.default.convertObj(doc, {});
259
+ return result.openapi;
260
+ }
261
+ }
262
+
263
+ // src/utils/isQuery.ts
264
+ function isQuery(verb, overrides) {
265
+ if (overrides?.type) {
266
+ return overrides.type === "query";
267
+ }
268
+ return verb === "get";
269
+ }
270
+
271
+ // src/utils/isValidUrl.ts
272
+ function isValidUrl(string) {
273
+ try {
274
+ new URL(string);
275
+ } catch (_) {
276
+ return false;
277
+ }
278
+ return true;
279
+ }
280
+
281
+ // src/utils/prettier.ts
282
+ var import_node_path = __toESM(require("node:path"));
283
+ var import_prettier = __toESM(require("prettier"));
284
+ var EXTENSION_TO_PARSER = {
285
+ ts: "typescript",
286
+ tsx: "typescript",
287
+ js: "babel",
288
+ jsx: "babel",
289
+ "js.flow": "flow",
290
+ flow: "flow",
291
+ gql: "graphql",
292
+ graphql: "graphql",
293
+ css: "scss",
294
+ scss: "scss",
295
+ less: "scss",
296
+ stylus: "scss",
297
+ markdown: "markdown",
298
+ md: "markdown",
299
+ json: "json"
300
+ };
301
+ async function prettify(filePath, content, prettierConfigFile) {
302
+ let config = null;
303
+ let parser = "typescript";
304
+ if (filePath) {
305
+ const fileExtension = import_node_path.default.extname(filePath).slice(1);
306
+ parser = EXTENSION_TO_PARSER[fileExtension];
307
+ config = await import_prettier.default.resolveConfig(process.cwd(), {
308
+ useCache: true,
309
+ editorconfig: !prettierConfigFile,
310
+ config: prettierConfigFile
311
+ });
312
+ } else if (prettierConfigFile) {
313
+ config = await import_prettier.default.resolveConfig(process.cwd(), {
314
+ useCache: true,
315
+ config: prettierConfigFile
316
+ });
317
+ }
318
+ return import_prettier.default.format(content, {
319
+ parser,
320
+ ...config
321
+ });
322
+ }
323
+
324
+ // src/utils/removeUndefined.ts
325
+ function removeUndefined(t) {
326
+ return typeof t !== "undefined";
327
+ }
328
+
329
+ // src/generators/react-hooks.ts
330
+ var createBinding = ({
331
+ operationDefinition: { verb, path: path4, operation },
332
+ overrides,
333
+ isLazy = false
334
+ }) => factory.createBindingElement(
335
+ void 0,
336
+ void 0,
337
+ factory.createIdentifier(
338
+ `use${isLazy ? "Lazy" : ""}${capitalize((0, import_generate.getOperationName)(verb, path4, operation.operationId))}${isQuery(verb, overrides) ? "Query" : "Mutation"}`
339
+ ),
340
+ void 0
341
+ );
342
+ var getReactHookName = ({ operationDefinition, endpointOverrides, config }) => {
343
+ const overrides = getOverrides(operationDefinition, endpointOverrides);
344
+ const baseParams = {
345
+ operationDefinition,
346
+ overrides
347
+ };
348
+ const _isQuery = isQuery(operationDefinition.verb, overrides);
349
+ if (typeof config === "boolean") {
350
+ return createBinding(baseParams);
351
+ }
352
+ if (_isQuery) {
353
+ return [
354
+ ...config.queries ? [createBinding(baseParams)] : [],
355
+ ...config.lazyQueries ? [createBinding({ ...baseParams, isLazy: true })] : []
356
+ ];
357
+ }
358
+ return config.mutations ? createBinding(baseParams) : [];
359
+ };
360
+ var generateReactHooks = ({
361
+ exportName,
362
+ operationDefinitions,
363
+ endpointOverrides,
364
+ config
365
+ }) => factory.createVariableStatement(
366
+ [factory.createModifier(import_typescript3.default.SyntaxKind.ExportKeyword)],
367
+ factory.createVariableDeclarationList(
368
+ [
369
+ factory.createVariableDeclaration(
370
+ factory.createObjectBindingPattern(
371
+ operationDefinitions.map((operationDefinition) => getReactHookName({ operationDefinition, endpointOverrides, config })).flat()
372
+ ),
373
+ void 0,
374
+ void 0,
375
+ factory.createIdentifier(exportName)
376
+ )
377
+ ],
378
+ import_typescript3.default.NodeFlags.Const
379
+ )
380
+ );
381
+
382
+ // src/generate.ts
383
+ var generatedApiName = "injectedRtkApi";
384
+ var v3DocCache = {};
385
+ var useFetcherImport = generateImportNode("@acrool/react-fetcher", {
386
+ IUseFetcherArgs: "IUseFetcherArgs"
387
+ });
388
+ function defaultIsDataResponse(code, includeDefault, response, allResponses) {
389
+ if (includeDefault && code === "default") {
390
+ return true;
391
+ }
392
+ const parsedCode = Number(code);
393
+ return !Number.isNaN(parsedCode) && parsedCode >= 200 && parsedCode < 300;
394
+ }
395
+ function getOperationName2({ verb, path: path4, operation }) {
396
+ return (0, import_generate3.getOperationName)(verb, path4, operation.operationId);
397
+ }
398
+ function getTags({ verb, pathItem }) {
399
+ const tags = verb && pathItem[verb]?.tags ? pathItem[verb].tags : [];
400
+ return tags.map((tag) => tag.toString());
401
+ }
402
+ function patternMatches(pattern) {
403
+ const filters = Array.isArray(pattern) ? pattern : [pattern];
404
+ return function matcher(operationName) {
405
+ if (!pattern) return true;
406
+ return filters.some(
407
+ (filter) => typeof filter === "string" ? filter === operationName : filter?.test(operationName)
408
+ );
409
+ };
410
+ }
411
+ function operationMatches(pattern) {
412
+ const checkMatch = typeof pattern === "function" ? pattern : patternMatches(pattern);
413
+ return function matcher(operationDefinition) {
414
+ if (!pattern) return true;
415
+ const operationName = getOperationName2(operationDefinition);
416
+ return checkMatch(operationName, operationDefinition);
417
+ };
418
+ }
419
+ function getOverrides(operation, endpointOverrides) {
420
+ return endpointOverrides?.find((override) => operationMatches(override.pattern)(operation));
421
+ }
422
+ async function generateApi(spec, {
423
+ apiFile,
424
+ apiImport = "api",
425
+ exportName = "enhancedApi",
426
+ argSuffix = "ApiArg",
427
+ responseSuffix = "ApiResponse",
428
+ operationNameSuffix = "",
429
+ hooks = false,
430
+ tag = false,
431
+ outputFile,
432
+ isDataResponse = defaultIsDataResponse,
433
+ filterEndpoints,
434
+ endpointOverrides,
435
+ unionUndefined,
436
+ encodePathParams = false,
437
+ encodeQueryParams = false,
438
+ flattenArg = false,
439
+ includeDefault = false,
440
+ useEnumType = false,
441
+ mergeReadWriteOnly = false,
442
+ httpResolverOptions
443
+ }) {
444
+ const v3Doc = v3DocCache[spec] ??= await getV3Doc(spec, httpResolverOptions);
445
+ const apiGen = new import_generate3.default(v3Doc, {
446
+ unionUndefined,
447
+ useEnumType,
448
+ mergeReadWriteOnly
449
+ });
450
+ if (apiGen.spec.components?.schemas) {
451
+ apiGen.preprocessComponents(apiGen.spec.components.schemas);
452
+ }
453
+ const operationDefinitions = getOperationDefinitions(v3Doc).filter(operationMatches(filterEndpoints));
454
+ const resultFile = import_typescript4.default.createSourceFile(
455
+ "someFileName.ts",
456
+ "",
457
+ import_typescript4.default.ScriptTarget.Latest,
458
+ /*setParentNodes*/
459
+ false,
460
+ import_typescript4.default.ScriptKind.TS
461
+ );
462
+ const printer = import_typescript4.default.createPrinter({ newLine: import_typescript4.default.NewLineKind.LineFeed });
463
+ const interfaces = {};
464
+ function registerInterface(declaration) {
465
+ const name = declaration.name.escapedText.toString();
466
+ if (name in interfaces) {
467
+ throw new Error(`interface/type alias ${name} already registered`);
468
+ }
469
+ interfaces[name] = declaration;
470
+ return declaration;
471
+ }
472
+ if (outputFile) {
473
+ outputFile = import_node_path2.default.resolve(process.cwd(), outputFile);
474
+ if (apiFile.startsWith(".")) {
475
+ apiFile = import_node_path2.default.relative(import_node_path2.default.dirname(outputFile), apiFile);
476
+ apiFile = apiFile.replace(/\\/g, "/");
477
+ if (!apiFile.startsWith(".")) apiFile = `./${apiFile}`;
478
+ }
479
+ }
480
+ apiFile = apiFile.replace(/\.[jt]sx?$/, "");
481
+ return printer.printNode(
482
+ import_typescript4.default.EmitHint.Unspecified,
483
+ factory.createSourceFile(
484
+ [
485
+ generateImportNode(apiFile, { [apiImport]: "api" }),
486
+ ...tag ? [generateTagTypes({ addTagTypes: extractAllTagTypes({ operationDefinitions }) })] : [],
487
+ generateCreateApiCall({
488
+ tag,
489
+ endpointDefinitions: factory.createObjectLiteralExpression(
490
+ operationDefinitions.map(
491
+ (operationDefinition) => generateEndpoint({
492
+ operationDefinition,
493
+ overrides: getOverrides(operationDefinition, endpointOverrides)
494
+ })
495
+ ),
496
+ true
497
+ )
498
+ }),
499
+ factory.createExportDeclaration(
500
+ void 0,
501
+ false,
502
+ factory.createNamedExports([
503
+ factory.createExportSpecifier(
504
+ factory.createIdentifier(generatedApiName),
505
+ factory.createIdentifier(exportName)
506
+ )
507
+ ]),
508
+ void 0
509
+ ),
510
+ ...Object.values(interfaces),
511
+ ...apiGen.aliases,
512
+ ...apiGen.enumAliases,
513
+ ...hooks ? [
514
+ generateReactHooks({
515
+ exportName: generatedApiName,
516
+ operationDefinitions,
517
+ endpointOverrides,
518
+ config: hooks
519
+ })
520
+ ] : []
521
+ ],
522
+ factory.createToken(import_typescript4.default.SyntaxKind.EndOfFileToken),
523
+ import_typescript4.default.NodeFlags.None
524
+ ),
525
+ resultFile
526
+ );
527
+ function extractAllTagTypes({ operationDefinitions: operationDefinitions2 }) {
528
+ const allTagTypes = /* @__PURE__ */ new Set();
529
+ for (const operationDefinition of operationDefinitions2) {
530
+ const { verb, pathItem } = operationDefinition;
531
+ for (const tag2 of getTags({ verb, pathItem })) {
532
+ allTagTypes.add(tag2);
533
+ }
534
+ }
535
+ return [...allTagTypes];
536
+ }
537
+ function generateQueryArgType(operationDefinition) {
538
+ const {
539
+ operation: { parameters = [], requestBody }
540
+ } = operationDefinition;
541
+ const properties = [];
542
+ if (requestBody && !(0, import_generate3.isReference)(requestBody)) {
543
+ const bodySchema = requestBody.content?.["application/json"]?.schema;
544
+ if (bodySchema) {
545
+ properties.push(
546
+ factory.createPropertySignature(
547
+ void 0,
548
+ factory.createIdentifier("body"),
549
+ void 0,
550
+ factory.createTypeReferenceNode(factory.createIdentifier("any"), void 0)
551
+ )
552
+ );
553
+ }
554
+ }
555
+ const queryParams = parameters.filter((p) => !(0, import_generate3.isReference)(p) && p.in === "query");
556
+ if (queryParams.length > 0) {
557
+ properties.push(
558
+ factory.createPropertySignature(
559
+ void 0,
560
+ factory.createIdentifier("params"),
561
+ void 0,
562
+ factory.createTypeLiteralNode(
563
+ queryParams.map(
564
+ (param) => factory.createPropertySignature(
565
+ void 0,
566
+ factory.createIdentifier(param.name),
567
+ factory.createToken(import_typescript4.default.SyntaxKind.QuestionToken),
568
+ factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword)
569
+ )
570
+ )
571
+ )
572
+ )
573
+ );
574
+ }
575
+ const headerParams = parameters.filter((p) => !(0, import_generate3.isReference)(p) && p.in === "header");
576
+ if (headerParams.length > 0) {
577
+ properties.push(
578
+ factory.createPropertySignature(
579
+ void 0,
580
+ factory.createIdentifier("headers"),
581
+ void 0,
582
+ factory.createTypeLiteralNode(
583
+ headerParams.map(
584
+ (param) => factory.createPropertySignature(
585
+ void 0,
586
+ factory.createIdentifier(param.name),
587
+ factory.createToken(import_typescript4.default.SyntaxKind.QuestionToken),
588
+ factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword)
589
+ )
590
+ )
591
+ )
592
+ )
593
+ );
594
+ }
595
+ return factory.createTypeLiteralNode([
596
+ factory.createPropertySignature(
597
+ void 0,
598
+ factory.createIdentifier("variables"),
599
+ void 0,
600
+ factory.createTypeLiteralNode(properties)
601
+ ),
602
+ factory.createPropertySignature(
603
+ void 0,
604
+ factory.createIdentifier("fetchOptions"),
605
+ factory.createToken(import_typescript4.default.SyntaxKind.QuestionToken),
606
+ factory.createTypeReferenceNode(factory.createIdentifier("any"), void 0)
607
+ )
608
+ ]);
609
+ }
610
+ function generateQueryArgDefinitions(operationDefinition) {
611
+ const {
612
+ operation: { parameters = [], requestBody }
613
+ } = operationDefinition;
614
+ const queryArg = {};
615
+ if (requestBody && !(0, import_generate3.isReference)(requestBody)) {
616
+ const bodySchema = requestBody.content?.["application/json"]?.schema;
617
+ if (bodySchema) {
618
+ queryArg["body"] = {
619
+ name: "body",
620
+ originalName: "body",
621
+ type: factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.AnyKeyword),
622
+ required: true,
623
+ origin: "body",
624
+ body: requestBody
625
+ };
626
+ }
627
+ }
628
+ parameters.filter((p) => !(0, import_generate3.isReference)(p)).forEach((param) => {
629
+ queryArg[param.name] = {
630
+ name: param.name,
631
+ originalName: param.name,
632
+ type: factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword),
633
+ required: param.required || false,
634
+ origin: "param",
635
+ param
636
+ };
637
+ });
638
+ return queryArg;
639
+ }
640
+ function generateEndpoint({
641
+ operationDefinition,
642
+ overrides
643
+ }) {
644
+ const {
645
+ verb,
646
+ path: path4,
647
+ pathItem,
648
+ operation,
649
+ operation: { responses, requestBody }
650
+ } = operationDefinition;
651
+ const operationName = getOperationName2({ verb, path: path4, operation });
652
+ const tags = tag ? getTags({ verb, pathItem }) : [];
653
+ const isQuery2 = isQuery(verb, overrides);
654
+ const returnsJson = apiGen.getResponseType(responses) === "json";
655
+ let ResponseType = factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.UnknownKeyword);
656
+ if (returnsJson) {
657
+ const returnTypes = Object.entries(responses || {}).map(
658
+ ([code, response]) => isDataResponse(code, includeDefault, response, responses) && response ? apiGen.getTypeFromResponse(response) : void 0
659
+ ).filter(removeUndefined);
660
+ if (returnTypes.length === 1) {
661
+ ResponseType = returnTypes[0];
662
+ } else if (returnTypes.length > 1) {
663
+ ResponseType = factory.createUnionTypeNode(returnTypes);
664
+ }
665
+ }
666
+ const QueryArg = generateQueryArgType(operationDefinition);
667
+ const wrappedQueryArg = factory.createTypeReferenceNode(factory.createIdentifier("IUseFetcherArgs"), [QueryArg]);
668
+ const endpointBuilder = factory.createIdentifier("build");
669
+ const Response = factory.createTypeReferenceNode(
670
+ factory.createIdentifier(`${capitalize(operationName)}${responseSuffix}`),
671
+ void 0
672
+ );
673
+ const queryArgDefinitions = generateQueryArgDefinitions(operationDefinition);
674
+ const extraEndpointsProps = isQuery2 ? generateQueryEndpointProps({ operationDefinition }) : generateMutationEndpointProps({ operationDefinition });
675
+ return generateEndpointDefinition({
676
+ operationName,
677
+ type: isQuery2 ? "query" : "mutation",
678
+ Response,
679
+ QueryArg: wrappedQueryArg,
680
+ queryFn: generateQueryFn({
681
+ operationDefinition,
682
+ queryArg: queryArgDefinitions,
683
+ isFlatArg: flattenArg,
684
+ isQuery: isQuery2,
685
+ encodePathParams,
686
+ encodeQueryParams
687
+ }),
688
+ extraEndpointsProps,
689
+ tags,
690
+ endpointBuilder
691
+ });
692
+ }
693
+ function generateQueryFn({
694
+ operationDefinition,
695
+ queryArg,
696
+ isFlatArg,
697
+ isQuery: isQuery2,
698
+ encodePathParams: encodePathParams2,
699
+ encodeQueryParams: encodeQueryParams2
700
+ }) {
701
+ const {
702
+ verb,
703
+ path: path4,
704
+ operation: { parameters = [], requestBody }
705
+ } = operationDefinition;
706
+ const bodyParameter = requestBody && !(0, import_generate3.isReference)(requestBody) ? requestBody.content?.["application/json"]?.schema : void 0;
707
+ const bodyArg = bodyParameter ? queryArg["body"] : void 0;
708
+ const pathParameters = parameters.filter((p) => !(0, import_generate3.isReference)(p) && p.in === "path").map((param) => ({
709
+ name: param.name,
710
+ originalName: param.name,
711
+ type: factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword),
712
+ required: param.required,
713
+ param,
714
+ origin: "param"
715
+ }));
716
+ const queryParameters = parameters.filter((p) => !(0, import_generate3.isReference)(p) && p.in === "query").map((param) => ({
717
+ name: param.name,
718
+ originalName: param.name,
719
+ type: factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword),
720
+ required: param.required,
721
+ param,
722
+ origin: "param"
723
+ }));
724
+ const headerParameters = parameters.filter((p) => !(0, import_generate3.isReference)(p) && p.in === "header").map((param) => ({
725
+ name: param.name,
726
+ originalName: param.name,
727
+ type: factory.createKeywordTypeNode(import_typescript4.default.SyntaxKind.StringKeyword),
728
+ required: param.required,
729
+ param,
730
+ origin: "param"
731
+ }));
732
+ const rootObject = factory.createIdentifier("queryArg");
733
+ const objectProperties = [
734
+ factory.createPropertyAssignment(
735
+ "url",
736
+ generatePathExpression(path4, pathParameters, rootObject, isFlatArg, encodePathParams2)
737
+ ),
738
+ factory.createPropertyAssignment("method", factory.createStringLiteral(verb.toUpperCase()))
739
+ ];
740
+ if (bodyArg) {
741
+ objectProperties.push(
742
+ factory.createPropertyAssignment(
743
+ "body",
744
+ factory.createPropertyAccessExpression(
745
+ factory.createPropertyAccessExpression(rootObject, factory.createIdentifier("variables")),
746
+ factory.createIdentifier("body")
747
+ )
748
+ )
749
+ );
750
+ }
751
+ if (queryParameters.length) {
752
+ objectProperties.push(
753
+ factory.createPropertyAssignment(
754
+ "params",
755
+ factory.createPropertyAccessExpression(
756
+ factory.createPropertyAccessExpression(rootObject, factory.createIdentifier("variables")),
757
+ factory.createIdentifier("params")
758
+ )
759
+ )
760
+ );
761
+ }
762
+ if (headerParameters.length) {
763
+ objectProperties.push(
764
+ factory.createPropertyAssignment(
765
+ "headers",
766
+ factory.createPropertyAccessExpression(
767
+ factory.createPropertyAccessExpression(rootObject, factory.createIdentifier("variables")),
768
+ factory.createIdentifier("headers")
769
+ )
770
+ )
771
+ );
772
+ }
773
+ objectProperties.push(
774
+ factory.createPropertyAssignment(
775
+ "fetchOptions",
776
+ factory.createPropertyAccessExpression(rootObject, factory.createIdentifier("fetchOptions"))
777
+ )
778
+ );
779
+ return factory.createArrowFunction(
780
+ void 0,
781
+ void 0,
782
+ [factory.createParameterDeclaration(void 0, void 0, rootObject)],
783
+ void 0,
784
+ factory.createToken(import_typescript4.default.SyntaxKind.EqualsGreaterThanToken),
785
+ factory.createParenthesizedExpression(factory.createObjectLiteralExpression(objectProperties, true))
786
+ );
787
+ }
788
+ function generateQueryEndpointProps({}) {
789
+ return {};
790
+ }
791
+ function generateMutationEndpointProps({}) {
792
+ return {};
793
+ }
794
+ }
795
+ function generatePathExpression(path4, pathParameters, rootObject, isFlatArg, encodePathParams) {
796
+ const expressions = [];
797
+ const head = path4.replace(/\{(.*?)}(.*?)(?=\{|$)/g, (_, expression, literal) => {
798
+ const param = pathParameters.find((p) => p.originalName === expression);
799
+ if (!param) {
800
+ throw new Error(`path parameter ${expression} does not seem to be defined in '${path4}'!`);
801
+ }
802
+ expressions.push([param.name, literal]);
803
+ return "";
804
+ });
805
+ return expressions.length ? factory.createTemplateExpression(
806
+ factory.createTemplateHead(head, head),
807
+ expressions.map(([prop, literal], index) => {
808
+ const value = factory.createPropertyAccessExpression(
809
+ factory.createPropertyAccessExpression(rootObject, factory.createIdentifier("variables")),
810
+ factory.createIdentifier(prop)
811
+ );
812
+ const encodedValue = encodePathParams ? factory.createCallExpression(factory.createIdentifier("encodeURIComponent"), void 0, [
813
+ factory.createCallExpression(factory.createIdentifier("String"), void 0, [value])
814
+ ]) : value;
815
+ return factory.createTemplateSpan(
816
+ encodedValue,
817
+ index === expressions.length - 1 ? factory.createTemplateTail(literal, literal) : factory.createTemplateMiddle(literal, literal)
818
+ );
819
+ })
820
+ ) : factory.createStringLiteral(head);
821
+ }
822
+
823
+ // src/index.ts
824
+ var require2 = (0, import_node_module.createRequire)(__filename);
825
+ async function generateEndpoints(options) {
826
+ const schemaLocation = options.schemaFile;
827
+ const schemaAbsPath = isValidUrl(options.schemaFile) ? options.schemaFile : import_node_path3.default.resolve(process.cwd(), schemaLocation);
828
+ const sourceCode = await enforceOazapftsTsVersion(async () => {
829
+ return generateApi(schemaAbsPath, options);
830
+ });
831
+ const { outputFile, prettierConfigFile } = options;
832
+ if (outputFile) {
833
+ import_node_fs.default.writeFileSync(
834
+ import_node_path3.default.resolve(process.cwd(), outputFile),
835
+ await prettify(outputFile, sourceCode, prettierConfigFile)
836
+ );
837
+ } else {
838
+ return await prettify(null, sourceCode, prettierConfigFile);
839
+ }
840
+ }
841
+ function parseConfig(fullConfig) {
842
+ const outFiles = [];
843
+ if ("outputFiles" in fullConfig) {
844
+ const { outputFiles, ...commonConfig } = fullConfig;
845
+ for (const [outputFile, specificConfig] of Object.entries(outputFiles)) {
846
+ outFiles.push({
847
+ ...commonConfig,
848
+ ...specificConfig,
849
+ outputFile
850
+ });
851
+ }
852
+ } else {
853
+ outFiles.push(fullConfig);
854
+ }
855
+ return outFiles;
856
+ }
857
+ function enforceOazapftsTsVersion(cb) {
858
+ const ozTsPath = require2.resolve("typescript", { paths: [require2.resolve("oazapfts")] });
859
+ const tsPath = require2.resolve("typescript");
860
+ const originalEntry = require2.cache[ozTsPath];
861
+ try {
862
+ require2.cache[ozTsPath] = require2.cache[tsPath];
863
+ return cb();
864
+ } finally {
865
+ if (originalEntry) {
866
+ require2.cache[ozTsPath] = originalEntry;
867
+ } else {
868
+ delete require2.cache[ozTsPath];
869
+ }
870
+ }
871
+ }
872
+ // Annotate the CommonJS export names for ESM import in node:
873
+ 0 && (module.exports = {
874
+ generateEndpoints,
875
+ parseConfig
876
+ });
877
+ //# sourceMappingURL=index.js.map