@lunora/cli 1.0.0-alpha.21 → 1.0.0-alpha.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bin.mjs +2 -10
  5. package/dist/index.d.mts +731 -341
  6. package/dist/index.d.ts +731 -341
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +4 -22
  10. package/dist/packem_chunks/handler11.mjs +2 -192
  11. package/dist/packem_chunks/handler12.mjs +1 -131
  12. package/dist/packem_chunks/handler13.mjs +1 -65
  13. package/dist/packem_chunks/handler14.mjs +1 -58
  14. package/dist/packem_chunks/handler15.mjs +1 -79
  15. package/dist/packem_chunks/handler16.mjs +3 -43
  16. package/dist/packem_chunks/handler17.mjs +1 -105
  17. package/dist/packem_chunks/handler18.mjs +1 -170
  18. package/dist/packem_chunks/handler19.mjs +7 -89
  19. package/dist/packem_chunks/handler2.mjs +2 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  21. package/dist/packem_chunks/handler21.mjs +2 -311
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +3 -0
  24. package/dist/packem_chunks/handler24.mjs +1 -0
  25. package/dist/packem_chunks/handler25.mjs +99 -0
  26. package/dist/packem_chunks/handler26.mjs +10 -0
  27. package/dist/packem_chunks/handler3.mjs +1 -204
  28. package/dist/packem_chunks/handler4.mjs +1 -33
  29. package/dist/packem_chunks/handler5.mjs +1 -49
  30. package/dist/packem_chunks/handler6.mjs +1 -91
  31. package/dist/packem_chunks/handler7.mjs +3 -42
  32. package/dist/packem_chunks/handler8.mjs +1 -174
  33. package/dist/packem_chunks/handler9.mjs +1 -16
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -500
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +1 -504
  37. package/dist/packem_chunks/runInitCommand.mjs +118 -1383
  38. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-BKhYrmpZ.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Nf7GsE6v.mjs +1 -0
  43. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
  44. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
  45. package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  47. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  49. package/dist/packem_shared/cli-CrC0a7dH.mjs +3 -0
  50. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  51. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  52. package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
  53. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  54. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  55. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  56. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
  57. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  58. package/dist/packem_shared/import-CrVGrOt3.mjs +12 -0
  59. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  60. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  61. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  62. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  63. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  64. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  65. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  66. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  67. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  68. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  69. package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
  70. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  71. package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
  79. package/package.json +39 -17
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +65 -9
  82. package/skills/lunora-functions/SKILL.md +38 -3
  83. package/skills/lunora-migration-helper/SKILL.md +70 -17
  84. package/skills/lunora-performance-audit/SKILL.md +36 -6
  85. package/skills/lunora-quickstart/SKILL.md +90 -24
  86. package/skills/lunora-realtime/SKILL.md +58 -30
  87. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  88. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  89. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  90. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  91. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  92. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  93. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  94. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  95. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  96. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  97. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  98. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  99. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  100. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  101. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  102. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  103. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  104. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  105. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  106. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  107. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  108. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  109. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  110. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,504 +1 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { runCodegen, discoverMigrations } from '@lunora/codegen';
3
- import { readLinkedProject, writeLinkedProject, validateWranglerProject, inferLunoraBindings, reconcileWranglerBindings, DEV_VARS_FILE, parseDevVariableEntries, findWranglerFile, readWranglerJsonc, discoverContainerInfo } from '@lunora/config';
4
- import { join } from '@visulima/path';
5
- import { Spinner } from '@visulima/spinner';
6
- import { Project } from 'ts-morph';
7
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
8
- import { r as readWranglerName } from '../packem_shared/wrangler-name-cy4yhm9j.mjs';
9
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
10
- import { a as isRailpackAvailable, i as isDockerAvailable } from '../packem_shared/docker-hMQ97KSQ.mjs';
11
- import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
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 { runMigrateDataCommand } from './runMigrateGenerateCommand.mjs';
17
-
18
- const WORKERS_DEV_URL = /https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u;
19
- const ANY_HTTPS_URL = /https:\/\/[^\s"'<>]+/u;
20
- const parseDeployedUrl = (output) => {
21
- const workersDev = WORKERS_DEV_URL.exec(output);
22
- if (workersDev) {
23
- return workersDev[0];
24
- }
25
- return ANY_HTTPS_URL.exec(output)?.[0];
26
- };
27
- const autoLinkFromDeployOutput = ({ cwd, env, logger, now, output }) => {
28
- if (output === void 0 || readLinkedProject(cwd) !== void 0) {
29
- return;
30
- }
31
- const url = parseDeployedUrl(output);
32
- if (url === void 0) {
33
- return;
34
- }
35
- try {
36
- const stamp = (now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
37
- writeLinkedProject(cwd, { env, linkedAt: stamp, workerName: readWranglerName(cwd), workerUrl: url });
38
- logger.success(`link: recorded ${url} in .lunora/project.json (run \`lunora link\` to change)`);
39
- } catch {
40
- }
41
- };
42
-
43
- const renderDeploySummary = (inputs) => {
44
- const { cwd, env, logger, migrated } = inputs;
45
- try {
46
- const link = readLinkedProject(cwd);
47
- const workerName = link?.workerName ?? readWranglerName(cwd);
48
- logger.success("deploy complete");
49
- logger.info(` worker: ${workerName ?? "(see wrangler output above)"}`);
50
- if (env !== void 0) {
51
- logger.info(` env: ${env}`);
52
- }
53
- if (link?.workerUrl === void 0) {
54
- logger.info(" url: run `lunora link --url <https://your-worker>` to record it");
55
- } else {
56
- logger.info(` url: ${link.workerUrl}`);
57
- }
58
- if (migrated) {
59
- logger.info(" migrations: applied");
60
- }
61
- logger.info(" studio: lunora view --remote");
62
- logger.info(" logs: lunora logs");
63
- } catch {
64
- }
65
- };
66
-
67
- const buildRailpackImages = async (options) => {
68
- if (options.targets.length === 0) {
69
- return { builtTags: [], code: 0 };
70
- }
71
- if (!(options.railpackAvailable ?? isRailpackAvailable)()) {
72
- 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.";
73
- options.logger.error(message);
74
- return { builtTags: [], code: 1, error: message };
75
- }
76
- const spawner = options.spawner ?? defaultSpawner;
77
- const builtTags = [];
78
- for (const target of options.targets) {
79
- const tag = containerBuildTag(target.exportName);
80
- const build = { args: ["build", target.buildDir, "--name", tag], command: "railpack", cwd: options.cwd };
81
- const push = { args: ["exec", "wrangler", "containers", "push", tag], command: "pnpm", cwd: options.cwd };
82
- options.logger.info(`railpack: building "${target.exportName}" → ${tag} from ${target.buildDir}`);
83
- const buildResult = await spawner(build);
84
- if (buildResult.code !== 0) {
85
- const message = `railpack build failed for container "${target.exportName}" (${target.buildDir})`;
86
- options.logger.error(message);
87
- return { builtTags, code: buildResult.code, error: message };
88
- }
89
- options.logger.info(`railpack: pushing ${tag} to the Cloudflare Registry`);
90
- const pushResult = await spawner(push);
91
- if (pushResult.code !== 0) {
92
- const message = `wrangler containers push failed for "${target.exportName}" (${tag})`;
93
- options.logger.error(message);
94
- return { builtTags, code: pushResult.code, error: message };
95
- }
96
- builtTags.push(tag);
97
- }
98
- return { builtTags, code: 0 };
99
- };
100
-
101
- const D1_PLACEHOLDER_ID = "<replace-with-d1-create-id>";
102
- const ORIGIN_VAR_NAMES = ["LUNORA_ORIGIN_URL", "LUNORA_WORKER_ORIGIN", "AUTH_URL"];
103
- const isLocalhostUrl = (value) => {
104
- try {
105
- const { hostname } = new URL(value);
106
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
107
- } catch {
108
- return false;
109
- }
110
- };
111
- const isLocalImagePath = (image) => image.startsWith("./") || image.startsWith("../") || image.startsWith("/") || image.includes("Dockerfile");
112
- const checkContainerDockerPreflight = (cwd, logger, dockerAvailable) => {
113
- const wranglerPath = findWranglerFile(cwd);
114
- if (!wranglerPath) {
115
- return void 0;
116
- }
117
- const { parsed } = readWranglerJsonc(wranglerPath);
118
- const localImages = (parsed?.containers ?? []).filter((entry) => typeof entry?.image === "string" && isLocalImagePath(entry.image));
119
- if (localImages.length === 0 || dockerAvailable()) {
120
- return void 0;
121
- }
122
- 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.`;
123
- logger.error(message);
124
- return message;
125
- };
126
- const resolveComposedWorkerEntry = (cwd) => existsSync(join(cwd, "src", "worker.ts")) ? "src/worker.ts" : void 0;
127
- const checkContainerSourcesExist = (cwd, logger) => {
128
- for (const container of discoverContainerInfo(cwd, "lunora").containers) {
129
- const { image } = container;
130
- if (image.kind === "dockerfile" && !existsSync(join(cwd, image.dockerfilePath))) {
131
- 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.`;
132
- logger.error(message);
133
- return message;
134
- }
135
- if (image.kind === "build" && !existsSync(join(cwd, image.buildDir))) {
136
- 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.`;
137
- logger.error(message);
138
- return message;
139
- }
140
- }
141
- return void 0;
142
- };
143
- const isInteractive = (options) => {
144
- if (isJsonFormat(options.format)) {
145
- return false;
146
- }
147
- if (options.interactive !== void 0) {
148
- return options.interactive;
149
- }
150
- return process.stdout.isTTY && !process.env.CI;
151
- };
152
- const findD1PlaceholderBinding = (cwd) => {
153
- const wranglerPath = findWranglerFile(cwd);
154
- if (!wranglerPath) {
155
- return void 0;
156
- }
157
- const { parsed } = readWranglerJsonc(wranglerPath);
158
- if (!parsed) {
159
- return void 0;
160
- }
161
- const placeholder = (parsed.d1_databases ?? []).find((entry) => entry.database_id === D1_PLACEHOLDER_ID);
162
- return placeholder?.binding;
163
- };
164
- const buildContainerImages = async (cwd, options) => {
165
- const targets = discoverContainerInfo(cwd, "lunora").containers.filter((container) => container.image.kind === "build").map((container) => {
166
- return { buildDir: container.image.buildDir, exportName: container.exportName };
167
- });
168
- if (targets.length === 0) {
169
- return void 0;
170
- }
171
- const result = await buildRailpackImages({
172
- cwd,
173
- logger: options.logger,
174
- railpackAvailable: options.railpackAvailable,
175
- spawner: options.spawner,
176
- targets
177
- });
178
- return result.code === 0 ? void 0 : result.error ?? "railpack build failed";
179
- };
180
- const provisionBindings = async (cwd, logger) => {
181
- try {
182
- const inferred = await inferLunoraBindings({ projectRoot: cwd });
183
- const reconciled = reconcileWranglerBindings(cwd, inferred);
184
- if (reconciled.changed) {
185
- logger.success(`provisioned bindings: ${reconciled.added.join(", ")} → ${reconciled.wranglerPath ?? "wrangler.jsonc"}`);
186
- }
187
- for (const warning of reconciled.warnings) {
188
- logger.warn(warning);
189
- }
190
- } catch (error) {
191
- const message = error instanceof Error ? error.message : String(error);
192
- logger.warn(`binding inference skipped: ${message}`);
193
- }
194
- };
195
- const warnDevVariablesNotPushed = (cwd, logger) => {
196
- const devVariablesPath = join(cwd, DEV_VARS_FILE);
197
- if (!existsSync(devVariablesPath)) {
198
- return;
199
- }
200
- let keyCount;
201
- try {
202
- keyCount = parseDevVariableEntries(readFileSync(devVariablesPath, "utf8")).length;
203
- } catch {
204
- return;
205
- }
206
- if (keyCount === 0) {
207
- return;
208
- }
209
- logger.warn(
210
- `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.`
211
- );
212
- };
213
- const runPostDeployMigrations = async (options, cwd) => {
214
- const project = new Project({ skipAddingFilesFromTsConfig: true });
215
- const lunoraDirectory = join(cwd, "lunora");
216
- let migrations;
217
- try {
218
- migrations = discoverMigrations(project, lunoraDirectory);
219
- } catch (error) {
220
- const message = error instanceof Error ? error.message : String(error);
221
- options.logger.warn(`--migrate: could not discover migrations (${message}); skipping`);
222
- return 0;
223
- }
224
- if (migrations.length === 0) {
225
- options.logger.info("--migrate: no data migrations declared in lunora/");
226
- return 0;
227
- }
228
- options.logger.info(`--migrate: running ${String(migrations.length)} migration(s) against deployed worker`);
229
- for (const migration of migrations) {
230
- options.logger.info(`--migrate: up "${migration.id}" (table "${migration.table}")`);
231
- const migrateOptions = {
232
- cwd,
233
- fetchImpl: options.fetchImpl,
234
- id: migration.id,
235
- logger: options.logger,
236
- // A `--migrate-url` is always set by this point (guarded above), so this
237
- // is a production migration — gate it behind the operator's explicit
238
- // `--migrate-yes`/`--yes` rather than auto-confirming.
239
- prod: true,
240
- subcommand: "up",
241
- token: options.migrateToken,
242
- url: options.migrateUrl,
243
- yes: options.migrateYes === true
244
- };
245
- const migrateResult = await runMigrateDataCommand(migrateOptions);
246
- if (migrateResult.code !== 0) {
247
- options.logger.error(`--migrate: migration "${migration.id}" failed — see output above`);
248
- return migrateResult.code;
249
- }
250
- options.logger.success(`--migrate: "${migration.id}" applied`);
251
- }
252
- return 0;
253
- };
254
- const validateMigrateDeployPreflight = (options) => {
255
- if (!options.migrate || options.dryRun || options.preview) {
256
- return void 0;
257
- }
258
- if (options.migrateUrl === void 0) {
259
- const message = "--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";
260
- options.logger.error(message);
261
- return message;
262
- }
263
- if (options.migrateYes !== true) {
264
- const message = "--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";
265
- options.logger.error(message);
266
- return message;
267
- }
268
- if ((options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === void 0 || (options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === "") {
269
- const message = "admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";
270
- options.logger.error(message);
271
- return message;
272
- }
273
- return void 0;
274
- };
275
- const runCodegenStep = (cwd, interactive, logger, apiSpec) => {
276
- let codegenSpinner;
277
- if (interactive) {
278
- codegenSpinner = new Spinner({ name: "dots" });
279
- codegenSpinner.start("running codegen");
280
- } else {
281
- logger.info("running codegen");
282
- }
283
- try {
284
- const result = runCodegen({ apiSpec, projectRoot: cwd });
285
- codegenSpinner?.succeed("codegen complete");
286
- if (!codegenSpinner) {
287
- logger.success("codegen complete");
288
- }
289
- return { result };
290
- } catch (error) {
291
- codegenSpinner?.failed("codegen failed");
292
- const message = error instanceof Error ? error.message : String(error);
293
- logger.error(`codegen failed: ${message}`);
294
- return { error: `codegen failed: ${message}` };
295
- }
296
- };
297
- const checkD1Placeholder = (cwd, logger) => {
298
- const placeholderBinding = findD1PlaceholderBinding(cwd);
299
- if (placeholderBinding === void 0) {
300
- return void 0;
301
- }
302
- 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.`;
303
- logger.error(message);
304
- return message;
305
- };
306
- const checkLocalhostOriginVariables = (cwd, logger) => {
307
- const wranglerPath = findWranglerFile(cwd);
308
- if (!wranglerPath) {
309
- return void 0;
310
- }
311
- const { parsed } = readWranglerJsonc(wranglerPath);
312
- const variables = parsed?.vars;
313
- if (!variables) {
314
- return void 0;
315
- }
316
- const offenders = ORIGIN_VAR_NAMES.filter((name) => typeof variables[name] === "string" && isLocalhostUrl(variables[name]));
317
- if (offenders.length === 0) {
318
- return void 0;
319
- }
320
- 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.`;
321
- logger.error(message);
322
- return message;
323
- };
324
- const finalizeSuccessfulDeploy = async (options, cwd, descriptor, validation, reblessSchemaBaseline) => {
325
- if (options.migrate) {
326
- const migrateCode = await runPostDeployMigrations(options, cwd);
327
- if (migrateCode === 0) {
328
- reblessSchemaBaseline?.();
329
- }
330
- return { code: migrateCode, descriptor, validation };
331
- }
332
- reblessSchemaBaseline?.();
333
- return { code: 0, descriptor, validation };
334
- };
335
- const runPreDeployGates = async (cwd, options) => {
336
- const d1Error = checkD1Placeholder(cwd, options.logger);
337
- if (d1Error !== void 0) {
338
- return d1Error;
339
- }
340
- const localhostOriginError = checkLocalhostOriginVariables(cwd, options.logger);
341
- if (localhostOriginError !== void 0) {
342
- return localhostOriginError;
343
- }
344
- const sourceError = checkContainerSourcesExist(cwd, options.logger);
345
- if (sourceError !== void 0) {
346
- return sourceError;
347
- }
348
- const dockerError = checkContainerDockerPreflight(cwd, options.logger, options.dockerAvailable ?? isDockerAvailable);
349
- if (dockerError !== void 0) {
350
- return dockerError;
351
- }
352
- return buildContainerImages(cwd, options);
353
- };
354
- const buildWranglerDeployArgs = (cwd, options) => {
355
- const args = options.preview ? ["exec", "wrangler", "versions", "upload"] : ["exec", "wrangler", "deploy"];
356
- const composedEntry = resolveComposedWorkerEntry(cwd);
357
- if (composedEntry !== void 0) {
358
- args.push(composedEntry);
359
- options.logger.info(`class-B composition: deploying ${composedEntry} (overrides wrangler main)`);
360
- }
361
- if (options.env !== void 0) {
362
- args.push("--env", options.env);
363
- }
364
- if (options.temporary) {
365
- args.push("--temporary");
366
- options.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL");
367
- }
368
- if (options.dryRun) {
369
- args.push("--dry-run");
370
- options.logger.info("dry run: validating + bundling without publishing");
371
- }
372
- if (options.outDir !== void 0) {
373
- args.push("--outdir", options.outDir, "--metafile");
374
- options.logger.info(`build artifact: emitting bundle to ${options.outDir}`);
375
- }
376
- return args;
377
- };
378
- const executeDeploy = async (options) => {
379
- const cwd = options.cwd ?? process.cwd();
380
- const interactive = isInteractive(options);
381
- let codegen;
382
- if (!options.skipCodegen) {
383
- const codegenStep = runCodegenStep(cwd, interactive, options.logger, options.apiSpec);
384
- if (codegenStep.error !== void 0) {
385
- return {
386
- code: 1,
387
- descriptor: void 0,
388
- error: codegenStep.error,
389
- validation: { problems: [], wranglerPath: void 0 }
390
- };
391
- }
392
- codegen = codegenStep.result;
393
- }
394
- let reblessSchemaBaseline;
395
- if (codegen !== void 0) {
396
- const gate = runSchemaDriftGate({
397
- allowDrift: options.allowSchemaDrift === true,
398
- codegen,
399
- logger: options.logger,
400
- updateBaseline: options.updateSchemaBaseline === true
401
- });
402
- if (gate.blocked) {
403
- return {
404
- code: 1,
405
- descriptor: void 0,
406
- error: "schema drift gate blocked deploy",
407
- schemaDrift: { blocked: true, reason: gate.reason },
408
- validation: { problems: [], wranglerPath: void 0 }
409
- };
410
- }
411
- reblessSchemaBaseline = gate.rebless;
412
- }
413
- await provisionBindings(cwd, options.logger);
414
- const migratePreflightError = validateMigrateDeployPreflight(options);
415
- if (migratePreflightError !== void 0) {
416
- return { code: 1, descriptor: void 0, error: migratePreflightError, validation: { problems: [], wranglerPath: void 0 } };
417
- }
418
- const preflightError = await runPreDeployGates(cwd, options);
419
- if (preflightError !== void 0) {
420
- return { code: 1, descriptor: void 0, error: preflightError, validation: { problems: [], wranglerPath: void 0 } };
421
- }
422
- const validation = validateWranglerProject({ projectRoot: cwd });
423
- if (validation.problems.length > 0) {
424
- options.logger.error("wrangler.jsonc validation failed:");
425
- for (const problem of validation.problems) {
426
- options.logger.error(` - ${problem}`);
427
- }
428
- return {
429
- code: 1,
430
- descriptor: void 0,
431
- error: "wrangler validation failed",
432
- validation
433
- };
434
- }
435
- warnDevVariablesNotPushed(cwd, options.logger);
436
- const shouldAutoLink = !isJsonFormat(options.format) && options.dryRun !== true && options.preview !== true && readLinkedProject(cwd) === void 0;
437
- const descriptor = {
438
- args: buildWranglerDeployArgs(cwd, options),
439
- captureStdout: shouldAutoLink,
440
- command: "pnpm",
441
- cwd,
442
- // In `--format json` mode stdout is reserved for the single JSON document,
443
- // so route wrangler's progress + deployed-URL output to stderr instead.
444
- stdoutToStderr: isJsonFormat(options.format)
445
- };
446
- options.logger.info(`deploying via ${descriptor.command} ${descriptor.args.join(" ")}`);
447
- const spawner = options.spawner ?? defaultSpawner;
448
- const result = await spawner(descriptor);
449
- if (result.code !== 0) {
450
- return { code: result.code, descriptor, validation };
451
- }
452
- if (options.dryRun) {
453
- return { code: 0, descriptor, validation };
454
- }
455
- if (options.preview) {
456
- return { code: 0, descriptor, validation };
457
- }
458
- autoLinkFromDeployOutput({ cwd, env: options.env, logger: options.logger, output: result.stdout });
459
- return finalizeSuccessfulDeploy(options, cwd, descriptor, validation, reblessSchemaBaseline);
460
- };
461
- const runDeployCommand = async (options) => {
462
- const formatError = validateOutputFormat("deploy", options.format);
463
- if (formatError !== void 0) {
464
- options.logger.error(formatError);
465
- return { code: 1, descriptor: void 0, error: formatError, validation: { problems: [], wranglerPath: void 0 } };
466
- }
467
- const result = await executeDeploy({ ...options, logger: loggerForFormat(options.format, options.logger) });
468
- if (isJsonFormat(options.format)) {
469
- printJson(result);
470
- return result;
471
- }
472
- if (result.code === 0 && options.dryRun !== true && options.preview !== true) {
473
- renderDeploySummary({ cwd: options.cwd ?? process.cwd(), env: options.env, logger: options.logger, migrated: options.migrate === true });
474
- } else if (result.code === 0 && options.preview === true) {
475
- options.logger.success("preview version uploaded — see the preview URL in the wrangler output above");
476
- }
477
- return result;
478
- };
479
- const execute = defineHandler(async ({ cwd, logger, options }) => {
480
- const result = await runDeployCommand({
481
- allowSchemaDrift: options.allowSchemaDrift === true,
482
- apiSpec: parseApiSpec(options.apiSpec),
483
- cwd,
484
- dryRun: options.dryRun === true,
485
- env: options.env,
486
- format: options.format,
487
- logger,
488
- migrate: options.migrate === true,
489
- migrateToken: options.migrateToken,
490
- // Fall back to the `.lunora/project.json` link so a linked checkout no
491
- // longer needs --migrate-url repeated on every `deploy --migrate`.
492
- migrateUrl: resolveWorkerUrl({ cwd, url: options.migrateUrl }),
493
- migrateYes: options.migrateYes === true,
494
- preview: options.preview === true,
495
- // `--prebuilt` trusts a prior `lunora build`/`prepare`: skip codegen (and
496
- // thus the drift gate, which has no fresh snapshot to measure).
497
- skipCodegen: options.prebuilt === true,
498
- temporary: options.temporary === true,
499
- updateSchemaBaseline: options.updateSchemaBaseline === true
500
- });
501
- return { code: result.code };
502
- });
503
-
504
- export { execute, runDeployCommand };
1
+ import{existsSync as p,readFileSync as S}from"node:fs";import{runCodegen as F,discoverMigrations as O}from"@lunora/codegen";import{readLinkedProject as L,writeLinkedProject as H,execArgsFor as w,detectPackageManager as k,discoverContainerInfo as N,DEV_VARS_FILE as v,parseDevVariableEntries as T,isMintableSecretKey as E,runPostCodegenHook as M,resolveDeployDriver as D,inferLunoraBindings as _,packageNamesFromBindings as W,requiredSecrets as B,generateSecretValue as V,upsertDevVariableLine as K,writeDevVariablesFileAtomically as q,discoverSchemaInfo as Y}from"@lunora/config";import{validateWranglerProject as G,reconcileWranglerBindings as z,reconcileWranglerCompatibilityDate as J,reconcileWranglerCrons as Q,findWranglerFile as X,readWranglerJsonc as Z}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as ee}from"@visulima/spinner";import{Project as re}from"ts-morph";import{i as te,m as ae,e as ne}from"../packem_shared/vectorize-metadata-DbziRKpX.mjs";import{r as oe,e as ie}from"../packem_shared/advisory-gate-Cl8IEFIj.mjs";import{p as se}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as R}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{d as ce}from"../packem_shared/command-DwC11Cwe.mjs";import{r as le}from"../packem_shared/deploy-target-D9GPy_tq.mjs";import{a as de,i as ue}from"../packem_shared/docker-DpVxvYpL.mjs";import{r as ge,p as me,H as fe,a as he}from"../packem_shared/schema-drift-gate-DARCKocg.mjs";import{v as ve,l as pe,i as b,p as ye}from"../packem_shared/output-format-DfogXx0p.mjs";import{r as we}from"../packem_shared/platform-diagnostics-uOXqysk3.mjs";import{containerBuildTag as ke}from"@lunora/container";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{a as j}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{c as be}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{l as $e}from"../packem_shared/wrangler-secrets-CCdt0mUl.mjs";import{runMigrateDataCommand as Se}from"./runMigrateGenerateCommand.mjs";const De=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Re=/https:\/\/[^\s"'<>]+/u,Ce=e=>{if(e===void 0)return;const r=De.exec(e);return r?r[0]:Re.exec(e)?.[0]},P=e=>e===void 0?"":` (--env ${e})`,Ae=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=L(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${P(o.env)}, but this deploy published ${n}${P(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();H(e,{env:r,linkedAt:i,workerName:R(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Ee=e=>{const{cwd:r,env:a,logger:t,migrated:n,mintedSecretsFile:o}=e;try{const i=L(r),s=i?.workerName??R(r),c=e.url??i?.workerUrl;t.success("deploy complete"),t.info(` worker: ${s??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),c===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${c}`),n&&t.info(" migrations: applied"),o!==void 0&&t.info(` secrets: generated value(s) recorded in ${o}`),t.info(" studio: lunora view --remote"),t.info(" logs: lunora logs")}catch{}},Pe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??de)()){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??$,a=[];for(const t of e.targets){const n=ke(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=w(k(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},I="<replace-with-d1-create-id>",C=e=>{const r=X(e);return r?Z(r).parsed:void 0},xe=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],Le=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},Ne=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Te=(e,r,a,t="deploy")=>{const n=(C(e)?.containers??[]).filter(i=>typeof i?.image=="string"&&Ne(i.image));if(n.length===0||a())return;const o=`${t} blocked: wrangler.jsonc declares ${String(n.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(o),o},_e=e=>p(h(e,"src","worker.ts"))?"src/worker.ts":void 0,je=(e,r,a="deploy")=>{for(const t of N(e,"lunora").containers){const{image:n}=t;if(n.kind==="dockerfile"&&!p(h(e,n.dockerfilePath))){const o=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!p(h(e,n.buildDir))){const o=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},U=e=>b(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ie=e=>(C(e)?.d1_databases??[]).find(r=>r.database_id===I)?.binding,Ue=async(e,r)=>{const a=N(e,"lunora").containers.filter(n=>n.image.kind==="build").map(n=>({buildDir:n.image.buildDir,exportName:n.exportName}));if(a.length===0)return;const t=await Pe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},Fe=(e,r,a)=>{if(a!==void 0)try{const t=Q(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Oe=async(e,r,a,t,n)=>{try{D(t);const o=await _({projectRoot:e}),i=z(e,o,n);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const s of i.warnings)r.warn(s)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=J(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}Fe(e,r,a)},He=(e,r)=>{const a=h(e,v);if(!p(a))return;let t;try{t=T(S(a,"utf8")).length}catch{return}t!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${v} has ${String(t)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Me=async e=>{let r=[];try{r=W(await _({projectRoot:e}))}catch{}const a=B(r).map(n=>n.key);let t=[];try{const n=h(e,v);p(n)&&(t=T(S(n,"utf8")).map(o=>o.key).filter(o=>te(o)))}catch{}return[...new Set([...a,...t])]},We=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=k(e),s=r.env===void 0?"":` --env ${r.env}`,{toolchain:c}=D(t);if(c===void 0)return n.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const d=[];for(const l of a){const g=V(),u=c.secretPut({environment:r.env,key:l,temporary:r.temporary}),m=w(i,u.tool,u.args),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:g}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},Be=/^[\w-]+$/u,Ve=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!Be.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 n=r.env===void 0?v:`${v}.${r.env}`,o=h(e,n);let i=p(o)?S(o,"utf8"):"";for(const s of a)i=K(i,s.key,s.value);return q(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${v} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Ke=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??$e)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await Me(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(m=>!E(m)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>E(u));if(l.length===0)return{};if(await(r.secretConfirm??be())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await We(e,r,l,t),f=Ve(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},qe=async(e,r)=>{const a=new re({skipAddingFilesFromTsConfig:!0}),t=h(r,"lunora");let n;try{n=O(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Se(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},Ye=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--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(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Ge=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new ee({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=F({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=we(d.platformDiagnostics,a);if(l!==void 0)return{error:l};const{errorAdvisories:g,names:u,shouldBlock:m}=ie(d.advisories,s);if(m){const A=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and deploy anyway.`;return a.error(A),{error:A}}const f=await M({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},ze=(e,r,a="deploy")=>{const t=Ie(e);if(t===void 0)return;const n=`${a} blocked: the "${t}" D1 binding has a placeholder database_id ("${I}"). 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(n),n},Je=(e,r,a="deploy")=>{const t=C(e)?.vars;if(!t)return;const n=xe.filter(i=>typeof t[i]=="string"&&Le(t[i]));if(n.length===0)return;const o=`${a} blocked: ${n.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.`;return r.error(o),o},Qe=async(e,r)=>{const{info:a}=Y(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=ae(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}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await ne({cwd:r,entries:n,exec:w(k(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},x=5,Xe=2e3,Ze=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??j({cwd:r,env:e.env});if(t===void 0){const o="--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(o),{error:o,ok:!1,url:""}}const n=await me({attempts:x,baseUrl:t,delayMs:Xe,fetchImpl:e.healthFetch,paths:[fe,he],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(x)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},er=async(e,r,a,t,n,o)=>{await Qe(e,r);const i=e.migrate?await qe(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},rr=(e,r,a)=>{const t=ze(e,r.logger,a);if(t!==void 0)return t;const n=Je(e,r.logger,a);if(n!==void 0)return n;const o=je(e,r.logger,a);return o!==void 0?o:Te(e,r.logger,r.dockerAvailable??ue,a)},tr=(e,r,a)=>{const t=_e(e);t!==void 0&&r.logger.info(`class-B composition: deploying ${t} (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}`);const n=D(a),o={dryRun:r.dryRun,entry:t,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);return n.toolchain.deploy(o)},y=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),ar=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},nr=(e,r,a)=>{const t=b(r.format),n=r.dryRun!==!0,o=tr(e,r,a),i=w(k(e),o.tool,o.args);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},or=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Ce(o),workerName:R(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:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ae({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await Ze(t,e,s.url);return c?.error!==void 0?{code:1,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await er(t,e,r,i,n,a),deployment:s,healthCheck:c}},ir=async(e,r)=>{const a=e.cwd??process.cwd(),t=U(e),n=oe(e),o={problems:[],wranglerPath:void 0},i=le(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;let c;if(!e.skipCodegen){const u=await Ge(a,t,e.logger,e.apiSpec,s,e.spawner,b(e.format),n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=ge({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await Oe(a,e.logger,c?.cronTriggers,s,e.env);const l=rr(a,e,r);if(l!==void 0)return{error:l,target:s,validation:o};const g=G({environment:e.env,projectRoot:a});return ar(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:g}},sr=async e=>{const r=e.cwd??process.cwd(),a=U(e),t=await ir(e,"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:1,descriptor:void 0,error:t.error,validation:t.validation};const f=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return y(t.error,f)}const{reblessSchemaBaseline:n,validation:o}=t,i=t.target,s=Ye(e);if(s!==void 0)return y(s);const c=await Ue(r,e);if(c!==void 0)return y(c);He(r,e.logger);const{error:d,mintedSecretsFile:l}=await Ke(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:1,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const g=nr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const m=await(e.spawner??$)(g);return g.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:g,mintedSecretsFile:l,validation:o}:or({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:m.stdout,validation:o})},cr=async e=>{const r=ve("deploy",e.format);if(r!==void 0)return e.logger.error(r),y(r);const a=await sr({...e,logger:pe(e.format,e.logger)});if(b(e.format))return ye(a),a;if(a.code===0&&e.dryRun!==!0&&e.preview!==!0)Ee({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,migrated:e.migrate===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url});else if(a.code===0&&e.preview===!0){const t=a.deployment?.url;e.logger.success(t===void 0?"preview version uploaded":`preview version uploaded — ${t}`)}return a},Nr=ce(async({cwd:e,logger:r,options:a})=>({code:(await cr({allowSchemaDrift:a.allowSchemaDrift===!0,apiSpec:se(a.apiSpec),cwd:e,dryRun:a.dryRun===!0,env:a.env,format:a.format,healthCheck:a.healthCheck===!0,logger:r,migrate:a.migrate===!0,migrateToken:a.migrateToken,migrateUrl:j({cwd:e,env:a.env,url:a.migrateUrl}),migrateYes:a.migrateYes===!0,preview:a.preview===!0,skipCodegen:a.prebuilt===!0,strictAdvisories:a.strictAdvisories,target:a.target,temporary:a.temporary===!0,updateSchemaBaseline:a.updateSchemaBaseline===!0})).code}));export{Nr as execute,cr as runDeployCommand,ir as runPreDeployPipeline};