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

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