UNPKG

@lunora/cli

Version:

The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands

4 lines (3 loc) • 44.6 kB
import{randomUUID as V,createHash as gr,createHmac as yr}from"node:crypto";import{mkdirSync as $r,writeFileSync as ne,linkSync as xe,rmSync as F,statSync as Ce,unlinkSync as kr,readFileSync as L,existsSync as Q,mkdtempSync as Er}from"node:fs";import{tmpdir as br}from"node:os";import{join as ee,dirname as _r}from"node:path";import{SCHEMA_SNAPSHOT_FILENAME as Sr,readServiceBindings as Rr}from"@lunora/codegen";import{generateSecretValue as Ir}from"@lunora/config";import{readManifest as Ke,recordManifestKey as Or,findWranglerFile as He,readWranglerJsonc as $e,applyModify as Tr}from"@lunora/config/cloudflare";import{n as pe,r as Ar,c as Cr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as jr}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Ur}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{c as oe,d as Nr,b as Lr,e as Dr,r as Pr}from"./handler.mjs";import{runSeedCommand as Fr}from"./handler14.mjs";const Be=r=>{if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}},ve=r=>Number(L(r,"utf8")),je=r=>{try{return ve(r)}catch{return}},Mr=(r,e)=>{const t=`${r}.retire-${String(e)}`;try{xe(r,t)}catch{return!1}try{return ve(t)!==e||Be(ve(t))?!1:(Ce(r).ino===Ce(t).ino&&kr(r),!0)}finally{F(t,{force:!0})}},Wr=(r,e={})=>{const t=ee(r,".lunora","preview.lock"),n=`${t}.${String(process.pid)}.${V()}`;$r(_r(t),{recursive:!0}),ne(n,String(process.pid));try{for(let o=0;o<3;o+=1){try{return xe(n,t),{release:()=>{je(t)===process.pid&&F(t,{force:!0})}}}catch(i){if(i.code!=="EEXIST")throw i}const s=je(t);if(s!==void 0){if(Be(s))return{error:`another preview command is running in this checkout (pid ${String(s)}); wait for it, or remove ${t} if it is not`};if(e.afterReadingOwner?.(),!Mr(t,s))return{error:`another preview command is taking over the lock at ${t}; run this again in a moment. If none is running, remove ${t}.retire-${String(s)}`}}}return{error:`could not take the preview lock ${t}`}}finally{F(n,{force:!0})}},xr=[["SIGINT",130],["SIGTERM",143]],Kr=5e3,H=new Set,Ge=r=>process.exit(r);let Ve=Ge,Z=[],he;const Hr=async r=>{const e=[...H].map(async n=>{try{await n()}catch{}});H.clear();const t=new Promise(n=>{setTimeout(n,Kr).unref()});await Promise.race([Promise.all(e),t]),Ve(r)},Br=r=>(he??=Hr(r),he),ie=(r,e)=>(H.add(r),Z.length===0&&(Z=xr.map(([t,n])=>{const o=()=>{Br(n).catch(()=>{})};return process.on(t,o),[t,o]})),()=>{if(H.delete(r),H.size===0){for(const[t,n]of Z)process.off(t,n);Z=[],Ve=Ge,he=void 0}}),Gr=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,ke=r=>{const e=Ke(r)?.lunora?.appId;return typeof e=="string"&&Gr.test(e)?e.toLowerCase():void 0},Vr=r=>{const e=Ke(r);if(e===void 0||e.lunoraIsForeign||e.lunora?.appId!==void 0)return;const t=V();return Or(e,"appId",t),ke(r)===t?t:void 0},se=63,Ee=new Set(["$schema","account_id","alias","assets","base_dir","build","cache","compatibility_date","compatibility_flags","dev","env","find_additional_modules","jsx_factory","jsx_fragment","keep_names","keep_vars","limits","logpush","main","migrations","minify","name","no_bundle","observability","placement","preview_urls","routes","rules","send_metrics","triggers","tsconfig","upload_source_maps","workers_dev"]),Ye=["ai","browser","define","images","media","secrets","vars","version_metadata","worker_loaders"],Yr=new Set(["env","name","routes","triggers","workers_dev"]),Jr=new Set(["tail_consumers"]),Y={d1_databases:"d1",kv_namespaces:"kv",r2_buckets:"r2"},R=r=>r==null?!1:Array.isArray(r)?r.length>0:typeof r!="object"||Object.keys(r).length>0,I=r=>(Array.isArray(r)?r:[]).filter(e=>typeof e=="object"&&e!==null),Je=(r,e)=>{if(!(Ee.has(r)||Jr.has(r)||Ye.includes(r)||r in Y)){if(r==="route")return`"route": write it as "routes" so the preview can clear it — a preview must never claim production's hostname`;if(r==="durable_objects"){const t=I(e.bindings).find(n=>n.script_name!==void 0);return t===void 0?void 0:`"durable_objects": the "${String(t.name)}" binding reaches another Worker's Durable Objects (script_name "${String(t.script_name)}"), which the preview would share`}if(r==="exports"){const t=Object.entries(e).find(([,n])=>n?.type==="workflow");return t===void 0?void 0:`"exports": workflow "${t[0]}" has an account-wide name, so the preview would take over production's workflow`}return`"${r}": a preview cannot isolate this binding yet, and copying it would point the preview at production's resource`}},Ue="LUNORA_ORIGIN_URL",U="LUNORA_PREVIEW",M=r=>`${r.production}/${r.slug}`,Xr=/[^a-z0-9]+/u,Xe=r=>{const e=r.toLowerCase().split(Xr).filter(t=>t!=="").join("-");return e===""||e===r?e:`${e}-${gr("sha256").update(r).digest("hex").slice(0,6)}`},ae=(r,e)=>oe(`${r}-preview-${e}`,se),be=(r,e)=>{const t=typeof r.name=="string"?r.name:"",n=Xe(e);return t===""?{error:`wrangler.jsonc has no "name", which the preview Worker's name is derived from`}:n===""?{error:`"${e}" has no letter or digit to name a preview by`}:{names:{environment:oe(`preview-${n}`,se),production:t,slug:n,worker:ae(t,n)}}},J=(r,e,t)=>{const n=t?.vars?.[U],o=typeof n=="string"?n.lastIndexOf("/"):-1;if(typeof n!="string"||o<=0)return!1;const s=n.slice(0,o),i=n.slice(o+1);return Xe(i)===i&&M({production:s,slug:i})===n&&e===oe(`preview-${i}`,se)&&t?.name===ae(s,i)},ce=(r,e)=>{const t=Object.entries(r.env??{}).filter(([i,a])=>!J(r,i,a)),n=t.find(([i])=>i===e)?.[1];if(n===void 0)return{error:`wrangler.jsonc declares no environment "${e}"${t.length===0?", and no environments at all":`; the environments are: ${t.map(([i])=>i).join(", ")}`}`};const o=typeof r.name=="string"?r.name:"";return{config:{...Object.fromEntries(Object.entries(r).filter(([i])=>Ee.has(i)||i==="exports")),...n,env:r.env,name:typeof n.name=="string"?n.name:`${o}-${e}`}}},zr=r=>Object.entries(r.env??{}).filter(([e,t])=>!J(r,e,t)).filter(([,e])=>typeof e.account_id=="string"&&e.account_id!==""&&e.account_id!==r.account_id).map(([e])=>e),ze=(r,e)=>oe(`${r}-${e}`,se),Ne=(r,e)=>{const t=I(r==="durable_objects"?e?.bindings:e);return new Set(t.map(n=>String(r==="durable_objects"?n.name:n.binding)))},Qr=r=>Object.entries(r.env??{}).flatMap(([e,t])=>J(r,e,t)?[]:Object.entries(t).flatMap(([n,o])=>{const s=r[n];if(n in Y||n==="durable_objects"){const i=Ne(n,s),a=[...Ne(n,o)].filter(c=>!i.has(c));return a.length===0?[]:[`"env.${e}.${n}": binding ${a.map(c=>`"${c}"`).join(", ")} is declared only in this environment, and a preview is planned from the top-level config, which lacks it; pass --env ${e} to preview that environment`]}return Je(n,o)!==void 0&&R(o)&&!R(s)?[`"env.${e}.${n}": declared only in this environment, and a preview is planned from the top-level config, which has none; pass --env ${e} to preview that environment`]:[]})),Qe=(r,e)=>Object.entries(Y).flatMap(([t,n])=>I(r[t]).map(o=>{const s=String(o.binding);return{binding:s,kind:n,name:ze(e,s)}})),Ze=(r,e,t)=>{const n=be(r,e);if(n.error!==void 0)return{error:n.error};const{environment:o,worker:s}=n.names;if(r.env?.[o]!==void 0&&!J(r,o,r.env[o]))return{error:`wrangler.jsonc already declares "env.${o}"; a preview writes that block itself, so name the preview differently`};const i=Object.entries(r).flatMap(([f,l])=>{const m=R(l)?Je(f,l):void 0;return m===void 0?[]:[m]});i.push(...t===void 0?Qr(r):[]);const a=I(r.r2_buckets).find(f=>f.jurisdiction!==void 0);if(a!==void 0&&i.push(`"r2_buckets": the "${String(a.binding)}" bucket has a jurisdiction, which a preview bucket is not created in yet`),i.length>0)return{error:`this app cannot be previewed in isolation yet: - ${i.join(` - `)}`};const c=Object.keys(Y).find(f=>I(r[f]).some(l=>typeof l.binding!="string"||l.binding===""));if(c!==void 0)return{error:`"${c}": every entry needs a non-empty "binding"`};const d=Qe(r,s),u=d.find((f,l)=>d.findIndex(m=>m.kind===f.kind&&m.name===f.name)!==l);return u!==void 0?{error:`two bindings would share the preview resource name "${u.name}"; rename one of them (binding names differ only by case or punctuation)`}:{plan:{...n.names,...t===void 0?{}:{sourceEnv:t},resources:d}}},_e=(r,e)=>`${r}:${e}`,le=(r,e)=>Object.fromEntries(Object.entries(r).filter(([t])=>t!==e)),Zr=(r,e,t,n)=>{const o=String(e.binding),s=t.resources.find(a=>a.kind===r&&a.binding===o),i=n.get(_e(r,o));if(s===void 0||i===void 0)throw new Error(`no preview ${r} resource for the "${o}" binding`);return r==="d1"?{...le(e,"preview_database_id"),database_id:i,database_name:s.name}:r==="kv"?{...le(e,"preview_id"),id:i}:{...le(e,"preview_bucket_name"),bucket_name:i}},qr=(r,e,t)=>{if(t.sourceEnv!==void 0)for(const[n,o]of Object.entries(r))Ee.has(n)&&!(n in e)&&!Yr.has(n)&&R(o)&&(e[n]=o)},qe=(r,e,t,n={},o)=>{const s=r,i={name:e.worker,routes:[],triggers:{crons:[]},workers_dev:!0},a={[U]:M(e)};for(const d of Ye)R(s[d])&&(i[d]=s[d]);const c=R(r.vars)?{...r.vars}:{};Ue in c&&(c[Ue]=o??e.worker),i.vars={...c,...n,...a},qr(s,i,e),R(r.durable_objects)&&(i.durable_objects=r.durable_objects),R(s.exports)&&(i.exports=s.exports);for(const[d,u]of Object.entries(Y)){const f=I(s[d]);f.length>0&&(i[d]=f.map(l=>Zr(u,l,e,t)))}return i},et={analytics_engine_datasets:["dataset"],d1_databases:["database_id","database_name","preview_database_id"],hyperdrive:["id"],kv_namespaces:["id","preview_id"],r2_buckets:["bucket_name","preview_bucket_name"],vectorize:["index_name"]},rt={d1_databases:"d1",kv_namespaces:"kv",r2_buckets:"r2"},er=(r,e)=>`${r}:${e}`,tt=r=>{const e=Object.entries(et).flatMap(([t,n])=>I(r[t]).flatMap(o=>n.map(s=>[rt[t]??t,o[s]])));return[["worker",r.name],...e].flatMap(([t,n])=>typeof n=="string"&&n!==""?[er(t,n)]:[])},nt=r=>new Set([r,...Object.entries(r.env??{}).flatMap(([e,t])=>J(r,e,t)?[]:[t])].flatMap(e=>tt(e))),Se=(r,e)=>[{kind:"worker",value:r},...e.flatMap(t=>[...t.id===void 0?[]:[{kind:t.kind,value:t.id}],{kind:t.kind,value:t.name}])],B=(r,e)=>{const t=nt(r);return e.filter(n=>t.has(er(n.kind,n.value))).map(n=>n.value)},fe="lunora-preview-registry",re=50,de=r=>{try{const{errors:e}=JSON.parse(r.text),t=(e??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).join("; ");return t===""?`HTTP ${String(r.status)}`:`HTTP ${String(r.status)}: ${t}`}catch{return`HTTP ${String(r.status)}`}},k=(r,e)=>{if(!r.ok)throw new Error(`${e} failed (${de(r)})`);return r.body},X=r=>typeof r.result=="object"&&r.result!==null?r.result:{},rr=async(r,e,t,n)=>{const o=e.includes("?")?"&":"?";for(let s=1;s<=re;s+=1){const i=k(await r(`${e}${o}per_page=100&page=${String(s)}`),`listing ${t}`);if(!Array.isArray(i.result))throw new TypeError(`the listing of ${t} had no result list`);const a=i.result.find(d=>n(d)),c=typeof i.result_info=="object"&&i.result_info!==null?i.result_info:{};if(a!==void 0||typeof c.total_pages!="number"||s>=c.total_pages)return a}throw new Error(`the listing of ${t} has more than ${String(re)} pages`)},me=async(r,e)=>{const t=await rr(r,"/storage/kv/namespaces","KV namespaces",n=>n.title===e);return typeof t?.id=="string"?t.id:void 0},tr=async(r,e)=>{const{id:t}=X(k(await r("/storage/kv/namespaces",{body:JSON.stringify({title:e}),method:"POST"}),`creating KV namespace "${e}"`));if(typeof t!="string")throw new TypeError(`creating KV namespace "${e}" returned no id`);return t},Re=async(r,e)=>{const t=await me(r,fe);if(t!==void 0||!e)return t;try{return await tr(r,fe)}catch(n){const o=await me(r,fe);if(o===void 0)throw n;return o}},D=(r,e)=>`${r}/${e}`,Ie=(r,e)=>`/storage/kv/namespaces/${encodeURIComponent(r)}/values/${encodeURIComponent(e)}`,ot=new Set(["d1","kv","r2"]),it=(r,e)=>{const t=e;return typeof t=="object"&&t!==null&&ot.has(t.kind)&&typeof t.binding=="string"&&typeof t.id=="string"&&(t.pending===void 0||t.pending===!0)&&t.name===ze(r,t.binding)&&(t.kind!=="r2"||t.id===t.name)},st=r=>{const e=r;return typeof e=="object"&&e!==null&&typeof e.repository=="string"&&typeof e.pullRequest=="string"},at=r=>{const e=r;return typeof e=="object"&&e!==null&&e.version===1&&typeof e.worker=="string"&&typeof e.production=="string"&&(e.appId===void 0||typeof e.appId=="string")&&(e.sourceEnv===void 0||typeof e.sourceEnv=="string")&&(e.origin===void 0||st(e.origin))&&Array.isArray(e.resources)&&e.resources.every(t=>it(e.worker,t))},ge=async(r,e,t)=>{const n=await r(Ie(e,t));if(!n.ok&&n.status===404)return;const o=k(n,`reading the preview record "${t}"`);if(!at(o))throw new TypeError(`the preview record "${t}" is not one this CLI wrote; refusing to act on it`);return o},j=async(r,e,t)=>{k(await r(Ie(e,D(t.appId??t.production,t.name)),{body:JSON.stringify(t),method:"PUT"}),"writing the preview record")},nr=async(r,e,t)=>{k(await r(Ie(e,D(t.appId??t.production,t.name)),{method:"DELETE"}),"removing the preview record")},Le=async(r,e,t)=>{const n=`${t}/`,o=[];let s="";for(let a=1;;a+=1){if(a>re)throw new Error(`the preview records of "${t}" span more than ${String(re)} pages`);const c=`prefix=${encodeURIComponent(n)}${s===""?"":`&cursor=${encodeURIComponent(s)}`}`,d=k(await r(`/storage/kv/namespaces/${encodeURIComponent(e)}/keys?${c}`),"listing preview records");o.push(...(Array.isArray(d.result)?d.result:[]).flatMap(f=>typeof f.name=="string"?[f.name]:[]));const u=typeof d.result_info=="object"&&d.result_info!==null?d.result_info:{};if(typeof u.cursor!="string"||u.cursor==="")break;s=u.cursor}const i=await Promise.all(o.map(async a=>{try{return{key:a,record:await ge(r,e,a)}}catch(c){if(c instanceof TypeError)return{key:a,unreadable:!0};throw c}}));return{records:i.flatMap(a=>a.record===void 0?[]:[a.record]),unreadable:i.flatMap(a=>a.unreadable===!0?[a.key]:[])}},W=async(r,e,t)=>{if(e==="d1"){const o=await rr(r,`/d1/database?name=${encodeURIComponent(t)}`,"D1 databases",s=>s.name===t);return typeof o?.uuid=="string"?o.uuid:void 0}if(e==="kv")return me(r,t);const n=await r(`/r2/buckets/${encodeURIComponent(t)}`);if(!(!n.ok&&n.status===404))return k(n,`looking up R2 bucket "${t}"`),t},or=async(r,e,t)=>{if(e==="kv")return tr(r,t);if(e==="r2")return k(await r("/r2/buckets",{body:JSON.stringify({name:t}),method:"POST"}),`creating R2 bucket "${t}"`),t;const{uuid:n}=X(k(await r("/d1/database",{body:JSON.stringify({name:t}),method:"POST"}),`creating D1 database "${t}"`));if(typeof n!="string")throw new TypeError(`creating D1 database "${t}" returned no id`);return n},q="lunora-preview-locks",G=1800,ct=/UNIQUE constraint failed|SQLITE_CONSTRAINT/iu,dt="CREATE TABLE IF NOT EXISTS lunora_preview_locks (app_id TEXT NOT NULL, name TEXT NOT NULL, owner_token TEXT NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY (app_id, name))",ut="INSERT INTO lunora_preview_locks (app_id, name, owner_token, expires_at) VALUES (?, ?, ?, unixepoch() + ?)",lt="SELECT owner_token, expires_at, unixepoch() AS now FROM lunora_preview_locks WHERE app_id = ? AND name = ?",ft="UPDATE lunora_preview_locks SET owner_token = ?, expires_at = unixepoch() + ? WHERE app_id = ? AND name = ? AND owner_token = ? AND expires_at <= unixepoch()",wt="DELETE FROM lunora_preview_locks WHERE app_id = ? AND name = ? AND owner_token = ?",E=async(r,e,t,n)=>{const o=await r(`/d1/database/${encodeURIComponent(e)}/query`,{body:JSON.stringify({params:n,sql:t}),method:"POST"});if(!o.ok&&ct.test(o.text))return;const s=k(o,"using the preview lock database").result?.[0];return{changes:typeof s?.meta?.changes=="number"?s.meta.changes:0,rows:Array.isArray(s?.results)?s.results:[]}},pt=4,vt=50,ht=async r=>new Promise(e=>{setTimeout(e,r)}),z="lunora_preview_lock_owner",ir="lunora-preview-locks/v1",mt=`CREATE TABLE IF NOT EXISTS ${z} (marker TEXT NOT NULL)`,gt=`INSERT INTO ${z} (marker) VALUES (?)`,yt="SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",$t=`SELECT marker FROM ${z}`,De=async(r,e)=>((await E(r,e,yt,[z]))?.rows.length??0)===0?!1:(await E(r,e,$t,[]))?.rows.some(o=>o.marker===ir)===!0,sr=async r=>{let e=await W(r,"d1",q),t=!1;if(e===void 0)try{e=await or(r,"d1",q),t=!0}catch(n){if(e=await W(r,"d1",q),e===void 0)throw n}if(t)await E(r,e,mt,[]),await E(r,e,gt,[ir]);else{let n=await De(r,e);for(let o=1;o<=pt&&!n;o+=1)await ht(vt*o),n=await De(r,e);if(!n)throw new Error(`a D1 database named "${q}" exists but was not made by lunora preview (it has no ${z} marker), so it is not used or written to. Rename it, or delete it if it is an empty leftover, then run this again`)}return await E(r,e,dt,[]),e},ar=async(r,e,t,n)=>{const o=V();for(let s=0;s<2;s+=1){if(await E(r,e,ut,[t,n,o,G])!==void 0)return{token:o};const a=(await E(r,e,lt,[t,n]))?.rows[0];if(a===void 0)continue;const c=Number(a.expires_at),d=Number.isFinite(c)&&c<=Number(a.now);return typeof a.owner_token!="string"||!d?{held:new Date(c*1e3).toISOString()}:(await E(r,e,ft,[o,G,t,n,a.owner_token]))?.changes===1?{token:o}:{held:"just now"}}return{held:"just now"}},cr="UPDATE lunora_preview_locks SET expires_at = unixepoch() + ? WHERE app_id = ? AND name = ? AND owner_token = ?",dr=(r,e,t,n,o,s,i=G*1e3/3)=>{let a=Date.now();const c=async()=>{try{(await E(r,e,cr,[G,t,n,o]))?.changes===1?a=Date.now():s()}catch{Date.now()-a>=2*i&&s()}},d=setInterval(()=>{c().catch(()=>{})},i);return d.unref(),()=>{clearInterval(d)}},ur=async(r,e,t,n,o)=>(await E(r,e,cr,[G,t,n,o]))?.changes===1,te=async(r,e,t,n,o)=>{try{await E(r,e,wt,[t,n,o])}catch{}},lr={d1:r=>`/d1/database/${encodeURIComponent(r)}`,kv:r=>`/storage/kv/namespaces/${encodeURIComponent(r)}`,r2:r=>`/r2/buckets/${encodeURIComponent(r)}`},Oe=async(r,e)=>{if(e.pending===!0)return"present";const t=await r(lr[e.kind](e.id));if(!t.ok&&t.status===404)return"missing";const n=X(k(t,`looking up ${e.kind} "${e.name}"`));return{d1:n.name,kv:n.title,r2:n.name}[e.kind]===e.name?"present":"changed"},Pe=10,kt=(r,e)=>{const t=`/r2/buckets/${encodeURIComponent(r)}/objects/`,n=`${t}${e.split("/").map(o=>encodeURIComponent(o)).join("/")}`;return e.split("/").some(o=>o==="."||o==="..")?{error:`the object key ${JSON.stringify(e)} has a "." or ".." segment, which cannot be addressed without leaving the bucket`}:new URL(`https://api.invalid/accounts/a${n}`).pathname.startsWith(`/accounts/a${t}`)?{path:n}:{error:`the object key ${JSON.stringify(e)} resolves outside bucket "${r}"`}},Et=async(r,e,t)=>{const n=kt(e,t);if(n.error!==void 0)throw new Error(`${n.error}; remove the object by hand, then delete the preview again`);const o=await r(n.path,{method:"DELETE"});if(!o.ok&&o.status!==404)throw new Error(`deleting object "${t}" failed (${de(o)})`)},bt=async(r,e)=>{let t="";for(;;){const n=await r(`/r2/buckets/${encodeURIComponent(e)}/objects?per_page=1000`);if(!n.ok&&n.status===404)return;const o=k(n,`listing the objects of R2 bucket "${e}"`),s=(Array.isArray(o.result)?o.result:[]).flatMap(a=>typeof a.key=="string"?[a.key]:[]);if(s.length===0)return;const i=`${String(s.length)}:${s[0]??""}:${s.at(-1)??""}`;if(i===t)throw new Error(`R2 bucket "${e}" still holds the same ${String(s.length)} objects after deleting them`);t=i;for(let a=0;a<s.length;a+=Pe)await Promise.all(s.slice(a,a+Pe).map(async c=>Et(r,e,c)))}},fr=async(r,e)=>{e.kind==="r2"&&await bt(r,e.id);const t=await r(lr[e.kind](e.id),{method:"DELETE"});if(!(t.ok||t.status===404))throw new Error(de(t))},_t=async(r,e)=>{const t=await r(`/workers/scripts/${encodeURIComponent(e)}?force=true`,{method:"DELETE"});if(!t.ok&&t.status!==404)throw new Error(de(t))},ue=async(r,e,t)=>{const n=await r(`/workers/scripts/${encodeURIComponent(e)}/settings`);if(!n.ok&&n.status===404)return{exists:!1};const{bindings:o}=X(k(n,`reading Worker "${e}"`)),s=(Array.isArray(o)?o:[]).find(i=>i.type==="plain_text"&&i.name===t)?.text;return typeof s=="string"?{exists:!0,marker:s}:{exists:!0}},St=async r=>{const{subdomain:e}=X(k(await r("/workers/subdomain"),"reading the workers.dev subdomain"));if(typeof e!="string"||e==="")throw new TypeError("the account has no workers.dev subdomain; register one in the Cloudflare dashboard (Workers & Pages) first");return e},Fe=["deploy","list","delete"],Rt=15e3,It=5,Ot=1e3,we="LUNORA_ADMIN_TOKEN",Tt="LUNORA_PREVIEW_SECRET_SEED",At={celld:"celld has no isolated previews: it has no Wrangler environments, and an app's Durable Objects and storage live in its fleet bucket. Deploy the copy as its own config, with CELLD_BUCKET naming a bucket of its own, and delete that bucket to remove it.",node:"the Node target has no `lunora deploy`, so there is nothing to preview: run a second process with its own database for a copy."},p=(r,e,t=w.USAGE)=>(r.error(e),{code:t,error:e}),C=r=>({environment:r.environment,name:r.name,resources:r.resources,url:r.url,worker:r.worker}),Ct=async(r,e)=>{if(r===void 0)return e();r.begin();try{return await e()}finally{r.end()}},wr=(r,e)=>{const t=pe(r.GITHUB_REPOSITORY)??pe(r.CI_PROJECT_PATH);return t===void 0?void 0:{pullRequest:e,repository:t}},jt=(r,e)=>e!==void 0&&r.origin?.repository===e.repository&&r.origin.pullRequest===e.pullRequest,Ut=r=>`the record for preview "${r}" was not made by a deploy of this pull request in this repository, so the identity the pull request's files name cannot be used to delete it; nothing was deleted`,Nt=(r,e)=>{const t=Se(e.worker,e.resources);return[...B(r.config,t),...r.alsoProduction===void 0?[]:B(r.alsoProduction,t)]},Lt=(r,e,t)=>{Object.assign(r,{origin:wr(e.environment??process.env,t)??r.origin})},Dt=r=>{const e=r.cwd??process.cwd(),t=Ur(e,r.target);if(t.target===void 0)return{error:t.error??"unknown deploy target"};if(t.target!=="cloudflare")return{error:`lunora preview: ${At[t.target]??`target "${t.target}" has no isolated previews.`}`};const n=He(e),o=n===void 0?void 0:$e(n).parsed;return n===void 0||o===void 0?{error:"lunora preview needs a readable wrangler.jsonc (or wrangler.json) in the project root"}:{context:{config:o,cwd:e,appId:ke(e),wranglerPath:n}}},pr=(r,e)=>{if(e.env!==void 0)return ce(r,e.env);const t=zr(r);return t.length>0&&pe((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)===void 0?{error:`environment(s) ${t.join(", ")} name an account_id other than the top level's, so the account to look in is not clear: pass --env <name> to use that environment's account, or set CLOUDFLARE_ACCOUNT_ID`}:{config:r}},Te=(r,e)=>{const{accountId:t,token:n}=Ar(r.environment??process.env,e.account_id);if(t===void 0||n===void 0)return{error:"lunora preview needs CLOUDFLARE_API_TOKEN (Workers Scripts, D1, Workers KV Storage and Workers R2 Storage: Edit) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)"};const o=r.sleep??(async s=>new Promise(i=>{setTimeout(i,s)}));return{request:async(s,i)=>{for(let a=0;;a+=1){const c=await Cr({accountId:t,apiToken:n,...r.fetch===void 0?{}:{fetch:r.fetch},init:{...i,signal:AbortSignal.timeout(Rt)},path:s});if(c.ok||c.status!==429||a===It)return c;await o(Ot*2**a)}}}},Pt=r=>{const e={};for(const t of r){const n=t.indexOf("="),o=n===-1?"":t.slice(0,n);if(o==="")return{error:`--var ${t}: expected KEY=VALUE`};if(o===U)return{error:`--var ${o}: the preview sets ${o} itself; \`delete\` relies on it`};e[o]=t.slice(n+1)}return{variables:e}},$=r=>r instanceof Error?r.message:String(r),Ft=async(r,e,t,n)=>{const o=n.environment??process.env,s={},i=o[Tt],a=h=>i===void 0||i===""?Ir():yr("sha256",i).update(`${t}/${h}`).digest("hex");for(const h of n.secrets??[]){const y=o[h];if(y===void 0||y==="")return{error:`--secret ${h}: ${h} is not set in the environment, so there is no value to give the preview`};s[h]=y}const{fromLocal:c,fromPackages:d,mintableKeys:u}=await Dr(r,void 0);for(const h of[...d,...c,we])s[h]===void 0&&(u.has(h)||h===we)&&(s[h]=a(h));const f=[...new Set([...d,...c])].filter(h=>s[h]===void 0),m=(Array.isArray(e.secrets?.required)?e.secrets.required.filter(h=>typeof h=="string"):[]).filter(h=>s[h]===void 0);return m.length>0?{error:`the config requires ${m.join(", ")}, which a preview only gets when you pass ${m.map(h=>`--secret ${h}`).join(" ")}`}:{adminToken:s[we]??"",missing:f,values:s}},Mt=async(r,e,t,n)=>{const o=await Oe(r,t);if(o!=="present")throw new Error(`the record lists ${t.kind} "${t.name}" (${t.id}), which is ${o==="missing"?"gone":"now a different resource"}; run \`lunora preview delete ${e.slug}\`, then deploy again`);return n.info(`reusing preview ${t.kind} "${t.name}" for ${t.binding}`),t.id},Wt=3,xt=async(r,e,t,n)=>{let o;for(let s=1;s<=Wt;s+=1)try{await j(r,e,t);return}catch(i){o=i}try{await fr(r,n),t.resources.splice(t.resources.indexOf(n),1),await j(r,e,t).catch(()=>{})}catch{n.pending=!0}throw new Error(`${$(o)}; the ${n.kind} "${n.name}" just made could not be recorded, so it was removed again`)},Me=async(r,e,t,n,o)=>{let s=t.resources.find(i=>i.kind===n.kind&&i.binding===n.binding);if(s===void 0){if(await W(r,n.kind,n.name)!==void 0)throw new Error(`a ${n.kind} resource named "${n.name}" already exists but no preview record says this preview created it; refusing to bind or later delete it. Rename or remove it, then deploy again.`);s={binding:n.binding,id:n.kind==="r2"?n.name:"",kind:n.kind,name:n.name,pending:!0},t.resources.push(s),await j(r,e,t)}return s.id=await or(r,n.kind,n.name),delete s.pending,await xt(r,e,t,s),o.success(`created preview ${n.kind} "${n.name}" for ${n.binding}`),s.id},Kt=async(r,e,t,n,o,s,i)=>{const a=n.resources.find(c=>c.kind===o.kind&&c.binding===o.binding);if(i(),a?.pending===!0){if(await W(r,o.kind,o.name)!==void 0)throw new Error(`a ${o.kind} resource named "${o.name}" exists, but the record only claims it (a deploy was interrupted between creating it and confirming it), so nothing shows it is this preview's and it is left alone. If it is, delete it by hand, then deploy again`);return Me(r,e,n,o,s)}return a===void 0?Me(r,e,n,o,s):Mt(r,t,a,s)},Ht=async(r,e,t,n,o,s)=>{const i=new Map;for(const a of t.resources)i.set(_e(a.kind,a.binding),await Kt(r,e,t,n,a,o,s));return i},Ae=async(r,e,t)=>{const n=new Set((t?.resources??[]).map(i=>`${i.kind}:${i.name}`)),o=e.filter(i=>!n.has(`${i.kind}:${i.name}`));return(await Promise.all(o.map(async i=>await W(r,i.kind,i.name)===void 0?[]:[i]))).flat().map(i=>`${i.kind} "${i.name}"`)},vr=async(r,e,t,n,o,s,i=!0)=>{if(t!==void 0){const d=await ge(r,e,D(t,o));if(d!==void 0){if(d.appId!==t||d.name!==o)throw new Error(`the record at "${D(t,o)}" does not name this project and preview; refusing to act on it`);return d}}const a=await ge(r,e,D(n,o));if(a===void 0)return;if(a.appId!==void 0||a.production!==n||a.name!==o||a.worker!==ae(n,o))throw new Error(`the record at "${D(n,o)}" is not the one this CLI wrote for that Worker and preview; refusing to act on it`);if(t===void 0)throw new Error(`preview "${o}" is recorded under the Worker name, from before projects had an id. Add an app id to package.json (\`"lunora": { "appId": "${V()}" }\`), commit it, and run this again: it re-keys the record`);const c={...a,appId:t};return i&&(await j(r,e,c),await nr(r,e,a),s.warn(`preview "${o}" was recorded under the Worker name "${n}"; it is now recorded under project ${t}`)),c},Bt=async(r,e,t,n)=>{if(t===void 0&&n)return{code:w.USAGE,error:`a Worker named "${e.worker}" exists but no preview record says this preview deployed it; refusing to deploy over it`};if(t!==void 0&&t.worker!==e.worker)return{code:w.USAGE,error:`the record for preview "${e.slug}" names Worker "${t.worker}", not "${e.worker}" (the app was renamed since it was deployed); run \`lunora preview delete ${e.slug}\` first, then deploy it again`};const o=await Ae(r,e.resources,t);return o.length===0?void 0:{code:w.FAILURE,error:`${o.join(", ")} already exist(s) but no preview record read says this preview created it, so nothing was written or deployed. If a deploy of this preview just ran, its record may not have reached this location yet: run the deploy again. Otherwise rename or remove it, then deploy again.`}},Gt=r=>{const e=Er(ee(br(),"lunora-preview-")),t=ee(e,"secrets.json");return ne(t,JSON.stringify(r),{encoding:"utf8",mode:384}),{directory:e,path:t}},Vt=r=>({environment:r.environment,name:r.slug,resources:r.resources,worker:r.worker}),Yt=(r,e,t)=>{r.info(`dry run: preview "${e.slug}" would deploy Worker "${e.worker}" (env.${e.environment}, its own Durable Object namespace)`);for(const s of e.resources)r.info(` ${s.kind} "${s.name}" for ${s.binding} (created, or reused when this preview's record lists it)`);const{vars:n}=t,o=n===void 0?t:{...t,vars:Object.fromEntries(Object.keys(n).map(s=>[s,"<redacted>"]))};r.info(` env.${e.environment}: ${JSON.stringify(o)}`)},hr=(r,e)=>`another run is deploying or deleting preview "${r}" (its hold lapses at ${e}); wait for it. A run that crashed lets go by itself`,mr=(r,e,t)=>{const n=`the hold on preview "${e}" was lost while this run worked, so another run may have changed it too; check it with \`lunora preview list\` and run \`lunora preview delete ${e}\` if it looks wrong`;return r.error(n),{...t,code:t.code===w.SUCCESS?w.FAILURE:t.code,error:n}},Jt=async(r,e,t)=>{try{const n=await ue(r,e,U);return n.exists&&n.marker===t?"present":"absent"}catch{return"unknown"}},ye=(r,e)=>{if(r.lost)throw new Error(`the hold on preview "${e}" can no longer be vouched for, so this run stopped before changing anything more; check it with \`lunora preview list\`, then run again`)},Xt=async(r,e,t,n,o,s)=>{const{config:i,cwd:a,wranglerPath:c}=r,{logger:d}=n,{appId:u,hold:f,namespace:l,secrets:m,subdomain:h}=s;let y,_;const v=`https://${e.worker}.${h}.workers.dev`;try{const g=await ue(o,e.worker,U);if(g.exists&&g.marker!==M(e))return p(d,`a Worker named "${e.worker}" already exists and was not deployed as preview "${e.slug}"; refusing to deploy over it`);const b=new Date().toISOString(),T=await vr(o,l,u,e.production,e.slug,d),A=await Bt(o,e,T,g.exists);if(A!==void 0)return p(d,A.error,A.code);const N=B(r.committed??i,Se(e.worker,T?.resources??[]));if(N.length>0)return p(d,`preview "${e.slug}" would bind production's ${N.join(", ")}; refusing to deploy, nothing was created`);y=T??{createdAt:b,environment:e.environment,name:e.slug,production:e.production,appId:u,...e.sourceEnv===void 0?{}:{sourceEnv:e.sourceEnv},resources:[],updatedAt:b,version:1,worker:e.worker},Lt(y,n,e.slug),await f.verify(),await j(o,l,y),_=await Ht(o,l,e,y,d,()=>{ye(f,e.slug)})}catch(g){return p(d,`preview "${e.slug}": ${$(g)}`,w.FAILURE)}const O=B(r.committed??i,[..._].map(([g,b])=>({kind:g.slice(0,g.indexOf(":")),value:b})));if(O.length>0)return p(d,`preview "${e.slug}" would bind production's ${O.join(", ")}; refusing to deploy`);const x=L(c,"utf8");ne(c,Tr(x,["env",e.environment],qe(i,e,_,t,v)),"utf8");const S=Gt(m.values),K=ie(()=>{F(S.directory,{force:!0,recursive:!0})});try{ye(f,e.slug);const g=await Ct(r.baseline,async()=>Pr({allowSchemaDrift:!0,cwd:a,env:e.environment,fetchImpl:n.adminFetch,format:n.format,healthCheck:!0,healthFetch:n.healthFetch,healthSleep:n.healthSleep,interactive:!1,isolatedPreview:!0,logger:d,migrate:!0,migrateToken:m.adminToken,migrateUrl:v,migrateYes:!0,secretsFile:S.path,spawner:n.spawner,target:"cloudflare"})),b=g.code===0?"present":await Jt(o,e.worker,M(e));if(b==="present"?y.url=v:b==="absent"&&delete y.url,y.updatedAt=new Date().toISOString(),await f.verify(),await j(o,l,y),g.code!==0)return{code:g.code,data:{preview:C(y)},error:g.error??`preview "${e.slug}" did not deploy`}}catch(g){return p(d,`preview "${e.slug}": ${$(g)}`,w.FAILURE)}finally{F(S.directory,{force:!0,recursive:!0}),K()}if(n.seed===!0){const g=await Fr({cwd:a,fetchImpl:n.adminFetch,format:n.format,logger:d,prod:!0,token:m.adminToken,url:y.url,yes:!0});if(g.code!==0)return{code:g.code,data:{preview:C(y)},error:g.error??`seeding preview "${e.slug}" failed`}}return d.success(`preview "${e.slug}" is live at ${y.url??v} — remove it with \`lunora preview delete ${e.slug}\``),{code:w.SUCCESS,data:{preview:C(y)}}},zt=async(r,e,t,n,o)=>{const{appId:s,config:i,cwd:a}=r,{logger:c}=n;if(s===void 0)return p(c,"the project has no id to key the preview record by");const d=await Ft(a,i,e.worker,n);if(d.error!==void 0)return p(c,d.error);for(const v of d.missing)c.warn(`the preview has no ${v}: production's is never copied. Pass --secret ${v} with ${v} set in the environment to give it one.`);let u,f,l,m;try{f=await St(o),u=await Re(o,!0)??"",l=await sr(o);const v=await ar(o,l,s,e.slug);if(v.held!==void 0)return p(c,hr(e.slug,v.held));({token:m}=v)}catch(v){return p(c,`preview "${e.slug}": ${$(v)}`,w.FAILURE)}const h={lost:!1,verify:async()=>{if(!await ur(o,l,s,e.slug,m))throw h.lost=!0,new Error(`the hold on preview "${e.slug}" is no longer this run's, so its record was left as the other run has it`)}},y=dr(o,l,s,e.slug,m,()=>{h.lost=!0}),_=ie(async()=>{y(),await te(o,l,s,e.slug,m)});try{const v=await Xt(r,e,t,n,o,{appId:s,hold:h,namespace:u,secrets:d,subdomain:f});return h.lost?mr(c,e.slug,v):v}finally{y(),await te(o,l,s,e.slug,m),_()}},Qt=(r,e)=>{if(r.appId!==void 0)return{appId:r.appId};const t=e.environment??process.env,n='package.json has a "lunora.appId" that is not a UUID, or no `lunora` object this CLI can add one to';if(e.dryRun===!0)return e.logger.info(" app id: none yet; the first deploy writes one to package.json for you to commit"),{appId:void 0};if(t.CI!==void 0&&t.CI!==""&&t.CI!=="false")return{error:`package.json has no "lunora.appId", and a CI run cannot mint one (its checkout is discarded, so the preview could never be found again to delete). Commit \`"lunora": { "appId": "${V()}" }\` to package.json`};const o=Vr(r.cwd);return o===void 0?{error:n}:(e.logger.warn(`wrote an app id to package.json ("lunora.appId"); commit it so CI finds this project's previews`),{appId:o})},Zt=async(r,e,t)=>{const{cwd:n}=r,{logger:o}=e,s=Pt(e.vars??[]);if(s.error!==void 0)return p(o,s.error);const{variables:i}=s,a=Wr(n);if(a.error!==void 0)return p(o,a.error);const c=Qt(r,e);if(c.error!==void 0)return a.release(),p(o,c.error);let d=()=>{};const u=ee(n,"lunora",Sr);let f;try{f=Q(u)?L(u):void 0}catch(v){return a.release(),p(o,`could not read ${u}: ${$(v)}`)}let l=!1,m;const h={begin:()=>{l=!0},end:()=>{m=Q(u)?L(u):void 0,l=!1}},y=()=>{try{if(d(),f===void 0){const v=Q(u)?L(u):void 0;v!==void 0&&(l||m!==void 0&&v.equals(m))&&F(u,{force:!0})}else f.equals(Q(u)?L(u):Buffer.alloc(0))||ne(u,f)}finally{a.release()}},_=ie(y);try{d=Nr(n),await Lr(n,o,void 0,"cloudflare",void 0);const{services:v}=Rr(n);if(v.length>0)return p(o,`this app cannot be previewed in isolation yet: it declares lunora.config services (${v.map(A=>A.name).join(", ")}), which a preview would share with production`);const O=$e(r.wranglerPath).parsed??r.config,x=e.env===void 0?{config:O}:ce(O,e.env);if(x.error!==void 0)return p(o,x.error);const{config:S}=x,K=Ze(S,t,e.env);if(K.error!==void 0)return p(o,K.error);const{plan:g}=K,b=B(O,Se(g.worker,g.resources));if(b.length>0)return p(o,`preview "${g.slug}" names collide with production's ${b.join(", ")}; name the preview differently`);if(e.dryRun===!0){const A=new Map(g.resources.map(N=>[_e(N.kind,N.binding),`<${N.name}>`]));return Yt(o,g,qe(S,g,A,i,`https://${g.worker}.<your-subdomain>.workers.dev`)),o.info(` secrets: every one Lunora can mint, fresh${(e.secrets??[]).length>0?`; from the environment: ${(e.secrets??[]).join(", ")}`:""}`),{code:w.SUCCESS,data:{plan:Vt(g)}}}const T=Te(e,S);return T.error!==void 0?p(o,T.error,w.AUTH):await zt({...r,baseline:h,committed:O,config:S,appId:c.appId},g,i,e,T.request)}finally{y(),_()}},qt=async(r,e,t)=>{try{if(e.pending===!0)return await W(r,e.kind,e.name)===void 0?!0:(t.error(`${e.kind} "${e.name}" exists, but the record only claims it (a deploy was interrupted before confirming it), so nothing shows it is this preview's: it was left alone. If it is, delete it by hand, then run \`lunora preview delete\` again`),!1);const n=await Oe(r,e);return n==="changed"?(t.error(`${e.kind} "${e.name}" (${e.id}): the recorded id now names a different resource, so it was left alone`),!1):(n==="present"&&(await fr(r,e),t.success(`deleted ${e.kind} "${e.name}"`)),!0)}catch(n){return t.error(`deleting ${e.kind} "${e.name}" failed (${$(n)}); it stays on record for the next \`lunora preview delete\``),!1}},en=async(r,e,t,n,o,s,i)=>{try{s();const u=await ue(r,t.worker,U);if(u.exists&&u.marker!==M({production:t.production,slug:t.name}))return p(o,`Worker "${t.worker}" was not deployed as preview "${t.name}"; refusing to delete anything`);u.exists&&(await _t(r,t.worker),o.success(`deleted Worker "${t.worker}"`))}catch(u){return p(o,`deleting Worker "${t.worker}" failed (${$(u)}); its resources were left in place`,w.FAILURE)}const a=[];for(const u of t.resources)s(),await qt(r,u,o)||a.push(u);const c={...t,resources:a,updatedAt:new Date().toISOString()};let d;try{d=await Ae(r,n?.resources??[],t),d.length===0&&(await i(),await(a.length===0?nr(r,e,t):j(r,e,c)))}catch(u){return p(o,`preview "${t.name}": ${$(u)}`,w.FAILURE)}return d.length>0?p(o,`${d.join(", ")} exist(s) under this preview's names but not in the record read (a deploy may have just recorded it); the record was left as it is — run \`lunora preview delete ${t.name}\` again. If that keeps failing, the resource was never recorded (a deploy stopped between creating and recording it): delete it by hand, then run delete once more`,w.FAILURE):a.length>0?{code:w.FAILURE,data:{preview:C(c)},error:`${String(a.length)} preview resource(s) could not be deleted`}:{code:w.SUCCESS,data:{deleted:C(t)}}},rn=async(r,e,t)=>{const n=[{config:e}];for(const s of Object.keys(e.env??{})){const i=ce(e,s);i.config!==void 0&&n.push({config:i.config,env:s})}const o=await Promise.all(n.map(async s=>{const{names:i}=be(s.config,t);if(i===void 0)return[];const a=Qe(s.config,i.worker),c=await ue(r,i.worker,U),d=await Ae(r,a,void 0);return[...c.exists&&c.marker===M(i)?[`Worker "${i.worker}" exists`]:[],...d.map(u=>`${u} exists`)]}));return[...new Set(o.flat())]},tn=(r,e)=>{const t=e.sourceEnv===void 0?{config:r}:ce(r,e.sourceEnv);return t.config===void 0?void 0:Ze({...t.config,name:e.production},e.name,e.sourceEnv).plan},nn=async(r,e,t,n)=>{const o=await rn(r,e,t);return o.length===0?void 0:p(n,`no record of preview "${t}" could be read, but ${o.join(" and ")}; nothing was deleted. If a deploy just ran, its record may not have reached this location yet: run delete again. Otherwise delete from a checkout whose package.json has the lunora.appId that deployed it`,w.FAILURE)},on=(r,e)=>{e.info(`dry run: would delete Worker "${r.worker}" and its Durable Objects`);for(const t of r.resources)e.info(` ${t.kind} "${t.name}" (${t.binding})`);return{code:w.SUCCESS,data:{plan:C(r)}}},sn=(r,e,t)=>e.worker===ae(e.production,e.name)&&e.appId===r.appId&&e.name===t,We=async(r,e,{hold:t,names:n,namespace:o,request:s})=>{const{config:i}=r,{logger:a}=e;let c;try{if(c=o===void 0?void 0:await vr(s,o,r.appId,n.production,n.slug,a,e.dryRun!==!0),o===void 0||c===void 0){const l=await nn(s,i,n.slug,a);if(l!==void 0)return l}}catch(l){return p(a,`preview "${n.slug}": ${$(l)}`,w.FAILURE)}if(o===void 0||c===void 0)return p(a,`no preview "${n.slug}" of "${n.production}" is on record; nothing was deleted`,w.NOT_FOUND);const d=Nt(r,c);if(!sn(r,c,n.slug)||d.length>0)return p(a,`the record for preview "${n.slug}" names ${d.length>0?`production's ${d.join(", ")}`:`Worker "${c.worker}", which is not the Worker of this preview`}; refusing to delete anything`);if(r.requireOrigin===!0&&!jt(c,wr(e.environment??process.env,n.slug)))return p(a,Ut(n.slug),w.FAILURE);let u;try{u=await Promise.all(c.resources.map(async l=>Oe(s,l)))}catch(l){return p(a,`preview "${n.slug}": ${$(l)}`,w.FAILURE)}const f=c.resources.filter((l,m)=>u[m]==="changed");return f.length>0?p(a,`the record for preview "${n.slug}" lists ${f.map(l=>`${l.kind} ${l.id}`).join(", ")}, which no longer name(s) the recorded resource; refusing to delete anything`):e.dryRun===!0?on(c,a):en(s,o,c,tn(i,c),a,()=>{ye(t,c.name)},t.verify)},P=async(r,e,t)=>{const{config:n}=r,{logger:o}=e,s=be(n,t);if(s.error!==void 0)return p(o,s.error);const{names:i}=s,a=pr(n,e);if(a.error!==void 0)return p(o,a.error,e.env===void 0?w.AUTH:w.USAGE);const c=Te(e,a.config);if(c.error!==void 0)return p(o,c.error,w.AUTH);const{request:d}=c;let u;try{u=await Re(d,!1)}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}if(r.appId===void 0||u===void 0||e.dryRun===!0)return We(r,e,{hold:{lost:!1,verify:()=>Promise.resolve()},names:i,namespace:u,request:d});const{appId:f}=r;let l,m;try{l=await sr(d);const v=await ar(d,l,f,i.slug);if(v.held!==void 0)return p(o,hr(i.slug,v.held));({token:m}=v)}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}const h={lost:!1,verify:async()=>{if(!await ur(d,l,f,i.slug,m))throw h.lost=!0,new Error(`the hold on preview "${i.slug}" is no longer this run's, so its record was left as the other run has it`)}},y=dr(d,l,f,i.slug,m,()=>{h.lost=!0}),_=ie(async()=>{y(),await te(d,l,f,i.slug,m)});try{const v=await We(r,e,{hold:h,names:i,namespace:u,request:d});return h.lost?mr(o,i.slug,v):v}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}finally{y(),await te(d,l,f,i.slug,m),_()}},an=async(r,e)=>{const{config:t}=r,{logger:n}=e,o=typeof t.name=="string"?t.name:"",s=pr(t,e);if(s.error!==void 0)return p(n,s.error,e.env===void 0?w.AUTH:w.USAGE);const i=Te(e,s.config);if(i.error!==void 0)return p(n,i.error,w.AUTH);let a;try{const c=await Re(i.request,!1),d={records:[],unreadable:[]},u=c===void 0||r.appId===void 0?d:await Le(i.request,c,r.appId),f=c===void 0?d:await Le(i.request,c,o);a=[...u.records,...f.records],f.records.length>0&&n.warn(`${String(f.records.length)} preview(s) are recorded under the Worker name, from before projects had an id: ${f.records.map(l=>l.name).join(", ")}. ${r.appId===void 0?"Add an app id to package.json, then run":"Run"} \`lunora preview delete <name>\` (or deploy it again) to re-key each`);for(const l of[...u.unreadable,...f.unreadable])n.warn(`the registry key "${l}" is not a preview record this CLI wrote; it is not listed, and \`delete\` will refuse it`)}catch(c){return p(n,$(c),w.FAILURE)}a.length===0&&n.info(`no previews of "${o}" are on record`);for(const c of a)n.info(`${c.name} ${c.url??"(not deployed)"} Worker ${c.worker}, ${String(c.resources.length)} resource(s), updated ${c.updatedAt}`);return{code:w.SUCCESS,data:{previews:a.map(c=>C(c))}}},cn=/^[\dA-Za-z][\w-]{0,62}$/u,dn=r=>{const e=ke(r);if(e===void 0)return{error:'its package.json has no readable "lunora.appId"'};const t=He(r);let n;try{n=t===void 0?void 0:$e(t).parsed}catch{n=void 0}const o=n?.name;return n===void 0||typeof o!="string"||!cn.test(o)?{error:"its wrangler config has no readable, valid Worker name"}:{identity:{appId:e,config:n,production:o}}},un=async(r,e,t,n)=>{const o=[...e];if(o.some(i=>i.code===w.SUCCESS)){for(const[i,a]of o.entries())if(a.code!==w.SUCCESS&&a.code!==w.NOT_FOUND){const c=await P(r[i],t,n);o[i]=c.code===w.NOT_FOUND?{code:w.SUCCESS}:c}}const s=o.find(i=>i.code!==w.SUCCESS&&i.code!==w.NOT_FOUND);return s!==void 0?s:o.find(i=>i.code===w.SUCCESS&&i.data!==void 0)??o.find(i=>i.code===w.SUCCESS)??p(t.logger,`no preview "${n}" is on record under this checkout's project or under the pull request head's, whose id or Worker name differs; nothing was deleted`,w.FAILURE)},ln=async(r,e,t,n)=>{const o=dn(n);if(o.error!==void 0){e.logger.warn(`the pull request head's identity could not be read (${o.error}); looking for the preview under this checkout's only`);const l=await P(r,e,t);return l.code===w.NOT_FOUND?p(e.logger,`no preview "${t}" is on record under this checkout's project, and the pull request head's identity could not be read (${o.error}), so it cannot be ruled out under that; nothing was deleted`,w.FAILURE):l}const{appId:s,config:i,production:a}=o.identity,c={...r,alsoProduction:i};if(s===r.appId&&a===r.config.name)return P(c,e,t);const d={...c,appId:s,config:{...r.config,...typeof i.account_id=="string"?{account_id:i.account_id}:{},name:a},requireOrigin:!0},u=[c,d],f=[await P(c,e,t),await P(d,e,t)];return un(u,f,e,t)},fn=async r=>{const{logger:e,subcommand:t}=r;if(!Fe.includes(t))return p(e,`usage: lunora preview <${Fe.join(" | ")}> [name]`);const n=Dt(r);return n.error!==void 0?p(e,n.error):r.headDir!==void 0&&t!=="delete"?p(e,"--head-dir applies to `lunora preview delete` only"):t==="list"?an(n.context,r):r.name===void 0||r.name===""?p(e,`usage: lunora preview ${t??""} <name> — e.g. the pull request number`):t==="deploy"?Zt(n.context,r,r.name):r.headDir===void 0?P(n.context,r,r.name):ln(n.context,r,r.name,r.headDir)},Rn=jr(async({argument:r,cwd:e,format:t,logger:n,options:o})=>{const s=await fn({cwd:e,dryRun:o.dryRun===!0,env:o.env,format:t,headDir:o.headDir,logger:n,name:r[1],secrets:o.secret??[],seed:o.seed===!0,subcommand:r[0],target:o.target,vars:o.var});return{code:s.code,data:s.data,error:s.error}});export{Rn as execute,fn as runPreviewCommand};