@lunora/runtime 1.0.0-alpha.44 → 1.0.0-alpha.45
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 +1 -1
- package/dist/packem_shared/{DEFAULT_REGISTRY_CACHE_TTL_MS-CsNnfJzB.mjs → DEFAULT_REGISTRY_CACHE_TTL_MS-BBf3mNrD.mjs} +1 -1
- package/dist/packem_shared/GET_AUTH_AUDIT_LOG_OP-DmxHQbZT.mjs +1 -0
- package/dist/packem_shared/{HEALTH_PATH-BEE0A_lZ.mjs → HEALTH_PATH-gr8vE39f.mjs} +1 -1
- package/dist/packem_shared/{LOG_ARCHIVE_PATH-DGsEec3K.mjs → LOG_ARCHIVE_PATH-6Y0IS1MS.mjs} +1 -1
- package/dist/packem_shared/{LunoraError-ByasbDmd.mjs → LunoraError-C08OP5Uq.mjs} +1 -1
- package/dist/packem_shared/{composeIdentityResolvers-DwE0Jbww.mjs → composeIdentityResolvers-DlBbYmBJ.mjs} +1 -1
- package/dist/packem_shared/composeWorker-D7XNECHA.mjs +6 -0
- package/dist/packem_shared/{createCrossShardRelationCapabilities-CMWiFA5s.mjs → createCrossShardRelationCapabilities-B2EKbSEs.mjs} +1 -1
- package/dist/packem_shared/{createQueryCoordinator-DqrEvhPD.mjs → createQueryCoordinator-DLsrcOkB.mjs} +1 -1
- package/dist/packem_shared/{decorateResponse-DBIWsRSZ.mjs → decorateResponse-C6TZSzID.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/composeWorker-i1cHDFrr.mjs +0 -6
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as s,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-D7XNECHA.mjs";import{createCrossShardRelationCapabilities as E}from"./packem_shared/createCrossShardRelationCapabilities-B2EKbSEs.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BBf3mNrD.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-C08OP5Uq.mjs";import{createKvCursorStore as y,createMemoryCursorStore as g,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-gr8vE39f.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as M}from"./packem_shared/LOG_ARCHIVE_PATH-6Y0IS1MS.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CZGtDc4H.mjs";import{e as W,a as Y}from"./packem_shared/observability-DYnm-d4g.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-CUWYuLHs.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-DU_CCGDA.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as ie,mergeStrategyForAggregate as se}from"./packem_shared/createQueryCoordinator-DLsrcOkB.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-uRQLx282.mjs";import{R as Re,d as Se,o as Ee}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{argsFromQuery as fe,buildRestRoutes as le,createRestRateLimit as xe,readShardKey as _e,restSurfaceFromRegistry as Ce}from"./packem_shared/argsFromQuery-BkJXnIpe.mjs";import{decorateResponse as ue,enforceOrigin as ye,handleCorsPreflight as ge,resolveSecurity as Te}from"./packem_shared/decorateResponse-C6TZSzID.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-62qcYKGl.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DlBbYmBJ.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,C as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,s as composeWorker,X as consoleSink,E as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,y as createKvCursorStore,n as createLunoraHandler,g as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,ie as createStaticShardRegistry,p as createWorker,F as d1Probe,ue as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ye as enforceOrigin,ge as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,se as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Se as requestCarriesCredentials,M as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Ee as restCacheHeaders,Ce as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,L as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"./LunoraError-
|
|
1
|
+
import{LunoraError as n}from"./LunoraError-C08OP5Uq.mjs";import{applyJurisdiction as m}from"./applyJurisdiction-uRQLx282.mjs";const S="__lunora_shard_registry__",_=3e4,l="https://shard-registry.internal",w=async s=>await s.json(),$=s=>{const p=s.instanceName??S,o=s.cacheTtlMs??_,a=new Map,c=m(s.namespace,s.jurisdiction);let d;const h=()=>(d??=c.get(c.idFromName(p)),d),y=async(t,e)=>h().fetch(new Request(`${l}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),u=async t=>h().fetch(new Request(`${l}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),r=a.get(t);if(r&&r.expiresAt>e)return r.shardKeys;const i=await u(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:g}=await w(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:g}),g},async register(t,e){const r=await y("/register",{shardKey:e,table:t});if(!r.ok)throw new n(`shard registry /register returned ${String(r.status)}`);a.delete(t)},async snapshot(){const t=await u("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await w(t);return e},async unregister(t,e){const r=await y("/unregister",{shardKey:e,table:t});if(!r.ok)throw new n(`shard registry /unregister returned ${String(r.status)}`);a.delete(t)}}};export{_ as DEFAULT_REGISTRY_CACHE_TTL_MS,S as SHARD_REGISTRY_DO_NAME,$ as createDynamicShardRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"./LunoraError-C08OP5Uq.mjs";const p="__lunora_admin__:getAuthAuditLog",A=e=>typeof e=="string"&&e!==""?e:void 0,_=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,v=e=>async(h,o)=>{e.assertAdmin(h);const r=e.getReader();if(r===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const t={},n=A(o.actorId),s=A(o.event),d=_(o.sinceSeq),u=_(o.limit);n!==void 0&&(t.actorId=n),s!==void 0&&(t.event=s),d!==void 0&&(t.sinceSeq=d),u!==void 0&&(t.limit=u);let c;try{c=await r.read(t)}catch(i){throw i instanceof a?i:(console.error("[lunora] auth audit read failed:",i),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const l={entries:c};return Response.json(l,{headers:{"content-type":"application/json"},status:200})};export{p as GET_AUTH_AUDIT_LOG_OP,v as buildGetAuthAuditLog};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"./LunoraError-
|
|
1
|
+
import{LunoraError as k}from"./LunoraError-C08OP5Uq.mjs";import{d as H}from"./method-guard-BbuR0VfS.mjs";const R="/_lunora/health",T="/_lunora/health/ready",N=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const _=a=>{const e=new P,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:N(t.kind)});return{criticalNames:s,registry:e}},j=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:j(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},M=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:E}=_(d(i)),{healthy:v,report:A}=await E.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!v:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[R]:(n,i)=>c(n,i,"aggregate"),[T]:(n,i)=>c(n,i,"readiness")}},q=(a,e,s)=>({check:async()=>{try{return await e.get(e.idFromName(s)).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:a}),L=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),$=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{R as HEALTH_PATH,T as HEALTH_READY_PATH,M as buildHealthRoutes,L as d1Probe,q as durableObjectProbe,$ as presenceProbe};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as p}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as m,c as f}from"./pipeline-log-reader-DU_CCGDA.mjs";import{LunoraError as _}from"./LunoraError-
|
|
1
|
+
import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as p}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as m,c as f}from"./pipeline-log-reader-DU_CCGDA.mjs";import{LunoraError as _}from"./LunoraError-C08OP5Uq.mjs";const E="/_lunora/admin/logs/archive",A="LUNORA_LOG_ARCHIVE_TABLE",O="LUNORA_LOG_ARCHIVE_NAMESPACE",D=e=>{if(typeof e!="object"||e===null)return;const t=e,o=t[A];if(typeof o!="string"||o==="")return;const i=t[O];return{table:o,...typeof i=="string"&&i!==""?{namespace:i}:{}}},g=new Set(m),b=e=>typeof e=="string"&&e!==""?e:void 0,v=(e,t)=>{if(e!==void 0){if(typeof e!="string"||!g.has(e))throw new _(`logs archive: invalid \`${t}\` — expected one of ${m.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},d=(e,t)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${t}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},C=e=>{const t={},o=r=>{const l=b(e[r]);l!==void 0&&(t[r]=l)};o("functionPath"),o("functionPathPrefix"),o("traceId"),o("shardKey"),o("userId");const i=v(e.level,"level");i!==void 0&&(t.level=i);const n=v(e.minLevel,"minLevel");n!==void 0&&(t.minLevel=n);const s=d(e.sinceTs,"sinceTs");s!==void 0&&(t.sinceTs=s);const u=d(e.untilTs,"untilTs");u!==void 0&&(t.untilTs=u);const a=d(e.limit,"limit");a!==void 0&&(t.limit=a);const c=e.cursor;if(typeof c=="object"&&c!==null){const r=d(c.ts,"cursor.ts");r!==void 0&&(t.cursor={ts:r})}return t},S=e=>{const t=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,o=e.R2_SQL_TOKEN,i=e.R2_SQL_BUCKET,n=[];if((t===void 0||t==="")&&n.push("R2_SQL_ACCOUNT_ID"),(o===void 0||o==="")&&n.push("R2_SQL_TOKEN"),(i===void 0||i==="")&&n.push("R2_SQL_BUCKET"),n.length>0)throw new _(`log archive not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:p,status:400});return{accountId:t,apiToken:o,bucket:i}},U=e=>{const{createReader:t=f,readJsonBody:o,requireAdminOption:i}=e,n=async(s,u)=>{if(s.method!=="POST")throw new _("Log-archive endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const a=i(s,e.logArchive,{code:p,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:c,apiToken:r,bucket:l}=S(u??{}),L=C(await o(s)),T=h({accountId:c,apiToken:r,bucket:l}),R=await t(T,{columnMap:a.columnMap,namespace:a.namespace,table:a.table}).query(L);return Response.json(R,{headers:{"content-type":"application/json"},status:200})};return{[E]:n}};export{p as LOG_ARCHIVE_NOT_CONFIGURED,E as LOG_ARCHIVE_PATH,U as buildLogArchiveAdminRoutes,D as resolveLogArchiveFromEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{toErrorBody as t,LunoraError as n}from"@lunora/errors";const a=e=>{const{body:o,redacted:r,status:s}=t(e,{fallbackCode:"INTERNAL",redactedMessage:"Internal error"});return r&&console.error("[lunora] internal error:",e),Response.json({error:o},{headers:{"content-type":"application/json"},status:s})};class u extends n{constructor(o,r){super(r?.code??"INTERNAL",o,{cause:r?.cause,status:r?.status})}toResponse(){return a(this)}}export{u as LunoraError,a as toErrorResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"./LunoraError-
|
|
1
|
+
import{LunoraError as c}from"./LunoraError-C08OP5Uq.mjs";const u=(r,n={})=>{const t=n.onError??"fail-closed";return async(o,e)=>{for(const i of r){let s;try{s=await i(o,e)}catch(a){if(t==="skip")continue;throw a}if(s)return s}return null}},d=r=>{const n=Object.keys(r).filter(t=>t!=="*").toSorted((t,o)=>o.length-t.length);return(t,o)=>{const{pathname:e}=new URL(t.url),i=n.find(a=>e===a||e.startsWith(a.endsWith("/")?a:`${a}/`)),s=i===void 0?r["*"]:r[i];return s===void 0?null:s(t,o)}},f=(r,n)=>n===void 0||r===void 0?r:async(t,o)=>{const e=await r(t,o);if(!e)return e;const i=n.validate(e);if(i.ok)return e;if(n.onInvalid==="reject")throw new c(`identity claims failed the declared contract: ${i.error}`,{code:"UNAUTHENTICATED",status:401});return null};export{u as composeIdentityResolvers,d as routeIdentityResolvers,f as wrapResolverWithContract};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as er,toErrorBody as tr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as rr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as nr,A as or,R as ar,d as sr,i as ir,s as dr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as a,toErrorResponse as We}from"./LunoraError-C08OP5Uq.mjs";import{GET_AUTH_AUDIT_LOG_OP as ur,buildGetAuthAuditLog as cr}from"./GET_AUTH_AUDIT_LOG_OP-DmxHQbZT.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Ne}from"./HEALTH_PATH-gr8vE39f.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{composeIdentityResolvers as wa,routeIdentityResolvers as ma}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-6Y0IS1MS.mjs";import{o as yr,f as He,a as ue}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as Je}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Ve,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ue,enforceWebSocketOrigin as Ye}from"./decorateResponse-C6TZSzID.mjs";const wt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,je=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.codePointAt(s)??0;return n},Sr=64,qe=new Map,mt=async e=>{const t=qe.get(e);if(t)return t;wt(qe,Sr);const r=crypto.subtle.importKey("raw",je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return qe.set(e,r),r},Ar=async(e,t)=>{const r=await mt(e),n=await crypto.subtle.sign("HMAC",r,je.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await mt(e);return crypto.subtle.verify("HMAC",n,r,je.encode(t))},yt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${yt}.${String(r)}`,s=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},Ir=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[s,d,c]=n;if(s!==yt||c.length===0)return!1;const l=Number(d);if(!Number.isFinite(l)||l<=r)return!1;let m;try{m=Rr(c)}catch{return!1}return vr(e,`${s}.${d}`,m)},D="/_lunora/admin/auth",Pr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},he=(e,t)=>{const r=e(t);if(r===void 0)throw new a(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},$e=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},ee=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Ze=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,s]of Object.entries(t))Array.isArray(s)&&s.every(d=>typeof d=="string")&&(r[n]=s);return r},Nr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:ee(e,"password"),role:$e(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ee(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:I(e,"name"),ownerId:ee(e,"ownerId"),slug:ee(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:ee(e,"name"),organizationId:I(e,"organizationId"),slug:ee(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:ee(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:ee(e,"inviterId"),organizationId:I(e,"organizationId"),role:ee(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=$e(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Ze(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Ze(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async s=>{try{return await s()}catch(d){if(d instanceof a)throw d;const c=d,l=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new a("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(s,d)=>{if(e.assertAdmin(s),s.method!==d.http)throw new a(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new a("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=c[d.method];if(l===void 0)throw new a(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const m=new URL(s.url),O={body:d.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:y=>e.queryParameter(m,y)},v=d.build(O),g=await t(()=>l(v));return Response.json(d.returns==="void"?{ok:!0}:g,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,d]of Object.entries(Nr))n[s]=c=>r(c,d);return n},et=500,qr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new a("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new a("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new a("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},$r=(e,t)=>{if(e.length>et)throw new a(`RPC batch exceeds the ${String(et)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:d,shardKey:c}=qr(s,n,t),l=r.get(c)??[];l.push(d),r.set(c,l)}return r},ge=1048576,se=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let s=0,d="";for(;;){const{done:c,value:l}=await r.read();if(c)break;if(l){if(s+=l.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});d+=n.decode(l,{stream:!0})}}return d+=n.decode(),d},Lr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:l,value:m}=await r.read();if(l)break;if(m){if(s+=m.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(m)}}const d=new Uint8Array(s);let c=0;for(const l of n)d.set(l,c),c+=l.byteLength;return d.buffer},te=async(e,t=ge)=>{try{const r=await se(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof a?r:new a("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},xr=new TextEncoder,Br=e=>{const t=JSON.stringify(e),r=xr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Cr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const s=JSON.parse(new TextDecoder().decode(n)),d=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[l,m]of Object.entries(d))typeof m=="number"&&Number.isFinite(m)&&(c[l]=m);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},jr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:n,table:t}},tt=(e,t,r)=>{for(const n of t)e.push(jr(n));return r!==void 0&&t.length>=r},Gr="/_lunora/admin/export",Kr="/_lunora/admin/import",Mr="/_lunora/admin/sync",Qr="/_lunora/admin/connector/sync",Fr="/_lunora/admin/apply",zr="/_lunora/admin/export-tap/run",Wr=new TextEncoder,Hr=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new a("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const s of r.tables){if(typeof s!="string"||s.length===0)throw new a("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(s)}return{tables:n}},Jr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:d,assertAdmin:c,requireAdminOption:l,resolveForwardContext:m,shardDO:O,streamExportRows:v,streamingImport:g,syncGlobals:y}=e,p=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Hr(S),{headers:M}=await m(S,G),Q=new ReadableStream({async pull(C){const K=X=>{C.enqueue(Wr.encode(`${JSON.stringify(X)}
|
|
2
|
+
`))};try{await v(Y,M,N.tables,K),C.close()}catch(X){C.error(X)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,C=typeof N.globalCursor=="number"?N.globalCursor:0,K=Array.isArray(N.tables)?N.tables.filter(Z=>typeof Z=="string"):void 0,{headers:X}=await m(S,G),J=K??s(),oe=await Y.orchestrateCdcSync(O,{cursors:M,headers:X,limit:Q,tables:J}),ie=y?await y({limit:Q,sinceSeq:C}):void 0;return Response.json({global:ie,shards:oe.shards},{status:200})},T=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=Cr(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(re=>typeof re=="string"):void 0,{headers:K}=await m(S,G),X=C??s(),J=await Y.orchestrateCdcSync(O,{cursors:M.s,headers:K,limit:Q,tables:X}),oe=[],ie={...M.s};let Z=!1;for(const re of J.shards)Z=tt(oe,re.changes??[],Q)||Z,ie[re.shardKey]=re.cursor;let pe=M.g;if(y){const re=await y({limit:Q,sinceSeq:M.g});Z=tt(oe,re.changes,Q)||Z,pe=re.cursor}const be=Br({g:pe,s:ie,v:1}),Ae={changes:oe,hasMore:Z,nextCursor:be};return Response.json(Ae,{status:200})},_=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await te(S),M=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:C}=await m(S,G),K=await Y.orchestrateApplyCdc(O,{batches:M,headers:C}),X=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},P=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;c(S);const{headers:Y}=await m(S,G),N=await g(S,Y);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},q=async(S,G)=>{const B=me(S,["POST"]);if(B)return B;const Y=l(S,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new a("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await te(S),M=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,C=Array.isArray(N.tables)?N.tables.filter(ie=>typeof ie=="string"):void 0;if(M===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[M];if(K===void 0)throw new a(`Export-tap sink "${M}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await m(S,G),J=C??s(),oe=await lr({coordinator:Y,cursorStore:r,headers:X,limit:Q,shardDO:O,sink:K,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[Fr]:_,[Qr]:T,[Gr]:p,[zr]:q,[Kr]:P,[Mr]:w}},gt=e=>[],Vr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?n.push(s):r.push(s);return{globalTables:n,shardLocalTables:r}},Yr=async(e,t,r,n,s,d,c)=>{if(n!==void 0&&s.length===0)return;const l=n===void 0?[]:s,m=n===void 0?gt():[],O=l.length>0?l:m,v=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:O});for(const g of v.shards)if(!g.error)for(const y of g.rows??[])d(y)},rt=async(e,t,r,n,s,d)=>{const{globalTables:c,shardLocalTables:l}=Vr(e,n);await Yr(e,t,r,n,l,s,d);const m=e.exportGlobals;if((n===void 0||c.length>0)&&m){const O=n===void 0?[]:c;for await(const v of m({tables:O}))s(v)}},Xr=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Zr=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},en=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],d=new Map;let c=0;const l=e.body.getReader(),m=new TextDecoder;let O="",v=0;const g=y=>{c+=1;const p=y.trim();if(p.length===0)return;const w=Xr(p,c);if(!w.ok){n.push(w.error);return}const{doc:T,table:_}=w,P=t.resolveTableSharding?.(_);if(P?.mode.kind==="global"){s.push({doc:T,line:c,table:_});return}const q=Zr(T,_,P,r,c);if(!q.ok){n.push(q.error);return}const S=d.get(q.shardKey);S?S.rows.push({doc:T,table:_}):d.set(q.shardKey,{rows:[{doc:T,table:_}],shardKey:q.shardKey,startLine:c})};for(;;){const{done:y,value:p}=await l.read();if(y)break;if(p&&(v+=p.byteLength,v>ge))throw await l.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=m.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
|
+
`);for(;w!==-1;){const T=O.slice(0,w);O=O.slice(w+1),g(T),w=O.indexOf(`
|
|
4
|
+
`)}}return O.length>0&&g(O),{errors:n,globalRows:s,perShard:d}},nt=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},tn=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:d,globalRows:c,perShard:l}=await en(e,t,s),m={conflicts:0,errors:d,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const v=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});nt(m,v)}if(c.length>0)if(t.importGlobals){const O=c[0]?.line??1,v=await t.importGlobals({rows:c,startLine:O});nt(m,v)}else for(const O of c)m.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:m.conflicts,errors:m.errors,inserted:m.inserted}},Le=e=>typeof e=="object"&&e!==null?e:{},xe=e=>typeof e.kind=="string"?e.kind:"unknown",rn=(e,t)=>{let r=Le(t),n=!1;xe(r)==="optional"&&(n=!0,r=Le(r._meta?.inner));const s=xe(r),d=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof d.tableName=="string"&&(c.table=d.tableName),s==="array"){const l=xe(Le(d.inner));l!=="unknown"&&(c.element=l)}return c},nn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>rn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),on="/_lunora/admin/functions",an="/_lunora/admin/cron-jobs",sn="/_lunora/admin/openapi",dn="/_lunora/admin/openrpc",un="/_lunora/admin/global/tables",cn="/_lunora/admin/global/table",ln="/_lunora/admin/global/facet",ot=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:s,value:d}=n;return[{column:s,value:d}]});return r.length===0?void 0:r},hn=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),pn=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),fn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:d}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),T=Object.entries(w).flatMap(([_,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:nn(P.args),kind:P.kind,path:_}]).toSorted((_,P)=>_.path.localeCompare(P.path));return Response.json({functions:T},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),T=Object.entries(w).flatMap(([_,P])=>P.map(q=>({args:q.args,cron:_,functionPath:q.functionPath,name:q.name,shardKey:q.shardKey,workflow:q.workflow}))).toSorted((_,P)=>_.name.localeCompare(P.name));return Response.json({jobs:T},{headers:{"content-type":"application/json"},status:200})},m=p=>{if(p.method!=="GET")throw new a("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??hn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new a("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??pn,{headers:{"content-type":"application/json"},status:200})},v=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(p.url),_=s(T,"table");if(_===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:ot(s(T,"filters")),table:_});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},y=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),T=new URL(p.url),_=s(T,"table"),P=s(T,"column");if(_===void 0||P===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const q=s(T,"limit"),S=q===void 0?void 0:Number(q),G=await w.facetColumn({column:P,filters:ot(s(T,"filters")),limit:S!==void 0&&Number.isFinite(S)?S:void 0,table:_});return Response.json(G,{headers:{"content-type":"application/json"},status:200})};return{[an]:l,[on]:c,[ln]:y,[cn]:g,[un]:v,[sn]:m,[dn]:O}},wn="/_lunora/admin/kv/namespaces",mn="/_lunora/admin/kv/keys",bt="/_lunora/admin/kv/value",Ot=32*1048576,at=60,yn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=g=>r(g,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=g=>Response.json(g,{headers:{"content-type":"application/json"},status:200}),d=(g,y)=>{const p=new URL(g.url),w=p.searchParams.get("namespace")??"",T=p.searchParams.get("key")??"";if(w==="")throw new a(`KV-value ${y} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(T==="")throw new a(`KV-value ${y} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:T,namespace:w}},c=async(g,y)=>{if(!(await g.listNamespaces()).some(p=>p.binding===y))throw new a(`Unknown KV namespace binding \`${y}\``,{code:"NOT_FOUND",status:404})},l=async g=>{if(g.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(g).listNamespaces()})},m=async g=>{if(g.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=n(g),p=new URL(g.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const T=p.searchParams.get("prefix")??void 0,_=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),q=P===null?void 0:Number.parseInt(P,10);if(q!==void 0&&(!Number.isInteger(q)||q<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const S=q===void 0?void 0:Math.min(q,1e3);return await c(y,w),s(await y.listKeys({cursor:_,limit:S,namespace:w,prefix:T}))},O={DELETE:async g=>{const y=n(g),p=d(g,"DELETE");return await c(y,p.namespace),await y.deleteKey(p),s({deleted:!0})},GET:async g=>{const y=n(g),p=d(g,"GET");return await c(y,p.namespace),s(await y.getValue(p))},PUT:async g=>{const y=n(g),p=await t(g,Ot);if(typeof p.namespace!="string"||p.namespace==="")throw new a("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new a("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new a("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<at))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+at;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new a("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(y,p.namespace),await y.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},v=g=>{const y=O[g.method];if(!y)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return y(g)};return{[wn]:l,[mn]:m,[bt]:v}},gn="/_lunora/migrate",bn="/_lunora/admin/pitr",On="/_lunora/admin/rank",En="/_lunora/admin/rankpage",Tn="/_lunora/admin/shard-traffic",_n=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Rn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Sn=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!_n.has(r.functionPath))throw new a("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},An=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new a("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new a("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new a("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new a("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},vn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new a('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Dn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new a("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new a("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new a("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 a("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 a("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},kn=async e=>{let t;try{const s=await se(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};Dn(r);const n=vn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},In=async e=>{let t;try{const n=await se(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Pn=async e=>{const t=await te(e);if(typeof t.functionPath!="string"||!Rn.has(t.functionPath))throw new a("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new a("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Nn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:d,shardDO:c}=e,l=async(y,p)=>{if(y.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(y))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Sn(y),{headers:T}=await d(y,p),_=await s.orchestrateMigration(c,{args:w.args,functionPath:w.functionPath,headers:T,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},m=async(y,p)=>{if(y.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(y))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await An(y),{headers:T}=await d(y,p),_=await s.orchestrateRank(c,{headers:T,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},O=async(y,p)=>{if(y.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(y))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await kn(y),{headers:T}=await d(y,p),_=await s.orchestrateRankPage(c,{...w,headers:T});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},v=async(y,p)=>{if(y.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(y))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await In(y),{headers:T}=await d(y,p),_=await s.orchestrateShardTraffic(c,{headers:T,table:w.table});return Response.json(_,{headers:{"content-type":"application/json"},status:200})},g=async(y,p)=>{if(y.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(y))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Pn(y),{headers:T}=await d(y,p),_=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:T,method:"POST"});return r(c,w.shardKey??t,_)};return{[gn]:l,[bn]:g,[On]:m,[En]:O,[Tn]:v}},Un=1,qn=0,$n=32,Ln=512,xn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Bn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Ln)return;const r=t.split(",");if(!(r.length>$n)){for(const n of r)if(!xn.test(n.trim()))return;return t}},Cn=e=>{const t=or(e.headers.get("traceparent"));if(t===void 0)return;const r=Bn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},jn=(e,t={})=>{const r=Cn(e),n=t.trustInbound===!0?r:void 0,s=Re(8),d=n?.traceId??Re(16),c=yr(t.sampling,n===void 0?s:d),l=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:s,traceFlags:l?Un:qn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Gn=(e,t)=>{t.traceparent=nr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Kn=(e,t)=>{let r;return()=>{if(r===void 0){const n=dr(e),s=t===void 0?void 0:t.cf;r=ar(ir(n),sr(n,s))}return r}},Mn="/_lunora/admin/scheduled",Qn="/_lunora/admin/scheduled/status",Fn="/_lunora/admin/scheduled/ws",zn="/_lunora/admin/scheduled/cancel",Wn="/_lunora/admin/scheduled/dead",Hn="/_lunora/admin/scheduled/dead/retry",Jn="/_lunora/admin/scheduled/dead/cancel",Vn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,d=async g=>{if(g.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async g=>{if(g.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async g=>{if(g.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(g))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=r();return Se(y,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},m=async g=>{if(g.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const y=n(g),p=await g.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return y.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async g=>{if(g.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(g).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},v=g=>async y=>{if(y.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(y),w=await y.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new a("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${g}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[zn]:m,[Jn]:v("/dead/cancel"),[Wn]:O,[Hn]:v("/dead/retry"),[Mn]:d,[Qn]:c,[Fn]:l}},Yn="/_lunora/admin/storage",Xn="/_lunora/admin/storage/url",Zn="/_lunora/admin/storage/buckets",eo=10080*60,to=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:d,storage:c}=e,l=w=>{const T=n(w,"key");if(T===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return T},m=async w=>{const T=d(w,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(w.url),P=await T(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},v=async w=>{const T=d(w,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(w.url),P=l(_);return await T(P,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},g=async w=>{const T=d(w,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(w.url),P=l(_),q=await s(w),S=w.headers.get("content-type"),G=S===null||S===""?void 0:S,B=await T(P,q,{bucket:n(_,"bucket"),contentType:G});return Response.json(B,{headers:{"content-type":"application/json"},status:200})},y=async w=>{switch(w.method){case"DELETE":return v(w);case"GET":return m(w);case"POST":case"PUT":return g(w);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const T=d(w,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(w.url),P=l(_),q=Number(n(_,"expiresIn")??""),S=Number.isFinite(q)&&q>0?Math.min(q,eo):void 0,G=await T(P,{bucket:n(_,"bucket"),expiresInSeconds:S});return Response.json({key:P,url:G},{headers:{"content-type":"application/json"},status:200})};return{[Zn]:O,[Yn]:y,[Xn]:p}},ro=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},no={mtls:e=>ro(e,"tlsClientAuth","certVerified")==="SUCCESS"},oo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(no).find(([t])=>t===e)?.[1]??(()=>!1),ao=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[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.'))}},so="/_lunora/admin/vector/indexes",io="/_lunora/admin/vector/query",uo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{if(d.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async d=>{if(d.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new a("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(d);if(typeof l.name!="string"||l.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[so]:n,[io]:s}},co="/_lunora/admin/workflows/instances",lo="/_lunora/admin/workflows/instance",ho="/_lunora/admin/workflows/status",po={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},fo=e=>e!==null&&Object.hasOwn(po,e)?e:void 0,st=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},it=()=>{throw new a("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},wo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,m)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const v=Be(m,"name"),g=fo(m.searchParams.get("status"));return Response.json(await O.listInstances({page:st(m,"page"),perPage:st(m,"perPage"),status:g,workflowName:v}))},s=async(c,l,m)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(m,"id"),workflowName:Be(m,"name")})):it()},d=async(c,l)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const m=r(l);if(!m)return it();const O=await c.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:v}=O;if(v!=="pause"&&v!=="resume"&&v!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await m.setInstanceStatus({action:v,instanceId:O.id,workflowName:O.name}))};return{[lo]:s,[co]:n,[ho]:d}},mo=new TextEncoder,dt="/_lunora/rpc",yo="/_lunora/rpc-batch",go="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Kn(e,t),...r===void 0?{}:{waitUntil:r}}),ut=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},ct=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ce=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const s=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(s)?void 0:s,scheme:n.protocol.replace(":",""),userAgent:r}},lt="/_lunora/voice/",bo="/_lunora/scheduler/dispatch",Oo="/_lunora/admin/cron-jobs/run",Eo="/_lunora/admin/ws-token",To="/_lunora/admin/",_o="/_lunora/migrate",Ro="/_lunora/status",So=e=>e.startsWith(To)||e===_o,Ao=new Set(["1","enabled","on","true","yes"]),vo=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Do="/api/auth",ko="__lunora_admin__:recordAuthEvent",Io="__lunora_admin__:listPushSubscriptions",Po=["/sign-in","/sign-up","/callback"],No=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Po.some(s=>n===s||n.startsWith(`${s}/`))},Te=(e,t,r,n)=>{const s=er(r),d=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:l,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Uo=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ht=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,qo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ce=async(e,t,r)=>{const n={"content-type":"application/json"},s=e.headers.get("authorization"),d=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),m=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),d&&(n.cookie=d),c&&(n["x-d1-bookmark"]=c),l&&(n["x-lunora-mutation-id"]=l),m&&(n["x-lunora-client-id"]=m),O&&(n["x-lunora-client-seq"]=O);const v=e.headers.get("cf-connecting-ip");if(v&&(n["x-lunora-client-ip"]=v),!r)return{claims:null,headers:n,identity:null,userId:null};const g=await r(e,t);if(!g||typeof g.userId!="string"||g.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=g.userId;const y=Uo(g);y!==void 0&&(n["x-lunora-identity-exp"]=String(y));const{userId:p,...w}=g,T=Object.keys(w).length>0?w:null;return T&&(n["x-lunora-identity"]=JSON.stringify(T)),{claims:T,headers:n,identity:g,userId:p}},$o=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Lo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new a("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 a("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new a("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!$o.has(r.kind))throw new a("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new a("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new a("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},xo=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},pt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new a("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new a(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Bo=async e=>{const t=await se(e);let r;try{r=JSON.parse(t)}catch{throw new a("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new a("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new a("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=r,d=Lo(s.fanOut),c=s.args??{};if(d&&s.functionPath.startsWith("__lunora_relation__:")){const l=c.table;if(typeof l=="string"&&l!==d.table)throw new a("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=d.table}return{args:c,fanOut:d,functionPath:s.functionPath,shardKey:s.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Co=5e3,jo=4096,Go=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let s=0;try{const d=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const c=(await d.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return wt(_e,jo),_e.set(t,{expiresMs:r+Co,relayCount:s}),s},Ko=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let s=0;s<r;s+=1){const d=s<e.length?e.codePointAt(s)??0:0,c=s<t.length?t.codePointAt(s)??0:0;n|=d^c}return n===0},Mo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),d=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(d);let l="";for(const O of c)l+=String.fromCodePoint(O);const m=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return Ge(m,r)},ft=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...s]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,s.join(" ").trim())},Qo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Ir(t,n)?!0:r?!1:Ge(t,n)},Fo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},Et=e=>{const t=oo(e.trustInboundTraceContext),r=ao(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=wr(e.resolveIdentity,e.identity),d=Je(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:Je(e.schedulerDO,e.jurisdiction);let l;const m=()=>e.adminToken??l;let O;const v=()=>e.requireEphemeralWsToken??O??!1,g=o=>{const i=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const u=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(O=Ao.has(u.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=i.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},y=new WeakSet,p=o=>ft(o,m())||y.has(o),w=async(o,i)=>{const h=await ce(o,i,e.resolveIdentity);if(y.has(o)&&h.headers.authorization===void 0){const u=m();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let T=!1;const _=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new a(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}T||(T=!0,console.warn([`[lunora] SECURITY: serving ${o} 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("")))},P=Nn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:d}),q=async(o,i,h,u,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(b["x-lunora-mutation-id"]=u);const R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:b,method:"POST"});return ae(d,h,R)},S=async(o,i,h,u)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new a(`${u} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:i})},G=async(o,i,h)=>S(o,i.args??{},h,`cron job "${i.name}"`),B=async(o,i)=>{if(o.workflow){await G(o.workflow,o,i);return}if(o.functionPath===void 0)throw new a(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await q(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,i,h,u)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await B(b,i)}catch(R){h.push(u(R))}},N=async(o,i)=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new a("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new a("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await te(o),u=typeof h.name=="string"?h.name:"";if(u==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===u);if(!f)throw new a(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await B(f,i),Response.json({name:u,ran:!0},{status:200})},M=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!c||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Q=async(o,i)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await se(o),u=i??{},f=typeof u.LUNORA_SCHEDULER_SECRET=="string"?u.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),R=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(R&&f?E=await Mo(f,h,R):b&&(E=ft(o,b)),!E)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=A??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await S(k.workflow,U,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const $=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,L=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=vo(o),W=await q(k.functionPath,U,$,L,x);return await M(k),W},C=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(o,i,h)=>{if(C(o),i===void 0)throw new a(h.message,{code:h.code,status:400});return i},X=cr({assertAdmin:C,getReader:()=>e.authAuditReader}),J=async(o,i)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const u=i?.kind,f=i?.userId,b=i?.limit,R=u==="fcm"||u==="web-push"?u:void 0,E=typeof f=="string"&&f!==""?f:void 0,A=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=A>0?Math.min(A,1e3):1e3,U=(await h.list({kind:R,limit:k,userId:E})).filter($=>R!==void 0&&$.kind!==R?!1:E===void 0||($.userId??null)===E).map(({keys:$,token:L,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===ur)return X(o,i.args??{});if(i.functionPath===Io)return J(o,i.args)}},ie=Jr({applyGlobals:e.applyGlobals,assertAdmin:C,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>gt(),queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:w,shardDO:d,streamExportRows:(o,i,h,u)=>rt(e,o,i,h,u,d),streamingImport:(o,i)=>tn(o,e,i,d),syncGlobals:e.syncGlobals}),Z=(o,i)=>{const h=o.searchParams.get(i);return h===null||h===""?void 0:h},pe=o=>{const i=new URL(o.url),h=i.searchParams.get("limit"),u=i.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Ae=Vn({checkWsAdmin:async o=>p(o)||Qo(o,m(),v()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=wo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Tt=to({assertAdmin:C,parsePaging:pe,queryParameter:Z,readBodyBytes:Lr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),_t=uo({readJsonBody:te,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Rt=yn({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:K}),St=mr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:K}),At=fn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:Z,requireAdminOption:K}),vt=o=>{const i=[],h=d??o?.SHARD;if(h!==void 0&&i.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const b=Fo(u,f);b!==void 0&&i.push(b)}for(const u of e.health?.probes??[])i.push(u);return i},Dt=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:vt}),kt=async(o,i,h)=>{const{claims:u,headers:f,userId:b}=await ce(o,i,s),R=async(E,A={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:A,functionPath:k}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),$=await ae(d,n,U),L=await $.json();if(L.error)throw new a(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:$.status});return L.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:R,runMutation:R,runQuery:R}},It=async(o,i,h)=>{if(!e.httpRouter)return;const u=await kt(o,i,h);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:u},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Pt=async(o,i,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Ye(o,de);if(u)return u;const f=h.searchParams.get("shard")??n,{headers:b,identity:R}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(R,f))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&_("shard");const E=new Headers(o.headers),A=[...E.keys()];for(const x of A)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],$=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),$!==void 0&&E.set("x-lunora-identity-exp",$);const L=Ko(i,e.shardDO);if(L!==void 0){E.set("x-lunora-shard-binding",L);const x=await Go(d,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return ae(d,W,new Request(o,{headers:E}))}}return ae(d,f,new Request(o,{headers:E}))},Nt=async(o,i,h)=>{const{voiceAgents:u}=e;if(u===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ye(o,de);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(lt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(u,b)?u[b]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:k}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else _("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const $=A["x-lunora-userid"],L=A["x-lunora-identity"],x=A["x-lunora-identity-exp"];return $!==void 0&&U.set("x-lunora-userid",$),L!==void 0&&U.set("x-lunora-identity",L),x!==void 0&&U.set("x-lunora-identity-exp",x),ae(R,E,new Request(o,{headers:U}))},Ut=async(o,i,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,i))throw new a("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new a("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 a("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},Oe=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Ut(o.fanOut,o.functionPath,i);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(i,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&_("shard")}},ve=async(o,i,h,u,f,b)=>{const R=Date.now(),{observability:E,sampling:A}=e,k=Ce(o),{decision:U,ignoredUpstream:$,trace:L}=jn(o,{...A===void 0?{}:{sampling:A},trustInbound:t(o)});$&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Gn(L,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:i}),headers:x,method:"POST"});try{const j=await ae(d,u,W);return ue(E,{...k,...ct(L),durationMs:Date.now()-R,functionPath:i,ok:j.ok,shardKey:u,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:L.sampled,keepErrors:U.keepErrors}),j}catch(j){throw ue(E,{...k,...ct(L),...Te(i,Date.now()-R,j,{shardKey:u})},b,void 0,{isTraced:L.sampled,keepErrors:U.keepErrors}),j}},qt=o=>{if(o.fanOut&&o.shardKey)throw new a("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new a("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},$t=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await Bo(o);xo(i,u),qt(u);const f=await oe(o,u);if(f!==void 0)return f;const{headers:b,identity:R}=await ce(o,i,s);await Oe(u,R);const E=pt(u,e);{const A=Date.now(),{observability:k}=e,U=Ce(o),$=Ee(i,o,h&&(W=>h.waitUntil?.(W)));if(u.fanOut){const W=e.queryCoordinator;if(!W)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:b});return ue(k,{durationMs:Date.now()-A,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},$),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw ue(k,{...Te(u.functionPath,Date.now()-A,j,{fanOut:{table:u.fanOut.table}}),...U},$),j}}const L=u.shardKey??n,x=()=>ve(o,u.functionPath,u.args??{},L,b,$);return E&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:E.price},x,ut(h)):x()}},Lt=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await se(o);let f;try{f=JSON.parse(u)}catch{throw new a("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new a("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:E}=await ce(o,i,s),A=$r(b,n);for(const F of A.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${dt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...A.entries()].flatMap(([F,z])=>z.map(ne=>Oe({functionPath:ne.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(i,o,h&&(F=>h.waitUntil?.(F))),$=Ce(o),L=[],x=[],W=(F,z,ne,le)=>({body:{error:{code:ne,message:le}},id:F.id,status:z}),j=(F,z,ne,le,fe)=>{for(const H of F)ue(k,fe(H),U),L.push(W(H,z,ne,le))},Vt=(F,z,ne,le,fe)=>{for(const H of F){const we=le.get(H.id)??fe,ye=we<400;ue(k,{durationMs:ne,functionPath:H.functionPath,...$,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},U)}};await Promise.all([...A.entries()].map(async([F,z])=>{const ne=new Headers(R);ne.set("content-type","application/json");const le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let H;try{H=await ae(d,F,le)}catch(V){const Pe=Date.now()-fe,{body:ze}=tr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,ze.code,ze.message,Zt=>({...Te(Zt.functionPath,Pe,V,{shardKey:F}),...$}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let ke;try{ke=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Pe=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Pe.functionPath,...$,ok:!1,shardKey:F}));return}const Ie=Array.isArray(ke.results)?ke.results:[],Yt=new Map(Ie.map(V=>[V.id,V.status??H.status])),Xt=new Set(Ie.map(V=>V.id));Vt(z,F,we,Yt,H.status),L.push(...Ie);for(const V of z)Xt.has(V.id)||L.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Qe={"content-type":"application/json"},[Fe]=x;return x.length===1&&Fe!==void 0&&(Qe["x-d1-bookmark"]=Fe),Response.json({results:L},{headers:Qe,status:200})},xt=async(o,i,h,u={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:R,identity:E}=await ce(o,i,s);await Oe({functionPath:b,shardKey:f.shardKey},E);const A=f.shardKey??n,k=Ee(i,o,f.waitUntil);return await ve(o,b,u,A,R,k)}catch(b){return We(b)}},Bt=1e3,Ct=async(o,i)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let R=0;R<Bt;R+=1){const E=await o.list({cursor:f,prefix:i});for(const A of E.objects)A.key.endsWith(".manifest.json")&&u.push(A.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=u.toSorted((R,E)=>E.localeCompare(R)).slice(h);await Promise.all(b.flatMap(R=>{const E=R.slice(0,-14);return[o.delete(R),o.delete(E)]}))},jt=async o=>{const i=e.backupStore,h=e.queryCoordinator;if(!i)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const u=m();if(!u||u.length===0)throw new a("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${u}`,"content-type":"application/json"},b=e.backupTables;let R=0,E=0;const A=[];await rt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
+
`;R+=1,E+=mo.encode(j).byteLength,A.push(j)},d);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),$=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,L=`${$}.manifest.json`;await i.put($,new Blob(A,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const x={bytes:E,createdAt:U,cron:o.cron,file:$,id:U,rows:R,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await i.put(L,`${JSON.stringify(x,void 0,2)}
|
|
6
|
+
`,{httpMetadata:{contentType:"application/json"}}),await Ct(i,k)},Ke=async(o,i,h)=>{const{observability:u}=e,f=Date.now(),b=Re(16),R=Re(8),E=ht(i);try{const A=await h();return ue(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:R,traceId:b},E),A}catch(A){throw ue(u,{...Te(o,Date.now()-f,A,{}),spanId:R,traceId:b},E),A}finally{He(u,E)}},Gt=async(o,i,h)=>{g(i);const u=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,i,h)}catch(E){u.push(f(E))}if(await Y(o.cron,i,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await jt(o)}catch(E){u.push(f(E))}const[R]=u;if(u.length===1&&R)throw R;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Kt=async(o,i)=>{try{const h=o??{},u=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:i},functionPath:ko}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await ae(d,n,f)}catch{}},Mt=async(o,i,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Do;return No(h.pathname,b)&&u.waitUntil?.(Kt(i,f.status>=400?"fail":"ok")),f},Qt=async({args:o,env:i,functionPath:h,request:u,shardKey:f,waitUntil:b})=>{const R={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:A}=await ce(u,i,s);await Oe(R,A);const k=f??n,U=Ee(i,u,b),$=()=>ve(u,h,o,k,E,U),L=pt(R,e);return L&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:L.price},$,ut({waitUntil:b})):$()},Ft=gr({functions:e.functions??{},invoke:Qt,readJsonBody:te,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,zt={[Ro]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[go]:(o,i,h)=>Pt(o,i,h),[dt]:(o,i,h,u)=>$t(o,i,u),[yo]:(o,i,h,u)=>Lt(o,i,u),[bo]:(o,i)=>Q(o,i),[Oo]:(o,i)=>N(o,i),[Eo]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const i=m();if(i===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ie,...Ae,...re,...Tt,..._t,...Rt,...St,...At,...Dt,...Ft,...Ur({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:Z,readJsonBody:te})};let de=Ve(e.security),Me=!1;const Wt=o=>{Me||(Me=!0,de=Ve(e.security,o??{}))},Ht=async(o,i)=>{if(!(e.adminGate===void 0||!So(i)))try{await e.adminGate(o)&&y.add(o)}catch{}},Jt=async(o,i,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),A=u.pathname===bt?Ot:ge;if(Number.isFinite(E)&&E>A)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Mt(o,i,u,h);if(f)return f;if(De){const E=`${o.method} ${u.pathname}`,A=De[E]??De[u.pathname];if(A)return A(o,i,h)}const b=zt[u.pathname];return b?(await Ht(o,u.pathname),b(o,i,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(lt)?Nt(o,i,u):await It(o,i,h)||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Wt(i),g(i);const u=br(o,de);if(u)return u;const f=Or(o,de);if(f)return Ue(f,o,de);try{const b=await Jt(o,i,h);return Ue(b,o,de)}catch(b){return Ue(We(b),o,de)}finally{He(e.observability,ht(h))}},async queue(o,i,h){await Ke(`queue:${qo(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await Ke(`cron:${o.cron}`,h,async()=>{await Gt(o,i,h)})},serverQuery:xt}},zo=e=>Et(e),Wo=e=>typeof e=="function"?{fetch:e}:e,Ho=e=>!!(e.crons??e.cronJobs??e.backupCron),ca=(e,t)=>{const r=Wo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const l=zo({...c,httpRouter:r});return n!==void 0&&!Ho(c)?{...l,scheduled:async(m,O,v)=>{await n(m,O,v)}}:l};if(typeof t!="function")return s(t);const d=t;return{fetch:(c,l,m)=>s(d(l)).fetch(c,l,m),queue:(c,l,m)=>s(d(l)).queue?.(c,l,m)??Promise.resolve(),scheduled:(c,l,m)=>s(d(l)).scheduled(c,l,m),serverQuery:(c,l,m,O,v)=>s(d(l)).serverQuery(c,l,m,O,v)}},Jo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new a("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},la=(e={})=>(t,r,n)=>Et(Jo(e,r)).fetch(t,r,n??rr),ha=e=>e;export{ur as GET_AUTH_AUDIT_LOG_OP,rr as NOOP_EXECUTION_CONTEXT,wa as composeIdentityResolvers,zo as composeWorker,la as createLunoraHandler,Et as createWorker,ha as defineRpcEnvelope,Go as probeRelayCount,Jo as resolveLunoraOptions,ma as routeIdentityResolvers,ca as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as o}from"./LunoraError-
|
|
1
|
+
import{LunoraError as o}from"./LunoraError-C08OP5Uq.mjs";const u="/_lunora/rpc",d=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=r.userId),r.identity!==void 0&&(t["x-lunora-identity"]=JSON.stringify(r.identity)),t},i=async(r,t,n)=>{const e=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${u}`,{body:JSON.stringify(t),headers:d(r),method:"POST"}));if(!e.ok)throw new o(`cross-shard relation ${n} failed: worker returned ${String(e.status)}`);const a=await e.json();if(typeof a.failed=="number"&&a.failed>0){const s=(typeof a.ok=="number"?a.ok:0)+a.failed;throw new o(`cross-shard relation ${n} failed on ${String(a.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return a.data},c=r=>({crossShardCounter:async(t,n)=>{const e=await i(r,{args:{table:t,where:n},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof e=="number"?e:0},crossShardReader:async(t,n)=>{const e=await i(r,{args:{orderBy:n?.orderBy,table:t,where:n?.where,with:n?.with},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(e)?e:[]}}});export{c as createCrossShardRelationCapabilities};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as M}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-uRQLx282.mjs";const ye=t=>({listShardKeys(e){return t[e]??[]}}),me=t=>{if(t.kind==="count")return{kind:"sum"};if(t.kind==="scalar"){if(t.op==="count"||t.op==="sum")return{kind:"sum"};if(t.op==="max")return{kind:"max"};if(t.op==="min")return{kind:"min"};throw new M('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=t.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new M('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},q=16,F=5e3,m=t=>t!==null&&typeof t=="object"&&"result"in t?t.result:t,B=t=>{const e=t??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},I=(t,e)=>t?"failed":e?"in_progress":"completed",R=t=>{const e=[];let s=0,o=0,r=0,a=0,n=!1,i=!1;for(const u of t){if(u.kind==="err"){o+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=m(u.value),c=B(d);r+=c.changed,a+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:r,failed:o,ok:s,processed:a,shards:e,status:I(i,n||o>0)}},D=t=>{const e=t??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},V=t=>{const e=[];let s=0,o=0,r=0,a=0;for(const n of t){if(n.kind==="err"){o+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=D(m(n.value));r+=i.before,a+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:o,ok:s,partial:o>0,position:r+1,shards:e,total:a}},T=0,j=1,$=2,N=t=>t==null?T:typeof t=="number"?j:$,x=(t,e)=>{const s=N(t),o=N(e);if(s!==o)return s<o?-1:1;if(s===T)return 0;if(s===j){const n=t,i=e;return n<i?-1:n>i?1:0}const r=String(t),a=String(e);return r<a?-1:r>a?1:0},J=(t,e,s)=>{const o=x(t.partitionKey,e.partitionKey);if(o!==0)return o;const r=Math.max(t.sortValues.length,e.sortValues.length);for(let a=0;a<r;a+=1){const n=x(t.sortValues[a],e.sortValues[a]);if(n!==0)return s[a]==="desc"?-n:n}return x(t.rowId,e.rowId)},Q=t=>{const e=JSON.stringify(t),s=new TextEncoder().encode(e);let o="";for(const r of s)o+=String.fromCodePoint(r);return btoa(o)},U=t=>{let e;try{const s=atob(t),o=Uint8Array.from(s,r=>r.codePointAt(0)??0);e=new TextDecoder().decode(o)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:o}=s;if(o!==null&&typeof o=="object")return{perShard:o}}}catch{}return{perShard:{}}},L=t=>{const e=t??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},G=(t,e)=>{let s,o;for(const r of t){const a=r.rows[r.head];a!==void 0&&(o===void 0||J(a.key,o,e)<0)&&(s=r,o=a.key)}return s},Y=(t,e)=>{let s=!1;const o=new Set;for(const a of t)o.add(a.shardKey),(a.head<a.rows.length||a.hasMore)&&(s=!0);const r={...e};for(const a of Object.keys(e))o.has(a)||(s=!0);return s?Q({perShard:r}):null},z=(t,e,s,o)=>{const r=[],a={...o};for(;r.length<e;){const i=G(t,s);if(i===void 0)break;const u=i.rows[i.head];u!==void 0&&(r.push(u.doc),a[i.shardKey]=u.key),i.head+=1}const n=Y(t,a);return{isDone:n===null,nextCursor:n,page:r}},H=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const a=m(r.value),n=Array.isArray(a?.rows)?a.rows:[];e.push({rows:n,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},W=t=>{const e=[];let s=0,o=0;for(const{outcome:r,sinceSeq:a}of t){if(r.kind==="err"){o+=1,e.push({cursor:a,error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const n=m(r.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:a;e.push({changes:i,cursor:u,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},X=t=>{let e=0,s=0,o=0;for(const r of t){if(r.kind==="err"){s+=1;continue}e+=1;const a=m(r.value);o+=typeof a?.applied=="number"?a.applied:0}return{applied:o,failed:s,ok:e}},Z=t=>{const e=t??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},ee=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({requests:0,shardKey:r.shardKey});continue}s+=1,e.push({requests:Z(m(r.value)),shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},te=t=>{const e=[],s={},o=[];let r=0,a=0,n=0;for(const i of t){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}a+=1;const u=m(i.value),d=u?.inserted??{};for(const[l,p]of Object.entries(d))s[l]=(s[l]??0)+p;const c=u?.errors;Array.isArray(c)&&o.push(...c),r+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:r,errors:o,failed:n,inserted:s,ok:a,shards:e}},k=t=>({body:JSON.stringify({args:t.args??{},functionPath:t.functionPath}),headers:{"content-type":"application/json",...t.headers}}),S=async(t,e,s,o)=>{const r=C(t,e),a=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:a.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{a.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const c=await r.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},K=async(t,e,s,o,r)=>{if(e.length===0)return[];const a=k(s),n=Array.from({length:e.length});let i=0;const u=async()=>{for(;;){const c=i;i+=1;const l=e[c];if(c>=e.length||l===void 0)return;n[c]=await S(t,l,a,r)}},d=Math.min(o,e.length);return await Promise.all(Array.from({length:d},()=>u())),n},re=(t,e)=>t<e?-1:t>e?1:0,se=t=>{const e={};for(const s of Object.keys(t).toSorted(re))e[s]=t[s]??null;return JSON.stringify(e)},oe=t=>{const e=[];for(const s of t)Array.isArray(s)&&e.push(...s);return e},ae=(t,e,s)=>{switch(s){case"max":return Math.max(t,e);case"min":return Math.min(t,e);case"sum":return t+e;default:return t}},ne=(t,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},r=e.value??null,a=se(o),n=t.get(a);if(!n){t.set(a,{key:o,value:r});return}if(n.value===null){n.value=r;return}r!==null&&(n.value=ae(n.value,r,s))},ie=(t,e)=>{const s=new Map;for(const o of t)if(Array.isArray(o))for(const r of o)ne(s,r,e);return[...s.values()]},E=(t,e)=>{let s=null;for(const o of t)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},ce=t=>{let e=0;for(const s of t)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ue=t=>{let e=0,s=0;for(const o of t){if(o===null||typeof o!="object")continue;const r=o;typeof r.before=="number"&&Number.isFinite(r.before)&&(e+=r.before),typeof r.total=="number"&&Number.isFinite(r.total)&&(s+=r.total)}return{position:e+1,total:s}},de=(t,e)=>{const s=[];for(const a of t)if(Array.isArray(a))for(const n of a){if(n===null||typeof n!="object")continue;const i=n[e.by],u=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:u})}const o=e.direction??"desc",r=(a,n)=>a<n?-1:a>n?1:0;return s.sort((a,n)=>o==="asc"?r(a.score,n.score):r(n.score,a.score)),s.slice(0,e.k).map(a=>a.row)},le=(t,e)=>{switch(e.kind){case"concat":return oe(t);case"first":return t[0];case"groupBy":return ie(t,e.op??"sum");case"max":return E(t,(s,o)=>Math.max(s,o));case"min":return E(t,(s,o)=>Math.min(s,o));case"rank":return ue(t);case"sum":return ce(t);case"topK":return de(t,e);default:return t}},ge=t=>{const e=t.maxConcurrency??q,s=t.perShardTimeoutMs??F;if(e<1)throw new M("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,r){const a=await t.registry.listShardKeys(r.fanOut.table),n=await K(o,a,r,e,s),i=[],u=[],d=[];for(const c of n)c.kind==="ok"?(i.push(c.value),u.push(c.shardKey)):d.push({message:c.message,shardKey:c.shardKey,timedOut:c.timedOut});return{data:le(i,r.fanOut.merge),errors:d,failed:d.length,ok:u.length}},async orchestrateExport(o,r){const a=new Set,n=await Promise.all(r.tables.map(async c=>t.registry.listShardKeys(c)));for(const c of n)for(const l of c)a.add(l);const i=[...a],u={args:{...r.args,tables:[...r.tables]},functionPath:"__lunora_admin__:exportShard",headers:r.headers},d=await K(o,i,u,e,s);return H(d)},async orchestrateCdcSync(o,r){const a=new Set,n=await Promise.all(r.tables.map(async f=>t.registry.listShardKeys(f)));for(const f of n)for(const y of f)a.add(y);const i=[...a],u=r.cursors??{},d=Array.from({length:i.length});let c=0;const l=Math.min(e,i.length),p=async()=>{for(;;){const f=c;c+=1;const y=i[f];if(f>=i.length||y===void 0)return;const g=u[y]??0,b=await S(o,y,k({args:{limit:r.limit,sinceSeq:g},functionPath:"__lunora_admin__:cdcSync",headers:r.headers}),s);d[f]={outcome:b,sinceSeq:g}}};return l>0&&await Promise.all(Array.from({length:l},()=>p())),W(d)},async orchestrateImport(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{rows:[...l.rows],startLine:l.startLine??1},functionPath:"__lunora_admin__:importShard",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),te(n)},async orchestrateApplyCdc(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{changes:[...l.changes]},functionPath:"__lunora_admin__:applyCdc",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),X(n)},async orchestrateMigration(o,r){const a=await t.registry.listShardKeys(r.table),n=await K(o,a,r,e,s);return R(n)},async orchestrateRank(o,r){const a=await t.registry.listShardKeys(r.table),n={args:{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:[...r.sortValues],table:r.table},functionPath:"__lunora_admin__:rankBefore",headers:r.headers},i=await K(o,a,n,e,s);return V(i)},async orchestrateRankPage(o,r){const a=await t.registry.listShardKeys(r.table),n=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),i=r.directions??[],u=r.cursor?U(r.cursor):{perShard:{}},d=Array.from({length:a.length});let c=0;const l=Math.min(e,a.length),p=async()=>{for(;;){const h=c;c+=1;const w=a[h];if(h>=a.length||w===void 0)return;const P=u.perShard[w],A={index:r.index,table:r.table,take:n};r.partitionKey!==void 0&&(A.partitionKey=r.partitionKey),P!==void 0&&(A.after=P);const _=await S(o,w,k({args:A,functionPath:"__lunora_admin__:rankPage",headers:r.headers}),s);if(_.kind==="err"){d[h]={error:{message:_.message,timedOut:_.timedOut},shardKey:w};continue}const O=L(m(_.value));d[h]={directions:O.directions,hasMore:O.hasMore,rows:O.rows,shardKey:w}}};l>0&&await Promise.all(Array.from({length:l},()=>p()));const f=[];let y=0,g=0,b;for(const h of d){if(h.error){g+=1;continue}y+=1,b===void 0&&h.directions&&h.directions.length>0&&(b=h.directions),f.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const v=z(f,n,b??i,u.perShard);return{continueCursor:v.nextCursor,failed:g,isDone:v.isDone,ok:y,page:v.page,partial:g>0,shards:d}},async orchestrateShardTraffic(o,r){const a=await t.registry.listShardKeys(r.table),n={functionPath:"__lunora_admin__:getMetrics",headers:r.headers},i=await K(o,a,n,e,s);return ee(i)},registry:t.registry}};export{ge as createQueryCoordinator,ye as createStaticShardRegistry,me as mergeStrategyForAggregate};
|
|
1
|
+
import{LunoraError as M}from"./LunoraError-C08OP5Uq.mjs";import{resolveShard as C}from"./applyJurisdiction-uRQLx282.mjs";const ye=t=>({listShardKeys(e){return t[e]??[]}}),me=t=>{if(t.kind==="count")return{kind:"sum"};if(t.kind==="scalar"){if(t.op==="count"||t.op==="sum")return{kind:"sum"};if(t.op==="max")return{kind:"max"};if(t.op==="min")return{kind:"min"};throw new M('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=t.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new M('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},q=16,F=5e3,m=t=>t!==null&&typeof t=="object"&&"result"in t?t.result:t,B=t=>{const e=t??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},I=(t,e)=>t?"failed":e?"in_progress":"completed",R=t=>{const e=[];let s=0,o=0,r=0,a=0,n=!1,i=!1;for(const u of t){if(u.kind==="err"){o+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=m(u.value),c=B(d);r+=c.changed,a+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:r,failed:o,ok:s,processed:a,shards:e,status:I(i,n||o>0)}},D=t=>{const e=t??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},V=t=>{const e=[];let s=0,o=0,r=0,a=0;for(const n of t){if(n.kind==="err"){o+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=D(m(n.value));r+=i.before,a+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:o,ok:s,partial:o>0,position:r+1,shards:e,total:a}},T=0,j=1,$=2,N=t=>t==null?T:typeof t=="number"?j:$,x=(t,e)=>{const s=N(t),o=N(e);if(s!==o)return s<o?-1:1;if(s===T)return 0;if(s===j){const n=t,i=e;return n<i?-1:n>i?1:0}const r=String(t),a=String(e);return r<a?-1:r>a?1:0},J=(t,e,s)=>{const o=x(t.partitionKey,e.partitionKey);if(o!==0)return o;const r=Math.max(t.sortValues.length,e.sortValues.length);for(let a=0;a<r;a+=1){const n=x(t.sortValues[a],e.sortValues[a]);if(n!==0)return s[a]==="desc"?-n:n}return x(t.rowId,e.rowId)},Q=t=>{const e=JSON.stringify(t),s=new TextEncoder().encode(e);let o="";for(const r of s)o+=String.fromCodePoint(r);return btoa(o)},U=t=>{let e;try{const s=atob(t),o=Uint8Array.from(s,r=>r.codePointAt(0)??0);e=new TextDecoder().decode(o)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:o}=s;if(o!==null&&typeof o=="object")return{perShard:o}}}catch{}return{perShard:{}}},L=t=>{const e=t??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},G=(t,e)=>{let s,o;for(const r of t){const a=r.rows[r.head];a!==void 0&&(o===void 0||J(a.key,o,e)<0)&&(s=r,o=a.key)}return s},Y=(t,e)=>{let s=!1;const o=new Set;for(const a of t)o.add(a.shardKey),(a.head<a.rows.length||a.hasMore)&&(s=!0);const r={...e};for(const a of Object.keys(e))o.has(a)||(s=!0);return s?Q({perShard:r}):null},z=(t,e,s,o)=>{const r=[],a={...o};for(;r.length<e;){const i=G(t,s);if(i===void 0)break;const u=i.rows[i.head];u!==void 0&&(r.push(u.doc),a[i.shardKey]=u.key),i.head+=1}const n=Y(t,a);return{isDone:n===null,nextCursor:n,page:r}},H=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const a=m(r.value),n=Array.isArray(a?.rows)?a.rows:[];e.push({rows:n,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},W=t=>{const e=[];let s=0,o=0;for(const{outcome:r,sinceSeq:a}of t){if(r.kind==="err"){o+=1,e.push({cursor:a,error:{message:r.message,timedOut:r.timedOut},shardKey:r.shardKey});continue}s+=1;const n=m(r.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:a;e.push({changes:i,cursor:u,shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},X=t=>{let e=0,s=0,o=0;for(const r of t){if(r.kind==="err"){s+=1;continue}e+=1;const a=m(r.value);o+=typeof a?.applied=="number"?a.applied:0}return{applied:o,failed:s,ok:e}},Z=t=>{const e=t??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},ee=t=>{const e=[];let s=0,o=0;for(const r of t){if(r.kind==="err"){o+=1,e.push({requests:0,shardKey:r.shardKey});continue}s+=1,e.push({requests:Z(m(r.value)),shardKey:r.shardKey})}return{failed:o,ok:s,shards:e}},te=t=>{const e=[],s={},o=[];let r=0,a=0,n=0;for(const i of t){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}a+=1;const u=m(i.value),d=u?.inserted??{};for(const[l,p]of Object.entries(d))s[l]=(s[l]??0)+p;const c=u?.errors;Array.isArray(c)&&o.push(...c),r+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:r,errors:o,failed:n,inserted:s,ok:a,shards:e}},k=t=>({body:JSON.stringify({args:t.args??{},functionPath:t.functionPath}),headers:{"content-type":"application/json",...t.headers}}),S=async(t,e,s,o)=>{const r=C(t,e),a=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:a.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{a.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const c=await r.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},K=async(t,e,s,o,r)=>{if(e.length===0)return[];const a=k(s),n=Array.from({length:e.length});let i=0;const u=async()=>{for(;;){const c=i;i+=1;const l=e[c];if(c>=e.length||l===void 0)return;n[c]=await S(t,l,a,r)}},d=Math.min(o,e.length);return await Promise.all(Array.from({length:d},()=>u())),n},re=(t,e)=>t<e?-1:t>e?1:0,se=t=>{const e={};for(const s of Object.keys(t).toSorted(re))e[s]=t[s]??null;return JSON.stringify(e)},oe=t=>{const e=[];for(const s of t)Array.isArray(s)&&e.push(...s);return e},ae=(t,e,s)=>{switch(s){case"max":return Math.max(t,e);case"min":return Math.min(t,e);case"sum":return t+e;default:return t}},ne=(t,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},r=e.value??null,a=se(o),n=t.get(a);if(!n){t.set(a,{key:o,value:r});return}if(n.value===null){n.value=r;return}r!==null&&(n.value=ae(n.value,r,s))},ie=(t,e)=>{const s=new Map;for(const o of t)if(Array.isArray(o))for(const r of o)ne(s,r,e);return[...s.values()]},E=(t,e)=>{let s=null;for(const o of t)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},ce=t=>{let e=0;for(const s of t)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ue=t=>{let e=0,s=0;for(const o of t){if(o===null||typeof o!="object")continue;const r=o;typeof r.before=="number"&&Number.isFinite(r.before)&&(e+=r.before),typeof r.total=="number"&&Number.isFinite(r.total)&&(s+=r.total)}return{position:e+1,total:s}},de=(t,e)=>{const s=[];for(const a of t)if(Array.isArray(a))for(const n of a){if(n===null||typeof n!="object")continue;const i=n[e.by],u=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:u})}const o=e.direction??"desc",r=(a,n)=>a<n?-1:a>n?1:0;return s.sort((a,n)=>o==="asc"?r(a.score,n.score):r(n.score,a.score)),s.slice(0,e.k).map(a=>a.row)},le=(t,e)=>{switch(e.kind){case"concat":return oe(t);case"first":return t[0];case"groupBy":return ie(t,e.op??"sum");case"max":return E(t,(s,o)=>Math.max(s,o));case"min":return E(t,(s,o)=>Math.min(s,o));case"rank":return ue(t);case"sum":return ce(t);case"topK":return de(t,e);default:return t}},ge=t=>{const e=t.maxConcurrency??q,s=t.perShardTimeoutMs??F;if(e<1)throw new M("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,r){const a=await t.registry.listShardKeys(r.fanOut.table),n=await K(o,a,r,e,s),i=[],u=[],d=[];for(const c of n)c.kind==="ok"?(i.push(c.value),u.push(c.shardKey)):d.push({message:c.message,shardKey:c.shardKey,timedOut:c.timedOut});return{data:le(i,r.fanOut.merge),errors:d,failed:d.length,ok:u.length}},async orchestrateExport(o,r){const a=new Set,n=await Promise.all(r.tables.map(async c=>t.registry.listShardKeys(c)));for(const c of n)for(const l of c)a.add(l);const i=[...a],u={args:{...r.args,tables:[...r.tables]},functionPath:"__lunora_admin__:exportShard",headers:r.headers},d=await K(o,i,u,e,s);return H(d)},async orchestrateCdcSync(o,r){const a=new Set,n=await Promise.all(r.tables.map(async f=>t.registry.listShardKeys(f)));for(const f of n)for(const y of f)a.add(y);const i=[...a],u=r.cursors??{},d=Array.from({length:i.length});let c=0;const l=Math.min(e,i.length),p=async()=>{for(;;){const f=c;c+=1;const y=i[f];if(f>=i.length||y===void 0)return;const g=u[y]??0,b=await S(o,y,k({args:{limit:r.limit,sinceSeq:g},functionPath:"__lunora_admin__:cdcSync",headers:r.headers}),s);d[f]={outcome:b,sinceSeq:g}}};return l>0&&await Promise.all(Array.from({length:l},()=>p())),W(d)},async orchestrateImport(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{rows:[...l.rows],startLine:l.startLine??1},functionPath:"__lunora_admin__:importShard",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),te(n)},async orchestrateApplyCdc(o,r){const{batches:a}=r,n=Array.from({length:a.length});let i=0;const u=Math.min(e,a.length),d=async()=>{for(;;){const c=i;i+=1;const l=a[c];if(c>=a.length||l===void 0)return;n[c]=await S(o,l.shardKey,k({args:{changes:[...l.changes]},functionPath:"__lunora_admin__:applyCdc",headers:r.headers}),s)}};return u>0&&await Promise.all(Array.from({length:u},()=>d())),X(n)},async orchestrateMigration(o,r){const a=await t.registry.listShardKeys(r.table),n=await K(o,a,r,e,s);return R(n)},async orchestrateRank(o,r){const a=await t.registry.listShardKeys(r.table),n={args:{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:[...r.sortValues],table:r.table},functionPath:"__lunora_admin__:rankBefore",headers:r.headers},i=await K(o,a,n,e,s);return V(i)},async orchestrateRankPage(o,r){const a=await t.registry.listShardKeys(r.table),n=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),i=r.directions??[],u=r.cursor?U(r.cursor):{perShard:{}},d=Array.from({length:a.length});let c=0;const l=Math.min(e,a.length),p=async()=>{for(;;){const h=c;c+=1;const w=a[h];if(h>=a.length||w===void 0)return;const P=u.perShard[w],A={index:r.index,table:r.table,take:n};r.partitionKey!==void 0&&(A.partitionKey=r.partitionKey),P!==void 0&&(A.after=P);const _=await S(o,w,k({args:A,functionPath:"__lunora_admin__:rankPage",headers:r.headers}),s);if(_.kind==="err"){d[h]={error:{message:_.message,timedOut:_.timedOut},shardKey:w};continue}const O=L(m(_.value));d[h]={directions:O.directions,hasMore:O.hasMore,rows:O.rows,shardKey:w}}};l>0&&await Promise.all(Array.from({length:l},()=>p()));const f=[];let y=0,g=0,b;for(const h of d){if(h.error){g+=1;continue}y+=1,b===void 0&&h.directions&&h.directions.length>0&&(b=h.directions),f.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const v=z(f,n,b??i,u.perShard);return{continueCursor:v.nextCursor,failed:g,isDone:v.isDone,ok:y,page:v.page,partial:g>0,shards:d}},async orchestrateShardTraffic(o,r){const a=await t.registry.listShardKeys(r.table),n={functionPath:"__lunora_admin__:getMetrics",headers:r.headers},i=await K(o,a,n,e,s);return ee(i)},registry:t.registry}};export{ge as createQueryCoordinator,ye as createStaticShardRegistry,me as mergeStrategyForAggregate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"./LunoraError-
|
|
1
|
+
import{LunoraError as m}from"./LunoraError-C08OP5Uq.mjs";const y="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",O=e=>{const r=["base-uri 'none'","object-src 'none'"];return e==="DENY"?r.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&r.push("frame-ancestors 'self'"),r.join("; ")},v="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],b=31536e3,A=new Set(["GET","HEAD","OPTIONS"]),L=e=>{if(e===!1)return;const r=e===void 0||e===!0?{}:e,s=r.maxAge??b,o=r.includeSubDomains??!0;return`max-age=${String(s)}${o?"; includeSubDomains":""}${r.preload?"; preload":""}`},R=(e,r)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:r,value:y}},S=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const r=e===void 0||e===!0?{}:e,s=r.frameOptions===!1?void 0:r.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:R(r.csp,O(s)),enabled:!0,frameOptions:s,hsts:L(r.hsts),permissionsPolicy:r.permissionsPolicy===!1?void 0:r.permissionsPolicy??v,referrerPolicy:r.referrerPolicy===!1?void 0:r.referrerPolicy??"strict-origin-when-cross-origin"}},E=e=>{const r={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return r;const s=e.allowCredentials??!1,o=e.allowedOrigins;let t,i;if(typeof o=="function")t=o,i=o,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" 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 l=o;if(l.includes("*")&&s)throw new m('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=n=>l.includes("*")||l.includes(n),i=n=>l.includes(n)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:i,maxAge:e.maxAge??600}},C=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const r=e===void 0||e===!0?{}:e;return{allowLoopback:r.allowLoopback??!0,enabled:!0,trustedOrigins:r.trustedOrigins??[]}},x=new Set(["0","disabled","false","no","off"]),I=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&x.has(e.trim().toLowerCase()),P=e=>typeof e=="string"&&I.has(e.trim().toLowerCase()),k=e=>{const r=e?.LUNORA_ALLOWED_ORIGINS;if(typeof r!="string")return;const s=r.split(",").map(o=>o.trim()).filter(o=>o.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&P(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},H=(e,r)=>{const s=e?.headers??(f(r?.LUNORA_SECURITY_HEADERS)?!1:void 0),o=e?.csrf??(f(r?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??k(r);return{cors:E(t),csrf:C(o),headers:S(s)}},N=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return N.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,r,s)=>e===r||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(r)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),g=(e,r,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${r===void 0?"was missing":`"${r}"`} is not trusted (this worker serves "${s}"). 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:r}},{headers:{"content-type":"application/json"},status:403}),j=(e,r)=>{if(!r.csrf.enabled||A.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin state-changing request",o,s)},$=(e,r)=>{if(!r.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin websocket upgrade",o,s)},w=(e,r)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.append("vary","Origin"),r.allowCredentials&&s.set("access-control-allow-credentials","true"),s},M=(e,r)=>{if(!r.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!r.cors.isAllowed(s))return;const o=w(s,r.cors),t=e.headers.get("access-control-request-headers");o.set("access-control-allow-methods",r.cors.allowedMethods.join(", "));let i;if(t===null)i=r.cors.allowedHeaders.join(", ");else{const l=new Set(r.cors.allowedHeaders.map(n=>n.toLowerCase()));i=t.split(",").map(n=>n.trim()).filter(n=>n.length>0&&l.has(n.toLowerCase())).join(", ")}return o.set("access-control-allow-headers",i),o.set("access-control-max-age",String(r.cors.maxAge)),new Response(null,{headers:o,status:204})},D=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,r,s)=>{e.has(r)||e.set(r,s)},T=(e,r,s,o)=>{if(o.hsts!==void 0&&new URL(r.url).protocol==="https:"&&a(e,"strict-transport-security",o.hsts),a(e,"x-content-type-options","nosniff"),o.frameOptions!==void 0&&a(e,"x-frame-options",o.frameOptions),o.referrerPolicy!==void 0&&a(e,"referrer-policy",o.referrerPolicy),o.permissionsPolicy!==void 0&&a(e,"permissions-policy",o.permissionsPolicy),o.coop!==void 0&&a(e,"cross-origin-opener-policy",o.coop),o.csp!==void 0){const t=D(s)?o.csp.htmlValue:o.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},U=(e,r,s)=>{const o=r.headers.get("origin");if(!(!o||!s.isAllowed(o)))for(const[t,i]of w(o,s).entries())t==="vary"?e.append("vary",i):a(e,t,i)},G=(e,r,s)=>{if(e.status===101||e.webSocket)return e;const o=new Headers(e.headers);return s.headers.enabled&&T(o,r,e,s.headers),s.cors.enabled&&U(o,r,s.cors),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})};export{G as decorateResponse,j as enforceOrigin,$ as enforceWebSocketOrigin,M as handleCorsPreflight,H as resolveSecurity};
|
package/package.json
CHANGED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as rr,toErrorBody as nr}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as ar,A as sr,R as ir,d as dr,i as ur,s as cr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as s,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as lr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as we}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as hr,durableObjectProbe as pr,d1Probe as fr,presenceProbe as Pe}from"./HEALTH_PATH-BEE0A_lZ.mjs";import{wrapResolverWithContract as wr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ma,routeIdentityResolvers as ya}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as mr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as yr,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as gr}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Je,handleCorsPreflight as br,enforceOrigin as Or,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const mt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Er="::relay::",Tr=(e,t)=>`${e}${Er}${String(t)}`,Ce=new TextEncoder,_r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Rr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},Sr=64,Ue=new Map,yt=async e=>{const t=Ue.get(e);if(t)return t;mt(Ue,Sr);const r=crypto.subtle.importKey("raw",Ce.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},Ar=async(e,t)=>{const r=await yt(e),n=await crypto.subtle.sign("HMAC",r,Ce.encode(t));return _r(new Uint8Array(n))},vr=async(e,t,r)=>{const n=await yt(e);return crypto.subtle.verify("HMAC",n,r,Ce.encode(t))},gt="v1",Dr=6e4,kr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${gt}.${String(r)}`,a=await Ar(e,n);return{expiresAtMs:r,token:`${n}.${a}`}},Ir=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[a,i,u]=n;if(a!==gt||u.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=Rr(u)}catch{return!1}return vr(e,`${a}.${i}`,y)},D="/_lunora/admin/auth",Pr={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new s(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new s(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},X=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(r[n]=a);return r},Nr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:X(e,"password"),role:qe(e.role)}),http:"POST",method:"createUser"},[`${D}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new s("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${D}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${D}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:X(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${D}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${D}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${D}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${D}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${D}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${D}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${D}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${D}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${D}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${D}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${D}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${D}/organizations/create`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:I(e,"name"),ownerId:X(e,"ownerId"),slug:X(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:X(e,"name"),organizationId:I(e,"organizationId"),slug:X(e,"slug")}),http:"POST",method:"updateOrganization"},[`${D}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${D}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:X(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:X(e,"inviterId"),organizationId:I(e,"organizationId"),role:X(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new s("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Xe(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Ur=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof s)throw i;const u=i,l=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new s("auth admin operation failed",{code:l,status:Pr[l]??500})}},r=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new s(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new s("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=u[i.method];if(l===void 0)throw new s(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(a.url),O={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:g=>e.queryParameter(y,g)},A=i.build(O),m=await t(()=>l(A));return Response.json(i.returns==="void"?{ok:!0}:m,{headers:{"content-type":"application/json"},status:200})},n={};for(const[a,i]of Object.entries(Nr))n[a]=u=>r(u,i);return n},qr="__lunora_admin__:getAuthAuditLog",Ze=e=>typeof e=="string"&&e!==""?e:void 0,et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$r=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new s("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const a={},i=Ze(r.actorId),u=Ze(r.event),l=et(r.sinceSeq),y=et(r.limit);i!==void 0&&(a.actorId=i),u!==void 0&&(a.event=u),l!==void 0&&(a.sinceSeq=l),y!==void 0&&(a.limit=y);let O;try{O=await n.read(a)}catch(m){throw m instanceof s?m:(console.error("[lunora] auth audit read failed:",m),new s("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const A={entries:O};return Response.json(A,{headers:{"content-type":"application/json"},status:200})},tt=500,Lr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new s("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new s("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new s("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Br=(e,t)=>{if(e.length>tt)throw new s(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,a]of e.entries()){const{entry:i,shardKey:u}=Lr(a,n,t),l=r.get(u)??[];l.push(i),r.set(u,l)}return r},ge=1048576,ae=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let a=0,i="";for(;;){const{done:u,value:l}=await r.read();if(u)break;if(l){if(a+=l.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},xr=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let a=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(a+=y.byteLength,a>t)throw await r.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const i=new Uint8Array(a);let u=0;for(const l of n)i.set(l,u),u+=l.byteLength;return i.buffer},Z=async(e,t=ge)=>{try{const r=await ae(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof s?r:new s("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Cr=new TextEncoder,jr=e=>{const t=JSON.stringify(e),r=Cr.encode(t);let n="";for(const a of r)n+=String.fromCodePoint(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Gr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const a=JSON.parse(new TextDecoder().decode(n)),i=a.s&&typeof a.s=="object"?a.s:{},u={};for(const[l,y]of Object.entries(i))typeof y=="number"&&Number.isFinite(y)&&(u[l]=y);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:u,v:1}}catch{return t}},Mr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:n,table:t}},rt=(e,t,r)=>{for(const n of t)e.push(Mr(n));return r!==void 0&&t.length>=r},Kr="/_lunora/admin/export",Qr="/_lunora/admin/import",Fr="/_lunora/admin/sync",zr="/_lunora/admin/connector/sync",Wr="/_lunora/admin/apply",Hr="/_lunora/admin/export-tap/run",Jr=new TextEncoder,Vr=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new s("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const a of r.tables){if(typeof a!="string"||a.length===0)throw new s("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(a)}return{tables:n}},Yr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:a,queryCoordinator:i,requireAdminOption:u,resolveForwardContext:l,shardDO:y,streamExportRows:O,streamingImport:A,syncGlobals:m}=e,g=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Vr(T),{headers:K}=await l(T,L),Q=new ReadableStream({async pull(Y){const C=G=>{Y.enqueue(Jr.encode(`${JSON.stringify(G)}
|
|
2
|
-
`))};try{await O(M,K,N.tables,C),Y.close()}catch(G){Y.error(G)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},p=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,Y=typeof N.globalCursor=="number"?N.globalCursor:0,C=Array.isArray(N.tables)?N.tables.filter(ne=>typeof ne=="string"):void 0,{headers:G}=await l(T,L),J=C??a(),re=await M.orchestrateCdcSync(y,{cursors:K,headers:G,limit:Q,tables:J}),se=m?await m({limit:Q,sinceSeq:Y}):void 0;return Response.json({global:se,shards:re.shards},{status:200})},w=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=Gr(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(ee=>typeof ee=="string"):void 0,{headers:C}=await l(T,L),G=Y??a(),J=await M.orchestrateCdcSync(y,{cursors:K.s,headers:C,limit:Q,tables:G}),re=[],se={...K.s};let ne=!1;for(const ee of J.shards)ne=rt(re,ee.changes??[],Q)||ne,se[ee.shardKey]=ee.cursor;let he=K.g;if(m){const ee=await m({limit:Q,sinceSeq:K.g});ne=rt(re,ee.changes,Q)||ne,he=ee.cursor}const me=jr({g:he,s:se,v:1}),be={changes:re,hasMore:ne,nextCursor:me};return Response.json(be,{status:200})},_=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),K=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:Y}=await l(T,L),C=await M.orchestrateApplyCdc(y,{batches:K,headers:Y}),G=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:C.applied+G,failed:C.failed,ok:C.ok},{status:200})},R=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;u(T,i,{code:"BAD_REQUEST",message:"Import endpoint requires a `queryCoordinator` on the worker"});const{headers:M}=await l(T,L),N=await A(T,M);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},P=async(T,L)=>{const B=we(T,["POST"]);if(B)return B;const M=u(T,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new s("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(T),K=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(se=>typeof se=="string"):void 0;if(K===void 0)throw new s("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const C=n[K];if(C===void 0)throw new s(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await l(T,L),J=Y??a(),re=await lr({coordinator:M,cursorStore:r,headers:G,limit:Q,shardDO:y,sink:C,tables:J});return Response.json(re,{headers:{"content-type":"application/json"},status:200})};return{[Wr]:_,[zr]:w,[Kr]:g,[Hr]:P,[Qr]:R,[Fr]:p}},bt=e=>[],Xr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?n.push(a):r.push(a);return{globalTables:n,shardLocalTables:r}},Zr=async(e,t,r,n,a,i,u)=>{if(n!==void 0&&a.length===0)return;const l=n===void 0?[]:a,y=n===void 0?bt():[],O=l.length>0?l:y,A=await t.orchestrateExport(u,{args:{tables:l},headers:r,tables:O});for(const m of A.shards)if(!m.error)for(const g of m.rows??[])i(g)},nt=async(e,t,r,n,a,i)=>{const{globalTables:u,shardLocalTables:l}=Xr(e,n);await Zr(e,t,r,n,l,a,i);const y=e.exportGlobals;if((n===void 0||u.length>0)&&y){const O=n===void 0?[]:u;for await(const A of y({tables:O}))a(A)}},en=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},tn=(e,t,r,n,a)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},rn=async(e,t,r)=>{if(!e.body)throw new s("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],a=[],i=new Map;let u=0;const l=e.body.getReader(),y=new TextDecoder;let O="",A=0;const m=g=>{u+=1;const p=g.trim();if(p.length===0)return;const w=en(p,u);if(!w.ok){n.push(w.error);return}const{doc:_,table:R}=w,P=t.resolveTableSharding?.(R);if(P?.mode.kind==="global"){a.push({doc:_,line:u,table:R});return}const T=tn(_,R,P,r,u);if(!T.ok){n.push(T.error);return}const L=i.get(T.shardKey);L?L.rows.push({doc:_,table:R}):i.set(T.shardKey,{rows:[{doc:_,table:R}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:g,value:p}=await l.read();if(g)break;if(p&&(A+=p.byteLength,A>ge))throw await l.cancel().catch(()=>{}),new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=y.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
|
-
`);for(;w!==-1;){const _=O.slice(0,w);O=O.slice(w+1),m(_),w=O.indexOf(`
|
|
4
|
-
`)}}return O.length>0&&m(O),{errors:n,globalRows:a,perShard:i}},ot=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},nn=async(e,t,r,n)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:l}=await rn(e,t,a),y={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new s("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const A=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});ot(y,A)}if(u.length>0)if(t.importGlobals){const O=u[0]?.line??1,A=await t.importGlobals({rows:u,startLine:O});ot(y,A)}else for(const O of u)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},$e=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",on=(e,t)=>{let r=$e(t),n=!1;Le(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const a=Le(r),i=r._meta??{},u={kind:a,name:e,optional:n};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const l=Le($e(i.inner));l!=="unknown"&&(u.element=l)}return u},an=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>on(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),sn="/_lunora/admin/functions",dn="/_lunora/admin/cron-jobs",un="/_lunora/admin/openapi",cn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",hn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",at=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:a,value:i}=n;return[{column:a,value:i}]});return r.length===0?void 0:r},fn=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),wn=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),mn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:a,requireAdminOption:i}=e,u=p=>{if(p.method!=="GET")throw new s("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:an(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new s("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.map(T=>({args:T.args,cron:R,functionPath:T.functionPath,name:T.name,shardKey:T.shardKey,workflow:T.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new s("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??fn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new s("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??wn,{headers:{"content-type":"application/json"},status:200})},A=async p=>{if(p.method!=="GET")throw new s("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},m=async p=>{if(p.method!=="GET")throw new s("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table");if(R===void 0)throw new s("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:at(a(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new s("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=a(_,"table"),P=a(_,"column");if(R===void 0||P===void 0)throw new s("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const T=a(_,"limit"),L=T===void 0?void 0:Number(T),B=await w.facetColumn({column:P,filters:at(a(_,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[dn]:l,[sn]:u,[pn]:g,[hn]:m,[ln]:A,[un]:y,[cn]:O}},yn="/_lunora/admin/kv/namespaces",gn="/_lunora/admin/kv/keys",Ot="/_lunora/admin/kv/value",Et=32*1048576,st=60,bn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=m=>r(m,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=m=>Response.json(m,{headers:{"content-type":"application/json"},status:200}),i=(m,g)=>{const p=new URL(m.url),w=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(w==="")throw new s(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new s(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:w}},u=async(m,g)=>{if(!(await m.listNamespaces()).some(p=>p.binding===g))throw new s(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async m=>{if(m.method!=="GET")throw new s("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return a({namespaces:await n(m).listNamespaces()})},y=async m=>{if(m.method!=="GET")throw new s("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=new URL(m.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new s("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),T=P===null?void 0:Number.parseInt(P,10);if(T!==void 0&&(!Number.isInteger(T)||T<1))throw new s("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const L=T===void 0?void 0:Math.min(T,1e3);return await u(g,w),a(await g.listKeys({cursor:R,limit:L,namespace:w,prefix:_}))},O={DELETE:async m=>{const g=n(m),p=i(m,"DELETE");return await u(g,p.namespace),await g.deleteKey(p),a({deleted:!0})},GET:async m=>{const g=n(m),p=i(m,"GET");return await u(g,p.namespace),a(await g.getValue(p))},PUT:async m=>{const g=n(m),p=await t(m,Et);if(typeof p.namespace!="string"||p.namespace==="")throw new s("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new s("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new s("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<st))throw new s("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new s("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),a({ok:!0})}},A=m=>{const g=O[m.method];if(!g)throw new s("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(m)};return{[yn]:l,[gn]:y,[Ot]:A}},On="/_lunora/migrate",En="/_lunora/admin/pitr",Tn="/_lunora/admin/rank",_n="/_lunora/admin/rankpage",Rn="/_lunora/admin/shard-traffic",Sn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),An=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),vn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Sn.has(r.functionPath))throw new s("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Dn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new s("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new s("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new s("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new s("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},kn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new s('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},In=e=>{if(typeof e.table!="string"||e.table.length===0)throw new s("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new s("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new s("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 s("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 s("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Pn=async e=>{let t;try{const a=await ae(e);t=a===""?{}:JSON.parse(a)}catch(a){throw a instanceof s?a:new s("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};In(r);const n=kn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},Nn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof s?n:new s("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new s("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Un=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!An.has(t.functionPath))throw new s("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new s("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},qn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,l=async(g,p)=>{if(g.method!=="POST")throw new s("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:_}=await i(g,p),R=await a.orchestrateMigration(u,{args:w.args,functionPath:w.functionPath,headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new s("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Dn(g),{headers:_}=await i(g,p),R=await a.orchestrateRank(u,{headers:_,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new s("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Pn(g),{headers:_}=await i(g,p),R=await a.orchestrateRankPage(u,{...w,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},A=async(g,p)=>{if(g.method!=="POST")throw new s("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new s("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Nn(g),{headers:_}=await i(g,p),R=await a.orchestrateShardTraffic(u,{headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new s("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new s("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await Un(g),{headers:_}=await i(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:_,method:"POST"});return r(u,w.shardKey??t,R)};return{[On]:l,[En]:m,[Tn]:y,[_n]:O,[Rn]:A}},$n=1,Ln=0,Bn=32,xn=512,Cn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,jn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>xn)return;const r=t.split(",");if(!(r.length>Bn)){for(const n of r)if(!Cn.test(n.trim()))return;return t}},Gn=e=>{const t=sr(e.headers.get("traceparent"));if(t===void 0)return;const r=jn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Mn=(e,t={})=>{const r=Gn(e),n=t.trustInbound===!0?r:void 0,a=Re(8),i=n?.traceId??Re(16),u=yr(t.sampling,n===void 0?a:i),l=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:a,traceFlags:l?$n:Ln,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Kn=(e,t)=>{t.traceparent=ar(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Qn=(e,t)=>{let r;return()=>{if(r===void 0){const n=cr(e),a=t===void 0?void 0:t.cf;r=ir(ur(n),dr(n,a))}return r}},Fn="/_lunora/admin/scheduled",zn="/_lunora/admin/scheduled/status",Wn="/_lunora/admin/scheduled/ws",Hn="/_lunora/admin/scheduled/cancel",Jn="/_lunora/admin/scheduled/dead",Vn="/_lunora/admin/scheduled/dead/retry",Yn="/_lunora/admin/scheduled/dead/cancel",Xn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:a}=e,i=async m=>{if(m.method!=="GET")throw new s("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},u=async m=>{if(m.method!=="GET")throw new s("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new s("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async m=>{if(m.method!=="POST")throw new s("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=await m.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new s("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async m=>{if(m.method!=="GET")throw new s("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},A=m=>async g=>{if(g.method!=="POST")throw new s("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new s("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Hn]:y,[Yn]:A("/dead/cancel"),[Jn]:O,[Vn]:A("/dead/retry"),[Fn]:i,[zn]:u,[Wn]:l}},Zn="/_lunora/admin/storage",eo="/_lunora/admin/storage/url",to="/_lunora/admin/storage/buckets",ro=10080*60,no=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:a,requireAdminOption:i,storage:u}=e,l=w=>{const _=n(w,"key");if(_===void 0)throw new s("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async w=>{const _=i(w,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(w.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new s("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},A=async w=>{const _=i(w,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(w.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},m=async w=>{const _=i(w,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(w.url),P=l(R),T=await a(w),L=w.headers.get("content-type"),B=L===null||L===""?void 0:L,M=await _(P,T,{bucket:n(R,"bucket"),contentType:B});return Response.json(M,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return A(w);case"GET":return y(w);case"POST":case"PUT":return m(w);default:throw new s("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new s("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=i(w,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(w.url),P=l(R),T=Number(n(R,"expiresIn")??""),L=Number.isFinite(T)&&T>0?Math.min(T,ro):void 0,B=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:L});return Response.json({key:P,url:B},{headers:{"content-type":"application/json"},status:200})};return{[to]:O,[Zn]:g,[eo]:p}},oo=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ao={mtls:e=>oo(e,"tlsClientAuth","certVerified")==="SUCCESS"},so=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ao).find(([t])=>t===e)?.[1]??(()=>!1),io=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[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.'))}},uo="/_lunora/admin/vector/indexes",co="/_lunora/admin/vector/query",lo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new s("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{if(i.method!=="POST")throw new s("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new s("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new s("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new s("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new s("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await u.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[uo]:n,[co]:a}},ho="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",wo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},mo=e=>e!==null&&Object.hasOwn(wo,e)?e:void 0,it=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new s(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{throw new s("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},yo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const A=Be(y,"name"),m=mo(y.searchParams.get("status"));return Response.json(await O.listInstances({page:it(y,"page"),perPage:it(y,"perPage"),status:m,workflowName:A}))},a=async(u,l,y)=>{if(u.method!=="GET")throw new s("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):dt()},i=async(u,l)=>{if(u.method!=="POST")throw new s("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(u);const y=r(l);if(!y)return dt();const O=await u.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new s("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:A}=O;if(A!=="pause"&&A!=="resume"&&A!=="terminate")throw new s("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:A,instanceId:O.id,workflowName:O.name}))};return{[po]:a,[ho]:n,[fo]:i}},go=new TextEncoder,ut="/_lunora/rpc",bo="/_lunora/rpc-batch",Oo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Qn(e,t),...r===void 0?{}:{waitUntil:r}}),ct=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},lt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),xe=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const a=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(a)?void 0:a,scheme:n.protocol.replace(":",""),userAgent:r}},ht="/_lunora/voice/",Eo="/_lunora/scheduler/dispatch",To="/_lunora/admin/cron-jobs/run",_o="/_lunora/admin/ws-token",Ro="/_lunora/admin/",So="/_lunora/migrate",Ao="/_lunora/status",vo=e=>e.startsWith(Ro)||e===So,Do=new Set(["1","enabled","on","true","yes"]),ko=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Io="/api/auth",Po="__lunora_admin__:recordAuthEvent",No="__lunora_admin__:listPushSubscriptions",Uo=["/sign-in","/sign-up","/callback"],qo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Uo.some(a=>n===a||n.startsWith(`${a}/`))},Te=(e,t,r,n)=>{const a=rr(r),i=a?r.code:"INTERNAL_SERVER_ERROR",u=a?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},$o=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},pt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Lo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},a=e.headers.get("authorization"),i=e.headers.get("cookie"),u=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");a&&(n.authorization=a),i&&(n.cookie=i),u&&(n["x-d1-bookmark"]=u),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),O&&(n["x-lunora-client-seq"]=O);const A=e.headers.get("cf-connecting-ip");if(A&&(n["x-lunora-client-ip"]=A),!r)return{claims:null,headers:n,identity:null,userId:null};const m=await r(e,t);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=m.userId;const g=$o(m);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=m,_=Object.keys(w).length>0?w:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:m,userId:p}},Bo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),xo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new s("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 s("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new s("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Bo.has(r.kind))throw new s("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new s("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new s("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Co=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ft=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new s("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new s(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},jo=async e=>{const t=await ae(e);let r;try{r=JSON.parse(t)}catch{throw new s("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new s("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new s("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new s("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=r,i=xo(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const l=u.table;if(typeof l=="string"&&l!==i.table)throw new s("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},oe=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,Go=5e3,Mo=4096,Ko=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let a=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const u=(await i.json()).relayCount;typeof u=="number"&&u>0&&(a=Math.floor(u))}}catch{a=0}return mt(_e,Mo),_e.set(t,{expiresMs:r+Go,relayCount:a}),a},Qo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let a=0;a<r;a+=1){const i=a<e.length?e.codePointAt(a)??0:0,u=a<t.length?t.codePointAt(a)??0:0;n|=i^u}return n===0},Fo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,a=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",a,n.encode(t)),u=new Uint8Array(i);let l="";for(const O of u)l+=String.fromCodePoint(O);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(y,r)},wt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...a]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,a.join(" ").trim())},zo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Ir(t,n)?!0:r?!1:je(t,n)},Wo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return fr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},Tt=e=>{const t=so(e.trustInboundTraceContext),r=io(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",a=wr(e.resolveIdentity,e.identity),i=He(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let O;const A=()=>e.requireEphemeralWsToken??O??!1,m=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const c=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(O=Do.has(c.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>wt(o,y())||g.has(o),w=async(o,d)=>{const h=await ue(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const c=y();c!==void 0&&(h.headers.authorization=`Bearer ${c}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new s(`${o} access is default-denied: configure \`${d}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${o} 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("")))},P=qn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),T=async(o,d,h,c,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),c!==void 0&&c.length>0&&(b["x-lunora-mutation-id"]=c);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return oe(i,h,S)},L=async(o,d,h,c)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new s(`${c} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},B=async(o,d,h)=>L(o,d.args??{},h,`cron job "${d.name}"`),M=async(o,d)=>{if(o.workflow){await B(o.workflow,o,d);return}if(o.functionPath===void 0)throw new s(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await T(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new s(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},N=async(o,d,h,c)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await M(b,d)}catch(S){h.push(c(S))}},K=async(o,d)=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new s("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new s("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),c=typeof h.name=="string"?h.name:"";if(c==="")throw new s("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===c);if(!f)throw new s(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await M(f,d),Response.json({name:c,ran:!0},{status:200})},Q=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!u||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await u.get(u.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Y=async(o,d)=>{if(o.method!=="POST")throw new s("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(o),c=d??{},f=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(S&&f?E=await Fo(f,h,S):b&&(E=wt(o,b)),!E)throw new s("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let v;try{v=JSON.parse(h)}catch{throw new s("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=v??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await L(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new s("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,$=typeof k.id=="string"&&k.id.length>0?k.id:void 0,x=ko(o),W=await T(k.functionPath,U,q,$,x);return await Q(k),W},C=o=>{if(!p(o))throw new s("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},G=(o,d,h)=>{if(C(o),d===void 0)throw new s(h.message,{code:h.code,status:400});return d},J=$r({assertAdmin:C,getReader:()=>e.authAuditReader}),re=async(o,d)=>{C(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=d?.kind,f=d?.userId,b=d?.limit,S=c==="fcm"||c==="web-push"?c:void 0,E=typeof f=="string"&&f!==""?f:void 0,v=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,k=v>0?Math.min(v,1e3):1e3,U=(await h.list({kind:S,limit:k,userId:E})).filter(q=>S!==void 0&&q.kind!==S?!1:E===void 0||(q.userId??null)===E).map(({keys:q,token:$,...x})=>x);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},se=async(o,d)=>{if(!d.fanOut){if(d.functionPath===qr)return J(o,d.args??{});if(d.functionPath===No)return re(o,d.args)}},ne=Yr({applyGlobals:e.applyGlobals,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>bt(),queryCoordinator:e.queryCoordinator,requireAdminOption:G,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,c)=>nt(e,o,d,h,c,i),streamingImport:(o,d)=>nn(o,e,d,i),syncGlobals:e.syncGlobals}),he=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},me=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),c=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=c===null?void 0:Number.parseInt(c,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(u===void 0)throw new s("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},ee=Xn({checkWsAdmin:async o=>p(o)||zo(o,y(),A()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(C(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),_t=yo({assertAdmin:C,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=no({assertAdmin:C,parsePaging:me,queryParameter:he,readBodyBytes:xr,requireAdminOption:G,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=lo({readJsonBody:Z,requireAdminOption:G,vectorIntrospector:e.vectorIntrospector}),At=bn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:G}),vt=mr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:G}),Dt=mn({assertAdmin:C,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:me,queryParameter:he,requireAdminOption:G}),kt=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(pr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[c,f]of Object.entries(o??{})){const b=Wo(c,f);b!==void 0&&d.push(b)}for(const c of e.health?.probes??[])d.push(c);return d},It=hr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=async(o,d,h)=>{const{claims:c,headers:f,userId:b}=await ue(o,d,a),S=async(E,v={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new s("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v,functionPath:k}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),q=await oe(i,n,U),$=await q.json();if($.error)throw new s($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S}},Nt=async(o,d,h)=>{if(!e.httpRouter)return;const c=await Pt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:c},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},Ut=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new s("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ve(o,ie);if(c)return c;const f=h.searchParams.get("shard")??n,{headers:b,identity:S}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const E=new Headers(o.headers),v=[...E.keys()];for(const x of v)x.startsWith("x-lunora-")&&E.delete(x);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),q!==void 0&&E.set("x-lunora-identity-exp",q);const $=Qo(d,e.shardDO);if($!==void 0){E.set("x-lunora-shard-binding",$);const x=await Ko(i,f);if(x>0){const W=Tr(f,Math.floor(Math.random()*x));return oe(i,W,new Request(o,{headers:E}))}}return oe(i,f,new Request(o,{headers:E}))},qt=async(o,d,h)=>{const{voiceAgents:c}=e;if(c===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ve(o,ie);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(c,b)?c[b]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:v,identity:k}=await ue(o,d,a);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const q=v["x-lunora-userid"],$=v["x-lunora-identity"],x=v["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),x!==void 0&&U.set("x-lunora-identity-exp",x),oe(S,E,new Request(o,{headers:U}))},$t=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new s("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new s("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 s("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await $t(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new s("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},Ae=async(o,d,h,c,f,b)=>{const S=Date.now(),{observability:E,sampling:v}=e,k=xe(o),{decision:U,ignoredUpstream:q,trace:$}=Mn(o,{...v===void 0?{}:{sampling:v},trustInbound:t(o)});q&&r();const x={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Kn($,x);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:x,method:"POST"});try{const j=await oe(i,c,W);return de(E,{...k,...lt($),durationMs:Date.now()-S,functionPath:d,ok:j.ok,shardKey:c,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}catch(j){throw de(E,{...k,...lt($),...Te(d,Date.now()-S,j,{shardKey:c})},b,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),j}},Lt=o=>{if(o.fanOut&&o.shardKey)throw new s("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new s("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Bt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await jo(o);Co(d,c),Lt(c);const f=await se(o,c);if(f!==void 0)return f;const{headers:b,identity:S}=await ue(o,d,a);await Oe(c,S);const E=ft(c,e);{const v=Date.now(),{observability:k}=e,U=xe(o),q=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(c.fanOut){const W=e.queryCoordinator;if(!W)throw new s("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:b});return de(k,{durationMs:Date.now()-v,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:c.fanOut.table},functionPath:c.functionPath,...U,ok:!0},q),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw de(k,{...Te(c.functionPath,Date.now()-v,j,{fanOut:{table:c.fanOut.table}}),...U},q),j}}const $=c.shardKey??n,x=()=>Ae(o,c.functionPath,c.args??{},$,b,q);return E&&e.x402Charge?e.x402Charge(o,{functionPath:c.functionPath,price:E.price},x,ct(h)):x()}},xt=async(o,d,h)=>{if(o.method!=="POST")throw new s("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=await ae(o);let f;try{f=JSON.parse(c)}catch{throw new s("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new s("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new s("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a),v=Br(b,n);for(const F of v.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new s(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...v.entries()].flatMap(([F,z])=>z.map(te=>Oe({functionPath:te.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(d,o,h&&(F=>h.waitUntil?.(F))),q=xe(o),$=[],x=[],W=(F,z,te,ce)=>({body:{error:{code:te,message:ce}},id:F.id,status:z}),j=(F,z,te,ce,pe)=>{for(const H of F)de(k,pe(H),U),$.push(W(H,z,te,ce))},Xt=(F,z,te,ce,pe)=>{for(const H of F){const fe=ce.get(H.id)??pe,ye=fe<400;de(k,{durationMs:te,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},U)}};await Promise.all([...v.entries()].map(async([F,z])=>{const te=new Headers(S);te.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:te,method:"POST"}),pe=Date.now();let H;try{H=await oe(i,F,ce)}catch(V){const Ie=Date.now()-pe,{body:Fe}=nr(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Fe.code,Fe.message,tr=>({...Te(tr.functionPath,Ie,V,{shardKey:F}),...q}));return}const fe=Date.now()-pe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let De;try{De=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:fe,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...q,ok:!1,shardKey:F}));return}const ke=Array.isArray(De.results)?De.results:[],Zt=new Map(ke.map(V=>[V.id,V.status??H.status])),er=new Set(ke.map(V=>V.id));Xt(z,F,fe,Zt,H.status),$.push(...ke);for(const V of z)er.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Qe]=x;return x.length===1&&Qe!==void 0&&(Ke["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Ke,status:200})},Ct=async(o,d,h,c={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new s("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,a);await Oe({functionPath:b,shardKey:f.shardKey},E);const v=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await Ae(o,b,c,v,S,k)}catch(b){return ze(b)}},jt=1e3,Gt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const c=[];let f;for(let S=0;S<jt;S+=1){const E=await o.list({cursor:f,prefix:d});for(const v of E.objects)v.key.endsWith(".manifest.json")&&c.push(v.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=c.toSorted((S,E)=>E.localeCompare(S)).slice(h);await Promise.all(b.flatMap(S=>{const E=S.slice(0,-14);return[o.delete(S),o.delete(E)]}))},Mt=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new s("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new s("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=y();if(!c||c.length===0)throw new s("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${c}`,"content-type":"application/json"},b=e.backupTables;let S=0,E=0;const v=[];await nt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
-
`;S+=1,E+=go.encode(j).byteLength,v.push(j)},i);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),q=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${q}.manifest.json`;await d.put(q,new Blob(v,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const x={bytes:E,createdAt:U,cron:o.cron,file:q,id:U,rows:S,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await d.put($,`${JSON.stringify(x,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Gt(d,k)},Ge=async(o,d,h)=>{const{observability:c}=e,f=Date.now(),b=Re(16),S=Re(8),E=pt(d);try{const v=await h();return de(c,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:b},E),v}catch(v){throw de(c,{...Te(o,Date.now()-f,v,{}),spanId:S,traceId:b},E),v}finally{We(c,E)}},Kt=async(o,d,h)=>{m(d);const c=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,d,h)}catch(E){c.push(f(E))}if(await N(o.cron,d,c,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Mt(o)}catch(E){c.push(f(E))}const[S]=c;if(c.length===1&&S)throw S;if(c.length>1)throw new AggregateError(c,`scheduled("${o.cron}") had ${String(c.length)} failure(s)`)},Qt=async(o,d)=>{try{const h=o??{},c=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:d},functionPath:Po}),headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},method:"POST"});await oe(i,n,f)}catch{}},Ft=async(o,d,h,c)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Io;return qo(h.pathname,b)&&c.waitUntil?.(Qt(d,f.status>=400?"fail":"ok")),f},zt=async({args:o,env:d,functionPath:h,request:c,shardKey:f,waitUntil:b})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:v}=await ue(c,d,a);await Oe(S,v);const k=f??n,U=Ee(d,c,b),q=()=>Ae(c,h,o,k,E,U),$=ft(S,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:h,price:$.price},q,ct({waitUntil:b})):q()},Wt=gr({functions:e.functions??{},invoke:zt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Ht={[Ao]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Oo]:(o,d,h)=>Ut(o,d,h),[ut]:(o,d,h,c)=>Bt(o,d,c),[bo]:(o,d,h,c)=>xt(o,d,c),[Eo]:(o,d)=>Y(o,d),[To]:(o,d)=>K(o,d),[_o]:async o=>{if(o.method!=="POST")throw new s("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});C(o);const d=y();if(d===void 0)throw new s("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await kr(d);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ne,...ee,..._t,...Rt,...St,...At,...vt,...Dt,...It,...Wt,...Ur({assertAdmin:C,getAuthAdmin:()=>e.authAdmin,parsePaging:me,queryParameter:he,readJsonBody:Z})};let ie=Je(e.security),Me=!1;const Jt=o=>{Me||(Me=!0,ie=Je(e.security,o??{}))},Vt=async(o,d)=>{if(!(e.adminGate===void 0||!vo(d)))try{await e.adminGate(o)&&g.add(o)}catch{}},Yt=async(o,d,h)=>{const c=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),v=c.pathname===Ot?Et:ge;if(Number.isFinite(E)&&E>v)throw new s("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Ft(o,d,c,h);if(f)return f;if(ve){const E=`${o.method} ${c.pathname}`,v=ve[E]??ve[c.pathname];if(v)return v(o,d,h)}const b=Ht[c.pathname];return b?(await Vt(o,c.pathname),b(o,d,c,h)):e.voiceAgents!==void 0&&c.pathname.startsWith(ht)?qt(o,d,c):await Nt(o,d,h)||new Response("Not found",{status:404})};return{async fetch(o,d,h){e.passThroughOnException&&h.passThroughOnException?.(),Jt(d),m(d);const c=br(o,ie);if(c)return c;const f=Or(o,ie);if(f)return Ne(f,o,ie);try{const b=await Yt(o,d,h);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,pt(h))}},async queue(o,d,h){await Ge(`queue:${Lo(o)}`,h,async()=>{await e.queue?.(o,d,h)})},async scheduled(o,d,h){await Ge(`cron:${o.cron}`,h,async()=>{await Kt(o,d,h)})},serverQuery:Ct}},Ho=e=>Tt(e),Jo=e=>typeof e=="function"?{fetch:e}:e,Vo=e=>!!(e.crons??e.cronJobs??e.backupCron),la=(e,t)=>{const r=Jo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,a=u=>{const l=Ho({...u,httpRouter:r});return n!==void 0&&!Vo(u)?{...l,scheduled:async(y,O,A)=>{await n(y,O,A)}}:l};if(typeof t!="function")return a(t);const i=t;return{fetch:(u,l,y)=>a(i(l)).fetch(u,l,y),queue:(u,l,y)=>a(i(l)).queue?.(u,l,y)??Promise.resolve(),scheduled:(u,l,y)=>a(i(l)).scheduled(u,l,y),serverQuery:(u,l,y,O,A)=>a(i(l)).serverQuery(u,l,y,O,A)}},Yo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new s("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},ha=(e={})=>(t,r,n)=>Tt(Yo(e,r)).fetch(t,r,n??or),pa=e=>e;export{qr as GET_AUTH_AUDIT_LOG_OP,or as NOOP_EXECUTION_CONTEXT,ma as composeIdentityResolvers,Ho as composeWorker,ha as createLunoraHandler,Tt as createWorker,pa as defineRpcEnvelope,Ko as probeRelayCount,Yo as resolveLunoraOptions,ya as routeIdentityResolvers,la as withFrameworkWorker};
|