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