@lunora/runtime 1.0.0-alpha.39 → 1.0.0-alpha.40
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.d.mts +136 -20
- package/dist/index.d.ts +136 -20
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{DEFAULT_LOG_COLUMNS-CpZ9kd-q.mjs → DEFAULT_LOG_COLUMNS-B0imn1l0.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_REGISTRY_CACHE_TTL_MS-BBf3mNrD.mjs → DEFAULT_REGISTRY_CACHE_TTL_MS-CsNnfJzB.mjs} +1 -1
- package/dist/packem_shared/HEALTH_PATH-BEE0A_lZ.mjs +1 -0
- package/dist/packem_shared/{LOG_ARCHIVE_PATH-e8U3ftfM.mjs → LOG_ARCHIVE_PATH-DGsEec3K.mjs} +1 -1
- package/dist/packem_shared/{LunoraError-C08OP5Uq.mjs → LunoraError-ByasbDmd.mjs} +1 -1
- package/dist/packem_shared/analyticsEngineSink-CUWYuLHs.mjs +1 -0
- package/dist/packem_shared/{composeIdentityResolvers-DlBbYmBJ.mjs → composeIdentityResolvers-DwE0Jbww.mjs} +1 -1
- package/dist/packem_shared/composeWorker-IO6LYYK2.mjs +6 -0
- package/dist/packem_shared/{createCrossShardRelationCapabilities-B2EKbSEs.mjs → createCrossShardRelationCapabilities-CMWiFA5s.mjs} +1 -1
- package/dist/packem_shared/{createQueryCoordinator-DLsrcOkB.mjs → createQueryCoordinator-DqrEvhPD.mjs} +1 -1
- package/dist/packem_shared/{decorateResponse-C6TZSzID.mjs → decorateResponse-DBIWsRSZ.mjs} +1 -1
- package/dist/packem_shared/emitLogEvent-BcdChmSV.mjs +1 -0
- package/dist/packem_shared/memoizeIdentity-CZGtDc4H.mjs +1 -0
- package/dist/packem_shared/observability-DYnm-d4g.mjs +1 -0
- package/dist/packem_shared/otlp-resource-B-ByO9qo.mjs +1 -0
- package/dist/packem_shared/pipeline-log-reader-DU_CCGDA.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/GET_AUTH_AUDIT_LOG_OP-DmxHQbZT.mjs +0 -1
- package/dist/packem_shared/HEALTH_PATH-DiZqjEGp.mjs +0 -1
- package/dist/packem_shared/analyticsEngineSink-DOoyBx4o.mjs +0 -1
- package/dist/packem_shared/composeWorker-D7Zi6kZR.mjs +0 -6
- package/dist/packem_shared/emitLogEvent-CEbCh6FQ.mjs +0 -1
- package/dist/packem_shared/memoizeIdentity-DRYIK1yT.mjs +0 -1
- package/dist/packem_shared/observability-B0MYwNDB.mjs +0 -1
- package/dist/packem_shared/otlp-resource-cAjGEywx.mjs +0 -1
- package/dist/packem_shared/pipeline-log-reader-tDuvc_Ty.mjs +0 -1
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as Zt,toErrorBody as er}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as tr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{O as Re,m as rr,A as nr,R as or,d as ar,i as sr,s as ir}from"./otlp-resource-cAjGEywx.mjs";import{LunoraError as a,toErrorResponse as ze}from"./LunoraError-C08OP5Uq.mjs";import{GET_AUTH_AUDIT_LOG_OP as dr,buildGetAuthAuditLog as ur}from"./GET_AUTH_AUDIT_LOG_OP-DmxHQbZT.mjs";import{runExportTap as cr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as we}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as lr,durableObjectProbe as hr,d1Probe as pr,presenceProbe as Pe}from"./HEALTH_PATH-DiZqjEGp.mjs";import{wrapResolverWithContract as fr}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{composeIdentityResolvers as fa,routeIdentityResolvers as wa}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{buildLogArchiveAdminRoutes as wr}from"./LOG_ARCHIVE_PATH-e8U3ftfM.mjs";import{o as mr,f as We,a as de}from"./observability-B0MYwNDB.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-uRQLx282.mjs";import{buildRestRoutes as yr}from"./argsFromQuery-0KrWTkNx.mjs";import{resolveSecurity as Je,handleCorsPreflight as gr,enforceOrigin as br,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-C6TZSzID.mjs";const pt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},Or="::relay::",Er=(e,t)=>`${e}${Or}${String(t)}`,Ce=new TextEncoder,Tr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},_r=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.codePointAt(s)??0;return n},Rr=64,Ue=new Map,ft=async e=>{const t=Ue.get(e);if(t)return t;pt(Ue,Rr);const r=crypto.subtle.importKey("raw",Ce.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},Sr=async(e,t)=>{const r=await ft(e),n=await crypto.subtle.sign("HMAC",r,Ce.encode(t));return Tr(new Uint8Array(n))},Ar=async(e,t,r)=>{const n=await ft(e);return crypto.subtle.verify("HMAC",n,r,Ce.encode(t))},wt="v1",Dr=6e4,vr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Dr),n=`${wt}.${String(r)}`,s=await Sr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},kr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[s,i,c]=n;if(s!==wt||c.length===0)return!1;const l=Number(i);if(!Number.isFinite(l)||l<=r)return!1;let y;try{y=_r(c)}catch{return!1}return Ar(e,`${s}.${i}`,y)},v="/_lunora/admin/auth",Ir={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},I=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new a(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},X=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(r[n]=s);return r},Pr={[`${v}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${v}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${v}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${v}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${v}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${v}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${v}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${v}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${v}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${v}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${v}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${v}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${v}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:I(e,"email"),name:I(e,"name"),password:X(e,"password"),role:qe(e.role)}),http:"POST",method:"createUser"},[`${v}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:I(e,"userId")}},http:"POST",method:"updateUser"},[`${v}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:I(e,"userId")}},http:"POST",method:"setRole"},[`${v}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:X(e,"reason"),userId:I(e,"userId")}),http:"POST",method:"banUser"},[`${v}/users/unban`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"unbanUser"},[`${v}/users/password`]:{build:({body:e})=>({newPassword:I(e,"newPassword"),userId:I(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${v}/users/remove`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${v}/users/impersonate`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"impersonateUser"},[`${v}/sessions/revoke`]:{build:({body:e})=>({sessionId:I(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${v}/sessions/revoke-all`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${v}/accounts/unlink`]:{build:({body:e})=>({accountId:I(e,"accountId"),userId:I(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${v}/two-factor/disable`]:{build:({body:e})=>({userId:I(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${v}/passkeys/delete`]:{build:({body:e})=>({passkeyId:I(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${v}/organizations/members/remove`]:{build:({body:e})=>({memberId:I(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${v}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:I(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${v}/organizations/create`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:I(e,"name"),ownerId:X(e,"ownerId"),slug:X(e,"slug")}),http:"POST",method:"createOrganization"},[`${v}/organizations/update`]:{build:({body:e})=>({logo:X(e,"logo"),metadata:Ye(e,"metadata"),name:X(e,"name"),organizationId:I(e,"organizationId"),slug:X(e,"slug")}),http:"POST",method:"updateOrganization"},[`${v}/organizations/remove`]:{build:({body:e})=>({organizationId:I(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${v}/organizations/members/add`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),role:X(e,"role"),userId:I(e,"userId")}),http:"POST",method:"addMember"},[`${v}/organizations/members/invite`]:{build:({body:e})=>({email:I(e,"email"),inviterId:X(e,"inviterId"),organizationId:I(e,"organizationId"),role:X(e,"role")}),http:"POST",method:"inviteMember"},[`${v}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:I(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${v}/organizations/teams/create`]:{build:({body:e})=>({name:I(e,"name"),organizationId:I(e,"organizationId")}),http:"POST",method:"createTeam"},[`${v}/organizations/teams/update`]:{build:({body:e})=>({name:I(e,"name"),teamId:I(e,"teamId")}),http:"POST",method:"updateTeam"},[`${v}/organizations/teams/remove`]:{build:({body:e})=>({teamId:I(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${v}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:I(e,"teamId"),userId:I(e,"userId")}),http:"POST",method:"addTeamMember"},[`${v}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:I(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${v}/organizations/roles/create`]:{build:({body:e})=>({organizationId:I(e,"organizationId"),permission:Xe(e),role:I(e,"role")}),http:"POST",method:"createOrgRole"},[`${v}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:I(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${v}/organizations/roles/remove`]:{build:({body:e})=>({roleId:I(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Nr=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof a)throw i;const c=i,l=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new a("auth admin operation failed",{code:l,status:Ir[l]??500})}},r=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new a(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new a("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const l=c[i.method];if(l===void 0)throw new a(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const y=new URL(s.url),O={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:g=>e.queryParameter(y,g)},D=i.build(O),m=await t(()=>l(D));return Response.json(i.returns==="void"?{ok:!0}:m,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,i]of Object.entries(Pr))n[s]=c=>r(c,i);return n},Ze=500,Ur=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new a("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new a("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new a("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},qr=(e,t)=>{if(e.length>Ze)throw new a(`RPC batch exceeds the ${String(Ze)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:i,shardKey:c}=Ur(s,n,t),l=r.get(c)??[];l.push(i),r.set(c,l)}return r},ge=1048576,ae=async(e,t=ge)=>{if(!e.body)return"";const r=e.body.getReader(),n=new TextDecoder;let s=0,i="";for(;;){const{done:c,value:l}=await r.read();if(c)break;if(l){if(s+=l.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});i+=n.decode(l,{stream:!0})}}return i+=n.decode(),i},$r=async(e,t=ge)=>{if(!e.body)return new ArrayBuffer(0);const r=e.body.getReader(),n=[];let s=0;for(;;){const{done:l,value:y}=await r.read();if(l)break;if(y){if(s+=y.byteLength,s>t)throw await r.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(y)}}const i=new Uint8Array(s);let c=0;for(const l of n)i.set(l,c),c+=l.byteLength;return i.buffer},Z=async(e,t=ge)=>{try{const r=await ae(e,t);return r===""?{}:JSON.parse(r)}catch(r){throw r instanceof a?r:new a("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}},Lr=new TextEncoder,Br=e=>{const t=JSON.stringify(e),r=Lr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},xr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let l=0;l<r.length;l+=1)n[l]=r.codePointAt(l)??0;const s=JSON.parse(new TextDecoder().decode(n)),i=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[l,y]of Object.entries(i))typeof y=="number"&&Number.isFinite(y)&&(c[l]=y);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Cr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:n,table:t}},et=(e,t,r)=>{for(const n of t)e.push(Cr(n));return r!==void 0&&t.length>=r},jr="/_lunora/admin/export",Gr="/_lunora/admin/import",Kr="/_lunora/admin/sync",Mr="/_lunora/admin/connector/sync",Qr="/_lunora/admin/apply",Fr="/_lunora/admin/export-tap/run",zr=new TextEncoder,Wr=async e=>{let t;try{const s=await ae(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new a("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const s of r.tables){if(typeof s!="string"||s.length===0)throw new a("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(s)}return{tables:n}},Hr=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:i,requireAdminOption:c,resolveForwardContext:l,shardDO:y,streamExportRows:O,streamingImport:D,syncGlobals:m}=e,g=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;const K=c(T,i,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),N=await Wr(T),{headers:M}=await l(T,q),Q=new ReadableStream({async pull(Y){const x=G=>{Y.enqueue(zr.encode(`${JSON.stringify(G)}
|
|
2
|
-
`))};try{await O(K,M,N.tables,x),Y.close()}catch(G){Y.error(G)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},p=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;const K=c(T,i,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),M=typeof N.cursors=="object"&&N.cursors!==null?N.cursors:{},Q=typeof N.limit=="number"?N.limit:void 0,Y=typeof N.globalCursor=="number"?N.globalCursor:0,x=Array.isArray(N.tables)?N.tables.filter(ne=>typeof ne=="string"):void 0,{headers:G}=await l(T,q),J=x??s(),re=await K.orchestrateCdcSync(y,{cursors:M,headers:G,limit:Q,tables:J}),se=m?await m({limit:Q,sinceSeq:Y}):void 0;return Response.json({global:se,shards:re.shards},{status:200})},w=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;const K=c(T,i,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),M=xr(N.cursor),Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(ee=>typeof ee=="string"):void 0,{headers:x}=await l(T,q),G=Y??s(),J=await K.orchestrateCdcSync(y,{cursors:M.s,headers:x,limit:Q,tables:G}),re=[],se={...M.s};let ne=!1;for(const ee of J.shards)ne=et(re,ee.changes??[],Q)||ne,se[ee.shardKey]=ee.cursor;let he=M.g;if(m){const ee=await m({limit:Q,sinceSeq:M.g});ne=et(re,ee.changes,Q)||ne,he=ee.cursor}const me=Br({g:he,s:se,v:1}),be={changes:re,hasMore:ne,nextCursor:me};return Response.json(be,{status:200})},_=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;const K=c(T,i,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),N=await Z(T),M=(Array.isArray(N.batches)?N.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),Q=Array.isArray(N.globalChanges)?N.globalChanges:[],{headers:Y}=await l(T,q),x=await K.orchestrateApplyCdc(y,{batches:M,headers:Y}),G=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:x.applied+G,failed:x.failed,ok:x.ok},{status:200})},R=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;c(T,i,{code:"BAD_REQUEST",message:"Import endpoint requires a `queryCoordinator` on the worker"});const{headers:K}=await l(T,q),N=await D(T,K);return Response.json(N,{headers:{"content-type":"application/json"},status:200})},P=async(T,q)=>{const B=we(T,["POST"]);if(B)return B;const K=c(T,i,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new a("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const N=await Z(T),M=typeof N.sink=="string"?N.sink:void 0,Q=typeof N.limit=="number"&&N.limit>0?N.limit:void 0,Y=Array.isArray(N.tables)?N.tables.filter(se=>typeof se=="string"):void 0;if(M===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const x=n[M];if(x===void 0)throw new a(`Export-tap sink "${M}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await l(T,q),J=Y??s(),re=await cr({coordinator:K,cursorStore:r,headers:G,limit:Q,shardDO:y,sink:x,tables:J});return Response.json(re,{headers:{"content-type":"application/json"},status:200})};return{[Qr]:_,[Mr]:w,[jr]:g,[Fr]:P,[Gr]:R,[Kr]:p}},mt=e=>[],Jr=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?n.push(s):r.push(s);return{globalTables:n,shardLocalTables:r}},Vr=async(e,t,r,n,s,i,c)=>{if(n!==void 0&&s.length===0)return;const l=n===void 0?[]:s,y=n===void 0?mt():[],O=l.length>0?l:y,D=await t.orchestrateExport(c,{args:{tables:l},headers:r,tables:O});for(const m of D.shards)if(!m.error)for(const g of m.rows??[])i(g)},tt=async(e,t,r,n,s,i)=>{const{globalTables:c,shardLocalTables:l}=Jr(e,n);await Vr(e,t,r,n,l,s,i);const y=e.exportGlobals;if((n===void 0||c.length>0)&&y){const O=n===void 0?[]:c;for await(const D of y({tables:O}))s(D)}},Yr=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},Xr=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const i=e[r.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:n}},Zr=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],i=new Map;let c=0;const l=e.body.getReader(),y=new TextDecoder;let O="",D=0;const m=g=>{c+=1;const p=g.trim();if(p.length===0)return;const w=Yr(p,c);if(!w.ok){n.push(w.error);return}const{doc:_,table:R}=w,P=t.resolveTableSharding?.(R);if(P?.mode.kind==="global"){s.push({doc:_,line:c,table:R});return}const T=Xr(_,R,P,r,c);if(!T.ok){n.push(T.error);return}const q=i.get(T.shardKey);q?q.rows.push({doc:_,table:R}):i.set(T.shardKey,{rows:[{doc:_,table:R}],shardKey:T.shardKey,startLine:c})};for(;;){const{done:g,value:p}=await l.read();if(g)break;if(p&&(D+=p.byteLength,D>ge))throw await l.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});O+=y.decode(p,{stream:!0});let w=O.indexOf(`
|
|
3
|
-
`);for(;w!==-1;){const _=O.slice(0,w);O=O.slice(w+1),m(_),w=O.indexOf(`
|
|
4
|
-
`)}}return O.length>0&&m(O),{errors:n,globalRows:s,perShard:i}},rt=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},en=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:i,globalRows:c,perShard:l}=await Zr(e,t,s),y={conflicts:0,errors:i,inserted:{}};if(l.size>0){const O=t.queryCoordinator;if(!O)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const D=await O.orchestrateImport(n,{batches:[...l.values()],headers:r});rt(y,D)}if(c.length>0)if(t.importGlobals){const O=c[0]?.line??1,D=await t.importGlobals({rows:c,startLine:O});rt(y,D)}else for(const O of c)y.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:O.line,message:`row targets global table "${O.table}" but no \`importGlobals\` is configured`,table:O.table});return{conflicts:y.conflicts,errors:y.errors,inserted:y.inserted}},$e=e=>typeof e=="object"&&e!==null?e:{},Le=e=>typeof e.kind=="string"?e.kind:"unknown",tn=(e,t)=>{let r=$e(t),n=!1;Le(r)==="optional"&&(n=!0,r=$e(r._meta?.inner));const s=Le(r),i=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof i.tableName=="string"&&(c.table=i.tableName),s==="array"){const l=Le($e(i.inner));l!=="unknown"&&(c.element=l)}return c},rn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>tn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),nn="/_lunora/admin/functions",on="/_lunora/admin/cron-jobs",an="/_lunora/admin/openapi",sn="/_lunora/admin/openrpc",dn="/_lunora/admin/global/tables",un="/_lunora/admin/global/table",cn="/_lunora/admin/global/facet",nt=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:s,value:i}=n;return[{column:s,value:i}]});return r.length===0?void 0:r},ln=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:{}}),hn=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"}),pn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:i}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:rn(P.args),kind:P.kind,path:R}]).toSorted((R,P)=>R.path.localeCompare(P.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},l=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(w).flatMap(([R,P])=>P.map(T=>({args:T.args,cron:R,functionPath:T.functionPath,name:T.name,shardKey:T.shardKey,workflow:T.workflow}))).toSorted((R,P)=>R.name.localeCompare(P.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},y=p=>{if(p.method!=="GET")throw new a("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??ln,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new a("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??hn,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},m=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table");if(R===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const P=await w.readTablePage({...n(p),filters:nt(s(_,"filters")),table:R});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const w=i(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),R=s(_,"table"),P=s(_,"column");if(R===void 0||P===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const T=s(_,"limit"),q=T===void 0?void 0:Number(T),B=await w.facetColumn({column:P,filters:nt(s(_,"filters")),limit:q!==void 0&&Number.isFinite(q)?q:void 0,table:R});return Response.json(B,{headers:{"content-type":"application/json"},status:200})};return{[on]:l,[nn]:c,[cn]:g,[un]:m,[dn]:D,[an]:y,[sn]:O}},fn="/_lunora/admin/kv/namespaces",wn="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",gt=32*1048576,ot=60,mn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=m=>r(m,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=m=>Response.json(m,{headers:{"content-type":"application/json"},status:200}),i=(m,g)=>{const p=new URL(m.url),w=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(w==="")throw new a(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:w}},c=async(m,g)=>{if(!(await m.listNamespaces()).some(p=>p.binding===g))throw new a(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},l=async m=>{if(m.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(m).listNamespaces()})},y=async m=>{if(m.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=new URL(m.url),w=p.searchParams.get("namespace")??"";if(w==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,R=p.searchParams.get("cursor")??void 0,P=p.searchParams.get("limit"),T=P===null?void 0:Number.parseInt(P,10);if(T!==void 0&&(!Number.isInteger(T)||T<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const q=T===void 0?void 0:Math.min(T,1e3);return await c(g,w),s(await g.listKeys({cursor:R,limit:q,namespace:w,prefix:_}))},O={DELETE:async m=>{const g=n(m),p=i(m,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),s({deleted:!0})},GET:async m=>{const g=n(m),p=i(m,"GET");return await c(g,p.namespace),s(await g.getValue(p))},PUT:async m=>{const g=n(m),p=await t(m,gt);if(typeof p.namespace!="string"||p.namespace==="")throw new a("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new a("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new a("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<ot))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const w=Math.floor(Date.now()/1e3)+ot;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<w))throw new a("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=m=>{const g=O[m.method];if(!g)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(m)};return{[fn]:l,[wn]:y,[yt]:D}},yn="/_lunora/migrate",gn="/_lunora/admin/pitr",bn="/_lunora/admin/rank",On="/_lunora/admin/rankpage",En="/_lunora/admin/shard-traffic",Tn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),_n=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Rn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Tn.has(r.functionPath))throw new a("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Sn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new a("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new a("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new a("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new a("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},An=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new a('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Dn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new a("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new a("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new a("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new a("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new a("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},vn=async e=>{let t;try{const s=await ae(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};Dn(r);const n=An(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},kn=async e=>{let t;try{const n=await ae(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},In=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!_n.has(t.functionPath))throw new a("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new a("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Pn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:i,shardDO:c}=e,l=async(g,p)=>{if(g.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Rn(g),{headers:_}=await i(g,p),R=await s.orchestrateMigration(c,{args:w.args,functionPath:w.functionPath,headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},y=async(g,p)=>{if(g.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await Sn(g),{headers:_}=await i(g,p),R=await s.orchestrateRank(c,{headers:_,index:w.index,partitionKey:w.partitionKey,rowId:w.rowId,sortValues:w.sortValues,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await vn(g),{headers:_}=await i(g,p),R=await s.orchestrateRankPage(c,{...w,headers:_});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},D=async(g,p)=>{if(g.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const w=await kn(g),{headers:_}=await i(g,p),R=await s.orchestrateShardTraffic(c,{headers:_,table:w.table});return Response.json(R,{headers:{"content-type":"application/json"},status:200})},m=async(g,p)=>{if(g.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const w=await In(g),{headers:_}=await i(g,p),R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w.args,functionPath:w.functionPath}),headers:_,method:"POST"});return r(c,w.shardKey??t,R)};return{[yn]:l,[gn]:m,[bn]:y,[On]:O,[En]:D}},Nn=1,Un=0,qn=32,$n=512,Ln=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Bn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>$n)return;const r=t.split(",");if(!(r.length>qn)){for(const n of r)if(!Ln.test(n.trim()))return;return t}},xn=e=>{const t=nr(e.headers.get("traceparent"));if(t===void 0)return;const r=Bn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Cn=(e,t={})=>{const r=xn(e),n=t.trustInbound===!0?r:void 0,s=Re(8),i=n?.traceId??Re(16),c=mr(t.sampling,n===void 0?s:i),l=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:l,spanId:s,traceFlags:l?Nn:Un,traceId:i,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},jn=(e,t)=>{t.traceparent=rr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Gn=(e,t)=>{let r;return()=>{if(r===void 0){const n=ir(e),s=t===void 0?void 0:t.cf;r=or(sr(n),ar(n,s))}return r}},Kn="/_lunora/admin/scheduled",Mn="/_lunora/admin/scheduled/status",Qn="/_lunora/admin/scheduled/ws",Fn="/_lunora/admin/scheduled/cancel",zn="/_lunora/admin/scheduled/dead",Wn="/_lunora/admin/scheduled/dead/retry",Hn="/_lunora/admin/scheduled/dead/cancel",Jn=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,i=async m=>{if(m.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async m=>{if(m.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},l=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},y=async m=>{if(m.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(m),p=await m.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async m=>{if(m.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(m).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=m=>async g=>{if(g.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),w=await g.json().catch(()=>{});if(typeof w?.id!="string"||w.id==="")throw new a("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[Fn]:y,[Hn]:D("/dead/cancel"),[zn]:O,[Wn]:D("/dead/retry"),[Kn]:i,[Mn]:c,[Qn]:l}},Vn="/_lunora/admin/storage",Yn="/_lunora/admin/storage/url",Xn="/_lunora/admin/storage/buckets",Zn=10080*60,eo=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:i,storage:c}=e,l=w=>{const _=n(w,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},y=async w=>{const _=i(w,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),R=new URL(w.url),P=await _(n(R,"prefix"),{bucket:n(R,"bucket"),cursor:n(R,"cursor"),...r(w)});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},O=w=>{if(w.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(w),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async w=>{const _=i(w,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),R=new URL(w.url),P=l(R);return await _(P,{bucket:n(R,"bucket")}),Response.json({deleted:!0,key:P},{headers:{"content-type":"application/json"},status:200})},m=async w=>{const _=i(w,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),R=new URL(w.url),P=l(R),T=await s(w),q=w.headers.get("content-type"),B=q===null||q===""?void 0:q,K=await _(P,T,{bucket:n(R,"bucket"),contentType:B});return Response.json(K,{headers:{"content-type":"application/json"},status:200})},g=async w=>{switch(w.method){case"DELETE":return D(w);case"GET":return y(w);case"POST":case"PUT":return m(w);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async w=>{if(w.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=i(w,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),R=new URL(w.url),P=l(R),T=Number(n(R,"expiresIn")??""),q=Number.isFinite(T)&&T>0?Math.min(T,Zn):void 0,B=await _(P,{bucket:n(R,"bucket"),expiresInSeconds:q});return Response.json({key:P,url:B},{headers:{"content-type":"application/json"},status:200})};return{[Xn]:O,[Vn]:g,[Yn]:p}},to=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ro={mtls:e=>to(e,"tlsClientAuth","certVerified")==="SUCCESS"},no=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(ro).find(([t])=>t===e)?.[1]??(()=>!1),oo=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.'))}},ao="/_lunora/admin/vector/indexes",so="/_lunora/admin/vector/query",io=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async i=>{if(i.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{if(i.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new a("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const l=await t(i);if(typeof l.name!="string"||l.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof l.text!="string"||l.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(l.topK!==void 0&&(typeof l.topK!="number"||!Number.isInteger(l.topK)||l.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const y=await c.queryIndex({name:l.name,text:l.text,topK:l.topK});return Response.json(y,{headers:{"content-type":"application/json"},status:200})};return{[ao]:n,[so]:s}},uo="/_lunora/admin/workflows/instances",co="/_lunora/admin/workflows/instance",lo="/_lunora/admin/workflows/status",ho={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},po=e=>e!==null&&Object.hasOwn(ho,e)?e:void 0,at=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},st=()=>{throw new a("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},fo=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,l,y)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(y,"name"),m=po(y.searchParams.get("status"));return Response.json(await O.listInstances({page:at(y,"page"),perPage:at(y,"perPage"),status:m,workflowName:D}))},s=async(c,l,y)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(l);return O?Response.json(await O.getInstance({instanceId:Be(y,"id"),workflowName:Be(y,"name")})):st()},i=async(c,l)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const y=r(l);if(!y)return st();const O=await c.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:D}=O;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await y.setInstanceStatus({action:D,instanceId:O.id,workflowName:O.name}))};return{[co]:s,[uo]:n,[lo]:i}},wo=new TextEncoder,it="/_lunora/rpc",mo="/_lunora/rpc-batch",yo="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Gn(e,t),...r===void 0?{}:{waitUntil:r}}),dt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),xe=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const s=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(s)?void 0:s,scheme:n.protocol.replace(":",""),userAgent:r}},ut="/_lunora/voice/",go="/_lunora/scheduler/dispatch",bo="/_lunora/admin/cron-jobs/run",Oo="/_lunora/admin/ws-token",Eo="/_lunora/admin/",To="/_lunora/migrate",_o="/_lunora/status",Ro=e=>e.startsWith(Eo)||e===To,So=new Set(["1","enabled","on","true","yes"]),Ao=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Do="/api/auth",vo="__lunora_admin__:recordAuthEvent",ko="__lunora_admin__:listPushSubscriptions",Io=["/sign-in","/sign-up","/callback"],Po=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Io.some(s=>n===s||n.startsWith(`${s}/`))},Te=(e,t,r,n)=>{const s=Zt(r),i=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,l=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:i,message:l,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},No=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},ct=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Uo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},s=e.headers.get("authorization"),i=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),l=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),i&&(n.cookie=i),c&&(n["x-d1-bookmark"]=c),l&&(n["x-lunora-mutation-id"]=l),y&&(n["x-lunora-client-id"]=y),O&&(n["x-lunora-client-seq"]=O);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const m=await r(e,t);if(!m||typeof m.userId!="string"||m.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=m.userId;const g=No(m);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...w}=m,_=Object.keys(w).length>0?w:null;return _&&(n["x-lunora-identity"]=JSON.stringify(_)),{claims:_,headers:n,identity:m,userId:p}},qo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),$o=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new a("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new a("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new a("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!qo.has(r.kind))throw new a("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new a("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new a("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Lo=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},lt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new a("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new a(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Bo=async e=>{const t=await ae(e);let r;try{r=JSON.parse(t)}catch{throw new a("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new a("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("RPC `args` must be an object",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new a("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=r,i=$o(s.fanOut),c=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const l=c.table;if(typeof l=="string"&&l!==i.table)throw new a("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=i.table}return{args:c,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},oe=async(e,t,r)=>Se(e,t).fetch(r),_e=new Map,xo=5e3,Co=4096,jo=async(e,t)=>{const r=Date.now(),n=_e.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&_e.delete(t);let s=0;try{const i=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const c=(await i.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return pt(_e,Co),_e.set(t,{expiresMs:r+xo,relayCount:s}),s},Go=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let s=0;s<r;s+=1){const i=s<e.length?e.codePointAt(s)??0:0,c=s<t.length?t.codePointAt(s)??0:0;n|=i^c}return n===0},Ko=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(i);let l="";for(const O of c)l+=String.fromCodePoint(O);const y=btoa(l).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(y,r)},ht=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...s]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,s.join(" ").trim())},Mo=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await kr(t,n)?!0:r?!1:je(t,n)},Qo=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return pr(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},bt=e=>{const t=no(e.trustInboundTraceContext),r=oo(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=fr(e.resolveIdentity,e.identity),i=He(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let l;const y=()=>e.adminToken??l;let O;const D=()=>e.requireEphemeralWsToken??O??!1,m=o=>{const d=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const u=d.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof u=="string"&&u.length>0&&(O=So.has(u.trim().toLowerCase()))}if(l!==void 0||e.adminToken!==void 0)return;const h=d.LUNORA_ADMIN_TOKEN;typeof h=="string"&&h.length>0&&(l=h)},g=new WeakSet,p=o=>ht(o,y())||g.has(o),w=async(o,d)=>{const h=await ue(o,d,e.resolveIdentity);if(g.has(o)&&h.headers.authorization===void 0){const u=y();u!==void 0&&(h.headers.authorization=`Bearer ${u}`)}return h};let _=!1;const R=o=>{if(!e.allowUnauthenticatedShardAccess){const d=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new a(`${o} access is default-denied: configure \`${d}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},P=Pn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:w,shardDO:i}),T=async(o,d,h,u,f)=>{if(e.authorizeShard&&!await e.authorizeShard(null,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};f?.userId!==void 0&&f.userId.length>0&&(b["x-lunora-userid"]=f.userId),f?.identity!==void 0&&f.identity.length>0&&(b["x-lunora-identity"]=f.identity),u!==void 0&&u.length>0&&(b["x-lunora-mutation-id"]=u);const S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:d,functionPath:o}),headers:b,method:"POST"});return oe(i,h,S)},q=async(o,d,h,u)=>{const f=h?.[o];if(!f||typeof f.create!="function")throw new a(`${u} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});await f.create({params:d})},B=async(o,d,h)=>q(o,d.args??{},h,`cron job "${d.name}"`),K=async(o,d)=>{if(o.workflow){await B(o.workflow,o,d);return}if(o.functionPath===void 0)throw new a(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await T(o.functionPath,o.args??{},o.shardKey??n);if(!h.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},N=async(o,d,h,u)=>{const f=e.cronJobs?.[o];if(f)for(const b of f)try{await K(b,d)}catch(S){h.push(u(S))}},M=async(o,d)=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new a("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new a("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const h=await Z(o),u=typeof h.name=="string"?h.name:"";if(u==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const f=Object.values(e.cronJobs).flat().find(b=>b.name===u);if(!f)throw new a(`no cron job named "${u}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await K(f,d),Response.json({name:u,ran:!0},{status:200})},Q=async o=>{const d=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!d||!c||typeof o.id!="string")return;const h=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(h)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:d}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Y=async(o,d)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await ae(o),u=d??{},f=typeof u.LUNORA_SCHEDULER_SECRET=="string"?u.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0),S=o.headers.get("x-lunora-scheduler-signature");let E=!1;if(S&&f?E=await Ko(f,h,S):b&&(E=ht(o,b)),!E)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let A;try{A=JSON.parse(h)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const k=A??{},U=k.args??{};if(typeof k.workflow=="string"&&k.workflow.length>0)return await q(k.workflow,U,d,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof k.functionPath!="string"||k.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const L=typeof k.shardKey=="string"&&k.shardKey.length>0?k.shardKey:n,$=typeof k.id=="string"&&k.id.length>0?k.id:void 0,C=Ao(o),W=await T(k.functionPath,U,L,$,C);return await Q(k),W},x=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},G=(o,d,h)=>{if(x(o),d===void 0)throw new a(h.message,{code:h.code,status:400});return d},J=ur({assertAdmin:x,getReader:()=>e.authAuditReader}),re=async(o,d)=>{x(o);const h=e.notifySubscriptionStore;if(h===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const u=d?.kind,f=d?.userId,b=typeof u=="string"&&u!==""?u:void 0,S=typeof f=="string"&&f!==""?f:void 0,E=(await h.list()).filter(A=>(b===void 0||A.kind===b)&&(S===void 0||A.userId===S)).map(({keys:A,token:k,...U})=>U);return Response.json({subscriptions:E},{headers:{"content-type":"application/json"},status:200})},se=async(o,d)=>{if(!d.fanOut){if(d.functionPath===dr)return J(o,d.args??{});if(d.functionPath===ko)return re(o,d.args)}},ne=Hr({applyGlobals:e.applyGlobals,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>mt(),queryCoordinator:e.queryCoordinator,requireAdminOption:G,resolveForwardContext:w,shardDO:i,streamExportRows:(o,d,h,u)=>tt(e,o,d,h,u,i),streamingImport:(o,d)=>en(o,e,d,i),syncGlobals:e.syncGlobals}),he=(o,d)=>{const h=o.searchParams.get(d);return h===null||h===""?void 0:h},me=o=>{const d=new URL(o.url),h=d.searchParams.get("limit"),u=d.searchParams.get("offset"),f=h===null?void 0:Number.parseInt(h,10),b=u===null?void 0:Number.parseInt(u,10);return{limit:f!==void 0&&Number.isFinite(f)&&f>=0?f:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},be=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},ee=Jn({checkWsAdmin:async o=>p(o)||Mo(o,y(),D()),requireSchedulerNamespace:be,resolveSchedulerStub:o=>(x(o),Se(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Ot=fo({assertAdmin:x,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Et=eo({assertAdmin:x,parsePaging:me,queryParameter:he,readBodyBytes:$r,requireAdminOption:G,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Tt=io({readJsonBody:Z,requireAdminOption:G,vectorIntrospector:e.vectorIntrospector}),_t=mn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:G}),Rt=wr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:G}),St=pn({assertAdmin:x,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:me,queryParameter:he,requireAdminOption:G}),At=o=>{const d=[],h=i??o?.SHARD;if(h!==void 0&&d.push(hr("durable-object",h,n)),e.health?.disableBindingProbes!==!0)for(const[u,f]of Object.entries(o??{})){const b=Qo(u,f);b!==void 0&&d.push(b)}for(const u of e.health?.probes??[])d.push(u);return d},Dt=lr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",isAdmin:p,resolveProbes:At}),vt=async(o,d,h)=>{const{claims:u,headers:f,userId:b}=await ue(o,d,s),S=async(E,A={})=>{const k=E.__lunoraRef;if(typeof k!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const U=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:A,functionPath:k}),headers:f,method:"POST"}),L=await oe(i,n,U),$=await L.json();if($.error)throw new a($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:L.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(u),userId:b},cache:h.cache,fetch:globalThis.fetch.bind(globalThis),runAction:S,runMutation:S,runQuery:S}},kt=async(o,d,h)=>{if(!e.httpRouter)return;const u=await vt(o,d,h);try{return await e.httpRouter.fetch(o,{...d,__lunoraCtx:u},h)}catch(f){return console.error("[lunora] httpRouter (SSR) handler threw:",f),new Response("Internal Server Error",{status:500})}},It=async(o,d,h)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const u=Ve(o,ie);if(u)return u;const f=h.searchParams.get("shard")??n,{headers:b,identity:S}=await ue(o,d,s);if(e.authorizeShard){if(!await e.authorizeShard(S,f))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else f!==n&&R("shard");const E=new Headers(o.headers),A=[...E.keys()];for(const C of A)C.startsWith("x-lunora-")&&E.delete(C);const k=b["x-lunora-userid"],U=b["x-lunora-identity"],L=b["x-lunora-identity-exp"];k!==void 0&&E.set("x-lunora-userid",k),U!==void 0&&E.set("x-lunora-identity",U),L!==void 0&&E.set("x-lunora-identity-exp",L);const $=Go(d,e.shardDO);if($!==void 0){E.set("x-lunora-shard-binding",$);const C=await jo(i,f);if(C>0){const W=Er(f,Math.floor(Math.random()*C));return oe(i,W,new Request(o,{headers:E}))}}return oe(i,f,new Request(o,{headers:E}))},Pt=async(o,d,h)=>{const{voiceAgents:u}=e;if(u===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const f=Ve(o,ie);if(f)return f;let b;try{b=decodeURIComponent(h.pathname.slice(ut.length))}catch{return new Response("Unknown voice agent",{status:404})}const S=Object.hasOwn(u,b)?u[b]:void 0;if(S===void 0)return new Response("Unknown voice agent",{status:404});const E=h.searchParams.get("threadKey");if(E===null||E.length===0)return new Response("Missing threadKey",{status:400});const{headers:A,identity:k}=await ue(o,d,s);if(e.authorizeShard){if(!await e.authorizeShard(k,E))return new Response("Forbidden",{status:403})}else R("shard");const U=new Headers(o.headers);U.delete("x-lunora-userid"),U.delete("x-lunora-identity"),U.delete("x-lunora-identity-exp");const L=A["x-lunora-userid"],$=A["x-lunora-identity"],C=A["x-lunora-identity-exp"];return L!==void 0&&U.set("x-lunora-userid",L),$!==void 0&&U.set("x-lunora-identity",$),C!==void 0&&U.set("x-lunora-identity-exp",C),oe(S,E,new Request(o,{headers:U}))},Nt=async(o,d,h)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(h,o.table,d))throw new a("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(d.startsWith("__lunora_relation__:"))throw new a("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new a("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});R("fan-out")},Oe=async(o,d)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Nt(o.fanOut,o.functionPath,d);return}if(e.authorizeShard){const h=o.shardKey??n;if(!await e.authorizeShard(d,h))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&R("shard")}},Ae=async(o,d,h,u,f,b)=>{const S=Date.now(),{observability:E,sampling:A}=e,k=xe(o),{decision:U,ignoredUpstream:L,trace:$}=Cn(o,{...A===void 0?{}:{sampling:A},trustInbound:t(o)});L&&r();const C={...f,"x-lunora-sample-errors":U.keepErrors?"1":"0"};jn($,C);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:h,functionPath:d}),headers:C,method:"POST"});try{const j=await oe(i,u,W);return de(E,{...k,...dt($),durationMs:Date.now()-S,functionPath:d,ok:j.ok,shardKey:u,...j.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(j.status)}`,status:j.status}}},b,A),j}catch(j){throw de(E,{...k,...dt($),...Te(d,Date.now()-S,j,{shardKey:u})},b,A),j}},Ut=o=>{if(o.fanOut&&o.shardKey)throw new a("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new a("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},qt=async(o,d,h)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await Bo(o);Lo(d,u),Ut(u);const f=await se(o,u);if(f!==void 0)return f;const{headers:b,identity:S}=await ue(o,d,s);await Oe(u,S);const E=lt(u,e);{const A=Date.now(),{observability:k}=e,U=xe(o),L=Ee(d,o,h&&(W=>h.waitUntil?.(W)));if(u.fanOut){const W=e.queryCoordinator;if(!W)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const j=await W.fanOut(i,{args:u.args??{},fanOut:u.fanOut,functionPath:u.functionPath,headers:b});return de(k,{durationMs:Date.now()-A,fanOut:{failed:j.failed,shards:j.ok+j.failed,table:u.fanOut.table},functionPath:u.functionPath,...U,ok:!0},L),Response.json(j,{headers:{"content-type":"application/json"},status:200})}catch(j){throw de(k,{...Te(u.functionPath,Date.now()-A,j,{fanOut:{table:u.fanOut.table}}),...U},L),j}}const $=u.shardKey??n,C=()=>Ae(o,u.functionPath,u.args??{},$,b,L);return E&&e.x402Charge?e.x402Charge(o,{functionPath:u.functionPath,price:E.price},C):C()}},$t=async(o,d,h)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const u=await ae(o);let f;try{f=JSON.parse(u)}catch{throw new a("RPC batch body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(typeof f!="object"||f===null||Array.isArray(f))throw new a("RPC batch body must be an object",{code:"BAD_REQUEST",status:400});const{calls:b}=f;if(!Array.isArray(b))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,s),A=qr(b,n);for(const F of A.values())for(const z of F)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${it}`,{code:"BAD_REQUEST",status:400});await Promise.all([...A.entries()].flatMap(([F,z])=>z.map(te=>Oe({functionPath:te.functionPath,shardKey:F},E))));const{observability:k}=e,U=Ee(d,o,h&&(F=>h.waitUntil?.(F))),L=xe(o),$=[],C=[],W=(F,z,te,ce)=>({body:{error:{code:te,message:ce}},id:F.id,status:z}),j=(F,z,te,ce,pe)=>{for(const H of F)de(k,pe(H),U),$.push(W(H,z,te,ce))},Jt=(F,z,te,ce,pe)=>{for(const H of F){const fe=ce.get(H.id)??pe,ye=fe<400;de(k,{durationMs:te,functionPath:H.functionPath,...L,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(fe)}`,status:fe}}},U)}};await Promise.all([...A.entries()].map(async([F,z])=>{const te=new Headers(S);te.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:te,method:"POST"}),pe=Date.now();let H;try{H=await oe(i,F,ce)}catch(V){const Ie=Date.now()-pe,{body:Fe}=er(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});j(z,502,Fe.code,Fe.message,Xt=>({...Te(Xt.functionPath,Ie,V,{shardKey:F}),...L}));return}const fe=Date.now()-pe,ye=H.headers.get("x-d1-bookmark");ye&&C.push(ye);let ve;try{ve=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;j(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:fe,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...L,ok:!1,shardKey:F}));return}const ke=Array.isArray(ve.results)?ve.results:[],Vt=new Map(ke.map(V=>[V.id,V.status??H.status])),Yt=new Set(ke.map(V=>V.id));Jt(z,F,fe,Vt,H.status),$.push(...ke);for(const V of z)Yt.has(V.id)||$.push(W(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Me={"content-type":"application/json"},[Qe]=C;return C.length===1&&Qe!==void 0&&(Me["x-d1-bookmark"]=Qe),Response.json({results:$},{headers:Me,status:200})},Lt=async(o,d,h,u={},f={})=>{try{const b=h.__lunoraRef;if(typeof b!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:S,identity:E}=await ue(o,d,s);await Oe({functionPath:b,shardKey:f.shardKey},E);const A=f.shardKey??n,k=Ee(d,o,f.waitUntil);return await Ae(o,b,u,A,S,k)}catch(b){return ze(b)}},Bt=1e3,xt=async(o,d)=>{const h=e.backupRetain;if(h===void 0||h<=0)return;const u=[];let f;for(let S=0;S<Bt;S+=1){const E=await o.list({cursor:f,prefix:d});for(const A of E.objects)A.key.endsWith(".manifest.json")&&u.push(A.key);if(!E.truncated||E.cursor===void 0)break;f=E.cursor}const b=u.toSorted((S,E)=>E.localeCompare(S)).slice(h);await Promise.all(b.flatMap(S=>{const E=S.slice(0,-14);return[o.delete(S),o.delete(E)]}))},Ct=async o=>{const d=e.backupStore,h=e.queryCoordinator;if(!d)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!h)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const u=y();if(!u||u.length===0)throw new a("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const f={authorization:`Bearer ${u}`,"content-type":"application/json"},b=e.backupTables;let S=0,E=0;const A=[];await tt(e,h,f,b,W=>{const j=`${JSON.stringify(W)}
|
|
5
|
-
`;S+=1,E+=wo.encode(j).byteLength,A.push(j)},i);const k=e.backupPrefix??"backups/",U=new Date(o.scheduledTime).toISOString(),L=`${k}lunora-backup-${U.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${L}.manifest.json`;await d.put(L,new Blob(A,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const C={bytes:E,createdAt:U,cron:o.cron,file:L,id:U,rows:S,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await d.put($,`${JSON.stringify(C,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await xt(d,k)},Ge=async(o,d,h)=>{const{observability:u}=e,f=Date.now(),b=Re(16),S=Re(8),E=ct(d);try{const A=await h();return de(u,{durationMs:Date.now()-f,functionPath:o,ok:!0,spanId:S,traceId:b},E),A}catch(A){throw de(u,{...Te(o,Date.now()-f,A,{}),spanId:S,traceId:b},E),A}finally{We(u,E)}},jt=async(o,d,h)=>{m(d);const u=[],f=E=>E instanceof Error?E:new Error(String(E)),b=e.crons?.[o.cron];if(b)try{await b(o,d,h)}catch(E){u.push(f(E))}if(await N(o.cron,d,u,f),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Ct(o)}catch(E){u.push(f(E))}const[S]=u;if(u.length===1&&S)throw S;if(u.length>1)throw new AggregateError(u,`scheduled("${o.cron}") had ${String(u.length)} failure(s)`)},Gt=async(o,d)=>{try{const h=o??{},u=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!u||u.length===0)return;const f=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:d},functionPath:vo}),headers:{authorization:`Bearer ${u}`,"content-type":"application/json"},method:"POST"});await oe(i,n,f)}catch{}},Kt=async(o,d,h,u)=>{if(!e.authHandler)return;const f=await e.authHandler(o);if(!f)return;const b=e.authBasePath??Do;return Po(h.pathname,b)&&u.waitUntil?.(Gt(d,f.status>=400?"fail":"ok")),f},Mt=async({args:o,env:d,functionPath:h,request:u,shardKey:f,waitUntil:b})=>{const S={functionPath:h,...f===void 0?{}:{shardKey:f}},{headers:E,identity:A}=await ue(u,d,s);await Oe(S,A);const k=f??n,U=Ee(d,u,b),L=()=>Ae(u,h,o,k,E,U),$=lt(S,e);return $&&e.x402Charge?e.x402Charge(u,{functionPath:h,price:$.price},L):L()},Qt=yr({functions:e.functions??{},invoke:Mt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),De=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Ft={[_o]: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"}}),[yo]:(o,d,h)=>It(o,d,h),[it]:(o,d,h,u)=>qt(o,d,u),[mo]:(o,d,h,u)=>$t(o,d,u),[go]:(o,d)=>Y(o,d),[bo]:(o,d)=>M(o,d),[Oo]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});x(o);const d=y();if(d===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const h=await vr(d);return Response.json(h,{headers:{"cache-control":"no-store"}})},...P,...ne,...ee,...Ot,...Et,...Tt,..._t,...Rt,...St,...Dt,...Qt,...Nr({assertAdmin:x,getAuthAdmin:()=>e.authAdmin,parsePaging:me,queryParameter:he,readJsonBody:Z})};let ie=Je(e.security),Ke=!1;const zt=o=>{Ke||(Ke=!0,ie=Je(e.security,o??{}))},Wt=async(o,d)=>{if(!(e.adminGate===void 0||!Ro(d)))try{await e.adminGate(o)&&g.add(o)}catch{}},Ht=async(o,d,h)=>{const u=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const E=Number(o.headers.get("content-length")??""),A=u.pathname===yt?gt:ge;if(Number.isFinite(E)&&E>A)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const f=await Kt(o,d,u,h);if(f)return f;if(De){const E=`${o.method} ${u.pathname}`,A=De[E]??De[u.pathname];if(A)return A(o,d,h)}const b=Ft[u.pathname];return b?(await Wt(o,u.pathname),b(o,d,u,h)):e.voiceAgents!==void 0&&u.pathname.startsWith(ut)?Pt(o,d,u):await kt(o,d,h)||new Response("Not found",{status:404})};return{async fetch(o,d,h){e.passThroughOnException&&h.passThroughOnException?.(),zt(d),m(d);const u=gr(o,ie);if(u)return u;const f=br(o,ie);if(f)return Ne(f,o,ie);try{const b=await Ht(o,d,h);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,ct(h))}},async queue(o,d,h){await Ge(`queue:${Uo(o)}`,h,async()=>{await e.queue?.(o,d,h)})},async scheduled(o,d,h){await Ge(`cron:${o.cron}`,h,async()=>{await jt(o,d,h)})},serverQuery:Lt}},Fo=e=>bt(e),zo=e=>typeof e=="function"?{fetch:e}:e,Wo=e=>!!(e.crons??e.cronJobs??e.backupCron),ua=(e,t)=>{const r=zo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const l=Fo({...c,httpRouter:r});return n!==void 0&&!Wo(c)?{...l,scheduled:async(y,O,D)=>{await n(y,O,D)}}:l};if(typeof t!="function")return s(t);const i=t;return{fetch:(c,l,y)=>s(i(l)).fetch(c,l,y),queue:(c,l,y)=>s(i(l)).queue?.(c,l,y)??Promise.resolve(),scheduled:(c,l,y)=>s(i(l)).scheduled(c,l,y),serverQuery:(c,l,y,O,D)=>s(i(l)).serverQuery(c,l,y,O,D)}},Ho=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new a("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},ca=(e={})=>(t,r,n)=>bt(Ho(e,r)).fetch(t,r,n??tr),la=e=>e;export{dr as GET_AUTH_AUDIT_LOG_OP,tr as NOOP_EXECUTION_CONTEXT,fa as composeIdentityResolvers,Fo as composeWorker,ca as createLunoraHandler,bt as createWorker,la as defineRpcEnvelope,jo as probeRelayCount,Ho as resolveLunoraOptions,wa as routeIdentityResolvers,ua as withFrameworkWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as a,a as s,f}from"./observability-B0MYwNDB.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v=s=>{const t=new WeakMap;return(r,i)=>{const o=t.get(r);if(o)return o;const e=Promise.resolve(s(r,i));return t.set(r,e),e}},f=s=>{const t=s.headers.get("cookie")??"",r=s.headers.get("authorization")??"";if(!(t===""&&r===""))return`${r}\0${t}`},p=(s,t={})=>{const r=t.ttlMs??5e3,i=Math.max(1,t.maxEntries??500),o=v(s),e=new Map;return(u,l)=>{const n=f(u);if(n===void 0)return o(u,l);const d=Date.now(),c=e.get(n);if(c&&c.expiresAt>d)return c.value;const a=Promise.resolve(o(u,l));for(a.catch(()=>{e.get(n)?.value===a&&e.delete(n)}),e.delete(n),e.set(n,{expiresAt:d+r,value:a});e.size>i;){const m=e.keys().next();if(m.done===!0)break;e.delete(m.value)}return a}};export{p as memoizeIdentity,v as memoizeIdentityPerRequest};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const t=r=>{const e=Number.parseInt(r.slice(0,8),16);return Number.isFinite(e)?e/4294967296:0},o=(r,e=1)=>e>=1?!0:e<=0?!1:t(r)<e,c=(r,e)=>({isTraced:o(e,r?.headRate??1),keepErrors:r?.alwaysSampleErrors??!0}),i=(r,e)=>r.isTraced||r.keepErrors&&e,n=(r,e,s,a)=>{if(r?.onRpc&&!(a!==void 0&&e.traceId!==void 0&&!i(c(a,e.traceId),!e.ok)))try{r.onRpc(e,s)}catch{}},f=(r,e,s)=>{if(r?.onLog)try{r.onLog(e,s)}catch{}},p=(r,e)=>{if(r?.flush)try{r.flush(e)}catch{}};export{n as a,f as e,p as f,c as o};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},O=e=>`${String(Math.round(e))}000000`,b=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(const o of t)r+=o.toString(16).padStart(2,"0");return r},a=/^[0-9a-f]+$/,m=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`,E=e=>{if(e==null)return;const t=e.trim().toLowerCase().split("-"),[r,o,n,s]=t;if(!(t.length<4||r===void 0||r.length!==2||!a.test(r)||r==="ff"||r==="00"&&t.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!a.test(s)||o.length!==32||n.length!==16||!a.test(o)||!a.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},p=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},y=e=>e===void 0?[]:Object.entries(e).map(([t,r])=>p(t,r)),S=(e,t,r)=>{const o={},n=new Map,s=(i,c)=>{const d=i.toLowerCase(),f=n.get(d);f===void 0?(n.set(d,i),o[i]=c):o[f]=c};for(const[i,c]of Object.entries(e))s(i,c);for(const[i,c]of Object.entries(t??{}))s(i,c);return r!==void 0&&r.length>0&&s("authorization",`Bearer ${r}`),o},u=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},l=(e,t)=>{const r={"service.name":e};for(const[o,n]of Object.entries(t??{}))r[o]=n;return Object.entries(r).map(([o,n])=>p(o,n))},N=(e,t,r,o)=>({resourceSpans:[{resource:{attributes:l(r,o)},scopeSpans:[{scope:{name:t},spans:u(e)}]}]}),I=(e,t,r,o)=>({resourceLogs:[{resource:{attributes:l(r,o)},scopeLogs:[{logRecords:u(e),scope:{name:t}}]}]}),V=(e,t,r,o)=>({resourceMetrics:[{resource:{attributes:l(r,o)},scopeMetrics:[{metrics:u(e),scope:{name:t}}]}]}),_=e=>t=>{const r=e?.[t];return typeof r=="string"&&r.length>0?r:void 0},g=(e,t)=>{if(typeof e!="object"||e===null)return;const r=e[t];return typeof r=="string"&&r.length>0?r:void 0},A=e=>{const t={},r=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");r!==void 0&&(t["service.version"]=r);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(t["deployment.environment"]=o),t},L=(e,t)=>{if(!(t!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const r={"cloud.provider":"cloudflare"},o=g(t,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return o!==void 0&&(r["cloud.region"]=o),r},M=(...e)=>{const t={};for(const r of e)if(r!==void 0)for(const[o,n]of Object.entries(r))t[o]=n;return t};export{E as A,V as L,b as O,M as R,I as S,y as V,S as a,v as b,p as c,L as d,O as f,A as i,m,_ as s,C as w,N as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{raw as r,sql as l,desc as x}from"@lunora/bindings/r2sql";const h=["trace","debug","log","info","warn","error","fatal"],g={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},K=500,f=1e4,E=s=>{if(s===void 0||!Number.isFinite(s))return K;const n=Math.floor(s);return n<1?1:n>f?f:n},P=s=>typeof s=="number"?s:Number(s),c=s=>s==null?"":String(s),_=s=>{if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return s}},N=g,D=K,R=(s,n)=>{const e={...g,...n.columnMap},T=n.namespace===void 0?n.table:`${n.namespace}.${n.table}`;return{query:async(t={})=>{const d=E(t.limit),b=Math.min(d+1,f),a=s.from(T).select(r(e.functionPath),r(e.level),r(e.message),r(e.ts),r(e.fields),r(e.shardKey),r(e.userId),r(e.traceId),r(e.spanId));if(t.sinceTs!==void 0&&a.where(l`${r(e.ts)} >= ${t.sinceTs}`),t.untilTs!==void 0&&a.where(l`${r(e.ts)} <= ${t.untilTs}`),t.level!==void 0)a.where(l`${r(e.level)} = ${t.level}`);else if(t.minLevel!==void 0){const o=h.indexOf(t.minLevel),i=o===-1?[...h]:h.slice(o);a.where(l`${r(e.level)} IN ${i}`)}t.functionPath!==void 0&&a.where(l`${r(e.functionPath)} = ${t.functionPath}`),t.functionPathPrefix!==void 0&&a.where(l`${r(e.functionPath)} LIKE ${`${t.functionPathPrefix}%`}`),t.traceId!==void 0&&a.where(l`${r(e.traceId)} = ${t.traceId}`),t.shardKey!==void 0&&a.where(l`${r(e.shardKey)} = ${t.shardKey}`),t.userId!==void 0&&a.where(l`${r(e.userId)} = ${t.userId}`),t.cursor!==void 0&&a.where(l`${r(e.ts)} < ${t.cursor.ts}`),a.orderBy(x(r(e.ts))).limit(b);const{rows:u}=await a.run(),v=u.length>d,O=v?u.slice(0,d):u,I=v?u[d]:void 0,$=O.map(o=>{const i={functionPath:c(o[e.functionPath]),level:c(o[e.level]),message:c(o[e.message]),ts:P(o[e.ts])},m=o[e.fields];m!=null&&(i.fields=_(m));const w=o[e.shardKey];w!=null&&(i.shardKey=c(w));const p=o[e.userId];p!=null&&(i.userId=c(p));const L=o[e.traceId];L!=null&&(i.traceId=c(L));const y=o[e.spanId];return y!=null&&(i.spanId=c(y)),i});return I===void 0?{rows:$}:{nextCursor:{ts:P(I[e.ts])},rows:$}}}};export{N as D,h as L,D as a,R as c};
|