@geekmidas/cli 10.0.0-alpha.74 → 10.0.0-alpha.76
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.
- package/dist/{LegacyStateStore-D_78eaHM.cjs → LegacyStateStore-DwngfJxr.cjs} +2 -2
- package/dist/{LegacyStateStore-D_78eaHM.cjs.map → LegacyStateStore-DwngfJxr.cjs.map} +1 -1
- package/dist/{LegacyStateStore-DTo7z924.mjs → LegacyStateStore-dyq07_Ir.mjs} +2 -2
- package/dist/{LegacyStateStore-DTo7z924.mjs.map → LegacyStateStore-dyq07_Ir.mjs.map} +1 -1
- package/dist/{LocalStateStore-BhrlQIXD.cjs → LocalStateStore-B0NCde8Z.cjs} +2 -2
- package/dist/{LocalStateStore-BhrlQIXD.cjs.map → LocalStateStore-B0NCde8Z.cjs.map} +1 -1
- package/dist/{LocalStateStore-CNjgkRk4.mjs → LocalStateStore-DLxCCatI.mjs} +2 -2
- package/dist/{LocalStateStore-CNjgkRk4.mjs.map → LocalStateStore-DLxCCatI.mjs.map} +1 -1
- package/dist/{S3StateStore-oCxRs6HM.cjs → S3StateStore-BOenb-3o.cjs} +2 -2
- package/dist/{S3StateStore-oCxRs6HM.cjs.map → S3StateStore-BOenb-3o.cjs.map} +1 -1
- package/dist/{S3StateStore-g2P7T_Mo.mjs → S3StateStore-CGK_4hlo.mjs} +2 -2
- package/dist/{S3StateStore-g2P7T_Mo.mjs.map → S3StateStore-CGK_4hlo.mjs.map} +1 -1
- package/dist/{SSMStateStore-CYenunmK.mjs → SSMStateStore-B_5_RqY-.mjs} +2 -2
- package/dist/{SSMStateStore-CYenunmK.mjs.map → SSMStateStore-B_5_RqY-.mjs.map} +1 -1
- package/dist/{SSMStateStore-DXp0m7XI.cjs → SSMStateStore-DYeD__7p.cjs} +2 -2
- package/dist/{SSMStateStore-DXp0m7XI.cjs.map → SSMStateStore-DYeD__7p.cjs.map} +1 -1
- package/dist/{add-BTH7WaH3.mjs → add-B7IMXzou.mjs} +3 -3
- package/dist/{add-BTH7WaH3.mjs.map → add-B7IMXzou.mjs.map} +1 -1
- package/dist/{add-Djrr12Xc.cjs → add-j2yI3cbS.cjs} +3 -3
- package/dist/{add-Djrr12Xc.cjs.map → add-j2yI3cbS.cjs.map} +1 -1
- package/dist/{aws-DojzQnLd.mjs → aws-Bja4zGSs.mjs} +13 -9
- package/dist/aws-Bja4zGSs.mjs.map +1 -0
- package/dist/{aws-DkHdTV-p.cjs → aws-CQAuluiu.cjs} +13 -9
- package/dist/aws-CQAuluiu.cjs.map +1 -0
- package/dist/awsStore-7VmS_cZR.cjs +54 -0
- package/dist/awsStore-7VmS_cZR.cjs.map +1 -0
- package/dist/awsStore-B529csle.mjs +43 -0
- package/dist/awsStore-B529csle.mjs.map +1 -0
- package/dist/{bundler-utHuESvL.cjs → bundler-Cf6OgaOe.cjs} +5 -5
- package/dist/bundler-Cf6OgaOe.cjs.map +1 -0
- package/dist/{bundler-BUojOkof.mjs → bundler-DO6bHhnb.mjs} +5 -5
- package/dist/bundler-DO6bHhnb.mjs.map +1 -0
- package/dist/{cli-CyYceKTS.mjs → cli-BCPOHmg9.mjs} +3 -3
- package/dist/{cli-CyYceKTS.mjs.map → cli-BCPOHmg9.mjs.map} +1 -1
- package/dist/{cli-Bx0sUzxH.cjs → cli-CNanUB7a.cjs} +3 -3
- package/dist/{cli-Bx0sUzxH.cjs.map → cli-CNanUB7a.cjs.map} +1 -1
- package/dist/{compose-DZp8DJ0A.mjs → compose-Dq4VCtu5.mjs} +221 -153
- package/dist/compose-Dq4VCtu5.mjs.map +1 -0
- package/dist/{compose-iuw8wfHk.cjs → compose-h_6oNnHC.cjs} +243 -151
- package/dist/compose-h_6oNnHC.cjs.map +1 -0
- package/dist/{config-B38YWicj.d.cts → config-CWyhLSY1.d.cts} +3 -3
- package/dist/{config-B38YWicj.d.cts.map → config-CWyhLSY1.d.cts.map} +1 -1
- package/dist/{config-DA0kRTQe.d.mts → config-CqAvPP-f.d.mts} +3 -3
- package/dist/{config-DA0kRTQe.d.mts.map → config-CqAvPP-f.d.mts.map} +1 -1
- package/dist/config.cjs +1 -1
- package/dist/config.d.cts +3 -3
- package/dist/config.d.mts +3 -3
- package/dist/config.mjs +1 -1
- package/dist/deploy/public.cjs +7 -6
- package/dist/deploy/public.d.cts +14 -3
- package/dist/deploy/public.d.cts.map +1 -1
- package/dist/deploy/public.d.mts +14 -3
- package/dist/deploy/public.d.mts.map +1 -1
- package/dist/deploy/public.mjs +7 -7
- package/dist/{deploy-eWorhvQp.cjs → deploy-CT3R9de9.cjs} +27 -5
- package/dist/deploy-CT3R9de9.cjs.map +1 -0
- package/dist/{deploy-C17K7Imy.mjs → deploy-CVXEx7Nm.mjs} +22 -6
- package/dist/deploy-CVXEx7Nm.mjs.map +1 -0
- package/dist/{dokploy-DKa49Nqm.mjs → dokploy-CYm2ozFs.mjs} +2 -2
- package/dist/{dokploy-DKa49Nqm.mjs.map → dokploy-CYm2ozFs.mjs.map} +1 -1
- package/dist/{dokploy-DKzcI-RL.cjs → dokploy-eSGmlhhj.cjs} +2 -2
- package/dist/{dokploy-DKzcI-RL.cjs.map → dokploy-eSGmlhhj.cjs.map} +1 -1
- package/dist/{encryption-sTMz3aWi.mjs → encryption-DC0rsR1W.mjs} +3 -3
- package/dist/{encryption-sTMz3aWi.mjs.map → encryption-DC0rsR1W.mjs.map} +1 -1
- package/dist/{encryption-DSkJdoyk.cjs → encryption-vS3Qzw73.cjs} +3 -3
- package/dist/{encryption-DSkJdoyk.cjs.map → encryption-vS3Qzw73.cjs.map} +1 -1
- package/dist/{engine-B1b4I34Z.mjs → engine-BOO5TWZd.mjs} +193 -5
- package/dist/engine-BOO5TWZd.mjs.map +1 -0
- package/dist/{engine-Bh76sAHy.cjs → engine-C0N2d1i5.cjs} +196 -8
- package/dist/engine-C0N2d1i5.cjs.map +1 -0
- package/dist/{github-C9ODoyZU.mjs → github-CEaFDL6t.mjs} +6 -6
- package/dist/github-CEaFDL6t.mjs.map +1 -0
- package/dist/{github-BvN3CfxM.cjs → github-ClkdCOL9.cjs} +6 -6
- package/dist/github-ClkdCOL9.cjs.map +1 -0
- package/dist/{index-B-1lLGzy.d.mts → index-Ccu0f_2m.d.cts} +2 -2
- package/dist/{index-B-1lLGzy.d.mts.map → index-Ccu0f_2m.d.cts.map} +1 -1
- package/dist/{index-vMidfqhU.d.cts → index-DOxmDKqv.d.mts} +2 -2
- package/dist/{index-vMidfqhU.d.cts.map → index-DOxmDKqv.d.mts.map} +1 -1
- package/dist/index.cjs +106 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +105 -51
- package/dist/index.mjs.map +1 -1
- package/dist/migrate-BRbYtFXG.cjs +93 -0
- package/dist/migrate-BRbYtFXG.cjs.map +1 -0
- package/dist/migrate-D3NAT7Ns.mjs +93 -0
- package/dist/migrate-D3NAT7Ns.mjs.map +1 -0
- package/dist/{migrate-B0FCZNkp.cjs → migrate-D5_-ylI1.cjs} +3 -3
- package/dist/{migrate-B0FCZNkp.cjs.map → migrate-D5_-ylI1.cjs.map} +1 -1
- package/dist/{migrate-CTtJhGV9.mjs → migrate-DrO2p9Rl.mjs} +3 -3
- package/dist/{migrate-CTtJhGV9.mjs.map → migrate-DrO2p9Rl.mjs.map} +1 -1
- package/dist/openapi.cjs +16 -6
- package/dist/openapi.cjs.map +1 -1
- package/dist/openapi.d.cts +1 -1
- package/dist/openapi.d.cts.map +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/openapi.d.mts.map +1 -1
- package/dist/openapi.mjs +16 -6
- package/dist/openapi.mjs.map +1 -1
- package/dist/reconcile/public.d.cts +1 -1
- package/dist/reconcile/public.d.mts +1 -1
- package/dist/{resolve-DSAXj_47.mjs → resolve-C1muFos5.mjs} +3 -3
- package/dist/{resolve-DSAXj_47.mjs.map → resolve-C1muFos5.mjs.map} +1 -1
- package/dist/{resolve-D_BU-wKA.cjs → resolve-Fa1Ii0BK.cjs} +3 -3
- package/dist/{resolve-D_BU-wKA.cjs.map → resolve-Fa1Ii0BK.cjs.map} +1 -1
- package/dist/{rollback-DJy3t696.cjs → rollback-C9N5lKVf.cjs} +5 -5
- package/dist/{rollback-DJy3t696.cjs.map → rollback-C9N5lKVf.cjs.map} +1 -1
- package/dist/{rollback-CWYTUhfW.mjs → rollback-DeQzbRqM.mjs} +5 -5
- package/dist/{rollback-CWYTUhfW.mjs.map → rollback-DeQzbRqM.mjs.map} +1 -1
- package/dist/{runtime-BzZD5HHi.d.cts → runtime-BSvzPqXW.d.mts} +2 -2
- package/dist/{runtime-BzZD5HHi.d.cts.map → runtime-BSvzPqXW.d.mts.map} +1 -1
- package/dist/{runtime-Cm6J6L7n.d.mts → runtime-Cm7QA53H.d.cts} +2 -2
- package/dist/{runtime-Cm6J6L7n.d.mts.map → runtime-Cm7QA53H.d.cts.map} +1 -1
- package/dist/secretsManager-DUXW3fQt.cjs +70 -0
- package/dist/secretsManager-DUXW3fQt.cjs.map +1 -0
- package/dist/secretsManager-Ti0oZwsS.mjs +70 -0
- package/dist/secretsManager-Ti0oZwsS.mjs.map +1 -0
- package/dist/{sniffer-BFmdZpZ2.mjs → sniffer-DR8AlRCk.mjs} +67 -15
- package/dist/sniffer-DR8AlRCk.mjs.map +1 -0
- package/dist/{sniffer-C-T7dSMN.cjs → sniffer-Y6GQOCXB.cjs} +83 -13
- package/dist/sniffer-Y6GQOCXB.cjs.map +1 -0
- package/dist/{state-DCwRWyh-.cjs → state-C2qi0iQw.cjs} +241 -334
- package/dist/state-C2qi0iQw.cjs.map +1 -0
- package/dist/{state-DpkxSwzI.mjs → state-CUecOCNJ.mjs} +213 -306
- package/dist/state-CUecOCNJ.mjs.map +1 -0
- package/dist/target/public.cjs +1 -1
- package/dist/target/public.d.cts +2 -2
- package/dist/target/public.d.mts +2 -2
- package/dist/target/public.mjs +1 -1
- package/dist/{types-TzCChNrA.d.cts → types-BdptGBFS.d.cts} +59 -6
- package/dist/types-BdptGBFS.d.cts.map +1 -0
- package/dist/{types-Dp9lgx_S.d.mts → types-OxE0OAn2.d.mts} +59 -6
- package/dist/types-OxE0OAn2.d.mts.map +1 -0
- package/dist/workspace/index.cjs +1 -1
- package/dist/workspace/index.d.cts +2 -2
- package/dist/workspace/index.d.mts +2 -2
- package/dist/workspace/index.mjs +1 -1
- package/dist/{workspace-vdrcRI-m.cjs → workspace-DOm81oUo.cjs} +54 -1
- package/dist/workspace-DOm81oUo.cjs.map +1 -0
- package/dist/{workspace-C7NqCsQF.mjs → workspace-QUTqYmVy.mjs} +43 -2
- package/dist/workspace-QUTqYmVy.mjs.map +1 -0
- package/package.json +18 -17
- package/dist/aws-DkHdTV-p.cjs.map +0 -1
- package/dist/aws-DojzQnLd.mjs.map +0 -1
- package/dist/bundler-BUojOkof.mjs.map +0 -1
- package/dist/bundler-utHuESvL.cjs.map +0 -1
- package/dist/compose-DZp8DJ0A.mjs.map +0 -1
- package/dist/compose-iuw8wfHk.cjs.map +0 -1
- package/dist/deploy-C17K7Imy.mjs.map +0 -1
- package/dist/deploy-eWorhvQp.cjs.map +0 -1
- package/dist/engine-B1b4I34Z.mjs.map +0 -1
- package/dist/engine-Bh76sAHy.cjs.map +0 -1
- package/dist/github-BvN3CfxM.cjs.map +0 -1
- package/dist/github-C9ODoyZU.mjs.map +0 -1
- package/dist/sniffer-BFmdZpZ2.mjs.map +0 -1
- package/dist/sniffer-C-T7dSMN.cjs.map +0 -1
- package/dist/state-DCwRWyh-.cjs.map +0 -1
- package/dist/state-DpkxSwzI.mjs.map +0 -1
- package/dist/types-Dp9lgx_S.d.mts.map +0 -1
- package/dist/types-TzCChNrA.d.cts.map +0 -1
- package/dist/workspace-C7NqCsQF.mjs.map +0 -1
- package/dist/workspace-vdrcRI-m.cjs.map +0 -1
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const require_workspace = require("./workspace-DOm81oUo.cjs");
|
|
2
|
+
const require_config = require("./config.cjs");
|
|
3
|
+
const require_state = require("./state-C2qi0iQw.cjs");
|
|
4
|
+
//#region src/secrets/migrate.ts
|
|
5
|
+
/**
|
|
6
|
+
* `gkm secrets:migrate` — copy a deployed stage's secrets from the store
|
|
7
|
+
* `secrets.store` names to another one, whole: service passwords, URLs and
|
|
8
|
+
* custom keys alike, so nothing is regenerated and running services keep
|
|
9
|
+
* their credentials.
|
|
10
|
+
*
|
|
11
|
+
* It copies and nothing more. The source is left as it was, and gkm.config.ts
|
|
12
|
+
* is not edited: pointing `secrets.store` at the new store is the switch, and
|
|
13
|
+
* the old copy is deleted by hand once deploys read from the new one.
|
|
14
|
+
*/
|
|
15
|
+
const logger = console;
|
|
16
|
+
/** An AWS store to copy to, with no region given and none configured. */
|
|
17
|
+
var MigrateTargetNeedsRegion = class extends Error {
|
|
18
|
+
to;
|
|
19
|
+
constructor(to) {
|
|
20
|
+
super(`Copying to ${to} needs a region, and secrets.store has none to reuse. Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`);
|
|
21
|
+
this.to = to;
|
|
22
|
+
this.name = "MigrateTargetNeedsRegion";
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/** The target is the store the stage is already read from. */
|
|
26
|
+
var MigrateTargetIsSource = class extends Error {
|
|
27
|
+
stage;
|
|
28
|
+
to;
|
|
29
|
+
constructor(stage, to) {
|
|
30
|
+
super(`Stage "${stage}" is already kept in ${to}, so there is nothing to copy. Name a different store with --to, or a different region with --region.`);
|
|
31
|
+
this.stage = stage;
|
|
32
|
+
this.to = to;
|
|
33
|
+
this.name = "MigrateTargetIsSource";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** The configured store holds nothing for the stage. */
|
|
37
|
+
var NoSecretsToMigrate = class extends Error {
|
|
38
|
+
stage;
|
|
39
|
+
store;
|
|
40
|
+
constructor(stage, store) {
|
|
41
|
+
super(`The ${store} store holds no secrets for stage "${stage}", so there is nothing to copy. Check secrets.store in gkm.config.ts still names the store the stage is in, or create the stage there with gkm secrets:init --stage ${stage}.`);
|
|
42
|
+
this.stage = stage;
|
|
43
|
+
this.store = store;
|
|
44
|
+
this.name = "NoSecretsToMigrate";
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** The target already holds the stage, and `--force` was not given. */
|
|
48
|
+
var MigrateTargetHoldsStage = class extends Error {
|
|
49
|
+
stage;
|
|
50
|
+
to;
|
|
51
|
+
constructor(stage, to) {
|
|
52
|
+
super(`The ${to} store already holds secrets for stage "${stage}". Pass --force to replace them with the ones being copied.`);
|
|
53
|
+
this.stage = stage;
|
|
54
|
+
this.to = to;
|
|
55
|
+
this.name = "MigrateTargetHoldsStage";
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
/** The store a `--to` name and region describe. */
|
|
59
|
+
function targetConfig(to, region, configured) {
|
|
60
|
+
if (!require_workspace.SECRETS_STORE_PROVIDERS.includes(to)) throw new require_workspace.UnknownSecretsStoreProvider(to);
|
|
61
|
+
const provider = to;
|
|
62
|
+
if (provider === "file") return "file";
|
|
63
|
+
const fallback = typeof configured === "object" && "region" in configured ? configured.region : void 0;
|
|
64
|
+
const resolved = region ?? fallback;
|
|
65
|
+
if (!resolved) throw new MigrateTargetNeedsRegion(provider);
|
|
66
|
+
return {
|
|
67
|
+
provider,
|
|
68
|
+
region: resolved
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
async function secretsMigrateCommand(options) {
|
|
72
|
+
const { stage, to } = options;
|
|
73
|
+
const workspace = await require_config.loadWorkspaceSettings();
|
|
74
|
+
require_workspace.assertDeployedStage(workspace.stages, stage);
|
|
75
|
+
const configured = workspace.secrets.store ?? "file";
|
|
76
|
+
const target = targetConfig(to, options.region, configured);
|
|
77
|
+
if (typeof configured === "string" || typeof target === "string" ? configured === target : configured.provider === target.provider && "region" in configured && "region" in target && configured.region === target.region) throw new MigrateTargetIsSource(stage, to);
|
|
78
|
+
const storeOptions = options.profile ? { profile: options.profile } : {};
|
|
79
|
+
const source = await require_state.secretsStoreFor(workspace, stage, storeOptions);
|
|
80
|
+
const destination = await require_state.storeFromConfig(workspace, target, storeOptions);
|
|
81
|
+
const secrets = await source.read(stage);
|
|
82
|
+
if (!secrets) throw new NoSecretsToMigrate(stage, source.name);
|
|
83
|
+
if (!options.force && await destination.read(stage)) throw new MigrateTargetHoldsStage(stage, destination.name);
|
|
84
|
+
await destination.write(stage, secrets);
|
|
85
|
+
const shape = typeof target === "object" && "region" in target ? `{ provider: '${target.provider}', region: '${target.region}' }` : `'file'`;
|
|
86
|
+
logger.log(`\n✓ Copied the secrets for stage "${stage}" from ${source.name} to ${destination.name}`);
|
|
87
|
+
logger.log(`\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`);
|
|
88
|
+
logger.log(` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`);
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
exports.secretsMigrateCommand = secretsMigrateCommand;
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=migrate-BRbYtFXG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate-BRbYtFXG.cjs","names":["SECRETS_STORE_PROVIDERS","UnknownSecretsStoreProvider","loadWorkspaceSettings","secretsStoreFor","storeFromConfig"],"sources":["../src/secrets/migrate.ts"],"sourcesContent":["/**\n * `gkm secrets:migrate` — copy a deployed stage's secrets from the store\n * `secrets.store` names to another one, whole: service passwords, URLs and\n * custom keys alike, so nothing is regenerated and running services keep\n * their credentials.\n *\n * It copies and nothing more. The source is left as it was, and gkm.config.ts\n * is not edited: pointing `secrets.store` at the new store is the switch, and\n * the old copy is deleted by hand once deploys read from the new one.\n */\n\nimport { loadWorkspaceSettings } from '../config.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport {\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreConfig,\n\ttype SecretsStoreOptions,\n\ttype SecretsStoreProvider,\n\tsecretsStoreFor,\n\tstoreFromConfig,\n\tUnknownSecretsStoreProvider,\n} from './store.js';\n\nconst logger = console;\n\nexport interface SecretsMigrateOptions {\n\tstage: string;\n\t/** The store to copy to: `'file'`, `'ssm'` or `'secrets-manager'`. */\n\tto: string;\n\t/** The target's AWS region; defaults to the configured store's. */\n\tregion?: string;\n\t/** Overwrite a stage the target already holds. */\n\tforce?: boolean;\n\t/** The AWS profile for the stage's account, for both stores. */\n\tprofile?: string;\n}\n\n/** An AWS store to copy to, with no region given and none configured. */\nexport class MigrateTargetNeedsRegion extends Error {\n\tconstructor(readonly to: string) {\n\t\tsuper(\n\t\t\t`Copying to ${to} needs a region, and secrets.store has none to reuse. ` +\n\t\t\t\t`Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`,\n\t\t);\n\t\tthis.name = 'MigrateTargetNeedsRegion';\n\t}\n}\n\n/** The target is the store the stage is already read from. */\nexport class MigrateTargetIsSource extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`Stage \"${stage}\" is already kept in ${to}, so there is nothing to copy. ` +\n\t\t\t\t'Name a different store with --to, or a different region with --region.',\n\t\t);\n\t\tthis.name = 'MigrateTargetIsSource';\n\t}\n}\n\n/** The configured store holds nothing for the stage. */\nexport class NoSecretsToMigrate extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${store} store holds no secrets for stage \"${stage}\", so there is nothing to copy. ` +\n\t\t\t\t`Check secrets.store in gkm.config.ts still names the store the stage is in, ` +\n\t\t\t\t`or create the stage there with gkm secrets:init --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'NoSecretsToMigrate';\n\t}\n}\n\n/** The target already holds the stage, and `--force` was not given. */\nexport class MigrateTargetHoldsStage extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${to} store already holds secrets for stage \"${stage}\". ` +\n\t\t\t\t'Pass --force to replace them with the ones being copied.',\n\t\t);\n\t\tthis.name = 'MigrateTargetHoldsStage';\n\t}\n}\n\n/** The store a `--to` name and region describe. */\nfunction targetConfig(\n\tto: string,\n\tregion: string | undefined,\n\tconfigured: SecretsStoreConfig,\n): SecretsStoreConfig {\n\tif (!(SECRETS_STORE_PROVIDERS as readonly string[]).includes(to)) {\n\t\tthrow new UnknownSecretsStoreProvider(to);\n\t}\n\tconst provider = to as SecretsStoreProvider;\n\tif (provider === 'file') return 'file';\n\n\tconst fallback =\n\t\ttypeof configured === 'object' && 'region' in configured\n\t\t\t? configured.region\n\t\t\t: undefined;\n\tconst resolved = region ?? fallback;\n\tif (!resolved) throw new MigrateTargetNeedsRegion(provider);\n\treturn { provider, region: resolved };\n}\n\nexport async function secretsMigrateCommand(\n\toptions: SecretsMigrateOptions,\n): Promise<void> {\n\tconst { stage, to } = options;\n\tconst workspace = await loadWorkspaceSettings();\n\tassertDeployedStage(workspace.stages, stage);\n\n\tconst configured = workspace.secrets.store ?? 'file';\n\tconst target = targetConfig(to, options.region, configured);\n\tconst sameStore =\n\t\ttypeof configured === 'string' || typeof target === 'string'\n\t\t\t? configured === target\n\t\t\t: configured.provider === target.provider &&\n\t\t\t\t'region' in configured &&\n\t\t\t\t'region' in target &&\n\t\t\t\tconfigured.region === target.region;\n\tif (sameStore) throw new MigrateTargetIsSource(stage, to);\n\n\tconst storeOptions: SecretsStoreOptions = options.profile\n\t\t? { profile: options.profile }\n\t\t: {};\n\tconst source = await secretsStoreFor(workspace, stage, storeOptions);\n\tconst destination = await storeFromConfig(workspace, target, storeOptions);\n\n\tconst secrets = await source.read(stage);\n\tif (!secrets) throw new NoSecretsToMigrate(stage, source.name);\n\n\tif (!options.force && (await destination.read(stage))) {\n\t\tthrow new MigrateTargetHoldsStage(stage, destination.name);\n\t}\n\n\tawait destination.write(stage, secrets);\n\n\tconst shape =\n\t\ttypeof target === 'object' && 'region' in target\n\t\t\t? `{ provider: '${target.provider}', region: '${target.region}' }`\n\t\t\t: `'file'`;\n\tlogger.log(\n\t\t`\\n✓ Copied the secrets for stage \"${stage}\" from ${source.name} to ${destination.name}`,\n\t);\n\tlogger.log(\n\t\t`\\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`,\n\t);\n\tlogger.log(\n\t\t` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAM,SAAS;;AAef,IAAa,2BAAb,cAA8C,MAAM;CAC9B;CAArB,YAAY,IAAqB;EAChC,MACC,cAAc,GAAG,0FACqB,GAAG,oCAC1C;EAJoB,KAAA,KAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wBAAb,cAA2C,MAAM;CAEtC;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,UAAU,MAAM,uBAAuB,GAAG,sGAE3C;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAEnC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,OAAO,MAAM,qCAAqC,MAAM,sKAEI,MAAM,EACnE;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,0BAAb,cAA6C,MAAM;CAExC;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,OAAO,GAAG,0CAA0C,MAAM,4DAE3D;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,aACR,IACA,QACA,YACqB;CACrB,IAAI,CAAEA,kBAAAA,wBAA8C,SAAS,EAAE,GAC9D,MAAM,IAAIC,kBAAAA,4BAA4B,EAAE;CAEzC,MAAM,WAAW;CACjB,IAAI,aAAa,QAAQ,OAAO;CAEhC,MAAM,WACL,OAAO,eAAe,YAAY,YAAY,aAC3C,WAAW,SACX,KAAA;CACJ,MAAM,WAAW,UAAU;CAC3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@@
|
|
|
1
|
+
import { F as UnknownSecretsStoreProvider, P as SECRETS_STORE_PROVIDERS, k as assertDeployedStage } from "./workspace-QUTqYmVy.mjs";
|
|
2
|
+
import { loadWorkspaceSettings } from "./config.mjs";
|
|
3
|
+
import { Gt as secretsStoreFor, Kt as storeFromConfig } from "./state-CUecOCNJ.mjs";
|
|
4
|
+
//#region src/secrets/migrate.ts
|
|
5
|
+
/**
|
|
6
|
+
* `gkm secrets:migrate` — copy a deployed stage's secrets from the store
|
|
7
|
+
* `secrets.store` names to another one, whole: service passwords, URLs and
|
|
8
|
+
* custom keys alike, so nothing is regenerated and running services keep
|
|
9
|
+
* their credentials.
|
|
10
|
+
*
|
|
11
|
+
* It copies and nothing more. The source is left as it was, and gkm.config.ts
|
|
12
|
+
* is not edited: pointing `secrets.store` at the new store is the switch, and
|
|
13
|
+
* the old copy is deleted by hand once deploys read from the new one.
|
|
14
|
+
*/
|
|
15
|
+
const logger = console;
|
|
16
|
+
/** An AWS store to copy to, with no region given and none configured. */
|
|
17
|
+
var MigrateTargetNeedsRegion = class extends Error {
|
|
18
|
+
to;
|
|
19
|
+
constructor(to) {
|
|
20
|
+
super(`Copying to ${to} needs a region, and secrets.store has none to reuse. Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`);
|
|
21
|
+
this.to = to;
|
|
22
|
+
this.name = "MigrateTargetNeedsRegion";
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
/** The target is the store the stage is already read from. */
|
|
26
|
+
var MigrateTargetIsSource = class extends Error {
|
|
27
|
+
stage;
|
|
28
|
+
to;
|
|
29
|
+
constructor(stage, to) {
|
|
30
|
+
super(`Stage "${stage}" is already kept in ${to}, so there is nothing to copy. Name a different store with --to, or a different region with --region.`);
|
|
31
|
+
this.stage = stage;
|
|
32
|
+
this.to = to;
|
|
33
|
+
this.name = "MigrateTargetIsSource";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** The configured store holds nothing for the stage. */
|
|
37
|
+
var NoSecretsToMigrate = class extends Error {
|
|
38
|
+
stage;
|
|
39
|
+
store;
|
|
40
|
+
constructor(stage, store) {
|
|
41
|
+
super(`The ${store} store holds no secrets for stage "${stage}", so there is nothing to copy. Check secrets.store in gkm.config.ts still names the store the stage is in, or create the stage there with gkm secrets:init --stage ${stage}.`);
|
|
42
|
+
this.stage = stage;
|
|
43
|
+
this.store = store;
|
|
44
|
+
this.name = "NoSecretsToMigrate";
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** The target already holds the stage, and `--force` was not given. */
|
|
48
|
+
var MigrateTargetHoldsStage = class extends Error {
|
|
49
|
+
stage;
|
|
50
|
+
to;
|
|
51
|
+
constructor(stage, to) {
|
|
52
|
+
super(`The ${to} store already holds secrets for stage "${stage}". Pass --force to replace them with the ones being copied.`);
|
|
53
|
+
this.stage = stage;
|
|
54
|
+
this.to = to;
|
|
55
|
+
this.name = "MigrateTargetHoldsStage";
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
/** The store a `--to` name and region describe. */
|
|
59
|
+
function targetConfig(to, region, configured) {
|
|
60
|
+
if (!SECRETS_STORE_PROVIDERS.includes(to)) throw new UnknownSecretsStoreProvider(to);
|
|
61
|
+
const provider = to;
|
|
62
|
+
if (provider === "file") return "file";
|
|
63
|
+
const fallback = typeof configured === "object" && "region" in configured ? configured.region : void 0;
|
|
64
|
+
const resolved = region ?? fallback;
|
|
65
|
+
if (!resolved) throw new MigrateTargetNeedsRegion(provider);
|
|
66
|
+
return {
|
|
67
|
+
provider,
|
|
68
|
+
region: resolved
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
async function secretsMigrateCommand(options) {
|
|
72
|
+
const { stage, to } = options;
|
|
73
|
+
const workspace = await loadWorkspaceSettings();
|
|
74
|
+
assertDeployedStage(workspace.stages, stage);
|
|
75
|
+
const configured = workspace.secrets.store ?? "file";
|
|
76
|
+
const target = targetConfig(to, options.region, configured);
|
|
77
|
+
if (typeof configured === "string" || typeof target === "string" ? configured === target : configured.provider === target.provider && "region" in configured && "region" in target && configured.region === target.region) throw new MigrateTargetIsSource(stage, to);
|
|
78
|
+
const storeOptions = options.profile ? { profile: options.profile } : {};
|
|
79
|
+
const source = await secretsStoreFor(workspace, stage, storeOptions);
|
|
80
|
+
const destination = await storeFromConfig(workspace, target, storeOptions);
|
|
81
|
+
const secrets = await source.read(stage);
|
|
82
|
+
if (!secrets) throw new NoSecretsToMigrate(stage, source.name);
|
|
83
|
+
if (!options.force && await destination.read(stage)) throw new MigrateTargetHoldsStage(stage, destination.name);
|
|
84
|
+
await destination.write(stage, secrets);
|
|
85
|
+
const shape = typeof target === "object" && "region" in target ? `{ provider: '${target.provider}', region: '${target.region}' }` : `'file'`;
|
|
86
|
+
logger.log(`\n✓ Copied the secrets for stage "${stage}" from ${source.name} to ${destination.name}`);
|
|
87
|
+
logger.log(`\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`);
|
|
88
|
+
logger.log(` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`);
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { secretsMigrateCommand };
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=migrate-D3NAT7Ns.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate-D3NAT7Ns.mjs","names":[],"sources":["../src/secrets/migrate.ts"],"sourcesContent":["/**\n * `gkm secrets:migrate` — copy a deployed stage's secrets from the store\n * `secrets.store` names to another one, whole: service passwords, URLs and\n * custom keys alike, so nothing is regenerated and running services keep\n * their credentials.\n *\n * It copies and nothing more. The source is left as it was, and gkm.config.ts\n * is not edited: pointing `secrets.store` at the new store is the switch, and\n * the old copy is deleted by hand once deploys read from the new one.\n */\n\nimport { loadWorkspaceSettings } from '../config.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport {\n\tSECRETS_STORE_PROVIDERS,\n\ttype SecretsStoreConfig,\n\ttype SecretsStoreOptions,\n\ttype SecretsStoreProvider,\n\tsecretsStoreFor,\n\tstoreFromConfig,\n\tUnknownSecretsStoreProvider,\n} from './store.js';\n\nconst logger = console;\n\nexport interface SecretsMigrateOptions {\n\tstage: string;\n\t/** The store to copy to: `'file'`, `'ssm'` or `'secrets-manager'`. */\n\tto: string;\n\t/** The target's AWS region; defaults to the configured store's. */\n\tregion?: string;\n\t/** Overwrite a stage the target already holds. */\n\tforce?: boolean;\n\t/** The AWS profile for the stage's account, for both stores. */\n\tprofile?: string;\n}\n\n/** An AWS store to copy to, with no region given and none configured. */\nexport class MigrateTargetNeedsRegion extends Error {\n\tconstructor(readonly to: string) {\n\t\tsuper(\n\t\t\t`Copying to ${to} needs a region, and secrets.store has none to reuse. ` +\n\t\t\t\t`Pass it: gkm secrets:migrate --to ${to} --region <region> --stage <stage>.`,\n\t\t);\n\t\tthis.name = 'MigrateTargetNeedsRegion';\n\t}\n}\n\n/** The target is the store the stage is already read from. */\nexport class MigrateTargetIsSource extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`Stage \"${stage}\" is already kept in ${to}, so there is nothing to copy. ` +\n\t\t\t\t'Name a different store with --to, or a different region with --region.',\n\t\t);\n\t\tthis.name = 'MigrateTargetIsSource';\n\t}\n}\n\n/** The configured store holds nothing for the stage. */\nexport class NoSecretsToMigrate extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly store: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${store} store holds no secrets for stage \"${stage}\", so there is nothing to copy. ` +\n\t\t\t\t`Check secrets.store in gkm.config.ts still names the store the stage is in, ` +\n\t\t\t\t`or create the stage there with gkm secrets:init --stage ${stage}.`,\n\t\t);\n\t\tthis.name = 'NoSecretsToMigrate';\n\t}\n}\n\n/** The target already holds the stage, and `--force` was not given. */\nexport class MigrateTargetHoldsStage extends Error {\n\tconstructor(\n\t\treadonly stage: string,\n\t\treadonly to: string,\n\t) {\n\t\tsuper(\n\t\t\t`The ${to} store already holds secrets for stage \"${stage}\". ` +\n\t\t\t\t'Pass --force to replace them with the ones being copied.',\n\t\t);\n\t\tthis.name = 'MigrateTargetHoldsStage';\n\t}\n}\n\n/** The store a `--to` name and region describe. */\nfunction targetConfig(\n\tto: string,\n\tregion: string | undefined,\n\tconfigured: SecretsStoreConfig,\n): SecretsStoreConfig {\n\tif (!(SECRETS_STORE_PROVIDERS as readonly string[]).includes(to)) {\n\t\tthrow new UnknownSecretsStoreProvider(to);\n\t}\n\tconst provider = to as SecretsStoreProvider;\n\tif (provider === 'file') return 'file';\n\n\tconst fallback =\n\t\ttypeof configured === 'object' && 'region' in configured\n\t\t\t? configured.region\n\t\t\t: undefined;\n\tconst resolved = region ?? fallback;\n\tif (!resolved) throw new MigrateTargetNeedsRegion(provider);\n\treturn { provider, region: resolved };\n}\n\nexport async function secretsMigrateCommand(\n\toptions: SecretsMigrateOptions,\n): Promise<void> {\n\tconst { stage, to } = options;\n\tconst workspace = await loadWorkspaceSettings();\n\tassertDeployedStage(workspace.stages, stage);\n\n\tconst configured = workspace.secrets.store ?? 'file';\n\tconst target = targetConfig(to, options.region, configured);\n\tconst sameStore =\n\t\ttypeof configured === 'string' || typeof target === 'string'\n\t\t\t? configured === target\n\t\t\t: configured.provider === target.provider &&\n\t\t\t\t'region' in configured &&\n\t\t\t\t'region' in target &&\n\t\t\t\tconfigured.region === target.region;\n\tif (sameStore) throw new MigrateTargetIsSource(stage, to);\n\n\tconst storeOptions: SecretsStoreOptions = options.profile\n\t\t? { profile: options.profile }\n\t\t: {};\n\tconst source = await secretsStoreFor(workspace, stage, storeOptions);\n\tconst destination = await storeFromConfig(workspace, target, storeOptions);\n\n\tconst secrets = await source.read(stage);\n\tif (!secrets) throw new NoSecretsToMigrate(stage, source.name);\n\n\tif (!options.force && (await destination.read(stage))) {\n\t\tthrow new MigrateTargetHoldsStage(stage, destination.name);\n\t}\n\n\tawait destination.write(stage, secrets);\n\n\tconst shape =\n\t\ttypeof target === 'object' && 'region' in target\n\t\t\t? `{ provider: '${target.provider}', region: '${target.region}' }`\n\t\t\t: `'file'`;\n\tlogger.log(\n\t\t`\\n✓ Copied the secrets for stage \"${stage}\" from ${source.name} to ${destination.name}`,\n\t);\n\tlogger.log(\n\t\t`\\n Next: set secrets.store to ${shape} in gkm.config.ts, so commands and deploys read from ${destination.name}.`,\n\t);\n\tlogger.log(\n\t\t` The copy in ${source.name} is left as it was; delete it once deploys read from ${destination.name}.`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAM,SAAS;;AAef,IAAa,2BAAb,cAA8C,MAAM;CAC9B;CAArB,YAAY,IAAqB;EAChC,MACC,cAAc,GAAG,0FACqB,GAAG,oCAC1C;EAJoB,KAAA,KAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wBAAb,cAA2C,MAAM;CAEtC;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,UAAU,MAAM,uBAAuB,GAAG,sGAE3C;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,qBAAb,cAAwC,MAAM;CAEnC;CACA;CAFV,YACC,OACA,OACC;EACD,MACC,OAAO,MAAM,qCAAqC,MAAM,sKAEI,MAAM,EACnE;EAPS,KAAA,QAAA;EACA,KAAA,QAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,0BAAb,cAA6C,MAAM;CAExC;CACA;CAFV,YACC,OACA,IACC;EACD,MACC,OAAO,GAAG,0CAA0C,MAAM,4DAE3D;EANS,KAAA,QAAA;EACA,KAAA,KAAA;EAMT,KAAK,OAAO;CACb;AACD;;AAGA,SAAS,aACR,IACA,QACA,YACqB;CACrB,IAAI,CAAE,wBAA8C,SAAS,EAAE,GAC9D,MAAM,IAAI,4BAA4B,EAAE;CAEzC,MAAM,WAAW;CACjB,IAAI,aAAa,QAAQ,OAAO;CAEhC,MAAM,W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D,YAAY,KAAK,EACtG;AACD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_discover = require("./discover-D1It5r_h.cjs");
|
|
2
|
-
const require_workspace = require("./workspace-
|
|
2
|
+
const require_workspace = require("./workspace-DOm81oUo.cjs");
|
|
3
3
|
const require_config = require("./config.cjs");
|
|
4
|
-
const require_state = require("./state-
|
|
4
|
+
const require_state = require("./state-C2qi0iQw.cjs");
|
|
5
5
|
require("./provider-B3Sv_a74.cjs");
|
|
6
6
|
const require_databases = require("./databases-C2p5LGAp.cjs");
|
|
7
7
|
const require_index = require("./index.cjs");
|
|
@@ -268,4 +268,4 @@ exports.prepareDevDatabases = prepareDevDatabases;
|
|
|
268
268
|
exports.reportPendingMigrations = reportPendingMigrations;
|
|
269
269
|
exports.seedCommand = seedCommand;
|
|
270
270
|
|
|
271
|
-
//# sourceMappingURL=migrate-
|
|
271
|
+
//# sourceMappingURL=migrate-D5_-ylI1.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-B0FCZNkp.cjs","names":["TEST_STAGE","loadWorkspaceConfig","discover","constructGlobs","reconcileWorkspace","migrateDatabases","migrateAndSeed","pendingMigrations","migrationTargets","canonicalId","NoSuchMigrationTarget","stamp","slug","loadSecretsForApp","secretsStoreFor","EnvironmentParser","serviceContext","join","mkdir","writeFile"],"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,MAA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AEA,MAAM,OAAO;;;;;;;;;;AAWb,eAAe,MACd,MACA,QACA,MACA,SACkB;CAClB,MAAM,UAAA,GAASK,UAAAA,KAAAA,CAAK,MAAM,OAAO,UAAU;CAC3C,OAAA,GAAMC,iBAAAA,MAAAA,CAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;CACvC,OAAA,GAAMC,iBAAAA,UAAAA,EAAAA,GAAUF,UAAAA,KAAAA,CAAK,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-D5_-ylI1.cjs","names":["TEST_STAGE","loadWorkspaceConfig","discover","constructGlobs","reconcileWorkspace","migrateDatabases","migrateAndSeed","pendingMigrations","migrationTargets","canonicalId","NoSuchMigrationTarget","stamp","slug","loadSecretsForApp","secretsStoreFor","EnvironmentParser","serviceContext","join","mkdir","writeFile"],"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,QAAQA,kBAAAA,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,UAA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,EAAE,WAAW,KAAK,CAAC;CACvC,OAAA,GAAMC,iBAAAA,UAAAA,EAAAA,GAAUF,UAAAA,KAAAA,CAAK,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,7 +1,7 @@
|
|
|
1
1
|
import { r as discover } from "./discover-BPelzeGW.mjs";
|
|
2
|
-
import { O as TEST_STAGE } from "./workspace-
|
|
2
|
+
import { O as TEST_STAGE } from "./workspace-QUTqYmVy.mjs";
|
|
3
3
|
import { loadWorkspaceConfig } from "./config.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { Gt as secretsStoreFor, Ht as loadSecretsForApp, Y as constructGlobs, Z as reconcileWorkspace } from "./state-CUecOCNJ.mjs";
|
|
5
5
|
import "./provider-D7rQzzzf.mjs";
|
|
6
6
|
import { a as NoSuchMigrationTarget, d as pendingMigrations, l as migrateAndSeed, u as migrateDatabases } from "./databases-hUHTuwhx.mjs";
|
|
7
7
|
import { n as slug, r as stamp } from "./index.mjs";
|
|
@@ -263,4 +263,4 @@ function ids(targets) {
|
|
|
263
263
|
//#endregion
|
|
264
264
|
export { migrateAndSeed, migrateCommand, migrationCommand, prepareDevDatabases, reportPendingMigrations, seedCommand };
|
|
265
265
|
|
|
266
|
-
//# sourceMappingURL=migrate-
|
|
266
|
+
//# sourceMappingURL=migrate-DrO2p9Rl.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-CTtJhGV9.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 Mig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ClB,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-DrO2p9Rl.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,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AAW,KAAK,GAC5C,KACD;CACA,MAAM,UAAU,MAAM,KAAK,iBAAiB;EAC3C,WAAW,IAAI,kBAAkB;GAAE,GAAG;GAAS,GAAG,MAAM;EAAI,CAAC;EAC7D,SAAS;CACV,CAAC;CAED,IAAI,CAAC,SAAS;EACb,OAAO,IAAI,KAAK,OAAO,WAAW,IAAI,KAAK,GAAG,eAAe;EAC7D;CACD;CAEA,MAAM,OAAO,MAAM,MAClB,MAAM,UAAU,MAChB,QACA,GAAG,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,QAAQ,QAAQ,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"}
|
package/dist/openapi.cjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const require_derive = require("./derive-DAbo49sm.cjs");
|
|
4
|
+
const require_workspace = require("./workspace-DOm81oUo.cjs");
|
|
3
5
|
const require_config = require("./config.cjs");
|
|
4
6
|
const require_EndpointGenerator = require("./EndpointGenerator-CP6sBvQV.cjs");
|
|
5
7
|
const require_OpenApiTsGenerator = require("./OpenApiTsGenerator-CKBCckKz.cjs");
|
|
@@ -125,14 +127,14 @@ async function openapiCommand(options = {}) {
|
|
|
125
127
|
const entry = backendApps.find(([name]) => name === options.app);
|
|
126
128
|
if (!entry) throw new Error(`App "${options.app}" not found or has OpenAPI disabled`);
|
|
127
129
|
const [appName, app] = entry;
|
|
128
|
-
const result = await generateOpenApiForApp(
|
|
130
|
+
const result = await generateOpenApiForApp(workspace, appName, app);
|
|
129
131
|
if (result) logger.log(`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`);
|
|
130
132
|
return;
|
|
131
133
|
}
|
|
132
134
|
for (const [appName, app] of backendApps) {
|
|
133
135
|
const appPath = (0, node_path.join)(workspaceRoot, app.path);
|
|
134
136
|
if ((0, node_path.resolve)(appPath) === (0, node_path.resolve)(workspaceRoot)) {
|
|
135
|
-
const result = await generateOpenApiForApp(
|
|
137
|
+
const result = await generateOpenApiForApp(workspace, appName, app, false);
|
|
136
138
|
if (result) logger.log(`Found ${result.endpointCount} endpoints`);
|
|
137
139
|
continue;
|
|
138
140
|
}
|
|
@@ -147,14 +149,22 @@ async function openapiCommand(options = {}) {
|
|
|
147
149
|
* Generate OpenAPI for a single named app within a workspace.
|
|
148
150
|
* Runs in-process. The caller is responsible for ensuring `process.cwd()`
|
|
149
151
|
* is the app's directory so tsx loads the app's tsconfig path aliases.
|
|
152
|
+
*
|
|
153
|
+
* The endpoints are found the way the app's build finds them — through the
|
|
154
|
+
* workspace's constructs globs — never by importing every `.ts` under the app,
|
|
155
|
+
* which loaded its tests and gkm's own generated files with them.
|
|
150
156
|
*/
|
|
151
|
-
async function generateOpenApiForApp(
|
|
157
|
+
async function generateOpenApiForApp(workspace, appName, app, silent = true) {
|
|
152
158
|
if (app.type !== "backend") return null;
|
|
153
|
-
|
|
154
|
-
|
|
159
|
+
return generateOpenApi((await new require_EndpointGenerator.EndpointGenerator().load(require_workspace.appConstructGlobs(workspace, appName))).map(({ construct }) => construct).filter((endpoint) => {
|
|
160
|
+
const owner = endpoint.owner ?? endpoint.surface?.id;
|
|
161
|
+
if (!owner) return false;
|
|
162
|
+
const key = require_derive.appKey(owner);
|
|
163
|
+
return key === appName || !workspace.apps[key];
|
|
164
|
+
}), {
|
|
155
165
|
openapi: app.openapi ?? { enabled: true },
|
|
156
166
|
silent,
|
|
157
|
-
root:
|
|
167
|
+
root: workspace.root
|
|
158
168
|
});
|
|
159
169
|
}
|
|
160
170
|
/**
|
package/dist/openapi.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.cjs","names":["kebabCase","EndpointGenerator","OpenApiTsGenerator","join","mkdir","dirname","writeFile","relativePath","loadWorkspaceConfig","resolve","fileURLToPath","spawn"],"sources":["../src/openapi.ts"],"sourcesContent":["#!/usr/bin/env -S npx tsx\n\nimport { spawn } from 'node:child_process';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative as relativePath, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { kebabCase } from '@geekmidas/manifest';\nimport { loadWorkspaceConfig } from './config.js';\nimport { EndpointGenerator } from './generators/EndpointGenerator.js';\nimport { OpenApiTsGenerator } from './generators/OpenApiTsGenerator.js';\nimport type { GkmConfig, OpenApiConfig, Routes } from './types.js';\nimport { normalizeRoutes } from './workspace/client-generator.js';\nimport type { NormalizedAppConfig } from './workspace/types.js';\n\ninterface OpenAPIOptions {\n\tcwd?: string;\n\t/**\n\t * Workspace mode: generate for a single named backend app. When set,\n\t * generation runs in-process against the current CWD. When unset,\n\t * workspace mode spawns one subprocess per backend app so each gets a\n\t * fresh tsx that loads the app's own tsconfig (path aliases included).\n\t */\n\tapp?: string;\n}\n\n/**\n * Where a surface's generated client lands, under the workspace root.\n *\n * Named from the surface, so `new RestApi('Webhooks')` writes\n * `.gkm/client/webhooks.ts` — the same kebab form that gives it its container\n * name and its `WEBHOOKS_URL` — and a site imports it as\n * `@<name>/client/webhooks`, through the alias its tsconfig maps.\n */\nexport function openApiPathFor(surfaceId: string): string {\n\treturn `./.gkm/client/${kebabCase(surfaceId)}.ts`;\n}\n\n/**\n * Resolve OpenAPI config from GkmConfig\n */\nexport function resolveOpenApiConfig(config: {\n\topenapi?: boolean | OpenApiConfig;\n}): OpenApiConfig & { enabled: boolean } {\n\tif (config.openapi === false) {\n\t\treturn { enabled: false };\n\t}\n\n\tif (config.openapi === true || config.openapi === undefined) {\n\t\t// Enable by default when not explicitly set (undefined) or explicitly true\n\t\treturn {\n\t\t\tenabled: true,\n\t\t\ttitle: 'API Documentation',\n\t\t\tversion: '1.0.0',\n\t\t\tdescription: 'Auto-generated API documentation from endpoints',\n\t\t};\n\t}\n\n\treturn {\n\t\tenabled: config.openapi.enabled !== false,\n\t\ttitle: config.openapi.title || 'API Documentation',\n\t\tversion: config.openapi.version || '1.0.0',\n\t\tdescription:\n\t\t\tconfig.openapi.description ||\n\t\t\t'Auto-generated API documentation from endpoints',\n\t};\n}\n\n/** What a generation run wrote. */\nexport interface OpenApiResult {\n\t/** The first spec written — kept so existing callers still compile. */\n\toutputPath: string;\n\t/** Every spec written, one per surface. */\n\toutputPaths: string[];\n\t/** Endpoints across all of them. */\n\tendpointCount: number;\n}\n\n/**\n * Load endpoints from a glob, then generate.\n *\n * For the callers that have no endpoints in hand — `gkm openapi`, and `gkm dev`\n * regenerating on reload. The glob is the app's derived one — the conventional\n * directories under it — not a `routes` field anybody wrote.\n */\nexport async function generateOpenApiFrom(\n\troutes: Routes,\n\toptions: {\n\t\topenapi?: boolean | OpenApiConfig;\n\t\tsilent?: boolean;\n\t\tbustCache?: boolean;\n\t\troot?: string;\n\t} = {},\n): Promise<OpenApiResult | null> {\n\tconst loaded = await new EndpointGenerator().load(\n\t\troutes,\n\t\tundefined,\n\t\toptions.bustCache,\n\t);\n\n\treturn generateOpenApi(\n\t\tloaded.map(({ construct }) => construct),\n\t\toptions,\n\t);\n}\n\n/**\n * Generate an OpenAPI spec for each surface these endpoints name.\n *\n * Takes the endpoints, not a glob to find them with. The build has already\n * loaded every one of them to generate handlers, so globbing again was a second\n * discovery pass over the same files — and the reason this function needed a\n * `routes` to be told where to look, which is how a retired config field stayed\n * load-bearing.\n *\n * @returns What was written, or null if disabled or there were none\n */\nexport async function generateOpenApi(\n\tendpoints: readonly Endpoint<any, any, any, any, any>[],\n\toptions: {\n\t\topenapi?: boolean | OpenApiConfig;\n\t\tsilent?: boolean;\n\t\t/**\n\t\t * The workspace root, whose `.gkm/client/` holds every surface's client.\n\t\t * The client is the application's, like its manifest — a site reaches it\n\t\t * as `@<name>/client/<surface>` — so it is written there whichever\n\t\t * directory the build happened to run in.\n\t\t */\n\t\troot?: string;\n\t} = {},\n): Promise<OpenApiResult | null> {\n\tconst root = options.root ?? process.cwd();\n\tconst logger = options.silent ? { log: () => {} } : console;\n\tconst openApiConfig = resolveOpenApiConfig({ openapi: options.openapi });\n\n\tif (!openApiConfig.enabled) {\n\t\treturn null;\n\t}\n\n\tif (endpoints.length === 0) {\n\t\tlogger.log('No valid endpoints found for OpenAPI generation');\n\t\treturn null;\n\t}\n\n\t// One spec per surface, not one per glob.\n\t//\n\t// The glob is a directory, and a directory is not a surface: two `RestApi`s\n\t// whose endpoints live side by side produced a single spec describing both,\n\t// under a filename that named neither. Every endpoint carries the surface\n\t// that serves it, so that is what the spec is cut along — `Api` becomes\n\t// `api.ts`, `Webhooks` becomes `webhooks.ts`, by the same kebab rule that\n\t// gives the surface its container name and its environment keys.\n\tconst bySurface = new Map<string, Endpoint<any, any, any, any, any>[]>();\n\tfor (const endpoint of endpoints) {\n\t\tconst owner = endpoint.owner ?? endpoint.surface?.id;\n\t\tif (!owner) continue;\n\t\tconst existing = bySurface.get(owner);\n\t\tif (existing) existing.push(endpoint);\n\t\telse bySurface.set(owner, [endpoint]);\n\t}\n\n\tif (bySurface.size === 0) {\n\t\tlogger.log('No endpoints named a surface, so no OpenAPI was generated');\n\t\treturn null;\n\t}\n\n\tconst tsGenerator = new OpenApiTsGenerator();\n\tconst written: string[] = [];\n\n\tfor (const [surfaceId, surfaceEndpoints] of bySurface) {\n\t\tconst relative = openApiPathFor(surfaceId);\n\t\tconst outputPath = join(root, relative);\n\n\t\tawait mkdir(dirname(outputPath), { recursive: true });\n\n\t\tconst tsContent = await tsGenerator.generate(surfaceEndpoints, {\n\t\t\t// The surface's own name, so a spec says which API it describes\n\t\t\t// rather than repeating one title across all of them.\n\t\t\ttitle: openApiConfig.title ?? surfaceId,\n\t\t\tversion: openApiConfig.version!,\n\t\t\tdescription: openApiConfig.description!,\n\t\t});\n\n\t\tawait writeFile(outputPath, tsContent);\n\t\twritten.push(relative);\n\t\tlogger.log(\n\t\t\t`📄 OpenAPI client generated: ${relativePath(process.cwd(), outputPath)} (${surfaceEndpoints.length} endpoints)`,\n\t\t);\n\t}\n\n\treturn {\n\t\t// The first, for a caller that wants one path. `outputPaths` has them all.\n\t\toutputPath: join(root, written[0]!),\n\t\toutputPaths: written.map((r) => join(root, r)),\n\t\tendpointCount: endpoints.length,\n\t};\n}\n\nexport async function openapiCommand(\n\toptions: OpenAPIOptions = {},\n): Promise<void> {\n\tconst logger = console;\n\n\ttry {\n\t\tconst loadedConfig = await loadWorkspaceConfig(options.cwd);\n\n\t\tif (loadedConfig.type === 'single') {\n\t\t\t// Single-app config - use existing behavior\n\t\t\tconst config = loadedConfig.raw as GkmConfig;\n\n\t\t\t// Enable openapi if not configured\n\t\t\tif (!config.openapi) {\n\t\t\t\tconfig.openapi = { enabled: true };\n\t\t\t}\n\n\t\t\tconst result = await generateOpenApiFrom(config.constructs, {\n\t\t\t\topenapi: config.openapi,\n\t\t\t\troot: loadedConfig.workspace.root,\n\t\t\t});\n\n\t\t\tif (result) {\n\t\t\t\tlogger.log(`Found ${result.endpointCount} endpoints`);\n\t\t\t}\n\t\t} else {\n\t\t\t// Workspace config - generate for each backend app\n\t\t\tconst { workspace } = loadedConfig;\n\t\t\t// Always derive the workspace root from the loaded config rather than\n\t\t\t// CWD. Subprocesses run with CWD set to an app directory, and falling\n\t\t\t// back to CWD there causes `join(workspaceRoot, app.path)` to point at\n\t\t\t// a non-existent nested path (e.g. `apps/api/apps/api`).\n\t\t\tconst workspaceRoot = workspace.root;\n\n\t\t\t// Backend apps with openapi enabled — which is all of them that have\n\t\t\t// routes, unless one says otherwise.\n\t\t\t//\n\t\t\t// This used to require `openapi: true` written out, while the app's\n\t\t\t// own build generated a spec regardless. Two paths disagreeing about\n\t\t\t// the same flag: the app emitted `.gkm/openapi.ts` and this pass,\n\t\t\t// finding nothing \"enabled\", skipped copying it to the frontends that\n\t\t\t// consume it. A surface whose routes are declared rather than\n\t\t\t// discovered has no spec to generate, so it is not a candidate.\n\t\t\tconst backendApps = Object.entries(workspace.apps).filter(\n\t\t\t\t([_, app]) =>\n\t\t\t\t\tapp.type === 'backend' &&\n\t\t\t\t\tapp.openapi !== false &&\n\t\t\t\t\t(typeof app.openapi !== 'object' || app.openapi.enabled !== false),\n\t\t\t);\n\n\t\t\tif (backendApps.length === 0) {\n\t\t\t\tlogger.log('No backend apps with OpenAPI enabled found');\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Single-app mode: generate in-process. The caller is expected to\n\t\t\t// have CWD set to the app's directory (e.g., when invoked as a\n\t\t\t// subprocess), so tsx picks up the app's tsconfig path aliases.\n\t\t\tif (options.app) {\n\t\t\t\tconst entry = backendApps.find(([name]) => name === options.app);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`App \"${options.app}\" not found or has OpenAPI disabled`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst [appName, app] = entry;\n\t\t\t\tconst result = await generateOpenApiForApp(workspaceRoot, appName, app);\n\t\t\t\tif (result) {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Multi-app mode: spawn a subprocess per backend app. Each\n\t\t\t// subprocess starts with CWD at the app's directory so that\n\t\t\t// tsx's tsconfig discovery picks up the app's `paths` aliases\n\t\t\t// (e.g., `~/*`) instead of the workspace root's tsconfig.\n\t\t\tfor (const [appName, app] of backendApps) {\n\t\t\t\t// No `app.routes` check any more: the per-kind globs are gone, and\n\t\t\t\t// an app's code is found by one glob rather than by a field naming\n\t\t\t\t// endpoints. Guarding on `routes` here meant every app was skipped\n\t\t\t\t// the moment that field stopped existing — silently, because a loop\n\t\t\t\t// that runs zero times looks exactly like one with nothing to do.\n\t\t\t\tconst appPath = join(workspaceRoot, app.path);\n\n\t\t\t\t// A subprocess exists to put CWD inside the app, so tsx picks up\n\t\t\t\t// that app's tsconfig aliases instead of the workspace root's. When\n\t\t\t\t// the app *is* the root there is nothing to change: spawning would\n\t\t\t\t// re-enter the same directory, having paid for a process and a\n\t\t\t\t// module graph, and needing `tsx` resolvable from it.\n\t\t\t\tif (resolve(appPath) === resolve(workspaceRoot)) {\n\t\t\t\t\t// Not silent: silence is for a subprocess whose output the\n\t\t\t\t\t// parent relays, and there is no parent here to relay it. The\n\t\t\t\t\t// per-surface lines come from the generator; the count is this\n\t\t\t\t\t// command's own summary, as in the single-app path.\n\t\t\t\t\tconst result = await generateOpenApiForApp(\n\t\t\t\t\t\tworkspaceRoot,\n\t\t\t\t\t\tappName,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t);\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tlogger.log(`Found ${result.endpointCount} endpoints`);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait runOpenApiInSubprocess(appPath, appName);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tthrow new Error(`OpenAPI generation failed: ${(error as Error).message}`);\n\t}\n}\n\n/**\n * Generate OpenAPI for a single named app within a workspace.\n * Runs in-process. The caller is responsible for ensuring `process.cwd()`\n * is the app's directory so tsx loads the app's tsconfig path aliases.\n */\nasync function generateOpenApiForApp(\n\tworkspaceRoot: string,\n\t_appName: string,\n\tapp: NormalizedAppConfig,\n\t/**\n\t * Quiet by default, because the usual caller is a subprocess whose output\n\t * the parent relays. Generating in-process there is no parent to relay to,\n\t * and silence would swallow the only report of what happened.\n\t */\n\tsilent = true,\n): Promise<{ outputPath: string; endpointCount: number } | null> {\n\t// A backend app, and everything under it.\n\t//\n\t// It used to gate on `app.routes` and glob that; derive no longer sets it,\n\t// because an app has one glob and which kind a module exports is decided by\n\t// the value. A surface is an app, so an app's own directory contains exactly\n\t// its own surface's endpoints — and the split inside is by surface anyway.\n\tif (app.type !== 'backend') {\n\t\treturn null;\n\t}\n\n\tconst appPath = join(workspaceRoot, app.path);\n\tconst globs = [join(appPath, '**/*.ts')];\n\n\treturn generateOpenApiFrom(globs, {\n\t\t// Absent means enabled, which is what the caller's filter already decided\n\t\t// when it kept this app: it skips one that says `openapi: false` and keeps\n\t\t// every other. Passing `undefined` through let `resolveOpenApiConfig`\n\t\t// default it to *disabled*, so an app selected for generation generated\n\t\t// nothing and said nothing — two places disagreeing about one flag, which\n\t\t// is the failure the filter above was written to describe.\n\t\topenapi: app.openapi ?? { enabled: true },\n\t\tsilent,\n\t\troot: workspaceRoot,\n\t});\n}\n\n/**\n * Resolve the gkm bin path. Tests can override via `GKM_BIN_PATH` env var\n * to avoid depending on the built dist.\n */\nfunction resolveGkmBinPath(): string {\n\tif (process.env.GKM_BIN_PATH) {\n\t\treturn process.env.GKM_BIN_PATH;\n\t}\n\treturn fileURLToPath(new URL('../bin/gkm.mjs', import.meta.url));\n}\n\n/**\n * Spawn a subprocess that runs `gkm openapi --app <name>` with `cwd` set to\n * the app's directory. Inherits `NODE_OPTIONS` (which already contains\n * `--import tsx`), so the child gets a fresh tsx instance whose tsconfig\n * discovery picks up the app's tsconfig path aliases.\n */\nasync function runOpenApiInSubprocess(\n\tappCwd: string,\n\tappName: string,\n): Promise<void> {\n\tconst binPath = resolveGkmBinPath();\n\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[binPath, 'openapi', '--app', appName],\n\t\t\t{\n\t\t\t\tcwd: appCwd,\n\t\t\t\tstdio: 'inherit',\n\t\t\t\tenv: process.env,\n\t\t\t},\n\t\t);\n\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t`OpenAPI generation for app \"${appName}\" exited with code ${code}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,eAAe,WAA2B;CACzD,OAAO,kBAAA,GAAiBA,oBAAAA,UAAAA,CAAU,SAAS,EAAE;AAC9C;;;;AAKA,SAAgB,qBAAqB,QAEI;CACxC,IAAI,OAAO,YAAY,OACtB,OAAO,EAAE,SAAS,MAAM;CAGzB,IAAI,OAAO,YAAY,QAAQ,OAAO,YAAY,KAAA,GAEjD,OAAO;EACN,SAAS;EACT,OAAO;EACP,SAAS;EACT,aAAa;CACd;CAGD,OAAO;EACN,SAAS,OAAO,QAAQ,YAAY;EACpC,OAAO,OAAO,QAAQ,SAAS;EAC/B,SAAS,OAAO,QAAQ,WAAW;EACnC,aACC,OAAO,QAAQ,eACf;CACF;AACD;;;;;;;;AAmBA,eAAsB,oBACrB,QACA,UAKI,CAAC,GAC2B;CAOhC,OAAO,iBACN,MAPoB,IAAIC,0BAAAA,kBAAkB,CAAC,CAAC,KAC5C,QACA,KAAA,GACA,QAAQ,SACT,EAAA,CAGQ,KAAK,EAAE,gBAAgB,SAAS,GACvC,OACD;AACD;;;;;;;;;;;;AAaA,eAAsB,gBACrB,WACA,UAUI,CAAC,GAC2B;CAChC,MAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI;CACzC,MAAM,SAAS,QAAQ,SAAS,EAAE,WAAW,CAAC,EAAE,IAAI;CACp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,"file":"openapi.cjs","names":["kebabCase","EndpointGenerator","OpenApiTsGenerator","join","mkdir","dirname","writeFile","relativePath","loadWorkspaceConfig","resolve","appConstructGlobs","appKey","fileURLToPath","spawn"],"sources":["../src/openapi.ts"],"sourcesContent":["#!/usr/bin/env -S npx tsx\n\nimport { spawn } from 'node:child_process';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative as relativePath, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { kebabCase } from '@geekmidas/manifest';\nimport { loadWorkspaceConfig } from './config.js';\nimport { EndpointGenerator } from './generators/EndpointGenerator.js';\nimport { OpenApiTsGenerator } from './generators/OpenApiTsGenerator.js';\nimport type { GkmConfig, OpenApiConfig, Routes } from './types.js';\nimport { appKey } from './workspace/derive.js';\nimport { appConstructGlobs } from './workspace/index.js';\nimport type {\n\tNormalizedAppConfig,\n\tNormalizedWorkspace,\n} from './workspace/types.js';\n\ninterface OpenAPIOptions {\n\tcwd?: string;\n\t/**\n\t * Workspace mode: generate for a single named backend app. When set,\n\t * generation runs in-process against the current CWD. When unset,\n\t * workspace mode spawns one subprocess per backend app so each gets a\n\t * fresh tsx that loads the app's own tsconfig (path aliases included).\n\t */\n\tapp?: string;\n}\n\n/**\n * Where a surface's generated client lands, under the workspace root.\n *\n * Named from the surface, so `new RestApi('Webhooks')` writes\n * `.gkm/client/webhooks.ts` — the same kebab form that gives it its container\n * name and its `WEBHOOKS_URL` — and a site imports it as\n * `@<name>/client/webhooks`, through the alias its tsconfig maps.\n */\nexport function openApiPathFor(surfaceId: string): string {\n\treturn `./.gkm/client/${kebabCase(surfaceId)}.ts`;\n}\n\n/**\n * Resolve OpenAPI config from GkmConfig\n */\nexport function resolveOpenApiConfig(config: {\n\topenapi?: boolean | OpenApiConfig;\n}): OpenApiConfig & { enabled: boolean } {\n\tif (config.openapi === false) {\n\t\treturn { enabled: false };\n\t}\n\n\tif (config.openapi === true || config.openapi === undefined) {\n\t\t// Enable by default when not explicitly set (undefined) or explicitly true\n\t\treturn {\n\t\t\tenabled: true,\n\t\t\ttitle: 'API Documentation',\n\t\t\tversion: '1.0.0',\n\t\t\tdescription: 'Auto-generated API documentation from endpoints',\n\t\t};\n\t}\n\n\treturn {\n\t\tenabled: config.openapi.enabled !== false,\n\t\ttitle: config.openapi.title || 'API Documentation',\n\t\tversion: config.openapi.version || '1.0.0',\n\t\tdescription:\n\t\t\tconfig.openapi.description ||\n\t\t\t'Auto-generated API documentation from endpoints',\n\t};\n}\n\n/** What a generation run wrote. */\nexport interface OpenApiResult {\n\t/** The first spec written — kept so existing callers still compile. */\n\toutputPath: string;\n\t/** Every spec written, one per surface. */\n\toutputPaths: string[];\n\t/** Endpoints across all of them. */\n\tendpointCount: number;\n}\n\n/**\n * Load endpoints from a glob, then generate.\n *\n * For the callers that have no endpoints in hand — `gkm openapi`, and `gkm dev`\n * regenerating on reload. The glob is the app's derived one — the conventional\n * directories under it — not a `routes` field anybody wrote.\n */\nexport async function generateOpenApiFrom(\n\troutes: Routes,\n\toptions: {\n\t\topenapi?: boolean | OpenApiConfig;\n\t\tsilent?: boolean;\n\t\tbustCache?: boolean;\n\t\troot?: string;\n\t} = {},\n): Promise<OpenApiResult | null> {\n\tconst loaded = await new EndpointGenerator().load(\n\t\troutes,\n\t\tundefined,\n\t\toptions.bustCache,\n\t);\n\n\treturn generateOpenApi(\n\t\tloaded.map(({ construct }) => construct),\n\t\toptions,\n\t);\n}\n\n/**\n * Generate an OpenAPI spec for each surface these endpoints name.\n *\n * Takes the endpoints, not a glob to find them with. The build has already\n * loaded every one of them to generate handlers, so globbing again was a second\n * discovery pass over the same files — and the reason this function needed a\n * `routes` to be told where to look, which is how a retired config field stayed\n * load-bearing.\n *\n * @returns What was written, or null if disabled or there were none\n */\nexport async function generateOpenApi(\n\tendpoints: readonly Endpoint<any, any, any, any, any>[],\n\toptions: {\n\t\topenapi?: boolean | OpenApiConfig;\n\t\tsilent?: boolean;\n\t\t/**\n\t\t * The workspace root, whose `.gkm/client/` holds every surface's client.\n\t\t * The client is the application's, like its manifest — a site reaches it\n\t\t * as `@<name>/client/<surface>` — so it is written there whichever\n\t\t * directory the build happened to run in.\n\t\t */\n\t\troot?: string;\n\t} = {},\n): Promise<OpenApiResult | null> {\n\tconst root = options.root ?? process.cwd();\n\tconst logger = options.silent ? { log: () => {} } : console;\n\tconst openApiConfig = resolveOpenApiConfig({ openapi: options.openapi });\n\n\tif (!openApiConfig.enabled) {\n\t\treturn null;\n\t}\n\n\tif (endpoints.length === 0) {\n\t\tlogger.log('No valid endpoints found for OpenAPI generation');\n\t\treturn null;\n\t}\n\n\t// One spec per surface, not one per glob.\n\t//\n\t// The glob is a directory, and a directory is not a surface: two `RestApi`s\n\t// whose endpoints live side by side produced a single spec describing both,\n\t// under a filename that named neither. Every endpoint carries the surface\n\t// that serves it, so that is what the spec is cut along — `Api` becomes\n\t// `api.ts`, `Webhooks` becomes `webhooks.ts`, by the same kebab rule that\n\t// gives the surface its container name and its environment keys.\n\tconst bySurface = new Map<string, Endpoint<any, any, any, any, any>[]>();\n\tfor (const endpoint of endpoints) {\n\t\tconst owner = endpoint.owner ?? endpoint.surface?.id;\n\t\tif (!owner) continue;\n\t\tconst existing = bySurface.get(owner);\n\t\tif (existing) existing.push(endpoint);\n\t\telse bySurface.set(owner, [endpoint]);\n\t}\n\n\tif (bySurface.size === 0) {\n\t\tlogger.log('No endpoints named a surface, so no OpenAPI was generated');\n\t\treturn null;\n\t}\n\n\tconst tsGenerator = new OpenApiTsGenerator();\n\tconst written: string[] = [];\n\n\tfor (const [surfaceId, surfaceEndpoints] of bySurface) {\n\t\tconst relative = openApiPathFor(surfaceId);\n\t\tconst outputPath = join(root, relative);\n\n\t\tawait mkdir(dirname(outputPath), { recursive: true });\n\n\t\tconst tsContent = await tsGenerator.generate(surfaceEndpoints, {\n\t\t\t// The surface's own name, so a spec says which API it describes\n\t\t\t// rather than repeating one title across all of them.\n\t\t\ttitle: openApiConfig.title ?? surfaceId,\n\t\t\tversion: openApiConfig.version!,\n\t\t\tdescription: openApiConfig.description!,\n\t\t});\n\n\t\tawait writeFile(outputPath, tsContent);\n\t\twritten.push(relative);\n\t\tlogger.log(\n\t\t\t`📄 OpenAPI client generated: ${relativePath(process.cwd(), outputPath)} (${surfaceEndpoints.length} endpoints)`,\n\t\t);\n\t}\n\n\treturn {\n\t\t// The first, for a caller that wants one path. `outputPaths` has them all.\n\t\toutputPath: join(root, written[0]!),\n\t\toutputPaths: written.map((r) => join(root, r)),\n\t\tendpointCount: endpoints.length,\n\t};\n}\n\nexport async function openapiCommand(\n\toptions: OpenAPIOptions = {},\n): Promise<void> {\n\tconst logger = console;\n\n\ttry {\n\t\tconst loadedConfig = await loadWorkspaceConfig(options.cwd);\n\n\t\tif (loadedConfig.type === 'single') {\n\t\t\t// Single-app config - use existing behavior\n\t\t\tconst config = loadedConfig.raw as GkmConfig;\n\n\t\t\t// Enable openapi if not configured\n\t\t\tif (!config.openapi) {\n\t\t\t\tconfig.openapi = { enabled: true };\n\t\t\t}\n\n\t\t\tconst result = await generateOpenApiFrom(config.constructs, {\n\t\t\t\topenapi: config.openapi,\n\t\t\t\troot: loadedConfig.workspace.root,\n\t\t\t});\n\n\t\t\tif (result) {\n\t\t\t\tlogger.log(`Found ${result.endpointCount} endpoints`);\n\t\t\t}\n\t\t} else {\n\t\t\t// Workspace config - generate for each backend app\n\t\t\tconst { workspace } = loadedConfig;\n\t\t\t// Always derive the workspace root from the loaded config rather than\n\t\t\t// CWD. Subprocesses run with CWD set to an app directory, and falling\n\t\t\t// back to CWD there causes `join(workspaceRoot, app.path)` to point at\n\t\t\t// a non-existent nested path (e.g. `apps/api/apps/api`).\n\t\t\tconst workspaceRoot = workspace.root;\n\n\t\t\t// Backend apps with openapi enabled — which is all of them that have\n\t\t\t// routes, unless one says otherwise.\n\t\t\t//\n\t\t\t// This used to require `openapi: true` written out, while the app's\n\t\t\t// own build generated a spec regardless. Two paths disagreeing about\n\t\t\t// the same flag: the app emitted `.gkm/openapi.ts` and this pass,\n\t\t\t// finding nothing \"enabled\", skipped copying it to the frontends that\n\t\t\t// consume it. A surface whose routes are declared rather than\n\t\t\t// discovered has no spec to generate, so it is not a candidate.\n\t\t\tconst backendApps = Object.entries(workspace.apps).filter(\n\t\t\t\t([_, app]) =>\n\t\t\t\t\tapp.type === 'backend' &&\n\t\t\t\t\tapp.openapi !== false &&\n\t\t\t\t\t(typeof app.openapi !== 'object' || app.openapi.enabled !== false),\n\t\t\t);\n\n\t\t\tif (backendApps.length === 0) {\n\t\t\t\tlogger.log('No backend apps with OpenAPI enabled found');\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Single-app mode: generate in-process. The caller is expected to\n\t\t\t// have CWD set to the app's directory (e.g., when invoked as a\n\t\t\t// subprocess), so tsx picks up the app's tsconfig path aliases.\n\t\t\tif (options.app) {\n\t\t\t\tconst entry = backendApps.find(([name]) => name === options.app);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`App \"${options.app}\" not found or has OpenAPI disabled`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst [appName, app] = entry;\n\t\t\t\tconst result = await generateOpenApiForApp(workspace, appName, app);\n\t\t\t\tif (result) {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`📄 [${appName}] Generated OpenAPI (${result.endpointCount} endpoints)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Multi-app mode: spawn a subprocess per backend app. Each\n\t\t\t// subprocess starts with CWD at the app's directory so that\n\t\t\t// tsx's tsconfig discovery picks up the app's `paths` aliases\n\t\t\t// (e.g., `~/*`) instead of the workspace root's tsconfig.\n\t\t\tfor (const [appName, app] of backendApps) {\n\t\t\t\t// No `app.routes` check any more: the per-kind globs are gone, and\n\t\t\t\t// an app's code is found by one glob rather than by a field naming\n\t\t\t\t// endpoints. Guarding on `routes` here meant every app was skipped\n\t\t\t\t// the moment that field stopped existing — silently, because a loop\n\t\t\t\t// that runs zero times looks exactly like one with nothing to do.\n\t\t\t\tconst appPath = join(workspaceRoot, app.path);\n\n\t\t\t\t// A subprocess exists to put CWD inside the app, so tsx picks up\n\t\t\t\t// that app's tsconfig aliases instead of the workspace root's. When\n\t\t\t\t// the app *is* the root there is nothing to change: spawning would\n\t\t\t\t// re-enter the same directory, having paid for a process and a\n\t\t\t\t// module graph, and needing `tsx` resolvable from it.\n\t\t\t\tif (resolve(appPath) === resolve(workspaceRoot)) {\n\t\t\t\t\t// Not silent: silence is for a subprocess whose output the\n\t\t\t\t\t// parent relays, and there is no parent here to relay it. The\n\t\t\t\t\t// per-surface lines come from the generator; the count is this\n\t\t\t\t\t// command's own summary, as in the single-app path.\n\t\t\t\t\tconst result = await generateOpenApiForApp(\n\t\t\t\t\t\tworkspace,\n\t\t\t\t\t\tappName,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t);\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tlogger.log(`Found ${result.endpointCount} endpoints`);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait runOpenApiInSubprocess(appPath, appName);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tthrow new Error(`OpenAPI generation failed: ${(error as Error).message}`);\n\t}\n}\n\n/**\n * Generate OpenAPI for a single named app within a workspace.\n * Runs in-process. The caller is responsible for ensuring `process.cwd()`\n * is the app's directory so tsx loads the app's tsconfig path aliases.\n *\n * The endpoints are found the way the app's build finds them — through the\n * workspace's constructs globs — never by importing every `.ts` under the app,\n * which loaded its tests and gkm's own generated files with them.\n */\nasync function generateOpenApiForApp(\n\tworkspace: NormalizedWorkspace,\n\tappName: string,\n\tapp: NormalizedAppConfig,\n\t/**\n\t * Quiet by default, because the usual caller is a subprocess whose output\n\t * the parent relays. Generating in-process there is no parent to relay to,\n\t * and silence would swallow the only report of what happened.\n\t */\n\tsilent = true,\n): Promise<{ outputPath: string; endpointCount: number } | null> {\n\tif (app.type !== 'backend') {\n\t\treturn null;\n\t}\n\n\tconst loaded = await new EndpointGenerator().load(\n\t\tappConstructGlobs(workspace, appName),\n\t);\n\n\t// The workspace's globs reach every app's code, so each app writes its own\n\t// surfaces' clients and no other's. An endpoint whose surface is no app of\n\t// this workspace's has nowhere else to go, and stays.\n\tconst endpoints = loaded\n\t\t.map(({ construct }) => construct)\n\t\t.filter((endpoint) => {\n\t\t\tconst owner = endpoint.owner ?? endpoint.surface?.id;\n\t\t\tif (!owner) return false;\n\t\t\tconst key = appKey(owner);\n\t\t\treturn key === appName || !workspace.apps[key];\n\t\t});\n\n\treturn generateOpenApi(endpoints, {\n\t\t// Absent means enabled, which is what the caller's filter already decided\n\t\t// when it kept this app: it skips one that says `openapi: false` and keeps\n\t\t// every other. Passing `undefined` through let `resolveOpenApiConfig`\n\t\t// default it to *disabled*, so an app selected for generation generated\n\t\t// nothing and said nothing — two places disagreeing about one flag, which\n\t\t// is the failure the filter above was written to describe.\n\t\topenapi: app.openapi ?? { enabled: true },\n\t\tsilent,\n\t\troot: workspace.root,\n\t});\n}\n\n/**\n * Resolve the gkm bin path. Tests can override via `GKM_BIN_PATH` env var\n * to avoid depending on the built dist.\n */\nfunction resolveGkmBinPath(): string {\n\tif (process.env.GKM_BIN_PATH) {\n\t\treturn process.env.GKM_BIN_PATH;\n\t}\n\treturn fileURLToPath(new URL('../bin/gkm.mjs', import.meta.url));\n}\n\n/**\n * Spawn a subprocess that runs `gkm openapi --app <name>` with `cwd` set to\n * the app's directory. Inherits `NODE_OPTIONS` (which already contains\n * `--import tsx`), so the child gets a fresh tsx instance whose tsconfig\n * discovery picks up the app's tsconfig path aliases.\n */\nasync function runOpenApiInSubprocess(\n\tappCwd: string,\n\tappName: string,\n): Promise<void> {\n\tconst binPath = resolveGkmBinPath();\n\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[binPath, 'openapi', '--app', appName],\n\t\t\t{\n\t\t\t\tcwd: appCwd,\n\t\t\t\tstdio: 'inherit',\n\t\t\t\tenv: process.env,\n\t\t\t},\n\t\t);\n\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(\n\t\t\t\t\tnew Error(\n\t\t\t\t\t\t`OpenAPI generation for app \"${appName}\" exited with code ${code}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,eAAe,WAA2B;CACzD,OAAO,kBAAA,GAAiBA,oBAAAA,UAAAA,CAAU,SAAS,EAAE;AAC9C;;;;AAKA,SAAgB,qBAAqB,QAEI;CACxC,IAAI,OAAO,YAAY,OACtB,OAAO,EAAE,SAAS,MAAM;CAGzB,IAAI,OAAO,YAAY,QAAQ,OAAO,YAAY,KAAA,GAEjD,OAAO;EACN,SAAS;EACT,OAAO;EACP,SAAS;EACT,aAAa;CACd;CAGD,OAAO;EACN,SAAS,OAAO,QAAQ,YAAY;EACpC,OAAO,OAAO,QAAQ,SAAS;EAC/B,SAAS,OAAO,QAAQ,WAAW;EACnC,aACC,OAAO,QAAQ,eACf;CACF;AACD;;;;;;;;AAmBA,eAAsB,oBACrB,QACA,UAKI,CAAC,GAC2B;CAOhC,OAAO,iBACN,MAPoB,IAAIC,0BAAAA,kBAAkB,CAAC,CAAC,KAC5C,QACA,KAAA,GACA,QAAQ,SACT,EAAA,CAGQ,KAAK,EAAE,gBAAgB,SAAS,GACvC,OACD;AACD;;;;;;;;;;;;AAaA,eAAsB,gBACrB,WACA,UAUI,CAAC,GAC2B;CAChC,MAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI;CACzC,MAAM,SAAS,QAAQ,SAAS,EAAE,WAAW,CAAC,EAAE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KAAK,QAAQ;EACd,CACD;EAEA,MAAM,GAAG,SAAS,MAAM;EACxB,MAAM,GAAG,UAAU,SAAS;GAC3B,IAAI,SAAS,GACZ,QAAQ;QAER,uBACC,IAAI,MACH,+BAA+B,QAAQ,qBAAqB,MAC7D,CACD;EAEF,CAAC;CACF,CAAC;AACF"}
|
package/dist/openapi.d.cts
CHANGED
package/dist/openapi.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.d.cts","names":[],"sources":["../src/openapi.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"openapi.d.cts","names":[],"sources":["../src/openapi.ts"],"mappings":";;;UAmBU;EACT;;;;;;;EAOA;;;;;;;;;;wBAWe,eAAe;;;;wBAOf,qBAAqB;EACpC,oBAAoB;IACjB;EAAkB;;;iBA0BL;;EAEhB;;EAEA;;EAEA;;;;;;;;;wBAUqB,oBACrB,QAAQ,QACR;EACC,oBAAoB;EACpB;EACA;EACA;IAEC,QAAQ;;;;;;;;;;;;wBAwBW,gBACrB,oBAAoB,qCACpB;EACC,oBAAoB;EACpB;;;;;;;EAOA;IAEC,QAAQ;wBAoEW,eACrB,UAAS,iBACP"}
|