@lunora/runtime 1.0.0-alpha.49 → 1.0.0-alpha.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{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-HS52JXMo.mjs";import{createCrossShardRelationCapabilities as E}from"./packem_shared/createCrossShardRelationCapabilities-CMWiFA5s.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-BclNO0yc.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-ByasbDmd.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-BpCNEAIa.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as M}from"./packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.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-DYm2p9dH.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.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-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BkZ9FokE.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-DwE0Jbww.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
+ import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DBTuFjb5.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-BieBiNab.mjs";import{createCrossShardRelationCapabilities as f}from"./packem_shared/createCrossShardRelationCapabilities-Cr8V1uO_.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as d,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs";import{LunoraError as C,toErrorResponse as L}from"./packem_shared/LunoraError-ByasbDmd.mjs";import{createKvCursorStore as u,createMemoryCursorStore as y,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-BpCNEAIa.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.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 se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-DQ7dkxS6.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Se,o as fe}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as de,S as le,U as xe,p as _e,f as Ce}from"./packem_shared/rest-routes-BJLWmBgK.mjs";import{decorateResponse as ge,enforceOrigin as ue,handleCorsPreflight as ye,resolveSecurity as Te}from"./packem_shared/decorateResponse-DBIWsRSZ.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-BKC5nGNh.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-DwE0Jbww.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,d 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,de as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,f as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,u as createKvCursorStore,n as createLunoraHandler,y as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,ge as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ue as enforceOrigin,ye as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Se as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,fe 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};
@@ -0,0 +1 @@
1
+ import"./rest-cache-5unAzdFN.mjs";import{g as t,S as o,U as i,p as m,f as R}from"./rest-routes-BJLWmBgK.mjs";import"./method-guard-BbuR0VfS.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as or,toErrorBody as ar}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as sr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as ir,u as dr}from"./identity-header-CDgIrYAz.mjs";import{O as _e,m as ur,A as cr,R as lr,d as hr,i as pr,s as fr}from"./otlp-resource-B-ByO9qo.mjs";import{b as Z,a as he,d as mt,S as wr,e as yt,w as mr}from"./rest-routes-BJLWmBgK.mjs";import{LunoraError as a,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as yr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as gr,durableObjectProbe as br,d1Probe as Er,presenceProbe as Pe}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as Or}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Ra,routeIdentityResolvers as Aa}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Tr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as _r,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Je,handleCorsPreflight as Sr,enforceOrigin as Rr,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const Ar=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},gt="__lunoraBranch",vr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,gt),Dr=`may not contain the reserved workflow branch-marker key ("${gt}")`,je=(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 u=s<e.length?e.charCodeAt(s):0,c=s<t.length?t.charCodeAt(s):0;n|=u^c}return n===0},bt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},kr="::relay::",Ir=(e,t)=>`${e}${kr}${String(t)}`,$e=new TextEncoder,Pr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Pr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Nr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Ur=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},qr=64,Ue=new Map,Et=async e=>{const t=Ue.get(e);if(t)return t;bt(Ue,qr);const r=crypto.subtle.importKey("raw",$e.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},xr=async(e,t)=>{const r=await Et(e),n=await crypto.subtle.sign("HMAC",r,$e.encode(t));return Nr(new Uint8Array(n))},Cr=async(e,t,r)=>{const n=await Et(e);return crypto.subtle.verify("HMAC",n,r,$e.encode(t))},Ot="v1",Br=6e4,Lr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Br),n=`${Ot}.${String(r)}`,s=await xr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},jr=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,u,c]=n;if(s!==Ot||c.length===0)return!1;const h=Number(u);if(!Number.isFinite(h)||h<=r)return!1;let E;try{E=Ur(c)}catch{return!1}return Cr(e,`${s}.${u}`,E)},k="/_lunora/admin/auth",$r={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},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(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},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(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 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(u=>typeof u=="string")&&(r[n]=s);return r},Gr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/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"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:qe(e.role)}),http:"POST",method:"createUser"},[`${k}/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:P(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>{const t=qe(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:P(e,"userId")}},http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ye(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ye(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:P(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:Xe(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mr=e=>{const t=async s=>{try{return await s()}catch(u){if(u instanceof a)throw u;const c=u,h=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",u),new a("auth admin operation failed",{code:h,status:$r[h]??500})}},r=async(s,u)=>{if(e.assertAdmin(s),s.method!==u.http)throw new a(`Auth admin endpoint requires ${u.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 h=c[u.method];if(h===void 0)throw new a(`auth admin does not support \`${u.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const E=new URL(s.url),O={body:u.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:g=>e.queryParameter(E,g)},D=u.build(O),f=await t(()=>h(D));return Response.json(u.returns==="void"?{ok:!0}:f,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,u]of Object.entries(Gr))n[s]=c=>r(c,u);return n},Kr="__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,Fr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s={},u=Ze(r.actorId),c=Ze(r.event),h=et(r.sinceSeq),E=et(r.limit);u!==void 0&&(s.actorId=u),c!==void 0&&(s.event=c),h!==void 0&&(s.sinceSeq=h),E!==void 0&&(s.limit=E);let O;try{O=await n.read(s)}catch(f){throw f instanceof a?f:(console.error("[lunora] auth audit read failed:",f),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const D={entries:O};return Response.json(D,{headers:{"content-type":"application/json"},status:200})},tt=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}},zr=(e,t)=>{if(e.length>tt)throw new a(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:u,shardKey:c}=Qr(s,n,t),h=r.get(c)??[];h.push(u),r.set(c,h)}return r},Wr=new TextEncoder,Hr=e=>{const t=JSON.stringify(e),r=Wr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Jr=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 h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const s=JSON.parse(new TextDecoder().decode(n)),u=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[h,E]of Object.entries(u))typeof E=="number"&&Number.isFinite(E)&&(c[h]=E);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Vr=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}},rt=(e,t,r)=>{for(const n of t)e.push(Vr(n));return r!==void 0&&t.length>=r},Yr="/_lunora/admin/export",Xr="/_lunora/admin/import",Zr="/_lunora/admin/sync",en="/_lunora/admin/connector/sync",tn="/_lunora/admin/apply",rn="/_lunora/admin/export-tap/run",nn=new TextEncoder,on=async e=>{let t;try{const s=await he(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}},an=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:u,assertAdmin:c,requireAdminOption:h,resolveForwardContext:E,shardDO:O,streamExportRows:D,streamingImport:f,syncGlobals:g}=e,p=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await on(v),{headers:K}=await E(v,L),F=new ReadableStream({async pull($){const M=X=>{$.enqueue(nn.encode(`${JSON.stringify(X)}
2
+ `))};try{await D(Y,K,U.tables,M),$.close()}catch(X){$.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},y=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,$=typeof U.globalCursor=="number"?U.globalCursor:0,M=Array.isArray(U.tables)?U.tables.filter(ee=>typeof ee=="string"):void 0,{headers:X}=await E(v,L),J=M??s(),oe=await Y.orchestrateCdcSync(O,{cursors:K,headers:X,limit:F,tables:J}),se=g?await g({limit:F,sinceSeq:$}):void 0;return Response.json({global:se,shards:oe.shards},{status:200})},_=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=Jr(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,$=Array.isArray(U.tables)?U.tables.filter(re=>typeof re=="string"):void 0,{headers:M}=await E(v,L),X=$??s(),J=await Y.orchestrateCdcSync(O,{cursors:K.s,headers:M,limit:F,tables:X}),oe=[],se={...K.s};let ee=!1;for(const re of J.shards)ee=rt(oe,re.changes??[],F)||ee,se[re.shardKey]=re.cursor;let pe=K.g;if(g){const re=await g({limit:F,sinceSeq:K.g});ee=rt(oe,re.changes,F)||ee,pe=re.cursor}const ge=Hr({g:pe,s:se,v:1}),Re={changes:oe,hasMore:ee,nextCursor:ge};return Response.json(Re,{status:200})},S=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=(Array.isArray(U.batches)?U.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),F=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:$}=await E(v,L),M=await Y.orchestrateApplyCdc(O,{batches:K,headers:$}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:M.applied+X,failed:M.failed,ok:M.ok},{status:200})},I=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;c(v);const{headers:Y}=await E(v,L),U=await f(v,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},C=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{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 U=await Z(v),K=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,$=Array.isArray(U.tables)?U.tables.filter(se=>typeof se=="string"):void 0;if(K===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=n[K];if(M===void 0)throw new a(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await E(v,L),J=$??s(),oe=await yr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:O,sink:M,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[tn]:S,[en]:_,[Yr]:p,[rn]:C,[Xr]:I,[Zr]:y}},Tt=e=>[],sn=(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}},dn=async(e,t,r,n,s,u,c)=>{if(n!==void 0&&s.length===0)return;const h=n===void 0?[]:s,E=n===void 0?Tt():[],O=h.length>0?h:E,D=await t.orchestrateExport(c,{args:{tables:h},headers:r,tables:O});for(const f of D.shards)if(!f.error)for(const g of f.rows??[])u(g)},nt=async(e,t,r,n,s,u)=>{const{globalTables:c,shardLocalTables:h}=sn(e,n);await dn(e,t,r,n,h,s,u);const E=e.exportGlobals;if((n===void 0||c.length>0)&&E){const O=n===void 0?[]:c;for await(const D of E({tables:O}))s(D)}},un=(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}},cn=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const u=e[r.mode.field];return u==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 u=="string"?u:JSON.stringify(u)}}return{ok:!0,shardKey:n}},ln=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],u=new Map;let c=0,h=0;const E=e.body.getReader(),O=new TextDecoder;let D="",f=0;const g=p=>{h+=1;const y=p.trim();if(y.length===0)return;c+=1;const _=un(y,h);if(!_.ok){n.push(_.error);return}const{doc:S,table:I}=_,C=t.resolveTableSharding?.(I);if(C?.mode.kind==="global"){s.push({doc:S,line:h,table:I});return}const v=cn(S,I,C,r,h);if(!v.ok){n.push(v.error);return}const L=u.get(v.shardKey);L?L.rows.push({doc:S,table:I}):u.set(v.shardKey,{rows:[{doc:S,table:I}],shardKey:v.shardKey,startLine:h})};for(;;){const{done:p,value:y}=await E.read();if(p)break;if(y&&(f+=y.byteLength,f>mt))throw await E.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});D+=O.decode(y,{stream:!0});let _=D.indexOf(`
3
+ `);for(;_!==-1;){const S=D.slice(0,_);D=D.slice(_+1),g(S),_=D.indexOf(`
4
+ `)}}return D.length>0&&g(D),{errors:n,globalRows:s,perShard:u,received:c}},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},hn=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:u,globalRows:c,perShard:h,received:E}=await ln(e,t,s),O={conflicts:0,errors:u,inserted:{}},D=[];if(t.resolveTableSharding===void 0&&h.size>0&&D.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const f=t.queryCoordinator;if(!f)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const g=await f.orchestrateImport(n,{batches:[...h.values()],headers:r});ot(O,g)}if(c.length>0)if(t.importGlobals){const f=c[0]?.line??1,g=await t.importGlobals({rows:c,startLine:f});ot(O,g)}else for(const f of c)O.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:f.line,message:`row targets global table "${f.table}" but no \`importGlobals\` is configured`,table:f.table});return{conflicts:O.conflicts,errors:O.errors,inserted:O.inserted,received:E,...D.length>0?{warnings:D}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},Ce=e=>typeof e.kind=="string"?e.kind:"unknown",pn=(e,t)=>{let r=xe(t),n=!1;Ce(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const s=Ce(r),u=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof u.tableName=="string"&&(c.table=u.tableName),s==="array"){const h=Ce(xe(u.inner));h!=="unknown"&&(c.element=h)}return c},fn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>pn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),wn="/_lunora/admin/functions",mn="/_lunora/admin/cron-jobs",yn="/_lunora/admin/openapi",gn="/_lunora/admin/openrpc",bn="/_lunora/admin/global/tables",En="/_lunora/admin/global/table",On="/_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:s,value:u}=n;return[{column:s,value:u}]});return r.length===0?void 0:r},Tn=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:{}}),_n=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"}),Sn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:u}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([S,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:fn(I.args),kind:I.kind,path:S}]).toSorted((S,I)=>S.path.localeCompare(I.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([S,I])=>I.map(C=>({args:C.args,cron:S,functionPath:C.functionPath,name:C.name,shardKey:C.shardKey,workflow:C.workflow}))).toSorted((S,I)=>S.name.localeCompare(I.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},E=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??Tn,{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??_n,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},f=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),S=s(_,"table");if(S===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...n(p),filters:at(s(_,"filters")),table:S});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),S=s(_,"table"),I=s(_,"column");if(S===void 0||I===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const C=s(_,"limit"),v=C===void 0?void 0:Number(C),L=await y.facetColumn({column:I,filters:at(s(_,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:S});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[mn]:h,[wn]:c,[On]:g,[En]:f,[bn]:D,[yn]:E,[gn]:O}},Rn="/_lunora/admin/kv/namespaces",An="/_lunora/admin/kv/keys",_t="/_lunora/admin/kv/value",St=32*1048576,st=60,vn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=f=>r(f,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=f=>Response.json(f,{headers:{"content-type":"application/json"},status:200}),u=(f,g)=>{const p=new URL(f.url),y=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(y==="")throw new a(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:y}},c=async(f,g)=>{if(!(await f.listNamespaces()).some(p=>p.binding===g))throw new a(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},h=async f=>{if(f.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(f).listNamespaces()})},E=async f=>{if(f.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(f),p=new URL(f.url),y=p.searchParams.get("namespace")??"";if(y==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,S=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),C=I===null?void 0:Number.parseInt(I,10);if(C!==void 0&&(!Number.isInteger(C)||C<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=C===void 0?void 0:Math.min(C,1e3);return await c(g,y),s(await g.listKeys({cursor:S,limit:v,namespace:y,prefix:_}))},O={DELETE:async f=>{const g=n(f),p=u(f,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),s({deleted:!0})},GET:async f=>{const g=n(f),p=u(f,"GET");return await c(g,p.namespace),s(await g.getValue(p))},PUT:async f=>{const g=n(f),p=await t(f,St);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<st))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const y=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<y))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(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=f=>{const g=O[f.method];if(!g)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(f)};return{[Rn]:h,[An]:E,[_t]:D}},Dn="/_lunora/migrate",kn="/_lunora/admin/pitr",In="/_lunora/admin/rank",Pn="/_lunora/admin/rankpage",Nn="/_lunora/admin/shard-traffic",Un=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),qn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xn=async e=>{let t;try{const n=await he(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"||!Un.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}},Cn=async e=>{let t;try{const n=await he(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}},Bn=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}},Ln=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})},jn=async e=>{let t;try{const s=await he(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??{};Ln(r);const n=Bn(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}},$n=async e=>{let t;try{const n=await he(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}},Gn=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!qn.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}},Mn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:u,shardDO:c}=e,h=async(g,p)=>{if(g.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await xn(g),{headers:_}=await u(g,p),S=await s.orchestrateMigration(c,{args:y.args,functionPath:y.functionPath,headers:_,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},E=async(g,p)=>{if(g.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await Cn(g),{headers:_}=await u(g,p),S=await s.orchestrateRank(c,{headers:_,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await jn(g),{headers:_}=await u(g,p),S=await s.orchestrateRankPage(c,{...y,headers:_});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},D=async(g,p)=>{if(g.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await $n(g),{headers:_}=await u(g,p),S=await s.orchestrateShardTraffic(c,{headers:_,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},f=async(g,p)=>{if(g.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const y=await Gn(g),{headers:_}=await u(g,p),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:y.args,functionPath:y.functionPath}),headers:_,method:"POST"});return r(c,y.shardKey??t,S)};return{[Dn]:h,[kn]:f,[In]:E,[Pn]:O,[Nn]:D}},Kn=1,Fn=0,Qn=32,zn=512,Wn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Hn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>zn)return;const r=t.split(",");if(!(r.length>Qn)){for(const n of r)if(!Wn.test(n.trim()))return;return t}},Jn=e=>{const t=cr(e.headers.get("traceparent"));if(t===void 0)return;const r=Hn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Vn=(e,t={})=>{const r=Jn(e),n=t.trustInbound===!0?r:void 0,s=_e(8),u=n?.traceId??_e(16),c=_r(t.sampling,n===void 0?s:u),h=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:s,traceFlags:h?Kn:Fn,traceId:u,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Yn=(e,t)=>{t.traceparent=ur(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Xn=(e,t)=>{let r;return()=>{if(r===void 0){const n=fr(e),s=t===void 0?void 0:t.cf;r=lr(pr(n),hr(n,s))}return r}},Zn="/_lunora/admin/scheduled",eo="/_lunora/admin/scheduled/status",to="/_lunora/admin/scheduled/ws",ro="/_lunora/admin/scheduled/cancel",no="/_lunora/admin/scheduled/dead",oo="/_lunora/admin/scheduled/dead/retry",ao="/_lunora/admin/scheduled/dead/cancel",so=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,u=async f=>{if(f.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async f=>{if(f.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},E=async f=>{if(f.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(f),p=await f.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("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 f=>{if(f.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=f=>async g=>{if(g.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),y=await g.json().catch(()=>{});if(typeof y?.id!="string"||y.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${f}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[ro]:E,[ao]:D("/dead/cancel"),[no]:O,[oo]:D("/dead/retry"),[Zn]:u,[eo]:c,[to]:h}},io="/_lunora/admin/storage",uo="/_lunora/admin/storage/url",co="/_lunora/admin/storage/buckets",lo=10080*60,ho=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:u,storage:c}=e,h=y=>{const _=n(y,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},E=async y=>{const _=u(y,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),S=new URL(y.url),I=await _(n(S,"prefix"),{bucket:n(S,"bucket"),cursor:n(S,"cursor"),...r(y)});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},O=y=>{if(y.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(y),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async y=>{const _=u(y,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),S=new URL(y.url),I=h(S);return await _(I,{bucket:n(S,"bucket")}),Response.json({deleted:!0,key:I},{headers:{"content-type":"application/json"},status:200})},f=async y=>{const _=u(y,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),S=new URL(y.url),I=h(S),C=await s(y),v=y.headers.get("content-type"),L=v===null||v===""?void 0:v,j=await _(I,C,{bucket:n(S,"bucket"),contentType:L});return Response.json(j,{headers:{"content-type":"application/json"},status:200})},g=async y=>{switch(y.method){case"DELETE":return D(y);case"GET":return E(y);case"POST":case"PUT":return f(y);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async y=>{if(y.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=u(y,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),S=new URL(y.url),I=h(S),C=Number(n(S,"expiresIn")??""),v=Number.isFinite(C)&&C>0?Math.min(C,lo):void 0,L=await _(I,{bucket:n(S,"bucket"),expiresInSeconds:v});return Response.json({key:I,url:L},{headers:{"content-type":"application/json"},status:200})};return{[co]:O,[io]:g,[uo]:p}},po=(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},fo={mtls:e=>po(e,"tlsClientAuth","certVerified")==="SUCCESS"},wo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(fo).find(([t])=>t===e)?.[1]??(()=>!1),mo=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.'))}},yo="/_lunora/admin/vector/indexes",go="/_lunora/admin/vector/query",bo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async u=>{if(u.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(u,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 u=>{if(u.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(u,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 h=await t(u);if(typeof h.name!="string"||h.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const E=await c.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(E,{headers:{"content-type":"application/json"},status:200})};return{[yo]:n,[go]:s}},Eo="/_lunora/admin/workflows/instances",Oo="/_lunora/admin/workflows/instance",To="/_lunora/admin/workflows/status",_o={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},So=e=>e!==null&&Object.hasOwn(_o,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 a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{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})},Ro=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,h,E)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(h);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(E,"name"),f=So(E.searchParams.get("status"));return Response.json(await O.listInstances({page:it(E,"page"),perPage:it(E,"perPage"),status:f,workflowName:D}))},s=async(c,h,E)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(h);return O?Response.json(await O.getInstance({instanceId:Be(E,"id"),workflowName:Be(E,"name")})):dt()},u=async(c,h)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const E=r(h);if(!E)return dt();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:D}=O;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await E.setInstanceStatus({action:D,instanceId:O.id,workflowName:O.name}))};return{[Oo]:s,[Eo]:n,[To]:u}},Ao=new TextEncoder,ut="/_lunora/rpc",vo="/_lunora/rpc-batch",Do="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Xn(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}}),Le=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}},ht="/_lunora/voice/",ko="/_lunora/scheduler/dispatch",Io="/_lunora/admin/cron-jobs/run",Po="/_lunora/admin/ws-token",No="/_lunora/admin/",Uo="/_lunora/migrate",qo="/_lunora/status",xo=e=>e.startsWith(No)||e===Uo,Co=new Set(["1","enabled","on","true","yes"]),Bo=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}}},Lo="/api/auth",jo="__lunora_admin__:recordAuthEvent",$o="__lunora_admin__:listPushSubscriptions",Go=["/sign-in","/sign-up","/callback"],Mo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Go.some(s=>n===s||n.startsWith(`${s}/`))},Oe=(e,t,r,n)=>{const s=or(r),u=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:u,message:h,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ko=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,Fo=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"},s=e.headers.get("authorization"),u=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),E=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),u&&(n.cookie=u),c&&(n["x-d1-bookmark"]=c),h&&(n["x-lunora-mutation-id"]=h),E&&(n["x-lunora-client-id"]=E),O&&(n["x-lunora-client-seq"]=O);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const f=await r(e,t);if(!f||typeof f.userId!="string"||f.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=ir(f.userId);const g=Ko(f);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...y}=f,_=Object.keys(y).length>0?y:null;return _&&(n["x-lunora-identity"]=dr(_)),{claims:_,headers:n,identity:f,userId:p}},Qo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),zo=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"||!Qo.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},Wo=(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 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}},Ho=async e=>{const t=await he(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&&yt(n.args,"RPC"),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,u=zo(s.fanOut),c=s.args??{};if(u&&s.functionPath.startsWith("__lunora_relation__:")){const h=c.table;if(typeof h=="string"&&h!==u.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=u.table}return{args:c,fanOut:u,functionPath:s.functionPath,shardKey:s.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),Te=new Map,Jo=5e3,Vo=4096,Yo=async(e,t)=>{const r=Date.now(),n=Te.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Te.delete(t);let s=0;try{const u=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(u.ok){const c=(await u.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return bt(Te,Vo),Te.set(t,{expiresMs:r+Jo,relayCount:s}),s},Xo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Zo=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"]),u=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(u);let h="";for(const O of c)h+=String.fromCodePoint(O);const E=btoa(h).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(E,r)},wt=(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:je(t,s.join(" ").trim())},ea=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 jr(t,n)?!0:r?!1:je(t,n)},ta=(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 Er(`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)},Rt=e=>{const t=wo(e.trustInboundTraceContext),r=mo(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=Or(e.resolveIdentity,e.identity),u=He(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let h;const E=()=>e.adminToken??h;let O;const D=()=>e.requireEphemeralWsToken??O??!1,f=o=>{const i=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const d=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(O=Co.has(d.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const l=i.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},g=new WeakSet,p=o=>wt(o,E())||g.has(o),y=async(o,i)=>{const l=await ue(o,i,e.resolveIdentity);if(g.has(o)&&l.headers.authorization===void 0){const d=E();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let _=!1;const S=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})}_||(_=!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("")))},I=Mn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:y,shardDO:u}),C=async(o,i,l,d,w)=>{if(e.authorizeShard&&!await e.authorizeShard(null,l))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};w?.userId!==void 0&&w.userId.length>0&&(b["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(b["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d);const R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:b,method:"POST"});return ae(u,l,R)},v=async(o,i,l,d)=>{const w=l?.[o];if(!w||typeof w.create!="function")throw new a(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(vr(i))throw new a(`${d} params ${Dr}`,{code:"BAD_REQUEST",status:400});await w.create({params:i})},L=async(o,i,l)=>v(o,i.args??{},l,`cron job "${i.name}"`),j=async(o,i)=>{if(o.workflow){await L(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 l=await C(o.functionPath,o.args??{},o.shardKey??n);if(!l.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,i,l,d)=>{const w=e.cronJobs?.[o];if(w)for(const b of w)try{await j(b,i)}catch(R){l.push(d(R))}},U=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 l=await Z(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!w)throw new a(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(w,i),Response.json({name:d,ran:!0},{status:200})},K=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 l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(l)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},F=async(o,i)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const l=await he(o),d=i??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),R=o.headers.get("x-lunora-scheduler-signature");let m=!1;if(R&&w?m=await Zo(w,l,R):b&&(m=wt(o,b)),!m)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let T;try{T=JSON.parse(l)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const A=T??{},N=A.args??{};if(typeof A.workflow=="string"&&A.workflow.length>0)return await v(A.workflow,N,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof A.functionPath!="string"||A.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof A.shardKey=="string"&&A.shardKey.length>0?A.shardKey:n,x=typeof A.id=="string"&&A.id.length>0?A.id:void 0,B=Bo(o),W=await C(A.functionPath,N,q,x,B);return await K(A),W},$=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},M=(o,i,l)=>{if($(o),i===void 0)throw new a(l.message,{code:l.code,status:400});return i},X=Fr({assertAdmin:$,getReader:()=>e.authAuditReader}),J=async(o,i)=>{$(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const d=i?.kind,w=i?.userId,b=i?.limit,R=d==="fcm"||d==="web-push"?d:void 0,m=typeof w=="string"&&w!==""?w:void 0,T=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,A=T>0?Math.min(T,1e3):1e3,N=(await l.list({kind:R,limit:A,userId:m})).filter(q=>R!==void 0&&q.kind!==R?!1:m===void 0||(q.userId??null)===m).map(({keys:q,token:x,...B})=>B);return Response.json({subscriptions:N},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Kr)return X(o,i.args??{});if(i.functionPath===$o)return J(o,i.args)}},se=an({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Tt(),queryCoordinator:e.queryCoordinator,requireAdminOption:M,resolveForwardContext:y,shardDO:u,streamExportRows:(o,i,l,d)=>nt(e,o,i,l,d,u),streamingImport:(o,i)=>hn(o,e,i,u),syncGlobals:e.syncGlobals}),ee=(o,i)=>{const l=o.searchParams.get(i);return l===null||l===""?void 0:l},pe=o=>{const i=new URL(o.url),l=i.searchParams.get("limit"),d=i.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},ge=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Re=so({checkWsAdmin:async o=>p(o)||ea(o,E(),D()),requireSchedulerNamespace:ge,resolveSchedulerStub:o=>($(o),Se(ge(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=Ro({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),At=ho({assertAdmin:$,parsePaging:pe,queryParameter:ee,readBodyBytes:mr,requireAdminOption:M,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),vt=bo({readJsonBody:Z,requireAdminOption:M,vectorIntrospector:e.vectorIntrospector}),Dt=vn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:M}),kt=Tr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:M}),It=Sn({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ee,requireAdminOption:M}),Pt=o=>{const i=[],l=u??o?.SHARD;if(l!==void 0&&i.push(br("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=ta(d,w);b!==void 0&&i.push(b)}for(const d of e.health?.probes??[])i.push(d);return i},Nt=gr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Pt}),Ut=o=>{const i=e.schedulerInstanceName??"default",l=()=>o.get(o.idFromName(i)),d=async(m,T)=>{const A=await l().fetch(new Request(`https://scheduler.internal${m}`,T));if(!A.ok)throw new a(`ctx.scheduler: SchedulerDO ${m} failed (${String(A.status)}): ${await A.text()}`,{code:"INTERNAL",status:500});return await A.json()},w=async(m,T)=>await d(m,{body:JSON.stringify(T),headers:{"content-type":"application/json"},method:"POST"}),b=m=>{const T=m;if(T==null)throw new a("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof T.binding=="string"&&T.binding.length>0)return{workflow:T.binding};if(typeof T.__lunoraRef=="string")return{functionPath:T.__lunoraRef};throw new a("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},R=async(m,T,A={})=>{const{id:N}=await w("/schedule",{args:A,scheduledFor:m,...b(T)});return N};return{cancel:async m=>await w("/cancel",{id:m}),get:async m=>await d(`/get?id=${encodeURIComponent(m)}`,{method:"GET"}),list:async()=>await d("/list",{method:"GET"}),runAfter:async(m,T,A)=>{if(!Number.isFinite(m)||m<0)throw new a("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await R(Date.now()+m,T,A)},runAt:async(m,T,A)=>{if(!Number.isFinite(m))throw new a("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await R(m,T,A)}}},qt=async(o,i,l)=>{const{claims:d,headers:w,userId:b}=await ue(o,i,s),R=async(m,T={})=>{const A=m.__lunoraRef;if(typeof A!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const N=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:T,functionPath:A}),headers:{...w,"x-lunora-system":"1"},method:"POST"}),q=await ae(u,n,N),x=await q.json();if(x.error)throw new a(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:q.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:R,runMutation:R,runQuery:R,...c===void 0?{}:{scheduler:Ut(c)},...e.storage===void 0?{}:{storage:Ar(e.storage(i))}}},xt=async(o,i,l)=>{if(!e.httpRouter)return;const d=await qt(o,i,l);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},Ct=async(o,i,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=Ve(o,ie);if(d)return d;const w=l.searchParams.get("shard")??n,{headers:b,identity:R}=await ue(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(R,w))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else w!==n&&S("shard");const m=new Headers(o.headers),T=[...m.keys()];for(const B of T)B.startsWith("x-lunora-")&&m.delete(B);const A=b["x-lunora-userid"],N=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];A!==void 0&&m.set("x-lunora-userid",A),N!==void 0&&m.set("x-lunora-identity",N),q!==void 0&&m.set("x-lunora-identity-exp",q);const x=Xo(i,e.shardDO);if(x!==void 0){m.set("x-lunora-shard-binding",x);const B=await Yo(u,w);if(B>0){const W=Ir(w,Math.floor(Math.random()*B));return ae(u,W,new Request(o,{headers:m}))}}return ae(u,w,new Request(o,{headers:m}))},Bt=async(o,i,l)=>{const{voiceAgents:d}=e;if(d===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 w=Ve(o,ie);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(d,b)?d[b]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const m=l.searchParams.get("threadKey");if(m===null||m.length===0)return new Response("Missing threadKey",{status:400});const{headers:T,identity:A}=await ue(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(A,m))return new Response("Forbidden",{status:403})}else S("shard");const N=new Headers(o.headers);N.delete("x-lunora-userid"),N.delete("x-lunora-identity"),N.delete("x-lunora-identity-exp");const q=T["x-lunora-userid"],x=T["x-lunora-identity"],B=T["x-lunora-identity-exp"];return q!==void 0&&N.set("x-lunora-userid",q),x!==void 0&&N.set("x-lunora-identity",x),B!==void 0&&N.set("x-lunora-identity-exp",B),ae(R,m,new Request(o,{headers:N}))},Lt=async(o,i,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,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});S("fan-out")},be=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Lt(o.fanOut,o.functionPath,i);return}if(e.authorizeShard){const l=o.shardKey??n;if(!await e.authorizeShard(i,l))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&S("shard")}},Ae=async(o,i,l,d,w,b)=>{const R=Date.now(),{observability:m,sampling:T}=e,A=Le(o),{decision:N,ignoredUpstream:q,trace:x}=Vn(o,{...T===void 0?{}:{sampling:T},trustInbound:t(o)});q&&r();const B={...w,"x-lunora-sample-errors":N.keepErrors?"1":"0"};Yn(x,B);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:l,functionPath:i}),headers:B,method:"POST"});try{const G=await ae(u,d,W);return de(m,{...A,...lt(x),durationMs:Date.now()-R,functionPath:i,ok:G.ok,shardKey:d,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},b,void 0,{isTraced:x.sampled,keepErrors:N.keepErrors}),G}catch(G){throw de(m,{...A,...lt(x),...Oe(i,Date.now()-R,G,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:N.keepErrors}),G}},jt=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,l)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const d=await Ho(o);Wo(i,d),jt(d);const w=await oe(o,d);if(w!==void 0)return w;const{headers:b,identity:R}=await ue(o,i,s);await be(d,R);const m=ft(d,e);{const T=Date.now(),{observability:A}=e,N=Le(o),q=Ee(i,o,l&&(W=>l.waitUntil?.(W)));if(d.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 G=await W.fanOut(u,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return de(A,{durationMs:Date.now()-T,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:d.fanOut.table},functionPath:d.functionPath,...N,ok:!0},q),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw de(A,{...Oe(d.functionPath,Date.now()-T,G,{fanOut:{table:d.fanOut.table}}),...N},q),G}}const x=d.shardKey??n,B=()=>Ae(o,d.functionPath,d.args??{},x,b,q);return m&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:m.price},B,ct(l)):B()}},Gt=async(o,i,l)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const d=await Z(o),{calls:w}=d;if(!Array.isArray(w))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:R}=await ue(o,i,s),m=zr(w,n);for(const Q of m.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...m.entries()].flatMap(([Q,z])=>z.map(ne=>be({functionPath:ne.functionPath,shardKey:Q},R))));const{observability:T}=e,A=Ee(i,o,l&&(Q=>l.waitUntil?.(Q))),N=Le(o),q=[],x=[],B=(Q,z,ne,ce)=>({body:{error:{code:ne,message:ce}},id:Q.id,status:z}),W=(Q,z,ne,ce,fe)=>{for(const H of Q)de(T,fe(H),A),q.push(B(H,z,ne,ce))},G=(Q,z,ne,ce,fe)=>{for(const H of Q){const we=ce.get(H.id)??fe,ye=we<400;de(T,{durationMs:ne,functionPath:H.functionPath,...N,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},A)}};await Promise.all([...m.entries()].map(async([Q,z])=>{const ne=new Headers(b);ne.set("content-type","application/json");const ce=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(u,Q,ce)}catch(V){const Ie=Date.now()-fe,{body:Qe}=ar(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});W(z,502,Qe.code,Qe.message,nr=>({...Oe(nr.functionPath,Ie,V,{shardKey:Q}),...N}));return}const we=Date.now()-fe,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)})`;W(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...N,ok:!1,shardKey:Q}));return}const ke=Array.isArray(De.results)?De.results:[],tr=new Map(ke.map(V=>[V.id,V.status??H.status])),rr=new Set(ke.map(V=>V.id));G(z,Q,we,tr,H.status),q.push(...ke);for(const V of z)rr.has(V.id)||q.push(B(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Fe]=x;return x.length===1&&Fe!==void 0&&(Ke["x-d1-bookmark"]=Fe),Response.json({results:q},{headers:Ke,status:200})},Mt=async(o,i,l,d={},w={})=>{try{const b=l.__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:m}=await ue(o,i,s);await be({functionPath:b,shardKey:w.shardKey},m);const T=w.shardKey??n,A=Ee(i,o,w.waitUntil);return await Ae(o,b,d,T,R,A)}catch(b){return ze(b)}},Kt=1e3,Ft=async(o,i)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const d=[];let w;for(let R=0;R<Kt;R+=1){const m=await o.list({cursor:w,prefix:i});for(const T of m.objects)T.key.endsWith(".manifest.json")&&d.push(T.key);if(!m.truncated||m.cursor===void 0)break;w=m.cursor}const b=d.toSorted((R,m)=>m.localeCompare(R)).slice(l);await Promise.all(b.flatMap(R=>{const m=R.slice(0,-14);return[o.delete(R),o.delete(m)]}))},Qt=async o=>{const i=e.backupStore,l=e.queryCoordinator;if(!i)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const d=E();if(!d||d.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 w={authorization:`Bearer ${d}`,"content-type":"application/json"},b=e.backupTables;let R=0,m=0;const T=[];await nt(e,l,w,b,W=>{const G=`${JSON.stringify(W)}
5
+ `;R+=1,m+=Ao.encode(G).byteLength,T.push(G)},u);const A=e.backupPrefix??"backups/",N=new Date(o.scheduledTime).toISOString(),q=`${A}lunora-backup-${N.replaceAll(/[.:]/gu,"-")}.ndjson`,x=`${q}.manifest.json`;await i.put(q,new Blob(T,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const B={bytes:m,createdAt:N,cron:o.cron,file:q,id:N,rows:R,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await i.put(x,`${JSON.stringify(B,void 0,2)}
6
+ `,{httpMetadata:{contentType:"application/json"}}),await Ft(i,A)},Ge=async(o,i,l)=>{const{observability:d}=e,w=Date.now(),b=_e(16),R=_e(8),m=pt(i);try{const T=await l();return de(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:R,traceId:b},m),T}catch(T){throw de(d,{...Oe(o,Date.now()-w,T,{}),spanId:R,traceId:b},m),T}finally{We(d,m)}},zt=async(o,i,l)=>{f(i);const d=[],w=m=>m instanceof Error?m:new Error(String(m)),b=e.crons?.[o.cron];if(b)try{await b(o,i,l)}catch(m){d.push(w(m))}if(await Y(o.cron,i,d,w),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Qt(o)}catch(m){d.push(w(m))}const[R]=d;if(d.length===1&&R)throw R;if(d.length>1)throw new AggregateError(d,`scheduled("${o.cron}") had ${String(d.length)} failure(s)`)},Wt=async(o,i)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;const w=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:i},functionPath:jo}),headers:{authorization:`Bearer ${d}`,"content-type":"application/json"},method:"POST"});await ae(u,n,w)}catch{}},Ht=async(o,i,l,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??Lo;return Mo(l.pathname,b)&&d.waitUntil?.(Wt(i,w.status>=400?"fail":"ok")),w},Jt=async({args:o,env:i,functionPath:l,request:d,shardKey:w,waitUntil:b})=>{yt(o,"REST");const R={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:m,identity:T}=await ue(d,i,s);await be(R,T);const A=w??n,N=Ee(i,d,b),q=()=>Ae(d,l,o,A,m,N),x=ft(R,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},q,ct({waitUntil:b})):q()},Vt=wr({functions:e.functions??{},invoke:Jt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Yt={[qo]: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"}}),[Do]:(o,i,l)=>Ct(o,i,l),[ut]:(o,i,l,d)=>$t(o,i,d),[vo]:(o,i,l,d)=>Gt(o,i,d),[ko]:(o,i)=>F(o,i),[Io]:(o,i)=>U(o,i),[Po]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});$(o);const i=E();if(i===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Lr(i);return Response.json(l,{headers:{"cache-control":"no-store"}})},...I,...se,...Re,...re,...At,...vt,...Dt,...kt,...It,...Nt,...Vt,...Mr({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ee,readJsonBody:Z})};let ie=Je(e.security),Me=!1;const Xt=o=>{Me||(Me=!0,ie=Je(e.security,o??{}))},Zt=async(o,i)=>{if(!(e.adminGate===void 0||!xo(i)))try{await e.adminGate(o)&&g.add(o)}catch{}},er=async(o,i,l)=>{const d=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const m=Number(o.headers.get("content-length")??""),T=d.pathname===_t?St:mt;if(Number.isFinite(m)&&m>T)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const w=await Ht(o,i,d,l);if(w)return w;if(ve){const m=`${o.method} ${d.pathname}`,T=ve[m]??ve[d.pathname];if(T)return T(o,i,l)}const b=Yt[d.pathname];return b?(await Zt(o,d.pathname),b(o,i,d,l)):e.voiceAgents!==void 0&&d.pathname.startsWith(ht)?Bt(o,i,d):await xt(o,i,l)||new Response("Not found",{status:404})};return{async fetch(o,i,l){e.passThroughOnException&&l.passThroughOnException?.(),Xt(i),f(i);const d=Sr(o,ie);if(d)return d;const w=Rr(o,ie);if(w)return Ne(w,o,ie);try{const b=await er(o,i,l);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,pt(l))}},async queue(o,i,l){await Ge(`queue:${Fo(o)}`,l,async()=>{await e.queue?.(o,i,l)})},async scheduled(o,i,l){await Ge(`cron:${o.cron}`,l,async()=>{await zt(o,i,l)})},serverQuery:Mt}},ra=e=>Rt(e),na=e=>typeof e=="function"?{fetch:e}:e,oa=e=>!!(e.crons??e.cronJobs??e.backupCron),Ea=(e,t)=>{const r=na(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const h=ra({...c,httpRouter:r});return n!==void 0&&!oa(c)?{...h,scheduled:async(E,O,D)=>{await n(E,O,D)}}:h};if(typeof t!="function")return s(t);const u=t;return{fetch:(c,h,E)=>s(u(h)).fetch(c,h,E),queue:(c,h,E)=>s(u(h)).queue?.(c,h,E)??Promise.resolve(),scheduled:(c,h,E)=>s(u(h)).scheduled(c,h,E),serverQuery:(c,h,E,O,D)=>s(u(h)).serverQuery(c,h,E,O,D)}},aa=(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}},Oa=(e={})=>(t,r,n)=>Rt(aa(e,r)).fetch(t,r,n??sr),Ta=e=>e;export{Kr as GET_AUTH_AUDIT_LOG_OP,sr as NOOP_EXECUTION_CONTEXT,Ra as composeIdentityResolvers,ra as composeWorker,Oa as createLunoraHandler,Rt as createWorker,Ta as defineRpcEnvelope,Yo as probeRelayCount,aa as resolveLunoraOptions,Aa as routeIdentityResolvers,Ea as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{f as u,u as d}from"./identity-header-CDgIrYAz.mjs";import{LunoraError as o}from"./LunoraError-ByasbDmd.mjs";const l="/_lunora/rpc",c=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=u(r.userId)),r.identity!==void 0&&(t["x-lunora-identity"]=d(r.identity)),t},i=async(r,t,a)=>{const e=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${l}`,{body:JSON.stringify(t),headers:c(r),method:"POST"}));if(!e.ok)throw new o(`cross-shard relation ${a} failed: worker returned ${String(e.status)}`);const n=await e.json();if(typeof n.failed=="number"&&n.failed>0){const s=(typeof n.ok=="number"?n.ok:0)+n.failed;throw new o(`cross-shard relation ${a} failed on ${String(n.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return n.data},y=r=>({crossShardCounter:async(t,a)=>{const e=await i(r,{args:{table:t,where:a},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof e=="number"?e:0},crossShardReader:async(t,a)=>{const e=await i(r,{args:{orderBy:a?.orderBy,table:t,where:a?.where,with:a?.with},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(e)?e:[]}}});export{y as createCrossShardRelationCapabilities};
@@ -0,0 +1 @@
1
+ import{LunoraError as O}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as E}from"./applyJurisdiction-8bzZjAPR.mjs";const he=r=>({listShardKeys(e){return r[e]??[]}}),le=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new O('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.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 O('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},T=16,j=5e3,f=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,C=r=>{const e=r??{};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}},q=(r,e)=>r?"failed":e?"in_progress":"completed",F=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}s+=1;const d=f(c.value),u=C(d);t+=u.changed,o+=u.processed,n||=u.status==="in_progress",i||=u.status==="failed",e.push({result:d,shardKey:c.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:q(i,n||a>0)}},B=r=>{const e=r??{};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}},I=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=B(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},P=0,N=1,D=2,x=r=>r==null?P:typeof r=="number"?N:D,v=(r,e)=>{const s=x(r),a=x(e);if(s!==a)return s<a?-1:1;if(s===P)return 0;if(s===N){const n=r,i=e;return n<i?-1:n>i?1:0}const t=String(r),o=String(e);return t<o?-1:t>o?1:0},R=(r,e,s)=>{const a=v(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=v(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return v(r.rowId,e.rowId)},V=r=>{const e=JSON.stringify(r),s=new TextEncoder().encode(e);let a="";for(const t of s)a+=String.fromCodePoint(t);return btoa(a)},$=r=>{let e;try{const s=atob(r),a=Uint8Array.from(s,t=>t.codePointAt(0)??0);e=new TextDecoder().decode(a)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:a}=s;if(a!==null&&typeof a=="object")return{perShard:a}}}catch{}return{perShard:{}}},J=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Q=(r,e)=>{let s,a;for(const t of r){const o=t.rows[t.head];o!==void 0&&(a===void 0||R(o.key,a,e)<0)&&(s=t,a=o.key)}return s},U=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?V({perShard:t}):null},L=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Q(r,s);if(i===void 0)break;const c=i.rows[i.head];c!==void 0&&(t.push(c.doc),o[i.shardKey]=c.key),i.head+=1}const n=U(r,o);return{isDone:n===null,nextCursor:n,page:t}},G=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Y=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],c=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:c,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,failed:s,ok:e}},H=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:H(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const c=f(i.value),d=c?.inserted??{};for(const[h,y]of Object.entries(d))s[h]=(s[h]??0)+y;const u=c?.errors;Array.isArray(u)&&a.push(...u),t+=c?.conflicts??0,e.push({result:{conflicts:c?.conflicts??0,errors:c?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,a)=>{const t=E(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const c=new Promise(u=>{i=setTimeout(()=>{try{o.abort()}catch{}u({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const u=await t.fetch(n);if(!u.ok)return{kind:"err",message:`shard "${e}" returned ${String(u.status)}`,shardKey:e,timedOut:!1};const h=await u.json();return{kind:"ok",shardKey:e,value:h}}catch(u){const h=u instanceof Error?u.message:String(u);return{kind:"err",message:`shard "${e}" threw: ${h}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,c])}finally{i!==void 0&&clearTimeout(i)}},b=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const c=r[i];if(i>=r.length||c===void 0)return;a[i]=await s(c,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},m=async(r,e,s,a,t)=>{const o=p(s);return b(e,a,async n=>g(r,n,o,t))},Z=(r,e)=>r<e?-1:r>e?1:0,ee=r=>{const e={};for(const s of Object.keys(r).toSorted(Z))e[s]=r[s]??null;return JSON.stringify(e)},re=r=>{const e=[];for(const s of r)Array.isArray(s)&&e.push(...s);return e},te=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},se=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=ee(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=te(n.value,t,s))},ae=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)se(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},oe=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ne=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ie=(r,e)=>{const s=[];for(const o of r)if(Array.isArray(o))for(const n of o){if(n===null||typeof n!="object")continue;const i=n[e.by],c=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const a=e.direction??"desc",t=(o,n)=>o<n?-1:o>n?1:0;return s.sort((o,n)=>a==="asc"?t(o.score,n.score):t(n.score,o.score)),s.slice(0,e.k).map(o=>o.row)},ue=(r,e)=>{switch(e.kind){case"concat":return re(r);case"first":return r[0];case"groupBy":return ae(r,e.op??"sum");case"max":return M(r,(s,a)=>Math.max(s,a));case"min":return M(r,(s,a)=>Math.min(s,a));case"rank":return ne(r);case"sum":return oe(r);case"topK":return ie(r,e);default:return r}},fe=r=>{const e=r.maxConcurrency??T,s=r.perShardTimeoutMs??j;if(e<1)throw new O("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],c=[],d=[];for(const u of n)u.kind==="ok"?(i.push(u.value),c.push(u.shardKey)):d.push({message:u.message,shardKey:u.shardKey,timedOut:u.timedOut});return{data:ue(i,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(a,t){const o=new Set,n=await Promise.all(t.tables.map(async u=>r.registry.listShardKeys(u)));for(const u of n)for(const h of u)o.add(h);const i=[...o],c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await m(a,i,c,e,s);return G(d)},async orchestrateCdcSync(a,t){const o=new Set,n=await Promise.all(t.tables.map(async u=>r.registry.listShardKeys(u)));for(const u of n)for(const h of u)o.add(h);const i=[...o],c=t.cursors??{},d=await b(i,e,async u=>{const h=c[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:h},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:h}});return Y(d)},async orchestrateImport(a,t){const{batches:o}=t,n=await b(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return X(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await b(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return F(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return I(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],c=t.cursor?$(t.cursor):{perShard:{}},d=await b(o,e,async l=>{const A=c.perShard[l],S={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(S.partitionKey=t.partitionKey),A!==void 0&&(S.after=A);const w=await g(a,l,p({args:S,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(w.kind==="err")return{error:{message:w.message,timedOut:w.timedOut},shardKey:l};const _=J(f(w.value));return{directions:_.directions,hasMore:_.hasMore,rows:_.rows,shardKey:l}}),u=[];let h=0,y=0,K;for(const l of d){if(l.error){y+=1;continue}h+=1,K===void 0&&l.directions&&l.directions.length>0&&(K=l.directions),u.push({hasMore:l.hasMore??!1,head:0,rows:l.rows??[],shardKey:l.shardKey})}const k=L(u,n,K??i,c.perShard);return{continueCursor:k.nextCursor,failed:y,isDone:k.isDone,ok:h,page:k.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},registry:r.registry}};export{fe as createQueryCoordinator,he as createStaticShardRegistry,le as mergeStrategyForAggregate};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{a as m,o as E,f as O,u as j}from"./identity-header-CDgIrYAz.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const s="$lunora.wire$",w=64,A=1024,v="__proto__",$={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},S={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[s,"undefined"];if(e===null)return null;const l=typeof e;if(l==="bigint")return[s,"bigint",e.toString()];if(l==="number"){const t=e;return Number.isNaN(t)?[s,"nan"]:t===1/0?[s,"inf"]:t===-1/0?[s,"-inf"]:t}if(l!=="object")return e;if(e instanceof Date)return[s,"date",f(e.getTime(),n+1)];if(e instanceof Error){const t=e,a={};for(const u of Object.keys(t))t[u]!==void 0&&(a[u]=f(t[u],n+1));const i=[s,"error",t.name,t.message,a];return t.cause!==void 0&&i.push(f(t.cause,n+1)),i}if(e instanceof URL)return[s,"url",e.href];if(e instanceof Map)return[s,"map",[...e.entries()].map(([t,a])=>[f(t,n+1),f(a,n+1)])];if(e instanceof Set)return[s,"set",[...e].map(t=>f(t,n+1))];if(e instanceof ArrayBuffer)return[s,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,a=t.constructor.name,i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return a==="Uint8Array"?[s,"bytes",m(i)]:[s,"bytes",m(i),a]}if(Array.isArray(e)){const t=e.map(a=>f(a,n+1));return t.length>0&&t[0]===s?[s,"arr",t]:t}const d=Object.getPrototypeOf(e);if(d!==null&&d!==Object.prototype){const t=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const r=e,o={};for(const t of Object.keys(r)){const a=r[t];a!==void 0&&(o[t]=f(a,n+1))}return o},c=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===s)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>c(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(c(e[2],n+1));case"map":return new Map(e[2].map(([r,o])=>[c(r,n+1),c(o,n+1)]));case"set":return new Set(e[2].map(r=>c(r,n+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],o=e[3],t=(Object.hasOwn(S,r)?S[r]:void 0)??Error,a=new t(o);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const i=c(e[4],n+1);for(const u of Object.keys(i))u===v?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:i[u],writable:!0}):a[u]=i[u];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:c(e[5],n+1),writable:!0}),a}case"bytes":{const r=E(e[2]),o=e[3]??"Uint8Array";if(o==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const t=Object.hasOwn($,o)?$[o]:void 0;return t?new t(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>c(r,n+1))}return e.map(r=>c(r,n+1))}const l=e,d={};for(const r of Object.keys(l)){const o=c(l[r],n+1);r===v?Object.defineProperty(d,r,{configurable:!0,enumerable:!0,value:o,writable:!0}):d[r]=o}return d},x=e=>{if(typeof e=="string")return e;const n=e?.__lunoraRef;if(typeof n!="string"||n.length===0)throw new p("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return n},I=e=>{const n=new p(e.code,e.message);return e.data!==void 0&&(n.data=c(e.data)),n},U=(e,n={})=>{const l=N(e,n.jurisdiction),d=n.system??!0,r=o=>U(e,{...n,...o});return{as:o=>r({as:o}),asSystem:()=>r({as:void 0}),call:async(o,t,a)=>{const i=x(o),u=a?.shardKey??n.shardKey;if(u===void 0||u.length===0)throw new p("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const h={"content-type":"application/json"};d&&(h["x-lunora-system"]="1"),n.as&&(h["x-lunora-userid"]=O(n.as.userId),n.as.claims&&(h["x-lunora-identity"]=j(n.as.claims))),a?.mutationId!==void 0&&a.mutationId.length>0&&(h["x-lunora-mutation-id"]=a.mutationId);const y=await R(l,u).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(t??{}),functionPath:i}),headers:h,method:"POST"}));let b;try{b=await y.json()}catch{const g=y.statusText?` ${y.statusText}`:"";throw new p("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(y.status)}${g})`)}if("error"in b)throw I(b.error);if(!y.ok){const g=y.statusText?` ${y.statusText}`:"";throw new p("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(y.status)}${g})`)}return c(b.result)},forShard:o=>r({shardKey:o})}};export{U as createShardClient};
@@ -0,0 +1 @@
1
+ const c=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},f=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},l=t=>c(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");new TextDecoder;const a=new TextEncoder,o="=",s=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},d=t=>l(a.encode(JSON.stringify(t))),h=t=>!t.startsWith(o)&&s(t)?t:`${o}${l(a.encode(t))}`;export{c as a,h as f,f as o,d as u};
@@ -0,0 +1 @@
1
+ import{R as A,a as E}from"./rest-cache-5unAzdFN.mjs";import{LunoraError as d}from"./LunoraError-ByasbDmd.mjs";import{d as O}from"./method-guard-BbuR0VfS.mjs";const h=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),T=async(t,a=h)=>{if(!t.body)return"";const e=t.body.getReader(),r=new TextDecoder;let s=0,n="";for(;;){const{done:o,value:c}=await e.read();if(o)break;if(c){if(s+=c.byteLength,s>a)throw await e.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n+=r.decode(c,{stream:!0})}}return n+=r.decode(),n},B=async(t,a=h)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),r=[];let s=0;for(;;){const{done:c,value:u}=await e.read();if(c)break;if(u){if(s+=u.byteLength,s>a)throw await e.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});r.push(u)}}const n=new Uint8Array(s);let o=0;for(const c of r)n.set(c,o),o+=c.byteLength;return n.buffer},D=async(t,a=h)=>{let e;try{const r=await T(t,a);e=r===""?{}:JSON.parse(r)}catch(r){throw r instanceof d?r:new d("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!p(e))throw new d("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},k=(t,a)=>{if(!p(t))throw new d(`${a} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},v=t=>Object.entries(t).map(([a,e])=>({exposure:e.expose,functionPath:a,kind:e.kind})),L=t=>E(v(t)),P=(t,a)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const r=a.headers.get("x-lunora-shard-key");return r===null||r===""?void 0:r},S=t=>{const a=Object.create(null);for(const[e,r]of t.searchParams.entries())if(e!=="shardKey")try{a[e]=JSON.parse(r)}catch{a[e]=r}return a},$=t=>{const{functions:a,invoke:e,rateLimit:r,readJsonBody:s}=t,n={};for(const o of L(a)){const c=o.kind==="query"?["GET","POST"]:["POST"],u=a[o.functionPath].expose?.cache;n[o.path]=async(i,R,U,l)=>{const w=O(i,c);if(w)return w;const b=new URL(i.url);if(r){const y=await r(i,o.functionPath);if(y)return y}let f;i.method==="GET"?f=S(b):f=i.body===null?{}:await s(i),k(f,"REST");const m=P(b,i),g=await e({args:f,env:R,functionPath:o.functionPath,request:i,...m===void 0?{}:{shardKey:m},...l?.waitUntil===void 0?{}:{waitUntil:y=>l.waitUntil?.(y)}});return A(g,u,i)}}return n},q=(t,a)=>async(e,r)=>{const s=a.key?a.key(e,r):e.headers.get("cf-connecting-ip")??void 0,n=await t.limit(a.name,s===void 0?{}:{key:s});if(n.ok)return;const o=Math.max(1,Math.ceil(n.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{$ as S,q as U,T as a,D as b,h as d,k as e,L as f,S as g,P as p,B as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.49",
3
+ "version": "1.0.0-alpha.50",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.15",
50
- "@lunora/errors": "1.0.0-alpha.10",
51
- "@lunora/platform": "1.0.0-alpha.1"
49
+ "@lunora/bindings": "1.0.0-alpha.17",
50
+ "@lunora/errors": "1.0.0-alpha.12",
51
+ "@lunora/platform": "1.0.0-alpha.3"
52
52
  },
53
53
  "engines": {
54
54
  "node": "^22.15.0 || >=24.11.0"
@@ -1 +0,0 @@
1
- import{R as g,a as k}from"./rest-cache-5unAzdFN.mjs";import{d as w}from"./method-guard-BbuR0VfS.mjs";const P=r=>Object.entries(r).map(([e,t])=>({exposure:t.expose,functionPath:e,kind:t.kind})),v=r=>k(P(r)),x=(r,e)=>{const t=r.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const a=e.headers.get("x-lunora-shard-key");return a===null||a===""?void 0:a},S=r=>{const e={};for(const[t,a]of r.searchParams.entries())if(t!=="shardKey")try{e[t]=JSON.parse(a)}catch{e[t]=a}return e},K=r=>{const{functions:e,invoke:t,rateLimit:a,readJsonBody:s}=r,i={};for(const o of v(e)){const l=o.kind==="query"?["GET","POST"]:["POST"],m=e[o.functionPath].expose?.cache;i[o.path]=async(n,p,T,d)=>{const f=w(n,l);if(f)return f;const h=new URL(n.url);if(a){const c=await a(n,o.functionPath);if(c)return c}let u;n.method==="GET"?u=S(h):u=n.body===null?{}:await s(n);const y=x(h,n),R=await t({args:u,env:p,functionPath:o.functionPath,request:n,...y===void 0?{}:{shardKey:y},...d?.waitUntil===void 0?{}:{waitUntil:c=>d.waitUntil?.(c)}});return g(R,m,n)}}return i},L=(r,e)=>async(t,a)=>{const s=e.key?e.key(t,a):t.headers.get("cf-connecting-ip")??void 0,i=await r.limit(e.name,s===void 0?{}:{key:s});if(i.ok)return;const o=Math.max(1,Math.ceil(i.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{S as argsFromQuery,K as buildRestRoutes,L as createRestRateLimit,x as readShardKey,v as restSurfaceFromRegistry};
@@ -1,6 +0,0 @@
1
- import{isLunoraError as nr,toErrorBody as or}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as ar}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as sr,A as ir,R as dr,d as ur,i as cr,s as lr}from"./otlp-resource-B-ByO9qo.mjs";import{LunoraError as a,toErrorResponse as We}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as hr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as pr,durableObjectProbe as fr,d1Probe as wr,presenceProbe as Ne}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as mr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as ga,routeIdentityResolvers as ba}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as yr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as gr,f as He,a as ue}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as Je}from"./applyJurisdiction-8bzZjAPR.mjs";import{buildRestRoutes as br}from"./argsFromQuery-BkJXnIpe.mjs";import{resolveSecurity as Ve,handleCorsPreflight as Or,enforceOrigin as Er,decorateResponse as Ue,enforceWebSocketOrigin as Ye}from"./decorateResponse-DBIWsRSZ.mjs";const Tr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},yt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},_r="::relay::",Rr=(e,t)=>`${e}${_r}${String(t)}`,je=new TextEncoder,Sr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Ar=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},vr=64,qe=new Map,gt=async e=>{const t=qe.get(e);if(t)return t;yt(qe,vr);const r=crypto.subtle.importKey("raw",je.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return qe.set(e,r),r},Dr=async(e,t)=>{const r=await gt(e),n=await crypto.subtle.sign("HMAC",r,je.encode(t));return Sr(new Uint8Array(n))},kr=async(e,t,r)=>{const n=await gt(e);return crypto.subtle.verify("HMAC",n,r,je.encode(t))},bt="v1",Ir=6e4,Pr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Ir),n=`${bt}.${String(r)}`,s=await Dr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},Nr=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!==bt||c.length===0)return!1;const l=Number(d);if(!Number.isFinite(l)||l<=r)return!1;let b;try{b=Ar(c)}catch{return!1}return kr(e,`${s}.${d}`,b)},k="/_lunora/admin/auth",Ur={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},P=(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},qr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/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"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:P(e,"email"),name:P(e,"name"),password:ee(e,"password"),role:$e(e.role)}),http:"POST",method:"createUser"},[`${k}/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:P(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/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:P(e,"userId")}},http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:ee(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:P(e,"name"),ownerId:ee(e,"ownerId"),slug:ee(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:ee(e,"logo"),metadata:Xe(e,"metadata"),name:ee(e,"name"),organizationId:P(e,"organizationId"),slug:ee(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:ee(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:ee(e,"inviterId"),organizationId:P(e,"organizationId"),role:ee(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/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:P(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:Ze(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:Ze(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},$r=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:Ur[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 b=new URL(s.url),T={body:d.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:g=>e.queryParameter(b,g)},D=d.build(T),w=await t(()=>l(D));return Response.json(d.returns==="void"?{ok:!0}:w,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,d]of Object.entries(qr))n[s]=c=>r(c,d);return n},xr="__lunora_admin__:getAuthAuditLog",et=e=>typeof e=="string"&&e!==""?e:void 0,tt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Lr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s={},d=et(r.actorId),c=et(r.event),l=tt(r.sinceSeq),b=tt(r.limit);d!==void 0&&(s.actorId=d),c!==void 0&&(s.event=c),l!==void 0&&(s.sinceSeq=l),b!==void 0&&(s.limit=b);let T;try{T=await n.read(s)}catch(w){throw w instanceof a?w:(console.error("[lunora] auth audit read failed:",w),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const D={entries:T};return Response.json(D,{headers:{"content-type":"application/json"},status:200})},rt=500,Br=(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}},Cr=(e,t)=>{if(e.length>rt)throw new a(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:d,shardKey:c}=Br(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},jr=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:b}=await r.read();if(l)break;if(b){if(s+=b.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(b)}}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})}},Gr=new TextEncoder,Mr=e=>{const t=JSON.stringify(e),r=Gr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Kr=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,b]of Object.entries(d))typeof b=="number"&&Number.isFinite(b)&&(c[l]=b);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Fr=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}},nt=(e,t,r)=>{for(const n of t)e.push(Fr(n));return r!==void 0&&t.length>=r},Qr="/_lunora/admin/export",zr="/_lunora/admin/import",Wr="/_lunora/admin/sync",Hr="/_lunora/admin/connector/sync",Jr="/_lunora/admin/apply",Vr="/_lunora/admin/export-tap/run",Yr=new TextEncoder,Xr=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}},Zr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:d,assertAdmin:c,requireAdminOption:l,resolveForwardContext:b,shardDO:T,streamExportRows:D,streamingImport:w,syncGlobals:g}=e,p=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Xr(v),{headers:K}=await b(v,B),F=new ReadableStream({async pull(j){const M=X=>{j.enqueue(Yr.encode(`${JSON.stringify(X)}
2
- `))};try{await D(Y,K,N.tables,M),j.close()}catch(X){j.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},y=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},F=typeof N.limit=="number"?N.limit:void 0,j=typeof N.globalCursor=="number"?N.globalCursor:0,M=Array.isArray(N.tables)?N.tables.filter(Z=>typeof Z=="string"):void 0,{headers:X}=await b(v,B),J=M??s(),oe=await Y.orchestrateCdcSync(T,{cursors:K,headers:X,limit:F,tables:J}),ie=g?await g({limit:F,sinceSeq:j}):void 0;return Response.json({global:ie,shards:oe.shards},{status:200})},_=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),K=Kr(N.cursor),F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,j=Array.isArray(N.tables)?N.tables.filter(re=>typeof re=="string"):void 0,{headers:M}=await b(v,B),X=j??s(),J=await Y.orchestrateCdcSync(T,{cursors:K.s,headers:M,limit:F,tables:X}),oe=[],ie={...K.s};let Z=!1;for(const re of J.shards)Z=nt(oe,re.changes??[],F)||Z,ie[re.shardKey]=re.cursor;let pe=K.g;if(g){const re=await g({limit:F,sinceSeq:K.g});Z=nt(oe,re.changes,F)||Z,pe=re.cursor}const be=Mr({g:pe,s:ie,v:1}),Ae={changes:oe,hasMore:Z,nextCursor:be};return Response.json(Ae,{status:200})},R=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await te(v),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)),F=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:j}=await b(v,B),M=await Y.orchestrateApplyCdc(T,{batches:K,headers:j}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:M.applied+X,failed:M.failed,ok:M.ok},{status:200})},I=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;c(v);const{headers:Y}=await b(v,B),N=await w(v,Y);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},x=async(v,B)=>{const C=me(v,["POST"]);if(C)return C;const Y=l(v,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(v),K=typeof N.sink=="string"?N.sink:void 0,F=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,j=Array.isArray(N.tables)?N.tables.filter(ie=>typeof ie=="string"):void 0;if(K===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=n[K];if(M===void 0)throw new a(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await b(v,B),J=j??s(),oe=await hr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:T,sink:M,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[Jr]:R,[Hr]:_,[Qr]:p,[Vr]:x,[zr]:I,[Wr]:y}},Ot=e=>[],en=(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}},tn=async(e,t,r,n,s,d,c)=>{if(n!==void 0&&s.length===0)return;const l=n===void 0?[]:s,b=n===void 0?Ot():[],T=l.length>0?l:b,D=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:T});for(const w of D.shards)if(!w.error)for(const g of w.rows??[])d(g)},ot=async(e,t,r,n,s,d)=>{const{globalTables:c,shardLocalTables:l}=en(e,n);await tn(e,t,r,n,l,s,d);const b=e.exportGlobals;if((n===void 0||c.length>0)&&b){const T=n===void 0?[]:c;for await(const D of b({tables:T}))s(D)}},rn=(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}},nn=(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}},on=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,l=0;const b=e.body.getReader(),T=new TextDecoder;let D="",w=0;const g=p=>{l+=1;const y=p.trim();if(y.length===0)return;c+=1;const _=rn(y,l);if(!_.ok){n.push(_.error);return}const{doc:R,table:I}=_,x=t.resolveTableSharding?.(I);if(x?.mode.kind==="global"){s.push({doc:R,line:l,table:I});return}const v=nn(R,I,x,r,l);if(!v.ok){n.push(v.error);return}const B=d.get(v.shardKey);B?B.rows.push({doc:R,table:I}):d.set(v.shardKey,{rows:[{doc:R,table:I}],shardKey:v.shardKey,startLine:l})};for(;;){const{done:p,value:y}=await b.read();if(p)break;if(y&&(w+=y.byteLength,w>ge))throw await b.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});D+=T.decode(y,{stream:!0});let _=D.indexOf(`
3
- `);for(;_!==-1;){const R=D.slice(0,_);D=D.slice(_+1),g(R),_=D.indexOf(`
4
- `)}}return D.length>0&&g(D),{errors:n,globalRows:s,perShard:d,received:c}},at=(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},an=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:d,globalRows:c,perShard:l,received:b}=await on(e,t,s),T={conflicts:0,errors:d,inserted:{}},D=[];if(t.resolveTableSharding===void 0&&l.size>0&&D.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),l.size>0){const w=t.queryCoordinator;if(!w)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const g=await w.orchestrateImport(n,{batches:[...l.values()],headers:r});at(T,g)}if(c.length>0)if(t.importGlobals){const w=c[0]?.line??1,g=await t.importGlobals({rows:c,startLine:w});at(T,g)}else for(const w of c)T.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:w.line,message:`row targets global table "${w.table}" but no \`importGlobals\` is configured`,table:w.table});return{conflicts:T.conflicts,errors:T.errors,inserted:T.inserted,received:b,...D.length>0?{warnings:D}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",sn=(e,t)=>{let r=xe(t),n=!1;Le(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const s=Le(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=Le(xe(d.inner));l!=="unknown"&&(c.element=l)}return c},dn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>sn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),un="/_lunora/admin/functions",cn="/_lunora/admin/cron-jobs",ln="/_lunora/admin/openapi",hn="/_lunora/admin/openrpc",pn="/_lunora/admin/global/tables",fn="/_lunora/admin/global/table",wn="/_lunora/admin/global/facet",st=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},mn=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:{}}),yn=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"}),gn=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 y=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([R,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:dn(I.args),kind:I.kind,path:R}]).toSorted((R,I)=>R.path.localeCompare(I.path));return Response.json({functions:_},{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 y=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([R,I])=>I.map(x=>({args:x.args,cron:R,functionPath:x.functionPath,name:x.name,shardKey:x.shardKey,workflow:x.workflow}))).toSorted((R,I)=>R.name.localeCompare(I.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},b=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??mn,{headers:{"content-type":"application/json"},status:200})},T=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??yn,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},w=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table");if(R===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...n(p),filters:st(s(_,"filters")),table:R});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table"),I=s(_,"column");if(R===void 0||I===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const x=s(_,"limit"),v=x===void 0?void 0:Number(x),B=await y.facetColumn({column:I,filters:st(s(_,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[cn]:l,[un]:c,[wn]:g,[fn]:w,[pn]:D,[ln]:b,[hn]:T}},bn="/_lunora/admin/kv/namespaces",On="/_lunora/admin/kv/keys",Et="/_lunora/admin/kv/value",Tt=32*1048576,it=60,En=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=w=>r(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),d=(w,g)=>{const p=new URL(w.url),y=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(y==="")throw new a(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:y}},c=async(w,g)=>{if(!(await w.listNamespaces()).some(p=>p.binding===g))throw new a(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async w=>{if(w.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(w).listNamespaces()})},b=async w=>{if(w.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(w),p=new URL(w.url),y=p.searchParams.get("namespace")??"";if(y==="")throw new a("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,I=p.searchParams.get("limit"),x=I===null?void 0:Number.parseInt(I,10);if(x!==void 0&&(!Number.isInteger(x)||x<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=x===void 0?void 0:Math.min(x,1e3);return await c(g,y),s(await g.listKeys({cursor:R,limit:v,namespace:y,prefix:_}))},T={DELETE:async w=>{const g=n(w),p=d(w,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),s({deleted:!0})},GET:async w=>{const g=n(w),p=d(w,"GET");return await c(g,p.namespace),s(await g.getValue(p))},PUT:async w=>{const g=n(w),p=await t(w,Tt);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<it))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const y=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<y))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(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=w=>{const g=T[w.method];if(!g)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[bn]:l,[On]:b,[Et]:D}},Tn="/_lunora/migrate",_n="/_lunora/admin/pitr",Rn="/_lunora/admin/rank",Sn="/_lunora/admin/rankpage",An="/_lunora/admin/shard-traffic",vn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Dn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),kn=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"||!vn.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}},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("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}},Pn=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}},Nn=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})},Un=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??{};Nn(r);const n=Pn(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}},qn=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}},$n=async e=>{const t=await te(e);if(typeof t.functionPath!="string"||!Dn.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}},xn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:d,shardDO:c}=e,l=async(g,p)=>{if(g.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await kn(g),{headers:_}=await d(g,p),R=await s.orchestrateMigration(c,{args:y.args,functionPath:y.functionPath,headers:_,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},b=async(g,p)=>{if(g.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await In(g),{headers:_}=await d(g,p),R=await s.orchestrateRank(c,{headers:_,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},T=async(g,p)=>{if(g.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await Un(g),{headers:_}=await d(g,p),R=await s.orchestrateRankPage(c,{...y,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},D=async(g,p)=>{if(g.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))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 y=await qn(g),{headers:_}=await d(g,p),R=await s.orchestrateShardTraffic(c,{headers:_,table:y.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},w=async(g,p)=>{if(g.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const y=await $n(g),{headers:_}=await d(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:y.args,functionPath:y.functionPath}),headers:_,method:"POST"});return r(c,y.shardKey??t,R)};return{[Tn]:l,[_n]:w,[Rn]:b,[Sn]:T,[An]:D}},Ln=1,Bn=0,Cn=32,jn=512,Gn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Mn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>jn)return;const r=t.split(",");if(!(r.length>Cn)){for(const n of r)if(!Gn.test(n.trim()))return;return t}},Kn=e=>{const t=ir(e.headers.get("traceparent"));if(t===void 0)return;const r=Mn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Fn=(e,t={})=>{const r=Kn(e),n=t.trustInbound===!0?r:void 0,s=Re(8),d=n?.traceId??Re(16),c=gr(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?Ln:Bn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Qn=(e,t)=>{t.traceparent=sr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},zn=(e,t)=>{let r;return()=>{if(r===void 0){const n=lr(e),s=t===void 0?void 0:t.cf;r=dr(cr(n),ur(n,s))}return r}},Wn="/_lunora/admin/scheduled",Hn="/_lunora/admin/scheduled/status",Jn="/_lunora/admin/scheduled/ws",Vn="/_lunora/admin/scheduled/cancel",Yn="/_lunora/admin/scheduled/dead",Xn="/_lunora/admin/scheduled/dead/retry",Zn="/_lunora/admin/scheduled/dead/cancel",eo=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,d=async w=>{if(w.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async w=>{if(w.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},b=async w=>{if(w.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(w),p=await w.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("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"}))},T=async w=>{if(w.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(w).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=w=>async g=>{if(g.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),y=await g.json().catch(()=>{});if(typeof y?.id!="string"||y.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${w}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Vn]:b,[Zn]:D("/dead/cancel"),[Yn]:T,[Xn]:D("/dead/retry"),[Wn]:d,[Hn]:c,[Jn]:l}},to="/_lunora/admin/storage",ro="/_lunora/admin/storage/url",no="/_lunora/admin/storage/buckets",oo=10080*60,ao=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:d,storage:c}=e,l=y=>{const _=n(y,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},b=async y=>{const _=d(y,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(y.url),I=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(y)});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},T=y=>{if(y.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(y),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async y=>{const _=d(y,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(y.url),I=l(R);return await _(I,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:I},{headers:{"content-type":"application/json"},status:200})},w=async y=>{const _=d(y,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(y.url),I=l(R),x=await s(y),v=y.headers.get("content-type"),B=v===null||v===""?void 0:v,C=await _(I,x,{bucket:n(R,"bucket"),contentType:B});return Response.json(C,{headers:{"content-type":"application/json"},status:200})},g=async y=>{switch(y.method){case"DELETE":return D(y);case"GET":return b(y);case"POST":case"PUT":return w(y);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async y=>{if(y.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=d(y,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(y.url),I=l(R),x=Number(n(R,"expiresIn")??""),v=Number.isFinite(x)&&x>0?Math.min(x,oo):void 0,B=await _(I,{bucket:n(R,"bucket"),expiresInSeconds:v});return Response.json({key:I,url:B},{headers:{"content-type":"application/json"},status:200})};return{[no]:T,[to]:g,[ro]:p}},so=(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},io={mtls:e=>so(e,"tlsClientAuth","certVerified")==="SUCCESS"},uo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(io).find(([t])=>t===e)?.[1]??(()=>!1),co=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.'))}},lo="/_lunora/admin/vector/indexes",ho="/_lunora/admin/vector/query",po=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 b=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(b,{headers:{"content-type":"application/json"},status:200})};return{[lo]:n,[ho]:s}},fo="/_lunora/admin/workflows/instances",wo="/_lunora/admin/workflows/instance",mo="/_lunora/admin/workflows/status",yo={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},go=e=>e!==null&&Object.hasOwn(yo,e)?e:void 0,dt=(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},ut=()=>{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})},bo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,b)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const T=r(l);if(!T)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(b,"name"),w=go(b.searchParams.get("status"));return Response.json(await T.listInstances({page:dt(b,"page"),perPage:dt(b,"perPage"),status:w,workflowName:D}))},s=async(c,l,b)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const T=r(l);return T?Response.json(await T.getInstance({instanceId:Be(b,"id"),workflowName:Be(b,"name")})):ut()},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 b=r(l);if(!b)return ut();const T=await c.json().catch(()=>{});if(typeof T?.name!="string"||T.name===""||typeof T.id!="string"||T.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:D}=T;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await b.setInstanceStatus({action:D,instanceId:T.id,workflowName:T.name}))};return{[wo]:s,[fo]:n,[mo]:d}},Oo=new TextEncoder,ct="/_lunora/rpc",Eo="/_lunora/rpc-batch",To="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:zn(e,t),...r===void 0?{}:{waitUntil:r}}),lt=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},ht=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}},pt="/_lunora/voice/",_o="/_lunora/scheduler/dispatch",Ro="/_lunora/admin/cron-jobs/run",So="/_lunora/admin/ws-token",Ao="/_lunora/admin/",vo="/_lunora/migrate",Do="/_lunora/status",ko=e=>e.startsWith(Ao)||e===vo,Io=new Set(["1","enabled","on","true","yes"]),Po=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}}},No="/api/auth",Uo="__lunora_admin__:recordAuthEvent",qo="__lunora_admin__:listPushSubscriptions",$o=["/sign-in","/sign-up","/callback"],xo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return $o.some(s=>n===s||n.startsWith(`${s}/`))},Te=(e,t,r,n)=>{const s=nr(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}:{}}},Lo=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},ft=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Bo=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"),b=e.headers.get("x-lunora-client-id"),T=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),b&&(n["x-lunora-client-id"]=b),T&&(n["x-lunora-client-seq"]=T);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const w=await r(e,t);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=w.userId;const g=Lo(w);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...y}=w,_=Object.keys(y).length>0?y:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:w,userId:p}},Co=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),jo=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"||!Co.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},Go=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(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}},Mo=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=jo(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,Ko=5e3,Fo=4096,Qo=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 yt(_e,Fo),_e.set(t,{expiresMs:r+Ko,relayCount:s}),s},zo=(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},Wo=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 T of c)l+=String.fromCodePoint(T);const b=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return Ge(b,r)},mt=(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())},Ho=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 Nr(t,n)?!0:r?!1:Ge(t,n)},Jo=(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 wr(`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)},_t=e=>{const t=uo(e.trustInboundTraceContext),r=co(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=mr(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 b=()=>e.adminToken??l;let T;const D=()=>e.requireEphemeralWsToken??T??!1,w=o=>{const i=o??{};if(T===void 0&&e.requireEphemeralWsToken===void 0){const u=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(T=Io.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)},g=new WeakSet,p=o=>mt(o,b())||g.has(o),y=async(o,i)=>{const h=await ce(o,i,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const u=b();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let _=!1;const R=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})}_||(_=!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("")))},I=xn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:y,shardDO:d}),x=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 O={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(O["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(O["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(O["x-lunora-mutation-id"]=u);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:O,method:"POST"});return ae(d,h,S)},v=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})},B=async(o,i,h)=>v(o,i.args??{},h,`cron job "${i.name}"`),C=async(o,i)=>{if(o.workflow){await B(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 x(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 O of f)try{await C(O,i)}catch(S){h.push(u(S))}},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(O=>O.name===u);if(!f)throw new a(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await C(f,i),Response.json({name:u,ran:!0},{status:200})},K=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{}},F=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,O=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let m=!1;if(S&&f?m=await Wo(f,h,S):O&&(m=mt(o,O)),!m)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let E;try{E=JSON.parse(h)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const A=E??{},U=A.args??{};if(typeof A.workflow=="string"&&A.workflow.length>0)return await v(A.workflow,U,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof A.functionPath!="string"||A.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof A.shardKey=="string"&&A.shardKey.length>0?A.shardKey:n,$=typeof A.id=="string"&&A.id.length>0?A.id:void 0,L=Po(o),W=await x(A.functionPath,U,q,$,L);return await K(A),W},j=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},M=(o,i,h)=>{if(j(o),i===void 0)throw new a(h.message,{code:h.code,status:400});return i},X=Lr({assertAdmin:j,getReader:()=>e.authAuditReader}),J=async(o,i)=>{j(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,O=i?.limit,S=u==="fcm"||u==="web-push"?u:void 0,m=typeof f=="string"&&f!==""?f:void 0,E=typeof O=="number"&&Number.isFinite(O)?Math.trunc(O):0,A=E>0?Math.min(E,1e3):1e3,U=(await h.list({kind:S,limit:A,userId:m})).filter(q=>S!==void 0&&q.kind!==S?!1:m===void 0||(q.userId??null)===m).map(({keys:q,token:$,...L})=>L);return Response.json({subscriptions:U},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===xr)return X(o,i.args??{});if(i.functionPath===qo)return J(o,i.args)}},ie=Zr({applyGlobals:e.applyGlobals,assertAdmin:j,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Ot(),queryCoordinator:e.queryCoordinator,requireAdminOption:M,resolveForwardContext:y,shardDO:d,streamExportRows:(o,i,h,u)=>ot(e,o,i,h,u,d),streamingImport:(o,i)=>an(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),O=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:O!==void 0&&Number.isFinite(O)&&O>=0?O: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=eo({checkWsAdmin:async o=>p(o)||Ho(o,b(),D()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(j(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=bo({assertAdmin:j,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Rt=ao({assertAdmin:j,parsePaging:pe,queryParameter:Z,readBodyBytes:jr,requireAdminOption:M,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),St=po({readJsonBody:te,requireAdminOption:M,vectorIntrospector:e.vectorIntrospector}),At=En({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:M}),vt=yr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:M}),Dt=gn({assertAdmin:j,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:Z,requireAdminOption:M}),kt=o=>{const i=[],h=d??o?.SHARD;if(h!==void 0&&i.push(fr("durable-object:default",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const O=Jo(u,f);O!==void 0&&i.push(O)}for(const u of e.health?.probes??[])i.push(u);return i},It=pr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:kt}),Pt=o=>{const i=e.schedulerInstanceName??"default",h=()=>o.get(o.idFromName(i)),u=async(m,E)=>{const A=await h().fetch(new Request(`https://scheduler.internal${m}`,E));if(!A.ok)throw new a(`ctx.scheduler: SchedulerDO ${m} failed (${String(A.status)}): ${await A.text()}`,{code:"INTERNAL",status:500});return await A.json()},f=async(m,E)=>await u(m,{body:JSON.stringify(E),headers:{"content-type":"application/json"},method:"POST"}),O=m=>{const E=m;if(E==null)throw new a("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof E.binding=="string"&&E.binding.length>0)return{workflow:E.binding};if(typeof E.__lunoraRef=="string")return{functionPath:E.__lunoraRef};throw new a("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},S=async(m,E,A={})=>{const{id:U}=await f("/schedule",{args:A,scheduledFor:m,...O(E)});return U};return{cancel:async m=>await f("/cancel",{id:m}),get:async m=>await u(`/get?id=${encodeURIComponent(m)}`,{method:"GET"}),list:async()=>await u("/list",{method:"GET"}),runAfter:async(m,E,A)=>{if(!Number.isFinite(m)||m<0)throw new a("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await S(Date.now()+m,E,A)},runAt:async(m,E,A)=>{if(!Number.isFinite(m))throw new a("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await S(m,E,A)}}},Nt=async(o,i,h)=>{const{claims:u,headers:f,userId:O}=await ce(o,i,s),S=async(m,E={})=>{const A=m.__lunoraRef;if(typeof A!="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:E,functionPath:A}),headers:{...f,"x-lunora-system":"1"},method:"POST"}),q=await ae(d,n,U),$=await q.json();if($.error)throw new a($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:q.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:O},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S,...c===void 0?{}:{scheduler:Pt(c)},...e.storage===void 0?{}:{storage:Tr(e.storage(i))}}},Ut=async(o,i,h)=>{if(!e.httpRouter)return;const u=await Nt(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})}},qt=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:O,identity:S}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const m=new Headers(o.headers),E=[...m.keys()];for(const L of E)L.startsWith("x-lunora-")&&m.delete(L);const A=O["x-lunora-userid"],U=O["x-lunora-identity"],q=O["x-lunora-identity-exp"];A!==void 0&&m.set("x-lunora-userid",A),U!==void 0&&m.set("x-lunora-identity",U),q!==void 0&&m.set("x-lunora-identity-exp",q);const $=zo(i,e.shardDO);if($!==void 0){m.set("x-lunora-shard-binding",$);const L=await Qo(d,f);if(L>0){const W=Rr(f,Math.floor(Math.random()*L));return ae(d,W,new Request(o,{headers:m}))}}return ae(d,f,new Request(o,{headers:m}))},$t=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 O;try{O=decodeURIComponent(h.pathname.slice(pt.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(u,O)?u[O]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const m=h.searchParams.get("threadKey");if(m===null||m.length===0)return new Response("Missing threadKey",{status:400});const{headers:E,identity:A}=await ce(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(A,m))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=E["x-lunora-userid"],$=E["x-lunora-identity"],L=E["x-lunora-identity-exp"];return q!==void 0&&U.set("x-lunora-userid",q),$!==void 0&&U.set("x-lunora-identity",$),L!==void 0&&U.set("x-lunora-identity-exp",L),ae(S,m,new Request(o,{headers:U}))},xt=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});R("fan-out")},Oe=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await xt(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&&R("shard")}},ve=async(o,i,h,u,f,O)=>{const S=Date.now(),{observability:m,sampling:E}=e,A=Ce(o),{decision:U,ignoredUpstream:q,trace:$}=Fn(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});q&&r();const L={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};Qn($,L);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:i}),headers:L,method:"POST"});try{const G=await ae(d,u,W);return ue(m,{...A,...ht($),durationMs:Date.now()-S,functionPath:i,ok:G.ok,shardKey:u,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},O,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),G}catch(G){throw ue(m,{...A,...ht($),...Te(i,Date.now()-S,G,{shardKey:u})},O,void 0,{isTraced:$.sampled,keepErrors:U.keepErrors}),G}},Lt=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})},Bt=async(o,i,h)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await Mo(o);Go(i,u),Lt(u);const f=await oe(o,u);if(f!==void 0)return f;const{headers:O,identity:S}=await ce(o,i,s);await Oe(u,S);const m=wt(u,e);{const E=Date.now(),{observability:A}=e,U=Ce(o),q=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 G=await W.fanOut(d,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:O});return ue(A,{durationMs:Date.now()-E,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},q),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ue(A,{...Te(u.functionPath,Date.now()-E,G,{fanOut:{table:u.fanOut.table}}),...U},q),G}}const $=u.shardKey??n,L=()=>ve(o,u.functionPath,u.args??{},$,O,q);return m&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:m.price},L,lt(h)):L()}},Ct=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:O}=f;if(!Array.isArray(O))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:m}=await ce(o,i,s),E=Cr(O,n);for(const Q of E.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...E.entries()].flatMap(([Q,z])=>z.map(ne=>Oe({functionPath:ne.functionPath,shardKey:Q},m))));const{observability:A}=e,U=Ee(i,o,h&&(Q=>h.waitUntil?.(Q))),q=Ce(o),$=[],L=[],W=(Q,z,ne,le)=>({body:{error:{code:ne,message:le}},id:Q.id,status:z}),G=(Q,z,ne,le,fe)=>{for(const H of Q)ue(A,fe(H),U),$.push(W(H,z,ne,le))},Zt=(Q,z,ne,le,fe)=>{for(const H of Q){const we=le.get(H.id)??fe,ye=we<400;ue(A,{durationMs:ne,functionPath:H.functionPath,...q,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},U)}};await Promise.all([...E.entries()].map(async([Q,z])=>{const ne=new Headers(S);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,Q,le)}catch(V){const Pe=Date.now()-fe,{body:ze}=or(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});G(z,502,ze.code,ze.message,rr=>({...Te(rr.functionPath,Pe,V,{shardKey:Q}),...q}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&L.push(ye);let ke;try{ke=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;G(z,H.status,"SHARD_ERROR",V,Pe=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Pe.functionPath,...q,ok:!1,shardKey:Q}));return}const Ie=Array.isArray(ke.results)?ke.results:[],er=new Map(Ie.map(V=>[V.id,V.status??H.status])),tr=new Set(Ie.map(V=>V.id));Zt(z,Q,we,er,H.status),$.push(...Ie);for(const V of z)tr.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Fe={"content-type":"application/json"},[Qe]=L;return L.length===1&&Qe!==void 0&&(Fe["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Fe,status:200})},jt=async(o,i,h,u={},f={})=>{try{const O=h.__lunoraRef;if(typeof O!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:m}=await ce(o,i,s);await Oe({functionPath:O,shardKey:f.shardKey},m);const E=f.shardKey??n,A=Ee(i,o,f.waitUntil);return await ve(o,O,u,E,S,A)}catch(O){return We(O)}},Gt=1e3,Mt=async(o,i)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let S=0;S<Gt;S+=1){const m=await o.list({cursor:f,prefix:i});for(const E of m.objects)E.key.endsWith(".manifest.json")&&u.push(E.key);if(!m.truncated||m.cursor===void 0)break;f=m.cursor}const O=u.toSorted((S,m)=>m.localeCompare(S)).slice(h);await Promise.all(O.flatMap(S=>{const m=S.slice(0,-14);return[o.delete(S),o.delete(m)]}))},Kt=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=b();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"},O=e.backupTables;let S=0,m=0;const E=[];await ot(e,h,f,O,W=>{const G=`${JSON.stringify(W)}
5
- `;S+=1,m+=Oo.encode(G).byteLength,E.push(G)},d);const A=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),q=`${A}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${q}.manifest.json`;await i.put(q,new Blob(E,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const L={bytes:m,createdAt:U,cron:o.cron,file:q,id:U,rows:S,scheduledTime:o.scheduledTime,...O?{tables:O.join(",")}:{}};await i.put($,`${JSON.stringify(L,void 0,2)}
6
- `,{httpMetadata:{contentType:"application/json"}}),await Mt(i,A)},Me=async(o,i,h)=>{const{observability:u}=e,f=Date.now(),O=Re(16),S=Re(8),m=ft(i);try{const E=await h();return ue(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:O},m),E}catch(E){throw ue(u,{...Te(o,Date.now()-f,E,{}),spanId:S,traceId:O},m),E}finally{He(u,m)}},Ft=async(o,i,h)=>{w(i);const u=[],f=m=>m instanceof Error?m:new Error(String(m)),O=e.crons?.[o.cron];if(O)try{await O(o,i,h)}catch(m){u.push(f(m))}if(await Y(o.cron,i,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Kt(o)}catch(m){u.push(f(m))}const[S]=u;if(u.length===1&&S)throw S;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Qt=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:Uo}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await ae(d,n,f)}catch{}},zt=async(o,i,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const O=e.authBasePath??No;return xo(h.pathname,O)&&u.waitUntil?.(Qt(i,f.status>=400?"fail":"ok")),f},Wt=async({args:o,env:i,functionPath:h,request:u,shardKey:f,waitUntil:O})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:m,identity:E}=await ce(u,i,s);await Oe(S,E);const A=f??n,U=Ee(i,u,O),q=()=>ve(u,h,o,A,m,U),$=wt(S,e);return $&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:$.price},q,lt({waitUntil:O})):q()},Ht=br({functions:e.functions??{},invoke:Wt,readJsonBody:te,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Jt={[Do]: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"}}),[To]:(o,i,h)=>qt(o,i,h),[ct]:(o,i,h,u)=>Bt(o,i,u),[Eo]:(o,i,h,u)=>Ct(o,i,u),[_o]:(o,i)=>F(o,i),[Ro]:(o,i)=>N(o,i),[So]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});j(o);const i=b();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 Pr(i);return Response.json(h,{headers:{"cache-control":"no-store"}})},...I,...ie,...Ae,...re,...Rt,...St,...At,...vt,...Dt,...It,...Ht,...$r({assertAdmin:j,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:Z,readJsonBody:te})};let de=Ve(e.security),Ke=!1;const Vt=o=>{Ke||(Ke=!0,de=Ve(e.security,o??{}))},Yt=async(o,i)=>{if(!(e.adminGate===void 0||!ko(i)))try{await e.adminGate(o)&&g.add(o)}catch{}},Xt=async(o,i,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const m=Number(o.headers.get("content-length")??""),E=u.pathname===Et?Tt:ge;if(Number.isFinite(m)&&m>E)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await zt(o,i,u,h);if(f)return f;if(De){const m=`${o.method} ${u.pathname}`,E=De[m]??De[u.pathname];if(E)return E(o,i,h)}const O=Jt[u.pathname];return O?(await Yt(o,u.pathname),O(o,i,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(pt)?$t(o,i,u):await Ut(o,i,h)||new Response("Not found",{status:404})};return{async fetch(o,i,h){e.passThroughOnException&&h.passThroughOnException?.(),Vt(i),w(i);const u=Or(o,de);if(u)return u;const f=Er(o,de);if(f)return Ue(f,o,de);try{const O=await Xt(o,i,h);return Ue(O,o,de)}catch(O){return Ue(We(O),o,de)}finally{He(e.observability,ft(h))}},async queue(o,i,h){await Me(`queue:${Bo(o)}`,h,async()=>{await e.queue?.(o,i,h)})},async scheduled(o,i,h){await Me(`cron:${o.cron}`,h,async()=>{await Ft(o,i,h)})},serverQuery:jt}},Vo=e=>_t(e),Yo=e=>typeof e=="function"?{fetch:e}:e,Xo=e=>!!(e.crons??e.cronJobs??e.backupCron),pa=(e,t)=>{const r=Yo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const l=Vo({...c,httpRouter:r});return n!==void 0&&!Xo(c)?{...l,scheduled:async(b,T,D)=>{await n(b,T,D)}}:l};if(typeof t!="function")return s(t);const d=t;return{fetch:(c,l,b)=>s(d(l)).fetch(c,l,b),queue:(c,l,b)=>s(d(l)).queue?.(c,l,b)??Promise.resolve(),scheduled:(c,l,b)=>s(d(l)).scheduled(c,l,b),serverQuery:(c,l,b,T,D)=>s(d(l)).serverQuery(c,l,b,T,D)}},Zo=(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}},fa=(e={})=>(t,r,n)=>_t(Zo(e,r)).fetch(t,r,n??ar),wa=e=>e;export{xr as GET_AUTH_AUDIT_LOG_OP,ar as NOOP_EXECUTION_CONTEXT,ga as composeIdentityResolvers,Vo as composeWorker,fa as createLunoraHandler,_t as createWorker,wa as defineRpcEnvelope,Qo as probeRelayCount,Zo as resolveLunoraOptions,ba as routeIdentityResolvers,pa as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{LunoraError as o}from"./LunoraError-ByasbDmd.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 +0,0 @@
1
- import{LunoraError as M}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as C}from"./applyJurisdiction-8bzZjAPR.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 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{applyJurisdiction as O,resolveShard as $}from"./applyJurisdiction-8bzZjAPR.mjs";const m=e=>{let r="";for(let i=0;i<e.length;i+=32768)r+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(r)},j=e=>{const r=atob(e),i=new Uint8Array(r.length);for(let c=0;c<r.length;c+=1)i[c]=r.codePointAt(c)??0;return i},s="$lunora.wire$",g=64,A=1024,v="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},d=(e,r=0)=>{if(r>g)throw new RangeError(`wire-codec: value nesting exceeds the ${g}-level limit`);if(e===void 0)return[s,"undefined"];if(e===null)return null;const i=typeof e;if(i==="bigint")return[s,"bigint",e.toString()];if(i==="number"){const n=e;return Number.isNaN(n)?[s,"nan"]:n===1/0?[s,"inf"]:n===-1/0?[s,"-inf"]:n}if(i!=="object")return e;if(e instanceof Date)return[s,"date",d(e.getTime(),r+1)];if(e instanceof Error){const n=e,a={};for(const f of Object.keys(n))n[f]!==void 0&&(a[f]=d(n[f],r+1));const u=[s,"error",n.name,n.message,a];return n.cause!==void 0&&u.push(d(n.cause,r+1)),u}if(e instanceof URL)return[s,"url",e.href];if(e instanceof Map)return[s,"map",[...e.entries()].map(([n,a])=>[d(n,r+1),d(a,r+1)])];if(e instanceof Set)return[s,"set",[...e].map(n=>d(n,r+1))];if(e instanceof ArrayBuffer)return[s,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const n=e,a=n.constructor.name,u=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[s,"bytes",m(u)]:[s,"bytes",m(u),a]}if(Array.isArray(e)){const n=e.map(a=>d(a,r+1));return n.length>0&&n[0]===s?[s,"arr",n]:n}const c=Object.getPrototypeOf(e);if(c!==null&&c!==Object.prototype){const n=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const t=e,o={};for(const n of Object.keys(t)){const a=t[n];a!==void 0&&(o[n]=d(a,r+1))}return o},l=(e,r=0)=>{if(r>g)throw new RangeError(`wire-codec: value nesting exceeds the ${g}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===s)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(t=>l(t,r+1));case"bigint":{const t=e[2];if(typeof t!="string"||t.length>A||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(t)}case"date":return new Date(l(e[2],r+1));case"map":return new Map(e[2].map(([t,o])=>[l(t,r+1),l(o,r+1)]));case"set":return new Set(e[2].map(t=>l(t,r+1)));case"url":return new URL(e[2]);case"error":{const t=e[2],o=e[3],n=(Object.hasOwn(E,t)?E[t]:void 0)??Error,a=new n(o);a.name!==t&&Object.defineProperty(a,"name",{configurable:!0,value:t,writable:!0});const u=l(e[4],r+1);for(const f of Object.keys(u))f===v?Object.defineProperty(a,f,{configurable:!0,enumerable:!0,value:u[f],writable:!0}):a[f]=u[f];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:l(e[5],r+1),writable:!0}),a}case"bytes":{const t=j(e[2]),o=e[3]??"Uint8Array";if(o==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(S,o)?S[o]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(t=>l(t,r+1))}return e.map(t=>l(t,r+1))}const i=e,c={};for(const t of Object.keys(i)){const o=l(i[t],r+1);t===v?Object.defineProperty(c,t,{configurable:!0,enumerable:!0,value:o,writable:!0}):c[t]=o}return c},N=e=>{if(typeof e=="string")return e;const r=e?.__lunoraRef;if(typeof r!="string"||r.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return r},R=e=>{const r=new b(e.code,e.message);return e.data!==void 0&&(r.data=l(e.data)),r},x=(e,r={})=>{const i=O(e,r.jurisdiction),c=r.system??!0,t=o=>x(e,{...r,...o});return{as:o=>t({as:o}),asSystem:()=>t({as:void 0}),call:async(o,n,a)=>{const u=N(o),f=a?.shardKey??r.shardKey;if(f===void 0||f.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${u}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const h={"content-type":"application/json"};c&&(h["x-lunora-system"]="1"),r.as&&(h["x-lunora-userid"]=r.as.userId,r.as.claims&&(h["x-lunora-identity"]=JSON.stringify(r.as.claims))),a?.mutationId!==void 0&&a.mutationId.length>0&&(h["x-lunora-mutation-id"]=a.mutationId);const y=await $(i,f).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d(n??{}),functionPath:u}),headers:h,method:"POST"}));let p;try{p=await y.json()}catch{const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard response for "${u}" was not JSON (status ${String(y.status)}${w})`)}if("error"in p)throw R(p.error);if(!y.ok){const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard call "${u}" failed (status ${String(y.status)}${w})`)}return l(p.result)},forShard:o=>t({shardKey:o})}};export{x as createShardClient};