@keq-request/cli 5.0.0-alpha.27 → 5.0.0-alpha.29

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.
Files changed (109) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cli.cjs +1060 -1112
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +1180 -1232
  5. package/dist/cli.js.map +1 -1
  6. package/dist/compiler/compiler.d.ts.map +1 -1
  7. package/dist/compiler/tasks/setup/index.d.ts.map +1 -1
  8. package/dist/compiler/tasks/setup/utils/index.d.ts +0 -1
  9. package/dist/compiler/tasks/setup/utils/index.d.ts.map +1 -1
  10. package/dist/compiler/tasks/setup/utils/parse-runtime-config.d.ts +3 -0
  11. package/dist/compiler/tasks/setup/utils/parse-runtime-config.d.ts.map +1 -0
  12. package/dist/compiler/types/compiler-context.d.ts +1 -1
  13. package/dist/compiler/types/compiler-context.d.ts.map +1 -1
  14. package/dist/compiler/types/compiler-hooks.d.ts +2 -1
  15. package/dist/compiler/types/compiler-hooks.d.ts.map +1 -1
  16. package/dist/define-config.d.ts +3 -0
  17. package/dist/define-config.d.ts.map +1 -0
  18. package/dist/index.cjs +1130 -1184
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1041 -1094
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/module-definition.d.ts +3 -2
  25. package/dist/models/module-definition.d.ts.map +1 -1
  26. package/dist/plugins/body-fallback/constants/index.d.ts +2 -0
  27. package/dist/plugins/body-fallback/constants/index.d.ts.map +1 -0
  28. package/dist/plugins/body-fallback/constants/metadata-storage.d.ts +6 -0
  29. package/dist/plugins/body-fallback/constants/metadata-storage.d.ts.map +1 -0
  30. package/dist/plugins/body-fallback/index.d.ts +3 -0
  31. package/dist/plugins/body-fallback/index.d.ts.map +1 -1
  32. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts +3 -0
  33. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts.map +1 -1
  34. package/dist/plugins/chinese-to-pinyin/constants/index.d.ts +2 -0
  35. package/dist/plugins/chinese-to-pinyin/constants/index.d.ts.map +1 -0
  36. package/dist/plugins/chinese-to-pinyin/constants/metadata-storage.d.ts +6 -0
  37. package/dist/plugins/chinese-to-pinyin/constants/metadata-storage.d.ts.map +1 -0
  38. package/dist/plugins/download-http-file/constants/index.d.ts +2 -0
  39. package/dist/plugins/download-http-file/constants/index.d.ts.map +1 -0
  40. package/dist/plugins/download-http-file/constants/metadata-storage.d.ts +6 -0
  41. package/dist/plugins/download-http-file/constants/metadata-storage.d.ts.map +1 -0
  42. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts +5 -2
  43. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts.map +1 -1
  44. package/dist/plugins/download-local-file/constants/index.d.ts +2 -0
  45. package/dist/plugins/download-local-file/constants/index.d.ts.map +1 -0
  46. package/dist/plugins/download-local-file/constants/metadata-storage.d.ts +6 -0
  47. package/dist/plugins/download-local-file/constants/metadata-storage.d.ts.map +1 -0
  48. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts +3 -0
  49. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts.map +1 -1
  50. package/dist/plugins/eslint/constants/index.d.ts +2 -0
  51. package/dist/plugins/eslint/constants/index.d.ts.map +1 -0
  52. package/dist/plugins/eslint/constants/metadata-storage.d.ts +6 -0
  53. package/dist/plugins/eslint/constants/metadata-storage.d.ts.map +1 -0
  54. package/dist/plugins/eslint/eslint.plugin.d.ts +18 -0
  55. package/dist/plugins/eslint/eslint.plugin.d.ts.map +1 -0
  56. package/dist/plugins/eslint/index.d.ts +1 -14
  57. package/dist/plugins/eslint/index.d.ts.map +1 -1
  58. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts.map +1 -1
  59. package/dist/plugins/generate-declaration/generators/schema-declaration/schema.generator.d.ts.map +1 -1
  60. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts.map +1 -1
  61. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts.map +1 -1
  62. package/dist/plugins/initialize/initialize.plugin.d.ts.map +1 -1
  63. package/dist/plugins/prettier/constants/index.d.ts +2 -0
  64. package/dist/plugins/prettier/constants/index.d.ts.map +1 -0
  65. package/dist/plugins/prettier/constants/metadata-storage.d.ts +6 -0
  66. package/dist/plugins/prettier/constants/metadata-storage.d.ts.map +1 -0
  67. package/dist/plugins/prettier/prettier.plugin.d.ts +3 -0
  68. package/dist/plugins/prettier/prettier.plugin.d.ts.map +1 -1
  69. package/dist/plugins/shaking/constants/index.d.ts +2 -0
  70. package/dist/plugins/shaking/constants/index.d.ts.map +1 -0
  71. package/dist/plugins/shaking/constants/metadata-storage.d.ts +6 -0
  72. package/dist/plugins/shaking/constants/metadata-storage.d.ts.map +1 -0
  73. package/dist/plugins/shaking/shaking.plugin.d.ts +3 -0
  74. package/dist/plugins/shaking/shaking.plugin.d.ts.map +1 -1
  75. package/dist/plugins/terminal-select/constants/index.d.ts +2 -0
  76. package/dist/plugins/terminal-select/constants/index.d.ts.map +1 -0
  77. package/dist/plugins/terminal-select/constants/metadata-storage.d.ts +6 -0
  78. package/dist/plugins/terminal-select/constants/metadata-storage.d.ts.map +1 -0
  79. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts +3 -0
  80. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts.map +1 -1
  81. package/dist/plugins.cjs +208 -47
  82. package/dist/plugins.cjs.map +1 -1
  83. package/dist/plugins.js +208 -47
  84. package/dist/plugins.js.map +1 -1
  85. package/dist/translators/index.d.ts +3 -0
  86. package/dist/translators/index.d.ts.map +1 -0
  87. package/dist/translators/micro-function.translator.d.ts +5 -0
  88. package/dist/translators/micro-function.translator.d.ts.map +1 -0
  89. package/dist/translators/nestjs.translator.d.ts +5 -0
  90. package/dist/translators/nestjs.translator.d.ts.map +1 -0
  91. package/dist/translators.cjs +2061 -0
  92. package/dist/translators.cjs.map +1 -0
  93. package/dist/translators.js +2023 -0
  94. package/dist/translators.js.map +1 -0
  95. package/dist/types/address.d.ts +8 -0
  96. package/dist/types/address.d.ts.map +1 -0
  97. package/dist/types/index.d.ts +3 -1
  98. package/dist/types/index.d.ts.map +1 -1
  99. package/dist/types/runtime-config.d.ts +39 -8
  100. package/dist/types/runtime-config.d.ts.map +1 -1
  101. package/dist/types/translator.d.ts +5 -0
  102. package/dist/types/translator.d.ts.map +1 -0
  103. package/dist/utils/is-valid-url.d.ts +16 -0
  104. package/dist/utils/is-valid-url.d.ts.map +1 -0
  105. package/package.json +8 -3
  106. package/dist/compiler/tasks/setup/utils/validate-modules.d.ts +0 -2
  107. package/dist/compiler/tasks/setup/utils/validate-modules.d.ts.map +0 -1
  108. package/dist/define-keq-config.d.ts +0 -3
  109. package/dist/define-keq-config.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,8 @@
1
- // src/define-keq-config.ts
2
- function defineKeqConfig(config) {
1
+ // src/define-config.ts
2
+ function defineConfig(config) {
3
3
  return config;
4
4
  }
5
5
 
6
- // src/types/runtime-config.ts
7
- import { Type } from "@sinclair/typebox";
8
-
9
6
  // src/constants/file-naming-style.ts
10
7
  var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
11
8
  FileNamingStyle2["camelCase"] = "camelCase";
@@ -22,39 +19,6 @@ var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
22
19
  return FileNamingStyle2;
23
20
  })(FileNamingStyle || {});
24
21
 
25
- // src/types/runtime-config.ts
26
- var RuntimeConfig = Type.Object({
27
- mode: Type.Optional(
28
- Type.Union([
29
- Type.Literal("micro-function"),
30
- Type.Literal("nestjs-module"),
31
- Type.Literal("none")
32
- ], { default: "micro-function" })
33
- ),
34
- /**
35
- * Whether to generate ES Module code
36
- *
37
- * If not specified, the module system will be inferred from the nearest package.json "type" field
38
- * or defaults to "cjs" if no package.json is found.
39
- */
40
- esm: Type.Optional(Type.Boolean({ default: false })),
41
- /**
42
- * Output directory for generated files
43
- */
44
- outdir: Type.String({ default: `${process.cwd()}/api` }),
45
- /**
46
- * File naming style for generated files
47
- */
48
- fileNamingStyle: Type.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
49
- modules: Type.Record(Type.String(), Type.String()),
50
- debug: Type.Optional(Type.Boolean({ default: false })),
51
- /**
52
- * Whether to tolerate wrong openapi/swagger structure
53
- */
54
- tolerant: Type.Optional(Type.Boolean({ default: false })),
55
- plugins: Type.Optional(Type.Array(Type.Any(), { default: [] }))
56
- });
57
-
58
22
  // src/constants/qs-array-format.ts
59
23
  var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
60
24
  QsArrayFormat2["brackets"] = "brackets";
@@ -82,9 +46,8 @@ import { Listr } from "listr2";
82
46
  import { AsyncParallelHook, AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } from "tapable";
83
47
 
84
48
  // src/compiler/tasks/setup/index.ts
85
- import fs3 from "fs-extra";
86
- import path2 from "path";
87
- import { Value } from "@sinclair/typebox/value";
49
+ import fs4 from "fs-extra";
50
+ import path10 from "path";
88
51
  import { cosmiconfig } from "cosmiconfig";
89
52
 
90
53
  // src/utils/ignore-matcher.ts
@@ -178,35 +141,6 @@ var IgnoreMatcher = class _IgnoreMatcher {
178
141
  }
179
142
  };
180
143
 
181
- // src/compiler/tasks/setup/utils/validate-modules.ts
182
- import * as R2 from "ramda";
183
- import validator from "validator";
184
- function validateModules(modules) {
185
- const keys2 = Object.keys(modules);
186
- for (const key of keys2) {
187
- if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(key)) {
188
- throw new Error(`Module name "${key}" is not valid. It must start with a letter or underscore, and can only contain letters, numbers, and underscores.`);
189
- }
190
- }
191
- const keysGroupByLowerCase = R2.groupBy(R2.toLower, keys2);
192
- for (const groupKey in keysGroupByLowerCase) {
193
- const keys3 = keysGroupByLowerCase[groupKey] || [];
194
- if (keys3.length > 1) {
195
- throw new Error(`Module names ${keys3.map((name) => `"${name}"`).join(", ")} are case-insensitively duplicated.`);
196
- }
197
- }
198
- for (const key in modules) {
199
- const address = modules[key];
200
- if (validator.isURL(address, { require_host: true, require_protocol: true, protocols: ["http", "https"] })) {
201
- continue;
202
- }
203
- if (/^(\/|\.\/|\.\.\/)/.test(address)) {
204
- continue;
205
- }
206
- throw new Error(`Module address "${address}" of module "${key}" is not valid. It must be a URL or a local path.`);
207
- }
208
- }
209
-
210
144
  // src/compiler/tasks/setup/utils/find-nearest-package-json.ts
211
145
  import fs2 from "fs";
212
146
  import path from "path";
@@ -233,80 +167,193 @@ function getProjectModuleSystem(pkgInfo) {
233
167
  return "cjs";
234
168
  }
235
169
 
236
- // src/compiler/tasks/setup/index.ts
237
- var explore = cosmiconfig("keq");
238
- function main(compiler, options) {
239
- return {
240
- task: async (context, task) => {
241
- const result = options?.config ? await explore.load(options.config) : await explore.search();
242
- if (!result || "isEmpty" in result && result.isEmpty) {
243
- throw new Error("Cannot find config file.");
244
- }
245
- if (!Value.Check(RuntimeConfig, result.config)) {
246
- const errors = [...Value.Errors(RuntimeConfig, result.config)];
247
- const message = errors.map(({ path: path13, message: message2 }) => `${path13}: ${message2}`).join("\n");
248
- throw new Error(`Invalid Config: ${message}`);
249
- }
250
- const rc = Value.Default(RuntimeConfig, result.config);
251
- validateModules(rc.modules);
252
- if (options?.debug) {
253
- await fs3.ensureDir(".keq");
254
- rc.debug = true;
255
- }
256
- rc.tolerant = Boolean(rc.tolerant);
257
- const packageJsonInfo = findNearestPackageJson();
258
- if (packageJsonInfo) {
259
- const moduleSystem = getProjectModuleSystem(packageJsonInfo);
260
- rc.esm = moduleSystem === "esm";
261
- }
262
- context.rc = rc;
263
- let matcher = new IgnoreMatcher([]);
264
- if (result.filepath) {
265
- const ignoreFilepath = path2.resolve(path2.dirname(result.filepath), ".keqignore");
266
- if (await fs3.exists(ignoreFilepath)) {
267
- matcher = await IgnoreMatcher.read(ignoreFilepath);
268
- }
269
- }
270
- const ignoreRules = options.ignore === false ? [] : options.ignore?.rules || [];
271
- for (const rule of ignoreRules) {
272
- matcher.append({
273
- persist: !!rule.persist,
274
- ignore: rule.ignore,
275
- moduleName: rule.moduleName,
276
- operationMethod: rule.operationMethod,
277
- operationPathname: rule.operationPathname
278
- });
279
- }
280
- context.matcher = matcher;
281
- await compiler.hooks.setup.promise(task);
170
+ // src/compiler/tasks/setup/utils/parse-runtime-config.ts
171
+ import { Value } from "@sinclair/typebox/value";
172
+
173
+ // src/types/address.ts
174
+ import { Type } from "@sinclair/typebox";
175
+ var Address = Type.Object({
176
+ url: Type.String(),
177
+ headers: Type.Optional(Type.Record(Type.String(), Type.String(), { default: {} })),
178
+ encoding: Type.Optional(
179
+ Type.Union([
180
+ Type.Literal("utf8"),
181
+ Type.Literal("ascii")
182
+ ], { default: "utf8" })
183
+ )
184
+ });
185
+
186
+ // src/types/runtime-config.ts
187
+ import * as R2 from "ramda";
188
+ import { Type as Type2 } from "@sinclair/typebox";
189
+
190
+ // src/utils/is-valid-url.ts
191
+ var URL_REGEX = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^\s@]+@)?[^\s/:?#]*(?::\d+)?(?:\/[^\s?#]*)?(?:\?[^\s#]*)?(?:#[^\s]*)?$/;
192
+ function isValidURL(url) {
193
+ return URL_REGEX.test(url);
194
+ }
195
+
196
+ // src/types/runtime-config.ts
197
+ var Modules = Type2.Transform(
198
+ Type2.Record(
199
+ Type2.String(),
200
+ Type2.Union([Type2.String(), Address])
201
+ )
202
+ ).Decode((value) => {
203
+ const keys2 = Object.keys(value);
204
+ for (const key of keys2) {
205
+ if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(key)) {
206
+ throw new Error(`Module name "${key}" is not valid. It must start with a letter or underscore, and can only contain letters, numbers, and underscores.`);
282
207
  }
283
- };
208
+ }
209
+ const keysGroupByLowerCase = R2.groupBy(R2.toLower, keys2);
210
+ for (const groupKey in keysGroupByLowerCase) {
211
+ const keys3 = keysGroupByLowerCase[groupKey] || [];
212
+ if (keys3.length > 1) {
213
+ throw new Error(`Module names ${keys3.map((name) => `"${name}"`).join(", ")} are case-insensitively duplicated.`);
214
+ }
215
+ }
216
+ for (const key in value) {
217
+ const url = typeof value[key] === "string" ? value[key] : value[key].url;
218
+ if (isValidURL(url)) continue;
219
+ throw new Error(`The ${JSON.stringify(url)} of module "${key}" is not a valid URL.`);
220
+ }
221
+ return R2.map(
222
+ (item) => typeof item !== "string" ? item : { url: item, headers: {}, encoding: "utf8" },
223
+ value
224
+ );
225
+ }).Encode((value) => value);
226
+ var RawConfig = Type2.Object({
227
+ /**
228
+ * Whether to generate ES Module code
229
+ *
230
+ * If not specified, the module system will be inferred from the nearest package.json "type" field
231
+ * or defaults to "cjs" if no package.json is found.
232
+ */
233
+ esm: Type2.Optional(Type2.Boolean({ default: false })),
234
+ /**
235
+ * Output directory for generated files
236
+ */
237
+ outdir: Type2.String({ default: `${process.cwd()}/api` }),
238
+ /**
239
+ * File naming style for generated files
240
+ */
241
+ fileNamingStyle: Type2.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
242
+ /**
243
+ * OpenAPI/Swagger document sources
244
+ *
245
+ * A map of module names to their document URLs or Address objects.
246
+ * The module name must be a valid JavaScript identifier.
247
+ */
248
+ modules: Modules,
249
+ /**
250
+ * Enable debug mode to output detailed logs during compilation
251
+ */
252
+ debug: Type2.Optional(Type2.Boolean({ default: false })),
253
+ /**
254
+ * Whether to tolerate wrong openapi/swagger structure
255
+ */
256
+ tolerant: Type2.Optional(Type2.Boolean({ default: false })),
257
+ /**
258
+ * Translators to transform generated code
259
+ *
260
+ * Used to customize the code generation process for different frameworks or patterns.
261
+ * Can be a single translator or an array of translators.
262
+ */
263
+ translators: Type2.Optional(
264
+ Type2.Transform(
265
+ Type2.Union([
266
+ Type2.Unsafe(Type2.Any()),
267
+ Type2.Array(Type2.Unsafe(Type2.Any()))
268
+ ], { default: [] })
269
+ ).Decode((value) => {
270
+ if (value === void 0) return [];
271
+ if (Array.isArray(value)) return value;
272
+ return [value];
273
+ }).Encode((value) => value)
274
+ ),
275
+ /**
276
+ * Plugins to extend code generation functionality
277
+ *
278
+ * An array of plugin instances that can hook into various stages of the compilation process,
279
+ * such as code transformation, formatting, linting, or custom file generation.
280
+ */
281
+ plugins: Type2.Optional(Type2.Array(Type2.Unsafe(Type2.Any()), { default: [] }))
282
+ });
283
+
284
+ // src/compiler/tasks/setup/utils/parse-runtime-config.ts
285
+ function parseRuntimeConfig(data) {
286
+ try {
287
+ const originalPlugins = typeof data === "object" && data !== null && "plugins" in data ? data.plugins : void 0;
288
+ const originTranslators = typeof data === "object" && data !== null && "translators" in data ? data.translators : void 0;
289
+ const parsed = Value.Parse(RawConfig, data);
290
+ if (originalPlugins !== void 0) {
291
+ parsed.plugins = originalPlugins;
292
+ }
293
+ if (originTranslators !== void 0) {
294
+ parsed.translators = originTranslators;
295
+ }
296
+ return parsed;
297
+ } catch (error) {
298
+ if (error instanceof Error) {
299
+ error.message = `Invalid Config: ${error.message}`;
300
+ }
301
+ throw error;
302
+ }
284
303
  }
285
- function createSetupTask(compiler, options) {
286
- return {
287
- title: "Setup",
288
- enabled: options?.enabled,
289
- skip: options?.skip,
290
- task: (context, task) => task.newListr(
291
- [
292
- main(compiler, options),
293
- {
294
- task: (context2, task2) => compiler.hooks.afterSetup.promise(task2)
295
- }
296
- ],
297
- {
298
- concurrent: false
299
- }
300
- )
301
- };
304
+
305
+ // src/plugins/eslint/eslint.plugin.ts
306
+ import { ESLint } from "eslint";
307
+
308
+ // src/plugins/prettier/prettier.plugin.ts
309
+ import { exec } from "child_process";
310
+ import { promisify } from "util";
311
+ var execAsync = promisify(exec);
312
+
313
+ // src/plugins/body-fallback/index.ts
314
+ import * as R21 from "ramda";
315
+
316
+ // src/utils/json-schema-utils/is-array.ts
317
+ function isArray(schema) {
318
+ return schema.type === "array";
302
319
  }
303
320
 
304
- // src/compiler/tasks/download/index.ts
305
- import { PRESET_TIMER } from "listr2";
306
- import { validate } from "@scalar/openapi-parser";
321
+ // src/utils/json-schema-utils/is-mixed.ts
322
+ function isMixed(schema) {
323
+ return Array.isArray(schema.type);
324
+ }
325
+
326
+ // src/utils/json-schema-utils/is-non-array.ts
327
+ function isNonArray(schema) {
328
+ return typeof schema.type === "string" && schema.type !== "array";
329
+ }
330
+
331
+ // src/utils/json-schema-utils/is-ref.ts
332
+ function isRef(schema) {
333
+ return "$ref" in schema;
334
+ }
335
+
336
+ // src/utils/json-schema-utils/index.ts
337
+ var JsonSchemaUtils = class {
338
+ static isRef = isRef;
339
+ static isArray = isArray;
340
+ static isNonArray = isNonArray;
341
+ static isMixed = isMixed;
342
+ };
343
+
344
+ // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
345
+ import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook2 } from "tapable";
346
+
347
+ // src/plugins/generate-micro-function/constants/metadata-storage.ts
348
+ var MetadataStorage3 = /* @__PURE__ */ new WeakMap();
349
+
350
+ // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
351
+ import * as R20 from "ramda";
352
+ import * as path8 from "path";
353
+ import * as changeCase6 from "change-case";
307
354
 
308
355
  // src/models/artifact.ts
309
- import * as path3 from "path";
356
+ import * as path2 from "path";
310
357
 
311
358
  // src/models/anchor.ts
312
359
  var AnchorBlock = class {
@@ -392,11 +439,11 @@ var Artifact = class {
392
439
  constructor(options) {
393
440
  this.id = options.id;
394
441
  this.filepath = options.filepath;
395
- this.extensionName = options.extensionName || path3.extname(options.filepath);
442
+ this.extensionName = options.extensionName || path2.extname(options.filepath);
396
443
  this.content = options.content;
397
444
  }
398
445
  get dirname() {
399
- return path3.dirname(this.filepath);
446
+ return path2.dirname(this.filepath);
400
447
  }
401
448
  renderer() {
402
449
  return `${HeaderComment}${this.content}`;
@@ -412,10 +459,14 @@ var ModuleDefinition = class _ModuleDefinition {
412
459
  address;
413
460
  constructor(name, address) {
414
461
  this.name = name;
415
- this.address = address;
462
+ if (typeof address === "string") {
463
+ this.address = { url: address, headers: {}, encoding: "utf8" };
464
+ } else {
465
+ this.address = address;
466
+ }
416
467
  }
417
468
  static unknown() {
418
- return new _ModuleDefinition("", "");
469
+ return new _ModuleDefinition("", { url: "", headers: {}, encoding: "utf8" });
419
470
  }
420
471
  };
421
472
 
@@ -635,8 +686,8 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
635
686
  }
636
687
  isRefDefined($ref) {
637
688
  if ($ref.startsWith("#/")) {
638
- const path13 = $ref.replace("#/", "").split("/");
639
- return R5.path(path13, this.specification) !== void 0;
689
+ const path12 = $ref.replace("#/", "").split("/");
690
+ return R5.path(path12, this.specification) !== void 0;
640
691
  }
641
692
  return false;
642
693
  }
@@ -648,532 +699,22 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
648
699
  // src/models/asset.ts
649
700
  var Asset = class {
650
701
  path;
651
- constructor(path13) {
652
- this.path = path13;
702
+ constructor(path12) {
703
+ this.path = path12;
653
704
  }
654
705
  };
655
706
 
656
- // src/exception.ts
657
- import { CustomError } from "ts-custom-error";
658
- import wrap from "word-wrap";
659
- var Exception = class extends CustomError {
660
- constructor(module, message) {
661
- const moduleName = typeof module === "string" ? module : module.name;
662
- const msg = wrap(message, { width: 60, indent: " " });
663
- super(`${moduleName} module failed to compile:
664
- ${msg}`);
665
- Object.defineProperty(this, "name", { value: "KeqCLI_Exception" });
666
- }
667
- };
668
-
669
- // src/utils/openapi-utils/dereference.ts
670
- function dereference($ref, swagger) {
671
- let value;
672
- for (const key of $ref.split("/")) {
673
- if (key === "#") {
674
- value = swagger;
675
- } else {
676
- value = value[key];
677
- }
678
- if (!value) break;
679
- }
680
- return value;
681
- }
682
-
683
- // src/utils/openapi-utils/dereference-operation.ts
684
- import * as R8 from "ramda";
685
- import jsonpointer2 from "jsonpointer";
686
- import { JSONPath as JSONPath4 } from "jsonpath-plus";
707
+ // src/plugins/generate-declaration/generate-declaration.plugin.ts
708
+ import { AsyncSeriesWaterfallHook } from "tapable";
687
709
 
688
- // src/utils/openapi-utils/remove-undefined-ref.ts
689
- import * as R7 from "ramda";
690
- import jsonpointer from "jsonpointer";
691
- import { JSONPath as JSONPath3 } from "jsonpath-plus";
710
+ // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
711
+ import * as path7 from "path";
712
+ import * as changeCase5 from "change-case";
692
713
 
693
- // src/utils/openapi-utils/is-ref-defined.ts
694
- import * as R6 from "ramda";
695
- function isRefDefined($ref, swagger) {
696
- if ($ref.startsWith("#/")) {
697
- const path13 = $ref.replace("#/", "").split("/");
698
- return R6.path(path13, swagger) !== void 0;
699
- }
700
- return false;
701
- }
702
-
703
- // src/utils/openapi-utils/remove-undefined-ref.ts
704
- function removeUndefinedRef(swagger) {
705
- const shadow = R7.clone(swagger);
706
- const matches = JSONPath3({
707
- path: "$..*['$ref']^",
708
- json: swagger,
709
- resultType: "all"
710
- });
711
- for (const match of matches) {
712
- if (match.value.$ref && !isRefDefined(match.value.$ref, swagger)) {
713
- jsonpointer.set(shadow, match.pointer, R7.omit(["$ref"], match.value));
714
- }
715
- }
716
- return shadow;
717
- }
718
-
719
- // src/utils/openapi-utils/dereference-operation.ts
720
- function dereferencePathObject(swagger) {
721
- const matches = JSONPath4({
722
- path: "$.paths.*.$ref^",
723
- json: swagger,
724
- resultType: "all"
725
- });
726
- for (const match of matches) {
727
- const value = dereference(match.value.$ref, swagger);
728
- jsonpointer2.set(swagger, match.pointer, value);
729
- }
730
- }
731
- function dereferenceRequestBody(swagger) {
732
- const matches = JSONPath4({
733
- path: "$.paths.*.*.requestBody.$ref^",
734
- json: swagger,
735
- resultType: "all"
736
- });
737
- for (const match of matches) {
738
- const value = dereference(match.value.$ref, swagger);
739
- jsonpointer2.set(swagger, match.pointer, value);
740
- }
741
- }
742
- function dereferenceResponses(swagger) {
743
- const matches = [
744
- ...JSONPath4({
745
- path: "$.paths.*.*.responses.*.$ref^",
746
- json: swagger,
747
- resultType: "all"
748
- }),
749
- ...JSONPath4({
750
- path: "$.paths.*.*.responses.*.headers.*.$ref^",
751
- json: swagger,
752
- resultType: "all"
753
- })
754
- ];
755
- for (const match of matches) {
756
- const value = dereference(match.value.$ref, swagger);
757
- jsonpointer2.set(swagger, match.pointer, value);
758
- }
759
- }
760
- function dereferenceParameters(swagger) {
761
- const matches = JSONPath4({
762
- path: "$.paths.*.*.parameters.*.$ref^",
763
- json: swagger,
764
- resultType: "all"
765
- });
766
- for (const match of matches) {
767
- const value = dereference(match.value.$ref, swagger);
768
- jsonpointer2.set(swagger, match.pointer, value);
769
- }
770
- }
771
- function dereferenceOperation(swagger) {
772
- const shadow = R8.clone(swagger);
773
- dereferencePathObject(shadow);
774
- dereferenceRequestBody(shadow);
775
- dereferenceResponses(shadow);
776
- dereferenceParameters(shadow);
777
- return removeUndefinedRef(shadow);
778
- }
779
-
780
- // src/utils/json-schema-utils/is-array.ts
781
- function isArray(schema) {
782
- return schema.type === "array";
783
- }
784
-
785
- // src/utils/json-schema-utils/is-mixed.ts
786
- function isMixed(schema) {
787
- return Array.isArray(schema.type);
788
- }
789
-
790
- // src/utils/json-schema-utils/is-non-array.ts
791
- function isNonArray(schema) {
792
- return typeof schema.type === "string" && schema.type !== "array";
793
- }
794
-
795
- // src/utils/json-schema-utils/is-ref.ts
796
- function isRef(schema) {
797
- return "$ref" in schema;
798
- }
799
-
800
- // src/utils/json-schema-utils/index.ts
801
- var JsonSchemaUtils = class {
802
- static isRef = isRef;
803
- static isArray = isArray;
804
- static isNonArray = isNonArray;
805
- static isMixed = isMixed;
806
- };
807
-
808
- // src/utils/openapi-utils/dereference-deep.ts
809
- function dereferenceDeep($ref, swagger) {
810
- const stack = [$ref];
811
- let value;
812
- while (true) {
813
- const last2 = stack[stack.length - 1];
814
- value = dereference(last2, swagger);
815
- if (JsonSchemaUtils.isRef(value)) {
816
- if (!stack.includes(value.$ref)) {
817
- stack.push(value.$ref);
818
- continue;
819
- } else {
820
- throw new Error(`Circular reference detected: ${stack.join(" -> ")} -> ${value.$ref}`);
821
- }
822
- }
823
- break;
824
- }
825
- return value;
826
- }
827
-
828
- // src/utils/openapi-utils/to-3_1.ts
829
- import { upgrade } from "@scalar/openapi-parser";
830
- function To3_1(openapi) {
831
- const { specification } = upgrade(openapi);
832
- return specification;
833
- }
834
-
835
- // src/utils/openapi-utils/map-operation.ts
836
- import * as R9 from "ramda";
837
- function mapOperation(specification, mapper) {
838
- const shadow = R9.clone(specification);
839
- for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
840
- for (const m in pathItem) {
841
- const method = m.toLowerCase();
842
- if (!SupportedMethods.includes(method)) continue;
843
- if (typeof pathItem[m] !== "object" || Array.isArray(pathItem[m]) || pathItem[m] === null) continue;
844
- const operation = pathItem[m];
845
- pathItem[m] = mapper(method, pathname, operation);
846
- }
847
- }
848
- return shadow;
849
- }
850
-
851
- // src/utils/openapi-utils/map-parameter.ts
852
- function mapParameter(specification, mapper) {
853
- return mapOperation(specification, (method, pathname, operation) => {
854
- if (!operation.parameters) return operation;
855
- operation.parameters = operation.parameters.map((parameter) => mapper(method, pathname, operation, parameter));
856
- return operation;
857
- });
858
- }
859
-
860
- // src/utils/openapi-utils/index.ts
861
- var OpenapiUtils = class {
862
- static isRefDefined = isRefDefined;
863
- static dereference = dereference;
864
- static dereferenceDeep = dereferenceDeep;
865
- static removeUndefinedRef = removeUndefinedRef;
866
- static dereferenceOperation = dereferenceOperation;
867
- static mapOperation = mapOperation;
868
- static mapParameter = mapParameter;
869
- // static updateOperationId = updateOperationId
870
- static to3_1 = To3_1;
871
- };
872
-
873
- // src/compiler/tasks/download/index.ts
874
- function main2(compiler, options) {
875
- return {
876
- task: (context, task) => {
877
- if (!context.rc || !context.matcher) {
878
- throw new Error("Please run setup task first.");
879
- }
880
- const rc = context.rc;
881
- const matcher = context.matcher;
882
- context.documents = [];
883
- return task.newListr(
884
- Object.entries(rc.modules).map(([moduleName, address]) => new ModuleDefinition(moduleName, address)).map((moduleDefinition) => ({
885
- title: moduleDefinition.name,
886
- task: async (ctx, task2) => {
887
- if (options?.skipIgnoredModules && matcher.isModuleIgnored(moduleDefinition)) {
888
- task2.skip(`(${moduleDefinition.name}) is ignored`);
889
- return;
890
- }
891
- task2.output = `Downloaded from ${moduleDefinition.address}`;
892
- const content = await compiler.hooks.download.promise(moduleDefinition.address, moduleDefinition, task2);
893
- if (!content) {
894
- throw new Exception(moduleDefinition, `Cannot download document from ${moduleDefinition.address}`);
895
- }
896
- const spec = JSON.parse(content);
897
- const { valid, errors } = await validate(spec);
898
- if (!valid) {
899
- const message = `${moduleDefinition.name} module openapi/swagger file does not conform to the openapi specifications or have grammatical errors, which may cause unexpected errors:
900
- ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
901
- task2.output = message;
902
- }
903
- OpenapiUtils.dereferenceOperation(spec);
904
- const document = new ApiDocumentV3_1(
905
- spec,
906
- moduleDefinition
907
- );
908
- ctx.documents?.push(document);
909
- }
910
- })),
911
- {
912
- concurrent: true,
913
- exitOnError: false,
914
- collectErrors: "minimal",
915
- rendererOptions: {
916
- collapseSubtasks: false,
917
- // collapseSkips: false,
918
- suffixSkips: true,
919
- timer: PRESET_TIMER
920
- }
921
- }
922
- );
923
- }
924
- };
925
- }
926
- function createDownloadTask(compiler, options) {
927
- return {
928
- title: "Download",
929
- enabled: options?.enabled,
930
- skip: options?.skip,
931
- task: (_, task) => task.newListr(
932
- [
933
- main2(compiler, options),
934
- {
935
- task: (context, task2) => compiler.hooks.afterDownload.promise(task2)
936
- }
937
- ],
938
- {
939
- concurrent: false
940
- }
941
- )
942
- };
943
- }
944
-
945
- // src/compiler/tasks/persist/index.ts
946
- import * as path6 from "path";
947
- import fs4 from "fs-extra";
948
- function createPersistArtifactTask() {
949
- return {
950
- title: "Write files",
951
- task: async (context, task) => {
952
- if (!context.rc) throw new Error("Please run setup task first.");
953
- if (!context.artifacts || context.artifacts.length === 0) {
954
- task.skip("No compiled artifacts to persist.");
955
- return;
956
- }
957
- const rc = context.rc;
958
- const artifacts = context.artifacts;
959
- const total = artifacts.length;
960
- let completed = 0;
961
- const files = await Promise.all(artifacts.map(async (artifact) => {
962
- const realpath = `./${path6.join(rc.outdir, artifact.filepath)}`;
963
- await fs4.ensureFile(realpath);
964
- await fs4.writeFile(realpath, artifact.renderer());
965
- completed += 1;
966
- task.output = `Persisted ${completed}/${total} files`;
967
- return new Asset(path6.resolve(realpath));
968
- }));
969
- context.assets = files;
970
- }
971
- };
972
- }
973
- function createPersistIgnoreTask() {
974
- return {
975
- title: "Update .keqignore",
976
- task: async (context, task) => {
977
- if (!context.matcher) throw new Error("Please run setup task first.");
978
- const matcher = context.matcher;
979
- await matcher.write(".keqignore");
980
- }
981
- };
982
- }
983
- function main3() {
984
- return {
985
- task: (context, task) => task.newListr(
986
- [
987
- createPersistArtifactTask(),
988
- createPersistIgnoreTask()
989
- ],
990
- {
991
- concurrent: true,
992
- rendererOptions: {
993
- collapseSubtasks: true
994
- }
995
- }
996
- )
997
- };
998
- }
999
- function createPersistTask(compiler, options) {
1000
- return {
1001
- title: "Persist",
1002
- enabled: options?.enabled,
1003
- skip: options?.skip,
1004
- task: (context, task) => task.newListr(
1005
- [
1006
- main3(),
1007
- {
1008
- task: (context2, task2) => compiler.hooks.afterPersist.promise(task2)
1009
- }
1010
- ],
1011
- {
1012
- concurrent: false
1013
- }
1014
- )
1015
- };
1016
- }
1017
-
1018
- // src/compiler/tasks/compile/index.ts
1019
- function main4(compiler) {
1020
- return {
1021
- task: async (context, task) => {
1022
- if (!context.rc) throw new Error("Please run setup task first.");
1023
- if (!context.documents) throw new Error("Please run shaking task first.");
1024
- context.artifacts = [];
1025
- await compiler.hooks.compile.promise(task);
1026
- }
1027
- };
1028
- }
1029
- function createCompileTask(compiler, options) {
1030
- return {
1031
- title: "Compile",
1032
- enabled: options?.enabled,
1033
- skip: options?.skip,
1034
- task: (context, task) => task.newListr(
1035
- [
1036
- {
1037
- task: (context2, task2) => compiler.hooks.beforeCompile.promise(task2)
1038
- },
1039
- main4(compiler),
1040
- {
1041
- task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
1042
- }
1043
- ],
1044
- {
1045
- concurrent: false
1046
- }
1047
- )
1048
- };
1049
- }
1050
-
1051
- // src/compiler/intercepter/print-information.ts
1052
- function proxyTaskWrapper(pluginName, task) {
1053
- return new Proxy(task, {
1054
- set(target, prop2, value) {
1055
- if (prop2 !== "output") {
1056
- return Reflect.set(target, prop2, value);
1057
- }
1058
- target.output = `[Plugin: ${pluginName}] ${value}`;
1059
- return true;
1060
- }
1061
- });
1062
- }
1063
- function printInformation(taskIndex) {
1064
- return {
1065
- register: (tap) => {
1066
- const fn = tap.fn;
1067
- if (tap.type === "promise") {
1068
- tap.fn = (...args) => {
1069
- const task = args[taskIndex];
1070
- const proxyTask = proxyTaskWrapper(tap.name, task);
1071
- args[taskIndex] = proxyTask;
1072
- proxyTask.output = "Processing...";
1073
- return fn(...args);
1074
- };
1075
- }
1076
- if (tap.type === "sync") {
1077
- tap.fn = (...args) => {
1078
- const task = args[taskIndex];
1079
- const proxyTask = proxyTaskWrapper(tap.name, task);
1080
- args[taskIndex] = proxyTask;
1081
- proxyTask.output = "Processing...";
1082
- return fn(...args);
1083
- };
1084
- }
1085
- if (tap.type === "async") {
1086
- tap.fn = (...args) => {
1087
- const task = args[taskIndex];
1088
- const proxyTask = proxyTaskWrapper(tap.name, task);
1089
- args[taskIndex] = proxyTask;
1090
- proxyTask.output = "Processing...";
1091
- return fn(...args);
1092
- };
1093
- }
1094
- return tap;
1095
- }
1096
- };
1097
- }
1098
-
1099
- // src/compiler/intercepter/perfect-error-message.ts
1100
- import * as R10 from "ramda";
1101
- function perfectErrorMessage() {
1102
- return {
1103
- register: (tap) => {
1104
- const fn = tap.fn;
1105
- function prefix(err) {
1106
- if (err instanceof Error) {
1107
- err.message = `[Plugin: ${tap.name}] ${err.message}`;
1108
- }
1109
- }
1110
- if (tap.type === "promise") {
1111
- tap.fn = async (...args) => {
1112
- try {
1113
- return await fn(...args);
1114
- } catch (err) {
1115
- prefix(err);
1116
- throw err;
1117
- }
1118
- };
1119
- }
1120
- if (tap.type === "sync") {
1121
- tap.fn = (...args) => {
1122
- try {
1123
- return fn(...args);
1124
- } catch (err) {
1125
- prefix(err);
1126
- throw err;
1127
- }
1128
- };
1129
- }
1130
- if (tap.type === "async") {
1131
- tap.fn = (...args) => {
1132
- const callback = R10.last(args);
1133
- return fn(...R10.init(args), (err, result) => {
1134
- prefix(err);
1135
- return callback(err, result);
1136
- });
1137
- };
1138
- }
1139
- return tap;
1140
- }
1141
- };
1142
- }
1143
-
1144
- // src/plugins/eslint/index.ts
1145
- import { ESLint } from "eslint";
1146
-
1147
- // src/plugins/prettier/prettier.plugin.ts
1148
- import { exec } from "child_process";
1149
- import { promisify } from "util";
1150
- var execAsync = promisify(exec);
1151
-
1152
- // src/plugins/body-fallback/index.ts
1153
- import * as R22 from "ramda";
1154
-
1155
- // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
1156
- import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook2 } from "tapable";
1157
-
1158
- // src/plugins/generate-micro-function/constants/metadata-storage.ts
1159
- var MetadataStorage = /* @__PURE__ */ new WeakMap();
1160
-
1161
- // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
1162
- import * as R21 from "ramda";
1163
- import * as path10 from "path";
1164
- import * as changeCase6 from "change-case";
1165
-
1166
- // src/plugins/generate-declaration/generate-declaration.plugin.ts
1167
- import { AsyncSeriesWaterfallHook } from "tapable";
1168
-
1169
- // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
1170
- import * as path9 from "path";
1171
- import * as changeCase5 from "change-case";
1172
-
1173
- // src/transformers/json-schema/comment.renderer.ts
1174
- var CommentRenderer = class {
1175
- constructor(schema) {
1176
- this.schema = schema;
714
+ // src/transformers/json-schema/comment.renderer.ts
715
+ var CommentRenderer = class {
716
+ constructor(schema) {
717
+ this.schema = schema;
1177
718
  }
1178
719
  render() {
1179
720
  const schema = this.schema;
@@ -1198,7 +739,7 @@ var CommentRenderer = class {
1198
739
  };
1199
740
 
1200
741
  // src/transformers/json-schema/declaration.renderer.ts
1201
- import * as R12 from "ramda";
742
+ import * as R7 from "ramda";
1202
743
 
1203
744
  // src/utils/indent.ts
1204
745
  function indent(space, text) {
@@ -1208,9 +749,9 @@ function indent(space, text) {
1208
749
  }
1209
750
 
1210
751
  // src/transformers/json-schema/reference.transformer.ts
1211
- import * as R11 from "ramda";
752
+ import * as R6 from "ramda";
1212
753
  var ReferenceTransformer = class {
1213
- static toDeclaration(schema, alias2 = R11.identity) {
754
+ static toDeclaration(schema, alias2 = R6.identity) {
1214
755
  if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
1215
756
  const parts = schema.$ref.split("/");
1216
757
  return alias2(parts[parts.length - 1]) || "unknown";
@@ -1266,7 +807,7 @@ var DeclarationRenderer = class {
1266
807
  return "any[]";
1267
808
  }
1268
809
  renderObject(schema) {
1269
- if ((!schema.properties || R12.isEmpty(schema.properties)) && (!schema.additionalProperties || R12.isEmpty(schema.additionalProperties))) {
810
+ if ((!schema.properties || R7.isEmpty(schema.properties)) && (!schema.additionalProperties || R7.isEmpty(schema.additionalProperties))) {
1270
811
  return "object";
1271
812
  }
1272
813
  const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
@@ -1332,7 +873,7 @@ var JsonSchemaTransformer = class {
1332
873
  };
1333
874
 
1334
875
  // src/transformers/schema-definition/schema-definition.transformer.ts
1335
- import * as R13 from "ramda";
876
+ import * as R8 from "ramda";
1336
877
  var SchemaDefinitionTransformer = class {
1337
878
  static toDeclaration(schemaDefinition, options) {
1338
879
  const dependencies = schemaDefinition.getDependencies();
@@ -1352,7 +893,7 @@ var SchemaDefinitionTransformer = class {
1352
893
  `type ${schemaDefinition.name} = unknown`,
1353
894
  "",
1354
895
  "/* @anchor:file:end */"
1355
- ].filter(R13.isNotNil).join("\n");
896
+ ].filter(R8.isNotNil).join("\n");
1356
897
  }
1357
898
  if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
1358
899
  const $schema = JsonSchemaTransformer.toDeclaration(schemaDefinition.schema);
@@ -1365,7 +906,7 @@ var SchemaDefinitionTransformer = class {
1365
906
  $declaration,
1366
907
  "",
1367
908
  "/* @anchor:file:end */"
1368
- ].filter(R13.isNotNil).join("\n");
909
+ ].filter(R8.isNotNil).join("\n");
1369
910
  }
1370
911
  return [
1371
912
  "/* @anchor:file:start */",
@@ -1375,12 +916,12 @@ var SchemaDefinitionTransformer = class {
1375
916
  `export type ${schemaDefinition.name} = ${JsonSchemaTransformer.toDeclaration(schemaDefinition.schema)}`,
1376
917
  "",
1377
918
  "/* @anchor:file:end */"
1378
- ].filter(R13.isNotNil).join("\n");
919
+ ].filter(R8.isNotNil).join("\n");
1379
920
  }
1380
921
  };
1381
922
 
1382
923
  // src/transformers/operation-definition/comment.renderer.ts
1383
- import * as R14 from "ramda";
924
+ import * as R9 from "ramda";
1384
925
  var CommentRenderer2 = class {
1385
926
  constructor(operationDefinition) {
1386
927
  this.operationDefinition = operationDefinition;
@@ -1390,11 +931,11 @@ var CommentRenderer2 = class {
1390
931
  if (!operation.summary && !operation.description) return "";
1391
932
  const lines = ["/**"];
1392
933
  if (operation.summary && typeof operation.summary === "string") {
1393
- lines.push(` * ${R14.trim(operation.summary)}`);
934
+ lines.push(` * ${R9.trim(operation.summary)}`);
1394
935
  lines.push(" *");
1395
936
  }
1396
937
  if (operation.description && typeof operation.description === "string") {
1397
- lines.push(` * @description ${R14.trim(operation.description)}`);
938
+ lines.push(` * @description ${R9.trim(operation.description)}`);
1398
939
  }
1399
940
  lines.push(" */");
1400
941
  return lines.join("\n");
@@ -1402,7 +943,7 @@ var CommentRenderer2 = class {
1402
943
  };
1403
944
 
1404
945
  // src/transformers/operation-definition/declaration.renderer.ts
1405
- import * as R15 from "ramda";
946
+ import * as R14 from "ramda";
1406
947
 
1407
948
  // src/transformers/operation-definition/utils/type-name-factory.ts
1408
949
  import * as changeCase from "change-case";
@@ -1411,6 +952,182 @@ function typeNameFactory(operationDefinition) {
1411
952
  return (name) => `${pascalCaseOperationId}${name}`;
1412
953
  }
1413
954
 
955
+ // src/utils/openapi-utils/dereference.ts
956
+ function dereference($ref, swagger) {
957
+ let value;
958
+ for (const key of $ref.split("/")) {
959
+ if (key === "#") {
960
+ value = swagger;
961
+ } else {
962
+ value = value[key];
963
+ }
964
+ if (!value) break;
965
+ }
966
+ return value;
967
+ }
968
+
969
+ // src/utils/openapi-utils/dereference-operation.ts
970
+ import * as R12 from "ramda";
971
+ import jsonpointer2 from "jsonpointer";
972
+ import { JSONPath as JSONPath4 } from "jsonpath-plus";
973
+
974
+ // src/utils/openapi-utils/remove-undefined-ref.ts
975
+ import * as R11 from "ramda";
976
+ import jsonpointer from "jsonpointer";
977
+ import { JSONPath as JSONPath3 } from "jsonpath-plus";
978
+
979
+ // src/utils/openapi-utils/is-ref-defined.ts
980
+ import * as R10 from "ramda";
981
+ function isRefDefined($ref, swagger) {
982
+ if ($ref.startsWith("#/")) {
983
+ const path12 = $ref.replace("#/", "").split("/");
984
+ return R10.path(path12, swagger) !== void 0;
985
+ }
986
+ return false;
987
+ }
988
+
989
+ // src/utils/openapi-utils/remove-undefined-ref.ts
990
+ function removeUndefinedRef(swagger) {
991
+ const shadow = R11.clone(swagger);
992
+ const matches = JSONPath3({
993
+ path: "$..*['$ref']^",
994
+ json: swagger,
995
+ resultType: "all"
996
+ });
997
+ for (const match of matches) {
998
+ if (match.value.$ref && !isRefDefined(match.value.$ref, swagger)) {
999
+ jsonpointer.set(shadow, match.pointer, R11.omit(["$ref"], match.value));
1000
+ }
1001
+ }
1002
+ return shadow;
1003
+ }
1004
+
1005
+ // src/utils/openapi-utils/dereference-operation.ts
1006
+ function dereferencePathObject(swagger) {
1007
+ const matches = JSONPath4({
1008
+ path: "$.paths.*.$ref^",
1009
+ json: swagger,
1010
+ resultType: "all"
1011
+ });
1012
+ for (const match of matches) {
1013
+ const value = dereference(match.value.$ref, swagger);
1014
+ jsonpointer2.set(swagger, match.pointer, value);
1015
+ }
1016
+ }
1017
+ function dereferenceRequestBody(swagger) {
1018
+ const matches = JSONPath4({
1019
+ path: "$.paths.*.*.requestBody.$ref^",
1020
+ json: swagger,
1021
+ resultType: "all"
1022
+ });
1023
+ for (const match of matches) {
1024
+ const value = dereference(match.value.$ref, swagger);
1025
+ jsonpointer2.set(swagger, match.pointer, value);
1026
+ }
1027
+ }
1028
+ function dereferenceResponses(swagger) {
1029
+ const matches = [
1030
+ ...JSONPath4({
1031
+ path: "$.paths.*.*.responses.*.$ref^",
1032
+ json: swagger,
1033
+ resultType: "all"
1034
+ }),
1035
+ ...JSONPath4({
1036
+ path: "$.paths.*.*.responses.*.headers.*.$ref^",
1037
+ json: swagger,
1038
+ resultType: "all"
1039
+ })
1040
+ ];
1041
+ for (const match of matches) {
1042
+ const value = dereference(match.value.$ref, swagger);
1043
+ jsonpointer2.set(swagger, match.pointer, value);
1044
+ }
1045
+ }
1046
+ function dereferenceParameters(swagger) {
1047
+ const matches = JSONPath4({
1048
+ path: "$.paths.*.*.parameters.*.$ref^",
1049
+ json: swagger,
1050
+ resultType: "all"
1051
+ });
1052
+ for (const match of matches) {
1053
+ const value = dereference(match.value.$ref, swagger);
1054
+ jsonpointer2.set(swagger, match.pointer, value);
1055
+ }
1056
+ }
1057
+ function dereferenceOperation(swagger) {
1058
+ const shadow = R12.clone(swagger);
1059
+ dereferencePathObject(shadow);
1060
+ dereferenceRequestBody(shadow);
1061
+ dereferenceResponses(shadow);
1062
+ dereferenceParameters(shadow);
1063
+ return removeUndefinedRef(shadow);
1064
+ }
1065
+
1066
+ // src/utils/openapi-utils/dereference-deep.ts
1067
+ function dereferenceDeep($ref, swagger) {
1068
+ const stack = [$ref];
1069
+ let value;
1070
+ while (true) {
1071
+ const last2 = stack[stack.length - 1];
1072
+ value = dereference(last2, swagger);
1073
+ if (JsonSchemaUtils.isRef(value)) {
1074
+ if (!stack.includes(value.$ref)) {
1075
+ stack.push(value.$ref);
1076
+ continue;
1077
+ } else {
1078
+ throw new Error(`Circular reference detected: ${stack.join(" -> ")} -> ${value.$ref}`);
1079
+ }
1080
+ }
1081
+ break;
1082
+ }
1083
+ return value;
1084
+ }
1085
+
1086
+ // src/utils/openapi-utils/to-3_1.ts
1087
+ import { upgrade } from "@scalar/openapi-parser";
1088
+ function To3_1(openapi) {
1089
+ const { specification } = upgrade(openapi);
1090
+ return specification;
1091
+ }
1092
+
1093
+ // src/utils/openapi-utils/map-operation.ts
1094
+ import * as R13 from "ramda";
1095
+ function mapOperation(specification, mapper) {
1096
+ const shadow = R13.clone(specification);
1097
+ for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
1098
+ for (const m in pathItem) {
1099
+ const method = m.toLowerCase();
1100
+ if (!SupportedMethods.includes(method)) continue;
1101
+ if (typeof pathItem[m] !== "object" || Array.isArray(pathItem[m]) || pathItem[m] === null) continue;
1102
+ const operation = pathItem[m];
1103
+ pathItem[m] = mapper(method, pathname, operation);
1104
+ }
1105
+ }
1106
+ return shadow;
1107
+ }
1108
+
1109
+ // src/utils/openapi-utils/map-parameter.ts
1110
+ function mapParameter(specification, mapper) {
1111
+ return mapOperation(specification, (method, pathname, operation) => {
1112
+ if (!operation.parameters) return operation;
1113
+ operation.parameters = operation.parameters.map((parameter) => mapper(method, pathname, operation, parameter));
1114
+ return operation;
1115
+ });
1116
+ }
1117
+
1118
+ // src/utils/openapi-utils/index.ts
1119
+ var OpenapiUtils = class {
1120
+ static isRefDefined = isRefDefined;
1121
+ static dereference = dereference;
1122
+ static dereferenceDeep = dereferenceDeep;
1123
+ static removeUndefinedRef = removeUndefinedRef;
1124
+ static dereferenceOperation = dereferenceOperation;
1125
+ static mapOperation = mapOperation;
1126
+ static mapParameter = mapParameter;
1127
+ // static updateOperationId = updateOperationId
1128
+ static to3_1 = To3_1;
1129
+ };
1130
+
1414
1131
  // src/transformers/operation-definition/declaration.renderer.ts
1415
1132
  var alias = (name) => `${name}Schema`;
1416
1133
  var DeclarationRenderer2 = class {
@@ -1421,7 +1138,7 @@ var DeclarationRenderer2 = class {
1421
1138
  }
1422
1139
  typeName;
1423
1140
  renderResponseBodies(operation, options) {
1424
- if (!operation.responses || R15.isEmpty(operation.responses)) {
1141
+ if (!operation.responses || R14.isEmpty(operation.responses)) {
1425
1142
  return `export interface ${this.typeName("ResponseBodies")} {}`;
1426
1143
  }
1427
1144
  const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
@@ -1572,15 +1289,28 @@ var DeclarationRenderer2 = class {
1572
1289
  "}",
1573
1290
  "",
1574
1291
  "/* @anchor:file:end */"
1575
- ].filter(R15.isNotNil).join("\n");
1292
+ ].filter(R14.isNotNil).join("\n");
1576
1293
  }
1577
1294
  };
1578
1295
 
1579
1296
  // src/transformers/operation-definition/micro-function.renderer.ts
1580
- import * as R17 from "ramda";
1297
+ import * as R16 from "ramda";
1298
+
1299
+ // src/exception.ts
1300
+ import { CustomError } from "ts-custom-error";
1301
+ import wrap from "word-wrap";
1302
+ var Exception = class extends CustomError {
1303
+ constructor(module, message) {
1304
+ const moduleName = typeof module === "string" ? module : module.name;
1305
+ const msg = wrap(message, { width: 60, indent: " " });
1306
+ super(`${moduleName} module failed to compile:
1307
+ ${msg}`);
1308
+ Object.defineProperty(this, "name", { value: "KeqCLI_Exception" });
1309
+ }
1310
+ };
1581
1311
 
1582
1312
  // src/transformers/operation-definition/typescript-snippet.ts
1583
- import * as R16 from "ramda";
1313
+ import * as R15 from "ramda";
1584
1314
  var OperationDefinitionSnippet = class {
1585
1315
  constructor(operationDefinition, options) {
1586
1316
  this.operationDefinition = operationDefinition;
@@ -1637,7 +1367,7 @@ var OperationDefinitionSnippet = class {
1637
1367
  const { operation } = this.operationDefinition;
1638
1368
  const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1639
1369
  const option = this.getQsParameters(p);
1640
- const $option = !option || R16.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1370
+ const $option = !option || R15.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1641
1371
  return `if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1642
1372
  }).join("\n");
1643
1373
  return $query;
@@ -1707,7 +1437,7 @@ var OperationDefinitionSnippet = class {
1707
1437
  } catch (err) {
1708
1438
  return this.renderErrorComment(err, mediaType);
1709
1439
  }
1710
- }).filter(R16.isNotNil).join("\n");
1440
+ }).filter(R15.isNotNil).join("\n");
1711
1441
  return $requestBody;
1712
1442
  }
1713
1443
  renderErrorComment(err, mediaType) {
@@ -1782,7 +1512,7 @@ var OperationDefinitionMicroFunctionRenderer = class {
1782
1512
  `${operationId}.pathname = pathname`,
1783
1513
  `${operationId}.method = method`,
1784
1514
  "/* @anchor:file:end */"
1785
- ].filter(R17.isNotNil).join("\n");
1515
+ ].filter(R16.isNotNil).join("\n");
1786
1516
  }
1787
1517
  renderDependencies() {
1788
1518
  const declarationFilepath = this.options.getOperationDefinitionDeclarationFilepath(this.operationDefinition);
@@ -1809,7 +1539,7 @@ var OperationDefinitionMicroFunctionRenderer = class {
1809
1539
  };
1810
1540
 
1811
1541
  // src/transformers/operation-definition/nestjs-method.renderer.ts
1812
- import * as R18 from "ramda";
1542
+ import * as R17 from "ramda";
1813
1543
  var OperationDefinitionNestjsMethodRenderer = class {
1814
1544
  constructor(operationDefinition, options) {
1815
1545
  this.operationDefinition = operationDefinition;
@@ -1862,7 +1592,7 @@ var OperationDefinitionNestjsMethodRenderer = class {
1862
1592
  "",
1863
1593
  " return req",
1864
1594
  "}"
1865
- ].filter(R18.isNotNil).join("\n");
1595
+ ].filter(R17.isNotNil).join("\n");
1866
1596
  }
1867
1597
  renderOperationDeclaration(operationDefinition) {
1868
1598
  const { operationId } = operationDefinition;
@@ -1896,11 +1626,11 @@ var OperationDefinitionTransformer = class {
1896
1626
  };
1897
1627
 
1898
1628
  // src/transformers/entrypoint/entrypoint.transformer.ts
1899
- import * as path7 from "path";
1629
+ import * as path5 from "path";
1900
1630
  var EntrypointTransformer = class {
1901
1631
  static toTypescript(exports, options) {
1902
1632
  const $exports = exports.map((exportArtifact) => {
1903
- const relativePath = path7.relative(
1633
+ const relativePath = path5.relative(
1904
1634
  options.dirpath,
1905
1635
  exportArtifact.filepath
1906
1636
  ).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, options.esm ? ".js" : "");
@@ -1917,128 +1647,26 @@ var EntrypointTransformer = class {
1917
1647
  };
1918
1648
 
1919
1649
  // src/transformers/api-document/nestjs-client.renderer.ts
1920
- import * as R19 from "ramda";
1650
+ import * as R18 from "ramda";
1921
1651
  import * as changeCase2 from "change-case";
1922
- var NestjsClientRenderer = class {
1923
- constructor(document, options) {
1924
- this.document = document;
1925
- this.options = options;
1926
- }
1927
- renderDependencies() {
1928
- const $operations = this.document.operations.map((operationDefinition) => {
1929
- const filepath = this.options.getOperationDefinitionDeclarationFilepath(operationDefinition);
1930
- const typeName = typeNameFactory(operationDefinition);
1931
- return `import type { ${typeName("Operation")}, ${typeName("ResponseBodies")}, ${typeName("RequestParameters")} } from "${filepath}"`;
1932
- }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
1933
- return [
1934
- 'import { Injectable, Logger } from "@nestjs/common"',
1935
- 'import { Keq, KeqRequest } from "keq"',
1936
- ...$operations
1937
- ].join("\n");
1938
- }
1939
- render() {
1940
- const moduleName = changeCase2.pascalCase(this.document.module.name);
1941
- const $dependencies = this.renderDependencies();
1942
- const $operations = this.document.operations.map((operation) => OperationDefinitionTransformer.toNestjsMethod(operation, {
1943
- esm: this.options.esm
1944
- })).join("\n\n");
1945
- return [
1946
- "/* @anchor:file:start */",
1947
- "",
1948
- $dependencies,
1949
- "",
1950
- "@Injectable()",
1951
- `export class ${moduleName}Client {`,
1952
- ` private readonly logger = new Logger(${moduleName}Client.name)`,
1953
- "",
1954
- " constructor(",
1955
- " // @anchor:client-constructor-parameters:start",
1956
- " private readonly request: KeqRequest,",
1957
- " // @anchor:client-constructor-parameters:end",
1958
- " ) {}",
1959
- "",
1960
- indent(2, $operations),
1961
- "}",
1962
- "",
1963
- "/* @anchor:file:end */"
1964
- ].filter(R19.isNotNil).join("\n");
1965
- }
1966
- };
1967
1652
 
1968
1653
  // src/transformers/api-document/nestjs-module.renderer.ts
1969
1654
  import * as changeCase3 from "change-case";
1970
- var NestjsModuleRenderer = class {
1971
- constructor(document, options) {
1972
- this.document = document;
1973
- this.options = options;
1974
- }
1975
- render() {
1976
- const moduleName = changeCase3.pascalCase(this.document.module.name);
1977
- const clientFilepath = this.options.getNestjsClientFilepath(this.document).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, this.options.esm ? ".js" : "");
1978
- return [
1979
- "/* @anchor:file:start */",
1980
- 'import { Module, Inject, ConfigurableModuleBuilder, Global } from "@nestjs/common"',
1981
- 'import { KeqRequest } from "keq"',
1982
- 'import { KeqModuleOptions } from "@keq-request/nestjs"',
1983
- `import { ${moduleName}Client } from "${clientFilepath}"`,
1984
- "",
1985
- "",
1986
- "const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = new ConfigurableModuleBuilder<KeqModuleOptions>().build()",
1987
- "",
1988
- "@Global()",
1989
- "@Module({",
1990
- " imports: [],",
1991
- " controllers: [],",
1992
- ` providers: [${moduleName}Client],`,
1993
- ` exports: [${moduleName}Client],`,
1994
- "})",
1995
- `export class ${moduleName}Module extends ConfigurableModuleClass {`,
1996
- "",
1997
- " constructor(",
1998
- " @Inject(MODULE_OPTIONS_TOKEN) private readonly options: KeqModuleOptions,",
1999
- " private readonly request: KeqRequest,",
2000
- " ) {",
2001
- " super()",
2002
- " }",
2003
- "",
2004
- " onModuleInit() {",
2005
- " if (this.options.middlewares) {",
2006
- " for (const middleware of this.options.middlewares) {",
2007
- " this.request.use(middleware)",
2008
- " }",
2009
- " }",
2010
- " }",
2011
- "}",
2012
- "",
2013
- "/* @anchor:file:end */"
2014
- ].join("\n");
2015
- }
2016
- };
2017
-
2018
- // src/transformers/api-document/api-document.transformer.ts
2019
- var ApiDocumentTransformer = class {
2020
- static toNestjsModule(document, options) {
2021
- return new NestjsModuleRenderer(document, options).render();
2022
- }
2023
- static toNestjsClient(document, options) {
2024
- return new NestjsClientRenderer(document, options).render();
2025
- }
2026
- };
2027
1655
 
2028
1656
  // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2029
- import * as R20 from "ramda";
2030
- import * as path8 from "path";
1657
+ import * as R19 from "ramda";
1658
+ import * as path6 from "path";
2031
1659
  import * as changeCase4 from "change-case";
2032
1660
 
2033
1661
  // src/plugins/generate-declaration/constants/metadata-storage.ts
2034
- var MetadataStorage2 = /* @__PURE__ */ new WeakMap();
1662
+ var MetadataStorage4 = /* @__PURE__ */ new WeakMap();
2035
1663
 
2036
1664
  // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2037
1665
  var SCHEMA_GENERATOR = "schemaGenerator";
2038
1666
  var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2039
1667
  async compile(compiler, task) {
2040
1668
  const context = compiler.context;
2041
- const metadata = MetadataStorage2.get(compiler);
1669
+ const metadata = MetadataStorage4.get(compiler);
2042
1670
  const rc = context.rc;
2043
1671
  const documents = context.documents;
2044
1672
  const schemaDefinitions = documents.flatMap((document) => document.schemas);
@@ -2054,7 +1682,7 @@ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2054
1682
  ])
2055
1683
  )
2056
1684
  );
2057
- const entrypoints = R20.collectBy(
1685
+ const entrypoints = R19.collectBy(
2058
1686
  (schemaDefinition) => schemaDefinition.module.name,
2059
1687
  schemaDefinitions
2060
1688
  ).map((schemaDefinitions2) => [
@@ -2069,7 +1697,7 @@ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2069
1697
  }
2070
1698
  generateSchemaDefinitionsArtifact(schemaDefinition, rc) {
2071
1699
  const filepath = _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(schemaDefinition, rc.fileNamingStyle);
2072
- const dirpath = path8.dirname(filepath);
1700
+ const dirpath = path6.dirname(filepath);
2073
1701
  const artifact = new Artifact({
2074
1702
  id: _SchemaDeclarationGenerator.getSchemaDefinitionArtifactId(schemaDefinition),
2075
1703
  filepath,
@@ -2078,7 +1706,7 @@ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2078
1706
  {
2079
1707
  esm: rc.esm,
2080
1708
  getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2081
- const relativePath = path8.relative(
1709
+ const relativePath = path6.relative(
2082
1710
  dirpath,
2083
1711
  _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2084
1712
  );
@@ -2092,7 +1720,7 @@ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2092
1720
  }
2093
1721
  generateEntrypointArtifact(moduleDefinition, exports, rc) {
2094
1722
  const filepath = _SchemaDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2095
- const dirpath = path8.dirname(filepath);
1723
+ const dirpath = path6.dirname(filepath);
2096
1724
  const artifact = new Artifact({
2097
1725
  id: _SchemaDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2098
1726
  filepath,
@@ -2111,7 +1739,7 @@ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2111
1739
  ].join("/");
2112
1740
  }
2113
1741
  static getEntrypointArtifactId(moduleDefinition) {
2114
- return `${moduleDefinition.address}/components/schemas/entrypoint?generator=${SCHEMA_GENERATOR}`;
1742
+ return `${moduleDefinition.address.url}/components/schemas/entrypoint?generator=${SCHEMA_GENERATOR}`;
2115
1743
  }
2116
1744
  static getSchemaDefinitionArtifactFilepath(schemaDefinition, fileNamingStyle) {
2117
1745
  const filename = `${changeCase4[fileNamingStyle](schemaDefinition.name)}.schema.ts`;
@@ -2134,7 +1762,7 @@ var OPERATION_GENERATOR = "operationDeclarationGenerator";
2134
1762
  var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2135
1763
  async compile(compiler, task) {
2136
1764
  const context = compiler.context;
2137
- const metadata = MetadataStorage2.get(compiler);
1765
+ const metadata = MetadataStorage4.get(compiler);
2138
1766
  const rc = context.rc;
2139
1767
  const documents = context.documents;
2140
1768
  const operationDefinitions = documents.flatMap((document) => document.operations);
@@ -2154,7 +1782,7 @@ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2154
1782
  }
2155
1783
  generateOperationDefinitionArtifact(operationDefinition, rc) {
2156
1784
  const filepath = _OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2157
- const dirpath = path9.dirname(filepath);
1785
+ const dirpath = path7.dirname(filepath);
2158
1786
  const artifact = new Artifact({
2159
1787
  id: _OperationDeclarationGenerator.getOperationDefinitionArtifactId(operationDefinition),
2160
1788
  filepath,
@@ -2163,7 +1791,7 @@ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2163
1791
  {
2164
1792
  esm: rc.esm,
2165
1793
  getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2166
- const relativePath = path9.relative(
1794
+ const relativePath = path7.relative(
2167
1795
  dirpath,
2168
1796
  SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2169
1797
  );
@@ -2177,7 +1805,7 @@ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2177
1805
  }
2178
1806
  generateEntrypointArtifact(moduleDefinition, exports, rc) {
2179
1807
  const filepath = _OperationDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2180
- const dirpath = path9.dirname(filepath);
1808
+ const dirpath = path7.dirname(filepath);
2181
1809
  const artifact = new Artifact({
2182
1810
  id: _OperationDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2183
1811
  filepath,
@@ -2209,7 +1837,7 @@ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2209
1837
  ].join("/");
2210
1838
  }
2211
1839
  static getEntrypointArtifactId(moduleDefinition) {
2212
- return `${moduleDefinition.address}/paths/entrypoint?generator=${OPERATION_GENERATOR}`;
1840
+ return `${moduleDefinition.address.url}/paths/entrypoint?generator=${OPERATION_GENERATOR}`;
2213
1841
  }
2214
1842
  };
2215
1843
 
@@ -2222,6 +1850,7 @@ var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
2222
1850
  constructor() {
2223
1851
  }
2224
1852
  apply(compiler) {
1853
+ if (MetadataStorage4.has(compiler)) return;
2225
1854
  _GenerateDeclarationPlugin.register(compiler);
2226
1855
  compiler.hooks.compile.tapPromise(_GenerateDeclarationPlugin.name, async (task) => {
2227
1856
  compiler.context.artifacts?.push(
@@ -2231,8 +1860,8 @@ var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
2231
1860
  });
2232
1861
  }
2233
1862
  static register(compiler) {
2234
- if (!MetadataStorage2.has(compiler)) {
2235
- MetadataStorage2.set(compiler, {
1863
+ if (!MetadataStorage4.has(compiler)) {
1864
+ MetadataStorage4.set(compiler, {
2236
1865
  hooks: {
2237
1866
  afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "task"]),
2238
1867
  afterSchemaDeclarationArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "schemaDefinition", "task"]),
@@ -2240,7 +1869,7 @@ var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
2240
1869
  }
2241
1870
  });
2242
1871
  }
2243
- return MetadataStorage2.get(compiler);
1872
+ return MetadataStorage4.get(compiler);
2244
1873
  }
2245
1874
  static of(compiler) {
2246
1875
  return this.register(compiler);
@@ -2285,7 +1914,7 @@ var RequestGenerator = class _RequestGenerator {
2285
1914
  var MICRO_FUNCTION_GENERATOR = "microFunctionGenerator";
2286
1915
  var MicroFunctionGenerator = class _MicroFunctionGenerator {
2287
1916
  async compile(compiler, task) {
2288
- const metadata = MetadataStorage.get(compiler);
1917
+ const metadata = MetadataStorage3.get(compiler);
2289
1918
  const context = compiler.context;
2290
1919
  const rc = context.rc;
2291
1920
  const documents = context.documents;
@@ -2303,7 +1932,7 @@ var MicroFunctionGenerator = class _MicroFunctionGenerator {
2303
1932
  )
2304
1933
  );
2305
1934
  const entrypoints = await Promise.all(
2306
- R21.collectBy(
1935
+ R20.collectBy(
2307
1936
  (operationDefinition) => operationDefinition.module.name,
2308
1937
  operationDefinitions
2309
1938
  ).map((operationDefinitions2) => [
@@ -2322,21 +1951,21 @@ var MicroFunctionGenerator = class _MicroFunctionGenerator {
2322
1951
  }
2323
1952
  generateOperationDefinitionArtifact(operationDefinition, rc) {
2324
1953
  const filepath = _MicroFunctionGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2325
- const dirpath = path10.dirname(filepath);
1954
+ const dirpath = path8.dirname(filepath);
2326
1955
  const artifact = new Artifact({
2327
1956
  id: _MicroFunctionGenerator.getOperationDefinitionArtifactId(operationDefinition),
2328
1957
  filepath,
2329
1958
  content: OperationDefinitionTransformer.toMicroFunction(operationDefinition, {
2330
1959
  esm: rc.esm,
2331
1960
  getOperationDefinitionDeclarationFilepath(operationDefinition2) {
2332
- const relativePath = path10.relative(
1961
+ const relativePath = path8.relative(
2333
1962
  dirpath,
2334
1963
  OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition2, rc.fileNamingStyle)
2335
1964
  );
2336
1965
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2337
1966
  },
2338
1967
  getRequestFilepath() {
2339
- const relativePath = path10.relative(
1968
+ const relativePath = path8.relative(
2340
1969
  dirpath,
2341
1970
  RequestGenerator.getRequestArtifactFilepath()
2342
1971
  );
@@ -2388,6 +2017,7 @@ var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2388
2017
  microFunctionGenerator = new MicroFunctionGenerator();
2389
2018
  requestGenerator = new RequestGenerator();
2390
2019
  apply(compiler) {
2020
+ if (MetadataStorage3.has(compiler)) return;
2391
2021
  _GenerateMicroFunctionPlugin.register(compiler);
2392
2022
  compiler.hooks.compile.tapPromise(_GenerateMicroFunctionPlugin.name, async (task) => {
2393
2023
  const artifacts = [
@@ -2398,15 +2028,15 @@ var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2398
2028
  });
2399
2029
  }
2400
2030
  static register(compiler) {
2401
- if (!MetadataStorage.has(compiler)) {
2402
- MetadataStorage.set(compiler, {
2031
+ if (!MetadataStorage3.has(compiler)) {
2032
+ MetadataStorage3.set(compiler, {
2403
2033
  hooks: {
2404
2034
  afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "task"]),
2405
2035
  afterMicroFunctionArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "operationDefinition", "task"])
2406
2036
  }
2407
2037
  });
2408
2038
  }
2409
- return MetadataStorage.get(compiler);
2039
+ return MetadataStorage3.get(compiler);
2410
2040
  }
2411
2041
  static of(compiler) {
2412
2042
  return this.register(compiler);
@@ -2416,328 +2046,646 @@ var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2416
2046
  // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2417
2047
  import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook3 } from "tapable";
2418
2048
 
2419
- // src/plugins/generate-nestjs-module/constants/metadata-storage.ts
2420
- var MetadataStorage3 = /* @__PURE__ */ new WeakMap();
2421
-
2422
2049
  // src/plugins/generate-nestjs-module/generators/nestjs-module.generator.ts
2423
- import * as path11 from "path";
2424
2050
  import * as changeCase7 from "change-case";
2425
- var NESTJS_MODULE_GENERATOR = "nestjs-module-generator";
2426
- var NestjsModuleGenerator = class _NestjsModuleGenerator {
2427
- generateNestjsModuleArtifact(document, rc) {
2428
- const filepath = _NestjsModuleGenerator.getNestjsModuleArtifactFilepath(document, rc.fileNamingStyle);
2429
- const dirname6 = path11.dirname(filepath);
2430
- const artifact = new Artifact({
2431
- id: _NestjsModuleGenerator.getNestjsModuleArtifactId(document),
2432
- filepath,
2433
- content: ApiDocumentTransformer.toNestjsModule(document, {
2434
- esm: rc.esm,
2435
- getNestjsClientFilepath(document2) {
2436
- const relativePath = path11.relative(
2437
- dirname6,
2438
- _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document2, rc.fileNamingStyle)
2439
- );
2440
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2441
- }
2442
- })
2051
+
2052
+ // src/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.ts
2053
+ import { fixSwagger } from "swagger-fix";
2054
+
2055
+ // src/plugins/download-http-file/constants/metadata-storage.ts
2056
+ var MetadataStorage8 = /* @__PURE__ */ new WeakMap();
2057
+
2058
+ // src/plugins/download-http-file/download-http-file.plugin.ts
2059
+ var DownloadHttpFilePlugin = class _DownloadHttpFilePlugin {
2060
+ apply(compiler) {
2061
+ if (MetadataStorage8.has(compiler)) return;
2062
+ _DownloadHttpFilePlugin.register(compiler);
2063
+ compiler.hooks.download.tapPromise(_DownloadHttpFilePlugin.name, async (address, task) => {
2064
+ const { url } = address;
2065
+ if (!url.startsWith("http://") && !url.startsWith("https://")) return void 0;
2066
+ const content = await this.download(address);
2067
+ const spec = this.deserialize(content);
2068
+ return JSON.stringify(spec);
2443
2069
  });
2444
- return artifact;
2445
2070
  }
2446
- generateNestjsClientArtifact(document, rc) {
2447
- const filepath = _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document, rc.fileNamingStyle);
2448
- const dirpath = path11.dirname(filepath);
2449
- const artifact = new Artifact({
2450
- id: _NestjsModuleGenerator.getNestjsClientArtifactId(document),
2451
- filepath,
2452
- content: ApiDocumentTransformer.toNestjsClient(document, {
2453
- esm: rc.esm,
2454
- getOperationDefinitionDeclarationFilepath(operationDefinition) {
2455
- const relativePath = path11.relative(
2456
- dirpath,
2457
- OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle)
2458
- );
2459
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2460
- }
2461
- })
2071
+ async download(address) {
2072
+ const { url, headers } = address;
2073
+ try {
2074
+ const res = await fetch(url, { headers });
2075
+ if (res.status >= 400) throw new Error(`failed with status code ${res.status}`);
2076
+ return await res.text();
2077
+ } catch (e) {
2078
+ if (e instanceof Error) {
2079
+ e.message = `Unable get the openapi/swagger file from ${url}: ${e.message}`;
2080
+ }
2081
+ throw e;
2082
+ }
2083
+ }
2084
+ deserialize(content) {
2085
+ const json = JSON.parse(content);
2086
+ const spec = OpenapiUtils.to3_1(json);
2087
+ return spec;
2088
+ }
2089
+ static register(compiler) {
2090
+ if (!MetadataStorage8.has(compiler)) {
2091
+ MetadataStorage8.set(compiler, {
2092
+ hooks: {}
2093
+ });
2094
+ }
2095
+ return MetadataStorage8.get(compiler);
2096
+ }
2097
+ static of(compiler) {
2098
+ return this.register(compiler);
2099
+ }
2100
+ };
2101
+
2102
+ // src/plugins/download-local-file/download-local-file.plugin.ts
2103
+ import * as path9 from "path";
2104
+ import * as fs3 from "fs/promises";
2105
+ import * as yaml from "js-yaml";
2106
+ import { fileURLToPath } from "url";
2107
+
2108
+ // src/plugins/download-local-file/constants/metadata-storage.ts
2109
+ var MetadataStorage9 = /* @__PURE__ */ new WeakMap();
2110
+
2111
+ // src/plugins/download-local-file/download-local-file.plugin.ts
2112
+ var DownloadLocalFilePlugin = class _DownloadLocalFilePlugin {
2113
+ apply(compiler) {
2114
+ if (MetadataStorage9.has(compiler)) return;
2115
+ _DownloadLocalFilePlugin.register(compiler);
2116
+ compiler.hooks.download.tapPromise(_DownloadLocalFilePlugin.name, async (address, task) => {
2117
+ const { url, encoding } = address;
2118
+ if (!url.startsWith("file://")) return void 0;
2119
+ const filepath = fileURLToPath(url);
2120
+ const fileExt = path9.extname(filepath);
2121
+ const content = await fs3.readFile(filepath, encoding);
2122
+ const str = typeof content === "string" ? content : content.toString(encoding);
2123
+ if ([".yml", ".yaml"].includes(fileExt)) {
2124
+ const value = yaml.load(str);
2125
+ return JSON.stringify(OpenapiUtils.to3_1(value));
2126
+ } else if (fileExt === ".json") {
2127
+ return JSON.stringify(OpenapiUtils.to3_1(JSON.parse(str)));
2128
+ }
2462
2129
  });
2463
- return artifact;
2464
2130
  }
2465
- async compile(compiler, task) {
2466
- const metadata = MetadataStorage3.get(compiler);
2131
+ static register(compiler) {
2132
+ if (!MetadataStorage9.has(compiler)) {
2133
+ MetadataStorage9.set(compiler, {
2134
+ hooks: {}
2135
+ });
2136
+ }
2137
+ return MetadataStorage9.get(compiler);
2138
+ }
2139
+ static of(compiler) {
2140
+ return this.register(compiler);
2141
+ }
2142
+ };
2143
+
2144
+ // src/plugins/shaking/shaking.plugin.ts
2145
+ import { openapiShakingSync } from "@opendoc/openapi-shaking";
2146
+
2147
+ // src/plugins/shaking/constants/metadata-storage.ts
2148
+ var MetadataStorage10 = /* @__PURE__ */ new WeakMap();
2149
+
2150
+ // src/plugins/shaking/shaking.plugin.ts
2151
+ var ShakingPlugin = class _ShakingPlugin {
2152
+ apply(compiler) {
2153
+ if (MetadataStorage10.has(compiler)) return;
2154
+ _ShakingPlugin.register(compiler);
2155
+ compiler.hooks.beforeCompile.tap(_ShakingPlugin.name, (task) => {
2156
+ const matcher = compiler.context.matcher;
2157
+ const documents = compiler.context.documents;
2158
+ compiler.context.documents = documents.map((document) => this.shaking(compiler, document)).filter((document) => !document.isEmpty()).filter((document) => !matcher.isModuleIgnored(document.module));
2159
+ });
2160
+ }
2161
+ shaking(compiler, document) {
2467
2162
  const rc = compiler.context.rc;
2468
- const documents = compiler.context.documents;
2469
- const nestjsModuleArtifacts = await Promise.all(
2470
- documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2471
- this.generateNestjsModuleArtifact(document, rc),
2472
- document,
2473
- task
2474
- ))
2163
+ const matcher = compiler.context.matcher;
2164
+ const isAccepted = (pathname, method, operation) => {
2165
+ if (!SupportedMethods.includes(method)) return false;
2166
+ return !matcher.isOperationIgnored(new OperationDefinition({
2167
+ method,
2168
+ pathname,
2169
+ operation,
2170
+ module: document.module,
2171
+ document
2172
+ }));
2173
+ };
2174
+ const sharkedSwagger = openapiShakingSync(
2175
+ document.specification,
2176
+ isAccepted,
2177
+ { tolerant: rc.tolerant }
2475
2178
  );
2476
- const nestjsClientArtifacts = await Promise.all(
2477
- documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2478
- this.generateNestjsClientArtifact(document, rc),
2479
- document,
2480
- task
2481
- ))
2179
+ return new ApiDocumentV3_1(
2180
+ sharkedSwagger,
2181
+ new ModuleDefinition(
2182
+ document.module.name,
2183
+ {
2184
+ url: `memory://${document.module.name}.v3_1.sharked.json`,
2185
+ headers: {},
2186
+ encoding: "utf8"
2187
+ }
2188
+ )
2482
2189
  );
2483
- return [...nestjsModuleArtifacts, ...nestjsClientArtifacts];
2484
- }
2485
- static getNestjsModuleArtifactFilepath(document, fileNamingStyle) {
2486
- const filename = `${changeCase7[fileNamingStyle](document.module.name)}.module.ts`;
2487
- const filepath = [
2488
- ".",
2489
- changeCase7[fileNamingStyle](document.module.name),
2490
- filename
2491
- ];
2492
- return filepath.join("/");
2493
2190
  }
2494
- static getNestjsModuleArtifactId(document) {
2495
- return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}`;
2496
- }
2497
- static getNestjsClientArtifactFilepath(document, fileNamingStyle) {
2498
- const filename = `${changeCase7[fileNamingStyle](document.module.name)}.client.ts`;
2499
- const filepath = [
2500
- ".",
2501
- changeCase7[fileNamingStyle](document.module.name),
2502
- filename
2503
- ];
2504
- return filepath.join("/");
2191
+ static register(compiler) {
2192
+ if (!MetadataStorage10.has(compiler)) {
2193
+ MetadataStorage10.set(compiler, {
2194
+ hooks: {}
2195
+ });
2196
+ }
2197
+ return MetadataStorage10.get(compiler);
2505
2198
  }
2506
- static getNestjsClientArtifactId(document) {
2507
- return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}-client`;
2199
+ static of(compiler) {
2200
+ return this.register(compiler);
2508
2201
  }
2509
2202
  };
2510
2203
 
2511
- // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2512
- var GenerateNestjsModulePlugin = class _GenerateNestjsModulePlugin {
2513
- nestjsModuleGenerator = new NestjsModuleGenerator();
2204
+ // src/plugins/terminal-select/utils/select-operation-definitions.ts
2205
+ import { select } from "inquirer-select-pro";
2206
+ import { ListrInquirerPromptAdapter } from "@listr2/prompt-adapter-inquirer";
2207
+ async function selectOperationDefinitions(task, operationDefinitions) {
2208
+ const selectedOperationDefinitions = await task.prompt(ListrInquirerPromptAdapter).run(
2209
+ select,
2210
+ {
2211
+ message: "Select Pathname",
2212
+ defaultValue: [],
2213
+ options: (input) => {
2214
+ const items = operationDefinitions.map((op) => ({ name: `${op.module.name} ${op.method.toUpperCase()} ${op.pathname}`, value: op }));
2215
+ if (!input) return items;
2216
+ const keys2 = input.trim().toLowerCase().split(/\s+/);
2217
+ return items.filter((i) => {
2218
+ const name = i.name.toLowerCase();
2219
+ return keys2.every((q) => name.includes(q));
2220
+ });
2221
+ }
2222
+ }
2223
+ );
2224
+ return selectedOperationDefinitions;
2225
+ }
2226
+
2227
+ // src/plugins/terminal-select/constants/metadata-storage.ts
2228
+ var MetadataStorage11 = /* @__PURE__ */ new WeakMap();
2229
+
2230
+ // src/plugins/terminal-select/terminal-select.plugin.ts
2231
+ var TerminalSelectPlugin = class _TerminalSelectPlugin {
2232
+ constructor(options) {
2233
+ this.options = options;
2234
+ }
2514
2235
  apply(compiler) {
2515
- _GenerateNestjsModulePlugin.register(compiler);
2516
- compiler.hooks.compile.tapPromise(_GenerateNestjsModulePlugin.name, async (task) => {
2517
- const artifacts = await this.nestjsModuleGenerator.compile(compiler, task);
2518
- compiler.context.artifacts.push(...artifacts);
2236
+ if (MetadataStorage11.has(compiler)) return;
2237
+ _TerminalSelectPlugin.register(compiler);
2238
+ compiler.hooks.afterDownload.tapPromise(_TerminalSelectPlugin.name, async (task) => {
2239
+ const context = compiler.context;
2240
+ const matcher = context.matcher;
2241
+ const documents = context.documents;
2242
+ const operationDefinitions = documents.flatMap((document) => document.operations);
2243
+ const selectedOperationDefinitions = await selectOperationDefinitions(task, operationDefinitions);
2244
+ if (this.options.clear) {
2245
+ matcher.append({
2246
+ persist: false,
2247
+ ignore: true,
2248
+ moduleName: "*",
2249
+ operationMethod: "*",
2250
+ operationPathname: "*"
2251
+ });
2252
+ }
2253
+ for (const op of selectedOperationDefinitions) {
2254
+ matcher.append({
2255
+ persist: !!this.options.persist,
2256
+ ignore: this.options.mode === "add",
2257
+ moduleName: op.module.name,
2258
+ operationMethod: op.method,
2259
+ operationPathname: op.pathname
2260
+ });
2261
+ }
2519
2262
  });
2520
2263
  }
2521
- static register(compiler) {
2522
- if (!MetadataStorage3.has(compiler)) {
2523
- MetadataStorage3.set(compiler, {
2524
- hooks: {
2525
- afterNestjsModuleArtifactGenerated: new AsyncSeriesWaterfallHook3(["artifact", "document", "task"])
2526
- }
2264
+ static register(compiler) {
2265
+ if (!MetadataStorage11.has(compiler)) {
2266
+ MetadataStorage11.set(compiler, {
2267
+ hooks: {}
2527
2268
  });
2528
2269
  }
2529
- return MetadataStorage3.get(compiler);
2270
+ return MetadataStorage11.get(compiler);
2530
2271
  }
2531
2272
  static of(compiler) {
2532
- return MetadataStorage3.get(compiler);
2273
+ return this.register(compiler);
2533
2274
  }
2534
2275
  };
2535
2276
 
2536
- // src/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.ts
2537
- import { fixSwagger } from "swagger-fix";
2538
-
2539
- // src/plugins/download-http-file/download-http-file.plugin.ts
2540
- import * as validUrl from "valid-url";
2541
- var DownloadHttpFilePlugin = class _DownloadHttpFilePlugin {
2542
- apply(compiler) {
2543
- compiler.hooks.download.tapPromise(_DownloadHttpFilePlugin.name, async (address, task) => {
2544
- if (!validUrl.isUri(address)) return void 0;
2545
- const content = await this.download(address);
2546
- const spec = this.deserialize(content);
2547
- return JSON.stringify(spec);
2548
- });
2277
+ // src/plugins/initialize/initialize.plugin.ts
2278
+ import * as R22 from "ramda";
2279
+ var InitializePlugin = class _InitializePlugin {
2280
+ constructor(options) {
2281
+ this.options = options;
2549
2282
  }
2550
- async download(address) {
2551
- try {
2552
- const res = await fetch(address);
2553
- if (res.status >= 400) throw new Error(`failed with status code ${res.status}`);
2554
- return await res.text();
2555
- } catch (e) {
2556
- if (e instanceof Error) {
2557
- e.message = `Unable get the openapi/swagger file from ${address}: ${e.message}`;
2283
+ apply(compiler) {
2284
+ compiler.hooks.setup.tap(_InitializePlugin.name, (task) => {
2285
+ const plugins = [
2286
+ new DownloadHttpFilePlugin(),
2287
+ new DownloadLocalFilePlugin()
2288
+ ];
2289
+ if (this.options.build) {
2290
+ plugins.push(new ShakingPlugin());
2558
2291
  }
2559
- throw e;
2292
+ if (this.options.interactive) {
2293
+ plugins.push(
2294
+ new TerminalSelectPlugin(
2295
+ typeof this.options.interactive === "object" ? this.options.interactive : { mode: "except" }
2296
+ )
2297
+ );
2298
+ }
2299
+ const rc = compiler.context.rc;
2300
+ plugins.push(
2301
+ ...R22.unnest(
2302
+ (rc.translators || []).map((translator) => {
2303
+ const plugins2 = translator.apply();
2304
+ return plugins2;
2305
+ })
2306
+ )
2307
+ );
2308
+ if (rc.plugins && rc.plugins.length) {
2309
+ plugins.push(...rc.plugins);
2310
+ }
2311
+ for (const plugin of plugins) {
2312
+ plugin.apply(compiler);
2313
+ }
2314
+ });
2315
+ if (this.options.includes && this.options.includes.length) {
2316
+ const modulesIncludes = this.options.includes;
2317
+ compiler.hooks.afterSetup.tap(_InitializePlugin.name, (task) => {
2318
+ const rc = compiler.context.rc;
2319
+ const matcher = compiler.context.matcher;
2320
+ const notExistModules = modulesIncludes.filter((moduleName) => !(moduleName in rc.modules));
2321
+ if (notExistModules.length) {
2322
+ throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
2323
+ }
2324
+ const ignoredModules = R22.difference(R22.keys(rc.modules), modulesIncludes);
2325
+ for (const moduleName of ignoredModules) {
2326
+ matcher.append({
2327
+ persist: false,
2328
+ ignore: true,
2329
+ moduleName,
2330
+ operationMethod: "*",
2331
+ operationPathname: "*"
2332
+ });
2333
+ }
2334
+ });
2560
2335
  }
2561
2336
  }
2562
- deserialize(content) {
2563
- const json = JSON.parse(content);
2564
- const spec = OpenapiUtils.to3_1(json);
2565
- return spec;
2337
+ };
2338
+
2339
+ // src/plugins/overwrite-query-options/overwrite-query-options.plugin.ts
2340
+ var QsArrayFormatUnion = Object.values(QsArrayFormat);
2341
+
2342
+ // src/translators/micro-function.translator.ts
2343
+ var MicroFunctionTranslator = class {
2344
+ apply() {
2345
+ return [
2346
+ new GenerateDeclarationPlugin(),
2347
+ new GenerateMicroFunctionPlugin()
2348
+ ];
2566
2349
  }
2567
2350
  };
2568
2351
 
2569
- // src/plugins/download-local-file/download-local-file.plugin.ts
2570
- import * as path12 from "path";
2571
- import * as fs5 from "fs/promises";
2572
- import * as yaml from "js-yaml";
2573
- var DownloadLocalFilePlugin = class _DownloadLocalFilePlugin {
2574
- apply(compiler) {
2575
- compiler.hooks.download.tapPromise(_DownloadLocalFilePlugin.name, async (address, task) => {
2576
- if (!address.startsWith("./") && !address.startsWith("/") && !address.startsWith("../")) return void 0;
2577
- const fileExt = path12.extname(address);
2578
- const content = await fs5.readFile(address, "utf8");
2579
- if ([".yml", ".yaml"].includes(fileExt)) {
2580
- const value = yaml.load(content);
2581
- return JSON.stringify(OpenapiUtils.to3_1(value));
2582
- } else if (fileExt === ".json") {
2583
- return JSON.stringify(OpenapiUtils.to3_1(JSON.parse(content)));
2352
+ // src/compiler/tasks/setup/index.ts
2353
+ var explore = cosmiconfig("keq");
2354
+ function main(compiler, options) {
2355
+ return {
2356
+ task: async (context, task) => {
2357
+ const result = options?.config ? await explore.load(options.config) : await explore.search();
2358
+ if (!result || "isEmpty" in result && result.isEmpty) {
2359
+ throw new Error("Cannot find config file.");
2360
+ }
2361
+ const rc = parseRuntimeConfig(result.config);
2362
+ if (options?.debug) {
2363
+ await fs4.ensureDir(".keq");
2364
+ rc.debug = true;
2365
+ }
2366
+ rc.tolerant = Boolean(rc.tolerant);
2367
+ if (!rc.translators || !rc.translators.length) {
2368
+ rc.translators = [new MicroFunctionTranslator()];
2369
+ }
2370
+ const packageJsonInfo = findNearestPackageJson();
2371
+ if (packageJsonInfo) {
2372
+ const moduleSystem = getProjectModuleSystem(packageJsonInfo);
2373
+ rc.esm = moduleSystem === "esm";
2374
+ }
2375
+ context.rc = rc;
2376
+ let matcher = new IgnoreMatcher([]);
2377
+ if (result.filepath) {
2378
+ const ignoreFilepath = path10.resolve(path10.dirname(result.filepath), ".keqignore");
2379
+ if (await fs4.exists(ignoreFilepath)) {
2380
+ matcher = await IgnoreMatcher.read(ignoreFilepath);
2381
+ }
2382
+ }
2383
+ const ignoreRules = options.ignore === false ? [] : options.ignore?.rules || [];
2384
+ for (const rule of ignoreRules) {
2385
+ matcher.append({
2386
+ persist: !!rule.persist,
2387
+ ignore: rule.ignore,
2388
+ moduleName: rule.moduleName,
2389
+ operationMethod: rule.operationMethod,
2390
+ operationPathname: rule.operationPathname
2391
+ });
2392
+ }
2393
+ context.matcher = matcher;
2394
+ await compiler.hooks.setup.promise(task);
2395
+ }
2396
+ };
2397
+ }
2398
+ function createSetupTask(compiler, options) {
2399
+ return {
2400
+ title: "Setup",
2401
+ enabled: options?.enabled,
2402
+ skip: options?.skip,
2403
+ task: (context, task) => task.newListr(
2404
+ [
2405
+ main(compiler, options),
2406
+ {
2407
+ task: (context2, task2) => compiler.hooks.afterSetup.promise(task2)
2408
+ }
2409
+ ],
2410
+ {
2411
+ concurrent: false
2412
+ }
2413
+ )
2414
+ };
2415
+ }
2416
+
2417
+ // src/compiler/tasks/download/index.ts
2418
+ import { PRESET_TIMER } from "listr2";
2419
+ import { validate } from "@scalar/openapi-parser";
2420
+ function main2(compiler, options) {
2421
+ return {
2422
+ task: (context, task) => {
2423
+ if (!context.rc || !context.matcher) {
2424
+ throw new Error("Please run setup task first.");
2425
+ }
2426
+ const rc = context.rc;
2427
+ const matcher = context.matcher;
2428
+ context.documents = [];
2429
+ return task.newListr(
2430
+ Object.entries(rc.modules).map(([moduleName, address]) => new ModuleDefinition(moduleName, address)).map((moduleDefinition) => ({
2431
+ title: moduleDefinition.name,
2432
+ task: async (ctx, task2) => {
2433
+ if (options?.skipIgnoredModules && matcher.isModuleIgnored(moduleDefinition)) {
2434
+ task2.skip(`(${moduleDefinition.name}) is ignored`);
2435
+ return;
2436
+ }
2437
+ task2.output = `Downloaded from ${moduleDefinition.address.url}`;
2438
+ const content = await compiler.hooks.download.promise(moduleDefinition.address, moduleDefinition, task2);
2439
+ if (!content) {
2440
+ throw new Exception(moduleDefinition, `Cannot download document from ${moduleDefinition.address.url}`);
2441
+ }
2442
+ const spec = JSON.parse(content);
2443
+ const { valid, errors } = await validate(spec);
2444
+ if (!valid) {
2445
+ const message = `${moduleDefinition.name} module openapi/swagger file does not conform to the openapi specifications or have grammatical errors, which may cause unexpected errors:
2446
+ ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
2447
+ task2.output = message;
2448
+ }
2449
+ OpenapiUtils.dereferenceOperation(spec);
2450
+ const document = new ApiDocumentV3_1(
2451
+ spec,
2452
+ moduleDefinition
2453
+ );
2454
+ ctx.documents?.push(document);
2455
+ }
2456
+ })),
2457
+ {
2458
+ concurrent: true,
2459
+ exitOnError: false,
2460
+ collectErrors: "minimal",
2461
+ rendererOptions: {
2462
+ collapseSubtasks: false,
2463
+ // collapseSkips: false,
2464
+ suffixSkips: true,
2465
+ timer: PRESET_TIMER
2466
+ }
2467
+ }
2468
+ );
2469
+ }
2470
+ };
2471
+ }
2472
+ function createDownloadTask(compiler, options) {
2473
+ return {
2474
+ title: "Download",
2475
+ enabled: options?.enabled,
2476
+ skip: options?.skip,
2477
+ task: (_, task) => task.newListr(
2478
+ [
2479
+ main2(compiler, options),
2480
+ {
2481
+ task: (context, task2) => compiler.hooks.afterDownload.promise(task2)
2482
+ }
2483
+ ],
2484
+ {
2485
+ concurrent: false
2486
+ }
2487
+ )
2488
+ };
2489
+ }
2490
+
2491
+ // src/compiler/tasks/persist/index.ts
2492
+ import * as path11 from "path";
2493
+ import fs5 from "fs-extra";
2494
+ function createPersistArtifactTask() {
2495
+ return {
2496
+ title: "Write files",
2497
+ task: async (context, task) => {
2498
+ if (!context.rc) throw new Error("Please run setup task first.");
2499
+ if (!context.artifacts || context.artifacts.length === 0) {
2500
+ task.skip("No compiled artifacts to persist.");
2501
+ return;
2502
+ }
2503
+ const rc = context.rc;
2504
+ const artifacts = context.artifacts;
2505
+ const total = artifacts.length;
2506
+ let completed = 0;
2507
+ const files = await Promise.all(artifacts.map(async (artifact) => {
2508
+ const realpath = `./${path11.join(rc.outdir, artifact.filepath)}`;
2509
+ await fs5.ensureFile(realpath);
2510
+ await fs5.writeFile(realpath, artifact.renderer());
2511
+ completed += 1;
2512
+ task.output = `Persisted ${completed}/${total} files`;
2513
+ return new Asset(path11.resolve(realpath));
2514
+ }));
2515
+ context.assets = files;
2516
+ }
2517
+ };
2518
+ }
2519
+ function createPersistIgnoreTask() {
2520
+ return {
2521
+ title: "Update .keqignore",
2522
+ task: async (context, task) => {
2523
+ if (!context.matcher) throw new Error("Please run setup task first.");
2524
+ const matcher = context.matcher;
2525
+ await matcher.write(".keqignore");
2526
+ }
2527
+ };
2528
+ }
2529
+ function main3() {
2530
+ return {
2531
+ task: (context, task) => task.newListr(
2532
+ [
2533
+ createPersistArtifactTask(),
2534
+ createPersistIgnoreTask()
2535
+ ],
2536
+ {
2537
+ concurrent: true,
2538
+ rendererOptions: {
2539
+ collapseSubtasks: true
2540
+ }
2541
+ }
2542
+ )
2543
+ };
2544
+ }
2545
+ function createPersistTask(compiler, options) {
2546
+ return {
2547
+ title: "Persist",
2548
+ enabled: options?.enabled,
2549
+ skip: options?.skip,
2550
+ task: (context, task) => task.newListr(
2551
+ [
2552
+ main3(),
2553
+ {
2554
+ task: (context2, task2) => compiler.hooks.afterPersist.promise(task2)
2555
+ }
2556
+ ],
2557
+ {
2558
+ concurrent: false
2584
2559
  }
2585
- });
2586
- }
2587
- };
2560
+ )
2561
+ };
2562
+ }
2588
2563
 
2589
- // src/plugins/shaking/shaking.plugin.ts
2590
- import { openapiShakingSync } from "@opendoc/openapi-shaking";
2591
- var ShakingPlugin = class _ShakingPlugin {
2592
- apply(compiler) {
2593
- compiler.hooks.beforeCompile.tap(_ShakingPlugin.name, (task) => {
2594
- const matcher = compiler.context.matcher;
2595
- const documents = compiler.context.documents;
2596
- compiler.context.documents = documents.map((document) => this.shaking(compiler, document)).filter((document) => !document.isEmpty()).filter((document) => !matcher.isModuleIgnored(document.module));
2597
- });
2598
- }
2599
- shaking(compiler, document) {
2600
- const rc = compiler.context.rc;
2601
- const matcher = compiler.context.matcher;
2602
- const isAccepted = (pathname, method, operation) => {
2603
- if (!SupportedMethods.includes(method)) return false;
2604
- return !matcher.isOperationIgnored(new OperationDefinition({
2605
- method,
2606
- pathname,
2607
- operation,
2608
- module: document.module,
2609
- document
2610
- }));
2611
- };
2612
- const sharkedSwagger = openapiShakingSync(
2613
- document.specification,
2614
- isAccepted,
2615
- { tolerant: rc.tolerant }
2616
- );
2617
- return new ApiDocumentV3_1(
2618
- sharkedSwagger,
2619
- new ModuleDefinition(
2620
- document.module.name,
2621
- `file://${document.module.name}.v3_1.sharked.json`
2622
- )
2623
- );
2624
- }
2625
- };
2564
+ // src/compiler/tasks/compile/index.ts
2565
+ function main4(compiler) {
2566
+ return {
2567
+ task: async (context, task) => {
2568
+ if (!context.rc) throw new Error("Please run setup task first.");
2569
+ if (!context.documents) throw new Error("Please run shaking task first.");
2570
+ context.artifacts = [];
2571
+ await compiler.hooks.compile.promise(task);
2572
+ }
2573
+ };
2574
+ }
2575
+ function createCompileTask(compiler, options) {
2576
+ return {
2577
+ title: "Compile",
2578
+ enabled: options?.enabled,
2579
+ skip: options?.skip,
2580
+ task: (context, task) => task.newListr(
2581
+ [
2582
+ {
2583
+ task: (context2, task2) => compiler.hooks.beforeCompile.promise(task2)
2584
+ },
2585
+ main4(compiler),
2586
+ {
2587
+ task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
2588
+ }
2589
+ ],
2590
+ {
2591
+ concurrent: false
2592
+ }
2593
+ )
2594
+ };
2595
+ }
2626
2596
 
2627
- // src/plugins/terminal-select/utils/select-operation-definitions.ts
2628
- import { select } from "inquirer-select-pro";
2629
- import { ListrInquirerPromptAdapter } from "@listr2/prompt-adapter-inquirer";
2630
- async function selectOperationDefinitions(task, operationDefinitions) {
2631
- const selectedOperationDefinitions = await task.prompt(ListrInquirerPromptAdapter).run(
2632
- select,
2633
- {
2634
- message: "Select Pathname",
2635
- defaultValue: [],
2636
- options: (input) => {
2637
- const items = operationDefinitions.map((op) => ({ name: `${op.module.name} ${op.method.toUpperCase()} ${op.pathname}`, value: op }));
2638
- if (!input) return items;
2639
- const keys2 = input.trim().toLowerCase().split(/\s+/);
2640
- return items.filter((i) => {
2641
- const name = i.name.toLowerCase();
2642
- return keys2.every((q) => name.includes(q));
2643
- });
2597
+ // src/compiler/intercepter/print-information.ts
2598
+ function proxyTaskWrapper(pluginName, task) {
2599
+ return new Proxy(task, {
2600
+ set(target, prop2, value) {
2601
+ if (prop2 !== "output") {
2602
+ return Reflect.set(target, prop2, value);
2644
2603
  }
2604
+ target.output = `[Plugin: ${pluginName}] ${value}`;
2605
+ return true;
2645
2606
  }
2646
- );
2647
- return selectedOperationDefinitions;
2607
+ });
2648
2608
  }
2649
-
2650
- // src/plugins/terminal-select/terminal-select.plugin.ts
2651
- var TerminalSelectPlugin = class _TerminalSelectPlugin {
2652
- constructor(options) {
2653
- this.options = options;
2654
- }
2655
- apply(compiler) {
2656
- compiler.hooks.afterDownload.tapPromise(_TerminalSelectPlugin.name, async (task) => {
2657
- const context = compiler.context;
2658
- const matcher = context.matcher;
2659
- const documents = context.documents;
2660
- const operationDefinitions = documents.flatMap((document) => document.operations);
2661
- const selectedOperationDefinitions = await selectOperationDefinitions(task, operationDefinitions);
2662
- if (this.options.clear) {
2663
- matcher.append({
2664
- persist: false,
2665
- ignore: true,
2666
- moduleName: "*",
2667
- operationMethod: "*",
2668
- operationPathname: "*"
2669
- });
2609
+ function printInformation(taskIndex) {
2610
+ return {
2611
+ register: (tap) => {
2612
+ const fn = tap.fn;
2613
+ if (tap.type === "promise") {
2614
+ tap.fn = (...args) => {
2615
+ const task = args[taskIndex];
2616
+ const proxyTask = proxyTaskWrapper(tap.name, task);
2617
+ args[taskIndex] = proxyTask;
2618
+ proxyTask.output = "Processing...";
2619
+ return fn(...args);
2620
+ };
2670
2621
  }
2671
- for (const op of selectedOperationDefinitions) {
2672
- matcher.append({
2673
- persist: !!this.options.persist,
2674
- ignore: this.options.mode === "add",
2675
- moduleName: op.module.name,
2676
- operationMethod: op.method,
2677
- operationPathname: op.pathname
2678
- });
2622
+ if (tap.type === "sync") {
2623
+ tap.fn = (...args) => {
2624
+ const task = args[taskIndex];
2625
+ const proxyTask = proxyTaskWrapper(tap.name, task);
2626
+ args[taskIndex] = proxyTask;
2627
+ proxyTask.output = "Processing...";
2628
+ return fn(...args);
2629
+ };
2679
2630
  }
2680
- });
2681
- }
2682
- };
2631
+ if (tap.type === "async") {
2632
+ tap.fn = (...args) => {
2633
+ const task = args[taskIndex];
2634
+ const proxyTask = proxyTaskWrapper(tap.name, task);
2635
+ args[taskIndex] = proxyTask;
2636
+ proxyTask.output = "Processing...";
2637
+ return fn(...args);
2638
+ };
2639
+ }
2640
+ return tap;
2641
+ }
2642
+ };
2643
+ }
2683
2644
 
2684
- // src/plugins/initialize/initialize.plugin.ts
2645
+ // src/compiler/intercepter/perfect-error-message.ts
2685
2646
  import * as R23 from "ramda";
2686
- var InitializePlugin = class _InitializePlugin {
2687
- constructor(options) {
2688
- this.options = options;
2689
- }
2690
- apply(compiler) {
2691
- compiler.hooks.setup.tap(_InitializePlugin.name, (task) => {
2692
- new DownloadHttpFilePlugin().apply(compiler);
2693
- new DownloadLocalFilePlugin().apply(compiler);
2694
- new GenerateDeclarationPlugin().apply(compiler);
2695
- if (this.options.build) {
2696
- new ShakingPlugin().apply(compiler);
2697
- }
2698
- if (this.options.interactive) {
2699
- new TerminalSelectPlugin(
2700
- typeof this.options.interactive === "object" ? this.options.interactive : { mode: "except" }
2701
- ).apply(compiler);
2647
+ function perfectErrorMessage() {
2648
+ return {
2649
+ register: (tap) => {
2650
+ const fn = tap.fn;
2651
+ function prefix(err) {
2652
+ if (err instanceof Error) {
2653
+ err.message = `[Plugin: ${tap.name}] ${err.message}`;
2654
+ }
2702
2655
  }
2703
- const rc = compiler.context.rc;
2704
- if (rc.mode === "micro-function") {
2705
- new GenerateMicroFunctionPlugin().apply(compiler);
2706
- } else if (rc.mode === "nestjs-module") {
2707
- new GenerateNestjsModulePlugin().apply(compiler);
2656
+ if (tap.type === "promise") {
2657
+ tap.fn = async (...args) => {
2658
+ try {
2659
+ return await fn(...args);
2660
+ } catch (err) {
2661
+ prefix(err);
2662
+ throw err;
2663
+ }
2664
+ };
2708
2665
  }
2709
- if (rc.plugins && rc.plugins.length) {
2710
- for (const plugin of rc.plugins) {
2711
- plugin.apply(compiler);
2712
- }
2666
+ if (tap.type === "sync") {
2667
+ tap.fn = (...args) => {
2668
+ try {
2669
+ return fn(...args);
2670
+ } catch (err) {
2671
+ prefix(err);
2672
+ throw err;
2673
+ }
2674
+ };
2713
2675
  }
2714
- });
2715
- if (this.options.includes && this.options.includes.length) {
2716
- const modulesIncludes = this.options.includes;
2717
- compiler.hooks.afterSetup.tap(_InitializePlugin.name, (task) => {
2718
- const rc = compiler.context.rc;
2719
- const matcher = compiler.context.matcher;
2720
- const notExistModules = modulesIncludes.filter((moduleName) => !(moduleName in rc.modules));
2721
- if (notExistModules.length) {
2722
- throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
2723
- }
2724
- const ignoredModules = R23.difference(R23.keys(rc.modules), modulesIncludes);
2725
- for (const moduleName of ignoredModules) {
2726
- matcher.append({
2727
- persist: false,
2728
- ignore: true,
2729
- moduleName,
2730
- operationMethod: "*",
2731
- operationPathname: "*"
2676
+ if (tap.type === "async") {
2677
+ tap.fn = (...args) => {
2678
+ const callback = R23.last(args);
2679
+ return fn(...R23.init(args), (err, result) => {
2680
+ prefix(err);
2681
+ return callback(err, result);
2732
2682
  });
2733
- }
2734
- });
2683
+ };
2684
+ }
2685
+ return tap;
2735
2686
  }
2736
- }
2737
- };
2738
-
2739
- // src/plugins/overwrite-query-options/overwrite-query-options.plugin.ts
2740
- var QsArrayFormatUnion = Object.values(QsArrayFormat);
2687
+ };
2688
+ }
2741
2689
 
2742
2690
  // src/compiler/compiler.ts
2743
2691
  var Compiler = class {
@@ -2801,8 +2749,7 @@ export {
2801
2749
  ModuleDefinition,
2802
2750
  OperationDefinition,
2803
2751
  QsArrayFormat,
2804
- RuntimeConfig,
2805
2752
  SchemaDefinition,
2806
- defineKeqConfig
2753
+ defineConfig
2807
2754
  };
2808
2755
  //# sourceMappingURL=index.js.map