@keq-request/cli 5.0.0-alpha.22 → 5.0.0-alpha.23

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 (299) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli.cjs +2015 -1498
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +2007 -1490
  5. package/dist/cli.js.map +1 -1
  6. package/dist/compiler/compiler.d.ts +8 -20
  7. package/dist/compiler/compiler.d.ts.map +1 -1
  8. package/dist/compiler/index.d.ts +2 -0
  9. package/dist/compiler/index.d.ts.map +1 -1
  10. package/dist/compiler/intercepter/index.d.ts +3 -0
  11. package/dist/compiler/intercepter/index.d.ts.map +1 -0
  12. package/dist/compiler/intercepter/print-information.d.ts +1 -1
  13. package/dist/compiler/intercepter/print-information.d.ts.map +1 -1
  14. package/dist/compiler/tasks/compile/index.d.ts +6 -0
  15. package/dist/compiler/tasks/compile/index.d.ts.map +1 -0
  16. package/dist/{tasks → compiler/tasks}/download/index.d.ts +3 -3
  17. package/dist/compiler/tasks/download/index.d.ts.map +1 -0
  18. package/dist/compiler/tasks/index.d.ts +6 -0
  19. package/dist/compiler/tasks/index.d.ts.map +1 -0
  20. package/dist/compiler/tasks/persist/index.d.ts +5 -0
  21. package/dist/compiler/tasks/persist/index.d.ts.map +1 -0
  22. package/dist/{tasks → compiler/tasks}/setup/index.d.ts +4 -5
  23. package/dist/compiler/tasks/setup/index.d.ts.map +1 -0
  24. package/dist/compiler/tasks/setup/utils/find-nearest-package-json.d.ts.map +1 -0
  25. package/dist/compiler/tasks/setup/utils/get-project-module-system.d.ts.map +1 -0
  26. package/dist/compiler/tasks/setup/utils/index.d.ts.map +1 -0
  27. package/dist/compiler/tasks/setup/utils/validate-modules.d.ts.map +1 -0
  28. package/dist/compiler/tasks/types/base-task-options.d.ts +6 -0
  29. package/dist/compiler/tasks/types/base-task-options.d.ts.map +1 -0
  30. package/dist/compiler/tasks/types/index.d.ts +3 -0
  31. package/dist/compiler/tasks/types/index.d.ts.map +1 -0
  32. package/dist/compiler/tasks/types/task-wrapper.d.ts +4 -0
  33. package/dist/compiler/tasks/types/task-wrapper.d.ts.map +1 -0
  34. package/dist/compiler/types/compiler-context.d.ts +11 -0
  35. package/dist/compiler/types/compiler-context.d.ts.map +1 -0
  36. package/dist/compiler/types/compiler-hooks.d.ts +18 -0
  37. package/dist/compiler/types/compiler-hooks.d.ts.map +1 -0
  38. package/dist/compiler/types/index.d.ts +3 -0
  39. package/dist/compiler/types/index.d.ts.map +1 -0
  40. package/dist/constants/index.d.ts +4 -0
  41. package/dist/constants/index.d.ts.map +1 -0
  42. package/dist/exception.d.ts +1 -1
  43. package/dist/exception.d.ts.map +1 -1
  44. package/dist/generators/index.d.ts +2 -0
  45. package/dist/generators/index.d.ts.map +1 -0
  46. package/dist/index.cjs +1882 -1353
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.ts +4 -11
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1876 -1347
  51. package/dist/index.js.map +1 -1
  52. package/dist/models/anchor.d.ts.map +1 -0
  53. package/dist/{tasks/utils → models}/api-document_v3_1.d.ts +1 -0
  54. package/dist/models/api-document_v3_1.d.ts.map +1 -0
  55. package/dist/models/artifact.d.ts +19 -0
  56. package/dist/models/artifact.d.ts.map +1 -0
  57. package/dist/models/asset.d.ts +5 -0
  58. package/dist/models/asset.d.ts.map +1 -0
  59. package/dist/{tasks/utils → models}/index.d.ts +2 -5
  60. package/dist/models/index.d.ts.map +1 -0
  61. package/dist/{tasks/utils → models}/module-definition.d.ts +1 -0
  62. package/dist/models/module-definition.d.ts.map +1 -0
  63. package/dist/{tasks/utils → models}/operation-definition.d.ts +1 -0
  64. package/dist/models/operation-definition.d.ts.map +1 -0
  65. package/dist/{tasks/utils → models}/schema-definition.d.ts +3 -2
  66. package/dist/models/schema-definition.d.ts.map +1 -0
  67. package/dist/models/utils/to-comment.d.ts.map +1 -0
  68. package/dist/plugins/body-fallback/index.d.ts.map +1 -1
  69. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts +5 -0
  70. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts.map +1 -0
  71. package/dist/plugins/chinese-to-pinyin/index.d.ts +2 -0
  72. package/dist/plugins/chinese-to-pinyin/index.d.ts.map +1 -0
  73. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts +8 -0
  74. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts.map +1 -0
  75. package/dist/plugins/download-http-file/index.d.ts +2 -0
  76. package/dist/plugins/download-http-file/index.d.ts.map +1 -0
  77. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts +6 -0
  78. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts.map +1 -0
  79. package/dist/plugins/download-local-file/index.d.ts +2 -0
  80. package/dist/plugins/download-local-file/index.d.ts.map +1 -0
  81. package/dist/plugins/generate-declaration/constants/index.d.ts +2 -0
  82. package/dist/plugins/generate-declaration/constants/index.d.ts.map +1 -0
  83. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts +12 -0
  84. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts.map +1 -0
  85. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts +15 -0
  86. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts.map +1 -0
  87. package/dist/plugins/generate-declaration/generators/index.d.ts +3 -0
  88. package/dist/plugins/generate-declaration/generators/index.d.ts.map +1 -0
  89. package/dist/plugins/generate-declaration/generators/operation-declaration/index.d.ts +2 -0
  90. package/dist/plugins/generate-declaration/generators/operation-declaration/index.d.ts.map +1 -0
  91. package/dist/plugins/generate-declaration/generators/operation-declaration/operation.generator.d.ts +15 -0
  92. package/dist/plugins/generate-declaration/generators/operation-declaration/operation.generator.d.ts.map +1 -0
  93. package/dist/plugins/generate-declaration/generators/schema-declaration/index.d.ts +2 -0
  94. package/dist/plugins/generate-declaration/generators/schema-declaration/index.d.ts.map +1 -0
  95. package/dist/plugins/generate-declaration/generators/schema-declaration/schema.generator.d.ts +15 -0
  96. package/dist/plugins/generate-declaration/generators/schema-declaration/schema.generator.d.ts.map +1 -0
  97. package/dist/plugins/generate-declaration/index.d.ts +3 -0
  98. package/dist/plugins/generate-declaration/index.d.ts.map +1 -0
  99. package/dist/plugins/generate-micro-function/constants/index.d.ts +2 -0
  100. package/dist/plugins/generate-micro-function/constants/index.d.ts.map +1 -0
  101. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts +11 -0
  102. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts.map +1 -0
  103. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts +11 -0
  104. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts.map +1 -0
  105. package/dist/plugins/generate-micro-function/generators/index.d.ts +3 -0
  106. package/dist/plugins/generate-micro-function/generators/index.d.ts.map +1 -0
  107. package/dist/plugins/generate-micro-function/generators/micro_function/index.d.ts +2 -0
  108. package/dist/plugins/generate-micro-function/generators/micro_function/index.d.ts.map +1 -0
  109. package/dist/plugins/generate-micro-function/generators/micro_function/micro-function.generator.d.ts +15 -0
  110. package/dist/plugins/generate-micro-function/generators/micro_function/micro-function.generator.d.ts.map +1 -0
  111. package/dist/plugins/generate-micro-function/generators/request/index.d.ts +2 -0
  112. package/dist/plugins/generate-micro-function/generators/request/index.d.ts.map +1 -0
  113. package/dist/plugins/generate-micro-function/generators/request/request.generator.d.ts +11 -0
  114. package/dist/plugins/generate-micro-function/generators/request/request.generator.d.ts.map +1 -0
  115. package/dist/plugins/generate-micro-function/index.d.ts +3 -0
  116. package/dist/plugins/generate-micro-function/index.d.ts.map +1 -0
  117. package/dist/plugins/generate-nestjs-module/constants/index.d.ts +2 -0
  118. package/dist/plugins/generate-nestjs-module/constants/index.d.ts.map +1 -0
  119. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts +10 -0
  120. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts.map +1 -0
  121. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts +10 -0
  122. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts.map +1 -0
  123. package/dist/plugins/generate-nestjs-module/generators/index.d.ts +2 -0
  124. package/dist/plugins/generate-nestjs-module/generators/index.d.ts.map +1 -0
  125. package/dist/plugins/generate-nestjs-module/generators/nestjs-module.generator.d.ts +14 -0
  126. package/dist/plugins/generate-nestjs-module/generators/nestjs-module.generator.d.ts.map +1 -0
  127. package/dist/plugins/generate-nestjs-module/index.d.ts +3 -0
  128. package/dist/plugins/generate-nestjs-module/index.d.ts.map +1 -0
  129. package/dist/plugins/index.d.ts +9 -0
  130. package/dist/plugins/index.d.ts.map +1 -1
  131. package/dist/plugins/initialize/index.d.ts +2 -0
  132. package/dist/plugins/initialize/index.d.ts.map +1 -0
  133. package/dist/plugins/initialize/initialize.plugin.d.ts +15 -0
  134. package/dist/plugins/initialize/initialize.plugin.d.ts.map +1 -0
  135. package/dist/plugins/shaking/index.d.ts +2 -0
  136. package/dist/plugins/shaking/index.d.ts.map +1 -0
  137. package/dist/plugins/shaking/shaking.plugin.d.ts +8 -0
  138. package/dist/plugins/shaking/shaking.plugin.d.ts.map +1 -0
  139. package/dist/plugins/terminal-select/index.d.ts +2 -0
  140. package/dist/plugins/terminal-select/index.d.ts.map +1 -0
  141. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts +18 -0
  142. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts.map +1 -0
  143. package/dist/plugins/terminal-select/types/ignore-mode.d.ts.map +1 -0
  144. package/dist/plugins/terminal-select/types/index.d.ts +2 -0
  145. package/dist/plugins/terminal-select/types/index.d.ts.map +1 -0
  146. package/dist/plugins/terminal-select/utils/index.d.ts +2 -0
  147. package/dist/plugins/terminal-select/utils/index.d.ts.map +1 -0
  148. package/dist/plugins/terminal-select/utils/select-operation-definitions.d.ts +5 -0
  149. package/dist/plugins/terminal-select/utils/select-operation-definitions.d.ts.map +1 -0
  150. package/dist/plugins.cjs +2225 -30
  151. package/dist/plugins.cjs.map +1 -1
  152. package/dist/plugins.js +2205 -29
  153. package/dist/plugins.js.map +1 -1
  154. package/dist/transformers/api-document/api-document.transformer.d.ts +8 -0
  155. package/dist/transformers/api-document/api-document.transformer.d.ts.map +1 -0
  156. package/dist/transformers/api-document/index.d.ts +2 -0
  157. package/dist/transformers/api-document/index.d.ts.map +1 -0
  158. package/dist/transformers/api-document/nestjs-client.renderer.d.ts +17 -0
  159. package/dist/transformers/api-document/nestjs-client.renderer.d.ts.map +1 -0
  160. package/dist/transformers/api-document/nestjs-module.renderer.d.ts +12 -0
  161. package/dist/transformers/api-document/nestjs-module.renderer.d.ts.map +1 -0
  162. package/dist/transformers/entrypoint/entrypoint.transformer.d.ts +10 -0
  163. package/dist/transformers/entrypoint/entrypoint.transformer.d.ts.map +1 -0
  164. package/dist/transformers/entrypoint/index.d.ts +2 -0
  165. package/dist/transformers/entrypoint/index.d.ts.map +1 -0
  166. package/dist/transformers/index.d.ts +6 -0
  167. package/dist/transformers/index.d.ts.map +1 -0
  168. package/dist/transformers/json-schema/comment.renderer.d.ts +8 -0
  169. package/dist/transformers/json-schema/comment.renderer.d.ts.map +1 -0
  170. package/dist/transformers/json-schema/declaration.renderer.d.ts +26 -0
  171. package/dist/transformers/json-schema/declaration.renderer.d.ts.map +1 -0
  172. package/dist/transformers/json-schema/index.d.ts +4 -0
  173. package/dist/transformers/json-schema/index.d.ts.map +1 -0
  174. package/dist/transformers/json-schema/json-schema.transformer.d.ts +7 -0
  175. package/dist/transformers/json-schema/json-schema.transformer.d.ts.map +1 -0
  176. package/dist/transformers/json-schema/reference.transformer.d.ts +5 -0
  177. package/dist/transformers/json-schema/reference.transformer.d.ts.map +1 -0
  178. package/dist/transformers/json-schema/types/any-other-attribute.d.ts.map +1 -0
  179. package/dist/transformers/json-schema/types/index.d.ts +3 -0
  180. package/dist/transformers/json-schema/types/index.d.ts.map +1 -0
  181. package/dist/transformers/json-schema/types/mixed-schema-object.d.ts.map +1 -0
  182. package/dist/transformers/operation-definition/comment.renderer.d.ts +8 -0
  183. package/dist/transformers/operation-definition/comment.renderer.d.ts.map +1 -0
  184. package/dist/transformers/operation-definition/declaration.renderer.d.ts +20 -0
  185. package/dist/transformers/operation-definition/declaration.renderer.d.ts.map +1 -0
  186. package/dist/transformers/operation-definition/index.d.ts +3 -0
  187. package/dist/transformers/operation-definition/index.d.ts.map +1 -0
  188. package/dist/transformers/operation-definition/micro-function.renderer.d.ts +19 -0
  189. package/dist/transformers/operation-definition/micro-function.renderer.d.ts.map +1 -0
  190. package/dist/transformers/operation-definition/nestjs-method.renderer.d.ts +15 -0
  191. package/dist/transformers/operation-definition/nestjs-method.renderer.d.ts.map +1 -0
  192. package/dist/transformers/operation-definition/operation-definition.transformer.d.ts +11 -0
  193. package/dist/transformers/operation-definition/operation-definition.transformer.d.ts.map +1 -0
  194. package/dist/transformers/operation-definition/typescript-helper.d.ts +25 -0
  195. package/dist/transformers/operation-definition/typescript-helper.d.ts.map +1 -0
  196. package/dist/transformers/operation-definition/utils/index.d.ts +2 -0
  197. package/dist/transformers/operation-definition/utils/index.d.ts.map +1 -0
  198. package/dist/transformers/operation-definition/utils/type-name-factory.d.ts +4 -0
  199. package/dist/transformers/operation-definition/utils/type-name-factory.d.ts.map +1 -0
  200. package/dist/transformers/schema-definition/index.d.ts +2 -0
  201. package/dist/transformers/schema-definition/index.d.ts.map +1 -0
  202. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts +10 -0
  203. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts.map +1 -0
  204. package/dist/transformers/types/renderer.d.ts +4 -0
  205. package/dist/transformers/types/renderer.d.ts.map +1 -0
  206. package/dist/types/generator.d.ts +7 -0
  207. package/dist/types/generator.d.ts.map +1 -0
  208. package/dist/types/index.d.ts +1 -0
  209. package/dist/types/index.d.ts.map +1 -1
  210. package/dist/types/operation-id-factory.d.ts +1 -1
  211. package/dist/types/operation-id-factory.d.ts.map +1 -1
  212. package/dist/types/runtime-config.d.ts +1 -0
  213. package/dist/types/runtime-config.d.ts.map +1 -1
  214. package/dist/utils/ignore-matcher.d.ts +1 -2
  215. package/dist/utils/ignore-matcher.d.ts.map +1 -1
  216. package/dist/utils/indent.d.ts +2 -0
  217. package/dist/utils/indent.d.ts.map +1 -0
  218. package/dist/utils/openapi-utils/index.d.ts +2 -0
  219. package/dist/utils/openapi-utils/index.d.ts.map +1 -1
  220. package/dist/utils/openapi-utils/to-3_1.d.ts +3 -0
  221. package/dist/utils/openapi-utils/to-3_1.d.ts.map +1 -0
  222. package/package.json +3 -3
  223. package/dist/renderer/json-schema/index.d.ts +0 -3
  224. package/dist/renderer/json-schema/index.d.ts.map +0 -1
  225. package/dist/renderer/operation-request/error-to-comment.d.ts +0 -2
  226. package/dist/renderer/operation-request/error-to-comment.d.ts.map +0 -1
  227. package/dist/renderer/operation-request/index.d.ts +0 -8
  228. package/dist/renderer/operation-request/index.d.ts.map +0 -1
  229. package/dist/renderer/operation-request/request-body.d.ts +0 -4
  230. package/dist/renderer/operation-request/request-body.d.ts.map +0 -1
  231. package/dist/renderer/operation-type/index.d.ts +0 -6
  232. package/dist/renderer/operation-type/index.d.ts.map +0 -1
  233. package/dist/renderer/request/index.d.ts +0 -2
  234. package/dist/renderer/request/index.d.ts.map +0 -1
  235. package/dist/renderer/types/any-other-attribute.d.ts.map +0 -1
  236. package/dist/renderer/types/mixed-schema-object.d.ts.map +0 -1
  237. package/dist/renderer/utils/generate-schema.d.ts +0 -6
  238. package/dist/renderer/utils/generate-schema.d.ts.map +0 -1
  239. package/dist/tasks/compile/index.d.ts +0 -6
  240. package/dist/tasks/compile/index.d.ts.map +0 -1
  241. package/dist/tasks/compile/utils/compile-operation-definition.d.ts +0 -15
  242. package/dist/tasks/compile/utils/compile-operation-definition.d.ts.map +0 -1
  243. package/dist/tasks/compile/utils/compile-schema-definition.d.ts +0 -13
  244. package/dist/tasks/compile/utils/compile-schema-definition.d.ts.map +0 -1
  245. package/dist/tasks/download/index.d.ts.map +0 -1
  246. package/dist/tasks/index.d.ts +0 -10
  247. package/dist/tasks/index.d.ts.map +0 -1
  248. package/dist/tasks/interactive/index.d.ts +0 -15
  249. package/dist/tasks/interactive/index.d.ts.map +0 -1
  250. package/dist/tasks/interactive/utils/select-operation-definitions.d.ts +0 -5
  251. package/dist/tasks/interactive/utils/select-operation-definitions.d.ts.map +0 -1
  252. package/dist/tasks/persist/index.d.ts +0 -6
  253. package/dist/tasks/persist/index.d.ts.map +0 -1
  254. package/dist/tasks/setup/index.d.ts.map +0 -1
  255. package/dist/tasks/setup/utils/find-nearest-package-json.d.ts.map +0 -1
  256. package/dist/tasks/setup/utils/get-project-module-system.d.ts.map +0 -1
  257. package/dist/tasks/setup/utils/index.d.ts.map +0 -1
  258. package/dist/tasks/setup/utils/validate-modules.d.ts.map +0 -1
  259. package/dist/tasks/shaking/index.d.ts +0 -10
  260. package/dist/tasks/shaking/index.d.ts.map +0 -1
  261. package/dist/tasks/types/base-task-options.d.ts +0 -6
  262. package/dist/tasks/types/base-task-options.d.ts.map +0 -1
  263. package/dist/tasks/types/file.d.ts +0 -4
  264. package/dist/tasks/types/file.d.ts.map +0 -1
  265. package/dist/tasks/types/ignore-mode.d.ts.map +0 -1
  266. package/dist/tasks/types/index.d.ts +0 -6
  267. package/dist/tasks/types/index.d.ts.map +0 -1
  268. package/dist/tasks/types/task-context.d.ts +0 -28
  269. package/dist/tasks/types/task-context.d.ts.map +0 -1
  270. package/dist/tasks/types/task-wrapper.d.ts +0 -4
  271. package/dist/tasks/types/task-wrapper.d.ts.map +0 -1
  272. package/dist/tasks/utils/anchor.d.ts.map +0 -1
  273. package/dist/tasks/utils/api-document.d.ts +0 -18
  274. package/dist/tasks/utils/api-document.d.ts.map +0 -1
  275. package/dist/tasks/utils/api-document_v3_1.d.ts.map +0 -1
  276. package/dist/tasks/utils/artifact.d.ts +0 -27
  277. package/dist/tasks/utils/artifact.d.ts.map +0 -1
  278. package/dist/tasks/utils/dependency.d.ts +0 -24
  279. package/dist/tasks/utils/dependency.d.ts.map +0 -1
  280. package/dist/tasks/utils/index.d.ts.map +0 -1
  281. package/dist/tasks/utils/json-schema.d.ts +0 -8
  282. package/dist/tasks/utils/json-schema.d.ts.map +0 -1
  283. package/dist/tasks/utils/module-definition.d.ts.map +0 -1
  284. package/dist/tasks/utils/operation-definition.d.ts.map +0 -1
  285. package/dist/tasks/utils/proxy-task-wrapper.d.ts +0 -3
  286. package/dist/tasks/utils/proxy-task-wrapper.d.ts.map +0 -1
  287. package/dist/tasks/utils/schema-definition.d.ts.map +0 -1
  288. package/dist/tasks/utils/to-comment.d.ts.map +0 -1
  289. package/dist/tasks/validate/index.d.ts +0 -6
  290. package/dist/tasks/validate/index.d.ts.map +0 -1
  291. /package/dist/{tasks → compiler/tasks}/setup/utils/find-nearest-package-json.d.ts +0 -0
  292. /package/dist/{tasks → compiler/tasks}/setup/utils/get-project-module-system.d.ts +0 -0
  293. /package/dist/{tasks → compiler/tasks}/setup/utils/index.d.ts +0 -0
  294. /package/dist/{tasks → compiler/tasks}/setup/utils/validate-modules.d.ts +0 -0
  295. /package/dist/{tasks/utils → models}/anchor.d.ts +0 -0
  296. /package/dist/{tasks → models}/utils/to-comment.d.ts +0 -0
  297. /package/dist/{tasks → plugins/terminal-select}/types/ignore-mode.d.ts +0 -0
  298. /package/dist/{renderer → transformers/json-schema}/types/any-other-attribute.d.ts +0 -0
  299. /package/dist/{renderer → transformers/json-schema}/types/mixed-schema-object.d.ts +0 -0
package/dist/cli.cjs CHANGED
@@ -47,87 +47,15 @@ var logger = {
47
47
  };
48
48
 
49
49
  // src/compiler/compiler.ts
50
- var import_tapable = require("tapable");
51
50
  var import_listr22 = require("listr2");
51
+ var import_tapable4 = require("tapable");
52
52
 
53
- // src/tasks/setup/index.ts
54
- var R3 = __toESM(require("ramda"), 1);
53
+ // src/compiler/tasks/setup/index.ts
55
54
  var import_fs_extra2 = __toESM(require("fs-extra"), 1);
56
55
  var import_path = __toESM(require("path"), 1);
57
56
  var import_value = require("@sinclair/typebox/value");
58
57
  var import_cosmiconfig = require("cosmiconfig");
59
58
 
60
- // src/types/runtime-config.ts
61
- var import_typebox2 = require("@sinclair/typebox");
62
-
63
- // src/constants/file-naming-style.ts
64
- var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
65
- FileNamingStyle2["camelCase"] = "camelCase";
66
- FileNamingStyle2["capitalCase"] = "capitalCase";
67
- FileNamingStyle2["constantCase"] = "constantCase";
68
- FileNamingStyle2["dotCase"] = "dotCase";
69
- FileNamingStyle2["headerCase"] = "headerCase";
70
- FileNamingStyle2["noCase"] = "noCase";
71
- FileNamingStyle2["paramCase"] = "paramCase";
72
- FileNamingStyle2["pascalCase"] = "pascalCase";
73
- FileNamingStyle2["pathCase"] = "pathCase";
74
- FileNamingStyle2["sentenceCase"] = "sentenceCase";
75
- FileNamingStyle2["snakeCase"] = "snakeCase";
76
- return FileNamingStyle2;
77
- })(FileNamingStyle || {});
78
-
79
- // src/types/qs.ts
80
- var import_typebox = require("@sinclair/typebox");
81
-
82
- // src/constants/qs-array-format.ts
83
- var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
84
- QsArrayFormat2["brackets"] = "brackets";
85
- QsArrayFormat2["indices"] = "indices";
86
- QsArrayFormat2["repeat"] = "repeat";
87
- QsArrayFormat2["comma"] = "comma";
88
- QsArrayFormat2["space"] = "space";
89
- QsArrayFormat2["pipe"] = "pipe";
90
- return QsArrayFormat2;
91
- })(QsArrayFormat || {});
92
-
93
- // src/types/qs.ts
94
- var Qs = import_typebox.Type.Object({
95
- indices: import_typebox.Type.Optional(import_typebox.Type.Boolean()),
96
- arrayFormat: import_typebox.Type.Optional(import_typebox.Type.Enum(QsArrayFormat)),
97
- allowDots: import_typebox.Type.Optional(import_typebox.Type.Boolean())
98
- });
99
-
100
- // src/types/runtime-config.ts
101
- var RuntimeConfig = import_typebox2.Type.Object({
102
- /**
103
- * Whether to generate ES Module code
104
- *
105
- * If not specified, the module system will be inferred from the nearest package.json "type" field
106
- * or defaults to "cjs" if no package.json is found.
107
- */
108
- esm: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
109
- /**
110
- * Output directory for generated files
111
- */
112
- outdir: import_typebox2.Type.String({ default: `${process.cwd()}/api` }),
113
- /**
114
- * File naming style for generated files
115
- */
116
- fileNamingStyle: import_typebox2.Type.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
117
- modules: import_typebox2.Type.Record(import_typebox2.Type.String(), import_typebox2.Type.String()),
118
- operationIdFactory: import_typebox2.Type.Optional(import_typebox2.Type.Function([import_typebox2.Type.Any()], import_typebox2.Type.String())),
119
- qs: import_typebox2.Type.Optional(import_typebox2.Type.Union([
120
- Qs,
121
- import_typebox2.Type.Function([import_typebox2.Type.Any()], Qs)
122
- ])),
123
- debug: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
124
- /**
125
- * Whether to tolerate wrong openapi/swagger structure
126
- */
127
- tolerant: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
128
- plugins: import_typebox2.Type.Optional(import_typebox2.Type.Array(import_typebox2.Type.Any(), { default: [] }))
129
- });
130
-
131
59
  // src/utils/ignore-matcher.ts
132
60
  var R = __toESM(require("ramda"), 1);
133
61
  var import_fs_extra = __toESM(require("fs-extra"), 1);
@@ -219,7 +147,85 @@ var IgnoreMatcher = class _IgnoreMatcher {
219
147
  }
220
148
  };
221
149
 
222
- // src/tasks/setup/utils/validate-modules.ts
150
+ // src/types/qs.ts
151
+ var import_typebox = require("@sinclair/typebox");
152
+
153
+ // src/constants/qs-array-format.ts
154
+ var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
155
+ QsArrayFormat2["brackets"] = "brackets";
156
+ QsArrayFormat2["indices"] = "indices";
157
+ QsArrayFormat2["repeat"] = "repeat";
158
+ QsArrayFormat2["comma"] = "comma";
159
+ QsArrayFormat2["space"] = "space";
160
+ QsArrayFormat2["pipe"] = "pipe";
161
+ return QsArrayFormat2;
162
+ })(QsArrayFormat || {});
163
+
164
+ // src/types/qs.ts
165
+ var Qs = import_typebox.Type.Object({
166
+ indices: import_typebox.Type.Optional(import_typebox.Type.Boolean()),
167
+ arrayFormat: import_typebox.Type.Optional(import_typebox.Type.Enum(QsArrayFormat)),
168
+ allowDots: import_typebox.Type.Optional(import_typebox.Type.Boolean())
169
+ });
170
+
171
+ // src/types/runtime-config.ts
172
+ var import_typebox2 = require("@sinclair/typebox");
173
+
174
+ // src/constants/file-naming-style.ts
175
+ var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
176
+ FileNamingStyle2["camelCase"] = "camelCase";
177
+ FileNamingStyle2["capitalCase"] = "capitalCase";
178
+ FileNamingStyle2["constantCase"] = "constantCase";
179
+ FileNamingStyle2["dotCase"] = "dotCase";
180
+ FileNamingStyle2["headerCase"] = "headerCase";
181
+ FileNamingStyle2["noCase"] = "noCase";
182
+ FileNamingStyle2["paramCase"] = "paramCase";
183
+ FileNamingStyle2["pascalCase"] = "pascalCase";
184
+ FileNamingStyle2["pathCase"] = "pathCase";
185
+ FileNamingStyle2["sentenceCase"] = "sentenceCase";
186
+ FileNamingStyle2["snakeCase"] = "snakeCase";
187
+ return FileNamingStyle2;
188
+ })(FileNamingStyle || {});
189
+
190
+ // src/types/runtime-config.ts
191
+ var RuntimeConfig = import_typebox2.Type.Object({
192
+ mode: import_typebox2.Type.Optional(
193
+ import_typebox2.Type.Union([
194
+ import_typebox2.Type.Literal("micro-function"),
195
+ import_typebox2.Type.Literal("nestjs-module"),
196
+ import_typebox2.Type.Literal("none")
197
+ ], { default: "micro-function" })
198
+ ),
199
+ /**
200
+ * Whether to generate ES Module code
201
+ *
202
+ * If not specified, the module system will be inferred from the nearest package.json "type" field
203
+ * or defaults to "cjs" if no package.json is found.
204
+ */
205
+ esm: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
206
+ /**
207
+ * Output directory for generated files
208
+ */
209
+ outdir: import_typebox2.Type.String({ default: `${process.cwd()}/api` }),
210
+ /**
211
+ * File naming style for generated files
212
+ */
213
+ fileNamingStyle: import_typebox2.Type.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
214
+ modules: import_typebox2.Type.Record(import_typebox2.Type.String(), import_typebox2.Type.String()),
215
+ operationIdFactory: import_typebox2.Type.Optional(import_typebox2.Type.Function([import_typebox2.Type.Any()], import_typebox2.Type.String())),
216
+ qs: import_typebox2.Type.Optional(import_typebox2.Type.Union([
217
+ Qs,
218
+ import_typebox2.Type.Function([import_typebox2.Type.Any()], Qs)
219
+ ])),
220
+ debug: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
221
+ /**
222
+ * Whether to tolerate wrong openapi/swagger structure
223
+ */
224
+ tolerant: import_typebox2.Type.Optional(import_typebox2.Type.Boolean({ default: false })),
225
+ plugins: import_typebox2.Type.Optional(import_typebox2.Type.Array(import_typebox2.Type.Any(), { default: [] }))
226
+ });
227
+
228
+ // src/compiler/tasks/setup/utils/validate-modules.ts
223
229
  var R2 = __toESM(require("ramda"), 1);
224
230
  var import_validator = __toESM(require("validator"), 1);
225
231
  function validateModules(modules) {
@@ -248,7 +254,7 @@ function validateModules(modules) {
248
254
  }
249
255
  }
250
256
 
251
- // src/tasks/setup/utils/find-nearest-package-json.ts
257
+ // src/compiler/tasks/setup/utils/find-nearest-package-json.ts
252
258
  var import_node_fs = __toESM(require("fs"), 1);
253
259
  var import_node_path = __toESM(require("path"), 1);
254
260
  function findNearestPackageJson(startDir = process.cwd()) {
@@ -266,7 +272,7 @@ function findNearestPackageJson(startDir = process.cwd()) {
266
272
  return null;
267
273
  }
268
274
 
269
- // src/tasks/setup/utils/get-project-module-system.ts
275
+ // src/compiler/tasks/setup/utils/get-project-module-system.ts
270
276
  function getProjectModuleSystem(pkgInfo) {
271
277
  if (!pkgInfo?.json) return "cjs";
272
278
  const { json } = pkgInfo;
@@ -274,7 +280,7 @@ function getProjectModuleSystem(pkgInfo) {
274
280
  return "cjs";
275
281
  }
276
282
 
277
- // src/tasks/setup/index.ts
283
+ // src/compiler/tasks/setup/index.ts
278
284
  var explore = (0, import_cosmiconfig.cosmiconfig)("keq");
279
285
  function main(compiler, options) {
280
286
  return {
@@ -285,7 +291,7 @@ function main(compiler, options) {
285
291
  }
286
292
  if (!import_value.Value.Check(RuntimeConfig, result.config)) {
287
293
  const errors = [...import_value.Value.Errors(RuntimeConfig, result.config)];
288
- const message = errors.map(({ path: path9, message: message2 }) => `${path9}: ${message2}`).join("\n");
294
+ const message = errors.map(({ path: path13, message: message2 }) => `${path13}: ${message2}`).join("\n");
289
295
  throw new Error(`Invalid Config: ${message}`);
290
296
  }
291
297
  const rc = import_value.Value.Default(RuntimeConfig, result.config);
@@ -302,6 +308,12 @@ function main(compiler, options) {
302
308
  const moduleSystem = getProjectModuleSystem(packageJsonInfo);
303
309
  rc.esm = moduleSystem === "esm";
304
310
  }
311
+ context.rc = rc;
312
+ if (rc.plugins && rc.plugins.length) {
313
+ for (const plugin of rc.plugins) {
314
+ plugin.apply(compiler);
315
+ }
316
+ }
305
317
  let matcher = new IgnoreMatcher([]);
306
318
  if (result.filepath) {
307
319
  const ignoreFilepath = import_path.default.resolve(import_path.default.dirname(result.filepath), ".keqignore");
@@ -319,28 +331,8 @@ function main(compiler, options) {
319
331
  operationPathname: rule.operationPathname
320
332
  });
321
333
  }
322
- if (options?.modules && options.modules.length) {
323
- const notExistModules = options.modules.filter((moduleName) => !(moduleName in rc.modules));
324
- if (notExistModules.length) {
325
- throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
326
- }
327
- const ignoredModules = R3.difference(R3.keys(rc.modules), options.modules);
328
- for (const moduleName of ignoredModules) {
329
- matcher.append({
330
- persist: false,
331
- ignore: true,
332
- moduleName,
333
- operationMethod: "*",
334
- operationPathname: "*"
335
- });
336
- }
337
- }
338
- context.setup = { rc, matcher };
339
- if (rc.plugins && rc.plugins.length) {
340
- for (const plugin of rc.plugins) {
341
- plugin.apply(compiler);
342
- }
343
- }
334
+ context.matcher = matcher;
335
+ await compiler.hooks.setup.promise(task);
344
336
  }
345
337
  };
346
338
  }
@@ -363,142 +355,261 @@ function createSetupTask(compiler, options) {
363
355
  };
364
356
  }
365
357
 
366
- // src/tasks/download/index.ts
358
+ // src/compiler/tasks/download/index.ts
367
359
  var import_listr2 = require("listr2");
360
+ var import_openapi_parser2 = require("@scalar/openapi-parser");
368
361
 
369
- // src/tasks/utils/module-definition.ts
370
- var ModuleDefinition = class {
371
- name;
372
- address;
373
- constructor(name, address) {
374
- this.name = name;
375
- this.address = address;
376
- }
377
- };
378
-
379
- // src/tasks/utils/api-document.ts
380
- var import_fs_extra4 = __toESM(require("fs-extra"), 1);
381
- var path5 = __toESM(require("path"), 1);
382
- var yaml = __toESM(require("js-yaml"), 1);
383
- var validUrl = __toESM(require("valid-url"), 1);
384
- var import_keq = require("keq");
385
- var import_openapi_parser = require("@scalar/openapi-parser");
386
-
387
- // src/tasks/utils/api-document_v3_1.ts
388
- var R6 = __toESM(require("ramda"), 1);
389
-
390
- // src/tasks/utils/operation-definition.ts
391
- var R5 = __toESM(require("ramda"), 1);
392
-
393
- // src/utils/is-keywords.ts
394
- var keywords = [
395
- "break",
396
- "case",
397
- "catch",
398
- "continue",
399
- "default",
400
- "delete",
401
- "do",
402
- "else",
403
- "finally",
404
- "for",
405
- "function",
406
- "if",
407
- "in",
408
- "instanceof",
409
- "new",
410
- "return",
411
- "switch",
412
- "this",
413
- "throw",
414
- "try",
415
- "typeof",
416
- "var",
417
- "void",
418
- "while",
419
- "with"
420
- ];
421
- function isKeywords(str) {
422
- return keywords.includes(str);
423
- }
362
+ // src/models/artifact.ts
363
+ var path3 = __toESM(require("path"), 1);
424
364
 
425
- // src/utils/is-reserved-word.ts
426
- var reservedWords = [
427
- "abstract",
428
- "boolean",
429
- "byte",
430
- "char",
431
- "class",
432
- "const",
433
- "debugger",
434
- "double",
435
- "enum",
436
- "export",
437
- "extends",
438
- "final",
439
- "float",
440
- "goto",
441
- "implements",
442
- "import",
443
- "int",
444
- "interface",
445
- "long",
446
- "native",
447
- "package",
448
- "private",
449
- "protected",
450
- "public",
451
- "short",
452
- "static",
453
- "super",
454
- "synchronized",
455
- "throws",
456
- "transient",
457
- "volatile"
458
- ];
459
- function isReservedWord(str) {
460
- return reservedWords.includes(str);
365
+ // src/models/utils/to-comment.ts
366
+ function toComment(msg) {
367
+ if (!msg) return "";
368
+ return msg.split("\n").map((str) => `// ${str}`).join("\n");
461
369
  }
462
370
 
463
- // src/tasks/utils/operation-definition.ts
464
- var import_jsonpath_plus2 = require("jsonpath-plus");
465
-
466
- // src/tasks/utils/schema-definition.ts
467
- var R4 = __toESM(require("ramda"), 1);
371
+ // src/models/anchor.ts
372
+ var AnchorBlock = class {
373
+ constructor(artifact) {
374
+ this.artifact = artifact;
375
+ }
376
+ /**
377
+ * Append content to the end of the anchor block.
378
+ */
379
+ append(anchorName, content) {
380
+ const lines = this.artifact.content.split("\n");
381
+ const anchor = `@anchor:${anchorName}:end`;
382
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
383
+ if (anchorIndex === -1) {
384
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
385
+ }
386
+ lines.splice(anchorIndex, 0, content);
387
+ this.artifact.content = lines.join("\n");
388
+ }
389
+ prepend(anchorName, content) {
390
+ const lines = this.artifact.content.split("\n");
391
+ const anchor = `@anchor:${anchorName}:start`;
392
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
393
+ if (anchorIndex === -1) {
394
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
395
+ }
396
+ lines.splice(anchorIndex + 1, 0, content);
397
+ this.artifact.content = lines.join("\n");
398
+ }
399
+ replace(anchorName, content) {
400
+ const lines = this.artifact.content.split("\n");
401
+ const startIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:start */`));
402
+ const endIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:end */`));
403
+ if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
404
+ throw new Error(`"@anchor:${anchorName}:start" or "@anchor:${anchorName}:end" not found in artifact "${this.artifact.filepath}".`);
405
+ }
406
+ lines.splice(startIndex + 1, endIndex - startIndex - 1, content);
407
+ this.artifact.content = lines.join("\n");
408
+ }
409
+ };
410
+ var Anchor = class {
411
+ constructor(artifact) {
412
+ this.artifact = artifact;
413
+ this.block = new AnchorBlock(artifact);
414
+ }
415
+ block;
416
+ append(anchorName, content) {
417
+ const lines = this.artifact.content.split("\n");
418
+ const anchor = `@anchor:${anchorName}`;
419
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
420
+ if (anchorIndex === -1) {
421
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
422
+ }
423
+ lines.splice(anchorIndex + 1, 0, content);
424
+ this.artifact.content = lines.join("\n");
425
+ }
426
+ prepend(anchorName, content) {
427
+ const lines = this.artifact.content.split("\n");
428
+ const anchor = `@anchor:${anchorName}`;
429
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
430
+ if (anchorIndex === -1) {
431
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
432
+ }
433
+ lines.splice(anchorIndex, 0, content);
434
+ this.artifact.content = lines.join("\n");
435
+ }
436
+ };
437
+
438
+ // src/models/artifact.ts
439
+ var HeaderComment = [
440
+ "// Code generated by keq-cli. DO NOT EDIT.",
441
+ "// Code generated by keq-cli. DO NOT EDIT.",
442
+ "// Code generated by keq-cli. DO NOT EDIT.",
443
+ "",
444
+ ""
445
+ ].join("\n");
446
+ var Artifact = class {
447
+ id;
448
+ filepath;
449
+ warns = [];
450
+ content;
451
+ extensionName;
452
+ anchor = new Anchor(this);
453
+ constructor(options) {
454
+ this.id = options.id;
455
+ this.filepath = options.filepath;
456
+ this.extensionName = options.extensionName || path3.extname(options.filepath);
457
+ this.content = options.content;
458
+ }
459
+ get dirname() {
460
+ return path3.dirname(this.filepath);
461
+ }
462
+ addWarn(message) {
463
+ this.warns.push(message);
464
+ }
465
+ renderer() {
466
+ let $warns = "";
467
+ if (this.warns.length) {
468
+ $warns = toComment([
469
+ "!!! Here is some Problems !!!",
470
+ "",
471
+ this.warns
472
+ ].join("\n"));
473
+ $warns += "\n\n";
474
+ }
475
+ return `${HeaderComment}${$warns}${this.content}`;
476
+ }
477
+ };
478
+
479
+ // src/models/api-document_v3_1.ts
480
+ var R5 = __toESM(require("ramda"), 1);
481
+
482
+ // src/models/module-definition.ts
483
+ var ModuleDefinition = class _ModuleDefinition {
484
+ name;
485
+ address;
486
+ constructor(name, address) {
487
+ this.name = name;
488
+ this.address = address;
489
+ }
490
+ static unknown() {
491
+ return new _ModuleDefinition("", "");
492
+ }
493
+ };
494
+
495
+ // src/models/operation-definition.ts
496
+ var R4 = __toESM(require("ramda"), 1);
497
+
498
+ // src/utils/is-keywords.ts
499
+ var keywords = [
500
+ "break",
501
+ "case",
502
+ "catch",
503
+ "continue",
504
+ "default",
505
+ "delete",
506
+ "do",
507
+ "else",
508
+ "finally",
509
+ "for",
510
+ "function",
511
+ "if",
512
+ "in",
513
+ "instanceof",
514
+ "new",
515
+ "return",
516
+ "switch",
517
+ "this",
518
+ "throw",
519
+ "try",
520
+ "typeof",
521
+ "var",
522
+ "void",
523
+ "while",
524
+ "with"
525
+ ];
526
+ function isKeywords(str) {
527
+ return keywords.includes(str);
528
+ }
529
+
530
+ // src/utils/is-reserved-word.ts
531
+ var reservedWords = [
532
+ "abstract",
533
+ "boolean",
534
+ "byte",
535
+ "char",
536
+ "class",
537
+ "const",
538
+ "debugger",
539
+ "double",
540
+ "enum",
541
+ "export",
542
+ "extends",
543
+ "final",
544
+ "float",
545
+ "goto",
546
+ "implements",
547
+ "import",
548
+ "int",
549
+ "interface",
550
+ "long",
551
+ "native",
552
+ "package",
553
+ "private",
554
+ "protected",
555
+ "public",
556
+ "short",
557
+ "static",
558
+ "super",
559
+ "synchronized",
560
+ "throws",
561
+ "transient",
562
+ "volatile"
563
+ ];
564
+ function isReservedWord(str) {
565
+ return reservedWords.includes(str);
566
+ }
567
+
568
+ // src/models/operation-definition.ts
569
+ var import_jsonpath_plus2 = require("jsonpath-plus");
570
+
571
+ // src/models/schema-definition.ts
572
+ var R3 = __toESM(require("ramda"), 1);
468
573
  var import_jsonpath_plus = require("jsonpath-plus");
469
574
  var SchemaDefinition = class _SchemaDefinition {
470
- id;
471
575
  name;
472
576
  schema;
473
577
  module;
474
578
  document;
579
+ get id() {
580
+ return `${this.module.address}#/components/schemas/${this.name}`;
581
+ }
475
582
  constructor(args) {
476
583
  this.module = args.module;
477
584
  this.name = args.name;
478
- this.id = args.id;
479
585
  this.schema = args.schema;
480
586
  this.document = args.document;
481
587
  }
482
588
  getDependencies() {
483
- const refs = R4.uniq((0, import_jsonpath_plus.JSONPath)({
589
+ const refs = R3.uniq((0, import_jsonpath_plus.JSONPath)({
484
590
  path: "$..*['$ref']",
485
591
  json: this.schema
486
592
  }));
487
593
  return refs.filter((ref) => typeof ref === "string" && !!ref.trim()).map((ref) => {
488
594
  const definition = this.document.dereference(ref);
489
595
  if (definition) return definition;
490
- return new _SchemaDefinition({
491
- id: ref,
492
- name: "unknown",
493
- schema: {},
494
- module: this.module,
495
- document: this.document
496
- });
596
+ return _SchemaDefinition.unknown();
497
597
  });
498
598
  }
599
+ static unknown() {
600
+ return new _SchemaDefinition({
601
+ name: "",
602
+ schema: {},
603
+ module: ModuleDefinition.unknown(),
604
+ document: ApiDocumentV3_1.unknown()
605
+ });
606
+ }
607
+ static isUnknown(definition) {
608
+ return definition.name === "";
609
+ }
499
610
  };
500
611
 
501
- // src/tasks/utils/operation-definition.ts
612
+ // src/models/operation-definition.ts
502
613
  var OperationDefinition = class {
503
614
  module;
504
615
  operationId;
@@ -506,6 +617,9 @@ var OperationDefinition = class {
506
617
  pathname;
507
618
  operation;
508
619
  document;
620
+ get id() {
621
+ return `${this.module.address}#/paths/${this.pathname}/${this.method}`;
622
+ }
509
623
  constructor(args) {
510
624
  this.module = args.module;
511
625
  this.method = args.method.toLowerCase();
@@ -525,7 +639,7 @@ var OperationDefinition = class {
525
639
  return `${method}_${pathname}`.replace(/\//g, "_").replace(/-/g, "_").replace(/:/g, "$$").replace(/{(.+)}/, "$$$1");
526
640
  }
527
641
  getDependencies() {
528
- const refs = R5.uniq([
642
+ const refs = R4.uniq([
529
643
  ...(0, import_jsonpath_plus2.JSONPath)({
530
644
  path: "$.requestBody.content..schema..$ref",
531
645
  json: this.operation
@@ -542,19 +656,13 @@ var OperationDefinition = class {
542
656
  const dependencies = refs.filter((ref) => typeof ref === "string" && ref).map((ref) => {
543
657
  const schemaDefinition = this.document.dereference(ref);
544
658
  if (schemaDefinition) return schemaDefinition;
545
- return new SchemaDefinition({
546
- id: ref,
547
- name: "unknown",
548
- schema: {},
549
- module: this.module,
550
- document: this.document
551
- });
659
+ return SchemaDefinition.unknown();
552
660
  });
553
661
  return dependencies;
554
662
  }
555
663
  };
556
664
 
557
- // src/tasks/utils/api-document_v3_1.ts
665
+ // src/models/api-document_v3_1.ts
558
666
  var import_openapi_shaking = require("@opendoc/openapi-shaking");
559
667
  var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
560
668
  module;
@@ -566,7 +674,6 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
566
674
  get schemas() {
567
675
  const module2 = this.module;
568
676
  return Object.entries(this.specification.components?.schemas || {}).map(([name, schema]) => new SchemaDefinition({
569
- id: `#/components/schemas/${name}`,
570
677
  name,
571
678
  schema,
572
679
  module: module2,
@@ -584,18 +691,18 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
584
691
  })));
585
692
  }
586
693
  isEmpty() {
587
- return R6.isEmpty(this.specification.paths);
694
+ return R5.isEmpty(this.specification.paths);
588
695
  }
589
696
  dereference($ref) {
590
697
  if ($ref.startsWith("#/")) {
591
- return this.schemas.find((schema) => schema.id === $ref);
698
+ return this.schemas.find((schema) => schema.id.endsWith($ref));
592
699
  }
593
700
  logger.warn(`The $ref(${$ref}) is not defined in ${this.module.name} openapi/swagger.`);
594
701
  }
595
702
  isRefDefined($ref) {
596
703
  if ($ref.startsWith("#/")) {
597
- const path9 = $ref.replace("#/", "").split("/");
598
- return R6.path(path9, this.specification) !== void 0;
704
+ const path13 = $ref.replace("#/", "").split("/");
705
+ return R5.path(path13, this.specification) !== void 0;
599
706
  }
600
707
  return false;
601
708
  }
@@ -624,21 +731,29 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
624
731
  )
625
732
  );
626
733
  }
734
+ static unknown() {
735
+ return new _ApiDocumentV3_1({}, ModuleDefinition.unknown());
736
+ }
627
737
  };
628
738
 
629
- // src/tasks/utils/api-document.ts
630
- var import_swagger_fix = require("swagger-fix");
631
-
632
- // src/utils/debugger.ts
633
- var import_fs_extra3 = __toESM(require("fs-extra"), 1);
634
- var Debugger = class {
635
- constructor(rc) {
636
- this.rc = rc;
739
+ // src/models/asset.ts
740
+ var Asset = class {
741
+ path;
742
+ constructor(path13) {
743
+ this.path = path13;
637
744
  }
638
- writeOpenapi(fullpath, openapi) {
639
- if (this.rc?.debug) {
640
- void import_fs_extra3.default.writeJSON(fullpath, openapi, { spaces: 2 });
641
- }
745
+ };
746
+
747
+ // src/exception.ts
748
+ var import_ts_custom_error = require("ts-custom-error");
749
+ var import_word_wrap = __toESM(require("word-wrap"), 1);
750
+ var Exception = class extends import_ts_custom_error.CustomError {
751
+ constructor(module2, message) {
752
+ const moduleName = typeof module2 === "string" ? module2 : module2.name;
753
+ const msg = (0, import_word_wrap.default)(message, { width: 60, indent: " " });
754
+ super(`${moduleName} module failed to compile:
755
+ ${msg}`);
756
+ Object.defineProperty(this, "name", { value: "KeqCLI_Exception" });
642
757
  }
643
758
  };
644
759
 
@@ -657,28 +772,28 @@ function dereference($ref, swagger) {
657
772
  }
658
773
 
659
774
  // src/utils/openapi-utils/dereference-operation.ts
660
- var R9 = __toESM(require("ramda"), 1);
775
+ var R8 = __toESM(require("ramda"), 1);
661
776
  var import_jsonpointer2 = __toESM(require("jsonpointer"), 1);
662
777
  var import_jsonpath_plus4 = require("jsonpath-plus");
663
778
 
664
779
  // src/utils/openapi-utils/remove-undefined-ref.ts
665
- var R8 = __toESM(require("ramda"), 1);
780
+ var R7 = __toESM(require("ramda"), 1);
666
781
  var import_jsonpointer = __toESM(require("jsonpointer"), 1);
667
782
  var import_jsonpath_plus3 = require("jsonpath-plus");
668
783
 
669
784
  // src/utils/openapi-utils/is-ref-defined.ts
670
- var R7 = __toESM(require("ramda"), 1);
785
+ var R6 = __toESM(require("ramda"), 1);
671
786
  function isRefDefined($ref, swagger) {
672
787
  if ($ref.startsWith("#/")) {
673
- const path9 = $ref.replace("#/", "").split("/");
674
- return R7.path(path9, swagger) !== void 0;
788
+ const path13 = $ref.replace("#/", "").split("/");
789
+ return R6.path(path13, swagger) !== void 0;
675
790
  }
676
791
  return false;
677
792
  }
678
793
 
679
794
  // src/utils/openapi-utils/remove-undefined-ref.ts
680
795
  function removeUndefinedRef(swagger) {
681
- const shadow = R8.clone(swagger);
796
+ const shadow = R7.clone(swagger);
682
797
  const matches = (0, import_jsonpath_plus3.JSONPath)({
683
798
  path: "$..*['$ref']^",
684
799
  json: swagger,
@@ -686,7 +801,7 @@ function removeUndefinedRef(swagger) {
686
801
  });
687
802
  for (const match of matches) {
688
803
  if (match.value.$ref && !isRefDefined(match.value.$ref, swagger)) {
689
- import_jsonpointer.default.set(shadow, match.pointer, R8.omit(["$ref"], match.value));
804
+ import_jsonpointer.default.set(shadow, match.pointer, R7.omit(["$ref"], match.value));
690
805
  }
691
806
  }
692
807
  return shadow;
@@ -700,7 +815,7 @@ function dereferencePathObject(swagger) {
700
815
  resultType: "all"
701
816
  });
702
817
  for (const match of matches) {
703
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
818
+ const value = dereference(match.value.$ref, swagger);
704
819
  import_jsonpointer2.default.set(swagger, match.pointer, value);
705
820
  }
706
821
  }
@@ -711,7 +826,7 @@ function dereferenceRequestBody(swagger) {
711
826
  resultType: "all"
712
827
  });
713
828
  for (const match of matches) {
714
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
829
+ const value = dereference(match.value.$ref, swagger);
715
830
  import_jsonpointer2.default.set(swagger, match.pointer, value);
716
831
  }
717
832
  }
@@ -729,7 +844,7 @@ function dereferenceResponses(swagger) {
729
844
  })
730
845
  ];
731
846
  for (const match of matches) {
732
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
847
+ const value = dereference(match.value.$ref, swagger);
733
848
  import_jsonpointer2.default.set(swagger, match.pointer, value);
734
849
  }
735
850
  }
@@ -740,12 +855,12 @@ function dereferenceParameters(swagger) {
740
855
  resultType: "all"
741
856
  });
742
857
  for (const match of matches) {
743
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
858
+ const value = dereference(match.value.$ref, swagger);
744
859
  import_jsonpointer2.default.set(swagger, match.pointer, value);
745
860
  }
746
861
  }
747
862
  function dereferenceOperation(swagger) {
748
- const shadow = R9.clone(swagger);
863
+ const shadow = R8.clone(swagger);
749
864
  dereferencePathObject(shadow);
750
865
  dereferenceRequestBody(shadow);
751
866
  dereferenceResponses(shadow);
@@ -754,9 +869,9 @@ function dereferenceOperation(swagger) {
754
869
  }
755
870
 
756
871
  // src/utils/openapi-utils/update-operation-id.ts
757
- var R10 = __toESM(require("ramda"), 1);
872
+ var R9 = __toESM(require("ramda"), 1);
758
873
  function updateOperationId(swagger, fn) {
759
- const shadow = R10.clone(swagger);
874
+ const shadow = R9.clone(swagger);
760
875
  for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
761
876
  for (const m in pathItem) {
762
877
  const method = m.toLowerCase();
@@ -820,6 +935,13 @@ function dereferenceDeep($ref, swagger) {
820
935
  return value;
821
936
  }
822
937
 
938
+ // src/utils/openapi-utils/to-3_1.ts
939
+ var import_openapi_parser = require("@scalar/openapi-parser");
940
+ function To3_1(openapi) {
941
+ const { specification } = (0, import_openapi_parser.upgrade)(openapi);
942
+ return specification;
943
+ }
944
+
823
945
  // src/utils/openapi-utils/index.ts
824
946
  var OpenapiUtils = class {
825
947
  static isRefDefined = isRefDefined;
@@ -828,106 +950,19 @@ var OpenapiUtils = class {
828
950
  static removeUndefinedRef = removeUndefinedRef;
829
951
  static dereferenceOperation = dereferenceOperation;
830
952
  static updateOperationId = updateOperationId;
953
+ static to3_1 = To3_1;
831
954
  };
832
955
 
833
- // src/tasks/utils/api-document.ts
834
- var ApiDocument = class _ApiDocument {
835
- module;
836
- specification;
837
- constructor(specification, module2) {
838
- this.module = module2;
839
- this.specification = specification;
840
- }
841
- static cache = /* @__PURE__ */ new Map();
842
- static async download(url) {
843
- let content;
844
- try {
845
- const res = await import_keq.request.get(url).resolveWith("response");
846
- if (res.status >= 400) throw new Error(`Request failed with status code ${res.status}`);
847
- content = await res.text();
848
- } catch (e) {
849
- if (e instanceof Error) {
850
- e.message = `Unable get the openapi/swagger file from ${url}: ${e.message}`;
956
+ // src/compiler/tasks/download/index.ts
957
+ function main2(compiler, options) {
958
+ return {
959
+ task: (context, task) => {
960
+ if (!context.rc || !context.matcher) {
961
+ throw new Error("Please run setup task first.");
851
962
  }
852
- throw e;
853
- }
854
- try {
855
- return JSON.parse(content);
856
- } catch (e) {
857
- throw new Error(`The openapi/swagger file get from url isn't json: ${url}`);
858
- }
859
- }
860
- static async read(filePath) {
861
- const fileExt = path5.extname(filePath);
862
- const content = await import_fs_extra4.default.readFile(filePath, "utf8");
863
- if ([".yml", ".yaml"].includes(fileExt)) {
864
- return yaml.load(content);
865
- } else if (fileExt === ".json") {
866
- return JSON.parse(content);
867
- }
868
- throw new Error(`File ${fileExt} not support.`);
869
- }
870
- static async create(moduleDefinition) {
871
- const { address } = moduleDefinition;
872
- if (this.cache.has(moduleDefinition.address)) {
873
- return this.cache.get(moduleDefinition.address);
874
- }
875
- const openapi = validUrl.isUri(address) ? await this.download(address) : await this.read(address);
876
- return new _ApiDocument(openapi, moduleDefinition);
877
- }
878
- async validate() {
879
- return await (0, import_openapi_parser.validate)(this.specification);
880
- }
881
- // remove chinese and special symbols
882
- fix() {
883
- const openapi = (0, import_swagger_fix.fixSwagger)(this.specification);
884
- return new _ApiDocument(
885
- openapi,
886
- new ModuleDefinition(
887
- this.module.name,
888
- `file://${this.module.name}.fixed.json`
889
- )
890
- );
891
- }
892
- // eslint-disable-next-line @typescript-eslint/require-await
893
- async toV3_1(rc) {
894
- const debug = new Debugger(rc);
895
- let spec = this.specification;
896
- const { specification } = (0, import_openapi_parser.upgrade)(spec);
897
- spec = specification;
898
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.json`, spec);
899
- spec = OpenapiUtils.dereferenceOperation(spec);
900
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.sharked.json`, spec);
901
- if (rc?.operationIdFactory) {
902
- const operationIdFactory = rc.operationIdFactory;
903
- spec = OpenapiUtils.updateOperationId(
904
- spec,
905
- (method, pathname, operation) => operationIdFactory({ method, pathname, operation, module: this.module })
906
- );
907
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.formatted.json`, spec);
908
- }
909
- return new ApiDocumentV3_1(
910
- spec,
911
- new ModuleDefinition(
912
- this.module.name,
913
- `file://${this.module.name}.v3_1.json`
914
- )
915
- );
916
- }
917
- };
918
-
919
- // src/tasks/download/index.ts
920
- function main2(compiler, options) {
921
- return {
922
- task: (context, task) => {
923
- if (!context.setup) {
924
- throw new Error("Please run setup task first.");
925
- }
926
- const rc = context.setup.rc;
927
- const matcher = context.setup.matcher;
928
- context.downloaded = {
929
- documents: []
930
- };
963
+ const rc = context.rc;
964
+ const matcher = context.matcher;
965
+ context.documents = [];
931
966
  return task.newListr(
932
967
  Object.entries(rc.modules).map(([moduleName, address]) => new ModuleDefinition(moduleName, address)).map((moduleDefinition) => ({
933
968
  title: moduleDefinition.name,
@@ -937,8 +972,31 @@ function main2(compiler, options) {
937
972
  return;
938
973
  }
939
974
  task2.output = `Downloaded from ${moduleDefinition.address}`;
940
- const document = await ApiDocument.create(moduleDefinition);
941
- ctx.downloaded.documents.push(document);
975
+ const content = await compiler.hooks.download.promise(moduleDefinition.address, moduleDefinition, task2);
976
+ if (!content) {
977
+ throw new Exception(moduleDefinition, `Cannot download document from ${moduleDefinition.address}`);
978
+ }
979
+ let spec = JSON.parse(content);
980
+ const { valid, errors } = await (0, import_openapi_parser2.validate)(spec);
981
+ if (!valid) {
982
+ const message = `${moduleDefinition.name} module openapi/swagger file does not conform to the openapi specifications or have grammatical errors, which may cause unexpected errors:
983
+ ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
984
+ task2.output = message;
985
+ }
986
+ OpenapiUtils.dereferenceOperation(spec);
987
+ const rc2 = context.rc;
988
+ if (rc2?.operationIdFactory) {
989
+ const operationIdFactory = rc2.operationIdFactory;
990
+ spec = OpenapiUtils.updateOperationId(
991
+ spec,
992
+ (method, pathname, operation) => operationIdFactory({ method, pathname, operation, module: moduleDefinition })
993
+ );
994
+ }
995
+ const document = new ApiDocumentV3_1(
996
+ spec,
997
+ moduleDefinition
998
+ );
999
+ ctx.documents?.push(document);
942
1000
  }
943
1001
  })),
944
1002
  {
@@ -975,151 +1033,31 @@ function createDownloadTask(compiler, options) {
975
1033
  };
976
1034
  }
977
1035
 
978
- // src/tasks/validate/index.ts
979
- function main3() {
980
- return {
981
- task: (context, task) => {
982
- if (!context.setup) throw new Error("Please run setup task first.");
983
- if (!context.downloaded) throw new Error("Please run download task first.");
984
- const rc = context.setup.rc;
985
- const downloadedDocuments = context.downloaded.documents;
986
- const debug = new Debugger(rc);
987
- context.validated = {
988
- documents: []
989
- };
990
- return task.newListr(
991
- downloadedDocuments.map((document) => ({
992
- title: document.module.name,
993
- task: async (ctx, task2) => {
994
- const { valid, errors } = await document.validate();
995
- if (!valid) {
996
- const message = `${document.module.name} module openapi/swagger file does not conform to the openapi@3.1 standard specifications or have grammatical errors, which may cause unexpected errors:
997
- ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
998
- task2.output = message;
999
- }
1000
- const fixedDocument = document.fix();
1001
- debug.writeOpenapi(`.keq/${document.module.name}.fixed.json`, fixedDocument.specification);
1002
- const v3_1Document = await fixedDocument.toV3_1(rc);
1003
- ctx.validated.documents.push(v3_1Document);
1004
- }
1005
- })),
1006
- {
1007
- concurrent: true,
1008
- rendererOptions: {
1009
- collapseSubtasks: false,
1010
- persistentOutput: true
1011
- }
1012
- }
1013
- );
1014
- }
1015
- };
1016
- }
1017
- function createValidateTask(compiler, options) {
1018
- return {
1019
- title: "Validate",
1020
- enabled: options?.enabled,
1021
- skip: options?.skip,
1022
- task: (context, task) => task.newListr(
1023
- [
1024
- main3(),
1025
- {
1026
- task: (context2, task2) => compiler.hooks.afterValidate.promise(task2)
1027
- }
1028
- ],
1029
- {
1030
- concurrent: false
1031
- }
1032
- )
1033
- };
1034
- }
1035
-
1036
- // src/tasks/shaking/index.ts
1037
- function main4(compiler, options) {
1038
- return {
1039
- task: (context, task) => {
1040
- if (!context.setup) throw new Error("Please run setup task first.");
1041
- if (!context.validated) throw new Error("Please run validate task first.");
1042
- const matcher = context.setup.matcher;
1043
- const documents = context.validated.documents;
1044
- context.shaken = {
1045
- documents: []
1046
- };
1047
- return task.newListr(
1048
- documents.map((document) => ({
1049
- title: document.module.name,
1050
- task: (ctx, task2) => {
1051
- if (options?.skipIgnoredModules && matcher.isModuleIgnored(document.module)) {
1052
- task2.skip(`${document.module.name} module is ignored`);
1053
- return;
1054
- }
1055
- const shakenDocument = document.sharking(
1056
- (operationDefinition) => !matcher.isOperationIgnored(operationDefinition)
1057
- );
1058
- if (options?.skipEmptyDocuments && shakenDocument.isEmpty()) {
1059
- task2.skip(`${document.module.name} module is empty`);
1060
- return;
1061
- }
1062
- ctx.shaken.documents.push(shakenDocument);
1063
- }
1064
- })),
1065
- {
1066
- concurrent: true,
1067
- rendererOptions: {
1068
- collapseSubtasks: false,
1069
- suffixSkips: true
1070
- }
1071
- }
1072
- );
1073
- }
1074
- };
1075
- }
1076
- function createShakingTask(compiler, options) {
1077
- return {
1078
- title: "Shaking",
1079
- enabled: options?.enabled,
1080
- skip: options?.skip,
1081
- task: (context, task) => task.newListr(
1082
- [
1083
- main4(compiler, options),
1084
- {
1085
- task: (context2, task2) => compiler.hooks.afterShaking.promise(task2)
1086
- }
1087
- ],
1088
- {
1089
- concurrent: false
1090
- }
1091
- )
1092
- };
1093
- }
1094
-
1095
- // src/tasks/persist/index.ts
1036
+ // src/compiler/tasks/persist/index.ts
1096
1037
  var path6 = __toESM(require("path"), 1);
1097
- var import_fs_extra5 = __toESM(require("fs-extra"), 1);
1038
+ var import_fs_extra3 = __toESM(require("fs-extra"), 1);
1098
1039
  function createPersistArtifactTask() {
1099
1040
  return {
1100
1041
  title: "Write files",
1101
1042
  task: async (context, task) => {
1102
- if (!context.setup) throw new Error("Please run setup task first.");
1103
- if (!context.compiled) {
1043
+ if (!context.rc) throw new Error("Please run setup task first.");
1044
+ if (!context.artifacts || context.artifacts.length === 0) {
1104
1045
  task.skip("No compiled artifacts to persist.");
1105
1046
  return;
1106
1047
  }
1107
- const rc = context.setup.rc;
1108
- const artifacts = context.compiled.artifacts;
1109
- for (const artifact of artifacts) {
1110
- artifact.changeFileNameCase(rc.fileNamingStyle);
1111
- }
1048
+ const rc = context.rc;
1049
+ const artifacts = context.artifacts;
1112
1050
  const total = artifacts.length;
1113
1051
  let completed = 0;
1114
1052
  const files = await Promise.all(artifacts.map(async (artifact) => {
1115
1053
  const realpath = `./${path6.join(rc.outdir, artifact.filepath)}`;
1116
- await import_fs_extra5.default.ensureFile(realpath);
1117
- await import_fs_extra5.default.writeFile(realpath, artifact.toCode({ esm: !!rc.esm }));
1054
+ await import_fs_extra3.default.ensureFile(realpath);
1055
+ await import_fs_extra3.default.writeFile(realpath, artifact.renderer());
1118
1056
  completed += 1;
1119
1057
  task.output = `Persisted ${completed}/${total} files`;
1120
- return { path: path6.resolve(realpath) };
1058
+ return new Asset(path6.resolve(realpath));
1121
1059
  }));
1122
- context.persisted = { files };
1060
+ context.assets = files;
1123
1061
  }
1124
1062
  };
1125
1063
  }
@@ -1127,13 +1065,13 @@ function createPersistIgnoreTask() {
1127
1065
  return {
1128
1066
  title: "Update .keqignore",
1129
1067
  task: async (context, task) => {
1130
- if (!context.setup) throw new Error("Please run setup task first.");
1131
- const matcher = context.setup.matcher;
1068
+ if (!context.matcher) throw new Error("Please run setup task first.");
1069
+ const matcher = context.matcher;
1132
1070
  await matcher.write(".keqignore");
1133
1071
  }
1134
1072
  };
1135
1073
  }
1136
- function main5() {
1074
+ function main3() {
1137
1075
  return {
1138
1076
  task: (context, task) => task.newListr(
1139
1077
  [
@@ -1156,7 +1094,7 @@ function createPersistTask(compiler, options) {
1156
1094
  skip: options?.skip,
1157
1095
  task: (context, task) => task.newListr(
1158
1096
  [
1159
- main5(),
1097
+ main3(),
1160
1098
  {
1161
1099
  task: (context2, task2) => compiler.hooks.afterPersist.promise(task2)
1162
1100
  }
@@ -1168,965 +1106,1598 @@ function createPersistTask(compiler, options) {
1168
1106
  };
1169
1107
  }
1170
1108
 
1171
- // src/tasks/compile/utils/compile-schema-definition.ts
1172
- var R14 = __toESM(require("ramda"), 1);
1173
-
1174
- // src/renderer/json-schema/index.ts
1175
- var R12 = __toESM(require("ramda"), 1);
1176
-
1177
- // src/renderer/utils/generate-schema.ts
1178
- var R11 = __toESM(require("ramda"), 1);
1179
- function generateComment(schema) {
1180
- const lines = ["/**"];
1181
- if (schema.description) {
1182
- const description = schema.description.replace("*/", "*\\/");
1183
- lines.push(...description.split("\n").map((line) => ` * ${line}`));
1184
- }
1185
- if (schema.deprecated) {
1186
- lines.push(" * @deprecated");
1187
- }
1188
- if (schema.readOnly) {
1189
- lines.push(" * @readonly");
1190
- }
1191
- if (schema.format) {
1192
- lines.push(` * @format ${schema.format}`);
1193
- }
1194
- lines.push(" */");
1195
- if (lines.length === 2) return "";
1196
- return lines.join("\n");
1109
+ // src/compiler/tasks/compile/index.ts
1110
+ function main4(compiler) {
1111
+ return {
1112
+ task: async (context, task) => {
1113
+ if (!context.rc) throw new Error("Please run setup task first.");
1114
+ if (!context.documents) throw new Error("Please run shaking task first.");
1115
+ context.artifacts = [];
1116
+ await compiler.hooks.compile.promise(task);
1117
+ }
1118
+ };
1197
1119
  }
1198
- function generateSchema(schema, alias = R11.identity) {
1199
- if (typeof schema === "boolean") return "unknown";
1200
- if (JsonSchemaUtils.isRef(schema)) return generateReference(schema, alias);
1201
- if (JsonSchemaUtils.isMixed(schema)) return generateMixed(schema, alias);
1202
- if (JsonSchemaUtils.isArray(schema)) return generateArray(schema, alias);
1203
- if (schema.type === "object") return generateObject(schema, alias);
1204
- if (schema.enum) return generateEnum(schema, alias);
1205
- if (schema.oneOf) return generateOneOf(schema, alias);
1206
- if (schema.anyOf) return generateAnyOf(schema, alias);
1207
- if (schema.allOf) return generateAllOf(schema, alias);
1208
- if (schema.type === "string") return generateString(schema, alias);
1209
- if (schema.type === "number") return generateNumber(schema, alias);
1210
- if (schema.type === "boolean") return generateBoolean(schema, alias);
1211
- if (schema.type === "null") return generateNull(schema, alias);
1212
- if (schema.type === "integer") return generateInteger(schema, alias);
1213
- return "unknown";
1120
+ function createCompileTask(compiler, options) {
1121
+ return {
1122
+ title: "Compile",
1123
+ enabled: options?.enabled,
1124
+ skip: options?.skip,
1125
+ task: (context, task) => task.newListr(
1126
+ [
1127
+ {
1128
+ task: (context2, task2) => compiler.hooks.beforeCompile.promise(task2)
1129
+ },
1130
+ main4(compiler),
1131
+ {
1132
+ task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
1133
+ }
1134
+ ],
1135
+ {
1136
+ concurrent: false
1137
+ }
1138
+ )
1139
+ };
1214
1140
  }
1215
- function generateMixed(schema, alias) {
1216
- if (Array.isArray(schema.type)) {
1217
- schema.type.map((type) => ({ ...schema, type })).map((schema2) => generateSchema(schema2, alias)).join(" | ");
1218
- }
1219
- return "unknown";
1141
+
1142
+ // src/compiler/intercepter/print-information.ts
1143
+ function proxyTaskWrapper(pluginName, task) {
1144
+ return new Proxy(task, {
1145
+ set(target, prop2, value) {
1146
+ if (prop2 !== "output") {
1147
+ return Reflect.set(target, prop2, value);
1148
+ }
1149
+ target.output = `[Plugin: ${pluginName}] ${value}`;
1150
+ return true;
1151
+ }
1152
+ });
1220
1153
  }
1221
- function generateReference(schema, alias) {
1222
- if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
1223
- const parts = schema.$ref.split("/");
1224
- return alias(parts[parts.length - 1]) || "unknown";
1154
+ function printInformation(taskIndex) {
1155
+ return {
1156
+ register: (tap) => {
1157
+ const fn = tap.fn;
1158
+ if (tap.type === "promise") {
1159
+ tap.fn = (...args) => {
1160
+ const task = args[taskIndex];
1161
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1162
+ args[taskIndex] = proxyTask;
1163
+ proxyTask.output = "Processing...";
1164
+ return fn(...args);
1165
+ };
1166
+ }
1167
+ if (tap.type === "sync") {
1168
+ tap.fn = (...args) => {
1169
+ const task = args[taskIndex];
1170
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1171
+ args[taskIndex] = proxyTask;
1172
+ proxyTask.output = "Processing...";
1173
+ return fn(...args);
1174
+ };
1175
+ }
1176
+ if (tap.type === "async") {
1177
+ tap.fn = (...args) => {
1178
+ const task = args[taskIndex];
1179
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1180
+ args[taskIndex] = proxyTask;
1181
+ proxyTask.output = "Processing...";
1182
+ return fn(...args);
1183
+ };
1184
+ }
1185
+ return tap;
1186
+ }
1187
+ };
1225
1188
  }
1226
- function generateArray(schema, alias) {
1227
- if (schema.items && Array.isArray(schema.items)) {
1228
- const items = schema.items.map((s) => generateSchema(s, alias)).join(", ");
1229
- return `[${items}]`;
1230
- }
1231
- if (schema.items && typeof schema.items === "object") {
1232
- return `${generateSchema(schema.items, alias)}[]`;
1233
- }
1234
- return "any[]";
1189
+
1190
+ // src/compiler/intercepter/perfect-error-message.ts
1191
+ var R10 = __toESM(require("ramda"), 1);
1192
+ function perfectErrorMessage() {
1193
+ return {
1194
+ register: (tap) => {
1195
+ const fn = tap.fn;
1196
+ function prefix(err) {
1197
+ if (err instanceof Error) {
1198
+ err.message = `[Plugin: ${tap.name}] ${err.message}`;
1199
+ }
1200
+ }
1201
+ if (tap.type === "promise") {
1202
+ tap.fn = async (...args) => {
1203
+ try {
1204
+ return await fn(...args);
1205
+ } catch (err) {
1206
+ prefix(err);
1207
+ throw err;
1208
+ }
1209
+ };
1210
+ }
1211
+ if (tap.type === "sync") {
1212
+ tap.fn = (...args) => {
1213
+ try {
1214
+ return fn(...args);
1215
+ } catch (err) {
1216
+ prefix(err);
1217
+ throw err;
1218
+ }
1219
+ };
1220
+ }
1221
+ if (tap.type === "async") {
1222
+ tap.fn = (...args) => {
1223
+ const callback = R10.last(args);
1224
+ return fn(...R10.init(args), (err, result) => {
1225
+ prefix(err);
1226
+ return callback(err, result);
1227
+ });
1228
+ };
1229
+ }
1230
+ return tap;
1231
+ }
1232
+ };
1235
1233
  }
1234
+
1235
+ // src/plugins/eslint/index.ts
1236
+ var import_eslint = require("eslint");
1237
+
1238
+ // src/plugins/prettier/index.ts
1239
+ var import_child_process = require("child_process");
1240
+ var import_util = require("util");
1241
+ var execAsync = (0, import_util.promisify)(import_child_process.exec);
1242
+
1243
+ // src/plugins/body-fallback/index.ts
1244
+ var R22 = __toESM(require("ramda"), 1);
1245
+
1246
+ // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
1247
+ var import_tapable2 = require("tapable");
1248
+
1249
+ // src/plugins/generate-micro-function/constants/metadata-storage.ts
1250
+ var MetadataStorage = /* @__PURE__ */ new WeakMap();
1251
+
1252
+ // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
1253
+ var R21 = __toESM(require("ramda"), 1);
1254
+ var path10 = __toESM(require("path"), 1);
1255
+ var changeCase6 = __toESM(require("change-case"), 1);
1256
+
1257
+ // src/plugins/generate-declaration/generate-declaration.plugin.ts
1258
+ var import_tapable = require("tapable");
1259
+
1260
+ // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
1261
+ var path9 = __toESM(require("path"), 1);
1262
+ var changeCase5 = __toESM(require("change-case"), 1);
1263
+
1264
+ // src/transformers/json-schema/comment.renderer.ts
1265
+ var CommentRenderer = class {
1266
+ constructor(schema) {
1267
+ this.schema = schema;
1268
+ }
1269
+ render() {
1270
+ const schema = this.schema;
1271
+ const lines = ["/**"];
1272
+ if (schema.description) {
1273
+ const description = schema.description.replace("*/", "*\\/");
1274
+ lines.push(...description.split("\n").map((line) => ` * ${line}`));
1275
+ }
1276
+ if (schema.deprecated) {
1277
+ lines.push(" * @deprecated");
1278
+ }
1279
+ if (schema.readOnly) {
1280
+ lines.push(" * @readonly");
1281
+ }
1282
+ if (schema.format) {
1283
+ lines.push(` * @format ${schema.format}`);
1284
+ }
1285
+ lines.push(" */");
1286
+ if (lines.length === 2) return "";
1287
+ return lines.join("\n");
1288
+ }
1289
+ };
1290
+
1291
+ // src/transformers/json-schema/declaration.renderer.ts
1292
+ var R12 = __toESM(require("ramda"), 1);
1293
+
1294
+ // src/utils/indent.ts
1236
1295
  function indent(space, text) {
1237
1296
  if (text === "") return "";
1238
1297
  const indentation = " ".repeat(space);
1239
- return text.split("\n").map((line) => `${indentation}${line}`).join("\n");
1298
+ return text.split("\n").map((line) => line ? `${indentation}${line}` : line).join("\n");
1240
1299
  }
1241
- function generateObject(schema, alias) {
1242
- if ((!schema.properties || R11.isEmpty(schema.properties)) && (!schema.additionalProperties || R11.isEmpty(schema.additionalProperties))) {
1243
- return "object";
1300
+
1301
+ // src/transformers/json-schema/reference.transformer.ts
1302
+ var R11 = __toESM(require("ramda"), 1);
1303
+ var ReferenceTransformer = class {
1304
+ static toDeclaration(schema, alias2 = R11.identity) {
1305
+ if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
1306
+ const parts = schema.$ref.split("/");
1307
+ return alias2(parts[parts.length - 1]) || "unknown";
1244
1308
  }
1245
- const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
1246
- let $comment = generateComment(propertySchema);
1247
- if ($comment) $comment += "\n";
1248
- const $key = `"${propertyName}"${schema.required?.includes(propertyName) ? "" : "?"}`;
1249
- const $value = generateSchema(propertySchema, alias);
1250
- return indent(2, `${$comment}${$key}: ${$value}`);
1251
- });
1252
- if (schema.additionalProperties) {
1253
- const $value = schema.additionalProperties === true ? "any" : generateSchema(schema.additionalProperties, alias);
1254
- $properties.push(indent(2, `[key: string]: ${$value}`));
1255
- }
1256
- return [
1257
- "{",
1258
- ...$properties,
1259
- "}"
1260
- ].join("\n");
1261
- }
1262
- function generateOneOf(schema, alias) {
1263
- if (!schema.oneOf) return "unknown";
1264
- return schema.oneOf.map((s) => generateSchema(s, alias)).join(" | ");
1265
- }
1266
- function generateAnyOf(schema, alias) {
1267
- if (!schema.anyOf) return "unknown";
1268
- return schema.anyOf.map((s) => generateSchema(s, alias)).join(" | ");
1269
- }
1270
- function generateAllOf(schema, alias) {
1271
- if (!schema.allOf) return "unknown";
1272
- return schema.allOf.map((s) => generateSchema(s, alias)).join(" & ");
1273
- }
1274
- function generateEnum(schema, alias) {
1275
- if (!schema.enum) return "unknown";
1276
- return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
1277
- }
1278
- function generateString(schema, alias) {
1279
- if (schema.contentMediaType === "application/octet-stream") return "Blob | Buffer";
1280
- if (schema.format === "binary") return "Blob | Buffer";
1281
- return "string";
1282
- }
1283
- function generateNumber(schema, alias) {
1284
- return "number";
1285
- }
1286
- function generateBoolean(schema, alias) {
1287
- return "boolean";
1288
- }
1289
- function generateNull(schema, alias) {
1290
- return "null";
1291
- }
1292
- function generateInteger(schema, alias) {
1293
- return "number";
1294
- }
1309
+ };
1295
1310
 
1296
- // src/renderer/json-schema/index.ts
1297
- async function jsonSchemaRenderer(schemaDefinition) {
1298
- let $comment = generateComment(schemaDefinition.schema);
1299
- if ($comment) $comment += "\n";
1300
- if (typeof schemaDefinition.schema === "boolean") {
1301
- return [
1302
- "/* @anchor:file:start */",
1303
- "",
1304
- $comment || void 0,
1305
- `type ${schemaDefinition.name} = unknown`,
1306
- "",
1307
- "/* @anchor:file:end */"
1308
- ].filter(R12.isNotNil).join("\n");
1311
+ // src/transformers/json-schema/declaration.renderer.ts
1312
+ var DeclarationRenderer = class {
1313
+ constructor(schema, options = {}) {
1314
+ this.schema = schema;
1315
+ this.options = options;
1309
1316
  }
1310
- if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
1311
- const $schema = generateSchema(schemaDefinition.schema);
1312
- const $declaration = $schema.startsWith("{") ? `export interface ${schemaDefinition.name} ${$schema}` : `export type ${schemaDefinition.name} = ${$schema}`;
1313
- return [
1314
- "/* @anchor:file:start */",
1315
- "",
1316
- $comment || void 0,
1317
- $declaration,
1318
- "",
1319
- "/* @anchor:file:end */"
1320
- ].filter(R12.isNotNil).join("\n");
1321
- }
1322
- return [
1323
- "/* @anchor:file:start */",
1324
- "",
1325
- $comment || void 0,
1326
- `export type ${schemaDefinition.name} = ${generateSchema(schemaDefinition.schema)}`,
1327
- "",
1328
- "/* @anchor:file:end */"
1329
- ].filter(R12.isNotNil).join("\n");
1330
- }
1331
-
1332
- // src/tasks/utils/anchor.ts
1333
- var AnchorBlock = class {
1334
- constructor(artifact) {
1335
- this.artifact = artifact;
1317
+ render() {
1318
+ return this.renderSchema(this.schema);
1319
+ }
1320
+ renderSchema(schema) {
1321
+ if (typeof schema === "boolean") return "unknown";
1322
+ if (JsonSchemaUtils.isRef(schema)) return this.renderReference(schema);
1323
+ if (JsonSchemaUtils.isMixed(schema)) return this.renderMixed(schema);
1324
+ if (JsonSchemaUtils.isArray(schema)) return this.renderArray(schema);
1325
+ if (schema.type === "object") return this.renderObject(schema);
1326
+ if (schema.enum) return this.renderEnum(schema);
1327
+ if (schema.oneOf) return this.renderOneOf(schema);
1328
+ if (schema.anyOf) return this.renderAnyOf(schema);
1329
+ if (schema.allOf) return this.renderAllOf(schema);
1330
+ if (schema.type === "string") return this.renderString(schema);
1331
+ if (schema.type === "number") return this.renderNumber(schema);
1332
+ if (schema.type === "boolean") return this.renderBoolean(schema);
1333
+ if (schema.type === "null") return this.renderNull(schema);
1334
+ if (schema.type === "integer") return this.renderInteger(schema);
1335
+ return "unknown";
1336
+ }
1337
+ renderMixed(schema) {
1338
+ if (Array.isArray(schema.type)) {
1339
+ schema.type.map((type) => ({ ...schema, type })).map((schema2) => this.renderSchema(schema2)).join(" | ");
1340
+ }
1341
+ return "unknown";
1336
1342
  }
1337
- /**
1338
- * Append content to the end of the anchor block.
1339
- */
1340
- append(anchorName, content) {
1341
- const lines = this.artifact.content.split("\n");
1342
- const anchor = `@anchor:${anchorName}:end`;
1343
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1344
- if (anchorIndex === -1) {
1345
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1343
+ renderReference(schema) {
1344
+ if (!this.options.referenceTransformer) {
1345
+ return ReferenceTransformer.toDeclaration(schema);
1346
1346
  }
1347
- lines.splice(anchorIndex, 0, content);
1348
- this.artifact.content = lines.join("\n");
1347
+ return this.options.referenceTransformer(schema);
1349
1348
  }
1350
- prepend(anchorName, content) {
1351
- const lines = this.artifact.content.split("\n");
1352
- const anchor = `@anchor:${anchorName}:start`;
1353
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1354
- if (anchorIndex === -1) {
1355
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1349
+ renderArray(schema) {
1350
+ if (schema.items && Array.isArray(schema.items)) {
1351
+ const items = schema.items.map((s) => this.renderSchema(s)).join(", ");
1352
+ return `[${items}]`;
1356
1353
  }
1357
- lines.splice(anchorIndex + 1, 0, content);
1358
- this.artifact.content = lines.join("\n");
1354
+ if (schema.items && typeof schema.items === "object") {
1355
+ return `${this.renderSchema(schema.items)}[]`;
1356
+ }
1357
+ return "any[]";
1359
1358
  }
1360
- replace(anchorName, content) {
1361
- const lines = this.artifact.content.split("\n");
1362
- const startIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:start */`));
1363
- const endIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:end */`));
1364
- if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
1365
- throw new Error(`"@anchor:${anchorName}:start" or "@anchor:${anchorName}:end" not found in artifact "${this.artifact.filepath}".`);
1359
+ renderObject(schema) {
1360
+ if ((!schema.properties || R12.isEmpty(schema.properties)) && (!schema.additionalProperties || R12.isEmpty(schema.additionalProperties))) {
1361
+ return "object";
1366
1362
  }
1367
- lines.splice(startIndex + 1, endIndex - startIndex - 1, content);
1368
- this.artifact.content = lines.join("\n");
1363
+ const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
1364
+ let $comment = new CommentRenderer(propertySchema).render();
1365
+ if ($comment) $comment += "\n";
1366
+ const $key = `"${propertyName}"${schema.required?.includes(propertyName) ? "" : "?"}`;
1367
+ const $value = this.renderSchema(propertySchema);
1368
+ return indent(2, `${$comment}${$key}: ${$value}`);
1369
+ });
1370
+ if (schema.additionalProperties) {
1371
+ const $value = schema.additionalProperties === true ? "any" : this.renderSchema(schema.additionalProperties);
1372
+ $properties.push(indent(2, `[key: string]: ${$value}`));
1373
+ }
1374
+ return [
1375
+ "{",
1376
+ ...$properties,
1377
+ "}"
1378
+ ].join("\n");
1379
+ }
1380
+ renderOneOf(schema) {
1381
+ if (!schema.oneOf) return "unknown";
1382
+ return schema.oneOf.map((s) => this.renderSchema(s)).join(" | ");
1383
+ }
1384
+ renderAnyOf(schema) {
1385
+ if (!schema.anyOf) return "unknown";
1386
+ return schema.anyOf.map((s) => this.renderSchema(s)).join(" | ");
1387
+ }
1388
+ renderAllOf(schema) {
1389
+ if (!schema.allOf) return "unknown";
1390
+ return schema.allOf.map((s) => this.renderSchema(s)).join(" & ");
1391
+ }
1392
+ renderEnum(schema) {
1393
+ if (!schema.enum) return "unknown";
1394
+ return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
1395
+ }
1396
+ renderString(schema) {
1397
+ if (schema.contentMediaType === "application/octet-stream") return "Blob | Buffer";
1398
+ if (schema.format === "binary") return "Blob | Buffer";
1399
+ return "string";
1400
+ }
1401
+ renderNumber(schema) {
1402
+ return "number";
1403
+ }
1404
+ renderBoolean(schema) {
1405
+ return "boolean";
1406
+ }
1407
+ renderNull(schema) {
1408
+ return "null";
1409
+ }
1410
+ renderInteger(schema) {
1411
+ return "number";
1369
1412
  }
1370
1413
  };
1371
- var Anchor = class {
1372
- constructor(artifact) {
1373
- this.artifact = artifact;
1374
- this.block = new AnchorBlock(artifact);
1414
+
1415
+ // src/transformers/json-schema/json-schema.transformer.ts
1416
+ var JsonSchemaTransformer = class {
1417
+ static toComment(schema) {
1418
+ return new CommentRenderer(schema).render();
1375
1419
  }
1376
- block;
1377
- append(anchorName, content) {
1378
- const lines = this.artifact.content.split("\n");
1379
- const anchor = `@anchor:${anchorName}`;
1380
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1381
- if (anchorIndex === -1) {
1382
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1383
- }
1384
- lines.splice(anchorIndex + 1, 0, content);
1385
- this.artifact.content = lines.join("\n");
1420
+ static toDeclaration(schema, options) {
1421
+ return new DeclarationRenderer(schema, options).render();
1386
1422
  }
1387
- prepend(anchorName, content) {
1388
- const lines = this.artifact.content.split("\n");
1389
- const anchor = `@anchor:${anchorName}`;
1390
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1391
- if (anchorIndex === -1) {
1392
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1423
+ };
1424
+
1425
+ // src/transformers/schema-definition/schema-definition.transformer.ts
1426
+ var R13 = __toESM(require("ramda"), 1);
1427
+ var SchemaDefinitionTransformer = class {
1428
+ static toDeclaration(schemaDefinition, options) {
1429
+ const dependencies = schemaDefinition.getDependencies();
1430
+ let $dependencies = dependencies.filter((dep) => !SchemaDefinition.isUnknown(dep)).map((dep) => {
1431
+ const filepath = options.getDependentSchemaDefinitionFilepath(dep);
1432
+ return `import type { ${dep.name} } from "${filepath}"`;
1433
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
1434
+ if ($dependencies) $dependencies += "\n";
1435
+ let $comment = JsonSchemaTransformer.toComment(schemaDefinition.schema);
1436
+ if ($comment) $comment += "\n";
1437
+ if (typeof schemaDefinition.schema === "boolean") {
1438
+ return [
1439
+ "/* @anchor:file:start */",
1440
+ "",
1441
+ $dependencies,
1442
+ $comment || void 0,
1443
+ `type ${schemaDefinition.name} = unknown`,
1444
+ "",
1445
+ "/* @anchor:file:end */"
1446
+ ].filter(R13.isNotNil).join("\n");
1393
1447
  }
1394
- lines.splice(anchorIndex, 0, content);
1395
- this.artifact.content = lines.join("\n");
1448
+ if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
1449
+ const $schema = JsonSchemaTransformer.toDeclaration(schemaDefinition.schema);
1450
+ const $declaration = $schema.startsWith("{") ? `export interface ${schemaDefinition.name} ${$schema}` : `export type ${schemaDefinition.name} = ${$schema}`;
1451
+ return [
1452
+ "/* @anchor:file:start */",
1453
+ "",
1454
+ $dependencies,
1455
+ $comment || void 0,
1456
+ $declaration,
1457
+ "",
1458
+ "/* @anchor:file:end */"
1459
+ ].filter(R13.isNotNil).join("\n");
1460
+ }
1461
+ return [
1462
+ "/* @anchor:file:start */",
1463
+ "",
1464
+ $dependencies,
1465
+ $comment || void 0,
1466
+ `export type ${schemaDefinition.name} = ${JsonSchemaTransformer.toDeclaration(schemaDefinition.schema)}`,
1467
+ "",
1468
+ "/* @anchor:file:end */"
1469
+ ].filter(R13.isNotNil).join("\n");
1396
1470
  }
1397
1471
  };
1398
1472
 
1399
- // src/tasks/utils/artifact.ts
1400
- var path8 = __toESM(require("path"), 1);
1401
- var changeCase = __toESM(require("change-case"), 1);
1473
+ // src/transformers/operation-definition/comment.renderer.ts
1474
+ var R14 = __toESM(require("ramda"), 1);
1475
+ var CommentRenderer2 = class {
1476
+ constructor(operationDefinition) {
1477
+ this.operationDefinition = operationDefinition;
1478
+ }
1479
+ render() {
1480
+ const operation = this.operationDefinition.operation;
1481
+ if (!operation.summary && !operation.description) return "";
1482
+ const lines = ["/**"];
1483
+ if (operation.summary && typeof operation.summary === "string") {
1484
+ lines.push(` * ${R14.trim(operation.summary)}`);
1485
+ lines.push(" *");
1486
+ }
1487
+ if (operation.description && typeof operation.description === "string") {
1488
+ lines.push(` * @description ${R14.trim(operation.description)}`);
1489
+ }
1490
+ lines.push(" */");
1491
+ return lines.join("\n");
1492
+ }
1493
+ };
1402
1494
 
1403
- // src/tasks/utils/dependency.ts
1404
- var path7 = __toESM(require("path"), 1);
1495
+ // src/transformers/operation-definition/declaration.renderer.ts
1496
+ var R15 = __toESM(require("ramda"), 1);
1405
1497
 
1406
- // src/tasks/utils/to-comment.ts
1407
- function toComment(msg) {
1408
- if (!msg) return "";
1409
- return msg.split("\n").map((str) => `// ${str}`).join("\n");
1498
+ // src/transformers/operation-definition/utils/type-name-factory.ts
1499
+ var changeCase = __toESM(require("change-case"), 1);
1500
+ function typeNameFactory(operationDefinition) {
1501
+ const pascalCaseOperationId = changeCase.pascalCase(operationDefinition.operationId);
1502
+ return (name) => `${pascalCaseOperationId}${name}`;
1410
1503
  }
1411
1504
 
1412
- // src/tasks/utils/dependency.ts
1413
- var DependencyIdentifier = class {
1414
- constructor(name, alias, type = false) {
1415
- this.name = name;
1416
- this.alias = alias;
1417
- this.type = type;
1505
+ // src/transformers/operation-definition/declaration.renderer.ts
1506
+ var alias = (name) => `${name}Schema`;
1507
+ var DeclarationRenderer2 = class {
1508
+ constructor(operationDefinition, options) {
1509
+ this.operationDefinition = operationDefinition;
1510
+ this.options = options;
1511
+ this.typeName = typeNameFactory(operationDefinition);
1512
+ }
1513
+ typeName;
1514
+ renderResponseBodies(operation, options) {
1515
+ if (!operation.responses || R15.isEmpty(operation.responses)) {
1516
+ return `export interface ${this.typeName("ResponseBodies")} {}`;
1517
+ }
1518
+ const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
1519
+ if (!JsonSchemaUtils.isRef(response)) {
1520
+ const $value = Object.values(response.content || {}).map((mediaTypeObject) => mediaTypeObject.schema).filter((schema) => !!schema).map((schema) => JsonSchemaTransformer.toDeclaration(schema, options)).join(" | ");
1521
+ return indent(2, `${statusCode}: ${$value || "void"}`);
1522
+ }
1523
+ }).join("\n");
1524
+ return [
1525
+ `export interface ${this.typeName("ResponseBodies")} {`,
1526
+ $responses,
1527
+ "}"
1528
+ ].join("\n");
1529
+ }
1530
+ renderRequestBodies(operation, options) {
1531
+ let $requestBodies = `export interface ${this.typeName("RequestBodies")} {}`;
1532
+ if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1533
+ const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1534
+ if (!schema) return `${JSON.stringify(mediaType)}: unknown`;
1535
+ return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schema, options)}`;
1536
+ }).map((pair) => indent(2, pair));
1537
+ $requestBodies = [
1538
+ `export interface ${this.typeName("RequestBodies")} {`,
1539
+ ...$mediaTypes,
1540
+ "}"
1541
+ ].join("\n");
1542
+ }
1543
+ return $requestBodies;
1544
+ }
1545
+ renderParameterBodies(operationDefinition, options) {
1546
+ const { operation } = operationDefinition;
1547
+ let parameterBodies = "";
1548
+ if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1549
+ const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schemaOrRef]) => {
1550
+ if (!schemaOrRef) return `${JSON.stringify(mediaType)}: unknown`;
1551
+ const schema = JsonSchemaUtils.isRef(schemaOrRef) ? OpenapiUtils.dereferenceDeep(schemaOrRef.$ref, operationDefinition.document.specification) : schemaOrRef;
1552
+ if (schema.type === "object" || schema.properties) {
1553
+ return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schemaOrRef, options)} & { [key: string]: any }`;
1554
+ }
1555
+ return `${JSON.stringify(mediaType)}: { [key: string]: any }`;
1556
+ }).map((pair) => indent(2, pair));
1557
+ parameterBodies = [
1558
+ `interface ${this.typeName("ParameterBodies")} {`,
1559
+ ...$mediaTypes,
1560
+ "}",
1561
+ ""
1562
+ ].join("\n");
1563
+ }
1564
+ return parameterBodies;
1418
1565
  }
1419
- toCode() {
1420
- const $type = this.type ? "type " : "";
1421
- if (this.alias) {
1422
- return `${$type}${this.name} as ${this.alias}`;
1566
+ renderRequestParameters(operation, options) {
1567
+ const mediaTypes = operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody) ? Object.keys(operation.requestBody.content || {}) : [];
1568
+ const base = `${this.typeName("RequestQuery")} & ${this.typeName("RouteParameters")} & ${this.typeName("RequestHeaders")}`;
1569
+ if (mediaTypes.length === 1) {
1570
+ return `export type ${this.typeName("RequestParameters")} = ${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaTypes[0])}]`;
1423
1571
  }
1424
- return `${$type}${this.name}`;
1572
+ if (mediaTypes.length > 1) {
1573
+ const unions = mediaTypes.map((mediaType) => `(${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaType)}] & { "content-type": ${JSON.stringify(mediaType)} })`).join("\n| ");
1574
+ return `export type ${this.typeName("RequestParameters")} = ${unions}`;
1575
+ }
1576
+ return `export type ${this.typeName("RequestParameters")} = ${base}`;
1577
+ }
1578
+ rendererParameters(name, parameters, options) {
1579
+ if (parameters.length === 0) {
1580
+ return `export type ${name} = {}`;
1581
+ }
1582
+ const $parameters = parameters.map((parameter) => {
1583
+ const parameterName = `"${parameter.name}"`;
1584
+ const $key = parameter.required ? parameterName : `${parameterName}?`;
1585
+ const $value = JsonSchemaTransformer.toDeclaration(parameter.schema || { type: "any" }, options);
1586
+ return indent(2, `${$key}: ${$value}`);
1587
+ }).join("\n");
1588
+ return [
1589
+ `export type ${name} = {`,
1590
+ $parameters,
1591
+ "}"
1592
+ ].filter(Boolean).join("\n");
1593
+ }
1594
+ renderDependencies() {
1595
+ const schemaDefinitions = this.operationDefinition.getDependencies().filter((schemaDefinition) => !SchemaDefinition.isUnknown(schemaDefinition));
1596
+ const $schemaDefinitions = schemaDefinitions.map((schemaDefinition) => {
1597
+ const filepath = this.options.getDependentSchemaDefinitionFilepath(schemaDefinition);
1598
+ const schemaName = schemaDefinition.name;
1599
+ return `import type { ${schemaName} as ${alias(schemaName)} } from "${filepath}"`;
1600
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
1601
+ return [
1602
+ 'import type { KeqOperation, KeqPathParameterInit, KeqQueryInit } from "keq"',
1603
+ ...$schemaDefinitions
1604
+ ].join("\n");
1605
+ }
1606
+ render() {
1607
+ const { operation } = this.operationDefinition;
1608
+ if (!operation.responses) return "";
1609
+ const jsonSchemaDeclarationRendererOptions = {
1610
+ referenceTransformer: (schema) => {
1611
+ return ReferenceTransformer.toDeclaration(schema, alias);
1612
+ }
1613
+ };
1614
+ const $dependencies = this.renderDependencies();
1615
+ const $responseBodies = this.renderResponseBodies(operation, jsonSchemaDeclarationRendererOptions);
1616
+ const $requestBodies = this.renderRequestBodies(operation, jsonSchemaDeclarationRendererOptions);
1617
+ const $parameterBodies = this.renderParameterBodies(this.operationDefinition, jsonSchemaDeclarationRendererOptions);
1618
+ const $requestParameters = this.renderRequestParameters(operation, jsonSchemaDeclarationRendererOptions);
1619
+ const $requestQuery = this.rendererParameters(
1620
+ `${this.typeName("RequestQuery")}`,
1621
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "query") || [],
1622
+ jsonSchemaDeclarationRendererOptions
1623
+ );
1624
+ const $routeParameters = this.rendererParameters(
1625
+ `${this.typeName("RouteParameters")}`,
1626
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "path") || [],
1627
+ jsonSchemaDeclarationRendererOptions
1628
+ );
1629
+ const $requestHeaders = this.rendererParameters(
1630
+ `${this.typeName("RequestHeaders")}`,
1631
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "header") || [],
1632
+ jsonSchemaDeclarationRendererOptions
1633
+ );
1634
+ return [
1635
+ "/* @anchor:file:start */",
1636
+ "",
1637
+ $dependencies,
1638
+ "",
1639
+ $responseBodies,
1640
+ "",
1641
+ $requestBodies,
1642
+ "",
1643
+ $requestQuery,
1644
+ "",
1645
+ $routeParameters,
1646
+ "",
1647
+ $requestHeaders,
1648
+ "",
1649
+ $parameterBodies || void 0,
1650
+ $requestParameters,
1651
+ "",
1652
+ `export interface ${this.typeName("Operation")}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${$parameterBodies ? `keyof ${this.typeName("ParameterBodies")}` : "string"} > extends KeqOperation {`,
1653
+ ` requestParams: ${this.typeName("RouteParameters")} & { [key: string]: KeqPathParameterInit }`,
1654
+ ` requestQuery: ${this.typeName("RequestQuery")} & { [key: string]: KeqQueryInit }`,
1655
+ ` requestHeaders: ${this.typeName("RequestHeaders")} & { [key: string]: string | number }`,
1656
+ ` requestBody: ${$parameterBodies ? `${this.typeName("ParameterBodies")}[CONTENT_TYPE] | ` : "object | "}BodyInit`,
1657
+ ` responseBody: ${this.typeName("ResponseBodies")}[STATUS]`,
1658
+ "}",
1659
+ "",
1660
+ "/* @anchor:file:end */"
1661
+ ].filter(R15.isNotNil).join("\n");
1425
1662
  }
1426
1663
  };
1427
- var Dependency = class {
1428
- source;
1429
- identifiers;
1430
- export;
1431
- belongTo;
1432
- constructor(source, identifiers, belongTo, options) {
1433
- this.source = source;
1434
- this.identifiers = identifiers.map((i) => typeof i === "string" ? new DependencyIdentifier(i) : i);
1435
- if (options?.type) {
1436
- for (const identifier of this.identifiers) {
1437
- identifier.type = true;
1664
+
1665
+ // src/transformers/operation-definition/micro-function.renderer.ts
1666
+ var R17 = __toESM(require("ramda"), 1);
1667
+
1668
+ // src/transformers/operation-definition/typescript-helper.ts
1669
+ var R16 = __toESM(require("ramda"), 1);
1670
+ var OperationDefinitionSnippet = class {
1671
+ constructor(operationDefinition, options) {
1672
+ this.operationDefinition = operationDefinition;
1673
+ this.options = options;
1674
+ this.typeName = typeNameFactory(operationDefinition);
1675
+ }
1676
+ typeName;
1677
+ getQsParameters(parameter) {
1678
+ if (typeof this.options.qs === "function") {
1679
+ return this.options.qs(parameter);
1680
+ } else if (typeof this.options.qs === "object") {
1681
+ return this.options.qs;
1682
+ }
1683
+ const style = parameter.style || "form";
1684
+ const explode = parameter.explode ?? true;
1685
+ if (style === "deepObject") {
1686
+ return { arrayFormat: "brackets" };
1687
+ } else if (explode) {
1688
+ return { arrayFormat: "repeat" };
1689
+ } else {
1690
+ if (style === "form") {
1691
+ return { arrayFormat: "comma" };
1692
+ } else if (style === "spaceDelimited") {
1693
+ return { arrayFormat: "space" };
1694
+ } else if (style === "pipeDelimited") {
1695
+ return { arrayFormat: "pipe" };
1438
1696
  }
1439
1697
  }
1440
- this.export = !!options?.export;
1441
- this.belongTo = belongTo;
1698
+ return {};
1442
1699
  }
1443
- get realSource() {
1444
- if (typeof this.source === "string") {
1445
- if (this.source.startsWith(".")) return path7.relative(this.belongTo.filepath, this.source);
1446
- return this.source;
1700
+ // render: "if (args && 'Authorization' in args) req.header('Authorization', args['Authorization'])"
1701
+ renderRequestHeaders() {
1702
+ const { operation } = this.operationDefinition;
1703
+ const $headers = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "header").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.header(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1704
+ return $headers;
1705
+ }
1706
+ // render: "if (args && 'id' in args) req.query('id', args['id'], options)"
1707
+ renderRequestQuery() {
1708
+ const { operation } = this.operationDefinition;
1709
+ const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1710
+ const option = this.getQsParameters(p);
1711
+ const $option = !option || R16.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1712
+ return `if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1713
+ }).join("\n");
1714
+ return $query;
1715
+ }
1716
+ // render: "if (args && 'id' in args) req.params('id', args['id'])"
1717
+ renderRequestPathParameters() {
1718
+ const { operation } = this.operationDefinition;
1719
+ const $pathParameters = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "path").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.params(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1720
+ return $pathParameters;
1721
+ }
1722
+ getRequestMediaTypes() {
1723
+ const { operation } = this.operationDefinition;
1724
+ const requestBodyContent = operation.requestBody?.content || {};
1725
+ return Object.keys(requestBodyContent);
1726
+ }
1727
+ // render "req.type("application/json")"
1728
+ renderMediaType() {
1729
+ const mediaTypes = this.getRequestMediaTypes();
1730
+ if (mediaTypes.length === 1 && !mediaTypes[0].endsWith("/*")) {
1731
+ return `req.type("${mediaTypes[0]}")
1732
+ `;
1733
+ } else if (mediaTypes.some((mediaType) => mediaType === "*/*")) {
1734
+ } else if (mediaTypes.some((mediaType) => mediaType.endsWith("/*"))) {
1735
+ return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1736
+ } else if (mediaTypes.length > 1) {
1737
+ return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1447
1738
  }
1448
- return this.source.relativeTo(this.belongTo.dirname);
1739
+ return "";
1449
1740
  }
1450
- toCode(options) {
1451
- const { esm } = options;
1741
+ // render body
1742
+ requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType) {
1452
1743
  try {
1453
- let fullpath = this.realSource;
1454
- if (fullpath.startsWith(".") && fullpath.endsWith(".ts")) {
1455
- if (esm) {
1456
- fullpath = fullpath.replace(/\.ts$/, ".js");
1457
- } else {
1458
- fullpath = fullpath.replace(/\.ts$/, "");
1459
- }
1460
- }
1461
- if (this.identifiers.length > 0) {
1462
- const $identifiers = this.identifiers.map((i) => i.toCode()).join(", ");
1463
- return `${this.export ? "export" : "import"} { ${$identifiers} } from '${fullpath}'`;
1744
+ const $propertyName = JSON.stringify(propertyName);
1745
+ const schema = JsonSchemaUtils.isRef(propertySchema) ? OpenapiUtils.dereferenceDeep(propertySchema.$ref, this.operationDefinition.document.specification) : propertySchema;
1746
+ if (schema.type === "string" && schema.format === "binary" || schema.contentMediaType === "application/octet-stream") {
1747
+ return `if (args && ${$propertyName} in args && args[${$propertyName}]) req.attach(${$propertyName}, args[${$propertyName}])`;
1748
+ } else if (schema.type === "string" || schema.type === "array" && schema.items && schema.items.type === "string") {
1749
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, args[${$propertyName}])`;
1750
+ } else if (schema.type === "number" || schema.type === "integer") {
1751
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]))`;
1464
1752
  }
1465
- if (this.export) {
1466
- return `export * from '${fullpath}'`;
1467
- }
1468
- return `import '${fullpath}'`;
1753
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]) /* type is non-string in schema; triggers type coercion here */)`;
1469
1754
  } catch (err) {
1470
- return toComment(String(err));
1755
+ return this.renderErrorComment(err, mediaType);
1471
1756
  }
1472
1757
  }
1473
- };
1474
-
1475
- // src/tasks/utils/artifact.ts
1476
- var HeaderComment = [
1477
- "// Code generated by keq-cli. DO NOT EDIT.",
1478
- "// Code generated by keq-cli. DO NOT EDIT.",
1479
- "// Code generated by keq-cli. DO NOT EDIT.",
1480
- "",
1481
- ""
1482
- ].join("\n");
1483
- var Artifact = class {
1484
- id;
1485
- filepath;
1486
- dependencies = [];
1487
- warns = [];
1488
- content;
1489
- extensionName;
1490
- anchor = new Anchor(this);
1491
- constructor(options) {
1492
- this.id = options.id;
1493
- this.filepath = options.filepath;
1494
- this.extensionName = options.extensionName || path8.extname(options.filepath);
1495
- this.content = options.content;
1496
- if (options.dependencies) this.dependencies = options.dependencies;
1497
- }
1498
- get dirname() {
1499
- return path8.dirname(this.filepath);
1758
+ requestBodyPropertyRenderer(propertyName, propertySchema, mediaType) {
1759
+ if (mediaType === "application/json") {
1760
+ const $propertyName = JSON.stringify(propertyName);
1761
+ return `if (args && ${$propertyName} in args) req.send({ ${$propertyName}: args[${$propertyName}] })`;
1762
+ } else if (mediaType === "multipart/form-data") {
1763
+ return this.requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType);
1764
+ } else {
1765
+ throw new Error(`Unsupported media type: ${mediaType}`);
1766
+ }
1500
1767
  }
1501
- changeFileNameCase(style) {
1502
- this.filepath = this.filepath.split("/").map((part, index, arr) => {
1503
- if (part === "." || part === "..") return part;
1504
- if (index !== arr.length - 1) {
1505
- return `${changeCase[style](part)}`;
1768
+ renderRequestBody() {
1769
+ const { operation } = this.operationDefinition;
1770
+ const requestBodyContent = operation.requestBody?.content || {};
1771
+ const $requestBody = Object.entries(requestBodyContent).map(([mediaType, mediaTypeObject]) => {
1772
+ if (!mediaTypeObject.schema) return;
1773
+ try {
1774
+ const schema = JsonSchemaUtils.isRef(mediaTypeObject.schema) ? OpenapiUtils.dereferenceDeep(mediaTypeObject.schema.$ref, this.operationDefinition.document.specification) : mediaTypeObject.schema;
1775
+ if (schema.type !== "object") return;
1776
+ const properties = schema.properties || {};
1777
+ return Object.entries(properties).map(([propertyName, propertySchema]) => this.requestBodyPropertyRenderer(propertyName, propertySchema, mediaType)).join("\n");
1778
+ } catch (err) {
1779
+ return this.renderErrorComment(err, mediaType);
1506
1780
  }
1507
- const baesname = path8.basename(part, this.extensionName);
1508
- return `${changeCase[style](baesname)}${this.extensionName}`;
1509
- }).join("/");
1510
- return this;
1511
- }
1512
- relativeTo(filepath) {
1513
- const relativePath = path8.relative(filepath, this.filepath);
1514
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1515
- }
1516
- addDependence(source, identifiers, options) {
1517
- const dependence = new Dependency(
1518
- source,
1519
- identifiers,
1520
- this,
1521
- options
1522
- );
1523
- this.dependencies.push(dependence);
1524
- return dependence;
1781
+ }).filter(R16.isNotNil).join("\n");
1782
+ return $requestBody;
1525
1783
  }
1526
- addWarn(message) {
1527
- this.warns.push(message);
1784
+ renderErrorComment(err, mediaType) {
1785
+ const $err = String(err).split("\n").map(((line) => ` * ${line}`)).join("\n");
1786
+ return [
1787
+ "/**",
1788
+ ` * Unable to dereference schema for media type ${mediaType}`,
1789
+ $err,
1790
+ " */"
1791
+ ].join("\n");
1528
1792
  }
1529
- toCode(options) {
1530
- let $dependencies = this.dependencies.map((dependency) => dependency.toCode(options)).filter((line) => line.trim() !== "").join("\n");
1531
- if ($dependencies) {
1532
- $dependencies += "\n\n";
1533
- }
1534
- let $warns = "";
1535
- if (this.warns.length) {
1536
- $warns = toComment([
1537
- "!!! Here is some Problems !!!",
1538
- "",
1539
- this.warns
1540
- ].join("\n"));
1541
- $warns += "\n\n";
1793
+ };
1794
+
1795
+ // src/transformers/operation-definition/micro-function.renderer.ts
1796
+ var OperationDefinitionMicroFunctionRenderer = class {
1797
+ constructor(operationDefinition, options) {
1798
+ this.operationDefinition = operationDefinition;
1799
+ this.options = options;
1800
+ this.typeName = typeNameFactory(operationDefinition);
1801
+ this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1802
+ }
1803
+ helper;
1804
+ typeName;
1805
+ render() {
1806
+ const { operation, operationId, method, pathname } = this.operationDefinition;
1807
+ if (!operation.responses) return "";
1808
+ const $dependencies = this.renderDependencies();
1809
+ const $comment = new CommentRenderer2(this.operationDefinition).render();
1810
+ const moduleName = this.operationDefinition.module.name;
1811
+ const $method = method.toLowerCase();
1812
+ const $queryParameters = this.helper.renderRequestQuery();
1813
+ const $headerParameters = this.helper.renderRequestHeaders();
1814
+ const $pathParameters = this.helper.renderRequestPathParameters();
1815
+ const $mediaType = this.helper.renderMediaType();
1816
+ const $requestBody = this.helper.renderRequestBody();
1817
+ const $operationDeclaration = this.renderOperationDeclaration();
1818
+ return [
1819
+ "/* @anchor:file:start */",
1820
+ "",
1821
+ $dependencies,
1822
+ "",
1823
+ `const moduleName = "${moduleName}"`,
1824
+ `const method = "${method}"`,
1825
+ `const pathname = "${pathname}"`,
1826
+ "",
1827
+ $comment || void 0,
1828
+ `export ${$operationDeclaration} {`,
1829
+ ` const req = request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>("${pathname}")`,
1830
+ " .option('module', { name: moduleName, pathname, method })",
1831
+ "",
1832
+ $mediaType || void 0,
1833
+ " /* @anchor:query:start */",
1834
+ $queryParameters ? indent(2, $queryParameters) : void 0,
1835
+ " /* @anchor:query:end */",
1836
+ "",
1837
+ " /* @anchor:headers:start */",
1838
+ $headerParameters ? indent(2, $headerParameters) : void 0,
1839
+ " /* @anchor:headers:end */",
1840
+ "",
1841
+ " /* @anchor:path-parameters:start */",
1842
+ $pathParameters ? indent(2, $pathParameters) : void 0,
1843
+ " /* @anchor:path-parameters:end */",
1844
+ "",
1845
+ " /* @anchor:body:start */",
1846
+ $requestBody ? indent(2, $requestBody) : void 0,
1847
+ " /* @anchor:body:end */",
1848
+ "",
1849
+ " /* @anchor:operation-return */",
1850
+ ` return req as ReturnType<typeof ${operationId}<STATUS${$operationDeclaration.includes("CONTENT_TYPE") ? ", CONTENT_TYPE" : ""}>>`,
1851
+ "}",
1852
+ "",
1853
+ `${operationId}.pathname = pathname`,
1854
+ `${operationId}.method = method`,
1855
+ "/* @anchor:file:end */"
1856
+ ].filter(R17.isNotNil).join("\n");
1857
+ }
1858
+ renderDependencies() {
1859
+ const declarationFilepath = this.options.getOperationDefinitionDeclarationFilepath(this.operationDefinition);
1860
+ const requestFilepath = this.options.getRequestFilepath();
1861
+ return [
1862
+ 'import { Keq } from "keq"',
1863
+ `import { request } from "${requestFilepath}"`,
1864
+ `import type { ${this.typeName("Operation")}, ${this.typeName("ResponseBodies")}, ${this.typeName("RequestParameters")} } from "${declarationFilepath}"`,
1865
+ `export type { ${this.typeName("RequestQuery")}, ${this.typeName("RequestHeaders")}, ${this.typeName("RequestBodies")} } from "${declarationFilepath}"`
1866
+ ].map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
1867
+ }
1868
+ renderOperationDeclaration() {
1869
+ const { operationId } = this.operationDefinition;
1870
+ const mediaTypes = this.helper.getRequestMediaTypes();
1871
+ if (mediaTypes.length === 0) {
1872
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1873
+ } else if (mediaTypes.length === 1) {
1874
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1875
+ } else if (mediaTypes.length > 1) {
1876
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${this.typeName("RequestParameters")}["content-type"]>(args?: Extract<${this.typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1542
1877
  }
1543
- return `${HeaderComment}${$warns}${$dependencies}${this.content}`;
1878
+ throw new Exception(this.operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1544
1879
  }
1545
1880
  };
1546
1881
 
1547
- // src/tasks/utils/json-schema.ts
1548
- var R13 = __toESM(require("ramda"), 1);
1549
- var import_jsonpath_plus5 = require("jsonpath-plus");
1550
-
1551
- // src/tasks/compile/utils/compile-schema-definition.ts
1552
- function genSchemaDefinitionFilepath(schemaDefinition) {
1553
- const filename = `${schemaDefinition.name}.schema.ts`;
1554
- return [
1555
- ".",
1556
- schemaDefinition.module.name,
1557
- "components",
1558
- "schemas",
1559
- filename
1560
- ].join("/");
1561
- }
1562
- function genEntrypointFilepath(moduleName) {
1563
- return [
1564
- ".",
1565
- moduleName,
1566
- "components",
1567
- "schemas",
1568
- "index.ts"
1569
- ].join("/");
1570
- }
1571
- var isArtifactCompiledBy = function(schemaDefinition) {
1572
- return (artifact) => artifact.id === genSchemaDefinitionFilepath(schemaDefinition);
1573
- };
1574
- async function compileSchemaDefinition(options) {
1575
- const { task, compiler, schemaDefinitions } = options;
1576
- const artifacts = await Promise.all(
1577
- schemaDefinitions.map(async (schemaDefinition) => {
1578
- const content = await jsonSchemaRenderer(schemaDefinition);
1579
- const filepath = genSchemaDefinitionFilepath(schemaDefinition);
1580
- const artifact = new Artifact({
1581
- id: filepath,
1582
- filepath,
1583
- content,
1584
- extensionName: ".schema.ts"
1585
- });
1586
- return await compiler.hooks.afterCompileSchema.promise(artifact, schemaDefinition, task);
1587
- })
1588
- );
1589
- for (const schemaDefinition of schemaDefinitions) {
1590
- const artifact = artifacts.find(isArtifactCompiledBy(schemaDefinition));
1591
- if (!artifact) continue;
1592
- const dependentSchemaDefinitions = schemaDefinition.getDependencies();
1593
- for (const dependentSchemaDefinition of dependentSchemaDefinitions) {
1594
- const dependentArtifact = artifacts.find(isArtifactCompiledBy(dependentSchemaDefinition));
1595
- if (!dependentArtifact) {
1596
- artifact.addWarn(`Cannot find dependent $ref: ${dependentSchemaDefinition.id}`);
1597
- continue;
1598
- }
1599
- artifact.addDependence(dependentArtifact, [dependentSchemaDefinition.name]);
1600
- }
1882
+ // src/transformers/operation-definition/nestjs-method.renderer.ts
1883
+ var R18 = __toESM(require("ramda"), 1);
1884
+ var OperationDefinitionNestjsMethodRenderer = class {
1885
+ constructor(operationDefinition, options) {
1886
+ this.operationDefinition = operationDefinition;
1887
+ this.options = options;
1888
+ this.typeName = typeNameFactory(operationDefinition);
1889
+ this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1890
+ }
1891
+ helper;
1892
+ typeName;
1893
+ render() {
1894
+ const pathname = this.operationDefinition.pathname;
1895
+ const $comment = new CommentRenderer2(this.operationDefinition).render();
1896
+ const $method = this.operationDefinition.method.toLowerCase();
1897
+ const $mediaType = this.helper.renderMediaType();
1898
+ const $operationDeclaration = this.renderOperationDeclaration(this.operationDefinition);
1899
+ const $queryParameters = this.helper.renderRequestQuery();
1900
+ const $headerParameters = this.helper.renderRequestHeaders();
1901
+ const $pathParameters = this.helper.renderRequestPathParameters();
1902
+ const $requestBody = this.helper.renderRequestBody();
1903
+ return [
1904
+ $comment,
1905
+ `${$operationDeclaration} {`,
1906
+ ` const req = this.request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>(${JSON.stringify(pathname)})`,
1907
+ " .option(",
1908
+ ' "module",',
1909
+ " {",
1910
+ ` name: ${JSON.stringify(this.operationDefinition.module.name)},`,
1911
+ ` pathname: ${JSON.stringify(pathname)},`,
1912
+ ` method: ${JSON.stringify($method)},`,
1913
+ " },",
1914
+ " )",
1915
+ "",
1916
+ $mediaType ? indent(2, $mediaType) : void 0,
1917
+ "",
1918
+ " /* @anchor:query:start */",
1919
+ $queryParameters ? indent(2, $queryParameters) : void 0,
1920
+ " /* @anchor:query:end */",
1921
+ "",
1922
+ " /* @anchor:headers:start */",
1923
+ $headerParameters ? indent(2, $headerParameters) : void 0,
1924
+ " /* @anchor:headers:end */",
1925
+ "",
1926
+ " /* @anchor:path-parameters:start */",
1927
+ $pathParameters ? indent(2, $pathParameters) : void 0,
1928
+ " /* @anchor:path-parameters:end */",
1929
+ "",
1930
+ " /* @anchor:body:start */",
1931
+ $requestBody ? indent(2, $requestBody) : void 0,
1932
+ " /* @anchor:body:end */",
1933
+ "",
1934
+ " return req",
1935
+ "}"
1936
+ ].filter(R18.isNotNil).join("\n");
1601
1937
  }
1602
- const schemaDefinitionsGroupByModuleName = R14.groupBy(
1603
- (schemaDefinition) => schemaDefinition.module.name,
1604
- schemaDefinitions
1605
- );
1606
- const entrypointArtifacts = Object.entries(schemaDefinitionsGroupByModuleName).map(([moduleName, schemaDefinitions2]) => {
1607
- const filepath = genEntrypointFilepath(moduleName);
1608
- const artifact = new Artifact({
1609
- id: filepath,
1610
- filepath,
1611
- content: [
1612
- "/* @anchor:file:start */",
1613
- "/* @anchor:file:end */"
1614
- ].join("\n")
1615
- });
1616
- for (const schemaDefinition of schemaDefinitions2 || []) {
1617
- const dependentArtifact = artifacts.find(isArtifactCompiledBy(schemaDefinition));
1618
- if (!dependentArtifact) {
1619
- artifact.addWarn(`Cannot find dependent $ref: ${schemaDefinition.id}`);
1620
- continue;
1621
- }
1622
- artifact.addDependence(dependentArtifact, [], { export: true });
1938
+ renderOperationDeclaration(operationDefinition) {
1939
+ const { operationId } = operationDefinition;
1940
+ const typeName = typeNameFactory(operationDefinition);
1941
+ const mediaTypes = this.helper.getRequestMediaTypes();
1942
+ if (mediaTypes.length === 0) {
1943
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1944
+ } else if (mediaTypes.length === 1) {
1945
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1946
+ } else if (mediaTypes.length > 1) {
1947
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${typeName("RequestParameters")}["content-type"]>(args?: Extract<${typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1623
1948
  }
1624
- return artifact;
1625
- });
1626
- return [...artifacts, ...entrypointArtifacts];
1627
- }
1949
+ throw new Exception(operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1950
+ }
1951
+ };
1628
1952
 
1629
- // src/tasks/compile/utils/compile-operation-definition.ts
1630
- var R18 = __toESM(require("ramda"), 1);
1953
+ // src/transformers/operation-definition/operation-definition.transformer.ts
1954
+ var OperationDefinitionTransformer = class {
1955
+ static toDeclaration(operationDefinition, options) {
1956
+ return new DeclarationRenderer2(operationDefinition, options).render();
1957
+ }
1958
+ static toMicroFunction(operationDefinition, options) {
1959
+ return new OperationDefinitionMicroFunctionRenderer(operationDefinition, options).render();
1960
+ }
1961
+ static toNestjsMethod(operationDefinition, options) {
1962
+ return new OperationDefinitionNestjsMethodRenderer(operationDefinition, options).render();
1963
+ }
1964
+ static toComment(operationDefinition) {
1965
+ return new CommentRenderer2(operationDefinition).render();
1966
+ }
1967
+ };
1631
1968
 
1632
- // src/renderer/operation-type/index.ts
1633
- var R15 = __toESM(require("ramda"), 1);
1969
+ // src/transformers/entrypoint/entrypoint.transformer.ts
1970
+ var path7 = __toESM(require("path"), 1);
1971
+ var EntrypointTransformer = class {
1972
+ static toTypescript(exports2, options) {
1973
+ const $exports = exports2.map((exportArtifact) => {
1974
+ const relativePath = path7.relative(
1975
+ options.dirpath,
1976
+ exportArtifact.filepath
1977
+ ).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, options.esm ? ".js" : "");
1978
+ return relativePath.startsWith(".") ? `export * from '${relativePath}'` : `export * from './${relativePath}'`;
1979
+ });
1980
+ return [
1981
+ "/* @anchor:file:start */",
1982
+ "",
1983
+ ...$exports,
1984
+ "",
1985
+ "/* @anchor:file:end */"
1986
+ ].join("\n");
1987
+ }
1988
+ };
1989
+
1990
+ // src/transformers/api-document/nestjs-client.renderer.ts
1991
+ var R19 = __toESM(require("ramda"), 1);
1634
1992
  var changeCase2 = __toESM(require("change-case"), 1);
1635
- function typeNameFactory(operationDefinition) {
1636
- const pascalCaseOperationId = changeCase2.pascalCase(operationDefinition.operationId);
1637
- return (name) => `${pascalCaseOperationId}${name}`;
1638
- }
1639
- function responseBodies(operation, alias = R15.identity, typeName) {
1640
- if (!operation.responses || R15.isEmpty(operation.responses)) {
1641
- return `export interface ${typeName("ResponseBodies")} {}`;
1642
- }
1643
- const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
1644
- if (!JsonSchemaUtils.isRef(response)) {
1645
- const $value = Object.values(response.content || {}).map((mediaTypeObject) => mediaTypeObject.schema).filter((schema) => !!schema).map((schema) => generateSchema(schema, alias)).join(" | ");
1646
- return indent(2, `${statusCode}: ${$value || "void"}`);
1647
- }
1648
- }).join("\n");
1649
- return [
1650
- `export interface ${typeName("ResponseBodies")} {`,
1651
- $responses,
1652
- "}"
1653
- ].join("\n");
1654
- }
1655
- function requestBodies(operation, alias = R15.identity, typeName) {
1656
- let $requestBodies = `export interface ${typeName("RequestBodies")} {}`;
1657
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1658
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1659
- if (!schema) return `${JSON.stringify(mediaType)}: unknown`;
1660
- return `${JSON.stringify(mediaType)}: ${generateSchema(schema, alias)}`;
1661
- }).map((pair) => indent(2, pair));
1662
- $requestBodies = [
1663
- `export interface ${typeName("RequestBodies")} {`,
1664
- ...$mediaTypes,
1665
- "}"
1993
+ var NestjsClientRenderer = class {
1994
+ constructor(document, options) {
1995
+ this.document = document;
1996
+ this.options = options;
1997
+ }
1998
+ renderDependencies() {
1999
+ const $operations = this.document.operations.map((operationDefinition) => {
2000
+ const filepath = this.options.getOperationDefinitionDeclarationFilepath(operationDefinition);
2001
+ const typeName = typeNameFactory(operationDefinition);
2002
+ return `import type { ${typeName("Operation")}, ${typeName("ResponseBodies")}, ${typeName("RequestParameters")} } from "${filepath}"`;
2003
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
2004
+ return [
2005
+ 'import { Injectable, Logger } from "@nestjs/common"',
2006
+ 'import { Keq, KeqRequest } from "keq"',
2007
+ ...$operations
1666
2008
  ].join("\n");
1667
2009
  }
1668
- return $requestBodies;
1669
- }
1670
- function parameterBodies(operationDefinition, alias = R15.identity, typeName) {
1671
- const { operation } = operationDefinition;
1672
- let parameterBodies2 = "";
1673
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1674
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schemaOrRef]) => {
1675
- if (!schemaOrRef) return `${JSON.stringify(mediaType)}: unknown`;
1676
- const schema = JsonSchemaUtils.isRef(schemaOrRef) ? OpenapiUtils.dereferenceDeep(schemaOrRef.$ref, operationDefinition.document.specification) : schemaOrRef;
1677
- if (schema.type === "object" || schema.properties) {
1678
- return `${JSON.stringify(mediaType)}: ${generateSchema(schemaOrRef, alias)} & { [key: string]: any }`;
1679
- }
1680
- return `${JSON.stringify(mediaType)}: { [key: string]: any }`;
1681
- }).map((pair) => indent(2, pair));
1682
- parameterBodies2 = [
1683
- `interface ${typeName("ParameterBodies")} {`,
1684
- ...$mediaTypes,
2010
+ render() {
2011
+ const moduleName = changeCase2.pascalCase(this.document.module.name);
2012
+ const $dependencies = this.renderDependencies();
2013
+ const $operations = this.document.operations.map((operation) => OperationDefinitionTransformer.toNestjsMethod(operation, {
2014
+ esm: this.options.esm,
2015
+ qs: this.options.qs
2016
+ })).join("\n\n");
2017
+ return [
2018
+ "/* @anchor:file:start */",
2019
+ "",
2020
+ $dependencies,
2021
+ "",
2022
+ "@Injectable()",
2023
+ `export class ${moduleName}Client {`,
2024
+ ` private readonly logger = new Logger(${moduleName}Client.name)`,
2025
+ "",
2026
+ " constructor(",
2027
+ " // @anchor:client-constructor-parameters:start",
2028
+ " private readonly request: KeqRequest,",
2029
+ " // @anchor:client-constructor-parameters:end",
2030
+ " ) {}",
2031
+ "",
2032
+ indent(2, $operations),
1685
2033
  "}",
1686
- ""
1687
- ].join("\n");
2034
+ "",
2035
+ "/* @anchor:file:end */"
2036
+ ].filter(R19.isNotNil).join("\n");
1688
2037
  }
1689
- return parameterBodies2;
1690
- }
1691
- function requestParameters(operation, alias = R15.identity, typeName) {
1692
- const mediaTypes = operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody) ? Object.keys(operation.requestBody.content || {}) : [];
1693
- const base = `${typeName("RequestQuery")} & ${typeName("RouteParameters")} & ${typeName("RequestHeaders")}`;
1694
- if (mediaTypes.length === 1) {
1695
- return `export type ${typeName("RequestParameters")} = ${base} & ${typeName("RequestBodies")}[${JSON.stringify(mediaTypes[0])}]`;
2038
+ };
2039
+
2040
+ // src/transformers/api-document/nestjs-module.renderer.ts
2041
+ var changeCase3 = __toESM(require("change-case"), 1);
2042
+ var NestjsModuleRenderer = class {
2043
+ constructor(document, options) {
2044
+ this.document = document;
2045
+ this.options = options;
1696
2046
  }
1697
- if (mediaTypes.length > 1) {
1698
- const unions = mediaTypes.map((mediaType) => `(${base} & ${typeName("RequestBodies")}[${JSON.stringify(mediaType)}] & { "content-type": ${JSON.stringify(mediaType)} })`).join("\n| ");
1699
- return `export type ${typeName("RequestParameters")} = ${unions}`;
2047
+ render() {
2048
+ const moduleName = changeCase3.pascalCase(this.document.module.name);
2049
+ const clientFilepath = this.options.getNestjsClientFilepath(this.document).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, this.options.esm ? ".js" : "");
2050
+ return [
2051
+ "/* @anchor:file:start */",
2052
+ 'import { Module, Inject, ConfigurableModuleBuilder, Global } from "@nestjs/common"',
2053
+ 'import { KeqRequest } from "keq"',
2054
+ 'import { KeqModuleOptions } from "@keq-request/nestjs"',
2055
+ `import { ${moduleName}Client } from "${clientFilepath}"`,
2056
+ "",
2057
+ "",
2058
+ "const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = new ConfigurableModuleBuilder<KeqModuleOptions>().build()",
2059
+ "",
2060
+ "@Global()",
2061
+ "@Module({",
2062
+ " imports: [],",
2063
+ " controllers: [],",
2064
+ ` providers: [${moduleName}Client],`,
2065
+ ` exports: [${moduleName}Client],`,
2066
+ "})",
2067
+ `export class ${moduleName}Module extends ConfigurableModuleClass {`,
2068
+ "",
2069
+ " constructor(",
2070
+ " @Inject(MODULE_OPTIONS_TOKEN) private readonly options: KeqModuleOptions,",
2071
+ " private readonly request: KeqRequest,",
2072
+ " ) {",
2073
+ " super()",
2074
+ " }",
2075
+ "",
2076
+ " onModuleInit() {",
2077
+ " if (this.options.middlewares) {",
2078
+ " for (const middleware of this.options.middlewares) {",
2079
+ " this.request.use(middleware)",
2080
+ " }",
2081
+ " }",
2082
+ " }",
2083
+ "}",
2084
+ "",
2085
+ "/* @anchor:file:end */"
2086
+ ].join("\n");
1700
2087
  }
1701
- return `export type ${typeName("RequestParameters")} = ${base}`;
1702
- }
1703
- async function operationTypeRenderer(operationDefinition, alias = R15.identity) {
1704
- const { operation } = operationDefinition;
1705
- if (!operation.responses) return "";
1706
- const typeName = typeNameFactory(operationDefinition);
1707
- const $responseBodies = responseBodies(operation, alias, typeName);
1708
- const $requestBodies = requestBodies(operation, alias, typeName);
1709
- const $parameterBodies = parameterBodies(operationDefinition, alias, typeName);
1710
- const $requestParameters = requestParameters(operation, alias, typeName);
1711
- return [
1712
- "/* @anchor:file:start */",
1713
- "",
1714
- $responseBodies,
1715
- "",
1716
- $requestBodies,
1717
- "",
1718
- generateParameters(`${typeName("RequestQuery")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "query") || [], alias),
1719
- "",
1720
- generateParameters(`${typeName("RouteParameters")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "path") || [], alias),
1721
- "",
1722
- generateParameters(`${typeName("RequestHeaders")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "header") || [], alias),
1723
- "",
1724
- $parameterBodies || void 0,
1725
- $requestParameters,
1726
- "",
1727
- `export interface Operation<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${$parameterBodies ? `keyof ${typeName("ParameterBodies")}` : "string"} > extends KeqOperation {`,
1728
- ` requestParams: ${typeName("RouteParameters")} & { [key: string]: KeqPathParameterInit }`,
1729
- ` requestQuery: ${typeName("RequestQuery")} & { [key: string]: KeqQueryInit }`,
1730
- ` requestHeaders: ${typeName("RequestHeaders")} & { [key: string]: string | number }`,
1731
- ` requestBody: ${$parameterBodies ? `${typeName("ParameterBodies")}[CONTENT_TYPE] | ` : "object | "}BodyInit`,
1732
- ` responseBody: ${typeName("ResponseBodies")}[STATUS]`,
1733
- "}",
1734
- "",
1735
- "/* @anchor:file:end */"
1736
- ].filter(R15.isNotNil).join("\n");
1737
- }
1738
- function generateParameters(name, parameters, alias) {
1739
- if (parameters.length === 0) {
1740
- return `export type ${name} = {}`;
1741
- }
1742
- const $parameters = parameters.map((parameter) => {
1743
- const parameterName = `"${parameter.name}"`;
1744
- const $key = parameter.required ? parameterName : `${parameterName}?`;
1745
- const $value = generateSchema(parameter.schema || { type: "any" }, alias);
1746
- return indent(2, `${$key}: ${$value}`);
1747
- }).join("\n");
1748
- return [
1749
- `export type ${name} = {`,
1750
- $parameters,
1751
- "}"
1752
- ].filter(Boolean).join("\n");
1753
- }
1754
-
1755
- // src/renderer/operation-request/index.ts
1756
- var R17 = __toESM(require("ramda"), 1);
2088
+ };
1757
2089
 
1758
- // src/renderer/operation-request/request-body.ts
1759
- var R16 = __toESM(require("ramda"), 1);
2090
+ // src/transformers/api-document/api-document.transformer.ts
2091
+ var ApiDocumentTransformer = class {
2092
+ static toNestjsModule(document, options) {
2093
+ return new NestjsModuleRenderer(document, options).render();
2094
+ }
2095
+ static toNestjsClient(document, options) {
2096
+ return new NestjsClientRenderer(document, options).render();
2097
+ }
2098
+ };
1760
2099
 
1761
- // src/renderer/operation-request/error-to-comment.ts
1762
- function errorToComment(err, mediaType) {
1763
- const $err = String(err).split("\n").map(((line) => ` * ${line}`)).join("\n");
1764
- return [
1765
- "/**",
1766
- ` * Unable to dereference schema for media type ${mediaType}`,
1767
- $err,
1768
- " */"
1769
- ].join("\n");
1770
- }
2100
+ // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2101
+ var R20 = __toESM(require("ramda"), 1);
2102
+ var path8 = __toESM(require("path"), 1);
2103
+ var changeCase4 = __toESM(require("change-case"), 1);
2104
+
2105
+ // src/plugins/generate-declaration/constants/metadata-storage.ts
2106
+ var MetadataStorage2 = /* @__PURE__ */ new WeakMap();
2107
+
2108
+ // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2109
+ var SCHEMA_GENERATOR = "schemaGenerator";
2110
+ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2111
+ async compile(compiler, task) {
2112
+ const context = compiler.context;
2113
+ const metadata = MetadataStorage2.get(compiler);
2114
+ const rc = context.rc;
2115
+ const documents = context.documents;
2116
+ const schemaDefinitions = documents.flatMap((document) => document.schemas);
2117
+ const artifactMap = new Map(
2118
+ await Promise.all(
2119
+ schemaDefinitions.map(async (schemaDefinition) => [
2120
+ schemaDefinition,
2121
+ await metadata.hooks.afterSchemaDeclarationArtifactGenerated.promise(
2122
+ this.generateSchemaDefinitionsArtifact(schemaDefinition, rc),
2123
+ schemaDefinition,
2124
+ task
2125
+ )
2126
+ ])
2127
+ )
2128
+ );
2129
+ const entrypoints = R20.collectBy(
2130
+ (schemaDefinition) => schemaDefinition.module.name,
2131
+ schemaDefinitions
2132
+ ).map((schemaDefinitions2) => [
2133
+ schemaDefinitions2[0].module,
2134
+ schemaDefinitions2.map((schemaDefinition) => artifactMap.get(schemaDefinition)).filter((artifact) => Boolean(artifact))
2135
+ ]).map(([moduleDefinition, artifacts]) => this.generateEntrypointArtifact(
2136
+ moduleDefinition,
2137
+ artifacts,
2138
+ rc
2139
+ ));
2140
+ return [...artifactMap.values(), ...entrypoints];
2141
+ }
2142
+ generateSchemaDefinitionsArtifact(schemaDefinition, rc) {
2143
+ const filepath = _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(schemaDefinition, rc.fileNamingStyle);
2144
+ const dirpath = path8.dirname(filepath);
2145
+ const artifact = new Artifact({
2146
+ id: _SchemaDeclarationGenerator.getSchemaDefinitionArtifactId(schemaDefinition),
2147
+ filepath,
2148
+ content: SchemaDefinitionTransformer.toDeclaration(
2149
+ schemaDefinition,
2150
+ {
2151
+ esm: rc.esm,
2152
+ getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2153
+ const relativePath = path8.relative(
2154
+ dirpath,
2155
+ _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2156
+ );
2157
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2158
+ }
2159
+ }
2160
+ ),
2161
+ extensionName: ".schema.ts"
2162
+ });
2163
+ return artifact;
2164
+ }
2165
+ generateEntrypointArtifact(moduleDefinition, exports2, rc) {
2166
+ const filepath = _SchemaDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2167
+ const dirpath = path8.dirname(filepath);
2168
+ const artifact = new Artifact({
2169
+ id: _SchemaDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2170
+ filepath,
2171
+ content: EntrypointTransformer.toTypescript(exports2, { dirpath })
2172
+ });
2173
+ return artifact;
2174
+ }
2175
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2176
+ return [
2177
+ ".",
2178
+ changeCase4[fileNamingStyle](moduleDefinition.name),
2179
+ "types",
2180
+ "components",
2181
+ "schemas",
2182
+ "index.ts"
2183
+ ].join("/");
2184
+ }
2185
+ static getEntrypointArtifactId(moduleDefinition) {
2186
+ return `${moduleDefinition.address}/components/schemas/entrypoint?generator=${SCHEMA_GENERATOR}`;
2187
+ }
2188
+ static getSchemaDefinitionArtifactFilepath(schemaDefinition, fileNamingStyle) {
2189
+ const filename = `${changeCase4[fileNamingStyle](schemaDefinition.name)}.schema.ts`;
2190
+ return [
2191
+ ".",
2192
+ changeCase4[fileNamingStyle](schemaDefinition.module.name),
2193
+ "types",
2194
+ "components",
2195
+ "schemas",
2196
+ filename
2197
+ ].join("/");
2198
+ }
2199
+ static getSchemaDefinitionArtifactId(schemaDefinition) {
2200
+ return `${schemaDefinition.id}?generator=${SCHEMA_GENERATOR}`;
2201
+ }
2202
+ };
1771
2203
 
1772
- // src/renderer/operation-request/request-body.ts
1773
- function requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition) {
1774
- try {
1775
- const $propertyName = JSON.stringify(propertyName);
1776
- const schema = JsonSchemaUtils.isRef(propertySchema) ? OpenapiUtils.dereferenceDeep(propertySchema.$ref, operationDefinition.document.specification) : propertySchema;
1777
- if (schema.type === "string" && schema.format === "binary" || schema.contentMediaType === "application/octet-stream") {
1778
- return `if (args && ${$propertyName} in args && args[${$propertyName}]) req.attach(${$propertyName}, args[${$propertyName}])`;
1779
- } else if (schema.type === "string" || schema.type === "array" && schema.items && schema.items.type === "string") {
1780
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, args[${$propertyName}])`;
1781
- } else if (schema.type === "number" || schema.type === "integer") {
1782
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]))`;
1783
- }
1784
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]) /* type is non-string in schema; triggers type coercion here */)`;
1785
- } catch (err) {
1786
- return errorToComment(err, mediaType);
2204
+ // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
2205
+ var OPERATION_GENERATOR = "operationDeclarationGenerator";
2206
+ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2207
+ async compile(compiler, task) {
2208
+ const context = compiler.context;
2209
+ const metadata = MetadataStorage2.get(compiler);
2210
+ const rc = context.rc;
2211
+ const documents = context.documents;
2212
+ const operationDefinitions = documents.flatMap((document) => document.operations);
2213
+ const artifactMap = new Map(
2214
+ await Promise.all(
2215
+ operationDefinitions.map(async (operationDefinition) => [
2216
+ operationDefinition,
2217
+ await metadata.hooks.afterOperationDeclarationArtifactGenerated.promise(
2218
+ this.generateOperationDefinitionArtifact(operationDefinition, rc),
2219
+ operationDefinition,
2220
+ task
2221
+ )
2222
+ ])
2223
+ )
2224
+ );
2225
+ return Array.from(artifactMap.values());
1787
2226
  }
1788
- }
1789
- function requestBodyPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition) {
1790
- if (mediaType === "application/json") {
1791
- const $propertyName = JSON.stringify(propertyName);
1792
- return `if (args && ${$propertyName} in args) req.send({ ${$propertyName}: args[${$propertyName}] })`;
1793
- } else if (mediaType === "multipart/form-data") {
1794
- return requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition);
1795
- } else {
1796
- throw new Error(`Unsupported media type: ${mediaType}`);
2227
+ generateOperationDefinitionArtifact(operationDefinition, rc) {
2228
+ const filepath = _OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2229
+ const dirpath = path9.dirname(filepath);
2230
+ const artifact = new Artifact({
2231
+ id: _OperationDeclarationGenerator.getOperationDefinitionArtifactId(operationDefinition),
2232
+ filepath,
2233
+ content: OperationDefinitionTransformer.toDeclaration(
2234
+ operationDefinition,
2235
+ {
2236
+ esm: rc.esm,
2237
+ getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2238
+ const relativePath = path9.relative(
2239
+ dirpath,
2240
+ SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2241
+ );
2242
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2243
+ }
2244
+ }
2245
+ ),
2246
+ extensionName: ".type.ts"
2247
+ });
2248
+ return artifact;
1797
2249
  }
1798
- }
1799
- function requestBodyRenderer(operationDefinition, typeName) {
1800
- const { operation } = operationDefinition;
1801
- const requestBodyContent = operation.requestBody?.content || {};
1802
- const $requestBody = Object.entries(requestBodyContent).map(([mediaType, mediaTypeObject]) => {
1803
- if (!mediaTypeObject.schema) return;
1804
- try {
1805
- const schema = JsonSchemaUtils.isRef(mediaTypeObject.schema) ? OpenapiUtils.dereferenceDeep(mediaTypeObject.schema.$ref, operationDefinition.document.specification) : mediaTypeObject.schema;
1806
- if (schema.type !== "object") return;
1807
- const properties = schema.properties || {};
1808
- return Object.entries(properties).map(([propertyName, propertySchema]) => {
1809
- return indent(
1810
- 2,
1811
- requestBodyPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition)
1812
- );
1813
- }).join("\n");
1814
- } catch (err) {
1815
- return indent(2, errorToComment(err, mediaType));
2250
+ generateEntrypointArtifact(moduleDefinition, exports2, rc) {
2251
+ const filepath = _OperationDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2252
+ const dirpath = path9.dirname(filepath);
2253
+ const artifact = new Artifact({
2254
+ id: _OperationDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2255
+ filepath,
2256
+ content: EntrypointTransformer.toTypescript(exports2, { dirpath })
2257
+ });
2258
+ return artifact;
2259
+ }
2260
+ static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
2261
+ const filename = `${changeCase5[fileNamingStyle](operationDefinition.operationId)}.type.ts`;
2262
+ const filepath = [
2263
+ ".",
2264
+ changeCase5[fileNamingStyle](operationDefinition.module.name),
2265
+ "types",
2266
+ "operations",
2267
+ filename
2268
+ ].join("/");
2269
+ return filepath;
2270
+ }
2271
+ static getOperationDefinitionArtifactId(operationDefinition) {
2272
+ return `${operationDefinition.id}?generator=${OPERATION_GENERATOR}`;
2273
+ }
2274
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2275
+ return [
2276
+ ".",
2277
+ changeCase5[fileNamingStyle](moduleDefinition.name),
2278
+ "types",
2279
+ "operations",
2280
+ "index.ts"
2281
+ ].join("/");
2282
+ }
2283
+ static getEntrypointArtifactId(moduleDefinition) {
2284
+ return `${moduleDefinition.address}/paths/entrypoint?generator=${OPERATION_GENERATOR}`;
2285
+ }
2286
+ };
2287
+
2288
+ // src/plugins/generate-declaration/generate-declaration.plugin.ts
2289
+ var DECLARATION_GENERATOR = "declarationGenerator";
2290
+ var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
2291
+ name = DECLARATION_GENERATOR;
2292
+ operationGenerator = new OperationDeclarationGenerator();
2293
+ schemaGenerator = new SchemaDeclarationGenerator();
2294
+ constructor() {
2295
+ }
2296
+ apply(compiler) {
2297
+ _GenerateDeclarationPlugin.register(compiler);
2298
+ compiler.hooks.compile.tapPromise(_GenerateDeclarationPlugin.name, async (task) => {
2299
+ compiler.context.artifacts?.push(
2300
+ ...await this.schemaGenerator.compile(compiler, task),
2301
+ ...await this.operationGenerator.compile(compiler, task)
2302
+ );
2303
+ });
2304
+ }
2305
+ static register(compiler) {
2306
+ if (!MetadataStorage2.has(compiler)) {
2307
+ MetadataStorage2.set(compiler, {
2308
+ hooks: {
2309
+ afterEntrypointArtifactGenerated: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "task"]),
2310
+ afterSchemaDeclarationArtifactGenerated: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "schemaDefinition", "task"]),
2311
+ afterOperationDeclarationArtifactGenerated: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "operationDefinition", "task"])
2312
+ }
2313
+ });
1816
2314
  }
1817
- }).filter(R16.isNotNil).join("\n");
1818
- return $requestBody;
1819
- }
2315
+ return MetadataStorage2.get(compiler);
2316
+ }
2317
+ static of(compiler) {
2318
+ return this.register(compiler);
2319
+ }
2320
+ };
1820
2321
 
1821
- // src/renderer/operation-request/index.ts
1822
- function requestHeadersRenderer(operationDefinition, typeName) {
1823
- const { operation } = operationDefinition;
1824
- const $headers = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "header").map((p) => ` if (args && ${JSON.stringify(p.name)} in args) req.header(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).concat("").join("\n");
1825
- return $headers;
1826
- }
1827
- function requestQueryRenderer(operationDefinition, qs, typeName) {
1828
- const { operation } = operationDefinition;
1829
- const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1830
- const option = qs(p);
1831
- const $option = !option || R17.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1832
- return ` if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1833
- }).concat("").join("\n");
1834
- return $query;
1835
- }
1836
- function requestPathParametersRenderer(operationDefinition, typeName) {
1837
- const { operation } = operationDefinition;
1838
- const $pathParameters = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "path").map((p) => ` if (args && ${JSON.stringify(p.name)} in args) req.params(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).concat("").join("\n");
1839
- return $pathParameters;
1840
- }
1841
- function getRequestMediaTypes(operationDefinition) {
1842
- const { operation } = operationDefinition;
1843
- const requestBodyContent = operation.requestBody?.content || {};
1844
- return Object.keys(requestBodyContent);
1845
- }
1846
- function mediaTypeRenderer(operationDefinition) {
1847
- const mediaTypes = getRequestMediaTypes(operationDefinition);
1848
- if (mediaTypes.length === 1 && !mediaTypes[0].endsWith("/*")) {
1849
- return ` req.type("${mediaTypes[0]}")
1850
- `;
1851
- } else if (mediaTypes.some((mediaType) => mediaType === "*/*")) {
1852
- } else if (mediaTypes.some((mediaType) => mediaType.endsWith("/*"))) {
1853
- return ' if(args?.["content-type"]) req.type(args["content-type"])\n';
1854
- } else if (mediaTypes.length > 1) {
1855
- return ' if(args?.["content-type"]) req.type(args["content-type"])\n';
2322
+ // src/plugins/generate-micro-function/generators/request/request.generator.ts
2323
+ var MICRO_FUNCTION_REQUEST_GENERATOR = "microFunctionRequestGenerator";
2324
+ var RequestGenerator = class _RequestGenerator {
2325
+ generateRequestArtifact() {
2326
+ const content = [
2327
+ "/* @anchor:file:start */",
2328
+ "",
2329
+ 'import { KeqRequest } from "keq"',
2330
+ "",
2331
+ "/* @anchor:request-declaration */",
2332
+ "export const request = new KeqRequest()",
2333
+ "",
2334
+ "/* @anchor:file:end */"
2335
+ ].join("\n");
2336
+ return new Artifact({
2337
+ id: _RequestGenerator.getRequestArtifactId(),
2338
+ filepath: _RequestGenerator.getRequestArtifactFilepath(),
2339
+ content
2340
+ });
1856
2341
  }
1857
- return "";
1858
- }
1859
- function operationDeclarationRenderer(operationDefinition, typeName) {
1860
- const { operationId } = operationDefinition;
1861
- const mediaTypes = getRequestMediaTypes(operationDefinition);
1862
- if (mediaTypes.length === 0) {
1863
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${typeName("RequestParameters")}): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1864
- } else if (mediaTypes.length === 1) {
1865
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${typeName("RequestParameters")}): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1866
- } else if (mediaTypes.length > 1) {
1867
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${typeName("RequestParameters")}["content-type"]>(args?: Extract<${typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1868
- }
1869
- throw new Error("[operationDeclarationRenderer] Unreachable");
1870
- }
1871
- async function operationRequestRenderer(operationDefinition, options) {
1872
- const { operation, operationId, method, pathname } = operationDefinition;
1873
- const { qs } = options;
1874
- if (!operation.responses) return "";
1875
- const typeName = typeNameFactory(operationDefinition);
1876
- const moduleName = operationDefinition.module.name;
1877
- const $method = method.toLowerCase();
1878
- const $queryParameters = requestQueryRenderer(operationDefinition, qs, typeName);
1879
- const $headerParameters = requestHeadersRenderer(operationDefinition, typeName);
1880
- const $pathParameters = requestPathParametersRenderer(operationDefinition, typeName);
1881
- const $mediaType = mediaTypeRenderer(operationDefinition);
1882
- const $requestBody = requestBodyRenderer(operationDefinition, typeName);
1883
- const $operationDeclaration = operationDeclarationRenderer(operationDefinition, typeName);
1884
- return [
1885
- "/* @anchor:file:start */",
1886
- "",
1887
- `const moduleName = "${moduleName}"`,
1888
- `const method = "${method}"`,
1889
- `const pathname = "${pathname}"`,
1890
- "",
1891
- "/* @anchor:operation-declaration */",
1892
- `export ${$operationDeclaration} {`,
1893
- ` const req = request.${$method}<${typeName("ResponseBodies")}[STATUS]>("${pathname}")`,
1894
- " .option('module', { name: moduleName, pathname, method })",
1895
- "",
1896
- $mediaType || void 0,
1897
- " /* @anchor:query:start */",
1898
- $queryParameters || void 0,
1899
- " /* @anchor:query:end */",
1900
- "",
1901
- " /* @anchor:headers:start */",
1902
- $headerParameters || void 0,
1903
- " /* @anchor:headers:end */",
1904
- "",
1905
- " /* @anchor:path-parameters:start */",
1906
- $pathParameters || void 0,
1907
- " /* @anchor:path-parameters:end */",
1908
- "",
1909
- " /* @anchor:body:start */",
1910
- $requestBody || void 0,
1911
- " /* @anchor:body:end */",
1912
- "",
1913
- " /* @anchor:operation-return */",
1914
- ` return req as ReturnType<typeof ${operationId}<STATUS${$operationDeclaration.includes("CONTENT_TYPE") ? ", CONTENT_TYPE" : ""}>>`,
1915
- "}",
1916
- "",
1917
- `${operationId}.pathname = pathname`,
1918
- `${operationId}.method = method`,
1919
- "/* @anchor:file:end */"
1920
- ].filter(R17.isNotNil).join("\n");
1921
- }
2342
+ // eslint-disable-next-line @typescript-eslint/require-await
2343
+ async compile(compiler, task) {
2344
+ return [
2345
+ this.generateRequestArtifact()
2346
+ ];
2347
+ }
2348
+ static getRequestArtifactFilepath() {
2349
+ return "./request.ts";
2350
+ }
2351
+ static getRequestArtifactId() {
2352
+ return `request?generator=${MICRO_FUNCTION_REQUEST_GENERATOR}`;
2353
+ }
2354
+ };
1922
2355
 
1923
- // src/tasks/compile/utils/compile-operation-definition.ts
1924
- function genOperationTypeFilepath(operationDefinition) {
1925
- const filename = `${operationDefinition.operationId}.type.ts`;
1926
- return [
1927
- ".",
1928
- operationDefinition.module.name,
1929
- "types",
1930
- filename
1931
- ].join("/");
1932
- }
1933
- function genOperationRequestFilepath(operationDefinition) {
1934
- const filename = `${operationDefinition.operationId}.request.ts`;
1935
- return [
1936
- ".",
1937
- operationDefinition.module.name,
1938
- "operations",
1939
- filename
1940
- ].join("/");
1941
- }
1942
- function genEntrypointFilepath2(moduleName) {
1943
- return [
1944
- ".",
1945
- moduleName,
1946
- "operations",
1947
- "index.ts"
1948
- ].join("/");
1949
- }
1950
- async function compileOperationDefinition(options) {
1951
- const { compiler, task, rc, requestArtifact, schemaArtifacts, operationDefinitions } = options;
1952
- const alias = (name) => `${name}Schema`;
1953
- const qs = (parameter) => {
1954
- if (typeof rc.qs === "function") {
1955
- return rc.qs(parameter);
1956
- } else if (typeof rc.qs === "object") {
1957
- return rc.qs;
1958
- }
1959
- const style = parameter.style || "form";
1960
- const explode = parameter.explode ?? true;
1961
- if (style === "deepObject") {
1962
- return { arrayFormat: "brackets" };
1963
- } else if (explode) {
1964
- return { arrayFormat: "repeat" };
1965
- } else {
1966
- if (style === "form") {
1967
- return { arrayFormat: "comma" };
1968
- } else if (style === "spaceDelimited") {
1969
- return { arrayFormat: "space" };
1970
- } else if (style === "pipeDelimited") {
1971
- return { arrayFormat: "pipe" };
1972
- }
1973
- }
1974
- return {};
1975
- };
1976
- async function createTypeArtifact(operationDefinition) {
1977
- const content = await operationTypeRenderer(operationDefinition, alias);
1978
- const filepath = genOperationTypeFilepath(operationDefinition);
1979
- const typeArtifact = new Artifact({
1980
- id: filepath,
2356
+ // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
2357
+ var MICRO_FUNCTION_GENERATOR = "microFunctionGenerator";
2358
+ var MicroFunctionGenerator = class _MicroFunctionGenerator {
2359
+ async compile(compiler, task) {
2360
+ const metadata = MetadataStorage.get(compiler);
2361
+ const context = compiler.context;
2362
+ const rc = context.rc;
2363
+ const documents = context.documents;
2364
+ const operationDefinitions = documents.flatMap((document) => document.operations);
2365
+ const artifactMap = new Map(
2366
+ await Promise.all(
2367
+ operationDefinitions.map(async (operationDefinition) => [
2368
+ operationDefinition,
2369
+ await metadata.hooks.afterMicroFunctionArtifactGenerated.promise(
2370
+ this.generateOperationDefinitionArtifact(operationDefinition, rc),
2371
+ operationDefinition,
2372
+ task
2373
+ )
2374
+ ])
2375
+ )
2376
+ );
2377
+ const entrypoints = await Promise.all(
2378
+ R21.collectBy(
2379
+ (operationDefinition) => operationDefinition.module.name,
2380
+ operationDefinitions
2381
+ ).map((operationDefinitions2) => [
2382
+ operationDefinitions2[0].module,
2383
+ operationDefinitions2.map((operationDefinition) => artifactMap.get(operationDefinition)).filter((artifact) => Boolean(artifact))
2384
+ ]).map(async ([moduleDefinition, artifacts]) => await metadata.hooks.afterEntrypointArtifactGenerated.promise(
2385
+ this.generateEntrypointArtifact(
2386
+ moduleDefinition,
2387
+ artifacts,
2388
+ rc
2389
+ ),
2390
+ task
2391
+ ))
2392
+ );
2393
+ return [...entrypoints, ...artifactMap.values()];
2394
+ }
2395
+ generateOperationDefinitionArtifact(operationDefinition, rc) {
2396
+ const filepath = _MicroFunctionGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2397
+ const dirpath = path10.dirname(filepath);
2398
+ const artifact = new Artifact({
2399
+ id: _MicroFunctionGenerator.getOperationDefinitionArtifactId(operationDefinition),
1981
2400
  filepath,
1982
- content,
2401
+ content: OperationDefinitionTransformer.toMicroFunction(operationDefinition, {
2402
+ qs: rc.qs,
2403
+ esm: rc.esm,
2404
+ getOperationDefinitionDeclarationFilepath(operationDefinition2) {
2405
+ const relativePath = path10.relative(
2406
+ dirpath,
2407
+ OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition2, rc.fileNamingStyle)
2408
+ );
2409
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2410
+ },
2411
+ getRequestFilepath() {
2412
+ const relativePath = path10.relative(
2413
+ dirpath,
2414
+ RequestGenerator.getRequestArtifactFilepath()
2415
+ );
2416
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2417
+ }
2418
+ }),
1983
2419
  extensionName: ".type.ts"
1984
2420
  });
1985
- typeArtifact.addDependence("keq", ["KeqOperation", "KeqQueryInit", "KeqPathParameterInit"]);
1986
- const dependentSchemaDefinitions = operationDefinition.getDependencies();
1987
- for (const dependentSchemaDefinition of dependentSchemaDefinitions) {
1988
- const dependentArtifact = schemaArtifacts.find(isArtifactCompiledBy(dependentSchemaDefinition));
1989
- if (!dependentArtifact) {
1990
- typeArtifact.addWarn(`Cannot find dependent $ref: ${dependentSchemaDefinition.id}`);
1991
- continue;
1992
- }
1993
- typeArtifact.addDependence(dependentArtifact, [
1994
- new DependencyIdentifier(dependentSchemaDefinition.name, alias(dependentSchemaDefinition.name))
1995
- ]);
1996
- }
1997
- return await compiler.hooks.afterCompileOperationType.promise(typeArtifact, operationDefinition, task);
2421
+ return artifact;
1998
2422
  }
1999
- async function createRequestArtifact(operationDefinition, typeArtifact) {
2000
- const typeName = typeNameFactory(operationDefinition);
2001
- const content = await operationRequestRenderer(operationDefinition, { qs });
2002
- const filepath = genOperationRequestFilepath(operationDefinition);
2423
+ generateEntrypointArtifact(moduleDefinition, exports2, rc) {
2424
+ const filepath = _MicroFunctionGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2425
+ const dirpath = filepath.substring(0, filepath.lastIndexOf("/"));
2003
2426
  const artifact = new Artifact({
2004
- id: filepath,
2427
+ id: _MicroFunctionGenerator.getEntrypointArtifactId(moduleDefinition),
2005
2428
  filepath,
2006
- content,
2007
- extensionName: ".request.ts"
2429
+ content: EntrypointTransformer.toTypescript(exports2, { dirpath })
2008
2430
  });
2009
- artifact.addDependence("keq", ["Keq"]);
2010
- artifact.addDependence(requestArtifact, ["request"]);
2011
- artifact.addDependence(
2012
- typeArtifact,
2013
- [
2014
- "Operation",
2015
- typeName("ResponseBodies"),
2016
- typeName("RequestParameters")
2017
- ],
2018
- { type: true }
2019
- );
2020
- artifact.addDependence(
2021
- typeArtifact,
2022
- [
2023
- `${typeName("RequestQuery")}`,
2024
- `${typeName("RequestHeaders")}`,
2025
- `${typeName("RequestBodies")}`
2026
- ],
2027
- { export: true, type: true }
2028
- );
2029
- return await compiler.hooks.afterCompileOperationRequest.promise(artifact, operationDefinition, task);
2030
- }
2031
- const artifacts = R18.unnest(
2032
- await Promise.all(
2033
- operationDefinitions.map(async (operationDefinition) => {
2034
- const typeArtifact = await createTypeArtifact(operationDefinition);
2035
- const operationArtifact = await createRequestArtifact(operationDefinition, typeArtifact);
2036
- return [typeArtifact, operationArtifact];
2431
+ return artifact;
2432
+ }
2433
+ static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
2434
+ const filename = `${changeCase6[fileNamingStyle](operationDefinition.operationId)}.fn.ts`;
2435
+ const filepath = [
2436
+ ".",
2437
+ changeCase6[fileNamingStyle](operationDefinition.module.name),
2438
+ "operations",
2439
+ filename
2440
+ ].join("/");
2441
+ return filepath;
2442
+ }
2443
+ static getOperationDefinitionArtifactId(operationDefinition) {
2444
+ return `${operationDefinition.id}?generator=${MICRO_FUNCTION_GENERATOR}`;
2445
+ }
2446
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2447
+ return [
2448
+ ".",
2449
+ changeCase6[fileNamingStyle](moduleDefinition.name),
2450
+ "operations",
2451
+ "index.ts"
2452
+ ].join("/");
2453
+ }
2454
+ static getEntrypointArtifactId(moduleDefinition) {
2455
+ return `${moduleDefinition.address}/paths/entrypoint?generator=${MICRO_FUNCTION_GENERATOR}`;
2456
+ }
2457
+ };
2458
+
2459
+ // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
2460
+ var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2461
+ microFunctionGenerator = new MicroFunctionGenerator();
2462
+ requestGenerator = new RequestGenerator();
2463
+ apply(compiler) {
2464
+ _GenerateMicroFunctionPlugin.register(compiler);
2465
+ compiler.hooks.compile.tapPromise(_GenerateMicroFunctionPlugin.name, async (task) => {
2466
+ const artifacts = [
2467
+ ...await this.requestGenerator.compile(compiler, task),
2468
+ ...await this.microFunctionGenerator.compile(compiler, task)
2469
+ ];
2470
+ compiler.context.artifacts.push(...artifacts);
2471
+ });
2472
+ }
2473
+ static register(compiler) {
2474
+ if (!MetadataStorage.has(compiler)) {
2475
+ MetadataStorage.set(compiler, {
2476
+ hooks: {
2477
+ afterEntrypointArtifactGenerated: new import_tapable2.AsyncSeriesWaterfallHook(["artifact", "task"]),
2478
+ afterMicroFunctionArtifactGenerated: new import_tapable2.AsyncSeriesWaterfallHook(["artifact", "operationDefinition", "task"])
2479
+ }
2480
+ });
2481
+ }
2482
+ return MetadataStorage.get(compiler);
2483
+ }
2484
+ static of(compiler) {
2485
+ return this.register(compiler);
2486
+ }
2487
+ };
2488
+
2489
+ // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2490
+ var import_tapable3 = require("tapable");
2491
+
2492
+ // src/plugins/generate-nestjs-module/constants/metadata-storage.ts
2493
+ var MetadataStorage3 = /* @__PURE__ */ new WeakMap();
2494
+
2495
+ // src/plugins/generate-nestjs-module/generators/nestjs-module.generator.ts
2496
+ var path11 = __toESM(require("path"), 1);
2497
+ var changeCase7 = __toESM(require("change-case"), 1);
2498
+ var NESTJS_MODULE_GENERATOR = "nestjs-module-generator";
2499
+ var NestjsModuleGenerator = class _NestjsModuleGenerator {
2500
+ generateNestjsModuleArtifact(document, rc) {
2501
+ const filepath = _NestjsModuleGenerator.getNestjsModuleArtifactFilepath(document, rc.fileNamingStyle);
2502
+ const dirname6 = path11.dirname(filepath);
2503
+ const artifact = new Artifact({
2504
+ id: _NestjsModuleGenerator.getNestjsModuleArtifactId(document),
2505
+ filepath,
2506
+ content: ApiDocumentTransformer.toNestjsModule(document, {
2507
+ esm: rc.esm,
2508
+ getNestjsClientFilepath(document2) {
2509
+ const relativePath = path11.relative(
2510
+ dirname6,
2511
+ _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document2, rc.fileNamingStyle)
2512
+ );
2513
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2514
+ }
2037
2515
  })
2038
- )
2039
- );
2040
- const operationDefinitionsGroupByModuleName = R18.groupBy(
2041
- (operationDefinition) => operationDefinition.module.name,
2042
- operationDefinitions
2043
- );
2044
- const entrypointArtifacts = Object.entries(operationDefinitionsGroupByModuleName).map(([moduleName, operationDefinitions2]) => {
2045
- const filepath = genEntrypointFilepath2(moduleName);
2516
+ });
2517
+ return artifact;
2518
+ }
2519
+ generateNestjsClientArtifact(document, rc) {
2520
+ const filepath = _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document, rc.fileNamingStyle);
2521
+ const dirpath = path11.dirname(filepath);
2046
2522
  const artifact = new Artifact({
2047
- id: filepath,
2523
+ id: _NestjsModuleGenerator.getNestjsClientArtifactId(document),
2048
2524
  filepath,
2049
- content: [
2050
- "/* @anchor:file:start */",
2051
- "/* @anchor:file:end */"
2052
- ].join("\n")
2525
+ content: ApiDocumentTransformer.toNestjsClient(document, {
2526
+ esm: rc.esm,
2527
+ qs: rc.qs,
2528
+ getOperationDefinitionDeclarationFilepath(operationDefinition) {
2529
+ const relativePath = path11.relative(
2530
+ dirpath,
2531
+ OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle)
2532
+ );
2533
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2534
+ }
2535
+ })
2053
2536
  });
2054
- for (const operationDefinition of operationDefinitions2 || []) {
2055
- const dependentArtifact = artifacts.find((artifact2) => artifact2.filepath === genOperationRequestFilepath(operationDefinition));
2056
- if (!dependentArtifact) {
2057
- artifact.addWarn(`Cannot find operation: operation = ${operationDefinition.operationId}, pathname = ${operationDefinition.pathname}, method = ${operationDefinition.method}`);
2058
- continue;
2059
- }
2060
- artifact.addDependence(dependentArtifact, [], { export: true });
2061
- }
2062
2537
  return artifact;
2063
- });
2064
- return [...artifacts, ...entrypointArtifacts];
2065
- }
2066
-
2067
- // src/renderer/request/index.ts
2068
- async function requestRenderer() {
2069
- return [
2070
- "/* @anchor:file:start */",
2071
- "",
2072
- "/* @anchor:request-declaration */",
2073
- "export const request = new KeqRequest()",
2074
- "",
2075
- "/* @anchor:file:end */"
2076
- ].join("\n");
2077
- }
2538
+ }
2539
+ async compile(compiler, task) {
2540
+ const metadata = MetadataStorage3.get(compiler);
2541
+ const rc = compiler.context.rc;
2542
+ const documents = compiler.context.documents;
2543
+ const nestjsModuleArtifacts = await Promise.all(
2544
+ documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2545
+ this.generateNestjsModuleArtifact(document, rc),
2546
+ document,
2547
+ task
2548
+ ))
2549
+ );
2550
+ const nestjsClientArtifacts = await Promise.all(
2551
+ documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2552
+ this.generateNestjsClientArtifact(document, rc),
2553
+ document,
2554
+ task
2555
+ ))
2556
+ );
2557
+ return [...nestjsModuleArtifacts, ...nestjsClientArtifacts];
2558
+ }
2559
+ static getNestjsModuleArtifactFilepath(document, fileNamingStyle) {
2560
+ const filename = `${changeCase7[fileNamingStyle](document.module.name)}.module.ts`;
2561
+ const filepath = [
2562
+ ".",
2563
+ changeCase7[fileNamingStyle](document.module.name),
2564
+ filename
2565
+ ];
2566
+ return filepath.join("/");
2567
+ }
2568
+ static getNestjsModuleArtifactId(document) {
2569
+ return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}`;
2570
+ }
2571
+ static getNestjsClientArtifactFilepath(document, fileNamingStyle) {
2572
+ const filename = `${changeCase7[fileNamingStyle](document.module.name)}.client.ts`;
2573
+ const filepath = [
2574
+ ".",
2575
+ changeCase7[fileNamingStyle](document.module.name),
2576
+ filename
2577
+ ];
2578
+ return filepath.join("/");
2579
+ }
2580
+ static getNestjsClientArtifactId(document) {
2581
+ return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}-client`;
2582
+ }
2583
+ };
2078
2584
 
2079
- // src/tasks/compile/index.ts
2080
- function main6(compiler) {
2081
- return {
2082
- task: async (context, task) => {
2083
- if (!context.setup) throw new Error("Please run setup task first.");
2084
- if (!context.shaken) throw new Error("Please run shaking task first.");
2085
- const rc = context.setup.rc;
2086
- const matcher = context.setup.matcher;
2087
- const documents = context.shaken.documents.filter((document) => !matcher.isModuleIgnored(document.module));
2088
- let requestArtifact = new Artifact({
2089
- id: "request",
2090
- filepath: "request",
2091
- content: await requestRenderer(),
2092
- extensionName: ".ts"
2585
+ // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2586
+ var GenerateNestjsModulePlugin = class _GenerateNestjsModulePlugin {
2587
+ nestjsModuleGenerator = new NestjsModuleGenerator();
2588
+ apply(compiler) {
2589
+ _GenerateNestjsModulePlugin.register(compiler);
2590
+ compiler.hooks.compile.tapPromise(_GenerateNestjsModulePlugin.name, async (task) => {
2591
+ const artifacts = await this.nestjsModuleGenerator.compile(compiler, task);
2592
+ compiler.context.artifacts.push(...artifacts);
2593
+ });
2594
+ }
2595
+ static register(compiler) {
2596
+ if (!MetadataStorage3.has(compiler)) {
2597
+ MetadataStorage3.set(compiler, {
2598
+ hooks: {
2599
+ afterNestjsModuleArtifactGenerated: new import_tapable3.AsyncSeriesWaterfallHook(["artifact", "document", "task"])
2600
+ }
2093
2601
  });
2094
- requestArtifact.addDependence("keq", ["KeqRequest"]);
2095
- requestArtifact = await compiler.hooks.afterCompileKeqRequest.promise(
2096
- requestArtifact,
2097
- task
2098
- );
2099
- const schemaDefinitions = documents.flatMap((document) => document.schemas);
2100
- const operationDefinitions = documents.flatMap((document) => document.operations);
2101
- const schemaArtifacts = await compileSchemaDefinition({ compiler, task, schemaDefinitions });
2102
- const operationArtifacts = await compileOperationDefinition({ compiler, task, rc, operationDefinitions, schemaArtifacts, requestArtifact });
2103
- const artifacts = [requestArtifact, ...schemaArtifacts, ...operationArtifacts];
2104
- context.compiled = {
2105
- artifacts
2106
- };
2107
2602
  }
2108
- };
2109
- }
2110
- function createCompileTask(compiler, options) {
2111
- return {
2112
- title: "Compile",
2113
- enabled: options?.enabled,
2114
- skip: options?.skip,
2115
- task: (context, task) => task.newListr(
2116
- [
2117
- main6(compiler),
2118
- {
2119
- task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
2120
- }
2121
- ],
2122
- {
2123
- concurrent: false
2603
+ return MetadataStorage3.get(compiler);
2604
+ }
2605
+ static of(compiler) {
2606
+ return MetadataStorage3.get(compiler);
2607
+ }
2608
+ };
2609
+
2610
+ // src/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.ts
2611
+ var import_swagger_fix = require("swagger-fix");
2612
+
2613
+ // src/plugins/download-http-file/download-http-file.plugin.ts
2614
+ var validUrl = __toESM(require("valid-url"), 1);
2615
+ var DownloadHttpFilePlugin = class _DownloadHttpFilePlugin {
2616
+ apply(compiler) {
2617
+ compiler.hooks.download.tapPromise(_DownloadHttpFilePlugin.name, async (address, task) => {
2618
+ if (!validUrl.isUri(address)) return void 0;
2619
+ const content = await this.download(address);
2620
+ const spec = this.deserialize(content);
2621
+ return JSON.stringify(spec);
2622
+ });
2623
+ }
2624
+ async download(address) {
2625
+ try {
2626
+ const res = await fetch(address);
2627
+ if (res.status >= 400) throw new Error(`failed with status code ${res.status}`);
2628
+ return await res.text();
2629
+ } catch (e) {
2630
+ if (e instanceof Error) {
2631
+ e.message = `Unable get the openapi/swagger file from ${address}: ${e.message}`;
2124
2632
  }
2125
- )
2126
- };
2127
- }
2633
+ throw e;
2634
+ }
2635
+ }
2636
+ deserialize(content) {
2637
+ const json = JSON.parse(content);
2638
+ const spec = OpenapiUtils.to3_1(json);
2639
+ return spec;
2640
+ }
2641
+ };
2642
+
2643
+ // src/plugins/download-local-file/download-local-file.plugin.ts
2644
+ var path12 = __toESM(require("path"), 1);
2645
+ var fs5 = __toESM(require("fs/promises"), 1);
2646
+ var yaml = __toESM(require("js-yaml"), 1);
2647
+ var DownloadLocalFilePlugin = class _DownloadLocalFilePlugin {
2648
+ apply(compiler) {
2649
+ compiler.hooks.download.tapPromise(_DownloadLocalFilePlugin.name, async (address, task) => {
2650
+ if (!address.startsWith("./") && !address.startsWith("/") && !address.startsWith("../")) return void 0;
2651
+ const fileExt = path12.extname(address);
2652
+ const content = await fs5.readFile(address, "utf8");
2653
+ if ([".yml", ".yaml"].includes(fileExt)) {
2654
+ const value = yaml.load(content);
2655
+ return JSON.stringify(OpenapiUtils.to3_1(value));
2656
+ } else if (fileExt === ".json") {
2657
+ return JSON.stringify(OpenapiUtils.to3_1(JSON.parse(content)));
2658
+ }
2659
+ });
2660
+ }
2661
+ };
2662
+
2663
+ // src/plugins/shaking/shaking.plugin.ts
2664
+ var import_openapi_shaking2 = require("@opendoc/openapi-shaking");
2665
+ var ShakingPlugin = class _ShakingPlugin {
2666
+ apply(compiler) {
2667
+ compiler.hooks.beforeCompile.tap(_ShakingPlugin.name, (task) => {
2668
+ const matcher = compiler.context.matcher;
2669
+ const documents = compiler.context.documents;
2670
+ compiler.context.documents = documents.map((document) => this.shaking(compiler, document)).filter((document) => !document.isEmpty()).filter((document) => !matcher.isModuleIgnored(document.module));
2671
+ });
2672
+ }
2673
+ shaking(compiler, document) {
2674
+ const matcher = compiler.context.matcher;
2675
+ const isAccepted = (pathname, method, operation) => {
2676
+ if (!SupportedMethods.includes(method)) return false;
2677
+ return !matcher.isOperationIgnored(new OperationDefinition({
2678
+ method,
2679
+ pathname,
2680
+ operation,
2681
+ module: document.module,
2682
+ document
2683
+ }));
2684
+ };
2685
+ const sharkedSwagger = (0, import_openapi_shaking2.openapiShakingSync)(
2686
+ document.specification,
2687
+ isAccepted,
2688
+ { tolerant: true }
2689
+ );
2690
+ return new ApiDocumentV3_1(
2691
+ sharkedSwagger,
2692
+ new ModuleDefinition(
2693
+ document.module.name,
2694
+ `file://${document.module.name}.v3_1.sharked.json`
2695
+ )
2696
+ );
2697
+ }
2698
+ };
2128
2699
 
2129
- // src/tasks/interactive/utils/select-operation-definitions.ts
2700
+ // src/plugins/terminal-select/utils/select-operation-definitions.ts
2130
2701
  var import_inquirer_select_pro = require("inquirer-select-pro");
2131
2702
  var import_prompt_adapter_inquirer = require("@listr2/prompt-adapter-inquirer");
2132
2703
  async function selectOperationDefinitions(task, operationDefinitions) {
@@ -2149,19 +2720,19 @@ async function selectOperationDefinitions(task, operationDefinitions) {
2149
2720
  return selectedOperationDefinitions;
2150
2721
  }
2151
2722
 
2152
- // src/tasks/interactive/index.ts
2153
- function createInteractiveTask(options) {
2154
- return {
2155
- enabled: options?.enabled,
2156
- skip: options?.skip,
2157
- task: async (context, task) => {
2158
- if (!context.setup) throw new Error("Please run setup task first.");
2159
- if (!context.validated) throw new Error("Please run validate task first.");
2160
- const matcher = context.setup.matcher;
2161
- const documents = context.validated.documents;
2723
+ // src/plugins/terminal-select/terminal-select.plugin.ts
2724
+ var TerminalSelectPlugin = class _TerminalSelectPlugin {
2725
+ constructor(options) {
2726
+ this.options = options;
2727
+ }
2728
+ apply(compiler) {
2729
+ compiler.hooks.afterDownload.tapPromise(_TerminalSelectPlugin.name, async (task) => {
2730
+ const context = compiler.context;
2731
+ const matcher = context.matcher;
2732
+ const documents = context.documents;
2162
2733
  const operationDefinitions = documents.flatMap((document) => document.operations);
2163
2734
  const selectedOperationDefinitions = await selectOperationDefinitions(task, operationDefinitions);
2164
- if (options.clear) {
2735
+ if (this.options.clear) {
2165
2736
  matcher.append({
2166
2737
  persist: false,
2167
2738
  ignore: true,
@@ -2172,109 +2743,66 @@ function createInteractiveTask(options) {
2172
2743
  }
2173
2744
  for (const op of selectedOperationDefinitions) {
2174
2745
  matcher.append({
2175
- persist: !!options.persist,
2176
- ignore: options.mode === "add",
2746
+ persist: !!this.options.persist,
2747
+ ignore: this.options.mode === "add",
2177
2748
  moduleName: op.module.name,
2178
2749
  operationMethod: op.method,
2179
2750
  operationPathname: op.pathname
2180
2751
  });
2181
2752
  }
2182
- }
2183
- };
2184
- }
2753
+ });
2754
+ }
2755
+ };
2185
2756
 
2186
- // src/compiler/intercepter/perfect-error-message.ts
2187
- var R19 = __toESM(require("ramda"), 1);
2188
- function perfectErrorMessage() {
2189
- return {
2190
- register: (tap) => {
2191
- const fn = tap.fn;
2192
- function prefix(err) {
2193
- if (err instanceof Error) {
2194
- err.message = `[Plugin: ${tap.name}] ${err.message}`;
2195
- }
2757
+ // src/plugins/initialize/initialize.plugin.ts
2758
+ var R23 = __toESM(require("ramda"), 1);
2759
+ var InitializePlugin = class _InitializePlugin {
2760
+ constructor(options) {
2761
+ this.options = options;
2762
+ }
2763
+ apply(compiler) {
2764
+ compiler.hooks.setup.tap(_InitializePlugin.name, (task) => {
2765
+ new DownloadHttpFilePlugin().apply(compiler);
2766
+ new DownloadLocalFilePlugin().apply(compiler);
2767
+ new GenerateDeclarationPlugin().apply(compiler);
2768
+ if (this.options.build) {
2769
+ new ShakingPlugin().apply(compiler);
2196
2770
  }
2197
- if (tap.type === "promise") {
2198
- tap.fn = async (...args) => {
2199
- try {
2200
- return await fn(...args);
2201
- } catch (err) {
2202
- prefix(err);
2203
- throw err;
2204
- }
2205
- };
2771
+ if (this.options.interactive) {
2772
+ new TerminalSelectPlugin(
2773
+ typeof this.options.interactive === "object" ? this.options.interactive : { mode: "except" }
2774
+ ).apply(compiler);
2206
2775
  }
2207
- if (tap.type === "sync") {
2208
- tap.fn = (...args) => {
2209
- try {
2210
- return fn(...args);
2211
- } catch (err) {
2212
- prefix(err);
2213
- throw err;
2214
- }
2215
- };
2776
+ const rc = compiler.context.rc;
2777
+ if (rc.mode === "micro-function") {
2778
+ new GenerateMicroFunctionPlugin().apply(compiler);
2779
+ } else if (rc.mode === "nestjs-module") {
2780
+ new GenerateNestjsModulePlugin().apply(compiler);
2216
2781
  }
2217
- if (tap.type === "async") {
2218
- tap.fn = (...args) => {
2219
- const callback = R19.last(args);
2220
- return fn(...R19.init(args), (err, result) => {
2221
- prefix(err);
2222
- return callback(err, result);
2782
+ });
2783
+ if (this.options.includes && this.options.includes.length) {
2784
+ const modulesIncludes = this.options.includes;
2785
+ compiler.hooks.afterSetup.tap(_InitializePlugin.name, (task) => {
2786
+ const rc = compiler.context.rc;
2787
+ const matcher = compiler.context.matcher;
2788
+ const notExistModules = modulesIncludes.filter((moduleName) => !(moduleName in rc.modules));
2789
+ if (notExistModules.length) {
2790
+ throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
2791
+ }
2792
+ const ignoredModules = R23.difference(R23.keys(rc.modules), modulesIncludes);
2793
+ for (const moduleName of ignoredModules) {
2794
+ matcher.append({
2795
+ persist: false,
2796
+ ignore: true,
2797
+ moduleName,
2798
+ operationMethod: "*",
2799
+ operationPathname: "*"
2223
2800
  });
2224
- };
2225
- }
2226
- return tap;
2227
- }
2228
- };
2229
- }
2230
-
2231
- // src/compiler/intercepter/print-information.ts
2232
- function proxyTaskWrapper(pluginName, task) {
2233
- return new Proxy(task, {
2234
- set(target, prop2, value) {
2235
- if (prop2 !== "output") {
2236
- return Reflect.set(target, prop2, value);
2237
- }
2238
- target.output = `[Plugin: ${pluginName}] ${value}`;
2239
- return true;
2240
- }
2241
- });
2242
- }
2243
- function printInformation(taskIndex) {
2244
- return {
2245
- register: (tap) => {
2246
- const fn = tap.fn;
2247
- if (tap.type === "promise") {
2248
- tap.fn = (...args) => {
2249
- const task = args[taskIndex];
2250
- const proxyTask = proxyTaskWrapper(tap.name, task);
2251
- args[taskIndex] = proxyTask;
2252
- proxyTask.output = "Processing...";
2253
- return fn(...args);
2254
- };
2255
- }
2256
- if (tap.type === "sync") {
2257
- tap.fn = (...args) => {
2258
- const task = args[taskIndex];
2259
- const proxyTask = proxyTaskWrapper(tap.name, task);
2260
- args[taskIndex] = proxyTask;
2261
- proxyTask.output = "Processing...";
2262
- return fn(...args);
2263
- };
2264
- }
2265
- if (tap.type === "async") {
2266
- tap.fn = (...args) => {
2267
- const task = args[taskIndex];
2268
- const proxyTask = proxyTaskWrapper(tap.name, task);
2269
- args[taskIndex] = proxyTask;
2270
- proxyTask.output = "Processing...";
2271
- return fn(...args);
2272
- };
2273
- }
2274
- return tap;
2801
+ }
2802
+ });
2275
2803
  }
2276
- };
2277
- }
2804
+ }
2805
+ };
2278
2806
 
2279
2807
  // src/compiler/compiler.ts
2280
2808
  var Compiler = class {
@@ -2285,22 +2813,26 @@ var Compiler = class {
2285
2813
  }
2286
2814
  this.hooks.afterSetup.intercept(printInformation(0));
2287
2815
  this.hooks.afterPersist.intercept(printInformation(0));
2816
+ new InitializePlugin({
2817
+ build: options.build,
2818
+ interactive: options.interactive,
2819
+ includes: options.includes
2820
+ }).apply(this);
2288
2821
  }
2289
2822
  context = {};
2290
2823
  hooks = {
2291
- // core
2292
- afterSetup: new import_tapable.AsyncSeriesHook(["task"]),
2293
- afterDownload: new import_tapable.AsyncSeriesHook(["task"]),
2294
- afterValidate: new import_tapable.AsyncSeriesHook(["task"]),
2295
- afterShaking: new import_tapable.AsyncSeriesHook(["task"]),
2296
- afterCompile: new import_tapable.AsyncSeriesHook(["task"]),
2297
- afterPersist: new import_tapable.AsyncSeriesHook(["task"]),
2298
- done: new import_tapable.SyncHook(),
2299
- // compile
2300
- afterCompileKeqRequest: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "task"]),
2301
- afterCompileSchema: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "schema", "task"]),
2302
- afterCompileOperationType: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "operation", "task"]),
2303
- afterCompileOperationRequest: new import_tapable.AsyncSeriesWaterfallHook(["artifact", "operation", "task"])
2824
+ setup: new import_tapable4.AsyncParallelHook(["task"]),
2825
+ afterSetup: new import_tapable4.AsyncSeriesHook(["task"]),
2826
+ beforeDownload: new import_tapable4.AsyncSeriesHook(["task"]),
2827
+ download: new import_tapable4.AsyncSeriesBailHook(["address", "moduleDefinition", "task"]),
2828
+ afterDownload: new import_tapable4.AsyncSeriesHook(["task"]),
2829
+ beforeCompile: new import_tapable4.AsyncSeriesHook(["task"]),
2830
+ compile: new import_tapable4.AsyncParallelHook(["task"]),
2831
+ afterCompile: new import_tapable4.AsyncSeriesHook(["task"]),
2832
+ beforePersist: new import_tapable4.AsyncSeriesHook(["task"]),
2833
+ persist: new import_tapable4.AsyncParallelHook(["task"]),
2834
+ afterPersist: new import_tapable4.AsyncSeriesHook(["task"]),
2835
+ done: new import_tapable4.SyncHook()
2304
2836
  };
2305
2837
  async run() {
2306
2838
  const options = this.options;
@@ -2308,9 +2840,6 @@ var Compiler = class {
2308
2840
  [
2309
2841
  createSetupTask(this, options),
2310
2842
  createDownloadTask(this, { skipIgnoredModules: !options.interactive }),
2311
- createValidateTask(this),
2312
- createInteractiveTask({ enabled: !!options.interactive, ...typeof options.interactive === "object" ? options.interactive : { mode: "except" } }),
2313
- createShakingTask(this, { enabled: !!options.build, ...typeof options.build === "object" ? options.build.shaking : void 0 }),
2314
2843
  createCompileTask(this, { enabled: !!options.build }),
2315
2844
  createPersistTask(this)
2316
2845
  ],
@@ -2330,23 +2859,21 @@ var Compiler = class {
2330
2859
  };
2331
2860
 
2332
2861
  // src/cli.ts
2333
- if (import_semver.default.lt(process.version, "18.0.0")) {
2334
- throw new Error("Node.js version must be greater than 18");
2862
+ if (import_semver.default.lt(process.version, "20.0.0")) {
2863
+ throw new Error("Node.js version must be greater than 20");
2335
2864
  }
2336
2865
  var program = new import_commander.Command();
2337
2866
  program.command("build").option("-c --config <config>", "The keq-cli config file").option("--module <modules...>", "Filter module(s) to generate").option("--debug", "Print debug information").option("--tolerant", "Tolerate wrong swagger/openapi structure").option("-i --interactive", "Interactive select the scope of generation").action(async (options) => {
2338
2867
  const compiler = new Compiler({
2339
- build: {
2340
- shaking: {
2341
- skipIgnoredModules: true,
2342
- skipEmptyDocuments: true
2343
- }
2344
- },
2868
+ build: true,
2345
2869
  config: options.config,
2346
- modules: options.module,
2870
+ includes: options.module,
2347
2871
  debug: !!options.debug,
2348
2872
  tolerant: !!options.tolerant,
2349
- interactive: !!options.interactive
2873
+ interactive: !!options.interactive && {
2874
+ mode: "except",
2875
+ clear: true
2876
+ }
2350
2877
  });
2351
2878
  await compiler.run();
2352
2879
  });
@@ -2364,7 +2891,7 @@ program.command("ignore").addArgument(
2364
2891
  compiler = new Compiler({
2365
2892
  build: false,
2366
2893
  config: options.config,
2367
- modules: options.module,
2894
+ includes: options.module,
2368
2895
  debug: !!options.debug,
2369
2896
  interactive: false,
2370
2897
  ignore: {
@@ -2383,14 +2910,9 @@ program.command("ignore").addArgument(
2383
2910
  if (options.pathname) throw new Error("'--pathname' cannot be used with '--interactive'");
2384
2911
  }
2385
2912
  compiler = new Compiler({
2386
- build: !!options.build && {
2387
- shaking: {
2388
- skipIgnoredModules: true,
2389
- skipEmptyDocuments: true
2390
- }
2391
- },
2913
+ build: !!options.build,
2392
2914
  config: options.config,
2393
- modules: options.module,
2915
+ includes: options.module,
2394
2916
  debug: !!options.debug,
2395
2917
  interactive: {
2396
2918
  mode,
@@ -2403,15 +2925,10 @@ program.command("ignore").addArgument(
2403
2925
  }
2404
2926
  const moduleNames = options.module || ["*"];
2405
2927
  compiler = new Compiler({
2406
- build: !!options.build && {
2407
- shaking: {
2408
- skipIgnoredModules: true,
2409
- skipEmptyDocuments: true
2410
- }
2411
- },
2928
+ build: !!options.build,
2412
2929
  config: options.config,
2413
2930
  debug: !!options.debug,
2414
- modules: options.module,
2931
+ includes: options.module,
2415
2932
  ignore: {
2416
2933
  rules: moduleNames.map((moduleNames2) => ({
2417
2934
  persist: true,
@@ -2426,7 +2943,7 @@ program.command("ignore").addArgument(
2426
2943
  }
2427
2944
  await compiler.run();
2428
2945
  });
2429
- async function main7() {
2946
+ async function main5() {
2430
2947
  program.on("command:*", function(operands) {
2431
2948
  throw new Error(`Unknown command '${String(operands[0])}'`);
2432
2949
  });
@@ -2440,5 +2957,5 @@ async function main7() {
2440
2957
  }
2441
2958
  }
2442
2959
  }
2443
- void main7();
2960
+ void main5();
2444
2961
  //# sourceMappingURL=cli.cjs.map