@geekmidas/cli 10.0.0-alpha.99 → 10.0.0

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 (676) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/FUNCTION_CRON_SUPPORT.md +266 -0
  3. package/README.md +533 -382
  4. package/bin/gkm.mjs +2 -16
  5. package/dist/CachedStateProvider-BdX7klRc.cjs +3 -0
  6. package/dist/CachedStateProvider-CzyFct42.mjs +54 -0
  7. package/dist/CachedStateProvider-CzyFct42.mjs.map +1 -0
  8. package/dist/CachedStateProvider-GcGziXh1.mjs +3 -0
  9. package/dist/CachedStateProvider-klLWZXWF.cjs +60 -0
  10. package/dist/CachedStateProvider-klLWZXWF.cjs.map +1 -0
  11. package/dist/{HostingerProvider-BNpS9aRJ.mjs → HostingerProvider-B2ZYz7Yc.mjs} +26 -31
  12. package/dist/HostingerProvider-B2ZYz7Yc.mjs.map +1 -0
  13. package/dist/{HostingerProvider-DR1iws1P.cjs → HostingerProvider-CrHfsgz9.cjs} +26 -31
  14. package/dist/HostingerProvider-CrHfsgz9.cjs.map +1 -0
  15. package/dist/LocalStateProvider-CP49rjzt.mjs +42 -0
  16. package/dist/LocalStateProvider-CP49rjzt.mjs.map +1 -0
  17. package/dist/LocalStateProvider-CalzNfNA.cjs +43 -0
  18. package/dist/LocalStateProvider-CalzNfNA.cjs.map +1 -0
  19. package/dist/{Route53Provider-Bllus2NR.cjs → Route53Provider-DwgXiLxt.cjs} +22 -21
  20. package/dist/Route53Provider-DwgXiLxt.cjs.map +1 -0
  21. package/dist/{Route53Provider-QXxjkZO1.mjs → Route53Provider-tlgBzrRQ.mjs} +13 -13
  22. package/dist/Route53Provider-tlgBzrRQ.mjs.map +1 -0
  23. package/dist/SSMStateProvider-BlrTiV5m.mjs +66 -0
  24. package/dist/SSMStateProvider-BlrTiV5m.mjs.map +1 -0
  25. package/dist/SSMStateProvider-Bt6r8CTL.cjs +66 -0
  26. package/dist/SSMStateProvider-Bt6r8CTL.cjs.map +1 -0
  27. package/dist/{backup-provisioner-oDEsPj02.cjs → backup-provisioner-B3HBN-2k.cjs} +20 -22
  28. package/dist/backup-provisioner-B3HBN-2k.cjs.map +1 -0
  29. package/dist/{backup-provisioner-C8DnCmxK.mjs → backup-provisioner-Xunq-p_8.mjs} +9 -12
  30. package/dist/backup-provisioner-Xunq-p_8.mjs.map +1 -0
  31. package/dist/bundler-DkA4qzUD.mjs +135 -0
  32. package/dist/bundler-DkA4qzUD.mjs.map +1 -0
  33. package/dist/bundler-Dufq3uvI.cjs +136 -0
  34. package/dist/bundler-Dufq3uvI.cjs.map +1 -0
  35. package/dist/{rolldown-runtime-C0BPl7ul.cjs → chunk-CUT6urMc.cjs} +10 -23
  36. package/dist/chunk-Duj1WY3L.mjs +7 -0
  37. package/dist/config-Bbu1JKvf.mjs +211 -0
  38. package/dist/config-Bbu1JKvf.mjs.map +1 -0
  39. package/dist/config-DujV8DbR.cjs +253 -0
  40. package/dist/config-DujV8DbR.cjs.map +1 -0
  41. package/dist/config.cjs +10 -421
  42. package/dist/config.d.cts +120 -4
  43. package/dist/config.d.cts.map +1 -0
  44. package/dist/config.d.mts +120 -4
  45. package/dist/config.d.mts.map +1 -0
  46. package/dist/config.mjs +3 -405
  47. package/dist/credentials-C8DWtnMY.cjs +174 -0
  48. package/dist/credentials-C8DWtnMY.cjs.map +1 -0
  49. package/dist/credentials-s1kLcIzK.mjs +126 -0
  50. package/dist/credentials-s1kLcIzK.mjs.map +1 -0
  51. package/dist/deploy/sniffer-envkit-patch.cjs +10 -18
  52. package/dist/deploy/sniffer-envkit-patch.cjs.map +1 -1
  53. package/dist/deploy/sniffer-envkit-patch.d.cts +2 -0
  54. package/dist/deploy/sniffer-envkit-patch.d.cts.map +1 -1
  55. package/dist/deploy/sniffer-envkit-patch.d.mts +2 -0
  56. package/dist/deploy/sniffer-envkit-patch.d.mts.map +1 -1
  57. package/dist/deploy/sniffer-envkit-patch.mjs +2 -10
  58. package/dist/deploy/sniffer-envkit-patch.mjs.map +1 -1
  59. package/dist/deploy/sniffer-hooks.cjs +7 -13
  60. package/dist/deploy/sniffer-hooks.cjs.map +1 -1
  61. package/dist/deploy/sniffer-hooks.d.cts +2 -1
  62. package/dist/deploy/sniffer-hooks.d.cts.map +1 -1
  63. package/dist/deploy/sniffer-hooks.d.mts +2 -1
  64. package/dist/deploy/sniffer-hooks.d.mts.map +1 -1
  65. package/dist/deploy/sniffer-hooks.mjs +3 -10
  66. package/dist/deploy/sniffer-hooks.mjs.map +1 -1
  67. package/dist/deploy/sniffer-loader.cjs +7 -16
  68. package/dist/deploy/sniffer-loader.cjs.map +1 -1
  69. package/dist/deploy/sniffer-loader.d.cts +1 -1
  70. package/dist/deploy/sniffer-loader.d.mts +1 -1
  71. package/dist/deploy/sniffer-loader.mjs +3 -14
  72. package/dist/deploy/sniffer-loader.mjs.map +1 -1
  73. package/dist/deploy/sniffer-routes-worker.cjs +13 -17
  74. package/dist/deploy/sniffer-routes-worker.cjs.map +1 -1
  75. package/dist/deploy/sniffer-routes-worker.d.cts +1 -1
  76. package/dist/deploy/sniffer-routes-worker.d.mts +1 -1
  77. package/dist/deploy/sniffer-routes-worker.mjs +6 -10
  78. package/dist/deploy/sniffer-routes-worker.mjs.map +1 -1
  79. package/dist/deploy/sniffer-worker.cjs +6 -15
  80. package/dist/deploy/sniffer-worker.cjs.map +1 -1
  81. package/dist/deploy/sniffer-worker.d.cts +3 -1
  82. package/dist/deploy/sniffer-worker.d.cts.map +1 -1
  83. package/dist/deploy/sniffer-worker.d.mts +3 -1
  84. package/dist/deploy/sniffer-worker.d.mts.map +1 -1
  85. package/dist/deploy/sniffer-worker.mjs +4 -15
  86. package/dist/deploy/sniffer-worker.mjs.map +1 -1
  87. package/dist/dokploy-api-BPYkG-ZZ.cjs +3 -0
  88. package/dist/dokploy-api-BiSzWM4v.mjs +3 -0
  89. package/dist/dokploy-api-CqOIKHme.cjs +609 -0
  90. package/dist/dokploy-api-CqOIKHme.cjs.map +1 -0
  91. package/dist/dokploy-api-sfZFlWuE.mjs +597 -0
  92. package/dist/dokploy-api-sfZFlWuE.mjs.map +1 -0
  93. package/dist/encryption-BVS7Vmzs.cjs +4 -0
  94. package/dist/encryption-Bd_m4q3g.mjs +3 -0
  95. package/dist/encryption-CO5Q4Bhf.mjs +42 -0
  96. package/dist/encryption-CO5Q4Bhf.mjs.map +1 -0
  97. package/dist/encryption-MfXAiFTm.cjs +54 -0
  98. package/dist/encryption-MfXAiFTm.cjs.map +1 -0
  99. package/dist/fullstack-secrets-BYzi6Hwl.cjs +402 -0
  100. package/dist/fullstack-secrets-BYzi6Hwl.cjs.map +1 -0
  101. package/dist/fullstack-secrets-l8s3II_H.mjs +336 -0
  102. package/dist/fullstack-secrets-l8s3II_H.mjs.map +1 -0
  103. package/dist/index-CoVW_fFS.d.cts +1737 -0
  104. package/dist/index-CoVW_fFS.d.cts.map +1 -0
  105. package/dist/index-oWibAYQY.d.mts +1737 -0
  106. package/dist/index-oWibAYQY.d.mts.map +1 -0
  107. package/dist/index.cjs +11324 -10240
  108. package/dist/index.cjs.map +1 -1
  109. package/dist/index.d.cts +1 -1
  110. package/dist/index.d.mts +1 -1
  111. package/dist/index.mjs +11327 -10231
  112. package/dist/index.mjs.map +1 -1
  113. package/dist/openapi-BzNOC7_i.cjs +1931 -0
  114. package/dist/openapi-BzNOC7_i.cjs.map +1 -0
  115. package/dist/openapi-Cfwi0fqF.mjs +1883 -0
  116. package/dist/openapi-Cfwi0fqF.mjs.map +1 -0
  117. package/dist/openapi-react-query-C4iIvpPf.mjs +167 -0
  118. package/dist/openapi-react-query-C4iIvpPf.mjs.map +1 -0
  119. package/dist/openapi-react-query-CYWik72n.cjs +173 -0
  120. package/dist/openapi-react-query-CYWik72n.cjs.map +1 -0
  121. package/dist/openapi-react-query.cjs +4 -0
  122. package/dist/openapi-react-query.d.cts +11 -0
  123. package/dist/openapi-react-query.d.cts.map +1 -0
  124. package/dist/openapi-react-query.d.mts +11 -0
  125. package/dist/openapi-react-query.d.mts.map +1 -0
  126. package/dist/openapi-react-query.mjs +4 -0
  127. package/dist/openapi.cjs +7 -214
  128. package/dist/openapi.d.cts +15 -72
  129. package/dist/openapi.d.cts.map +1 -1
  130. package/dist/openapi.d.mts +15 -72
  131. package/dist/openapi.d.mts.map +1 -1
  132. package/dist/openapi.mjs +4 -208
  133. package/dist/{reconcile--I7V4Klj.mjs → reconcile-B2FoJE0a.mjs} +8 -6
  134. package/dist/reconcile-B2FoJE0a.mjs.map +1 -0
  135. package/dist/{reconcile-CuCQBa5-.cjs → reconcile-BzqKJ2Rt.cjs} +8 -6
  136. package/dist/reconcile-BzqKJ2Rt.cjs.map +1 -0
  137. package/dist/setup-DDXUXzzl.mjs +765 -0
  138. package/dist/setup-DDXUXzzl.mjs.map +1 -0
  139. package/dist/setup-DLwhfyt-.cjs +8 -0
  140. package/dist/setup-Dh-B7YTX.mjs +8 -0
  141. package/dist/setup-WZ-xqAQO.cjs +849 -0
  142. package/dist/setup-WZ-xqAQO.cjs.map +1 -0
  143. package/dist/storage-B1wvztiJ.cjs +363 -0
  144. package/dist/storage-B1wvztiJ.cjs.map +1 -0
  145. package/dist/storage-Cs4WBsc4.mjs +3 -0
  146. package/dist/storage-DOEtT2Hr.cjs +7 -0
  147. package/dist/storage-dbb9RyBl.mjs +297 -0
  148. package/dist/storage-dbb9RyBl.mjs.map +1 -0
  149. package/dist/sync-B5UHXwRM.mjs +3 -0
  150. package/dist/sync-BLA94rgC.cjs +4 -0
  151. package/dist/sync-CSooqRQ8.mjs +76 -0
  152. package/dist/sync-CSooqRQ8.mjs.map +1 -0
  153. package/dist/sync-o_CtEbvR.cjs +93 -0
  154. package/dist/sync-o_CtEbvR.cjs.map +1 -0
  155. package/dist/types-B3GQUg3k.d.mts +280 -0
  156. package/dist/types-B3GQUg3k.d.mts.map +1 -0
  157. package/dist/types-BWQDiooe.d.cts +280 -0
  158. package/dist/types-BWQDiooe.d.cts.map +1 -0
  159. package/dist/workspace/index.cjs +4 -12
  160. package/dist/workspace/index.d.cts +3 -3
  161. package/dist/workspace/index.d.mts +3 -3
  162. package/dist/workspace/index.mjs +3 -2
  163. package/dist/workspace-CQTT7HJQ.cjs +4361 -0
  164. package/dist/workspace-CQTT7HJQ.cjs.map +1 -0
  165. package/dist/workspace-D-37Ylqo.mjs +4236 -0
  166. package/dist/workspace-D-37Ylqo.mjs.map +1 -0
  167. package/docs/OPENAPI_TYPESCRIPT_DESIGN.md +408 -0
  168. package/docs/dev-server-resilience-design.md +189 -0
  169. package/docs/manifest-refactor-design.md +287 -0
  170. package/examples/cron-example.ts +45 -0
  171. package/examples/env.ts +33 -0
  172. package/examples/function-example.ts +40 -0
  173. package/examples/gkm.config.json +22 -0
  174. package/examples/gkm.config.ts +14 -0
  175. package/examples/gkm.minimal.config.json +7 -0
  176. package/examples/gkm.production.config.json +27 -0
  177. package/examples/logger.ts +10 -0
  178. package/package.json +37 -87
  179. package/scripts/sync-versions.ts +108 -0
  180. package/src/__tests__/EndpointGenerator.hooks.spec.ts +204 -0
  181. package/src/__tests__/config.spec.ts +422 -0
  182. package/src/__tests__/loadEnvFiles.spec.ts +131 -0
  183. package/src/__tests__/normalizeHooksConfig.spec.ts +63 -0
  184. package/src/__tests__/openapi-react-query.spec.ts +506 -0
  185. package/src/__tests__/openapi.spec.ts +625 -0
  186. package/src/__tests__/test-helpers.ts +180 -0
  187. package/src/auth/__tests__/credentials.spec.ts +331 -0
  188. package/src/auth/__tests__/index.spec.ts +237 -0
  189. package/src/auth/credentials.ts +286 -0
  190. package/src/auth/index.ts +233 -0
  191. package/src/build/__tests__/bundler.spec.ts +446 -0
  192. package/src/build/__tests__/endpoint-analyzer.spec.ts +623 -0
  193. package/src/build/__tests__/handler-templates.spec.ts +1287 -0
  194. package/src/build/__tests__/index-new.spec.ts +550 -0
  195. package/src/build/__tests__/manifests.spec.ts +583 -0
  196. package/src/build/__tests__/partitions.spec.ts +110 -0
  197. package/src/build/__tests__/workspace-build.spec.ts +215 -0
  198. package/src/build/bundler.ts +256 -0
  199. package/src/build/endpoint-analyzer.ts +236 -0
  200. package/src/build/handler-templates.ts +1253 -0
  201. package/src/build/index.ts +616 -0
  202. package/src/build/manifests.ts +285 -0
  203. package/src/build/partitions.ts +58 -0
  204. package/src/build/providerResolver.ts +184 -0
  205. package/src/build/types.ts +104 -0
  206. package/src/config.ts +330 -0
  207. package/src/credentials/__tests__/fullDockerPorts.spec.ts +144 -0
  208. package/src/credentials/__tests__/helpers.ts +112 -0
  209. package/src/credentials/__tests__/prepareEntryCredentials.spec.ts +125 -0
  210. package/src/credentials/__tests__/readonlyDockerPorts.spec.ts +190 -0
  211. package/src/credentials/__tests__/workspaceCredentials.spec.ts +209 -0
  212. package/src/credentials/index.ts +843 -0
  213. package/src/debug.ts +68 -0
  214. package/src/deploy/CachedStateProvider.ts +86 -0
  215. package/src/deploy/LocalStateProvider.ts +57 -0
  216. package/src/deploy/SSMStateProvider.ts +117 -0
  217. package/src/deploy/StateProvider.ts +175 -0
  218. package/src/deploy/__tests__/CachedStateProvider.spec.ts +235 -0
  219. package/src/deploy/__tests__/HostingerProvider.spec.ts +347 -0
  220. package/src/deploy/__tests__/LocalStateProvider.spec.ts +130 -0
  221. package/src/deploy/__tests__/Route53Provider.spec.ts +425 -0
  222. package/src/deploy/__tests__/SSMStateProvider.spec.ts +201 -0
  223. package/src/deploy/__tests__/__fixtures__/entry-apps/async-entry.ts +24 -0
  224. package/src/deploy/__tests__/__fixtures__/entry-apps/nested-config-entry.ts +24 -0
  225. package/src/deploy/__tests__/__fixtures__/entry-apps/no-env-entry.ts +12 -0
  226. package/src/deploy/__tests__/__fixtures__/entry-apps/simple-entry.ts +14 -0
  227. package/src/deploy/__tests__/__fixtures__/entry-apps/throwing-entry.ts +16 -0
  228. package/src/deploy/__tests__/__fixtures__/env-parsers/non-function-export.ts +10 -0
  229. package/src/deploy/__tests__/__fixtures__/env-parsers/optional-env-parser.ts +21 -0
  230. package/src/deploy/__tests__/__fixtures__/env-parsers/parseable-env-parser.ts +18 -0
  231. package/src/deploy/__tests__/__fixtures__/env-parsers/throwing-env-parser.ts +16 -0
  232. package/src/deploy/__tests__/__fixtures__/env-parsers/valid-env-parser.ts +16 -0
  233. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/auth.ts +16 -0
  234. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/health.ts +13 -0
  235. package/src/deploy/__tests__/__fixtures__/route-apps/endpoints/users.ts +15 -0
  236. package/src/deploy/__tests__/__fixtures__/route-apps/services.ts +55 -0
  237. package/src/deploy/__tests__/backup-provisioner.spec.ts +428 -0
  238. package/src/deploy/__tests__/createDnsProvider.spec.ts +195 -0
  239. package/src/deploy/__tests__/createStateProvider.spec.ts +126 -0
  240. package/src/deploy/__tests__/dns-orchestration.spec.ts +192 -0
  241. package/src/deploy/__tests__/dns-verification.spec.ts +229 -0
  242. package/src/deploy/__tests__/docker.spec.ts +149 -0
  243. package/src/deploy/__tests__/dokploy-api.spec.ts +697 -0
  244. package/src/deploy/__tests__/dokploy.spec.ts +435 -0
  245. package/src/deploy/__tests__/domain.spec.ts +235 -0
  246. package/src/deploy/__tests__/env-resolver.spec.ts +903 -0
  247. package/src/deploy/__tests__/index.spec.ts +1091 -0
  248. package/src/deploy/__tests__/init.spec.ts +793 -0
  249. package/src/deploy/__tests__/secrets.spec.ts +303 -0
  250. package/src/deploy/__tests__/sniffer.spec.ts +838 -0
  251. package/src/deploy/__tests__/state-e2e.spec.ts +387 -0
  252. package/src/deploy/__tests__/state.spec.ts +876 -0
  253. package/src/deploy/__tests__/undeploy.spec.ts +758 -0
  254. package/src/deploy/backup-provisioner.ts +316 -0
  255. package/src/deploy/dns/DnsProvider.ts +201 -0
  256. package/src/deploy/dns/HostingerProvider.ts +174 -0
  257. package/src/deploy/dns/Route53Provider.ts +340 -0
  258. package/src/deploy/dns/hostinger-api.ts +261 -0
  259. package/src/deploy/dns/index.ts +627 -0
  260. package/src/deploy/docker.ts +260 -0
  261. package/src/deploy/dokploy-api.ts +1101 -0
  262. package/src/deploy/dokploy.ts +177 -0
  263. package/src/deploy/domain.ts +134 -0
  264. package/src/deploy/env-resolver.ts +305 -0
  265. package/src/deploy/index.ts +2094 -0
  266. package/src/deploy/init.ts +427 -0
  267. package/src/deploy/secrets.ts +187 -0
  268. package/src/deploy/sniffer-envkit-patch.ts +61 -0
  269. package/src/deploy/sniffer-hooks.ts +57 -0
  270. package/src/deploy/sniffer-loader.ts +28 -0
  271. package/src/deploy/sniffer-routes-worker.ts +104 -0
  272. package/src/deploy/sniffer-worker.ts +75 -0
  273. package/src/deploy/sniffer.ts +578 -0
  274. package/src/deploy/state-commands.ts +274 -0
  275. package/src/deploy/state.ts +482 -0
  276. package/src/deploy/types.ts +102 -0
  277. package/src/deploy/undeploy.ts +407 -0
  278. package/src/dev/__tests__/entry-integration.spec.ts +347 -0
  279. package/src/dev/__tests__/entry.spec.ts +144 -0
  280. package/src/dev/__tests__/index.spec.ts +2084 -0
  281. package/src/dev/index.ts +1649 -0
  282. package/src/docker/__tests__/compose.spec.ts +1142 -0
  283. package/src/docker/__tests__/templates.spec.ts +694 -0
  284. package/src/docker/compose.ts +812 -0
  285. package/src/docker/index.ts +523 -0
  286. package/src/docker/templates.ts +1067 -0
  287. package/src/exec/index.ts +118 -0
  288. package/src/generators/CronGenerator.ts +105 -0
  289. package/src/generators/EndpointGenerator.ts +954 -0
  290. package/src/generators/FunctionGenerator.ts +117 -0
  291. package/src/generators/Generator.ts +147 -0
  292. package/src/generators/OpenApiTsGenerator.ts +821 -0
  293. package/src/generators/QueueGenerator.ts +245 -0
  294. package/src/generators/SubscriberGenerator.ts +282 -0
  295. package/src/generators/TopicGenerator.ts +45 -0
  296. package/src/generators/__tests__/CronGenerator.spec.ts +445 -0
  297. package/src/generators/__tests__/EndpointGenerator.spec.ts +544 -0
  298. package/src/generators/__tests__/FunctionGenerator.spec.ts +256 -0
  299. package/src/generators/__tests__/Generator.bustCache.spec.ts +72 -0
  300. package/src/generators/__tests__/OpenApiTsGenerator.registry.spec.ts +98 -0
  301. package/src/generators/__tests__/OpenApiTsGenerator.responseType.spec.ts +56 -0
  302. package/src/generators/__tests__/QueueGenerator.spec.ts +141 -0
  303. package/src/generators/__tests__/SubscriberGenerator.spec.ts +410 -0
  304. package/src/generators/index.ts +11 -0
  305. package/src/index.ts +972 -0
  306. package/src/init/__tests__/generators.spec.ts +1072 -0
  307. package/src/init/__tests__/init.spec.ts +577 -0
  308. package/src/init/__tests__/utils.spec.ts +104 -0
  309. package/src/init/generators/auth.ts +225 -0
  310. package/src/init/generators/config.ts +316 -0
  311. package/src/init/generators/docker.ts +388 -0
  312. package/src/init/generators/env.ts +62 -0
  313. package/src/init/generators/index.ts +6 -0
  314. package/src/init/generators/mobile-expo.ts +576 -0
  315. package/src/init/generators/models.ts +153 -0
  316. package/src/init/generators/monorepo.ts +475 -0
  317. package/src/init/generators/package.ts +95 -0
  318. package/src/init/generators/source.ts +15 -0
  319. package/src/init/generators/test.ts +178 -0
  320. package/src/init/generators/ui.ts +1473 -0
  321. package/src/init/generators/web-tanstack.ts +348 -0
  322. package/src/init/generators/web.ts +363 -0
  323. package/src/init/index.ts +542 -0
  324. package/src/init/templates/api.ts +404 -0
  325. package/src/init/templates/index.ts +342 -0
  326. package/src/init/templates/minimal.ts +207 -0
  327. package/src/init/templates/serverless.ts +148 -0
  328. package/src/init/templates/worker.ts +216 -0
  329. package/src/init/utils.ts +197 -0
  330. package/src/init/versions.ts +52 -0
  331. package/src/openapi-react-query.ts +288 -0
  332. package/src/openapi.ts +259 -0
  333. package/src/secrets/__tests__/encryption.spec.ts +226 -0
  334. package/src/secrets/__tests__/generator.spec.ts +575 -0
  335. package/src/secrets/__tests__/index.spec.ts +91 -0
  336. package/src/secrets/__tests__/reconcile.spec.ts +123 -0
  337. package/src/secrets/__tests__/storage.spec.ts +645 -0
  338. package/src/secrets/encryption.ts +91 -0
  339. package/src/secrets/generator.ts +329 -0
  340. package/src/secrets/index.ts +417 -0
  341. package/src/secrets/keystore.ts +144 -0
  342. package/src/secrets/reconcile.ts +53 -0
  343. package/src/secrets/storage.ts +337 -0
  344. package/src/secrets/sync.ts +136 -0
  345. package/src/secrets/types.ts +70 -0
  346. package/src/setup/__tests__/auto-setup.spec.ts +147 -0
  347. package/src/setup/__tests__/reconcile-secrets.spec.ts +439 -0
  348. package/src/setup/fullstack-secrets.ts +140 -0
  349. package/src/setup/index.ts +411 -0
  350. package/src/test/__tests__/__fixtures__/workspace.ts +104 -0
  351. package/src/test/__tests__/api.spec.ts +199 -0
  352. package/src/test/__tests__/auth.spec.ts +162 -0
  353. package/src/test/__tests__/index.spec.ts +502 -0
  354. package/src/test/__tests__/web.spec.ts +210 -0
  355. package/src/test/index.ts +198 -0
  356. package/src/types.ts +363 -0
  357. package/src/upgrade/__tests__/index.spec.ts +354 -0
  358. package/src/upgrade/index.ts +253 -0
  359. package/src/workspace/__tests__/client-generator.spec.ts +326 -0
  360. package/src/workspace/__tests__/index.spec.ts +766 -0
  361. package/src/workspace/__tests__/publicEnv.spec.ts +64 -0
  362. package/src/workspace/__tests__/schema.spec.ts +737 -0
  363. package/src/workspace/__tests__/type-inference.spec.ts +251 -0
  364. package/src/workspace/client-generator.ts +109 -0
  365. package/src/workspace/index.ts +433 -0
  366. package/src/workspace/publicEnv.ts +57 -0
  367. package/src/workspace/schema.ts +861 -0
  368. package/src/workspace/types.ts +943 -0
  369. package/tsconfig.json +9 -0
  370. package/tsdown.config.ts +22 -0
  371. package/bin/adjacent-tsconfig.mjs +0 -97
  372. package/bin/owning-tsconfig-jsx-register.mjs +0 -18
  373. package/bin/owning-tsconfig-jsx.mjs +0 -108
  374. package/dist/EndpointGenerator-Bor2tZCm.mjs +0 -1031
  375. package/dist/EndpointGenerator-Bor2tZCm.mjs.map +0 -1
  376. package/dist/EndpointGenerator-De03t1hd.cjs +0 -1090
  377. package/dist/EndpointGenerator-De03t1hd.cjs.map +0 -1
  378. package/dist/GoDaddyProvider-206NguW1.mjs +0 -388
  379. package/dist/GoDaddyProvider-206NguW1.mjs.map +0 -1
  380. package/dist/GoDaddyProvider-D1aQy2i1.cjs +0 -388
  381. package/dist/GoDaddyProvider-D1aQy2i1.cjs.map +0 -1
  382. package/dist/HostingerProvider-BNpS9aRJ.mjs.map +0 -1
  383. package/dist/HostingerProvider-DR1iws1P.cjs.map +0 -1
  384. package/dist/LegacyStateStore-CgJEr1G7.cjs +0 -124
  385. package/dist/LegacyStateStore-CgJEr1G7.cjs.map +0 -1
  386. package/dist/LegacyStateStore-wmFfdzuh.mjs +0 -124
  387. package/dist/LegacyStateStore-wmFfdzuh.mjs.map +0 -1
  388. package/dist/LocalStateStore-BD14kra9.cjs +0 -178
  389. package/dist/LocalStateStore-BD14kra9.cjs.map +0 -1
  390. package/dist/LocalStateStore-C5mNp91D.mjs +0 -167
  391. package/dist/LocalStateStore-C5mNp91D.mjs.map +0 -1
  392. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs +0 -541
  393. package/dist/OpenApiTsGenerator-CS_RtWOz.cjs.map +0 -1
  394. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs +0 -536
  395. package/dist/OpenApiTsGenerator-DWAF-7Fu.mjs.map +0 -1
  396. package/dist/Route53Provider-Bllus2NR.cjs.map +0 -1
  397. package/dist/Route53Provider-QXxjkZO1.mjs.map +0 -1
  398. package/dist/S3StateStore-CEGbsDHi.mjs +0 -223
  399. package/dist/S3StateStore-CEGbsDHi.mjs.map +0 -1
  400. package/dist/S3StateStore-Csu_kJCy.cjs +0 -222
  401. package/dist/S3StateStore-Csu_kJCy.cjs.map +0 -1
  402. package/dist/SSMStateStore-Bd62qwp4.mjs +0 -205
  403. package/dist/SSMStateStore-Bd62qwp4.mjs.map +0 -1
  404. package/dist/SSMStateStore-Rp21jtP5.cjs +0 -204
  405. package/dist/SSMStateStore-Rp21jtP5.cjs.map +0 -1
  406. package/dist/SubscriberGenerator-CyN2VF5X.mjs +0 -449
  407. package/dist/SubscriberGenerator-CyN2VF5X.mjs.map +0 -1
  408. package/dist/SubscriberGenerator-Dvz7EzqK.cjs +0 -490
  409. package/dist/SubscriberGenerator-Dvz7EzqK.cjs.map +0 -1
  410. package/dist/add-DyIEYI97.mjs +0 -718
  411. package/dist/add-DyIEYI97.mjs.map +0 -1
  412. package/dist/add-Iuo3ao5E.cjs +0 -720
  413. package/dist/add-Iuo3ao5E.cjs.map +0 -1
  414. package/dist/appPorts-C9z9Pzn9.mjs +0 -223
  415. package/dist/appPorts-C9z9Pzn9.mjs.map +0 -1
  416. package/dist/appPorts-Cu79hJF6.cjs +0 -264
  417. package/dist/appPorts-Cu79hJF6.cjs.map +0 -1
  418. package/dist/aws-8QQ8n-t6.mjs +0 -89
  419. package/dist/aws-8QQ8n-t6.mjs.map +0 -1
  420. package/dist/aws-DY9NqQIT.cjs +0 -100
  421. package/dist/aws-DY9NqQIT.cjs.map +0 -1
  422. package/dist/awsStore-Bx5nCFnS.mjs +0 -121
  423. package/dist/awsStore-Bx5nCFnS.mjs.map +0 -1
  424. package/dist/awsStore-u3ehhMoY.cjs +0 -138
  425. package/dist/awsStore-u3ehhMoY.cjs.map +0 -1
  426. package/dist/backup-provisioner-C8DnCmxK.mjs.map +0 -1
  427. package/dist/backup-provisioner-oDEsPj02.cjs.map +0 -1
  428. package/dist/bundler-Bgoq8IyR.cjs +0 -169
  429. package/dist/bundler-Bgoq8IyR.cjs.map +0 -1
  430. package/dist/bundler-Q6Kp8b0r.mjs +0 -169
  431. package/dist/bundler-Q6Kp8b0r.mjs.map +0 -1
  432. package/dist/cli-B9BudUV0.mjs +0 -71
  433. package/dist/cli-B9BudUV0.mjs.map +0 -1
  434. package/dist/cli-W2DMRIbP.cjs +0 -71
  435. package/dist/cli-W2DMRIbP.cjs.map +0 -1
  436. package/dist/compose-CIrFNWHb.cjs +0 -3147
  437. package/dist/compose-CIrFNWHb.cjs.map +0 -1
  438. package/dist/compose-CLsRcHkA.mjs +0 -3052
  439. package/dist/compose-CLsRcHkA.mjs.map +0 -1
  440. package/dist/config-BVdHfj8b.d.cts +0 -269
  441. package/dist/config-BVdHfj8b.d.cts.map +0 -1
  442. package/dist/config-D2OqCmAM.d.mts +0 -269
  443. package/dist/config-D2OqCmAM.d.mts.map +0 -1
  444. package/dist/config.cjs.map +0 -1
  445. package/dist/config.mjs.map +0 -1
  446. package/dist/credentialSchemas-BJFvfkaz.mjs +0 -237
  447. package/dist/credentialSchemas-BJFvfkaz.mjs.map +0 -1
  448. package/dist/credentialSchemas-CAPKFkrG.cjs +0 -272
  449. package/dist/credentialSchemas-CAPKFkrG.cjs.map +0 -1
  450. package/dist/credentials-B5N5yKk6.mjs +0 -267
  451. package/dist/credentials-B5N5yKk6.mjs.map +0 -1
  452. package/dist/credentials-Zqr3QQYB.cjs +0 -350
  453. package/dist/credentials-Zqr3QQYB.cjs.map +0 -1
  454. package/dist/databases-BeGP5eDh.mjs +0 -495
  455. package/dist/databases-BeGP5eDh.mjs.map +0 -1
  456. package/dist/databases-DGALFDG3.cjs +0 -598
  457. package/dist/databases-DGALFDG3.cjs.map +0 -1
  458. package/dist/define-6poNqm5O.mjs +0 -106
  459. package/dist/define-6poNqm5O.mjs.map +0 -1
  460. package/dist/define-crmMcXFS.cjs +0 -153
  461. package/dist/define-crmMcXFS.cjs.map +0 -1
  462. package/dist/deploy/public.cjs +0 -212
  463. package/dist/deploy/public.cjs.map +0 -1
  464. package/dist/deploy/public.d.cts +0 -653
  465. package/dist/deploy/public.d.cts.map +0 -1
  466. package/dist/deploy/public.d.mts +0 -653
  467. package/dist/deploy/public.d.mts.map +0 -1
  468. package/dist/deploy/public.mjs +0 -145
  469. package/dist/deploy/public.mjs.map +0 -1
  470. package/dist/deploy/sniffer-envparser-worker.cjs +0 -54
  471. package/dist/deploy/sniffer-envparser-worker.cjs.map +0 -1
  472. package/dist/deploy/sniffer-envparser-worker.d.cts +0 -1
  473. package/dist/deploy/sniffer-envparser-worker.d.mts +0 -1
  474. package/dist/deploy/sniffer-envparser-worker.mjs +0 -55
  475. package/dist/deploy/sniffer-envparser-worker.mjs.map +0 -1
  476. package/dist/deploy-CbJMJsgX.cjs +0 -2032
  477. package/dist/deploy-CbJMJsgX.cjs.map +0 -1
  478. package/dist/deploy-n_IB8r6H.mjs +0 -1977
  479. package/dist/deploy-n_IB8r6H.mjs.map +0 -1
  480. package/dist/derive-B4vDpzgP.mjs +0 -150
  481. package/dist/derive-B4vDpzgP.mjs.map +0 -1
  482. package/dist/derive-DAbo49sm.cjs +0 -161
  483. package/dist/derive-DAbo49sm.cjs.map +0 -1
  484. package/dist/discover-Caf6Hnv1.d.cts +0 -108
  485. package/dist/discover-Caf6Hnv1.d.cts.map +0 -1
  486. package/dist/discover-Cd5M2jPv.d.mts +0 -108
  487. package/dist/discover-Cd5M2jPv.d.mts.map +0 -1
  488. package/dist/discover-DPgu-ScS.cjs +0 -600
  489. package/dist/discover-DPgu-ScS.cjs.map +0 -1
  490. package/dist/discover-qjFapetL.mjs +0 -527
  491. package/dist/discover-qjFapetL.mjs.map +0 -1
  492. package/dist/dns-C_LPS3qV.mjs +0 -610
  493. package/dist/dns-C_LPS3qV.mjs.map +0 -1
  494. package/dist/dns-kp8To8Qj.cjs +0 -663
  495. package/dist/dns-kp8To8Qj.cjs.map +0 -1
  496. package/dist/dokploy-Dl_kNVeE.mjs +0 -38
  497. package/dist/dokploy-Dl_kNVeE.mjs.map +0 -1
  498. package/dist/dokploy-gRIae9Ht.cjs +0 -38
  499. package/dist/dokploy-gRIae9Ht.cjs.map +0 -1
  500. package/dist/drivers-CTaWrA_L.mjs +0 -177
  501. package/dist/drivers-CTaWrA_L.mjs.map +0 -1
  502. package/dist/drivers-DDojgzz0.cjs +0 -200
  503. package/dist/drivers-DDojgzz0.cjs.map +0 -1
  504. package/dist/emit-C1e8qD08.mjs +0 -193
  505. package/dist/emit-C1e8qD08.mjs.map +0 -1
  506. package/dist/emit-Dmc1nvdS.cjs +0 -210
  507. package/dist/emit-Dmc1nvdS.cjs.map +0 -1
  508. package/dist/encryption-C3DcVZQs.mjs +0 -89
  509. package/dist/encryption-C3DcVZQs.mjs.map +0 -1
  510. package/dist/encryption-CmQvQOSe.cjs +0 -90
  511. package/dist/encryption-CmQvQOSe.cjs.map +0 -1
  512. package/dist/engine-DBXuhHyf.mjs +0 -3081
  513. package/dist/engine-DBXuhHyf.mjs.map +0 -1
  514. package/dist/engine-Dk19Mxc4.cjs +0 -3194
  515. package/dist/engine-Dk19Mxc4.cjs.map +0 -1
  516. package/dist/errors-D8Gwp5kU.mjs +0 -23
  517. package/dist/errors-D8Gwp5kU.mjs.map +0 -1
  518. package/dist/errors-DMC4Umsb.cjs +0 -34
  519. package/dist/errors-DMC4Umsb.cjs.map +0 -1
  520. package/dist/github-Ds2RYnSU.cjs +0 -819
  521. package/dist/github-Ds2RYnSU.cjs.map +0 -1
  522. package/dist/github-RawRLERq.mjs +0 -819
  523. package/dist/github-RawRLERq.mjs.map +0 -1
  524. package/dist/identity-CBXr4wNi.mjs +0 -129
  525. package/dist/identity-CBXr4wNi.mjs.map +0 -1
  526. package/dist/identity-CbLfgQNT.cjs +0 -182
  527. package/dist/identity-CbLfgQNT.cjs.map +0 -1
  528. package/dist/index-BU4G20G6.d.cts +0 -190
  529. package/dist/index-BU4G20G6.d.cts.map +0 -1
  530. package/dist/index-yDbd1WcM.d.mts +0 -190
  531. package/dist/index-yDbd1WcM.d.mts.map +0 -1
  532. package/dist/local-BwC2v2Y8.mjs +0 -224
  533. package/dist/local-BwC2v2Y8.mjs.map +0 -1
  534. package/dist/local-DNhnkugT.cjs +0 -241
  535. package/dist/local-DNhnkugT.cjs.map +0 -1
  536. package/dist/migrate-CZIGT3kB.mjs +0 -266
  537. package/dist/migrate-CZIGT3kB.mjs.map +0 -1
  538. package/dist/migrate-CxZYzF_u.cjs +0 -181
  539. package/dist/migrate-CxZYzF_u.cjs.map +0 -1
  540. package/dist/migrate-DR1x96I4.mjs +0 -181
  541. package/dist/migrate-DR1x96I4.mjs.map +0 -1
  542. package/dist/migrate-DjrTwWJA.cjs +0 -271
  543. package/dist/migrate-DjrTwWJA.cjs.map +0 -1
  544. package/dist/openapi.cjs.map +0 -1
  545. package/dist/openapi.mjs.map +0 -1
  546. package/dist/projectBucket-BYOxRnHY.mjs +0 -177
  547. package/dist/projectBucket-BYOxRnHY.mjs.map +0 -1
  548. package/dist/projectBucket-CDu5rXjp.cjs +0 -206
  549. package/dist/projectBucket-CDu5rXjp.cjs.map +0 -1
  550. package/dist/provider-BqpjG9QM.cjs +0 -57
  551. package/dist/provider-BqpjG9QM.cjs.map +0 -1
  552. package/dist/provider-CEOKk8NS.mjs +0 -46
  553. package/dist/provider-CEOKk8NS.mjs.map +0 -1
  554. package/dist/ready-D3PIjx3S.cjs +0 -403
  555. package/dist/ready-D3PIjx3S.cjs.map +0 -1
  556. package/dist/ready-naOSJpeJ.mjs +0 -374
  557. package/dist/ready-naOSJpeJ.mjs.map +0 -1
  558. package/dist/reconcile/public.cjs +0 -7
  559. package/dist/reconcile/public.d.cts +0 -49
  560. package/dist/reconcile/public.d.cts.map +0 -1
  561. package/dist/reconcile/public.d.mts +0 -49
  562. package/dist/reconcile/public.d.mts.map +0 -1
  563. package/dist/reconcile/public.mjs +0 -3
  564. package/dist/reconcile--I7V4Klj.mjs.map +0 -1
  565. package/dist/reconcile-CuCQBa5-.cjs.map +0 -1
  566. package/dist/resolve-CNYbGH8g.mjs +0 -263
  567. package/dist/resolve-CNYbGH8g.mjs.map +0 -1
  568. package/dist/resolve-DC98Rl1t.cjs +0 -316
  569. package/dist/resolve-DC98Rl1t.cjs.map +0 -1
  570. package/dist/rollback-BkIkE8Qe.mjs +0 -136
  571. package/dist/rollback-BkIkE8Qe.mjs.map +0 -1
  572. package/dist/rollback-DBfLvC8k.cjs +0 -165
  573. package/dist/rollback-DBfLvC8k.cjs.map +0 -1
  574. package/dist/rolldown-runtime-BhDjJH2R.mjs +0 -15
  575. package/dist/run-BJLIerMM.mjs +0 -133
  576. package/dist/run-BJLIerMM.mjs.map +0 -1
  577. package/dist/run-fVZ-rLnc.cjs +0 -174
  578. package/dist/run-fVZ-rLnc.cjs.map +0 -1
  579. package/dist/runtime-CLz3bf07.d.mts +0 -82
  580. package/dist/runtime-CLz3bf07.d.mts.map +0 -1
  581. package/dist/runtime-CUWf0IUk.d.cts +0 -82
  582. package/dist/runtime-CUWf0IUk.d.cts.map +0 -1
  583. package/dist/s3-BwhQk3QM.mjs +0 -215
  584. package/dist/s3-BwhQk3QM.mjs.map +0 -1
  585. package/dist/s3-DLp0V-Ox.cjs +0 -215
  586. package/dist/s3-DLp0V-Ox.cjs.map +0 -1
  587. package/dist/sandbox/config-worker.cjs +0 -43
  588. package/dist/sandbox/config-worker.cjs.map +0 -1
  589. package/dist/sandbox/config-worker.d.cts +0 -1
  590. package/dist/sandbox/config-worker.d.mts +0 -1
  591. package/dist/sandbox/config-worker.mjs +0 -44
  592. package/dist/sandbox/config-worker.mjs.map +0 -1
  593. package/dist/sandbox/credentials-worker.cjs +0 -54
  594. package/dist/sandbox/credentials-worker.cjs.map +0 -1
  595. package/dist/sandbox/credentials-worker.d.cts +0 -1
  596. package/dist/sandbox/credentials-worker.d.mts +0 -1
  597. package/dist/sandbox/credentials-worker.mjs +0 -55
  598. package/dist/sandbox/credentials-worker.mjs.map +0 -1
  599. package/dist/sandbox/discover-worker.cjs +0 -47
  600. package/dist/sandbox/discover-worker.cjs.map +0 -1
  601. package/dist/sandbox/discover-worker.d.cts +0 -1
  602. package/dist/sandbox/discover-worker.d.mts +0 -1
  603. package/dist/sandbox/discover-worker.mjs +0 -48
  604. package/dist/sandbox/discover-worker.mjs.map +0 -1
  605. package/dist/sandbox/migrate-worker.cjs +0 -75
  606. package/dist/sandbox/migrate-worker.cjs.map +0 -1
  607. package/dist/sandbox/migrate-worker.d.cts +0 -1
  608. package/dist/sandbox/migrate-worker.d.mts +0 -1
  609. package/dist/sandbox/migrate-worker.mjs +0 -76
  610. package/dist/sandbox/migrate-worker.mjs.map +0 -1
  611. package/dist/sandbox-CHv3OYXg.cjs +0 -165
  612. package/dist/sandbox-CHv3OYXg.cjs.map +0 -1
  613. package/dist/sandbox-CbVB7uOD.mjs +0 -118
  614. package/dist/sandbox-CbVB7uOD.mjs.map +0 -1
  615. package/dist/sandbox-CfpLWTPP.d.mts +0 -104
  616. package/dist/sandbox-CfpLWTPP.d.mts.map +0 -1
  617. package/dist/sandbox-D1XeNEJ9.d.cts +0 -104
  618. package/dist/sandbox-D1XeNEJ9.d.cts.map +0 -1
  619. package/dist/schemas-BObwxB_t.cjs +0 -6017
  620. package/dist/schemas-BObwxB_t.cjs.map +0 -1
  621. package/dist/schemas-D-xeKJDD.mjs +0 -5916
  622. package/dist/schemas-D-xeKJDD.mjs.map +0 -1
  623. package/dist/secretsManager-CQORubp9.mjs +0 -97
  624. package/dist/secretsManager-CQORubp9.mjs.map +0 -1
  625. package/dist/secretsManager-RAGcEDX1.cjs +0 -108
  626. package/dist/secretsManager-RAGcEDX1.cjs.map +0 -1
  627. package/dist/seeds-BNHSpjNP.cjs +0 -9096
  628. package/dist/seeds-BNHSpjNP.cjs.map +0 -1
  629. package/dist/seeds-C4bZ8L-T.mjs +0 -8141
  630. package/dist/seeds-C4bZ8L-T.mjs.map +0 -1
  631. package/dist/sniffer-BIBm9dAb.mjs +0 -1825
  632. package/dist/sniffer-BIBm9dAb.mjs.map +0 -1
  633. package/dist/sniffer-Cylp9W2D.cjs +0 -1998
  634. package/dist/sniffer-Cylp9W2D.cjs.map +0 -1
  635. package/dist/sst-CGdjHn2A.mjs +0 -441
  636. package/dist/sst-CGdjHn2A.mjs.map +0 -1
  637. package/dist/sst-DGuHDxVU.cjs +0 -464
  638. package/dist/sst-DGuHDxVU.cjs.map +0 -1
  639. package/dist/stages-CcS9vnNu.mjs +0 -176
  640. package/dist/stages-CcS9vnNu.mjs.map +0 -1
  641. package/dist/stages-DdBV7msu.cjs +0 -176
  642. package/dist/stages-DdBV7msu.cjs.map +0 -1
  643. package/dist/target/public.cjs +0 -15
  644. package/dist/target/public.d.cts +0 -28
  645. package/dist/target/public.d.cts.map +0 -1
  646. package/dist/target/public.d.mts +0 -28
  647. package/dist/target/public.d.mts.map +0 -1
  648. package/dist/target/public.mjs +0 -4
  649. package/dist/terminal-CPHuH4S1.cjs +0 -85
  650. package/dist/terminal-CPHuH4S1.cjs.map +0 -1
  651. package/dist/terminal-iNmAXXjs.mjs +0 -85
  652. package/dist/terminal-iNmAXXjs.mjs.map +0 -1
  653. package/dist/types-BhThob0H.d.mts +0 -7621
  654. package/dist/types-BhThob0H.d.mts.map +0 -1
  655. package/dist/types-DwoLHelT.d.cts +0 -7622
  656. package/dist/types-DwoLHelT.d.cts.map +0 -1
  657. package/dist/utils-D2Nk1Nv2.cjs +0 -205
  658. package/dist/utils-D2Nk1Nv2.cjs.map +0 -1
  659. package/dist/utils-D_fxUqvU.mjs +0 -156
  660. package/dist/utils-D_fxUqvU.mjs.map +0 -1
  661. package/dist/vitest.cjs +0 -65
  662. package/dist/vitest.cjs.map +0 -1
  663. package/dist/vitest.d.cts +0 -29
  664. package/dist/vitest.d.cts.map +0 -1
  665. package/dist/vitest.d.mts +0 -29
  666. package/dist/vitest.d.mts.map +0 -1
  667. package/dist/vitest.mjs +0 -65
  668. package/dist/vitest.mjs.map +0 -1
  669. package/dist/workerRuntime-BXfhbe13.cjs +0 -108
  670. package/dist/workerRuntime-BXfhbe13.cjs.map +0 -1
  671. package/dist/workerRuntime-CsOyBRx2.mjs +0 -79
  672. package/dist/workerRuntime-CsOyBRx2.mjs.map +0 -1
  673. package/dist/workspace-D5CpOp1y.mjs +0 -2108
  674. package/dist/workspace-D5CpOp1y.mjs.map +0 -1
  675. package/dist/workspace-DRjdu1OY.cjs +0 -2514
  676. package/dist/workspace-DRjdu1OY.cjs.map +0 -1
@@ -0,0 +1,1883 @@
1
+ import { loadWorkspaceConfig } from "./config-Bbu1JKvf.mjs";
2
+ import { dirname, join, relative } from "node:path";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { spawn } from "node:child_process";
5
+ import fg from "fast-glob";
6
+ import kebabCase from "lodash.kebabcase";
7
+ import { Endpoint } from "@geekmidas/constructs/endpoints";
8
+ import { fileURLToPath } from "node:url";
9
+ import { StandardSchemaJsonSchema, getRegisteredZodJsonSchemas, getSchemaMetadata } from "@geekmidas/schema/conversion";
10
+
11
+ //#region src/types.ts
12
+ function isPartitionedRoutes(routes) {
13
+ return typeof routes === "object" && routes !== null && !Array.isArray(routes) && "paths" in routes;
14
+ }
15
+
16
+ //#endregion
17
+ //#region src/generators/Generator.ts
18
+ /**
19
+ * Zod v4 maintains a process-wide registry of schemas registered via
20
+ * `.meta({ id })`. When we cache-bust user module imports (by appending a
21
+ * `?t=timestamp` query), those modules re-execute and try to register the
22
+ * same ids again, which throws `ID X already exists in the registry`.
23
+ *
24
+ * Clearing the registry in the CLI process is safe: the user's running
25
+ * server lives in a subprocess and has its own isolated registry.
26
+ *
27
+ * Exported for tests.
28
+ */
29
+ function clearZodGlobalRegistry() {
30
+ const registry = globalThis.__zod_globalRegistry;
31
+ if (registry && typeof registry.clear === "function") registry.clear();
32
+ }
33
+ var ConstructGenerator = class {
34
+ static async build(context, outputDir, generator, patterns, options) {
35
+ const constructs = await generator.load(patterns);
36
+ return generator.build(context, constructs, outputDir, options);
37
+ }
38
+ async load(patterns, cwd = process.cwd(), bustCache = false) {
39
+ const logger = console;
40
+ let globPatterns;
41
+ let partitionFn;
42
+ if (isPartitionedRoutes(patterns)) {
43
+ globPatterns = Array.isArray(patterns.paths) ? patterns.paths : [patterns.paths];
44
+ partitionFn = patterns.partition;
45
+ } else globPatterns = Array.isArray(patterns) ? patterns : patterns ? [patterns] : [];
46
+ const files = fg.stream(globPatterns, {
47
+ cwd,
48
+ absolute: true
49
+ });
50
+ if (bustCache) clearZodGlobalRegistry();
51
+ const constructs = [];
52
+ for await (const f of files) try {
53
+ const file = f.toString();
54
+ const importPath = bustCache ? `${file}?t=${Date.now()}` : file;
55
+ const module = await import(importPath);
56
+ const partition = partitionFn ? partitionFn(file) : void 0;
57
+ for (const [key, construct] of Object.entries(module)) if (this.isConstruct(construct)) constructs.push({
58
+ key,
59
+ name: kebabCase(key),
60
+ construct,
61
+ path: {
62
+ absolute: file,
63
+ relative: relative(process.cwd(), file)
64
+ },
65
+ partition
66
+ });
67
+ } catch (error) {
68
+ const err = error;
69
+ logger.error(`Failed to load ${f}: ${err.message}`);
70
+ if (err.stack) logger.error(err.stack);
71
+ throw error;
72
+ }
73
+ return constructs;
74
+ }
75
+ };
76
+
77
+ //#endregion
78
+ //#region src/build/endpoint-analyzer.ts
79
+ /**
80
+ * Analyze an endpoint to extract its features
81
+ */
82
+ function analyzeEndpointFeatures(endpoint) {
83
+ return {
84
+ hasAuth: !!endpoint.authorizer,
85
+ hasServices: endpoint.services.length > 0,
86
+ hasDatabase: !!endpoint.databaseService,
87
+ hasBodyValidation: !!endpoint.input?.body,
88
+ hasQueryValidation: !!endpoint.input?.query,
89
+ hasParamValidation: !!endpoint.input?.params,
90
+ hasAudits: (endpoint.audits?.length ?? 0) > 0,
91
+ hasEvents: (endpoint.events?.length ?? 0) > 0,
92
+ hasRateLimit: !!endpoint.rateLimit,
93
+ hasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,
94
+ hasOutputValidation: !!endpoint.outputSchema
95
+ };
96
+ }
97
+ /**
98
+ * Determine the optimization tier for an endpoint based on its features
99
+ */
100
+ function determineEndpointTier(features) {
101
+ const { hasAuth, hasServices, hasDatabase, hasAudits, hasEvents, hasRateLimit, hasRls } = features;
102
+ if (!hasAuth && !hasServices && !hasDatabase && !hasAudits && !hasEvents && !hasRateLimit && !hasRls) return "minimal";
103
+ if (hasAudits || hasRls || hasRateLimit) return "full";
104
+ return "standard";
105
+ }
106
+ /**
107
+ * Perform complete analysis of an endpoint
108
+ */
109
+ function analyzeEndpoint(endpoint, exportName) {
110
+ const features = analyzeEndpointFeatures(endpoint);
111
+ const tier = determineEndpointTier(features);
112
+ return {
113
+ route: endpoint.route,
114
+ method: endpoint.method,
115
+ exportName,
116
+ features,
117
+ tier,
118
+ serviceNames: endpoint.services.map((s) => s.serviceName),
119
+ databaseServiceName: endpoint.databaseService?.serviceName
120
+ };
121
+ }
122
+ /**
123
+ * Generate a summary of endpoint analysis for logging
124
+ */
125
+ function summarizeAnalysis(analyses) {
126
+ const byTier = {
127
+ minimal: 0,
128
+ standard: 0,
129
+ full: 0
130
+ };
131
+ const byFeature = {
132
+ hasAuth: 0,
133
+ hasServices: 0,
134
+ hasDatabase: 0,
135
+ hasBodyValidation: 0,
136
+ hasQueryValidation: 0,
137
+ hasParamValidation: 0,
138
+ hasAudits: 0,
139
+ hasEvents: 0,
140
+ hasRateLimit: 0,
141
+ hasRls: 0,
142
+ hasOutputValidation: 0
143
+ };
144
+ for (const analysis of analyses) {
145
+ byTier[analysis.tier]++;
146
+ for (const [feature, enabled] of Object.entries(analysis.features)) if (enabled) byFeature[feature]++;
147
+ }
148
+ return {
149
+ total: analyses.length,
150
+ byTier,
151
+ byFeature
152
+ };
153
+ }
154
+
155
+ //#endregion
156
+ //#region src/build/handler-templates.ts
157
+ /**
158
+ * Generate validator references for an endpoint
159
+ */
160
+ function generateValidators(exportName, features) {
161
+ const validators = [];
162
+ if (features.hasBodyValidation) validators.push(`validateBody(${exportName})`);
163
+ if (features.hasQueryValidation) validators.push(`validateQuery(${exportName})`);
164
+ if (features.hasParamValidation) validators.push(`validateParams(${exportName})`);
165
+ return validators.length > 0 ? `\n ${validators.join(",\n ")},` : "";
166
+ }
167
+ /**
168
+ * Generate a minimal handler (near-raw-Hono performance)
169
+ *
170
+ * Used for: Health checks, public endpoints with no services
171
+ */
172
+ function generateMinimalHandler(analysis) {
173
+ const { exportName, features } = analysis;
174
+ const method = analysis.method.toLowerCase();
175
+ const validators = generateValidators(exportName, features);
176
+ const hasValidators = validators.length > 0;
177
+ if (!hasValidators && !features.hasOutputValidation) return `
178
+ // Minimal handler: ${analysis.route} (${analysis.method})
179
+ app.${method}('${analysis.route}', async (c) => {
180
+ const result = await ${exportName}.handler(
181
+ {
182
+ services: {},
183
+ logger,
184
+ body: undefined,
185
+ query: undefined,
186
+ params: undefined,
187
+ session: undefined,
188
+ header: Endpoint.createHeaders(c.req.header()),
189
+ cookie: Endpoint.createCookies(c.req.header().cookie),
190
+ auditor: undefined,
191
+ db: undefined,
192
+ } as any,
193
+ { getMetadata: () => ({}) } as any,
194
+ );
195
+ return c.json(result, ${exportName}.status as any);
196
+ });`;
197
+ return `
198
+ // Minimal handler with validation: ${analysis.route} (${analysis.method})
199
+ app.${method}('${analysis.route}',${validators}
200
+ async (c) => {
201
+ const result = await ${exportName}.handler(
202
+ {
203
+ services: {},
204
+ logger,
205
+ body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
206
+ query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
207
+ params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
208
+ session: undefined,
209
+ header: Endpoint.createHeaders(c.req.header()),
210
+ cookie: Endpoint.createCookies(c.req.header().cookie),
211
+ auditor: undefined,
212
+ db: undefined,
213
+ } as any,
214
+ { getMetadata: () => ({}) } as any,
215
+ );
216
+ ${features.hasOutputValidation ? `const output = await ${exportName}.parseOutput(result);
217
+ return c.json(output, ${exportName}.status as any);` : `return c.json(result, ${exportName}.status as any);`}
218
+ }
219
+ );`;
220
+ }
221
+ /**
222
+ * Generate a standard handler (auth and/or services)
223
+ *
224
+ * Used for: Authenticated endpoints, endpoints with services
225
+ */
226
+ function generateStandardHandler(analysis) {
227
+ const { exportName, features } = analysis;
228
+ const method = analysis.method.toLowerCase();
229
+ const validators = generateValidators(exportName, features);
230
+ let serviceResolution = "";
231
+ if (features.hasServices || features.hasDatabase) serviceResolution = `
232
+ const services = await serviceDiscovery.register(${exportName}.services);
233
+ ${features.hasDatabase ? `const db = ${exportName}.databaseService
234
+ ? (await serviceDiscovery.register([${exportName}.databaseService]) as any)[${exportName}.databaseService.serviceName]
235
+ : undefined;` : "const db = undefined;"}`;
236
+ else serviceResolution = `
237
+ const services = {};
238
+ const db = undefined;`;
239
+ let authCode = "";
240
+ if (features.hasAuth) authCode = `
241
+ // Authentication
242
+ const session = await ${exportName}.getSession({
243
+ services,
244
+ logger,
245
+ header,
246
+ cookie,
247
+ ...(db !== undefined && { db }),
248
+ } as any);
249
+
250
+ const isAuthorized = await ${exportName}.authorize({
251
+ header,
252
+ cookie,
253
+ services,
254
+ logger,
255
+ session,
256
+ } as any);
257
+
258
+ if (!isAuthorized) {
259
+ return c.json({ error: 'Unauthorized' }, 401);
260
+ }`;
261
+ let eventCode = "";
262
+ if (features.hasEvents) eventCode = `
263
+ // Publish events on success
264
+ if (Endpoint.isSuccessStatus(${exportName}.status)) {
265
+ await (publishConstructEvents as any)(
266
+ ${exportName},
267
+ result,
268
+ serviceDiscovery,
269
+ logger,
270
+ );
271
+ }`;
272
+ return `
273
+ // Standard handler: ${analysis.route} (${analysis.method})
274
+ app.${method}('${analysis.route}',${validators}
275
+ async (c) => {
276
+ const headerValues = c.req.header();
277
+ const header = Endpoint.createHeaders(headerValues);
278
+ const cookie = Endpoint.createCookies(headerValues.cookie);
279
+ ${serviceResolution}
280
+ ${authCode}
281
+
282
+ const responseBuilder = new ResponseBuilder();
283
+ const result = await ${exportName}.handler(
284
+ {
285
+ services,
286
+ logger,
287
+ body: ${features.hasBodyValidation ? "(c.req.valid as any)('json')" : "undefined"},
288
+ query: ${features.hasQueryValidation ? "(c.req.valid as any)('query')" : "undefined"},
289
+ params: ${features.hasParamValidation ? "(c.req.valid as any)('param')" : "undefined"},
290
+ session: ${features.hasAuth ? "session" : "undefined"},
291
+ header,
292
+ cookie,
293
+ auditor: undefined,
294
+ db,
295
+ } as any,
296
+ responseBuilder,
297
+ );
298
+
299
+ let data = result;
300
+ let metadata = responseBuilder.getMetadata();
301
+
302
+ if (Endpoint.hasMetadata(result)) {
303
+ data = result.data;
304
+ metadata = result.metadata;
305
+ }
306
+
307
+ ${features.hasOutputValidation ? `const output = ${exportName}.outputSchema
308
+ ? await ${exportName}.parseOutput(data)
309
+ : data;` : "const output = data;"}
310
+ ${eventCode}
311
+
312
+ const status = (metadata.status ?? ${exportName}.status) as any;
313
+ return c.json(output, status);
314
+ }
315
+ );`;
316
+ }
317
+ /**
318
+ * Generate validators.ts - Shared validator middleware factories
319
+ */
320
+ function generateValidatorsFile(analyses) {
321
+ const needsBody = analyses.some((a) => a.features.hasBodyValidation);
322
+ const needsQuery = analyses.some((a) => a.features.hasQueryValidation);
323
+ const needsParams = analyses.some((a) => a.features.hasParamValidation);
324
+ if (!needsBody && !needsQuery && !needsParams) return `// No validators needed for this build\nexport {};\n`;
325
+ const exports = [];
326
+ const factories = [];
327
+ if (needsBody) {
328
+ exports.push("validateBody");
329
+ factories.push(`
330
+ export const validateBody = (endpoint: any) =>
331
+ validator('json', async (value, c) => {
332
+ if (!endpoint.input?.body) return undefined;
333
+ const parsed = await Endpoint.validate(endpoint.input.body, value);
334
+ if (parsed.issues) return c.json(parsed.issues, 422);
335
+ return parsed.value;
336
+ });`);
337
+ }
338
+ if (needsQuery) {
339
+ exports.push("validateQuery");
340
+ factories.push(`
341
+ export const validateQuery = (endpoint: any) =>
342
+ validator('query', async (_, c) => {
343
+ if (!endpoint.input?.query) return undefined;
344
+ const rawQuery = Object.fromEntries(new URL(c.req.url).searchParams);
345
+ const parsed = await Endpoint.validate(endpoint.input.query, rawQuery);
346
+ if (parsed.issues) return c.json(parsed.issues, 422);
347
+ return parsed.value;
348
+ });`);
349
+ }
350
+ if (needsParams) {
351
+ exports.push("validateParams");
352
+ factories.push(`
353
+ export const validateParams = (endpoint: any) =>
354
+ validator('param', async (params, c) => {
355
+ if (!endpoint.input?.params) return undefined;
356
+ const parsed = await Endpoint.validate(endpoint.input.params, params);
357
+ if (parsed.issues) return c.json(parsed.issues, 422);
358
+ return parsed.value;
359
+ });`);
360
+ }
361
+ return `/**
362
+ * Generated validator middleware factories
363
+ * Shared across all endpoint tiers that need validation
364
+ */
365
+ import { validator } from 'hono/validator';
366
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
367
+ ${factories.join("\n")}
368
+ `;
369
+ }
370
+ /**
371
+ * Generate a standalone minimal endpoint file
372
+ */
373
+ function generateMinimalEndpointFile(analysis, endpointImport) {
374
+ const { exportName, features } = analysis;
375
+ const needsValidators = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation;
376
+ const validatorImport = needsValidators ? generateValidatorImportsForEndpoint(analysis) : "";
377
+ const handler = generateMinimalHandler(analysis);
378
+ return `/**
379
+ * Minimal endpoint: ${analysis.route} (${analysis.method})
380
+ * Near-raw-Hono performance
381
+ */
382
+ import type { Hono } from 'hono';
383
+ import type { Logger } from '@geekmidas/logger';
384
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
385
+ ${validatorImport}
386
+ import { ${exportName} } from '${endpointImport.importPath}';
387
+
388
+ export function setup${capitalize(exportName)}(
389
+ app: Hono,
390
+ logger: Logger,
391
+ ): void {
392
+ ${handler}
393
+ }
394
+ `;
395
+ }
396
+ /**
397
+ * Generate a standalone standard endpoint file
398
+ */
399
+ function generateStandardEndpointFile(analysis, endpointImport) {
400
+ const { exportName, features } = analysis;
401
+ const needsValidators = features.hasBodyValidation || features.hasQueryValidation || features.hasParamValidation;
402
+ const validatorImport = needsValidators ? generateValidatorImportsForEndpoint(analysis) : "";
403
+ const eventsImport = features.hasEvents ? `import { publishConstructEvents } from '@geekmidas/constructs/endpoints';` : "";
404
+ const handler = generateStandardHandler(analysis);
405
+ return `/**
406
+ * Standard endpoint: ${analysis.route} (${analysis.method})
407
+ * Auth and/or services enabled
408
+ */
409
+ import type { Hono } from 'hono';
410
+ import type { Logger } from '@geekmidas/logger';
411
+ import type { ServiceDiscovery } from '@geekmidas/services';
412
+ import { Endpoint, ResponseBuilder } from '@geekmidas/constructs/endpoints';
413
+ ${eventsImport}
414
+ ${validatorImport}
415
+ import { ${exportName} } from '${endpointImport.importPath}';
416
+
417
+ export function setup${capitalize(exportName)}(
418
+ app: Hono,
419
+ serviceDiscovery: ServiceDiscovery<any, any>,
420
+ logger: Logger,
421
+ ): void {
422
+ ${handler}
423
+ }
424
+ `;
425
+ }
426
+ /**
427
+ * Generate a standalone full endpoint file
428
+ */
429
+ function generateFullEndpointFile(analysis, endpointImport) {
430
+ const { exportName } = analysis;
431
+ return `/**
432
+ * Full endpoint: ${analysis.route} (${analysis.method})
433
+ * Complex features: audits, RLS, rate limiting
434
+ */
435
+ import type { Hono } from 'hono';
436
+ import type { ServiceDiscovery } from '@geekmidas/services';
437
+ import { HonoEndpoint } from '@geekmidas/constructs/hono';
438
+ import { ${exportName} } from '${endpointImport.importPath}';
439
+
440
+ export function setup${capitalize(exportName)}(
441
+ app: Hono,
442
+ serviceDiscovery: ServiceDiscovery<any, any>,
443
+ openApiOptions: any,
444
+ ): void {
445
+ HonoEndpoint.addRoutes([${exportName}] as any, serviceDiscovery, app, openApiOptions);
446
+ }
447
+ `;
448
+ }
449
+ /**
450
+ * Generate tier index file that imports and calls all endpoint setup functions
451
+ */
452
+ function generateTierIndexFile(tier, analyses) {
453
+ const tierEndpoints = analyses.filter((a) => a.tier === tier);
454
+ if (tierEndpoints.length === 0) {
455
+ if (tier === "minimal") return `// No minimal-tier endpoints in this build
456
+ import type { Hono } from 'hono';
457
+ import type { Logger } from '@geekmidas/logger';
458
+
459
+ export function setupMinimalEndpoints(
460
+ _app: Hono,
461
+ _logger: Logger,
462
+ ): void {
463
+ // No minimal endpoints
464
+ }
465
+ `;
466
+ if (tier === "standard") return `// No standard-tier endpoints in this build
467
+ import type { Hono } from 'hono';
468
+ import type { Logger } from '@geekmidas/logger';
469
+ import type { ServiceDiscovery } from '@geekmidas/services';
470
+
471
+ export function setupStandardEndpoints(
472
+ _app: Hono,
473
+ _serviceDiscovery: ServiceDiscovery<any, any>,
474
+ _logger: Logger,
475
+ ): void {
476
+ // No standard endpoints
477
+ }
478
+ `;
479
+ return `// No full-tier endpoints in this build
480
+ import type { Hono } from 'hono';
481
+ import type { ServiceDiscovery } from '@geekmidas/services';
482
+
483
+ export function setupFullEndpoints(
484
+ _app: Hono,
485
+ _serviceDiscovery: ServiceDiscovery<any, any>,
486
+ _enableOpenApi: boolean,
487
+ ): void {
488
+ // No full endpoints
489
+ }
490
+ `;
491
+ }
492
+ const imports = tierEndpoints.map((a) => `import { setup${capitalize(a.exportName)} } from './${a.exportName}.js';`).join("\n");
493
+ if (tier === "minimal") {
494
+ const calls$1 = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, logger);`).join("\n");
495
+ return `/**
496
+ * Minimal-tier endpoint index (${tierEndpoints.length} endpoints)
497
+ * Near-raw-Hono performance
498
+ */
499
+ import type { Hono } from 'hono';
500
+ import type { Logger } from '@geekmidas/logger';
501
+ ${imports}
502
+
503
+ export function setupMinimalEndpoints(
504
+ app: Hono,
505
+ logger: Logger,
506
+ ): void {
507
+ ${calls$1}
508
+ }
509
+ `;
510
+ }
511
+ if (tier === "standard") {
512
+ const calls$1 = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, logger);`).join("\n");
513
+ return `/**
514
+ * Standard-tier endpoint index (${tierEndpoints.length} endpoints)
515
+ * Auth and/or services enabled
516
+ */
517
+ import type { Hono } from 'hono';
518
+ import type { Logger } from '@geekmidas/logger';
519
+ import type { ServiceDiscovery } from '@geekmidas/services';
520
+ ${imports}
521
+
522
+ export function setupStandardEndpoints(
523
+ app: Hono,
524
+ serviceDiscovery: ServiceDiscovery<any, any>,
525
+ logger: Logger,
526
+ ): void {
527
+ ${calls$1}
528
+ }
529
+ `;
530
+ }
531
+ const calls = tierEndpoints.map((a) => ` setup${capitalize(a.exportName)}(app, serviceDiscovery, openApiOptions);`).join("\n");
532
+ return `/**
533
+ * Full-tier endpoint index (${tierEndpoints.length} endpoints)
534
+ * Complex features: audits, RLS, rate limiting
535
+ */
536
+ import type { Hono } from 'hono';
537
+ import type { ServiceDiscovery } from '@geekmidas/services';
538
+ ${imports}
539
+
540
+ export function setupFullEndpoints(
541
+ app: Hono,
542
+ serviceDiscovery: ServiceDiscovery<any, any>,
543
+ enableOpenApi: boolean,
544
+ ): void {
545
+ const openApiOptions: any = enableOpenApi ? {
546
+ docsPath: '/__docs',
547
+ openApiOptions: {
548
+ title: 'API Documentation',
549
+ version: '1.0.0',
550
+ description: 'Generated API documentation'
551
+ }
552
+ } : { docsPath: false };
553
+
554
+ ${calls}
555
+ }
556
+ `;
557
+ }
558
+ /**
559
+ * Generate validator imports for a single endpoint
560
+ */
561
+ function generateValidatorImportsForEndpoint(analysis) {
562
+ const imports = [];
563
+ if (analysis.features.hasBodyValidation) imports.push("validateBody");
564
+ if (analysis.features.hasQueryValidation) imports.push("validateQuery");
565
+ if (analysis.features.hasParamValidation) imports.push("validateParams");
566
+ if (imports.length === 0) return "";
567
+ return `import { ${imports.join(", ")} } from '../validators.js';`;
568
+ }
569
+ /**
570
+ * Capitalize first letter
571
+ */
572
+ function capitalize(str) {
573
+ return str.charAt(0).toUpperCase() + str.slice(1);
574
+ }
575
+ /**
576
+ * Generate all endpoint files with nested folder structure (per-endpoint files)
577
+ */
578
+ function generateEndpointFilesNested(analyses, endpointImports) {
579
+ const files = {
580
+ "validators.ts": generateValidatorsFile(analyses),
581
+ "minimal/index.ts": generateTierIndexFile("minimal", analyses),
582
+ "standard/index.ts": generateTierIndexFile("standard", analyses),
583
+ "full/index.ts": generateTierIndexFile("full", analyses),
584
+ "index.ts": generateNestedIndexFile(analyses)
585
+ };
586
+ for (const analysis of analyses) {
587
+ const endpointImport = endpointImports.find((i) => i.exportName === analysis.exportName);
588
+ if (!endpointImport) continue;
589
+ const fileName = `${analysis.tier}/${analysis.exportName}.ts`;
590
+ switch (analysis.tier) {
591
+ case "minimal":
592
+ files[fileName] = generateMinimalEndpointFile(analysis, endpointImport);
593
+ break;
594
+ case "standard":
595
+ files[fileName] = generateStandardEndpointFile(analysis, endpointImport);
596
+ break;
597
+ case "full":
598
+ files[fileName] = generateFullEndpointFile(analysis, endpointImport);
599
+ break;
600
+ }
601
+ }
602
+ return files;
603
+ }
604
+ /**
605
+ * Generate index.ts for nested structure
606
+ */
607
+ function generateNestedIndexFile(analyses) {
608
+ const minimalCount = analyses.filter((a) => a.tier === "minimal").length;
609
+ const standardCount = analyses.filter((a) => a.tier === "standard").length;
610
+ const fullCount = analyses.filter((a) => a.tier === "full").length;
611
+ return `/**
612
+ * Generated optimized endpoints
613
+ *
614
+ * Build-time optimization tiers:
615
+ * - minimal: ${minimalCount} endpoints (near-raw-Hono)
616
+ * - standard: ${standardCount} endpoints (auth/services)
617
+ * - full: ${fullCount} endpoints (audits/rls/rate-limit)
618
+ */
619
+ import type { EnvironmentParser } from '@geekmidas/envkit';
620
+ import type { Logger } from '@geekmidas/logger';
621
+ import type { Hono } from 'hono';
622
+ import { ServiceDiscovery } from '@geekmidas/services';
623
+ import { setupMinimalEndpoints } from './minimal/index.js';
624
+ import { setupStandardEndpoints } from './standard/index.js';
625
+ import { setupFullEndpoints } from './full/index.js';
626
+
627
+ export async function setupEndpoints(
628
+ app: Hono,
629
+ envParser: EnvironmentParser<any>,
630
+ logger: Logger,
631
+ enableOpenApi: boolean = false,
632
+ ): Promise<void> {
633
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
634
+
635
+ // Minimal handlers (${minimalCount} endpoints) - near-raw-Hono performance
636
+ setupMinimalEndpoints(app, logger);
637
+
638
+ // Standard handlers (${standardCount} endpoints) - auth/services
639
+ setupStandardEndpoints(app, serviceDiscovery, logger);
640
+
641
+ // Full handlers (${fullCount} endpoints) - audits/rls/rate-limit
642
+ setupFullEndpoints(app, serviceDiscovery, enableOpenApi);
643
+
644
+ // Add Swagger UI if OpenAPI is enabled
645
+ if (enableOpenApi) {
646
+ try {
647
+ const { swaggerUI } = await import('@hono/swagger-ui');
648
+ app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
649
+ } catch {
650
+ // @hono/swagger-ui not installed, skip Swagger UI
651
+ }
652
+ }
653
+ }
654
+ `;
655
+ }
656
+
657
+ //#endregion
658
+ //#region src/generators/EndpointGenerator.ts
659
+ var EndpointGenerator = class extends ConstructGenerator {
660
+ isConstruct(value) {
661
+ return Endpoint.isEndpoint(value);
662
+ }
663
+ async build(context, constructs, outputDir, options) {
664
+ const provider = options?.provider || "aws-apigatewayv2";
665
+ const enableOpenApi = options?.enableOpenApi || false;
666
+ const logger = console;
667
+ const routes = [];
668
+ if (constructs.length === 0) return routes;
669
+ if (provider === "server") {
670
+ await this.generateEndpointsFile(outputDir, constructs, context);
671
+ const appFile = await this.generateAppFile(outputDir, context);
672
+ routes.push({
673
+ path: "*",
674
+ method: "ALL",
675
+ handler: relative(process.cwd(), appFile),
676
+ authorizer: "none"
677
+ });
678
+ logger.log(`Generated server with ${constructs.length} endpoints${enableOpenApi ? " (OpenAPI enabled)" : ""}`);
679
+ } else if (provider === "aws-lambda") {
680
+ const routesDir = join(outputDir, "routes");
681
+ await mkdir(routesDir, { recursive: true });
682
+ for (const { key, construct, path } of constructs) {
683
+ const handlerFile = await this.generateHandlerFile(routesDir, path.relative, key, "aws-apigatewayv2", construct, context);
684
+ const routeInfo = {
685
+ path: construct._path,
686
+ method: construct.method,
687
+ handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
688
+ timeout: construct.timeout,
689
+ memorySize: construct.memorySize,
690
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
691
+ authorizer: construct.authorizer?.name ?? "none"
692
+ };
693
+ routes.push(routeInfo);
694
+ logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
695
+ }
696
+ } else for (const { key, construct, path } of constructs) {
697
+ const handlerFile = await this.generateHandlerFile(outputDir, path.relative, key, provider, construct, context);
698
+ const routeInfo = {
699
+ path: construct._path,
700
+ method: construct.method,
701
+ handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
702
+ timeout: construct.timeout,
703
+ memorySize: construct.memorySize,
704
+ environment: await construct.getEnvironment({ markOptional: context.markOptional }),
705
+ authorizer: construct.authorizer?.name ?? "none"
706
+ };
707
+ routes.push(routeInfo);
708
+ logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
709
+ }
710
+ return routes;
711
+ }
712
+ async generateHandlerFile(outputDir, sourceFile, exportName, provider, _endpoint, context) {
713
+ const handlerFileName = `${exportName}.ts`;
714
+ const handlerPath = join(outputDir, handlerFileName);
715
+ const relativePath = relative(dirname(handlerPath), sourceFile);
716
+ const importPath = relativePath.replace(/\.ts$/, ".js");
717
+ const relativeEnvParserPath = relative(dirname(handlerPath), context.envParserPath);
718
+ let content;
719
+ switch (provider) {
720
+ case "aws-apigatewayv1":
721
+ content = this.generateAWSApiGatewayV1Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
722
+ break;
723
+ case "aws-apigatewayv2":
724
+ content = this.generateAWSApiGatewayV2Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
725
+ break;
726
+ case "server":
727
+ content = this.generateServerHandler(importPath, exportName);
728
+ break;
729
+ default: throw new Error(`Unsupported provider: ${provider}`);
730
+ }
731
+ await writeFile(handlerPath, content);
732
+ return handlerPath;
733
+ }
734
+ async generateEndpointsFile(outputDir, endpoints, context) {
735
+ const endpointsFileName = "endpoints.ts";
736
+ const endpointsPath = join(outputDir, endpointsFileName);
737
+ const importsByFile = /* @__PURE__ */ new Map();
738
+ for (const { path, key } of endpoints) {
739
+ const relativePath = relative(dirname(endpointsPath), path.relative);
740
+ const importPath = relativePath.replace(/\.ts$/, ".js");
741
+ if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
742
+ importsByFile.get(importPath)?.push(key);
743
+ }
744
+ const endpointImports = Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n");
745
+ const allExportNames = endpoints.map(({ key }) => key);
746
+ if (context.production?.enabled && context.production.optimizedHandlers) return this.generateOptimizedEndpointsFile(endpointsPath, endpoints, endpointImports, allExportNames);
747
+ const content = `import type { EnvironmentParser } from '@geekmidas/envkit';
748
+ import type { Logger } from '@geekmidas/logger';
749
+ import { HonoEndpoint } from '@geekmidas/constructs/hono';
750
+ import { Endpoint } from '@geekmidas/constructs/endpoints';
751
+ import { ServiceDiscovery } from '@geekmidas/services';
752
+ import type { Hono } from 'hono';
753
+ ${endpointImports}
754
+
755
+ export const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any, any, any>[] = [
756
+ ${allExportNames.join(",\n ")}
757
+ ];
758
+
759
+ export async function setupEndpoints(
760
+ app: Hono,
761
+ envParser: EnvironmentParser<any>,
762
+ logger: Logger,
763
+ enableOpenApi: boolean = true,
764
+ ): Promise<void> {
765
+ const serviceDiscovery = ServiceDiscovery.getInstance(envParser);
766
+
767
+ // Configure OpenAPI options based on enableOpenApi flag
768
+ const openApiOptions: any = enableOpenApi ? {
769
+ docsPath: '/__docs',
770
+ openApiOptions: {
771
+ title: 'API Documentation',
772
+ version: '1.0.0',
773
+ description: 'Generated API documentation'
774
+ }
775
+ } : { docsPath: false };
776
+
777
+ HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);
778
+
779
+ // Add Swagger UI if OpenAPI is enabled
780
+ if (enableOpenApi) {
781
+ try {
782
+ const { swaggerUI } = await import('@hono/swagger-ui');
783
+ app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));
784
+ } catch {
785
+ // @hono/swagger-ui not installed, skip Swagger UI
786
+ }
787
+ }
788
+ }
789
+ `;
790
+ await writeFile(endpointsPath, content);
791
+ return endpointsPath;
792
+ }
793
+ /**
794
+ * Generate optimized endpoints files with nested folder structure (per-endpoint files)
795
+ */
796
+ async generateOptimizedEndpointsFile(endpointsPath, endpoints, _endpointImports, _allExportNames) {
797
+ const logger = console;
798
+ const outputDir = dirname(endpointsPath);
799
+ const endpointsDir = join(outputDir, "endpoints");
800
+ await mkdir(join(endpointsDir, "minimal"), { recursive: true });
801
+ await mkdir(join(endpointsDir, "standard"), { recursive: true });
802
+ await mkdir(join(endpointsDir, "full"), { recursive: true });
803
+ const analyses = endpoints.map(({ key, construct }) => analyzeEndpoint(construct, key));
804
+ const endpointImports = endpoints.map(({ key, path }) => {
805
+ const tierDir = join(endpointsDir, "standard");
806
+ const relativePath = relative(tierDir, path.relative);
807
+ const importPath = relativePath.replace(/\.ts$/, ".js");
808
+ return {
809
+ exportName: key,
810
+ importPath
811
+ };
812
+ });
813
+ const summary = summarizeAnalysis(analyses);
814
+ logger.log(`\n📊 Endpoint Analysis:`);
815
+ logger.log(` Total: ${summary.total} endpoints`);
816
+ logger.log(` - Minimal (near-raw-Hono): ${summary.byTier.minimal} endpoints`);
817
+ logger.log(` - Standard (auth/services): ${summary.byTier.standard} endpoints`);
818
+ logger.log(` - Full (audits/rls/rate-limit): ${summary.byTier.full} endpoints`);
819
+ const files = generateEndpointFilesNested(analyses, endpointImports);
820
+ for (const [filename, content] of Object.entries(files)) {
821
+ const filePath = join(endpointsDir, filename);
822
+ await mkdir(dirname(filePath), { recursive: true });
823
+ await writeFile(filePath, content);
824
+ }
825
+ const endpointFiles = Object.keys(files).filter((f) => !f.endsWith("index.ts") && !f.endsWith("validators.ts")).length;
826
+ const indexFiles = Object.keys(files).filter((f) => f.endsWith("index.ts")).length;
827
+ logger.log(` Generated ${endpointFiles} endpoint files + ${indexFiles} index files + validators.ts`);
828
+ return join(endpointsDir, "index.ts");
829
+ }
830
+ async generateAppFile(outputDir, context) {
831
+ if (context.production?.enabled) return this.generateProductionAppFile(outputDir, context);
832
+ const appFileName = "app.ts";
833
+ const appPath = join(outputDir, appFileName);
834
+ const relativeLoggerPath = relative(dirname(appPath), context.loggerPath);
835
+ const relativeEnvParserPath = relative(dirname(appPath), context.envParserPath);
836
+ const telescopeEnabled = context.telescope?.enabled;
837
+ const telescopeWebSocketEnabled = context.telescope?.websocket;
838
+ const usesExternalTelescope = !!context.telescope?.telescopePath;
839
+ const studioEnabled = context.studio?.enabled;
840
+ const usesExternalStudio = !!context.studio?.studioPath;
841
+ let telescopeImports = "";
842
+ if (telescopeEnabled) if (usesExternalTelescope) {
843
+ const relativeTelescopePath = relative(dirname(appPath), context.telescope?.telescopePath);
844
+ telescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';
845
+ import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
846
+ } else telescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
847
+ import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
848
+ let studioImports = "";
849
+ if (studioEnabled) if (usesExternalStudio) {
850
+ const relativeStudioPath = relative(dirname(appPath), context.studio?.studioPath);
851
+ studioImports = `import ${context.studio?.studioImportPattern} from '${relativeStudioPath}';
852
+ import { createStudioApp } from '@geekmidas/studio/server/hono';`;
853
+ } else studioImports = `// Studio requires a configured instance - use studio config path
854
+ // import { createStudioApp } from '@geekmidas/studio/server/hono';`;
855
+ let hooksImports = "";
856
+ let beforeSetupCall = "";
857
+ let afterSetupCall = "";
858
+ if (context.hooks?.serverHooksPath) {
859
+ const relativeHooksPath = relative(dirname(appPath), context.hooks.serverHooksPath);
860
+ hooksImports = `import * as serverHooks from '${relativeHooksPath}';`;
861
+ beforeSetupCall = `
862
+ // Call beforeSetup hook if defined
863
+ if (typeof serverHooks.beforeSetup === 'function') {
864
+ await serverHooks.beforeSetup(honoApp, { envParser, logger });
865
+ }
866
+ `;
867
+ afterSetupCall = `
868
+ // Call afterSetup hook if defined
869
+ if (typeof serverHooks.afterSetup === 'function') {
870
+ await serverHooks.afterSetup(honoApp, { envParser, logger });
871
+ }
872
+ `;
873
+ }
874
+ const telescopeWebSocketSetupCode = telescopeWebSocketEnabled ? `
875
+ // Setup WebSocket for real-time telescope updates
876
+ try {
877
+ const { createNodeWebSocket } = await import('@hono/node-ws');
878
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });
879
+ // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)
880
+ honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({
881
+ onOpen: (_event: Event, ws: any) => {
882
+ telescope.addWsClient(ws);
883
+ },
884
+ onClose: (_event: Event, ws: any) => {
885
+ telescope.removeWsClient(ws);
886
+ },
887
+ onMessage: (event: MessageEvent, ws: any) => {
888
+ try {
889
+ const data = JSON.parse(event.data);
890
+ if (data.type === 'ping') {
891
+ ws.send(JSON.stringify({ type: 'pong' }));
892
+ }
893
+ } catch {
894
+ // Ignore invalid messages
895
+ }
896
+ },
897
+ })));
898
+ // Store injectWebSocket for server entry to call after serve()
899
+ (honoApp as any).__injectWebSocket = injectWebSocket;
900
+ logger.info('Telescope WebSocket enabled');
901
+ } catch (e) {
902
+ logger.warn({ error: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');
903
+ }
904
+ ` : "";
905
+ let telescopeSetup = "";
906
+ if (telescopeEnabled) if (usesExternalTelescope) telescopeSetup = `
907
+ ${telescopeWebSocketSetupCode}
908
+ // Add telescope middleware (before endpoints to capture all requests)
909
+ honoApp.use('*', createMiddleware(telescope));
910
+
911
+ // Mount telescope UI
912
+ const telescopeUI = createUI(telescope);
913
+ honoApp.route('${context.telescope?.path}', telescopeUI);
914
+ `;
915
+ else telescopeSetup = `
916
+ // Setup Telescope for debugging/monitoring
917
+ const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });
918
+ const telescope = new Telescope({
919
+ enabled: true,
920
+ path: '${context.telescope?.path}',
921
+ ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},
922
+ recordBody: ${context.telescope?.recordBody},
923
+ storage: telescopeStorage,
924
+ });
925
+ ${telescopeWebSocketSetupCode}
926
+ // Add telescope middleware (before endpoints to capture all requests)
927
+ honoApp.use('*', createMiddleware(telescope));
928
+
929
+ // Mount telescope UI
930
+ const telescopeUI = createUI(telescope);
931
+ honoApp.route('${context.telescope?.path}', telescopeUI);
932
+ `;
933
+ let studioSetup = "";
934
+ if (studioEnabled && usesExternalStudio) studioSetup = `
935
+ // Mount Studio data browser UI
936
+ const studioApp = createStudioApp(studio);
937
+ honoApp.route('${context.studio?.path}', studioApp);
938
+ `;
939
+ const content = `/**
940
+ * Generated server application
941
+ *
942
+ * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
943
+ * The subscriber polling mechanism is not production-ready.
944
+ * For production, use AWS Lambda with SQS/SNS event sources.
945
+ */
946
+ import { Hono } from 'hono';
947
+ import type { Hono as HonoType } from 'hono';
948
+ import { setupEndpoints } from './endpoints.js';
949
+ import { setupSubscribers } from './subscribers.js';
950
+ import { setupQueues } from './queues.js';
951
+ import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
952
+ import ${context.loggerImportPattern} from '${relativeLoggerPath}';
953
+ ${telescopeImports}
954
+ ${studioImports}
955
+ ${hooksImports}
956
+
957
+ export interface ServerApp {
958
+ app: HonoType;
959
+ start: (options?: {
960
+ port?: number;
961
+ serve: (app: HonoType, port: number) => void | Promise<void>;
962
+ }) => Promise<void>;
963
+ }
964
+
965
+ /**
966
+ * Create and configure the Hono application
967
+ *
968
+ * @param app - Optional Hono app instance to configure (creates new one if not provided)
969
+ * @param enableOpenApi - Enable OpenAPI documentation (default: true)
970
+ * @returns Server app with configured Hono app and start function
971
+ *
972
+ * @example
973
+ * // With Bun
974
+ * import { createApp } from './.gkm/server/app.js';
975
+ *
976
+ * const { app, start } = await createApp();
977
+ *
978
+ * await start({
979
+ * port: 3000,
980
+ * serve: (app, port) => {
981
+ * Bun.serve({ port, fetch: app.fetch });
982
+ * }
983
+ * });
984
+ *
985
+ * @example
986
+ * // With Node.js (using @hono/node-server)
987
+ * import { serve } from '@hono/node-server';
988
+ * import { createApp } from './.gkm/server/app.js';
989
+ *
990
+ * const { app, start } = await createApp();
991
+ *
992
+ * await start({
993
+ * port: 3000,
994
+ * serve: (app, port) => {
995
+ * serve({ fetch: app.fetch, port });
996
+ * }
997
+ * });
998
+ */
999
+ export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
1000
+ const honoApp = app || new Hono();
1001
+ ${telescopeSetup}${beforeSetupCall}${studioSetup}
1002
+ // Setup HTTP endpoints
1003
+ await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
1004
+ ${afterSetupCall}
1005
+
1006
+ return {
1007
+ app: honoApp,
1008
+ async start(options) {
1009
+ if (!options?.serve) {
1010
+ throw new Error(
1011
+ 'serve function is required. Pass a serve function for your runtime:\\n' +
1012
+ ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1013
+ ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1014
+ );
1015
+ }
1016
+
1017
+ const port = options.port ?? 3000;
1018
+
1019
+ // Start subscribers in background (non-blocking, local development only)
1020
+ await setupSubscribers(envParser, logger).catch((error) => {
1021
+ logger.error({ error }, 'Failed to start subscribers');
1022
+ });
1023
+
1024
+ // Start queue workers in background (non-blocking, local development only)
1025
+ await setupQueues(envParser, logger).catch((error) => {
1026
+ logger.error({ error }, 'Failed to start queue workers');
1027
+ });
1028
+
1029
+ logger.info({ port }, 'Starting server');
1030
+
1031
+ // Start HTTP server using provided serve function
1032
+ await options.serve(honoApp, port);
1033
+
1034
+ logger.info({ port }, 'Server started');
1035
+ }
1036
+ };
1037
+ }
1038
+
1039
+ // Default export for convenience
1040
+ export default createApp;
1041
+ `;
1042
+ await writeFile(appPath, content);
1043
+ return appPath;
1044
+ }
1045
+ generateAWSApiGatewayV1Handler(importPath, exportName, envParserPath, envParserImportPattern) {
1046
+ return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
1047
+ import { ${exportName} } from '${importPath}';
1048
+ import ${envParserImportPattern} from '${envParserPath}';
1049
+
1050
+ const adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});
1051
+
1052
+ export const handler = adapter.handler;
1053
+ `;
1054
+ }
1055
+ generateAWSApiGatewayV2Handler(importPath, exportName, envParserPath, envParserImportPattern) {
1056
+ return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
1057
+ import { ${exportName} } from '${importPath}';
1058
+ import ${envParserImportPattern} from '${envParserPath}';
1059
+
1060
+ const adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});
1061
+
1062
+ export const handler = adapter.handler;
1063
+ `;
1064
+ }
1065
+ generateServerHandler(importPath, exportName) {
1066
+ return `import { ${exportName} } from '${importPath}';
1067
+
1068
+ // Server handler - implement based on your server framework
1069
+ export const handler = ${exportName};
1070
+ `;
1071
+ }
1072
+ /**
1073
+ * Generate a production-optimized app.ts file
1074
+ * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown
1075
+ */
1076
+ async generateProductionAppFile(outputDir, context) {
1077
+ const appFileName = "app.ts";
1078
+ const appPath = join(outputDir, appFileName);
1079
+ const relativeLoggerPath = relative(dirname(appPath), context.loggerPath);
1080
+ const relativeEnvParserPath = relative(dirname(appPath), context.envParserPath);
1081
+ const production = context.production;
1082
+ const healthCheckPath = production.healthCheck;
1083
+ const enableGracefulShutdown = production.gracefulShutdown;
1084
+ const enableOpenApi = production.openapi;
1085
+ const includeSubscribers = production.subscribers === "include";
1086
+ let hooksImports = "";
1087
+ let beforeSetupCall = "";
1088
+ let afterSetupCall = "";
1089
+ if (context.hooks?.serverHooksPath) {
1090
+ const relativeHooksPath = relative(dirname(appPath), context.hooks.serverHooksPath);
1091
+ hooksImports = `import * as serverHooks from '${relativeHooksPath}';`;
1092
+ beforeSetupCall = `
1093
+ // Call beforeSetup hook if defined
1094
+ if (typeof serverHooks.beforeSetup === 'function') {
1095
+ await serverHooks.beforeSetup(honoApp, { envParser, logger });
1096
+ }
1097
+ `;
1098
+ afterSetupCall = `
1099
+ // Call afterSetup hook if defined
1100
+ if (typeof serverHooks.afterSetup === 'function') {
1101
+ await serverHooks.afterSetup(honoApp, { envParser, logger });
1102
+ }
1103
+ `;
1104
+ }
1105
+ const subscriberSetup = includeSubscribers ? `
1106
+ // Start subscribers in background
1107
+ await setupSubscribers(envParser, logger).catch((error) => {
1108
+ logger.error({ error }, 'Failed to start subscribers');
1109
+ });
1110
+
1111
+ // Start queue workers in background
1112
+ await setupQueues(envParser, logger).catch((error) => {
1113
+ logger.error({ error }, 'Failed to start queue workers');
1114
+ });
1115
+ ` : "";
1116
+ const subscriberImport = includeSubscribers ? `import { setupSubscribers } from './subscribers.js';
1117
+ import { setupQueues } from './queues.js';` : "";
1118
+ const gracefulShutdownCode = enableGracefulShutdown ? `
1119
+ // Graceful shutdown handling
1120
+ let isShuttingDown = false;
1121
+
1122
+ const shutdown = async () => {
1123
+ if (isShuttingDown) return;
1124
+ isShuttingDown = true;
1125
+ logger.info('Graceful shutdown initiated');
1126
+ // Allow in-flight requests to complete (30s timeout)
1127
+ setTimeout(() => process.exit(0), 30000);
1128
+ };
1129
+
1130
+ process.on('SIGTERM', shutdown);
1131
+ process.on('SIGINT', shutdown);
1132
+ ` : "";
1133
+ const endpointsImportPath = production.optimizedHandlers ? "./endpoints/index.js" : "./endpoints.js";
1134
+ const content = `/**
1135
+ * Generated production server application
1136
+ *
1137
+ * This is a production-optimized build without dev tools.
1138
+ * - No Telescope debugging dashboard
1139
+ * - No Studio database browser
1140
+ * - No WebSocket updates
1141
+ * - Includes health checks and graceful shutdown
1142
+ */
1143
+ import { Hono } from 'hono';
1144
+ import type { Hono as HonoType } from 'hono';
1145
+ import { setupEndpoints } from '${endpointsImportPath}';
1146
+ ${subscriberImport}
1147
+ import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
1148
+ import ${context.loggerImportPattern} from '${relativeLoggerPath}';
1149
+ ${hooksImports}
1150
+
1151
+ export interface ServerApp {
1152
+ app: HonoType;
1153
+ start: (options?: {
1154
+ port?: number;
1155
+ serve: (app: HonoType, port: number) => void | Promise<void>;
1156
+ }) => Promise<void>;
1157
+ }
1158
+
1159
+ /**
1160
+ * Create and configure the production Hono application
1161
+ */
1162
+ export async function createApp(app?: HonoType): Promise<ServerApp> {
1163
+ const honoApp = app || new Hono();
1164
+
1165
+ // Health check endpoint (always first)
1166
+ honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
1167
+ honoApp.get('/ready', (c) => c.json({ ready: true }));
1168
+ ${beforeSetupCall}
1169
+ // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})
1170
+ await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});
1171
+ ${afterSetupCall}
1172
+ return {
1173
+ app: honoApp,
1174
+ async start(options) {
1175
+ if (!options?.serve) {
1176
+ throw new Error(
1177
+ 'serve function is required. Pass a serve function for your runtime:\\n' +
1178
+ ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
1179
+ ' - Node: (app, port) => serve({ fetch: app.fetch, port })'
1180
+ );
1181
+ }
1182
+
1183
+ const port = options.port ?? Number(process.env.PORT) ?? 3000;
1184
+ ${gracefulShutdownCode}${subscriberSetup}
1185
+ logger.info({ port }, 'Starting production server');
1186
+
1187
+ // Start HTTP server using provided serve function
1188
+ await options.serve(honoApp, port);
1189
+
1190
+ logger.info({ port }, 'Production server started');
1191
+ }
1192
+ };
1193
+ }
1194
+
1195
+ // Default export for convenience
1196
+ export default createApp;
1197
+ `;
1198
+ await writeFile(appPath, content);
1199
+ await this.generateProductionServerEntry(outputDir);
1200
+ return appPath;
1201
+ }
1202
+ /**
1203
+ * Generate production server.ts entry point
1204
+ */
1205
+ async generateProductionServerEntry(outputDir) {
1206
+ const serverPath = join(outputDir, "server.ts");
1207
+ const content = `#!/usr/bin/env node
1208
+ /**
1209
+ * Production server entry point
1210
+ * Generated by 'gkm build --provider server --production'
1211
+ */
1212
+ import { serve } from '@hono/node-server';
1213
+ import { createApp } from './app.js';
1214
+
1215
+ const port = Number(process.env.PORT) || 3000;
1216
+
1217
+ const { start } = await createApp();
1218
+
1219
+ await start({
1220
+ port,
1221
+ serve: (app, port) => { serve({ fetch: app.fetch, port }); },
1222
+ });
1223
+ `;
1224
+ await writeFile(serverPath, content);
1225
+ }
1226
+ };
1227
+
1228
+ //#endregion
1229
+ //#region src/generators/OpenApiTsGenerator.ts
1230
+ /**
1231
+ * Generates TypeScript OpenAPI module from endpoints.
1232
+ * Outputs:
1233
+ * - securitySchemes: typed security scheme definitions
1234
+ * - endpointAuth: runtime map of endpoints to auth requirements
1235
+ * - paths: TypeScript interface for type-safe fetcher
1236
+ * - schema interfaces: reusable TypeScript types from Zod/Valibot schemas
1237
+ */
1238
+ var OpenApiTsGenerator = class {
1239
+ async generate(endpoints, options = {}) {
1240
+ const { title = "API", version = "1.0.0", description } = options;
1241
+ const endpointInfos = await this.extractEndpointInfos(endpoints);
1242
+ const securitySchemes = this.collectSecuritySchemes(endpointInfos);
1243
+ const endpointAuth = this.buildEndpointAuthMap(endpointInfos);
1244
+ const schemaInterfaces = await this.generateSchemaInterfaces(endpointInfos);
1245
+ const pathsInterface = await this.generatePathsInterface(endpointInfos);
1246
+ return this.buildModule({
1247
+ title,
1248
+ version,
1249
+ description,
1250
+ securitySchemes,
1251
+ endpointAuth,
1252
+ schemaInterfaces,
1253
+ pathsInterface
1254
+ });
1255
+ }
1256
+ async extractEndpointInfos(endpoints) {
1257
+ return endpoints.map((ep) => {
1258
+ const route = ep.route.replace(/:(\w+)/g, "{$1}");
1259
+ const method = ep.method.toUpperCase();
1260
+ const securityScheme = ep.authorizer?.securityScheme;
1261
+ return {
1262
+ endpoint: `${method} ${route}`,
1263
+ route,
1264
+ method,
1265
+ authorizerName: ep.authorizer?.name ?? null,
1266
+ authorizerType: ep.authorizer?.type ?? null,
1267
+ securityScheme: securityScheme ?? null,
1268
+ input: ep.input,
1269
+ output: ep.outputSchema,
1270
+ description: ep.description,
1271
+ tags: ep.tags,
1272
+ operationId: ep.operationId,
1273
+ responseType: ep.responseType ?? "application/json"
1274
+ };
1275
+ });
1276
+ }
1277
+ collectSecuritySchemes(endpointInfos) {
1278
+ const schemes = /* @__PURE__ */ new Map();
1279
+ for (const info of endpointInfos) if (info.authorizerName && !schemes.has(info.authorizerName)) {
1280
+ const scheme = info.securityScheme ?? (info.authorizerType ? this.mapAuthorizerToSecurityScheme(info.authorizerType, info.authorizerName) : null);
1281
+ if (scheme) schemes.set(info.authorizerName, {
1282
+ name: info.authorizerName,
1283
+ type: scheme.type,
1284
+ scheme
1285
+ });
1286
+ }
1287
+ return Array.from(schemes.values());
1288
+ }
1289
+ mapAuthorizerToSecurityScheme(type, _name) {
1290
+ switch (type.toLowerCase()) {
1291
+ case "jwt":
1292
+ case "bearer": return {
1293
+ type: "http",
1294
+ scheme: "bearer",
1295
+ bearerFormat: "JWT"
1296
+ };
1297
+ case "iam":
1298
+ case "aws-sigv4":
1299
+ case "sigv4": return {
1300
+ type: "apiKey",
1301
+ in: "header",
1302
+ name: "Authorization",
1303
+ "x-amazon-apigateway-authtype": "awsSigv4"
1304
+ };
1305
+ case "apikey":
1306
+ case "api-key": return {
1307
+ type: "apiKey",
1308
+ in: "header",
1309
+ name: "X-API-Key"
1310
+ };
1311
+ case "oauth2": return {
1312
+ type: "oauth2",
1313
+ flows: {}
1314
+ };
1315
+ case "oidc":
1316
+ case "openidconnect": return {
1317
+ type: "openIdConnect",
1318
+ openIdConnectUrl: ""
1319
+ };
1320
+ default: return {
1321
+ type: "http",
1322
+ scheme: "bearer"
1323
+ };
1324
+ }
1325
+ }
1326
+ buildEndpointAuthMap(endpointInfos) {
1327
+ const authMap = {};
1328
+ for (const info of endpointInfos) authMap[info.endpoint] = info.authorizerName;
1329
+ return authMap;
1330
+ }
1331
+ async generateSchemaInterfaces(endpointInfos) {
1332
+ const interfaces = [];
1333
+ const generatedNames = /* @__PURE__ */ new Set();
1334
+ const collectedDefs = /* @__PURE__ */ new Map();
1335
+ for (const info of endpointInfos) {
1336
+ const baseName = this.getSchemaBaseName(info);
1337
+ if (info.input?.body) {
1338
+ const name = await this.getSchemaName(info.input.body, `${baseName}Input`);
1339
+ if (!generatedNames.has(name)) {
1340
+ const schema = await this.schemaToInterfaceWithDefs(info.input.body, name, collectedDefs);
1341
+ if (schema) {
1342
+ interfaces.push(schema);
1343
+ generatedNames.add(name);
1344
+ }
1345
+ }
1346
+ }
1347
+ if (info.input?.params) {
1348
+ const name = await this.getSchemaName(info.input.params, `${baseName}Params`);
1349
+ if (!generatedNames.has(name)) {
1350
+ const schema = await this.schemaToInterfaceWithDefs(info.input.params, name, collectedDefs);
1351
+ if (schema) {
1352
+ interfaces.push(schema);
1353
+ generatedNames.add(name);
1354
+ }
1355
+ }
1356
+ }
1357
+ if (info.input?.query) {
1358
+ const name = await this.getSchemaName(info.input.query, `${baseName}Query`);
1359
+ if (!generatedNames.has(name)) {
1360
+ const schema = await this.schemaToInterfaceWithDefs(info.input.query, name, collectedDefs);
1361
+ if (schema) {
1362
+ interfaces.push(schema);
1363
+ generatedNames.add(name);
1364
+ }
1365
+ }
1366
+ }
1367
+ if (info.output) {
1368
+ const name = await this.getSchemaName(info.output, `${baseName}Output`);
1369
+ if (!generatedNames.has(name)) {
1370
+ const schema = await this.schemaToInterfaceWithDefs(info.output, name, collectedDefs);
1371
+ if (schema) {
1372
+ interfaces.push(schema);
1373
+ generatedNames.add(name);
1374
+ }
1375
+ }
1376
+ }
1377
+ }
1378
+ const registrySchemas = await getRegisteredZodJsonSchemas();
1379
+ for (const [rawName, rawSchema] of Object.entries(registrySchemas)) {
1380
+ const defName = this.pascalCase(rawName);
1381
+ if (collectedDefs.has(defName) || generatedNames.has(defName)) continue;
1382
+ const { id: _id, $defs: _defs,...rest } = rawSchema;
1383
+ collectedDefs.set(defName, rest);
1384
+ }
1385
+ for (const [defName, defSchema] of collectedDefs) if (!generatedNames.has(defName)) {
1386
+ const interfaceStr = this.jsonSchemaToInterface(defSchema, defName);
1387
+ interfaces.push(interfaceStr);
1388
+ generatedNames.add(defName);
1389
+ }
1390
+ return interfaces.join("\n\n");
1391
+ }
1392
+ /**
1393
+ * Get the name for a schema, using metadata `id` if available,
1394
+ * otherwise falling back to the provided default name.
1395
+ */
1396
+ async getSchemaName(schema, defaultName) {
1397
+ try {
1398
+ const metadata = await getSchemaMetadata(schema);
1399
+ if (metadata?.id) return this.pascalCase(metadata.id);
1400
+ } catch {}
1401
+ return defaultName;
1402
+ }
1403
+ getSchemaBaseName(info) {
1404
+ if (info.operationId) return this.pascalCase(info.operationId);
1405
+ const routeParts = info.route.replace(/[{}]/g, "").split("/").filter(Boolean).map((part) => this.pascalCase(part));
1406
+ return `${this.pascalCase(info.method.toLowerCase())}${routeParts.join("")}`;
1407
+ }
1408
+ pascalCase(str) {
1409
+ return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toUpperCase());
1410
+ }
1411
+ /**
1412
+ * Convert schema to interface while collecting $defs for nested schemas
1413
+ * with .meta({ id: 'X' }).
1414
+ */
1415
+ async schemaToInterfaceWithDefs(schema, name, collectedDefs) {
1416
+ try {
1417
+ const vendor = schema["~standard"]?.vendor;
1418
+ if (!vendor || !(vendor in StandardSchemaJsonSchema)) return null;
1419
+ const toJsonSchema = StandardSchemaJsonSchema[vendor];
1420
+ const jsonSchema = await toJsonSchema(schema);
1421
+ if (!jsonSchema) return null;
1422
+ if (jsonSchema.$defs && typeof jsonSchema.$defs === "object") {
1423
+ for (const [defName, defSchema] of Object.entries(jsonSchema.$defs)) if (!collectedDefs.has(defName)) {
1424
+ const { id,...schemaWithoutId } = defSchema;
1425
+ collectedDefs.set(defName, schemaWithoutId);
1426
+ }
1427
+ }
1428
+ const { $defs,...schemaWithoutDefs } = jsonSchema;
1429
+ return this.jsonSchemaToInterface(schemaWithoutDefs, name);
1430
+ } catch {
1431
+ return null;
1432
+ }
1433
+ }
1434
+ jsonSchemaToInterface(schema, name) {
1435
+ if (schema.type !== "object" || !schema.properties) {
1436
+ const typeStr = this.jsonSchemaTypeToTs(schema);
1437
+ return `export type ${name} = ${typeStr};`;
1438
+ }
1439
+ const props = [];
1440
+ const required = new Set(schema.required || []);
1441
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1442
+ const isRequired = required.has(propName);
1443
+ const typeStr = this.jsonSchemaTypeToTs(propSchema);
1444
+ const optionalMark = isRequired ? "" : "?";
1445
+ props.push(` ${propName}${optionalMark}: ${typeStr};`);
1446
+ }
1447
+ return `export interface ${name} {\n${props.join("\n")}\n}`;
1448
+ }
1449
+ jsonSchemaTypeToTs(schema) {
1450
+ if (!schema) return "unknown";
1451
+ if (schema.$ref) {
1452
+ const refName = schema.$ref.split("/").pop() || "unknown";
1453
+ return refName;
1454
+ }
1455
+ if (schema.anyOf) return schema.anyOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1456
+ if (schema.oneOf) return schema.oneOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" | ");
1457
+ if (schema.allOf) return schema.allOf.map((s) => this.jsonSchemaTypeToTs(s)).join(" & ");
1458
+ switch (schema.type) {
1459
+ case "string":
1460
+ if (schema.enum) return schema.enum.map((e) => `'${e}'`).join(" | ");
1461
+ return "string";
1462
+ case "number":
1463
+ case "integer": return "number";
1464
+ case "boolean": return "boolean";
1465
+ case "null": return "null";
1466
+ case "array":
1467
+ if (schema.items) return `Array<${this.jsonSchemaTypeToTs(schema.items)}>`;
1468
+ return "Array<unknown>";
1469
+ case "object":
1470
+ if (schema.properties) {
1471
+ const props = [];
1472
+ const required = new Set(schema.required || []);
1473
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1474
+ const isRequired = required.has(propName);
1475
+ const typeStr = this.jsonSchemaTypeToTs(propSchema);
1476
+ const optionalMark = isRequired ? "" : "?";
1477
+ props.push(`${propName}${optionalMark}: ${typeStr}`);
1478
+ }
1479
+ return `{ ${props.join("; ")} }`;
1480
+ }
1481
+ if (schema.additionalProperties) {
1482
+ const valueType = this.jsonSchemaTypeToTs(schema.additionalProperties);
1483
+ return `Record<string, ${valueType}>`;
1484
+ }
1485
+ return "Record<string, unknown>";
1486
+ default: return "unknown";
1487
+ }
1488
+ }
1489
+ async generatePathsInterface(endpointInfos) {
1490
+ const pathGroups = /* @__PURE__ */ new Map();
1491
+ for (const info of endpointInfos) {
1492
+ const existing = pathGroups.get(info.route) || [];
1493
+ existing.push(info);
1494
+ pathGroups.set(info.route, existing);
1495
+ }
1496
+ const pathEntries = [];
1497
+ for (const [route, infos] of pathGroups) {
1498
+ const methodEntries = [];
1499
+ for (const info of infos) {
1500
+ const methodDef = await this.generateMethodDefinition(info);
1501
+ methodEntries.push(` ${info.method.toLowerCase()}: ${methodDef};`);
1502
+ }
1503
+ const firstWithParams = infos.find((i) => i.input?.params);
1504
+ let paramsEntry = "";
1505
+ if (firstWithParams?.input?.params) {
1506
+ const paramsName = await this.getSchemaName(firstWithParams.input.params, `${this.getSchemaBaseName(firstWithParams)}Params`);
1507
+ paramsEntry = `\n parameters: {\n path: ${paramsName};\n };`;
1508
+ }
1509
+ pathEntries.push(` '${route}': {${paramsEntry}\n${methodEntries.join("\n")}\n };`);
1510
+ }
1511
+ return `export interface paths {\n${pathEntries.join("\n")}\n}`;
1512
+ }
1513
+ async generateMethodDefinition(info) {
1514
+ const parts = [];
1515
+ const baseName = this.getSchemaBaseName(info);
1516
+ if (info.input?.body) {
1517
+ const bodyName = await this.getSchemaName(info.input.body, `${baseName}Input`);
1518
+ parts.push(`requestBody: {
1519
+ content: {
1520
+ 'application/json': ${bodyName};
1521
+ };
1522
+ }`);
1523
+ }
1524
+ if (info.input?.query) {
1525
+ const queryName = await this.getSchemaName(info.input.query, `${baseName}Query`);
1526
+ parts.push(`parameters: {
1527
+ query: ${queryName};
1528
+ }`);
1529
+ }
1530
+ const outputName = info.output ? await this.getSchemaName(info.output, `${baseName}Output`) : "unknown";
1531
+ parts.push(`responses: {
1532
+ 200: {
1533
+ content: {
1534
+ '${info.responseType}': ${outputName};
1535
+ };
1536
+ };
1537
+ }`);
1538
+ return `{\n ${parts.join(";\n ")};\n }`;
1539
+ }
1540
+ buildModule(params) {
1541
+ const { title, version, description, securitySchemes, endpointAuth, schemaInterfaces, pathsInterface } = params;
1542
+ const securitySchemesObj = securitySchemes.reduce((acc, s) => {
1543
+ acc[s.name] = s.scheme;
1544
+ return acc;
1545
+ }, {});
1546
+ const schemeNames = securitySchemes.map((s) => `'${s.name}'`).join(" | ");
1547
+ const hasSecuritySchemes = schemeNames.length > 0;
1548
+ const createApiSection = hasSecuritySchemes ? `
1549
+ // ============================================================
1550
+ // API Client Factory
1551
+ // ============================================================
1552
+
1553
+ import {
1554
+ createAuthAwareFetcher,
1555
+ type AuthStrategy,
1556
+ } from '@geekmidas/client/auth-fetcher';
1557
+ import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1558
+ import type { QueryClient } from '@tanstack/react-query';
1559
+
1560
+ /**
1561
+ * Options for creating the API client.
1562
+ */
1563
+ export interface CreateApiOptions {
1564
+ /** Base URL for all API requests (required) */
1565
+ baseURL: string;
1566
+ /** Auth strategies for each security scheme used in this API */
1567
+ authStrategies: Record<SecuritySchemeId, AuthStrategy>;
1568
+ /** Optional React Query client instance */
1569
+ queryClient?: QueryClient;
1570
+ /** Optional request interceptor */
1571
+ onRequest?: (config: RequestInit) => RequestInit | Promise<RequestInit>;
1572
+ }
1573
+
1574
+ /**
1575
+ * Create a type-safe API client with authentication and React Query hooks.
1576
+ *
1577
+ * @example
1578
+ * \`\`\`typescript
1579
+ * const api = createApi({
1580
+ * baseURL: 'https://api.example.com',
1581
+ * authStrategies: {
1582
+ * jwt: { type: 'bearer', tokenProvider },
1583
+ * },
1584
+ * });
1585
+ *
1586
+ * // Imperative fetch
1587
+ * const user = await api('GET /users/{id}', { params: { id: '123' } });
1588
+ *
1589
+ * // React Query hooks
1590
+ * const { data } = api.useQuery('GET /users/{id}', { params: { id: '123' } });
1591
+ * const mutation = api.useMutation('POST /users');
1592
+ * \`\`\`
1593
+ */
1594
+ export function createApi(options: CreateApiOptions) {
1595
+ const fetcher = createAuthAwareFetcher<paths, typeof endpointAuth, typeof securitySchemes>({
1596
+ baseURL: options.baseURL,
1597
+ endpointAuth,
1598
+ securitySchemes,
1599
+ authStrategies: options.authStrategies,
1600
+ onRequest: options.onRequest,
1601
+ });
1602
+
1603
+ const hooks = createEndpointHooks<paths>(fetcher, { queryClient: options.queryClient });
1604
+
1605
+ return Object.assign(fetcher, hooks);
1606
+ }
1607
+ ` : `
1608
+ // ============================================================
1609
+ // API Client Factory
1610
+ // ============================================================
1611
+
1612
+ import { createTypedFetcher, type FetcherOptions } from '@geekmidas/client/fetcher';
1613
+ import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
1614
+ import type { QueryClient } from '@tanstack/react-query';
1615
+
1616
+ /**
1617
+ * Options for creating the API client.
1618
+ */
1619
+ export interface CreateApiOptions extends Omit<FetcherOptions, 'baseURL'> {
1620
+ /** Base URL for all API requests (required) */
1621
+ baseURL: string;
1622
+ /** Optional React Query client instance */
1623
+ queryClient?: QueryClient;
1624
+ }
1625
+
1626
+ /**
1627
+ * Create a type-safe API client with React Query hooks.
1628
+ *
1629
+ * @example
1630
+ * \`\`\`typescript
1631
+ * const api = createApi({
1632
+ * baseURL: 'https://api.example.com',
1633
+ * });
1634
+ *
1635
+ * // Imperative fetch
1636
+ * const data = await api('GET /health');
1637
+ *
1638
+ * // React Query hooks
1639
+ * const { data } = api.useQuery('GET /health');
1640
+ * \`\`\`
1641
+ */
1642
+ export function createApi(options: CreateApiOptions) {
1643
+ const { queryClient, ...fetcherOptions } = options;
1644
+ const request = createTypedFetcher<paths>(fetcherOptions);
1645
+
1646
+ const hooks = createEndpointHooks<paths>(request, { queryClient });
1647
+
1648
+ return Object.assign(request, hooks);
1649
+ }
1650
+ `;
1651
+ return `// Auto-generated by @geekmidas/cli - DO NOT EDIT
1652
+
1653
+ // ============================================================
1654
+ // Security Scheme Type
1655
+ // ============================================================
1656
+
1657
+ interface SecuritySchemeObject {
1658
+ type: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';
1659
+ description?: string;
1660
+ name?: string;
1661
+ in?: 'query' | 'header' | 'cookie';
1662
+ scheme?: string;
1663
+ bearerFormat?: string;
1664
+ flows?: Record<string, unknown>;
1665
+ openIdConnectUrl?: string;
1666
+ [key: string]: unknown;
1667
+ }
1668
+
1669
+ // ============================================================
1670
+ // API Info
1671
+ // ============================================================
1672
+
1673
+ export const apiInfo = {
1674
+ title: '${title}',
1675
+ version: '${version}',${description ? `\n description: '${description.replace(/'/g, "\\'")}',` : ""}
1676
+ } as const;
1677
+
1678
+ // ============================================================
1679
+ // Security Schemes
1680
+ // ============================================================
1681
+
1682
+ /**
1683
+ * Available security schemes for this API.
1684
+ * Maps authorizer names to OpenAPI security scheme definitions.
1685
+ */
1686
+ export const securitySchemes = ${JSON.stringify(securitySchemesObj, null, 2).replace(/"([a-zA-Z_$][a-zA-Z0-9_$]*)":/g, "$1:")} as const satisfies Record<string, SecuritySchemeObject>;
1687
+
1688
+ export type SecuritySchemeId = ${schemeNames || "never"};
1689
+
1690
+ // ============================================================
1691
+ // Endpoint Authentication Map
1692
+ // ============================================================
1693
+
1694
+ /**
1695
+ * Runtime map of endpoints to their required authentication scheme.
1696
+ * \`null\` indicates a public endpoint (no auth required).
1697
+ */
1698
+ export const endpointAuth = ${JSON.stringify(endpointAuth, null, 2).replace(/"([^"]+)":/g, "'$1':")} as const satisfies Record<string, SecuritySchemeId | null>;
1699
+
1700
+ export type EndpointString = keyof typeof endpointAuth;
1701
+
1702
+ export type AuthenticatedEndpoint = {
1703
+ [K in EndpointString]: typeof endpointAuth[K] extends null ? never : K;
1704
+ }[EndpointString];
1705
+
1706
+ export type PublicEndpoint = {
1707
+ [K in EndpointString]: typeof endpointAuth[K] extends null ? K : never;
1708
+ }[EndpointString];
1709
+
1710
+ // ============================================================
1711
+ // Schema Definitions
1712
+ // ============================================================
1713
+
1714
+ ${schemaInterfaces}
1715
+
1716
+ // ============================================================
1717
+ // OpenAPI Paths
1718
+ // ============================================================
1719
+
1720
+ ${pathsInterface}
1721
+ ${createApiSection}
1722
+ `;
1723
+ }
1724
+ };
1725
+
1726
+ //#endregion
1727
+ //#region src/workspace/client-generator.ts
1728
+ /**
1729
+ * Normalize routes to an array of patterns.
1730
+ * Handles string, string[], and PartitionedRoutes (extracts paths).
1731
+ * @internal Exported for use in dev command
1732
+ */
1733
+ function normalizeRoutes(routes) {
1734
+ if (!routes) return [];
1735
+ if (isPartitionedRoutes(routes)) return Array.isArray(routes.paths) ? routes.paths : [routes.paths];
1736
+ return Array.isArray(routes) ? routes : [routes];
1737
+ }
1738
+
1739
+ //#endregion
1740
+ //#region src/openapi.ts
1741
+ /**
1742
+ * Default output path for generated OpenAPI client (used for single-app configs)
1743
+ */
1744
+ const OPENAPI_OUTPUT_PATH = "./.gkm/openapi.ts";
1745
+ /**
1746
+ * Resolve OpenAPI config from GkmConfig
1747
+ */
1748
+ function resolveOpenApiConfig(config) {
1749
+ if (config.openapi === false) return { enabled: false };
1750
+ if (config.openapi === true || config.openapi === void 0) return {
1751
+ enabled: true,
1752
+ title: "API Documentation",
1753
+ version: "1.0.0",
1754
+ description: "Auto-generated API documentation from endpoints"
1755
+ };
1756
+ return {
1757
+ enabled: config.openapi.enabled !== false,
1758
+ title: config.openapi.title || "API Documentation",
1759
+ version: config.openapi.version || "1.0.0",
1760
+ description: config.openapi.description || "Auto-generated API documentation from endpoints"
1761
+ };
1762
+ }
1763
+ /**
1764
+ * Generate OpenAPI spec from endpoints
1765
+ * @returns Object with output path and endpoint count, or null if disabled
1766
+ */
1767
+ async function generateOpenApi(config, options = {}) {
1768
+ const logger = options.silent ? { log: () => {} } : console;
1769
+ const openApiConfig = resolveOpenApiConfig(config);
1770
+ if (!openApiConfig.enabled) return null;
1771
+ const endpointGenerator = new EndpointGenerator();
1772
+ const loadedEndpoints = await endpointGenerator.load(config.routes, void 0, options.bustCache);
1773
+ if (loadedEndpoints.length === 0) {
1774
+ logger.log("No valid endpoints found for OpenAPI generation");
1775
+ return null;
1776
+ }
1777
+ const endpoints = loadedEndpoints.map(({ construct }) => construct);
1778
+ const outputPath = join(process.cwd(), OPENAPI_OUTPUT_PATH);
1779
+ await mkdir(dirname(outputPath), { recursive: true });
1780
+ const tsGenerator = new OpenApiTsGenerator();
1781
+ const tsContent = await tsGenerator.generate(endpoints, {
1782
+ title: openApiConfig.title,
1783
+ version: openApiConfig.version,
1784
+ description: openApiConfig.description
1785
+ });
1786
+ await writeFile(outputPath, tsContent);
1787
+ logger.log(`📄 OpenAPI client generated: ${OPENAPI_OUTPUT_PATH}`);
1788
+ return {
1789
+ outputPath,
1790
+ endpointCount: loadedEndpoints.length
1791
+ };
1792
+ }
1793
+ async function openapiCommand(options = {}) {
1794
+ const logger = console;
1795
+ try {
1796
+ const loadedConfig = await loadWorkspaceConfig(options.cwd);
1797
+ if (loadedConfig.type === "single") {
1798
+ const config = loadedConfig.raw;
1799
+ if (!config.openapi) config.openapi = { enabled: true };
1800
+ const result = await generateOpenApi(config);
1801
+ if (result) logger.log(`Found ${result.endpointCount} endpoints`);
1802
+ } else {
1803
+ const { workspace } = loadedConfig;
1804
+ const workspaceRoot = workspace.root;
1805
+ const backendApps = Object.entries(workspace.apps).filter(([_, app]) => app.type === "backend" && (app.openapi === true || typeof app.openapi === "object" && app.openapi.enabled !== false));
1806
+ if (backendApps.length === 0) {
1807
+ logger.log("No backend apps with OpenAPI enabled found");
1808
+ return;
1809
+ }
1810
+ if (options.app) {
1811
+ const entry = backendApps.find(([name]) => name === options.app);
1812
+ if (!entry) throw new Error(`App "${options.app}" not found or has OpenAPI disabled`);
1813
+ const [appName, app] = entry;
1814
+ const result = await generateOpenApiForApp(workspaceRoot, appName, app);
1815
+ if (result) logger.log(`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`);
1816
+ return;
1817
+ }
1818
+ for (const [appName, app] of backendApps) {
1819
+ if (app.type !== "backend" || !app.routes) continue;
1820
+ const appPath = join(workspaceRoot, app.path);
1821
+ await runOpenApiInSubprocess(appPath, appName);
1822
+ }
1823
+ }
1824
+ } catch (error) {
1825
+ throw new Error(`OpenAPI generation failed: ${error.message}`);
1826
+ }
1827
+ }
1828
+ /**
1829
+ * Generate OpenAPI for a single named app within a workspace.
1830
+ * Runs in-process. The caller is responsible for ensuring `process.cwd()`
1831
+ * is the app's directory so tsx loads the app's tsconfig path aliases.
1832
+ */
1833
+ async function generateOpenApiForApp(workspaceRoot, _appName, app) {
1834
+ if (app.type !== "backend" || !app.routes) return null;
1835
+ const appPath = join(workspaceRoot, app.path);
1836
+ const routes = normalizeRoutes(app.routes);
1837
+ const routesGlob = routes.map((r) => join(appPath, r));
1838
+ const gkmConfig = {
1839
+ routes: routesGlob,
1840
+ envParser: app.envParser || "",
1841
+ logger: app.logger || "",
1842
+ openapi: app.openapi
1843
+ };
1844
+ return generateOpenApi(gkmConfig, { silent: true });
1845
+ }
1846
+ /**
1847
+ * Resolve the gkm bin path. Tests can override via `GKM_BIN_PATH` env var
1848
+ * to avoid depending on the built dist.
1849
+ */
1850
+ function resolveGkmBinPath() {
1851
+ if (process.env.GKM_BIN_PATH) return process.env.GKM_BIN_PATH;
1852
+ return fileURLToPath(new URL("../bin/gkm.mjs", import.meta.url));
1853
+ }
1854
+ /**
1855
+ * Spawn a subprocess that runs `gkm openapi --app <name>` with `cwd` set to
1856
+ * the app's directory. Inherits `NODE_OPTIONS` (which already contains
1857
+ * `--import tsx`), so the child gets a fresh tsx instance whose tsconfig
1858
+ * discovery picks up the app's tsconfig path aliases.
1859
+ */
1860
+ async function runOpenApiInSubprocess(appCwd, appName) {
1861
+ const binPath = resolveGkmBinPath();
1862
+ await new Promise((resolve$1, reject) => {
1863
+ const child = spawn(process.execPath, [
1864
+ binPath,
1865
+ "openapi",
1866
+ "--app",
1867
+ appName
1868
+ ], {
1869
+ cwd: appCwd,
1870
+ stdio: "inherit",
1871
+ env: process.env
1872
+ });
1873
+ child.on("error", reject);
1874
+ child.on("close", (code) => {
1875
+ if (code === 0) resolve$1();
1876
+ else reject(new Error(`OpenAPI generation for app "${appName}" exited with code ${code}`));
1877
+ });
1878
+ });
1879
+ }
1880
+
1881
+ //#endregion
1882
+ export { ConstructGenerator, EndpointGenerator, OPENAPI_OUTPUT_PATH, generateOpenApi, isPartitionedRoutes, normalizeRoutes, openapiCommand, resolveOpenApiConfig };
1883
+ //# sourceMappingURL=openapi-Cfwi0fqF.mjs.map