@lunora/runtime 1.0.0-alpha.305 → 1.0.0-alpha.306

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-BK8tTJR3.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-T5iLUYuZ.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-B-vhtsPD.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,4 +1,4 @@
1
- import{isLunoraError as Ur,toErrorBody as _i}from"@lunora/errors";import{encodeWire as Re,decodeWire as Nt,encodeArgsOrThrow as bi}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 Si}from"./memoize-identity-Cbr1Sdt3.mjs";import{d as yo,E as _o,a as Ei,b as Ai,W as bo}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as Ti}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as vi,a as Ri,i as Oi,e as Ii,E as So,b as Ni}from"./identity-header-DqrLFqFq.mjs";import{O as Lr,a as Mr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ye,b as $r,p as ki,m as Di,d as Pi,a as Ui,r as Ci}from"./otlp-resource-BBR8xs6m.mjs";import{r as Li,f as Eo,a as Le,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 me,M as Br,b as Mi,f as $i,g as xr,w as Bi,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 xi,backupObjectKeyOfManifest as Kr,backupObjectKey as Hi,backupManifestKey as ji}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as tt,STORAGE_UPLOAD_MAX_BODY_BYTES as Be,buildStorageAdminRoutes as Ki,STORAGE_PATH as Gi}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Fi,e as Wi,f as vo,g as Qi,h as Vi}from"./export-tap-CMyD7rin.mjs";import{sha256 as Gr}from"@noble/hashes/sha2.js";import{buildHealthRoutes as zi,durableObjectProbe as Ji,d1Probe as Yi,presenceProbe as on}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Xi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as tw,routeIdentityResolvers as nw}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Zi}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as qi,createQueryCoordinator as ec,createDefaultShardRegistry as tc,refreshShardHeadersPerCall as nc,refreshedShardHeaders as oc}from"./createQueryCoordinator-BuoncR2C.mjs";import{i as Ro,r as Oo,h as rc,e as sc,d as rn,a as Io}from"./security-headers-0DqdJ04h.mjs";const ac=(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},ic=new TextEncoder,cc=64,dc=new Map,Fr=async e=>ac(dc,e,async()=>crypto.subtle.importKey("raw",ic.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),cc),Wr=new TextEncoder,uc=Array.from({length:32},(e,t)=>t);new RegExp(`[${uc.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",lc="__lunora_admin_revocations__",hc=/^[a-z0-9][a-z0-9_-]{0,63}$/u,fc=/^[\w-]{43}$/u,Rt="x-lunora-admin-signal",pc="as1",mc=6e4,wc=5e3,zr=e=>hc.test(e),gc=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Vr)return;const[,n,o]=t;return zr(n)&&fc.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:gc(t[1])},yc=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(""),_c=async(e,t,n=Date.now(),o=Number.POSITIVE_INFINITY)=>{const r=`${pc}.${String(Math.floor(Math.min(n+mc,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"],bc="schema",Sc=e=>e==null||e===""?bc:typeof e=="string"&&An.includes(e)?e:"disabled",Ec=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",Ac=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,qr),Tc=`may not contain the reserved workflow branch-marker key ("${qr}")`,vc=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",Rc=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!vc.has(n)));return Object.keys(t).length===0?"":Tn(t)},Oc=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,Ic=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+Oc[_]+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},Nc=(e,t)=>Un(Ic(new TextEncoder().encode(`${JSON.stringify(e??null)}|${Rc(t)}`)).subarray(0,16)),kc=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}},Dc=/^\w[\w-]{0,99}$/u,Pc="`dedupKey` must match ^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$",Uc=e=>typeof e=="string"&&Dc.test(e),Cc=9e5,Lc="x-lunora-dispatch-declined",Mc=/already[\s_-]?exists/iu,$c=e=>Mc.test(e instanceof Error?e.message:String(e)),Bc="/_lunora/live/publish",xc="cf-ray",Hc="x-lunora-ray-id",jc=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Kc=e=>e==null?void 0:jc.exec(e.trim())?.[1]?.toLowerCase(),Gc=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Gc);const Fc=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Wc=-100,Qc=15,Vc=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Fc.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Qc?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Wc?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},No=e=>{const t=e.cf;return t===void 0?void 0:Vc(t)},Ft="::relay::",zc=(e,t)=>`${e}${Ft}${String(t)}`,Wt="::replica::",Jc=(e,t)=>`${e}${Wt}${t}`,Yc=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Xc=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Zc=/^[\da-f]{32}$/u,qc="`dedupScope` must be 32 lowercase hex characters",es=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")},ed=e=>typeof e=="string"&&Zc.test(e),td=async e=>(await es(e)).slice(0,32),nd=async(e,t,n)=>await es(`${e}\0${t??""}\0${n}`),ts=(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},od="/_lunora/scheduler/dispatch",rd="__lunora_relation__:",sd=e=>e.startsWith(rd),ns="agents:agentRun",ad=(e,t,n)=>e===ns&&t!==n,id=`\`${ns}\` 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:ts(t,r.join(" ").trim())},cd="x-lunora-scheduler-signature",dd="x-lunora-scheduler-timestamp",ud=5*6e4,ld=e=>["v1",String(e.timestamp),e.userId??"",e.identity??"",e.body].join(`
1
+ import{isLunoraError as Ur,toErrorBody as _i}from"@lunora/errors";import{encodeWire as Re,decodeWire as Nt,encodeArgsOrThrow as bi}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 Si}from"./memoize-identity-Cbr1Sdt3.mjs";import{d as yo,E as _o,a as Ei,b as Ai,W as bo}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as Ti}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as vi,a as Ri,i as Oi,e as Ii,E as So,b as Ni}from"./identity-header-DqrLFqFq.mjs";import{O as Lr,a as Mr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ye,b as $r,p as ki,m as Di,d as Pi,a as Ui,r as Ci}from"./otlp-resource-BBR8xs6m.mjs";import{r as Li,f as Eo,a as Le,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 me,M as Br,b as Mi,f as $i,g as xr,w as Bi,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 xi,backupObjectKeyOfManifest as Kr,backupObjectKey as Hi,backupManifestKey as ji}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as tt,STORAGE_UPLOAD_MAX_BODY_BYTES as Be,buildStorageAdminRoutes as Ki,STORAGE_PATH as Gi}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as Fi,e as Wi,f as vo,g as Qi,h as Vi}from"./export-tap-CMyD7rin.mjs";import{sha256 as Gr}from"@noble/hashes/sha2.js";import{buildHealthRoutes as zi,durableObjectProbe as Ji,d1Probe as Yi,presenceProbe as on}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Xi}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as tw,routeIdentityResolvers as nw}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Zi}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as qi,createQueryCoordinator as ec,createDefaultShardRegistry as tc,refreshShardHeadersPerCall as nc,refreshedShardHeaders as oc}from"./createQueryCoordinator-BuoncR2C.mjs";import{i as Ro,r as Oo,h as rc,e as sc,d as rn,a as Io}from"./security-headers-B-vhtsPD.mjs";const ac=(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},ic=new TextEncoder,cc=64,dc=new Map,Fr=async e=>ac(dc,e,async()=>crypto.subtle.importKey("raw",ic.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),cc),Wr=new TextEncoder,uc=Array.from({length:32},(e,t)=>t);new RegExp(`[${uc.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",lc="__lunora_admin_revocations__",hc=/^[a-z0-9][a-z0-9_-]{0,63}$/u,fc=/^[\w-]{43}$/u,Rt="x-lunora-admin-signal",pc="as1",mc=6e4,wc=5e3,zr=e=>hc.test(e),gc=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Vr)return;const[,n,o]=t;return zr(n)&&fc.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:gc(t[1])},yc=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(""),_c=async(e,t,n=Date.now(),o=Number.POSITIVE_INFINITY)=>{const r=`${pc}.${String(Math.floor(Math.min(n+mc,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"],bc="schema",Sc=e=>e==null||e===""?bc:typeof e=="string"&&An.includes(e)?e:"disabled",Ec=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",Ac=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,qr),Tc=`may not contain the reserved workflow branch-marker key ("${qr}")`,vc=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",Rc=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!vc.has(n)));return Object.keys(t).length===0?"":Tn(t)},Oc=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,Ic=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+Oc[_]+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},Nc=(e,t)=>Un(Ic(new TextEncoder().encode(`${JSON.stringify(e??null)}|${Rc(t)}`)).subarray(0,16)),kc=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}},Dc=/^\w[\w-]{0,99}$/u,Pc="`dedupKey` must match ^[A-Za-z0-9_][A-Za-z0-9_-]{0,99}$",Uc=e=>typeof e=="string"&&Dc.test(e),Cc=9e5,Lc="x-lunora-dispatch-declined",Mc=/already[\s_-]?exists/iu,$c=e=>Mc.test(e instanceof Error?e.message:String(e)),Bc="/_lunora/live/publish",xc="cf-ray",Hc="x-lunora-ray-id",jc=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Kc=e=>e==null?void 0:jc.exec(e.trim())?.[1]?.toLowerCase(),Gc=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Gc);const Fc=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Wc=-100,Qc=15,Vc=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Fc.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Qc?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Wc?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},No=e=>{const t=e.cf;return t===void 0?void 0:Vc(t)},Ft="::relay::",zc=(e,t)=>`${e}${Ft}${String(t)}`,Wt="::replica::",Jc=(e,t)=>`${e}${Wt}${t}`,Yc=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Xc=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Zc=/^[\da-f]{32}$/u,qc="`dedupScope` must be 32 lowercase hex characters",es=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")},ed=e=>typeof e=="string"&&Zc.test(e),td=async e=>(await es(e)).slice(0,32),nd=async(e,t,n)=>await es(`${e}\0${t??""}\0${n}`),ts=(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},od="/_lunora/scheduler/dispatch",rd="__lunora_relation__:",sd=e=>e.startsWith(rd),ns="agents:agentRun",ad=(e,t,n)=>e===ns&&t!==n,id=`\`${ns}\` 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:ts(t,r.join(" ").trim())},cd="x-lunora-scheduler-signature",dd="x-lunora-scheduler-timestamp",ud=5*6e4,ld=e=>["v1",String(e.timestamp),e.userId??"",e.identity??"",e.body].join(`
2
2
  `),hd=(e,t)=>Gt(e,ld(t)),fd=async(e,t,n)=>{const o=e.headers.get(cd),{schedulerSecret:r}=n;if(o!==null&&o.length>0&&r!==void 0&&r.length>0){const s=e.headers.get(dd);if(s===null||!/^\d+$/u.test(s))return!1;const a=Number(s);if(!Number.isSafeInteger(a)||Math.abs((n.now??Date.now)()-a)>ud)return!1;const d=await hd(r,{body:t,identity:e.headers.get("x-lunora-identity")??void 0,timestamp:a,userId:e.headers.get("x-lunora-userid")??void 0});return ts(d,o)}return Dt(e,n.adminToken)},ko="/_lunora/ws/reauth",pd="/_lunora/claims",md="x-lunora-scheduled-for",wd=({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[md]=String(Math.trunc(n))),r},gd=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}}},yd=(e,t,n)=>e?.[n]??t?.[n],_d=(e,t,n,o)=>{const r=yd(e,t,n);if(!(typeof r!="object"||r===null))return o.every(s=>typeof r[s]=="function")?r:void 0},os="v1",bd=6e4,Sd=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??bd),o=`${os}.${String(n)}`,r=await Gt(e,o);return{expiresAtMs:n,token:`${o}.${r}`}},Ed=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!==os||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)},Ad="https://admin-revocations.internal",Td=(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,lc).fetch(new Request(`${Ad}${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}}}},vd="/_lunora/admin/tokens",Rd="__lunora_admin__:createAdminToken",Do="__lunora_admin__:listAdminTokens",Po="__lunora_admin__:revokeAdminToken",sn={"cache-control":"no-store"},Od=(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},Id=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)]},Nd=e=>{const t=e.now??Date.now,n=async s=>{const a=await e.readJsonBody(s),d=Uo(a.name),c=Id(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}=yc(d),g=await e.revocations.latestRevoked(d),R=g===void 0?t():Math.max(t(),g+1),E=await e.callStore(Rd,{createdAt:R,digest:await Yr(p),expiresAt:h,name:d,scopes:c});if(!Od(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{[vd]: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}))}},kd=3e4,Dd=5e3,Pd=1024,Co=20,Lo=1e3,Ud=5e3,Cd=1024,Ld=({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,Cd),d.set(A,!0))};let R=Number.NEGATIVE_INFINITY,E;const S=()=>E!==void 0?E:e===void 0||n()-R<Ud?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,Pd),r.set(x?U:v,{name:A,scopes:[],until:n()+Dd})};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()+kd,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}}},Md="x",Mo=" ",$d={'"':'"',"'":"'","[":"]","`":"`"},rs=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
3
3
  `;)n+=1;return n},ss=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},Bd=e=>{const t=e.split("");let n=0;for(;n<e.length;){const o=e[n]??"",r=$d[o];if(o==="-"&&e[n+1]==="-"){const s=rs(e,n);t.fill(Mo,n,s),n=s}else if(o==="/"&&e[n+1]==="*"){const s=ss(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(Md,n,s+1),n=s+1}else n+=1}for(let o=0;o<e.length;o+=1)e[o]===`
4
4
  `&&(t[o]=`
@@ -1 +1 @@
1
- import{d as s,e as a,a as i,h as n,r as t}from"./security-headers-0DqdJ04h.mjs";import"./LunoraError-PkZWF-_g.mjs";export{s as decorateResponse,a as enforceOrigin,i as enforceWebSocketOrigin,n as handleCorsPreflight,t as resolveSecurity};
1
+ import{d as s,e as a,a as i,h as n,r as t}from"./security-headers-B-vhtsPD.mjs";import"./LunoraError-PkZWF-_g.mjs";export{s as decorateResponse,a as enforceOrigin,i as enforceWebSocketOrigin,n as handleCorsPreflight,t as resolveSecurity};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";const D=new Set(["0","disabled","false","no","off"]),R=new Set(["1","enabled","on","true","yes"]),O=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),C=e=>typeof e=="string"&&R.has(e.trim().toLowerCase()),S=e=>{if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===null||s===Object.prototype},_="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",N="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",P=31536e3,I={coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0},k=e=>{if(e===!1)return;const s=e===void 0||e===!0?{}:e,o=s.maxAge??P,r=s.includeSubDomains??!0;return`max-age=${String(o)}${r?"; includeSubDomains":""}${s.preload===!0?"; preload":""}`},x=(e,s)=>s!==void 0?["frame-ancestors 'self'",...s].join(" "):e==="DENY"?"frame-ancestors 'none'":e==="SAMEORIGIN"?"frame-ancestors 'self'":void 0,H=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,w=e=>[...e].every(s=>s===" "||s>=" "&&s!==""&&s<="ÿ"),T=["same-origin","same-origin-allow-popups","unsafe-none"],U=["DENY","SAMEORIGIN"],f=["includeSubDomains","maxAge","preload"],b=["csp","permissionsPolicy","referrerPolicy"],u=[...b,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],d=e=>e.map(s=>JSON.stringify(s)).join(", "),j=(e,s)=>{if(typeof e=="boolean")return e;if(!S(e)){s.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const n of Object.keys(e).filter(i=>!f.includes(i)))s.push(`security.headers.hsts.${n} is not an option (expected ${d(f)})`);const{includeSubDomains:o,maxAge:r,preload:t}=e;r!==void 0&&!(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&s.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(r)})`);for(const[n,i]of[["includeSubDomains",o],["preload",t]])i!==void 0&&typeof i!="boolean"&&s.push(`security.headers.hsts.${n} must be a boolean`);return{...o===void 0?{}:{includeSubDomains:o},...r===void 0?{}:{maxAge:r},...t===void 0?{}:{preload:t}}},p=(e,s,o,r)=>{if(s===void 0||s===!1||o.includes(s))return s;r.push(`security.headers.${e} must be one of ${d(o)} or false (got ${JSON.stringify(s)})`)},$=(e,s)=>{if(e!==void 0){if(!Array.isArray(e)){s.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const o of e)(typeof o!="string"||!H.test(o)||!w(o))&&s.push(`security.headers.frameAncestors entry ${JSON.stringify(o)} is not an origin like "https://partner.example"`);return[...e]}},M=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!S(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const s=Object.keys(e).filter(r=>!u.includes(r)).map(r=>`security.headers.${r} is not an option (expected ${d(u)})`),o={};for(const r of b){const t=e[r];t===void 0||t===!1?o[r]=t:typeof t!="string"?s.push(`security.headers.${r} must be a string or false`):w(t)?o[r]=t:s.push(`security.headers.${r} contains a line break or control character`)}return o.crossOriginOpenerPolicy=p("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,T,s),o.frameOptions=p("frameOptions",e.frameOptions,U,s),o.frameAncestors=$(e.frameAncestors,s),o.hsts=e.hsts===void 0?void 0:j(e.hsts,s),o.frameAncestors!==void 0&&typeof o.csp=="string"&&s.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),o.frameAncestors!==void 0&&o.frameOptions==="DENY"&&s.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),o.frameAncestors!==void 0&&o.csp===!1&&s.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),s.length>0?{ok:!1,problems:s}:{ok:!0,value:Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}},X=(e,s)=>e??(O(s)?!1:void 0),Y=e=>{if(e===!1)return I;const s=e===void 0||e===!0?{}:e,o=s.frameAncestors!==void 0||s.frameOptions===!1?void 0:s.frameOptions??"SAMEORIGIN",r=["base-uri 'none'","object-src 'none'",x(o,s.frameAncestors)].filter(n=>n!==void 0).join("; ");let t;return typeof s.csp=="string"?t={htmlValue:s.csp,value:s.csp}:s.csp!==!1&&(t={htmlValue:r,value:_}),{coop:s.crossOriginOpenerPolicy===!1?void 0:s.crossOriginOpenerPolicy??"same-origin-allow-popups",csp:t,enabled:!0,frameOptions:o,hsts:k(s.hsts),permissionsPolicy:s.permissionsPolicy===!1?void 0:s.permissionsPolicy??N,referrerPolicy:s.referrerPolicy===!1?void 0:s.referrerPolicy??"strict-origin-when-cross-origin"}},h=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],m=["DELETE","GET","HEAD","PATCH","POST","PUT","QUERY"],F=new Set(["GET","HEAD","OPTIONS"]),G=e=>{const s={allowCredentials:!1,allowedHeaders:h,allowedMethods:m,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return s;const o=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const i=v=>r(v)===!0;t=i,n=i,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const i=r;if(i.includes("*")&&o)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=a=>i.includes("*")||i.includes(a),n=a=>i.includes(a)}return{allowCredentials:o,allowedHeaders:[...new Set([...h,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??m,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},B=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const s=e===void 0||e===!0?{}:e;return{allowLoopback:s.allowLoopback??!0,enabled:!0,trustedOrigins:s.trustedOrigins??[]}},V=e=>{const s=e?.LUNORA_ALLOWED_ORIGINS;if(typeof s!="string")return;const o=s.split(",").map(n=>n.trim()).filter(n=>n.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&C(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},q=(e,s)=>{const o=M(X(e?.headers,s?.LUNORA_SECURITY_HEADERS)),r=e?.csrf??(O(s?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??V(s);if(!o.ok)throw new g(`@lunora/runtime: ${o.problems.join("; ")}`);return{cors:G(t),csrf:B(r),headers:Y(o.value)}},K=new Set(["127.0.0.1","::1","[::1]","localhost"]),y=e=>{try{return K.has(new URL(e).hostname)}catch{return!1}},l=e=>{if(e)try{return new URL(e).origin}catch{return}},A=(e,s,o)=>e===s||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&y(s)&&y(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),E=(e,s,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${s===void 0?"was missing":`"${s}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:s}},{headers:{"content-type":"application/json"},status:403}),ee=(e,s)=>{if(!s.csrf.enabled||F.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"))??l(e.headers.get("referer"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin state-changing request",r,o)},se=(e,s)=>{if(!s.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin websocket upgrade",r,o)},W=["Accept-Query","X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],L=(e,s)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",W.join(", ")),o.append("vary","Origin"),s.allowCredentials&&o.set("access-control-allow-credentials","true"),o},oe=(e,s)=>{if(!s.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!s.cors.isAllowed(o))return;const r=L(o,s.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",s.cors.allowedMethods.join(", "));let n;if(t===null)n=s.cors.allowedHeaders.join(", ");else{const i=new Set(s.cors.allowedHeaders.map(a=>a.toLowerCase()));n=t.split(",").map(a=>a.trim()).filter(a=>a.length>0&&i.has(a.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(s.cors.maxAge)),new Response(null,{headers:r,status:204})},J=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),c=(e,s,o)=>{e.has(s)||e.set(s,o)},z=(e,s,o,r)=>{r.hsts!==void 0&&new URL(s.url).protocol==="https:"&&c(e,"strict-transport-security",r.hsts),c(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&c(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&c(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&c(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&c(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0&&c(e,"content-security-policy",J(o)?r.csp.htmlValue:r.csp.value)},Q=(e,s,o)=>{const r=s.headers.get("origin");if(!(!r||!o.isAllowed(r)))for(const[t,n]of L(r,o).entries())t==="vary"?e.append("vary",n):c(e,t,n)},re=(e,s,o)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return o.headers.enabled&&z(r,s,e,o.headers),o.cors.enabled&&Q(r,s,o.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{se as a,re as d,ee as e,oe as h,S as i,q as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.305",
3
+ "version": "1.0.0-alpha.306",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";const D=new Set(["0","disabled","false","no","off"]),C=new Set(["1","enabled","on","true","yes"]),O=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),R=e=>typeof e=="string"&&C.has(e.trim().toLowerCase()),S=e=>{if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===null||s===Object.prototype},_="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",N="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",P=31536e3,I={coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0},k=e=>{if(e===!1)return;const s=e===void 0||e===!0?{}:e,o=s.maxAge??P,r=s.includeSubDomains??!0;return`max-age=${String(o)}${r?"; includeSubDomains":""}${s.preload===!0?"; preload":""}`},x=(e,s)=>s!==void 0?["frame-ancestors 'self'",...s].join(" "):e==="DENY"?"frame-ancestors 'none'":e==="SAMEORIGIN"?"frame-ancestors 'self'":void 0,H=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,w=e=>[...e].every(s=>s===" "||s>=" "&&s!==""&&s<="ÿ"),T=["same-origin","same-origin-allow-popups","unsafe-none"],U=["DENY","SAMEORIGIN"],f=["includeSubDomains","maxAge","preload"],b=["csp","permissionsPolicy","referrerPolicy"],u=[...b,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],d=e=>e.map(s=>JSON.stringify(s)).join(", "),j=(e,s)=>{if(typeof e=="boolean")return e;if(!S(e)){s.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const n of Object.keys(e).filter(i=>!f.includes(i)))s.push(`security.headers.hsts.${n} is not an option (expected ${d(f)})`);const{includeSubDomains:o,maxAge:r,preload:t}=e;r!==void 0&&!(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&s.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(r)})`);for(const[n,i]of[["includeSubDomains",o],["preload",t]])i!==void 0&&typeof i!="boolean"&&s.push(`security.headers.hsts.${n} must be a boolean`);return{...o===void 0?{}:{includeSubDomains:o},...r===void 0?{}:{maxAge:r},...t===void 0?{}:{preload:t}}},p=(e,s,o,r)=>{if(s===void 0||s===!1||o.includes(s))return s;r.push(`security.headers.${e} must be one of ${d(o)} or false (got ${JSON.stringify(s)})`)},$=(e,s)=>{if(e!==void 0){if(!Array.isArray(e)){s.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const o of e)(typeof o!="string"||!H.test(o)||!w(o))&&s.push(`security.headers.frameAncestors entry ${JSON.stringify(o)} is not an origin like "https://partner.example"`);return[...e]}},M=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!S(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const s=Object.keys(e).filter(r=>!u.includes(r)).map(r=>`security.headers.${r} is not an option (expected ${d(u)})`),o={};for(const r of b){const t=e[r];t===void 0||t===!1?o[r]=t:typeof t!="string"?s.push(`security.headers.${r} must be a string or false`):w(t)?o[r]=t:s.push(`security.headers.${r} contains a line break or control character`)}return o.crossOriginOpenerPolicy=p("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,T,s),o.frameOptions=p("frameOptions",e.frameOptions,U,s),o.frameAncestors=$(e.frameAncestors,s),o.hsts=e.hsts===void 0?void 0:j(e.hsts,s),o.frameAncestors!==void 0&&typeof o.csp=="string"&&s.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),o.frameAncestors!==void 0&&o.frameOptions==="DENY"&&s.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),o.frameAncestors!==void 0&&o.csp===!1&&s.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),s.length>0?{ok:!1,problems:s}:{ok:!0,value:Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}},X=(e,s)=>e??(O(s)?!1:void 0),F=e=>{if(e===!1)return I;const s=e===void 0||e===!0?{}:e,o=s.frameAncestors!==void 0||s.frameOptions===!1?void 0:s.frameOptions??"SAMEORIGIN",r=["base-uri 'none'","object-src 'none'",x(o,s.frameAncestors)].filter(n=>n!==void 0).join("; ");let t;return typeof s.csp=="string"?t={htmlValue:s.csp,value:s.csp}:s.csp!==!1&&(t={htmlValue:r,value:_}),{coop:s.crossOriginOpenerPolicy===!1?void 0:s.crossOriginOpenerPolicy??"same-origin-allow-popups",csp:t,enabled:!0,frameOptions:o,hsts:k(s.hsts),permissionsPolicy:s.permissionsPolicy===!1?void 0:s.permissionsPolicy??N,referrerPolicy:s.referrerPolicy===!1?void 0:s.referrerPolicy??"strict-origin-when-cross-origin"}},h=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],m=["DELETE","GET","HEAD","PATCH","POST","PUT"],Y=new Set(["GET","HEAD","OPTIONS"]),G=e=>{const s={allowCredentials:!1,allowedHeaders:h,allowedMethods:m,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return s;const o=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const i=v=>r(v)===!0;t=i,n=i,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const i=r;if(i.includes("*")&&o)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=a=>i.includes("*")||i.includes(a),n=a=>i.includes(a)}return{allowCredentials:o,allowedHeaders:[...new Set([...h,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??m,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},B=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const s=e===void 0||e===!0?{}:e;return{allowLoopback:s.allowLoopback??!0,enabled:!0,trustedOrigins:s.trustedOrigins??[]}},V=e=>{const s=e?.LUNORA_ALLOWED_ORIGINS;if(typeof s!="string")return;const o=s.split(",").map(n=>n.trim()).filter(n=>n.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&R(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},q=(e,s)=>{const o=M(X(e?.headers,s?.LUNORA_SECURITY_HEADERS)),r=e?.csrf??(O(s?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??V(s);if(!o.ok)throw new g(`@lunora/runtime: ${o.problems.join("; ")}`);return{cors:G(t),csrf:B(r),headers:F(o.value)}},K=new Set(["127.0.0.1","::1","[::1]","localhost"]),y=e=>{try{return K.has(new URL(e).hostname)}catch{return!1}},l=e=>{if(e)try{return new URL(e).origin}catch{return}},A=(e,s,o)=>e===s||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&y(s)&&y(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),E=(e,s,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${s===void 0?"was missing":`"${s}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:s}},{headers:{"content-type":"application/json"},status:403}),ee=(e,s)=>{if(!s.csrf.enabled||Y.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"))??l(e.headers.get("referer"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin state-changing request",r,o)},se=(e,s)=>{if(!s.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin websocket upgrade",r,o)},W=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],L=(e,s)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",W.join(", ")),o.append("vary","Origin"),s.allowCredentials&&o.set("access-control-allow-credentials","true"),o},oe=(e,s)=>{if(!s.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!s.cors.isAllowed(o))return;const r=L(o,s.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",s.cors.allowedMethods.join(", "));let n;if(t===null)n=s.cors.allowedHeaders.join(", ");else{const i=new Set(s.cors.allowedHeaders.map(a=>a.toLowerCase()));n=t.split(",").map(a=>a.trim()).filter(a=>a.length>0&&i.has(a.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(s.cors.maxAge)),new Response(null,{headers:r,status:204})},J=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),c=(e,s,o)=>{e.has(s)||e.set(s,o)},z=(e,s,o,r)=>{r.hsts!==void 0&&new URL(s.url).protocol==="https:"&&c(e,"strict-transport-security",r.hsts),c(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&c(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&c(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&c(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&c(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0&&c(e,"content-security-policy",J(o)?r.csp.htmlValue:r.csp.value)},Q=(e,s,o)=>{const r=s.headers.get("origin");if(!(!r||!o.isAllowed(r)))for(const[t,n]of L(r,o).entries())t==="vary"?e.append("vary",n):c(e,t,n)},re=(e,s,o)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return o.headers.enabled&&z(r,s,e,o.headers),o.cors.enabled&&Q(r,s,o.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{se as a,re as d,ee as e,oe as h,S as i,q as r};