@geekmidas/cli 10.0.0-alpha.63 → 10.0.0-alpha.64

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 (193) hide show
  1. package/dist/{HostingerProvider-mJ7YruxH.cjs → HostingerProvider-Bx2lHHvu.cjs} +3 -3
  2. package/dist/{HostingerProvider-mJ7YruxH.cjs.map → HostingerProvider-Bx2lHHvu.cjs.map} +1 -1
  3. package/dist/{HostingerProvider-DBBwpDjn.mjs → HostingerProvider-Cd4aS5Kj.mjs} +2 -2
  4. package/dist/{HostingerProvider-DBBwpDjn.mjs.map → HostingerProvider-Cd4aS5Kj.mjs.map} +1 -1
  5. package/dist/{LegacyStateStore-CP7SZwTP.cjs → LegacyStateStore-C2abV49N.cjs} +2 -2
  6. package/dist/{LegacyStateStore-CP7SZwTP.cjs.map → LegacyStateStore-C2abV49N.cjs.map} +1 -1
  7. package/dist/{LegacyStateStore-Q3GmKOdw.mjs → LegacyStateStore-DIgkGaUP.mjs} +2 -2
  8. package/dist/{LegacyStateStore-Q3GmKOdw.mjs.map → LegacyStateStore-DIgkGaUP.mjs.map} +1 -1
  9. package/dist/{LocalStateStore-BGIXcrvX.mjs → LocalStateStore-Cy1ZBW7U.mjs} +2 -2
  10. package/dist/{LocalStateStore-BGIXcrvX.mjs.map → LocalStateStore-Cy1ZBW7U.mjs.map} +1 -1
  11. package/dist/{LocalStateStore-sS8mvLeq.cjs → LocalStateStore-DiJqKyPy.cjs} +2 -2
  12. package/dist/{LocalStateStore-sS8mvLeq.cjs.map → LocalStateStore-DiJqKyPy.cjs.map} +1 -1
  13. package/dist/{OpenApiTsGenerator-CjHWFRDd.cjs → OpenApiTsGenerator-BWuDRHe9.cjs} +2 -2
  14. package/dist/{OpenApiTsGenerator-CjHWFRDd.cjs.map → OpenApiTsGenerator-BWuDRHe9.cjs.map} +1 -1
  15. package/dist/{OpenApiTsGenerator-CnAwhGxi.mjs → OpenApiTsGenerator-C6v-IeHt.mjs} +2 -2
  16. package/dist/{OpenApiTsGenerator-CnAwhGxi.mjs.map → OpenApiTsGenerator-C6v-IeHt.mjs.map} +1 -1
  17. package/dist/{S3StateStore-D7l_lWJ3.mjs → S3StateStore-D3x6ivBL.mjs} +2 -2
  18. package/dist/{S3StateStore-D7l_lWJ3.mjs.map → S3StateStore-D3x6ivBL.mjs.map} +1 -1
  19. package/dist/{S3StateStore-6jqITH2F.cjs → S3StateStore-Ds0V1Lgm.cjs} +2 -2
  20. package/dist/{S3StateStore-6jqITH2F.cjs.map → S3StateStore-Ds0V1Lgm.cjs.map} +1 -1
  21. package/dist/{SSMStateStore-B__F7IJa.cjs → SSMStateStore-CLipvx47.cjs} +2 -2
  22. package/dist/{SSMStateStore-B__F7IJa.cjs.map → SSMStateStore-CLipvx47.cjs.map} +1 -1
  23. package/dist/{SSMStateStore-CAQDVpoc.mjs → SSMStateStore-DfF174xQ.mjs} +2 -2
  24. package/dist/{SSMStateStore-CAQDVpoc.mjs.map → SSMStateStore-DfF174xQ.mjs.map} +1 -1
  25. package/dist/{bundler-DLfOn0ls.cjs → bundler-C8uJf324.cjs} +3 -3
  26. package/dist/{bundler-DLfOn0ls.cjs.map → bundler-C8uJf324.cjs.map} +1 -1
  27. package/dist/{bundler-DyWI41Iy.mjs → bundler-DYgm9xsd.mjs} +3 -3
  28. package/dist/{bundler-DyWI41Iy.mjs.map → bundler-DYgm9xsd.mjs.map} +1 -1
  29. package/dist/{cli-PkVF28LM.mjs → cli-Bogz-zEj.mjs} +5 -4
  30. package/dist/{cli-PkVF28LM.mjs.map → cli-Bogz-zEj.mjs.map} +1 -1
  31. package/dist/{cli-D-ZM-X2s.cjs → cli-D3jofJ6j.cjs} +7 -6
  32. package/dist/{cli-D-ZM-X2s.cjs.map → cli-D3jofJ6j.cjs.map} +1 -1
  33. package/dist/{config-CemHVcIr.d.cts → config-Be-4_I6H.d.cts} +3 -3
  34. package/dist/{config-C2BUosLm.d.mts.map → config-Be-4_I6H.d.cts.map} +1 -1
  35. package/dist/{config-C2BUosLm.d.mts → config-DqNRiQOp.d.mts} +3 -3
  36. package/dist/{config-CemHVcIr.d.cts.map → config-DqNRiQOp.d.mts.map} +1 -1
  37. package/dist/config.cjs +416 -17
  38. package/dist/config.cjs.map +1 -0
  39. package/dist/config.d.cts +3 -3
  40. package/dist/config.d.mts +3 -3
  41. package/dist/config.mjs +401 -2
  42. package/dist/config.mjs.map +1 -0
  43. package/dist/credentials-B70vmLcm.cjs +125 -0
  44. package/dist/credentials-B70vmLcm.cjs.map +1 -0
  45. package/dist/credentials-s0wMeZBU.mjs +108 -0
  46. package/dist/credentials-s0wMeZBU.mjs.map +1 -0
  47. package/dist/{define-CHBIEc5j.mjs → define-CYs0PEfZ.mjs} +2 -3
  48. package/dist/define-CYs0PEfZ.mjs.map +1 -0
  49. package/dist/{define-Cv_QvDrg.cjs → define-zUsP72ym.cjs} +2 -3
  50. package/dist/define-zUsP72ym.cjs.map +1 -0
  51. package/dist/deploy/public.cjs +32 -26
  52. package/dist/deploy/public.cjs.map +1 -1
  53. package/dist/deploy/public.d.cts +40 -4
  54. package/dist/deploy/public.d.cts.map +1 -1
  55. package/dist/deploy/public.d.mts +40 -4
  56. package/dist/deploy/public.d.mts.map +1 -1
  57. package/dist/deploy/public.mjs +15 -12
  58. package/dist/deploy/public.mjs.map +1 -1
  59. package/dist/{deploy-ABBI0lf1.cjs → deploy-55rJkdKz.cjs} +17 -14
  60. package/dist/{deploy-ABBI0lf1.cjs.map → deploy-55rJkdKz.cjs.map} +1 -1
  61. package/dist/{deploy-CGW-QY9D.mjs → deploy-Dc2LBJaK.mjs} +8 -7
  62. package/dist/{deploy-CGW-QY9D.mjs.map → deploy-Dc2LBJaK.mjs.map} +1 -1
  63. package/dist/{deploy-CG8bfFij.mjs → deploy-ZRXIPp1c.mjs} +11 -8
  64. package/dist/{deploy-CG8bfFij.mjs.map → deploy-ZRXIPp1c.mjs.map} +1 -1
  65. package/dist/{deploy-BiMrP9i7.cjs → deploy-yUcR2OlW.cjs} +12 -11
  66. package/dist/{deploy-BiMrP9i7.cjs.map → deploy-yUcR2OlW.cjs.map} +1 -1
  67. package/dist/derive-B4vDpzgP.mjs +150 -0
  68. package/dist/derive-B4vDpzgP.mjs.map +1 -0
  69. package/dist/derive-DAbo49sm.cjs +161 -0
  70. package/dist/derive-DAbo49sm.cjs.map +1 -0
  71. package/dist/{discover-C_6COHEv.cjs → discover-DHdECueV.cjs} +6 -157
  72. package/dist/discover-DHdECueV.cjs.map +1 -0
  73. package/dist/{discover-BaT6bpnA.mjs → discover-LMrqsWSU.mjs} +8 -117
  74. package/dist/discover-LMrqsWSU.mjs.map +1 -0
  75. package/dist/{dokploy-CwdmlyQL.mjs → dokploy-CepdXuMl.mjs} +3 -3
  76. package/dist/{dokploy-CwdmlyQL.mjs.map → dokploy-CepdXuMl.mjs.map} +1 -1
  77. package/dist/{dokploy-QJxMhxdf.cjs → dokploy-D1d37rvM.cjs} +3 -3
  78. package/dist/{dokploy-QJxMhxdf.cjs.map → dokploy-D1d37rvM.cjs.map} +1 -1
  79. package/dist/{encryption-DXw3jj0c.cjs → encryption-C9X98u2F.cjs} +5 -5
  80. package/dist/{encryption-DXw3jj0c.cjs.map → encryption-C9X98u2F.cjs.map} +1 -1
  81. package/dist/{encryption-CbQG_ayW.mjs → encryption-CKHjMpCr.mjs} +5 -5
  82. package/dist/{encryption-CbQG_ayW.mjs.map → encryption-CKHjMpCr.mjs.map} +1 -1
  83. package/dist/{github-ciwbIwVa.mjs → github-D-byNI7T.mjs} +4 -4
  84. package/dist/{github-ciwbIwVa.mjs.map → github-D-byNI7T.mjs.map} +1 -1
  85. package/dist/{github-BH_mETav.cjs → github-Dd3tMa1u.cjs} +4 -4
  86. package/dist/{github-BH_mETav.cjs.map → github-Dd3tMa1u.cjs.map} +1 -1
  87. package/dist/{index-DrKzpHl-.d.mts → index-CJ2qsSpp.d.mts} +2 -2
  88. package/dist/{index-BtXDZQuF.d.cts.map → index-CJ2qsSpp.d.mts.map} +1 -1
  89. package/dist/{index-BtXDZQuF.d.cts → index-CfE9Y885.d.cts} +2 -2
  90. package/dist/{index-DrKzpHl-.d.mts.map → index-CfE9Y885.d.cts.map} +1 -1
  91. package/dist/index.cjs +100 -235
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.mjs +71 -206
  94. package/dist/index.mjs.map +1 -1
  95. package/dist/local-C7wnrcYK.cjs +586 -0
  96. package/dist/local-C7wnrcYK.cjs.map +1 -0
  97. package/dist/local-Cd8ZYQG3.mjs +473 -0
  98. package/dist/local-Cd8ZYQG3.mjs.map +1 -0
  99. package/dist/{migrate-ImBKTBcW.mjs → migrate-B4gngTLe.mjs} +6 -6
  100. package/dist/{migrate-ImBKTBcW.mjs.map → migrate-B4gngTLe.mjs.map} +1 -1
  101. package/dist/{migrate-6oa9y_f2.cjs → migrate-tx9-P9uz.cjs} +6 -6
  102. package/dist/{migrate-6oa9y_f2.cjs.map → migrate-tx9-P9uz.cjs.map} +1 -1
  103. package/dist/openapi.cjs +2 -2
  104. package/dist/openapi.d.cts +1 -1
  105. package/dist/openapi.d.mts +1 -1
  106. package/dist/openapi.mjs +2 -2
  107. package/dist/{ready-Bpdnn2ON.mjs → ready-bQfu9GES.mjs} +3 -3
  108. package/dist/{ready-Bpdnn2ON.mjs.map → ready-bQfu9GES.mjs.map} +1 -1
  109. package/dist/{ready-BiG0rt4h.cjs → ready-brEhh68f.cjs} +3 -3
  110. package/dist/{ready-BiG0rt4h.cjs.map → ready-brEhh68f.cjs.map} +1 -1
  111. package/dist/reconcile/public.cjs +1 -1
  112. package/dist/reconcile/public.d.cts +1 -1
  113. package/dist/reconcile/public.d.mts +1 -1
  114. package/dist/reconcile/public.mjs +1 -1
  115. package/dist/{resolve-xytBTtG4.cjs → resolve-BXsNQjMR.cjs} +9 -6
  116. package/dist/resolve-BXsNQjMR.cjs.map +1 -0
  117. package/dist/{resolve-B1T0hUaR.mjs → resolve-DZ2IJ0qY.mjs} +9 -6
  118. package/dist/resolve-DZ2IJ0qY.mjs.map +1 -0
  119. package/dist/{runtime-CMwtq0AL.cjs → runtime-BGNDrHzh.cjs} +2 -2
  120. package/dist/{runtime-CMwtq0AL.cjs.map → runtime-BGNDrHzh.cjs.map} +1 -1
  121. package/dist/{runtime-Dn_n-29S.d.cts → runtime-CJEYK4Gz.d.mts} +2 -2
  122. package/dist/{runtime-CXPlkZzs.d.mts.map → runtime-CJEYK4Gz.d.mts.map} +1 -1
  123. package/dist/{runtime-CXPlkZzs.d.mts → runtime-Cjq1jlVX.d.cts} +2 -2
  124. package/dist/{runtime-Dn_n-29S.d.cts.map → runtime-Cjq1jlVX.d.cts.map} +1 -1
  125. package/dist/{runtime-DbakJS8u.mjs → runtime-Cmn-FeYO.mjs} +2 -2
  126. package/dist/{runtime-DbakJS8u.mjs.map → runtime-Cmn-FeYO.mjs.map} +1 -1
  127. package/dist/sandbox/discover-worker.cjs +1 -1
  128. package/dist/sandbox/discover-worker.mjs +1 -1
  129. package/dist/sandbox-CL--ZDui.cjs +164 -0
  130. package/dist/sandbox-CL--ZDui.cjs.map +1 -0
  131. package/dist/sandbox-Dm247NGx.mjs +117 -0
  132. package/dist/sandbox-Dm247NGx.mjs.map +1 -0
  133. package/dist/{sniffer-aO_-s5vq.mjs → sniffer-49KPbDgq.mjs} +25 -470
  134. package/dist/sniffer-49KPbDgq.mjs.map +1 -0
  135. package/dist/{sniffer-D_SYc_pO.cjs → sniffer-ByhbEW5A.cjs} +38 -567
  136. package/dist/sniffer-ByhbEW5A.cjs.map +1 -0
  137. package/dist/sst-BdALKEas.cjs +453 -0
  138. package/dist/sst-BdALKEas.cjs.map +1 -0
  139. package/dist/sst-Cper040I.mjs +430 -0
  140. package/dist/sst-Cper040I.mjs.map +1 -0
  141. package/dist/{store-BS8A7NcA.mjs → store-BaaonhkJ.mjs} +2 -2
  142. package/dist/{store-BS8A7NcA.mjs.map → store-BaaonhkJ.mjs.map} +1 -1
  143. package/dist/{store-KvNQwYaB.cjs → store-D_2ByRtW.cjs} +4 -4
  144. package/dist/{store-KvNQwYaB.cjs.map → store-D_2ByRtW.cjs.map} +1 -1
  145. package/dist/target/public.cjs +3 -3
  146. package/dist/target/public.d.cts +3 -3
  147. package/dist/target/public.d.mts +3 -3
  148. package/dist/target/public.mjs +3 -3
  149. package/dist/{terminal-D0f1u0LG.cjs → terminal-Bdv--jhY.cjs} +16 -111
  150. package/dist/terminal-Bdv--jhY.cjs.map +1 -0
  151. package/dist/{terminal-gMxAo9Dj.mjs → terminal-D7Ntz6WE.mjs} +13 -90
  152. package/dist/terminal-D7Ntz6WE.mjs.map +1 -0
  153. package/dist/{types-DIA7Li-J.d.cts → types-B_bEQvb9.d.mts} +42 -7
  154. package/dist/types-B_bEQvb9.d.mts.map +1 -0
  155. package/dist/{types-CfLKGfC_.d.mts → types-DkrDOMxw.d.cts} +43 -6
  156. package/dist/types-DkrDOMxw.d.cts.map +1 -0
  157. package/dist/utils-D2Nk1Nv2.cjs +205 -0
  158. package/dist/utils-D2Nk1Nv2.cjs.map +1 -0
  159. package/dist/utils-D_fxUqvU.mjs +156 -0
  160. package/dist/utils-D_fxUqvU.mjs.map +1 -0
  161. package/dist/vitest.cjs +1 -1
  162. package/dist/vitest.mjs +1 -1
  163. package/dist/workspace/index.cjs +1 -1
  164. package/dist/workspace/index.d.cts +2 -2
  165. package/dist/workspace/index.d.mts +2 -2
  166. package/dist/workspace/index.mjs +1 -1
  167. package/dist/{workspace-Kl4NG9IH.cjs → workspace-BwgWJK7h.cjs} +5 -5
  168. package/dist/workspace-BwgWJK7h.cjs.map +1 -0
  169. package/dist/{workspace-Dh7rr7l4.mjs → workspace-Bwit4q9O.mjs} +5 -5
  170. package/dist/workspace-Bwit4q9O.mjs.map +1 -0
  171. package/package.json +13 -13
  172. package/dist/config-BEJYKd4s.cjs +0 -648
  173. package/dist/config-BEJYKd4s.cjs.map +0 -1
  174. package/dist/config-LKKCVCnC.mjs +0 -547
  175. package/dist/config-LKKCVCnC.mjs.map +0 -1
  176. package/dist/define-CHBIEc5j.mjs.map +0 -1
  177. package/dist/define-Cv_QvDrg.cjs.map +0 -1
  178. package/dist/discover-BaT6bpnA.mjs.map +0 -1
  179. package/dist/discover-C_6COHEv.cjs.map +0 -1
  180. package/dist/home-DOzBaWaL.cjs +0 -33
  181. package/dist/home-DOzBaWaL.cjs.map +0 -1
  182. package/dist/home-GI7pJl1M.mjs +0 -22
  183. package/dist/home-GI7pJl1M.mjs.map +0 -1
  184. package/dist/resolve-B1T0hUaR.mjs.map +0 -1
  185. package/dist/resolve-xytBTtG4.cjs.map +0 -1
  186. package/dist/sniffer-D_SYc_pO.cjs.map +0 -1
  187. package/dist/sniffer-aO_-s5vq.mjs.map +0 -1
  188. package/dist/terminal-D0f1u0LG.cjs.map +0 -1
  189. package/dist/terminal-gMxAo9Dj.mjs.map +0 -1
  190. package/dist/types-CfLKGfC_.d.mts.map +0 -1
  191. package/dist/types-DIA7Li-J.d.cts.map +0 -1
  192. package/dist/workspace-Dh7rr7l4.mjs.map +0 -1
  193. package/dist/workspace-Kl4NG9IH.cjs.map +0 -1
@@ -0,0 +1,473 @@
1
+ import { a as assertSecretNames, o as confineCwd, t as SECRETS_DIR_ENV } from "./sandbox-Dm247NGx.mjs";
2
+ import { join, resolve } from "node:path";
3
+ import { existsSync, mkdirSync } from "node:fs";
4
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { spawn } from "node:child_process";
7
+ //#region src/home.ts
8
+ /**
9
+ * Where the CLI keeps what belongs to a person rather than a project: stage
10
+ * keys and stored provider credentials.
11
+ *
12
+ * `GKM_HOME` names it, so a CI job, a shared build runner or a test can give
13
+ * every run its own instead of reaching into whoever's home directory the
14
+ * process happens to have. Unset, it is `~/.gkm`, where it has always been.
15
+ */
16
+ /** The environment variable that moves the CLI's home. */
17
+ const GKM_HOME_ENV = "GKM_HOME";
18
+ /** The CLI's home: `GKM_HOME` if set, else `~/.gkm`. */
19
+ function gkmHome(env = process.env) {
20
+ const configured = env[GKM_HOME_ENV];
21
+ return configured ? resolve(configured) : join(homedir(), ".gkm");
22
+ }
23
+ //#endregion
24
+ //#region src/auth/credentials.ts
25
+ /**
26
+ * Get the path to the credentials directory
27
+ */
28
+ function getCredentialsDir(options) {
29
+ if (options?.home) return options.home;
30
+ return options?.root ? join(options.root, ".gkm") : gkmHome();
31
+ }
32
+ /**
33
+ * Get the path to the credentials file
34
+ */
35
+ function getCredentialsPath(options) {
36
+ return join(getCredentialsDir(options), "credentials.json");
37
+ }
38
+ /**
39
+ * Ensure the credentials directory exists
40
+ */
41
+ function ensureCredentialsDir(options) {
42
+ const dir = getCredentialsDir(options);
43
+ if (!existsSync(dir)) mkdirSync(dir, {
44
+ recursive: true,
45
+ mode: 448
46
+ });
47
+ }
48
+ /**
49
+ * Read stored credentials from disk
50
+ */
51
+ async function readCredentials(options) {
52
+ const path = getCredentialsPath(options);
53
+ if (!existsSync(path)) return {};
54
+ try {
55
+ const content = await readFile(path, "utf-8");
56
+ return JSON.parse(content);
57
+ } catch {
58
+ return {};
59
+ }
60
+ }
61
+ /**
62
+ * Write credentials to disk
63
+ */
64
+ async function writeCredentials(credentials, options) {
65
+ ensureCredentialsDir(options);
66
+ const path = getCredentialsPath(options);
67
+ await writeFile(path, JSON.stringify(credentials, null, 2), { mode: 384 });
68
+ }
69
+ /**
70
+ * Store Dokploy credentials
71
+ */
72
+ async function storeDokployCredentials(token, endpoint, options) {
73
+ const credentials = await readCredentials(options);
74
+ credentials.dokploy = {
75
+ token,
76
+ endpoint,
77
+ storedAt: (/* @__PURE__ */ new Date()).toISOString()
78
+ };
79
+ await writeCredentials(credentials, options);
80
+ }
81
+ /**
82
+ * Get stored Dokploy credentials
83
+ */
84
+ async function getDokployCredentials(options) {
85
+ const credentials = await readCredentials(options);
86
+ const token = process.env.DOKPLOY_API_TOKEN ?? credentials.dokploy?.token;
87
+ const endpoint = process.env.DOKPLOY_ENDPOINT ?? credentials.dokploy?.endpoint;
88
+ if (!token || !endpoint) return null;
89
+ return {
90
+ token,
91
+ endpoint: endpoint.replace(/\/$/, ""),
92
+ ...credentials.dokploy?.registryId ? { registryId: credentials.dokploy.registryId } : {}
93
+ };
94
+ }
95
+ /**
96
+ * Remove Dokploy credentials
97
+ */
98
+ async function removeDokployCredentials(options) {
99
+ const credentials = await readCredentials(options);
100
+ if (!credentials.dokploy) return false;
101
+ delete credentials.dokploy;
102
+ await writeCredentials(credentials, options);
103
+ return true;
104
+ }
105
+ /**
106
+ * Get Dokploy API token, checking stored credentials first, then environment
107
+ */
108
+ async function getDokployToken(options) {
109
+ const envToken = process.env.DOKPLOY_API_TOKEN;
110
+ if (envToken) return envToken;
111
+ const stored = await getDokployCredentials(options);
112
+ if (stored) return stored.token;
113
+ return null;
114
+ }
115
+ /**
116
+ * Get Dokploy registry ID from stored credentials
117
+ */
118
+ async function getDokployRegistryId(options) {
119
+ return (await getDokployCredentials(options))?.registryId ?? void 0;
120
+ }
121
+ /**
122
+ * Store Hostinger API token
123
+ *
124
+ * @param token - API token from hpanel.hostinger.com/profile/api
125
+ */
126
+ async function storeHostingerToken(token, options) {
127
+ const credentials = await readCredentials(options);
128
+ credentials.hostinger = {
129
+ token,
130
+ storedAt: (/* @__PURE__ */ new Date()).toISOString()
131
+ };
132
+ await writeCredentials(credentials, options);
133
+ }
134
+ /**
135
+ * Get stored Hostinger API token
136
+ *
137
+ * Checks environment variable first (HOSTINGER_API_TOKEN),
138
+ * then falls back to stored credentials.
139
+ */
140
+ async function getHostingerToken(options) {
141
+ const envToken = process.env.HOSTINGER_API_TOKEN;
142
+ if (envToken) return envToken;
143
+ return (await readCredentials(options)).hostinger?.token ?? null;
144
+ }
145
+ //#endregion
146
+ //#region src/run.ts
147
+ /**
148
+ * Start a program with an argument array, never a shell string.
149
+ *
150
+ * `gkm build`, `gkm docker` and `gkm deploy` pass values that come from the
151
+ * workspace — image refs, tags, build args, package names — to `docker` and
152
+ * `turbo`. Joined into a string and handed to a shell, a package named
153
+ * `x;curl …|sh` or a tag holding `$(…)` became part of the command line, which
154
+ * matters most where the CLI builds a repository it didn't write: a CI job for a
155
+ * fork, a shared build runner. Here every value reaches the program as one
156
+ * `argv` element, whatever it contains.
157
+ */
158
+ /** Long enough for a cold image build; short enough that a hung one ends. */
159
+ const DEFAULT_TIMEOUT_MS = 18e5;
160
+ /** How long a timed-out child has to exit on SIGTERM before it is killed. */
161
+ const KILL_GRACE_MS$1 = 5e3;
162
+ /** The command line as a person would read it — for messages, never to run. */
163
+ function display(command, args) {
164
+ return [command, ...args].join(" ");
165
+ }
166
+ /** The program ran and exited unsuccessfully; its own output said why. */
167
+ var CommandFailed = class extends Error {
168
+ command;
169
+ args;
170
+ exitCode;
171
+ signal;
172
+ constructor(command, args, exitCode, signal) {
173
+ super(`\`${display(command, args)}\` ${exitCode === null ? `was stopped by ${signal ?? "a signal"}` : `exited with code ${exitCode}`}. Its output above says why; run it by hand to see it again.`);
174
+ this.command = command;
175
+ this.args = args;
176
+ this.exitCode = exitCode;
177
+ this.signal = signal;
178
+ this.name = "CommandFailed";
179
+ }
180
+ };
181
+ /** The program ran past its timeout and was killed. */
182
+ var CommandTimedOut = class extends Error {
183
+ command;
184
+ args;
185
+ timeoutMs;
186
+ constructor(command, args, timeoutMs) {
187
+ super(`\`${display(command, args)}\` was still running after ${Math.round(timeoutMs / 1e3)}s and was stopped. Check what it was waiting on — a registry, the Docker daemon, a prompt — and run it again.`);
188
+ this.command = command;
189
+ this.args = args;
190
+ this.timeoutMs = timeoutMs;
191
+ this.name = "CommandTimedOut";
192
+ }
193
+ };
194
+ /**
195
+ * Run `command` with `args`, resolving when it exits 0.
196
+ *
197
+ * Rejects with {@link CommandFailed} on any other exit, {@link CommandTimedOut}
198
+ * once `timeoutMs` passes (after the child is gone), and with the spawn error
199
+ * itself when the program cannot be started at all — `ENOENT` already names it.
200
+ */
201
+ async function run(command, args, options = {}) {
202
+ await spawnChild(command, args, options, false);
203
+ }
204
+ /**
205
+ * {@link run}, resolving with what the program wrote to stdout — for a value
206
+ * the CLI reads back, such as the digest `docker inspect` reports. stderr still
207
+ * reaches the terminal, so a failure explains itself the same way.
208
+ */
209
+ function runOutput(command, args, options = {}) {
210
+ return spawnChild(command, args, options, true);
211
+ }
212
+ function spawnChild(command, args, options, capture) {
213
+ const { timeoutMs = DEFAULT_TIMEOUT_MS, ...spawnOptions } = options;
214
+ return new Promise((resolve, reject) => {
215
+ const child = spawn(command, [...args], {
216
+ stdio: "inherit",
217
+ ...spawnOptions,
218
+ ...capture ? { stdio: [
219
+ "ignore",
220
+ "pipe",
221
+ "inherit"
222
+ ] } : {},
223
+ shell: false
224
+ });
225
+ let stdout = "";
226
+ child.stdout?.on("data", (chunk) => {
227
+ stdout += chunk.toString();
228
+ });
229
+ let timedOut = false;
230
+ let killer;
231
+ const timer = setTimeout(() => {
232
+ timedOut = true;
233
+ child.kill("SIGTERM");
234
+ killer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS$1);
235
+ killer.unref?.();
236
+ }, timeoutMs);
237
+ timer.unref?.();
238
+ const settle = () => {
239
+ clearTimeout(timer);
240
+ if (killer) clearTimeout(killer);
241
+ };
242
+ child.on("error", (error) => {
243
+ settle();
244
+ reject(spawnOptions.signal?.aborted ? spawnOptions.signal.reason : error);
245
+ });
246
+ child.on("close", (code, signal) => {
247
+ settle();
248
+ if (spawnOptions.signal?.aborted) reject(spawnOptions.signal.reason);
249
+ else if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));
250
+ else if (code === 0) resolve(stdout);
251
+ else reject(new CommandFailed(command, args, code, signal));
252
+ });
253
+ });
254
+ }
255
+ //#endregion
256
+ //#region src/sandbox/env.ts
257
+ /**
258
+ * What of the host's environment a local sandbox passes on.
259
+ *
260
+ * An allowlist, not a denylist: a credential's variable has any name its
261
+ * owner chose (`DOKPLOY_TOKEN`, `AWS_SECRET_ACCESS_KEY`, `MY_VAULT_TOKEN`), so
262
+ * the only safe default is to name what a program needs to *run* and pass
263
+ * nothing else.
264
+ */
265
+ /**
266
+ * Variables a command needs to find programs, write temp files, print in the
267
+ * user's locale and reach the network through the host's proxy — and nothing
268
+ * that authenticates as anyone.
269
+ *
270
+ * Deliberately left out:
271
+ * - `NODE_OPTIONS`: it can `--require` or `--import` code into every node
272
+ * process, and CI often holds `--import tsx` there. A step that needs a
273
+ * loader passes its own.
274
+ * - `NODE_AUTH_TOKEN`, `NPM_TOKEN`, `npm_config_*`: registry tokens
275
+ * (`actions/setup-node` writes `NODE_AUTH_TOKEN`), which is why there is no
276
+ * `NODE_*` wildcard.
277
+ * - `AWS_*`, `DOCKER_*`, `DOKPLOY_*`, `GITHUB_TOKEN`, `TURBO_TOKEN`, `GKM_*`:
278
+ * credentials, or where the deploy keeps them.
279
+ * - `SHELL`, `EDITOR` and the rest of a login session: nothing here starts a
280
+ * shell.
281
+ *
282
+ * Proxies are passed: behind one, nothing installs or builds without it. A
283
+ * proxy URL with a password in it reaches the command too — a host that keeps
284
+ * one there and builds code it does not trust should pass a sandbox of its
285
+ * own.
286
+ */
287
+ const SANDBOX_ENV_ALLOWLIST = [
288
+ "PATH",
289
+ "HOME",
290
+ "USER",
291
+ "LOGNAME",
292
+ "TMPDIR",
293
+ "TMP",
294
+ "TEMP",
295
+ "LANG",
296
+ "LANGUAGE",
297
+ "TZ",
298
+ /^LC_[A-Z]+$/,
299
+ "TERM",
300
+ "COLORTERM",
301
+ "NO_COLOR",
302
+ "FORCE_COLOR",
303
+ "CI",
304
+ "NODE_ENV",
305
+ "NODE_EXTRA_CA_CERTS",
306
+ "COREPACK_HOME",
307
+ "PNPM_HOME",
308
+ "XDG_CACHE_HOME",
309
+ "XDG_DATA_HOME",
310
+ "HTTP_PROXY",
311
+ "HTTPS_PROXY",
312
+ "NO_PROXY",
313
+ "http_proxy",
314
+ "https_proxy",
315
+ "no_proxy",
316
+ "SystemRoot",
317
+ "SYSTEMROOT",
318
+ "windir",
319
+ "WINDIR",
320
+ "ComSpec",
321
+ "COMSPEC",
322
+ "PATHEXT",
323
+ "USERPROFILE",
324
+ "APPDATA",
325
+ "LOCALAPPDATA"
326
+ ];
327
+ function allowed(name) {
328
+ return SANDBOX_ENV_ALLOWLIST.some((entry) => typeof entry === "string" ? entry === name : entry.test(name));
329
+ }
330
+ /**
331
+ * The allowlisted part of `source`, plus each of `extra` the host chose to
332
+ * pass on by name.
333
+ */
334
+ function allowlistedEnv(source = process.env, extra = []) {
335
+ const env = {};
336
+ for (const [name, value] of Object.entries(source)) {
337
+ if (value === void 0) continue;
338
+ if (allowed(name) || extra.includes(name)) env[name] = value;
339
+ }
340
+ return env;
341
+ }
342
+ //#endregion
343
+ //#region src/sandbox/local.ts
344
+ /** How long a timed-out command has to exit on SIGTERM before SIGKILL. */
345
+ const KILL_GRACE_MS = 5e3;
346
+ /** Where `output` sends a child's streams. */
347
+ const STDIO = {
348
+ capture: [
349
+ "ignore",
350
+ "pipe",
351
+ "pipe"
352
+ ],
353
+ inherit: "inherit",
354
+ stderr: [
355
+ "ignore",
356
+ 2,
357
+ 2
358
+ ],
359
+ ignore: "ignore"
360
+ };
361
+ /**
362
+ * A child process on this machine, as this user, with an allowlisted
363
+ * environment.
364
+ *
365
+ * What it withholds from the command: the host's environment beyond
366
+ * {@link SANDBOX_ENV_ALLOWLIST}, a shell, a working directory outside the
367
+ * project, and any time past the timeout. What it does not: the host's
368
+ * filesystem, which the command can read and write as the user running the
369
+ * deploy. So it is not `isolating`, and it is the default for projects the
370
+ * host already trusts — the developer's own, a team's own CI. Code nobody
371
+ * vetted belongs in a sandbox that is.
372
+ *
373
+ * A timed-out command is sent SIGTERM, then SIGKILL; processes it started
374
+ * itself are its to stop.
375
+ */
376
+ var LocalSandbox = class {
377
+ root;
378
+ isolating = false;
379
+ env;
380
+ constructor(options) {
381
+ this.root = resolve(options.root);
382
+ this.env = {
383
+ ...allowlistedEnv(options.hostEnv ?? process.env, options.passEnv),
384
+ ...options.home ? {
385
+ HOME: options.home,
386
+ USERPROFILE: options.home
387
+ } : {}
388
+ };
389
+ }
390
+ async exec(command, args, options) {
391
+ const cwd = confineCwd(this.root, options.cwd);
392
+ assertSecretNames(options.secrets);
393
+ options.signal?.throwIfAborted();
394
+ const secretsDir = await mountSecrets(options.secrets);
395
+ try {
396
+ return await spawnConfined(command, args, {
397
+ ...options,
398
+ cwd,
399
+ env: secretsDir ? {
400
+ ...options.env,
401
+ [SECRETS_DIR_ENV]: secretsDir
402
+ } : options.env
403
+ });
404
+ } finally {
405
+ if (secretsDir) await rm(secretsDir, {
406
+ recursive: true,
407
+ force: true
408
+ });
409
+ }
410
+ }
411
+ };
412
+ /**
413
+ * Each secret as a 0600 file in a fresh 0700 directory outside the project —
414
+ * where nothing the build writes, packs or commits will pick it up.
415
+ */
416
+ async function mountSecrets(secrets) {
417
+ if (!secrets || Object.keys(secrets).length === 0) return void 0;
418
+ const dir = await mkdtemp(join(tmpdir(), "gkm-secrets-"));
419
+ for (const [name, value] of Object.entries(secrets)) await writeFile(join(dir, name), value, { mode: 384 });
420
+ return dir;
421
+ }
422
+ function spawnConfined(command, args, options) {
423
+ const { output = "capture", signal, timeoutMs } = options;
424
+ return new Promise((resolvePromise, reject) => {
425
+ const child = spawn(command, [...args], {
426
+ cwd: options.cwd,
427
+ env: { ...options.env },
428
+ stdio: STDIO[output],
429
+ shell: false,
430
+ ...signal ? { signal } : {}
431
+ });
432
+ let stdout = "";
433
+ let stderr = "";
434
+ child.stdout?.on("data", (chunk) => {
435
+ stdout += chunk.toString();
436
+ });
437
+ child.stderr?.on("data", (chunk) => {
438
+ stderr += chunk.toString();
439
+ });
440
+ let timedOut = false;
441
+ let killer;
442
+ const timer = setTimeout(() => {
443
+ timedOut = true;
444
+ child.kill("SIGTERM");
445
+ killer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
446
+ killer.unref?.();
447
+ }, timeoutMs);
448
+ timer.unref?.();
449
+ const settle = () => {
450
+ clearTimeout(timer);
451
+ if (killer) clearTimeout(killer);
452
+ };
453
+ child.on("error", (error) => {
454
+ settle();
455
+ reject(signal?.aborted ? signal.reason : error);
456
+ });
457
+ child.on("close", (code, killedBy) => {
458
+ settle();
459
+ if (signal?.aborted) reject(signal.reason);
460
+ else if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));
461
+ else resolvePromise({
462
+ exitCode: code,
463
+ signal: killedBy ?? null,
464
+ stdout,
465
+ stderr
466
+ });
467
+ });
468
+ });
469
+ }
470
+ //#endregion
471
+ export { storeHostingerToken as _, CommandTimedOut as a, runOutput as c, getDokployRegistryId as d, getDokployToken as f, storeDokployCredentials as g, removeDokployCredentials as h, CommandFailed as i, getCredentialsPath as l, readCredentials as m, SANDBOX_ENV_ALLOWLIST as n, DEFAULT_TIMEOUT_MS as o, getHostingerToken as p, allowlistedEnv as r, run as s, LocalSandbox as t, getDokployCredentials as u, GKM_HOME_ENV as v, gkmHome as y };
472
+
473
+ //# sourceMappingURL=local-Cd8ZYQG3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-Cd8ZYQG3.mjs","names":["KILL_GRACE_MS"],"sources":["../src/home.ts","../src/auth/credentials.ts","../src/run.ts","../src/sandbox/env.ts","../src/sandbox/local.ts"],"sourcesContent":["/**\n * Where the CLI keeps what belongs to a person rather than a project: stage\n * keys and stored provider credentials.\n *\n * `GKM_HOME` names it, so a CI job, a shared build runner or a test can give\n * every run its own instead of reaching into whoever's home directory the\n * process happens to have. Unset, it is `~/.gkm`, where it has always been.\n */\n\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/** The environment variable that moves the CLI's home. */\nexport const GKM_HOME_ENV = 'GKM_HOME';\n\n/** The CLI's home: `GKM_HOME` if set, else `~/.gkm`. */\nexport function gkmHome(env: NodeJS.ProcessEnv = process.env): string {\n\tconst configured = env[GKM_HOME_ENV];\n\treturn configured ? resolve(configured) : join(homedir(), '.gkm');\n}\n","import { existsSync, mkdirSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { gkmHome } from '../home';\n\n/**\n * Stored credentials for various services\n */\nexport interface StoredCredentials {\n\tdokploy?: {\n\t\t/** API token */\n\t\ttoken: string;\n\t\t/** Dokploy endpoint URL */\n\t\tendpoint: string;\n\t\t/** Registry ID in Dokploy (for Docker image pulls) */\n\t\tregistryId?: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n\thostinger?: {\n\t\t/** API token from hpanel.hostinger.com/profile/api */\n\t\ttoken: string;\n\t\t/** When the credentials were stored */\n\t\tstoredAt: string;\n\t};\n}\n\n/**\n * Options for credential operations\n */\nexport interface CredentialOptions {\n\t/**\n\t * A directory whose `.gkm` holds the credentials. Default: the CLI's home\n\t * (`GKM_HOME`, else `~/.gkm`).\n\t */\n\troot?: string;\n\t/** The CLI's home itself, holding `credentials.json`. Wins over `root`. */\n\thome?: string;\n}\n\n/**\n * Get the path to the credentials directory\n */\nexport function getCredentialsDir(options?: CredentialOptions): string {\n\tif (options?.home) return options.home;\n\treturn options?.root ? join(options.root, '.gkm') : gkmHome();\n}\n\n/**\n * Get the path to the credentials file\n */\nexport function getCredentialsPath(options?: CredentialOptions): string {\n\treturn join(getCredentialsDir(options), 'credentials.json');\n}\n\n/**\n * Ensure the credentials directory exists\n */\nfunction ensureCredentialsDir(options?: CredentialOptions): void {\n\tconst dir = getCredentialsDir(options);\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t}\n}\n\n/**\n * Read stored credentials from disk\n */\nexport async function readCredentials(\n\toptions?: CredentialOptions,\n): Promise<StoredCredentials> {\n\tconst path = getCredentialsPath(options);\n\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\ttry {\n\t\tconst content = await readFile(path, 'utf-8');\n\t\treturn JSON.parse(content) as StoredCredentials;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n/**\n * Write credentials to disk\n */\nexport async function writeCredentials(\n\tcredentials: StoredCredentials,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tensureCredentialsDir(options);\n\tconst path = getCredentialsPath(options);\n\n\tawait writeFile(path, JSON.stringify(credentials, null, 2), {\n\t\tmode: 0o600, // Owner read/write only\n\t});\n}\n\n/**\n * Store Dokploy credentials\n */\nexport async function storeDokployCredentials(\n\ttoken: string,\n\tendpoint: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.dokploy = {\n\t\ttoken,\n\t\tendpoint,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Dokploy credentials\n */\nexport async function getDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<{\n\ttoken: string;\n\tendpoint: string;\n\tregistryId?: string;\n} | null> {\n\tconst credentials = await readCredentials(options);\n\n\t// The environment first, and each half independently.\n\t//\n\t// `getDokployToken` has always read `DOKPLOY_API_TOKEN` while this — the\n\t// function the deploy path actually calls — read only the file. So a CI job\n\t// given the token as a secret had a token and nowhere to send it, and the\n\t// only way through was committing a credentials file or running an\n\t// interactive login on the runner.\n\t//\n\t// Read separately rather than as a pair because they arrive separately: a\n\t// token is a secret and belongs in the environment, while an endpoint is\n\t// configuration and usually belongs in `deploy.dokploy.endpoint`. Requiring\n\t// both from the same place is what made either one useless alone.\n\tconst token = process.env.DOKPLOY_API_TOKEN ?? credentials.dokploy?.token;\n\tconst endpoint =\n\t\tprocess.env.DOKPLOY_ENDPOINT ?? credentials.dokploy?.endpoint;\n\n\tif (!token || !endpoint) return null;\n\n\treturn {\n\t\ttoken,\n\t\tendpoint: endpoint.replace(/\\/$/, ''),\n\t\t...(credentials.dokploy?.registryId\n\t\t\t? { registryId: credentials.dokploy.registryId }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Remove Dokploy credentials\n */\nexport async function removeDokployCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.dokploy;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n\n/**\n * Remove all stored credentials\n */\nexport async function removeAllCredentials(\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst path = getCredentialsPath(options);\n\n\tif (existsSync(path)) {\n\t\tawait unlink(path);\n\t}\n}\n\n/**\n * Get Dokploy API token, checking stored credentials first, then environment\n */\nexport async function getDokployToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.DOKPLOY_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst stored = await getDokployCredentials(options);\n\tif (stored) {\n\t\treturn stored.token;\n\t}\n\n\treturn null;\n}\n\n/**\n * Get Dokploy endpoint from stored credentials\n */\nexport async function getDokployEndpoint(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.endpoint ?? null;\n}\n\n/**\n * Store Dokploy registry ID\n */\nexport async function storeDokployRegistryId(\n\tregistryId: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.dokploy) {\n\t\tthrow new Error(\n\t\t\t'Dokploy credentials not found. Run \"gkm login --service dokploy\" first.',\n\t\t);\n\t}\n\n\tcredentials.dokploy.registryId = registryId;\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get Dokploy registry ID from stored credentials\n */\nexport async function getDokployRegistryId(\n\toptions?: CredentialOptions,\n): Promise<string | undefined> {\n\tconst stored = await getDokployCredentials(options);\n\treturn stored?.registryId ?? undefined;\n}\n\n// ============================================\n// Hostinger credentials\n// ============================================\n\n/**\n * Store Hostinger API token\n *\n * @param token - API token from hpanel.hostinger.com/profile/api\n */\nexport async function storeHostingerToken(\n\ttoken: string,\n\toptions?: CredentialOptions,\n): Promise<void> {\n\tconst credentials = await readCredentials(options);\n\n\tcredentials.hostinger = {\n\t\ttoken,\n\t\tstoredAt: new Date().toISOString(),\n\t};\n\n\tawait writeCredentials(credentials, options);\n}\n\n/**\n * Get stored Hostinger API token\n *\n * Checks environment variable first (HOSTINGER_API_TOKEN),\n * then falls back to stored credentials.\n */\nexport async function getHostingerToken(\n\toptions?: CredentialOptions,\n): Promise<string | null> {\n\t// First check environment variable (takes precedence)\n\tconst envToken = process.env.HOSTINGER_API_TOKEN;\n\tif (envToken) {\n\t\treturn envToken;\n\t}\n\n\t// Then check stored credentials\n\tconst credentials = await readCredentials(options);\n\treturn credentials.hostinger?.token ?? null;\n}\n\n/**\n * Remove Hostinger credentials\n */\nexport async function removeHostingerCredentials(\n\toptions?: CredentialOptions,\n): Promise<boolean> {\n\tconst credentials = await readCredentials(options);\n\n\tif (!credentials.hostinger) {\n\t\treturn false;\n\t}\n\n\tdelete credentials.hostinger;\n\tawait writeCredentials(credentials, options);\n\treturn true;\n}\n","/**\n * Start a program with an argument array, never a shell string.\n *\n * `gkm build`, `gkm docker` and `gkm deploy` pass values that come from the\n * workspace — image refs, tags, build args, package names — to `docker` and\n * `turbo`. Joined into a string and handed to a shell, a package named\n * `x;curl …|sh` or a tag holding `$(…)` became part of the command line, which\n * matters most where the CLI builds a repository it didn't write: a CI job for a\n * fork, a shared build runner. Here every value reaches the program as one\n * `argv` element, whatever it contains.\n */\n\nimport { type SpawnOptions, spawn } from 'node:child_process';\n\n/** Long enough for a cold image build; short enough that a hung one ends. */\nexport const DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\n/** How long a timed-out child has to exit on SIGTERM before it is killed. */\nconst KILL_GRACE_MS = 5_000;\n\nexport interface RunOptions {\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n\tstdio?: SpawnOptions['stdio'];\n\t/** Kill the child after this long. Defaults to {@link DEFAULT_TIMEOUT_MS}. */\n\ttimeoutMs?: number;\n\t/**\n\t * Kills the child when aborted, and rejects with the signal's reason — the\n\t * same as a stopped deploy's other calls.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The command line as a person would read it — for messages, never to run. */\nfunction display(command: string, args: readonly string[]): string {\n\treturn [command, ...args].join(' ');\n}\n\n/** The program ran and exited unsuccessfully; its own output said why. */\nexport class CommandFailed extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly exitCode: number | null,\n\t\treadonly signal: NodeJS.Signals | null,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` ${exitCode === null ? `was stopped by ${signal ?? 'a signal'}` : `exited with code ${exitCode}`}. Its output above says why; run it by hand to see it again.`,\n\t\t);\n\t\tthis.name = 'CommandFailed';\n\t}\n}\n\n/** The program ran past its timeout and was killed. */\nexport class CommandTimedOut extends Error {\n\tconstructor(\n\t\treadonly command: string,\n\t\treadonly args: readonly string[],\n\t\treadonly timeoutMs: number,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${display(command, args)}\\` was still running after ${Math.round(timeoutMs / 1000)}s and was stopped. Check what it was waiting on — a registry, the Docker daemon, a prompt — and run it again.`,\n\t\t);\n\t\tthis.name = 'CommandTimedOut';\n\t}\n}\n\n/**\n * Run `command` with `args`, resolving when it exits 0.\n *\n * Rejects with {@link CommandFailed} on any other exit, {@link CommandTimedOut}\n * once `timeoutMs` passes (after the child is gone), and with the spawn error\n * itself when the program cannot be started at all — `ENOENT` already names it.\n */\nexport async function run(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions = {},\n): Promise<void> {\n\tawait spawnChild(command, args, options, false);\n}\n\n/**\n * {@link run}, resolving with what the program wrote to stdout — for a value\n * the CLI reads back, such as the digest `docker inspect` reports. stderr still\n * reaches the terminal, so a failure explains itself the same way.\n */\nexport function runOutput(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: Omit<RunOptions, 'stdio'> = {},\n): Promise<string> {\n\treturn spawnChild(command, args, options, true);\n}\n\nfunction spawnChild(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: RunOptions,\n\tcapture: boolean,\n): Promise<string> {\n\tconst { timeoutMs = DEFAULT_TIMEOUT_MS, ...spawnOptions } = options;\n\n\treturn new Promise<string>((resolve, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tstdio: 'inherit',\n\t\t\t...spawnOptions,\n\t\t\t...(capture ? { stdio: ['ignore', 'pipe', 'inherit'] } : {}),\n\t\t\tshell: false,\n\t\t});\n\n\t\tlet stdout = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet killer: NodeJS.Timeout | undefined;\n\t\tconst timer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.kill('SIGTERM');\n\t\t\t// A child that ignores SIGTERM would hold the deploy open forever.\n\t\t\tkiller = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);\n\t\t\tkiller.unref?.();\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\n\t\tconst settle = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tif (killer) clearTimeout(killer);\n\t\t};\n\n\t\tchild.on('error', (error) => {\n\t\t\tsettle();\n\t\t\t// Node reports an abort as its own `AbortError`; the caller asked\n\t\t\t// with a reason, and that is what it should get back.\n\t\t\treject(spawnOptions.signal?.aborted ? spawnOptions.signal.reason : error);\n\t\t});\n\n\t\tchild.on('close', (code: number | null, signal: NodeJS.Signals | null) => {\n\t\t\tsettle();\n\t\t\tif (spawnOptions.signal?.aborted) reject(spawnOptions.signal.reason);\n\t\t\telse if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));\n\t\t\telse if (code === 0) resolve(stdout);\n\t\t\telse reject(new CommandFailed(command, args, code, signal));\n\t\t});\n\t});\n}\n","/**\n * What of the host's environment a local sandbox passes on.\n *\n * An allowlist, not a denylist: a credential's variable has any name its\n * owner chose (`DOKPLOY_TOKEN`, `AWS_SECRET_ACCESS_KEY`, `MY_VAULT_TOKEN`), so\n * the only safe default is to name what a program needs to *run* and pass\n * nothing else.\n */\n\n/**\n * Variables a command needs to find programs, write temp files, print in the\n * user's locale and reach the network through the host's proxy — and nothing\n * that authenticates as anyone.\n *\n * Deliberately left out:\n * - `NODE_OPTIONS`: it can `--require` or `--import` code into every node\n * process, and CI often holds `--import tsx` there. A step that needs a\n * loader passes its own.\n * - `NODE_AUTH_TOKEN`, `NPM_TOKEN`, `npm_config_*`: registry tokens\n * (`actions/setup-node` writes `NODE_AUTH_TOKEN`), which is why there is no\n * `NODE_*` wildcard.\n * - `AWS_*`, `DOCKER_*`, `DOKPLOY_*`, `GITHUB_TOKEN`, `TURBO_TOKEN`, `GKM_*`:\n * credentials, or where the deploy keeps them.\n * - `SHELL`, `EDITOR` and the rest of a login session: nothing here starts a\n * shell.\n *\n * Proxies are passed: behind one, nothing installs or builds without it. A\n * proxy URL with a password in it reaches the command too — a host that keeps\n * one there and builds code it does not trust should pass a sandbox of its\n * own.\n */\nexport const SANDBOX_ENV_ALLOWLIST: readonly (string | RegExp)[] = [\n\t// Finding programs and a home to cache in.\n\t'PATH',\n\t'HOME',\n\t'USER',\n\t'LOGNAME',\n\t'TMPDIR',\n\t'TMP',\n\t'TEMP',\n\t// Locale and terminal: output a person reads should look the same.\n\t'LANG',\n\t'LANGUAGE',\n\t'TZ',\n\t/^LC_[A-Z]+$/,\n\t'TERM',\n\t'COLORTERM',\n\t'NO_COLOR',\n\t'FORCE_COLOR',\n\t'CI',\n\t// Node: the mode a build runs in, and the CAs a corporate network adds.\n\t'NODE_ENV',\n\t'NODE_EXTRA_CA_CERTS',\n\t// Package managers' own homes, so a build reuses the host's store.\n\t'COREPACK_HOME',\n\t'PNPM_HOME',\n\t'XDG_CACHE_HOME',\n\t'XDG_DATA_HOME',\n\t// The network, through the host's proxy.\n\t'HTTP_PROXY',\n\t'HTTPS_PROXY',\n\t'NO_PROXY',\n\t'http_proxy',\n\t'https_proxy',\n\t'no_proxy',\n\t// Windows: without these, nothing starts.\n\t'SystemRoot',\n\t'SYSTEMROOT',\n\t'windir',\n\t'WINDIR',\n\t'ComSpec',\n\t'COMSPEC',\n\t'PATHEXT',\n\t'USERPROFILE',\n\t'APPDATA',\n\t'LOCALAPPDATA',\n];\n\nfunction allowed(name: string): boolean {\n\treturn SANDBOX_ENV_ALLOWLIST.some((entry) =>\n\t\ttypeof entry === 'string' ? entry === name : entry.test(name),\n\t);\n}\n\n/**\n * The allowlisted part of `source`, plus each of `extra` the host chose to\n * pass on by name.\n */\nexport function allowlistedEnv(\n\tsource: NodeJS.ProcessEnv = process.env,\n\textra: readonly string[] = [],\n): Record<string, string> {\n\tconst env: Record<string, string> = {};\n\tfor (const [name, value] of Object.entries(source)) {\n\t\tif (value === undefined) continue;\n\t\tif (allowed(name) || extra.includes(name)) env[name] = value;\n\t}\n\treturn env;\n}\n","import { type SpawnOptions, spawn } from 'node:child_process';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { CommandTimedOut } from '../run';\nimport { allowlistedEnv } from './env';\nimport {\n\tassertSecretNames,\n\tconfineCwd,\n\ttype Sandbox,\n\ttype SandboxExecOptions,\n\ttype SandboxOutput,\n\ttype SandboxResult,\n\tSECRETS_DIR_ENV,\n} from './sandbox';\n\n/** How long a timed-out command has to exit on SIGTERM before SIGKILL. */\nconst KILL_GRACE_MS = 5_000;\n\nexport interface LocalSandboxOptions {\n\t/** The project. Every command runs at or below it. */\n\troot: string;\n\t/**\n\t * `HOME` for every command. Defaults to the host's, because a build\n\t * reuses the caches kept there — the pnpm store, corepack's package\n\t * managers, turbo's cache — and a cold one re-downloads all of them.\n\t * Point it at an empty directory to keep `~/.aws`, `~/.npmrc` and\n\t * `~/.docker` out of reach of an SDK's default lookup — though, sharing\n\t * the host's filesystem, a command that goes looking still finds them.\n\t */\n\thome?: string;\n\t/**\n\t * Host variables to pass on beyond the allowlist, by name — a remote\n\t * cache's `TURBO_TOKEN`, for a build the host trusts with it.\n\t */\n\tpassEnv?: readonly string[];\n\t/** Where the allowlisted variables are read from. Defaults to `process.env`. */\n\thostEnv?: NodeJS.ProcessEnv;\n}\n\n/** Where `output` sends a child's streams. */\nconst STDIO: Record<SandboxOutput, SpawnOptions['stdio']> = {\n\tcapture: ['ignore', 'pipe', 'pipe'],\n\tinherit: 'inherit',\n\tstderr: ['ignore', 2, 2],\n\tignore: 'ignore',\n};\n\n/**\n * A child process on this machine, as this user, with an allowlisted\n * environment.\n *\n * What it withholds from the command: the host's environment beyond\n * {@link SANDBOX_ENV_ALLOWLIST}, a shell, a working directory outside the\n * project, and any time past the timeout. What it does not: the host's\n * filesystem, which the command can read and write as the user running the\n * deploy. So it is not `isolating`, and it is the default for projects the\n * host already trusts — the developer's own, a team's own CI. Code nobody\n * vetted belongs in a sandbox that is.\n *\n * A timed-out command is sent SIGTERM, then SIGKILL; processes it started\n * itself are its to stop.\n */\nexport class LocalSandbox implements Sandbox {\n\treadonly root: string;\n\treadonly isolating = false;\n\treadonly env: Readonly<Record<string, string>>;\n\n\tconstructor(options: LocalSandboxOptions) {\n\t\tthis.root = resolve(options.root);\n\t\tthis.env = {\n\t\t\t...allowlistedEnv(options.hostEnv ?? process.env, options.passEnv),\n\t\t\t...(options.home\n\t\t\t\t? { HOME: options.home, USERPROFILE: options.home }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\tasync exec(\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions: SandboxExecOptions,\n\t): Promise<SandboxResult> {\n\t\tconst cwd = confineCwd(this.root, options.cwd);\n\t\tassertSecretNames(options.secrets);\n\t\toptions.signal?.throwIfAborted();\n\n\t\tconst secretsDir = await mountSecrets(options.secrets);\n\t\ttry {\n\t\t\treturn await spawnConfined(command, args, {\n\t\t\t\t...options,\n\t\t\t\tcwd,\n\t\t\t\tenv: secretsDir\n\t\t\t\t\t? { ...options.env, [SECRETS_DIR_ENV]: secretsDir }\n\t\t\t\t\t: options.env,\n\t\t\t});\n\t\t} finally {\n\t\t\tif (secretsDir) await rm(secretsDir, { recursive: true, force: true });\n\t\t}\n\t}\n}\n\n/**\n * Each secret as a 0600 file in a fresh 0700 directory outside the project —\n * where nothing the build writes, packs or commits will pick it up.\n */\nasync function mountSecrets(\n\tsecrets: Readonly<Record<string, string>> | undefined,\n): Promise<string | undefined> {\n\tif (!secrets || Object.keys(secrets).length === 0) return undefined;\n\n\tconst dir = await mkdtemp(join(tmpdir(), 'gkm-secrets-'));\n\tfor (const [name, value] of Object.entries(secrets)) {\n\t\tawait writeFile(join(dir, name), value, { mode: 0o600 });\n\t}\n\treturn dir;\n}\n\nfunction spawnConfined(\n\tcommand: string,\n\targs: readonly string[],\n\toptions: SandboxExecOptions,\n): Promise<SandboxResult> {\n\tconst { output = 'capture', signal, timeoutMs } = options;\n\n\treturn new Promise<SandboxResult>((resolvePromise, reject) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\tcwd: options.cwd,\n\t\t\t// The whole environment, as given. `spawn` reads `process.env` only\n\t\t\t// when this is left out.\n\t\t\tenv: { ...options.env },\n\t\t\tstdio: STDIO[output],\n\t\t\tshell: false,\n\t\t\t...(signal ? { signal } : {}),\n\t\t});\n\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\n\t\tlet timedOut = false;\n\t\tlet killer: NodeJS.Timeout | undefined;\n\t\tconst timer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.kill('SIGTERM');\n\t\t\t// A command that ignores SIGTERM would otherwise outlive its timeout.\n\t\t\tkiller = setTimeout(() => child.kill('SIGKILL'), KILL_GRACE_MS);\n\t\t\tkiller.unref?.();\n\t\t}, timeoutMs);\n\t\ttimer.unref?.();\n\n\t\tconst settle = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tif (killer) clearTimeout(killer);\n\t\t};\n\n\t\tchild.on('error', (error) => {\n\t\t\tsettle();\n\t\t\t// Node reports an abort as its own `AbortError`; the caller asked\n\t\t\t// with a reason, and that is what it gets back.\n\t\t\treject(signal?.aborted ? signal.reason : error);\n\t\t});\n\n\t\tchild.on('close', (code: number | null, killedBy: string | null) => {\n\t\t\tsettle();\n\t\t\tif (signal?.aborted) reject(signal.reason);\n\t\t\telse if (timedOut) reject(new CommandTimedOut(command, args, timeoutMs));\n\t\t\telse\n\t\t\t\tresolvePromise({\n\t\t\t\t\texitCode: code,\n\t\t\t\t\tsignal: killedBy ?? null,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t});\n\t\t});\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAa,eAAe;;AAG5B,SAAgB,QAAQ,MAAyB,QAAQ,KAAa;CACrE,MAAM,aAAa,IAAI;CACvB,OAAO,aAAa,QAAQ,UAAU,IAAI,KAAK,QAAQ,GAAG,MAAM;AACjE;;;;;;ACwBA,SAAgB,kBAAkB,SAAqC;CACtE,IAAI,SAAS,MAAM,OAAO,QAAQ;CAClC,OAAO,SAAS,OAAO,KAAK,QAAQ,MAAM,MAAM,IAAI,QAAQ;AAC7D;;;;AAKA,SAAgB,mBAAmB,SAAqC;CACvE,OAAO,KAAK,kBAAkB,OAAO,GAAG,kBAAkB;AAC3D;;;;AAKA,SAAS,qBAAqB,SAAmC;CAChE,MAAM,MAAM,kBAAkB,OAAO;CACrC,IAAI,CAAC,WAAW,GAAG,GAClB,UAAU,KAAK;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;AAEjD;;;;AAKA,eAAsB,gBACrB,SAC6B;CAC7B,MAAM,OAAO,mBAAmB,OAAO;CAEvC,IAAI,CAAC,WAAW,IAAI,GACnB,OAAO,CAAC;CAGT,IAAI;EACH,MAAM,UAAU,MAAM,SAAS,MAAM,OAAO;EAC5C,OAAO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U;GAC5B,OAAO;GAGP,OAAO,QAAQ,UAAU,OAAO,SAAS,KAAK;EAC/C,CAAC;EAED,MAAM,GAAG,UAAU,MAAqB,aAA4B;GACnE,OAAO;GACP,IAAI,QAAQ,SAAS,OAAO,OAAO,MAAM;QACpC,IAAI,UAAU,OAAO,IAAI,gBAAgB,SAAS,MAAM,SAAS,CAAC;QAEtE,eAAe;IACd,UAAU;IACV,QAAQ,YAAY;IACpB;IACA;GACD,CAAC;EACH,CAAC;CACF,CAAC;AACF"}
@@ -1,8 +1,8 @@
1
- import { Q as reconcileWorkspace, X as constructGlobs, kt as loadSecretsForApp } from "./sniffer-aO_-s5vq.mjs";
2
- import { r as discover } from "./discover-BaT6bpnA.mjs";
3
- import { p as loadWorkspaceConfig } from "./config-LKKCVCnC.mjs";
4
- import { E as TEST_STAGE } from "./workspace-Dh7rr7l4.mjs";
5
- import { n as secretsStoreFor } from "./store-BS8A7NcA.mjs";
1
+ import { H as constructGlobs, W as reconcileWorkspace, xt as loadSecretsForApp } from "./sniffer-49KPbDgq.mjs";
2
+ import { r as discover } from "./discover-LMrqsWSU.mjs";
3
+ import { E as TEST_STAGE } from "./workspace-Bwit4q9O.mjs";
4
+ import { loadWorkspaceConfig } from "./config.mjs";
5
+ import { n as secretsStoreFor } from "./store-BaaonhkJ.mjs";
6
6
  import { h as pendingMigrations, l as NoSuchMigrationTarget, m as migrateDatabases, n as slug, p as migrateAndSeed, r as stamp } from "./index.mjs";
7
7
  import { join } from "node:path";
8
8
  import { mkdir, writeFile } from "node:fs/promises";
@@ -262,4 +262,4 @@ function ids(targets) {
262
262
  //#endregion
263
263
  export { migrateAndSeed, migrateCommand, migrationCommand, prepareDevDatabases, reportPendingMigrations, seedCommand };
264
264
 
265
- //# sourceMappingURL=migrate-ImBKTBcW.mjs.map
265
+ //# sourceMappingURL=migrate-B4gngTLe.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-ImBKTBcW.mjs","names":[],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends Error {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets.map((target) => target.id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0C,MAAM;CAErC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,IAAI,MAAM,8EACe,MAAM,gEACG,MAAM,QAAQ,WAAW,GAC5D;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CACxB;CAArB,YAAY,WAA4B;EACvC,MACC,uCAAuC,UAAU,yEAElD;EAJoB,KAAA,YAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;;;;AA2BA,eAAsB,WACrB,KACA,OACsB;CACtB,MAAM,EAAE,cAAc,MAAM,oBAAoB,GAAG;CACnD,MAAM,QAAQ,UAAU,OAAO;CAC/B,MAAM,SAAS,SAAS;CACxB,IAAI,WAAW,SAAS,WAAA,QACvB,MAAM,IAAI,qBAAqB,QAAQ,KAAK;CAG7C,MAAM,UAA2C,CAAC;CAClD,MAAM,WAAW,MAAM,SAAS;EAC/B,UAAU,eAAe,SAAS;EAClC,KAAK,UAAU;EACf;CACD,CAAC;CAQD,OAAO;EACN;EACA;EACA;EACA,KAAK,EAAE,IAAG,MAVc,mBAAmB,WAAW;GACtD,OAAO;GACP;GACA,OAAO;EACR,CAAC,EAAA,CAMqB,IAAI;EACzB,OAAO;CACR;AACD;;AAGA,eAAsB,eACrB,UAA0B,CAAC,GACX;CAChB,MAAM,QAAQ,MAAM,WAAW,QAAQ,IAAI,GAAG,QAAQ,KAAK;CAE3D,MAAM,OAAO,MAAM,iBAAiB;EACnC,MAAM,MAAM,UAAU;EAC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,aAAa,EAAE,OAC7D,GAAG,QAAQ,KAAK,EAAE,GACnB;CACA,OAAO,IAAI,MAAM,MAAM;CACvB,OAAO;AACR;AAEA,MAAM,OAAO;;;;;;;;;;AAWb,eAAe,MACd,MACA,QACA,MACA,SACkB;CAClB,MAAM,SAAS,KAAK,MAAM,OAAO,UAAU;CAC3C,MAAM,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;CACvC,MAAM,UAAU,KAAK,QAAQ,IAAI,GAAG,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,OAAO,GAAG,OAAO,WAAW,GAAG;AAChC;AAEA,SAAS,IAAI,SAA+C;CAC3D,OAAO,QAAQ,KAAK,WAAW,OAAO,EAAE;AACzC"}
1
+ {"version":3,"file":"migrate-B4gngTLe.mjs","names":[],"sources":["../src/migrate/index.ts"],"sourcesContent":["/**\n * `gkm migrate`, `gkm seed` and `gkm migration` — applying a construct's\n * migrations, running its seeds, and writing its next migration.\n *\n * Both work on a stage this machine reconciles: its containers up, its roles\n * provisioned, its owner URLs resolved. A deployed stage is migrated by the\n * deploy that ships it, which is the one thing that can reach its database.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\ttype ConstructManifest,\n\tcanonicalId,\n\ttype MigrationTarget,\n\tmigrationTargets,\n} from '@geekmidas/manifest';\nimport {\n\ttype ServiceRegisterOptions,\n\tserviceContext,\n} from '@geekmidas/services';\nimport { loadWorkspaceConfig } from '../config';\nimport { loadSecretsForApp } from '../credentials';\nimport { type ConstructSource, discover } from '../reconcile/discover';\nimport { constructGlobs, reconcileWorkspace } from '../reconcile/workspace.js';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { TEST_STAGE } from '../workspace/stages';\nimport type { NormalizedWorkspace } from '../workspace/types.js';\nimport {\n\ttype MigrationRun,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoSuchMigrationTarget,\n\tpendingMigrations,\n\ttype SeedRun,\n} from './databases';\nimport { slug, stamp } from './names';\n\nexport {\n\tKyselyNotFound,\n\tMigrationFailed,\n\ttype MigrationRun,\n\tMigrationsOutsideFolder,\n\tmigrateAndSeed,\n\tmigrateDatabases,\n\tNoOwnerCredential,\n\tNoSuchMigrationTarget,\n\ttype PendingMigrations,\n\tpendingMigrations,\n\tSeedFailed,\n\ttype SeedOptions,\n\ttype SeedRun,\n\tseedDatabases,\n\tUnknownDatabaseFolder,\n\tUnknownMigrationFolder,\n} from './databases';\nexport { slug, stamp } from './names';\nexport {\n\tDuplicateMigration,\n\tMigrationHasNoUp,\n\tSeedHasNoSeed,\n} from './provider';\n\nconst logger = console;\n\n/** `gkm migrate --stage` named a stage only a deploy can reach. */\nexport class MigrateDeployedStage extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly local: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${stage}' is a deployed stage, and its database is migrated by ` +\n\t\t\t\t`\\`gkm deploy --stage ${stage}\\`, which is what can reach it. ` +\n\t\t\t\t`\\`gkm migrate\\` runs against '${local}' or '${TEST_STAGE}'.`,\n\t\t);\n\t\tthis.name = 'MigrateDeployedStage';\n\t}\n}\n\n/** `gkm migration` for a Kysely database, with no name for the file. */\nexport class MigrationNeedsName extends Error {\n\tconstructor(readonly construct: string) {\n\t\tsuper(\n\t\t\t`Name the migration: \\`gkm migration ${construct} add_workouts\\`. ` +\n\t\t\t\t`The name is what the file — and the history — calls it.`,\n\t\t);\n\t\tthis.name = 'MigrationNeedsName';\n\t}\n}\n\nexport interface MigrateOptions {\n\t/** The stage to migrate: the project's local one, or `test`. */\n\tstage?: string;\n\t/** One construct, by name. All of them when absent. */\n\tconstruct?: string;\n}\n\n/** A workspace's stage, reconciled and ready to migrate. */\nexport interface ReadyStage {\n\tworkspace: NormalizedWorkspace;\n\tmanifest: ConstructManifest;\n\tsources: Record<string, ConstructSource>;\n\t/** Every URL the stage resolved — the owner URLs among them. */\n\tenv: Record<string, string>;\n\t/** The stage it is: the local one, or `test`. */\n\tstage: string;\n}\n\n/**\n * Reconcile a stage so it can be migrated: containers up, databases, schemas,\n * roles and grants in place, owner URLs resolved.\n *\n * Migrating assumes the roles exist, and this is what makes that true rather\n * than something a developer has to have run first.\n */\nexport async function readyStage(\n\tcwd: string,\n\tstage?: string,\n): Promise<ReadyStage> {\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tconst local = workspace.stages.local;\n\tconst target = stage ?? local;\n\tif (target !== local && target !== TEST_STAGE) {\n\t\tthrow new MigrateDeployedStage(target, local);\n\t}\n\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst reconciled = await reconcileWorkspace(workspace, {\n\t\tstage: target,\n\t\tmanifest,\n\t\tstart: true,\n\t});\n\n\treturn {\n\t\tworkspace,\n\t\tmanifest,\n\t\tsources,\n\t\tenv: { ...reconciled.env },\n\t\tstage: target,\n\t};\n}\n\n/** `gkm migrate [construct]`. */\nexport async function migrateCommand(\n\toptions: MigrateOptions = {},\n): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst runs = await migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (runs.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to migrate.');\n\t\treturn;\n\t}\n\n\tlogMigrations(runs);\n}\n\n/**\n * `gkm seed [construct]` — migrate, then run the seeds.\n *\n * Always migrates first: a seed is written against the schema its migrations\n * build, and against an older one it fails on a table that is not there yet.\n */\nexport async function seedCommand(options: MigrateOptions = {}): Promise<void> {\n\tconst ready = await readyStage(process.cwd(), options.stage);\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tstage: ready.stage,\n\t\t...(options.construct ? { only: options.construct } : {}),\n\t});\n\n\tif (migrations.length === 0) {\n\t\tlogger.log('🗄️ No database constructs to seed.');\n\t\treturn;\n\t}\n\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\n/** One line per construct: up to date, or what was applied. */\nexport function logMigrations(\n\truns: readonly MigrationRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, applied } of runs) {\n\t\tif (applied.length === 0) {\n\t\t\tlog(`🗄️ ${target.migrations}: up to date`);\n\t\t\tcontinue;\n\t\t}\n\t\tlog(`🗄️ ${target.migrations}: applied ${applied.length}`);\n\t\tfor (const name of applied) log(` ✓ ${name}`);\n\t}\n}\n\n/** One line per construct that has seeds, and each seed it ran. */\nexport function logSeeds(\n\truns: readonly SeedRun[],\n\tlog: (line: string) => void = logger.log,\n): void {\n\tfor (const { target, seeded } of runs) {\n\t\tif (seeded.length === 0) continue;\n\t\tlog(`🌱 ${target.seeds}: ran ${seeded.length}`);\n\t\tfor (const name of seeded) log(` ✓ ${name}`);\n\t}\n}\n\n/**\n * What `gkm dev` prints: one line per construct whose folder is ahead of its\n * history, and nothing when every folder is applied.\n *\n * Reported, never applied. A migration being written would otherwise run the\n * moment its file is saved, half-finished, against the database the developer\n * is working in.\n */\nexport async function reportPendingMigrations(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\n\tconst pending = await pendingMigrations({\n\t\troot: workspace.root,\n\t\tmanifest,\n\t\tsources,\n\t\tenv,\n\t});\n\n\tfor (const { target, pending: names } of pending) {\n\t\tlogger.log(\n\t\t\t`⚠️ ${target.migrations}: ${names.length} pending (${names.join(', ')}) — run gkm migrate`,\n\t\t);\n\t}\n}\n\n/**\n * What `gkm dev --migrate` and `gkm dev --seed` do before the apps start:\n * migrate, and with `seed`, run the seeds after — once, at startup, never on a\n * save, for the reason {@link reportPendingMigrations} gives.\n *\n * A failure here is thrown, unlike the report's: the developer asked for the\n * database to be brought up to date, and apps started against one in an\n * unknown state would fail somewhere less obvious.\n */\nexport async function prepareDevDatabases(\n\tworkspace: NormalizedWorkspace,\n\tenv: Readonly<Record<string, string>>,\n\t{ seed = false }: { seed?: boolean } = {},\n): Promise<void> {\n\tconst sources: Record<string, ConstructSource> = {};\n\tconst manifest = await discover({\n\t\tpatterns: constructGlobs(workspace),\n\t\tcwd: workspace.root,\n\t\tsources,\n\t});\n\tconst options = { root: workspace.root, manifest, sources, env };\n\n\tif (!seed) {\n\t\tlogMigrations(await migrateDatabases(options));\n\t\treturn;\n\t}\n\n\tconst { migrations, seeds } = await migrateAndSeed({\n\t\t...options,\n\t\tstage: workspace.stages.local,\n\t});\n\tlogMigrations(migrations);\n\tlogSeeds(seeds);\n}\n\nexport interface MigrationOptions {\n\t/** The construct the migration is for, by name. */\n\tconstruct: string;\n\t/** What the file is called, after its timestamp. */\n\tname?: string;\n\t/** The file's timestamp; the current time when absent. */\n\tnow?: Date;\n}\n\n/**\n * `gkm migration <construct> [name]` — write the construct's next migration.\n *\n * For a database, an empty `up`/`down` to fill in. For an auth server, what\n * its schema is missing, computed against its tenant once every committed\n * migration has been applied — so the file is only the change, and is\n * reviewed and committed like any other.\n */\nexport async function migrationCommand(\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\tconst ready = await readyStage(process.cwd());\n\tconst targets = migrationTargets(ready.manifest);\n\tconst id = canonicalId(options.construct);\n\n\tconst auth = authConstruct(ready.sources, id);\n\tif (auth) {\n\t\tconst target = targets.find((t) => t.id === auth.databaseId);\n\t\tif (!target) {\n\t\t\tthrow new NoSuchMigrationTarget(auth.databaseId, ids(targets));\n\t\t}\n\t\treturn writeAuthMigration(ready, auth, target, options);\n\t}\n\n\tconst target = targets.find((t) => t.id === id);\n\tif (!target) {\n\t\tthrow new NoSuchMigrationTarget(options.construct, [\n\t\t\t...ids(targets),\n\t\t\t...authIds(ready.sources),\n\t\t]);\n\t}\n\tif (!options.name) throw new MigrationNeedsName(options.construct);\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name)}.ts`,\n\t\tSTUB,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\n/** What an auth construct offers `gkm migration`, duck-typed across copies. */\ninterface AuthConstruct {\n\tid: string;\n\tdatabaseId: string;\n\tpendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined>;\n}\n\nfunction authConstruct(\n\tsources: Readonly<Record<string, ConstructSource>>,\n\tid: string,\n): AuthConstruct | undefined {\n\tconst construct = sources[id]?.construct as\n\t\t| Partial<AuthConstruct>\n\t\t| undefined;\n\treturn construct &&\n\t\ttypeof construct.pendingMigration === 'function' &&\n\t\ttypeof construct.databaseId === 'string'\n\t\t? (construct as AuthConstruct)\n\t\t: undefined;\n}\n\nfunction authIds(sources: Readonly<Record<string, ConstructSource>>): string[] {\n\treturn Object.keys(sources).filter((id) => authConstruct(sources, id));\n}\n\nasync function writeAuthMigration(\n\tready: ReadyStage,\n\tauth: AuthConstruct,\n\ttarget: MigrationTarget,\n\toptions: MigrationOptions,\n): Promise<string | undefined> {\n\t// Against a tenant already at its committed migrations, so the comparison\n\t// finds only what the files do not yet say.\n\tawait migrateDatabases({\n\t\troot: ready.workspace.root,\n\t\tmanifest: ready.manifest,\n\t\tsources: ready.sources,\n\t\tenv: ready.env,\n\t\tonly: target.id,\n\t});\n\n\t// Its secret and URL come from the stage's secrets; the tenant's owner URL\n\t// from the reconcile above, which wins.\n\tconst stage = ready.workspace.stages.local;\n\tconst secrets = await loadSecretsForApp(\n\t\tawait secretsStoreFor(ready.workspace, stage),\n\t\tstage,\n\t);\n\tconst pending = await auth.pendingMigration({\n\t\tenvParser: new EnvironmentParser({ ...secrets, ...ready.env }),\n\t\tcontext: serviceContext,\n\t});\n\n\tif (!pending) {\n\t\tlogger.log(`✓ ${target.migrations}: ${auth.id} is up to date`);\n\t\treturn undefined;\n\t}\n\n\tconst file = await write(\n\t\tready.workspace.root,\n\t\ttarget,\n\t\t`${stamp(options.now)}_${slug(options.name ?? 'better_auth')}.sql`,\n\t\t`${pending.trim()}\\n`,\n\t);\n\tlogger.log(`📝 ${file}`);\n\treturn file;\n}\n\nconst STUB = `import type { Kysely } from 'kysely';\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n // await db.schema.createTable('…').addColumn(…).execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n // await db.schema.dropTable('…').execute();\n}\n`;\n\nasync function write(\n\troot: string,\n\ttarget: MigrationTarget,\n\tfile: string,\n\tcontent: string,\n): Promise<string> {\n\tconst folder = join(root, target.migrations);\n\tawait mkdir(folder, { recursive: true });\n\tawait writeFile(join(folder, file), content, { flag: 'wx' });\n\treturn `${target.migrations}/${file}`;\n}\n\nfunction ids(targets: readonly MigrationTarget[]): string[] {\n\treturn targets.map((target) => target.id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,SAAS;;AAGf,IAAa,uBAAb,cAA0C,MAAM;CAErC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,IAAI,MAAM,8EACe,MAAM,gEACG,MAAM,QAAQ,WAAW,GAC5D;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CACxB;CAArB,YAAY,WAA4B;EACvC,MACC,uCAAuC,UAAU,yEAElD;EAJoB,KAAA,YAAA;EAKpB,KAAK,OAAO;CACb;AACD;;;;;;;;AA2BA,eAAsB,WACrB,KACA,OACsB;CACtB,MAAM,EAAE,cAAc,MAAM,oBAAoB,GAAG;CACnD,MAAM,QAAQ,UAAU,OAAO;CAC/B,MA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