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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"./packem_shared/cli-CrC0a7dH.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{r as e}from"./packem_shared/cli-C37AI4tr.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -141,6 +141,18 @@ interface ImportRowError {
141
141
  message: string;
142
142
  table: string;
143
143
  }
144
+ /**
145
+ * One SHARD the fan-out never reached, as the admin import endpoint reports it.
146
+ *
147
+ * Distinct from {@link ImportRowError}: the rows a dead shard owned contribute
148
+ * to neither `inserted` nor `errors`, so an unknown slice of the batch is simply
149
+ * missing. The endpoint answers 207 Multi-Status when this array is non-empty.
150
+ */
151
+ interface ImportShardFailure {
152
+ message: string;
153
+ shardKey: string;
154
+ timedOut: boolean;
155
+ }
144
156
  /**
145
157
  * The sources `--from` accepts.
146
158
  *
@@ -253,6 +265,8 @@ interface ImportCommandOptions {
253
265
  interface ImportSummary {
254
266
  conflicts: number;
255
267
  errors: ImportRowError[];
268
+ /** Shards the endpoint could not reach (it answered 207). Their rows are MISSING, not rejected — present only when non-empty. */
269
+ failed?: ImportShardFailure[];
256
270
  inserted: Record<string, number>;
257
271
  received: number;
258
272
  storage?: {
package/dist/index.d.ts CHANGED
@@ -141,6 +141,18 @@ interface ImportRowError {
141
141
  message: string;
142
142
  table: string;
143
143
  }
144
+ /**
145
+ * One SHARD the fan-out never reached, as the admin import endpoint reports it.
146
+ *
147
+ * Distinct from {@link ImportRowError}: the rows a dead shard owned contribute
148
+ * to neither `inserted` nor `errors`, so an unknown slice of the batch is simply
149
+ * missing. The endpoint answers 207 Multi-Status when this array is non-empty.
150
+ */
151
+ interface ImportShardFailure {
152
+ message: string;
153
+ shardKey: string;
154
+ timedOut: boolean;
155
+ }
144
156
  /**
145
157
  * The sources `--from` accepts.
146
158
  *
@@ -253,6 +265,8 @@ interface ImportCommandOptions {
253
265
  interface ImportSummary {
254
266
  conflicts: number;
255
267
  errors: ImportRowError[];
268
+ /** Shards the endpoint could not reach (it answered 207). Their rows are MISSING, not rejected — present only when non-empty. */
269
+ failed?: ImportShardFailure[];
256
270
  inserted: Record<string, number>;
257
271
  received: number;
258
272
  storage?: {
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-CrC0a7dH.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as s}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as R}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as E}from"./packem_shared/insertSchemaExtension-DY4pA8wE.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-hGafwf-3.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as b,renderCreateTable as h,renderDropIndex as y,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as w}from"./packem_shared/diffSnapshots-CIOFQN_a.mjs";import{default as F}from"./packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs";import{createRecordingSpawner as U,defaultSpawner as V}from"./packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{default as G}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Q,r as j}from"./packem_shared/import-CrVGrOt3.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-Zi3bBqpc.mjs";import{r as X,a as $,b as rr}from"./packem_shared/commands-BNKj7r1R.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-DmXKEWSq.mjs";export{o as COMMANDS,Q as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,V as defaultSpawner,v as diffSnapshots,E as insertSchemaExtension,c as pail,G as parseManifest,x as planDevCommand,_ as renderAddColumn,b as renderCreateIndex,h as renderCreateTable,y as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,s as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,R as runRpcCommand,F as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,w as validatorKindToSqlType};
1
+ import{C as o,V as a,r as n}from"./packem_shared/cli-C37AI4tr.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as s}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as R}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as E}from"./packem_shared/insertSchemaExtension-DY4pA8wE.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-hGafwf-3.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as b,renderCreateTable as h,renderDropIndex as y,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as w}from"./packem_shared/diffSnapshots-CIOFQN_a.mjs";import{default as F}from"./packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs";import{createRecordingSpawner as U,defaultSpawner as V}from"./packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{default as G}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Q,r as j}from"./packem_shared/import-CdHdZRjj.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-Zi3bBqpc.mjs";import{r as X,a as $,b as rr}from"./packem_shared/commands-BNKj7r1R.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-DmXKEWSq.mjs";export{o as COMMANDS,Q as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,V as defaultSpawner,v as diffSnapshots,E as insertSchemaExtension,c as pail,G as parseManifest,x as planDevCommand,_ as renderAddColumn,b as renderCreateIndex,h as renderCreateTable,y as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,s as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,R as runRpcCommand,F as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,w as validatorKindToSqlType};
@@ -1,3 +1,3 @@
1
- import{existsSync as S}from"node:fs";import{mkdtemp as k,writeFile as v,rm as R}from"node:fs/promises";import{tmpdir as T}from"node:os";import{discoverSchema as $,schemaFromIr as j}from"@lunora/codegen";import{seedPlan as C}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as F}from"ts-morph";import{i as x}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{d as z}from"../packem_shared/command-DwC11Cwe.mjs";import{r as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{b as A}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{runResetCommand as P}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-CrVGrOt3.mjs";const b=e=>e===""?!1:x(e),L=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,l=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),N=(e,r)=>{if(!S(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),l(1);if(e.reset===!0&&(e.prod===!0||!b(e.url)))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),l(1)},_=async(e,r,t,n)=>{const i=await k(m(T(),"lunora-seed-")),s=m(i,"rows.ndjson");await v(s,e,"utf8");try{const o=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:s,logger:n.logger,prod:n.prod,token:n.token,url:n.url}),d=o.body?.conflicts??0;return d>0&&n.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:o.code,conflicts:d,generated:r,inserted:o.inserted,ndjson:e}}finally{await R(i,{force:!0,recursive:!0}).catch(()=>{})}},B=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const t=r.tables.map(n=>n.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${t||"(no tables)"}`),l(1)},D=async(e,r)=>{if(!(e.prod===!0||!b(e.url))||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),l(1);if(!await(e.confirm??A)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),l(1)},H=async e=>{const r=e.cwd??process.cwd(),t=m(r,"lunora","schema.ts"),n=N(e,t);if(n!==void 0)return n;const i=new F({skipAddingFilesFromTsConfig:!0}),s=$(i,t),o=B(e,s);if(o!==void 0)return o;const d=j(s),g=C(d,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const y of f)u.push(JSON.stringify({doc:y,table:h},L));const a=u.length>0?`${u.join(`
1
+ import{existsSync as S}from"node:fs";import{mkdtemp as k,writeFile as v,rm as R}from"node:fs/promises";import{tmpdir as T}from"node:os";import{discoverSchema as $,schemaFromIr as j}from"@lunora/codegen";import{seedPlan as C}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as F}from"ts-morph";import{i as x}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{d as z}from"../packem_shared/command-DwC11Cwe.mjs";import{r as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{b as A}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{runResetCommand as P}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-CdHdZRjj.mjs";const b=e=>e===""?!1:x(e),L=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,l=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),N=(e,r)=>{if(!S(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),l(1);if(e.reset===!0&&(e.prod===!0||!b(e.url)))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),l(1)},_=async(e,r,t,n)=>{const i=await k(m(T(),"lunora-seed-")),s=m(i,"rows.ndjson");await v(s,e,"utf8");try{const o=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:s,logger:n.logger,prod:n.prod,token:n.token,url:n.url}),d=o.body?.conflicts??0;return d>0&&n.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:o.code,conflicts:d,generated:r,inserted:o.inserted,ndjson:e}}finally{await R(i,{force:!0,recursive:!0}).catch(()=>{})}},B=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const t=r.tables.map(n=>n.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${t||"(no tables)"}`),l(1)},D=async(e,r)=>{if(!(e.prod===!0||!b(e.url))||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),l(1);if(!await(e.confirm??A)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),l(1)},H=async e=>{const r=e.cwd??process.cwd(),t=m(r,"lunora","schema.ts"),n=N(e,t);if(n!==void 0)return n;const i=new F({skipAddingFilesFromTsConfig:!0}),s=$(i,t),o=B(e,s);if(o!==void 0)return o;const d=j(s),g=C(d,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const y of f)u.push(JSON.stringify({doc:y,table:h},L));const a=u.length>0?`${u.join(`
2
2
  `)}
3
3
  `:"",c=u.length;if(e.dryRun===!0)return a.length>0&&process.stdout.write(a),e.logger.info(`generated ${String(c)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:c,inserted:0,ndjson:a};if(e.reset===!0){const f=await P({cwd:r,logger:e.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:c,inserted:0,ndjson:a}}if(c===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:a};const w=await D(e,c);return w!==void 0?w:_(a,c,r,e)},p=z(async({cwd:e,logger:r,options:t})=>({code:(await H({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,logger:r,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:I({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{p as execute,H as runSeedCommand};
@@ -1 +1 @@
1
- import{existsSync as p}from"node:fs";import{join as h}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{p as g}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as v}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as y}from"../packem_shared/command-DwC11Cwe.mjs";import{r as w}from"../packem_shared/deploy-target-D9GPy_tq.mjs";import{r as S,p as k}from"../packem_shared/schema-drift-gate-DARCKocg.mjs";import{v as j,i as b,p as x,l as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{validateWranglerProject as U}from"@lunora/config/cloudflare";import{execArgsFor as D,detectPackageManager as R}from"@lunora/config";const $=async(r,t)=>{if(!p(h(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=D(R(r),"tsc",["--noEmit","-p","tsconfig.json"]),a=await t({args:e.args,command:e.command,cwd:r});return a.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(a.code)}`}},H=async(r,t)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await k({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(e.error===void 0){t.success(`verify: health probe ok (${e.url})`);return}return e.error},T=(r,t,e,a)=>{if(t.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:a};if(e.length>0){r.warn("verify: warnings:");for(const c of e)r.warn(` - ${c}`)}if(t.length>0){r.error("verify: errors:");for(const c of t){r.error(` - ${c}`);const n=v(c);n!==void 0&&r.error(n)}return{code:1,errors:t,warnings:e,wranglerPath:a}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:a}},C=async r=>{const t=r.cwd??process.cwd(),e=E(r.format,r.logger),a=j("verify",r.format);if(a!==void 0)return r.logger.error(a),{code:1,error:a,errors:[],warnings:[],wranglerPath:void 0};const c=U({projectRoot:t}),n=[...c.report.errors],f=[...c.report.warnings];try{const o=w(t,r.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.error(i),{code:1,error:i,errors:[i],warnings:[],wranglerPath:void 0}}const s=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:t,target:o.target}),m=S({allowDrift:r.allowSchemaDrift===!0,codegen:s,command:"verify",logger:e,readOnly:!0});m.blocked&&n.push(m.reason)}catch(o){const s=o instanceof Error?o.message:String(o);n.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const o=await $(t,r.spawner??F);o.error!==void 0&&n.push(o.error),o.warning!==void 0&&f.push(o.warning)}const l=await H(r,e);l!==void 0&&n.push(l);const d=T(e,n,f,c.wranglerPath);return b(r.format)&&x(d),d},K=y(async({cwd:r,logger:t,options:e})=>({code:(await C({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:g(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:t,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{K as execute,C as runVerifyCommand};
1
+ import{existsSync as p}from"node:fs";import{join as h}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{p as g}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as v}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as y}from"../packem_shared/command-DwC11Cwe.mjs";import{r as w}from"../packem_shared/deploy-target-D9GPy_tq.mjs";import{r as S,p as k}from"../packem_shared/schema-drift-gate-Bt_plRtS.mjs";import{v as j,i as b,p as x,l as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{validateWranglerProject as U}from"@lunora/config/cloudflare";import{execArgsFor as D,detectPackageManager as R}from"@lunora/config";const $=async(r,t)=>{if(!p(h(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=D(R(r),"tsc",["--noEmit","-p","tsconfig.json"]),a=await t({args:e.args,command:e.command,cwd:r});return a.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(a.code)}`}},H=async(r,t)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await k({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(e.error===void 0){t.success(`verify: health probe ok (${e.url})`);return}return e.error},T=(r,t,e,a)=>{if(t.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:a};if(e.length>0){r.warn("verify: warnings:");for(const c of e)r.warn(` - ${c}`)}if(t.length>0){r.error("verify: errors:");for(const c of t){r.error(` - ${c}`);const n=v(c);n!==void 0&&r.error(n)}return{code:1,errors:t,warnings:e,wranglerPath:a}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:a}},C=async r=>{const t=r.cwd??process.cwd(),e=E(r.format,r.logger),a=j("verify",r.format);if(a!==void 0)return r.logger.error(a),{code:1,error:a,errors:[],warnings:[],wranglerPath:void 0};const c=U({projectRoot:t}),n=[...c.report.errors],f=[...c.report.warnings];try{const o=w(t,r.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.error(i),{code:1,error:i,errors:[i],warnings:[],wranglerPath:void 0}}const s=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:t,target:o.target}),m=S({allowDrift:r.allowSchemaDrift===!0,codegen:s,command:"verify",logger:e,readOnly:!0});m.blocked&&n.push(m.reason)}catch(o){const s=o instanceof Error?o.message:String(o);n.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const o=await $(t,r.spawner??F);o.error!==void 0&&n.push(o.error),o.warning!==void 0&&f.push(o.warning)}const l=await H(r,e);l!==void 0&&n.push(l);const d=T(e,n,f,c.wranglerPath);return b(r.format)&&x(d),d},K=y(async({cwd:r,logger:t,options:e})=>({code:(await C({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:g(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:t,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{K as execute,C as runVerifyCommand};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as h,existsSync as S,readFileSync as b}from"node:fs";import{isAbsolute as w,join as p}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as A}from"@lunora/advisor";import{runCodegen as F}from"@lunora/codegen";import{d as M}from"../packem_shared/command-DwC11Cwe.mjs";import{v as R,p as D,l as k,i as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{D as f}from"../packem_shared/cli-CrC0a7dH.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),B=e=>`${e.id} (${e.visibility} ${e.kind})`,g=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},m=(e,r)=>` ${u(String(e.score),3)} ${l[e.coverage]} ${u(e.id,r)} ${e.visibility} ${e.kind}`,T=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},C=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),o=g(n),t=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&t.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&t.push("",...n.map(i=>m(i,o)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&t.push("",...T(r)),t.join(`
1
+ import{writeFileSync as h,existsSync as S,readFileSync as b}from"node:fs";import{isAbsolute as w,join as p}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as A}from"@lunora/advisor";import{runCodegen as F}from"@lunora/codegen";import{d as M}from"../packem_shared/command-DwC11Cwe.mjs";import{v as R,p as D,l as k,i as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{D as f}from"../packem_shared/cli-C37AI4tr.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),B=e=>`${e.id} (${e.visibility} ${e.kind})`,g=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},m=(e,r)=>` ${u(String(e.score),3)} ${l[e.coverage]} ${u(e.id,r)} ${e.visibility} ${e.kind}`,T=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},C=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),o=g(n),t=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&t.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&t.push("",...n.map(i=>m(i,o)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&t.push("",...T(r)),t.join(`
2
2
  `)},J=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),L=e=>{const r=new Map;for(const n of e){const o=r.get(n.file);o===void 0?r.set(n.file,[n]):o.push(n)}return[...r].toSorted(([n],[o])=>y(n,o))},N=e=>{const r=g(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[o,t]of L(e.procedures)){n.push("",` ${o}`);for(const i of t)n.push(m(i,r),...J(i))}return n.join(`
3
3
  `)},P=(e,r)=>{const n=e.procedures.find(t=>t.id===r);if(n===void 0){const t=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...t,e.procedures.length>10?" …":""].filter(Boolean).join(`
4
4
  `)}const o=[`${B(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return o.push(""," no rule fired"),o.join(`
@@ -1,3 +1,3 @@
1
- import K,{join as l,resolve as T}from"node:path";import{isInteractive as F,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as x,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as Y,backupObjectKeyOfManifest as O}from"@lunora/runtime";import{r as A}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as v}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as W}from"../packem_shared/command-DwC11Cwe.mjs";import{r as X}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as U,createHash as Q}from"node:crypto";import{existsSync as $,createReadStream as V,createWriteStream as Z}from"node:fs";import{mkdir as ee,rm as w,rename as B,readFile as D,writeFile as re,realpath as N,mkdtemp as S}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as E}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as I}from"node:os";import{Readable as te}from"node:stream";import{pipeline as ae}from"node:stream/promises";import{b as oe,l as ne,M as _,u as ie,r as ce}from"../packem_shared/import-CrVGrOt3.mjs";import{runExportCommand as se}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";const y="manifest.json",j=async e=>{const r=Q("sha256");let a=0;for await(const t of V(e)){const o=t;a+=o.byteLength,r.update(o)}return{bytes:a,sha256:r.digest("hex")}},P=async e=>{const r=l(e,y);if(!$(r))return[];let a;try{a=JSON.parse(await D(r,"utf8"))}catch(t){const o=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`backup: ${r} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:t})}if(!Array.isArray(a))throw new TypeError(`backup: ${r} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return a.filter(t=>x(t))},ue=async(e,r)=>{const a=l(e,`${y}.${U()}.tmp`);try{await re(a,`${JSON.stringify(r,void 0,2)}
1
+ import K,{join as l,resolve as T}from"node:path";import{isInteractive as F,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as x,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as Y,backupObjectKeyOfManifest as O}from"@lunora/runtime";import{r as A}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as v}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as W}from"../packem_shared/command-DwC11Cwe.mjs";import{r as X}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as U,createHash as Q}from"node:crypto";import{existsSync as $,createReadStream as V,createWriteStream as Z}from"node:fs";import{mkdir as ee,rm as w,rename as B,readFile as D,writeFile as re,realpath as N,mkdtemp as S}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as E}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as I}from"node:os";import{Readable as te}from"node:stream";import{pipeline as ae}from"node:stream/promises";import{b as oe,l as ne,M as _,u as ie,r as ce}from"../packem_shared/import-CdHdZRjj.mjs";import{runExportCommand as se}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";const y="manifest.json",j=async e=>{const r=Q("sha256");let a=0;for await(const t of V(e)){const o=t;a+=o.byteLength,r.update(o)}return{bytes:a,sha256:r.digest("hex")}},P=async e=>{const r=l(e,y);if(!$(r))return[];let a;try{a=JSON.parse(await D(r,"utf8"))}catch(t){const o=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`backup: ${r} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:t})}if(!Array.isArray(a))throw new TypeError(`backup: ${r} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return a.filter(t=>x(t))},ue=async(e,r)=>{const a=l(e,`${y}.${U()}.tmp`);try{await re(a,`${JSON.stringify(r,void 0,2)}
2
2
  `,"utf8"),await B(a,l(e,y))}catch(t){throw await w(a,{force:!0}),t}},de=async(e,r)=>{const a=T(e),t=T(a,r.file),o=()=>{throw new h("INTERNAL",`backup: entry ${r.id} points outside ${a} (${r.file}) — refusing to read it`)};if(E(a,t)||o(),!!$(t))return E(await N(a),await N(t))||o(),t},le=e=>{const r=a=>p("",a);return{commit:async(a,t)=>{await B(t,l(e,a))},label:e,list:async()=>P(e),locate:r,materialize:async(a,t)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(a===void 0?$(t)?t:void 0:await de(e,a))},record:async a=>{const t=await P(e);t.push(a),await ue(e,t)},stage:async a=>{await ee(e,{recursive:!0});const t=l(e,`${r(a)}.${U()}.partial`);return{path:t,release:()=>w(t,{force:!0})}}}},fe="/_lunora/admin/storage/object",me="/_lunora/admin/storage",R=8,ge=(e,r=K)=>{const a=r.basename(e);return a===""||a==="."||a===".."?"snapshot.ndjson":a},he=e=>{const{context:r,logger:a}=e,t=H(e.prefix??J),o=`bucket ${r.bucket??"(default)"} under ${t}`,i=oe(r),u=c=>`${r.baseUrl}${fe}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const n=await r.fetchImpl(u(c),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!n.ok){const d=await n.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not read ${c} (HTTP ${String(n.status)}): ${d}`)}return n.text()},C=async c=>{try{const n=JSON.parse(await f(c));if(x(n))return n;a.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(n){a.warn(`backup: ignoring ${c} — ${n instanceof Error?n.message:String(n)}`)}};return{commit:async(c,n,d)=>{if(d.bytes>_)throw new h("INTERNAL",`backup: the snapshot is ${String(d.bytes)} bytes, above the ${String(_)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const s=await D(n);await ie(r,c,s,{contentType:"application/x-ndjson",id:c,sha256:d.sha256,size:d.bytes},a)},label:o,list:async()=>{const n=(await ne(r,t)).map(s=>s.key).filter(s=>Y(s)),d=[];for(let s=0;s<n.length;s+=R){const m=await Promise.all(n.slice(s,s+R).map(async g=>C(g)));d.push(...m.filter(g=>g!==void 0))}return d.toSorted((s,m)=>s.id.localeCompare(m.id))},locate:c=>p(t,c),materialize:async(c,n)=>{const d=c?.file??n,s=await r.fetchImpl(u(d),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(s.status===404)return;if(!s.ok||s.body===null){const k=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not download ${d} (HTTP ${String(s.status)}): ${k}`)}const m=await S(l(I(),"lunora-backup-")),g=l(m,ge(d));try{await ae(te.from(s.body),Z(g))}catch(k){throw await w(m,{force:!0,recursive:!0}),k}return{path:g,release:async()=>w(m,{force:!0,recursive:!0})}},record:async c=>{const n=G(c.file),d=await r.fetchImpl(`${r.baseUrl}${me}?key=${encodeURIComponent(n)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
3
  `,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!d.ok){const s=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(d.status)}): ${s}`)}},stage:async c=>{const n=await S(l(I(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},we=".lunora-backups",L="/_lunora/admin/backup/retention",be="/_lunora/admin/backup/prune",ke="/_lunora/admin/pitr",pe="__lunora_admin__:getPitrBookmark",ye="__lunora_admin__:pitrRestore",ve=async(e,r)=>{const a=(e.now??(()=>new Date))().toISOString(),t=await r.stage(a);try{const o=await se({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:t.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=r.locate(a),u=await j(t.path);await r.commit(i,t.path,u);const f={bytes:u.bytes,createdAt:a,file:i,id:a,rows:o.rows,sha256:u.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await t.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},$e=async(e,r,a)=>{if(r?.sha256===void 0)return a.error(r===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${r.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const t=await j(e);if(t.sha256!==r.sha256)return a.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${t.sha256}) — nothing was imported`),{code:1};a.success(`verified ${r.file} against its recorded sha256`)},Te=async(e,r)=>{const a=await r.list();if(a.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const t of a)e.logger.info(`${t.id} ${t.rows.toString()} rows ${t.bytes.toString()} bytes ${t.file}`);return{code:0}},Ne=async(e,r)=>{const{target:a}=e;if(a===void 0||a.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const o=(await r.list()).find(u=>u.id===a),i=await r.materialize(o,a);if(i===void 0)return e.logger.error(`backup not found: ${a}`),{code:1};try{if(e.verify===!0){const f=await $e(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await ce({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes})).code}}finally{await i.release().catch(u=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${u instanceof Error?u.message:String(u)})`)})}},Se=e=>{const r=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!r){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0){e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(e.restore===!0&&e.prod===!0&&e.yes!==!0){e.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const t=e.adminFetch??globalThis.fetch;if(typeof t!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:t,requestUrl:`${a}${ke}`,token:r}},Ee=(e,r)=>{const a={};return e.at!==void 0&&(a.time=e.at),r&&e.bookmark!==void 0&&(a.bookmark=e.bookmark),r&&e.restart===!0&&(a.restart=!0),a},Ie=async e=>{const r=Se(e);if(r===void 0)return{code:1};const a=e.restore===!0,t=a?ye:pe,o=Ee(e,a),i=a?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const u=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:t,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(u,e.logger),{code:u.ok?0:1}},_e=(e,r)=>{if(e.bucket===void 0)return le(l(r,e.dir??we));if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:r,token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return he({context:{baseUrl:a,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:t},logger:e.logger,prefix:e.prefix})},q=e=>{const r=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(r.length>0){e.logger.error(`${r.join(" / ")} ${r.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:a,fetchImpl:o,token:t}},M=(e,r)=>{e.logger.info(`backup retention would keep the newest ${r.keep.toString()} of ${r.eligible.toString()} under ${r.prefix} and delete ${r.wouldDelete.length.toString()}`);for(const a of r.wouldDelete)e.logger.info(` ${O(a)}`)},Pe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();return t.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:t}):t.keep<=0?(e.logger.info(`retention is off for cron "${t.cron}" (\`backupRetain\` unset) — every snapshot under ${t.prefix} is kept`),{code:0,preview:t}):(M(e,t),t.eligible===0&&e.logger.info(`no snapshot under ${t.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:t})},Re=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const a of r.deleted)e.logger.info(` ${O(a)}`);r.failed.length>0&&e.logger.warn(`${r.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),r.ignored>0&&e.logger.info(`${r.ignored.toString()} were already gone by the time the delete ran`),r.remaining>0&&e.logger.info(`${r.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},xe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();if(t.keep<=0||t.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:t};if(t.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${t.eligible.toString()} snapshot(s) under ${t.prefix} and retention keeps the newest ${t.keep.toString()}`),{code:0,preview:t};if(M(e,t),e.yes!==!0){const u=e.confirm??(F()?z:void 0);if(u===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:t};if(!await u(`delete ${t.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:t}}const o=await r.fetchImpl(`${r.baseUrl}${be}`,{body:JSON.stringify({confirm:t.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:t};const i=await o.json();return Re(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:t}},Oe=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await Ie(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await xe(e);const a=_e(e,r);return a===void 0?{code:1}:e.subcommand==="create"?await ve(e,a):e.subcommand==="list"?await Te(e,a):await Ne(e,a)}catch(a){return e.logger.error(a instanceof Error?a.message:String(a)),{code:1}}},Ae=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ve=W(({argument:e,cwd:r,logger:a,options:t})=>{const o=e[0];return Ae(o)?Oe({at:t.at,bookmark:t.bookmark,bucket:t.bucket,cwd:r,dir:t.dir,logger:a,prefix:t.prefix,prod:t.prod===!0,restart:t.restart===!0,restore:t.restore===!0,shard:t.shard,subcommand:o,tables:t.tables,target:e[1],token:t.token,url:X({cwd:r,prod:t.prod===!0,url:t.url}),verify:t.verify===!0,yes:t.yes===!0}):(a.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ve as execute,Oe as runBackupCommand};
@@ -1,4 +1,4 @@
1
- import{V as R}from"../packem_shared/cli-CrC0a7dH.mjs";import{d as T}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as D,realpathSync as I,statSync as J,writeFileSync as W,chmodSync as z,renameSync as G,unlinkSync as H}from"node:fs";import{homedir as b}from"node:os";import{findWranglerFile as V}from"@lunora/config/cloudflare";import{join as s,dirname as K,relative as q}from"@visulima/path";import{stringify as B}from"smol-toml";import{parse as X,modify as Z,applyEdits as Q}from"jsonc-parser";import{detectPackageManager as Y,execArgsFor as ee,readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as re}from"@lunora/config/studio-host";import{connectLocalStdio as te}from"@lunora/mcp";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),h=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ne=e=>e.transport==="http"?{httpUrl:e.url}:f(e),oe=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ae=e=>({args:["-y","mcp-remote",e],command:"npx"}),le=e=>e.transport==="http"?ae(e.url):f(e),ce=e=>e.transport==="http"?{url:e.url}:f(e),se=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},ie=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},de=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ue=(e,r)=>B({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),p=[{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:h,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ne,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:le,paths:de,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:oe,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ce,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ue}],O=p.map(e=>e.id),fe=e=>p.find(r=>r.id===e.toLowerCase()),C=(e,r)=>{let t=e,n;try{t=I(e),n=J(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{W(a,r,"utf8"),n!==void 0&&z(a,n),G(a,t)}catch(o){try{H(a)}catch{}throw o}},me={formattingOptions:{insertSpaces:!0,tabSize:4}},w=e=>{const r=[],t=X(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),S=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},x=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=w(r);return t.length>0||!g(n)?"invalid":S(n,e.key,e.name)===void 0?"absent":"present"},ge=e=>x(e)==="present",M=(e,r,t,n,a)=>{try{const o=Z(e,[t,n],a,me);o.length>0&&C(r,Q(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},pe=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return D(K(o),{recursive:!0}),C(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
1
+ import{V as R}from"../packem_shared/cli-C37AI4tr.mjs";import{d as T}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as D,realpathSync as I,statSync as J,writeFileSync as W,chmodSync as z,renameSync as G,unlinkSync as H}from"node:fs";import{homedir as b}from"node:os";import{findWranglerFile as V}from"@lunora/config/cloudflare";import{join as s,dirname as K,relative as q}from"@visulima/path";import{stringify as B}from"smol-toml";import{parse as X,modify as Z,applyEdits as Q}from"jsonc-parser";import{detectPackageManager as Y,execArgsFor as ee,readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as re}from"@lunora/config/studio-host";import{connectLocalStdio as te}from"@lunora/mcp";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),h=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ne=e=>e.transport==="http"?{httpUrl:e.url}:f(e),oe=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ae=e=>({args:["-y","mcp-remote",e],command:"npx"}),le=e=>e.transport==="http"?ae(e.url):f(e),ce=e=>e.transport==="http"?{url:e.url}:f(e),se=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},ie=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},de=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ue=(e,r)=>B({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),p=[{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:h,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ne,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:le,paths:de,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:oe,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ce,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ue}],O=p.map(e=>e.id),fe=e=>p.find(r=>r.id===e.toLowerCase()),C=(e,r)=>{let t=e,n;try{t=I(e),n=J(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{W(a,r,"utf8"),n!==void 0&&z(a,n),G(a,t)}catch(o){try{H(a)}catch{}throw o}},me={formattingOptions:{insertSpaces:!0,tabSize:4}},w=e=>{const r=[],t=X(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),S=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},x=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=w(r);return t.length>0||!g(n)?"invalid":S(n,e.key,e.name)===void 0?"absent":"present"},ge=e=>x(e)==="present",M=(e,r,t,n,a)=>{try{const o=Z(e,[t,n],a,me);o.length>0&&C(r,Q(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},pe=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return D(K(o),{recursive:!0}),C(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
2
2
  `),{action:"created",path:o};const{errors:c,value:i}=w(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!g(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(S(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const k=M(l,o,n,a,r);return k===void 0?{action:"updated",path:o}:{action:"invalid",error:k,path:o}},ve=e=>{const{key:r,name:t,path:n}=e;if(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=w(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(S(l,r,t)===void 0)return{action:"absent",path:n};const c=M(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},he=["global","project"],d=(e,r)=>{const t=q(r,e);return t.length>0&&!t.startsWith("..")?t:e},ye=(e,r)=>{const t=e.paths(r);return he.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},be=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},we=e=>p.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),_=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=fe(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${O.join(", ")}.`);return}a.push(l)}return a},Se=e=>e.client.format==="json",ke="https://lunora.sh/mcp",L="lunora-docs",N="lunora",je=e=>u(s(e,"lunora"))&&V(e)!==void 0,$e=e=>{const{args:r,command:t}=ee(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Ee=e=>({transport:"http",url:e}),Oe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),U=(e,r,t)=>be(e,Oe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ce=(e,r,t)=>{const n=U(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=d(a,t.cwd);return t.force!==!0&&ge({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
3
3
  ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=pe({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},xe=(e,r,t)=>{const n=U(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${d(n,t.cwd)}
4
4
 
@@ -1 +1 @@
1
- import{d as o}from"../packem_shared/command-DwC11Cwe.mjs";import{r as f}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{I as u,r as d}from"../packem_shared/import-CrVGrOt3.mjs";const n=o(({argument:m,cwd:a,logger:e,options:r})=>{const t=m[0];return t?r.from!==void 0&&!u.includes(r.from)?(e.error(`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`),{code:1}):d({batchSize:r.batchSize,cwd:a,file:t,from:r.from,logger:e,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:f({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0}):(e.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{n as execute};
1
+ import{d as o}from"../packem_shared/command-DwC11Cwe.mjs";import{r as f}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{I as u,r as d}from"../packem_shared/import-CdHdZRjj.mjs";const n=o(({argument:m,cwd:a,logger:e,options:r})=>{const t=m[0];return t?r.from!==void 0&&!u.includes(r.from)?(e.error(`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`),{code:1}):d({batchSize:r.batchSize,cwd:a,file:t,from:r.from,logger:e,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:f({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0}):(e.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{n as execute};
@@ -1 +1 @@
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};
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-Bt_plRtS.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};