@lunora/cli 1.0.0-alpha.40 → 1.0.0-alpha.400
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/LICENSE.md +33 -0
- package/README.md +3 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +1034 -374
- package/dist/index.d.ts +1034 -374
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/dispatch.mjs +1 -0
- package/dist/packem_chunks/handler.mjs +1 -160
- package/dist/packem_chunks/handler10.mjs +1 -16
- package/dist/packem_chunks/handler11.mjs +1 -22
- package/dist/packem_chunks/handler12.mjs +1 -192
- package/dist/packem_chunks/handler13.mjs +3 -131
- package/dist/packem_chunks/handler14.mjs +1 -65
- package/dist/packem_chunks/handler15.mjs +1 -58
- package/dist/packem_chunks/handler16.mjs +1 -80
- package/dist/packem_chunks/handler17.mjs +7 -43
- package/dist/packem_chunks/handler18.mjs +1 -105
- package/dist/packem_chunks/handler19.mjs +1 -170
- package/dist/packem_chunks/handler2.mjs +1 -114
- package/dist/packem_chunks/handler20.mjs +3 -94
- package/dist/packem_chunks/handler21.mjs +3 -94
- package/dist/packem_chunks/handler22.mjs +1 -0
- package/dist/packem_chunks/handler23.mjs +2 -0
- package/dist/packem_chunks/handler24.mjs +99 -0
- package/dist/packem_chunks/handler25.mjs +2 -0
- package/dist/packem_chunks/handler26.mjs +9 -0
- package/dist/packem_chunks/handler27.mjs +1 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +3 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +1 -42
- package/dist/packem_chunks/handler8.mjs +2 -174
- package/dist/packem_chunks/handler9.mjs +1 -315
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +11 -594
- package/dist/packem_chunks/runDevCommand.mjs +2 -0
- package/dist/packem_chunks/runInitCommand.mjs +165 -1432
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-aSTSMwZS.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
- package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
- package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
- package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
- package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
- package/dist/packem_shared/cli-CFsmCYWp.mjs +2 -0
- package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
- package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-BgjsvUFg.mjs +1 -0
- package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
- package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
- package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
- package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
- package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
- package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
- package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
- package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
- package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
- package/dist/packem_shared/plan-DVfi3TrN.mjs +5 -0
- package/dist/packem_shared/planDevCommand-IglbXy5A.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
- package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
- package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
- package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
- package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
- package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
- package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
- package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
- package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
- package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
- package/package.json +39 -19
- package/skills/README.md +35 -17
- package/skills/lunora/SKILL.md +154 -64
- package/skills/lunora-create-package/SKILL.md +97 -84
- package/skills/lunora-deploy/SKILL.md +175 -105
- package/skills/lunora-functions/SKILL.md +362 -56
- package/skills/lunora-migration-helper/SKILL.md +162 -137
- package/skills/lunora-performance-audit/SKILL.md +137 -95
- package/skills/lunora-quickstart/SKILL.md +137 -136
- package/skills/lunora-realtime/SKILL.md +140 -99
- package/skills/lunora-setup-auth/SKILL.md +162 -102
- package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
- package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
- package/skills/lunora-setup-mail/SKILL.md +85 -113
- package/skills/lunora-setup-scheduler/SKILL.md +132 -96
- package/skills/lunora-setup-storage/SKILL.md +189 -95
- package/dist/packem_chunks/planDevCommand.mjs +0 -541
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
- package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
- package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
- package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
- package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
- package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
|
@@ -1,594 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { join } from '@visulima/path';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
import { a as isRailpackAvailable, i as isDockerAvailable } from '../packem_shared/docker-hMQ97KSQ.mjs';
|
|
11
|
-
|
|
12
|
-
import { containerBuildTag } from '@lunora/container';
|
|
13
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
14
|
-
import { r as resolveWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
|
|
15
|
-
import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
|
|
16
|
-
import { c as createTuiConfirm } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
|
|
17
|
-
import { l as listRemoteSecrets } from '../packem_shared/wrangler-secrets-P2_ZUR-k.mjs';
|
|
18
|
-
import { runMigrateDataCommand } from './runMigrateGenerateCommand.mjs';
|
|
19
|
-
|
|
20
|
-
const WORKERS_DEV_URL = /https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u;
|
|
21
|
-
const ANY_HTTPS_URL = /https:\/\/[^\s"'<>]+/u;
|
|
22
|
-
const parseDeployedUrl = (output) => {
|
|
23
|
-
const workersDev = WORKERS_DEV_URL.exec(output);
|
|
24
|
-
if (workersDev) {
|
|
25
|
-
return workersDev[0];
|
|
26
|
-
}
|
|
27
|
-
return ANY_HTTPS_URL.exec(output)?.[0];
|
|
28
|
-
};
|
|
29
|
-
const autoLinkFromDeployOutput = ({ cwd, env, logger, now, output }) => {
|
|
30
|
-
if (output === void 0 || readLinkedProject(cwd) !== void 0) {
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
const url = parseDeployedUrl(output);
|
|
34
|
-
if (url === void 0) {
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
try {
|
|
38
|
-
const stamp = (now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
|
|
39
|
-
writeLinkedProject(cwd, { env, linkedAt: stamp, workerName: readWranglerName(cwd), workerUrl: url });
|
|
40
|
-
logger.success(`link: recorded ${url} in .lunora/project.json (run \`lunora link\` to change)`);
|
|
41
|
-
} catch {
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
const renderDeploySummary = (inputs) => {
|
|
46
|
-
const { cwd, env, logger, migrated } = inputs;
|
|
47
|
-
try {
|
|
48
|
-
const link = readLinkedProject(cwd);
|
|
49
|
-
const workerName = link?.workerName ?? readWranglerName(cwd);
|
|
50
|
-
logger.success("deploy complete");
|
|
51
|
-
logger.info(` worker: ${workerName ?? "(see wrangler output above)"}`);
|
|
52
|
-
if (env !== void 0) {
|
|
53
|
-
logger.info(` env: ${env}`);
|
|
54
|
-
}
|
|
55
|
-
if (link?.workerUrl === void 0) {
|
|
56
|
-
logger.info(" url: run `lunora link --url <https://your-worker>` to record it");
|
|
57
|
-
} else {
|
|
58
|
-
logger.info(` url: ${link.workerUrl}`);
|
|
59
|
-
}
|
|
60
|
-
if (migrated) {
|
|
61
|
-
logger.info(" migrations: applied");
|
|
62
|
-
}
|
|
63
|
-
logger.info(" studio: lunora view --remote");
|
|
64
|
-
logger.info(" logs: lunora logs");
|
|
65
|
-
} catch {
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
const buildRailpackImages = async (options) => {
|
|
70
|
-
if (options.targets.length === 0) {
|
|
71
|
-
return { builtTags: [], code: 0 };
|
|
72
|
-
}
|
|
73
|
-
if (!(options.railpackAvailable ?? isRailpackAvailable)()) {
|
|
74
|
-
const message = "deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";
|
|
75
|
-
options.logger.error(message);
|
|
76
|
-
return { builtTags: [], code: 1, error: message };
|
|
77
|
-
}
|
|
78
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
79
|
-
const builtTags = [];
|
|
80
|
-
for (const target of options.targets) {
|
|
81
|
-
const tag = containerBuildTag(target.exportName);
|
|
82
|
-
const build = { args: ["build", target.buildDir, "--name", tag], command: "railpack", cwd: options.cwd };
|
|
83
|
-
const push = { args: ["exec", "wrangler", "containers", "push", tag], command: "pnpm", cwd: options.cwd };
|
|
84
|
-
options.logger.info(`railpack: building "${target.exportName}" → ${tag} from ${target.buildDir}`);
|
|
85
|
-
const buildResult = await spawner(build);
|
|
86
|
-
if (buildResult.code !== 0) {
|
|
87
|
-
const message = `railpack build failed for container "${target.exportName}" (${target.buildDir})`;
|
|
88
|
-
options.logger.error(message);
|
|
89
|
-
return { builtTags, code: buildResult.code, error: message };
|
|
90
|
-
}
|
|
91
|
-
options.logger.info(`railpack: pushing ${tag} to the Cloudflare Registry`);
|
|
92
|
-
const pushResult = await spawner(push);
|
|
93
|
-
if (pushResult.code !== 0) {
|
|
94
|
-
const message = `wrangler containers push failed for "${target.exportName}" (${tag})`;
|
|
95
|
-
options.logger.error(message);
|
|
96
|
-
return { builtTags, code: pushResult.code, error: message };
|
|
97
|
-
}
|
|
98
|
-
builtTags.push(tag);
|
|
99
|
-
}
|
|
100
|
-
return { builtTags, code: 0 };
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
const D1_PLACEHOLDER_ID = "<replace-with-d1-create-id>";
|
|
104
|
-
const ORIGIN_VAR_NAMES = ["LUNORA_ORIGIN_URL", "LUNORA_WORKER_ORIGIN", "AUTH_URL"];
|
|
105
|
-
const isLocalhostUrl = (value) => {
|
|
106
|
-
try {
|
|
107
|
-
const { hostname } = new URL(value);
|
|
108
|
-
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
|
|
109
|
-
} catch {
|
|
110
|
-
return false;
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
const isLocalImagePath = (image) => image.startsWith("./") || image.startsWith("../") || image.startsWith("/") || image.includes("Dockerfile");
|
|
114
|
-
const checkContainerDockerPreflight = (cwd, logger, dockerAvailable) => {
|
|
115
|
-
const wranglerPath = findWranglerFile(cwd);
|
|
116
|
-
if (!wranglerPath) {
|
|
117
|
-
return void 0;
|
|
118
|
-
}
|
|
119
|
-
const { parsed } = readWranglerJsonc(wranglerPath);
|
|
120
|
-
const localImages = (parsed?.containers ?? []).filter((entry) => typeof entry?.image === "string" && isLocalImagePath(entry.image));
|
|
121
|
-
if (localImages.length === 0 || dockerAvailable()) {
|
|
122
|
-
return void 0;
|
|
123
|
-
}
|
|
124
|
-
const message = `deploy blocked: wrangler.jsonc declares ${String(localImages.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;
|
|
125
|
-
logger.error(message);
|
|
126
|
-
return message;
|
|
127
|
-
};
|
|
128
|
-
const resolveComposedWorkerEntry = (cwd) => existsSync(join(cwd, "src", "worker.ts")) ? "src/worker.ts" : void 0;
|
|
129
|
-
const checkContainerSourcesExist = (cwd, logger) => {
|
|
130
|
-
for (const container of discoverContainerInfo(cwd, "lunora").containers) {
|
|
131
|
-
const { image } = container;
|
|
132
|
-
if (image.kind === "dockerfile" && !existsSync(join(cwd, image.dockerfilePath))) {
|
|
133
|
-
const message = `deploy blocked: container "${container.exportName}" references a Dockerfile at "${image.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;
|
|
134
|
-
logger.error(message);
|
|
135
|
-
return message;
|
|
136
|
-
}
|
|
137
|
-
if (image.kind === "build" && !existsSync(join(cwd, image.buildDir))) {
|
|
138
|
-
const message = `deploy blocked: container "${container.exportName}" references a Railpack build directory "${image.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;
|
|
139
|
-
logger.error(message);
|
|
140
|
-
return message;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
return void 0;
|
|
144
|
-
};
|
|
145
|
-
const isInteractive = (options) => {
|
|
146
|
-
if (isJsonFormat(options.format)) {
|
|
147
|
-
return false;
|
|
148
|
-
}
|
|
149
|
-
if (options.interactive !== void 0) {
|
|
150
|
-
return options.interactive;
|
|
151
|
-
}
|
|
152
|
-
return process.stdout.isTTY && !process.env.CI;
|
|
153
|
-
};
|
|
154
|
-
const findD1PlaceholderBinding = (cwd) => {
|
|
155
|
-
const wranglerPath = findWranglerFile(cwd);
|
|
156
|
-
if (!wranglerPath) {
|
|
157
|
-
return void 0;
|
|
158
|
-
}
|
|
159
|
-
const { parsed } = readWranglerJsonc(wranglerPath);
|
|
160
|
-
if (!parsed) {
|
|
161
|
-
return void 0;
|
|
162
|
-
}
|
|
163
|
-
const placeholder = (parsed.d1_databases ?? []).find((entry) => entry.database_id === D1_PLACEHOLDER_ID);
|
|
164
|
-
return placeholder?.binding;
|
|
165
|
-
};
|
|
166
|
-
const buildContainerImages = async (cwd, options) => {
|
|
167
|
-
const targets = discoverContainerInfo(cwd, "lunora").containers.filter((container) => container.image.kind === "build").map((container) => {
|
|
168
|
-
return { buildDir: container.image.buildDir, exportName: container.exportName };
|
|
169
|
-
});
|
|
170
|
-
if (targets.length === 0) {
|
|
171
|
-
return void 0;
|
|
172
|
-
}
|
|
173
|
-
const result = await buildRailpackImages({
|
|
174
|
-
cwd,
|
|
175
|
-
logger: options.logger,
|
|
176
|
-
railpackAvailable: options.railpackAvailable,
|
|
177
|
-
spawner: options.spawner,
|
|
178
|
-
targets
|
|
179
|
-
});
|
|
180
|
-
return result.code === 0 ? void 0 : result.error ?? "railpack build failed";
|
|
181
|
-
};
|
|
182
|
-
const provisionBindings = async (cwd, logger) => {
|
|
183
|
-
try {
|
|
184
|
-
const inferred = await inferLunoraBindings({ projectRoot: cwd });
|
|
185
|
-
const reconciled = reconcileWranglerBindings(cwd, inferred);
|
|
186
|
-
if (reconciled.changed) {
|
|
187
|
-
logger.success(`provisioned bindings: ${reconciled.added.join(", ")} → ${reconciled.wranglerPath ?? "wrangler.jsonc"}`);
|
|
188
|
-
}
|
|
189
|
-
for (const warning of reconciled.warnings) {
|
|
190
|
-
logger.warn(warning);
|
|
191
|
-
}
|
|
192
|
-
} catch (error) {
|
|
193
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
194
|
-
logger.warn(`binding inference skipped: ${message}`);
|
|
195
|
-
}
|
|
196
|
-
};
|
|
197
|
-
const warnDevVariablesNotPushed = (cwd, logger) => {
|
|
198
|
-
const devVariablesPath = join(cwd, DEV_VARS_FILE);
|
|
199
|
-
if (!existsSync(devVariablesPath)) {
|
|
200
|
-
return;
|
|
201
|
-
}
|
|
202
|
-
let keyCount;
|
|
203
|
-
try {
|
|
204
|
-
keyCount = parseDevVariableEntries(readFileSync(devVariablesPath, "utf8")).length;
|
|
205
|
-
} catch {
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
if (keyCount === 0) {
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
logger.warn(
|
|
212
|
-
`Note: \`lunora deploy\` does not push secrets. ${DEV_VARS_FILE} has ${String(keyCount)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`
|
|
213
|
-
);
|
|
214
|
-
};
|
|
215
|
-
const SECRET_LIKE_KEY = /(?:KEY|PASSWORD|SECRET|TOKEN)$/u;
|
|
216
|
-
const resolveRequiredSecretKeys = async (cwd) => {
|
|
217
|
-
let packages = [];
|
|
218
|
-
try {
|
|
219
|
-
packages = packageNamesFromBindings(await inferLunoraBindings({ projectRoot: cwd }));
|
|
220
|
-
} catch {
|
|
221
|
-
}
|
|
222
|
-
const fromPackages = requiredSecrets(packages).map((entry) => entry.key);
|
|
223
|
-
let fromLocal = [];
|
|
224
|
-
try {
|
|
225
|
-
const devVariablesPath = join(cwd, DEV_VARS_FILE);
|
|
226
|
-
if (existsSync(devVariablesPath)) {
|
|
227
|
-
fromLocal = parseDevVariableEntries(readFileSync(devVariablesPath, "utf8")).map((entry) => entry.key).filter((key) => SECRET_LIKE_KEY.test(key));
|
|
228
|
-
}
|
|
229
|
-
} catch {
|
|
230
|
-
}
|
|
231
|
-
return [.../* @__PURE__ */ new Set([...fromPackages, ...fromLocal])];
|
|
232
|
-
};
|
|
233
|
-
const pushMintableSecrets = async (cwd, options, keys) => {
|
|
234
|
-
const { logger } = options;
|
|
235
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
236
|
-
const environmentFlag = options.env === void 0 ? "" : ` --env ${options.env}`;
|
|
237
|
-
for (const key of keys) {
|
|
238
|
-
const args = ["exec", "wrangler", "secret", "put", key];
|
|
239
|
-
if (options.env !== void 0) {
|
|
240
|
-
args.push("--env", options.env);
|
|
241
|
-
}
|
|
242
|
-
if (options.temporary === true) {
|
|
243
|
-
args.push("--temporary");
|
|
244
|
-
}
|
|
245
|
-
const pushResult = await spawner({ args, command: "pnpm", cwd, input: generateSecretValue() });
|
|
246
|
-
if (pushResult.code !== 0) {
|
|
247
|
-
logger.error(
|
|
248
|
-
`failed to push secret ${key} (exit ${String(pushResult.code)}); set it manually with \`wrangler secret put ${key}${environmentFlag}\`.`
|
|
249
|
-
);
|
|
250
|
-
return false;
|
|
251
|
-
}
|
|
252
|
-
logger.success(`generated + pushed ${key}`);
|
|
253
|
-
}
|
|
254
|
-
return true;
|
|
255
|
-
};
|
|
256
|
-
const offerMissingSecrets = async (cwd, options, interactive) => {
|
|
257
|
-
if (options.dryRun === true || options.preview === true) {
|
|
258
|
-
return void 0;
|
|
259
|
-
}
|
|
260
|
-
const { logger } = options;
|
|
261
|
-
const environmentFlag = options.env === void 0 ? "" : ` --env ${options.env}`;
|
|
262
|
-
let remote;
|
|
263
|
-
try {
|
|
264
|
-
remote = await (options.secretLister ?? listRemoteSecrets)({ cwd, env: options.env, temporary: options.temporary });
|
|
265
|
-
} catch {
|
|
266
|
-
return void 0;
|
|
267
|
-
}
|
|
268
|
-
if (!remote.ok) {
|
|
269
|
-
return void 0;
|
|
270
|
-
}
|
|
271
|
-
const remoteNames = new Set(remote.names);
|
|
272
|
-
const required = await resolveRequiredSecretKeys(cwd);
|
|
273
|
-
const missing = required.filter((key) => !remoteNames.has(key));
|
|
274
|
-
if (missing.length === 0) {
|
|
275
|
-
return void 0;
|
|
276
|
-
}
|
|
277
|
-
if (!interactive) {
|
|
278
|
-
return `missing required secret(s) on the deploy target: ${missing.join(", ")}. Set them with \`wrangler secret put <KEY>${environmentFlag}\` (or \`lunora env generate --set\` then \`lunora env push --yes${options.env === void 0 ? "" : " --prod"}\`), then re-deploy.`;
|
|
279
|
-
}
|
|
280
|
-
for (const key of missing.filter((name) => !isMintableSecretKey(name))) {
|
|
281
|
-
logger.warn(`required secret ${key} is not set on the target — set it with: wrangler secret put ${key}${environmentFlag}`);
|
|
282
|
-
}
|
|
283
|
-
const mintable = missing.filter((key) => isMintableSecretKey(key));
|
|
284
|
-
if (mintable.length === 0) {
|
|
285
|
-
return void 0;
|
|
286
|
-
}
|
|
287
|
-
const confirm = options.secretConfirm ?? createTuiConfirm();
|
|
288
|
-
if (await confirm(`${String(mintable.length)} required secret(s) not set on the target (${mintable.join(", ")}). Generate strong values and push them now?`)) {
|
|
289
|
-
await pushMintableSecrets(cwd, options, mintable);
|
|
290
|
-
return void 0;
|
|
291
|
-
}
|
|
292
|
-
logger.warn(
|
|
293
|
-
`${String(mintable.length)} required secret(s) not set on the target: ${mintable.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${options.env === void 0 ? "" : " --prod"}\`.`
|
|
294
|
-
);
|
|
295
|
-
return void 0;
|
|
296
|
-
};
|
|
297
|
-
const runPostDeployMigrations = async (options, cwd) => {
|
|
298
|
-
const project = new Project({ skipAddingFilesFromTsConfig: true });
|
|
299
|
-
const lunoraDirectory = join(cwd, "lunora");
|
|
300
|
-
let migrations;
|
|
301
|
-
try {
|
|
302
|
-
migrations = discoverMigrations(project, lunoraDirectory);
|
|
303
|
-
} catch (error) {
|
|
304
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
305
|
-
options.logger.warn(`--migrate: could not discover migrations (${message}); skipping`);
|
|
306
|
-
return 0;
|
|
307
|
-
}
|
|
308
|
-
if (migrations.length === 0) {
|
|
309
|
-
options.logger.info("--migrate: no data migrations declared in lunora/");
|
|
310
|
-
return 0;
|
|
311
|
-
}
|
|
312
|
-
options.logger.info(`--migrate: running ${String(migrations.length)} migration(s) against deployed worker`);
|
|
313
|
-
for (const migration of migrations) {
|
|
314
|
-
options.logger.info(`--migrate: up "${migration.id}" (table "${migration.table}")`);
|
|
315
|
-
const migrateOptions = {
|
|
316
|
-
cwd,
|
|
317
|
-
fetchImpl: options.fetchImpl,
|
|
318
|
-
id: migration.id,
|
|
319
|
-
logger: options.logger,
|
|
320
|
-
// A `--migrate-url` is always set by this point (guarded above), so this
|
|
321
|
-
// is a production migration — gate it behind the operator's explicit
|
|
322
|
-
// `--migrate-yes`/`--yes` rather than auto-confirming.
|
|
323
|
-
prod: true,
|
|
324
|
-
subcommand: "up",
|
|
325
|
-
token: options.migrateToken,
|
|
326
|
-
url: options.migrateUrl,
|
|
327
|
-
yes: options.migrateYes === true
|
|
328
|
-
};
|
|
329
|
-
const migrateResult = await runMigrateDataCommand(migrateOptions);
|
|
330
|
-
if (migrateResult.code !== 0) {
|
|
331
|
-
options.logger.error(`--migrate: migration "${migration.id}" failed — see output above`);
|
|
332
|
-
return migrateResult.code;
|
|
333
|
-
}
|
|
334
|
-
options.logger.success(`--migrate: "${migration.id}" applied`);
|
|
335
|
-
}
|
|
336
|
-
return 0;
|
|
337
|
-
};
|
|
338
|
-
const validateMigrateDeployPreflight = (options) => {
|
|
339
|
-
if (!options.migrate || options.dryRun || options.preview) {
|
|
340
|
-
return void 0;
|
|
341
|
-
}
|
|
342
|
-
if (options.migrateUrl === void 0) {
|
|
343
|
-
const message = "--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";
|
|
344
|
-
options.logger.error(message);
|
|
345
|
-
return message;
|
|
346
|
-
}
|
|
347
|
-
if (options.migrateYes !== true) {
|
|
348
|
-
const message = "--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";
|
|
349
|
-
options.logger.error(message);
|
|
350
|
-
return message;
|
|
351
|
-
}
|
|
352
|
-
if ((options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === void 0 || (options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === "") {
|
|
353
|
-
const message = "admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";
|
|
354
|
-
options.logger.error(message);
|
|
355
|
-
return message;
|
|
356
|
-
}
|
|
357
|
-
return void 0;
|
|
358
|
-
};
|
|
359
|
-
const runCodegenStep = (cwd, interactive, logger, apiSpec) => {
|
|
360
|
-
let codegenSpinner;
|
|
361
|
-
if (interactive) {
|
|
362
|
-
codegenSpinner = new Spinner({ name: "dots" });
|
|
363
|
-
codegenSpinner.start("running codegen");
|
|
364
|
-
} else {
|
|
365
|
-
logger.info("running codegen");
|
|
366
|
-
}
|
|
367
|
-
try {
|
|
368
|
-
const result = runCodegen({ apiSpec, projectRoot: cwd });
|
|
369
|
-
codegenSpinner?.succeed("codegen complete");
|
|
370
|
-
if (!codegenSpinner) {
|
|
371
|
-
logger.success("codegen complete");
|
|
372
|
-
}
|
|
373
|
-
return { result };
|
|
374
|
-
} catch (error) {
|
|
375
|
-
codegenSpinner?.failed("codegen failed");
|
|
376
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
377
|
-
logger.error(`codegen failed: ${message}`);
|
|
378
|
-
return { error: `codegen failed: ${message}` };
|
|
379
|
-
}
|
|
380
|
-
};
|
|
381
|
-
const checkD1Placeholder = (cwd, logger) => {
|
|
382
|
-
const placeholderBinding = findD1PlaceholderBinding(cwd);
|
|
383
|
-
if (placeholderBinding === void 0) {
|
|
384
|
-
return void 0;
|
|
385
|
-
}
|
|
386
|
-
const message = `deploy blocked: the "${placeholderBinding}" D1 binding has a placeholder database_id ("${D1_PLACEHOLDER_ID}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;
|
|
387
|
-
logger.error(message);
|
|
388
|
-
return message;
|
|
389
|
-
};
|
|
390
|
-
const checkLocalhostOriginVariables = (cwd, logger) => {
|
|
391
|
-
const wranglerPath = findWranglerFile(cwd);
|
|
392
|
-
if (!wranglerPath) {
|
|
393
|
-
return void 0;
|
|
394
|
-
}
|
|
395
|
-
const { parsed } = readWranglerJsonc(wranglerPath);
|
|
396
|
-
const variables = parsed?.vars;
|
|
397
|
-
if (!variables) {
|
|
398
|
-
return void 0;
|
|
399
|
-
}
|
|
400
|
-
const offenders = ORIGIN_VAR_NAMES.filter((name) => typeof variables[name] === "string" && isLocalhostUrl(variables[name]));
|
|
401
|
-
if (offenders.length === 0) {
|
|
402
|
-
return void 0;
|
|
403
|
-
}
|
|
404
|
-
const message = `deploy blocked: ${offenders.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;
|
|
405
|
-
logger.error(message);
|
|
406
|
-
return message;
|
|
407
|
-
};
|
|
408
|
-
const finalizeSuccessfulDeploy = async (options, cwd, descriptor, validation, reblessSchemaBaseline) => {
|
|
409
|
-
if (options.migrate) {
|
|
410
|
-
const migrateCode = await runPostDeployMigrations(options, cwd);
|
|
411
|
-
if (migrateCode === 0) {
|
|
412
|
-
reblessSchemaBaseline?.();
|
|
413
|
-
}
|
|
414
|
-
return { code: migrateCode, descriptor, validation };
|
|
415
|
-
}
|
|
416
|
-
reblessSchemaBaseline?.();
|
|
417
|
-
return { code: 0, descriptor, validation };
|
|
418
|
-
};
|
|
419
|
-
const runPreDeployGates = async (cwd, options) => {
|
|
420
|
-
const d1Error = checkD1Placeholder(cwd, options.logger);
|
|
421
|
-
if (d1Error !== void 0) {
|
|
422
|
-
return d1Error;
|
|
423
|
-
}
|
|
424
|
-
const localhostOriginError = checkLocalhostOriginVariables(cwd, options.logger);
|
|
425
|
-
if (localhostOriginError !== void 0) {
|
|
426
|
-
return localhostOriginError;
|
|
427
|
-
}
|
|
428
|
-
const sourceError = checkContainerSourcesExist(cwd, options.logger);
|
|
429
|
-
if (sourceError !== void 0) {
|
|
430
|
-
return sourceError;
|
|
431
|
-
}
|
|
432
|
-
const dockerError = checkContainerDockerPreflight(cwd, options.logger, options.dockerAvailable ?? isDockerAvailable);
|
|
433
|
-
if (dockerError !== void 0) {
|
|
434
|
-
return dockerError;
|
|
435
|
-
}
|
|
436
|
-
return buildContainerImages(cwd, options);
|
|
437
|
-
};
|
|
438
|
-
const buildWranglerDeployArgs = (cwd, options) => {
|
|
439
|
-
const args = options.preview ? ["exec", "wrangler", "versions", "upload"] : ["exec", "wrangler", "deploy"];
|
|
440
|
-
const composedEntry = resolveComposedWorkerEntry(cwd);
|
|
441
|
-
if (composedEntry !== void 0) {
|
|
442
|
-
args.push(composedEntry);
|
|
443
|
-
options.logger.info(`class-B composition: deploying ${composedEntry} (overrides wrangler main)`);
|
|
444
|
-
}
|
|
445
|
-
if (options.env !== void 0) {
|
|
446
|
-
args.push("--env", options.env);
|
|
447
|
-
}
|
|
448
|
-
if (options.temporary) {
|
|
449
|
-
args.push("--temporary");
|
|
450
|
-
options.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL");
|
|
451
|
-
}
|
|
452
|
-
if (options.dryRun) {
|
|
453
|
-
args.push("--dry-run");
|
|
454
|
-
options.logger.info("dry run: validating + bundling without publishing");
|
|
455
|
-
}
|
|
456
|
-
if (options.outDir !== void 0) {
|
|
457
|
-
args.push("--outdir", options.outDir, "--metafile");
|
|
458
|
-
options.logger.info(`build artifact: emitting bundle to ${options.outDir}`);
|
|
459
|
-
}
|
|
460
|
-
return args;
|
|
461
|
-
};
|
|
462
|
-
const reportWranglerProblems = (validation, logger) => {
|
|
463
|
-
if (validation.problems.length === 0) {
|
|
464
|
-
return false;
|
|
465
|
-
}
|
|
466
|
-
logger.error("wrangler.jsonc validation failed:");
|
|
467
|
-
for (const problem of validation.problems) {
|
|
468
|
-
logger.error(` - ${problem}`);
|
|
469
|
-
}
|
|
470
|
-
return true;
|
|
471
|
-
};
|
|
472
|
-
const executeDeploy = async (options) => {
|
|
473
|
-
const cwd = options.cwd ?? process.cwd();
|
|
474
|
-
const interactive = isInteractive(options);
|
|
475
|
-
let codegen;
|
|
476
|
-
if (!options.skipCodegen) {
|
|
477
|
-
const codegenStep = runCodegenStep(cwd, interactive, options.logger, options.apiSpec);
|
|
478
|
-
if (codegenStep.error !== void 0) {
|
|
479
|
-
return {
|
|
480
|
-
code: 1,
|
|
481
|
-
descriptor: void 0,
|
|
482
|
-
error: codegenStep.error,
|
|
483
|
-
validation: { problems: [], wranglerPath: void 0 }
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
codegen = codegenStep.result;
|
|
487
|
-
}
|
|
488
|
-
let reblessSchemaBaseline;
|
|
489
|
-
if (codegen !== void 0) {
|
|
490
|
-
const gate = runSchemaDriftGate({
|
|
491
|
-
allowDrift: options.allowSchemaDrift === true,
|
|
492
|
-
codegen,
|
|
493
|
-
logger: options.logger,
|
|
494
|
-
updateBaseline: options.updateSchemaBaseline === true
|
|
495
|
-
});
|
|
496
|
-
if (gate.blocked) {
|
|
497
|
-
return {
|
|
498
|
-
code: 1,
|
|
499
|
-
descriptor: void 0,
|
|
500
|
-
error: "schema drift gate blocked deploy",
|
|
501
|
-
schemaDrift: { blocked: true, reason: gate.reason },
|
|
502
|
-
validation: { problems: [], wranglerPath: void 0 }
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
reblessSchemaBaseline = gate.rebless;
|
|
506
|
-
}
|
|
507
|
-
await provisionBindings(cwd, options.logger);
|
|
508
|
-
const migratePreflightError = validateMigrateDeployPreflight(options);
|
|
509
|
-
if (migratePreflightError !== void 0) {
|
|
510
|
-
return { code: 1, descriptor: void 0, error: migratePreflightError, validation: { problems: [], wranglerPath: void 0 } };
|
|
511
|
-
}
|
|
512
|
-
const preflightError = await runPreDeployGates(cwd, options);
|
|
513
|
-
if (preflightError !== void 0) {
|
|
514
|
-
return { code: 1, descriptor: void 0, error: preflightError, validation: { problems: [], wranglerPath: void 0 } };
|
|
515
|
-
}
|
|
516
|
-
const validation = validateWranglerProject({ projectRoot: cwd });
|
|
517
|
-
if (reportWranglerProblems(validation, options.logger)) {
|
|
518
|
-
return { code: 1, descriptor: void 0, error: "wrangler validation failed", validation };
|
|
519
|
-
}
|
|
520
|
-
warnDevVariablesNotPushed(cwd, options.logger);
|
|
521
|
-
const secretAbort = await offerMissingSecrets(cwd, options, interactive);
|
|
522
|
-
if (secretAbort !== void 0) {
|
|
523
|
-
options.logger.error(secretAbort);
|
|
524
|
-
return { code: 1, descriptor: void 0, error: secretAbort, validation };
|
|
525
|
-
}
|
|
526
|
-
const shouldAutoLink = !isJsonFormat(options.format) && options.dryRun !== true && options.preview !== true && readLinkedProject(cwd) === void 0;
|
|
527
|
-
const descriptor = {
|
|
528
|
-
args: buildWranglerDeployArgs(cwd, options),
|
|
529
|
-
captureStdout: shouldAutoLink,
|
|
530
|
-
command: "pnpm",
|
|
531
|
-
cwd,
|
|
532
|
-
// In `--format json` mode stdout is reserved for the single JSON document,
|
|
533
|
-
// so route wrangler's progress + deployed-URL output to stderr instead.
|
|
534
|
-
stdoutToStderr: isJsonFormat(options.format)
|
|
535
|
-
};
|
|
536
|
-
options.logger.info(`deploying via ${descriptor.command} ${descriptor.args.join(" ")}`);
|
|
537
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
538
|
-
const result = await spawner(descriptor);
|
|
539
|
-
if (result.code !== 0) {
|
|
540
|
-
return { code: result.code, descriptor, validation };
|
|
541
|
-
}
|
|
542
|
-
if (options.dryRun) {
|
|
543
|
-
return { code: 0, descriptor, validation };
|
|
544
|
-
}
|
|
545
|
-
if (options.preview) {
|
|
546
|
-
return { code: 0, descriptor, validation };
|
|
547
|
-
}
|
|
548
|
-
autoLinkFromDeployOutput({ cwd, env: options.env, logger: options.logger, output: result.stdout });
|
|
549
|
-
return finalizeSuccessfulDeploy(options, cwd, descriptor, validation, reblessSchemaBaseline);
|
|
550
|
-
};
|
|
551
|
-
const runDeployCommand = async (options) => {
|
|
552
|
-
const formatError = validateOutputFormat("deploy", options.format);
|
|
553
|
-
if (formatError !== void 0) {
|
|
554
|
-
options.logger.error(formatError);
|
|
555
|
-
return { code: 1, descriptor: void 0, error: formatError, validation: { problems: [], wranglerPath: void 0 } };
|
|
556
|
-
}
|
|
557
|
-
const result = await executeDeploy({ ...options, logger: loggerForFormat(options.format, options.logger) });
|
|
558
|
-
if (isJsonFormat(options.format)) {
|
|
559
|
-
printJson(result);
|
|
560
|
-
return result;
|
|
561
|
-
}
|
|
562
|
-
if (result.code === 0 && options.dryRun !== true && options.preview !== true) {
|
|
563
|
-
renderDeploySummary({ cwd: options.cwd ?? process.cwd(), env: options.env, logger: options.logger, migrated: options.migrate === true });
|
|
564
|
-
} else if (result.code === 0 && options.preview === true) {
|
|
565
|
-
options.logger.success("preview version uploaded — see the preview URL in the wrangler output above");
|
|
566
|
-
}
|
|
567
|
-
return result;
|
|
568
|
-
};
|
|
569
|
-
const execute = defineHandler(async ({ cwd, logger, options }) => {
|
|
570
|
-
const result = await runDeployCommand({
|
|
571
|
-
allowSchemaDrift: options.allowSchemaDrift === true,
|
|
572
|
-
apiSpec: parseApiSpec(options.apiSpec),
|
|
573
|
-
cwd,
|
|
574
|
-
dryRun: options.dryRun === true,
|
|
575
|
-
env: options.env,
|
|
576
|
-
format: options.format,
|
|
577
|
-
logger,
|
|
578
|
-
migrate: options.migrate === true,
|
|
579
|
-
migrateToken: options.migrateToken,
|
|
580
|
-
// Fall back to the `.lunora/project.json` link so a linked checkout no
|
|
581
|
-
// longer needs --migrate-url repeated on every `deploy --migrate`.
|
|
582
|
-
migrateUrl: resolveWorkerUrl({ cwd, url: options.migrateUrl }),
|
|
583
|
-
migrateYes: options.migrateYes === true,
|
|
584
|
-
preview: options.preview === true,
|
|
585
|
-
// `--prebuilt` trusts a prior `lunora build`/`prepare`: skip codegen (and
|
|
586
|
-
// thus the drift gate, which has no fresh snapshot to measure).
|
|
587
|
-
skipCodegen: options.prebuilt === true,
|
|
588
|
-
temporary: options.temporary === true,
|
|
589
|
-
updateSchemaBaseline: options.updateSchemaBaseline === true
|
|
590
|
-
});
|
|
591
|
-
return { code: result.code };
|
|
592
|
-
});
|
|
593
|
-
|
|
594
|
-
export { execute, runDeployCommand };
|
|
1
|
+
import{dirname as D,join as I,resolve as ve}from"node:path";import{discoverMigrations as pe,runCodegen as ye,readServiceBindings as we}from"@lunora/codegen";import{readLinkedProject as Q,discoverContainerInfo as Z,COMPOSED_WORKER_ENTRY as F,writeLinkedProject as be,discoverSchemaInfo as ee,DEV_VARS_FILE as $,parseDevVariableEntries as re,isMintableSecretKey as B,secretSourcesFromBindings as $e,inferLunoraBindings as te,resolveSchemaDirectory as x,requiredSecrets as ke,generateSecretValue as Se,upsertDevVariableLine as Ee,writeDevVariablesFileAtomically as Ae,resolveLazyFunctions as ne,createDiscoveryCache as Re,resolveDeployDriver as O,planToolchainInvocation as oe,runPostCodegenHook as Ce}from"@lunora/config";import{findWranglerFile as L,readWranglerJsonc as S,mergeWranglerEnvironment as ae,applyModify as ie,HYPERDRIVE_PLACEHOLDER_ID as De,warnCloudflareCliConfigOnce as je,validateWranglerProject as Pe,wranglerCodegenInputs as _e,reconcileWranglerBindings as Te,reconcileWranglerCompatibilityDate as Ne,reconcileWranglerCrons as Ie,describePreservedCrons as xe}from"@lunora/config/cloudflare";import{Spinner as Oe}from"@visulima/spinner";import{r as Le,a as Ue,e as He}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Me}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{mkdirSync as Fe,writeFileSync as E,existsSync as y,readFileSync as w}from"node:fs";import{m as Be,e as Ve,i as We,b as qe,a as Ge}from"../packem_shared/secret-key-8DPOH98z.mjs";import{w as Ke}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Ye}from"../packem_shared/command-BgjsvUFg.mjs";import{r as U}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as ze}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as p}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Je}from"@lunora/container";import{i as Xe,a as Qe}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as P}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as se,detectPackageManager as A,toolchainExecArgs as j}from"@lunora/config/cli";import{r as ce}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Ze,H as er,a as rr,r as tr}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as b}from"@visulima/path";import{createHash as nr}from"node:crypto";import{r as or,c as ar}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{Project as ir}from"ts-morph";import{runMigrateDataCommand as sr}from"../packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs";import{c as cr}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as dr}from"../packem_shared/wrangler-secrets-CTQPpalP.mjs";const lr=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),ur=20,V=e=>`${e.from} -${e.kind}-> ${e.to}`,R=(e,r)=>{const n=new Set(e);return r.filter(t=>!n.has(t)).toSorted((t,o)=>t.localeCompare(o))},gr=(e,r)=>{const n=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),o=e.edges.map(i=>V(i)),a=r.edges.map(i=>V(i));return{addedEdges:R(o,a),addedModules:R(n,t),removedEdges:R(a,o),removedModules:R(t,n)}},C=(e,r,n)=>{if(n.length===0)return[];const t=n.slice(0,ur).map(a=>` ${e} ${a}`),o=n.length-t.length;return[`${r}:`,...t,...o>0?[` … and ${o.toString()} more`]:[]]},fr=e=>{const r=[...C("+","modules added",e.addedModules),...C("-","modules removed",e.removedModules),...C("+","edges added",e.addedEdges),...C("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
|
|
2
|
+
${r.join(`
|
|
3
|
+
`)}`},mr=(e,r)=>I(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),hr=e=>{if(y(e))try{const r=JSON.parse(w(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},vr=e=>{const{cwd:r,environment:n,logger:t}=e,o=mr(r,n),a=hr(o),i=e.current??(a===void 0?void 0:lr);if(i===void 0)return;const s=a===void 0?void 0:fr(gr(a,i));return s!==void 0&&t.info(s),()=>{try{Fe(D(o),{recursive:!0}),E(o,`${JSON.stringify(i,void 0,2)}
|
|
4
|
+
`,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},pr=e=>{const{cwd:r,env:n,logger:t,mintedSecretsFile:o}=e;try{const a=Q(r),i=a?.workerName??U(r),s=e.url??a?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),n!==void 0&&t.info(` env: ${n}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),o!==void 0&&t.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},yr=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Xe)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??P,n=[];for(const t of e.targets){const o=Je(t.exportName),a={args:["build",t.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=se(A(e.cwd),"wrangler",["containers","push",o]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${o} from ${t.buildDir}`);const c=await r(a);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:n,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const u=await r(s);if(u.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${o})`;return e.logger.error(d),{builtTags:n,code:u.code,error:d}}n.push(o)}return{builtTags:n,code:0}},wr=e=>{const n=[L(e),I(e,"package.json")].filter(t=>t!==void 0&&y(t)).map(t=>[t,w(t,"utf8")]);return()=>{for(const[t,o]of n)w(t,"utf8")!==o&&E(t,o,"utf8")}},de="<replace-with-d1-create-id>",W=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,H=(e,r)=>{const n=L(e);if(!n)return;const{parsed:t}=S(n);if(t===void 0)return;const{error:o,merged:a}=ae(t,r),i=o===void 0?a:t,{containers:s,d1_databases:c,vars:u}=i;return{containers:W(s),d1_databases:W(c),vars:typeof u=="object"&&u!==null&&!Array.isArray(u)?u:void 0}},br=/^127(?:\.\d{1,3}){3}$/,$r=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||br.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},kr=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Sr=(e,r,n,t="deploy",o)=>{const a=(H(e,o)?.containers??[]).filter(s=>typeof s?.image=="string"&&kr(s.image));if(a.length===0||n())return;const i=`${t} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},le=e=>y(b(e,F))?F:void 0,Er=(e,r,n="deploy",t)=>{for(const o of Z(e,"lunora",t).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,s=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,u])=>u.kind==="dockerfile"?[{field:`images["${c}"]`,path:u.dockerfilePath}]:[])].find(c=>!y(b(e,c.path)));if(s!==void 0){const c=`${n} blocked: container "${o.exportName}" references a Dockerfile at "${s.path}" that does not exist. Create it or fix the \`${s.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(a?.kind==="build"&&!y(b(e,a.buildDir))){const c=`${n} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Ar=(e,r)=>(H(e,r)?.d1_databases??[]).find(n=>n.database_id===de)?.binding,Rr=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},Cr=(e,r,n="deploy",t)=>{const o=Ar(e,t);if(o===void 0)return;const a=`${n} blocked: the "${o}" D1 binding has a placeholder database_id ("${de}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(a),a},Dr=(e,r,n="deploy",t)=>{const o=H(e,t)?.vars;if(!o)return;const a=Object.entries(o).filter(([,s])=>typeof s=="string"&&$r(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(a.length===0)return;const i=`${n} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},jr=(e,r,n)=>{const t=Cr(e,r.logger,n,r.env);if(t!==void 0)return{code:p.USAGE,error:t};const o=Dr(e,r.logger,n,r.env);if(o!==void 0)return{code:p.USAGE,error:o};const a=Er(e,r.logger,n,r.discoveryCache);if(a!==void 0)return{code:p.USAGE,error:a};const i=Sr(e,r.logger,r.dockerAvailable??Qe,n,r.env);return i===void 0?void 0:{code:p.MISSING_DEPENDENCY,error:i}},q=32,Pr=15e3,_r=5432,Tr=3306,Nr=/[^a-z0-9-]/gu,Ir=/[^A-Za-z0-9]/gu,xr=/-$/u,k=e=>`LUNORA_${e.replaceAll(Ir,"_").toUpperCase()}_URL`,Or=e=>{const r=new Map;for(const n of e){const t=k(n),o=r.get(t);if(o!==void 0)return{bindings:[o,n],variable:t};r.set(t,n)}},G=7,Lr=(e,r)=>{const n=`${e}-${r}`.toLowerCase(),t=n.replaceAll(Nr,"-");if(t===n&&t.length<=q)return t;const o=nr("sha256").update(n).digest("hex").slice(0,G-1);return`${t.slice(0,q-G).replace(xr,"")}-${o}`},K=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Ur=e=>e==="mysql"?Tr:_r,Hr=e=>{try{const r=new URL(e),n=r.protocol.slice(0,-1),t=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(n)||r.hostname===""||t===""?void 0:{database:t,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?Ur(K(n)):Number(r.port),scheme:K(n),user:decodeURIComponent(r.username)}}catch{return}},Mr=(e,r)=>{const n=typeof r?.password=="string"?r.password:"",t=n===""?[]:[n,JSON.stringify(n).slice(1,-1),encodeURIComponent(n)];let o=e;for(const a of t)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},ue=e=>(Array.isArray(e)?e:[]).flatMap((r,n)=>{const{binding:t,id:o}=typeof r=="object"&&r!==null?r:{};return typeof t=="string"&&o===De?[{binding:t,index:n}]:[]}),N=e=>{let r="";try{const{errors:n}=JSON.parse(e.text);r=(n??[]).flatMap(t=>typeof t.message=="string"?[t.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},Fr=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Br=["scheme","host","port","database","user"],Vr=e=>e==="postgresql"?"postgres":e,Y=(e,r)=>{const n=Fr(r);return e==="scheme"?Vr(n):n},z=50,Wr=async(e,r)=>{for(let n=1;n<=z;n+=1){const t=await e(n===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(n)}`);if(!t.ok)throw new Error(`listing Hyperdrive configs failed (${N(t)})`);if(!Array.isArray(t.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=t.body.result.find(i=>i.name===r),a=typeof t.body.result_info=="object"&&t.body.result_info!==null?t.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||n>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(z)} pages, so "${r}" can't be shown to be absent`)},qr=async(e,r,n)=>{const t=await Wr(e,r);if(typeof t?.id=="string"){const i=Br.filter(c=>Y(c,t.origin?.[c])!==Y(c,n[c]));if(i.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${i.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const s=await e(`/hyperdrive/configs/${encodeURIComponent(t.id)}`,{body:JSON.stringify({origin:n}),method:"PATCH"});if(!s.ok)throw new Error(`updating its credentials failed (${N(s)})`);return{id:t.id,reused:!0}}const o=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:n}),method:"POST"});if(!o.ok)throw new Error(`creating it failed (${N(o)})`);const{id:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},Gr=(e,r,n,t)=>r===void 0&&t?`${k(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${k(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:n?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,Kr=async(e,r)=>{const n=Lr(e.workerName,e.binding),{id:t,reused:o}=await qr(async(a,i)=>ar({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Pr)},path:a}),n,e.origin);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${n}" for ${e.binding} → ${e.wranglerPath}`),{id:t,text:ie(r,[...e.path,e.index,"id"],t)}},Yr=e=>e===void 0||e===""?void 0:e,zr=e=>{const r=I(D(e),".wrangler","deploy","config.json");try{const{configPath:n}=JSON.parse(w(r,"utf8"));return typeof n=="string"?ve(D(r),n):void 0}catch{return}},Jr=(e,r,n,t,o)=>{const a=zr(e);if(a===void 0||a===e)return;if(t.built!==t.deployed){o.warn(`the build output ${a} was made for ${t.built===void 0?"the default environment":`"${t.built}"`}, not ${t.deployed===void 0?"the default environment":`"${t.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=S(a)}catch{return}const s=ue(i.parsed?.hyperdrive).find(c=>c.binding===r);s!==void 0&&E(a,ie(i.text,["hyperdrive",s.index,"id"],n),"utf8")},Xr=(e,r)=>{const n=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return n;const t=e.env?.[r]?.name;return typeof t=="string"&&t!==""?t:`${n}-${r}`},M=(e,r)=>{const n=L(e),t=n===void 0?void 0:S(n).parsed;if(n===void 0||t===void 0)return;const o=r===void 0?void 0:t.env?.[r],a=ue(r===void 0?t.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??t.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:Xr(t,r),wranglerPath:n}},Qr=(e,r,n)=>{const t=Or(e.map(({binding:o})=>o));if(t!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${t.bindings.map(a=>`"${a}"`).join(" and ")} both read ${t.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return n.logger.error(o),o}for(const{binding:o,origin:a,supplied:i}of e){const s=Gr(o,a,r,i);if(s!==void 0&&n.dryRun===!0)n.logger.warn(`dry run: ${s} A real deploy stops here.`);else if(s!==void 0){const c=`deploy blocked: ${s}`;return n.logger.error(c),c}}},Zr=async e=>{const r=M(e.cwd,e.wranglerEnvironment);if(r===void 0)return;const{entries:n,path:t,wranglerPath:o}=r,a=e.environment??process.env,{accountId:i,token:s}=or(a,r.accountId),c=n.map(({binding:d})=>{const m=a[k(d)]??"";return{binding:d,origin:Hr(m),supplied:m!==""}}),u=Qr(c,s!==void 0&&i!==void 0,e);if(u!==void 0)return u;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:m,index:g}]of n.entries()){const f=c[d]?.origin;if(!(f===void 0||s===void 0||i===void 0))try{const{id:l,text:h}=await Kr({accountId:i,binding:m,fetch:e.fetch,index:g,logger:e.logger,origin:f,path:t,token:s,workerName:r.workerName,wranglerPath:o},w(o,"utf8"));E(o,h,"utf8"),Jr(o,m,l,{built:Yr(a.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(l){const h=l instanceof Error?l.message:String(l),v=`deploy blocked: the "${m}" Hyperdrive config could not be set up: ${Mr(h,c[d]?.origin)}`;return e.logger.error(v),v}}},et=(e,r)=>{const n=M(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`prepare blocked: the "${n}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${k(n)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(t),t},rt=(e,r)=>{const n=M(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`deploy blocked: the "${n}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(t),t},ge=async(e,r,n,t,o="create")=>{if(t==="cloudflare")return n==="prepare"?et(e,r):r.temporary===!0?rt(e,r):Zr({checkOnly:o==="check",cwd:e,dryRun:r.dryRun,logger:r.logger,wranglerEnvironment:r.env})},tt=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,nt=/https:\/\/[^\s"'<>]+/u,ot=e=>{if(e===void 0)return;const r=tt.exec(e);return r?r[0]:nt.exec(e)?.[0]},J=e=>e===void 0?"":` (--env ${e})`,at=({cwd:e,env:r,logger:n,now:t,url:o})=>{if(o!==void 0)try{const a=Q(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;n.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${J(a.env)}, but this deploy published ${o}${J(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();be(e,{env:r,linkedAt:i,workerName:U(e),workerUrl:o}),n.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},it=async(e,r)=>{const n=new ir({skipAddingFilesFromTsConfig:!0}),t=b(r,"lunora");let o;try{o=pe(n,t)}catch(a){const i=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await sr(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},st=async(e,r)=>{const{info:n}=ee(r,"lunora",e.discoveryCache),t=n?.vectorMetadata??[];if(t.length===0)return;const o=[];for(const s of t){const c=Be(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:s.index,property:s.property,type:c})}if(o.length===0)return;const i=(await Ve({cwd:r,entries:o,exec:se(A(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??P})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},X=5,ct=2e3,dt=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??ce({cwd:r,env:e.env});if(t===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await Ze({attempts:X,baseUrl:t,delayMs:ct,fetchImpl:e.healthFetch,paths:[er,rr],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(X)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},lt=async(e,r,n,t,o,a)=>{await st(e,r);const i=e.migrate?await it(e,r):0;return i===0&&o?.(),{code:i,descriptor:n,mintedSecretsFile:a,validation:t}},ut=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:o,recordArchitecture:a,stdout:i,validation:s})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:ot(i),workerName:U(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:n,validation:s};t.temporary!==!0&&(a?.(),at({cwd:e,env:t.env,logger:t.logger,url:c.url}));const u=await dt(t,e,c.url);return u?.error!==void 0?{code:p.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:u,mintedSecretsFile:n,validation:s}:{...await lt(t,e,r,s,o,n),deployment:c,healthCheck:u}},gt=(e,r,n)=>{const t=b(e,$);if(!y(t))return;let o;try{o=re(w(t,"utf8")).length}catch{return}if(o===0)return;const a=n.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${$} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${n.name} deploys read no secrets. ${$} has ${String(o)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},ft=async(e,r)=>{let n=[];try{n=$e(await te({cache:r,projectRoot:e,schemaDir:x(e)}))}catch{}const t=ke(n).map(a=>a.key);let o=[];try{const a=b(e,$);y(a)&&(o=re(w(a,"utf8")).map(i=>i.key).filter(i=>We(i)))}catch{}return[...new Set([...t,...o])]},mt=async(e,r,n,t)=>{const{logger:o}=r,a=r.spawner??P,i=A(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const u=n.map(g=>({key:g,value:Se()})),d=t.toolchain?.secretBulk;if(d!==void 0&&u.length>=2){const g=j(i,d({environment:r.env,temporary:r.temporary})),f=await a({args:g.args,command:g.command,cwd:e,input:JSON.stringify(Object.fromEntries(u.map(l=>[l.key,l.value])))});if(f.code===0){for(const{key:l}of u)o.success(`generated + pushed ${l}`);return{minted:u,ok:!0}}o.warn(`bulk secret push failed (exit ${String(f.code)}); retrying one key at a time`)}const m=[];for(const{key:g,value:f}of u){const l=c({environment:r.env,key:g,temporary:r.temporary}),h=j(i,l),v=await a({args:h.args,command:h.command,cwd:e,input:f});if(v.code!==0)return o.error(`failed to push secret ${g} (exit ${String(v.code)}); set it manually with \`wrangler secret put ${g}${s}\`.`),{minted:m,ok:!1};m.push({key:g,value:f}),o.success(`generated + pushed ${g}`)}return{minted:m,ok:!0}},ht=/^[\w-]+$/u,_=[".dev.vars",".dev.vars.*","!.dev.vars.example"],vt=/\r?\n/u,pt=(e,r)=>{const n=b(e,".gitignore");try{const t=y(n)?w(n,"utf8"):"",o=new Set(t.split(vt).map(c=>c.trim())),a=_.filter(c=>!o.has(c));if(a.length===0)return;const i=a.some(c=>!c.startsWith("!"))?[...a.filter(c=>!c.startsWith("!")),..._.filter(c=>c.startsWith("!"))]:a,s=t.length>0&&!t.endsWith(`
|
|
5
|
+
`)?`
|
|
6
|
+
`:"";E(n,`${t}${s}
|
|
7
|
+
# Lunora — never commit a minted secret
|
|
8
|
+
${i.join(`
|
|
9
|
+
`)}
|
|
10
|
+
`,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${_.join("` and `")}\` by hand before committing.`)}},yt=(e,r,n)=>{if(n.length===0)return;const t=n.map(s=>s.key).join(", ");if(r.env!==void 0&&!ht.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?$:`${$}.${r.env}`;pt(e,r.logger);const a=b(e,o);let i=y(a)?w(a,"utf8"):"";for(const s of n)i=Ee(i,s.key,s.value);return Ae(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${o}`:`${t}: value(s) recorded in ${o} (kept separate from ${$} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},wt=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??dr)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),u=(await ft(e,r.discoveryCache)).filter(g=>!s.has(g));if(u.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${u.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const g of u.filter(f=>!B(f)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${a}`);const d=u.filter(g=>B(g));if(d.length===0)return{};if(await(r.secretConfirm??cr())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:f}=await mt(e,r,d,t),l=yt(e,r,g);return f?{mintedSecretsFile:l}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:l}}return o.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},fe=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,bt=async(e,r)=>{if(r.dryRun===!0)return;const n=Z(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(n.length===0)return;const t=await yr({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:n});return t.code===0?void 0:t.error??"railpack build failed"},$t=(e,r,n)=>{if(n!==void 0)try{const t=Ie(e,n);t.changed&&r.success(`synced ${String(n.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const o=xe(t.preserved);o!==void 0&&r.info(o)}catch(t){const o=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${o}`)}},kt=async(e,r,n,t,o,a)=>{try{O(t);const i=await te({cache:a,projectRoot:e,schemaDir:x(e)}),s=Te(e,i,{environment:o,target:t}),c=s.wranglerPath??"wrangler.jsonc";if(s.added.length>0&&r.success(`provisioned bindings: ${s.added.join(", ")} → ${c}`),s.updated.length>0&&r.success(`updated bindings: ${s.updated.join(", ")} → ${c}`),s.devConfig!==void 0){const{added:u,path:d,updated:m}=s.devConfig;r.success(`dev sidecar bindings: ${[...u,...m].join(", ")} → ${d}`)}for(const u of s.warnings)r.warn(u)}catch(i){const s=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${s}`)}try{const i=Ne(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const s=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${s}`)}$t(e,r,n)},St=async(e,r,n,t,o,a,i,s,c)=>{let u;r?(u=new Oe({name:"dots"}),u.start("running codegen")):n.info("running codegen");try{const d=ye({apiSpec:t,lazyFunctions:o,projectRoot:e,target:a,..._e(e)});u?.succeed("codegen complete"),u||n.success("codegen complete");const m=Ue(d.platformDiagnostics,n);if(m.errors.length>0)return{error:m.errors.join("; ")};const{errorAdvisories:g,names:f,shouldBlock:l}=He(d.advisories,c);if(l){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(v),{error:v}}const h=await Ce({cwd:e,logger:n,spawner:i,stdoutToStderr:s});return h.error!==void 0?{error:h.error}:{result:d}}catch(d){u?.failed("codegen failed");const m=d instanceof Error?d.message:String(d);return n.error(`codegen failed: ${m}`),{error:`codegen failed: ${m}`}}},Et=(e,r)=>({dryRun:r.dryRun,entry:le(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),me=(e,r,n)=>{const{toolchain:t}=n;if(t===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);const o=Et(e,r);return oe(n,e,"deploy",a=>t.deploy({...o,configPath:a}))},At=(e,r,n)=>{const t=me(e,r,n),o=le(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${n.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},T=(e,r)=>({code:p.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Rt=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},Ct=(e,r,n)=>{const t=r.format==="json",o=r.dryRun!==!0,a=At(e,r,n),i=j(A(e),a);return{args:i.args,captureStdout:o&&!t,captureStdoutSilently:o&&t,command:i.command,cwd:e,stdoutToStderr:t&&!o}},Dt=async(e,r)=>{const n=e.cwd??process.cwd(),t=fe(e),o=Le(e),a={problems:[],wranglerPath:void 0},i=ze(n,e.target);if(i.target===void 0){const l=i.error??"unknown deploy target";return e.logger.error(l),{error:l,validation:a}}const{target:s}=i;try{me(n,e,O(s))}catch(l){const h=l instanceof Error?l.message:String(l);return e.logger.error(h),{error:h,target:s,validation:a}}let c;if(!e.skipCodegen){const l=await St(n,t,e.logger,e.apiSpec,ne(e.lazyFunctions),s,e.spawner,e.format==="json",o);if(l.error!==void 0)return{error:l.error,target:s,validation:a};c=l.result,e.discoveryCache?.clear()}let u;if(c!==void 0){const l=tr({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(l.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:l.reason},target:s,validation:a};u=l.rebless}const d=c&&vr({current:c.architecture,cwd:n,environment:e.env,logger:e.logger});await kt(n,e.logger,c?.cronTriggers,s,e.env,e.discoveryCache);const m=await ge(n,e,r,s,"check");if(m!==void 0)return{error:m,target:s,validation:a};const g=jr(n,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const f=Pe({environment:e.env,projectRoot:n});return Rt(f,e.logger)?{error:"wrangler validation failed",target:s,validation:f}:{codegen:c,reblessSchemaBaseline:u,recordArchitecture:d,target:s,validation:f}},jt=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Pt=async(e,r,n,t)=>{const{error:o,services:a}=we(e);if(o!==void 0)return o;if(a.length===0)return;const{toolchain:i}=n,s=i===void 0?`target "${n.id}" has no deploy command`:jt(r);if(s!==void 0||i===void 0){const d=a.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=A(e),u=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of u){const m=D(d.wranglerPath);let g;try{g=oe(n,m,"deploy",h=>i.deploy({configPath:h??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(h){return`service ${d.name} (${d.worker}): ${h instanceof Error?h.message:String(h)}`}g.commit();const f=j(c,g.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${f.command} ${f.args.join(" ")}`);const l=await t({args:f.args,command:f.command,cwd:m,stdoutToStderr:r.format==="json"});if(l.code!==0)return`service ${d.name} (${d.worker}): ${f.command} ${f.args.join(" ")} exited ${String(l.code)} — stopping before the app`}},_t=async(e,r,n,t)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:S(e).parsed,a=(n===void 0?void 0:o?.env?.[n]?.account_id)??o?.account_id,i=await Ge({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Tt=e=>e.dryRun!==!0&&e.temporary!==!0,Nt=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",It=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},xt=(e,r,n)=>{const t=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&n==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=It(o);r.error(a),t.push(a)}return t},he=async(e,r,n,t,o,a,i)=>{const s=n==="cloudflare"&&r!==void 0?S(r).parsed:void 0;if(s===void 0)return;const c=(ae(s,t).merged.artifacts??[]).flatMap(l=>typeof l?.binding=="string"&&typeof l.namespace=="string"?[{binding:l.binding,namespace:l.namespace}]:[]),u=c.length===0?void 0:ee(e,x(e),a).info?.jurisdiction;if(u===void 0)return;const d=[...new Map(c.map(l=>[l.namespace,l])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${u}") of Artifacts namespace ${d.map(l=>`"${l.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const m=(t===void 0?void 0:s.env?.[t]?.account_id)??s.account_id,g=await Promise.all(d.map(async l=>qe({...l,accountId:m,create:i==="create",jurisdiction:u,missingOk:i==="defer"||i==="preview"}))),f=xt(g,o,i);return f.length===0?void 0:f.join(`
|
|
11
|
+
`)},Ot=async(e,r,n,t,o,a)=>(Tt(r)?await he(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0)??await ge(e,r,"deploy",o)??await Pt(e,r,n,t),Lt=async e=>{const r={...e,discoveryCache:e.discoveryCache??Re()},n=r.cwd??process.cwd(),t=fe(r),o=await Dt(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:p.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const v=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return T(o.error,{...v,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,i=O(o.target),s=Rr(r)??await he(n,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Nt(r));if(s!==void 0)return T(s);const c=i.toolchain?.prebuildsContainerImages===!0?await bt(n,r):void 0;if(c!==void 0)return T(c);gt(n,r.logger,i),je(n,v=>{r.logger.warn(v)}),await _t(a.wranglerPath,o.target,r.env,r.logger);const{error:u,mintedSecretsFile:d}=await wt(n,r,t,i);if(u!==void 0)return r.logger.error(u),{code:p.USAGE,descriptor:void 0,error:u,mintedSecretsFile:d,validation:a};const m=r.spawner??P,g=await Ot(n,r,i,m,o.target,a.wranglerPath);if(g!==void 0)return{code:p.FAILURE,descriptor:void 0,error:g,mintedSecretsFile:d,validation:a};const f=Ct(n,r,i);r.logger.info(`deploying via ${f.command} ${f.args.join(" ")}`);const l=await m(f);return f.captureStdoutSilently===!0&&l.stdout!==void 0&&l.stdout!==""&&process.stderr.write(l.stdout),l.code!==0?{code:l.code,descriptor:f,mintedSecretsFile:d,validation:a}:{...await ut({...o,cwd:n,descriptor:f,mintedSecretsFile:d,options:r,stdout:l.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Ut=async e=>{const{logger:r}=e,n=e.dryRun===!0?wr(e.cwd??process.cwd()):void 0;let t;try{if(t=await Lt({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:o}=Ke({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});o!==void 0&&(r.error(o),t={...t,code:p.USAGE})}}finally{n?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)pr({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const o=t.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return t},fn=Ye(async({cwd:e,format:r,logger:n,options:t})=>{const o=await Ut({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:Me(t.apiSpec),lazyFunctions:ne(t.lazyFunctions),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:n,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:ce({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:o.code,data:{deployment:o.deployment,healthCheck:o.healthCheck,mintedSecretsFile:o.mintedSecretsFile,schemaDrift:o.schemaDrift,validation:o.validation},error:o.error}});export{fn as execute,kt as provisionBindings,Ut as runDeployCommand,Dt as runPreDeployPipeline};
|