@lunora/runtime 1.0.0-alpha.303 → 1.0.0-alpha.304

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/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as E,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-BVogmTPJ.mjs";import{composeWorker as d,createLunoraHandler as l,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-CTThROLf.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-C3IBzt-b.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-CMyD7rin.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-Cbr1Sdt3.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-8_qnPWNH.mjs";import{a as ne,c as ce,b as me,o as fe,p as xe,w as Ee}from"./packem_shared/observability-sinks-BA76CH4h.mjs";import{D as Se,c as de}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-BuoncR2C.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-q5V06Etw.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-D5NWHmVl.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-0DqdJ04h.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-M_c0MHVS.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{loadStudioDocument as Be}from"./packem_shared/loadStudioDocument-BSYQEMnd.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as ze}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as je}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as We,routeIdentityResolvers as qe}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,ze as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,je as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,We as composeIdentityResolvers,d as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,l as createLunoraHandler,M as createMemoryCursorStore,de as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,Be as loadStudioDocument,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,xe as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,qe as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,E as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,Ee as webhookSink,b as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as E,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-BVogmTPJ.mjs";import{composeWorker as d,createLunoraHandler as l,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-BrPDyfY9.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-C3IBzt-b.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-CMyD7rin.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-Cbr1Sdt3.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-8_qnPWNH.mjs";import{a as ne,c as ce,b as me,o as fe,p as xe,w as Ee}from"./packem_shared/observability-sinks-BA76CH4h.mjs";import{D as Se,c as de}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-BuoncR2C.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-q5V06Etw.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-D5NWHmVl.mjs";import{d as Ie,e as De,h as Fe,r as Me}from"./packem_shared/security-headers-0DqdJ04h.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-M_c0MHVS.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{loadStudioDocument as Be}from"./packem_shared/loadStudioDocument-BSYQEMnd.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as ze}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as je}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as We,routeIdentityResolvers as qe}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,ze as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,je as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,We as composeIdentityResolvers,d as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,l as createLunoraHandler,M as createMemoryCursorStore,de as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,Be as loadStudioDocument,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,xe as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,qe as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,E as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,Ee as webhookSink,b as withFrameworkWorker};
@@ -1,5 +1,5 @@
1
- import{isLunoraError as Ur,toErrorBody as yi}from"@lunora/errors";import{encodeWire as Re,decodeWire as Nt,encodeArgsOrThrow as _i}from"@lunora/wire";import{t as Un,f as Cn,a as Cr,b as Kt}from"./base64-DANXv-kI.mjs";import{e as kt,b as bi}from"./memoize-identity-Cbr1Sdt3.mjs";import{d as yo,E as _o,a as Si,b as Ei,W as bo}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as Ai}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as Ti,a as vi,i as Ri,e as Oi,E as So,b as Ii}from"./identity-header-DqrLFqFq.mjs";import{O as Lr,a as Mr}from"./origin-paywall-B6eOO67m.mjs";import{o as Je,b as $r,p as Ni,m as ki,d as Di,a as Pi,r as Ui}from"./otlp-resource-BBR8xs6m.mjs";import{r as Ci,f as Eo,a as Ce,S as Ao}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as To}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as ve,applyJurisdiction as gt}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ae,e as we,M as Br,b as Li,f as Mi,g as xr,w as $i,h as Hr,t as jr}from"./rest-routes-D5NWHmVl.mjs";import{a as Y,m as ke}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Ln,BACKUP_KEY_PREFIX as Mn,isBackupManifestKey as Bi,backupObjectKeyOfManifest as Kr,backupObjectKey as xi,backupManifestKey as Hi}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as et,STORAGE_UPLOAD_MAX_BODY_BYTES as $e,buildStorageAdminRoutes as ji,STORAGE_PATH as Ki}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Gi,e as Fi,f as vo,g as Wi,h as Qi}from"./export-tap-CMyD7rin.mjs";import{sha256 as Gr}from"@noble/hashes/sha2.js";import{buildHealthRoutes as Vi,durableObjectProbe as zi,d1Probe as Ji,presenceProbe as on}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Yi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Vm,routeIdentityResolvers as zm}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Xi}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as Zi,createQueryCoordinator as qi,createDefaultShardRegistry as ec,refreshShardHeadersPerCall as tc,refreshedShardHeaders as nc}from"./createQueryCoordinator-BuoncR2C.mjs";import{i as Ro,r as Oo,h as oc,e as rc,d as rn,a as Io}from"./security-headers-0DqdJ04h.mjs";const sc=(e,t,n,o)=>{const r=e.get(t);if(r!==void 0)return r;kt(e,o);const s=n().catch(a=>{throw e.get(t)===s&&e.delete(t),a});return e.set(t,s),s},ac=new TextEncoder,ic=64,cc=new Map,Fr=async e=>sc(cc,e,async()=>crypto.subtle.importKey("raw",ac.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ic),Wr=new TextEncoder,dc=Array.from({length:32},(e,t)=>t);new RegExp(`[${dc.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Gt=async(e,t)=>{const n=await Fr(e),o=await crypto.subtle.sign("HMAC",n,Wr.encode(t));return Un(new Uint8Array(o))},Qr=async(e,t,n)=>{const o=await Fr(e);return crypto.subtle.verify("HMAC",o,n,Wr.encode(t))},Vr="lnat",uc="__lunora_admin_revocations__",lc=/^[a-z0-9][a-z0-9_-]{0,63}$/u,hc=/^[\w-]{43}$/u,Rt="x-lunora-admin-signal",fc="as1",pc=6e4,mc=5e3,zr=e=>lc.test(e),wc=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Vr)return;const[,n,o]=t;return zr(n)&&hc.test(o)?{name:n,secret:o}:void 0},Jr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:wc(t[1])},gc=e=>{const t=Un(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Vr}.${e}.${t}`}},Yr=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),yc=async(e,t,n=Date.now(),o=Number.POSITIVE_INFINITY)=>{const r=`${fc}.${String(Math.floor(Math.min(n+pc,o)))}.${t}`;return`${r}.${await Gt(e,r)}`},Xr=["migrations"],Zr=e=>Xr.some(t=>t===e),An=["disabled","schema","schema_and_log","schema_and_log_and_data"],_c="schema",bc=e=>e==null||e===""?_c:typeof e=="string"&&An.includes(e)?e:"disabled",Sc=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,r={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return r.bucket=()=>r,r},qr="__lunoraBranch",Ec=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,qr),Ac=`may not contain the reserved workflow branch-marker key ("${qr}")`,Tc=new Set(["exp","expiresAtMs","iat","jti","nbf"]),Tn=e=>Array.isArray(e)?`[${e.map(t=>Tn(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[o])=>n<o?-1:n>o?1:0).map(([n,o])=>`${JSON.stringify(n)}:${Tn(o)}`).join(",")}}`:JSON.stringify(e)??"null",vc=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Tc.has(n)));return Object.keys(t).length===0?"":Tn(t)},Rc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ae=(e,t)=>e>>>t|e<<32-t,Oc=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(n.length-8,Math.floor(e.length*8/2**32)),o.setUint32(n.length-4,e.length*8>>>0);const r=new Uint32Array(64);for(let d=0;d<n.length;d+=64){for(let _=0;_<16;_+=1)r[_]=o.getUint32(d+_*4);for(let _=16;_<64;_+=1){const S=r[_-15],O=r[_-2],T=Ae(S,7)^Ae(S,18)^S>>>3,U=Ae(O,17)^Ae(O,19)^O>>>10;r[_]=r[_-16]+T+r[_-7]+U>>>0}let[c,h,p,m,g,R,E,b]=t;for(let _=0;_<64;_+=1){const S=Ae(g,6)^Ae(g,11)^Ae(g,25),O=g&R^~g&E,T=b+S+O+Rc[_]+r[_]>>>0,U=Ae(c,2)^Ae(c,13)^Ae(c,22),v=c&h^c&p^h&p,x=U+v>>>0;b=E,E=R,R=g,g=m+T>>>0,m=p,p=h,h=c,c=T+x>>>0}[c,h,p,m,g,R,E,b].forEach((_,S)=>{t[S]=t[S]+_>>>0})}const s=new Uint8Array(32),a=new DataView(s.buffer);return t.forEach((d,c)=>{a.setUint32(c*4,d)}),s},Ic=(e,t)=>Un(Oc(new TextEncoder().encode(`${JSON.stringify(e??null)}|${vc(t)}`)).subarray(0,16)),Nc=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},kc=/^\w[\w-]{0,99}$/u,Dc="`dedupKey` must match ^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$",Pc=e=>typeof e=="string"&&kc.test(e),Uc=9e5,Cc="x-lunora-dispatch-declined",Lc=/already[\s_-]?exists/iu,Mc=e=>Lc.test(e instanceof Error?e.message:String(e)),$c="/_lunora/live/publish",Bc="cf-ray",xc="x-lunora-ray-id",Hc=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,jc=e=>e==null?void 0:Hc.exec(e.trim())?.[1]?.toLowerCase(),Kc=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Kc);const Gc=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Fc=-100,Wc=15,Qc=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Gc.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Wc?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Fc?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},No=e=>{const t=e.cf;return t===void 0?void 0:Qc(t)},Ft="::relay::",Vc=(e,t)=>`${e}${Ft}${String(t)}`,Wt="::replica::",zc=(e,t)=>`${e}${Wt}${t}`,Jc=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Yc=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},es=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let r=0;r<n;r+=1){const s=r<e.length?e.charCodeAt(r):0,a=r<t.length?t.charCodeAt(r):0;o|=s^a}return o===0},Xc="/_lunora/scheduler/dispatch",Zc="__lunora_relation__:",qc=e=>e.startsWith(Zc),ts="agents:agentRun",ed=(e,t,n)=>e===ts&&t!==n,td=`\`${ts}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,Dt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...r]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:es(t,r.join(" ").trim())},nd="x-lunora-scheduler-signature",od="x-lunora-scheduler-timestamp",rd=5*6e4,sd=e=>["v1",String(e.timestamp),e.userId??"",e.identity??"",e.body].join(`
2
- `),ad=(e,t)=>Gt(e,sd(t)),id=async(e,t,n)=>{const o=e.headers.get(nd),{schedulerSecret:r}=n;if(o!==null&&o.length>0&&r!==void 0&&r.length>0){const s=e.headers.get(od);if(s===null||!/^\d+$/u.test(s))return!1;const a=Number(s);if(!Number.isSafeInteger(a)||Math.abs((n.now??Date.now)()-a)>rd)return!1;const d=await ad(r,{body:t,identity:e.headers.get("x-lunora-identity")??void 0,timestamp:a,userId:e.headers.get("x-lunora-userid")??void 0});return es(d,o)}return Dt(e,n.adminToken)},ko="/_lunora/ws/reauth",cd="/_lunora/claims",dd="x-lunora-scheduled-for",ud=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:o})=>{const r={"content-type":"application/json",[Mr]:Lr,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),o!==void 0&&o.length>0&&(r.traceparent=o),n!==void 0&&Number.isFinite(n)&&(r[dd]=String(Math.trunc(n))),r},ld=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},hd=(e,t,n)=>e?.[n]??t?.[n],fd=(e,t,n,o)=>{const r=hd(e,t,n);if(!(typeof r!="object"||r===null))return o.every(s=>typeof r[s]=="function")?r:void 0},ns="v1",pd=6e4,md=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??pd),o=`${ns}.${String(n)}`,r=await Gt(e,o);return{expiresAtMs:n,token:`${o}.${r}`}},wd=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[r,s,a]=o;if(r!==ns||a.length===0)return!1;const d=Number(s);if(!Number.isFinite(d)||d<=n)return!1;let c;try{c=Cn(a)}catch{return!1}return Qr(e,`${r}.${s}`,c)},gd="https://admin-revocations.internal",yd=(e,t)=>{const n=async(o,r)=>{const s=t();if(s===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const a=await ve(e,uc).fetch(new Request(`${gd}${o}`,{...r,headers:{authorization:`Bearer ${s}`,"content-type":"application/json"}}));if(!a.ok)throw new l(`admin revocation store answered ${String(a.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return a};return{revoke:async(o,r)=>{await n("/revoke",{body:JSON.stringify({createdAt:r,name:o}),method:"POST"})},isRevoked:async(o,r)=>{const d=(await(await n(`/revoked?name=${encodeURIComponent(o)}&createdAt=${String(r)}`,{method:"GET"})).json())?.revoked;if(typeof d!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return d},latestRevoked:async o=>{const a=(await(await n(`/latest?name=${encodeURIComponent(o)}`,{method:"GET"})).json())?.latest;if(a!==null){if(typeof a!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return a}}}},_d="/_lunora/admin/tokens",bd="__lunora_admin__:createAdminToken",Do="__lunora_admin__:listAdminTokens",Po="__lunora_admin__:revokeAdminToken",sn={"cache-control":"no-store"},Sd=(e,t)=>{const n=Array.isArray(t)?t:[];return n.length===e.length&&e.every(o=>n.includes(o))},Uo=e=>{if(typeof e!="string"||!zr(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},Ed=e=>{if(e===void 0)return[];if(!Array.isArray(e)||!e.every(Zr))throw new l(`admin token \`scopes\` must be a list of ${Xr.join(", ")}`,{code:"BAD_REQUEST",status:400});return[...new Set(e)]},Ad=e=>{const t=e.now??Date.now,n=async s=>{const a=await e.readJsonBody(s),d=Uo(a.name),c=Ed(a.scopes),{expiresAt:h}=a;if(h!==void 0&&(typeof h!="number"||!Number.isFinite(h)||h<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:p,token:m}=gc(d),g=await e.revocations.latestRevoked(d),R=g===void 0?t():Math.max(t(),g+1),E=await e.callStore(bd,{createdAt:R,digest:await Yr(p),expiresAt:h,name:d,scopes:c});if(!Sd(c,E.scopes)){let b;try{await e.revocations.revoke(d,R);const{revoked:S}=await e.callStore(Po,{createdAt:R,name:d});b=S===!0}catch(S){b=!1,console.warn(`[lunora] admin token "${d}" was refused for its dropped scopes and its row was not removed: ${S instanceof Error?S.message:String(S)}`)}finally{e.evict(d)}const _=b?"the token was removed, so retry":`it could not be removed, so revoke "${d}" to free the name`;throw new l(`the store did not keep the scopes for admin token "${d}" (a shard on an older build ignores them); ${_}`,{code:"CONFLICT",status:409})}return e.evict(d),Response.json({...E,token:m},{headers:sn,status:201})},o=async()=>{const{revocations:s}=e;if(s===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:a}=await e.callStore(Do,{}),d=await Promise.all(a.map(async c=>await s.isRevoked(c.name,c.createdAt)?{...c,revoked:!0}:c));return Response.json({tokens:d},{headers:sn})},r=async s=>{const a=Uo(new URL(s.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:d}=await e.callStore(Do,{}),c=d.find(h=>h.name===a);if(c===void 0)throw new l(`no admin token named "${a}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(a,c.createdAt),await e.callStore(Po,{createdAt:c.createdAt,name:a})}finally{e.evict(a)}return Response.json({revoked:!0},{headers:sn})};return{[_d]:async s=>(e.assertRootAdmin(s),s.method==="GET"?o():s.method==="POST"?n(s):s.method==="DELETE"?r(s):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},Td=3e4,vd=5e3,Rd=1024,Co=20,Lo=1e3,Od=5e3,Id=1024,Nd=({listNames:e,lookup:t,now:n=Date.now})=>{const o=new Map,r=new Map,s=new Map,a=new Map,d=new Map;let c=Co,h=n();const p=()=>{const T=n()-h,U=Math.floor(T/Lo);return U>0&&(c=Math.min(Co,c+U),h+=U*Lo),c<=0?!1:(c-=1,!0)},m=(T,U)=>{for(const[v,x]of T)x.name===U&&T.delete(v)},g=T=>{d.has(T)||(kt(d,Id),d.set(T,!0))};let R=Number.NEGATIVE_INFINITY,E;const b=()=>E!==void 0?E:e===void 0||n()-R<Od?Promise.resolve():(R=n(),E=(async()=>{try{for(const T of await e())g(T)}catch{}finally{E=void 0}})(),E),_=async T=>(await b(),d.has(T)),S=(T,U,v)=>{const x=t(T,U);a.set(v,x);const W=()=>{a.get(v)===x&&a.delete(v)};return x.finally(W).catch(()=>{}),x},O=(T,U,v,x)=>{x?g(T):d.delete(T),kt(r,Rd),r.set(x?U:v,{name:T,scopes:[],until:n()+vd})};return{evict:T=>{m(o,T),m(r,T),d.delete(T);for(const U of a.keys())U.startsWith(`${T}\0`)&&a.delete(U);s.set(T,(s.get(T)??0)+1)},verify:async T=>{const U=Jr(T);if(U===void 0)return;const{name:v}=U,x=await Yr(U.secret),W=`${v}\0${x}`,X=`${v}\0*`,se=o.get(W);if(se!==void 0&&se.until>n())return se;if((r.get(X)?.until??0)>n()||(r.get(W)?.until??0)>n())return;o.delete(W),r.delete(W),r.delete(X);const Oe=s.get(v);let Ie=a.get(W);if(Ie===void 0){if(!(d.has(v)||p())&&!await _(v))return;Ie=S(v,x,W)}const C=await Ie;if(s.get(v)!==Oe)return;if(!C.live){if(C.transient===!0)return;O(v,W,X,C.nameKnown);return}const V=Math.min(n()+Td,C.expiresAt??Number.POSITIVE_INFINITY);if(V<=n())return;g(v);const G={name:v,scopes:C.scopes??[],until:V,...C.expiresAt===void 0?{}:{expiresAt:C.expiresAt}};return o.set(W,G),G}}},kd="x",Mo=" ",Dd={'"':'"',"'":"'","[":"]","`":"`"},os=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
1
+ import{isLunoraError as Ur,toErrorBody as yi}from"@lunora/errors";import{encodeWire as Re,decodeWire as Nt,encodeArgsOrThrow as _i}from"@lunora/wire";import{t as Un,f as Cn,a as Cr,b as Kt}from"./base64-DANXv-kI.mjs";import{e as kt,b as bi}from"./memoize-identity-Cbr1Sdt3.mjs";import{d as yo,E as _o,a as Si,b as Ei,W as bo}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as Ai}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as Ti,a as vi,i as Ri,e as Oi,E as So,b as Ii}from"./identity-header-DqrLFqFq.mjs";import{O as Lr,a as Mr}from"./origin-paywall-B6eOO67m.mjs";import{o as Je,b as $r,p as Ni,m as ki,d as Di,a as Pi,r as Ui}from"./otlp-resource-BBR8xs6m.mjs";import{r as Ci,f as Eo,a as Ce,S as Ao}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as To}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as ve,applyJurisdiction as gt}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ae,e as we,M as Br,b as Li,f as Mi,g as xr,w as $i,h as Hr,t as jr}from"./rest-routes-D5NWHmVl.mjs";import{a as Y,m as ke}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Ln,BACKUP_KEY_PREFIX as Mn,isBackupManifestKey as Bi,backupObjectKeyOfManifest as Kr,backupObjectKey as xi,backupManifestKey as Hi}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as et,STORAGE_UPLOAD_MAX_BODY_BYTES as $e,buildStorageAdminRoutes as ji,STORAGE_PATH as Ki}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Gi,e as Fi,f as vo,g as Wi,h as Qi}from"./export-tap-CMyD7rin.mjs";import{sha256 as Gr}from"@noble/hashes/sha2.js";import{buildHealthRoutes as Vi,durableObjectProbe as zi,d1Probe as Ji,presenceProbe as on}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Yi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as zm,routeIdentityResolvers as Jm}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Xi}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as Zi,createQueryCoordinator as qi,createDefaultShardRegistry as ec,refreshShardHeadersPerCall as tc,refreshedShardHeaders as nc}from"./createQueryCoordinator-BuoncR2C.mjs";import{i as Ro,r as Oo,h as oc,e as rc,d as rn,a as Io}from"./security-headers-0DqdJ04h.mjs";const sc=(e,t,n,o)=>{const r=e.get(t);if(r!==void 0)return r;kt(e,o);const s=n().catch(a=>{throw e.get(t)===s&&e.delete(t),a});return e.set(t,s),s},ac=new TextEncoder,ic=64,cc=new Map,Fr=async e=>sc(cc,e,async()=>crypto.subtle.importKey("raw",ac.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ic),Wr=new TextEncoder,dc=Array.from({length:32},(e,t)=>t);new RegExp(`[${dc.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Gt=async(e,t)=>{const n=await Fr(e),o=await crypto.subtle.sign("HMAC",n,Wr.encode(t));return Un(new Uint8Array(o))},Qr=async(e,t,n)=>{const o=await Fr(e);return crypto.subtle.verify("HMAC",o,n,Wr.encode(t))},Vr="lnat",uc="__lunora_admin_revocations__",lc=/^[a-z0-9][a-z0-9_-]{0,63}$/u,hc=/^[\w-]{43}$/u,Rt="x-lunora-admin-signal",fc="as1",pc=6e4,mc=5e3,zr=e=>lc.test(e),wc=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Vr)return;const[,n,o]=t;return zr(n)&&hc.test(o)?{name:n,secret:o}:void 0},Jr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:wc(t[1])},gc=e=>{const t=Un(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Vr}.${e}.${t}`}},Yr=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),yc=async(e,t,n=Date.now(),o=Number.POSITIVE_INFINITY)=>{const r=`${fc}.${String(Math.floor(Math.min(n+pc,o)))}.${t}`;return`${r}.${await Gt(e,r)}`},Xr=["migrations"],Zr=e=>Xr.some(t=>t===e),An=["disabled","schema","schema_and_log","schema_and_log_and_data"],_c="schema",bc=e=>e==null||e===""?_c:typeof e=="string"&&An.includes(e)?e:"disabled",Sc=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,r={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return r.bucket=()=>r,r},qr="__lunoraBranch",Ec=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,qr),Ac=`may not contain the reserved workflow branch-marker key ("${qr}")`,Tc=new Set(["exp","expiresAtMs","iat","jti","nbf"]),Tn=e=>Array.isArray(e)?`[${e.map(t=>Tn(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[o])=>n<o?-1:n>o?1:0).map(([n,o])=>`${JSON.stringify(n)}:${Tn(o)}`).join(",")}}`:JSON.stringify(e)??"null",vc=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!Tc.has(n)));return Object.keys(t).length===0?"":Tn(t)},Rc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ae=(e,t)=>e>>>t|e<<32-t,Oc=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const o=new DataView(n.buffer);o.setUint32(n.length-8,Math.floor(e.length*8/2**32)),o.setUint32(n.length-4,e.length*8>>>0);const r=new Uint32Array(64);for(let d=0;d<n.length;d+=64){for(let _=0;_<16;_+=1)r[_]=o.getUint32(d+_*4);for(let _=16;_<64;_+=1){const b=r[_-15],O=r[_-2],A=Ae(b,7)^Ae(b,18)^b>>>3,U=Ae(O,17)^Ae(O,19)^O>>>10;r[_]=r[_-16]+A+r[_-7]+U>>>0}let[c,h,p,m,g,R,E,S]=t;for(let _=0;_<64;_+=1){const b=Ae(g,6)^Ae(g,11)^Ae(g,25),O=g&R^~g&E,A=S+b+O+Rc[_]+r[_]>>>0,U=Ae(c,2)^Ae(c,13)^Ae(c,22),v=c&h^c&p^h&p,x=U+v>>>0;S=E,E=R,R=g,g=m+A>>>0,m=p,p=h,h=c,c=A+x>>>0}[c,h,p,m,g,R,E,S].forEach((_,b)=>{t[b]=t[b]+_>>>0})}const s=new Uint8Array(32),a=new DataView(s.buffer);return t.forEach((d,c)=>{a.setUint32(c*4,d)}),s},Ic=(e,t)=>Un(Oc(new TextEncoder().encode(`${JSON.stringify(e??null)}|${vc(t)}`)).subarray(0,16)),Nc=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},kc=/^\w[\w-]{0,99}$/u,Dc="`dedupKey` must match ^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$",Pc=e=>typeof e=="string"&&kc.test(e),Uc=9e5,Cc="x-lunora-dispatch-declined",Lc=/already[\s_-]?exists/iu,Mc=e=>Lc.test(e instanceof Error?e.message:String(e)),$c="/_lunora/live/publish",Bc="cf-ray",xc="x-lunora-ray-id",Hc=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,jc=e=>e==null?void 0:Hc.exec(e.trim())?.[1]?.toLowerCase(),Kc=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Kc);const Gc=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Fc=-100,Wc=15,Qc=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Gc.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Wc?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Fc?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},No=e=>{const t=e.cf;return t===void 0?void 0:Qc(t)},Ft="::relay::",Vc=(e,t)=>`${e}${Ft}${String(t)}`,Wt="::replica::",zc=(e,t)=>`${e}${Wt}${t}`,Jc=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Yc=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},es=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let r=0;r<n;r+=1){const s=r<e.length?e.charCodeAt(r):0,a=r<t.length?t.charCodeAt(r):0;o|=s^a}return o===0},Xc="/_lunora/scheduler/dispatch",Zc="__lunora_relation__:",qc=e=>e.startsWith(Zc),ts="agents:agentRun",ed=(e,t,n)=>e===ts&&t!==n,td=`\`${ts}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,Dt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...r]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:es(t,r.join(" ").trim())},nd="x-lunora-scheduler-signature",od="x-lunora-scheduler-timestamp",rd=5*6e4,sd=e=>["v1",String(e.timestamp),e.userId??"",e.identity??"",e.body].join(`
2
+ `),ad=(e,t)=>Gt(e,sd(t)),id=async(e,t,n)=>{const o=e.headers.get(nd),{schedulerSecret:r}=n;if(o!==null&&o.length>0&&r!==void 0&&r.length>0){const s=e.headers.get(od);if(s===null||!/^\d+$/u.test(s))return!1;const a=Number(s);if(!Number.isSafeInteger(a)||Math.abs((n.now??Date.now)()-a)>rd)return!1;const d=await ad(r,{body:t,identity:e.headers.get("x-lunora-identity")??void 0,timestamp:a,userId:e.headers.get("x-lunora-userid")??void 0});return es(d,o)}return Dt(e,n.adminToken)},ko="/_lunora/ws/reauth",cd="/_lunora/claims",dd="x-lunora-scheduled-for",ud=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:o})=>{const r={"content-type":"application/json",[Mr]:Lr,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),o!==void 0&&o.length>0&&(r.traceparent=o),n!==void 0&&Number.isFinite(n)&&(r[dd]=String(Math.trunc(n))),r},ld=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},hd=(e,t,n)=>e?.[n]??t?.[n],fd=(e,t,n,o)=>{const r=hd(e,t,n);if(!(typeof r!="object"||r===null))return o.every(s=>typeof r[s]=="function")?r:void 0},ns="v1",pd=6e4,md=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??pd),o=`${ns}.${String(n)}`,r=await Gt(e,o);return{expiresAtMs:n,token:`${o}.${r}`}},wd=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[r,s,a]=o;if(r!==ns||a.length===0)return!1;const d=Number(s);if(!Number.isFinite(d)||d<=n)return!1;let c;try{c=Cn(a)}catch{return!1}return Qr(e,`${r}.${s}`,c)},gd="https://admin-revocations.internal",yd=(e,t)=>{const n=async(o,r)=>{const s=t();if(s===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const a=await ve(e,uc).fetch(new Request(`${gd}${o}`,{...r,headers:{authorization:`Bearer ${s}`,"content-type":"application/json"}}));if(!a.ok)throw new l(`admin revocation store answered ${String(a.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return a};return{revoke:async(o,r)=>{await n("/revoke",{body:JSON.stringify({createdAt:r,name:o}),method:"POST"})},isRevoked:async(o,r)=>{const d=(await(await n(`/revoked?name=${encodeURIComponent(o)}&createdAt=${String(r)}`,{method:"GET"})).json())?.revoked;if(typeof d!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return d},latestRevoked:async o=>{const a=(await(await n(`/latest?name=${encodeURIComponent(o)}`,{method:"GET"})).json())?.latest;if(a!==null){if(typeof a!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return a}}}},_d="/_lunora/admin/tokens",bd="__lunora_admin__:createAdminToken",Do="__lunora_admin__:listAdminTokens",Po="__lunora_admin__:revokeAdminToken",sn={"cache-control":"no-store"},Sd=(e,t)=>{const n=Array.isArray(t)?t:[];return n.length===e.length&&e.every(o=>n.includes(o))},Uo=e=>{if(typeof e!="string"||!zr(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},Ed=e=>{if(e===void 0)return[];if(!Array.isArray(e)||!e.every(Zr))throw new l(`admin token \`scopes\` must be a list of ${Xr.join(", ")}`,{code:"BAD_REQUEST",status:400});return[...new Set(e)]},Ad=e=>{const t=e.now??Date.now,n=async s=>{const a=await e.readJsonBody(s),d=Uo(a.name),c=Ed(a.scopes),{expiresAt:h}=a;if(h!==void 0&&(typeof h!="number"||!Number.isFinite(h)||h<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:p,token:m}=gc(d),g=await e.revocations.latestRevoked(d),R=g===void 0?t():Math.max(t(),g+1),E=await e.callStore(bd,{createdAt:R,digest:await Yr(p),expiresAt:h,name:d,scopes:c});if(!Sd(c,E.scopes)){let S;try{await e.revocations.revoke(d,R);const{revoked:b}=await e.callStore(Po,{createdAt:R,name:d});S=b===!0}catch(b){S=!1,console.warn(`[lunora] admin token "${d}" was refused for its dropped scopes and its row was not removed: ${b instanceof Error?b.message:String(b)}`)}finally{e.evict(d)}const _=S?"the token was removed, so retry":`it could not be removed, so revoke "${d}" to free the name`;throw new l(`the store did not keep the scopes for admin token "${d}" (a shard on an older build ignores them); ${_}`,{code:"CONFLICT",status:409})}return e.evict(d),Response.json({...E,token:m},{headers:sn,status:201})},o=async()=>{const{revocations:s}=e;if(s===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:a}=await e.callStore(Do,{}),d=await Promise.all(a.map(async c=>await s.isRevoked(c.name,c.createdAt)?{...c,revoked:!0}:c));return Response.json({tokens:d},{headers:sn})},r=async s=>{const a=Uo(new URL(s.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:d}=await e.callStore(Do,{}),c=d.find(h=>h.name===a);if(c===void 0)throw new l(`no admin token named "${a}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(a,c.createdAt),await e.callStore(Po,{createdAt:c.createdAt,name:a})}finally{e.evict(a)}return Response.json({revoked:!0},{headers:sn})};return{[_d]:async s=>(e.assertRootAdmin(s),s.method==="GET"?o():s.method==="POST"?n(s):s.method==="DELETE"?r(s):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},Td=3e4,vd=5e3,Rd=1024,Co=20,Lo=1e3,Od=5e3,Id=1024,Nd=({listNames:e,lookup:t,now:n=Date.now})=>{const o=new Map,r=new Map,s=new Map,a=new Map,d=new Map;let c=Co,h=n();const p=()=>{const A=n()-h,U=Math.floor(A/Lo);return U>0&&(c=Math.min(Co,c+U),h+=U*Lo),c<=0?!1:(c-=1,!0)},m=(A,U)=>{for(const[v,x]of A)x.name===U&&A.delete(v)},g=A=>{d.has(A)||(kt(d,Id),d.set(A,!0))};let R=Number.NEGATIVE_INFINITY,E;const S=()=>E!==void 0?E:e===void 0||n()-R<Od?Promise.resolve():(R=n(),E=(async()=>{try{for(const A of await e())g(A)}catch{}finally{E=void 0}})(),E),_=async A=>(await S(),d.has(A)),b=(A,U,v)=>{const x=t(A,U);a.set(v,x);const W=()=>{a.get(v)===x&&a.delete(v)};return x.finally(W).catch(()=>{}),x},O=(A,U,v,x)=>{x?g(A):d.delete(A),kt(r,Rd),r.set(x?U:v,{name:A,scopes:[],until:n()+vd})};return{evict:A=>{m(o,A),m(r,A),d.delete(A);for(const U of a.keys())U.startsWith(`${A}\0`)&&a.delete(U);s.set(A,(s.get(A)??0)+1)},verify:async A=>{const U=Jr(A);if(U===void 0)return;const{name:v}=U,x=await Yr(U.secret),W=`${v}\0${x}`,X=`${v}\0*`,se=o.get(W);if(se!==void 0&&se.until>n())return se;if((r.get(X)?.until??0)>n()||(r.get(W)?.until??0)>n())return;o.delete(W),r.delete(W),r.delete(X);const Oe=s.get(v);let Ie=a.get(W);if(Ie===void 0){if(!(d.has(v)||p())&&!await _(v))return;Ie=b(v,x,W)}const C=await Ie;if(s.get(v)!==Oe)return;if(!C.live){if(C.transient===!0)return;O(v,W,X,C.nameKnown);return}const V=Math.min(n()+Td,C.expiresAt??Number.POSITIVE_INFINITY);if(V<=n())return;g(v);const G={name:v,scopes:C.scopes??[],until:V,...C.expiresAt===void 0?{}:{expiresAt:C.expiresAt}};return o.set(W,G),G}}},kd="x",Mo=" ",Dd={'"':'"',"'":"'","[":"]","`":"`"},os=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
3
3
  `;)n+=1;return n},rs=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},Pd=e=>{const t=e.split("");let n=0;for(;n<e.length;){const o=e[n]??"",r=Dd[o];if(o==="-"&&e[n+1]==="-"){const s=os(e,n);t.fill(Mo,n,s),n=s}else if(o==="/"&&e[n+1]==="*"){const s=rs(e,n);if(s===-1)return;t.fill(Mo,n,s),n=s}else if(r!==void 0){let s=n+1;for(;s<e.length;)if(e[s]!==r)s+=1;else if(r!=="]"&&e[s+1]===r)s+=2;else break;if(s>=e.length)return;t.fill(kd,n,s+1),n=s+1}else n+=1}for(let o=0;o<e.length;o+=1)e[o]===`
4
4
  `&&(t[o]=`
5
5
  `);return t.join("")},Ud="__lunora_admin_tokens__",$n=new Set([Ud,"dbstat","sqlite_dbpage"]),ss="pragma_",Cd=e=>/[\p{L}_]/u.test(e)||(e.codePointAt(0)??0)>127,Ld=e=>/[\p{L}\p{N}_$]/u.test(e)||(e.codePointAt(0)??0)>127,Md=/^pragma_\w+$/u,$d=e=>$n.has(e)||Md.test(e)?e:void 0,$o=e=>{if($n.has(e)||e.startsWith(ss))return e},Bo=(e,t,n)=>{let o="",r=t+1;for(;r<e.length;){const s=e[r];if(s===n){if(n!=="]"&&e[r+1]===n){o+=n,r+=2;continue}return{end:r+1,text:o}}o+=s,r+=1}},xo={'"':'"',"`":"`","[":"]"},an=e=>{const t=e.toLowerCase().replaceAll(/["'`[\]]/gu,"");for(const n of $n)if(t.includes(n))return n;return/\bpragma_/u.test(t)?ss:void 0},Bd=e=>{let t=0;for(;t<e.length;){const n=e[t];if(/\s/u.test(n))t+=1;else if(n==="-"&&e[t+1]==="-"){const o=e.indexOf(`
@@ -22,19 +22,19 @@ ${t.join(`
22
22
  `)}
23
23
  ${ut}
24
24
  `},Ru=(e,t,n,o)=>{const r=[eu(n),"",`${vu(o)}${dt}`];for(const s of e)r.push(`${s.role==="user"?"Developer":"Assistant"}: ${s.text}`);return r.push(`Developer: ${t}`,ut),r.join(`
25
- `)},Ou=async(e,t,n,o,r,s,a)=>{if(e===void 0)return Te("no-ai-binding");if(o==="disabled")return Te("ai-disabled");const d=ge(t.prompt,Vd);if(d==="")return Te("empty-response");const{truncated:c,turns:h}=wu(t.transcript),p=ou(t.model),m=Tu(o),g=await pu(t.approval,t.shardKey,t.approvalSecret),R=[],E=_=>{R.push(_),s?.({call:_,type:"tool"})};let b=Ru(h,d,n,t.knowledge);for(let _=0;_<=Fo;_+=1){if(a?.aborted)return Te("ai-error");let S;const O=s===void 0?void 0:bu(s);try{_===0&&g!==void 0?S=`${Ge}
25
+ `)},Ou=async(e,t,n,o,r,s,a)=>{if(e===void 0)return Te("no-ai-binding");if(o==="disabled")return Te("ai-disabled");const d=ge(t.prompt,Vd);if(d==="")return Te("empty-response");const{truncated:c,turns:h}=wu(t.transcript),p=ou(t.model),m=Tu(o),g=await pu(t.approval,t.shardKey,t.approvalSecret),R=[],E=_=>{R.push(_),s?.({call:_,type:"tool"})};let S=Ru(h,d,n,t.knowledge);for(let _=0;_<=Fo;_+=1){if(a?.aborted)return Te("ai-error");let b;const O=s===void 0?void 0:bu(s);try{_===0&&g!==void 0?b=`${Ge}
26
26
  ${JSON.stringify({name:"runSql",sql:g.sql})}
27
- ${Ct}`:S=await nu(e,p,m,b,O?.token,a)}catch{return Te("ai-error")}if(S===void 0)return Te("ai-error");const T=S.trim();if(T==="")return Te("empty-response");const U=yu(T);if(U===void 0&&O?.flush(),U===void 0||_===Fo){const X=U===void 0?T:Wo(T);return{degraded:!1,partial:U!==void 0,reply:X===""?gu:X,toolCalls:R,truncated:c}}const v=Su(U,o);if("refused"in v){E({...v.name===void 0?{}:{name:v.name},...v.needs===void 0?{}:{needs:v.needs},refused:v.refused}),b=`${b}
28
- ${yt(`refused — ${v.refused}`)}`;continue}if(v.sql!==void 0&&iu[v.name]){const X=g!==void 0&&g.sql===v.sql;if(X&&!g.allow){const se="the operator declined to run that statement";E({name:v.name,refused:se,sql:v.sql}),b=`${b}
29
- ${yt(`refused — ${se}`)}`;continue}if(!X)return{degraded:!1,partial:!1,pendingApproval:{name:v.name,sql:v.sql,ticket:await hu(t.approvalSecret,t.shardKey,v.sql)},reply:Wo(T),toolCalls:R,truncated:c}}if(r===void 0){const X="no tools are available in this deployment";E({name:v.name,refused:X}),b=`${b}
30
- ${yt(`refused — ${X}`)}`;continue}if(a?.aborted)return Te("ai-error");E({name:v.name,...v.sql===void 0?{}:{sql:v.sql}});const x={name:v.name,...v.sql===void 0?{}:{sql:v.sql}};let W;try{W=Eu(await r(x,a))}catch{W="the tool failed"}if(a?.aborted)return Te("ai-error");b=`${b}
27
+ ${Ct}`:b=await nu(e,p,m,S,O?.token,a)}catch{return Te("ai-error")}if(b===void 0)return Te("ai-error");const A=b.trim();if(A==="")return Te("empty-response");const U=yu(A);if(U===void 0&&O?.flush(),U===void 0||_===Fo){const X=U===void 0?A:Wo(A);return{degraded:!1,partial:U!==void 0,reply:X===""?gu:X,toolCalls:R,truncated:c}}const v=Su(U,o);if("refused"in v){E({...v.name===void 0?{}:{name:v.name},...v.needs===void 0?{}:{needs:v.needs},refused:v.refused}),S=`${S}
28
+ ${yt(`refused — ${v.refused}`)}`;continue}if(v.sql!==void 0&&iu[v.name]){const X=g!==void 0&&g.sql===v.sql;if(X&&!g.allow){const se="the operator declined to run that statement";E({name:v.name,refused:se,sql:v.sql}),S=`${S}
29
+ ${yt(`refused — ${se}`)}`;continue}if(!X)return{degraded:!1,partial:!1,pendingApproval:{name:v.name,sql:v.sql,ticket:await hu(t.approvalSecret,t.shardKey,v.sql)},reply:Wo(A),toolCalls:R,truncated:c}}if(r===void 0){const X="no tools are available in this deployment";E({name:v.name,refused:X}),S=`${S}
30
+ ${yt(`refused — ${X}`)}`;continue}if(a?.aborted)return Te("ai-error");E({name:v.name,...v.sql===void 0?{}:{sql:v.sql}});const x={name:v.name,...v.sql===void 0?{}:{sql:v.sql}};let W;try{W=Eu(await r(x,a))}catch{W="the tool failed"}if(a?.aborted)return Te("ai-error");S=`${S}
31
31
  ${yt(W)}`}return Te("ai-error")},Iu={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},Nu=(e,t,n)=>{const o=JSON.stringify(e),r="",s=t===void 0?"":`event: ${t}
32
32
  `;return`${r}${s}data: ${o}
33
33
 
34
- `},ku="__lunora_admin__:aiChat",Du="__lunora_admin__:aiAvailable",Pu=new Set(["__lunora_admin__:aiChartConfig","__lunora_admin__:aiCronExpression","__lunora_admin__:aiGenerateSql","__lunora_admin__:aiNameQuery","__lunora_admin__:aiTableFilter","__lunora_admin__:explainIssue"]),us=60,Qo=120,Uu=e=>{if(typeof e!="object"||e===null)return;const{columns:t,table:n}=e;if(!(typeof n!="string"||n===""||!Array.isArray(t)))return{columns:t.slice(0,as).filter(o=>typeof o=="string").map(o=>o.slice(0,Qo)),table:n.slice(0,Qo)}},Cu={describeTables:"__lunora_admin__:describeTables",readAdvisors:"__lunora_admin__:getAdvisories",readLogs:"__lunora_admin__:getLogs",readPolicies:"__lunora_admin__:rlsPolicies",runSql:"__lunora_admin__:runSql"},Lu="__lunora_admin__:listTables",Mu=(e,t,n,o,r)=>{const s=async(d,c,h)=>{const p=await e(o,d,c,t,await n(),void 0,h);if(!p.ok)return{error:`the tool call failed (${p.status.toString()})`};const m=await p.json();return Nt(m.result)},a=async d=>{if(r.length>0)return r.map(h=>h.table);const c=await s(Lu,{},d);return Array.isArray(c)?c.map(h=>h.name).filter(h=>typeof h=="string").slice(0,us):[]};return async(d,c)=>{const h=Cu[d.name];return d.name==="describeTables"?s(h,{tables:await a(c)},c):s(h,d.sql===void 0?{}:{sql:d.sql},c)}},$u=e=>async(n,o,r)=>{e.assertAdmin(n);const s=e.getBinding(r),a=o.schema,d=o.shardKey,c=typeof d=="string"&&d!==""?d:e.defaultShardKey();if(c.includes(Ft)||c.includes(Wt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const h={approval:o.approval,approvalSecret:e.approvalSecret(r),knowledge:o.knowledge,...typeof o.model=="string"?{model:o.model}:{},prompt:o.prompt,shardKey:c,transcript:o.transcript},p=Array.isArray(a)?a.slice(0,us).map(S=>Uu(S)).filter(S=>S!==void 0):[],m=e.optInLevel(r),g=s===void 0||m==="disabled"||e.forwardToShard===void 0?void 0:await(async()=>{const{forward:S,headers:O}=await e.forwardToShard(n,r);if(O.authorization===void 0&&O[Rt]===void 0)return;const{resolveToolHeaders:T}=e;return Mu(S,c,async()=>T===void 0?O:T(O),n,p)})(),R=new TextEncoder,E=new AbortController,b=()=>{E.abort()};n.signal.aborted?b():n.signal.addEventListener("abort",b,{once:!0});const _=new ReadableStream({cancel(){b()},async start(S){let O=!0;const T=(U,v)=>{if(O)try{S.enqueue(R.encode(Nu(U,v)))}catch{O=!1}};try{const U=await Ou(s,h,p,m,g,v=>{T(v)},E.signal);E.signal.aborted||T({result:Re(U)},"complete")}catch{T({code:"AI_CHAT_FAILED",message:"the assistant turn failed"},"error")}finally{n.signal.removeEventListener("abort",b);try{S.close()}catch{}}}});return new Response(_,{headers:Iu,status:200})},Bu=e=>(n,o,r)=>{e.assertAdmin(n);const s=e.optInLevel(r),a={available:s!=="disabled"&&e.getBinding(r)!==void 0,level:s};return Promise.resolve(Response.json({result:Re(a)},{headers:{"content-type":"application/json"},status:200}))},xu=e=>(t,n,o)=>{if(!(!Pu.has(n)||e.optInLevel(o)!=="disabled"))return e.assertAdmin(t),Response.json({result:Re({degraded:!0,reason:"no-ai-binding"})},{headers:{"content-type":"application/json"},status:200})},$="/_lunora/admin/auth",Hu=[["accountId","accountId"],["apiKeyId","keyId"],["invitationId","invitationId"],["memberId","memberId"],["organizationId","organizationId"],["ownerId","targetUserId"],["passkeyId","passkeyId"],["roleId","roleId"],["teamId","teamId"],["teamMemberId","teamMemberId"],["userId","targetUserId"]],ju=320,Ke=(e,t)=>{if(typeof e!="object"||e===null)return;const n=e[t];return typeof n=="string"&&n!==""?n:void 0},cn=e=>{const t=typeof e=="object"&&e!==null?e.role:void 0;if(Array.isArray(t)){const n=t.filter(o=>typeof o=="string"&&o!=="");return n.length===0?void 0:n.join(",")}return Ke(e,"role")},ls=e=>typeof e=="object"&&e!==null?e.data:void 0,Ku=(e,t,n)=>{const o=cn(ls(t))??cn(t);return o!==void 0||e.role===!0?cn(n)??o:void 0},Gu=(e,t)=>{const n=Ke(ls(e),"email")??Ke(e,"email");return n===void 0?void 0:Ke(t,"email")??n},Fu=512,Wu=(e,t,n,o,r,s)=>{const a={path:e};for(const[m,g]of Hu){const R=Ke(r,m);R!==void 0&&(a[g]=R)}const d=t.event.startsWith("org-")&&a.organizationId===void 0?Ke(s,"organizationId"):void 0;d!==void 0&&(a.organizationId=d);const c=Ku(t,r,s);c!==void 0&&(a[t.roleKey??"role"]=c);const h=t.resultId===void 0?void 0:Ke(s,"id");t.resultId!==void 0&&h!==void 0&&(a[t.resultId]=h);const p=Gu(r,s);return{actorId:n,detail:a,event:t.event,outcome:"success",ts:Date.now(),...o.ip===void 0?{}:{ip:o.ip},...p===void 0?{}:{targetEmail:p.slice(0,ju)},...o.userAgent===void 0?{}:{userAgent:o.userAgent.slice(0,Fu)}}},Qu=new Set(["banUser","cancelInvitation","capabilities","config","deleteApiKey","listAccounts","listApiKeys","listInvitations","listMembers","listOrganizations","listOrgRoles","listPasskeys","listSessions","listSignUpInvitations","listTeamMembers","listTeams","listUsers","revokeSignUpInvitation","revokeUserSession","revokeUserSessions"]),Vu={ACCOUNT_NOT_FOUND:404,API_KEY_NOT_FOUND:404,API_KEY_STORAGE_UNSUPPORTED:409,INVITATION_NOT_FOUND:404,INVITER_REQUIRED:400,LAST_ORGANIZATION_OWNER:409,MEMBER_NOT_FOUND:404,MEMBERSHIP_CHANGED:409,ORG_ROLE_NOT_FOUND:404,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,ORGANIZATION_NOT_FOUND:404,PASSKEY_NOT_FOUND:404,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,SESSION_NOT_FOUND:404,SIGN_UP_INVITATION_NOT_FOUND:404,TEAM_MEMBER_NOT_FOUND:404,TEAM_NOT_FOUND:404,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},H=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new l(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},Le=(e,t)=>{const n=e(t);if(n===void 0)throw new l(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},hs=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ye=(e,t)=>typeof e[t]=="string"?e[t]:void 0,dn=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Vo=e=>{const t=hs(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new l("`role` is required",{code:"BAD_REQUEST",status:400});return t},zo=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,r]of Object.entries(t))Array.isArray(r)&&r.every(s=>typeof s=="string")&&(n[o]=r);return n},zu={[`${$}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${$}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${$}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${$}/accounts`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listAccounts"},[`${$}/passkeys`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${$}/api-keys`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listApiKeys"},[`${$}/api-keys/delete`]:{audit:{event:"api-key-delete"},build:({body:e})=>({apiKeyId:H(e,"apiKeyId")}),http:"POST",method:"deleteApiKey",returns:"void"},[`${$}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${$}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${$}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${$}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${$}/sign-up-invitations/create`]:{audit:{event:"sign-up-invitation-create",resultId:"invitationId"},build:({body:e})=>({email:H(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:ye(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${$}/sign-up-invitations/revoke`]:{audit:{event:"sign-up-invitation-revoke"},build:({body:e})=>({email:H(e,"email").trim().toLowerCase()}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${$}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${$}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${$}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:Le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${$}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${$}/users/create`]:{audit:{event:"admin-user-create",resultId:"targetUserId",role:!0},build:({body:e})=>({data:dn(e,"data"),email:H(e,"email"),name:H(e,"name"),password:ye(e,"password"),role:hs(e.role)}),http:"POST",method:"createUser"},[`${$}/users/update`]:{audit:{event:"admin-user-update"},build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:H(e,"userId")}},http:"POST",method:"updateUser"},[`${$}/users/role`]:{audit:{event:"admin-role-change",role:!0},build:({body:e})=>({role:Vo(e),userId:H(e,"userId")}),http:"POST",method:"setRole"},[`${$}/users/ban`]:{audit:{event:"admin-user-ban"},build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ye(e,"reason"),userId:H(e,"userId")}),http:"POST",method:"banUser"},[`${$}/users/unban`]:{audit:{event:"admin-user-unban"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"unbanUser"},[`${$}/users/password`]:{audit:{event:"admin-password-set"},build:({body:e})=>({newPassword:H(e,"newPassword"),userId:H(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${$}/users/remove`]:{audit:{event:"admin-user-remove"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${$}/users/impersonate`]:{audit:{event:"admin-impersonate-start"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"impersonateUser"},[`${$}/sessions/revoke`]:{audit:{event:"admin-session-revoke"},build:({body:e})=>({sessionId:H(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${$}/sessions/revoke-all`]:{audit:{event:"admin-session-revoke"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${$}/accounts/unlink`]:{audit:{event:"account-unlink"},build:({body:e})=>({accountId:H(e,"accountId"),userId:H(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${$}/two-factor/disable`]:{audit:{event:"mfa-disable"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${$}/passkeys/delete`]:{audit:{event:"passkey-remove"},build:({body:e})=>({passkeyId:H(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${$}/organizations/members/remove`]:{audit:{event:"org-member-remove"},build:({body:e})=>({memberId:H(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${$}/organizations/invitations/cancel`]:{audit:{event:"org-invitation-cancel"},build:({body:e})=>({invitationId:H(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${$}/organizations/create`]:{audit:{event:"org-create",resultId:"organizationId"},build:({body:e})=>({logo:ye(e,"logo"),metadata:dn(e,"metadata"),name:H(e,"name"),ownerId:ye(e,"ownerId"),slug:ye(e,"slug")}),http:"POST",method:"createOrganization"},[`${$}/organizations/update`]:{audit:{event:"org-update"},build:({body:e})=>({logo:ye(e,"logo"),metadata:dn(e,"metadata"),name:ye(e,"name"),organizationId:H(e,"organizationId"),slug:ye(e,"slug")}),http:"POST",method:"updateOrganization"},[`${$}/organizations/remove`]:{audit:{event:"org-delete"},build:({body:e})=>({organizationId:H(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${$}/organizations/members/add`]:{audit:{event:"org-member-add",resultId:"memberId",role:!0},build:({body:e})=>({organizationId:H(e,"organizationId"),role:ye(e,"role"),userId:H(e,"userId")}),http:"POST",method:"addMember"},[`${$}/organizations/members/invite`]:{audit:{event:"org-invitation-create",resultId:"invitationId",role:!0},build:({body:e})=>({email:H(e,"email"),inviterId:ye(e,"inviterId"),organizationId:H(e,"organizationId"),role:ye(e,"role")}),http:"POST",method:"inviteMember"},[`${$}/organizations/members/role`]:{audit:{event:"org-member-role-change",role:!0},build:({body:e})=>({memberId:H(e,"memberId"),role:Vo(e)}),http:"POST",method:"updateMemberRole"},[`${$}/organizations/teams/create`]:{audit:{event:"org-team-create",resultId:"teamId"},build:({body:e})=>({name:H(e,"name"),organizationId:H(e,"organizationId")}),http:"POST",method:"createTeam"},[`${$}/organizations/teams/update`]:{audit:{event:"org-team-update"},build:({body:e})=>({name:H(e,"name"),teamId:H(e,"teamId")}),http:"POST",method:"updateTeam"},[`${$}/organizations/teams/remove`]:{audit:{event:"org-team-remove"},build:({body:e})=>({teamId:H(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${$}/organizations/teams/members/add`]:{audit:{event:"org-team-member-add",resultId:"teamMemberId"},build:({body:e})=>({teamId:H(e,"teamId"),userId:H(e,"userId")}),http:"POST",method:"addTeamMember"},[`${$}/organizations/teams/members/remove`]:{audit:{event:"org-team-member-remove"},build:({body:e})=>({teamMemberId:H(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${$}/organizations/roles/create`]:{audit:{event:"org-role-change",resultId:"roleId",roleKey:"roleName"},build:({body:e})=>({organizationId:H(e,"organizationId"),permission:zo(e),role:H(e,"role")}),http:"POST",method:"createOrgRole"},[`${$}/organizations/roles/update`]:{audit:{event:"org-role-change"},build:({body:e})=>({permission:zo(e),roleId:H(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${$}/organizations/roles/remove`]:{audit:{event:"org-role-change"},build:({body:e})=>({roleId:H(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ju=e=>{const t=async r=>{try{return await r()}catch(s){if(s instanceof l)throw s;const a=s,d=typeof a.code=="string"?a.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new l("auth admin operation failed",{code:d,status:Vu[d]??500})}},n=async(r,s)=>{if(e.assertAdmin(r),Qu.has(s.method)||e.assertRootAdmin(r),r.method!==s.http)throw new l(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const a=e.getAuthAdmin();if(a===void 0)throw new l("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const d=a[s.method];if(d===void 0)throw new l(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const c=new URL(r.url),h={body:s.http==="POST"?await e.readJsonBody(r):{},paging:e.parsePaging(r),query:R=>e.queryParameter(c,R)},p=s.build(h),m=await t(()=>d(p)),g=e.getAuditWriter();if(s.audit!==void 0&&g!==void 0)try{await g.write(Wu(c.pathname,s.audit,e.adminActor(r),{ip:e.clientIp(r),userAgent:r.headers.get("user-agent")??void 0},p,m))}catch(R){console.error("[lunora] auth admin audit write failed:",R)}return Response.json(s.returns==="void"?{ok:!0}:m,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[r,s]of Object.entries(zu))o[r]=a=>n(a,s);return o},Yu="__lunora_admin__:getAuthAuditLog",Jo=e=>typeof e=="string"&&e!==""?e:void 0,Yo=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Xu=e=>async(n,o)=>{e.assertAdmin(n);const r=e.getReader();if(r===void 0)throw new l("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=Jo(o.actorId),a=Jo(o.event),d=Yo(o.sinceSeq),c=Yo(o.limit),h={...s===void 0?{}:{actorId:s},...a===void 0?{}:{event:a},...d===void 0?{}:{sinceSeq:d},...c===void 0?{}:{limit:c}};let p;try{p=await r.read(h)}catch(g){throw g instanceof l?g:(console.error("[lunora] auth audit read failed:",g),new l("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const m={entries:p};return Response.json({result:Re(m)},{headers:{"content-type":"application/json"},status:200})},Xo="__lunora_admin__:copyAuthToJurisdiction",Zu="__lunora_admin__:purgeUnpinnedAuth",qu=e=>async(t,n,o)=>{if(n!==Xo&&n!==Zu)return;e.assertAdmin(t);const r=e.getMove();if(r===void 0)throw new l("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const s=n===Xo?await r.copy({force:o.force===!0}):await r.purge();return Response.json({result:Re(s)},{headers:{"content-type":"application/json"},status:200})},fs=e=>`${JSON.stringify({end:!0,rows:e})}
35
- `,el=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return;const t=e;if(!(t.end!==!0||t.table!==void 0))return typeof t.rows=="number"&&Number.isSafeInteger(t.rows)&&t.rows>=0?t.rows:Number.NaN},tl=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const r of t)e.resolveTableSharding?.(r)?.mode.kind==="global"?o.push(r):n.push(r);return{globalTables:o,shardLocalTables:n}},nl=async(e,t,n,o,r,s)=>{if(n!==void 0&&o.length===0)return[];const a=await e.orchestrateExport(r,{args:{tables:o},defaultShardKey:s,headers:t,tables:o}),d=a.shards.filter(c=>c.error);if(d.length>0){const c=d.map(h=>`${h.shardKey}: ${h.error?.message??"unknown error"}`).join("; ");throw new l(`export failed on ${String(d.length)} of ${String(a.shards.length)} shard(s) — ${c}`,{code:"EXPORT_SHARD_FAILED",status:502})}return a.shards.flatMap(c=>c.rows??[])},ps=async(e,t,n,o,r)=>{const s=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:a,shardLocalTables:d}=tl(e,s),c=await nl(t,n,s,d,r,e.defaultShardKey??"__root__"),h=e.exportGlobals,p=o===void 0||a.length>0;return(async function*(){yield*c,p&&h&&(yield*h({tables:a}))})()},ol=async(e,t,n,o,r,s)=>{for await(const a of await ps(e,t,n,o,s))r(a)},Zo=new TextEncoder,rl=1e3,ms=10,sl=200,qo=8,ws="lunoraBackupCron",vn=24*1048576,er=e=>new l(`scheduled backup reached ${String(e)} bytes of NDJSON, past the ${String(vn)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507}),tr=e=>{const t=e.slice(0,ms).map(o=>Kr(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},al=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const r of e)n.set(r,o),o+=r.byteLength;return n},Bn=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const r=[];let s;for(let a=0;a<rl;a+=1){const d=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const c of d.objects)Bi(c.key)&&c.customMetadata?.[ws]===o&&r.push(c.key);if(!d.truncated||d.cursor===void 0)break;s=d.cursor}return{eligible:r.length,stale:r.toSorted((a,d)=>d.localeCompare(a)).slice(n)}},il=async(e,t,n,o,r)=>{const{stale:s}=await Bn(e,t,n,o),a=new Set(r),d=s.filter(R=>a.has(R)),c=d.slice(0,sl),h=s.length-c.length,p=r.length-d.length;if(c.length===0)return{deleted:[],failed:[],ignored:p,remaining:h};const m=[],g=[];for(let R=0;R<c.length;R+=qo){const E=await Promise.allSettled(c.slice(R,R+qo).map(async b=>(await e.delete(Kr(b)),await e.delete(b),b)));for(const[b,_]of E.entries())_.status==="fulfilled"?m.push(_.value):g.push(c[R+b])}return m.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(m.length)}: ${tr(m)}`),g.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(g.length)}: ${tr(g)}`),{deleted:m,failed:g,ignored:p,remaining:h}},cl=async e=>{const t=e.backupStore;if(!t)throw new l("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Ln(e.backupPrefix??Mn),o=e.backupCron,{eligible:r,stale:s}=o===void 0?{eligible:0,stale:[]}:await Bn(t,n,e.backupRetain,o);return{cron:o,eligible:r,keep:e.backupRetain??0,prefix:n,wouldDelete:s}},dl=async(e,t,n,o,r)=>{const s=e.backupStore;if(!s)throw new l("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new l("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const a={authorization:`Bearer ${o}`,"content-type":"application/json"},d=e.backupTables;let c=0,h=0,p=[];await ol(e,t,a,d,T=>{const U=Zo.encode(`${JSON.stringify(T)}
36
- `);if(c+=1,h+=U.byteLength,h>vn)throw er(h);p.push(U)},n);const g=Zo.encode(fs(c));if(h+=g.byteLength,h>vn)throw er(h);p.push(g);const R=Ln(e.backupPrefix??Mn),E=new Date(r.scheduledTime).toISOString(),b=xi(R,E),_=al(p,h);p=[];const S=et(await crypto.subtle.digest("SHA-256",_));await s.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:S});const O={bytes:h,createdAt:E,cron:r.cron,file:b,id:E,rows:c,scheduledTime:r.scheduledTime,sha256:S,...d?{tables:d.join(",")}:{}};await s.put(Hi(b),`${JSON.stringify(O,void 0,2)}
37
- `,{customMetadata:{[ws]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:T}=await Bn(s,R,e.backupRetain,r.cron);if(T.length>0){const U=T.slice(0,ms),v=T.length-U.length;console.info(`[lunora] backup retention: ${String(T.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${v>0?` (+${String(v)} more)`:""}`)}}catch(T){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,T)}},ul=async(e,t)=>{const n=e.backupStore;if(!n)throw new l("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,r=e.backupRetain;if(o===void 0||r===void 0||!Number.isInteger(r)||r<=0)throw new l("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return il(n,Ln(e.backupPrefix??Mn),r,o,t)},ll="/_lunora/admin/backup/retention",hl="/_lunora/admin/backup/prune",fl=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,r=(d,c)=>{o(d,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${c} requires a \`backupStore\` on the worker`})},s=async d=>(Y(d,"GET","Backup-retention"),r(d,"retention preview"),Response.json(await cl(t),{headers:{"cache-control":"no-store"}})),a=async d=>{Y(d,"POST","Backup-prune"),r(d,"prune");const{confirm:c}=await n(d);if(!Array.isArray(c)||c.some(h=>typeof h!="string"))throw new l("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await ul(t,c),{headers:{"cache-control":"no-store"}})};return{[hl]:a,[ll]:s}},nr=500,pl=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new l("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new l("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new l("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new l("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new l("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},ml=(e,t)=>{if(e.length>nr)throw new l(`RPC batch exceeds the ${String(nr)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[r,s]of e.entries()){const{entry:a,shardKey:d}=pl(s,r,t);if(o.has(a.id))throw new l(`batch call id ${String(a.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(a.id);const c=n.get(d)??[];c.push(a),n.set(d,c)}return n},wl=3e5,Lt=e=>e instanceof Error?e.message:JSON.stringify(e),xn=async(e,t,n)=>{const o=await e.fetch(new Request(`https://scheduler.internal${t}`,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}));if(!o.ok)throw new Error(`SchedulerDO ${t} answered ${String(o.status)}`);return o.json()},gl=(e,t,n)=>{const o=setInterval(()=>{xn(e,"/cron/renew",{name:t,runId:n}).then(r=>{r.renewed===!1&&clearInterval(o)}).catch(r=>{console.warn(`[lunora] cron job "${t}" could not renew its lease: ${Lt(r)}`)})},wl);return o},or=async(e,t)=>{if(e===void 0)return{skip:!1};try{const n=await xn(e,"/cron/begin",{name:t});if(n.acquired===!1)return{reason:typeof n.reason=="string"?n.reason:"in-flight",skip:!0};const o=typeof n.runId=="string"?n.runId:void 0;return o===void 0?{skip:!1}:{renewal:gl(e,t,o),runId:o,skip:!1}}catch(n){return console.warn(`[lunora] cron job "${t}" runs without its overlap guard: ${Lt(n)}`),{skip:!1}}},_t=async(e,t,n,o)=>{if(!(e===void 0||n.skip||n.runId===void 0)){clearInterval(n.renewal);try{await xn(e,"/cron/end",{name:t,runId:n.runId,...o===void 0?{status:"succeeded"}:{error:Lt(o),status:"failed"}})}catch(r){console.warn(`[lunora] cron job "${t}" ran but its outcome was not recorded: ${Lt(r)}`)}}},Mt="_lunora/restore/",yl=1440*60*1e3,gs=9999999999999,_l=/^[\da-f]{64}\/(\d{13})\//u,bl=5*1024*1024,Sl=1e4,El=1e3,Xe=12,rr=new Map,ys=async e=>{let t=rr.get(e);return t===void 0&&(t=(async()=>{const n=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({hash:"SHA-256",info:new TextEncoder().encode("restore-staging"),name:"HKDF",salt:new TextEncoder().encode("lunora")},n,{length:256,name:"AES-GCM"},!1,["encrypt","decrypt"])})(),rr.set(e,t)),t},Hn=async(e,t,n)=>{const o=crypto.getRandomValues(new Uint8Array(Xe)),r=await crypto.subtle.encrypt({additionalData:new TextEncoder().encode(t),iv:o,name:"AES-GCM"},await ys(e),n),s=new Uint8Array(Xe+r.byteLength);return s.set(o),s.set(new Uint8Array(r),Xe),s.buffer},_s=async(e,t,n)=>{if(!(n.byteLength<=Xe))try{const o=await crypto.subtle.decrypt({additionalData:new TextEncoder().encode(t),iv:n.subarray(0,Xe),name:"AES-GCM"},await ys(e),n.subarray(Xe));return new Uint8Array(o)}catch{return}},Qe=e=>{const{adminToken:t,storageDelete:n,storageDownload:o,storageList:r,storageUpload:s}=e;return n&&o&&r&&s&&t?{delete:n,download:o,list:r,secret:t,upload:s}:void 0},Qt=e=>{const{data:t,last:n,offset:o,sha256:r,size:s}=e,a=n!==!0||typeof s=="number"&&Number.isInteger(s)&&s>=0;if(typeof t!="string"||typeof o!="number"||!Number.isInteger(o)||o<0||!a)return;let d;try{d=Cr(t)}catch{return}return{bytes:d,lastSize:n===!0?s:void 0,offset:o,...typeof r=="string"?{sha256:r}:{}}},jn=async function*(t,n,o){let r,s=!0;for(;s;){const a=await t(n,{...o,cursor:r,limit:El});yield*a.objects,r=a.cursor,s=r!==void 0&&(a.truncated??!0)}},bs=async function*(t,n){let o=new Uint8Array(n),r=0;for await(const s of t)for(let a=0;a<s.byteLength;){const d=Math.min(n-r,s.byteLength-a);o.set(s.subarray(a,a+d),r),r+=d,a+=d,r===n&&(yield o,o=new Uint8Array(n),r=0)}r>0&&(yield o.subarray(0,r))},Ss=async e=>`${Mt}${et(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}/`,Al=(e,t)=>`${e}${String(gs-t).padStart(13,"0")}/`,Es=async(e,t,n)=>{const{objects:o}=await e.list(t,{...n,limit:1}),r=o[0]?.key,s=r?.startsWith(t)?r.indexOf("/",t.length):-1;return r===void 0||s===-1?void 0:r.slice(0,s+1)},Kn=(e,t)=>`${e}${String(t).padStart(16,"0")}`,Tl=async(e,t,n,o)=>{const r=o.offset===0?Al(t,Date.now()):await Es(e,t,n);if(r===void 0)return!1;const s=Kn(r,o.offset);return await e.upload(s,await Hn(e.secret,s,o.bytes),n),!0},vl=async(e,t,n)=>{const o=[];for await(const r of jn(e.list,t,n))o.push(r.key);await Promise.all(o.map(async r=>e.delete(r,n)))},Vt=async function*(t,n,o,r,s){const a=h=>new l(h,{code:`${s}_RESTORE_INCOMPLETE`}),d=Gr.create();let c=0;if(r.offset+r.bytes.byteLength!==r.lastSize)throw a(`chunks add up to ${String(r.offset+r.bytes.byteLength)} of ${String(r.lastSize)} bytes`);for(;c<r.offset;){const h=Kn(o,c),p=await t.download(h,n);if(!p?.body)throw a(`the chunk at byte ${String(c)} never arrived`);const m=await _s(t.secret,h,new Uint8Array(await new Response(p.body).arrayBuffer()));if(m===void 0)throw a(`the chunk at byte ${String(c)} was not staged by this deployment`);if(m.byteLength===0||c+m.byteLength>r.offset)throw a(`the chunk at byte ${String(c)} overlaps the last chunk`);d.update(m),yield m,c+=m.byteLength}if(d.update(r.bytes),yield r.bytes,r.sha256!==void 0&&et(d.digest())!==r.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${r.sha256}`,{code:`${s}_SHA256_MISMATCH`})},Gn=(e,t)=>{if(e.bytes.byteLength!==e.lastSize)throw new l(`the record holds ${String(e.bytes.byteLength)} of ${String(e.lastSize)} bytes`,{code:`${t}_RESTORE_INCOMPLETE`});if(e.sha256!==void 0&&et(Gr(e.bytes))!==e.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${e.sha256}`,{code:`${t}_SHA256_MISMATCH`})},zt=async(e,t)=>{const n=new Uint8Array(t);let o=0;for await(const r of e)n.set(r,o),o+=r.byteLength;return n},As=async(e,t,n)=>{const o=[];try{for await(const r of bs(t,Math.max(bl,Math.ceil(n/Sl))))o.push(await e.uploadPart(o.length+1,r));await e.complete(o)}catch(r){throw await e.abort().catch(()=>{}),r}},Rl=e=>{const t=_l.exec(e.slice(Mt.length));return t?.[1]===void 0?void 0:gs-Number(t[1])},Ol=async(e,t,n)=>{let o=0;for(const r of t){const s=r===void 0?{}:{bucket:r},a=[];for await(const{key:d}of jn(e.list,Mt,s)){const c=Rl(d);d.startsWith(Mt)&&(c===void 0||n-c>yl)&&a.push(d)}await Promise.all(a.map(async d=>e.delete(d,s))),o+=a.length}return o},Rn=2,Fe="$lunora",_e="$auth",be="$kv",Se="$storage",Il=new Set([_e,Fe,be,Se]),sr=["auth","kv","storage"],Nl=["kv","storage"],Ye=512*1024,$t=25*1024*1024,Ts="_lunora/",vs=60,kl=1e3,ct=e=>e.storageBuckets!==void 0&&e.storageBuckets.length>0?e.storageBuckets:[void 0],Rs=(e,t)=>{const{bucket:n}=t.where;if(!(n===void 0||ct(e).includes(n)))return`${t.key} is in the bucket "${n}", which this worker does not declare`},Dl=(e,t)=>t.filter(n=>{switch(n){case"auth":return e.authData!==void 0;case"kv":return e.kvIntrospector!==void 0;case"storage":return e.storageList!==void 0&&e.storageDownload!==void 0;default:return!1}}),Pl=async function*(t){const n=t.getReader();let o=!1;try{for(;;){const{done:r,value:s}=await n.read();if(r){o=!0;return}yield s}}finally{o||await n.cancel().catch(()=>{})}},Ul=async function*(t){let n;for await(const o of t)n&&(yield{bytes:n,last:!1}),n=o;yield{bytes:n??new Uint8Array(0),last:!0}},Os=async function*(t,n){let o;do{const r=await t.listKeys({cursor:o,limit:kl,namespace:n});yield*r.keys,o=r.listComplete?void 0:r.cursor}while(o!==void 0)},Cl=async function*(t,n,o){const r=Cr(n);if(r.byteLength<=Ye){yield{doc:{...t,value:n,...o},table:be};return}const s=et(await crypto.subtle.digest("SHA-256",r));for(let a=0;a<r.byteLength;a+=Ye){const d=Kt(r.subarray(a,a+Ye)),c=a+Ye>=r.byteLength?{last:!0,sha256:s,size:r.byteLength,...o}:{};yield{doc:{...t,data:d,offset:a,...c},table:be}}},Ll=async function*(t){for(const{binding:n}of await t.listNamespaces())for await(const o of Os(t,n)){const{metadata:r,value:s}=await t.getValue({encoding:"base64",key:o.name,namespace:n});s!==null&&(yield*Cl({key:o.name,namespace:n},s,{...r==null?{}:{metadata:r},...o.expiration===void 0?{}:{expiration:o.expiration}}))}},Is=async function*(t,n){for await(const o of jn(t,void 0,n===void 0?{}:{bucket:n}))o.key.startsWith(Ts)||(yield o)},Ml=(e,t,n)=>({last:!0,size:n,...t===void 0?{}:{contentType:t},...e.customMetadata===void 0||Object.keys(e.customMetadata).length===0?{}:{customMetadata:e.customMetadata},...e.sha256===void 0?{}:{sha256:e.sha256}}),$l=async function*(t,n,o){const r=n===void 0?{key:t.key}:{bucket:n,key:t.key},s=t.httpMetadata?.contentType??o.httpMetadata?.contentType;let a=0;for await(const{bytes:d,last:c}of Ul(bs(Pl(o.body),Ye))){const h=c?Ml(t,s,a+d.byteLength):{};yield{doc:{...r,data:Kt(d),offset:a,...h},table:Se},a+=d.byteLength}},Bl=async function*(t,n,o){for(const r of o)for await(const s of Is(t,r)){const a=await n(s.key,{bucket:r});a?.body&&(yield*$l(s,r,{body:a.body,httpMetadata:a.httpMetadata}))}},xl=async function*(t){for await(const n of t.exportRows())yield{doc:{row:n.doc,table:n.table},table:_e}},Hl=(e,t)=>{const n=Dl(e,t),{authData:o,kvIntrospector:r,storageDownload:s,storageList:a}=e;return{header:n.length===0?void 0:{doc:{format:Rn,sections:n},table:Fe},rows:(async function*(){o&&n.includes("auth")&&(yield*xl(o)),r&&n.includes("kv")&&(yield*Ll(r)),a&&s&&n.includes("storage")&&(yield*Bl(a,s,ct(e)))})()}},jl=e=>{const{format:t}=e;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>Rn)throw new l(`Import format ${JSON.stringify(t)} is not supported (this runtime reads formats 1-${String(Rn)})`,{code:"IMPORT_FORMAT_UNSUPPORTED",status:400})},tt=(e,t,n=1)=>{e.inserted[t]=(e.inserted[t]??0)+n},Fn=e=>{e.conflicts+=1},re=(e,t,n,o)=>{e.errors.push({code:n,line:t.line,message:o,table:t.table})},Wn=e=>e instanceof Error?e.message:String(e),Qn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kl=async(e,t,n)=>{const o=[];for(const s of t){const{row:a,table:d}=s.doc;typeof d!="string"||!Qn(a)?re(n,s,"BAD_ROW","an `$auth` record needs a string `table` and an object `row`"):e.authData?o.push({doc:a,row:s,table:d}):re(n,s,"AUTH_NOT_CONFIGURED","row targets an auth table but this worker has no auth data port (`authData`)")}if(o.length===0||!e.authData)return;const r=await e.authData.importRows(o.map(({doc:s,table:a})=>({doc:s,table:a})));tt(n,_e,r.inserted),n.conflicts+=r.conflicts;for(const s of r.errors){const a=o[s.index]?.row;n.errors.push({code:"AUTH_IMPORT_FAILED",line:a?.line??0,message:s.message,table:_e})}},Ns=e=>e instanceof l&&(e.code.endsWith("_RESTORE_INCOMPLETE")||e.code.endsWith("_SHA256_MISMATCH")),ks=async(e,t,n,o,r)=>{await Tl(e,n.root,n.where,o)?tt(r,t.table):re(r,t,`${n.kind}_RESTORE_INCOMPLETE`,`the chunk at byte 0 never arrived, so the one at byte ${String(o.offset)} has nothing to join`)},Ds=async(e,t,n,o,r,s)=>{const a=o.offset===0?void 0:await Es(e,n.root,n.where);if(o.offset>0&&a===void 0){re(r,t,`${n.kind}_RESTORE_INCOMPLETE`,"the chunk at byte 0 never arrived");return}try{await s(Vt(e,n.where,a??"",o,n.kind))}catch(d){if(!Ns(d))throw d;re(r,t,d.code,d.message)}a!==void 0&&await vl(e,a,n.where)},Ps=async(e,t,n)=>{const{expiration:o,key:r,kv:s,metadata:a,namespace:d}=e,c=await s.getValue({key:r,namespace:d}),h=o!==void 0&&o<Math.floor(Date.now()/1e3)+vs;if(c.value!==null||h){Fn(n);return}await s.putValue({encoding:"base64",key:r,namespace:d,value:t,...o===void 0?{}:{expiration:o},...a===void 0?{}:{metadata:a}}),tt(n,be)},Gl=async(e,t,n,o,r,s)=>{const a=Qe(e),d=`KV value ${n.namespace}/${n.key}`;if(!a||o.offset+o.bytes.byteLength>$t){o.lastSize!==void 0&&!a?re(r,t,"KV_STAGING_NOT_CONFIGURED",`${d} is over ${String(Ye)} bytes; its chunks are staged in the default storage bucket, and this worker has no storage ops`):o.lastSize!==void 0&&re(r,t,"KV_VALUE_TOO_LARGE",`${d} is ${String(o.lastSize)} bytes, over KV's ${String($t)}`);return}const c={kind:"KV",root:await Ss(`kv\0${n.namespace}\0${n.key}\0${s}`),where:{}},h=o.lastSize;await(h===void 0?ks(a,t,c,o,r):Ds(a,t,c,o,r,async p=>Ps(n,Kt(await zt(p,h)),r)))},Fl=async(e,t,n,o)=>{const r=e.kvIntrospector,{expiration:s,key:a,metadata:d,namespace:c,value:h}=t.doc;if(!r){re(n,t,"KV_NOT_CONFIGURED","row targets a KV namespace but this worker has no `kvIntrospector`");return}if(typeof c!="string"||typeof a!="string"){re(n,t,"BAD_ROW","a `$kv` record needs a string `namespace` and `key`");return}const p=h===void 0?Qt(t.doc):void 0;if(typeof h!="string"&&!p||s!==void 0&&typeof s!="number"){re(n,t,"BAD_ROW","a `$kv` record needs a base64 string `value` (or a chunk's `data` and `offset`) and a numeric `expiration` if any");return}const m={expiration:s,key:a,kv:r,metadata:d,namespace:c};try{typeof h=="string"?await Ps(m,h,n):p&&await Gl(e,t,m,p,n,o)}catch(g){re(n,t,"KV_IMPORT_FAILED",`KV ${c}/${a}: ${Wn(g)}`)}},Wl=8192,Ql=e=>{if(!Qn(e))return!1;const t=new TextEncoder;let n=0;for(const[o,r]of Object.entries(e)){if(typeof r!="string")return!1;n+=t.encode(o).byteLength+t.encode(r).byteLength}return n<=Wl},Vn=e=>{const{bucket:t,contentType:n,customMetadata:o,key:r}=e,s=Qt(e);if(typeof r!="string"||r.startsWith(Ts)||!s||t!==void 0&&typeof t!="string")return;const a=o===void 0||Ql(o)?o:!1;if(a===!1)return;const d=t===void 0?{}:{bucket:t};return{...s,key:r,upload:{...d,...typeof n=="string"?{contentType:n}:{},...a===void 0?{}:{customMetadata:a},...s.sha256===void 0?{}:{sha256:s.sha256}},where:d}},Us=async(e,t)=>{const n=await e.storageDownload?.(t.key,t.where);return await n?.body?.cancel(),n!=null},Vl=async(e,t,n,o,r,s)=>{const a=o.lastSize??0,d=a>$e?e.storageMultipartUpload:void 0;if(a>$e&&!d){re(s,n,"STORAGE_OBJECT_TOO_LARGE",`${o.key} is ${String(a)} bytes; restoring an object over ${String($e)} bytes needs \`storageMultipartUpload\` on the worker (the export holds it)`);return}await Ds(t,n,r,o,s,async c=>{if(await Us(e,o)){Fn(s);return}if(d){const{contentType:h,customMetadata:p}=o.upload;await As(await d(o.key,{...o.where,contentType:h,customMetadata:p}),c,a)}else{const h=await zt(c,a);await t.upload(o.key,h.buffer,o.upload)}tt(s,Se)})},zl=async(e,t,n,o,r)=>{try{Gn(n,"STORAGE")}catch(s){if(!Ns(s))throw s;re(o,t,s.code,s.message);return}await Us(e,n)?Fn(o):(await r(n.key,n.bytes.buffer,n.upload),tt(o,Se))},Jl=async(e,t,n,o,r)=>{const s=e.storageUpload;if(!s){re(o,t,"STORAGE_NOT_CONFIGURED","row targets a storage bucket but this worker has no `storageUpload`");return}if(n.offset===0&&n.lastSize!==void 0){await zl(e,t,n,o,s);return}const a=Qe(e);if(!a){n.lastSize!==void 0&&re(o,t,"STORAGE_NOT_CONFIGURED","restoring a multi-chunk object needs `storageUpload`, `storageDownload`, `storageList` and `storageDelete` on the worker");return}const d={kind:"STORAGE",root:await Ss(`storage\0${n.where.bucket??""}\0${n.key}\0${r}`),where:n.where};n.lastSize!==void 0?await Vl(e,a,t,n,d,o):(e.storageMultipartUpload||n.offset+n.bytes.byteLength<=$e)&&await ks(a,t,d,n,o)},Yl=async(e,t,n,o)=>{const r=Vn(t.doc);if(!r){re(n,t,"BAD_ROW","a `$storage` record needs a string `key` outside `_lunora/` and base64 `data`, an integer `offset`, a `size` on its last chunk, and string `customMetadata` within 8,192 bytes if any");return}const s=Rs(e,r);if(s!==void 0){re(n,t,"BAD_ROW",s);return}try{await Jl(e,t,r,n,o)}catch(a){re(n,t,"STORAGE_IMPORT_FAILED",`${r.key}: ${Wn(a)}`)}},Xl=async(e,t,n)=>{const o=Qe(e);if(o)try{await Ol(o,ct(e),Date.now())}catch(r){re(n,t,"RESTORE_STAGING_SWEEP_FAILED",`could not delete stale staged chunks: ${Wn(r)}`)}},Zl=async(e,t,n)=>{const o={conflicts:0,errors:[],inserted:{}};await Kl(e,t.filter(r=>r.table===_e),o);for(const r of t)switch(r.table){case Fe:{tt(o,Fe),await Xl(e,r,o);break}case be:{await Fl(e,r,o,n);break}case Se:{await Yl(e,r,o,n);break}}return o},ql=e=>Il.has(e),Cs=e=>e.some(t=>t.table===_e||t.table===Fe&&Array.isArray(t.doc.sections)&&t.doc.sections.includes("auth")),eh="/_lunora/admin/export",th="/_lunora/admin/import",nh="/_lunora/admin/import/commit",oh="/_lunora/admin/import/abort",rh="/_lunora/admin/sync",sh="/_lunora/admin/connector/sync",ah="/_lunora/admin/apply",ih="/_lunora/admin/export-tap/run",ar=new TextEncoder,ch=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!sr.includes(t)))throw new l(`Export \`sections\` must be an array of ${sr.map(t=>`"${t}"`).join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},dh=async e=>{const n=await we(e,"Export")??{},o=ch(n.sections);if(n.tables===void 0)return{sections:o,tables:void 0};if(!Array.isArray(n.tables))throw new l("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new l("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{sections:o,tables:r}},un=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,uh=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSectionRows:r,exportSinks:s,importSession:a,knownTables:d,queryCoordinator:c,assertAdmin:h,assertRootAdmin:p,resolveForwardContext:m,shardDO:g,prepareExportRows:R,streamingImport:E,syncGlobals:b}=e,_=C=>()=>{p(C)},S=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await dh(C),Q=M.sections??(M.tables===void 0?Nl:[]);Q.includes("auth")&&p(C);const{headers:j}=await m(C,V),q=await R(j,M.tables),ee=r(Q),ce=(async function*(){ee.header&&(yield ee.header),yield*q,yield*ee.rows})()[Symbol.asyncIterator]();let te=0;const Ne=new ReadableStream({async cancel(){await ce.return(void 0)},async pull(J){try{const ue=await ce.next();ue.done?(J.enqueue(ar.encode(fs(te))),J.close()):(te+=1,J.enqueue(ar.encode(`${JSON.stringify(ue.value)}
38
- `)))}catch(ue){J.error(ue)}}});return new Response(Ne,{headers:{"content-type":"application/x-ndjson"},status:200})},O=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),Q=typeof M.cursors=="object"&&M.cursors!==null?M.cursors:{},j=typeof M.epochs=="object"&&M.epochs!==null?M.epochs:{},q=typeof M.limit=="number"?M.limit:void 0,ee=typeof M.globalCursor=="number"?M.globalCursor:0,ie=un(M.tables),{headers:ce}=await m(C,V),te=ie??d(),Ne=await c.orchestrateCdcSync(g,{cursors:Q,defaultShardKey:n,epochs:j,headers:ce,limit:q,tables:te}),J=b?await b({limit:q,sinceSeq:ee}):void 0;return Response.json({global:J,shards:Ne.shards},{status:200})},T=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),Q=Fi(M.cursor),j=typeof M.limit=="number"&&M.limit>0?M.limit:void 0,q=un(M.tables),{headers:ee}=await m(C,V),ie=q??d(),ce=await c.orchestrateCdcSync(g,{cursors:Q.s,defaultShardKey:n,headers:ee,limit:j,tables:ie}),te=[],Ne={...Q.s};let J=!1;for(const he of ce.shards)J=vo(te,he.changes??[],Qi(j))||J,Ne[he.shardKey]=he.cursor;let ue=Q.g;if(b){const he=await b({limit:j,sinceSeq:Q.g});J=vo(te,he.changes,j)||J,ue=he.cursor}const Ue=Wi({g:ue,s:Ne,v:1}),nt={changes:te,hasMore:J,nextCursor:Ue};return Response.json(nt,{status:200})},U=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),j=(Array.isArray(M.batches)?M.batches:[]).map(te=>te).filter(te=>te!==null&&typeof te=="object"&&typeof te.shardKey=="string"&&Array.isArray(te.changes)),q=Array.isArray(M.globalChanges)?M.globalChanges:[],{headers:ee}=await m(C,V),ie=await c.orchestrateApplyCdc(g,{batches:j,headers:ee}),ce=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:ie.applied+ce,failed:ie.failed,ok:ie.ok},{status:200})},v=C=>{const{searchParams:V}=new URL(C.url),G=V.get("mode")??"append";if(G==="append")return;if(G!=="replace")throw new l("Import `mode` must be `append` or `replace`",{code:"BAD_REQUEST",status:400});const M=d(),Q=V.get("tables")?.split(",").filter(ee=>ee.length>0),j=Q===void 0||Q.length===0?M:Q;if(j.length===0)throw new l("A replace import needs `tables`: this worker cannot list its schema's tables",{code:"BAD_REQUEST",status:400});const q=M.length>0?j.filter(ee=>!M.includes(ee)):[];if(q.length>0)throw new l(`Replace import names unknown table(s): ${q.join(", ")}`,{code:"BAD_REQUEST",status:400});return j},x=async(C,V,G,M)=>{const{headers:Q}=await m(C,V);if(M!==void 0){const q=await a.stage(C,Q,M,G,_(C));return Response.json(q,{status:q.failed.length>0?207:200})}const j=await a.replace(C,Q,G,_(C));return Response.json(j,{headers:{"content-type":"application/json"},status:j.failed.length>0?207:200})},W=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const{searchParams:M}=new URL(C.url),Q=M.get("dryRun")==="true",j=M.get("onConflict")??"skip";if(j!=="replace"&&j!=="skip")throw new l(`onConflict must be "skip" or "replace", got ${JSON.stringify(j)}`,{code:"BAD_REQUEST",status:400});const q=v(C),ee=M.get("stage")??void 0;if(ee!==void 0&&q===void 0)throw new l("Import `stage` needs `mode=replace`: only a replace is staged",{code:"BAD_REQUEST",status:400});if(q!==void 0){if(Q||M.has("onConflict"))throw new l("`mode=replace` takes neither `dryRun` nor `onConflict`",{code:"BAD_REQUEST",status:400});return x(C,V,q,ee)}const ie=await E(C,async()=>{const{headers:te}=await m(C,V);return te},Q,j,_(C)),ce={...ie,...Q?{dryRun:!0}:{},...j==="replace"?{onConflict:"replace"}:{}};return Response.json(ce,{headers:{"content-type":"application/json"},status:ie.failed.length>0?207:200})},X=async C=>{const V=await ae(C);if(typeof V.session!="string")throw new l("Import commit / abort needs a string `session`",{code:"BAD_REQUEST",status:400});return V.session},se=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await X(C),{headers:Q}=await m(C,V),j=await a.commit(Q,M,_(C)),q={committed:200,partial:502,refused:409}[j.status]??500;return Response.json(j,{status:q})},Oe=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await X(C),{headers:Q}=await m(C,V);return Response.json(await a.abort(Q,M),{status:200})},Ie=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;if(h(C),s===void 0||Object.keys(s).length===0||o===void 0)throw new l("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const M=await ae(C),Q=typeof M.sink=="string"?M.sink:void 0,j=typeof M.limit=="number"&&M.limit>0?M.limit:void 0,q=un(M.tables);if(Q===void 0)throw new l("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=s[Q];if(ee===void 0)throw new l(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:ie}=await m(C,V),ce=q??d(),te=await Gi({coordinator:c,cursorStore:o,defaultShardKey:n,headers:ie,limit:j,shardDO:g,sink:ee,tables:ce});return Response.json(te,{headers:{"content-type":"application/json"},status:200})};return{[ah]:U,[sh]:T,[eh]:S,[ih]:Ie,[oh]:Oe,[nh]:se,[th]:W,[rh]:O}},lh="/_lunora/admin/pause",hh=5e3,fh=3e3,ph=30,bt={paused:!1},ir=10,mh=async(e,t,n)=>{let o;try{const s=await e.fetch(new Request("https://scheduler.internal/instances"));if(!s.ok)throw new Error(`answered ${String(s.status)}`);o=(await s.json()).instances??[]}catch(s){return[`(the instance list: ${s instanceof Error?s.message:String(s)})`]}const r=[];for(let s=0;s<o.length;s+=ir)await Promise.all(o.slice(s,s+ir).map(async a=>{try{(await t(a)?.fetch(new Request("https://scheduler.internal/pause",n)))?.ok||r.push(a)}catch{r.push(a)}}));return r.toSorted((s,a)=>s.localeCompare(a))},wh=async(e,t)=>{let n;const o=new Promise(r=>{n=setTimeout(()=>{r(t())},fh)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}},gh=e=>{const t=e.now??Date.now;let n,o,r=0;const s=async(h,p)=>{const m=p?.method==="POST",g=r;m&&(r+=1);const R=await h.fetch(new Request("https://scheduler.internal/pause",p));if(!R.ok)throw new l(`SchedulerDO /pause answered ${String(R.status)}: ${await R.text()}`,{code:"INTERNAL",status:502});const E=await R.json();return m&&(r+=1),(m||r===g)&&(n={readAt:t(),state:E}),E},a=async()=>{const h=e.stub();if(h===void 0)return bt;if(n!==void 0&&t()-n.readAt<hh)return n.state;const p=r,m=o??s(h).catch(()=>{const g=n?.state??bt;return r===p&&(n={readAt:t(),state:g}),g}).finally(()=>{o===m&&(o=void 0)});return o=m,wh(m,()=>{const g=n?.state??bt;return o===m&&(o=void 0,r===p&&(n={readAt:t(),state:g}),r+=1),g})};return{handleRoute:async h=>{e.assertAdmin(h);const p=e.stub();if(h.method==="GET")return Response.json(p===void 0?{...bt,supported:!1}:{...await s(p),supported:!0});if(Y(h,"POST","Deployment pause"),p===void 0)throw new l("pausing a deployment requires a `schedulerDO` namespace on the worker",{code:"PAUSE_NOT_CONFIGURED",status:400});const m=await h.json().catch(()=>{});if(typeof m?.paused!="boolean")throw new l("Deployment pause requires a boolean `paused`",{code:"BAD_REQUEST",status:400});const g={body:JSON.stringify({paused:m.paused,...typeof m.reason=="string"?{reason:m.reason}:{}}),headers:{"content-type":"application/json"},method:"POST"},R=await s(p,g),E=e.instanceStub===void 0?[]:await mh(p,e.instanceStub,g);if(E.length>0)throw new l(`the deployment ${m.paused?"paused":"resumed"} on its main scheduler instance but not on: ${E.join(", ")}. Run the same command again to reach them`,{code:"PAUSE_INSTANCES_FAILED",status:502});return Response.json({...R,supported:!0})},read:a,refusal:async h=>{if(!(!(await a()).paused||await e.isAdmin(h)))return Response.json({error:{code:"DEPLOYMENT_PAUSED",message:"the deployment is paused"}},{headers:{"cache-control":"no-store","retry-after":String(ph)},status:503})}}},On=300,zn=["auth","kv","storage"],Jt={auth:_e,kv:be,storage:Se},yh="_lunora/restore-session/",Yt=e=>`${yh}${e.session}/${e.generation}/`,Jn=e=>`${Yt(e)}owed/`,Ls=async e=>et(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),Ms=async(e,t)=>`${Yt(e)}${await Ls(t)}/`,$s=(e,t)=>`kv\0${e}\0${t}`,Bs=(e,t)=>`storage\0${e.bucket??""}\0${t}`,_h=e=>{const t=e.find(o=>o.table===Fe),n=Array.isArray(t?.doc.sections)?t.doc.sections:[];return zn.filter(o=>n.includes(o))},le=(e,t,n,o)=>{e.push({code:n,line:t.line,message:o,table:t.table})},Yn=e=>e instanceof Error?e.message:String(e),bh=async(e,t,n,o)=>{const r=Kn(t,o.offset);await e.upload(r,await Hn(e.secret,r,o.bytes),n)},Sh=async(e,t,n,o,r)=>{try{let s=0;for await(const a of Vt(e,n,t,o,r))s+=a.byteLength;return s===o.lastSize?void 0:{code:`${r}_RESTORE_INCOMPLETE`,message:`read ${String(s)} of ${String(o.lastSize)} bytes`}}catch(s){return{code:s instanceof l?s.code:`${r}_RESTORE_INCOMPLETE`,message:Yn(s)}}},xs=async(e,t,n,o,r)=>{const s=await Ls(n);return{kind:t,label:o,owed:`${Jn(e)}${t==="KV"?"kv":"storage"}/${s}`,prefix:`${Yt(e)}${s}/`,where:r}},Hs=async(e,t,n,o,r)=>{if(r.lastSize===void 0){await e.upload(o.owed,await Hn(e.secret,o.owed,new TextEncoder().encode(o.label)),o.where),await bh(e,o.prefix,o.where,r);return}const s=await Sh(e,o.prefix,o.where,r,o.kind);if(s!==void 0){le(n,t,s.code,s.message);return}return await e.delete(o.owed,o.where),{doc:t.doc,line:t.line,table:t.table}},Eh=new Set(["__lunora_auth_audit__","devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),Ah=(e,t)=>{if(typeof e.doc.table!="string"||!Qn(e.doc.row)){le(t,e,"BAD_ROW","an `$auth` record needs a string `table` and an object `row`");return}if(Eh.has(e.doc.table.toLowerCase())){le(t,e,"BAD_ROW",`the auth table "${e.doc.table}" is never restored`);return}return{doc:e.doc,line:e.line,table:_e}},Th=async(e,t,n,o)=>{const{expiration:r,key:s,namespace:a,value:d}=n.doc;if(typeof a!="string"||typeof s!="string"||r!==void 0&&typeof r!="number"){le(o,n,"BAD_ROW","a `$kv` record needs a string `namespace` and `key`, and a numeric `expiration` if any");return}if(typeof d=="string")return{doc:n.doc,line:n.line,table:be};const c=Qt(n.doc);if(!c){le(o,n,"BAD_ROW","a `$kv` record needs a base64 string `value`, or a chunk's `data` and `offset`");return}const h=Qe(e);if(!h){le(o,n,"KV_STAGING_NOT_CONFIGURED",`KV value ${a}/${s} is chunked; staging its chunks needs the storage ops and an admin token`);return}if(c.offset+c.bytes.byteLength>$t){le(o,n,"KV_VALUE_TOO_LARGE",`KV value ${a}/${s} is over KV's ${String($t)} bytes`);return}return Hs(h,n,o,await xs(t,"KV",$s(a,s),`KV value ${a}/${s}`,{}),c)},vh=async(e,t,n,o)=>{const r=Vn(n.doc);if(!r){le(o,n,"BAD_ROW","a `$storage` record needs a string `key` outside `_lunora/` and base64 `data`, an integer `offset`, a `size` on its last chunk, and string `customMetadata` within 8,192 bytes if any");return}const s=Rs(e,r);if(s!==void 0){le(o,n,"BAD_ROW",s);return}if(r.offset===0&&r.lastSize!==void 0){try{Gn(r,"STORAGE")}catch(d){le(o,n,d instanceof l?d.code:"STORAGE_RESTORE_INCOMPLETE",Yn(d));return}return{doc:n.doc,line:n.line,table:Se}}const a=Qe(e);if(!a){le(o,n,"STORAGE_NOT_CONFIGURED","staging a multi-chunk object needs the four storage ops and an admin token");return}if(r.offset+r.bytes.byteLength>$e&&!e.storageMultipartUpload){le(o,n,"STORAGE_OBJECT_TOO_LARGE",`${r.key} is over ${String($e)} bytes; restoring it needs \`storageMultipartUpload\` on the worker`);return}return Hs(a,n,o,await xs(t,"STORAGE",Bs(r.where,r.key),`storage object ${r.where.bucket===void 0?"":`${r.where.bucket}/`}${r.key}`,r.where),r)},Rh=async(e,t,n,o)=>{const r=[],s=[],a=_h(n),d=new Set([...o,...a]);let c=!1;for(const h of n){let p;const m=zn.find(g=>Jt[g]===h.table);if(m!==void 0&&!d.has(m)){le(r,h,"BAD_ROW",`the snapshot header does not declare the \`${m}\` section, so this record would never be restored`);continue}try{switch(h.table){case _e:{p=Ah(h,r);break}case be:{c=!0,p=await Th(e,t,h,r);break}case Se:{c=!0,p=await vh(e,t,h,r);break}default:}}catch(g){le(r,h,"SECTION_STAGING_FAILED",Yn(g))}p&&s.push(p)}return{errors:r,rows:s,sections:a,storage:c}},Oh=(e,t)=>{switch(t){case"auth":return e.authData?.replaceRows?void 0:"the snapshot carries auth tables, but this worker's auth data port cannot replace them";case"kv":return e.kvIntrospector?void 0:"the snapshot carries KV, but this worker has no `kvIntrospector`";case"storage":return e.storageList&&e.storageDownload&&e.storageUpload&&e.storageDelete?void 0:"the snapshot carries storage objects, but this worker lacks `storageList`, `storageDownload`, `storageUpload` or `storageDelete`";default:return`unknown section "${t}"`}},js=async e=>{const t=[];for await(const n of e)t.push({doc:n.doc.row,table:String(n.doc.table)});return t},Ih=async(e,t)=>{const n=await js(t);return(await(e.authData?.replaceRows?.(n,{dryRun:!0})??Promise.reject(new TypeError("auth replace is not configured")))).errors.map(r=>({code:"AUTH_IMPORT_FAILED",line:0,message:r.message,table:_e}))},Nh=async(e,t)=>{const n=await js(t),o=await(e.authData?.replaceRows?.(n)??Promise.reject(new TypeError("auth replace is not configured")));if(o.errors.length>0)throw new l(`auth replace rolled back: ${o.errors.map(r=>r.message).join("; ")}`,{code:"AUTH_IMPORT_FAILED",status:409});return{deleted:{[_e]:o.deleted},inserted:{[_e]:o.inserted}}},Ks=e=>{const t=Qe(e);if(!t)throw new TypeError("restore staging needs the storage ops and an admin token");return t},kh=async(e,t,n)=>{if(typeof n.value=="string")return n.value;const o=Qt(n);if(o?.lastSize===void 0)throw new TypeError("a staged KV record is neither a value nor a last chunk");const r=await Ms(t,$s(String(n.namespace),String(n.key)));return Kt(await zt(Vt(Ks(e),{},r,o,"KV"),o.lastSize))},Dh=async(e,t,n)=>{const o=e.kvIntrospector;if(!o)throw new TypeError("kv replace is not configured");const r=new Set;let s=0;const a=Math.floor(Date.now()/1e3);for await(const{doc:d}of n){const c=String(d.namespace),h=String(d.key),{expiration:p,metadata:m}=d;typeof p=="number"&&p<a+vs||(await o.putValue({encoding:"base64",key:h,namespace:c,value:await kh(e,t,d),...typeof p=="number"?{expiration:p}:{},...m===void 0?{}:{metadata:m}}),r.add(`${c}\0${h}`),s+=1)}return{inserted:s,keep:r}},Ph=async(e,t,n)=>{const o=[];for await(const{name:r}of Os(e,t))n.has(`${t}\0${r}`)||o.push(r);for(const r of o)await e.deleteKey({key:r,namespace:t});return o.length},Uh=async(e,t,n)=>{const{inserted:o,keep:r}=await Dh(e,t,n),s=e.kvIntrospector;let a=0;for(const{binding:d}of await s?.listNamespaces()??[])a+=await Ph(s,d,r);return{deleted:{[be]:a},inserted:{[be]:o}}},Gs=async(e,t,n)=>{const o=[];let r;do{const s=await e(t,{...n,cursor:r,limit:1e3});o.push(...s.objects.map(a=>a.key).filter(a=>a.startsWith(t))),r=s.truncated===!1?void 0:s.cursor}while(r!==void 0);return o},Fs=async(e,t)=>{const{storageDelete:n,storageList:o}=e;if(!(!n||!o))for(const r of new Set([void 0,...e.storageBuckets??[]])){const s=r===void 0?{}:{bucket:r},a=await Gs(o,Yt(t),s);await Promise.all(a.map(async d=>n(d,s)))}},Ch=async(e,t,n,o)=>{const r=await e.download(n,o),s=r?.body?await _s(e.secret,n,new Uint8Array(await new Response(r.body).arrayBuffer())):void 0;return{code:"IMPORT_SESSION_INCOMPLETE",line:0,message:`${s===void 0?n:new TextDecoder().decode(s)} never received its last chunk — the snapshot stream ended part-way through it`,table:n.slice(Jn(t).length).startsWith("kv/")?be:Se}},Lh=async(e,t)=>{const n=Qe(e);if(!n)return[];const o=new Map;for(const r of new Set([void 0,...e.storageBuckets??[]])){const s=r===void 0?{}:{bucket:r};for(const a of await Gs(n.list,Jn(t),s))o.has(a)||o.set(a,s)}return Promise.all([...o].map(async([r,s])=>Ch(n,t,r,s)))},Mh=async(e,t,n)=>{const o=e.storageUpload;if(!o)throw new TypeError("storage replace is not configured");const r=n.lastSize??0;if(n.offset===0){Gn(n,"STORAGE"),await o(n.key,n.bytes.buffer,n.upload);return}const s=Vt(Ks(e),n.where,await Ms(t,Bs(n.where,n.key)),n,"STORAGE");if(r>$e&&e.storageMultipartUpload){const{contentType:d,customMetadata:c}=n.upload;await As(await e.storageMultipartUpload(n.key,{...n.where,contentType:d,customMetadata:c}),s,r);return}const a=await zt(s,r);await o(n.key,a.buffer,n.upload)},$h=async(e,t,n)=>{const{storageDelete:o,storageList:r}=e;if(!o||!r)throw new TypeError("storage replace is not configured");const s=new Set,a=ct(e),d=a.includes("default")?"default":a[0];let c=0,h=0;for await(const{doc:p}of n){const m=Vn(p);if(!m)throw new TypeError("a staged storage record does not parse");s.add(`${m.where.bucket??d??""}\0${m.key}`),await Mh(e,t,m),c+=1}for(const p of ct(e)){const m=[];for await(const g of Is(r,p))s.has(`${p??""}\0${g.key}`)||m.push(g.key);await Promise.all(m.map(async g=>o(g,p===void 0?{}:{bucket:p}))),h+=m.length}return{deleted:{[Se]:h},inserted:{[Se]:c}}},Bh=async(e,t,n,o)=>{switch(n){case"auth":return Nh(e,o);case"kv":return Uh(e,t,o);default:return $h(e,t,o)}},Ws=e=>new URL(e.url).searchParams.get("deletes")==="true",xh=/^[\w-]{1,64}$/u,Hh=e=>{const t=new URL(e.url).searchParams.get("import");if(t===null)return crypto.randomUUID();if(!xh.test(t))throw new l("Import `import` is 1-64 characters of [A-Za-z0-9_-]",{code:"BAD_REQUEST",status:400});return t},jh=(e,t,n)=>{let o;try{o=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=el(o);if(r!==void 0)return{end:r,ok:"end"};const s=o;return typeof s.table!="string"||s.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!s.doc||typeof s.doc!="object"||Array.isArray(s.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:s.table},ok:!1}:s.op==="delete"&&!n?{error:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `?deletes=true` on the import request',table:s.table},ok:!1}:s.op!==void 0&&s.op!=="delete"?{error:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(s.op)}`,table:s.table},ok:!1}:{doc:s.doc,ok:!0,...s.op==="delete"?{op:"delete"}:{},table:s.table}},Kh=(e,t,n,o,r)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const s=e[n.mode.field];return s==null?{error:{code:"BAD_ROW",line:r,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:o}},Gh=(e,t,n)=>{if(!(e===void 0||!t&&e===n))throw new l(t?"the import body continues after its end marker, so nothing was imported":`the import body's end marker declares ${String(e)} row(s) but ${String(n)} were read, so nothing was imported`,{code:"BAD_REQUEST",status:400})},Qs=async(e,t,n,o)=>{if(!e.body&&o===void 0)throw new l("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=Ws(e),s=[],a=[],d=new Map,c=[];let h=0;const p={declaredRows:void 0,trailingAfterEnd:!1};let m=0;if(!e.body)return{errors:s,globalRows:a,perShard:d,received:h,sectionRows:c};const g=e.body.getReader(),R=new TextDecoder;let E="",b=0;const _=S=>{m+=1;const O=S.trim();if(O.length===0)return;h+=1,p.declaredRows!==void 0&&(p.trailingAfterEnd=!0);const T=jh(O,m,r);if(T.ok==="end"){h-=1,p.declaredRows=T.end;return}if(!T.ok){s.push(T.error);return}const{doc:U,table:v}=T;if(ql(v)){v===Fe&&jl(U),c.push({doc:U,line:m,table:v});return}if(o!==void 0&&!o.has(v)){s.push({code:"BAD_ROW",line:m,message:`table "${v}" is not in this replace import's tables`,table:v});return}const x=T.op===void 0?{}:{op:T.op},W=t.resolveTableSharding?.(v);if(W?.mode.kind==="global"){a.push({doc:U,line:m,...x,table:v});return}const X=Kh(U,v,W,n,m);if(!X.ok){s.push(X.error);return}const se=d.get(X.shardKey);se?se.rows.push({doc:U,line:m,...x,table:v}):d.set(X.shardKey,{rows:[{doc:U,line:m,...x,table:v}],shardKey:X.shardKey,startLine:m})};for(;;){const{done:S,value:O}=await g.read();if(S)break;if(O&&(b+=O.byteLength,b>Br))throw await g.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=R.decode(O,{stream:!0});let T=E.indexOf(`
39
- `);for(;T!==-1;){const U=E.slice(0,T);E=E.slice(T+1),_(U),T=E.indexOf(`
40
- `)}}return E.length>0&&_(E),Gh(p.declaredRows,p.trailingAfterEnd,h),{errors:s,globalRows:a,perShard:d,received:h,sectionRows:c}},Fh=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),In=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts,e.deleted+=t.deleted??0,e.replaced+=t.replaced??0},cr=(e,t,n,o)=>{for(const r of t)e.errors.push({code:n,line:r.line,message:`row targets global table "${r.table}" but ${o}`,table:r.table})},Xn=async(e,t,n,o,r)=>{try{await e({conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted,op:n,...o.deleted===void 0?{}:{deleted:o.deleted},...o.replaced===void 0?{}:{replaced:o.replaced},...r})}catch(s){t.push(`the ${n} audit entry was not recorded: ${s instanceof Error?s.message:String(s)}`)}},Wh=async(e,t,n,o,r,s)=>{if(o.length===0)return;if(!e.importGlobals){cr(t,o,"GLOBAL_NOT_CONFIGURED","no `importGlobals` is configured");return}if(s.dryRun&&e.importGlobalsSupportsDryRun!==!0){cr(t,o,"GLOBAL_DRY_RUN_UNSUPPORTED","the configured `importGlobals` cannot check rows without writing them");return}const a=await e.importGlobals({dryRun:s.dryRun,onConflict:s.onConflict,rows:o,startLine:o[0]?.line??1});if(In(t,a),!s.dryRun){const d=[...new Set(o.map(c=>c.table))].toSorted((c,h)=>c.localeCompare(h));await Xn(r,n,"importGlobal",a,{tables:d})}},Vs="no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one",Qh=async(e,t,n,o,r,s,a,d,c)=>{const h=t.defaultShardKey??"__root__",p=Hh(e),{errors:m,globalRows:g,perShard:R,received:E,sectionRows:b}=await Qs(e,t,h,void 0);if(Cs(b)&&c(),a==="replace"&&g.length>0&&(t.importGlobals===void 0||t.importGlobalsSupportsReplace!==!0))throw new l("onConflict=replace: global rows are present but no `importGlobals` that can overwrite existing rows is configured, so nothing was imported",{code:"BAD_REQUEST",status:400});if(g.some(O=>O.op==="delete")&&t.importGlobalsSupportsDelete!==!0)throw new l("delete rows target global tables but no `importGlobals` that can delete rows is configured, so nothing was imported",{code:"BAD_REQUEST",status:400});const _={conflicts:0,deleted:0,errors:m,failed:[],inserted:{},replaced:0},S=[];if(t.resolveTableSharding===void 0&&R.size>0&&S.push(Vs),R.size>0){const O=await n.orchestrateImport(r,{batches:[...R.values()],deletes:Ws(e),dryRun:s,headers:await o(),onConflict:a});In(_,O),_.failed.push(...Fh(O.shards))}if(await Wh(t,_,S,g,d,{dryRun:s,onConflict:a}),b.length>0&&s)S.push(`a dry run does not check the export's sections ($auth, $kv, $storage): ${String(b.length)} section line(s) were not checked`);else if(b.length>0){const O=await Zl(t,b,p);In(_,O),await Xn(d,S,"importSections",O,{})}return{conflicts:_.conflicts,deleted:_.deleted,errors:_.errors,failed:_.failed,inserted:_.inserted,received:E,replaced:_.replaced,...S.length>0?{warnings:S}:{}}},Pe={abort:"__lunora_admin__:importAbort",commit:"__lunora_admin__:importCommit",manifest:"__lunora_admin__:importManifest",stage:"__lunora_admin__:importStage",stagedRows:"__lunora_admin__:importStagedRows"},zs={BAD_REQUEST:400,IMPORT_SESSION_CHANGED:409,IMPORT_SESSION_CLOSED:409,IMPORT_SESSION_COMMITTED:409,IMPORT_SESSION_COMMITTING:409,IMPORT_SESSION_CORRUPT:409,IMPORT_SESSION_EXPIRED:410,IMPORT_SESSION_INCOMPLETE:409,IMPORT_SESSION_MISMATCH:400,IMPORT_SESSION_NOT_COMMITTING:409,IMPORT_SESSION_NOT_FOUND:404,IMPORT_SESSION_REJECTED:409,IMPORT_SESSION_STALE:409,IMPORT_STEP_CLAIMED:409,IMPORT_STEP_DONE:409},Vh=/^[\w-]{1,64}$/u,Zn=e=>{if(!Vh.test(e))throw new l("An import session id is 1-64 characters of [A-Za-z0-9_-]",{code:"BAD_REQUEST",status:400})},Xt=e=>e.defaultShardKey??"__root__",dr=(e,t)=>e.resolveTableSharding?.(t)?.mode.kind==="global",Js=(e,t)=>({globalScope:t.filter(n=>dr(e,n)),shardScope:t.filter(n=>!dr(e,n))}),We=(e,t)=>{for(const[n,o]of Object.entries(t??{}))e[n]=(e[n]??0)+o},Ys=e=>e.error?{message:e.error.message,shardKey:e.shardKey,timedOut:e.error.timedOut}:void 0,De=(e,t)=>new l(t,{code:e,status:zs[e]??502}),qn=e=>{const t=e?.code;throw typeof t=="string"&&t in zs&&!(e instanceof l)?De(t,e instanceof Error?e.message:String(e)):e},qe=async(e,t,n)=>{const[o]=await e.coordinator.orchestrateImportSession(e.namespace,{calls:[{args:n,shardKey:Xt(e.options)}],functionPath:t,headers:e.headers});if(o===void 0||o.error)throw De(o?.error?.code??"SHARD_UNREACHABLE",o?.error?.message??"the root shard did not answer");return o.value},Xs=async(e,t)=>{const n=await qe(e,Pe.manifest,{op:"get",session:t});if(n===null||typeof n!="object"||!("manifest"in n))throw De("IMPORT_SESSION_CORRUPT",`the root shard answered no manifest for import session "${t}"`);return n.manifest??void 0},Ze=async(e,t,n)=>{const{manifest:o}=await qe(e,Pe.manifest,{op:"advance",session:t,...n});return o},lt=e=>({generation:e.generation,session:e.session}),Zs=async(e,t)=>{const n=t.shards.filter(s=>s!==Xt(e.options)),r=(await e.coordinator.orchestrateImportSession(e.namespace,{calls:n.map(s=>({args:{generation:t.generation,session:t.session},shardKey:s})),functionPath:Pe.abort,headers:e.headers})).find(s=>s.error);if(r?.error)throw De("SHARD_UNREACHABLE",`could not drop the staging on shard "${r.shardKey}": ${r.error.message}`);await e.options.importGlobalsStaging?.abort({generation:t.generation,session:t.session}).catch(qn),await Fs(e.options,lt(t))},zh=async(e,t)=>{for(const n of t)await Zs(e,n).catch(()=>{})},Jh=async(e,t,n,o)=>{const r=[],s=[],a={},d=await e.coordinator.orchestrateImportSession(e.namespace,{calls:[...o].map(([c,h])=>({args:{generation:t.generation,rows:h,session:t.session,tables:n},shardKey:c})),functionPath:Pe.stage,headers:e.headers});for(const c of d){const h=Ys(c);if(h){s.push(h);continue}const p=c.value;r.push(...p.errors??[]),We(a,p.staged)}return{errors:r,failed:s,staged:a}},qs=async(e,t,n,o)=>{const{options:r}=t,s=Xt(r),{globalScope:a,shardScope:d}=Js(r,o);if(Zn(n),a.length>0&&!r.importGlobalsStaging)throw new l(`replace import covers .global() table(s) ${a.join(", ")} but no \`importGlobalsStaging\` is configured`,{code:"GLOBAL_NOT_CONFIGURED",status:400});const c=await Qs(e,r,s,new Set(o));Cs(c.sectionRows)&&t.assertAuthSectionAllowed();const h=new Map;for(const O of c.perShard.values())h.set(O.shardKey,[...O.rows]);const p=c.sectionRows.length>0,m=await qe(t,Pe.manifest,{begin:!0,globals:c.globalRows.length>0,op:"touch",received:c.received,session:n,shards:[...h.keys(),...p?[s]:[]],storage:c.sectionRows.some(O=>O.table==="$kv"||O.table==="$storage"),tables:o});m.created&&m.expired.length>0&&await zh(t,m.expired);const g=lt(m.manifest),R=await Rh(r,g,c.sectionRows,m.manifest.sections),E=[...c.errors,...R.errors],b=[],_={},S=r.resolveTableSharding===void 0&&c.perShard.size>0?[Vs]:[];if(R.rows.length>0&&h.set(s,[...h.get(s)??[],...R.rows]),E.length===0){const O=await Jh(t,g,d,h);if(E.push(...O.errors),b.push(...O.failed),We(_,O.staged),c.globalRows.length>0&&r.importGlobalsStaging){const T=await r.importGlobalsStaging.stage({generation:g.generation,rows:c.globalRows,session:n,tables:a}).catch(qn);E.push(...T.errors),We(_,T.staged)}}return await qe(t,Pe.manifest,{begin:!1,op:"touch",rejected:E.length+b.length,sections:R.sections,session:n,tables:o}),{errors:E,failed:b,received:c.received,session:n,staged:_,...S.length>0?{warnings:S}:{}}},ea=async function*(t,n,o){let r=0;for(;;){const s=await qe(t,Pe.stagedRows,{afterSeq:r,limit:o==="auth"?200:8,sections:[Jt[o]],session:n});if(s.rows.length===0)return;yield*s.rows,r=s.seq}},ta=async(e,t,n,o,r)=>{const s=await e.coordinator.orchestrateImportSession(e.namespace,{calls:n.map(d=>({args:{dryRun:r,generation:t.generation,session:t.session,staged:t.shards.includes(d),tables:o},shardKey:d})),functionPath:Pe.commit,headers:e.headers}),a={deleted:{},errors:[],failed:[],inserted:{}};for(const d of s){const c=Ys(d);if(c){a.failed.push(c);continue}const h=d.value;a.errors.push(...h.errors??[]),We(a.deleted,h.deleted),We(a.inserted,h.inserted)}return a},Yh=e=>{const t={},n={},o=[];for(const r of Object.values(e.steps))We(t,r.deleted),We(n,r.inserted),o.push(...r.warnings??[]);return{deleted:t,inserted:n,warnings:o}},ur=e=>{const{deleted:t,inserted:n,warnings:o}=Yh(e);return{deleted:t,inserted:n,session:e.session,status:"committed",...o.length>0?{warnings:o}:{}}},Xh=(e,t,n)=>{if(t.state==="aborting")throw De("IMPORT_SESSION_CLOSED",`import session "${t.session}" is being aborted`);if(t.state==="open"&&t.rejected>0)throw De("IMPORT_SESSION_REJECTED",`import session "${t.session}" had ${String(t.rejected)} refused row(s) or unreachable shard(s) while staging — abort it`);if(t.state==="open"&&t.pending>0)throw De("IMPORT_SESSION_INCOMPLETE",`import session "${t.session}" has ${String(t.pending)} staging request(s) that never finished — abort it`);if(n.length>0&&!e.importGlobalsStaging)throw new l("replace import covers .global() tables but no `importGlobalsStaging` is configured",{code:"GLOBAL_NOT_CONFIGURED",status:400});for(const o of t.sections){const r=Oh(e,o);if(r!==void 0)throw new l(r,{code:"SECTION_NOT_CONFIGURED",status:400})}},ln=async(e,t,n,o,r)=>{if(t.steps[o]!==void 0)return t;const{session:s}=t;await Ze(e,s,{claim:n,step:o});try{return await Ze(e,s,{claimant:n,step:o,stepResult:await r()})}catch(a){throw await Ze(e,s,{release:n,step:o}).catch(()=>{}),a}};class Bt extends Error{errors;failed;constructor(t,n){super("commit step failed"),this.errors=t,this.failed=n}}const Zh=(e,t)=>new Bt([{code:"SECTION_COMMIT_FAILED",line:0,message:t instanceof Error?t.message:String(t),table:Jt[e]}],[]),lr=async(e,t,n,o,r)=>{const s=[...r.warnings??[]];return await Xn(e.recordAudit,s,t,{conflicts:0,deleted:r.deleted,errors:[],inserted:r.inserted},{replaceTables:o,session:n,tables:o}),{...r,...s.length>0?{warnings:s}:{}}},qh=async(e,t,n)=>{const{options:o}=e,{session:r}=t,s=crypto.randomUUID();let a=t;n.targets.length>0&&(a=await ln(e,a,s,"shards",async()=>{const c=await ta(e,t,n.targets,n.shardScope,!1);if(c.errors.length>0||c.failed.length>0)throw new Bt(c.errors,c.failed);return{deleted:c.deleted,inserted:c.inserted}}));const d=o.importGlobalsStaging;n.globalScope.length>0&&d&&(a=await ln(e,a,s,"globals",async()=>{const c=await d.commit({generation:t.generation,session:r,staged:t.globals,tables:n.globalScope}).catch(qn);if(c.errors.length>0)throw new Bt([...c.errors],[]);return lr(e,"importGlobal",r,n.globalScope,{deleted:c.deleted??{},inserted:c.inserted})}));for(const c of zn.filter(h=>t.sections.includes(h)))a=await ln(e,a,s,c,async()=>{const h=await Bh(o,lt(t),c,ea(e,r,c)).catch(p=>{throw Zh(c,p)});return lr(e,"importSections",r,[Jt[c]],h)});return a},ef=async(e,t,n,o)=>{const{options:r}=e,{session:s}=t,a=t.storage?await Lh(r,lt(t)):[];if(a.length>0)return{errors:a,failed:[],session:s,status:"refused"};const d=await ta(e,t,n,o,!0);if(d.errors.length>0||d.failed.length>0)return{errors:d.errors,failed:d.failed,session:s,status:"refused"};const c=t.sections.includes("auth")?await Ih(r,ea(e,s,"auth")):[];return c.length>0?{errors:c,failed:[],session:s,status:"refused"}:void 0},na=async(e,t)=>{const{options:n}=e;Zn(t);let o=await Xs(e,t);if(o===void 0)throw De("IMPORT_SESSION_NOT_FOUND",`import session "${t}" does not exist or has expired`);if(o.sections.includes("auth")&&e.assertAuthSectionAllowed(),o.state==="committed")return ur(o);const{globalScope:r,shardScope:s}=Js(n,o.tables);Xh(n,o,r);const a=s.length===0?[]:[...new Set([...o.shards,...await e.coordinator.shardKeysForTables(s,Xt(n))])];if(o.state==="open"){const d=await ef(e,o,a,s);if(d!==void 0)return d;o=await Ze(e,t,{batches:o.batches,state:"committing"})}try{await qh(e,o,{globalScope:r,shardScope:s,targets:a})}catch(d){if(d instanceof Bt)return{errors:d.errors,failed:d.failed,session:t,status:"partial"};throw d}return o=await Ze(e,t,{state:"committed"}),await Fs(n,lt(o)).catch(()=>{}),ur(o)},Ot=async(e,t)=>{Zn(t);const n=await Xs(e,t);if(n===void 0)return{aborted:!1};if(n.state==="committed"||n.state==="committing")throw De(n.state==="committed"?"IMPORT_SESSION_COMMITTED":"IMPORT_SESSION_COMMITTING",n.state==="committed"?`import session "${t}" is already committed`:`import session "${t}" is being committed — send the commit again to finish it`);const o=await Ze(e,t,{state:"aborting"});return await Zs(e,o),await qe(e,Pe.manifest,{op:"drop",session:t}),{aborted:!0}},tf=async(e,t,n)=>{const o=`once-${crypto.randomUUID()}`;let r;try{r=await qs(e,t,o,n)}catch(c){throw await Ot(t,o).catch(()=>{}),c}const s={conflicts:0,deleted:{},inserted:{},received:r.received,...r.warnings?{warnings:r.warnings}:{}};if(r.errors.length>0||r.failed.length>0)return await Ot(t,o).catch(()=>{}),{...s,errors:r.errors,failed:r.failed};const a=await na(t,o);if(a.status==="refused"&&await Ot(t,o).catch(()=>{}),a.status!=="committed")return{...s,errors:a.errors,failed:a.failed};const d=[...r.warnings??[],...a.warnings??[]];return{conflicts:0,deleted:a.deleted,errors:[],failed:[],inserted:a.inserted,received:r.received,...d.length>0?{warnings:d}:{}}},nf=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),It=e=>typeof e=="object"&&e!==null?e:{},oa=e=>{const t=It(e)._meta??{};if(t.sensitive===!0)return!0;const n=Array.isArray(t.members)?t.members:[],o=typeof t.shape=="object"&&t.shape!==null?Object.values(t.shape):[];return[t.inner,t.keyValidator,t.valueValidator,...n,...o].some(r=>typeof r=="object"&&r!==null&&oa(r))},hn=e=>typeof e.kind=="string"?e.kind:"unknown",of=(e,t)=>{let n=It(t),o=!1;hn(n)==="optional"&&(o=!0,n=It(n._meta?.inner));const r=hn(n),s=n._meta??{},a={kind:r,name:e,optional:o};if(oa(t)&&(a.sensitive=!0),r==="id"&&typeof s.tableName=="string"&&(a.table=s.tableName),r==="array"){const d=hn(It(s.inner));d!=="unknown"&&(a.element=d)}return a},rf=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>of(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),sf=Symbol.for("lunora.procedure.meta"),af="/_lunora/admin/functions",cf="/_lunora/admin/cron-jobs",df="/_lunora/admin/architecture",uf="/_lunora/admin/openapi",lf="/_lunora/admin/openrpc",hf="/_lunora/admin/global/tables",ff="/_lunora/admin/global/table",pf="/_lunora/admin/global/facet",hr=e=>{if(e===void 0||e==="")return;let t;try{t=Nt(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:r,operator:s,path:a,value:d}=o;return[{column:r,value:d,...s===void 0?{}:{operator:s},...a===void 0?{}:{path:a}}]});return n.length===0?void 0:n},mf=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then hand `createWorker` a loader for the generated module: `openApiSpec: () => import("./lunora/_generated/openapi").then((m) => m.openApiSpec)`. A worker that ships it as a Workers Static Asset reads `/_lunora/studio/openapi.json` through its assets binding; if that file is missing, deploy again with `lunora deploy`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),wf=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then hand `createWorker` a loader for the generated module: `openRpcSpec: () => import("./lunora/_generated/openrpc").then((m) => m.openRpcSpec)`. A worker that ships it as a Workers Static Asset reads `/_lunora/studio/openrpc.json` through its assets binding; if that file is missing, deploy again with `lunora deploy`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),fn={headers:{"cache-control":"no-store","content-type":"application/json"},status:200},pn=e=>{let t;return async()=>(t??=e?.().then(n=>(n===void 0&&(t=void 0),n),n=>{throw t=void 0,n}),t)},gf=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:r,requireAdminOption:s}=e,a=pn(n.architecture),d=pn(n.openApiSpec),c=pn(n.openRpcSpec),h=S=>{Y(S,"GET","Functions");const O=s(S,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),T=Object.entries(O).flatMap(([U,v])=>{if(v.visibility==="internal"||v.kind==="stream")return[];const x=v[sf];let W={};if(x==="unloaded")W={metaUnloaded:!0};else if(x!==void 0)try{W={meta:Re(x)}}catch{W={metaUnencodable:!0}}return[{args:[...v.argumentDescriptors??rf(v.args)],kind:v.kind,...W,path:U}]}).toSorted((U,v)=>U.path.localeCompare(v.path));return Response.json({functions:T},{headers:{"content-type":"application/json"},status:200})},p=S=>{Y(S,"GET","Cron-jobs");const O=s(S,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),T=Object.entries(O).flatMap(([U,v])=>v.map(x=>({args:x.args,cron:U,functionPath:x.functionPath,name:x.name,shardKey:x.shardKey,workflow:x.workflow}))).toSorted((U,v)=>U.name.localeCompare(v.name));return Response.json({jobs:T},{headers:{"content-type":"application/json"},status:200})},m=async S=>(Y(S,"GET","Architecture"),t(S),Response.json(await a()??nf,fn)),g=async S=>(Y(S,"GET","OpenAPI"),t(S),Response.json(await d()??mf,fn)),R=async S=>(Y(S,"GET","OpenRPC"),t(S),Response.json(await c()??wf,fn)),E=async S=>{Y(S,"GET","Global-tables");const O=s(S,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await O.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async S=>{Y(S,"GET","Global-table");const O=s(S,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(S.url),U=r(T,"table");if(U===void 0)throw new l("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await O.readTablePage({...o(S),filters:hr(r(T,"filters")),table:U});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},_=async S=>{Y(S,"GET","Global-facet");const O=s(S,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(S.url),U=r(T,"table"),v=r(T,"column");if(U===void 0||v===void 0)throw new l("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const x=r(T,"limit"),W=x===void 0?void 0:Number(x),X=await O.facetColumn({column:v,filters:hr(r(T,"filters")),limit:W!==void 0&&Number.isFinite(W)?W:void 0,table:U});return Response.json(X,{headers:{"content-type":"application/json"},status:200})};return{[cf]:p,[af]:h,[pf]:_,[ff]:b,[hf]:E,[df]:m,[uf]:g,[lf]:R}},yf="/_lunora/admin/kv/namespaces",_f="/_lunora/admin/kv/keys",ra="/_lunora/admin/kv/value",sa=32*1048576,fr=60,bf=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=E=>n(E,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),r=E=>Response.json(E,{headers:{"content-type":"application/json"},status:200}),s=(E,b)=>{const _=new URL(E.url),S=_.searchParams.get("namespace")??"",O=_.searchParams.get("key")??"";if(S==="")throw new l(`KV-value ${b} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(O==="")throw new l(`KV-value ${b} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:O,namespace:S}},a=async(E,b)=>{if(!(await E.listNamespaces()).some(S=>S.binding===b))throw new l(`Unknown KV namespace binding \`${b}\``,{code:"NOT_FOUND",status:404})},d=async E=>(Y(E,"GET","KV-namespaces"),r({namespaces:await o(E).listNamespaces()})),c=async E=>{Y(E,"GET","KV-keys");const b=o(E),_=new URL(E.url),S=_.searchParams.get("namespace")??"";if(S==="")throw new l("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const O=_.searchParams.get("prefix")??void 0,T=_.searchParams.get("cursor")??void 0,U=_.searchParams.get("limit"),v=U===null?void 0:Number.parseInt(U,10);if(v!==void 0&&(!Number.isInteger(v)||v<1))throw new l("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const x=v===void 0?void 0:Math.min(v,1e3);return await a(b,S),r(await b.listKeys({cursor:T,limit:x,namespace:S,prefix:O}))},g={DELETE:async E=>{const b=o(E),_=s(E,"DELETE");return await a(b,_.namespace),await b.deleteKey(_),r({deleted:!0})},GET:async E=>{const b=o(E),_=s(E,"GET");return await a(b,_.namespace),r(await b.getValue(_))},PUT:async E=>{const b=o(E),_=await t(E,sa);if(typeof _.namespace!="string"||_.namespace==="")throw new l("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof _.key!="string"||_.key==="")throw new l("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof _.value!="string")throw new l("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(_.expirationTtl!==void 0&&(typeof _.expirationTtl!="number"||!Number.isInteger(_.expirationTtl)||_.expirationTtl<fr))throw new l("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const S=Math.floor(Date.now()/1e3)+fr;if(_.expiration!==void 0&&(typeof _.expiration!="number"||!Number.isInteger(_.expiration)||_.expiration<S))throw new l("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await a(b,_.namespace),await b.putValue({expiration:_.expiration,expirationTtl:_.expirationTtl,key:_.key,metadata:_.metadata,namespace:_.namespace,value:_.value}),r({ok:!0})}},R=E=>{const b=g[E.method];if(!b)throw new l("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return b(E)};return{[yf]:d,[_f]:c,[ra]:R}},Sf="/_lunora/migrate",Ef="/_lunora/admin/pitr",Af="/_lunora/admin/rank",Tf="/_lunora/admin/rankpage",vf="/_lunora/admin/shard-registry/prune",Rf="/_lunora/admin/shard-traffic",Of=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),If=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Nf=async e=>{const n=await we(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Of.has(n.functionPath))throw new l("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},kf=async e=>{const n=await we(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new l("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new l("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new l("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new l("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Df=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new l('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Pf=e=>{if(typeof e.table!="string"||e.table.length===0)throw new l("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new l("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new l("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new l("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new l("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Uf=async e=>{const n=await we(e,"Rank page")??{};Pf(n);const o=Df(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Cf=async e=>{const n=await we(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Lf=async e=>{const n=await we(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new l("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Mf=async e=>{const n=await ae(e);if(typeof n.functionPath!="string"||!If.has(n.functionPath))throw new l("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new l("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},$f=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:r,resolveForwardContext:s,shardDO:a,shardedTables:d}=e,c=(b,_)=>{if(b.method!=="POST")throw new l(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(b))throw new l("Admin auth required",{code:"FORBIDDEN",status:403})},h=async(b,_)=>{c(b,"Migration");const S=await Nf(b),{headers:O}=await s(b,_),T=await r.orchestrateMigration(a,{args:S.args,defaultShardKey:t,functionPath:S.functionPath,headers:O,table:S.table});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},p=async(b,_)=>{c(b,"Rank");const S=await kf(b),{headers:O}=await s(b,_),T=await r.orchestrateRank(a,{headers:O,index:S.index,partitionKey:S.partitionKey,rowId:S.rowId,sortValues:S.sortValues,table:S.table});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},m=async(b,_)=>{c(b,"Rank page");const S=await Uf(b),{headers:O}=await s(b,_),T=await r.orchestrateRankPage(a,{...S,headers:O});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},g=async(b,_)=>{c(b,"Shard-traffic");const S=await Cf(b),{headers:O}=await s(b,_),T=await r.orchestrateShardTraffic(a,{headers:O,table:S.table});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},R=async(b,_)=>{c(b,"Shard-registry prune");const S=await Lf(b),O=d(),T=(S.tables??[]).filter(x=>!O.includes(x));if(T.length>0)throw new l(`Shard-registry prune names tables that are not \`.shardBy()\`: ${T.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:U}=await s(b,_),v=await Zi(r.registry,a,{dryRun:S.dryRun,headers:U,tables:S.tables??O});return Response.json(v,{status:v.failed.length>0?207:200})},E=async(b,_)=>{if(Y(b,"POST","PITR"),!o(b))throw new l("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const S=await Mf(b),{headers:O}=await s(b,_),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:S.args,functionPath:S.functionPath}),headers:O,method:"POST"});return n(a,S.shardKey??t,T)};return{[Sf]:h,[Ef]:E,[Af]:p,[Tf]:m,[vf]:R,[Rf]:g}},Bf=1,xf=0,Hf=32,jf=512,Kf=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Gf=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>jf)return;const n=t.split(",");if(!(n.length>Hf)){for(const o of n)if(!Kf.test(o.trim()))return;return t}},Ff=e=>{const t=Ni(e.headers.get("traceparent"));if(t===void 0)return;const n=Gf(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},pr=(e,t={})=>{const n=Ff(e),o=t.trustInbound===!0?n:void 0,r=Je(8),s=o?.traceId??Je(16),a=Ci(t.sampling,o===void 0?r:s),{rayId:d}=t,c=a.isTraced&&(o===void 0||o.sampled);return{decision:a,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:c,spanId:r,traceFlags:c?Bf:xf,traceId:s,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...d===void 0?{}:{rayId:d}}}},mr=(e,t)=>{t.traceparent=$r(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[xc]=e.rayId)},Wf=(e,t)=>{let n;return()=>{if(n===void 0){const o=Ui(e),r=t===void 0?void 0:t.cf;n=ki(Pi(o),Di(o,r))}return n}},Qf="/_lunora/admin/scheduled",Vf="/_lunora/admin/scheduled/status",zf="/_lunora/admin/scheduled/ws",Jf="/_lunora/admin/scheduled/cancel",Yf="/_lunora/admin/scheduled/dead",Xf="/_lunora/admin/scheduled/history",Zf="/_lunora/admin/scheduled/cron-runs",qf="/_lunora/admin/scheduled/job",ep="/_lunora/admin/scheduled/dead/retry",tp="/_lunora/admin/scheduled/dead/cancel",np="/_lunora/admin/scheduled/pool/release",op=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:r}=e,s=(p,m)=>g=>{if(g.method!=="GET")throw new l(`${m} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const R=new URL(g.url).searchParams.get("cursor"),E=R===null||R===""?"":`?cursor=${encodeURIComponent(R)}`;return o(g).fetch(new Request(`https://scheduler.internal${p}${E}`,{method:"GET"}))},a=p=>{if(p.method!=="GET")throw new l("Scheduled-job endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=o(p),g=new URL(p.url).searchParams.get("id");if(g===null||g==="")throw new l("Scheduled-job endpoint requires an `id`",{code:"BAD_REQUEST",status:400});return m.fetch(new Request(`https://scheduler.internal/get?id=${encodeURIComponent(g)}`,{method:"GET"}))},d=(p,m,g=m)=>async R=>{if(R.method!=="POST")throw new l(`${g} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const E=o(R),b=await we(R,m);if(typeof b?.id!="string"||b.id==="")throw new l(`${m} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return E.fetch(new Request(`https://scheduler.internal${p}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},c=async p=>{if(p.method!=="POST")throw new l("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=o(p),g=await we(p,"Scheduled pool-release");if(typeof g?.pool!="string"||g.pool==="")throw new l("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const R=typeof g.id=="string"&&g.id!==""?g.id:void 0;return m.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(R===void 0?{pool:g.pool}:{id:R,pool:g.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async p=>{if(p.headers.get("Upgrade")!=="websocket")throw new l("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(p))throw new l("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const m=n();return ve(m,r).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Jf]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Zf]:s("/cron/runs","Cron-runs"),[tp]:d("/dead/cancel","Scheduled dead-letter action"),[Yf]:s("/dead","Scheduled dead-letter"),[ep]:d("/dead/retry","Scheduled dead-letter action"),[Xf]:s("/history","Scheduled-history"),[qf]:a,[Qf]:s("/list","Scheduled-list"),[np]:c,[Vf]:s("/status","Scheduler-status"),[zf]:h}},wr=new WeakMap,aa=async(e,t)=>{const n=wr.get(e);if(n!==void 0)return n;const o=await e.fetch(new Request(new URL("/",t.url),{method:"HEAD"})),r=o.ok?o.headers.get("ETag")??void 0:void 0;return await o.body?.cancel(),r!==void 0&&wr.set(e,r),r},ia=e=>e.headers.get("Sec-Fetch-Mode")==="navigate"||(e.headers.get("Accept")??"").includes("text/html"),rp=async(e,t)=>{const n=await e.fetch(t);if(n.status>=300&&n.status<400&&n.status!==304)return n;if(!n.ok&&n.status!==304){await n.body?.cancel();return}const o=n.headers.get("ETag");if(!(o!==null&&new URL(t.url).pathname!=="/"&&o===await aa(e,t))||ia(t))return n;await n.body?.cancel()},sp=async(e,t)=>{if(!(t.method!=="GET"&&t.method!=="HEAD"))try{return await rp(e,t)}catch(n){console.error(`[lunora] spaAssets binding failed for ${t.method} ${new URL(t.url).pathname}:`,n);return}},ap=async(e,t)=>{if(!(t.method!=="GET"&&t.method!=="HEAD"||!ia(t)))try{const n=await e.fetch(t),o=n.ok||n.status===304?n.headers.get("ETag")??void 0:void 0;if(o!==void 0&&o===await aa(e,t))return n;await n.body?.cancel()}catch(n){console.error(`[lunora] spaAssets binding failed reading the shell for ${new URL(t.url).pathname}:`,n)}},ca="/_lunora/admin/sql-migrations",da=8*1048576,ip=e=>{if(!Array.isArray(e))throw new l("SQL migration request `files` must be an array",{code:"BAD_REQUEST",status:400});return e.map(t=>{const n=t;if(n===null||typeof n!="object"||typeof n.name!="string"||typeof n.sql!="string")throw new l("each SQL migration file needs a string `name` and a string `sql`",{code:"BAD_REQUEST",status:400});return{name:n.name,sql:n.sql}})},cp=e=>{const t=e.baselineThrough;if(t!==void 0&&typeof t!="string")throw new l("SQL migration `baselineThrough` must be a file name",{code:"BAD_REQUEST",status:400});return t},mn=(e,t)=>{if(e[t]!==void 0&&typeof e[t]!="boolean")throw new l(`SQL migration \`${t}\` must be a boolean`,{code:"BAD_REQUEST",status:400});return e[t]===!0},dp=e=>{if(e===null||typeof e!="object"&&typeof e!="function")return!1;const t=e;return typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function"},up=e=>typeof e=="object"&&e!==null&&Object.values(e).some(t=>dp(t)),lp=e=>{const t=async(n,o)=>{const r=ke(n,["POST"]);if(r)return r;if(!e.isAdmin(n))throw new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const s=e.applySqlMigrations;if(s===void 0)throw up(o)?new l("the worker has a D1 binding but no applySqlMigrations option, so the SQL files cannot run",{code:"MISCONFIGURED",status:500}):new l("SQL migrations run against the D1 global plane, and this worker has none to run them on",{code:"SQL_MIGRATIONS_NOT_CONFIGURED",status:400});e.assertAdmin(n);const a=await ae(n,da),d=cp(a),c=await s({additiveOnly:!e.isRootAdmin(n),baseline:mn(a,"baseline"),...d===void 0?{}:{baselineThrough:d},confirmDestructive:mn(a,"confirmDestructive"),dryRun:mn(a,"dryRun"),files:ip(a.files)});return Response.json(c,{headers:{"cache-control":"no-store"}})};return{[ca]:t}},hp="/_lunora/scheduled",ua="/_lunora/queue",la=16*1048576,fp=e=>{const{assertAdmin:t,dispatchScheduled:n,isPaused:o,queueHandler:r,queueHandlerHolds:s}=e,a=async(c,h,p)=>{if(t(c),c.method!=="POST")throw new l("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await we(c,"Scheduled tick"),g=typeof m?.cron=="string"?m.cron:"";if(g==="")throw new l("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},h,p),Response.json({cron:g,ok:!0})},d=async(c,h,p)=>{if(t(c),c.method!=="POST")throw new l("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new l("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await we(c,"Queue dispatch",la);if(!Array.isArray(m?.messages))throw new l("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof m.queue=="string"?m.queue:"",R=m.messages.filter(_=>typeof _=="object"&&_!==null&&typeof _.id=="string").map(_=>({...typeof _.attempts=="number"&&Number.isInteger(_.attempts)&&_.attempts>0?{attempts:_.attempts}:{},body:_.body,id:_.id})),E=await o();if(E&&!s)return Response.json({retry:R.map(_=>_.id),retryDelays:Object.fromEntries(R.map(_=>[_.id,On]))});const b=await r({messages:R,queue:g},h,p,E?{holdSeconds:On}:void 0);return Response.json({retry:b?.retry??[],...b?.retryDelays===void 0?{}:{retryDelays:b.retryDelays}})};return{[ua]:d,[hp]:a}},pp=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Nn={mtls:e=>pp(e,"tlsClientAuth","certVerified")==="SUCCESS"},mp=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Nn,e)?Nn[e]:void 0)??(()=>!1),wp=e=>typeof e=="string"&&Object.hasOwn(Nn,e),gp=e=>{const t=wp(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},yp="/_lunora/admin/vector/indexes",_p="/_lunora/admin/vector/query",bp=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async s=>{Y(s,"GET","Vector-indexes");const a=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await a.listIndexes()},{headers:{"content-type":"application/json"},status:200})},r=async s=>{Y(s,"POST","Vector-query");const a=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(a.queryIndex===void 0)throw new l("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const c=await t(s);if(typeof c.name!="string"||c.name==="")throw new l("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof c.text!="string"||c.text==="")throw new l("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(c.topK!==void 0&&(typeof c.topK!="number"||!Number.isInteger(c.topK)||c.topK<1))throw new l("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const h=await a.queryIndex({name:c.name,text:c.text,topK:c.topK});return Response.json(h,{headers:{"content-type":"application/json"},status:200})};return{[yp]:o,[_p]:r}},xt=async e=>await e===!0,ha=async(e,t,n,o=!1,r)=>{if(n.includes(Ft)||n.includes(Wt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!o)if(e.authorizeShard){if(!await xt(e.authorizeShard({functionPath:r,identity:t,shardKey:n})))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else n!==e.defaultShard&&e.guardUnauthenticatedShardAccess("shard")},Sp=async(e,t,n,o)=>{if(e.authorizeFanOut){if(!await xt(e.authorizeFanOut(o,t.table,n)))throw new l("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(n.startsWith("__lunora_relation__:"))throw new l("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new l("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});e.guardUnauthenticatedShardAccess("fan-out")},Ep=async(e,t,n)=>{if(e.assertAgentRunOnDefaultShard(t.functionPath,t.fanOut?void 0:t.shardKey??e.defaultShard),!(!t.fanOut&&t.functionPath.startsWith("__lunora_admin__:"))){if(t.fanOut){await Sp(e,t.fanOut,t.functionPath,n);return}await ha(e,n,t.shardKey??e.defaultShard,!1,t.functionPath)}},Ap="/_lunora/admin/workflows/instances",Tp="/_lunora/admin/workflows/instance",vp="/_lunora/admin/workflows/status",Rp="/_lunora/admin/workflows/create",Op="/_lunora/admin/workflows/event",Ip={complete:!0,errored:!0,paused:!0,queued:!0,rollingBack:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Np=e=>e!==null&&Object.hasOwn(Ip,e)?e:void 0,gr=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},wn=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new l(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},St=()=>{throw new l("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},kp=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(c,h,p)=>{Y(c,"GET","Workflows instances"),t(c);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=wn(p,"name"),R=Np(p.searchParams.get("status"));return Response.json(await m.listInstances({page:gr(p,"page"),perPage:gr(p,"perPage"),status:R,workflowName:g}))},r=async(c,h,p)=>{Y(c,"GET","Workflows instance"),t(c);const m=n(h);return m?Response.json(await m.getInstance({instanceId:wn(p,"id"),workflowName:wn(p,"name")})):St()},s=async(c,h)=>{Y(c,"POST","Workflows status"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new l("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:g}=m;if(g!=="pause"&&g!=="restart"&&g!=="resume"&&g!=="terminate")throw new l("Workflows status action must be one of: pause, restart, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:g,instanceId:m.id,workflowName:m.name}))},a=async(c,h)=>{Y(c,"POST","Workflows create"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows create");if(!Ro(m))throw new l("Workflows create body must be a JSON object",{code:"BAD_REQUEST",status:400});const g=m;if(typeof g.name!="string"||g.name==="")throw new l("Workflows create action requires a string `name`",{code:"BAD_REQUEST",status:400});if(g.id!==void 0&&(typeof g.id!="string"||g.id===""))throw new l("Workflows create action `id`, when given, must be a non-empty string",{code:"BAD_REQUEST",status:400});return Response.json(await p.createInstance({instanceId:g.id,params:g.params,workflowName:g.name}))},d=async(c,h)=>{Y(c,"POST","Workflows event"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows event");if(!Ro(m))throw new l("Workflows event body must be a JSON object",{code:"BAD_REQUEST",status:400});const g=m;if(typeof g.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new l("Workflows event action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});if(typeof g.type!="string"||g.type==="")throw new l("Workflows event action requires a string `type`",{code:"BAD_REQUEST",status:400});return Response.json(await p.sendEvent({eventType:g.type,instanceId:g.id,payload:g.payload,workflowName:g.name}))};return{[Tp]:r,[Ap]:o,[vp]:s,[Rp]:a,[Op]:d}},yr="lunora",kn="lunora.bearer.",Dp=/^[!-~]+$/u,Pp=e=>{if(e.startsWith(kn))try{const t=new TextDecoder("utf-8",{fatal:!0}).decode(Cn(e.slice(kn.length)));return Dp.test(t)?t:void 0}catch{return}},_r=e=>{const t=(e.headers.get("sec-websocket-protocol")??"").split(",").map(o=>o.trim()).filter(o=>o.length>0);let n;for(const o of t)n??=Pp(o);return{forwarded:t.filter(o=>!o.startsWith(kn)),token:n}},br=(e,t)=>{if(t.token===void 0||e.headers.has("authorization"))return e;const n=new Headers(e.headers);return n.set("authorization",`Bearer ${t.token}`),new Request(e,{headers:n})},Sr=(e,t)=>{const n=new Headers(e);return t.forwarded.length>0?n.set("sec-websocket-protocol",t.forwarded.join(", ")):n.delete("sec-websocket-protocol"),n},Er=(e,t)=>{const{webSocket:n}=t;if(t.status!==101||!n||!e.forwarded.includes(yr))return t;const o=new Headers(t.headers);o.set("sec-websocket-protocol",yr);const r={headers:o,status:101,webSocket:n};return new Response(null,r)},Up={[ra]:sa,[ua]:la,[ca]:da,[Ki]:$e},Cp="https://queue.lunora.internal",Ar=()=>({publish:()=>Promise.reject(new l("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),Lp=async(e,t)=>{const n=new l(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let o;try{o=await e.json()}catch{return n}const r=o?.error;return typeof r?.code!="string"||e.status<400?n:new l(typeof r.message=="string"?r.message:`ctx.live.publish to "${t}" was refused`,{code:r.code,status:e.status})},Dn="/_lunora/rpc",fa="/_lunora/rpc-batch",pa="/_lunora/ws",Mp=new Set([fa,Dn,pa]),it=(e,t,n)=>({resourceAttributes:Wf(e,t),...n===void 0?{}:{waitUntil:n}}),gn=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Tr=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),yn=(e,t)=>{const{method:n}=e,o=e.headers.get("user-agent")??void 0,r=jc(e.headers.get(Bc)),s=r===void 0?{}:{rayId:r};let a;try{a=t??new URL(e.url)}catch{return{method:n,...s,userAgent:o}}const d=a.port===""?void 0:Number(a.port);return{host:a.hostname,method:n,path:a.pathname,port:Number.isNaN(d)?void 0:d,...s,scheme:a.protocol.replace(":",""),userAgent:o}},vr="/_lunora/voice/",$p="/_lunora/admin/cron-jobs/run",Bp="/_lunora/admin/ws-token",xp="__lunora_admin__:verifyAdminToken",Hp="__lunora_admin__:listAdminTokens",ma="/_lunora/admin/",Ht="/_lunora/",jp="/_lunora/migrate",Kp="/_lunora/status",jt="/__lunora/advisor-procedures",Gp=e=>typeof e=="object"&&e!==null&&"fetch"in e&&typeof e.fetch=="function",Fp="__lunora_admin__",Wp=e=>e.startsWith(ma)||e===jp||e===jt,Et=e=>{if(qc(e))throw new l("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Rr=(e,t)=>{const n=e.headers.get(So);if(n===null)return;const o=Ii(n);if(o===void 0)throw new l(`malformed ${So} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new l("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Or="/api/auth",Qp="__lunora_admin__:recordAuthEvent",Vp="__lunora_admin__:recordImportAudit",zp="__lunora_admin__:listPushSubscriptions",Jp=["/sign-in","/sign-up","/callback"],Yp=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Jp.some(r=>o===r||o.startsWith(`${r}/`))},Ir=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},At=(e,t,n,o)=>{const r=Ur(n),s=r?n.code:"INTERNAL_SERVER_ERROR",a=r?n.status:500,{message:d,name:c,stack:h}=Si(n),p=Ei(n,{capped:!1});return{durationMs:t,error:{code:s,message:d,name:c,status:a,...h===void 0?{}:{stack:h},...p===void 0?{}:{internal:p}},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},wa=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ga=({identity:e})=>e!==null&&Ri(wa(e)),Nr=e=>{if(ga(e))throw new l("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},kr=e=>{if(!ga(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Dr=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Xp=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},je=new WeakMap,Zp=async(e,t,n,o,r=je.get(e),s=new URL(e.url).origin)=>{const a={"content-type":"application/json"},d=e.headers.get("authorization"),c=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),g=e.headers.get("x-lunora-client-seq"),R=e.headers.get("x-lunora-base-seq");d&&(a.authorization=d),c&&(a.cookie=c),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),g&&(a["x-lunora-client-seq"]=g),R&&(a["x-lunora-base-seq"]=R);const E=jr(e.headers,o);if(E&&(a["x-lunora-client-ip"]=E),a["x-lunora-origin"]=s,!n)return{claims:null,headers:a,identity:null,userId:null};const b=await n(e,t,r);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Oi(b.userId);const _=wa(b);_!==void 0&&(a["x-lunora-identity-exp"]=String(_));const{userId:S,...O}=b,T=Object.keys(O).length>0?O:null;return T&&(a["x-lunora-identity"]=bi(T)),{claims:T,headers:a,identity:b,userId:S}},qp=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),em=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new l("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new l("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new l("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!qp.has(n.kind))throw new l("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new l("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new l("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},_n=(e,t)=>e?.[t],tm=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},bn=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new l("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new l(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},nm=new Set(["args","functionPath","shardKey"]),om=(e,t)=>t===void 0&&Object.keys(e).every(n=>nm.has(n)),rm=async e=>{const t=await Hr(e);let n;try{n=JSON.parse(t)}catch{throw new l("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new l("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&xr(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new l("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const r=n,s=em(r.fanOut),a=r.args??{};if(s&&r.functionPath.startsWith("__lunora_relation__:")){const d=a.table;if(typeof d=="string"&&d!==s.table)throw new l("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});a.table=s.table}return{args:a,fanOut:s,forwardBody:om(n,s)?t:void 0,functionPath:r.functionPath,shardKey:r.shardKey}},Tt=new Map,sm=5e3,am=4096,im=async(e,t)=>{const n=Date.now(),o=Tt.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Tt.delete(t);let r=0;try{const s=await ve(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const a=await s.json();typeof a.relayCount=="number"&&a.relayCount>0&&(r=Math.floor(a.relayCount))}}catch{r=0}return kt(Tt,am),Tt.set(t,{expiresMs:n+sm,relayCount:r}),r},Sn=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ze=(e,t,n,o=JSON.stringify({args:t,functionPath:e}),r)=>new Request("https://shard.internal/rpc",{body:o,headers:n,method:"POST",...r===void 0?{}:{signal:r}}),cm=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ya=(e,t)=>{for(const n of cm){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},En=e=>e.headers.get("Upgrade")?.toLowerCase()==="websocket",Pn=(e,t)=>Jr(e.headers.get("authorization"))!==void 0&&!Dt(e,t),Pr=(e,t,n)=>{const o=new Headers(e.headers),r=[...o.keys()];for(const s of r)s.startsWith("x-lunora-")&&o.delete(s);return Pn(e,n)&&o.delete("authorization"),ya(o,t),o},vt=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:wd(t,n)},dm=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Ji(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return on(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return on(`queue:${e}`,!0);if(typeof n.connectionString=="string")return on(`hyperdrive:${e}`,!0)},um=e=>{for(const t of Object.keys(e??{})){const n=t.slice(t.indexOf(" ")+1);if(n===jt)throw new l(`route "${t}" is the framework's advisor endpoint, which carries its own admin gate — pick a different path.`,{code:"MISCONFIGURED",status:500});if(n.startsWith(Ht))throw new l(`route "${t}" is under the reserved ${Ht} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})}},lm=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new l("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},hm=e=>e.status===409&&e.headers.get(Cc)==="1",_a=e=>{lm(e);const t=mp(e.trustInboundTraceContext),n=gp(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",r=(i,u)=>{if(ed(i,u,o))throw new l(td,{code:"BAD_REQUEST",status:400})},s=e.queryCoordinator??qi({registry:ec(e.resolveTableSharding,o)}),a=Yi(e.resolveIdentity,e.identity),d=gt(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:gt(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([i,u])=>[i,gt(u,e.jurisdiction)]));let p=!1;const m=i=>{if(i===void 0||e.jurisdiction===void 0)return i;p||(p=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(i,u,f,w=e.shardRegion?.(u))=>ve(i,u,m(w)).fetch(f);let R;const E=()=>e.adminToken??R;let b;const _=i=>{const u=i??{};if(b??=Sn(i,e.shardDO),R!==void 0||e.adminToken!==void 0)return;const f=u.LUNORA_ADMIN_TOKEN;typeof f=="string"&&f.length>0&&(R=f)},S=new WeakMap,O=i=>Dt(i,E())||S.has(i),T=i=>{const u=S.get(i);return Dt(i,E())||u!==void 0&&u.tokenName===void 0},U=i=>{if(!(T(i)||(S.get(i)?.scopes??[]).includes("migrations")))throw O(i)?new l("this named admin token has no `migrations` scope, so it cannot run SQL migrations. Mint one with `lunora admin-token create <name> --scope migrations`.",{code:"ADMIN_SCOPE_REQUIRED",status:403}):new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},v=async(i,u)=>{const f=E();if(f===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const w=await g(d,o,ze(i,u,{authorization:`Bearer ${f}`,"content-type":"application/json"})),y=await w.json();if(!w.ok||y.error!==void 0)throw new l(y.error?.message??"admin token store unavailable",{code:y.error?.code??"SHARD_UNAVAILABLE",status:w.status});return y.result},x=e.adminRevocations===void 0?void 0:yd(gt(e.adminRevocations,e.jurisdiction),E),W=Nd({listNames:async()=>{const{tokens:i}=await v(Hp,{});return i.map(u=>u.name)},lookup:async(i,u)=>{try{const f=await v(xp,{digest:u,name:i});if(f.ok!==!0)return{live:!1,nameKnown:f.known!==!1};if(x===void 0||typeof f.createdAt!="number")throw new l("the admin revocation store is not available",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});if(await x.isRevoked(i,f.createdAt))return{live:!1,nameKnown:!0};const w=Array.isArray(f.scopes)?f.scopes.filter(Zr):[];return typeof f.expiresAt=="number"?{expiresAt:f.expiresAt,live:!0,scopes:w}:{live:!0,scopes:w}}catch(f){return console.error(`[lunora] admin token store lookup for "${i}" failed: ${Ur(f)?f.code:String(f)}`),{live:!1,nameKnown:!0,transient:!0}}}}),X=async i=>{if(S.has(i))return;const u=Pn(i,E())?await W.verify(i.headers.get("authorization")):void 0;if(u!==void 0){S.set(i,{scopes:u.scopes,tokenName:u.name});return}if(e.adminGate!==void 0)try{await xt(e.adminGate(i,je.get(i)))&&S.set(i,{})}catch{}},se=async(i,u,f,w={})=>{const y=await Zp(i,u,f,e.trustedClientIpHeader,w.executionContext,w.url?.origin);if(e.functions!==void 0&&(y.headers[Mr]=Lr),y.headers.authorization!==void 0&&Pn(i,E())){delete y.headers.authorization;const A=S.get(i)?.tokenName;if(A!==void 0){const D=i.headers.get("authorization"),P=async()=>{const k=E(),I=k===void 0?void 0:await W.verify(D);if(k===void 0||I?.name!==A)return;const N=Date.now();return yc(k,A,N,Math.min(Math.max(I.until,N+mc),I.expiresAt??Number.POSITIVE_INFINITY))},L=await P();L!==void 0&&(y.headers[Rt]=L),tc(y.headers,async({[Rt]:k,...I})=>{const N=await P();return N===void 0?I:{...I,[Rt]:N}})}}return y},Oe=async(i,u,f,w)=>Nr(await se(i,u,f,w)),Ie=async(i,u)=>{const f=await se(i,u,e.resolveIdentity),w=S.get(i);if(w!==void 0&&w.tokenName===void 0&&f.headers.authorization===void 0){const y=E();y!==void 0&&(f.headers.authorization=`Bearer ${y}`)}return f};let C=!1,V=!1;const G=()=>{V||(V=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},M=i=>{if(!e.allowUnauthenticatedShardAccess){const u=i==="fan-out"?"authorizeFanOut":"authorizeShard";throw new l(`${i} access is default-denied: configure \`${u}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${i} access (relying solely on per-row RLS).`,{code:i==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}C||(C=!0,console.warn([`[lunora] SECURITY: serving ${i} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},Q={assertAgentRunOnDefaultShard:r,get authorizeFanOut(){return e.authorizeFanOut===void 0?void 0:(i,u,f)=>e.authorizeFanOut?.(i,u,f)??!1},get authorizeShard(){return e.authorizeShard===void 0?void 0:i=>e.authorizeShard?.(i)??!1},defaultShard:o,guardUnauthenticatedShardAccess:M},j=(i,u,f=!1,w)=>ha(Q,i,u,f,w),q=$f({defaultShard:o,forwardToShard:g,isAdmin:O,queryCoordinator:s,resolveForwardContext:Ie,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(i=>e.resolveTableSharding?.(i)?.mode.kind==="shardBy")}),ee=async(i,u,f,w,y)=>{const{__lunoraLive:A,topic:D}=u,P=w?.shardKey??o;y==="trusted"?await j(null,P,!0):P!==o&&await j(y.identity,P);const L=await g(d,P,new Request(new URL($c,i),{body:JSON.stringify({data:Re(f??null),stream:A,topic:D}),headers:{"content-type":"application/json"},method:"POST"}));if(!L.ok)throw await Lp(L,D)},ie=async(i,u,f,w,y,A,D)=>{Et(i),r(i,f);const P=ud({forwardedIdentity:y,mutationId:w,scheduledFor:D,traceparent:A});return g(d,f,ze(i,u,P))},ce=async(i,u,f,w,y)=>{const A=fd(f.env,f.context?.exports,i,["create"]);if(A===void 0)throw new l(`${w} targets workflow "${i}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(Ec(u))throw new l(`${w} params ${Ac}`,{code:"BAD_REQUEST",status:400});try{await A.create(y===void 0?{params:u}:{id:y,params:u})}catch(D){if(!Mc(D))throw D}},te=(i,u,f)=>{const w=typeof f=="string"&&f.length>0?f:void 0;return e.agentWorkflows!==void 0&&!e.agentWorkflows.includes(i)?u:Yc(u,w)},Ne=async(i,u,f,w,y)=>{if(i.workflow){await ce(i.workflow,i.args??{},{context:f,env:u},`cron job "${i.name}"`);return}if(i.functionPath===void 0)throw new l(`cron job "${i.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const A=await ie(i.functionPath,i.args??{},i.shardKey??o,void 0,void 0,w,y);if(!A.ok)throw new l(`cron job "${i.name}" (${i.functionPath}) failed with shard status ${String(A.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=i=>{if(!O(i))throw new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ue=i=>{if(J(i),!T(i))throw new l("this admin endpoint requires the root admin token; named admin tokens cannot use it",{code:"ADMIN_ROOT_REQUIRED",status:403})},Ue=(i,u,f)=>{if(J(i),u===void 0)throw new l(f.message,{code:f.code,status:400});return u},nt=()=>c===void 0?void 0:ve(c,e.schedulerInstanceName??"default"),he=gh({assertAdmin:J,isAdmin:async i=>{await X(i);const u=i.headers.get("upgrade")?.toLowerCase()==="websocket";return O(i)||u&&await vt(i,E())},instanceStub:i=>c===void 0?void 0:ve(c,i),stub:nt}),eo=async()=>(await he.read()).paused,Sa=async(i,u,f,w,y,A,D)=>{const P=e.cronJobs?.[i];if(!P)return 0;const L=nt();for(const k of P){const I=await or(L,k.name);if(!I.skip)try{await Ne(k,u,f,A,D),await _t(L,k.name,I)}catch(N){w.push(y(N)),await _t(L,k.name,I,N)}}return P.length},Ea=async(i,u,f)=>{if(J(i),Y(i,"POST","cron-jobs run"),!e.cronJobs)throw new l("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const w=await ae(i),y=typeof w.name=="string"?w.name:"";if(y==="")throw new l("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const A=Object.values(e.cronJobs).flat().find(L=>L.name===y);if(!A)throw new l(`no cron job named "${y}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});const D=nt(),P=await or(D,A.name);if(P.skip&&P.reason==="paused")throw new l(`cron job "${y}" was not run: the deployment is paused`,{code:"DEPLOYMENT_PAUSED",status:503});if(P.skip)throw new l(`cron job "${y}" is already running`,{code:"CRON_JOB_IN_FLIGHT",status:409});try{await Ne(A,u,f)}catch(L){throw await _t(D,A.name,P,L),L}return await _t(D,A.name,P),Response.json({name:y,ran:!0},{status:200})},Aa=i=>{const{attempt:u,dedupKey:f,id:w,pool:y}=i;if(!c||typeof y!="string"||typeof u!="string"||typeof f!="string"||typeof w!="string")return()=>{};const A=typeof i.instanceName=="string"&&i.instanceName.length>0?i.instanceName:"default",D=JSON.stringify({attempt:u,dedupKey:f,id:w,pool:y}),P=setInterval(()=>{ve(c,A).fetch(new Request("https://scheduler.internal/pool/renew",{body:D,headers:{"content-type":"application/json"},method:"POST"})).then(async L=>{if(!L.ok)throw L.status<500&&clearInterval(P),new Error(`SchedulerDO /pool/renew answered ${String(L.status)}`);(await L.json()).renewed===!1&&clearInterval(P)}).catch(L=>{console.warn(`[lunora] pooled job "${w}" could not renew its slot in pool "${y}": ${L instanceof Error?L.message:String(L)}`)})},Uc/3);return()=>{clearInterval(P)}},to=async i=>{const u=typeof i.pool=="string"&&i.pool.length>0?i.pool:void 0;if(!u||!c||typeof i.id!="string")return;const f=typeof i.instanceName=="string"&&i.instanceName.length>0?i.instanceName:"default";try{await ve(c,f).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({attempt:i.attempt,dedupKey:i.dedupKey,id:i.id,pool:u}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Ta=async(i,u,f)=>{Y(i,"POST","Scheduler dispatch");const w=await Hr(i),y=u??{},A=typeof y.LUNORA_SCHEDULER_SECRET=="string"?y.LUNORA_SCHEDULER_SECRET:void 0,D=e.adminToken??(typeof y.LUNORA_ADMIN_TOKEN=="string"?y.LUNORA_ADMIN_TOKEN:void 0);if(!await id(i,w,{adminToken:D,schedulerSecret:A}))throw new l("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let L;try{L=JSON.parse(w)}catch{throw new l("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=L??{},I=k.args??{},N=typeof k.id=="string"&&k.id.length>0?k.id:void 0;if(k.dedupKey!==void 0&&!Pc(k.dedupKey))throw new l(`Scheduler dispatch: ${Dc}`,{code:"INVALID_INPUT",status:400});const B=k.dedupKey??N;if(typeof k.workflow=="string"&&k.workflow.length>0)return await ce(k.workflow,te(k.workflow,I,k.shardKey),{context:f,env:u},"scheduled workflow",B),await to(k),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new l("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const F=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:o,z=ld(i),K=typeof k.scheduledFor=="number"?k.scheduledFor:void 0,Z=Aa(k),fe=await ie(k.functionPath,I,F,B,z,i.headers.get("traceparent")??void 0,K).finally(Z);return hm(fe)||await to(k),fe},va=Xu({assertAdmin:J,getReader:()=>e.authAuditReader}),Ra=qu({assertAdmin:ue,getMove:()=>e.authJurisdictionMove}),Zt={assertAdmin:J,resolveToolHeaders:nc,defaultShardKey:()=>o,forwardToShard:async(i,u)=>{const f=await Ie(i,u),w=E();return S.get(i)?.tokenName!==void 0||(w===void 0?delete f.headers.authorization:f.headers.authorization=`Bearer ${w}`),{forward:ao,headers:f.headers}},getBinding:i=>e.aiChatBinding??_n(i,"AI"),optInLevel:i=>bc(e.aiOptInLevel??_n(i,"LUNORA_AI_OPT_IN")),approvalSecret:i=>{const u=_n(i,"LUNORA_AI_APPROVAL_SECRET");return typeof u=="string"?u:void 0}},Oa=$u(Zt),Ia=Bu(Zt),Na=xu(Zt),ka=async(i,u)=>{J(i);const f=e.notifySubscriptionStore;if(f===void 0)return Response.json({result:Re({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const w=u?.kind,y=u?.userId,A=u?.limit,D=w==="fcm"||w==="web-push"?w:void 0,P=typeof y=="string"&&y!==""?y:void 0,L=typeof A=="number"&&Number.isFinite(A)?Math.trunc(A):0,k=L>0?Math.min(L,1e3):1e3,N=(await f.list({kind:D,limit:k,userId:P})).filter(B=>D!==void 0&&B.kind!==D?!1:P===void 0||(B.userId??null)===P).map(({keys:B,token:F,...z})=>z);return Response.json({result:Re({subscriptions:N})},{headers:{"content-type":"application/json"},status:200})},Da=async(i,u,f)=>{if(u.fanOut)return;if(await(u.functionPath.startsWith(Fp)?ho(i,ma):Promise.resolve()),u.functionPath===Yu)return va(i,u.args??{});if(u.functionPath===zp)return ka(i,u.args);if(u.functionPath===ku){const y=u.args??{};return Oa(i,y.shardKey===void 0&&u.shardKey!==void 0?{...y,shardKey:u.shardKey}:y,f)}if(u.functionPath===Du)return Ia(i,u.args??{},f);const w=Na(i,u.functionPath,f);return w!==void 0?w:Ra(i,u.functionPath,u.args??{})},no=i=>async u=>{const f=await g(d,o,ze(Vp,u,i));if(!f.ok)throw new l(`the default shard answered HTTP ${String(f.status)}`,{code:"INTERNAL",status:500})},ht=(i,u)=>({assertAuthSectionAllowed:u,coordinator:s,headers:i,namespace:d,options:{...e,adminToken:E()},recordAudit:no(i)}),Pa=uh({applyGlobals:e.applyGlobals,assertAdmin:J,assertRootAdmin:ue,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:Ie,shardDO:d,exportSectionRows:i=>Hl(e,i),prepareExportRows:async(i,u)=>ps(e,s,i,u,d),importSession:{abort:async(i,u)=>Ot(ht(i,()=>{}),u),commit:async(i,u,f)=>na(ht(i,f),u),replace:async(i,u,f,w)=>tf(i,ht(u,w),f),stage:async(i,u,f,w,y)=>qs(i,ht(u,y),f,w)},streamingImport:async(i,u,f,w,y)=>Qh(i,{...e,adminToken:E()},s,u,d,f,w,async A=>no(await u())(A),y),syncGlobals:e.syncGlobals}),Ua=lp({applySqlMigrations:e.applySqlMigrations,assertAdmin:U,isAdmin:O,isRootAdmin:T}),qt=(i,u)=>{const f=i.searchParams.get(u);return f===null||f===""?void 0:f},en=i=>{const u=new URL(i.url),f=u.searchParams.get("limit"),w=u.searchParams.get("offset"),y=f===null?void 0:Number.parseInt(f,10),A=w===null?void 0:Number.parseInt(w,10);return{limit:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0,offset:A!==void 0&&Number.isFinite(A)&&A>=0?A:void 0}},oo=()=>{if(c===void 0)throw new l("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ca=op({checkWsAdmin:async i=>T(i)||vt(i,E()),requireSchedulerNamespace:oo,resolveSchedulerStub:i=>(J(i),ve(oo(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),La=kp({assertAdmin:J,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ma=ji({assertAdmin:J,assertRootAdmin:ue,parsePaging:en,queryParameter:qt,readBodyBytes:Mi,requireAdminOption:Ue,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),$a=fl({options:e,readJsonBody:ae,requireAdminOption:Ue}),Ba=bp({readJsonBody:ae,requireAdminOption:Ue,vectorIntrospector:e.vectorIntrospector}),xa=Ad({assertRootAdmin:ue,callStore:v,evict:W.evict,revocations:x,readJsonBody:ae}),Ha=bf({kvIntrospector:e.kvIntrospector,readJsonBody:ae,requireAdminOption:Ue}),ja=Xi({logArchive:e.logArchive,readJsonBody:ae,requireAdminOption:Ue}),Ka=gf({assertAdmin:J,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:en,queryParameter:qt,requireAdminOption:Ue}),Ga=i=>{const u=[],f=d??i?.SHARD;if(f!==void 0&&u.push(zi("durable-object:default",f,o)),e.health?.disableBindingProbes!==!0)for(const[w,y]of Object.entries(i??{})){const A=dm(w,y);A!==void 0&&u.push(A)}for(const w of e.health?.probes??[])u.push(w);return u},Fa=Vi({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:Ga}),Wa=(i,u)=>{const f=I=>"args"in I?{...I,args:Nt(I.args)}:I,w=e.schedulerInstanceName??"default",y=()=>ve(i,w),A=async(I,N)=>{const B=await y().fetch(new Request(`https://scheduler.internal${I}`,N));if(!B.ok)throw new l(`ctx.scheduler: SchedulerDO ${I} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},D=async(I,N)=>await A(I,{body:JSON.stringify(N),headers:{"content-type":"application/json"},method:"POST"}),P=I=>{const N=I;if(N==null)throw new l("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof N.binding=="string"&&N.binding.length>0)return{workflow:N.binding};if(typeof N.__lunoraRef=="string")return{functionPath:N.__lunoraRef};throw new l("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},L=async()=>(await Nc(async N=>A(N===void 0?"/list":`/list?cursor=${encodeURIComponent(N)}`,{method:"GET"}))).map(N=>f(N)),k=async(I,N,B={},F)=>{const z=P(N),K=F?.shardKey;if(K!==void 0&&K.length>0&&K!==o){const fe=typeof z.functionPath=="string"?z.functionPath:void 0;await j(u,K,!1,fe)}const{id:Z}=await D("/schedule",{args:_i("ctx.scheduler",String(z.functionPath??z.workflow),B),dedupKey:F?.dedupKey,scheduledFor:Math.ceil(I),retry:F?.retry,shardKey:F?.shardKey,...z});return Z};return{cancel:async I=>await D("/cancel",{id:I}),get:async I=>{const N=await A(`/get?id=${encodeURIComponent(I)}`,{method:"GET"});return N.record===void 0?null:f(N.record)},list:L,runAfter:async(I,N,B,F)=>{if(!Number.isFinite(I)||I<0)throw new l("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(Date.now()+I,N,B,F)},runAt:async(I,N,B,F)=>{if(!Number.isFinite(I))throw new l("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(I,N,B,F)}}},Qa=async(i,u,f)=>{const{claims:w,headers:y,identity:A,userId:D}=kr(await se(i,u,a)),P=it(u,i,N=>f.waitUntil?.(N)),L=N=>async(B,F={})=>{const z=B.__lunoraRef;if(typeof z!="string")throw new l("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Et(z),r(z,N),N!==o&&await j(A,N,!1,z);const K=await pt(i,z,Re(F),N,{...y,"x-lunora-system":"1"},P),Z=await K.json();if(Z.error)throw new l(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:K.status});return Nt(Z.result)},k=L(o),I=async(N,B,F={})=>{N!==void 0&&N!==o&&await j(A,N);const z=new Headers;for(const[K,Z]of Object.entries(F.headers??{}))K.toLowerCase().startsWith("x-lunora-")||z.set(K,Z);for(const[K,Z]of Object.entries(y))z.set(K,Z);return g(d,N??o,new Request(new URL(B,i.url),{headers:z,method:F.method??"GET",...F.body===void 0?{}:{body:F.body}}))};return{auth:{getIdentity:()=>Promise.resolve(w),userId:D},cache:f.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:I,forShard:N=>{const B=L(N);return{runAction:B,runMutation:B,runQuery:B}},live:e.liveStreams===!1?Ar():{publish:(N,B,F)=>ee(i.url,N,B,F,{identity:A})},runAction:k,runMutation:k,runQuery:k,...c===void 0?{}:{scheduler:Wa(c,A)},...f.waitUntil===void 0?{}:{waitUntil:f.waitUntil.bind(f)},...e.storage===void 0?{}:{storage:Sc(e.storage(u,new URL(i.url).origin))}}},tn=new WeakSet,Va=async(i,u,f)=>{const w=e.spaAssets===void 0||!f?void 0:await sp(e.spaAssets,i);return w===void 0?u:(await u.body?.cancel(),tn.add(w),w)},za=async(i,u,f,w)=>{const y=await e.authDiscoveryHandler?.(i);return y?(await Promise.all([u?.body?.cancel(),w?.body?.cancel()]),y):w!==void 0&&f?(await u?.body?.cancel(),tn.add(w),w):(await w?.body?.cancel(),Va(i,u??new Response("Not found",{status:404}),f))},Ja=async(i,u,f,w)=>{if(!e.httpRouter)return{response:void 0,unrouted:!0};let y=!1;const A=()=>{y=!0},D=await Qa(i,u,f);try{return{response:await e.httpRouter.fetch(i,{...u,__lunoraCtx:D,__lunoraShellFirst:w,__lunoraUnrouted:A},f),unrouted:y}}catch(P){return console.error("[lunora] httpRouter (SSR) handler threw:",P),{response:new Response("Internal Server Error",{status:500}),unrouted:!1}}},ro=new Set(Object.values(e.functions??{}).flatMap(i=>i.lifecycle==="socket"&&typeof i.socketPath=="string"?[i.socketPath]:[])),so=async(i,u,f)=>{if(!En(i))throw new l("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const w=Io(i,Ee);if(w)return w;const y=f.searchParams.get("shard")??o,A=_r(i),{headers:D,identity:P}=await se(br(i,A),u,a,{executionContext:je.get(i)}),L=T(i)||await vt(i,E());await j(P,y,L);const k=Sr(Pr(i,D,E()),A),I=Sn(u,e.shardDO);let N=y,B;if(I!==void 0){k.set("x-lunora-shard-binding",I);const F=ro.has(f.pathname)?0:await im(d,y);F>0&&(N=Vc(y,Math.floor(Math.random()*F)),B=No(i))}return Er(A,await g(d,N,new Request(i,{headers:k}),B))},Ya=async(i,u,f,w)=>{Y(i,"POST","ws reauth");const y=await ae(i);if(typeof y.connectionId!="string"||y.connectionId.length===0)throw new l("connectionId is required",{code:"BAD_REQUEST",status:400});const A=w.searchParams.get("shard")??o,D=O(i)||await vt(i,E()),P=await se(i,u,a,{executionContext:f??je.get(i),url:w}),{headers:L,identity:k}=D?kr(P):Nr(P);if(k===null&&!D)throw new l("re-authenticating a socket requires a credential",{code:"UNAUTHENTICATED",status:401});await j(k,A,D);const I=new Headers({"content-type":"application/json"});ya(I,L),D&&I.set("x-lunora-admin-reauth","1");const N=Sn(u,e.shardDO);return N!==void 0&&I.set("x-lunora-shard-binding",N),g(d,A,new Request(new URL(ko,w.origin),{body:JSON.stringify({connectionId:y.connectionId}),headers:I,method:"POST"}))},Xa=async(i,u,f,w)=>{Y(i,"POST","claims fingerprint");const{headers:y,identity:A}=await Oe(i,u,a,{executionContext:f??je.get(i),url:w});if(A===null)throw new l("a claims fingerprint requires a credential",{code:"UNAUTHENTICATED",status:401});return Response.json({claims:Ic(vi(y["x-lunora-userid"]),Ti(y["x-lunora-identity"]))},{headers:{"cache-control":"no-store"}})},Za=async(i,u,f)=>{if(h===void 0)return new Response("Not found",{status:404});if(!En(i))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=Io(i,Ee);if(w)return w;let y;try{y=decodeURIComponent(f.pathname.slice(vr.length))}catch{return new Response("Unknown voice agent",{status:404})}const A=Object.hasOwn(h,y)?h[y]:void 0;if(A===void 0)return new Response("Unknown voice agent",{status:404});const D=f.searchParams.get("threadKey");if(D===null||D.length===0)return new Response("Missing threadKey",{status:400});const P=_r(i),{headers:L,identity:k}=await se(br(i,P),u,a,{executionContext:je.get(i)});if(e.authorizeShard){if(!await xt(e.authorizeShard({identity:k,shardKey:D})))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else M("shard");const I=Sr(Pr(i,L,E()),P);return Er(P,await g(A,D,new Request(i,{headers:I})))},ft=(i,u)=>Ep(Q,i,u),qa=(i,u,f)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){G();return}if(e.functions[u]?.kind!=="query"||f.includes(Wt)||f.includes(Ft))return;const w=No(i);return w===void 0?void 0:{name:zc(f,w),region:w}},ao=async(i,u,f,w,y,A,D)=>{const P=qa(i,u,w);if(P!==void 0){const L={...y,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},k=Jc(i.headers.get("x-lunora-min-seq"));k!==void 0&&(L["x-lunora-min-seq"]=String(k));const I=await g(d,P.name,ze(u,f,L,A,D),P.region);if(I.status!==421)return I}return g(d,w,ze(u,f,y,A,D))},pt=async(i,u,f,w,y,A,D={})=>{const P=Date.now(),{observability:L,sampling:k}=e,I=yn(i,D.url),{decision:N,ignoredUpstream:B,trace:F}=pr(i,{...I.rayId===void 0?{}:{rayId:I.rayId},...k===void 0?{}:{sampling:k},trustInbound:t(i)});B&&n(i);const z={...y,[Ao]:N.keepErrors?"1":"0",[bo]:"1"};mr(F,z);try{const K=await ao(i,u,f,w,z,D.forwardBody),Z=yo(K.headers.get(_o));Ce(L,{...I,...Tr(F),durationMs:Date.now()-P,functionPath:u,ok:K.ok,shardKey:w,...K.ok?{}:{error:{...Z,code:Z?.code??"SHARD_ERROR",message:Z?.message??`shard returned ${String(K.status)}`,status:K.status}}},A,void 0,{isTraced:F.sampled,keepErrors:N.keepErrors});const fe=new Response(K.body,{headers:K.headers,status:K.status,statusText:K.statusText});return fe.headers.set("x-lunora-shard-key",w),fe.headers.delete(_o),fe}catch(K){throw Ce(L,{...I,...Tr(F),...At(u,Date.now()-P,K,{shardKey:w})},A,void 0,{isTraced:F.sampled,keepErrors:N.keepErrors}),K}},ei=i=>{if(i.fanOut&&i.shardKey)throw new l("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});i.fanOut||Et(i.functionPath)},ti=async(i,u,f,w)=>{Y(i,"POST","RPC");const y=await rm(i),A={forwardBody:y.forwardBody,url:w};tm(u,y),ei(y);const D=await Da(i,y,u);if(D!==void 0)return D;y.functionPath.startsWith("__lunora_admin__:")&&await X(i);const{headers:P,identity:L}=await Oe(i,u,a,A);Rr(i,L),await ft(y,L);const k=bn(y,e);{const I=Date.now(),{observability:N}=e,B=it(u,i,f&&(K=>f.waitUntil?.(K)));if(y.fanOut){const K=yn(i,w);try{const Z=await s.fanOut(d,{args:y.args??{},fanOut:y.fanOut,functionPath:y.functionPath,headers:P});return Ce(N,{durationMs:Date.now()-I,fanOut:{failed:Z.failed,shards:Z.ok+Z.failed,table:y.fanOut.table},functionPath:y.functionPath,...K,ok:!0},B),Response.json(Z,{headers:{"content-type":"application/json"},status:200})}catch(Z){throw Ce(N,{...At(y.functionPath,Date.now()-I,Z,{fanOut:{table:y.fanOut.table}}),...K},B),Z}}const F=y.shardKey??o,z=()=>pt(i,y.functionPath,y.args??{},F,P,B,A);return k&&e.x402Charge?e.x402Charge(i,{functionPath:y.functionPath,price:k.price},z,gn(f)):z()}},ni=async(i,u,f)=>{Y(i,"POST","RPC batch");const w=await ae(i),{calls:y}=w;if(!Array.isArray(y))throw new l("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:A,identity:D}=await Oe(i,u,a);Rr(i,D);const P=ml(y,o);for(const ne of P.values())for(const oe of ne)if(e.functions?.[oe.functionPath]?.x402)throw new l(`paid (\`.x402\`) function "${oe.functionPath}" cannot be called in a batch; dispatch it individually over ${Dn}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([ne,oe])=>oe.map(pe=>ft({args:pe.args,functionPath:pe.functionPath,shardKey:ne},D))));const{observability:L,sampling:k}=e,I=it(u,i,f&&(ne=>f.waitUntil?.(ne))),N=yn(i),{decision:B,ignoredUpstream:F,trace:z}=pr(i,{...N.rayId===void 0?{}:{rayId:N.rayId},...k===void 0?{}:{sampling:k},trustInbound:t(i)});F&&n(i);const K={isTraced:z.sampled,keepErrors:B.keepErrors},Z=ne=>{const oe={...A,"content-type":"application/json",[Ao]:B.keepErrors?"1":"0",[bo]:"1"};return mr({...z,spanId:ne},oe),oe},fe=ne=>({parentSpanId:ne,spanId:Je(8),traceFlags:z.traceFlags,traceId:z.traceId}),wt=[],nn=[],fo=(ne,oe,pe,Be)=>({body:{error:{code:pe,message:Be}},id:ne.id,status:oe}),po=(ne,oe,pe,Be,Ve)=>{for(const me of ne)Ce(L,Ve(me),I,void 0,K),wt.push(fo(me,oe,pe,Be))},wi=(ne,oe,pe,Be,Ve,me)=>{for(const ot of ne){const rt=Ve.get(ot.id),xe=rt?.status??me,He=xe<400,st=He?void 0:yo(rt?.errorDetail);Ce(L,{durationMs:Be,functionPath:ot.functionPath,...N,...fe(pe),ok:He,shardKey:oe,...He?{}:{error:{...st,code:st?.code??"SHARD_ERROR",message:st?.message??`batched call returned ${String(xe)}`,status:xe}}},I,void 0,K)}};await Promise.all([...P.entries()].map(async([ne,oe])=>{const pe=Je(8),Be=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:oe}),headers:new Headers(Z(pe)),method:"POST"}),Ve=Date.now();let me;try{me=await g(d,ne,Be)}catch(de){const at=Date.now()-Ve,{body:go}=yi(de,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});po(oe,502,go.code,go.message,gi=>({...At(gi.functionPath,at,de,{shardKey:ne}),...N,...fe(pe)}));return}const ot=Date.now()-Ve,rt=me.headers.get("x-d1-bookmark");rt&&nn.push(rt);let xe;try{xe=await me.json()}catch{const de=`shard batch returned a non-JSON response (${String(me.status)})`;po(oe,me.status,"SHARD_UNAVAILABLE",de,at=>({durationMs:ot,error:{code:"SHARD_UNAVAILABLE",message:de,status:me.status},functionPath:at.functionPath,...N,...fe(pe),ok:!1,shardKey:ne}));return}const He=Array.isArray(xe.results)?xe.results:[],st=new Set(He.map(de=>de.id));wi(oe,ne,pe,ot,new Map(He.map(de=>[de.id,de])),me.status),wt.push(...He.map(({errorDetail:de,...at})=>at));for(const de of oe)st.has(de.id)||wt.push(fo(de,me.status,"SHARD_UNAVAILABLE",`shard batch omitted result for call ${String(de.id)}`))}));const mo={"content-type":"application/json"},[wo]=nn;return nn.length===1&&wo!==void 0&&(mo["x-d1-bookmark"]=wo),Response.json({results:wt},{headers:mo,status:200})},oi=async(i,u,f,w={},y={})=>{try{const A=f.__lunoraRef;if(typeof A!="string")throw new l("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Et(A);const{headers:D,identity:P}=await Oe(i,u,a,{executionContext:y.context}),L={args:w,functionPath:A,shardKey:y.shardKey};await ft(L,P);const k=y.shardKey??o,I=it(u,i,y.waitUntil),N=()=>pt(i,A,w,k,D,I),B=bn(L,e);return B&&e.x402Charge?await e.x402Charge(i,{functionPath:A,price:B.price},N,gn(y.waitUntil?{waitUntil:y.waitUntil}:y.context)):await N()}catch(A){return To(A)}},io=async(i,u,f)=>{const{observability:w}=e,y=Date.now(),A=Je(16),D=Je(8),P=Dr(u),L=$r(A,D,!0);try{const k=await f(L);return Ce(w,{durationMs:Date.now()-y,functionPath:i,ok:!0,spanId:D,traceId:A},P),k}catch(k){throw Ce(w,{...At(i,Date.now()-y,k,{}),spanId:D,traceId:A},P),k}finally{Eo(w,P)}},ri=async(i,u,f,w,y,A)=>{if(await eo()){console.warn(`[lunora] scheduled("${u.cron}") skipped its crons handler: the deployment is paused.`);return}try{await i(u,f,w)}catch(D){y.push(A(D))}},co=async(i,u,f,w)=>{_(u);const y=[],A=I=>I instanceof Error?I:new Error(String(I)),D=e.crons?.[i.cron];D&&await ri(D,i,u,f,y,A);const P=await Sa(i.cron,u,f,y,A,w,i.scheduledTime),L=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===i.cron;if(L)try{await dl(e,s,d,E(),i)}catch(I){y.push(A(I))}if(!D&&P===0&&!L){const I=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${i.cron}") fired but no cron handler is registered for that expression. Registered: ${I.length===0?"(none)":I.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[k]=y;if(y.length===1&&k)throw k;if(y.length>1)throw new AggregateError(y,`scheduled("${i.cron}") had ${String(y.length)} failure(s)`)},si=fp({assertAdmin:J,dispatchScheduled:co,isPaused:eo,queueHandler:e.queueHandler,queueHandlerHolds:e.queueHandlerHolds===!0}),ai=async(i,u)=>{try{const f=i??{},w=e.adminToken??(typeof f.LUNORA_ADMIN_TOKEN=="string"?f.LUNORA_ADMIN_TOKEN:void 0);if(!w||w.length===0)return;await g(d,o,ze(Qp,{outcome:u},{authorization:`Bearer ${w}`,"content-type":"application/json"}))}catch{}},ii=async(i,u,f,w)=>{if(!e.authHandler)return;const y=e.authBasePath??Or,A=Ir(f.pathname,y)?$i(i):void 0;let D;try{D=await e.authHandler(A?.request??i)}catch(P){throw A?.overflowed()?new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(A?.overflowed())throw new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(D)return Yp(f.pathname,y)&&w.waitUntil?.(ai(u,D.status>=400?"fail":"ok")),D},ci=async({args:i,env:u,functionPath:f,request:w,shardKey:y,waitUntil:A})=>{xr(i,"REST");const D={functionPath:f,...y===void 0?{}:{shardKey:y}},{headers:P,identity:L}=await Oe(w,u,a);await ft(D,L);const k=y??o,I=it(u,w,A),N=()=>pt(w,f,i,k,P,I),B=bn(D,e);return B&&e.x402Charge?e.x402Charge(w,{functionPath:f,price:B.price},N,gn({waitUntil:A})):N()},uo=Li({functions:e.functions??{},invoke:ci,readJsonBody:ae,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),mt=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,di=new Set(e.liveStreamRoutes),ui=(i,u)=>{if(!mt)return;const f=`${i.method} ${u.pathname}`;if(!di.has(f))return mt[f]??mt[u.pathname]};um(mt);const li={[Kp]:i=>i.method!=="GET"&&i.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[jt]:async(i,u)=>{Y(i,"GET","Advisor procedures"),J(i);const f=typeof u=="object"&&u!==null?Reflect.get(u,"ADVISOR_COMPANION"):void 0;if(!Gp(f))return Response.json({error:"not found"},{headers:{"cache-control":"no-store"},status:404});const w=await f.fetch(new Request(new URL(jt,i.url),{method:"GET"})),y=new Headers(w.headers);return y.set("cache-control","no-store"),new Response(w.body,{headers:y,status:w.status,statusText:w.statusText})},[pa]:(i,u,f)=>so(i,u,f),[ko]:(i,u,f,w)=>Ya(i,u,w,f),[cd]:(i,u,f,w)=>Xa(i,u,w,f),[Dn]:(i,u,f,w)=>ti(i,u,w,f),[fa]:(i,u,f,w)=>ni(i,u,w),[Xc]:(i,u,f,w)=>Ta(i,u,w),[$p]:(i,u,f,w)=>Ea(i,u,w),[lh]:async i=>he.handleRoute(i),[Bp]:async i=>{Y(i,"POST","ws-token"),ue(i);const u=E();if(u===void 0)throw new l("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const f=await md(u);return Response.json(f,{headers:{"cache-control":"no-store"}})},...q,...Pa,...Ua,...Ca,...La,...Ma,...$a,...Ba,...Ha,...xa,...ja,...Ka,...Fa,...uo,...Ju({adminActor:i=>{const u=S.get(i)?.tokenName;return u===void 0?"admin:root":`admin:token:${u}`},assertAdmin:J,assertRootAdmin:ue,clientIp:i=>jr(i.headers,e.trustedClientIpHeader),getAuditWriter:()=>e.authAuditWriter,getAuthAdmin:()=>e.authAdmin,parsePaging:en,queryParameter:qt,readJsonBody:ae})};let Ee=Oo(e.security);const hi=i=>{const u=Ee.headers.enabled?Ee.headers.csp?.htmlValue:void 0;if(u===void 0||i.headers.has("content-security-policy"))return i;const f=new Headers(i.headers);return f.set("content-security-policy",u),new Response(i.body,{headers:f,status:i.status,statusText:i.statusText})};let lo=!1;const fi=i=>{lo||(lo=!0,Ee=Oo(e.security,i??{}))},ho=async(i,u)=>{Wp(u)&&await X(i)},pi=(i,u)=>{if(!(u.pathname.startsWith(Ht)||e.authHandler!==void 0&&Ir(u.pathname,e.authBasePath??Or))||i.method!=="POST"&&i.method!=="PUT")return;const w=Number(i.headers.get("content-length")??""),y=Up[u.pathname]??Br;if(Number.isFinite(w)&&w>y)throw new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},mi=async(i,u,f)=>{je.set(i,f);const w=new URL(i.url);pi(i,w);const y=await ii(i,u,w,f);if(y)return y;if(ro.has(w.pathname)&&i.method==="GET"&&En(i))return await he.refusal(i)??so(i,u,w);const A=ui(i,w);if(A)return A(i,u,f);const D=si[w.pathname];if(D)return D(i,u,f);const P=li[w.pathname];if(P)return await ho(i,w.pathname),(Mp.has(w.pathname)||Object.hasOwn(uo,w.pathname)?await he.refusal(i):void 0)??P(i,u,w,f);if(e.voiceAgents!==void 0&&w.pathname.startsWith(vr))return await he.refusal(i)??Za(i,u,w);if(w.pathname.startsWith(Ht))return new Response("Not found",{status:404});const L=e.spaAssets===void 0||!e.httpRouter?void 0:await ap(e.spaAssets,i),{response:k,unrouted:I}=await Ja(i,u,f,L!==void 0);return k&&k.status!==404?(await L?.body?.cancel(),k):za(i,k,I,L)};return{async fetch(i,u,f){e.passThroughOnException&&f.passThroughOnException?.(),fi(u),_(u);const w=oc(i,Ee);if(w)return w;const y=rc(i,Ee);if(y)return rn(y,i,Ee);try{const A=await mi(i,u,f);return rn(tn.has(A)?hi(A):A,i,Ee)}catch(A){return rn(To(A),i,Ee)}finally{Eo(e.observability,Dr(f))}},async queue(i,u,f){const w=await he.read();await io(`queue:${Xp(i)}`,f,async y=>{const A=e.liveStreams===!1?Ar():{publish:(D,P,L)=>ee(Cp,D,P,L,"trusted")};await e.queue?.(i,u,f,w.paused?{holdSeconds:On,traceparent:y}:{traceparent:y},A,e.queueFetchImpl)})},async scheduled(i,u,f){await io(`cron:${i.cron}`,f,async w=>{await co(i,u,f,w)})},serverQuery:oi}},fm=e=>_a(e),pm=e=>typeof e=="function"?{fetch:e}:e,mm=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,wm=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},ba=e=>{const t=new WeakMap;return n=>{if(n===null||typeof n!="object")return e(n);let o=t.get(n);return o===void 0&&(o=e(n),t.set(n,o)),o}},Km=(e,t)=>{const n=pm(e),{email:o,queue:r,scheduled:s}=wm(e),a=c=>{const p={...fm({...c,httpRouter:n})};return s!==void 0&&!mm(c)&&(p.scheduled=async(m,g,R)=>{await s(m,g,R)}),r!==void 0&&c.queue===void 0&&(p.queue=async(m,g,R)=>{await r(m,g,R)}),o!==void 0&&(p.email=async(m,g,R)=>{await o(m,g,R)}),p};if(typeof t!="function")return a(t);const d=ba(c=>a(t(c)));return{fetch:(c,h,p)=>d(h).fetch(c,h,p),queue:(c,h,p)=>d(h).queue?.(c,h,p)??Promise.resolve(),scheduled:(c,h,p)=>d(h).scheduled(c,h,p),serverQuery:(c,h,p,m,g)=>d(h).serverQuery(c,h,p,m,g),...o===void 0?{}:{email:(c,h,p)=>d(h).email?.(c,h,p)??Promise.resolve()}}},gm=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new l("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Gm=(e={})=>{const t=ba(n=>_a(gm(e,n)));return(n,o,r)=>t(o).fetch(n,o,r??Ai)},Fm=e=>e;export{Xo as COPY_AUTH_TO_JURISDICTION_OP,Yu as GET_AUTH_AUDIT_LOG_OP,Ai as NOOP_EXECUTION_CONTEXT,Zu as PURGE_UNPINNED_AUTH_OP,Vm as composeIdentityResolvers,fm as composeWorker,Gm as createLunoraHandler,_a as createWorker,Fm as defineRpcEnvelope,im as probeRelayCount,gm as resolveLunoraOptions,zm as routeIdentityResolvers,Km as withFrameworkWorker};
34
+ `},ku="__lunora_admin__:aiChat",Du="__lunora_admin__:aiAvailable",Pu=new Set(["__lunora_admin__:aiChartConfig","__lunora_admin__:aiCronExpression","__lunora_admin__:aiGenerateSql","__lunora_admin__:aiNameQuery","__lunora_admin__:aiTableFilter","__lunora_admin__:explainIssue"]),us=60,Qo=120,Uu=e=>{if(typeof e!="object"||e===null)return;const{columns:t,table:n}=e;if(!(typeof n!="string"||n===""||!Array.isArray(t)))return{columns:t.slice(0,as).filter(o=>typeof o=="string").map(o=>o.slice(0,Qo)),table:n.slice(0,Qo)}},Cu={describeTables:"__lunora_admin__:describeTables",readAdvisors:"__lunora_admin__:getAdvisories",readLogs:"__lunora_admin__:getLogs",readPolicies:"__lunora_admin__:rlsPolicies",runSql:"__lunora_admin__:runSql"},Lu="__lunora_admin__:listTables",Mu=(e,t,n,o,r)=>{const s=async(d,c,h)=>{const p=await e(o,d,c,t,await n(),void 0,h);if(!p.ok)return{error:`the tool call failed (${p.status.toString()})`};const m=await p.json();return Nt(m.result)},a=async d=>{if(r.length>0)return r.map(h=>h.table);const c=await s(Lu,{},d);return Array.isArray(c)?c.map(h=>h.name).filter(h=>typeof h=="string").slice(0,us):[]};return async(d,c)=>{const h=Cu[d.name];return d.name==="describeTables"?s(h,{tables:await a(c)},c):s(h,d.sql===void 0?{}:{sql:d.sql},c)}},$u=e=>async(n,o,r)=>{e.assertAdmin(n);const s=e.getBinding(r),a=o.schema,d=o.shardKey,c=typeof d=="string"&&d!==""?d:e.defaultShardKey();if(c.includes(Ft)||c.includes(Wt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const h={approval:o.approval,approvalSecret:e.approvalSecret(r),knowledge:o.knowledge,...typeof o.model=="string"?{model:o.model}:{},prompt:o.prompt,shardKey:c,transcript:o.transcript},p=Array.isArray(a)?a.slice(0,us).map(b=>Uu(b)).filter(b=>b!==void 0):[],m=e.optInLevel(r),g=s===void 0||m==="disabled"||e.forwardToShard===void 0?void 0:await(async()=>{const{forward:b,headers:O}=await e.forwardToShard(n,r);if(O.authorization===void 0&&O[Rt]===void 0)return;const{resolveToolHeaders:A}=e;return Mu(b,c,async()=>A===void 0?O:A(O),n,p)})(),R=new TextEncoder,E=new AbortController,S=()=>{E.abort()};n.signal.aborted?S():n.signal.addEventListener("abort",S,{once:!0});const _=new ReadableStream({cancel(){S()},async start(b){let O=!0;const A=(U,v)=>{if(O)try{b.enqueue(R.encode(Nu(U,v)))}catch{O=!1}};try{const U=await Ou(s,h,p,m,g,v=>{A(v)},E.signal);E.signal.aborted||A({result:Re(U)},"complete")}catch{A({code:"AI_CHAT_FAILED",message:"the assistant turn failed"},"error")}finally{n.signal.removeEventListener("abort",S);try{b.close()}catch{}}}});return new Response(_,{headers:Iu,status:200})},Bu=e=>(n,o,r)=>{e.assertAdmin(n);const s=e.optInLevel(r),a={available:s!=="disabled"&&e.getBinding(r)!==void 0,level:s};return Promise.resolve(Response.json({result:Re(a)},{headers:{"content-type":"application/json"},status:200}))},xu=e=>(t,n,o)=>{if(!(!Pu.has(n)||e.optInLevel(o)!=="disabled"))return e.assertAdmin(t),Response.json({result:Re({degraded:!0,reason:"no-ai-binding"})},{headers:{"content-type":"application/json"},status:200})},$="/_lunora/admin/auth",Hu=[["accountId","accountId"],["apiKeyId","keyId"],["invitationId","invitationId"],["memberId","memberId"],["organizationId","organizationId"],["ownerId","targetUserId"],["passkeyId","passkeyId"],["roleId","roleId"],["teamId","teamId"],["teamMemberId","teamMemberId"],["userId","targetUserId"]],ju=320,Ke=(e,t)=>{if(typeof e!="object"||e===null)return;const n=e[t];return typeof n=="string"&&n!==""?n:void 0},cn=e=>{const t=typeof e=="object"&&e!==null?e.role:void 0;if(Array.isArray(t)){const n=t.filter(o=>typeof o=="string"&&o!=="");return n.length===0?void 0:n.join(",")}return Ke(e,"role")},ls=e=>typeof e=="object"&&e!==null?e.data:void 0,Ku=(e,t,n)=>{const o=cn(ls(t))??cn(t);return o!==void 0||e.role===!0?cn(n)??o:void 0},Gu=(e,t)=>{const n=Ke(ls(e),"email")??Ke(e,"email");return n===void 0?void 0:Ke(t,"email")??n},Fu=512,Wu=e=>{const t={};for(const[n,o]of Hu){const r=Ke(e,n);r!==void 0&&(t[o]=r)}return t},Qu=(e,t,n,o,r,s)=>{const a={path:e,...Wu(r)},d={actorId:n,detail:a,event:t.event,ts:Date.now(),...o.ip===void 0?{}:{ip:o.ip},...o.userAgent===void 0?{}:{userAgent:o.userAgent.slice(0,Fu)}};if(s.outcome==="failure")return s.code!==void 0&&(a.code=s.code),{...d,outcome:"failure"};const{result:c}=s,h=t.event.startsWith("org-")&&a.organizationId===void 0?Ke(c,"organizationId"):void 0;h!==void 0&&(a.organizationId=h);const p=Ku(t,r,c);p!==void 0&&(a[t.roleKey??"role"]=p);const m=t.resultId===void 0?void 0:Ke(c,"id");t.resultId!==void 0&&m!==void 0&&(a[t.resultId]=m);const g=Gu(r,c);return{...d,outcome:"success",...g===void 0?{}:{targetEmail:g.slice(0,ju)}}},Vu=new Set(["banUser","cancelInvitation","capabilities","config","deleteApiKey","listAccounts","listApiKeys","listInvitations","listMembers","listOrganizations","listOrgRoles","listPasskeys","listSessions","listSignUpInvitations","listTeamMembers","listTeams","listUsers","revokeSignUpInvitation","revokeUserSession","revokeUserSessions"]),zu={ACCOUNT_NOT_FOUND:404,API_KEY_NOT_FOUND:404,API_KEY_STORAGE_UNSUPPORTED:409,INVITATION_NOT_FOUND:404,INVITER_REQUIRED:400,LAST_ORGANIZATION_OWNER:409,MEMBER_NOT_FOUND:404,MEMBERSHIP_CHANGED:409,ORG_ROLE_NOT_FOUND:404,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,ORGANIZATION_NOT_FOUND:404,PASSKEY_NOT_FOUND:404,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,SESSION_NOT_FOUND:404,SIGN_UP_INVITATION_NOT_FOUND:404,TEAM_MEMBER_NOT_FOUND:404,TEAM_NOT_FOUND:404,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},H=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new l(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},Le=(e,t)=>{const n=e(t);if(n===void 0)throw new l(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},hs=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ye=(e,t)=>typeof e[t]=="string"?e[t]:void 0,dn=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Vo=e=>{const t=hs(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new l("`role` is required",{code:"BAD_REQUEST",status:400});return t},zo=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,r]of Object.entries(t))Array.isArray(r)&&r.every(s=>typeof s=="string")&&(n[o]=r);return n},Ju={[`${$}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${$}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${$}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${$}/accounts`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listAccounts"},[`${$}/passkeys`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${$}/api-keys`]:{build:({query:e})=>({userId:Le(e,"userId")}),http:"GET",method:"listApiKeys"},[`${$}/api-keys/delete`]:{audit:{event:"api-key-delete"},build:({body:e})=>({apiKeyId:H(e,"apiKeyId")}),http:"POST",method:"deleteApiKey",returns:"void"},[`${$}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${$}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${$}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${$}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${$}/sign-up-invitations/create`]:{audit:{event:"sign-up-invitation-create",resultId:"invitationId"},build:({body:e})=>({email:H(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:ye(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${$}/sign-up-invitations/revoke`]:{audit:{event:"sign-up-invitation-revoke"},build:({body:e})=>({email:H(e,"email").trim().toLowerCase()}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${$}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${$}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${$}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:Le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${$}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:Le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${$}/users/create`]:{audit:{event:"admin-user-create",resultId:"targetUserId",role:!0},build:({body:e})=>({data:dn(e,"data"),email:H(e,"email"),name:H(e,"name"),password:ye(e,"password"),role:hs(e.role)}),http:"POST",method:"createUser"},[`${$}/users/update`]:{audit:{event:"admin-user-update"},build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new l("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:H(e,"userId")}},http:"POST",method:"updateUser"},[`${$}/users/role`]:{audit:{event:"admin-role-change",role:!0},build:({body:e})=>({role:Vo(e),userId:H(e,"userId")}),http:"POST",method:"setRole"},[`${$}/users/ban`]:{audit:{event:"admin-user-ban"},build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ye(e,"reason"),userId:H(e,"userId")}),http:"POST",method:"banUser"},[`${$}/users/unban`]:{audit:{event:"admin-user-unban"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"unbanUser"},[`${$}/users/password`]:{audit:{event:"admin-password-set"},build:({body:e})=>({newPassword:H(e,"newPassword"),userId:H(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${$}/users/remove`]:{audit:{event:"admin-user-remove"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${$}/users/impersonate`]:{audit:{event:"admin-impersonate-start"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"impersonateUser"},[`${$}/sessions/revoke`]:{audit:{event:"admin-session-revoke"},build:({body:e})=>({sessionId:H(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${$}/sessions/revoke-all`]:{audit:{event:"admin-session-revoke"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${$}/accounts/unlink`]:{audit:{event:"account-unlink"},build:({body:e})=>({accountId:H(e,"accountId"),userId:H(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${$}/two-factor/disable`]:{audit:{event:"mfa-disable"},build:({body:e})=>({userId:H(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${$}/passkeys/delete`]:{audit:{event:"passkey-remove"},build:({body:e})=>({passkeyId:H(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${$}/organizations/members/remove`]:{audit:{event:"org-member-remove"},build:({body:e})=>({memberId:H(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${$}/organizations/invitations/cancel`]:{audit:{event:"org-invitation-cancel"},build:({body:e})=>({invitationId:H(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${$}/organizations/create`]:{audit:{event:"org-create",resultId:"organizationId"},build:({body:e})=>({logo:ye(e,"logo"),metadata:dn(e,"metadata"),name:H(e,"name"),ownerId:ye(e,"ownerId"),slug:ye(e,"slug")}),http:"POST",method:"createOrganization"},[`${$}/organizations/update`]:{audit:{event:"org-update"},build:({body:e})=>({logo:ye(e,"logo"),metadata:dn(e,"metadata"),name:ye(e,"name"),organizationId:H(e,"organizationId"),slug:ye(e,"slug")}),http:"POST",method:"updateOrganization"},[`${$}/organizations/remove`]:{audit:{event:"org-delete"},build:({body:e})=>({organizationId:H(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${$}/organizations/members/add`]:{audit:{event:"org-member-add",resultId:"memberId",role:!0},build:({body:e})=>({organizationId:H(e,"organizationId"),role:ye(e,"role"),userId:H(e,"userId")}),http:"POST",method:"addMember"},[`${$}/organizations/members/invite`]:{audit:{event:"org-invitation-create",resultId:"invitationId",role:!0},build:({body:e})=>({email:H(e,"email"),inviterId:ye(e,"inviterId"),organizationId:H(e,"organizationId"),role:ye(e,"role")}),http:"POST",method:"inviteMember"},[`${$}/organizations/members/role`]:{audit:{event:"org-member-role-change",role:!0},build:({body:e})=>({memberId:H(e,"memberId"),role:Vo(e)}),http:"POST",method:"updateMemberRole"},[`${$}/organizations/teams/create`]:{audit:{event:"org-team-create",resultId:"teamId"},build:({body:e})=>({name:H(e,"name"),organizationId:H(e,"organizationId")}),http:"POST",method:"createTeam"},[`${$}/organizations/teams/update`]:{audit:{event:"org-team-update"},build:({body:e})=>({name:H(e,"name"),teamId:H(e,"teamId")}),http:"POST",method:"updateTeam"},[`${$}/organizations/teams/remove`]:{audit:{event:"org-team-remove"},build:({body:e})=>({teamId:H(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${$}/organizations/teams/members/add`]:{audit:{event:"org-team-member-add",resultId:"teamMemberId"},build:({body:e})=>({teamId:H(e,"teamId"),userId:H(e,"userId")}),http:"POST",method:"addTeamMember"},[`${$}/organizations/teams/members/remove`]:{audit:{event:"org-team-member-remove"},build:({body:e})=>({teamMemberId:H(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${$}/organizations/roles/create`]:{audit:{event:"org-role-change",resultId:"roleId",roleKey:"roleName"},build:({body:e})=>({organizationId:H(e,"organizationId"),permission:zo(e),role:H(e,"role")}),http:"POST",method:"createOrgRole"},[`${$}/organizations/roles/update`]:{audit:{event:"org-role-change"},build:({body:e})=>({permission:zo(e),roleId:H(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${$}/organizations/roles/remove`]:{audit:{event:"org-role-change"},build:({body:e})=>({roleId:H(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Yu=e=>{const t=async r=>{try{return await r()}catch(s){if(s instanceof l)throw s;const a=s,d=typeof a.code=="string"?a.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new l("auth admin operation failed",{code:d,status:zu[d]??500})}},n=async(r,s)=>{e.assertAdmin(r);const a=new URL(r.url),d=async(_,b)=>{const O=e.getAuditWriter();if(!(s.audit===void 0||O===void 0))try{await O.write(Qu(a.pathname,s.audit,e.adminActor(r),{ip:e.clientIp(r),userAgent:r.headers.get("user-agent")??void 0},_,b))}catch(A){console.error("[lunora] auth admin audit write failed:",A)}},c=(_,b)=>d(_,{code:b instanceof l?b.code:void 0,outcome:"failure"}),h=async()=>s.http==="POST"?e.readJsonBody(r):{},p=_=>s.build({body:_,paging:e.parsePaging(r),query:b=>e.queryParameter(a,b)}),m=async()=>{let _;try{_=await h()}catch{return}try{return p(_)}catch{return _}};if(!Vu.has(s.method))try{e.assertRootAdmin(r)}catch(_){const b=r.method===s.http?await m():void 0;throw await c(b,_),_}if(r.method!==s.http)throw new l(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const g=e.getAuthAdmin();if(g===void 0)throw new l("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const R=g[s.method];if(R===void 0)throw new l(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const E=p(await h());let S;try{S=await t(()=>R(E))}catch(_){throw await c(E,_),_}return await d(E,{outcome:"success",result:S}),Response.json(s.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[r,s]of Object.entries(Ju))o[r]=a=>n(a,s);return o},Xu="__lunora_admin__:getAuthAuditLog",Jo=e=>typeof e=="string"&&e!==""?e:void 0,Yo=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Zu=e=>async(n,o)=>{e.assertAdmin(n);const r=e.getReader();if(r===void 0)throw new l("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=Jo(o.actorId),a=Jo(o.event),d=Yo(o.sinceSeq),c=Yo(o.limit),h={...s===void 0?{}:{actorId:s},...a===void 0?{}:{event:a},...d===void 0?{}:{sinceSeq:d},...c===void 0?{}:{limit:c}};let p;try{p=await r.read(h)}catch(g){throw g instanceof l?g:(console.error("[lunora] auth audit read failed:",g),new l("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const m={entries:p};return Response.json({result:Re(m)},{headers:{"content-type":"application/json"},status:200})},Xo="__lunora_admin__:copyAuthToJurisdiction",qu="__lunora_admin__:purgeUnpinnedAuth",el=e=>async(t,n,o)=>{if(n!==Xo&&n!==qu)return;e.assertAdmin(t);const r=e.getMove();if(r===void 0)throw new l("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const s=n===Xo?await r.copy({force:o.force===!0}):await r.purge();return Response.json({result:Re(s)},{headers:{"content-type":"application/json"},status:200})},fs=e=>`${JSON.stringify({end:!0,rows:e})}
35
+ `,tl=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return;const t=e;if(!(t.end!==!0||t.table!==void 0))return typeof t.rows=="number"&&Number.isSafeInteger(t.rows)&&t.rows>=0?t.rows:Number.NaN},nl=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const r of t)e.resolveTableSharding?.(r)?.mode.kind==="global"?o.push(r):n.push(r);return{globalTables:o,shardLocalTables:n}},ol=async(e,t,n,o,r,s)=>{if(n!==void 0&&o.length===0)return[];const a=await e.orchestrateExport(r,{args:{tables:o},defaultShardKey:s,headers:t,tables:o}),d=a.shards.filter(c=>c.error);if(d.length>0){const c=d.map(h=>`${h.shardKey}: ${h.error?.message??"unknown error"}`).join("; ");throw new l(`export failed on ${String(d.length)} of ${String(a.shards.length)} shard(s) — ${c}`,{code:"EXPORT_SHARD_FAILED",status:502})}return a.shards.flatMap(c=>c.rows??[])},ps=async(e,t,n,o,r)=>{const s=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:a,shardLocalTables:d}=nl(e,s),c=await ol(t,n,s,d,r,e.defaultShardKey??"__root__"),h=e.exportGlobals,p=o===void 0||a.length>0;return(async function*(){yield*c,p&&h&&(yield*h({tables:a}))})()},rl=async(e,t,n,o,r,s)=>{for await(const a of await ps(e,t,n,o,s))r(a)},Zo=new TextEncoder,sl=1e3,ms=10,al=200,qo=8,ws="lunoraBackupCron",vn=24*1048576,er=e=>new l(`scheduled backup reached ${String(e)} bytes of NDJSON, past the ${String(vn)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507}),tr=e=>{const t=e.slice(0,ms).map(o=>Kr(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},il=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const r of e)n.set(r,o),o+=r.byteLength;return n},Bn=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const r=[];let s;for(let a=0;a<sl;a+=1){const d=await e.list({cursor:s,include:["customMetadata"],prefix:t});for(const c of d.objects)Bi(c.key)&&c.customMetadata?.[ws]===o&&r.push(c.key);if(!d.truncated||d.cursor===void 0)break;s=d.cursor}return{eligible:r.length,stale:r.toSorted((a,d)=>d.localeCompare(a)).slice(n)}},cl=async(e,t,n,o,r)=>{const{stale:s}=await Bn(e,t,n,o),a=new Set(r),d=s.filter(R=>a.has(R)),c=d.slice(0,al),h=s.length-c.length,p=r.length-d.length;if(c.length===0)return{deleted:[],failed:[],ignored:p,remaining:h};const m=[],g=[];for(let R=0;R<c.length;R+=qo){const E=await Promise.allSettled(c.slice(R,R+qo).map(async S=>(await e.delete(Kr(S)),await e.delete(S),S)));for(const[S,_]of E.entries())_.status==="fulfilled"?m.push(_.value):g.push(c[R+S])}return m.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(m.length)}: ${tr(m)}`),g.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(g.length)}: ${tr(g)}`),{deleted:m,failed:g,ignored:p,remaining:h}},dl=async e=>{const t=e.backupStore;if(!t)throw new l("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Ln(e.backupPrefix??Mn),o=e.backupCron,{eligible:r,stale:s}=o===void 0?{eligible:0,stale:[]}:await Bn(t,n,e.backupRetain,o);return{cron:o,eligible:r,keep:e.backupRetain??0,prefix:n,wouldDelete:s}},ul=async(e,t,n,o,r)=>{const s=e.backupStore;if(!s)throw new l("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.length===0)throw new l("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const a={authorization:`Bearer ${o}`,"content-type":"application/json"},d=e.backupTables;let c=0,h=0,p=[];await rl(e,t,a,d,A=>{const U=Zo.encode(`${JSON.stringify(A)}
36
+ `);if(c+=1,h+=U.byteLength,h>vn)throw er(h);p.push(U)},n);const g=Zo.encode(fs(c));if(h+=g.byteLength,h>vn)throw er(h);p.push(g);const R=Ln(e.backupPrefix??Mn),E=new Date(r.scheduledTime).toISOString(),S=xi(R,E),_=il(p,h);p=[];const b=et(await crypto.subtle.digest("SHA-256",_));await s.put(S,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:b});const O={bytes:h,createdAt:E,cron:r.cron,file:S,id:E,rows:c,scheduledTime:r.scheduledTime,sha256:b,...d?{tables:d.join(",")}:{}};await s.put(Hi(S),`${JSON.stringify(O,void 0,2)}
37
+ `,{customMetadata:{[ws]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:A}=await Bn(s,R,e.backupRetain,r.cron);if(A.length>0){const U=A.slice(0,ms),v=A.length-U.length;console.info(`[lunora] backup retention: ${String(A.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${U.join(", ")}${v>0?` (+${String(v)} more)`:""}`)}}catch(A){console.warn(`[lunora] backup ${S} was written, but the retention report failed:`,A)}},ll=async(e,t)=>{const n=e.backupStore;if(!n)throw new l("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,r=e.backupRetain;if(o===void 0||r===void 0||!Number.isInteger(r)||r<=0)throw new l("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return cl(n,Ln(e.backupPrefix??Mn),r,o,t)},hl="/_lunora/admin/backup/retention",fl="/_lunora/admin/backup/prune",pl=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,r=(d,c)=>{o(d,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${c} requires a \`backupStore\` on the worker`})},s=async d=>(Y(d,"GET","Backup-retention"),r(d,"retention preview"),Response.json(await dl(t),{headers:{"cache-control":"no-store"}})),a=async d=>{Y(d,"POST","Backup-prune"),r(d,"prune");const{confirm:c}=await n(d);if(!Array.isArray(c)||c.some(h=>typeof h!="string"))throw new l("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await ll(t,c),{headers:{"cache-control":"no-store"}})};return{[fl]:a,[hl]:s}},nr=500,ml=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new l("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new l("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new l("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new l("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new l("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},wl=(e,t)=>{if(e.length>nr)throw new l(`RPC batch exceeds the ${String(nr)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[r,s]of e.entries()){const{entry:a,shardKey:d}=ml(s,r,t);if(o.has(a.id))throw new l(`batch call id ${String(a.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(a.id);const c=n.get(d)??[];c.push(a),n.set(d,c)}return n},gl=3e5,Lt=e=>e instanceof Error?e.message:JSON.stringify(e),xn=async(e,t,n)=>{const o=await e.fetch(new Request(`https://scheduler.internal${t}`,{body:JSON.stringify(n),headers:{"content-type":"application/json"},method:"POST"}));if(!o.ok)throw new Error(`SchedulerDO ${t} answered ${String(o.status)}`);return o.json()},yl=(e,t,n)=>{const o=setInterval(()=>{xn(e,"/cron/renew",{name:t,runId:n}).then(r=>{r.renewed===!1&&clearInterval(o)}).catch(r=>{console.warn(`[lunora] cron job "${t}" could not renew its lease: ${Lt(r)}`)})},gl);return o},or=async(e,t)=>{if(e===void 0)return{skip:!1};try{const n=await xn(e,"/cron/begin",{name:t});if(n.acquired===!1)return{reason:typeof n.reason=="string"?n.reason:"in-flight",skip:!0};const o=typeof n.runId=="string"?n.runId:void 0;return o===void 0?{skip:!1}:{renewal:yl(e,t,o),runId:o,skip:!1}}catch(n){return console.warn(`[lunora] cron job "${t}" runs without its overlap guard: ${Lt(n)}`),{skip:!1}}},_t=async(e,t,n,o)=>{if(!(e===void 0||n.skip||n.runId===void 0)){clearInterval(n.renewal);try{await xn(e,"/cron/end",{name:t,runId:n.runId,...o===void 0?{status:"succeeded"}:{error:Lt(o),status:"failed"}})}catch(r){console.warn(`[lunora] cron job "${t}" ran but its outcome was not recorded: ${Lt(r)}`)}}},Mt="_lunora/restore/",_l=1440*60*1e3,gs=9999999999999,bl=/^[\da-f]{64}\/(\d{13})\//u,Sl=5*1024*1024,El=1e4,Al=1e3,Xe=12,rr=new Map,ys=async e=>{let t=rr.get(e);return t===void 0&&(t=(async()=>{const n=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({hash:"SHA-256",info:new TextEncoder().encode("restore-staging"),name:"HKDF",salt:new TextEncoder().encode("lunora")},n,{length:256,name:"AES-GCM"},!1,["encrypt","decrypt"])})(),rr.set(e,t)),t},Hn=async(e,t,n)=>{const o=crypto.getRandomValues(new Uint8Array(Xe)),r=await crypto.subtle.encrypt({additionalData:new TextEncoder().encode(t),iv:o,name:"AES-GCM"},await ys(e),n),s=new Uint8Array(Xe+r.byteLength);return s.set(o),s.set(new Uint8Array(r),Xe),s.buffer},_s=async(e,t,n)=>{if(!(n.byteLength<=Xe))try{const o=await crypto.subtle.decrypt({additionalData:new TextEncoder().encode(t),iv:n.subarray(0,Xe),name:"AES-GCM"},await ys(e),n.subarray(Xe));return new Uint8Array(o)}catch{return}},Qe=e=>{const{adminToken:t,storageDelete:n,storageDownload:o,storageList:r,storageUpload:s}=e;return n&&o&&r&&s&&t?{delete:n,download:o,list:r,secret:t,upload:s}:void 0},Qt=e=>{const{data:t,last:n,offset:o,sha256:r,size:s}=e,a=n!==!0||typeof s=="number"&&Number.isInteger(s)&&s>=0;if(typeof t!="string"||typeof o!="number"||!Number.isInteger(o)||o<0||!a)return;let d;try{d=Cr(t)}catch{return}return{bytes:d,lastSize:n===!0?s:void 0,offset:o,...typeof r=="string"?{sha256:r}:{}}},jn=async function*(t,n,o){let r,s=!0;for(;s;){const a=await t(n,{...o,cursor:r,limit:Al});yield*a.objects,r=a.cursor,s=r!==void 0&&(a.truncated??!0)}},bs=async function*(t,n){let o=new Uint8Array(n),r=0;for await(const s of t)for(let a=0;a<s.byteLength;){const d=Math.min(n-r,s.byteLength-a);o.set(s.subarray(a,a+d),r),r+=d,a+=d,r===n&&(yield o,o=new Uint8Array(n),r=0)}r>0&&(yield o.subarray(0,r))},Ss=async e=>`${Mt}${et(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}/`,Tl=(e,t)=>`${e}${String(gs-t).padStart(13,"0")}/`,Es=async(e,t,n)=>{const{objects:o}=await e.list(t,{...n,limit:1}),r=o[0]?.key,s=r?.startsWith(t)?r.indexOf("/",t.length):-1;return r===void 0||s===-1?void 0:r.slice(0,s+1)},Kn=(e,t)=>`${e}${String(t).padStart(16,"0")}`,vl=async(e,t,n,o)=>{const r=o.offset===0?Tl(t,Date.now()):await Es(e,t,n);if(r===void 0)return!1;const s=Kn(r,o.offset);return await e.upload(s,await Hn(e.secret,s,o.bytes),n),!0},Rl=async(e,t,n)=>{const o=[];for await(const r of jn(e.list,t,n))o.push(r.key);await Promise.all(o.map(async r=>e.delete(r,n)))},Vt=async function*(t,n,o,r,s){const a=h=>new l(h,{code:`${s}_RESTORE_INCOMPLETE`}),d=Gr.create();let c=0;if(r.offset+r.bytes.byteLength!==r.lastSize)throw a(`chunks add up to ${String(r.offset+r.bytes.byteLength)} of ${String(r.lastSize)} bytes`);for(;c<r.offset;){const h=Kn(o,c),p=await t.download(h,n);if(!p?.body)throw a(`the chunk at byte ${String(c)} never arrived`);const m=await _s(t.secret,h,new Uint8Array(await new Response(p.body).arrayBuffer()));if(m===void 0)throw a(`the chunk at byte ${String(c)} was not staged by this deployment`);if(m.byteLength===0||c+m.byteLength>r.offset)throw a(`the chunk at byte ${String(c)} overlaps the last chunk`);d.update(m),yield m,c+=m.byteLength}if(d.update(r.bytes),yield r.bytes,r.sha256!==void 0&&et(d.digest())!==r.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${r.sha256}`,{code:`${s}_SHA256_MISMATCH`})},Gn=(e,t)=>{if(e.bytes.byteLength!==e.lastSize)throw new l(`the record holds ${String(e.bytes.byteLength)} of ${String(e.lastSize)} bytes`,{code:`${t}_RESTORE_INCOMPLETE`});if(e.sha256!==void 0&&et(Gr(e.bytes))!==e.sha256.toLowerCase())throw new l(`the restored bytes do not match the exported sha256 ${e.sha256}`,{code:`${t}_SHA256_MISMATCH`})},zt=async(e,t)=>{const n=new Uint8Array(t);let o=0;for await(const r of e)n.set(r,o),o+=r.byteLength;return n},As=async(e,t,n)=>{const o=[];try{for await(const r of bs(t,Math.max(Sl,Math.ceil(n/El))))o.push(await e.uploadPart(o.length+1,r));await e.complete(o)}catch(r){throw await e.abort().catch(()=>{}),r}},Ol=e=>{const t=bl.exec(e.slice(Mt.length));return t?.[1]===void 0?void 0:gs-Number(t[1])},Il=async(e,t,n)=>{let o=0;for(const r of t){const s=r===void 0?{}:{bucket:r},a=[];for await(const{key:d}of jn(e.list,Mt,s)){const c=Ol(d);d.startsWith(Mt)&&(c===void 0||n-c>_l)&&a.push(d)}await Promise.all(a.map(async d=>e.delete(d,s))),o+=a.length}return o},Rn=2,Fe="$lunora",_e="$auth",be="$kv",Se="$storage",Nl=new Set([_e,Fe,be,Se]),sr=["auth","kv","storage"],kl=["kv","storage"],Ye=512*1024,$t=25*1024*1024,Ts="_lunora/",vs=60,Dl=1e3,ct=e=>e.storageBuckets!==void 0&&e.storageBuckets.length>0?e.storageBuckets:[void 0],Rs=(e,t)=>{const{bucket:n}=t.where;if(!(n===void 0||ct(e).includes(n)))return`${t.key} is in the bucket "${n}", which this worker does not declare`},Pl=(e,t)=>t.filter(n=>{switch(n){case"auth":return e.authData!==void 0;case"kv":return e.kvIntrospector!==void 0;case"storage":return e.storageList!==void 0&&e.storageDownload!==void 0;default:return!1}}),Ul=async function*(t){const n=t.getReader();let o=!1;try{for(;;){const{done:r,value:s}=await n.read();if(r){o=!0;return}yield s}}finally{o||await n.cancel().catch(()=>{})}},Cl=async function*(t){let n;for await(const o of t)n&&(yield{bytes:n,last:!1}),n=o;yield{bytes:n??new Uint8Array(0),last:!0}},Os=async function*(t,n){let o;do{const r=await t.listKeys({cursor:o,limit:Dl,namespace:n});yield*r.keys,o=r.listComplete?void 0:r.cursor}while(o!==void 0)},Ll=async function*(t,n,o){const r=Cr(n);if(r.byteLength<=Ye){yield{doc:{...t,value:n,...o},table:be};return}const s=et(await crypto.subtle.digest("SHA-256",r));for(let a=0;a<r.byteLength;a+=Ye){const d=Kt(r.subarray(a,a+Ye)),c=a+Ye>=r.byteLength?{last:!0,sha256:s,size:r.byteLength,...o}:{};yield{doc:{...t,data:d,offset:a,...c},table:be}}},Ml=async function*(t){for(const{binding:n}of await t.listNamespaces())for await(const o of Os(t,n)){const{metadata:r,value:s}=await t.getValue({encoding:"base64",key:o.name,namespace:n});s!==null&&(yield*Ll({key:o.name,namespace:n},s,{...r==null?{}:{metadata:r},...o.expiration===void 0?{}:{expiration:o.expiration}}))}},Is=async function*(t,n){for await(const o of jn(t,void 0,n===void 0?{}:{bucket:n}))o.key.startsWith(Ts)||(yield o)},$l=(e,t,n)=>({last:!0,size:n,...t===void 0?{}:{contentType:t},...e.customMetadata===void 0||Object.keys(e.customMetadata).length===0?{}:{customMetadata:e.customMetadata},...e.sha256===void 0?{}:{sha256:e.sha256}}),Bl=async function*(t,n,o){const r=n===void 0?{key:t.key}:{bucket:n,key:t.key},s=t.httpMetadata?.contentType??o.httpMetadata?.contentType;let a=0;for await(const{bytes:d,last:c}of Cl(bs(Ul(o.body),Ye))){const h=c?$l(t,s,a+d.byteLength):{};yield{doc:{...r,data:Kt(d),offset:a,...h},table:Se},a+=d.byteLength}},xl=async function*(t,n,o){for(const r of o)for await(const s of Is(t,r)){const a=await n(s.key,{bucket:r});a?.body&&(yield*Bl(s,r,{body:a.body,httpMetadata:a.httpMetadata}))}},Hl=async function*(t){for await(const n of t.exportRows())yield{doc:{row:n.doc,table:n.table},table:_e}},jl=(e,t)=>{const n=Pl(e,t),{authData:o,kvIntrospector:r,storageDownload:s,storageList:a}=e;return{header:n.length===0?void 0:{doc:{format:Rn,sections:n},table:Fe},rows:(async function*(){o&&n.includes("auth")&&(yield*Hl(o)),r&&n.includes("kv")&&(yield*Ml(r)),a&&s&&n.includes("storage")&&(yield*xl(a,s,ct(e)))})()}},Kl=e=>{const{format:t}=e;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>Rn)throw new l(`Import format ${JSON.stringify(t)} is not supported (this runtime reads formats 1-${String(Rn)})`,{code:"IMPORT_FORMAT_UNSUPPORTED",status:400})},tt=(e,t,n=1)=>{e.inserted[t]=(e.inserted[t]??0)+n},Fn=e=>{e.conflicts+=1},re=(e,t,n,o)=>{e.errors.push({code:n,line:t.line,message:o,table:t.table})},Wn=e=>e instanceof Error?e.message:String(e),Qn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gl=async(e,t,n)=>{const o=[];for(const s of t){const{row:a,table:d}=s.doc;typeof d!="string"||!Qn(a)?re(n,s,"BAD_ROW","an `$auth` record needs a string `table` and an object `row`"):e.authData?o.push({doc:a,row:s,table:d}):re(n,s,"AUTH_NOT_CONFIGURED","row targets an auth table but this worker has no auth data port (`authData`)")}if(o.length===0||!e.authData)return;const r=await e.authData.importRows(o.map(({doc:s,table:a})=>({doc:s,table:a})));tt(n,_e,r.inserted),n.conflicts+=r.conflicts;for(const s of r.errors){const a=o[s.index]?.row;n.errors.push({code:"AUTH_IMPORT_FAILED",line:a?.line??0,message:s.message,table:_e})}},Ns=e=>e instanceof l&&(e.code.endsWith("_RESTORE_INCOMPLETE")||e.code.endsWith("_SHA256_MISMATCH")),ks=async(e,t,n,o,r)=>{await vl(e,n.root,n.where,o)?tt(r,t.table):re(r,t,`${n.kind}_RESTORE_INCOMPLETE`,`the chunk at byte 0 never arrived, so the one at byte ${String(o.offset)} has nothing to join`)},Ds=async(e,t,n,o,r,s)=>{const a=o.offset===0?void 0:await Es(e,n.root,n.where);if(o.offset>0&&a===void 0){re(r,t,`${n.kind}_RESTORE_INCOMPLETE`,"the chunk at byte 0 never arrived");return}try{await s(Vt(e,n.where,a??"",o,n.kind))}catch(d){if(!Ns(d))throw d;re(r,t,d.code,d.message)}a!==void 0&&await Rl(e,a,n.where)},Ps=async(e,t,n)=>{const{expiration:o,key:r,kv:s,metadata:a,namespace:d}=e,c=await s.getValue({key:r,namespace:d}),h=o!==void 0&&o<Math.floor(Date.now()/1e3)+vs;if(c.value!==null||h){Fn(n);return}await s.putValue({encoding:"base64",key:r,namespace:d,value:t,...o===void 0?{}:{expiration:o},...a===void 0?{}:{metadata:a}}),tt(n,be)},Fl=async(e,t,n,o,r,s)=>{const a=Qe(e),d=`KV value ${n.namespace}/${n.key}`;if(!a||o.offset+o.bytes.byteLength>$t){o.lastSize!==void 0&&!a?re(r,t,"KV_STAGING_NOT_CONFIGURED",`${d} is over ${String(Ye)} bytes; its chunks are staged in the default storage bucket, and this worker has no storage ops`):o.lastSize!==void 0&&re(r,t,"KV_VALUE_TOO_LARGE",`${d} is ${String(o.lastSize)} bytes, over KV's ${String($t)}`);return}const c={kind:"KV",root:await Ss(`kv\0${n.namespace}\0${n.key}\0${s}`),where:{}},h=o.lastSize;await(h===void 0?ks(a,t,c,o,r):Ds(a,t,c,o,r,async p=>Ps(n,Kt(await zt(p,h)),r)))},Wl=async(e,t,n,o)=>{const r=e.kvIntrospector,{expiration:s,key:a,metadata:d,namespace:c,value:h}=t.doc;if(!r){re(n,t,"KV_NOT_CONFIGURED","row targets a KV namespace but this worker has no `kvIntrospector`");return}if(typeof c!="string"||typeof a!="string"){re(n,t,"BAD_ROW","a `$kv` record needs a string `namespace` and `key`");return}const p=h===void 0?Qt(t.doc):void 0;if(typeof h!="string"&&!p||s!==void 0&&typeof s!="number"){re(n,t,"BAD_ROW","a `$kv` record needs a base64 string `value` (or a chunk's `data` and `offset`) and a numeric `expiration` if any");return}const m={expiration:s,key:a,kv:r,metadata:d,namespace:c};try{typeof h=="string"?await Ps(m,h,n):p&&await Fl(e,t,m,p,n,o)}catch(g){re(n,t,"KV_IMPORT_FAILED",`KV ${c}/${a}: ${Wn(g)}`)}},Ql=8192,Vl=e=>{if(!Qn(e))return!1;const t=new TextEncoder;let n=0;for(const[o,r]of Object.entries(e)){if(typeof r!="string")return!1;n+=t.encode(o).byteLength+t.encode(r).byteLength}return n<=Ql},Vn=e=>{const{bucket:t,contentType:n,customMetadata:o,key:r}=e,s=Qt(e);if(typeof r!="string"||r.startsWith(Ts)||!s||t!==void 0&&typeof t!="string")return;const a=o===void 0||Vl(o)?o:!1;if(a===!1)return;const d=t===void 0?{}:{bucket:t};return{...s,key:r,upload:{...d,...typeof n=="string"?{contentType:n}:{},...a===void 0?{}:{customMetadata:a},...s.sha256===void 0?{}:{sha256:s.sha256}},where:d}},Us=async(e,t)=>{const n=await e.storageDownload?.(t.key,t.where);return await n?.body?.cancel(),n!=null},zl=async(e,t,n,o,r,s)=>{const a=o.lastSize??0,d=a>$e?e.storageMultipartUpload:void 0;if(a>$e&&!d){re(s,n,"STORAGE_OBJECT_TOO_LARGE",`${o.key} is ${String(a)} bytes; restoring an object over ${String($e)} bytes needs \`storageMultipartUpload\` on the worker (the export holds it)`);return}await Ds(t,n,r,o,s,async c=>{if(await Us(e,o)){Fn(s);return}if(d){const{contentType:h,customMetadata:p}=o.upload;await As(await d(o.key,{...o.where,contentType:h,customMetadata:p}),c,a)}else{const h=await zt(c,a);await t.upload(o.key,h.buffer,o.upload)}tt(s,Se)})},Jl=async(e,t,n,o,r)=>{try{Gn(n,"STORAGE")}catch(s){if(!Ns(s))throw s;re(o,t,s.code,s.message);return}await Us(e,n)?Fn(o):(await r(n.key,n.bytes.buffer,n.upload),tt(o,Se))},Yl=async(e,t,n,o,r)=>{const s=e.storageUpload;if(!s){re(o,t,"STORAGE_NOT_CONFIGURED","row targets a storage bucket but this worker has no `storageUpload`");return}if(n.offset===0&&n.lastSize!==void 0){await Jl(e,t,n,o,s);return}const a=Qe(e);if(!a){n.lastSize!==void 0&&re(o,t,"STORAGE_NOT_CONFIGURED","restoring a multi-chunk object needs `storageUpload`, `storageDownload`, `storageList` and `storageDelete` on the worker");return}const d={kind:"STORAGE",root:await Ss(`storage\0${n.where.bucket??""}\0${n.key}\0${r}`),where:n.where};n.lastSize!==void 0?await zl(e,a,t,n,d,o):(e.storageMultipartUpload||n.offset+n.bytes.byteLength<=$e)&&await ks(a,t,d,n,o)},Xl=async(e,t,n,o)=>{const r=Vn(t.doc);if(!r){re(n,t,"BAD_ROW","a `$storage` record needs a string `key` outside `_lunora/` and base64 `data`, an integer `offset`, a `size` on its last chunk, and string `customMetadata` within 8,192 bytes if any");return}const s=Rs(e,r);if(s!==void 0){re(n,t,"BAD_ROW",s);return}try{await Yl(e,t,r,n,o)}catch(a){re(n,t,"STORAGE_IMPORT_FAILED",`${r.key}: ${Wn(a)}`)}},Zl=async(e,t,n)=>{const o=Qe(e);if(o)try{await Il(o,ct(e),Date.now())}catch(r){re(n,t,"RESTORE_STAGING_SWEEP_FAILED",`could not delete stale staged chunks: ${Wn(r)}`)}},ql=async(e,t,n)=>{const o={conflicts:0,errors:[],inserted:{}};await Gl(e,t.filter(r=>r.table===_e),o);for(const r of t)switch(r.table){case Fe:{tt(o,Fe),await Zl(e,r,o);break}case be:{await Wl(e,r,o,n);break}case Se:{await Xl(e,r,o,n);break}}return o},eh=e=>Nl.has(e),Cs=e=>e.some(t=>t.table===_e||t.table===Fe&&Array.isArray(t.doc.sections)&&t.doc.sections.includes("auth")),th="/_lunora/admin/export",nh="/_lunora/admin/import",oh="/_lunora/admin/import/commit",rh="/_lunora/admin/import/abort",sh="/_lunora/admin/sync",ah="/_lunora/admin/connector/sync",ih="/_lunora/admin/apply",ch="/_lunora/admin/export-tap/run",ar=new TextEncoder,dh=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>!sr.includes(t)))throw new l(`Export \`sections\` must be an array of ${sr.map(t=>`"${t}"`).join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},uh=async e=>{const n=await we(e,"Export")??{},o=dh(n.sections);if(n.tables===void 0)return{sections:o,tables:void 0};if(!Array.isArray(n.tables))throw new l("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new l("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{sections:o,tables:r}},un=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,lh=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSectionRows:r,exportSinks:s,importSession:a,knownTables:d,queryCoordinator:c,assertAdmin:h,assertRootAdmin:p,resolveForwardContext:m,shardDO:g,prepareExportRows:R,streamingImport:E,syncGlobals:S}=e,_=C=>()=>{p(C)},b=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await uh(C),Q=M.sections??(M.tables===void 0?kl:[]);Q.includes("auth")&&p(C);const{headers:j}=await m(C,V),q=await R(j,M.tables),ee=r(Q),ce=(async function*(){ee.header&&(yield ee.header),yield*q,yield*ee.rows})()[Symbol.asyncIterator]();let te=0;const Ne=new ReadableStream({async cancel(){await ce.return(void 0)},async pull(J){try{const ue=await ce.next();ue.done?(J.enqueue(ar.encode(fs(te))),J.close()):(te+=1,J.enqueue(ar.encode(`${JSON.stringify(ue.value)}
38
+ `)))}catch(ue){J.error(ue)}}});return new Response(Ne,{headers:{"content-type":"application/x-ndjson"},status:200})},O=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),Q=typeof M.cursors=="object"&&M.cursors!==null?M.cursors:{},j=typeof M.epochs=="object"&&M.epochs!==null?M.epochs:{},q=typeof M.limit=="number"?M.limit:void 0,ee=typeof M.globalCursor=="number"?M.globalCursor:0,ie=un(M.tables),{headers:ce}=await m(C,V),te=ie??d(),Ne=await c.orchestrateCdcSync(g,{cursors:Q,defaultShardKey:n,epochs:j,headers:ce,limit:q,tables:te}),J=S?await S({limit:q,sinceSeq:ee}):void 0;return Response.json({global:J,shards:Ne.shards},{status:200})},A=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),Q=Fi(M.cursor),j=typeof M.limit=="number"&&M.limit>0?M.limit:void 0,q=un(M.tables),{headers:ee}=await m(C,V),ie=q??d(),ce=await c.orchestrateCdcSync(g,{cursors:Q.s,defaultShardKey:n,headers:ee,limit:j,tables:ie}),te=[],Ne={...Q.s};let J=!1;for(const he of ce.shards)J=vo(te,he.changes??[],Qi(j))||J,Ne[he.shardKey]=he.cursor;let ue=Q.g;if(S){const he=await S({limit:j,sinceSeq:Q.g});J=vo(te,he.changes,j)||J,ue=he.cursor}const Ue=Wi({g:ue,s:Ne,v:1}),nt={changes:te,hasMore:J,nextCursor:Ue};return Response.json(nt,{status:200})},U=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await ae(C),j=(Array.isArray(M.batches)?M.batches:[]).map(te=>te).filter(te=>te!==null&&typeof te=="object"&&typeof te.shardKey=="string"&&Array.isArray(te.changes)),q=Array.isArray(M.globalChanges)?M.globalChanges:[],{headers:ee}=await m(C,V),ie=await c.orchestrateApplyCdc(g,{batches:j,headers:ee}),ce=q.length>0&&t?await t({changes:q}):0;return Response.json({applied:ie.applied+ce,failed:ie.failed,ok:ie.ok},{status:200})},v=C=>{const{searchParams:V}=new URL(C.url),G=V.get("mode")??"append";if(G==="append")return;if(G!=="replace")throw new l("Import `mode` must be `append` or `replace`",{code:"BAD_REQUEST",status:400});const M=d(),Q=V.get("tables")?.split(",").filter(ee=>ee.length>0),j=Q===void 0||Q.length===0?M:Q;if(j.length===0)throw new l("A replace import needs `tables`: this worker cannot list its schema's tables",{code:"BAD_REQUEST",status:400});const q=M.length>0?j.filter(ee=>!M.includes(ee)):[];if(q.length>0)throw new l(`Replace import names unknown table(s): ${q.join(", ")}`,{code:"BAD_REQUEST",status:400});return j},x=async(C,V,G,M)=>{const{headers:Q}=await m(C,V);if(M!==void 0){const q=await a.stage(C,Q,M,G,_(C));return Response.json(q,{status:q.failed.length>0?207:200})}const j=await a.replace(C,Q,G,_(C));return Response.json(j,{headers:{"content-type":"application/json"},status:j.failed.length>0?207:200})},W=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const{searchParams:M}=new URL(C.url),Q=M.get("dryRun")==="true",j=M.get("onConflict")??"skip";if(j!=="replace"&&j!=="skip")throw new l(`onConflict must be "skip" or "replace", got ${JSON.stringify(j)}`,{code:"BAD_REQUEST",status:400});const q=v(C),ee=M.get("stage")??void 0;if(ee!==void 0&&q===void 0)throw new l("Import `stage` needs `mode=replace`: only a replace is staged",{code:"BAD_REQUEST",status:400});if(q!==void 0){if(Q||M.has("onConflict"))throw new l("`mode=replace` takes neither `dryRun` nor `onConflict`",{code:"BAD_REQUEST",status:400});return x(C,V,q,ee)}const ie=await E(C,async()=>{const{headers:te}=await m(C,V);return te},Q,j,_(C)),ce={...ie,...Q?{dryRun:!0}:{},...j==="replace"?{onConflict:"replace"}:{}};return Response.json(ce,{headers:{"content-type":"application/json"},status:ie.failed.length>0?207:200})},X=async C=>{const V=await ae(C);if(typeof V.session!="string")throw new l("Import commit / abort needs a string `session`",{code:"BAD_REQUEST",status:400});return V.session},se=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await X(C),{headers:Q}=await m(C,V),j=await a.commit(Q,M,_(C)),q={committed:200,partial:502,refused:409}[j.status]??500;return Response.json(j,{status:q})},Oe=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;h(C);const M=await X(C),{headers:Q}=await m(C,V);return Response.json(await a.abort(Q,M),{status:200})},Ie=async(C,V)=>{const G=ke(C,["POST"]);if(G)return G;if(h(C),s===void 0||Object.keys(s).length===0||o===void 0)throw new l("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const M=await ae(C),Q=typeof M.sink=="string"?M.sink:void 0,j=typeof M.limit=="number"&&M.limit>0?M.limit:void 0,q=un(M.tables);if(Q===void 0)throw new l("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=s[Q];if(ee===void 0)throw new l(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:ie}=await m(C,V),ce=q??d(),te=await Gi({coordinator:c,cursorStore:o,defaultShardKey:n,headers:ie,limit:j,shardDO:g,sink:ee,tables:ce});return Response.json(te,{headers:{"content-type":"application/json"},status:200})};return{[ih]:U,[ah]:A,[th]:b,[ch]:Ie,[rh]:Oe,[oh]:se,[nh]:W,[sh]:O}},hh="/_lunora/admin/pause",fh=5e3,ph=3e3,mh=30,bt={paused:!1},ir=10,wh=async(e,t,n)=>{let o;try{const s=await e.fetch(new Request("https://scheduler.internal/instances"));if(!s.ok)throw new Error(`answered ${String(s.status)}`);o=(await s.json()).instances??[]}catch(s){return[`(the instance list: ${s instanceof Error?s.message:String(s)})`]}const r=[];for(let s=0;s<o.length;s+=ir)await Promise.all(o.slice(s,s+ir).map(async a=>{try{(await t(a)?.fetch(new Request("https://scheduler.internal/pause",n)))?.ok||r.push(a)}catch{r.push(a)}}));return r.toSorted((s,a)=>s.localeCompare(a))},gh=async(e,t)=>{let n;const o=new Promise(r=>{n=setTimeout(()=>{r(t())},ph)});try{return await Promise.race([e,o])}finally{clearTimeout(n)}},yh=e=>{const t=e.now??Date.now;let n,o,r=0;const s=async(h,p)=>{const m=p?.method==="POST",g=r;m&&(r+=1);const R=await h.fetch(new Request("https://scheduler.internal/pause",p));if(!R.ok)throw new l(`SchedulerDO /pause answered ${String(R.status)}: ${await R.text()}`,{code:"INTERNAL",status:502});const E=await R.json();return m&&(r+=1),(m||r===g)&&(n={readAt:t(),state:E}),E},a=async()=>{const h=e.stub();if(h===void 0)return bt;if(n!==void 0&&t()-n.readAt<fh)return n.state;const p=r,m=o??s(h).catch(()=>{const g=n?.state??bt;return r===p&&(n={readAt:t(),state:g}),g}).finally(()=>{o===m&&(o=void 0)});return o=m,gh(m,()=>{const g=n?.state??bt;return o===m&&(o=void 0,r===p&&(n={readAt:t(),state:g}),r+=1),g})};return{handleRoute:async h=>{e.assertAdmin(h);const p=e.stub();if(h.method==="GET")return Response.json(p===void 0?{...bt,supported:!1}:{...await s(p),supported:!0});if(Y(h,"POST","Deployment pause"),p===void 0)throw new l("pausing a deployment requires a `schedulerDO` namespace on the worker",{code:"PAUSE_NOT_CONFIGURED",status:400});const m=await h.json().catch(()=>{});if(typeof m?.paused!="boolean")throw new l("Deployment pause requires a boolean `paused`",{code:"BAD_REQUEST",status:400});const g={body:JSON.stringify({paused:m.paused,...typeof m.reason=="string"?{reason:m.reason}:{}}),headers:{"content-type":"application/json"},method:"POST"},R=await s(p,g),E=e.instanceStub===void 0?[]:await wh(p,e.instanceStub,g);if(E.length>0)throw new l(`the deployment ${m.paused?"paused":"resumed"} on its main scheduler instance but not on: ${E.join(", ")}. Run the same command again to reach them`,{code:"PAUSE_INSTANCES_FAILED",status:502});return Response.json({...R,supported:!0})},read:a,refusal:async h=>{if(!(!(await a()).paused||await e.isAdmin(h)))return Response.json({error:{code:"DEPLOYMENT_PAUSED",message:"the deployment is paused"}},{headers:{"cache-control":"no-store","retry-after":String(mh)},status:503})}}},On=300,zn=["auth","kv","storage"],Jt={auth:_e,kv:be,storage:Se},_h="_lunora/restore-session/",Yt=e=>`${_h}${e.session}/${e.generation}/`,Jn=e=>`${Yt(e)}owed/`,Ls=async e=>et(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),Ms=async(e,t)=>`${Yt(e)}${await Ls(t)}/`,$s=(e,t)=>`kv\0${e}\0${t}`,Bs=(e,t)=>`storage\0${e.bucket??""}\0${t}`,bh=e=>{const t=e.find(o=>o.table===Fe),n=Array.isArray(t?.doc.sections)?t.doc.sections:[];return zn.filter(o=>n.includes(o))},le=(e,t,n,o)=>{e.push({code:n,line:t.line,message:o,table:t.table})},Yn=e=>e instanceof Error?e.message:String(e),Sh=async(e,t,n,o)=>{const r=Kn(t,o.offset);await e.upload(r,await Hn(e.secret,r,o.bytes),n)},Eh=async(e,t,n,o,r)=>{try{let s=0;for await(const a of Vt(e,n,t,o,r))s+=a.byteLength;return s===o.lastSize?void 0:{code:`${r}_RESTORE_INCOMPLETE`,message:`read ${String(s)} of ${String(o.lastSize)} bytes`}}catch(s){return{code:s instanceof l?s.code:`${r}_RESTORE_INCOMPLETE`,message:Yn(s)}}},xs=async(e,t,n,o,r)=>{const s=await Ls(n);return{kind:t,label:o,owed:`${Jn(e)}${t==="KV"?"kv":"storage"}/${s}`,prefix:`${Yt(e)}${s}/`,where:r}},Hs=async(e,t,n,o,r)=>{if(r.lastSize===void 0){await e.upload(o.owed,await Hn(e.secret,o.owed,new TextEncoder().encode(o.label)),o.where),await Sh(e,o.prefix,o.where,r);return}const s=await Eh(e,o.prefix,o.where,r,o.kind);if(s!==void 0){le(n,t,s.code,s.message);return}return await e.delete(o.owed,o.where),{doc:t.doc,line:t.line,table:t.table}},Ah=new Set(["__lunora_auth_audit__","devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),Th=(e,t)=>{if(typeof e.doc.table!="string"||!Qn(e.doc.row)){le(t,e,"BAD_ROW","an `$auth` record needs a string `table` and an object `row`");return}if(Ah.has(e.doc.table.toLowerCase())){le(t,e,"BAD_ROW",`the auth table "${e.doc.table}" is never restored`);return}return{doc:e.doc,line:e.line,table:_e}},vh=async(e,t,n,o)=>{const{expiration:r,key:s,namespace:a,value:d}=n.doc;if(typeof a!="string"||typeof s!="string"||r!==void 0&&typeof r!="number"){le(o,n,"BAD_ROW","a `$kv` record needs a string `namespace` and `key`, and a numeric `expiration` if any");return}if(typeof d=="string")return{doc:n.doc,line:n.line,table:be};const c=Qt(n.doc);if(!c){le(o,n,"BAD_ROW","a `$kv` record needs a base64 string `value`, or a chunk's `data` and `offset`");return}const h=Qe(e);if(!h){le(o,n,"KV_STAGING_NOT_CONFIGURED",`KV value ${a}/${s} is chunked; staging its chunks needs the storage ops and an admin token`);return}if(c.offset+c.bytes.byteLength>$t){le(o,n,"KV_VALUE_TOO_LARGE",`KV value ${a}/${s} is over KV's ${String($t)} bytes`);return}return Hs(h,n,o,await xs(t,"KV",$s(a,s),`KV value ${a}/${s}`,{}),c)},Rh=async(e,t,n,o)=>{const r=Vn(n.doc);if(!r){le(o,n,"BAD_ROW","a `$storage` record needs a string `key` outside `_lunora/` and base64 `data`, an integer `offset`, a `size` on its last chunk, and string `customMetadata` within 8,192 bytes if any");return}const s=Rs(e,r);if(s!==void 0){le(o,n,"BAD_ROW",s);return}if(r.offset===0&&r.lastSize!==void 0){try{Gn(r,"STORAGE")}catch(d){le(o,n,d instanceof l?d.code:"STORAGE_RESTORE_INCOMPLETE",Yn(d));return}return{doc:n.doc,line:n.line,table:Se}}const a=Qe(e);if(!a){le(o,n,"STORAGE_NOT_CONFIGURED","staging a multi-chunk object needs the four storage ops and an admin token");return}if(r.offset+r.bytes.byteLength>$e&&!e.storageMultipartUpload){le(o,n,"STORAGE_OBJECT_TOO_LARGE",`${r.key} is over ${String($e)} bytes; restoring it needs \`storageMultipartUpload\` on the worker`);return}return Hs(a,n,o,await xs(t,"STORAGE",Bs(r.where,r.key),`storage object ${r.where.bucket===void 0?"":`${r.where.bucket}/`}${r.key}`,r.where),r)},Oh=async(e,t,n,o)=>{const r=[],s=[],a=bh(n),d=new Set([...o,...a]);let c=!1;for(const h of n){let p;const m=zn.find(g=>Jt[g]===h.table);if(m!==void 0&&!d.has(m)){le(r,h,"BAD_ROW",`the snapshot header does not declare the \`${m}\` section, so this record would never be restored`);continue}try{switch(h.table){case _e:{p=Th(h,r);break}case be:{c=!0,p=await vh(e,t,h,r);break}case Se:{c=!0,p=await Rh(e,t,h,r);break}default:}}catch(g){le(r,h,"SECTION_STAGING_FAILED",Yn(g))}p&&s.push(p)}return{errors:r,rows:s,sections:a,storage:c}},Ih=(e,t)=>{switch(t){case"auth":return e.authData?.replaceRows?void 0:"the snapshot carries auth tables, but this worker's auth data port cannot replace them";case"kv":return e.kvIntrospector?void 0:"the snapshot carries KV, but this worker has no `kvIntrospector`";case"storage":return e.storageList&&e.storageDownload&&e.storageUpload&&e.storageDelete?void 0:"the snapshot carries storage objects, but this worker lacks `storageList`, `storageDownload`, `storageUpload` or `storageDelete`";default:return`unknown section "${t}"`}},js=async e=>{const t=[];for await(const n of e)t.push({doc:n.doc.row,table:String(n.doc.table)});return t},Nh=async(e,t)=>{const n=await js(t);return(await(e.authData?.replaceRows?.(n,{dryRun:!0})??Promise.reject(new TypeError("auth replace is not configured")))).errors.map(r=>({code:"AUTH_IMPORT_FAILED",line:0,message:r.message,table:_e}))},kh=async(e,t)=>{const n=await js(t),o=await(e.authData?.replaceRows?.(n)??Promise.reject(new TypeError("auth replace is not configured")));if(o.errors.length>0)throw new l(`auth replace rolled back: ${o.errors.map(r=>r.message).join("; ")}`,{code:"AUTH_IMPORT_FAILED",status:409});return{deleted:{[_e]:o.deleted},inserted:{[_e]:o.inserted}}},Ks=e=>{const t=Qe(e);if(!t)throw new TypeError("restore staging needs the storage ops and an admin token");return t},Dh=async(e,t,n)=>{if(typeof n.value=="string")return n.value;const o=Qt(n);if(o?.lastSize===void 0)throw new TypeError("a staged KV record is neither a value nor a last chunk");const r=await Ms(t,$s(String(n.namespace),String(n.key)));return Kt(await zt(Vt(Ks(e),{},r,o,"KV"),o.lastSize))},Ph=async(e,t,n)=>{const o=e.kvIntrospector;if(!o)throw new TypeError("kv replace is not configured");const r=new Set;let s=0;const a=Math.floor(Date.now()/1e3);for await(const{doc:d}of n){const c=String(d.namespace),h=String(d.key),{expiration:p,metadata:m}=d;typeof p=="number"&&p<a+vs||(await o.putValue({encoding:"base64",key:h,namespace:c,value:await Dh(e,t,d),...typeof p=="number"?{expiration:p}:{},...m===void 0?{}:{metadata:m}}),r.add(`${c}\0${h}`),s+=1)}return{inserted:s,keep:r}},Uh=async(e,t,n)=>{const o=[];for await(const{name:r}of Os(e,t))n.has(`${t}\0${r}`)||o.push(r);for(const r of o)await e.deleteKey({key:r,namespace:t});return o.length},Ch=async(e,t,n)=>{const{inserted:o,keep:r}=await Ph(e,t,n),s=e.kvIntrospector;let a=0;for(const{binding:d}of await s?.listNamespaces()??[])a+=await Uh(s,d,r);return{deleted:{[be]:a},inserted:{[be]:o}}},Gs=async(e,t,n)=>{const o=[];let r;do{const s=await e(t,{...n,cursor:r,limit:1e3});o.push(...s.objects.map(a=>a.key).filter(a=>a.startsWith(t))),r=s.truncated===!1?void 0:s.cursor}while(r!==void 0);return o},Fs=async(e,t)=>{const{storageDelete:n,storageList:o}=e;if(!(!n||!o))for(const r of new Set([void 0,...e.storageBuckets??[]])){const s=r===void 0?{}:{bucket:r},a=await Gs(o,Yt(t),s);await Promise.all(a.map(async d=>n(d,s)))}},Lh=async(e,t,n,o)=>{const r=await e.download(n,o),s=r?.body?await _s(e.secret,n,new Uint8Array(await new Response(r.body).arrayBuffer())):void 0;return{code:"IMPORT_SESSION_INCOMPLETE",line:0,message:`${s===void 0?n:new TextDecoder().decode(s)} never received its last chunk — the snapshot stream ended part-way through it`,table:n.slice(Jn(t).length).startsWith("kv/")?be:Se}},Mh=async(e,t)=>{const n=Qe(e);if(!n)return[];const o=new Map;for(const r of new Set([void 0,...e.storageBuckets??[]])){const s=r===void 0?{}:{bucket:r};for(const a of await Gs(n.list,Jn(t),s))o.has(a)||o.set(a,s)}return Promise.all([...o].map(async([r,s])=>Lh(n,t,r,s)))},$h=async(e,t,n)=>{const o=e.storageUpload;if(!o)throw new TypeError("storage replace is not configured");const r=n.lastSize??0;if(n.offset===0){Gn(n,"STORAGE"),await o(n.key,n.bytes.buffer,n.upload);return}const s=Vt(Ks(e),n.where,await Ms(t,Bs(n.where,n.key)),n,"STORAGE");if(r>$e&&e.storageMultipartUpload){const{contentType:d,customMetadata:c}=n.upload;await As(await e.storageMultipartUpload(n.key,{...n.where,contentType:d,customMetadata:c}),s,r);return}const a=await zt(s,r);await o(n.key,a.buffer,n.upload)},Bh=async(e,t,n)=>{const{storageDelete:o,storageList:r}=e;if(!o||!r)throw new TypeError("storage replace is not configured");const s=new Set,a=ct(e),d=a.includes("default")?"default":a[0];let c=0,h=0;for await(const{doc:p}of n){const m=Vn(p);if(!m)throw new TypeError("a staged storage record does not parse");s.add(`${m.where.bucket??d??""}\0${m.key}`),await $h(e,t,m),c+=1}for(const p of ct(e)){const m=[];for await(const g of Is(r,p))s.has(`${p??""}\0${g.key}`)||m.push(g.key);await Promise.all(m.map(async g=>o(g,p===void 0?{}:{bucket:p}))),h+=m.length}return{deleted:{[Se]:h},inserted:{[Se]:c}}},xh=async(e,t,n,o)=>{switch(n){case"auth":return kh(e,o);case"kv":return Ch(e,t,o);default:return Bh(e,t,o)}},Ws=e=>new URL(e.url).searchParams.get("deletes")==="true",Hh=/^[\w-]{1,64}$/u,jh=e=>{const t=new URL(e.url).searchParams.get("import");if(t===null)return crypto.randomUUID();if(!Hh.test(t))throw new l("Import `import` is 1-64 characters of [A-Za-z0-9_-]",{code:"BAD_REQUEST",status:400});return t},Kh=(e,t,n)=>{let o;try{o=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!o||typeof o!="object"||Array.isArray(o))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=tl(o);if(r!==void 0)return{end:r,ok:"end"};const s=o;return typeof s.table!="string"||s.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!s.doc||typeof s.doc!="object"||Array.isArray(s.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:s.table},ok:!1}:s.op==="delete"&&!n?{error:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `?deletes=true` on the import request',table:s.table},ok:!1}:s.op!==void 0&&s.op!=="delete"?{error:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(s.op)}`,table:s.table},ok:!1}:{doc:s.doc,ok:!0,...s.op==="delete"?{op:"delete"}:{},table:s.table}},Gh=(e,t,n,o,r)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const s=e[n.mode.field];return s==null?{error:{code:"BAD_ROW",line:r,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:o}},Fh=(e,t,n)=>{if(!(e===void 0||!t&&e===n))throw new l(t?"the import body continues after its end marker, so nothing was imported":`the import body's end marker declares ${String(e)} row(s) but ${String(n)} were read, so nothing was imported`,{code:"BAD_REQUEST",status:400})},Qs=async(e,t,n,o)=>{if(!e.body&&o===void 0)throw new l("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=Ws(e),s=[],a=[],d=new Map,c=[];let h=0;const p={declaredRows:void 0,trailingAfterEnd:!1};let m=0;if(!e.body)return{errors:s,globalRows:a,perShard:d,received:h,sectionRows:c};const g=e.body.getReader(),R=new TextDecoder;let E="",S=0;const _=b=>{m+=1;const O=b.trim();if(O.length===0)return;h+=1,p.declaredRows!==void 0&&(p.trailingAfterEnd=!0);const A=Kh(O,m,r);if(A.ok==="end"){h-=1,p.declaredRows=A.end;return}if(!A.ok){s.push(A.error);return}const{doc:U,table:v}=A;if(eh(v)){v===Fe&&Kl(U),c.push({doc:U,line:m,table:v});return}if(o!==void 0&&!o.has(v)){s.push({code:"BAD_ROW",line:m,message:`table "${v}" is not in this replace import's tables`,table:v});return}const x=A.op===void 0?{}:{op:A.op},W=t.resolveTableSharding?.(v);if(W?.mode.kind==="global"){a.push({doc:U,line:m,...x,table:v});return}const X=Gh(U,v,W,n,m);if(!X.ok){s.push(X.error);return}const se=d.get(X.shardKey);se?se.rows.push({doc:U,line:m,...x,table:v}):d.set(X.shardKey,{rows:[{doc:U,line:m,...x,table:v}],shardKey:X.shardKey,startLine:m})};for(;;){const{done:b,value:O}=await g.read();if(b)break;if(O&&(S+=O.byteLength,S>Br))throw await g.cancel().catch(()=>{}),new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=R.decode(O,{stream:!0});let A=E.indexOf(`
39
+ `);for(;A!==-1;){const U=E.slice(0,A);E=E.slice(A+1),_(U),A=E.indexOf(`
40
+ `)}}return E.length>0&&_(E),Fh(p.declaredRows,p.trailingAfterEnd,h),{errors:s,globalRows:a,perShard:d,received:h,sectionRows:c}},Wh=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),In=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts,e.deleted+=t.deleted??0,e.replaced+=t.replaced??0},cr=(e,t,n,o)=>{for(const r of t)e.errors.push({code:n,line:r.line,message:`row targets global table "${r.table}" but ${o}`,table:r.table})},Xn=async(e,t,n,o,r)=>{try{await e({conflicts:o.conflicts,errors:o.errors.length,inserted:o.inserted,op:n,...o.deleted===void 0?{}:{deleted:o.deleted},...o.replaced===void 0?{}:{replaced:o.replaced},...r})}catch(s){t.push(`the ${n} audit entry was not recorded: ${s instanceof Error?s.message:String(s)}`)}},Qh=async(e,t,n,o,r,s)=>{if(o.length===0)return;if(!e.importGlobals){cr(t,o,"GLOBAL_NOT_CONFIGURED","no `importGlobals` is configured");return}if(s.dryRun&&e.importGlobalsSupportsDryRun!==!0){cr(t,o,"GLOBAL_DRY_RUN_UNSUPPORTED","the configured `importGlobals` cannot check rows without writing them");return}const a=await e.importGlobals({dryRun:s.dryRun,onConflict:s.onConflict,rows:o,startLine:o[0]?.line??1});if(In(t,a),!s.dryRun){const d=[...new Set(o.map(c=>c.table))].toSorted((c,h)=>c.localeCompare(h));await Xn(r,n,"importGlobal",a,{tables:d})}},Vs="no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one",Vh=async(e,t,n,o,r,s,a,d,c)=>{const h=t.defaultShardKey??"__root__",p=jh(e),{errors:m,globalRows:g,perShard:R,received:E,sectionRows:S}=await Qs(e,t,h,void 0);if(Cs(S)&&c(),a==="replace"&&g.length>0&&(t.importGlobals===void 0||t.importGlobalsSupportsReplace!==!0))throw new l("onConflict=replace: global rows are present but no `importGlobals` that can overwrite existing rows is configured, so nothing was imported",{code:"BAD_REQUEST",status:400});if(g.some(O=>O.op==="delete")&&t.importGlobalsSupportsDelete!==!0)throw new l("delete rows target global tables but no `importGlobals` that can delete rows is configured, so nothing was imported",{code:"BAD_REQUEST",status:400});const _={conflicts:0,deleted:0,errors:m,failed:[],inserted:{},replaced:0},b=[];if(t.resolveTableSharding===void 0&&R.size>0&&b.push(Vs),R.size>0){const O=await n.orchestrateImport(r,{batches:[...R.values()],deletes:Ws(e),dryRun:s,headers:await o(),onConflict:a});In(_,O),_.failed.push(...Wh(O.shards))}if(await Qh(t,_,b,g,d,{dryRun:s,onConflict:a}),S.length>0&&s)b.push(`a dry run does not check the export's sections ($auth, $kv, $storage): ${String(S.length)} section line(s) were not checked`);else if(S.length>0){const O=await ql(t,S,p);In(_,O),await Xn(d,b,"importSections",O,{})}return{conflicts:_.conflicts,deleted:_.deleted,errors:_.errors,failed:_.failed,inserted:_.inserted,received:E,replaced:_.replaced,...b.length>0?{warnings:b}:{}}},Pe={abort:"__lunora_admin__:importAbort",commit:"__lunora_admin__:importCommit",manifest:"__lunora_admin__:importManifest",stage:"__lunora_admin__:importStage",stagedRows:"__lunora_admin__:importStagedRows"},zs={BAD_REQUEST:400,IMPORT_SESSION_CHANGED:409,IMPORT_SESSION_CLOSED:409,IMPORT_SESSION_COMMITTED:409,IMPORT_SESSION_COMMITTING:409,IMPORT_SESSION_CORRUPT:409,IMPORT_SESSION_EXPIRED:410,IMPORT_SESSION_INCOMPLETE:409,IMPORT_SESSION_MISMATCH:400,IMPORT_SESSION_NOT_COMMITTING:409,IMPORT_SESSION_NOT_FOUND:404,IMPORT_SESSION_REJECTED:409,IMPORT_SESSION_STALE:409,IMPORT_STEP_CLAIMED:409,IMPORT_STEP_DONE:409},zh=/^[\w-]{1,64}$/u,Zn=e=>{if(!zh.test(e))throw new l("An import session id is 1-64 characters of [A-Za-z0-9_-]",{code:"BAD_REQUEST",status:400})},Xt=e=>e.defaultShardKey??"__root__",dr=(e,t)=>e.resolveTableSharding?.(t)?.mode.kind==="global",Js=(e,t)=>({globalScope:t.filter(n=>dr(e,n)),shardScope:t.filter(n=>!dr(e,n))}),We=(e,t)=>{for(const[n,o]of Object.entries(t??{}))e[n]=(e[n]??0)+o},Ys=e=>e.error?{message:e.error.message,shardKey:e.shardKey,timedOut:e.error.timedOut}:void 0,De=(e,t)=>new l(t,{code:e,status:zs[e]??502}),qn=e=>{const t=e?.code;throw typeof t=="string"&&t in zs&&!(e instanceof l)?De(t,e instanceof Error?e.message:String(e)):e},qe=async(e,t,n)=>{const[o]=await e.coordinator.orchestrateImportSession(e.namespace,{calls:[{args:n,shardKey:Xt(e.options)}],functionPath:t,headers:e.headers});if(o===void 0||o.error)throw De(o?.error?.code??"SHARD_UNREACHABLE",o?.error?.message??"the root shard did not answer");return o.value},Xs=async(e,t)=>{const n=await qe(e,Pe.manifest,{op:"get",session:t});if(n===null||typeof n!="object"||!("manifest"in n))throw De("IMPORT_SESSION_CORRUPT",`the root shard answered no manifest for import session "${t}"`);return n.manifest??void 0},Ze=async(e,t,n)=>{const{manifest:o}=await qe(e,Pe.manifest,{op:"advance",session:t,...n});return o},lt=e=>({generation:e.generation,session:e.session}),Zs=async(e,t)=>{const n=t.shards.filter(s=>s!==Xt(e.options)),r=(await e.coordinator.orchestrateImportSession(e.namespace,{calls:n.map(s=>({args:{generation:t.generation,session:t.session},shardKey:s})),functionPath:Pe.abort,headers:e.headers})).find(s=>s.error);if(r?.error)throw De("SHARD_UNREACHABLE",`could not drop the staging on shard "${r.shardKey}": ${r.error.message}`);await e.options.importGlobalsStaging?.abort({generation:t.generation,session:t.session}).catch(qn),await Fs(e.options,lt(t))},Jh=async(e,t)=>{for(const n of t)await Zs(e,n).catch(()=>{})},Yh=async(e,t,n,o)=>{const r=[],s=[],a={},d=await e.coordinator.orchestrateImportSession(e.namespace,{calls:[...o].map(([c,h])=>({args:{generation:t.generation,rows:h,session:t.session,tables:n},shardKey:c})),functionPath:Pe.stage,headers:e.headers});for(const c of d){const h=Ys(c);if(h){s.push(h);continue}const p=c.value;r.push(...p.errors??[]),We(a,p.staged)}return{errors:r,failed:s,staged:a}},qs=async(e,t,n,o)=>{const{options:r}=t,s=Xt(r),{globalScope:a,shardScope:d}=Js(r,o);if(Zn(n),a.length>0&&!r.importGlobalsStaging)throw new l(`replace import covers .global() table(s) ${a.join(", ")} but no \`importGlobalsStaging\` is configured`,{code:"GLOBAL_NOT_CONFIGURED",status:400});const c=await Qs(e,r,s,new Set(o));Cs(c.sectionRows)&&t.assertAuthSectionAllowed();const h=new Map;for(const O of c.perShard.values())h.set(O.shardKey,[...O.rows]);const p=c.sectionRows.length>0,m=await qe(t,Pe.manifest,{begin:!0,globals:c.globalRows.length>0,op:"touch",received:c.received,session:n,shards:[...h.keys(),...p?[s]:[]],storage:c.sectionRows.some(O=>O.table==="$kv"||O.table==="$storage"),tables:o});m.created&&m.expired.length>0&&await Jh(t,m.expired);const g=lt(m.manifest),R=await Oh(r,g,c.sectionRows,m.manifest.sections),E=[...c.errors,...R.errors],S=[],_={},b=r.resolveTableSharding===void 0&&c.perShard.size>0?[Vs]:[];if(R.rows.length>0&&h.set(s,[...h.get(s)??[],...R.rows]),E.length===0){const O=await Yh(t,g,d,h);if(E.push(...O.errors),S.push(...O.failed),We(_,O.staged),c.globalRows.length>0&&r.importGlobalsStaging){const A=await r.importGlobalsStaging.stage({generation:g.generation,rows:c.globalRows,session:n,tables:a}).catch(qn);E.push(...A.errors),We(_,A.staged)}}return await qe(t,Pe.manifest,{begin:!1,op:"touch",rejected:E.length+S.length,sections:R.sections,session:n,tables:o}),{errors:E,failed:S,received:c.received,session:n,staged:_,...b.length>0?{warnings:b}:{}}},ea=async function*(t,n,o){let r=0;for(;;){const s=await qe(t,Pe.stagedRows,{afterSeq:r,limit:o==="auth"?200:8,sections:[Jt[o]],session:n});if(s.rows.length===0)return;yield*s.rows,r=s.seq}},ta=async(e,t,n,o,r)=>{const s=await e.coordinator.orchestrateImportSession(e.namespace,{calls:n.map(d=>({args:{dryRun:r,generation:t.generation,session:t.session,staged:t.shards.includes(d),tables:o},shardKey:d})),functionPath:Pe.commit,headers:e.headers}),a={deleted:{},errors:[],failed:[],inserted:{}};for(const d of s){const c=Ys(d);if(c){a.failed.push(c);continue}const h=d.value;a.errors.push(...h.errors??[]),We(a.deleted,h.deleted),We(a.inserted,h.inserted)}return a},Xh=e=>{const t={},n={},o=[];for(const r of Object.values(e.steps))We(t,r.deleted),We(n,r.inserted),o.push(...r.warnings??[]);return{deleted:t,inserted:n,warnings:o}},ur=e=>{const{deleted:t,inserted:n,warnings:o}=Xh(e);return{deleted:t,inserted:n,session:e.session,status:"committed",...o.length>0?{warnings:o}:{}}},Zh=(e,t,n)=>{if(t.state==="aborting")throw De("IMPORT_SESSION_CLOSED",`import session "${t.session}" is being aborted`);if(t.state==="open"&&t.rejected>0)throw De("IMPORT_SESSION_REJECTED",`import session "${t.session}" had ${String(t.rejected)} refused row(s) or unreachable shard(s) while staging — abort it`);if(t.state==="open"&&t.pending>0)throw De("IMPORT_SESSION_INCOMPLETE",`import session "${t.session}" has ${String(t.pending)} staging request(s) that never finished — abort it`);if(n.length>0&&!e.importGlobalsStaging)throw new l("replace import covers .global() tables but no `importGlobalsStaging` is configured",{code:"GLOBAL_NOT_CONFIGURED",status:400});for(const o of t.sections){const r=Ih(e,o);if(r!==void 0)throw new l(r,{code:"SECTION_NOT_CONFIGURED",status:400})}},ln=async(e,t,n,o,r)=>{if(t.steps[o]!==void 0)return t;const{session:s}=t;await Ze(e,s,{claim:n,step:o});try{return await Ze(e,s,{claimant:n,step:o,stepResult:await r()})}catch(a){throw await Ze(e,s,{release:n,step:o}).catch(()=>{}),a}};class Bt extends Error{errors;failed;constructor(t,n){super("commit step failed"),this.errors=t,this.failed=n}}const qh=(e,t)=>new Bt([{code:"SECTION_COMMIT_FAILED",line:0,message:t instanceof Error?t.message:String(t),table:Jt[e]}],[]),lr=async(e,t,n,o,r)=>{const s=[...r.warnings??[]];return await Xn(e.recordAudit,s,t,{conflicts:0,deleted:r.deleted,errors:[],inserted:r.inserted},{replaceTables:o,session:n,tables:o}),{...r,...s.length>0?{warnings:s}:{}}},ef=async(e,t,n)=>{const{options:o}=e,{session:r}=t,s=crypto.randomUUID();let a=t;n.targets.length>0&&(a=await ln(e,a,s,"shards",async()=>{const c=await ta(e,t,n.targets,n.shardScope,!1);if(c.errors.length>0||c.failed.length>0)throw new Bt(c.errors,c.failed);return{deleted:c.deleted,inserted:c.inserted}}));const d=o.importGlobalsStaging;n.globalScope.length>0&&d&&(a=await ln(e,a,s,"globals",async()=>{const c=await d.commit({generation:t.generation,session:r,staged:t.globals,tables:n.globalScope}).catch(qn);if(c.errors.length>0)throw new Bt([...c.errors],[]);return lr(e,"importGlobal",r,n.globalScope,{deleted:c.deleted??{},inserted:c.inserted})}));for(const c of zn.filter(h=>t.sections.includes(h)))a=await ln(e,a,s,c,async()=>{const h=await xh(o,lt(t),c,ea(e,r,c)).catch(p=>{throw qh(c,p)});return lr(e,"importSections",r,[Jt[c]],h)});return a},tf=async(e,t,n,o)=>{const{options:r}=e,{session:s}=t,a=t.storage?await Mh(r,lt(t)):[];if(a.length>0)return{errors:a,failed:[],session:s,status:"refused"};const d=await ta(e,t,n,o,!0);if(d.errors.length>0||d.failed.length>0)return{errors:d.errors,failed:d.failed,session:s,status:"refused"};const c=t.sections.includes("auth")?await Nh(r,ea(e,s,"auth")):[];return c.length>0?{errors:c,failed:[],session:s,status:"refused"}:void 0},na=async(e,t)=>{const{options:n}=e;Zn(t);let o=await Xs(e,t);if(o===void 0)throw De("IMPORT_SESSION_NOT_FOUND",`import session "${t}" does not exist or has expired`);if(o.sections.includes("auth")&&e.assertAuthSectionAllowed(),o.state==="committed")return ur(o);const{globalScope:r,shardScope:s}=Js(n,o.tables);Zh(n,o,r);const a=s.length===0?[]:[...new Set([...o.shards,...await e.coordinator.shardKeysForTables(s,Xt(n))])];if(o.state==="open"){const d=await tf(e,o,a,s);if(d!==void 0)return d;o=await Ze(e,t,{batches:o.batches,state:"committing"})}try{await ef(e,o,{globalScope:r,shardScope:s,targets:a})}catch(d){if(d instanceof Bt)return{errors:d.errors,failed:d.failed,session:t,status:"partial"};throw d}return o=await Ze(e,t,{state:"committed"}),await Fs(n,lt(o)).catch(()=>{}),ur(o)},Ot=async(e,t)=>{Zn(t);const n=await Xs(e,t);if(n===void 0)return{aborted:!1};if(n.state==="committed"||n.state==="committing")throw De(n.state==="committed"?"IMPORT_SESSION_COMMITTED":"IMPORT_SESSION_COMMITTING",n.state==="committed"?`import session "${t}" is already committed`:`import session "${t}" is being committed — send the commit again to finish it`);const o=await Ze(e,t,{state:"aborting"});return await Zs(e,o),await qe(e,Pe.manifest,{op:"drop",session:t}),{aborted:!0}},nf=async(e,t,n)=>{const o=`once-${crypto.randomUUID()}`;let r;try{r=await qs(e,t,o,n)}catch(c){throw await Ot(t,o).catch(()=>{}),c}const s={conflicts:0,deleted:{},inserted:{},received:r.received,...r.warnings?{warnings:r.warnings}:{}};if(r.errors.length>0||r.failed.length>0)return await Ot(t,o).catch(()=>{}),{...s,errors:r.errors,failed:r.failed};const a=await na(t,o);if(a.status==="refused"&&await Ot(t,o).catch(()=>{}),a.status!=="committed")return{...s,errors:a.errors,failed:a.failed};const d=[...r.warnings??[],...a.warnings??[]];return{conflicts:0,deleted:a.deleted,errors:[],failed:[],inserted:a.inserted,received:r.received,...d.length>0?{warnings:d}:{}}},of=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),It=e=>typeof e=="object"&&e!==null?e:{},oa=e=>{const t=It(e)._meta??{};if(t.sensitive===!0)return!0;const n=Array.isArray(t.members)?t.members:[],o=typeof t.shape=="object"&&t.shape!==null?Object.values(t.shape):[];return[t.inner,t.keyValidator,t.valueValidator,...n,...o].some(r=>typeof r=="object"&&r!==null&&oa(r))},hn=e=>typeof e.kind=="string"?e.kind:"unknown",rf=(e,t)=>{let n=It(t),o=!1;hn(n)==="optional"&&(o=!0,n=It(n._meta?.inner));const r=hn(n),s=n._meta??{},a={kind:r,name:e,optional:o};if(oa(t)&&(a.sensitive=!0),r==="id"&&typeof s.tableName=="string"&&(a.table=s.tableName),r==="array"){const d=hn(It(s.inner));d!=="unknown"&&(a.element=d)}return a},sf=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>rf(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),af=Symbol.for("lunora.procedure.meta"),cf="/_lunora/admin/functions",df="/_lunora/admin/cron-jobs",uf="/_lunora/admin/architecture",lf="/_lunora/admin/openapi",hf="/_lunora/admin/openrpc",ff="/_lunora/admin/global/tables",pf="/_lunora/admin/global/table",mf="/_lunora/admin/global/facet",hr=e=>{if(e===void 0||e==="")return;let t;try{t=Nt(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:r,operator:s,path:a,value:d}=o;return[{column:r,value:d,...s===void 0?{}:{operator:s},...a===void 0?{}:{path:a}}]});return n.length===0?void 0:n},wf=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then hand `createWorker` a loader for the generated module: `openApiSpec: () => import("./lunora/_generated/openapi").then((m) => m.openApiSpec)`. A worker that ships it as a Workers Static Asset reads `/_lunora/studio/openapi.json` through its assets binding; if that file is missing, deploy again with `lunora deploy`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),gf=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then hand `createWorker` a loader for the generated module: `openRpcSpec: () => import("./lunora/_generated/openrpc").then((m) => m.openRpcSpec)`. A worker that ships it as a Workers Static Asset reads `/_lunora/studio/openrpc.json` through its assets binding; if that file is missing, deploy again with `lunora deploy`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),fn={headers:{"cache-control":"no-store","content-type":"application/json"},status:200},pn=e=>{let t;return async()=>(t??=e?.().then(n=>(n===void 0&&(t=void 0),n),n=>{throw t=void 0,n}),t)},yf=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:r,requireAdminOption:s}=e,a=pn(n.architecture),d=pn(n.openApiSpec),c=pn(n.openRpcSpec),h=b=>{Y(b,"GET","Functions");const O=s(b,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),A=Object.entries(O).flatMap(([U,v])=>{if(v.visibility==="internal"||v.kind==="stream")return[];const x=v[af];let W={};if(x==="unloaded")W={metaUnloaded:!0};else if(x!==void 0)try{W={meta:Re(x)}}catch{W={metaUnencodable:!0}}return[{args:[...v.argumentDescriptors??sf(v.args)],kind:v.kind,...W,path:U}]}).toSorted((U,v)=>U.path.localeCompare(v.path));return Response.json({functions:A},{headers:{"content-type":"application/json"},status:200})},p=b=>{Y(b,"GET","Cron-jobs");const O=s(b,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),A=Object.entries(O).flatMap(([U,v])=>v.map(x=>({args:x.args,cron:U,functionPath:x.functionPath,name:x.name,shardKey:x.shardKey,workflow:x.workflow}))).toSorted((U,v)=>U.name.localeCompare(v.name));return Response.json({jobs:A},{headers:{"content-type":"application/json"},status:200})},m=async b=>(Y(b,"GET","Architecture"),t(b),Response.json(await a()??of,fn)),g=async b=>(Y(b,"GET","OpenAPI"),t(b),Response.json(await d()??wf,fn)),R=async b=>(Y(b,"GET","OpenRPC"),t(b),Response.json(await c()??gf,fn)),E=async b=>{Y(b,"GET","Global-tables");const O=s(b,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await O.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async b=>{Y(b,"GET","Global-table");const O=s(b,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),A=new URL(b.url),U=r(A,"table");if(U===void 0)throw new l("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await O.readTablePage({...o(b),filters:hr(r(A,"filters")),table:U});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},_=async b=>{Y(b,"GET","Global-facet");const O=s(b,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),A=new URL(b.url),U=r(A,"table"),v=r(A,"column");if(U===void 0||v===void 0)throw new l("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const x=r(A,"limit"),W=x===void 0?void 0:Number(x),X=await O.facetColumn({column:v,filters:hr(r(A,"filters")),limit:W!==void 0&&Number.isFinite(W)?W:void 0,table:U});return Response.json(X,{headers:{"content-type":"application/json"},status:200})};return{[df]:p,[cf]:h,[mf]:_,[pf]:S,[ff]:E,[uf]:m,[lf]:g,[hf]:R}},_f="/_lunora/admin/kv/namespaces",bf="/_lunora/admin/kv/keys",ra="/_lunora/admin/kv/value",sa=32*1048576,fr=60,Sf=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=E=>n(E,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),r=E=>Response.json(E,{headers:{"content-type":"application/json"},status:200}),s=(E,S)=>{const _=new URL(E.url),b=_.searchParams.get("namespace")??"",O=_.searchParams.get("key")??"";if(b==="")throw new l(`KV-value ${S} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(O==="")throw new l(`KV-value ${S} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:O,namespace:b}},a=async(E,S)=>{if(!(await E.listNamespaces()).some(b=>b.binding===S))throw new l(`Unknown KV namespace binding \`${S}\``,{code:"NOT_FOUND",status:404})},d=async E=>(Y(E,"GET","KV-namespaces"),r({namespaces:await o(E).listNamespaces()})),c=async E=>{Y(E,"GET","KV-keys");const S=o(E),_=new URL(E.url),b=_.searchParams.get("namespace")??"";if(b==="")throw new l("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const O=_.searchParams.get("prefix")??void 0,A=_.searchParams.get("cursor")??void 0,U=_.searchParams.get("limit"),v=U===null?void 0:Number.parseInt(U,10);if(v!==void 0&&(!Number.isInteger(v)||v<1))throw new l("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const x=v===void 0?void 0:Math.min(v,1e3);return await a(S,b),r(await S.listKeys({cursor:A,limit:x,namespace:b,prefix:O}))},g={DELETE:async E=>{const S=o(E),_=s(E,"DELETE");return await a(S,_.namespace),await S.deleteKey(_),r({deleted:!0})},GET:async E=>{const S=o(E),_=s(E,"GET");return await a(S,_.namespace),r(await S.getValue(_))},PUT:async E=>{const S=o(E),_=await t(E,sa);if(typeof _.namespace!="string"||_.namespace==="")throw new l("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof _.key!="string"||_.key==="")throw new l("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof _.value!="string")throw new l("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(_.expirationTtl!==void 0&&(typeof _.expirationTtl!="number"||!Number.isInteger(_.expirationTtl)||_.expirationTtl<fr))throw new l("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const b=Math.floor(Date.now()/1e3)+fr;if(_.expiration!==void 0&&(typeof _.expiration!="number"||!Number.isInteger(_.expiration)||_.expiration<b))throw new l("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await a(S,_.namespace),await S.putValue({expiration:_.expiration,expirationTtl:_.expirationTtl,key:_.key,metadata:_.metadata,namespace:_.namespace,value:_.value}),r({ok:!0})}},R=E=>{const S=g[E.method];if(!S)throw new l("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return S(E)};return{[_f]:d,[bf]:c,[ra]:R}},Ef="/_lunora/migrate",Af="/_lunora/admin/pitr",Tf="/_lunora/admin/rank",vf="/_lunora/admin/rankpage",Rf="/_lunora/admin/shard-registry/prune",Of="/_lunora/admin/shard-traffic",If=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Nf=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),kf=async e=>{const n=await we(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!If.has(n.functionPath))throw new l("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Df=async e=>{const n=await we(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new l("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new l("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new l("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new l("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},Pf=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new l('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Uf=e=>{if(typeof e.table!="string"||e.table.length===0)throw new l("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new l("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new l("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new l("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new l("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Cf=async e=>{const n=await we(e,"Rank page")??{};Uf(n);const o=Pf(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},Lf=async e=>{const n=await we(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new l("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Mf=async e=>{const n=await we(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new l("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},$f=async e=>{const n=await ae(e);if(typeof n.functionPath!="string"||!Nf.has(n.functionPath))throw new l("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new l("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},Bf=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:r,resolveForwardContext:s,shardDO:a,shardedTables:d}=e,c=(S,_)=>{if(S.method!=="POST")throw new l(`${_} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(S))throw new l("Admin auth required",{code:"FORBIDDEN",status:403})},h=async(S,_)=>{c(S,"Migration");const b=await kf(S),{headers:O}=await s(S,_),A=await r.orchestrateMigration(a,{args:b.args,defaultShardKey:t,functionPath:b.functionPath,headers:O,table:b.table});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},p=async(S,_)=>{c(S,"Rank");const b=await Df(S),{headers:O}=await s(S,_),A=await r.orchestrateRank(a,{headers:O,index:b.index,partitionKey:b.partitionKey,rowId:b.rowId,sortValues:b.sortValues,table:b.table});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},m=async(S,_)=>{c(S,"Rank page");const b=await Cf(S),{headers:O}=await s(S,_),A=await r.orchestrateRankPage(a,{...b,headers:O});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},g=async(S,_)=>{c(S,"Shard-traffic");const b=await Lf(S),{headers:O}=await s(S,_),A=await r.orchestrateShardTraffic(a,{headers:O,table:b.table});return Response.json(A,{headers:{"content-type":"application/json"},status:200})},R=async(S,_)=>{c(S,"Shard-registry prune");const b=await Mf(S),O=d(),A=(b.tables??[]).filter(x=>!O.includes(x));if(A.length>0)throw new l(`Shard-registry prune names tables that are not \`.shardBy()\`: ${A.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:U}=await s(S,_),v=await Zi(r.registry,a,{dryRun:b.dryRun,headers:U,tables:b.tables??O});return Response.json(v,{status:v.failed.length>0?207:200})},E=async(S,_)=>{if(Y(S,"POST","PITR"),!o(S))throw new l("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const b=await $f(S),{headers:O}=await s(S,_),A=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:b.args,functionPath:b.functionPath}),headers:O,method:"POST"});return n(a,b.shardKey??t,A)};return{[Ef]:h,[Af]:E,[Tf]:p,[vf]:m,[Rf]:R,[Of]:g}},xf=1,Hf=0,jf=32,Kf=512,Gf=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Ff=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Kf)return;const n=t.split(",");if(!(n.length>jf)){for(const o of n)if(!Gf.test(o.trim()))return;return t}},Wf=e=>{const t=Ni(e.headers.get("traceparent"));if(t===void 0)return;const n=Ff(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},pr=(e,t={})=>{const n=Wf(e),o=t.trustInbound===!0?n:void 0,r=Je(8),s=o?.traceId??Je(16),a=Ci(t.sampling,o===void 0?r:s),{rayId:d}=t,c=a.isTraced&&(o===void 0||o.sampled);return{decision:a,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:c,spanId:r,traceFlags:c?xf:Hf,traceId:s,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState},...d===void 0?{}:{rayId:d}}}},mr=(e,t)=>{t.traceparent=$r(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[xc]=e.rayId)},Qf=(e,t)=>{let n;return()=>{if(n===void 0){const o=Ui(e),r=t===void 0?void 0:t.cf;n=ki(Pi(o),Di(o,r))}return n}},Vf="/_lunora/admin/scheduled",zf="/_lunora/admin/scheduled/status",Jf="/_lunora/admin/scheduled/ws",Yf="/_lunora/admin/scheduled/cancel",Xf="/_lunora/admin/scheduled/dead",Zf="/_lunora/admin/scheduled/history",qf="/_lunora/admin/scheduled/cron-runs",ep="/_lunora/admin/scheduled/job",tp="/_lunora/admin/scheduled/dead/retry",np="/_lunora/admin/scheduled/dead/cancel",op="/_lunora/admin/scheduled/pool/release",rp=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:r}=e,s=(p,m)=>g=>{if(g.method!=="GET")throw new l(`${m} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const R=new URL(g.url).searchParams.get("cursor"),E=R===null||R===""?"":`?cursor=${encodeURIComponent(R)}`;return o(g).fetch(new Request(`https://scheduler.internal${p}${E}`,{method:"GET"}))},a=p=>{if(p.method!=="GET")throw new l("Scheduled-job endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const m=o(p),g=new URL(p.url).searchParams.get("id");if(g===null||g==="")throw new l("Scheduled-job endpoint requires an `id`",{code:"BAD_REQUEST",status:400});return m.fetch(new Request(`https://scheduler.internal/get?id=${encodeURIComponent(g)}`,{method:"GET"}))},d=(p,m,g=m)=>async R=>{if(R.method!=="POST")throw new l(`${g} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const E=o(R),S=await we(R,m);if(typeof S?.id!="string"||S.id==="")throw new l(`${m} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return E.fetch(new Request(`https://scheduler.internal${p}`,{body:JSON.stringify({id:S.id}),headers:{"content-type":"application/json"},method:"POST"}))},c=async p=>{if(p.method!=="POST")throw new l("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=o(p),g=await we(p,"Scheduled pool-release");if(typeof g?.pool!="string"||g.pool==="")throw new l("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const R=typeof g.id=="string"&&g.id!==""?g.id:void 0;return m.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(R===void 0?{pool:g.pool}:{id:R,pool:g.pool}),headers:{"content-type":"application/json"},method:"POST"}))},h=async p=>{if(p.headers.get("Upgrade")!=="websocket")throw new l("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(p))throw new l("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const m=n();return ve(m,r).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Yf]:d("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[qf]:s("/cron/runs","Cron-runs"),[np]:d("/dead/cancel","Scheduled dead-letter action"),[Xf]:s("/dead","Scheduled dead-letter"),[tp]:d("/dead/retry","Scheduled dead-letter action"),[Zf]:s("/history","Scheduled-history"),[ep]:a,[Vf]:s("/list","Scheduled-list"),[op]:c,[zf]:s("/status","Scheduler-status"),[Jf]:h}},wr=new WeakMap,aa=async(e,t)=>{const n=wr.get(e);if(n!==void 0)return n;const o=await e.fetch(new Request(new URL("/",t.url),{method:"HEAD"})),r=o.ok?o.headers.get("ETag")??void 0:void 0;return await o.body?.cancel(),r!==void 0&&wr.set(e,r),r},ia=e=>e.headers.get("Sec-Fetch-Mode")==="navigate"||(e.headers.get("Accept")??"").includes("text/html"),sp=async(e,t)=>{const n=await e.fetch(t);if(n.status>=300&&n.status<400&&n.status!==304)return n;if(!n.ok&&n.status!==304){await n.body?.cancel();return}const o=n.headers.get("ETag");if(!(o!==null&&new URL(t.url).pathname!=="/"&&o===await aa(e,t))||ia(t))return n;await n.body?.cancel()},ap=async(e,t)=>{if(!(t.method!=="GET"&&t.method!=="HEAD"))try{return await sp(e,t)}catch(n){console.error(`[lunora] spaAssets binding failed for ${t.method} ${new URL(t.url).pathname}:`,n);return}},ip=async(e,t)=>{if(!(t.method!=="GET"&&t.method!=="HEAD"||!ia(t)))try{const n=await e.fetch(t),o=n.ok||n.status===304?n.headers.get("ETag")??void 0:void 0;if(o!==void 0&&o===await aa(e,t))return n;await n.body?.cancel()}catch(n){console.error(`[lunora] spaAssets binding failed reading the shell for ${new URL(t.url).pathname}:`,n)}},ca="/_lunora/admin/sql-migrations",da=8*1048576,cp=e=>{if(!Array.isArray(e))throw new l("SQL migration request `files` must be an array",{code:"BAD_REQUEST",status:400});return e.map(t=>{const n=t;if(n===null||typeof n!="object"||typeof n.name!="string"||typeof n.sql!="string")throw new l("each SQL migration file needs a string `name` and a string `sql`",{code:"BAD_REQUEST",status:400});return{name:n.name,sql:n.sql}})},dp=e=>{const t=e.baselineThrough;if(t!==void 0&&typeof t!="string")throw new l("SQL migration `baselineThrough` must be a file name",{code:"BAD_REQUEST",status:400});return t},mn=(e,t)=>{if(e[t]!==void 0&&typeof e[t]!="boolean")throw new l(`SQL migration \`${t}\` must be a boolean`,{code:"BAD_REQUEST",status:400});return e[t]===!0},up=e=>{if(e===null||typeof e!="object"&&typeof e!="function")return!1;const t=e;return typeof t.prepare=="function"&&typeof t.batch=="function"&&typeof t.dump=="function"},lp=e=>typeof e=="object"&&e!==null&&Object.values(e).some(t=>up(t)),hp=e=>{const t=async(n,o)=>{const r=ke(n,["POST"]);if(r)return r;if(!e.isAdmin(n))throw new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const s=e.applySqlMigrations;if(s===void 0)throw lp(o)?new l("the worker has a D1 binding but no applySqlMigrations option, so the SQL files cannot run",{code:"MISCONFIGURED",status:500}):new l("SQL migrations run against the D1 global plane, and this worker has none to run them on",{code:"SQL_MIGRATIONS_NOT_CONFIGURED",status:400});e.assertAdmin(n);const a=await ae(n,da),d=dp(a),c=await s({additiveOnly:!e.isRootAdmin(n),baseline:mn(a,"baseline"),...d===void 0?{}:{baselineThrough:d},confirmDestructive:mn(a,"confirmDestructive"),dryRun:mn(a,"dryRun"),files:cp(a.files)});return Response.json(c,{headers:{"cache-control":"no-store"}})};return{[ca]:t}},fp="/_lunora/scheduled",ua="/_lunora/queue",la=16*1048576,pp=e=>{const{assertAdmin:t,dispatchScheduled:n,isPaused:o,queueHandler:r,queueHandlerHolds:s}=e,a=async(c,h,p)=>{if(t(c),c.method!=="POST")throw new l("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await we(c,"Scheduled tick"),g=typeof m?.cron=="string"?m.cron:"";if(g==="")throw new l("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},h,p),Response.json({cron:g,ok:!0})},d=async(c,h,p)=>{if(t(c),c.method!=="POST")throw new l("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new l("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await we(c,"Queue dispatch",la);if(!Array.isArray(m?.messages))throw new l("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof m.queue=="string"?m.queue:"",R=m.messages.filter(_=>typeof _=="object"&&_!==null&&typeof _.id=="string").map(_=>({...typeof _.attempts=="number"&&Number.isInteger(_.attempts)&&_.attempts>0?{attempts:_.attempts}:{},body:_.body,id:_.id})),E=await o();if(E&&!s)return Response.json({retry:R.map(_=>_.id),retryDelays:Object.fromEntries(R.map(_=>[_.id,On]))});const S=await r({messages:R,queue:g},h,p,E?{holdSeconds:On}:void 0);return Response.json({retry:S?.retry??[],...S?.retryDelays===void 0?{}:{retryDelays:S.retryDelays}})};return{[ua]:d,[fp]:a}},mp=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Nn={mtls:e=>mp(e,"tlsClientAuth","certVerified")==="SUCCESS"},wp=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Nn,e)?Nn[e]:void 0)??(()=>!1),gp=e=>typeof e=="string"&&Object.hasOwn(Nn,e),yp=e=>{const t=gp(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},_p="/_lunora/admin/vector/indexes",bp="/_lunora/admin/vector/query",Sp=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async s=>{Y(s,"GET","Vector-indexes");const a=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await a.listIndexes()},{headers:{"content-type":"application/json"},status:200})},r=async s=>{Y(s,"POST","Vector-query");const a=n(s,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(a.queryIndex===void 0)throw new l("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const c=await t(s);if(typeof c.name!="string"||c.name==="")throw new l("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof c.text!="string"||c.text==="")throw new l("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(c.topK!==void 0&&(typeof c.topK!="number"||!Number.isInteger(c.topK)||c.topK<1))throw new l("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const h=await a.queryIndex({name:c.name,text:c.text,topK:c.topK});return Response.json(h,{headers:{"content-type":"application/json"},status:200})};return{[_p]:o,[bp]:r}},xt=async e=>await e===!0,ha=async(e,t,n,o=!1,r)=>{if(n.includes(Ft)||n.includes(Wt))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!o)if(e.authorizeShard){if(!await xt(e.authorizeShard({functionPath:r,identity:t,shardKey:n})))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else n!==e.defaultShard&&e.guardUnauthenticatedShardAccess("shard")},Ep=async(e,t,n,o)=>{if(e.authorizeFanOut){if(!await xt(e.authorizeFanOut(o,t.table,n)))throw new l("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(n.startsWith("__lunora_relation__:"))throw new l("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new l("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});e.guardUnauthenticatedShardAccess("fan-out")},Ap=async(e,t,n)=>{if(e.assertAgentRunOnDefaultShard(t.functionPath,t.fanOut?void 0:t.shardKey??e.defaultShard),!(!t.fanOut&&t.functionPath.startsWith("__lunora_admin__:"))){if(t.fanOut){await Ep(e,t.fanOut,t.functionPath,n);return}await ha(e,n,t.shardKey??e.defaultShard,!1,t.functionPath)}},Tp="/_lunora/admin/workflows/instances",vp="/_lunora/admin/workflows/instance",Rp="/_lunora/admin/workflows/status",Op="/_lunora/admin/workflows/create",Ip="/_lunora/admin/workflows/event",Np={complete:!0,errored:!0,paused:!0,queued:!0,rollingBack:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},kp=e=>e!==null&&Object.hasOwn(Np,e)?e:void 0,gr=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},wn=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new l(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},St=()=>{throw new l("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Dp=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(c,h,p)=>{Y(c,"GET","Workflows instances"),t(c);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=wn(p,"name"),R=kp(p.searchParams.get("status"));return Response.json(await m.listInstances({page:gr(p,"page"),perPage:gr(p,"perPage"),status:R,workflowName:g}))},r=async(c,h,p)=>{Y(c,"GET","Workflows instance"),t(c);const m=n(h);return m?Response.json(await m.getInstance({instanceId:wn(p,"id"),workflowName:wn(p,"name")})):St()},s=async(c,h)=>{Y(c,"POST","Workflows status"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new l("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:g}=m;if(g!=="pause"&&g!=="restart"&&g!=="resume"&&g!=="terminate")throw new l("Workflows status action must be one of: pause, restart, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:g,instanceId:m.id,workflowName:m.name}))},a=async(c,h)=>{Y(c,"POST","Workflows create"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows create");if(!Ro(m))throw new l("Workflows create body must be a JSON object",{code:"BAD_REQUEST",status:400});const g=m;if(typeof g.name!="string"||g.name==="")throw new l("Workflows create action requires a string `name`",{code:"BAD_REQUEST",status:400});if(g.id!==void 0&&(typeof g.id!="string"||g.id===""))throw new l("Workflows create action `id`, when given, must be a non-empty string",{code:"BAD_REQUEST",status:400});return Response.json(await p.createInstance({instanceId:g.id,params:g.params,workflowName:g.name}))},d=async(c,h)=>{Y(c,"POST","Workflows event"),t(c);const p=n(h);if(!p)return St();const m=await we(c,"Workflows event");if(!Ro(m))throw new l("Workflows event body must be a JSON object",{code:"BAD_REQUEST",status:400});const g=m;if(typeof g.name!="string"||g.name===""||typeof g.id!="string"||g.id==="")throw new l("Workflows event action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});if(typeof g.type!="string"||g.type==="")throw new l("Workflows event action requires a string `type`",{code:"BAD_REQUEST",status:400});return Response.json(await p.sendEvent({eventType:g.type,instanceId:g.id,payload:g.payload,workflowName:g.name}))};return{[vp]:r,[Tp]:o,[Rp]:s,[Op]:a,[Ip]:d}},yr="lunora",kn="lunora.bearer.",Pp=/^[!-~]+$/u,Up=e=>{if(e.startsWith(kn))try{const t=new TextDecoder("utf-8",{fatal:!0}).decode(Cn(e.slice(kn.length)));return Pp.test(t)?t:void 0}catch{return}},_r=e=>{const t=(e.headers.get("sec-websocket-protocol")??"").split(",").map(o=>o.trim()).filter(o=>o.length>0);let n;for(const o of t)n??=Up(o);return{forwarded:t.filter(o=>!o.startsWith(kn)),token:n}},br=(e,t)=>{if(t.token===void 0||e.headers.has("authorization"))return e;const n=new Headers(e.headers);return n.set("authorization",`Bearer ${t.token}`),new Request(e,{headers:n})},Sr=(e,t)=>{const n=new Headers(e);return t.forwarded.length>0?n.set("sec-websocket-protocol",t.forwarded.join(", ")):n.delete("sec-websocket-protocol"),n},Er=(e,t)=>{const{webSocket:n}=t;if(t.status!==101||!n||!e.forwarded.includes(yr))return t;const o=new Headers(t.headers);o.set("sec-websocket-protocol",yr);const r={headers:o,status:101,webSocket:n};return new Response(null,r)},Cp={[ra]:sa,[ua]:la,[ca]:da,[Ki]:$e},Lp="https://queue.lunora.internal",Ar=()=>({publish:()=>Promise.reject(new l("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),Mp=async(e,t)=>{const n=new l(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let o;try{o=await e.json()}catch{return n}const r=o?.error;return typeof r?.code!="string"||e.status<400?n:new l(typeof r.message=="string"?r.message:`ctx.live.publish to "${t}" was refused`,{code:r.code,status:e.status})},Dn="/_lunora/rpc",fa="/_lunora/rpc-batch",pa="/_lunora/ws",$p=new Set([fa,Dn,pa]),it=(e,t,n)=>({resourceAttributes:Qf(e,t),...n===void 0?{}:{waitUntil:n}}),gn=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Tr=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),yn=(e,t)=>{const{method:n}=e,o=e.headers.get("user-agent")??void 0,r=jc(e.headers.get(Bc)),s=r===void 0?{}:{rayId:r};let a;try{a=t??new URL(e.url)}catch{return{method:n,...s,userAgent:o}}const d=a.port===""?void 0:Number(a.port);return{host:a.hostname,method:n,path:a.pathname,port:Number.isNaN(d)?void 0:d,...s,scheme:a.protocol.replace(":",""),userAgent:o}},vr="/_lunora/voice/",Bp="/_lunora/admin/cron-jobs/run",xp="/_lunora/admin/ws-token",Hp="__lunora_admin__:verifyAdminToken",jp="__lunora_admin__:listAdminTokens",ma="/_lunora/admin/",Ht="/_lunora/",Kp="/_lunora/migrate",Gp="/_lunora/status",jt="/__lunora/advisor-procedures",Fp=e=>typeof e=="object"&&e!==null&&"fetch"in e&&typeof e.fetch=="function",Wp="__lunora_admin__",Qp=e=>e.startsWith(ma)||e===Kp||e===jt,Et=e=>{if(qc(e))throw new l("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Rr=(e,t)=>{const n=e.headers.get(So);if(n===null)return;const o=Ii(n);if(o===void 0)throw new l(`malformed ${So} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new l("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},Or="/api/auth",Vp="__lunora_admin__:recordAuthEvent",zp="__lunora_admin__:recordImportAudit",Jp="__lunora_admin__:listPushSubscriptions",Yp=["/sign-in","/sign-up","/callback"],Xp=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Yp.some(r=>o===r||o.startsWith(`${r}/`))},Ir=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},At=(e,t,n,o)=>{const r=Ur(n),s=r?n.code:"INTERNAL_SERVER_ERROR",a=r?n.status:500,{message:d,name:c,stack:h}=Si(n),p=Ei(n,{capped:!1});return{durationMs:t,error:{code:s,message:d,name:c,status:a,...h===void 0?{}:{stack:h},...p===void 0?{}:{internal:p}},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},wa=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ga=({identity:e})=>e!==null&&Ri(wa(e)),Nr=e=>{if(ga(e))throw new l("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},kr=e=>{if(!ga(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Dr=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Zp=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},je=new WeakMap,qp=async(e,t,n,o,r=je.get(e),s=new URL(e.url).origin)=>{const a={"content-type":"application/json"},d=e.headers.get("authorization"),c=e.headers.get("cookie"),h=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),g=e.headers.get("x-lunora-client-seq"),R=e.headers.get("x-lunora-base-seq");d&&(a.authorization=d),c&&(a.cookie=c),h&&(a["x-d1-bookmark"]=h),p&&(a["x-lunora-mutation-id"]=p),m&&(a["x-lunora-client-id"]=m),g&&(a["x-lunora-client-seq"]=g),R&&(a["x-lunora-base-seq"]=R);const E=jr(e.headers,o);if(E&&(a["x-lunora-client-ip"]=E),a["x-lunora-origin"]=s,!n)return{claims:null,headers:a,identity:null,userId:null};const S=await n(e,t,r);if(!S||typeof S.userId!="string"||S.userId.length===0)return{claims:null,headers:a,identity:null,userId:null};a["x-lunora-userid"]=Oi(S.userId);const _=wa(S);_!==void 0&&(a["x-lunora-identity-exp"]=String(_));const{userId:b,...O}=S,A=Object.keys(O).length>0?O:null;return A&&(a["x-lunora-identity"]=bi(A)),{claims:A,headers:a,identity:S,userId:b}},em=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),tm=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new l("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new l("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new l("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!em.has(n.kind))throw new l("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new l("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new l("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},_n=(e,t)=>e?.[t],nm=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},bn=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new l("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new l(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},om=new Set(["args","functionPath","shardKey"]),rm=(e,t)=>t===void 0&&Object.keys(e).every(n=>om.has(n)),sm=async e=>{const t=await Hr(e);let n;try{n=JSON.parse(t)}catch{throw new l("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new l("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&xr(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new l("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const r=n,s=tm(r.fanOut),a=r.args??{};if(s&&r.functionPath.startsWith("__lunora_relation__:")){const d=a.table;if(typeof d=="string"&&d!==s.table)throw new l("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});a.table=s.table}return{args:a,fanOut:s,forwardBody:rm(n,s)?t:void 0,functionPath:r.functionPath,shardKey:r.shardKey}},Tt=new Map,am=5e3,im=4096,cm=async(e,t)=>{const n=Date.now(),o=Tt.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Tt.delete(t);let r=0;try{const s=await ve(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(s.ok){const a=await s.json();typeof a.relayCount=="number"&&a.relayCount>0&&(r=Math.floor(a.relayCount))}}catch{r=0}return kt(Tt,im),Tt.set(t,{expiresMs:n+am,relayCount:r}),r},Sn=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ze=(e,t,n,o=JSON.stringify({args:t,functionPath:e}),r)=>new Request("https://shard.internal/rpc",{body:o,headers:n,method:"POST",...r===void 0?{}:{signal:r}}),dm=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ya=(e,t)=>{for(const n of dm){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},En=e=>e.headers.get("Upgrade")?.toLowerCase()==="websocket",Pn=(e,t)=>Jr(e.headers.get("authorization"))!==void 0&&!Dt(e,t),Pr=(e,t,n)=>{const o=new Headers(e.headers),r=[...o.keys()];for(const s of r)s.startsWith("x-lunora-")&&o.delete(s);return Pn(e,n)&&o.delete("authorization"),ya(o,t),o},vt=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:wd(t,n)},um=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Ji(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return on(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return on(`queue:${e}`,!0);if(typeof n.connectionString=="string")return on(`hyperdrive:${e}`,!0)},lm=e=>{for(const t of Object.keys(e??{})){const n=t.slice(t.indexOf(" ")+1);if(n===jt)throw new l(`route "${t}" is the framework's advisor endpoint, which carries its own admin gate — pick a different path.`,{code:"MISCONFIGURED",status:500});if(n.startsWith(Ht))throw new l(`route "${t}" is under the reserved ${Ht} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})}},hm=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new l("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},fm=e=>e.status===409&&e.headers.get(Cc)==="1",_a=e=>{hm(e);const t=wp(e.trustInboundTraceContext),n=yp(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",r=(i,u)=>{if(ed(i,u,o))throw new l(td,{code:"BAD_REQUEST",status:400})},s=e.queryCoordinator??qi({registry:ec(e.resolveTableSharding,o)}),a=Yi(e.resolveIdentity,e.identity),d=gt(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:gt(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([i,u])=>[i,gt(u,e.jurisdiction)]));let p=!1;const m=i=>{if(i===void 0||e.jurisdiction===void 0)return i;p||(p=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(i,u,f,w=e.shardRegion?.(u))=>ve(i,u,m(w)).fetch(f);let R;const E=()=>e.adminToken??R;let S;const _=i=>{const u=i??{};if(S??=Sn(i,e.shardDO),R!==void 0||e.adminToken!==void 0)return;const f=u.LUNORA_ADMIN_TOKEN;typeof f=="string"&&f.length>0&&(R=f)},b=new WeakMap,O=i=>Dt(i,E())||b.has(i),A=i=>{const u=b.get(i);return Dt(i,E())||u!==void 0&&u.tokenName===void 0},U=i=>{if(!(A(i)||(b.get(i)?.scopes??[]).includes("migrations")))throw O(i)?new l("this named admin token has no `migrations` scope, so it cannot run SQL migrations. Mint one with `lunora admin-token create <name> --scope migrations`.",{code:"ADMIN_SCOPE_REQUIRED",status:403}):new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},v=async(i,u)=>{const f=E();if(f===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const w=await g(d,o,ze(i,u,{authorization:`Bearer ${f}`,"content-type":"application/json"})),y=await w.json();if(!w.ok||y.error!==void 0)throw new l(y.error?.message??"admin token store unavailable",{code:y.error?.code??"SHARD_UNAVAILABLE",status:w.status});return y.result},x=e.adminRevocations===void 0?void 0:yd(gt(e.adminRevocations,e.jurisdiction),E),W=Nd({listNames:async()=>{const{tokens:i}=await v(jp,{});return i.map(u=>u.name)},lookup:async(i,u)=>{try{const f=await v(Hp,{digest:u,name:i});if(f.ok!==!0)return{live:!1,nameKnown:f.known!==!1};if(x===void 0||typeof f.createdAt!="number")throw new l("the admin revocation store is not available",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});if(await x.isRevoked(i,f.createdAt))return{live:!1,nameKnown:!0};const w=Array.isArray(f.scopes)?f.scopes.filter(Zr):[];return typeof f.expiresAt=="number"?{expiresAt:f.expiresAt,live:!0,scopes:w}:{live:!0,scopes:w}}catch(f){return console.error(`[lunora] admin token store lookup for "${i}" failed: ${Ur(f)?f.code:String(f)}`),{live:!1,nameKnown:!0,transient:!0}}}}),X=async i=>{if(b.has(i))return;const u=Pn(i,E())?await W.verify(i.headers.get("authorization")):void 0;if(u!==void 0){b.set(i,{scopes:u.scopes,tokenName:u.name});return}if(e.adminGate!==void 0)try{await xt(e.adminGate(i,je.get(i)))&&b.set(i,{})}catch{}},se=async(i,u,f,w={})=>{const y=await qp(i,u,f,e.trustedClientIpHeader,w.executionContext,w.url?.origin);if(e.functions!==void 0&&(y.headers[Mr]=Lr),y.headers.authorization!==void 0&&Pn(i,E())){delete y.headers.authorization;const T=b.get(i)?.tokenName;if(T!==void 0){const D=i.headers.get("authorization"),P=async()=>{const k=E(),I=k===void 0?void 0:await W.verify(D);if(k===void 0||I?.name!==T)return;const N=Date.now();return yc(k,T,N,Math.min(Math.max(I.until,N+mc),I.expiresAt??Number.POSITIVE_INFINITY))},L=await P();L!==void 0&&(y.headers[Rt]=L),tc(y.headers,async({[Rt]:k,...I})=>{const N=await P();return N===void 0?I:{...I,[Rt]:N}})}}return y},Oe=async(i,u,f,w)=>Nr(await se(i,u,f,w)),Ie=async(i,u)=>{const f=await se(i,u,e.resolveIdentity),w=b.get(i);if(w!==void 0&&w.tokenName===void 0&&f.headers.authorization===void 0){const y=E();y!==void 0&&(f.headers.authorization=`Bearer ${y}`)}return f};let C=!1,V=!1;const G=()=>{V||(V=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},M=i=>{if(!e.allowUnauthenticatedShardAccess){const u=i==="fan-out"?"authorizeFanOut":"authorizeShard";throw new l(`${i} access is default-denied: configure \`${u}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${i} access (relying solely on per-row RLS).`,{code:i==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}C||(C=!0,console.warn([`[lunora] SECURITY: serving ${i} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},Q={assertAgentRunOnDefaultShard:r,get authorizeFanOut(){return e.authorizeFanOut===void 0?void 0:(i,u,f)=>e.authorizeFanOut?.(i,u,f)??!1},get authorizeShard(){return e.authorizeShard===void 0?void 0:i=>e.authorizeShard?.(i)??!1},defaultShard:o,guardUnauthenticatedShardAccess:M},j=(i,u,f=!1,w)=>ha(Q,i,u,f,w),q=Bf({defaultShard:o,forwardToShard:g,isAdmin:O,queryCoordinator:s,resolveForwardContext:Ie,shardDO:d,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(i=>e.resolveTableSharding?.(i)?.mode.kind==="shardBy")}),ee=async(i,u,f,w,y)=>{const{__lunoraLive:T,topic:D}=u,P=w?.shardKey??o;y==="trusted"?await j(null,P,!0):P!==o&&await j(y.identity,P);const L=await g(d,P,new Request(new URL($c,i),{body:JSON.stringify({data:Re(f??null),stream:T,topic:D}),headers:{"content-type":"application/json"},method:"POST"}));if(!L.ok)throw await Mp(L,D)},ie=async(i,u,f,w,y,T,D)=>{Et(i),r(i,f);const P=ud({forwardedIdentity:y,mutationId:w,scheduledFor:D,traceparent:T});return g(d,f,ze(i,u,P))},ce=async(i,u,f,w,y)=>{const T=fd(f.env,f.context?.exports,i,["create"]);if(T===void 0)throw new l(`${w} targets workflow "${i}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(Ec(u))throw new l(`${w} params ${Ac}`,{code:"BAD_REQUEST",status:400});try{await T.create(y===void 0?{params:u}:{id:y,params:u})}catch(D){if(!Mc(D))throw D}},te=(i,u,f)=>{const w=typeof f=="string"&&f.length>0?f:void 0;return e.agentWorkflows!==void 0&&!e.agentWorkflows.includes(i)?u:Yc(u,w)},Ne=async(i,u,f,w,y)=>{if(i.workflow){await ce(i.workflow,i.args??{},{context:f,env:u},`cron job "${i.name}"`);return}if(i.functionPath===void 0)throw new l(`cron job "${i.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const T=await ie(i.functionPath,i.args??{},i.shardKey??o,void 0,void 0,w,y);if(!T.ok)throw new l(`cron job "${i.name}" (${i.functionPath}) failed with shard status ${String(T.status)}`,{code:"CRON_JOB_FAILED",status:500})},J=i=>{if(!O(i))throw new l("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ue=i=>{if(J(i),!A(i))throw new l("this admin endpoint requires the root admin token; named admin tokens cannot use it",{code:"ADMIN_ROOT_REQUIRED",status:403})},Ue=(i,u,f)=>{if(J(i),u===void 0)throw new l(f.message,{code:f.code,status:400});return u},nt=()=>c===void 0?void 0:ve(c,e.schedulerInstanceName??"default"),he=yh({assertAdmin:J,isAdmin:async i=>{await X(i);const u=i.headers.get("upgrade")?.toLowerCase()==="websocket";return O(i)||u&&await vt(i,E())},instanceStub:i=>c===void 0?void 0:ve(c,i),stub:nt}),eo=async()=>(await he.read()).paused,Sa=async(i,u,f,w,y,T,D)=>{const P=e.cronJobs?.[i];if(!P)return 0;const L=nt();for(const k of P){const I=await or(L,k.name);if(!I.skip)try{await Ne(k,u,f,T,D),await _t(L,k.name,I)}catch(N){w.push(y(N)),await _t(L,k.name,I,N)}}return P.length},Ea=async(i,u,f)=>{if(J(i),Y(i,"POST","cron-jobs run"),!e.cronJobs)throw new l("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const w=await ae(i),y=typeof w.name=="string"?w.name:"";if(y==="")throw new l("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const T=Object.values(e.cronJobs).flat().find(L=>L.name===y);if(!T)throw new l(`no cron job named "${y}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});const D=nt(),P=await or(D,T.name);if(P.skip&&P.reason==="paused")throw new l(`cron job "${y}" was not run: the deployment is paused`,{code:"DEPLOYMENT_PAUSED",status:503});if(P.skip)throw new l(`cron job "${y}" is already running`,{code:"CRON_JOB_IN_FLIGHT",status:409});try{await Ne(T,u,f)}catch(L){throw await _t(D,T.name,P,L),L}return await _t(D,T.name,P),Response.json({name:y,ran:!0},{status:200})},Aa=i=>{const{attempt:u,dedupKey:f,id:w,pool:y}=i;if(!c||typeof y!="string"||typeof u!="string"||typeof f!="string"||typeof w!="string")return()=>{};const T=typeof i.instanceName=="string"&&i.instanceName.length>0?i.instanceName:"default",D=JSON.stringify({attempt:u,dedupKey:f,id:w,pool:y}),P=setInterval(()=>{ve(c,T).fetch(new Request("https://scheduler.internal/pool/renew",{body:D,headers:{"content-type":"application/json"},method:"POST"})).then(async L=>{if(!L.ok)throw L.status<500&&clearInterval(P),new Error(`SchedulerDO /pool/renew answered ${String(L.status)}`);(await L.json()).renewed===!1&&clearInterval(P)}).catch(L=>{console.warn(`[lunora] pooled job "${w}" could not renew its slot in pool "${y}": ${L instanceof Error?L.message:String(L)}`)})},Uc/3);return()=>{clearInterval(P)}},to=async i=>{const u=typeof i.pool=="string"&&i.pool.length>0?i.pool:void 0;if(!u||!c||typeof i.id!="string")return;const f=typeof i.instanceName=="string"&&i.instanceName.length>0?i.instanceName:"default";try{await ve(c,f).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({attempt:i.attempt,dedupKey:i.dedupKey,id:i.id,pool:u}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Ta=async(i,u,f)=>{Y(i,"POST","Scheduler dispatch");const w=await Hr(i),y=u??{},T=typeof y.LUNORA_SCHEDULER_SECRET=="string"?y.LUNORA_SCHEDULER_SECRET:void 0,D=e.adminToken??(typeof y.LUNORA_ADMIN_TOKEN=="string"?y.LUNORA_ADMIN_TOKEN:void 0);if(!await id(i,w,{adminToken:D,schedulerSecret:T}))throw new l("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let L;try{L=JSON.parse(w)}catch{throw new l("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=L??{},I=k.args??{},N=typeof k.id=="string"&&k.id.length>0?k.id:void 0;if(k.dedupKey!==void 0&&!Pc(k.dedupKey))throw new l(`Scheduler dispatch: ${Dc}`,{code:"INVALID_INPUT",status:400});const B=k.dedupKey??N;if(typeof k.workflow=="string"&&k.workflow.length>0)return await ce(k.workflow,te(k.workflow,I,k.shardKey),{context:f,env:u},"scheduled workflow",B),await to(k),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new l("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const F=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:o,z=ld(i),K=typeof k.scheduledFor=="number"?k.scheduledFor:void 0,Z=Aa(k),fe=await ie(k.functionPath,I,F,B,z,i.headers.get("traceparent")??void 0,K).finally(Z);return fm(fe)||await to(k),fe},va=Zu({assertAdmin:J,getReader:()=>e.authAuditReader}),Ra=el({assertAdmin:ue,getMove:()=>e.authJurisdictionMove}),Zt={assertAdmin:J,resolveToolHeaders:nc,defaultShardKey:()=>o,forwardToShard:async(i,u)=>{const f=await Ie(i,u),w=E();return b.get(i)?.tokenName!==void 0||(w===void 0?delete f.headers.authorization:f.headers.authorization=`Bearer ${w}`),{forward:ao,headers:f.headers}},getBinding:i=>e.aiChatBinding??_n(i,"AI"),optInLevel:i=>bc(e.aiOptInLevel??_n(i,"LUNORA_AI_OPT_IN")),approvalSecret:i=>{const u=_n(i,"LUNORA_AI_APPROVAL_SECRET");return typeof u=="string"?u:void 0}},Oa=$u(Zt),Ia=Bu(Zt),Na=xu(Zt),ka=async(i,u)=>{J(i);const f=e.notifySubscriptionStore;if(f===void 0)return Response.json({result:Re({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const w=u?.kind,y=u?.userId,T=u?.limit,D=w==="fcm"||w==="web-push"?w:void 0,P=typeof y=="string"&&y!==""?y:void 0,L=typeof T=="number"&&Number.isFinite(T)?Math.trunc(T):0,k=L>0?Math.min(L,1e3):1e3,N=(await f.list({kind:D,limit:k,userId:P})).filter(B=>D!==void 0&&B.kind!==D?!1:P===void 0||(B.userId??null)===P).map(({keys:B,token:F,...z})=>z);return Response.json({result:Re({subscriptions:N})},{headers:{"content-type":"application/json"},status:200})},Da=async(i,u,f)=>{if(u.fanOut)return;if(await(u.functionPath.startsWith(Wp)?ho(i,ma):Promise.resolve()),u.functionPath===Xu)return va(i,u.args??{});if(u.functionPath===Jp)return ka(i,u.args);if(u.functionPath===ku){const y=u.args??{};return Oa(i,y.shardKey===void 0&&u.shardKey!==void 0?{...y,shardKey:u.shardKey}:y,f)}if(u.functionPath===Du)return Ia(i,u.args??{},f);const w=Na(i,u.functionPath,f);return w!==void 0?w:Ra(i,u.functionPath,u.args??{})},no=i=>async u=>{const f=await g(d,o,ze(zp,u,i));if(!f.ok)throw new l(`the default shard answered HTTP ${String(f.status)}`,{code:"INTERNAL",status:500})},ht=(i,u)=>({assertAuthSectionAllowed:u,coordinator:s,headers:i,namespace:d,options:{...e,adminToken:E()},recordAudit:no(i)}),Pa=lh({applyGlobals:e.applyGlobals,assertAdmin:J,assertRootAdmin:ue,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:Ie,shardDO:d,exportSectionRows:i=>jl(e,i),prepareExportRows:async(i,u)=>ps(e,s,i,u,d),importSession:{abort:async(i,u)=>Ot(ht(i,()=>{}),u),commit:async(i,u,f)=>na(ht(i,f),u),replace:async(i,u,f,w)=>nf(i,ht(u,w),f),stage:async(i,u,f,w,y)=>qs(i,ht(u,y),f,w)},streamingImport:async(i,u,f,w,y)=>Vh(i,{...e,adminToken:E()},s,u,d,f,w,async T=>no(await u())(T),y),syncGlobals:e.syncGlobals}),Ua=hp({applySqlMigrations:e.applySqlMigrations,assertAdmin:U,isAdmin:O,isRootAdmin:A}),qt=(i,u)=>{const f=i.searchParams.get(u);return f===null||f===""?void 0:f},en=i=>{const u=new URL(i.url),f=u.searchParams.get("limit"),w=u.searchParams.get("offset"),y=f===null?void 0:Number.parseInt(f,10),T=w===null?void 0:Number.parseInt(w,10);return{limit:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0,offset:T!==void 0&&Number.isFinite(T)&&T>=0?T:void 0}},oo=()=>{if(c===void 0)throw new l("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ca=rp({checkWsAdmin:async i=>A(i)||vt(i,E()),requireSchedulerNamespace:oo,resolveSchedulerStub:i=>(J(i),ve(oo(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),La=Dp({assertAdmin:J,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ma=ji({assertAdmin:J,assertRootAdmin:ue,parsePaging:en,queryParameter:qt,readBodyBytes:Mi,requireAdminOption:Ue,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),$a=pl({options:e,readJsonBody:ae,requireAdminOption:Ue}),Ba=Sp({readJsonBody:ae,requireAdminOption:Ue,vectorIntrospector:e.vectorIntrospector}),xa=Ad({assertRootAdmin:ue,callStore:v,evict:W.evict,revocations:x,readJsonBody:ae}),Ha=Sf({kvIntrospector:e.kvIntrospector,readJsonBody:ae,requireAdminOption:Ue}),ja=Xi({logArchive:e.logArchive,readJsonBody:ae,requireAdminOption:Ue}),Ka=yf({assertAdmin:J,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:en,queryParameter:qt,requireAdminOption:Ue}),Ga=i=>{const u=[],f=d??i?.SHARD;if(f!==void 0&&u.push(zi("durable-object:default",f,o)),e.health?.disableBindingProbes!==!0)for(const[w,y]of Object.entries(i??{})){const T=um(w,y);T!==void 0&&u.push(T)}for(const w of e.health?.probes??[])u.push(w);return u},Fa=Vi({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:Ga}),Wa=(i,u)=>{const f=I=>"args"in I?{...I,args:Nt(I.args)}:I,w=e.schedulerInstanceName??"default",y=()=>ve(i,w),T=async(I,N)=>{const B=await y().fetch(new Request(`https://scheduler.internal${I}`,N));if(!B.ok)throw new l(`ctx.scheduler: SchedulerDO ${I} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},D=async(I,N)=>await T(I,{body:JSON.stringify(N),headers:{"content-type":"application/json"},method:"POST"}),P=I=>{const N=I;if(N==null)throw new l("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof N.binding=="string"&&N.binding.length>0)return{workflow:N.binding};if(typeof N.__lunoraRef=="string")return{functionPath:N.__lunoraRef};throw new l("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},L=async()=>(await Nc(async N=>T(N===void 0?"/list":`/list?cursor=${encodeURIComponent(N)}`,{method:"GET"}))).map(N=>f(N)),k=async(I,N,B={},F)=>{const z=P(N),K=F?.shardKey;if(K!==void 0&&K.length>0&&K!==o){const fe=typeof z.functionPath=="string"?z.functionPath:void 0;await j(u,K,!1,fe)}const{id:Z}=await D("/schedule",{args:_i("ctx.scheduler",String(z.functionPath??z.workflow),B),dedupKey:F?.dedupKey,scheduledFor:Math.ceil(I),retry:F?.retry,shardKey:F?.shardKey,...z});return Z};return{cancel:async I=>await D("/cancel",{id:I}),get:async I=>{const N=await T(`/get?id=${encodeURIComponent(I)}`,{method:"GET"});return N.record===void 0?null:f(N.record)},list:L,runAfter:async(I,N,B,F)=>{if(!Number.isFinite(I)||I<0)throw new l("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(Date.now()+I,N,B,F)},runAt:async(I,N,B,F)=>{if(!Number.isFinite(I))throw new l("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await k(I,N,B,F)}}},Qa=async(i,u,f)=>{const{claims:w,headers:y,identity:T,userId:D}=kr(await se(i,u,a)),P=it(u,i,N=>f.waitUntil?.(N)),L=N=>async(B,F={})=>{const z=B.__lunoraRef;if(typeof z!="string")throw new l("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Et(z),r(z,N),N!==o&&await j(T,N,!1,z);const K=await pt(i,z,Re(F),N,{...y,"x-lunora-system":"1"},P),Z=await K.json();if(Z.error)throw new l(Z.error.message??"shard RPC failed",{code:Z.error.code??"INTERNAL",status:K.status});return Nt(Z.result)},k=L(o),I=async(N,B,F={})=>{N!==void 0&&N!==o&&await j(T,N);const z=new Headers;for(const[K,Z]of Object.entries(F.headers??{}))K.toLowerCase().startsWith("x-lunora-")||z.set(K,Z);for(const[K,Z]of Object.entries(y))z.set(K,Z);return g(d,N??o,new Request(new URL(B,i.url),{headers:z,method:F.method??"GET",...F.body===void 0?{}:{body:F.body}}))};return{auth:{getIdentity:()=>Promise.resolve(w),userId:D},cache:f.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:I,forShard:N=>{const B=L(N);return{runAction:B,runMutation:B,runQuery:B}},live:e.liveStreams===!1?Ar():{publish:(N,B,F)=>ee(i.url,N,B,F,{identity:T})},runAction:k,runMutation:k,runQuery:k,...c===void 0?{}:{scheduler:Wa(c,T)},...f.waitUntil===void 0?{}:{waitUntil:f.waitUntil.bind(f)},...e.storage===void 0?{}:{storage:Sc(e.storage(u,new URL(i.url).origin))}}},tn=new WeakSet,Va=async(i,u,f)=>{const w=e.spaAssets===void 0||!f?void 0:await ap(e.spaAssets,i);return w===void 0?u:(await u.body?.cancel(),tn.add(w),w)},za=async(i,u,f,w)=>{const y=await e.authDiscoveryHandler?.(i);return y?(await Promise.all([u?.body?.cancel(),w?.body?.cancel()]),y):w!==void 0&&f?(await u?.body?.cancel(),tn.add(w),w):(await w?.body?.cancel(),Va(i,u??new Response("Not found",{status:404}),f))},Ja=async(i,u,f,w)=>{if(!e.httpRouter)return{response:void 0,unrouted:!0};let y=!1;const T=()=>{y=!0},D=await Qa(i,u,f);try{return{response:await e.httpRouter.fetch(i,{...u,__lunoraCtx:D,__lunoraShellFirst:w,__lunoraUnrouted:T},f),unrouted:y}}catch(P){return console.error("[lunora] httpRouter (SSR) handler threw:",P),{response:new Response("Internal Server Error",{status:500}),unrouted:!1}}},ro=new Set(Object.values(e.functions??{}).flatMap(i=>i.lifecycle==="socket"&&typeof i.socketPath=="string"?[i.socketPath]:[])),so=async(i,u,f)=>{if(!En(i))throw new l("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const w=Io(i,Ee);if(w)return w;const y=f.searchParams.get("shard")??o,T=_r(i),{headers:D,identity:P}=await se(br(i,T),u,a,{executionContext:je.get(i)}),L=A(i)||await vt(i,E());await j(P,y,L);const k=Sr(Pr(i,D,E()),T),I=Sn(u,e.shardDO);let N=y,B;if(I!==void 0){k.set("x-lunora-shard-binding",I);const F=ro.has(f.pathname)?0:await cm(d,y);F>0&&(N=Vc(y,Math.floor(Math.random()*F)),B=No(i))}return Er(T,await g(d,N,new Request(i,{headers:k}),B))},Ya=async(i,u,f,w)=>{Y(i,"POST","ws reauth");const y=await ae(i);if(typeof y.connectionId!="string"||y.connectionId.length===0)throw new l("connectionId is required",{code:"BAD_REQUEST",status:400});const T=w.searchParams.get("shard")??o,D=O(i)||await vt(i,E()),P=await se(i,u,a,{executionContext:f??je.get(i),url:w}),{headers:L,identity:k}=D?kr(P):Nr(P);if(k===null&&!D)throw new l("re-authenticating a socket requires a credential",{code:"UNAUTHENTICATED",status:401});await j(k,T,D);const I=new Headers({"content-type":"application/json"});ya(I,L),D&&I.set("x-lunora-admin-reauth","1");const N=Sn(u,e.shardDO);return N!==void 0&&I.set("x-lunora-shard-binding",N),g(d,T,new Request(new URL(ko,w.origin),{body:JSON.stringify({connectionId:y.connectionId}),headers:I,method:"POST"}))},Xa=async(i,u,f,w)=>{Y(i,"POST","claims fingerprint");const{headers:y,identity:T}=await Oe(i,u,a,{executionContext:f??je.get(i),url:w});if(T===null)throw new l("a claims fingerprint requires a credential",{code:"UNAUTHENTICATED",status:401});return Response.json({claims:Ic(vi(y["x-lunora-userid"]),Ti(y["x-lunora-identity"]))},{headers:{"cache-control":"no-store"}})},Za=async(i,u,f)=>{if(h===void 0)return new Response("Not found",{status:404});if(!En(i))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=Io(i,Ee);if(w)return w;let y;try{y=decodeURIComponent(f.pathname.slice(vr.length))}catch{return new Response("Unknown voice agent",{status:404})}const T=Object.hasOwn(h,y)?h[y]:void 0;if(T===void 0)return new Response("Unknown voice agent",{status:404});const D=f.searchParams.get("threadKey");if(D===null||D.length===0)return new Response("Missing threadKey",{status:400});const P=_r(i),{headers:L,identity:k}=await se(br(i,P),u,a,{executionContext:je.get(i)});if(e.authorizeShard){if(!await xt(e.authorizeShard({identity:k,shardKey:D})))throw new l("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else M("shard");const I=Sr(Pr(i,L,E()),P);return Er(P,await g(T,D,new Request(i,{headers:I})))},ft=(i,u)=>Ap(Q,i,u),qa=(i,u,f)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){G();return}if(e.functions[u]?.kind!=="query"||f.includes(Wt)||f.includes(Ft))return;const w=No(i);return w===void 0?void 0:{name:zc(f,w),region:w}},ao=async(i,u,f,w,y,T,D)=>{const P=qa(i,u,w);if(P!==void 0){const L={...y,"x-lunora-replica-read":"1",...S===void 0?{}:{"x-lunora-shard-binding":S}},k=Jc(i.headers.get("x-lunora-min-seq"));k!==void 0&&(L["x-lunora-min-seq"]=String(k));const I=await g(d,P.name,ze(u,f,L,T,D),P.region);if(I.status!==421)return I}return g(d,w,ze(u,f,y,T,D))},pt=async(i,u,f,w,y,T,D={})=>{const P=Date.now(),{observability:L,sampling:k}=e,I=yn(i,D.url),{decision:N,ignoredUpstream:B,trace:F}=pr(i,{...I.rayId===void 0?{}:{rayId:I.rayId},...k===void 0?{}:{sampling:k},trustInbound:t(i)});B&&n(i);const z={...y,[Ao]:N.keepErrors?"1":"0",[bo]:"1"};mr(F,z);try{const K=await ao(i,u,f,w,z,D.forwardBody),Z=yo(K.headers.get(_o));Ce(L,{...I,...Tr(F),durationMs:Date.now()-P,functionPath:u,ok:K.ok,shardKey:w,...K.ok?{}:{error:{...Z,code:Z?.code??"SHARD_ERROR",message:Z?.message??`shard returned ${String(K.status)}`,status:K.status}}},T,void 0,{isTraced:F.sampled,keepErrors:N.keepErrors});const fe=new Response(K.body,{headers:K.headers,status:K.status,statusText:K.statusText});return fe.headers.set("x-lunora-shard-key",w),fe.headers.delete(_o),fe}catch(K){throw Ce(L,{...I,...Tr(F),...At(u,Date.now()-P,K,{shardKey:w})},T,void 0,{isTraced:F.sampled,keepErrors:N.keepErrors}),K}},ei=i=>{if(i.fanOut&&i.shardKey)throw new l("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});i.fanOut||Et(i.functionPath)},ti=async(i,u,f,w)=>{Y(i,"POST","RPC");const y=await sm(i),T={forwardBody:y.forwardBody,url:w};nm(u,y),ei(y);const D=await Da(i,y,u);if(D!==void 0)return D;y.functionPath.startsWith("__lunora_admin__:")&&await X(i);const{headers:P,identity:L}=await Oe(i,u,a,T);Rr(i,L),await ft(y,L);const k=bn(y,e);{const I=Date.now(),{observability:N}=e,B=it(u,i,f&&(K=>f.waitUntil?.(K)));if(y.fanOut){const K=yn(i,w);try{const Z=await s.fanOut(d,{args:y.args??{},fanOut:y.fanOut,functionPath:y.functionPath,headers:P});return Ce(N,{durationMs:Date.now()-I,fanOut:{failed:Z.failed,shards:Z.ok+Z.failed,table:y.fanOut.table},functionPath:y.functionPath,...K,ok:!0},B),Response.json(Z,{headers:{"content-type":"application/json"},status:200})}catch(Z){throw Ce(N,{...At(y.functionPath,Date.now()-I,Z,{fanOut:{table:y.fanOut.table}}),...K},B),Z}}const F=y.shardKey??o,z=()=>pt(i,y.functionPath,y.args??{},F,P,B,T);return k&&e.x402Charge?e.x402Charge(i,{functionPath:y.functionPath,price:k.price},z,gn(f)):z()}},ni=async(i,u,f)=>{Y(i,"POST","RPC batch");const w=await ae(i),{calls:y}=w;if(!Array.isArray(y))throw new l("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:T,identity:D}=await Oe(i,u,a);Rr(i,D);const P=wl(y,o);for(const ne of P.values())for(const oe of ne)if(e.functions?.[oe.functionPath]?.x402)throw new l(`paid (\`.x402\`) function "${oe.functionPath}" cannot be called in a batch; dispatch it individually over ${Dn}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([ne,oe])=>oe.map(pe=>ft({args:pe.args,functionPath:pe.functionPath,shardKey:ne},D))));const{observability:L,sampling:k}=e,I=it(u,i,f&&(ne=>f.waitUntil?.(ne))),N=yn(i),{decision:B,ignoredUpstream:F,trace:z}=pr(i,{...N.rayId===void 0?{}:{rayId:N.rayId},...k===void 0?{}:{sampling:k},trustInbound:t(i)});F&&n(i);const K={isTraced:z.sampled,keepErrors:B.keepErrors},Z=ne=>{const oe={...T,"content-type":"application/json",[Ao]:B.keepErrors?"1":"0",[bo]:"1"};return mr({...z,spanId:ne},oe),oe},fe=ne=>({parentSpanId:ne,spanId:Je(8),traceFlags:z.traceFlags,traceId:z.traceId}),wt=[],nn=[],fo=(ne,oe,pe,Be)=>({body:{error:{code:pe,message:Be}},id:ne.id,status:oe}),po=(ne,oe,pe,Be,Ve)=>{for(const me of ne)Ce(L,Ve(me),I,void 0,K),wt.push(fo(me,oe,pe,Be))},wi=(ne,oe,pe,Be,Ve,me)=>{for(const ot of ne){const rt=Ve.get(ot.id),xe=rt?.status??me,He=xe<400,st=He?void 0:yo(rt?.errorDetail);Ce(L,{durationMs:Be,functionPath:ot.functionPath,...N,...fe(pe),ok:He,shardKey:oe,...He?{}:{error:{...st,code:st?.code??"SHARD_ERROR",message:st?.message??`batched call returned ${String(xe)}`,status:xe}}},I,void 0,K)}};await Promise.all([...P.entries()].map(async([ne,oe])=>{const pe=Je(8),Be=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:oe}),headers:new Headers(Z(pe)),method:"POST"}),Ve=Date.now();let me;try{me=await g(d,ne,Be)}catch(de){const at=Date.now()-Ve,{body:go}=yi(de,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});po(oe,502,go.code,go.message,gi=>({...At(gi.functionPath,at,de,{shardKey:ne}),...N,...fe(pe)}));return}const ot=Date.now()-Ve,rt=me.headers.get("x-d1-bookmark");rt&&nn.push(rt);let xe;try{xe=await me.json()}catch{const de=`shard batch returned a non-JSON response (${String(me.status)})`;po(oe,me.status,"SHARD_UNAVAILABLE",de,at=>({durationMs:ot,error:{code:"SHARD_UNAVAILABLE",message:de,status:me.status},functionPath:at.functionPath,...N,...fe(pe),ok:!1,shardKey:ne}));return}const He=Array.isArray(xe.results)?xe.results:[],st=new Set(He.map(de=>de.id));wi(oe,ne,pe,ot,new Map(He.map(de=>[de.id,de])),me.status),wt.push(...He.map(({errorDetail:de,...at})=>at));for(const de of oe)st.has(de.id)||wt.push(fo(de,me.status,"SHARD_UNAVAILABLE",`shard batch omitted result for call ${String(de.id)}`))}));const mo={"content-type":"application/json"},[wo]=nn;return nn.length===1&&wo!==void 0&&(mo["x-d1-bookmark"]=wo),Response.json({results:wt},{headers:mo,status:200})},oi=async(i,u,f,w={},y={})=>{try{const T=f.__lunoraRef;if(typeof T!="string")throw new l("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Et(T);const{headers:D,identity:P}=await Oe(i,u,a,{executionContext:y.context}),L={args:w,functionPath:T,shardKey:y.shardKey};await ft(L,P);const k=y.shardKey??o,I=it(u,i,y.waitUntil),N=()=>pt(i,T,w,k,D,I),B=bn(L,e);return B&&e.x402Charge?await e.x402Charge(i,{functionPath:T,price:B.price},N,gn(y.waitUntil?{waitUntil:y.waitUntil}:y.context)):await N()}catch(T){return To(T)}},io=async(i,u,f)=>{const{observability:w}=e,y=Date.now(),T=Je(16),D=Je(8),P=Dr(u),L=$r(T,D,!0);try{const k=await f(L);return Ce(w,{durationMs:Date.now()-y,functionPath:i,ok:!0,spanId:D,traceId:T},P),k}catch(k){throw Ce(w,{...At(i,Date.now()-y,k,{}),spanId:D,traceId:T},P),k}finally{Eo(w,P)}},ri=async(i,u,f,w,y,T)=>{if(await eo()){console.warn(`[lunora] scheduled("${u.cron}") skipped its crons handler: the deployment is paused.`);return}try{await i(u,f,w)}catch(D){y.push(T(D))}},co=async(i,u,f,w)=>{_(u);const y=[],T=I=>I instanceof Error?I:new Error(String(I)),D=e.crons?.[i.cron];D&&await ri(D,i,u,f,y,T);const P=await Sa(i.cron,u,f,y,T,w,i.scheduledTime),L=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===i.cron;if(L)try{await ul(e,s,d,E(),i)}catch(I){y.push(T(I))}if(!D&&P===0&&!L){const I=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${i.cron}") fired but no cron handler is registered for that expression. Registered: ${I.length===0?"(none)":I.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[k]=y;if(y.length===1&&k)throw k;if(y.length>1)throw new AggregateError(y,`scheduled("${i.cron}") had ${String(y.length)} failure(s)`)},si=pp({assertAdmin:J,dispatchScheduled:co,isPaused:eo,queueHandler:e.queueHandler,queueHandlerHolds:e.queueHandlerHolds===!0}),ai=async(i,u)=>{try{const f=i??{},w=e.adminToken??(typeof f.LUNORA_ADMIN_TOKEN=="string"?f.LUNORA_ADMIN_TOKEN:void 0);if(!w||w.length===0)return;await g(d,o,ze(Vp,{outcome:u},{authorization:`Bearer ${w}`,"content-type":"application/json"}))}catch{}},ii=async(i,u,f,w)=>{if(!e.authHandler)return;const y=e.authBasePath??Or,T=Ir(f.pathname,y)?$i(i):void 0;let D;try{D=await e.authHandler(T?.request??i)}catch(P){throw T?.overflowed()?new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(T?.overflowed())throw new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(D)return Xp(f.pathname,y)&&w.waitUntil?.(ai(u,D.status>=400?"fail":"ok")),D},ci=async({args:i,env:u,functionPath:f,request:w,shardKey:y,waitUntil:T})=>{xr(i,"REST");const D={functionPath:f,...y===void 0?{}:{shardKey:y}},{headers:P,identity:L}=await Oe(w,u,a);await ft(D,L);const k=y??o,I=it(u,w,T),N=()=>pt(w,f,i,k,P,I),B=bn(D,e);return B&&e.x402Charge?e.x402Charge(w,{functionPath:f,price:B.price},N,gn({waitUntil:T})):N()},uo=Li({functions:e.functions??{},invoke:ci,readJsonBody:ae,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),mt=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,di=new Set(e.liveStreamRoutes),ui=(i,u)=>{if(!mt)return;const f=`${i.method} ${u.pathname}`;if(!di.has(f))return mt[f]??mt[u.pathname]};lm(mt);const li={[Gp]:i=>i.method!=="GET"&&i.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[jt]:async(i,u)=>{Y(i,"GET","Advisor procedures"),J(i);const f=typeof u=="object"&&u!==null?Reflect.get(u,"ADVISOR_COMPANION"):void 0;if(!Fp(f))return Response.json({error:"not found"},{headers:{"cache-control":"no-store"},status:404});const w=await f.fetch(new Request(new URL(jt,i.url),{method:"GET"})),y=new Headers(w.headers);return y.set("cache-control","no-store"),new Response(w.body,{headers:y,status:w.status,statusText:w.statusText})},[pa]:(i,u,f)=>so(i,u,f),[ko]:(i,u,f,w)=>Ya(i,u,w,f),[cd]:(i,u,f,w)=>Xa(i,u,w,f),[Dn]:(i,u,f,w)=>ti(i,u,w,f),[fa]:(i,u,f,w)=>ni(i,u,w),[Xc]:(i,u,f,w)=>Ta(i,u,w),[Bp]:(i,u,f,w)=>Ea(i,u,w),[hh]:async i=>he.handleRoute(i),[xp]:async i=>{Y(i,"POST","ws-token"),ue(i);const u=E();if(u===void 0)throw new l("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const f=await md(u);return Response.json(f,{headers:{"cache-control":"no-store"}})},...q,...Pa,...Ua,...Ca,...La,...Ma,...$a,...Ba,...Ha,...xa,...ja,...Ka,...Fa,...uo,...Yu({adminActor:i=>{const u=b.get(i)?.tokenName;return u===void 0?"admin:root":`admin:token:${u}`},assertAdmin:J,assertRootAdmin:ue,clientIp:i=>jr(i.headers,e.trustedClientIpHeader),getAuditWriter:()=>e.authAuditWriter,getAuthAdmin:()=>e.authAdmin,parsePaging:en,queryParameter:qt,readJsonBody:ae})};let Ee=Oo(e.security);const hi=i=>{const u=Ee.headers.enabled?Ee.headers.csp?.htmlValue:void 0;if(u===void 0||i.headers.has("content-security-policy"))return i;const f=new Headers(i.headers);return f.set("content-security-policy",u),new Response(i.body,{headers:f,status:i.status,statusText:i.statusText})};let lo=!1;const fi=i=>{lo||(lo=!0,Ee=Oo(e.security,i??{}))},ho=async(i,u)=>{Qp(u)&&await X(i)},pi=(i,u)=>{if(!(u.pathname.startsWith(Ht)||e.authHandler!==void 0&&Ir(u.pathname,e.authBasePath??Or))||i.method!=="POST"&&i.method!=="PUT")return;const w=Number(i.headers.get("content-length")??""),y=Cp[u.pathname]??Br;if(Number.isFinite(w)&&w>y)throw new l("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},mi=async(i,u,f)=>{je.set(i,f);const w=new URL(i.url);pi(i,w);const y=await ii(i,u,w,f);if(y)return y;if(ro.has(w.pathname)&&i.method==="GET"&&En(i))return await he.refusal(i)??so(i,u,w);const T=ui(i,w);if(T)return T(i,u,f);const D=si[w.pathname];if(D)return D(i,u,f);const P=li[w.pathname];if(P)return await ho(i,w.pathname),($p.has(w.pathname)||Object.hasOwn(uo,w.pathname)?await he.refusal(i):void 0)??P(i,u,w,f);if(e.voiceAgents!==void 0&&w.pathname.startsWith(vr))return await he.refusal(i)??Za(i,u,w);if(w.pathname.startsWith(Ht))return new Response("Not found",{status:404});const L=e.spaAssets===void 0||!e.httpRouter?void 0:await ip(e.spaAssets,i),{response:k,unrouted:I}=await Ja(i,u,f,L!==void 0);return k&&k.status!==404?(await L?.body?.cancel(),k):za(i,k,I,L)};return{async fetch(i,u,f){e.passThroughOnException&&f.passThroughOnException?.(),fi(u),_(u);const w=oc(i,Ee);if(w)return w;const y=rc(i,Ee);if(y)return rn(y,i,Ee);try{const T=await mi(i,u,f);return rn(tn.has(T)?hi(T):T,i,Ee)}catch(T){return rn(To(T),i,Ee)}finally{Eo(e.observability,Dr(f))}},async queue(i,u,f){const w=await he.read();await io(`queue:${Zp(i)}`,f,async y=>{const T=e.liveStreams===!1?Ar():{publish:(D,P,L)=>ee(Lp,D,P,L,"trusted")};await e.queue?.(i,u,f,w.paused?{holdSeconds:On,traceparent:y}:{traceparent:y},T,e.queueFetchImpl)})},async scheduled(i,u,f){await io(`cron:${i.cron}`,f,async w=>{await co(i,u,f,w)})},serverQuery:oi}},pm=e=>_a(e),mm=e=>typeof e=="function"?{fetch:e}:e,wm=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,gm=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},ba=e=>{const t=new WeakMap;return n=>{if(n===null||typeof n!="object")return e(n);let o=t.get(n);return o===void 0&&(o=e(n),t.set(n,o)),o}},Gm=(e,t)=>{const n=mm(e),{email:o,queue:r,scheduled:s}=gm(e),a=c=>{const p={...pm({...c,httpRouter:n})};return s!==void 0&&!wm(c)&&(p.scheduled=async(m,g,R)=>{await s(m,g,R)}),r!==void 0&&c.queue===void 0&&(p.queue=async(m,g,R)=>{await r(m,g,R)}),o!==void 0&&(p.email=async(m,g,R)=>{await o(m,g,R)}),p};if(typeof t!="function")return a(t);const d=ba(c=>a(t(c)));return{fetch:(c,h,p)=>d(h).fetch(c,h,p),queue:(c,h,p)=>d(h).queue?.(c,h,p)??Promise.resolve(),scheduled:(c,h,p)=>d(h).scheduled(c,h,p),serverQuery:(c,h,p,m,g)=>d(h).serverQuery(c,h,p,m,g),...o===void 0?{}:{email:(c,h,p)=>d(h).email?.(c,h,p)??Promise.resolve()}}},ym=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new l("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Fm=(e={})=>{const t=ba(n=>_a(ym(e,n)));return(n,o,r)=>t(o).fetch(n,o,r??Ai)},Wm=e=>e;export{Xo as COPY_AUTH_TO_JURISDICTION_OP,Xu as GET_AUTH_AUDIT_LOG_OP,Ai as NOOP_EXECUTION_CONTEXT,qu as PURGE_UNPINNED_AUTH_OP,zm as composeIdentityResolvers,pm as composeWorker,Fm as createLunoraHandler,_a as createWorker,Wm as defineRpcEnvelope,cm as probeRelayCount,ym as resolveLunoraOptions,Jm as routeIdentityResolvers,Gm as withFrameworkWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.303",
3
+ "version": "1.0.0-alpha.304",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",