@lunora/runtime 1.0.0-alpha.115 → 1.0.0-alpha.117
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{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-CH0LLQzr.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-B1hLjwgx.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-JUcPmzoo.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-DlWITOu1.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpbO5QEx.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-I984JFkv.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as Qn,toErrorBody as Wn}from"@lunora/errors";import{e as Kt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as zn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as Vn,f as qn}from"./base64-Bl1_r2k1.mjs";import{e as Jn,a as Yn}from"./identity-header-C4Z5pldl.mjs";import{O as ut,a as lt}from"./origin-paywall-B6eOO67m.mjs";import{o as Ie,b as Ft,p as Xn,m as Zn,d as er,a as tr,r as nr}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as rr}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as ae,M as Gt,b as or,f as ar,g as Qt,t as sr,h as Wt}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as c,toErrorResponse as ht}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,isBackupManifestKey as ir,backupObjectKeyOfManifest as zt,backupObjectKey as cr,backupManifestKey as dr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as ur,buildStorageAdminRoutes as lr,STORAGE_UPLOAD_MAX_BODY_BYTES as hr,STORAGE_PATH as fr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as pr,e as mr,f as ft,g as wr,h as gr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as yr,durableObjectProbe as br,d1Probe as _r,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Er}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ys,routeIdentityResolvers as Xs}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Rr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as Sr,f as pt,a as ce}from"./observability-B1hLjwgx.mjs";import{resolveShard as we,applyJurisdiction as mt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as wt,handleCorsPreflight as Ar,enforceOrigin as Tr,decorateResponse as Me,enforceWebSocketOrigin as gt}from"./decorateResponse-Y2sCM0w1.mjs";const Or=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Vt="__lunoraBranch",vr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Vt),kr=`may not contain the reserved workflow branch-marker key ("${Vt}")`,Ir=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},et=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let a=0;a<n;a+=1){const i=a<e.length?e.charCodeAt(a):0,u=a<t.length?t.charCodeAt(a):0;r|=i^u}return r===0},Pr=/already[\s_-]?exists/iu,Dr=e=>Pr.test(e instanceof Error?e.message:String(e)),Nr=(e,t,n,r)=>{const a=e.get(t);if(a!==void 0)return a;Kt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},tt=new TextEncoder,Ur=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ur.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Cr=64,Br=new Map,qt=async e=>Nr(Br,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Cr),Jt=async(e,t)=>{const n=await qt(e),r=await crypto.subtle.sign("HMAC",n,tt.encode(t));return Vn(new Uint8Array(r))},xr=async(e,t,n)=>{const r=await qt(e);return crypto.subtle.verify("HMAC",r,n,tt.encode(t))},Hr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Hr);const Lr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Mr=-100,jr=15,$r=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Lr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>jr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Mr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},yt=e=>{const t=e.cf;return t===void 0?void 0:$r(t)},qe="::relay::",Kr=(e,t)=>`${e}${qe}${String(t)}`,Je="::replica::",Fr=(e,t)=>`${e}${Je}${t}`,Gr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Qr=new Set(["1","enabled","on","true","yes"]),Wr=new Set(["0","disabled","false","no","off"]),zr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Qr.has(n)?!0:Wr.has(n)?!1:t},Yt="v1",Vr=6e4,qr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Vr),r=`${Yt}.${String(n)}`,a=await Jt(e,r);return{expiresAtMs:n,token:`${r}.${a}`}},Jr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[a,i,u]=r;if(a!==Yt||u.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let p;try{p=qn(u)}catch{return!1}return xr(e,`${a}.${i}`,p)},I="/_lunora/admin/auth",Yr={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},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Xt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},bt=e=>{const t=Xt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},_t=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,a]of Object.entries(t))Array.isArray(a)&&a.every(i=>typeof i=="string")&&(n[r]=a);return n},Xr={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${I}/sign-up-invitations/create`]:{build:({body:e})=>({email:N(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${I}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:N(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Xt(e.role)}),http:"POST",method:"createUser"},[`${I}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${I}/users/role`]:{build:({body:e})=>({role:bt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:bt(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:_t(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:_t(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Zr=e=>{const t=async a=>{try{return await a()}catch(i){if(i instanceof c)throw i;const u=i,f=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Yr[f]??500})}},n=async(a,i)=>{if(e.assertAdmin(a),a.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=u[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(a.url),h={body:i.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(p,T)},y=i.build(h),S=await t(()=>f(y));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[a,i]of Object.entries(Xr))r[a]=u=>n(u,i);return r},Et="__lunora_admin__:getAuthAuditLog",Rt=e=>typeof e=="string"&&e!==""?e:void 0,St=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,eo=e=>async(n,r)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Rt(r.actorId),u=Rt(r.event),f=St(r.sinceSeq),p=St(r.limit),h={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...f===void 0?{}:{sinceSeq:f},...p===void 0?{}:{limit:p}};let y;try{y=await a.read(h)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:y};return Response.json({result:ke(S)},{headers:{"content-type":"application/json"},status:200})},to=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):n.push(a);return{globalTables:r,shardLocalTables:n}},no=async(e,t,n,r,a,i,u)=>{if(n!==void 0&&r.length===0)return;const f=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r});for(const p of f.shards)if(!p.error)for(const h of p.rows??[])a(h)},Zt=async(e,t,n,r,a,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:f,shardLocalTables:p}=to(e,u);await no(t,n,u,p,a,i,e.defaultShardKey??"__root__");const h=e.exportGlobals;if((r===void 0||f.length>0)&&h)for await(const S of h({tables:f}))a(S)},ro=new TextEncoder,oo=1e3,en=10,ao=200,At=8,tn="lunoraBackupCron",Tt=24*1048576,Ot=e=>{const t=e.slice(0,en).map(r=>zt(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},so=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const a of e)n.set(a,r),r+=a.byteLength;return n},nt=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let i;for(let u=0;u<oo;u+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of f.objects)ir(p.key)&&p.customMetadata?.[tn]===r&&a.push(p.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:a.length,stale:a.toSorted((u,f)=>f.localeCompare(u)).slice(n)}},io=async(e,t,n,r,a)=>{const{stale:i}=await nt(e,t,n,r),u=new Set(a),f=i.filter(m=>u.has(m)),p=f.slice(0,ao),h=i.length-p.length,y=a.length-f.length;if(p.length===0)return{deleted:[],failed:[],ignored:y,remaining:h};const S=[],T=[];for(let m=0;m<p.length;m+=At){const E=await Promise.allSettled(p.slice(m,m+At).map(async R=>(await e.delete(zt(R)),await e.delete(R),R)));for(const[R,g]of E.entries())g.status==="fulfilled"?S.push(g.value):T.push(p[m+R])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ot(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ot(T)}`),{deleted:S,failed:T,ignored:y,remaining:h}},co=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Xe(e.backupPrefix??Ze),r=e.backupCron,{eligible:a,stale:i}=r===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},uo=async(e,t,n,r)=>{const a=e.backupStore,i=e.queryCoordinator;if(!a)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},f=e.backupTables;let p=0,h=0,y=[];await Zt(e,i,u,f,U=>{const H=ro.encode(`${JSON.stringify(U)}
|
|
2
|
+
`);if(p+=1,h+=H.byteLength,h>Tt)throw new c(`scheduled backup reached ${String(h)} bytes of NDJSON, past the ${String(Tt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});y.push(H)},t);const T=Xe(e.backupPrefix??Ze),m=new Date(r.scheduledTime).toISOString(),E=cr(T,m),R=so(y,h);y=[];const g=ur(await crypto.subtle.digest("SHA-256",R));await a.put(E,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:h,createdAt:m,cron:r.cron,file:E,id:m,rows:p,scheduledTime:r.scheduledTime,sha256:g,...f?{tables:f.join(",")}:{}};await a.put(dr(E),`${JSON.stringify(O,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[tn]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,r.cron);if(U.length>0){const H=U.slice(0,en),P=U.length-H.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${H.join(", ")}${P>0?` (+${String(P)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${E} was written, but the retention report failed:`,U)}},lo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return io(n,Xe(e.backupPrefix??Ze),a,r,t)},ho="/_lunora/admin/backup/retention",fo="/_lunora/admin/backup/prune",po=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,a=(f,p)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async f=>($(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await co(t),{headers:{"cache-control":"no-store"}})),u=async f=>{$(f,"POST","Backup-prune"),a(f,"prune");const{confirm:p}=await n(f);if(!Array.isArray(p)||p.some(h=>typeof h!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await lo(t,p),{headers:{"cache-control":"no-store"}})};return{[fo]:u,[ho]:i}},vt=500,mo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},wo=(e,t)=>{if(e.length>vt)throw new c(`RPC batch exceeds the ${String(vt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[a,i]of e.entries()){const{entry:u,shardKey:f}=mo(i,a,t);if(r.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(u.id);const p=n.get(f)??[];p.push(u),n.set(f,p)}return n},go="/_lunora/admin/export",yo="/_lunora/admin/import",bo="/_lunora/admin/sync",_o="/_lunora/admin/connector/sync",Eo="/_lunora/admin/apply",Ro="/_lunora/admin/export-tap/run",So=new TextEncoder,Ao=async e=>{const n=await ae(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,To=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:a,knownTables:i,queryCoordinator:u,assertAdmin:f,requireAdminOption:p,resolveForwardContext:h,shardDO:y,streamExportRows:S,streamingImport:T,syncGlobals:m}=e,E=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;const Z=p(P,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await Ao(P),{headers:G}=await h(P,K),q=new ReadableStream({async pull(J){const ee=Q=>{J.enqueue(So.encode(`${JSON.stringify(Q)}
|
|
4
|
+
`))};try{await S(Z,G,C.tables,ee),J.close()}catch(Q){J.error(Q)}}});return new Response(q,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;const Z=p(P,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(P),G=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,ee=$e(C.tables),{headers:Q}=await h(P,K),F=ee??i(),j=await Z.orchestrateCdcSync(y,{cursors:G,defaultShardKey:n,headers:Q,limit:q,tables:F}),he=m?await m({limit:q,sinceSeq:J}):void 0;return Response.json({global:he,shards:j.shards},{status:200})},g=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;const Z=p(P,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(P),G=mr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables),{headers:ee}=await h(P,K),Q=J??i(),F=await Z.orchestrateCdcSync(y,{cursors:G.s,defaultShardKey:n,headers:ee,limit:q,tables:Q}),j=[],he={...G.s};let de=!1;for(const se of F.shards)de=ft(j,se.changes??[],gr(q))||de,he[se.shardKey]=se.cursor;let ge=G.g;if(m){const se=await m({limit:q,sinceSeq:G.g});de=ft(j,se.changes,q)||de,ge=se.cursor}const De=wr({g:ge,s:he,v:1}),Ne={changes:j,hasMore:de,nextCursor:De};return Response.json(Ne,{status:200})},O=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;const Z=p(P,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(P),q=(Array.isArray(C.batches)?C.batches:[]).map(j=>j).filter(j=>j!==null&&typeof j=="object"&&typeof j.shardKey=="string"&&Array.isArray(j.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await h(P,K),Q=await Z.orchestrateApplyCdc(y,{batches:q,headers:ee}),F=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:Q.applied+F,failed:Q.failed,ok:Q.ok},{status:200})},U=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;f(P);const{headers:Z}=await h(P,K),C=await T(P,Z);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},H=async(P,K)=>{const M=me(P,["POST"]);if(M)return M;const Z=p(P,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(P),G=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables);if(G===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[G];if(ee===void 0)throw new c(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Q}=await h(P,K),F=J??i(),j=await pr({coordinator:Z,cursorStore:r,defaultShardKey:n,headers:Q,limit:q,shardDO:y,sink:ee,tables:F});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[Eo]:O,[_o]:g,[go]:E,[Ro]:H,[yo]:U,[bo]:R}},Oo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},vo=(e,t,n,r,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},ko=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],i=new Map;let u=0,f=0;const p=e.body.getReader(),h=new TextDecoder;let y="",S=0;const T=m=>{f+=1;const E=m.trim();if(E.length===0)return;u+=1;const R=Oo(E,f);if(!R.ok){r.push(R.error);return}const{doc:g,table:O}=R,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:g,line:f,table:O});return}const H=vo(g,O,U,n,f);if(!H.ok){r.push(H.error);return}const P=i.get(H.shardKey);P?P.rows.push({doc:g,table:O}):i.set(H.shardKey,{rows:[{doc:g,table:O}],shardKey:H.shardKey,startLine:f})};for(;;){const{done:m,value:E}=await p.read();if(m)break;if(E&&(S+=E.byteLength,S>Gt))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});y+=h.decode(E,{stream:!0});let R=y.indexOf(`
|
|
5
|
+
`);for(;R!==-1;){const g=y.slice(0,R);y=y.slice(R+1),T(g),R=y.indexOf(`
|
|
6
|
+
`)}}return y.length>0&&T(y),{errors:r,globalRows:a,perShard:i,received:u}},Io=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),kt=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Po=async(e,t,n,r)=>{const a=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:f,received:p}=await ko(e,t,a),h={conflicts:0,errors:i,failed:[],inserted:{}},y=[];if(t.resolveTableSharding===void 0&&f.size>0&&y.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"),f.size>0){const S=t.queryCoordinator;if(!S)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(r,{batches:[...f.values()],headers:n});kt(h,T),h.failed.push(...Io(T.shards))}if(u.length>0)if(t.importGlobals){const S=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:S});kt(h,T)}else for(const S of u)h.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:h.conflicts,errors:h.errors,failed:h.failed,inserted:h.inserted,received:p,...y.length>0?{warnings:y}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Do=(e,t)=>{let n=Ke(t),r=!1;Fe(n)==="optional"&&(r=!0,n=Ke(n._meta?.inner));const a=Fe(n),i=n._meta??{},u={kind:a,name:e,optional:r};if(a==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),a==="array"){const f=Fe(Ke(i.inner));f!=="unknown"&&(u.element=f)}return u},No=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Do(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Uo="/_lunora/admin/functions",Co="/_lunora/admin/cron-jobs",Bo="/_lunora/admin/openapi",xo="/_lunora/admin/openrpc",Ho="/_lunora/admin/global/tables",Lo="/_lunora/admin/global/table",Mo="/_lunora/admin/global/facet",It=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:a,value:i}=r;return[{column:a,value:i}]});return n.length===0?void 0:n},jo=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:{}}),$o=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"}),Ko=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:a,requireAdminOption:i}=e,u=m=>{$(m,"GET","Functions");const E=i(m,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(E).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:No(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},f=m=>{$(m,"GET","Cron-jobs");const E=i(m,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(E).flatMap(([g,O])=>O.map(U=>({args:U.args,cron:g,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=m=>($(m,"GET","OpenAPI"),t(m),Response.json(n.openApiSpec??jo,{headers:{"content-type":"application/json"},status:200})),h=m=>($(m,"GET","OpenRPC"),t(m),Response.json(n.openRpcSpec??$o,{headers:{"content-type":"application/json"},status:200})),y=async m=>{$(m,"GET","Global-tables");const E=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await E.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async m=>{$(m,"GET","Global-table");const E=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(m.url),g=a(R,"table");if(g===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await E.readTablePage({...r(m),filters:It(a(R,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async m=>{$(m,"GET","Global-facet");const E=i(m,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(m.url),g=a(R,"table"),O=a(R,"column");if(g===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),H=U===void 0?void 0:Number(U),P=await E.facetColumn({column:O,filters:It(a(R,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:g});return Response.json(P,{headers:{"content-type":"application/json"},status:200})};return{[Co]:f,[Uo]:u,[Mo]:T,[Lo]:S,[Ho]:y,[Bo]:p,[xo]:h}},Fo="/_lunora/admin/kv/namespaces",Go="/_lunora/admin/kv/keys",nn="/_lunora/admin/kv/value",rn=32*1048576,Pt=60,Qo=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=E=>n(E,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=E=>Response.json(E,{headers:{"content-type":"application/json"},status:200}),i=(E,R)=>{const g=new URL(E.url),O=g.searchParams.get("namespace")??"",U=g.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},u=async(E,R)=>{if(!(await E.listNamespaces()).some(O=>O.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},f=async E=>($(E,"GET","KV-namespaces"),a({namespaces:await r(E).listNamespaces()})),p=async E=>{$(E,"GET","KV-keys");const R=r(E),g=new URL(E.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=g.searchParams.get("prefix")??void 0,H=g.searchParams.get("cursor")??void 0,P=g.searchParams.get("limit"),K=P===null?void 0:Number.parseInt(P,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const M=K===void 0?void 0:Math.min(K,1e3);return await u(R,O),a(await R.listKeys({cursor:H,limit:M,namespace:O,prefix:U}))},T={DELETE:async E=>{const R=r(E),g=i(E,"DELETE");return await u(R,g.namespace),await R.deleteKey(g),a({deleted:!0})},GET:async E=>{const R=r(E),g=i(E,"GET");return await u(R,g.namespace),a(await R.getValue(g))},PUT:async E=>{const R=r(E),g=await t(E,rn);if(typeof g.namespace!="string"||g.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<Pt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Pt;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,g.namespace),await R.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),a({ok:!0})}},m=E=>{const R=T[E.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(E)};return{[Fo]:f,[Go]:p,[nn]:m}},Wo="/_lunora/migrate",zo="/_lunora/admin/pitr",Vo="/_lunora/admin/rank",qo="/_lunora/admin/rankpage",Jo="/_lunora/admin/shard-traffic",Yo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Xo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Zo=async e=>{const n=await ae(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Yo.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},ea=async e=>{const n=await ae(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},ta=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new c('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},na=e=>{if(typeof e.table!="string"||e.table.length===0)throw new c("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new c("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new c("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 c("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 c("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},ra=async e=>{const n=await ae(e,"Rank page")??{};na(n);const r=ta(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},oa=async e=>{const n=await ae(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},aa=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Xo.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},sa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:a,resolveForwardContext:i,shardDO:u}=e,f=(m,E)=>{if(m.method!=="POST")throw new c(`${E} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(m))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new c(`${E} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},p=async(m,E)=>{const R=f(m,"Migration"),g=await Zo(m),{headers:O}=await i(m,E),U=await R.orchestrateMigration(u,{args:g.args,defaultShardKey:t,functionPath:g.functionPath,headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},h=async(m,E)=>{const R=f(m,"Rank"),g=await ea(m),{headers:O}=await i(m,E),U=await R.orchestrateRank(u,{headers:O,index:g.index,partitionKey:g.partitionKey,rowId:g.rowId,sortValues:g.sortValues,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},y=async(m,E)=>{const R=f(m,"Rank page"),g=await ra(m),{headers:O}=await i(m,E),U=await R.orchestrateRankPage(u,{...g,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(m,E)=>{const R=f(m,"Shard-traffic"),g=await oa(m),{headers:O}=await i(m,E),U=await R.orchestrateShardTraffic(u,{headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(m,E)=>{if($(m,"POST","PITR"),!r(m))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await aa(m),{headers:g}=await i(m,E),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:g,method:"POST"});return n(u,R.shardKey??t,O)};return{[Wo]:p,[zo]:T,[Vo]:h,[qo]:y,[Jo]:S}},ia=1,ca=0,da=32,ua=512,la=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ha=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ua)return;const n=t.split(",");if(!(n.length>da)){for(const r of n)if(!la.test(r.trim()))return;return t}},fa=e=>{const t=Xn(e.headers.get("traceparent"));if(t===void 0)return;const n=ha(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},pa=(e,t={})=>{const n=fa(e),r=t.trustInbound===!0?n:void 0,a=Ie(8),i=r?.traceId??Ie(16),u=Sr(t.sampling,r===void 0?a:i),f=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:f,spanId:a,traceFlags:f?ia:ca,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},ma=(e,t)=>{t.traceparent=Ft(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},wa=(e,t)=>{let n;return()=>{if(n===void 0){const r=nr(e),a=t===void 0?void 0:t.cf;n=Zn(tr(r),er(r,a))}return n}},ga="/_lunora/admin/scheduled",ya="/_lunora/admin/scheduled/status",ba="/_lunora/admin/scheduled/ws",_a="/_lunora/admin/scheduled/cancel",Ea="/_lunora/admin/scheduled/dead",Ra="/_lunora/admin/scheduled/dead/retry",Sa="/_lunora/admin/scheduled/dead/cancel",Aa="/_lunora/admin/scheduled/pool/release",Ta=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:a}=e,i=(h,y)=>S=>{if(S.method!=="GET")throw new c(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),m=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${h}${m}`,{method:"GET"}))},u=(h,y,S=y)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const m=r(T),E=await ae(T,y);if(typeof E?.id!="string"||E.id==="")throw new c(`${y} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return m.fetch(new Request(`https://scheduler.internal${h}`,{body:JSON.stringify({id:E.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async h=>{if(h.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const y=r(h),S=await ae(h,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return y.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async h=>{if(h.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(h))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=n();return we(y,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[_a]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Sa]:u("/dead/cancel","Scheduled dead-letter action"),[Ea]:i("/dead","Scheduled dead-letter"),[Ra]:u("/dead/retry","Scheduled dead-letter action"),[ga]:i("/list","Scheduled-list"),[Aa]:f,[ya]:i("/status","Scheduler-status"),[ba]:p}},Oa="/_lunora/scheduled",on="/_lunora/queue",an=16*1048576,va=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,a=async(u,f,p)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(u,"Scheduled tick"),y=typeof h?.cron=="string"?h.cron:"";if(y==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:y,noRetry:()=>{},scheduledTime:Date.now()},f,p),Response.json({cron:y,ok:!0})},i=async(u,f,p)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const h=await ae(u,"Queue dispatch",an);if(!Array.isArray(h?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const y=typeof h.queue=="string"?h.queue:"",S=h.messages.filter(m=>typeof m=="object"&&m!==null&&typeof m.id=="string").map(m=>({body:m.body,id:m.id})),T=await r({messages:S,queue:y},f,p);return Response.json({retry:T?.retry??[]})};return{[on]:i,[Oa]:a}},ka=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},Dt={mtls:e=>ka(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ia=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Dt,e)?Dt[e]:void 0)??(()=>!1),Pa=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.'))}},Da="/_lunora/admin/vector/indexes",Na="/_lunora/admin/vector/query",Ua=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{$(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async i=>{$(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const h=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(h,{headers:{"content-type":"application/json"},status:200})};return{[Da]:r,[Na]:a}},Ca="/_lunora/admin/workflows/instances",Ba="/_lunora/admin/workflows/instance",xa="/_lunora/admin/workflows/status",Ha={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},La=e=>e!==null&&Object.hasOwn(Ha,e)?e:void 0,Nt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ut=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ma=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,f,p)=>{$(u,"GET","Workflows instances"),t(u);const h=n(f);if(!h)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const y=Ge(p,"name"),S=La(p.searchParams.get("status"));return Response.json(await h.listInstances({page:Nt(p,"page"),perPage:Nt(p,"perPage"),status:S,workflowName:y}))},a=async(u,f,p)=>{$(u,"GET","Workflows instance"),t(u);const h=n(f);return h?Response.json(await h.getInstance({instanceId:Ge(p,"id"),workflowName:Ge(p,"name")})):Ut()},i=async(u,f)=>{$(u,"POST","Workflows status"),t(u);const p=n(f);if(!p)return Ut();const h=await ae(u,"Workflows status");if(typeof h?.name!="string"||h.name===""||typeof h.id!="string"||h.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:y}=h;if(y!=="pause"&&y!=="resume"&&y!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:y,instanceId:h.id,workflowName:h.name}))};return{[Ba]:a,[Ca]:r,[xa]:i}},ja={[nn]:rn,[on]:an,[fr]:hr},Ct="/_lunora/rpc",$a="/_lunora/rpc-batch",Ka="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:wa(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Bt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),We=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(a)?void 0:a,scheme:r.protocol.replace(":",""),userAgent:n}},xt="/_lunora/voice/",Fa="/_lunora/scheduler/dispatch",Ga="/_lunora/admin/cron-jobs/run",Qa="/_lunora/admin/ws-token",Wa="/_lunora/admin/",Pe="/_lunora/",za="/_lunora/migrate",Va="/_lunora/status",qa=e=>e.startsWith(Wa)||e===za,Ja="__lunora_relation__:",Se=e=>{if(e.startsWith(Ja))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Ya=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ht="/api/auth",Xa="__lunora_admin__:recordAuthEvent",Za="__lunora_admin__:listPushSubscriptions",es=["/sign-in","/sign-up","/callback"],ts=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return es.some(a=>r===a||r.startsWith(`${a}/`))},ns=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,r)=>{const a=Qn(n),i=a?n.code:"INTERNAL_SERVER_ERROR",u=a?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:f,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},rs=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Lt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,os=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,as=async(e,t,n,r,a=Ye.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),f=e.headers.get("cookie"),p=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");u&&(i.authorization=u),f&&(i.cookie=f),p&&(i["x-d1-bookmark"]=p),h&&(i["x-lunora-mutation-id"]=h),y&&(i["x-lunora-client-id"]=y),S&&(i["x-lunora-client-seq"]=S);const T=sr(e.headers,r);if(T&&(i["x-lunora-client-ip"]=T),!n)return{claims:null,headers:i,identity:null,userId:null};const m=await n(e,t,a);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=Jn(m.userId);const E=rs(m);E!==void 0&&(i["x-lunora-identity-exp"]=String(E));const{userId:R,...g}=m,O=Object.keys(g).length>0?g:null;return O&&(i["x-lunora-identity"]=Yn(O)),{claims:O,headers:i,identity:m,userId:R}},ss=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),is=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("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 c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!ss.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},cs=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ze=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},ds=async e=>{const t=await Wt(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&Qt(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,i=is(a.fanOut),u=a.args??{};if(i&&a.functionPath.startsWith("__lunora_relation__:")){const f=u.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,us=5e3,ls=4096,hs=async(e,t)=>{const n=Date.now(),r=Oe.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Oe.delete(t);let a=0;try{const i=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return Kt(Oe,ls),Oe.set(t,{expiresMs:n+us,relayCount:a}),a},Mt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),fs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ps=(e,t)=>{for(const n of fs){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},jt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const a of r)a.startsWith("x-lunora-")&&n.delete(a);return ps(n,t),n},ms=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Jt(e,t),n),$t=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:et(t,a.join(" ").trim())},ws=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await Jr(t,r)?!0:n?!1:et(t,r)},gs=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return _r(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},ys=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Pe))throw new c(`route "${t}" is under the reserved ${Pe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},bs=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},sn=e=>{bs(e);const t=Ia(e.trustInboundTraceContext),n=Pa(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",a=Er(e.resolveIdentity,e.identity),i=mt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:mt(e.schedulerDO,e.jurisdiction);let f=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;f||(f=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},h=async(o,s,l,d=e.shardRegion?.(s))=>we(o,s,p(d)).fetch(l);let y;const S=()=>e.adminToken??y;let T;const m=()=>e.requireEphemeralWsToken??T??!0;let E;const R=o=>{const s=o??{};if(E??=Mt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=zr(d,!0))}if(y!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(y=l)},g=new WeakSet,O=o=>$t(o,S())||g.has(o),U=async o=>{if(!(e.adminGate===void 0||g.has(o)))try{await Ae(e.adminGate(o,Ye.get(o)))&&g.add(o)}catch{}},H=async(o,s,l,d)=>{const w=await as(o,s,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(w.headers[lt]=ut),w},P=async(o,s)=>{const l=await H(o,s,e.resolveIdentity);if(g.has(o)&&l.headers.authorization===void 0){const d=S();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let K=!1,M=!1;const Z=()=>{M||(M=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},C=o=>{if(!e.allowUnauthenticatedShardAccess){const s=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${s}\` 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})}K||(K=!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("")))},G=async(o,s)=>{if(s.includes(qe)||s.includes(Je))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:o,shardKey:s})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==r&&C("shard")},q=sa({defaultShard:r,forwardToShard:h,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:P,shardDO:i}),J=async(o,s,l,d,w,b)=>{Se(o);const v={"content-type":"application/json",[lt]:ut,"x-lunora-system":"1"};return w?.userId!==void 0&&w.userId.length>0&&(v["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(v["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(v["x-lunora-mutation-id"]=d),b!==void 0&&b.length>0&&(v.traceparent=b),h(i,l,ve(o,s,v))},ee=async(o,s,l,d,w)=>{const b=l?.[o];if(!b||typeof b.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(vr(s))throw new c(`${d} params ${kr}`,{code:"BAD_REQUEST",status:400});try{await b.create(w===void 0?{params:s}:{id:w,params:s})}catch(v){if(!Dr(v))throw v}},Q=async(o,s,l)=>{if(o.workflow){await ee(o.workflow,o.args??{},s,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await J(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},j=(o,s,l)=>{if(F(o),s===void 0)throw new c(l.message,{code:l.code,status:400});return s},he=async(o,s,l,d,w)=>{const b=e.cronJobs?.[o];if(!b)return 0;for(const v of b)try{await Q(v,s,w)}catch(k){l.push(d(k))}return b.length},de=async(o,s)=>{if(F(o),$(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await te(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("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 c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Q(w,s),Response.json({name:d,ran:!0},{status:200})},ge=async o=>{const s=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!s||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await we(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},De=async(o,s)=>{$(o,"POST","Scheduler dispatch");const l=await Wt(o),d=s??{},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),v=o.headers.get("x-lunora-scheduler-signature");let k=!1;if(v&&w?k=await ms(w,l,v):b&&(k=$t(o,b)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let D;try{D=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=D??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await ee(_.workflow,A,s,"scheduled workflow",B),await ge(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:r,W=Ya(o),L=await J(_.functionPath,A,x,B,W,o.headers.get("traceparent")??void 0);return await ge(_),L},Ne=eo({assertAdmin:F,getReader:()=>e.authAuditReader}),se=async(o,s)=>{F(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=s?.kind,w=s?.userId,b=s?.limit,v=d==="fcm"||d==="web-push"?d:void 0,k=typeof w=="string"&&w!==""?w:void 0,D=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,_=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:v,limit:_,userId:k})).filter(x=>v!==void 0&&x.kind!==v?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:W,...L})=>L);return Response.json({result:ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},cn=async(o,s)=>{if(!s.fanOut&&!(s.functionPath!==Et&&s.functionPath!==Za))return await U(o),s.functionPath===Et?Ne(o,s.args??{}):se(o,s.args)},dn=To({applyGlobals:e.applyGlobals,assertAdmin:F,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:j,resolveForwardContext:P,shardDO:i,streamExportRows:(o,s,l,d)=>Zt(e,o,s,l,d,i),streamingImport:(o,s)=>Po(o,e,s,i),syncGlobals:e.syncGlobals}),Ue=(o,s)=>{const l=o.searchParams.get(s);return l===null||l===""?void 0:l},Ce=o=>{const s=new URL(o.url),l=s.searchParams.get("limit"),d=s.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}},rt=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},un=Ta({checkWsAdmin:async o=>O(o)||ws(o,S(),m()),requireSchedulerNamespace:rt,resolveSchedulerStub:o=>(F(o),we(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),ln=Ma({assertAdmin:F,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),hn=lr({assertAdmin:F,parsePaging:Ce,queryParameter:Ue,readBodyBytes:ar,requireAdminOption:j,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),fn=po({options:e,readJsonBody:te,requireAdminOption:j}),pn=Ua({readJsonBody:te,requireAdminOption:j,vectorIntrospector:e.vectorIntrospector}),mn=Qo({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:j}),wn=Rr({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:j}),gn=Ko({assertAdmin:F,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:j}),yn=o=>{const s=[],l=i??o?.SHARD;if(l!==void 0&&s.push(br("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=gs(d,w);b!==void 0&&s.push(b)}for(const d of e.health?.probes??[])s.push(d);return s},bn=yr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:yn}),_n=o=>{const s=_=>"args"in _?{..._,args:Ve(_.args)}:_,l=e.schedulerInstanceName??"default",d=()=>we(o,l),w=async(_,A)=>{const B=await d().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},b=async(_,A)=>await w(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;if(A==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new c("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})},k=async()=>(await Ir(async A=>w(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),D=async(_,A,B={})=>{const x=v(A),{id:W}=await b("/schedule",{args:rr("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:_,...x});return W};return{cancel:async _=>await b("/cancel",{id:_}),get:async _=>{const A=await w(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:k,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(_,A,B)}}},En=async(o,s,l)=>{const{claims:d,headers:w,userId:b}=await H(o,s,a),v=be(s,o,_=>l.waitUntil?.(_)),k=_=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const W=await Ee(o,x,ke(B),_,{...w,"x-lunora-system":"1"},v),L=await W.json();if(L.error)throw new c(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:W.status});return Ve(L.result)},D=k(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=k(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:D,runMutation:D,runQuery:D,...u===void 0?{}:{scheduler:_n(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:Or(e.storage(s))}}},Rn=async(o,s,l)=>{if(!e.httpRouter)return;const d=await En(o,s,l);try{return await e.httpRouter.fetch(o,{...s,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},Sn=async(o,s,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=gt(o,ie);if(d)return d;const w=l.searchParams.get("shard")??r,{headers:b,identity:v}=await H(o,s,a);await G(v,w);const k=jt(o,b),D=Mt(s,e.shardDO);if(D!==void 0){k.set("x-lunora-shard-binding",D);const _=await hs(i,w);if(_>0){const A=Kr(w,Math.floor(Math.random()*_));return h(i,A,new Request(o,{headers:k}),yt(o))}}return h(i,w,new Request(o,{headers:k}))},An=async(o,s,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=gt(o,ie);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(xt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(d,b)?d[b]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const k=l.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:D,identity:_}=await H(o,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:_,shardKey:k})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else C("shard");const A=jt(o,D);return h(v,k,new Request(o,{headers:A}))},Tn=async(o,s,l)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(l,o.table,s)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("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 c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});C("fan-out")},_e=async(o,s)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Tn(o.fanOut,o.functionPath,s);return}await G(s,o.shardKey??r)}},On=(o,s,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Z();return}if(e.functions[s]?.kind!=="query"||l.includes(Je)||l.includes(qe))return;const d=yt(o);return d===void 0?void 0:{name:Fr(l,d),region:d}},vn=async(o,s,l,d,w)=>{const b=On(o,s,d);if(b!==void 0){const v={...w,"x-lunora-replica-read":"1",...E===void 0?{}:{"x-lunora-shard-binding":E}},k=Gr(o.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const D=await h(i,b.name,ve(s,l,v),b.region);if(D.status!==421)return D}return h(i,d,ve(s,l,w))},Ee=async(o,s,l,d,w,b)=>{const v=Date.now(),{observability:k,sampling:D}=e,_=We(o),{decision:A,ignoredUpstream:B,trace:x}=pa(o,{...D===void 0?{}:{sampling:D},trustInbound:t(o)});B&&n();const W={...w,"x-lunora-sample-errors":A.keepErrors?"1":"0"};ma(x,W);try{const L=await vn(o,s,l,d,W);ce(k,{..._,...Bt(x),durationMs:Date.now()-v,functionPath:s,ok:L.ok,shardKey:d,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},b,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",d),ne}catch(L){throw ce(k,{..._,...Bt(x),...Te(s,Date.now()-v,L,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),L}},kn=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Se(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},In=async(o,s,l)=>{$(o,"POST","RPC");const d=await ds(o);cs(s,d),kn(d);const w=await cn(o,d);if(w!==void 0)return w;const{headers:b,identity:v}=await H(o,s,a);await _e(d,v);const k=ze(d,e);{const D=Date.now(),{observability:_}=e,A=We(o),B=be(s,o,l&&(L=>l.waitUntil?.(L)));if(d.fanOut){const L=e.queryCoordinator;if(!L)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return ce(_,{durationMs:Date.now()-D,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:d.fanOut.table},functionPath:d.functionPath,...A,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ce(_,{...Te(d.functionPath,Date.now()-D,ne,{fanOut:{table:d.fanOut.table}}),...A},B),ne}}const x=d.shardKey??r,W=()=>Ee(o,d.functionPath,d.args??{},x,b,B);return k&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:k.price},W,Qe(l)):W()}},Pn=async(o,s,l)=>{$(o,"POST","RPC batch");const d=await te(o),{calls:w}=d;if(!Array.isArray(w))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:v}=await H(o,s,a),k=wo(w,r);for(const z of k.values())for(const V of z)if(e.functions?.[V.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,V])=>V.map(oe=>_e({args:oe.args,functionPath:oe.functionPath,shardKey:z},v))));const{observability:D}=e,_=be(s,o,l&&(z=>l.waitUntil?.(z))),A=We(o),B=[],x=[],W=(z,V,oe,ue)=>({body:{error:{code:oe,message:ue}},id:z.id,status:V}),L=(z,V,oe,ue,fe)=>{for(const Y of z)ce(D,fe(Y),_),B.push(W(Y,V,oe,ue))},ne=(z,V,oe,ue,fe)=>{for(const Y of z){const pe=ue.get(Y.id)??fe,ye=pe<400;ce(D,{durationMs:oe,functionPath:Y.functionPath,...A,ok:ye,shardKey:V,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_)}};await Promise.all([...k.entries()].map(async([z,V])=>{const oe=new Headers(b);oe.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:oe,method:"POST"}),fe=Date.now();let Y;try{Y=await h(i,z,ue)}catch(X){const He=Date.now()-fe,{body:dt}=Wn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,dt.code,dt.message,Gn=>({...Te(Gn.functionPath,He,X,{shardKey:z}),...A}));return}const pe=Date.now()-fe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(V,Y.status,"SHARD_ERROR",X,He=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:He.functionPath,...A,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],Kn=new Map(xe.map(X=>[X.id,X.status??Y.status])),Fn=new Set(xe.map(X=>X.id));ne(V,z,pe,Kn,Y.status),B.push(...xe);for(const X of V)Fn.has(X.id)||B.push(W(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const it={"content-type":"application/json"},[ct]=x;return x.length===1&&ct!==void 0&&(it["x-d1-bookmark"]=ct),Response.json({results:B},{headers:it,status:200})},Dn=async(o,s,l,d={},w={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(b);const{headers:v,identity:k}=await H(o,s,a,w.context),D={args:d,functionPath:b,shardKey:w.shardKey};await _e(D,k);const _=w.shardKey??r,A=be(s,o,w.waitUntil),B=()=>Ee(o,b,d,_,v,A),x=ze(D,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},B,Qe(w.waitUntil?{waitUntil:w.waitUntil}:w.context)):await B()}catch(b){return ht(b)}},ot=async(o,s,l)=>{const{observability:d}=e,w=Date.now(),b=Ie(16),v=Ie(8),k=Lt(s),D=Ft(b,v,!0);try{const _=await l(D);return ce(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:v,traceId:b},k),_}catch(_){throw ce(d,{...Te(o,Date.now()-w,_,{}),spanId:v,traceId:b},k),_}finally{pt(d,k)}},at=async(o,s,l,d)=>{R(s);const w=[],b=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,s,l)}catch(A){w.push(b(A))}const k=await he(o.cron,s,w,b,d),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(D)try{await uo(e,i,S(),o)}catch(A){w.push(b(A))}if(!v&&k===0&&!D){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=w;if(w.length===1&&_)throw _;if(w.length>1)throw new AggregateError(w,`scheduled("${o.cron}") had ${String(w.length)} failure(s)`)},Nn=va({assertAdmin:F,dispatchScheduled:at,queueHandler:e.queueHandler}),Un=async(o,s)=>{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;await h(i,r,ve(Xa,{outcome:s},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Cn=async(o,s,l,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??Ht;return ts(l.pathname,b)&&d.waitUntil?.(Un(s,w.status>=400?"fail":"ok")),w},Bn=async({args:o,env:s,functionPath:l,request:d,shardKey:w,waitUntil:b})=>{Qt(o,"REST");const v={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:k,identity:D}=await H(d,s,a);await _e(v,D);const _=w??r,A=be(s,d,b),B=()=>Ee(d,l,o,_,k,A),x=ze(v,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},B,Qe({waitUntil:b})):B()},xn=or({functions:e.functions??{},invoke:Bn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Re=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;ys(Re);const Hn={[Va]: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"}}),[Ka]:(o,s,l)=>Sn(o,s,l),[Ct]:(o,s,l,d)=>In(o,s,d),[$a]:(o,s,l,d)=>Pn(o,s,d),[Fa]:(o,s)=>De(o,s),[Ga]:(o,s)=>de(o,s),[Qa]:async o=>{$(o,"POST","ws-token"),F(o);const s=S();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await qr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...q,...dn,...un,...ln,...hn,...fn,...pn,...mn,...wn,...gn,...bn,...xn,...Zr({assertAdmin:F,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:te})};let ie=wt(e.security),st=!1;const Ln=o=>{st||(st=!0,ie=wt(e.security,o??{}))},Mn=async(o,s)=>{qa(s)&&await U(o)},jn=(o,s)=>{if(!(s.pathname.startsWith(Pe)||e.authHandler!==void 0&&ns(s.pathname,e.authBasePath??Ht))||o.method!=="POST"&&o.method!=="PUT")return;const d=Number(o.headers.get("content-length")??""),w=ja[s.pathname]??Gt;if(Number.isFinite(d)&&d>w)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},$n=async(o,s,l)=>{Ye.set(o,l);const d=new URL(o.url);jn(o,d);const w=await Cn(o,s,d,l);if(w)return w;if(Re){const D=`${o.method} ${d.pathname}`,_=Re[D]??Re[d.pathname];if(_)return _(o,s,l)}const b=Nn[d.pathname];if(b)return b(o,s,l);const v=Hn[d.pathname];if(v)return await Mn(o,d.pathname),v(o,s,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(xt))return An(o,s,d);if(d.pathname.startsWith(Pe))return new Response("Not found",{status:404});const k=await Rn(o,s,l);return k||new Response("Not found",{status:404})};return{async fetch(o,s,l){e.passThroughOnException&&l.passThroughOnException?.(),Ln(s),R(s);const d=Ar(o,ie);if(d)return d;const w=Tr(o,ie);if(w)return Me(w,o,ie);try{const b=await $n(o,s,l);return Me(b,o,ie)}catch(b){return Me(ht(b),o,ie)}finally{pt(e.observability,Lt(l))}},async queue(o,s,l){await ot(`queue:${os(o)}`,l,async d=>{await e.queue?.(o,s,l,{traceparent:d})})},async scheduled(o,s,l){await ot(`cron:${o.cron}`,l,async d=>{await at(o,s,l,d)})},serverQuery:Dn}},_s=e=>sn(e),Es=e=>typeof e=="function"?{fetch:e}:e,Rs=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Ss=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Ws=(e,t)=>{const n=Es(e),{email:r,queue:a,scheduled:i}=Ss(e),u=p=>{const y={..._s({...p,httpRouter:n})};return i!==void 0&&!Rs(p)&&(y.scheduled=async(S,T,m)=>{await i(S,T,m)}),a!==void 0&&p.queue===void 0&&(y.queue=async(S,T,m)=>{await a(S,T,m)}),r!==void 0&&(y.email=async(S,T,m)=>{await r(S,T,m)}),y};if(typeof t!="function")return u(t);const f=t;return{fetch:(p,h,y)=>u(f(h)).fetch(p,h,y),queue:(p,h,y)=>u(f(h)).queue?.(p,h,y)??Promise.resolve(),scheduled:(p,h,y)=>u(f(h)).scheduled(p,h,y),serverQuery:(p,h,y,S,T)=>u(f(h)).serverQuery(p,h,y,S,T),...r===void 0?{}:{email:(p,h,y)=>u(f(h)).email?.(p,h,y)??Promise.resolve()}}},As=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},zs=(e={})=>(t,n,r)=>sn(As(e,n)).fetch(t,n,r??zn),Vs=e=>e;export{Et as GET_AUTH_AUDIT_LOG_OP,zn as NOOP_EXECUTION_CONTEXT,Ys as composeIdentityResolvers,_s as composeWorker,zs as createLunoraHandler,sn as createWorker,Vs as defineRpcEnvelope,hs as probeRelayCount,As as resolveLunoraOptions,Xs as routeIdentityResolvers,Ws as withFrameworkWorker};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.117",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
-
"@lunora/observability": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.58",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.36",
|
|
51
|
+
"@lunora/observability": "1.0.0-alpha.74",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.30"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"@lunora/shard-engine": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Gn,toErrorBody as Qn}from"@lunora/errors";import{e as Kt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Wn}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as zn,f as Vn}from"./base64-Bl1_r2k1.mjs";import{e as qn,a as Jn}from"./identity-header-C4Z5pldl.mjs";import{O as ut,a as lt}from"./origin-paywall-B6eOO67m.mjs";import{o as Ie,b as Ft,p as Yn,m as Xn,d as Zn,a as er,r as tr}from"./otlp-resource-JKBCWf6c.mjs";import{e as ke,d as Ve,a as nr}from"./wire-codec-BLvSm5Mn.mjs";import{d as te,e as le,M as Gt,b as rr,f as or,g as Qt,t as ar,h as Wt}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as d,toErrorResponse as ht}from"./LunoraError-DksAgIpa.mjs";import{a as $,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Xe,BACKUP_KEY_PREFIX as Ze,backupObjectKey as sr,backupManifestKey as ir,isBackupManifestKey as cr,backupObjectKeyOfManifest as zt}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as dr,buildStorageAdminRoutes as ur,STORAGE_UPLOAD_MAX_BODY_BYTES as lr,STORAGE_PATH as hr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{b as fr,e as pr,f as ft,g as mr,h as wr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as gr,durableObjectProbe as yr,d1Probe as br,presenceProbe as Le}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as _r}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Js,routeIdentityResolvers as Ys}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Er}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{r as Rr,f as pt,a as ie}from"./observability-B1hLjwgx.mjs";import{resolveShard as we,applyJurisdiction as mt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as wt,handleCorsPreflight as Sr,enforceOrigin as Ar,decorateResponse as Me,enforceWebSocketOrigin as gt}from"./decorateResponse-Y2sCM0w1.mjs";const Tr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,a={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return a.bucket=()=>a,a},Vt="__lunoraBranch",Or=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Vt),vr=`may not contain the reserved workflow branch-marker key ("${Vt}")`,kr=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},et=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let a=0;a<n;a+=1){const c=a<e.length?e.charCodeAt(a):0,l=a<t.length?t.charCodeAt(a):0;o|=c^l}return o===0},Ir=/already[\s_-]?exists/iu,Pr=e=>Ir.test(e instanceof Error?e.message:String(e)),Dr=(e,t,n,o)=>{const a=e.get(t);if(a!==void 0)return a;Kt(e,o);const c=n().catch(l=>{throw e.get(t)===c&&e.delete(t),l});return e.set(t,c),c},tt=new TextEncoder,Nr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Nr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Ur=64,Cr=new Map,qt=async e=>Dr(Cr,e,async()=>crypto.subtle.importKey("raw",tt.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Ur),Jt=async(e,t)=>{const n=await qt(e),o=await crypto.subtle.sign("HMAC",n,tt.encode(t));return zn(new Uint8Array(o))},Br=async(e,t,n)=>{const o=await qt(e);return crypto.subtle.verify("HMAC",o,n,tt.encode(t))},xr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(xr);const Hr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Lr=-100,Mr=15,jr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Hr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Mr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Lr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},yt=e=>{const t=e.cf;return t===void 0?void 0:jr(t)},qe="::relay::",$r=(e,t)=>`${e}${qe}${String(t)}`,Je="::replica::",Kr=(e,t)=>`${e}${Je}${t}`,Fr=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Gr=new Set(["1","enabled","on","true","yes"]),Qr=new Set(["0","disabled","false","no","off"]),Wr=(e,t)=>{const n=(e??"").trim().toLowerCase();return Gr.has(n)?!0:Qr.has(n)?!1:t},Yt="v1",zr=6e4,Vr=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??zr),o=`${Yt}.${String(n)}`,a=await Jt(e,o);return{expiresAtMs:n,token:`${o}.${a}`}},qr=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[a,c,l]=o;if(a!==Yt||l.length===0)return!1;const f=Number(c);if(!Number.isFinite(f)||f<=n)return!1;let m;try{m=Vn(l)}catch{return!1}return Br(e,`${a}.${c}`,m)},P="/_lunora/admin/auth",Jr={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},N=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new d(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},ue=(e,t)=>{const n=e(t);if(n===void 0)throw new d(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},Xt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,je=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},bt=e=>{const t=Xt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return t},_t=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,a]of Object.entries(t))Array.isArray(a)&&a.every(c=>typeof c=="string")&&(n[o]=a);return n},Yr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:ue(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${P}/sign-up-invitations/create`]:{build:({body:e})=>({email:N(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${P}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:N(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:ue(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:ue(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:je(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Xt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:bt(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:je(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:bt(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:_t(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:_t(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Xr=e=>{const t=async a=>{try{return await a()}catch(c){if(c instanceof d)throw c;const l=c,f=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",c),new d("auth admin operation failed",{code:f,status:Jr[f]??500})}},n=async(a,c)=>{if(e.assertAdmin(a),a.method!==c.http)throw new d(`Auth admin endpoint requires ${c.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=l[c.method];if(f===void 0)throw new d(`auth admin does not support \`${c.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const m=new URL(a.url),p={body:c.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:T=>e.queryParameter(m,T)},E=c.build(p),S=await t(()=>f(E));return Response.json(c.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[a,c]of Object.entries(Yr))o[a]=l=>n(l,c);return o},Et="__lunora_admin__:getAuthAuditLog",Rt=e=>typeof e=="string"&&e!==""?e:void 0,St=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Zr=e=>async(n,o)=>{e.assertAdmin(n);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const c=Rt(o.actorId),l=Rt(o.event),f=St(o.sinceSeq),m=St(o.limit),p={...c===void 0?{}:{actorId:c},...l===void 0?{}:{event:l},...f===void 0?{}:{sinceSeq:f},...m===void 0?{}:{limit:m}};let E;try{E=await a.read(p)}catch(T){throw T instanceof d?T:(console.error("[lunora] auth audit read failed:",T),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:E};return Response.json({result:ke(S)},{headers:{"content-type":"application/json"},status:200})},eo=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const a of t)e.resolveTableSharding?.(a)?.mode.kind==="global"?o.push(a):n.push(a);return{globalTables:o,shardLocalTables:n}},to=async(e,t,n,o,a,c,l)=>{if(n!==void 0&&o.length===0)return;const f=await e.orchestrateExport(c,{args:{tables:o},defaultShardKey:l,headers:t,tables:o});for(const m of f.shards)if(!m.error)for(const p of m.rows??[])a(p)},Zt=async(e,t,n,o,a,c)=>{const l=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:f,shardLocalTables:m}=eo(e,l);await to(t,n,l,m,a,c,e.defaultShardKey??"__root__");const p=e.exportGlobals;if((o===void 0||f.length>0)&&p)for await(const S of p({tables:f}))a(S)},no=new TextEncoder,ro=1e3,en=10,oo=200,At=8,tn="lunoraBackupCron",Tt=24*1048576,Ot=e=>{const t=e.slice(0,en).map(o=>zt(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ao=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const a of e)n.set(a,o),o+=a.byteLength;return n},nt=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const a=[];let c;for(let l=0;l<ro;l+=1){const f=await e.list({cursor:c,include:["customMetadata"],prefix:t});for(const m of f.objects)cr(m.key)&&m.customMetadata?.[tn]===o&&a.push(m.key);if(!f.truncated||f.cursor===void 0)break;c=f.cursor}return{eligible:a.length,stale:a.toSorted((l,f)=>f.localeCompare(l)).slice(n)}},so=async(e,t,n,o,a)=>{const{stale:c}=await nt(e,t,n,o),l=new Set(a),f=c.filter(w=>l.has(w)),m=f.slice(0,oo),p=c.length-m.length,E=a.length-f.length;if(m.length===0)return{deleted:[],failed:[],ignored:E,remaining:p};const S=[],T=[];for(let w=0;w<m.length;w+=At){const b=await Promise.allSettled(m.slice(w,w+At).map(async R=>(await e.delete(zt(R)),await e.delete(R),R)));for(const[R,g]of b.entries())g.status==="fulfilled"?S.push(g.value):T.push(m[w+R])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ot(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ot(T)}`),{deleted:S,failed:T,ignored:E,remaining:p}},io=async e=>{const t=e.backupStore;if(!t)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=Xe(e.backupPrefix??Ze),o=e.backupCron,{eligible:a,stale:c}=o===void 0?{eligible:0,stale:[]}:await nt(t,n,e.backupRetain,o);return{cron:o,eligible:a,keep:e.backupRetain??0,prefix:n,wouldDelete:c}},co=async(e,t,n,o)=>{const a=e.backupStore,c=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!c)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${n}`,"content-type":"application/json"},f=e.backupTables;let m=0,p=0,E=[];await Zt(e,c,l,f,U=>{const H=no.encode(`${JSON.stringify(U)}
|
|
2
|
-
`);if(m+=1,p+=H.byteLength,p>Tt)throw new d(`scheduled backup reached ${String(p)} bytes of NDJSON, past the ${String(Tt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});E.push(H)},t);const T=Xe(e.backupPrefix??Ze),w=new Date(o.scheduledTime).toISOString(),b=sr(T,w),R=ao(E,p);E=[];const g=dr(await crypto.subtle.digest("SHA-256",R));await a.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:p,createdAt:w,cron:o.cron,file:b,id:w,rows:m,scheduledTime:o.scheduledTime,sha256:g,...f?{tables:f.join(",")}:{}};await a.put(ir(b),`${JSON.stringify(O,void 0,2)}
|
|
3
|
-
`,{customMetadata:{[tn]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:U}=await nt(a,T,e.backupRetain,o.cron);if(U.length>0){const H=U.slice(0,en),D=U.length-H.length;console.info(`[lunora] backup retention: ${String(U.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${H.join(", ")}${D>0?` (+${String(D)} more)`:""}`)}}catch(U){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,U)}},uo=async(e,t)=>{const n=e.backupStore;if(!n)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,a=e.backupRetain;if(o===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return so(n,Xe(e.backupPrefix??Ze),a,o,t)},lo="/_lunora/admin/backup/retention",ho="/_lunora/admin/backup/prune",fo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,a=(f,m)=>{o(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${m} requires a \`backupStore\` on the worker`})},c=async f=>($(f,"GET","Backup-retention"),a(f,"retention preview"),Response.json(await io(t),{headers:{"cache-control":"no-store"}})),l=async f=>{$(f,"POST","Backup-prune"),a(f,"prune");const{confirm:m}=await n(f);if(!Array.isArray(m)||m.some(p=>typeof p!="string"))throw new d("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await uo(t,m),{headers:{"cache-control":"no-store"}})};return{[ho]:l,[lo]:c}},vt=500,po=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new d("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new d("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new d("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},mo=(e,t)=>{if(e.length>vt)throw new d(`RPC batch exceeds the ${String(vt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[a,c]of e.entries()){const{entry:l,shardKey:f}=po(c,a,t);if(o.has(l.id))throw new d(`batch call id ${String(l.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(l.id);const m=n.get(f)??[];m.push(l),n.set(f,m)}return n},wo="/_lunora/admin/export",go="/_lunora/admin/import",yo="/_lunora/admin/sync",bo="/_lunora/admin/connector/sync",_o="/_lunora/admin/apply",Eo="/_lunora/admin/export-tap/run",Ro=new TextEncoder,So=async e=>{const n=await le(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const a of n.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(a)}return{tables:o}},$e=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Ao=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:a,knownTables:c,queryCoordinator:l,assertAdmin:f,requireAdminOption:m,resolveForwardContext:p,shardDO:E,streamExportRows:S,streamingImport:T,syncGlobals:w}=e,b=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await So(D),{headers:G}=await p(D,F),q=new ReadableStream({async pull(J){const ee=Q=>{J.enqueue(Ro.encode(`${JSON.stringify(Q)}
|
|
4
|
-
`))};try{await S(Z,G,C.tables,ee),J.close()}catch(Q){J.error(Q)}}});return new Response(q,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),G=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},q=typeof C.limit=="number"?C.limit:void 0,J=typeof C.globalCursor=="number"?C.globalCursor:0,ee=$e(C.tables),{headers:Q}=await p(D,F),K=ee??c(),j=await Z.orchestrateCdcSync(E,{cursors:G,defaultShardKey:n,headers:Q,limit:q,tables:K}),he=w?await w({limit:q,sinceSeq:J}):void 0;return Response.json({global:he,shards:j.shards},{status:200})},g=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),G=pr(C.cursor),q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables),{headers:ee}=await p(D,F),Q=J??c(),K=await Z.orchestrateCdcSync(E,{cursors:G.s,defaultShardKey:n,headers:ee,limit:q,tables:Q}),j=[],he={...G.s};let ce=!1;for(const ae of K.shards)ce=ft(j,ae.changes??[],wr(q))||ce,he[ae.shardKey]=ae.cursor;let ge=G.g;if(w){const ae=await w({limit:q,sinceSeq:G.g});ce=ft(j,ae.changes,q)||ce,ge=ae.cursor}const De=mr({g:ge,s:he,v:1}),Ne={changes:j,hasMore:ce,nextCursor:De};return Response.json(Ne,{status:200})},O=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await te(D),q=(Array.isArray(C.batches)?C.batches:[]).map(j=>j).filter(j=>j!==null&&typeof j=="object"&&typeof j.shardKey=="string"&&Array.isArray(j.changes)),J=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await p(D,F),Q=await Z.orchestrateApplyCdc(E,{batches:q,headers:ee}),K=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:Q.applied+K,failed:Q.failed,ok:Q.ok},{status:200})},U=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;f(D);const{headers:Z}=await p(D,F),C=await T(D,Z);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},H=async(D,F)=>{const M=me(D,["POST"]);if(M)return M;const Z=m(D,l,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(a===void 0||Object.keys(a).length===0||o===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await te(D),G=typeof C.sink=="string"?C.sink:void 0,q=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,J=$e(C.tables);if(G===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=a[G];if(ee===void 0)throw new d(`Export-tap sink "${G}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Q}=await p(D,F),K=J??c(),j=await fr({coordinator:Z,cursorStore:o,defaultShardKey:n,headers:Q,limit:q,shardDO:E,sink:ee,tables:K});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[_o]:O,[bo]:g,[wo]:b,[Eo]:H,[go]:U,[yo]:R}},To=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},Oo=(e,t,n,o,a)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const c=e[n.mode.field];return c==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof c=="string"?c:JSON.stringify(c)}}return{ok:!0,shardKey:o}},vo=async(e,t,n)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],a=[],c=new Map;let l=0,f=0;const m=e.body.getReader(),p=new TextDecoder;let E="",S=0;const T=w=>{f+=1;const b=w.trim();if(b.length===0)return;l+=1;const R=To(b,f);if(!R.ok){o.push(R.error);return}const{doc:g,table:O}=R,U=t.resolveTableSharding?.(O);if(U?.mode.kind==="global"){a.push({doc:g,line:f,table:O});return}const H=Oo(g,O,U,n,f);if(!H.ok){o.push(H.error);return}const D=c.get(H.shardKey);D?D.rows.push({doc:g,table:O}):c.set(H.shardKey,{rows:[{doc:g,table:O}],shardKey:H.shardKey,startLine:f})};for(;;){const{done:w,value:b}=await m.read();if(w)break;if(b&&(S+=b.byteLength,S>Gt))throw await m.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=p.decode(b,{stream:!0});let R=E.indexOf(`
|
|
5
|
-
`);for(;R!==-1;){const g=E.slice(0,R);E=E.slice(R+1),T(g),R=E.indexOf(`
|
|
6
|
-
`)}}return E.length>0&&T(E),{errors:o,globalRows:a,perShard:c,received:l}},ko=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),kt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Io=async(e,t,n,o)=>{const a=t.defaultShardKey??"__root__",{errors:c,globalRows:l,perShard:f,received:m}=await vo(e,t,a),p={conflicts:0,errors:c,failed:[],inserted:{}},E=[];if(t.resolveTableSharding===void 0&&f.size>0&&E.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"),f.size>0){const S=t.queryCoordinator;if(!S)throw new d("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(o,{batches:[...f.values()],headers:n});kt(p,T),p.failed.push(...ko(T.shards))}if(l.length>0)if(t.importGlobals){const S=l[0]?.line??1,T=await t.importGlobals({rows:l,startLine:S});kt(p,T)}else for(const S of l)p.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:p.conflicts,errors:p.errors,failed:p.failed,inserted:p.inserted,received:m,...E.length>0?{warnings:E}:{}}},Ke=e=>typeof e=="object"&&e!==null?e:{},Fe=e=>typeof e.kind=="string"?e.kind:"unknown",Po=(e,t)=>{let n=Ke(t),o=!1;Fe(n)==="optional"&&(o=!0,n=Ke(n._meta?.inner));const a=Fe(n),c=n._meta??{},l={kind:a,name:e,optional:o};if(a==="id"&&typeof c.tableName=="string"&&(l.table=c.tableName),a==="array"){const f=Fe(Ke(c.inner));f!=="unknown"&&(l.element=f)}return l},Do=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Po(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),No="/_lunora/admin/functions",Uo="/_lunora/admin/cron-jobs",Co="/_lunora/admin/openapi",Bo="/_lunora/admin/openrpc",xo="/_lunora/admin/global/tables",Ho="/_lunora/admin/global/table",Lo="/_lunora/admin/global/facet",It=e=>{if(e===void 0||e==="")return;let t;try{t=Ve(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:a,value:c}=o;return[{column:a,value:c}]});return n.length===0?void 0:n},Mo=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:{}}),jo=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"}),$o=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:a,requireAdminOption:c}=e,l=w=>{$(w,"GET","Functions");const b=c(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:Do(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},f=w=>{$(w,"GET","Cron-jobs");const b=c(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.map(U=>({args:U.args,cron:g,functionPath:U.functionPath,name:U.name,shardKey:U.shardKey,workflow:U.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},m=w=>($(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Mo,{headers:{"content-type":"application/json"},status:200})),p=w=>($(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??jo,{headers:{"content-type":"application/json"},status:200})),E=async w=>{$(w,"GET","Global-tables");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{$(w,"GET","Global-table");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=a(R,"table");if(g===void 0)throw new d("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await b.readTablePage({...o(w),filters:It(a(R,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async w=>{$(w,"GET","Global-facet");const b=c(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=a(R,"table"),O=a(R,"column");if(g===void 0||O===void 0)throw new d("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const U=a(R,"limit"),H=U===void 0?void 0:Number(U),D=await b.facetColumn({column:O,filters:It(a(R,"filters")),limit:H!==void 0&&Number.isFinite(H)?H:void 0,table:g});return Response.json(D,{headers:{"content-type":"application/json"},status:200})};return{[Uo]:f,[No]:l,[Lo]:T,[Ho]:S,[xo]:E,[Co]:m,[Bo]:p}},Ko="/_lunora/admin/kv/namespaces",Fo="/_lunora/admin/kv/keys",nn="/_lunora/admin/kv/value",rn=32*1048576,Pt=60,Go=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),a=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),c=(b,R)=>{const g=new URL(b.url),O=g.searchParams.get("namespace")??"",U=g.searchParams.get("key")??"";if(O==="")throw new d(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(U==="")throw new d(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:U,namespace:O}},l=async(b,R)=>{if(!(await b.listNamespaces()).some(O=>O.binding===R))throw new d(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},f=async b=>($(b,"GET","KV-namespaces"),a({namespaces:await o(b).listNamespaces()})),m=async b=>{$(b,"GET","KV-keys");const R=o(b),g=new URL(b.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new d("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const U=g.searchParams.get("prefix")??void 0,H=g.searchParams.get("cursor")??void 0,D=g.searchParams.get("limit"),F=D===null?void 0:Number.parseInt(D,10);if(F!==void 0&&(!Number.isInteger(F)||F<1))throw new d("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const M=F===void 0?void 0:Math.min(F,1e3);return await l(R,O),a(await R.listKeys({cursor:H,limit:M,namespace:O,prefix:U}))},T={DELETE:async b=>{const R=o(b),g=c(b,"DELETE");return await l(R,g.namespace),await R.deleteKey(g),a({deleted:!0})},GET:async b=>{const R=o(b),g=c(b,"GET");return await l(R,g.namespace),a(await R.getValue(g))},PUT:async b=>{const R=o(b),g=await t(b,rn);if(typeof g.namespace!="string"||g.namespace==="")throw new d("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new d("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new d("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<Pt))throw new d("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Pt;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new d("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await l(R,g.namespace),await R.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),a({ok:!0})}},w=b=>{const R=T[b.method];if(!R)throw new d("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[Ko]:f,[Fo]:m,[nn]:w}},Qo="/_lunora/migrate",Wo="/_lunora/admin/pitr",zo="/_lunora/admin/rank",Vo="/_lunora/admin/rankpage",qo="/_lunora/admin/shard-traffic",Jo=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Yo=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Xo=async e=>{const n=await le(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!Jo.has(n.functionPath))throw new d("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},Zo=async e=>{const n=await le(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new d("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new d("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new d("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new d("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},ea=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new d('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},ta=e=>{if(typeof e.table!="string"||e.table.length===0)throw new d("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new d("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new d("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 d("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 d("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},na=async e=>{const n=await le(e,"Rank page")??{};ta(n);const o=ea(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},ra=async e=>{const n=await le(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new d("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},oa=async e=>{const n=await te(e);if(typeof n.functionPath!="string"||!Yo.has(n.functionPath))throw new d("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new d("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},aa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:a,resolveForwardContext:c,shardDO:l}=e,f=(w,b)=>{if(w.method!=="POST")throw new d(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(w))throw new d("Admin auth required",{code:"FORBIDDEN",status:403});if(!a)throw new d(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return a},m=async(w,b)=>{const R=f(w,"Migration"),g=await Xo(w),{headers:O}=await c(w,b),U=await R.orchestrateMigration(l,{args:g.args,defaultShardKey:t,functionPath:g.functionPath,headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},p=async(w,b)=>{const R=f(w,"Rank"),g=await Zo(w),{headers:O}=await c(w,b),U=await R.orchestrateRank(l,{headers:O,index:g.index,partitionKey:g.partitionKey,rowId:g.rowId,sortValues:g.sortValues,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},E=async(w,b)=>{const R=f(w,"Rank page"),g=await na(w),{headers:O}=await c(w,b),U=await R.orchestrateRankPage(l,{...g,headers:O});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},S=async(w,b)=>{const R=f(w,"Shard-traffic"),g=await ra(w),{headers:O}=await c(w,b),U=await R.orchestrateShardTraffic(l,{headers:O,table:g.table});return Response.json(U,{headers:{"content-type":"application/json"},status:200})},T=async(w,b)=>{if($(w,"POST","PITR"),!o(w))throw new d("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await oa(w),{headers:g}=await c(w,b),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:g,method:"POST"});return n(l,R.shardKey??t,O)};return{[Qo]:m,[Wo]:T,[zo]:p,[Vo]:E,[qo]:S}},sa=1,ia=0,ca=32,da=512,ua=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,la=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>da)return;const n=t.split(",");if(!(n.length>ca)){for(const o of n)if(!ua.test(o.trim()))return;return t}},ha=e=>{const t=Yn(e.headers.get("traceparent"));if(t===void 0)return;const n=la(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},fa=(e,t={})=>{const n=ha(e),o=t.trustInbound===!0?n:void 0,a=Ie(8),c=o?.traceId??Ie(16),l=Rr(t.sampling,o===void 0?a:c),f=l.isTraced&&(o===void 0||o.sampled);return{decision:l,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:f,spanId:a,traceFlags:f?sa:ia,traceId:c,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},pa=(e,t)=>{t.traceparent=Ft(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},ma=(e,t)=>{let n;return()=>{if(n===void 0){const o=tr(e),a=t===void 0?void 0:t.cf;n=Xn(er(o),Zn(o,a))}return n}},wa="/_lunora/admin/scheduled",ga="/_lunora/admin/scheduled/status",ya="/_lunora/admin/scheduled/ws",ba="/_lunora/admin/scheduled/cancel",_a="/_lunora/admin/scheduled/dead",Ea="/_lunora/admin/scheduled/dead/retry",Ra="/_lunora/admin/scheduled/dead/cancel",Sa="/_lunora/admin/scheduled/pool/release",Aa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:a}=e,c=(p,E)=>S=>{if(S.method!=="GET")throw new d(`${E} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),w=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${p}${w}`,{method:"GET"}))},l=(p,E,S=E)=>async T=>{if(T.method!=="POST")throw new d(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const w=o(T),b=await le(T,E);if(typeof b?.id!="string"||b.id==="")throw new d(`${E} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return w.fetch(new Request(`https://scheduler.internal${p}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async p=>{if(p.method!=="POST")throw new d("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const E=o(p),S=await le(p,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new d("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return E.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},m=async p=>{if(p.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(p))throw new d("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const E=n();return we(E,a).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ba]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Ra]:l("/dead/cancel","Scheduled dead-letter action"),[_a]:c("/dead","Scheduled dead-letter"),[Ea]:l("/dead/retry","Scheduled dead-letter action"),[wa]:c("/list","Scheduled-list"),[Sa]:f,[ga]:c("/status","Scheduler-status"),[ya]:m}},Ta=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},Dt={mtls:e=>Ta(e,"tlsClientAuth","certVerified")==="SUCCESS"},Oa=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(Dt,e)?Dt[e]:void 0)??(()=>!1),va=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.'))}},ka="/_lunora/admin/vector/indexes",Ia="/_lunora/admin/vector/query",Pa=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async c=>{$(c,"GET","Vector-indexes");const l=n(c,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},a=async c=>{$(c,"POST","Vector-query");const l=n(c,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new d("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const m=await t(c);if(typeof m.name!="string"||m.name==="")throw new d("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof m.text!="string"||m.text==="")throw new d("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(m.topK!==void 0&&(typeof m.topK!="number"||!Number.isInteger(m.topK)||m.topK<1))throw new d("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const p=await l.queryIndex({name:m.name,text:m.text,topK:m.topK});return Response.json(p,{headers:{"content-type":"application/json"},status:200})};return{[ka]:o,[Ia]:a}},Da="/_lunora/admin/workflows/instances",Na="/_lunora/admin/workflows/instance",Ua="/_lunora/admin/workflows/status",Ca={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ba=e=>e!==null&&Object.hasOwn(Ca,e)?e:void 0,Nt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ge=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new d(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Ut=()=>{throw new d("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},xa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(l,f,m)=>{$(l,"GET","Workflows instances"),t(l);const p=n(f);if(!p)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const E=Ge(m,"name"),S=Ba(m.searchParams.get("status"));return Response.json(await p.listInstances({page:Nt(m,"page"),perPage:Nt(m,"perPage"),status:S,workflowName:E}))},a=async(l,f,m)=>{$(l,"GET","Workflows instance"),t(l);const p=n(f);return p?Response.json(await p.getInstance({instanceId:Ge(m,"id"),workflowName:Ge(m,"name")})):Ut()},c=async(l,f)=>{$(l,"POST","Workflows status"),t(l);const m=n(f);if(!m)return Ut();const p=await l.json().catch(()=>{});if(typeof p?.name!="string"||p.name===""||typeof p.id!="string"||p.id==="")throw new d("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:E}=p;if(E!=="pause"&&E!=="resume"&&E!=="terminate")throw new d("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await m.setInstanceStatus({action:E,instanceId:p.id,workflowName:p.name}))};return{[Na]:a,[Da]:o,[Ua]:c}},Ha={[nn]:rn,[hr]:lr},Ct="/_lunora/rpc",La="/_lunora/rpc-batch",Ma="/_lunora/ws",be=(e,t,n)=>({resourceAttributes:ma(e,t),...n===void 0?{}:{waitUntil:n}}),Qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Bt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),We=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const a=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(a)?void 0:a,scheme:o.protocol.replace(":",""),userAgent:n}},xt="/_lunora/voice/",ja="/_lunora/scheduler/dispatch",$a="/_lunora/admin/cron-jobs/run",Ka="/_lunora/admin/ws-token",Fa="/_lunora/admin/",Pe="/_lunora/",Ga="/_lunora/migrate",Qa="/_lunora/status",Wa=e=>e.startsWith(Fa)||e===Ga,za="/_lunora/scheduled",Va="/_lunora/queue",qa="__lunora_relation__:",Se=e=>{if(e.startsWith(qa))throw new d("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ae=async e=>await e===!0,Ja=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Ht="/api/auth",Ya="__lunora_admin__:recordAuthEvent",Xa="__lunora_admin__:listPushSubscriptions",Za=["/sign-in","/sign-up","/callback"],es=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Za.some(a=>o===a||o.startsWith(`${a}/`))},ts=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Te=(e,t,n,o)=>{const a=Gn(n),c=a?n.code:"INTERNAL_SERVER_ERROR",l=a?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:c,message:f,status:l},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},ns=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Lt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,rs=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Ye=new WeakMap,os=async(e,t,n,o,a=Ye.get(e))=>{const c={"content-type":"application/json"},l=e.headers.get("authorization"),f=e.headers.get("cookie"),m=e.headers.get("x-d1-bookmark"),p=e.headers.get("x-lunora-mutation-id"),E=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq");l&&(c.authorization=l),f&&(c.cookie=f),m&&(c["x-d1-bookmark"]=m),p&&(c["x-lunora-mutation-id"]=p),E&&(c["x-lunora-client-id"]=E),S&&(c["x-lunora-client-seq"]=S);const T=ar(e.headers,o);if(T&&(c["x-lunora-client-ip"]=T),!n)return{claims:null,headers:c,identity:null,userId:null};const w=await n(e,t,a);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:c,identity:null,userId:null};c["x-lunora-userid"]=qn(w.userId);const b=ns(w);b!==void 0&&(c["x-lunora-identity-exp"]=String(b));const{userId:R,...g}=w,O=Object.keys(g).length>0?g:null;return O&&(c["x-lunora-identity"]=Jn(O)),{claims:O,headers:c,identity:w,userId:R}},as=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ss=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new d("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 d("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new d("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!as.has(n.kind))throw new d("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new d("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new d("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},is=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ze=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new d("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new d(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},cs=async e=>{const t=await Wt(e);let n;try{n=JSON.parse(t)}catch{throw new d("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new d("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&Qt(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new d("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const a=n,c=ss(a.fanOut),l=a.args??{};if(c&&a.functionPath.startsWith("__lunora_relation__:")){const f=l.table;if(typeof f=="string"&&f!==c.table)throw new d("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=c.table}return{args:l,fanOut:c,functionPath:a.functionPath,shardKey:a.shardKey}},Oe=new Map,ds=5e3,us=4096,ls=async(e,t)=>{const n=Date.now(),o=Oe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Oe.delete(t);let a=0;try{const c=await we(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(c.ok){const f=(await c.json()).relayCount;typeof f=="number"&&f>0&&(a=Math.floor(f))}}catch{a=0}return Kt(Oe,us),Oe.set(t,{expiresMs:n+ds,relayCount:a}),a},Mt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},ve=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),hs=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],fs=(e,t)=>{for(const n of hs){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},jt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const a of o)a.startsWith("x-lunora-")&&n.delete(a);return fs(n,t),n},ps=async(e,t,n)=>e.length===0||n.length===0?!1:et(await Jt(e,t),n),$t=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:et(t,a.join(" ").trim())},ms=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await qr(t,o)?!0:n?!1:et(t,o)},ws=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return br(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Le(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Le(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Le(`hyperdrive:${e}`,!0)},gs=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Pe))throw new d(`route "${t}" is under the reserved ${Pe} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ys=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new d("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},on=e=>{ys(e);const t=Oa(e.trustInboundTraceContext),n=va(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",a=_r(e.resolveIdentity,e.identity),c=mt(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:mt(e.schedulerDO,e.jurisdiction);let f=!1;const m=r=>{if(r===void 0||e.jurisdiction===void 0)return r;f||(f=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},p=async(r,s,u,i=e.shardRegion?.(s))=>we(r,s,m(i)).fetch(u);let E;const S=()=>e.adminToken??E;let T;const w=()=>e.requireEphemeralWsToken??T??!0;let b;const R=r=>{const s=r??{};if(b??=Mt(r,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const i=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof i=="string"&&i.length>0&&(T=Wr(i,!0))}if(E!==void 0||e.adminToken!==void 0)return;const u=s.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(E=u)},g=new WeakSet,O=r=>$t(r,S())||g.has(r),U=async r=>{if(!(e.adminGate===void 0||g.has(r)))try{await Ae(e.adminGate(r,Ye.get(r)))&&g.add(r)}catch{}},H=async(r,s,u,i)=>{const h=await os(r,s,u,e.trustedClientIpHeader,i);return e.functions!==void 0&&(h.headers[lt]=ut),h},D=async(r,s)=>{const u=await H(r,s,e.resolveIdentity);if(g.has(r)&&u.headers.authorization===void 0){const i=S();i!==void 0&&(u.headers.authorization=`Bearer ${i}`)}return u};let F=!1,M=!1;const Z=()=>{M||(M=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},C=r=>{if(!e.allowUnauthenticatedShardAccess){const s=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new d(`${r} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}F||(F=!0,console.warn([`[lunora] SECURITY: serving ${r} 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("")))},G=async(r,s)=>{if(s.includes(qe)||s.includes(Je))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:r,shardKey:s})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else s!==o&&C("shard")},q=aa({defaultShard:o,forwardToShard:p,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:D,shardDO:c}),J=async(r,s,u,i,h,y)=>{Se(r);const v={"content-type":"application/json",[lt]:ut,"x-lunora-system":"1"};return h?.userId!==void 0&&h.userId.length>0&&(v["x-lunora-userid"]=h.userId),h?.identity!==void 0&&h.identity.length>0&&(v["x-lunora-identity"]=h.identity),i!==void 0&&i.length>0&&(v["x-lunora-mutation-id"]=i),y!==void 0&&y.length>0&&(v.traceparent=y),p(c,u,ve(r,s,v))},ee=async(r,s,u,i,h)=>{const y=u?.[r];if(!y||typeof y.create!="function")throw new d(`${i} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Or(s))throw new d(`${i} params ${vr}`,{code:"BAD_REQUEST",status:400});try{await y.create(h===void 0?{params:s}:{id:h,params:s})}catch(v){if(!Pr(v))throw v}},Q=async(r,s,u)=>{if(r.workflow){await ee(r.workflow,r.args??{},s,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new d(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const i=await J(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,u);if(!i.ok)throw new d(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(i.status)}`,{code:"CRON_JOB_FAILED",status:500})},K=r=>{if(!O(r))throw new d("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},j=(r,s,u)=>{if(K(r),s===void 0)throw new d(u.message,{code:u.code,status:400});return s},he=async(r,s,u,i,h)=>{const y=e.cronJobs?.[r];if(!y)return 0;for(const v of y)try{await Q(v,s,h)}catch(k){u.push(i(k))}return y.length},ce=async(r,s)=>{if(K(r),$(r,"POST","cron-jobs run"),!e.cronJobs)throw new d("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const u=await te(r),i=typeof u.name=="string"?u.name:"";if(i==="")throw new d("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const h=Object.values(e.cronJobs).flat().find(y=>y.name===i);if(!h)throw new d(`no cron job named "${i}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await Q(h,s),Response.json({name:i,ran:!0},{status:200})},ge=async r=>{const s=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!s||!l||typeof r.id!="string")return;const u=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await we(l,u).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},De=async(r,s)=>{$(r,"POST","Scheduler dispatch");const u=await Wt(r),i=s??{},h=typeof i.LUNORA_SCHEDULER_SECRET=="string"?i.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof i.LUNORA_ADMIN_TOKEN=="string"?i.LUNORA_ADMIN_TOKEN:void 0),v=r.headers.get("x-lunora-scheduler-signature");let k=!1;if(v&&h?k=await ps(h,u,v):y&&(k=$t(r,y)),!k)throw new d("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let I;try{I=JSON.parse(u)}catch{throw new d("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=I??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await ee(_.workflow,A,s,"scheduled workflow",B),await ge(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new d("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,W=Ja(r),L=await J(_.functionPath,A,x,B,W,r.headers.get("traceparent")??void 0);return await ge(_),L},Ne=Zr({assertAdmin:K,getReader:()=>e.authAuditReader}),ae=async(r,s)=>{K(r);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({result:ke({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const i=s?.kind,h=s?.userId,y=s?.limit,v=i==="fcm"||i==="web-push"?i:void 0,k=typeof h=="string"&&h!==""?h:void 0,I=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,_=I>0?Math.min(I,1e3):1e3,B=(await u.list({kind:v,limit:_,userId:k})).filter(x=>v!==void 0&&x.kind!==v?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:W,...L})=>L);return Response.json({result:ke({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},an=async(r,s)=>{if(!s.fanOut&&!(s.functionPath!==Et&&s.functionPath!==Xa))return await U(r),s.functionPath===Et?Ne(r,s.args??{}):ae(r,s.args)},sn=Ao({applyGlobals:e.applyGlobals,assertAdmin:K,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:j,resolveForwardContext:D,shardDO:c,streamExportRows:(r,s,u,i)=>Zt(e,r,s,u,i,c),streamingImport:(r,s)=>Io(r,e,s,c),syncGlobals:e.syncGlobals}),Ue=(r,s)=>{const u=r.searchParams.get(s);return u===null||u===""?void 0:u},Ce=r=>{const s=new URL(r.url),u=s.searchParams.get("limit"),i=s.searchParams.get("offset"),h=u===null?void 0:Number.parseInt(u,10),y=i===null?void 0:Number.parseInt(i,10);return{limit:h!==void 0&&Number.isFinite(h)&&h>=0?h:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},rt=()=>{if(l===void 0)throw new d("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},cn=Aa({checkWsAdmin:async r=>O(r)||ms(r,S(),w()),requireSchedulerNamespace:rt,resolveSchedulerStub:r=>(K(r),we(rt(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),dn=xa({assertAdmin:K,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),un=ur({assertAdmin:K,parsePaging:Ce,queryParameter:Ue,readBodyBytes:or,requireAdminOption:j,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),ln=fo({options:e,readJsonBody:te,requireAdminOption:j}),hn=Pa({readJsonBody:te,requireAdminOption:j,vectorIntrospector:e.vectorIntrospector}),fn=Go({kvIntrospector:e.kvIntrospector,readJsonBody:te,requireAdminOption:j}),pn=Er({logArchive:e.logArchive,readJsonBody:te,requireAdminOption:j}),mn=$o({assertAdmin:K,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:j}),wn=r=>{const s=[],u=c??r?.SHARD;if(u!==void 0&&s.push(yr("durable-object:default",u,o)),e.health?.disableBindingProbes!==!0)for(const[i,h]of Object.entries(r??{})){const y=ws(i,h);y!==void 0&&s.push(y)}for(const i of e.health?.probes??[])s.push(i);return s},gn=gr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:wn}),yn=r=>{const s=_=>"args"in _?{..._,args:Ve(_.args)}:_,u=e.schedulerInstanceName??"default",i=()=>we(r,u),h=async(_,A)=>{const B=await i().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new d(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},y=async(_,A)=>await h(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=_=>{const A=_;if(A==null)throw new d("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new d("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})},k=async()=>(await kr(async A=>h(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>s(A)),I=async(_,A,B={})=>{const x=v(A),{id:W}=await y("/schedule",{args:nr("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:_,...x});return W};return{cancel:async _=>await y("/cancel",{id:_}),get:async _=>{const A=await h(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:s(A.record)},list:k,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new d("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new d("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await I(_,A,B)}}},bn=async(r,s,u)=>{const{claims:i,headers:h,userId:y}=await H(r,s,a),v=be(s,r,_=>u.waitUntil?.(_)),k=_=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new d("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(x);const W=await Ee(r,x,ke(B),_,{...h,"x-lunora-system":"1"},v),L=await W.json();if(L.error)throw new d(L.error.message??"shard RPC failed",{code:L.error.code??"INTERNAL",status:W.status});return Ve(L.result)},I=k(o);return{auth:{getIdentity:()=>Promise.resolve(i),userId:y},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=k(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:I,runMutation:I,runQuery:I,...l===void 0?{}:{scheduler:yn(l)},...u.waitUntil===void 0?{}:{waitUntil:u.waitUntil.bind(u)},...e.storage===void 0?{}:{storage:Tr(e.storage(s))}}},_n=async(r,s,u)=>{if(!e.httpRouter)return;const i=await bn(r,s,u);try{return await e.httpRouter.fetch(r,{...s,__lunoraCtx:i},u)}catch(h){return console.error("[lunora] httpRouter (SSR) handler threw:",h),new Response("Internal Server Error",{status:500})}},En=async(r,s,u)=>{if(r.headers.get("Upgrade")!=="websocket")throw new d("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const i=gt(r,se);if(i)return i;const h=u.searchParams.get("shard")??o,{headers:y,identity:v}=await H(r,s,a);await G(v,h);const k=jt(r,y),I=Mt(s,e.shardDO);if(I!==void 0){k.set("x-lunora-shard-binding",I);const _=await ls(c,h);if(_>0){const A=$r(h,Math.floor(Math.random()*_));return p(c,A,new Request(r,{headers:k}),yt(r))}}return p(c,h,new Request(r,{headers:k}))},Rn=async(r,s,u)=>{const{voiceAgents:i}=e;if(i===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const h=gt(r,se);if(h)return h;let y;try{y=decodeURIComponent(u.pathname.slice(xt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(i,y)?i[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const k=u.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:I,identity:_}=await H(r,s,a);if(e.authorizeShard){if(!await Ae(e.authorizeShard({identity:_,shardKey:k})))throw new d("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else C("shard");const A=jt(r,I);return p(v,k,new Request(r,{headers:A}))},Sn=async(r,s,u)=>{if(e.authorizeFanOut){if(!await Ae(e.authorizeFanOut(u,r.table,s)))throw new d("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new d("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 d("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});C("fan-out")},_e=async(r,s)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Sn(r.fanOut,r.functionPath,s);return}await G(s,r.shardKey??o)}},An=(r,s,u)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Z();return}if(e.functions[s]?.kind!=="query"||u.includes(Je)||u.includes(qe))return;const i=yt(r);return i===void 0?void 0:{name:Kr(u,i),region:i}},Tn=async(r,s,u,i,h)=>{const y=An(r,s,i);if(y!==void 0){const v={...h,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},k=Fr(r.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const I=await p(c,y.name,ve(s,u,v),y.region);if(I.status!==421)return I}return p(c,i,ve(s,u,h))},Ee=async(r,s,u,i,h,y)=>{const v=Date.now(),{observability:k,sampling:I}=e,_=We(r),{decision:A,ignoredUpstream:B,trace:x}=fa(r,{...I===void 0?{}:{sampling:I},trustInbound:t(r)});B&&n();const W={...h,"x-lunora-sample-errors":A.keepErrors?"1":"0"};pa(x,W);try{const L=await Tn(r,s,u,i,W);ie(k,{..._,...Bt(x),durationMs:Date.now()-v,functionPath:s,ok:L.ok,shardKey:i,...L.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(L.status)}`,status:L.status}}},y,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const ne=new Response(L.body,{headers:L.headers,status:L.status,statusText:L.statusText});return ne.headers.set("x-lunora-shard-key",i),ne}catch(L){throw ie(k,{..._,...Bt(x),...Te(s,Date.now()-v,L,{shardKey:i})},y,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),L}},On=r=>{if(r.fanOut&&r.shardKey)throw new d("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(r.fanOut||Se(r.functionPath),r.fanOut&&!e.queryCoordinator)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},vn=async(r,s,u)=>{$(r,"POST","RPC");const i=await cs(r);is(s,i),On(i);const h=await an(r,i);if(h!==void 0)return h;const{headers:y,identity:v}=await H(r,s,a);await _e(i,v);const k=ze(i,e);{const I=Date.now(),{observability:_}=e,A=We(r),B=be(s,r,u&&(L=>u.waitUntil?.(L)));if(i.fanOut){const L=e.queryCoordinator;if(!L)throw new d("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ne=await L.fanOut(c,{args:i.args??{},fanOut:i.fanOut,functionPath:i.functionPath,headers:y});return ie(_,{durationMs:Date.now()-I,fanOut:{failed:ne.failed,shards:ne.ok+ne.failed,table:i.fanOut.table},functionPath:i.functionPath,...A,ok:!0},B),Response.json(ne,{headers:{"content-type":"application/json"},status:200})}catch(ne){throw ie(_,{...Te(i.functionPath,Date.now()-I,ne,{fanOut:{table:i.fanOut.table}}),...A},B),ne}}const x=i.shardKey??o,W=()=>Ee(r,i.functionPath,i.args??{},x,y,B);return k&&e.x402Charge?e.x402Charge(r,{functionPath:i.functionPath,price:k.price},W,Qe(u)):W()}},kn=async(r,s,u)=>{$(r,"POST","RPC batch");const i=await te(r),{calls:h}=i;if(!Array.isArray(h))throw new d("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await H(r,s,a),k=mo(h,o);for(const z of k.values())for(const V of z)if(e.functions?.[V.functionPath]?.x402)throw new d(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${Ct}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([z,V])=>V.map(oe=>_e({args:oe.args,functionPath:oe.functionPath,shardKey:z},v))));const{observability:I}=e,_=be(s,r,u&&(z=>u.waitUntil?.(z))),A=We(r),B=[],x=[],W=(z,V,oe,de)=>({body:{error:{code:oe,message:de}},id:z.id,status:V}),L=(z,V,oe,de,fe)=>{for(const Y of z)ie(I,fe(Y),_),B.push(W(Y,V,oe,de))},ne=(z,V,oe,de,fe)=>{for(const Y of z){const pe=de.get(Y.id)??fe,ye=pe<400;ie(I,{durationMs:oe,functionPath:Y.functionPath,...A,ok:ye,shardKey:V,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_)}};await Promise.all([...k.entries()].map(async([z,V])=>{const oe=new Headers(y);oe.set("content-type","application/json");const de=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:oe,method:"POST"}),fe=Date.now();let Y;try{Y=await p(c,z,de)}catch(X){const He=Date.now()-fe,{body:dt}=Qn(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});L(V,502,dt.code,dt.message,Fn=>({...Te(Fn.functionPath,He,X,{shardKey:z}),...A}));return}const pe=Date.now()-fe,ye=Y.headers.get("x-d1-bookmark");ye&&x.push(ye);let Be;try{Be=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;L(V,Y.status,"SHARD_ERROR",X,He=>({durationMs:pe,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:He.functionPath,...A,ok:!1,shardKey:z}));return}const xe=Array.isArray(Be.results)?Be.results:[],$n=new Map(xe.map(X=>[X.id,X.status??Y.status])),Kn=new Set(xe.map(X=>X.id));ne(V,z,pe,$n,Y.status),B.push(...xe);for(const X of V)Kn.has(X.id)||B.push(W(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const it={"content-type":"application/json"},[ct]=x;return x.length===1&&ct!==void 0&&(it["x-d1-bookmark"]=ct),Response.json({results:B},{headers:it,status:200})},In=async(r,s,u,i={},h={})=>{try{const y=u.__lunoraRef;if(typeof y!="string")throw new d("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Se(y);const{headers:v,identity:k}=await H(r,s,a,h.context),I={args:i,functionPath:y,shardKey:h.shardKey};await _e(I,k);const _=h.shardKey??o,A=be(s,r,h.waitUntil),B=()=>Ee(r,y,i,_,v,A),x=ze(I,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:y,price:x.price},B,Qe(h.waitUntil?{waitUntil:h.waitUntil}:h.context)):await B()}catch(y){return ht(y)}},ot=async(r,s,u)=>{const{observability:i}=e,h=Date.now(),y=Ie(16),v=Ie(8),k=Lt(s),I=Ft(y,v,!0);try{const _=await u(I);return ie(i,{durationMs:Date.now()-h,functionPath:r,ok:!0,spanId:v,traceId:y},k),_}catch(_){throw ie(i,{...Te(r,Date.now()-h,_,{}),spanId:v,traceId:y},k),_}finally{pt(i,k)}},at=async(r,s,u,i)=>{R(s);const h=[],y=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[r.cron];if(v)try{await v(r,s,u)}catch(A){h.push(y(A))}const k=await he(r.cron,s,h,y,i),I=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(I)try{await co(e,c,S(),r)}catch(A){h.push(y(A))}if(!v&&k===0&&!I){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=h;if(h.length===1&&_)throw _;if(h.length>1)throw new AggregateError(h,`scheduled("${r.cron}") had ${String(h.length)} failure(s)`)},Pn=async(r,s,u)=>{if(K(r),r.method!=="POST")throw new d("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const i=await r.json().catch(()=>{}),h=typeof i?.cron=="string"?i.cron:"";if(h==="")throw new d("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await at({cron:h,noRetry:()=>{},scheduledTime:Date.now()},s,u),Response.json({cron:h,ok:!0})},Dn=async(r,s,u)=>{if(K(r),r.method!=="POST")throw new d("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.queueHandler)throw new d("no queueHandler configured",{code:"BAD_REQUEST",status:400});const i=await r.json().catch(()=>{}),h=typeof i?.queue=="string"?i.queue:"",v=(Array.isArray(i?.messages)?i.messages:[]).filter(I=>typeof I=="object"&&I!==null&&typeof I.id=="string").map(I=>({body:I.body,id:I.id})),k=await e.queueHandler({messages:v,queue:h},s,u);return Response.json({retry:k?.retry??[]})},Nn=async(r,s)=>{try{const u=r??{},i=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!i||i.length===0)return;await p(c,o,ve(Ya,{outcome:s},{authorization:`Bearer ${i}`,"content-type":"application/json"}))}catch{}},Un=async(r,s,u,i)=>{if(!e.authHandler)return;const h=await e.authHandler(r);if(!h)return;const y=e.authBasePath??Ht;return es(u.pathname,y)&&i.waitUntil?.(Nn(s,h.status>=400?"fail":"ok")),h},Cn=async({args:r,env:s,functionPath:u,request:i,shardKey:h,waitUntil:y})=>{Qt(r,"REST");const v={functionPath:u,...h===void 0?{}:{shardKey:h}},{headers:k,identity:I}=await H(i,s,a);await _e(v,I);const _=h??o,A=be(s,i,y),B=()=>Ee(i,u,r,_,k,A),x=ze(v,e);return x&&e.x402Charge?e.x402Charge(i,{functionPath:u,price:x.price},B,Qe({waitUntil:y})):B()},Bn=rr({functions:e.functions??{},invoke:Cn,readJsonBody:te,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Re=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;gs(Re);const xn={[Qa]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Ma]:(r,s,u)=>En(r,s,u),[Ct]:(r,s,u,i)=>vn(r,s,i),[La]:(r,s,u,i)=>kn(r,s,i),[ja]:(r,s)=>De(r,s),[$a]:(r,s)=>ce(r,s),[Ka]:async r=>{$(r,"POST","ws-token"),K(r);const s=S();if(s===void 0)throw new d("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await Vr(s);return Response.json(u,{headers:{"cache-control":"no-store"}})},...q,...sn,...cn,...dn,...un,...ln,...hn,...fn,...pn,...mn,...gn,...Bn,...Xr({assertAdmin:K,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:te})};let se=wt(e.security),st=!1;const Hn=r=>{st||(st=!0,se=wt(e.security,r??{}))},Ln=async(r,s)=>{Wa(s)&&await U(r)},Mn=(r,s)=>{if(!(s.pathname.startsWith(Pe)||e.authHandler!==void 0&&ts(s.pathname,e.authBasePath??Ht))||r.method!=="POST"&&r.method!=="PUT")return;const i=Number(r.headers.get("content-length")??""),h=Ha[s.pathname]??Gt;if(Number.isFinite(i)&&i>h)throw new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},jn=async(r,s,u)=>{Ye.set(r,u);const i=new URL(r.url);Mn(r,i);const h=await Un(r,s,i,u);if(h)return h;if(Re){const k=`${r.method} ${i.pathname}`,I=Re[k]??Re[i.pathname];if(I)return I(r,s,u)}if(i.pathname===za)return Pn(r,s,u);if(i.pathname===Va)return Dn(r,s,u);const y=xn[i.pathname];if(y)return await Ln(r,i.pathname),y(r,s,i,u);if(e.voiceAgents!==void 0&&i.pathname.startsWith(xt))return Rn(r,s,i);if(i.pathname.startsWith(Pe))return new Response("Not found",{status:404});const v=await _n(r,s,u);return v||new Response("Not found",{status:404})};return{async fetch(r,s,u){e.passThroughOnException&&u.passThroughOnException?.(),Hn(s),R(s);const i=Sr(r,se);if(i)return i;const h=Ar(r,se);if(h)return Me(h,r,se);try{const y=await jn(r,s,u);return Me(y,r,se)}catch(y){return Me(ht(y),r,se)}finally{pt(e.observability,Lt(u))}},async queue(r,s,u){await ot(`queue:${rs(r)}`,u,async i=>{await e.queue?.(r,s,u,{traceparent:i})})},async scheduled(r,s,u){await ot(`cron:${r.cron}`,u,async i=>{await at(r,s,u,i)})},serverQuery:In}},bs=e=>on(e),_s=e=>typeof e=="function"?{fetch:e}:e,Es=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Rs=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},Qs=(e,t)=>{const n=_s(e),{email:o,queue:a,scheduled:c}=Rs(e),l=m=>{const E={...bs({...m,httpRouter:n})};return c!==void 0&&!Es(m)&&(E.scheduled=async(S,T,w)=>{await c(S,T,w)}),a!==void 0&&m.queue===void 0&&(E.queue=async(S,T,w)=>{await a(S,T,w)}),o!==void 0&&(E.email=async(S,T,w)=>{await o(S,T,w)}),E};if(typeof t!="function")return l(t);const f=t;return{fetch:(m,p,E)=>l(f(p)).fetch(m,p,E),queue:(m,p,E)=>l(f(p)).queue?.(m,p,E)??Promise.resolve(),scheduled:(m,p,E)=>l(f(p)).scheduled(m,p,E),serverQuery:(m,p,E,S,T)=>l(f(p)).serverQuery(m,p,E,S,T),...o===void 0?{}:{email:(m,p,E)=>l(f(p)).email?.(m,p,E)??Promise.resolve()}}},Ss=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new d("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},Ws=(e={})=>(t,n,o)=>on(Ss(e,n)).fetch(t,n,o??Wn),zs=e=>e;export{Et as GET_AUTH_AUDIT_LOG_OP,Wn as NOOP_EXECUTION_CONTEXT,Js as composeIdentityResolvers,bs as composeWorker,Ws as createLunoraHandler,on as createWorker,zs as defineRpcEnvelope,ls as probeRelayCount,Ss as resolveLunoraOptions,Ys as routeIdentityResolvers,Qs as withFrameworkWorker};
|