@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
@@ -1,2032 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_errors = require("./errors-DMC4Umsb.cjs");
3
- const require_run = require("./run-fVZ-rLnc.cjs");
4
- const require_credentials = require("./credentials-Zqr3QQYB.cjs");
5
- const require_discover = require("./discover-DPgu-ScS.cjs");
6
- const require_sandbox = require("./sandbox-CHv3OYXg.cjs");
7
- const require_derive = require("./derive-DAbo49sm.cjs");
8
- const require_workspace = require("./workspace-DRjdu1OY.cjs");
9
- const require_define = require("./define-crmMcXFS.cjs");
10
- const require_config = require("./config.cjs");
11
- const require_seeds = require("./seeds-BNHSpjNP.cjs");
12
- const require_identity = require("./identity-CbLfgQNT.cjs");
13
- const require_resolve = require("./resolve-DC98Rl1t.cjs");
14
- const require_local = require("./local-DNhnkugT.cjs");
15
- const require_sniffer = require("./sniffer-Cylp9W2D.cjs");
16
- const require_dns = require("./dns-kp8To8Qj.cjs");
17
- const require_credentialSchemas = require("./credentialSchemas-CAPKFkrG.cjs");
18
- let node_path = require("node:path");
19
- let _geekmidas_manifest = require("@geekmidas/manifest");
20
- let node_crypto = require("node:crypto");
21
- let _geekmidas_storage_s3_url = require("@geekmidas/storage/s3-url");
22
- _geekmidas_storage_s3_url = require_rolldown_runtime.__toESM(_geekmidas_storage_s3_url, 1);
23
- //#region src/target/secrets.ts
24
- /**
25
- * A stage's secrets as a target sees them: read and written through the
26
- * stage's own store, and masked in everything the run prints once read.
27
- */
28
- /**
29
- * Shorter values are left alone: what a progress line legitimately prints —
30
- * a port, a stage, an app name — would otherwise come out as `***` wherever
31
- * a secret happened to share it.
32
- */
33
- const SHORTEST_MASKED = 6;
34
- /** The values a run must never print, and the rewrite that keeps it so. */
35
- var Redactor = class {
36
- values = /* @__PURE__ */ new Set();
37
- add(value) {
38
- if (value && value.length >= SHORTEST_MASKED) this.values.add(value);
39
- }
40
- /** `text` with every masked value replaced by `***`, longest first. */
41
- redact(text) {
42
- if (this.values.size === 0) return text;
43
- let out = text;
44
- const longestFirst = [...this.values].sort((a, b) => b.length - a.length);
45
- for (const value of longestFirst) out = out.replaceAll(value, "***");
46
- return out;
47
- }
48
- };
49
- /** Every value in `secrets` that is a secret rather than a label. */
50
- function secretValues(secrets) {
51
- return [
52
- secrets.seed,
53
- ...Object.entries(secrets.custom ?? {}).filter(([key]) => !require_workspace.isReservedStageKey(key)).map(([, value]) => value),
54
- ...Object.values(secrets.urls ?? {}),
55
- ...Object.values(secrets.services ?? {}).map((service) => service?.password)
56
- ].filter((value) => typeof value === "string");
57
- }
58
- /**
59
- * The stage's secrets through the store `secrets.store` names for it. Opening
60
- * one builds a client and makes no request, so a target that never reads them
61
- * costs nothing.
62
- */
63
- async function deploySecrets(workspace, stage, redactor, options = {}) {
64
- const store = await require_seeds.secretsStoreFor(workspace, stage, options);
65
- const mask = (secrets) => {
66
- for (const value of secretValues(secrets)) redactor.add(value);
67
- };
68
- return {
69
- store: store.name,
70
- async read() {
71
- const secrets = await store.read(stage);
72
- if (secrets) mask(secrets);
73
- return secrets;
74
- },
75
- async write(secrets) {
76
- mask(secrets);
77
- await store.write(stage, secrets);
78
- },
79
- mask: (value) => redactor.add(value)
80
- };
81
- }
82
- //#endregion
83
- //#region src/providers/dns.ts
84
- /** Whether the workspace deploys through the compose target. */
85
- function deploysWithCompose(workspace) {
86
- return workspace.deploy?.default === "compose" || Object.values(workspace.apps).some((app) => app.resolvedDeployTarget === "compose");
87
- }
88
- //#endregion
89
- //#region src/providers/aws.ts
90
- /**
91
- * The AWS account a provider provisions in — the stage's, found the way the
92
- * SSM and Secrets Manager stores find it.
93
- *
94
- * 1. `--profile`, resolved on its own: exported keys left over from another
95
- * account never win over a profile someone named.
96
- * 2. `AWS_PROFILE`, else `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` — the
97
- * deploy's own `aws` credential kind (`storedCredentials`).
98
- * 3. The SDK's default chain: `~/.aws` default profile, SSO, a role. In CI,
99
- * whatever `aws-actions/configure-aws-credentials` exported.
100
- *
101
- * None of them: the provider has no provisioning credentials, and the stage
102
- * is treated as `external`.
103
- */
104
- async function awsProvisioningCredentials(lookup) {
105
- const region = lookup.env.AWS_REGION ?? lookup.env.AWS_DEFAULT_REGION;
106
- const where = region ? { region } : {};
107
- if (lookup.profile) return {
108
- profile: lookup.profile,
109
- ...where
110
- };
111
- const stored = await require_credentials.storedCredentials({
112
- env: lookup.env,
113
- ...lookup.home ? { home: lookup.home } : {}
114
- }).get({
115
- kind: "aws",
116
- stage: lookup.stage
117
- });
118
- if (stored) return stored;
119
- try {
120
- const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
121
- await fromNodeProviderChain({
122
- timeout: 1e3,
123
- maxRetries: 0
124
- })();
125
- return {
126
- chain: true,
127
- ...where
128
- };
129
- } catch {
130
- return;
131
- }
132
- }
133
- /**
134
- * An S3-compatible endpoint the environment points the SDK at — the AWS
135
- * emulator in tests. The SDK reads it itself; it is read here too, because
136
- * an emulator takes path-style requests, and a key written for one has to
137
- * say where it is.
138
- */
139
- function awsEndpoint(env, service) {
140
- return env[`AWS_ENDPOINT_URL_${service}`] ?? env.AWS_ENDPOINT_URL;
141
- }
142
- /** An SDK client's config for a provisioning credential. */
143
- async function awsClientConfig(credential, region) {
144
- if ("profile" in credential) {
145
- const { fromIni } = await import("@aws-sdk/credential-providers");
146
- return {
147
- region,
148
- credentials: fromIni({ profile: credential.profile })
149
- };
150
- }
151
- if ("accessKeyId" in credential) return {
152
- region,
153
- credentials: {
154
- accessKeyId: credential.accessKeyId,
155
- secretAccessKey: credential.secretAccessKey,
156
- ...credential.sessionToken ? { sessionToken: credential.sessionToken } : {}
157
- }
158
- };
159
- return { region };
160
- }
161
- const SUFFIX_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
162
- /** A name that S3 would refuse — what the name builder never returns. */
163
- var InvalidBucketName = class extends require_errors.GkmError {
164
- bucket;
165
- reason;
166
- constructor(bucket, reason) {
167
- super(`'${bucket}' is not a valid S3 bucket name: ${reason}. Rename the construct or set deploy.namespace in gkm.config.ts to something that leaves room for it.`);
168
- this.bucket = bucket;
169
- this.reason = reason;
170
- this.name = "InvalidBucketName";
171
- }
172
- };
173
- /** Lowercase `[a-z0-9-]`, runs of anything else one `-`, no edge dashes. */
174
- function part(value) {
175
- return (0, _geekmidas_manifest.kebabCase)(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
176
- }
177
- /**
178
- * `parts` joined by `-`, shortened to `max` characters by trimming the longest
179
- * part one character at a time — so a long construct id gives way before a
180
- * short stage name does, and every part keeps its start.
181
- */
182
- function fitParts(parts, max) {
183
- const kept = parts.map(part).filter(Boolean);
184
- const length = () => kept.reduce((sum, p) => sum + p.length, 0) + kept.length - 1;
185
- while (length() > max) {
186
- let longest = 0;
187
- for (let i = 1; i < kept.length; i++) if (kept[i].length > kept[longest].length) longest = i;
188
- if (kept[longest].length <= 1) break;
189
- kept[longest] = kept[longest].slice(0, -1).replace(/-+$/, "");
190
- }
191
- return kept.join("-");
192
- }
193
- /** Why `name` is not a valid bucket name, or undefined when it is. */
194
- function bucketNameProblem(name) {
195
- if (name.length < 3 || name.length > 63) return `it is ${name.length} characters, and S3 takes 3 to 63`;
196
- if (!/^[a-z0-9-]+$/.test(name)) return "it may hold only lowercase letters, digits and -";
197
- if (!/^[a-z0-9].*[a-z0-9]$/.test(name)) return "it must start and end with a letter or a digit";
198
- if (name.startsWith("xn--") || name.startsWith("sthree-")) return "it starts with a prefix S3 reserves ('xn--', 'sthree-')";
199
- if (name.endsWith("-s3alias") || name.endsWith("--ol-s3")) return "it ends with a suffix S3 reserves ('-s3alias', '--ol-s3')";
200
- }
201
- /**
202
- * The good name: `<namespace>-<project>-<stage>-<bucket id>`, lowercased, no
203
- * dots, shortened to leave room for a clash's suffix.
204
- *
205
- * @throws {InvalidBucketName} when nothing usable is left
206
- */
207
- function bucketName(input) {
208
- const name = fitParts([
209
- input.scope,
210
- input.stage,
211
- input.id
212
- ], 56);
213
- const problem = bucketNameProblem(name);
214
- if (problem) throw new InvalidBucketName(name, problem);
215
- return name;
216
- }
217
- /** Six random `[a-z0-9]` characters. */
218
- function randomSuffix(random = node_crypto.randomInt) {
219
- let suffix = "";
220
- for (let i = 0; i < 6; i++) suffix += SUFFIX_ALPHABET[random(36)];
221
- return suffix;
222
- }
223
- /** The good name with a clash's suffix. */
224
- function suffixedBucketName(good, suffix) {
225
- return `${good}-${suffix}`;
226
- }
227
- /**
228
- * The IAM user a bucket is reached with on a stage:
229
- * `gkm-<project>-<stage>-<bucket id>`, at most 64 characters.
230
- */
231
- function iamUserName(input) {
232
- return fitParts([
233
- "gkm",
234
- input.scope,
235
- input.stage,
236
- input.id
237
- ], 64);
238
- }
239
- /** The path every user gkm creates is under, so it finds its own. */
240
- const IAM_USER_PATH = "/gkm/";
241
- /** The inline policy each user is given. */
242
- const IAM_POLICY_NAME = "gkm-bucket";
243
- //#endregion
244
- //#region src/providers/s3/origins.ts
245
- /**
246
- * Which browser origins may call a bucket: the stage's sites that depend on
247
- * an API using it.
248
- *
249
- * The same reading of the graph an API's own CORS origins are — its callers —
250
- * taken one step further: a site that calls an API which hands it a presigned
251
- * upload URL is a site whose browser PUTs to the bucket. A site that reads the
252
- * bucket (or a file server over it) itself is one too. Nothing is written
253
- * down: add a site that calls the API and the next provision run allows it.
254
- */
255
- /** The keys a reader of this bucket holds: its URL, and each server's over it. */
256
- function bucketKeys(manifest, bucket) {
257
- return [(0, _geekmidas_manifest.provideKey)(bucket, "url"), ...Object.entries(manifest).filter(([, d]) => d.kind === "file-server" && d.of === bucket).map(([id]) => (0, _geekmidas_manifest.provideKey)(id, "url"))];
258
- }
259
- function bucketOrigins(input) {
260
- const { manifest, workspace, stage } = input;
261
- const keys = bucketKeys(manifest, input.bucket);
262
- const readers = Object.entries(manifest).filter(([, d]) => d.kind === "rest-api" || d.kind === "site").filter(([id]) => {
263
- const env = require_seeds.appEnvKeys(manifest, require_derive.appKey(id), input.runnables);
264
- return env !== void 0 && keys.some((key) => env.has(key));
265
- });
266
- const sites = /* @__PURE__ */ new Set();
267
- for (const [id, declaration] of readers) {
268
- if (declaration.kind === "site") {
269
- sites.add(id);
270
- continue;
271
- }
272
- for (const caller of (0, _geekmidas_manifest.dependentsOf)(manifest, id)) if (manifest[caller]?.kind === "site") sites.add(caller);
273
- }
274
- const origins = /* @__PURE__ */ new Set();
275
- const unresolved = [];
276
- for (const id of [...sites].sort()) {
277
- const name = require_derive.appKey(id);
278
- const app = workspace.apps[name];
279
- if (!app) {
280
- unresolved.push(name);
281
- continue;
282
- }
283
- try {
284
- const host = require_seeds.resolveHost(name, app, stage, workspace.domains, require_seeds.isMainFrontendApp(name, app, workspace.apps));
285
- origins.add(`https://${host}`);
286
- } catch (error) {
287
- if (!(error instanceof require_seeds.NoDomainForStage)) throw error;
288
- unresolved.push(name);
289
- }
290
- }
291
- return {
292
- origins: [...origins].sort(),
293
- unresolved
294
- };
295
- }
296
- //#endregion
297
- //#region src/providers/s3/policy.ts
298
- const bucketArn = (bucket) => `arn:aws:s3:::${bucket}`;
299
- /**
300
- * What the app's key may do: objects in this bucket, and listing it — and
301
- * nothing else in the account.
302
- *
303
- * Multipart uploads are in it because a presigned upload of a large file is
304
- * one, and an abandoned one is cleaned up by the app. Reading old versions is
305
- * added only when the bucket keeps them.
306
- */
307
- function userPolicy(bucket, options = {}) {
308
- return {
309
- Version: "2012-10-17",
310
- Statement: [{
311
- Sid: "GkmObjects",
312
- Effect: "Allow",
313
- Action: [
314
- "s3:GetObject",
315
- "s3:PutObject",
316
- "s3:DeleteObject",
317
- "s3:AbortMultipartUpload",
318
- "s3:ListMultipartUploadParts",
319
- ...options.versioning ? ["s3:GetObjectVersion"] : []
320
- ],
321
- Resource: `${bucketArn(bucket)}/*`
322
- }, {
323
- Sid: "GkmBucket",
324
- Effect: "Allow",
325
- Action: [
326
- "s3:ListBucket",
327
- "s3:GetBucketLocation",
328
- "s3:ListBucketMultipartUploads"
329
- ],
330
- Resource: bucketArn(bucket)
331
- }]
332
- };
333
- }
334
- /**
335
- * One open pattern as the resource it is public on. A `**` is S3's `*`; a
336
- * single `*` is too, which crosses `/` where the construct's own check does
337
- * not — the construct is the stricter of the two (see `bucketPolicy` in
338
- * reconcile, which the local MinIO is given the same way).
339
- */
340
- function openResource(bucket, pattern) {
341
- const path = pattern.replace(/^\/+/, "").replace(/\*\*/g, "*");
342
- return `${bucketArn(bucket)}/${path}`;
343
- }
344
- /**
345
- * The bucket's own policy: every request refused unless it came over TLS,
346
- * and — only when a file server opens paths on it — anonymous `s3:GetObject`
347
- * on exactly those prefixes.
348
- */
349
- function bucketPolicy(bucket, open = []) {
350
- const statements = [{
351
- Sid: "GkmDenyInsecureTransport",
352
- Effect: "Deny",
353
- Principal: "*",
354
- Action: "s3:*",
355
- Resource: [bucketArn(bucket), `${bucketArn(bucket)}/*`],
356
- Condition: { Bool: { "aws:SecureTransport": "false" } }
357
- }];
358
- if (open.length > 0) statements.push({
359
- Sid: "GkmOpenPaths",
360
- Effect: "Allow",
361
- Principal: "*",
362
- Action: "s3:GetObject",
363
- Resource: [...new Set(open.map((p) => openResource(bucket, p)))].sort()
364
- });
365
- return {
366
- Version: "2012-10-17",
367
- Statement: statements
368
- };
369
- }
370
- /**
371
- * Block Public Access. All four flags on, unless the bucket has open paths:
372
- * then a *policy* may make it public (`BlockPublicPolicy`,
373
- * `RestrictPublicBuckets` off), and ACLs still may not.
374
- */
375
- function publicAccessBlock(open) {
376
- return {
377
- BlockPublicAcls: true,
378
- IgnorePublicAcls: true,
379
- BlockPublicPolicy: !open,
380
- RestrictPublicBuckets: !open
381
- };
382
- }
383
- function corsRule(origins) {
384
- return {
385
- AllowedMethods: [
386
- "GET",
387
- "HEAD",
388
- "POST",
389
- "PUT"
390
- ],
391
- AllowedOrigins: [...new Set(origins)].sort(),
392
- AllowedHeaders: ["*"],
393
- ExposeHeaders: ["ETag"],
394
- MaxAgeSeconds: 3e3
395
- };
396
- }
397
- /**
398
- * A policy document in one canonical form — keys sorted, a lone string a
399
- * one-element list, lists sorted — so one AWS reformatted reads as the same
400
- * document rather than as drift.
401
- */
402
- function canonicalPolicy(value) {
403
- return JSON.stringify(canonical(value));
404
- }
405
- function canonical(value, key) {
406
- if (Array.isArray(value)) {
407
- const items = value.map((v) => canonical(v));
408
- return key === "Statement" ? items : items.map((v) => JSON.stringify(v)).sort();
409
- }
410
- if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => {
411
- const v = value[k];
412
- return [k, canonical(k === "Action" || k === "Resource" || k === "AWS" ? Array.isArray(v) ? v : [v] : v, k)];
413
- }));
414
- return value;
415
- }
416
- //#endregion
417
- //#region src/providers/s3/index.ts
418
- /** The tags gkm finds its own buckets and users by. */
419
- const TAG_PROJECT = "gkm:project";
420
- const TAG_STAGE = "gkm:stage";
421
- const TAG_CONSTRUCT = "gkm:construct";
422
- function bucketConstructs(manifest) {
423
- return Object.entries(manifest).filter(([, d]) => d.kind === "objects").map(([id, d]) => ({
424
- id,
425
- versioned: d.versioned === true,
426
- servers: Object.entries(manifest).filter(([, s]) => s.kind === "file-server" && s.of === id).map(([sid, s]) => ({
427
- id: sid,
428
- open: s.open ?? []
429
- })).sort((a, b) => a.id.localeCompare(b.id))
430
- })).sort((a, b) => a.id.localeCompare(b.id));
431
- }
432
- /**
433
- * The region the stage's buckets are created in: the entry's, the secrets
434
- * store's when it is in AWS, the credential's, `AWS_REGION`.
435
- */
436
- function s3Region(ctx, env = process.env) {
437
- const store = ctx.workspace.secrets?.store;
438
- const storeRegion = store && typeof store === "object" && "region" in store ? store.region : void 0;
439
- const region = ctx.config.region ?? storeRegion ?? ctx.credential?.region ?? env.AWS_REGION ?? env.AWS_DEFAULT_REGION;
440
- if (!region) throw new require_workspace.S3RegionRequired(ctx.stage);
441
- return region;
442
- }
443
- /**
444
- * The address a file server over `bucket` serves on: the bucket's regional
445
- * virtual-host endpoint, which is what `FileServer.url(key)` appends a key to
446
- * — `https://<bucket>.s3.<region>.amazonaws.com/<key>`. Against an emulator,
447
- * its path-style address.
448
- */
449
- function bucketPublicUrl(bucket, region, endpoint) {
450
- if (endpoint) return `${endpoint.replace(/\/+$/, "")}/${bucket}`;
451
- return `https://${bucket}.s3.${region}.amazonaws.com`;
452
- }
453
- /** What an AWS SDK error is called, whichever field carries it. */
454
- function errorName(error) {
455
- const e = error;
456
- return e?.Code ?? e?.name ?? "";
457
- }
458
- /** The answer an SDK call failed with. */
459
- function s3Answer(error) {
460
- const e = error;
461
- const headers = Object.fromEntries(Object.entries(e?.$response?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
462
- const status = e?.$metadata?.httpStatusCode ?? e?.$response?.statusCode;
463
- const region = headers["x-amz-bucket-region"];
464
- const requestId = e?.$metadata?.requestId ?? headers["x-amz-request-id"];
465
- const id2 = e?.$metadata?.extendedRequestId ?? headers["x-amz-id-2"];
466
- return {
467
- ...status !== void 0 ? { status } : {},
468
- name: errorName(error) || "Error",
469
- message: e?.message ?? String(error),
470
- ...region ? { region } : {},
471
- ...requestId ? { requestId } : {},
472
- ...id2 ? { id2 } : {}
473
- };
474
- }
475
- /**
476
- * `HTTP 403 Unknown: UnknownError [x-amz-bucket-region: eu-west-1,
477
- * x-amz-request-id: …, x-amz-id-2: …]` — everything S3 said, for a message.
478
- */
479
- function describeAnswer(answer) {
480
- const said = answer.message && answer.message !== answer.name ? `${answer.name}: ${answer.message}` : answer.name;
481
- const headers = [
482
- answer.region && `x-amz-bucket-region: ${answer.region}`,
483
- answer.requestId && `x-amz-request-id: ${answer.requestId}`,
484
- answer.id2 && `x-amz-id-2: ${answer.id2}`
485
- ].filter(Boolean);
486
- return `${answer.status === void 0 ? "no response" : `HTTP ${answer.status}`} ${said}` + (headers.length > 0 ? ` [${headers.join(", ")}]` : "");
487
- }
488
- /** `HeadBucket`: the bucket's region when it answers, else what S3 said. */
489
- async function headBucket(S3, client, bucket) {
490
- try {
491
- const out = await client.send(new S3.HeadBucketCommand({ Bucket: bucket }));
492
- return {
493
- ok: true,
494
- ...out.BucketRegion ? { region: out.BucketRegion } : {}
495
- };
496
- } catch (error) {
497
- return {
498
- ok: false,
499
- ...s3Answer(error)
500
- };
501
- }
502
- }
503
- /** `GetBucketLocation`'s answer as a region: none is us-east-1, `EU` eu-west-1. */
504
- async function bucketLocation(S3, client, bucket) {
505
- try {
506
- const location = (await client.send(new S3.GetBucketLocationCommand({ Bucket: bucket }))).LocationConstraint;
507
- return { region: !location ? "us-east-1" : location === "EU" ? "eu-west-1" : location };
508
- } catch (error) {
509
- return { failed: s3Answer(error) };
510
- }
511
- }
512
- /**
513
- * Where `bucket` is: `HeadBucket`'s `x-amz-bucket-region` — on a 200, a 301
514
- * or a 400 alike — else `GetBucketLocation`.
515
- *
516
- * @throws {BucketRegionUnknown}
517
- */
518
- async function bucketRegion(clients, bucket) {
519
- const { S3, s3 } = clients;
520
- const head = await headBucket(S3, s3, bucket);
521
- if (head.region) return head.region;
522
- const location = await bucketLocation(S3, s3, bucket);
523
- if ("region" in location) return location.region;
524
- throw new require_workspace.BucketRegionUnknown(bucket, head.ok ? "HTTP 200 without x-amz-bucket-region" : describeAnswer(head), describeAnswer(location.failed));
525
- }
526
- /** A read whose "there is none" answer is one of `missing`. */
527
- async function readOr(read, missing) {
528
- try {
529
- return await read();
530
- } catch (error) {
531
- if (missing.includes(errorName(error))) return void 0;
532
- throw error;
533
- }
534
- }
535
- const defaultClients = async (credential, region) => {
536
- const S3 = await import("@aws-sdk/client-s3");
537
- const IAM = await import("@aws-sdk/client-iam");
538
- const config = await awsClientConfig(credential, region);
539
- const endpoint = awsEndpoint(process.env, "S3");
540
- return {
541
- S3,
542
- IAM,
543
- s3: new S3.S3Client({
544
- ...config,
545
- ...endpoint ? {
546
- endpoint,
547
- forcePathStyle: true
548
- } : {}
549
- }),
550
- iam: new IAM.IAMClient(config),
551
- region,
552
- ...endpoint ? { endpoint } : {}
553
- };
554
- };
555
- /** For tests: what makes the clients. */
556
- let makeClients = defaultClients;
557
- async function ensureS3(ctx) {
558
- const region = s3Region(ctx);
559
- const clients = await makeClients(ctx.credential, region);
560
- for (const construct of bucketConstructs(ctx.manifest)) await ensureBucket(ctx, clients, construct);
561
- }
562
- /** The keys gkm tags a bucket and a user with. */
563
- function identityTags(ctx, id) {
564
- return [
565
- {
566
- Key: TAG_PROJECT,
567
- Value: ctx.identity.key
568
- },
569
- {
570
- Key: TAG_STAGE,
571
- Value: ctx.stage
572
- },
573
- {
574
- Key: TAG_CONSTRUCT,
575
- Value: id
576
- }
577
- ];
578
- }
579
- async function ensureBucket(ctx, stageClients, construct) {
580
- const { id } = construct;
581
- const nameInput = {
582
- scope: ctx.identity.scope,
583
- stage: ctx.stage,
584
- id: require_derive.appKey(id)
585
- };
586
- const versioning = ctx.config.versioning ?? construct.versioned;
587
- const open = [...new Set(construct.servers.flatMap((s) => s.open))].sort();
588
- const located = await ensureBucketName(ctx, stageClients, id, bucketName(nameInput));
589
- const { bucket, exists } = located;
590
- let clients = stageClients;
591
- if (located.region !== stageClients.region) {
592
- clients = await makeClients(ctx.credential, located.region);
593
- ctx.log(` '${bucket}' is in ${located.region}, not ${stageClients.region}: '${id}' is reached and addressed there`);
594
- }
595
- await ensureBucketSettings(ctx, clients, {
596
- id,
597
- bucket,
598
- exists,
599
- versioning,
600
- open
601
- });
602
- const user = await ensureUser(ctx, clients, id, iamUserName(nameInput), userPolicy(bucket, { versioning }));
603
- await ensureAccessKey(ctx, clients, {
604
- id,
605
- bucket,
606
- ...user
607
- });
608
- const publicUrl = bucketPublicUrl(bucket, clients.region, clients.endpoint);
609
- for (const server of construct.servers) {
610
- const key = (0, _geekmidas_manifest.provideKey)(server.id, "url");
611
- const entry = {
612
- key: `file-server:${server.id}`,
613
- type: "url"
614
- };
615
- const recorded = ctx.state.record(entry.key)?.id;
616
- const current = ctx.secrets[key];
617
- if (current === publicUrl) {
618
- await ctx.state.ready(entry, publicUrl);
619
- continue;
620
- }
621
- if (current !== void 0 && current !== recorded) {
622
- ctx.log(` ${key} is set to ${current} by you, and kept — the bucket's own address is ${publicUrl}`);
623
- continue;
624
- }
625
- await ctx.change({
626
- construct: server.id,
627
- resource: key,
628
- change: `set to ${publicUrl}`
629
- }, async () => {
630
- await ctx.writeSecrets({ [key]: publicUrl });
631
- await ctx.state.ready(entry, publicUrl);
632
- });
633
- }
634
- }
635
- /**
636
- * The bucket's name: the recorded one, else the good name, else the good
637
- * name with a random suffix — up to {@link SUFFIX_ATTEMPTS} times.
638
- */
639
- async function ensureBucketName(ctx, clients, id, good) {
640
- const { S3, s3, region } = clients;
641
- const key = `s3-bucket:${id}`;
642
- const record = ctx.state.record(key);
643
- const entry = (name, where) => ({
644
- key,
645
- type: "s3-bucket",
646
- data: {
647
- name,
648
- region: where
649
- }
650
- });
651
- /**
652
- * Whether this account holds `name`: yes, no, or someone else does. Read
653
- * by status — a `HEAD` has no body, so its error is named `Unknown` — and,
654
- * when S3 says the bucket is in another region, asked again there.
655
- */
656
- const probe = async (name) => {
657
- let head = await headBucket(S3, s3, name);
658
- if (!head.ok && head.region && head.region !== region && (head.status === 301 || head.status === 400)) {
659
- const there = await makeClients(ctx.credential, head.region);
660
- head = await headBucket(there.S3, there.s3, name);
661
- }
662
- if (head.ok) return "ours";
663
- if (head.status === 404) return "none";
664
- if (head.status === 403) return "taken";
665
- throw new require_workspace.BucketProbeFailed(name, describeAnswer(head));
666
- };
667
- /** Where the bucket is now — read, not assumed: it may be adopted. */
668
- const located = async (name, made) => ctx.dryRun && made === "created" ? region : bucketRegion(clients, name);
669
- const create = async (name) => {
670
- if (ctx.dryRun) {
671
- const found = await probe(name);
672
- if (found === "none") {
673
- await ctx.change({
674
- construct: id,
675
- resource: `bucket ${name}`,
676
- change: `create in ${region}`
677
- }, async () => {});
678
- return "created";
679
- }
680
- return found;
681
- }
682
- await ctx.state.pending(entry(name, region));
683
- try {
684
- await s3.send(new S3.CreateBucketCommand({
685
- Bucket: name,
686
- ...region === "us-east-1" ? {} : { CreateBucketConfiguration: { LocationConstraint: region } }
687
- }));
688
- } catch (error) {
689
- const code = errorName(error);
690
- if (code === "BucketAlreadyOwnedByYou") return "ours";
691
- if (code === "BucketAlreadyExists") return "taken";
692
- throw error;
693
- }
694
- await ctx.change({
695
- construct: id,
696
- resource: `bucket ${name}`,
697
- change: `create in ${region}`
698
- }, async () => {});
699
- return "created";
700
- };
701
- const adopt = async (name, where) => {
702
- const there = where === region ? clients : await makeClients(ctx.credential, where);
703
- const owner = (await readOr(() => there.s3.send(new there.S3.GetBucketTaggingCommand({ Bucket: name })), ["NoSuchTagSet", "NoSuchTagSetError"]))?.TagSet?.find((t) => t.Key === TAG_PROJECT)?.Value;
704
- if (owner && owner !== ctx.identity.key) throw new require_workspace.BucketOwnedByAnotherProject(name, owner, ctx.identity.key);
705
- };
706
- if (record?.status === "ready" && record.id) {
707
- const found = await probe(record.id);
708
- if (found === "taken") throw new require_workspace.RecordedBucketUnreachable(id, record.id);
709
- const made = found === "ours" ? "ours" : await create(record.id);
710
- if (made === "taken") throw new require_workspace.RecordedBucketUnreachable(id, record.id);
711
- const where = await located(record.id, made);
712
- if (!ctx.dryRun) await ctx.state.ready(entry(record.id, where), record.id);
713
- return {
714
- bucket: record.id,
715
- exists: made === "ours",
716
- region: where
717
- };
718
- }
719
- const pending = record?.data?.name;
720
- const names = [
721
- ...typeof pending === "string" && pending !== good ? [pending] : [],
722
- good,
723
- ...Array.from({ length: 5 }, () => suffixedBucketName(good, randomSuffix()))
724
- ];
725
- const tried = [];
726
- for (const name of names) {
727
- tried.push(name);
728
- const made = await create(name);
729
- if (made === "taken") continue;
730
- const where = await located(name, made);
731
- if (made === "ours") await adopt(name, where);
732
- if (!ctx.dryRun) await ctx.state.ready(entry(name, where), name);
733
- if (name !== good) ctx.log(` '${good}' is taken by another account; '${id}' is '${name}', recorded in the stage's state`);
734
- return {
735
- bucket: name,
736
- exists: made === "ours",
737
- region: where
738
- };
739
- }
740
- throw new require_workspace.BucketNameUnavailable(id, tried.filter((n) => n !== pending));
741
- }
742
- /** Tags, Block Public Access, encryption, policy, versioning and CORS. */
743
- async function ensureBucketSettings(ctx, clients, input) {
744
- const { S3, s3 } = clients;
745
- const { id, bucket } = input;
746
- const Bucket = bucket;
747
- const fresh = ctx.dryRun && !input.exists;
748
- const read = async (fn, missing) => fresh ? void 0 : readOr(fn, missing);
749
- const set = (change, apply) => ctx.change({
750
- construct: id,
751
- resource: `bucket ${bucket}`,
752
- change
753
- }, () => apply().then(() => void 0));
754
- const tagged = await read(() => s3.send(new S3.GetBucketTaggingCommand({ Bucket })), ["NoSuchTagSet", "NoSuchTagSetError"]);
755
- const ours = identityTags(ctx, id);
756
- const others = (tagged?.TagSet ?? []).filter((t) => !ours.some((o) => o.Key === t.Key));
757
- if (ours.some((o) => !tagged?.TagSet?.some((t) => t.Key === o.Key && t.Value === o.Value))) await set("tag", () => s3.send(new S3.PutBucketTaggingCommand({
758
- Bucket,
759
- Tagging: { TagSet: [...others, ...ours].map((t) => ({
760
- Key: t.Key,
761
- Value: t.Value
762
- })) }
763
- })));
764
- const isOpen = input.open.length > 0;
765
- const block = publicAccessBlock(isOpen);
766
- const ensureBlock = async () => {
767
- const now = (await read(() => s3.send(new S3.GetPublicAccessBlockCommand({ Bucket })), ["NoSuchPublicAccessBlockConfiguration"]))?.PublicAccessBlockConfiguration;
768
- if (!(now && Object.keys(block).every((k) => (now[k] ?? false) === block[k]))) await set(isOpen ? "block public access (ACLs; the policy opens the open paths)" : "block all public access", () => s3.send(new S3.PutPublicAccessBlockCommand({
769
- Bucket,
770
- PublicAccessBlockConfiguration: block
771
- })));
772
- };
773
- const policy = bucketPolicy(bucket, input.open);
774
- const ensurePolicy = async () => {
775
- const current = await read(() => s3.send(new S3.GetBucketPolicyCommand({ Bucket })), ["NoSuchBucketPolicy"]);
776
- if (!(current?.Policy !== void 0 && canonicalPolicy(JSON.parse(current.Policy)) === canonicalPolicy(policy))) await set(isOpen ? `policy: TLS only, public read on ${input.open.join(", ")}` : "policy: TLS only", () => s3.send(new S3.PutBucketPolicyCommand({
777
- Bucket,
778
- Policy: JSON.stringify(policy)
779
- })));
780
- };
781
- if (isOpen) {
782
- await ensureBlock();
783
- await ensurePolicy();
784
- } else {
785
- await ensurePolicy();
786
- await ensureBlock();
787
- }
788
- if ((await read(() => s3.send(new S3.GetBucketEncryptionCommand({ Bucket })), ["ServerSideEncryptionConfigurationNotFoundError"]))?.ServerSideEncryptionConfiguration?.Rules?.[0]?.ApplyServerSideEncryptionByDefault?.SSEAlgorithm !== "AES256" && !fresh) await set("encrypt by default (SSE-S3)", () => s3.send(new S3.PutBucketEncryptionCommand({
789
- Bucket,
790
- ServerSideEncryptionConfiguration: { Rules: [{ ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" } }] }
791
- })));
792
- const status = (await read(() => s3.send(new S3.GetBucketVersioningCommand({ Bucket })), []))?.Status;
793
- if (input.versioning && status !== "Enabled") await set("enable versioning", () => s3.send(new S3.PutBucketVersioningCommand({
794
- Bucket,
795
- VersioningConfiguration: { Status: "Enabled" }
796
- })));
797
- else if (!input.versioning && status === "Enabled") await set("suspend versioning", () => s3.send(new S3.PutBucketVersioningCommand({
798
- Bucket,
799
- VersioningConfiguration: { Status: "Suspended" }
800
- })));
801
- const { origins, unresolved } = bucketOrigins({
802
- workspace: ctx.workspace,
803
- manifest: ctx.manifest,
804
- runnables: ctx.runnables,
805
- stage: ctx.stage,
806
- bucket: id
807
- });
808
- if (unresolved.length > 0) ctx.log(` ${unresolved.join(", ")} ${unresolved.length === 1 ? "has" : "have"} no address on '${ctx.stage}' (domains.${ctx.stage}), so ${unresolved.length === 1 ? "is" : "are"} not in '${bucket}''s CORS`);
809
- if (origins.length === 0) return;
810
- const rule = corsRule(origins);
811
- const cors = await read(() => s3.send(new S3.GetBucketCorsCommand({ Bucket })), ["NoSuchCORSConfiguration"]);
812
- if (!(cors?.CORSRules?.length === 1 && canonicalCors(cors.CORSRules[0]) === canonicalCors(rule))) await set(`CORS for ${origins.join(", ")}`, () => s3.send(new S3.PutBucketCorsCommand({
813
- Bucket,
814
- CORSConfiguration: { CORSRules: [rule] }
815
- })));
816
- }
817
- function canonicalCors(rule) {
818
- const sorted = (list) => [...list ?? []].sort();
819
- return JSON.stringify({
820
- AllowedMethods: sorted(rule.AllowedMethods),
821
- AllowedOrigins: sorted(rule.AllowedOrigins),
822
- AllowedHeaders: sorted(rule.AllowedHeaders),
823
- ExposeHeaders: sorted(rule.ExposeHeaders),
824
- MaxAgeSeconds: rule.MaxAgeSeconds ?? null
825
- });
826
- }
827
- /** The bucket's IAM user and its inline policy. */
828
- async function ensureUser(ctx, clients, id, user, policy) {
829
- const { IAM, iam } = clients;
830
- const entry = {
831
- key: `iam-user:${id}`,
832
- type: "iam-user"
833
- };
834
- const found = await readOr(() => iam.send(new IAM.GetUserCommand({ UserName: user })), ["NoSuchEntity", "NoSuchEntityException"]);
835
- if (found?.User) {
836
- const tags = await iam.send(new IAM.ListUserTagsCommand({ UserName: user }));
837
- const tag = (key) => tags.Tags?.find((t) => t.Key === key)?.Value;
838
- if (found.User.Path !== "/gkm/" || tag("gkm:project") !== ctx.identity.key || tag("gkm:stage") !== ctx.stage) throw new require_workspace.IamUserNotOwned(user, ctx.identity.key, ctx.stage);
839
- await ctx.state.ready(entry, user);
840
- } else await ctx.change({
841
- construct: id,
842
- resource: `IAM user ${user}`,
843
- change: `create under ${IAM_USER_PATH}`
844
- }, async () => {
845
- await ctx.state.pending(entry);
846
- await iam.send(new IAM.CreateUserCommand({
847
- UserName: user,
848
- Path: IAM_USER_PATH,
849
- Tags: identityTags(ctx, id)
850
- }));
851
- await ctx.state.ready(entry, user);
852
- });
853
- const exists = Boolean(found?.User) || !ctx.dryRun;
854
- const current = exists ? await readOr(() => iam.send(new IAM.GetUserPolicyCommand({
855
- UserName: user,
856
- PolicyName: IAM_POLICY_NAME
857
- })), ["NoSuchEntity", "NoSuchEntityException"]) : void 0;
858
- const document = current?.PolicyDocument ? JSON.parse(decodePolicy(current.PolicyDocument)) : void 0;
859
- if (!document || canonicalPolicy(document) !== canonicalPolicy(policy)) await ctx.change({
860
- construct: id,
861
- resource: `IAM user ${user}`,
862
- change: `policy ${IAM_POLICY_NAME}: this bucket only`
863
- }, async () => {
864
- await iam.send(new IAM.PutUserPolicyCommand({
865
- UserName: user,
866
- PolicyName: IAM_POLICY_NAME,
867
- PolicyDocument: JSON.stringify(policy)
868
- }));
869
- });
870
- return {
871
- user,
872
- exists
873
- };
874
- }
875
- /** IAM returns a policy document URL-encoded; an emulator may not. */
876
- function decodePolicy(document) {
877
- try {
878
- return decodeURIComponent(document);
879
- } catch {
880
- return document;
881
- }
882
- }
883
- /**
884
- * The user's access key, in the stage's secrets as the bucket's URL.
885
- *
886
- * - First run: one key, written into the stage's secrets.
887
- * - `--rotate-keys`: a second key, written in place of the first; the first
888
- * stays active until the stage has deployed with the second, and the next
889
- * run after that deploy — or `--retire-old-keys` — deletes it.
890
- * - A key the secrets no longer hold (a store emptied by hand): replaced the
891
- * same way, since its secret cannot be read back.
892
- */
893
- async function ensureAccessKey(ctx, clients, input) {
894
- const { IAM, iam } = clients;
895
- const { id, bucket, user } = input;
896
- const urlKey = (0, _geekmidas_manifest.provideKey)(id, "url");
897
- const entryKey = `iam-access-key:${id}`;
898
- const record = ctx.state.record(entryKey);
899
- const given = ctx.secrets[urlKey];
900
- let inUrl;
901
- let parsed;
902
- if (given !== void 0) {
903
- try {
904
- parsed = _geekmidas_storage_s3_url.parse(given);
905
- } catch {
906
- parsed = void 0;
907
- }
908
- if (parsed?.bucket !== bucket) throw new require_workspace.BucketKeySetElsewhere(urlKey, bucket, parsed?.bucket ?? given.replace(/\/\/[^@]*@/, "//"), ctx.stage);
909
- inUrl = parsed.accessKeyId;
910
- }
911
- const listed = input.exists ? (await iam.send(new IAM.ListAccessKeysCommand({ UserName: user }))).AccessKeyMetadata?.map((k) => k.AccessKeyId) ?? [] : [];
912
- let current = record?.status === "ready" ? record.id : void 0;
913
- let previous = typeof record?.data?.previous === "string" ? record.data.previous : void 0;
914
- const rotatedAt = typeof record?.data?.rotatedAt === "string" ? record.data.rotatedAt : void 0;
915
- const entry = (data = {}) => ({
916
- key: entryKey,
917
- type: "iam-access-key",
918
- data: {
919
- user,
920
- ...data
921
- }
922
- });
923
- if (previous && current) {
924
- const deployed = rotatedAt !== void 0 && ctx.state.lastDeployedAt !== void 0 && ctx.state.lastDeployedAt > rotatedAt;
925
- if (ctx.retireOldKeys || deployed) {
926
- const old = previous;
927
- const keep = current;
928
- await ctx.change({
929
- construct: id,
930
- resource: `IAM user ${user}`,
931
- change: `delete the rotated-out access key ${old}`
932
- }, async () => {
933
- if (listed.includes(old)) await iam.send(new IAM.DeleteAccessKeyCommand({
934
- UserName: user,
935
- AccessKeyId: old
936
- }));
937
- await ctx.state.ready(entry(), keep);
938
- });
939
- previous = void 0;
940
- } else ctx.log(` ${id}: the old access key ${previous} stays active until '${ctx.stage}' is deployed with the new one; the next deploy after that deletes it (or pass --retire-old-keys)`);
941
- }
942
- if (!current && inUrl && listed.includes(inUrl)) {
943
- await ctx.state.ready(entry(), inUrl);
944
- current = inUrl;
945
- }
946
- if (current !== void 0 && listed.includes(current) && inUrl === current && !ctx.rotateKeys) {
947
- if (parsed && parsed.region !== clients.region) {
948
- const address = parsed;
949
- await ctx.change({
950
- construct: id,
951
- resource: urlKey,
952
- change: `name ${clients.region}, the bucket's region (it said ${address.region ?? "none"})`
953
- }, () => ctx.writeSecrets({ [urlKey]: _geekmidas_storage_s3_url.build({
954
- ...address,
955
- region: clients.region
956
- }) }));
957
- }
958
- return;
959
- }
960
- if (ctx.rotateKeys && previous) throw new require_workspace.RotationInProgress(id, previous, ctx.stage);
961
- const outgoing = current && listed.includes(current) ? current : void 0;
962
- if (listed.length >= 2) throw new require_workspace.AccessKeyLimit(user, listed);
963
- const why = !current ? "create an access key" : ctx.rotateKeys ? "rotate: issue a new access key" : "issue a new access key (the secrets no longer hold the recorded one)";
964
- await ctx.change({
965
- construct: id,
966
- resource: `IAM user ${user}`,
967
- change: why
968
- }, async () => {
969
- await ctx.state.pending(entry(outgoing ? { previous: outgoing } : {}));
970
- const key = (await iam.send(new IAM.CreateAccessKeyCommand({ UserName: user }))).AccessKey;
971
- await ctx.writeSecrets({ [urlKey]: _geekmidas_storage_s3_url.build({
972
- bucket,
973
- region: clients.region,
974
- ...clients.endpoint ? {
975
- endpoint: clients.endpoint,
976
- forcePathStyle: true
977
- } : {},
978
- accessKeyId: key.AccessKeyId,
979
- secretAccessKey: key.SecretAccessKey
980
- }) });
981
- const issuedAt = (/* @__PURE__ */ new Date()).toISOString();
982
- await ctx.state.ready(entry(outgoing ? {
983
- previous: outgoing,
984
- rotatedAt: issuedAt,
985
- issuedAt
986
- } : { issuedAt }), key.AccessKeyId);
987
- });
988
- if (outgoing) ctx.log(` ${urlKey} holds the new key. This deploy moves '${ctx.stage}' onto it; the next deploy after it deletes the old key ${outgoing}`);
989
- }
990
- /** How long a key issued this recently counts as new to IAM. */
991
- const NEW_KEY_WINDOW_MS = 6e5;
992
- /** The waits between asks while a new key becomes usable: about a minute. */
993
- let newKeyWaits = [
994
- 2e3,
995
- 4e3,
996
- 8e3,
997
- 15e3,
998
- 15e3,
999
- 15e3
1000
- ];
1001
- /** When the key in the URL was issued, if the stage's state says it was just now. */
1002
- function issuedJustNow(ctx, id, accessKeyId) {
1003
- const record = ctx.resources?.[`iam-access-key:${id}`];
1004
- const issuedAt = record?.data?.issuedAt;
1005
- if (record?.id !== accessKeyId || typeof issuedAt !== "string") return;
1006
- const age = Date.now() - Date.parse(issuedAt);
1007
- return age >= 0 && age < NEW_KEY_WINDOW_MS ? issuedAt : void 0;
1008
- }
1009
- /**
1010
- * Each provisioned bucket answers `HeadBucket` to the key in the stage's
1011
- * secrets — the one the apps will use. A bucket whose URL carries no key is
1012
- * not one this provider wrote, and the deploy's own check covers a URL that
1013
- * is missing.
1014
- *
1015
- * A failure is read by its status, never its name — a `HEAD` has no body,
1016
- * so SDK v3 calls a 301, 400 or 403 `Unknown` — and the message carries
1017
- * everything S3 said: status, error, region, request ids.
1018
- *
1019
- * @throws {BucketRegionMismatch} the bucket is in another region than its URL says
1020
- * @throws {ProvisionedBucketUnreachable}
1021
- */
1022
- async function verifyS3(ctx) {
1023
- const S3 = await import("@aws-sdk/client-s3");
1024
- for (const { id } of bucketConstructs(ctx.manifest)) {
1025
- const urlKey = (0, _geekmidas_manifest.provideKey)(id, "url");
1026
- const url = ctx.secrets[urlKey];
1027
- if (url === void 0) continue;
1028
- const address = _geekmidas_storage_s3_url.parse(url);
1029
- if (!address.accessKeyId || !address.secretAccessKey) continue;
1030
- const asked = address.region ?? ctx.config.region ?? "us-east-1";
1031
- const client = new S3.S3Client({
1032
- region: asked,
1033
- credentials: {
1034
- accessKeyId: address.accessKeyId,
1035
- secretAccessKey: address.secretAccessKey
1036
- },
1037
- ...address.endpoint ? { endpoint: address.endpoint } : {},
1038
- ...address.forcePathStyle ? { forcePathStyle: true } : {}
1039
- });
1040
- try {
1041
- let head = await headBucket(S3, client, address.bucket);
1042
- const issuedAt = issuedJustNow(ctx, id, address.accessKeyId);
1043
- let waited = 0;
1044
- if (!head.ok && head.status === 403 && issuedAt) {
1045
- ctx.log?.(` ${id}: waiting for the new key ${address.accessKeyId} to become active…`);
1046
- for (const wait of newKeyWaits) {
1047
- await new Promise((resolve) => setTimeout(resolve, wait));
1048
- waited += wait;
1049
- head = await headBucket(S3, client, address.bucket);
1050
- if (head.ok || head.status !== 403) break;
1051
- }
1052
- }
1053
- if (head.ok) continue;
1054
- const fail = (reason) => new require_workspace.ProvisionedBucketUnreachable(id, address.bucket, ctx.stage, reason);
1055
- const said = describeAnswer(head);
1056
- if (head.status === 301 || head.status === 400 && head.region && head.region !== asked) {
1057
- let where = head.region;
1058
- let located = "";
1059
- if (!where) {
1060
- const location = await bucketLocation(S3, client, address.bucket);
1061
- if ("region" in location) where = location.region;
1062
- else located = `; GetBucketLocation answered ${describeAnswer(location.failed)}`;
1063
- }
1064
- if (where && where !== asked) throw new require_workspace.BucketRegionMismatch(id, address.bucket, ctx.stage, urlKey, where, address.region, asked, said);
1065
- throw fail(`S3 redirected the request (${said}${located})`);
1066
- }
1067
- if (head.status === 404) throw fail(`it does not exist (${said})`);
1068
- if (head.status === 403) throw fail(`the key is refused — AccessDenied, or an invalid or not-yet-active key (${said})` + (issuedAt ? `. The key was issued at ${issuedAt} by this deploy, and IAM keys take seconds to become usable: it was still refused after waiting ${Math.round(waited / 1e3)}s` : ""));
1069
- throw fail(said);
1070
- } finally {
1071
- client.destroy();
1072
- }
1073
- }
1074
- }
1075
- //#endregion
1076
- //#region src/providers/registry.ts
1077
- /**
1078
- * The providers gkm ships, by kind and name — registered the way a deploy
1079
- * target's built-ins are (`target/builtins.ts`). A provider from a package is
1080
- * one more entry here once there is a loading story for it.
1081
- */
1082
- const BUILTIN_PROVIDERS = { objects: { s3: {
1083
- kind: "objects",
1084
- name: "s3",
1085
- check: require_workspace.checkS3Config,
1086
- provisioning: require_workspace.S3_PROVISIONING,
1087
- credentials: awsProvisioningCredentials,
1088
- runtimeKeys(manifest) {
1089
- return bucketConstructs(manifest).flatMap((b) => [(0, _geekmidas_manifest.provideKey)(b.id, "url"), ...b.servers.map((s) => (0, _geekmidas_manifest.provideKey)(s.id, "url"))]);
1090
- },
1091
- ensure: ensureS3,
1092
- verify: verifyS3
1093
- } } };
1094
- /** The provider `kind` names `name`, if gkm has one. */
1095
- function builtinProvider(kind, name) {
1096
- return Object.hasOwn(BUILTIN_PROVIDERS[kind], name) ? BUILTIN_PROVIDERS[kind][name] : void 0;
1097
- }
1098
- //#endregion
1099
- //#region src/providers/index.ts
1100
- /** The constructs of a kind: `objects` is every bucket. */
1101
- function constructsOf(manifest, kind) {
1102
- return Object.entries(manifest).filter(([, d]) => d.kind === kind).map(([id]) => id).sort();
1103
- }
1104
- /**
1105
- * What every deploy runs: each provider's `verify()` — the cheap check that
1106
- * what it created is still there and the stage's key reaches it. Nothing on
1107
- * the local stage, and nothing for a kind on `external` or `false` — a kind
1108
- * the stage has none of is the deploy's readiness check's to refuse.
1109
- */
1110
- async function verifyStageProviders(input) {
1111
- const verified = [];
1112
- for (const kind of require_seeds.PROVIDER_KINDS) {
1113
- if (constructsOf(input.manifest, kind).length === 0) continue;
1114
- const choice = require_workspace.stageProvider(input.workspace, kind, input.stage);
1115
- if (choice.mode !== "provider") continue;
1116
- const provider = builtinProvider(kind, choice.name);
1117
- await provider.verify({
1118
- workspace: input.workspace,
1119
- manifest: input.manifest,
1120
- stage: input.stage,
1121
- config: choice.config,
1122
- secrets: input.secrets,
1123
- ...input.resources ? { resources: input.resources } : {},
1124
- ...input.log ? { log: input.log } : {}
1125
- });
1126
- verified.push(`${kind}: ${provider.name}`);
1127
- }
1128
- return verified;
1129
- }
1130
- /**
1131
- * A stage whose provider creates its resources, and no credentials to create
1132
- * them with. Raised before anything is created, built or started.
1133
- */
1134
- var ProviderCredentialsMissing = class extends require_errors.GkmError {
1135
- stage;
1136
- kind;
1137
- provider;
1138
- ids;
1139
- env;
1140
- describe;
1141
- login;
1142
- constructor(stage, kind, provider, ids, env, describe, login) {
1143
- super(`deploy.${kind}.${stage} is ${provider}, so the deploy creates what ${ids.join(", ")} ${ids.length === 1 ? "is" : "are"} backed by on '${stage}' and writes ${ids.length === 1 ? "its key" : "their keys"} into the stage's secrets — and it found no ${provider} credentials to do it with. On this machine, supply ${describe}` + (login ? `, or run gkm login --provider ${login}` : "") + `. In CI, the step that runs the deploy needs them: the '${stage}' environment's role (AWS_ROLE_ARN, from gkm deploy:github), assumed before that step. With the keys set by hand instead, set deploy.${kind}.${stage} to 'external'.`);
1144
- this.stage = stage;
1145
- this.kind = kind;
1146
- this.provider = provider;
1147
- this.ids = ids;
1148
- this.env = env;
1149
- this.describe = describe;
1150
- this.login = login;
1151
- this.name = "ProviderCredentialsMissing";
1152
- }
1153
- };
1154
- /**
1155
- * `ensure()` for every provider the stage configures — find or create, fix
1156
- * drift, record in the stage's state, write the runtime keys into its
1157
- * secrets. Run by the deploy, which holds the stage's lock. A provider with
1158
- * no provisioning credentials stops the run with
1159
- * {@link ProviderCredentialsMissing} before anything is created.
1160
- */
1161
- async function provisionStage(options) {
1162
- const { workspace, stage, manifest } = options;
1163
- const dryRun = options.dryRun === true;
1164
- const env = options.env ?? process.env;
1165
- const log = options.log ?? ((line) => console.log(line));
1166
- const runnables = options.runnables ?? {};
1167
- const reports = [];
1168
- const configured = [];
1169
- for (const kind of require_seeds.PROVIDER_KINDS) {
1170
- const choice = require_workspace.stageProvider(workspace, kind, stage);
1171
- if (choice.mode !== "provider") {
1172
- reports.push({
1173
- kind,
1174
- mode: choice.mode,
1175
- actions: [],
1176
- planned: []
1177
- });
1178
- continue;
1179
- }
1180
- const provider = builtinProvider(kind, choice.name);
1181
- const report = {
1182
- kind,
1183
- mode: "provider",
1184
- provider: provider.name,
1185
- actions: [],
1186
- planned: []
1187
- };
1188
- reports.push(report);
1189
- const ids = constructsOf(manifest, kind);
1190
- if (ids.length === 0) continue;
1191
- const credential = await provider.credentials({
1192
- stage,
1193
- env,
1194
- ...options.profile ? { profile: options.profile } : {},
1195
- ...options.home ? { home: options.home } : {}
1196
- });
1197
- if (credential === void 0) throw new ProviderCredentialsMissing(stage, kind, provider.name, ids, provider.provisioning.env, provider.provisioning.describe, provider.provisioning.login);
1198
- configured.push({
1199
- kind,
1200
- provider,
1201
- config: choice.config,
1202
- credential,
1203
- report
1204
- });
1205
- }
1206
- if (configured.length === 0) return reports;
1207
- const identity = require_identity.deployIdentity(workspace, stage);
1208
- let secrets = (await options.secrets.read())?.custom ?? {};
1209
- for (const entry of configured) entry.report.planned = entry.provider.runtimeKeys(manifest).filter((key) => secrets[key] === void 0);
1210
- const state = dryRun ? await readOnlyState(options.state, stage) : journalState(await require_seeds.DeployJournal.open(options.state, stage, () => deploysWithCompose(workspace) ? require_seeds.createComposeState(stage) : require_seeds.createEmptyState(stage, "", "")));
1211
- const writeSecrets = async (values) => {
1212
- if (dryRun) return;
1213
- const stored = await options.secrets.read() ?? require_seeds.initStageSecrets(stage);
1214
- const next = {
1215
- ...stored,
1216
- custom: {
1217
- ...stored.custom,
1218
- ...values
1219
- },
1220
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1221
- };
1222
- await options.secrets.write(next);
1223
- secrets = next.custom;
1224
- };
1225
- for (const entry of configured) {
1226
- log(`☁️ ${entry.kind}: ${entry.provider.name}${dryRun ? " (dry run)" : ""}`);
1227
- await entry.provider.ensure({
1228
- workspace,
1229
- manifest,
1230
- runnables,
1231
- stage,
1232
- identity,
1233
- config: entry.config,
1234
- credential: entry.credential,
1235
- get secrets() {
1236
- return secrets;
1237
- },
1238
- state,
1239
- dryRun,
1240
- rotateKeys: options.rotateKeys === true,
1241
- retireOldKeys: options.retireOldKeys === true,
1242
- async change(action, apply) {
1243
- if (!dryRun) await apply();
1244
- entry.report.actions.push(action);
1245
- log(` ${dryRun ? "would " : ""}${action.change} — ${action.resource}`);
1246
- },
1247
- writeSecrets,
1248
- log
1249
- });
1250
- if (entry.report.actions.length === 0) log(" up to date");
1251
- }
1252
- return reports;
1253
- }
1254
- /** The journal as `ensure()` sees it. */
1255
- function journalState(journal) {
1256
- return {
1257
- record: (key) => journal.record(key),
1258
- pending: (entry) => journal.pending(entry),
1259
- ready: (entry, id) => journal.ready(entry, id),
1260
- lastDeployedAt: journal.existed ? journal.state.lastDeployedAt : void 0
1261
- };
1262
- }
1263
- /** What a dry run reads, and the writes it does not make. */
1264
- async function readOnlyState(store, stage) {
1265
- const stored = await store.read(stage);
1266
- return {
1267
- record: (key) => stored?.resources[key],
1268
- pending: async () => {},
1269
- ready: async () => {},
1270
- ...stored ? { lastDeployedAt: stored.state.lastDeployedAt } : {}
1271
- };
1272
- }
1273
- //#endregion
1274
- //#region src/secrets/stale.ts
1275
- /**
1276
- * Stored secrets an older gkm generated that now shadow a derived value.
1277
- *
1278
- * Before constructs, initialising a stage wrote an address for each app into
1279
- * its custom secrets: `<APP>_DATABASE_URL` as a `postgresql://…@localhost`
1280
- * URL with a password of its own, and `http://localhost:<port>` for a site or
1281
- * an auth server. Those keys are now a construct's — `database.schema('AuthDatabase')`
1282
- * provides `AUTH_DATABASE_URL`, `new BetterAuth('Auth')` provides `AUTH_URL`
1283
- * — and a deploy derives them. A value the stage holds is a value set by hand,
1284
- * and set by hand wins: the container is handed `localhost`, where nothing
1285
- * answers, with a password no role has.
1286
- *
1287
- * So a deploy refuses such a stage rather than run it, naming each key and
1288
- * the command that removes it. Nothing is deleted for the user: the value is
1289
- * theirs, and only they can say it is stale. A URL that names a real host — a
1290
- * managed database — is a deliberate choice and still wins.
1291
- */
1292
- /** The kinds whose URL an older gkm wrote into a stage's secrets. */
1293
- const ADDRESSED = /* @__PURE__ */ new Set([
1294
- "database",
1295
- "database-reader",
1296
- "database-schema",
1297
- "rest-api",
1298
- "site"
1299
- ]);
1300
- /** Hosts that are this machine — never anything, inside a container. */
1301
- const LOOPBACK = /* @__PURE__ */ new Set([
1302
- "localhost",
1303
- "127.0.0.1",
1304
- "[::1]",
1305
- "::1"
1306
- ]);
1307
- /**
1308
- * A stage holds a construct's address as a custom secret, pointing at
1309
- * `localhost` — what an older `gkm secrets:init`, `gkm setup` or `gkm init`
1310
- * generated. Set by hand wins over derived, so the app would be handed it.
1311
- */
1312
- var StaleStageSecrets = class extends require_errors.GkmError {
1313
- stage;
1314
- stale;
1315
- constructor(stage, stale) {
1316
- const one = stale.length === 1;
1317
- super(`The stage '${stage}' holds ${one ? "a value" : "values"} an older gkm generated for ${one ? "an address a construct" : "addresses constructs"} now ${one ? "provides" : "provide"}:\n` + stale.map((s) => ` ${s.key}: ${s.construct}'s, stored pointing at ${s.host}`).join("\n") + `
1318
- A stored value wins over the derived one, so the app would be handed an address where nothing answers inside its container. Remove ${one ? "it" : "each"}, and the construct's own value is used:\n` + stale.map((s) => ` gkm secrets:unset ${s.key} --stage ${stage}`).join("\n") + "\nA managed service set with its real host is not affected.");
1319
- this.stage = stage;
1320
- this.stale = stale;
1321
- this.name = "StaleStageSecrets";
1322
- }
1323
- };
1324
- /** The host a stored value names, if it is a URL. */
1325
- function hostOf(value) {
1326
- try {
1327
- return new URL(value).hostname;
1328
- } catch {
1329
- return;
1330
- }
1331
- }
1332
- /**
1333
- * Each stored key that a construct provides an address for, holding an
1334
- * address on this machine.
1335
- */
1336
- function staleStageSecrets(manifest, supplied) {
1337
- const stale = [];
1338
- for (const [id, declaration] of Object.entries(manifest)) {
1339
- if (!ADDRESSED.has(declaration.kind)) continue;
1340
- const key = (0, _geekmidas_manifest.providedKeyFor)(id, declaration.kind, "url");
1341
- const value = supplied[key];
1342
- if (value === void 0) continue;
1343
- const host = hostOf(value);
1344
- if (host === void 0 || !LOOPBACK.has(host)) continue;
1345
- stale.push({
1346
- key,
1347
- construct: id,
1348
- host
1349
- });
1350
- }
1351
- return stale.sort((a, b) => a.key.localeCompare(b.key));
1352
- }
1353
- /**
1354
- * Refuse a stage whose stored secrets would shadow a construct's address with
1355
- * `localhost`.
1356
- *
1357
- * @throws {StaleStageSecrets} naming each key and the command removing it
1358
- */
1359
- function assertNoStaleSecrets(options) {
1360
- const stale = staleStageSecrets(options.manifest, options.supplied);
1361
- if (stale.length > 0) throw new StaleStageSecrets(options.stage, stale);
1362
- }
1363
- //#endregion
1364
- //#region src/deploy/readiness.ts
1365
- /**
1366
- * Whether a stage is ready to be deployed: the one check, run once by every
1367
- * deploy through a server target — after the stage's providers have created
1368
- * what they create and written its keys, and before the target touches
1369
- * anything.
1370
- *
1371
- * A build is not a deploy. Images carry no stage's keys, so a build-only run
1372
- * (`gkm compose --build --push`) never calls this: a key the deploy itself
1373
- * writes — a provider's bucket URL — is not there yet when CI builds, and
1374
- * must not stop the build.
1375
- */
1376
- /**
1377
- * The stage has every key it needs, read from its secrets as the providers
1378
- * left them:
1379
- *
1380
- * 1. no kind it declares is one the stage set to `false`;
1381
- * 2. its mail and storage are its own — or a dev service, where allowed,
1382
- * reported once, loudly;
1383
- * 3. what its providers created is still there, and its key reaches it;
1384
- * 4. no key holds an address an older gkm stored for what a construct now
1385
- * provides;
1386
- * 5. each third party's credentials match their construct's schema.
1387
- *
1388
- * The local stage derives its mail and storage, so only 4 and 5 apply to it.
1389
- *
1390
- * @throws {StageProviderDisabled}
1391
- * @throws {ExternalServicesNotConfigured} naming every missing key at once
1392
- * @throws {StaleStageSecrets}
1393
- * @throws {CredentialsInvalid}
1394
- */
1395
- async function assertStageReady(ctx) {
1396
- const { workspace, manifest, stage } = ctx;
1397
- const supplied = (await ctx.secrets.read())?.custom ?? {};
1398
- if (stage !== workspace.stages.local) {
1399
- require_seeds.assertStageProvidersEnabled(workspace, manifest, stage);
1400
- const domain = workspace.domains?.[stage];
1401
- const services = require_seeds.externalServices({
1402
- stage,
1403
- declarations: require_seeds.stageServiceDeclarations({
1404
- manifest,
1405
- ...ctx.runnables ? { runnables: ctx.runnables } : {}
1406
- }),
1407
- supplied,
1408
- allow: ctx.allowDevServices,
1409
- ...domain ? { domain } : {},
1410
- providers: require_seeds.stageProviderNotes(workspace, stage)
1411
- });
1412
- if (services.missing.length > 0) throw new require_seeds.ExternalServicesNotConfigured(stage, services.missing);
1413
- require_seeds.reportDevServices(ctx, require_seeds.devServicesUsed(services));
1414
- const verified = await verifyStageProviders({
1415
- workspace,
1416
- manifest,
1417
- stage,
1418
- secrets: supplied,
1419
- resources: (await ctx.state.read(stage))?.resources ?? {},
1420
- log: (line) => ctx.logger.info(line)
1421
- });
1422
- for (const line of verified) ctx.logger.info(`✓ ${line} verified`);
1423
- }
1424
- assertNoStaleSecrets({
1425
- manifest,
1426
- stage,
1427
- supplied
1428
- });
1429
- await require_credentialSchemas.assertStageCredentials({
1430
- root: workspace.root,
1431
- patterns: require_seeds.constructGlobs(workspace),
1432
- manifest,
1433
- stage,
1434
- supplied
1435
- });
1436
- }
1437
- //#endregion
1438
- //#region src/deploy/orchestrate.ts
1439
- /**
1440
- * The run around a target: what every deploy does whatever it deploys
1441
- * through.
1442
- *
1443
- * It loads the workspace, resolves the target, works out the apps and the
1444
- * identity, takes the stage's lock, and calls the target's phases in order,
1445
- * reporting each as it starts, finishes or fails. Everything that is about
1446
- * *where* the stage goes is the target's.
1447
- */
1448
- /** Apps were asked for by name that the workspace does not have. */
1449
- var UnknownDeployApps = class extends require_errors.GkmError {
1450
- apps;
1451
- available;
1452
- constructor(apps, available) {
1453
- super(`Unknown apps: ${apps.join(", ")}\nAvailable apps: ${available.join(", ")}`);
1454
- this.apps = apps;
1455
- this.available = available;
1456
- this.name = "UnknownDeployApps";
1457
- }
1458
- };
1459
- /** Every app asked for deploys through some other target. */
1460
- var NoDeployableApps = class extends require_errors.GkmError {
1461
- stage;
1462
- target;
1463
- constructor(stage, target) {
1464
- super(`No apps to deploy through "${target}": every selected app deploys somewhere else. Pick the target with --target, or set each app's deploy in gkm.config.ts.`);
1465
- this.stage = stage;
1466
- this.target = target;
1467
- this.name = "NoDeployableApps";
1468
- }
1469
- };
1470
- /** A build-only run through a target with no build phase. */
1471
- var TargetBuildsNothing = class extends require_errors.GkmError {
1472
- target;
1473
- constructor(target) {
1474
- super(`"${target}" has no build phase, so a build-only run would do nothing. Deploy it in full, or build through a target that builds images (compose).`);
1475
- this.target = target;
1476
- this.name = "TargetBuildsNothing";
1477
- }
1478
- };
1479
- /** A failed rollback, after the failure that called for it. */
1480
- var RollbackFailed = class extends Error {
1481
- target;
1482
- failure;
1483
- constructor(target, failure, cause) {
1484
- super(`Deploying through "${target}" failed, and so did rolling it back: ${cause instanceof Error ? cause.message : String(cause)}. The stage may be part-released; deploy again, or roll it back by hand. The first failure: ${failure instanceof Error ? failure.message : String(failure)}`, { cause });
1485
- this.target = target;
1486
- this.failure = failure;
1487
- this.name = "RollbackFailed";
1488
- }
1489
- };
1490
- /**
1491
- * Generate image tag from stage and timestamp
1492
- */
1493
- function generateTag(stage) {
1494
- return `${stage}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
1495
- }
1496
- /** Why an app that deploys through another target is left out. */
1497
- function elsewhere(target, stage) {
1498
- const instead = require_define.builtinTarget(target)?.instead?.(stage);
1499
- if (instead) return `it deploys through "${target}" — ${instead}`;
1500
- return `it deploys through "${target}" — run \`gkm deploy --target ${target} --stage ${stage}\``;
1501
- }
1502
- /**
1503
- * Deploy a workspace's stage through its target.
1504
- *
1505
- * The engine under `deploy()` and `gkm deploy`. It never prompts and never
1506
- * exits: credentials come from `ctx.credentials`, progress goes to
1507
- * `ctx.emit` and to `output`, and every failure is thrown.
1508
- *
1509
- * @internal
1510
- */
1511
- async function runDeploy(source, request, ctx) {
1512
- const { stage } = request;
1513
- const redactor = ctx.redactor ?? new Redactor();
1514
- const emit = (event) => ctx.emit(event.type === "log" ? {
1515
- ...event,
1516
- message: redactor.redact(event.message)
1517
- } : event);
1518
- /** Run one phase between its events. */
1519
- const phase = async (name, body) => {
1520
- ctx.signal?.throwIfAborted();
1521
- emit({
1522
- type: "phase.started",
1523
- phase: name
1524
- });
1525
- try {
1526
- const value = await body();
1527
- emit({
1528
- type: "phase.finished",
1529
- phase: name
1530
- });
1531
- return value;
1532
- } catch (error) {
1533
- emit({
1534
- type: "phase.failed",
1535
- phase: name,
1536
- error: require_sniffer.eventError(error)
1537
- });
1538
- throw error;
1539
- }
1540
- };
1541
- ctx.signal?.throwIfAborted();
1542
- emit({
1543
- type: "phase.started",
1544
- phase: "validate"
1545
- });
1546
- let prepared;
1547
- try {
1548
- prepared = await prepare(source, request, ctx, emit, redactor);
1549
- } catch (error) {
1550
- emit({
1551
- type: "phase.failed",
1552
- phase: "validate",
1553
- error: require_sniffer.eventError(error)
1554
- });
1555
- throw error;
1556
- }
1557
- const { resolved, phaseCtx, store } = prepared;
1558
- const { target } = resolved;
1559
- const resources = !ctx.buildOnly && phaseCtx.stage !== phaseCtx.workspace.stages.local;
1560
- const provision = async () => {
1561
- if (!request.skipDns && resolved.target.runtime === "server") try {
1562
- await require_dns.dnsCredentials(phaseCtx.stage, require_dns.stageDnsDomains(phaseCtx.stage, phaseCtx.workspace.domains, phaseCtx.workspace.dns), ctx.credentials);
1563
- } catch (error) {
1564
- emit({
1565
- type: "phase.failed",
1566
- phase: "validate",
1567
- error: require_sniffer.eventError(error)
1568
- });
1569
- throw error;
1570
- }
1571
- await provisionResources(phaseCtx, request, ctx, store, emit);
1572
- };
1573
- if (ctx.dryRun) {
1574
- if (resources) await provision();
1575
- const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1576
- await phase("plan", () => target.plan(phaseCtx, run));
1577
- return target.result(phaseCtx, run);
1578
- }
1579
- if (ctx.buildOnly) {
1580
- if (!target.build) throw new TargetBuildsNothing(resolved.name);
1581
- const run = await validate(phaseCtx, emit, () => target.validate(phaseCtx));
1582
- await phase("build", () => target.build(phaseCtx, run));
1583
- return target.result(phaseCtx, run);
1584
- }
1585
- let lock;
1586
- try {
1587
- require_sniffer.assertStateOutlivesRun(phaseCtx.workspace, stage, "deploy");
1588
- lock = await store.lock(stage, { operation: "deploy" });
1589
- } catch (error) {
1590
- emit({
1591
- type: "phase.failed",
1592
- phase: "validate",
1593
- error: require_sniffer.eventError(error)
1594
- });
1595
- throw error;
1596
- }
1597
- try {
1598
- try {
1599
- await require_sniffer.assertStateRoom(store, stage);
1600
- } catch (error) {
1601
- emit({
1602
- type: "phase.failed",
1603
- phase: "validate",
1604
- error: require_sniffer.eventError(error)
1605
- });
1606
- throw error;
1607
- }
1608
- if (resources) await provision();
1609
- const run = await validate(phaseCtx, emit, () => readyToDeploy(target, phaseCtx));
1610
- if (target.provision) await phase("provision", () => target.provision(phaseCtx, run));
1611
- if (target.build) await phase("build", () => target.build(phaseCtx, run));
1612
- let releasing = "release";
1613
- try {
1614
- await phase("release", () => target.release(phaseCtx, run));
1615
- releasing = "verify";
1616
- if (target.verify) await phase("verify", () => target.verify(phaseCtx, run));
1617
- } catch (error) {
1618
- if (ctx.signal?.aborted || !target.capabilities.rollback) throw error;
1619
- if (!target.rollback) throw error;
1620
- try {
1621
- await phase("rollback", () => target.rollback(phaseCtx, run, {
1622
- phase: releasing,
1623
- error
1624
- }));
1625
- } catch (rollbackError) {
1626
- throw new RollbackFailed(resolved.name, error, rollbackError);
1627
- }
1628
- throw error;
1629
- }
1630
- return await target.result(phaseCtx, run);
1631
- } finally {
1632
- await lock.release();
1633
- }
1634
- }
1635
- /**
1636
- * The stage's providers, run inside the validate phase. A dry run plans them
1637
- * and, so the checks after it see the stage as the run would leave it, reads
1638
- * the keys they would write as placeholders.
1639
- */
1640
- async function provisionResources(phaseCtx, request, ctx, store, emit) {
1641
- try {
1642
- const reports = await provisionStage({
1643
- workspace: phaseCtx.workspace,
1644
- stage: phaseCtx.stage,
1645
- manifest: phaseCtx.manifest,
1646
- runnables: phaseCtx.runnables ?? {},
1647
- secrets: phaseCtx.secrets,
1648
- state: store,
1649
- dryRun: ctx.dryRun,
1650
- ...request.rotateKeys ? { rotateKeys: true } : {},
1651
- ...request.retireOldKeys ? { retireOldKeys: true } : {},
1652
- ...ctx.home ? { home: ctx.home } : {},
1653
- log: (line) => phaseCtx.logger.info(line)
1654
- });
1655
- if (!ctx.dryRun) return;
1656
- const planned = reports.flatMap((r) => r.planned);
1657
- if (planned.length === 0) return;
1658
- const secrets = phaseCtx.secrets;
1659
- phaseCtx.secrets = {
1660
- ...secrets,
1661
- async read() {
1662
- const stored = await secrets.read() ?? require_seeds.initStageSecrets(phaseCtx.stage);
1663
- const custom = { ...stored.custom };
1664
- for (const key of planned) custom[key] ??= PLANNED_BY_THE_DEPLOY;
1665
- return {
1666
- ...stored,
1667
- custom
1668
- };
1669
- }
1670
- };
1671
- } catch (error) {
1672
- emit({
1673
- type: "phase.failed",
1674
- phase: "validate",
1675
- error: require_sniffer.eventError(error)
1676
- });
1677
- throw error;
1678
- }
1679
- }
1680
- /** What a dry run reads for a key its providers would write. */
1681
- const PLANNED_BY_THE_DEPLOY = "s3://planned-by-this-deploy";
1682
- /**
1683
- * What a deploy validates: the stage ready to be deployed — every key it
1684
- * needs, read as its providers left them — then what the target would run,
1685
- * then whatever only the target checks. A build-only run validates the
1686
- * target's run alone: it calls neither readiness check.
1687
- */
1688
- async function readyToDeploy(target, phaseCtx) {
1689
- if (target.runtime === "server") await assertStageReady(phaseCtx);
1690
- const run = await target.validate(phaseCtx);
1691
- await target.ready?.(phaseCtx, run);
1692
- return run;
1693
- }
1694
- /** `body`, then the run's `deploy.started`, inside the validate phase. */
1695
- async function validate(phaseCtx, emit, body) {
1696
- try {
1697
- const run = await body();
1698
- const skipped = new Set(phaseCtx.skipped.map((s) => s.app));
1699
- emit({
1700
- type: "deploy.started",
1701
- stage: phaseCtx.stage,
1702
- target: phaseCtx.target,
1703
- identity: phaseCtx.identity.key,
1704
- tag: phaseCtx.tag,
1705
- apps: phaseCtx.apps.filter((app) => !skipped.has(app)),
1706
- dryRun: phaseCtx.dryRun
1707
- });
1708
- emit({
1709
- type: "phase.finished",
1710
- phase: "validate"
1711
- });
1712
- return run;
1713
- } catch (error) {
1714
- emit({
1715
- type: "phase.failed",
1716
- phase: "validate",
1717
- error: require_sniffer.eventError(error)
1718
- });
1719
- throw error;
1720
- }
1721
- }
1722
- /** Everything the phases are handed, worked out before the first of them. */
1723
- async function prepare(source, request, ctx, emit, redactor) {
1724
- const { stage } = request;
1725
- const configured = typeof source === "function" ? await source() : source;
1726
- const local = stage === configured.stages.local;
1727
- if (!local) require_workspace.assertDeployedStage(configured.stages, stage);
1728
- const targetName = request.target ?? configured.deploy?.default ?? "dokploy";
1729
- const resolved = await require_resolve.resolveTarget(targetName, {
1730
- workspace: configured,
1731
- stage,
1732
- ...ctx.targets ? { host: ctx.targets } : {}
1733
- });
1734
- if (local && !resolved.target.capabilities.localStage) require_workspace.assertDeployedStage(configured.stages, stage);
1735
- const options = await require_resolve.parseTargetOptions(resolved);
1736
- const allowDevServices = request.allowDevServices === true;
1737
- if (allowDevServices && resolved.target.runtime === "aws") throw new require_seeds.DevServicesNeedServerTarget(targetName);
1738
- const runnables = {};
1739
- const background = {};
1740
- const manifest = await require_discover.discover({
1741
- patterns: require_seeds.constructGlobs(configured),
1742
- cwd: configured.root,
1743
- runnables,
1744
- background
1745
- });
1746
- require_workspace.resolveStageTelemetry({
1747
- ...configured.deploy?.telemetry ? { telemetry: configured.deploy.telemetry } : {},
1748
- stage,
1749
- local,
1750
- target: targetName,
1751
- runtime: resolved.target.runtime,
1752
- selfHosted: resolved.target.capabilities.selfHostedTelemetry === true,
1753
- used: require_seeds.usesTelemetry(manifest)
1754
- });
1755
- const units = require_derive.derivedApps(manifest, configured);
1756
- const workspace = Object.keys(units).length > 0 ? {
1757
- ...configured,
1758
- apps: units
1759
- } : configured;
1760
- const identity = require_identity.deployIdentity(workspace, stage);
1761
- const tag = request.tag ?? (resolved.target.tag ? await resolved.target.tag({
1762
- cwd: workspace.root,
1763
- stage
1764
- }) : generateTag(stage));
1765
- const buildOrder = require_workspace.getAppBuildOrder(workspace);
1766
- let selected = buildOrder;
1767
- if (request.apps && request.apps.length > 0) {
1768
- const unknown = request.apps.filter((name) => !workspace.apps[name]);
1769
- if (unknown.length > 0) throw new UnknownDeployApps(unknown, Object.keys(workspace.apps));
1770
- selected = buildOrder.filter((name) => request.apps.includes(name));
1771
- }
1772
- const skipped = [];
1773
- const skip = (app, reason) => {
1774
- skipped.push({
1775
- app,
1776
- reason
1777
- });
1778
- emit({
1779
- type: "app.skipped",
1780
- app,
1781
- reason
1782
- });
1783
- };
1784
- const byDefault = configured.deploy?.default ?? "dokploy";
1785
- const apps = selected.filter((name) => {
1786
- const own = workspace.apps[name].resolvedDeployTarget;
1787
- const deploysThrough = own === byDefault ? targetName : own;
1788
- if (deploysThrough === targetName) return true;
1789
- skip(name, elsewhere(deploysThrough, stage));
1790
- return false;
1791
- });
1792
- if (apps.length === 0) throw new NoDeployableApps(stage, targetName);
1793
- const store = await require_sniffer.createStateStore({
1794
- config: workspace.state,
1795
- workspaceRoot: workspace.root,
1796
- workspaceName: workspace.name,
1797
- namespace: workspace.deploy?.namespace
1798
- });
1799
- const secrets = await deploySecrets(workspace, stage, redactor, { ...ctx.home ? { home: ctx.home } : {} });
1800
- const line = (level) => (message) => emit({
1801
- type: "log",
1802
- level,
1803
- message
1804
- });
1805
- const logger = {
1806
- info: line("info"),
1807
- warn: line("warn"),
1808
- error: line("error")
1809
- };
1810
- return {
1811
- resolved,
1812
- phaseCtx: {
1813
- target: targetName,
1814
- cwd: workspace.root,
1815
- stage,
1816
- tag,
1817
- tagGiven: request.tag !== void 0,
1818
- apps,
1819
- skipped,
1820
- identity,
1821
- workspace,
1822
- manifest,
1823
- runnables,
1824
- background,
1825
- options,
1826
- dryRun: ctx.dryRun,
1827
- atomic: request.atomic ?? false,
1828
- allowDevServices,
1829
- ...request.skipDns ? { skipDns: true } : {},
1830
- credentials: ctx.credentials,
1831
- state: store,
1832
- secrets,
1833
- logger,
1834
- signal: ctx.signal ?? new AbortController().signal,
1835
- childOutput: ctx.childOutput ?? "inherit",
1836
- emit,
1837
- skip,
1838
- name: (resource) => require_identity.applicationName(identity, resource)
1839
- },
1840
- store
1841
- };
1842
- }
1843
- //#endregion
1844
- //#region src/deploy/deploy.ts
1845
- /**
1846
- * `deploy()`: a deploy as a library call.
1847
- *
1848
- * `gkm deploy` could only be driven from an interactive terminal: it prompted
1849
- * for what it lacked and exited the process on failure, worked out of
1850
- * `process.cwd()`, and reported progress by printing. Here the caller says
1851
- * where the project is, hands over the credentials and a signal, and gets back
1852
- * a run — events to iterate while it goes, and a structured result at the end.
1853
- * Nothing below this asks a person anything or ends the process; `gkm deploy`
1854
- * is a thin wrapper that does both.
1855
- */
1856
- /**
1857
- * Every event a run emits, kept so that each iteration — however late it
1858
- * starts — sees the run from its first event to its last.
1859
- */
1860
- var EventLog = class {
1861
- events = [];
1862
- closed = false;
1863
- waiting = [];
1864
- push(event) {
1865
- this.events.push(event);
1866
- this.wake();
1867
- }
1868
- close() {
1869
- this.closed = true;
1870
- this.wake();
1871
- }
1872
- wake() {
1873
- const waiting = this.waiting;
1874
- this.waiting = [];
1875
- for (const resume of waiting) resume();
1876
- }
1877
- async *iterate() {
1878
- let next = 0;
1879
- while (true) if (next < this.events.length) yield this.events[next++];
1880
- else if (this.closed) return;
1881
- else await new Promise((resume) => this.waiting.push(resume));
1882
- }
1883
- };
1884
- function forward(logger, level, message) {
1885
- if (!logger) return;
1886
- if (level === "info") logger.info(message);
1887
- else if (level === "error" && logger.error) logger.error(message);
1888
- else logger.warn(message);
1889
- }
1890
- /**
1891
- * Deploy a project's stage.
1892
- *
1893
- * ```ts
1894
- * import { deploy } from '@geekmidas/cli/deploy';
1895
- *
1896
- * const run = deploy({ cwd: '/srv/checkouts/shop', stage: 'production' });
1897
- * for await (const event of run) {
1898
- * if (event.type === 'app.deployed') console.log(event.app, event.url);
1899
- * }
1900
- * const result = await run.result;
1901
- * ```
1902
- *
1903
- * The run starts at once; iterating it is optional, and an iteration started
1904
- * late still sees every event from the first.
1905
- */
1906
- function deploy(input) {
1907
- const log = new EventLog();
1908
- const redactor = new Redactor();
1909
- const emit = (event) => {
1910
- const masked = event.type === "log" ? {
1911
- ...event,
1912
- message: redactor.redact(event.message)
1913
- } : event;
1914
- log.push(masked);
1915
- if (masked.type === "log") forward(input.logger, masked.level, masked.message);
1916
- };
1917
- const ctx = {
1918
- emit,
1919
- credentials: input.credentials ?? require_credentials.storedCredentials({ home: input.home ?? require_run.gkmHome() }),
1920
- dryRun: input.dryRun ?? false,
1921
- ...input.buildOnly ? { buildOnly: true } : {},
1922
- home: input.home ?? require_run.gkmHome(),
1923
- redactor,
1924
- ...input.signal ? { signal: input.signal } : {},
1925
- ...input.childOutput ? { childOutput: input.childOutput } : {},
1926
- ...input.targets ? { targets: input.targets } : {}
1927
- };
1928
- const result = require_discover.withOutput((level, message) => emit({
1929
- type: "log",
1930
- level,
1931
- message
1932
- }), async () => {
1933
- try {
1934
- input.signal?.throwIfAborted();
1935
- const sandbox = input.sandbox ?? new require_local.LocalSandbox({ root: require_config.findWorkspaceRoot((0, node_path.resolve)(input.cwd)) });
1936
- const deployed = await require_sandbox.withSandbox(sandbox, () => runDeploy(() => load(input, sandbox), {
1937
- stage: input.stage,
1938
- ...input.target ? { target: input.target } : {},
1939
- ...input.tag ? { tag: input.tag } : {},
1940
- ...input.apps ? { apps: input.apps } : {},
1941
- ...input.atomic ? { atomic: true } : {},
1942
- ...input.allowDevServices ? { allowDevServices: input.allowDevServices } : {},
1943
- ...input.skipDns ? { skipDns: true } : {},
1944
- ...input.rotateKeys ? { rotateKeys: true } : {},
1945
- ...input.retireOldKeys ? { retireOldKeys: true } : {}
1946
- }, ctx));
1947
- emit({
1948
- type: "deploy.finished",
1949
- result: deployed
1950
- });
1951
- return deployed;
1952
- } catch (error) {
1953
- emit({
1954
- type: "deploy.failed",
1955
- error: require_sniffer.eventError(error)
1956
- });
1957
- throw error;
1958
- } finally {
1959
- log.close();
1960
- }
1961
- });
1962
- result.catch(() => {});
1963
- return {
1964
- result,
1965
- [Symbol.asyncIterator]: () => log.iterate()
1966
- };
1967
- }
1968
- /**
1969
- * The workspace at `input.cwd`. The stage is checked by the run, once it
1970
- * knows the target: one that runs on this machine may take the local stage.
1971
- */
1972
- async function load(input, sandbox) {
1973
- const { workspace } = await require_config.loadWorkspaceConfig((0, node_path.resolve)(input.cwd), { sandbox });
1974
- return workspace;
1975
- }
1976
- //#endregion
1977
- Object.defineProperty(exports, "IAM_USER_PATH", {
1978
- enumerable: true,
1979
- get: function() {
1980
- return IAM_USER_PATH;
1981
- }
1982
- });
1983
- Object.defineProperty(exports, "NoDeployableApps", {
1984
- enumerable: true,
1985
- get: function() {
1986
- return NoDeployableApps;
1987
- }
1988
- });
1989
- Object.defineProperty(exports, "RollbackFailed", {
1990
- enumerable: true,
1991
- get: function() {
1992
- return RollbackFailed;
1993
- }
1994
- });
1995
- Object.defineProperty(exports, "TargetBuildsNothing", {
1996
- enumerable: true,
1997
- get: function() {
1998
- return TargetBuildsNothing;
1999
- }
2000
- });
2001
- Object.defineProperty(exports, "UnknownDeployApps", {
2002
- enumerable: true,
2003
- get: function() {
2004
- return UnknownDeployApps;
2005
- }
2006
- });
2007
- Object.defineProperty(exports, "bucketName", {
2008
- enumerable: true,
2009
- get: function() {
2010
- return bucketName;
2011
- }
2012
- });
2013
- Object.defineProperty(exports, "deploy", {
2014
- enumerable: true,
2015
- get: function() {
2016
- return deploy;
2017
- }
2018
- });
2019
- Object.defineProperty(exports, "deploysWithCompose", {
2020
- enumerable: true,
2021
- get: function() {
2022
- return deploysWithCompose;
2023
- }
2024
- });
2025
- Object.defineProperty(exports, "iamUserName", {
2026
- enumerable: true,
2027
- get: function() {
2028
- return iamUserName;
2029
- }
2030
- });
2031
-
2032
- //# sourceMappingURL=deploy-CbJMJsgX.cjs.map