@lunora/runtime 1.0.0-alpha.205 → 1.0.0-alpha.206

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-w6a4qeri.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-CXdh_RxT.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-kkJnK_7t.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BmGOuTrp.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CdACWUQW.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w as B}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as w,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-CAX2UeFy.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as $,memoizeIdentityPerRequest as ee}from"./packem_shared/memoizeIdentity-BNnHkqeF.mjs";import{e as oe,a as te}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as se,combineSinks as ie,consoleSink as pe,otlpSink as ne,pipelineLogSink as ce,webhookSink as me}from"./packem_shared/analyticsEngineSink-BZB-ZYCP.mjs";import{D as Ee,c as Re}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Se,createStaticShardRegistry as le}from"./packem_shared/createQueryCoordinator-es4jrL6Q.mjs";import{applyJurisdiction as ue,resolveShard as _e}from"./packem_shared/applyJurisdiction-D4vryLhj.mjs";import{a as ye,r as Ce,b as Oe}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Ae,b as Le,c as Te,r as he}from"./packem_shared/rest-routes-DQkyqlym.mjs";import{decorateResponse as Pe,enforceOrigin as ge,handleCorsPreflight as ve,resolveSecurity as Ie}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Fe}from"./packem_shared/createShardClient-DIVRljRz.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ne}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Be}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as we,routeIdentityResolvers as ze}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Ee as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,w as HEALTH_PATH,z as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,Be as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ne as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,se as analyticsEngineSink,ue as applyJurisdiction,ye as applyRestCache,Ae as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,Le as buildRestRoutes,ie as combineSinks,we as composeIdentityResolvers,l as composeWorker,pe as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,Re as createPipelineLogReader,Se as createQueryCoordinator,Te as createRestRateLimit,Fe as createShardClient,le as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Pe as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,ge as enforceOrigin,ve as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,ne as otlpSink,H as parseStackFrames,ce as pipelineLogSink,W as presenceProbe,G as r2Sink,Ce as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Ie as resolveSecurity,_e as resolveShard,Oe as restCacheHeaders,he as restSurfaceFromRegistry,ze as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,R as toAirbyteMessages,P as toError,I as toErrorResponse,x as toFivetranResponse,B as webhookExportSink,me as webhookSink,y as withFrameworkWorker};
@@ -1,4 +1,4 @@
1
- import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as sn,b as Pr,f as Dr,g as an,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-CXdh_RxT.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=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}},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,s.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?ln(await fn(s,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},No=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}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const s=Uo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,s=await fn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ho=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[s,i,d]=r;if(s!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${s}.${i}`,h)},N="/_lunora/admin/auth",Lo={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},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(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},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=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,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/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"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/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:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Lo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(jo))r[s]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===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=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},yn=async(e,t,n,r,s)=>{const i=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:d,shardLocalTables:f}=Fo(e,i),h=await Go(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,s,i)=>{for await(const d of await yn(e,t,n,r,i))s(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=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=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.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 d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
1
+ import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{encodeWire as Te,decodeWire as Xe,encodeArgsOrThrow as wr}from"@lunora/wire";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as gr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as yr,e as br,a as _r,E as gt,d as Rr}from"./identity-header-pR617HTs.mjs";import{O as nn,a as rn}from"./origin-paywall-B6eOO67m.mjs";import{o as we,b as on,p as Er,m as Ar,d as Tr,a as Sr,r as Or}from"./otlp-resource-BwFJnvwB.mjs";import{r as vr,f as yt,a as ie,S as bt}from"./observability-DgurIZIR.mjs";import{t as Ir,f as kr}from"./base64-Bl1_r2k1.mjs";import{d as ee,e as ne,M as sn,b as Pr,f as Dr,g as an,w as Nr,h as cn,t as Ur}from"./rest-routes-DQkyqlym.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as ot,BACKUP_KEY_PREFIX as st,isBackupManifestKey as Cr,backupObjectKeyOfManifest as dn,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as Rt,g as Fr,h as Gr}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as $e}from"./HEALTH_PATH-CAX2UeFy.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Hi,routeIdentityResolvers as Li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-es4jrL6Q.mjs";import{resolveShard as ge,applyJurisdiction as Ke}from"./applyJurisdiction-D4vryLhj.mjs";import{resolveSecurity as Et,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as Fe,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},un="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,un),ro=`may not contain the reserved workflow branch-marker key ("${un}")`,oo=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}},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),Tt="x-lunora-want-error-detail",St="x-lunora-error-detail",io=8192,co=e=>{if(!(e instanceof Error))return{message:String(e),name:typeof e};const{code:t}=e;return{...typeof t=="string"?{code:t}:{},message:e.message,name:e.name,...e.stack===void 0?{}:{stack:e.stack.slice(0,io)}}},Ot=e=>{if(e!=null)try{const t=JSON.parse(decodeURIComponent(e));return typeof t?.message=="string"&&typeof t.name=="string"?t:void 0}catch{return}},uo="cf-ray",lo="x-lunora-ray-id",ho=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,fo=e=>e==null?void 0:ho.exec(e.trim())?.[1]?.toLowerCase(),po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(po);const mo=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),wo=-100,go=15,yo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&mo.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>go?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<wo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},vt=e=>{const t=e.cf;return t===void 0?void 0:yo(t)},Ze="::relay::",bo=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",_o=(e,t)=>`${e}${et}${t}`,Ro=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ln=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,d=s<t.length?t.charCodeAt(s):0;r|=i^d}return r===0},Eo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,r);const i=n().catch(d=>{throw e.get(t)===i&&e.delete(t),d});return e.set(t,i),i},at=new TextEncoder,Ao=Array.from({length:32},(e,t)=>t);new RegExp(`[${Ao.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const To=64,So=new Map,hn=async e=>Eo(So,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),To),fn=async(e,t)=>{const n=await hn(e),r=await crypto.subtle.sign("HMAC",n,at.encode(t));return Ir(new Uint8Array(r))},Oo=async(e,t,n)=>{const r=await hn(e);return crypto.subtle.verify("HMAC",r,n,at.encode(t))},vo="/_lunora/scheduler/dispatch",Io="__lunora_relation__:",ko=e=>e.startsWith(Io),pn=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ln(t,s.join(" ").trim())},Po=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?ln(await fn(s,t),r):pn(e,n.adminToken)},Do=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[rn]:nn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},No=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}}},Uo=(e,t,n)=>e?.[n]??t?.[n],Co=(e,t,n,r)=>{const s=Uo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(i=>typeof s[i]=="function")?s:void 0},mn="v1",Bo=6e4,xo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Bo),r=`${mn}.${String(n)}`,s=await fn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Ho=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[s,i,d]=r;if(s!==mn||d.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let h;try{h=kr(d)}catch{return!1}return Oo(e,`${s}.${i}`,h)},N="/_lunora/admin/auth",Lo={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},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(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},wn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},It=e=>{const t=wn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=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,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},jo={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/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"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:wn(e.role)}),http:"POST",method:"createUser"},[`${N}/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:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:It(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ge(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:It(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:kt(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const d=i,f=typeof d.code=="string"?d.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:Lo[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const d=e.getAuthAdmin();if(d===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=d[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const h=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(h,S)},b=i.build(m),T=await t(()=>f(b));return Response.json(i.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(jo))r[s]=d=>n(d,i);return r},Pt="__lunora_admin__:getAuthAuditLog",Dt=e=>typeof e=="string"&&e!==""?e:void 0,Nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,$o=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===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=Dt(r.actorId),d=Dt(r.event),f=Nt(r.sinceSeq),h=Nt(r.limit),m={...i===void 0?{}:{actorId:i},...d===void 0?{}:{event:d},...f===void 0?{}:{sinceSeq:f},...h===void 0?{}:{limit:h}};let b;try{b=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:b};return Response.json({result:Te(T)},{headers:{"content-type":"application/json"},status:200})},tt="__lunora_admin__:copyAuthToJurisdiction",gn="__lunora_admin__:purgeUnpinnedAuth",Ko=e=>async(t,n,r)=>{if(n!==tt&&n!==gn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===tt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:Te(i)},{headers:{"content-type":"application/json"},status:200})},Fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},Go=async(e,t,n,r,s,i)=>{if(n!==void 0&&r.length===0)return[];const d=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:i,headers:t,tables:r}),f=d.shards.filter(h=>h.error);if(f.length>0){const h=f.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(f.length)} of ${String(d.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}return d.shards.flatMap(h=>h.rows??[])},yn=async(e,t,n,r,s)=>{const i=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:d,shardLocalTables:f}=Fo(e,i),h=await Go(t,n,i,f,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=r===void 0||d.length>0;return(async function*(){yield*h,b&&m&&(yield*m({tables:d}))})()},Qo=async(e,t,n,r,s,i)=>{for await(const d of await yn(e,t,n,r,i))s(d)},Wo=new TextEncoder,zo=1e3,bn=10,Vo=200,Ut=8,_n="lunoraBackupCron",Ct=24*1048576,Bt=e=>{const t=e.slice(0,bn).map(r=>dn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Jo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},it=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let d=0;d<zo;d+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const h of f.objects)Cr(h.key)&&h.customMetadata?.[_n]===r&&s.push(h.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((d,f)=>f.localeCompare(d)).slice(n)}},Yo=async(e,t,n,r,s)=>{const{stale:i}=await it(e,t,n,r),d=new Set(s),f=i.filter(k=>d.has(k)),h=f.slice(0,Vo),m=i.length-h.length,b=s.length-f.length;if(h.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const T=[],S=[];for(let k=0;k<h.length;k+=Ut){const w=await Promise.allSettled(h.slice(k,k+Ut).map(async g=>(await e.delete(dn(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?T.push(y.value):S.push(h[k+g])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${Bt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${Bt(S)}`),{deleted:T,failed:S,ignored:b,remaining:m}},qo=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=ot(e.backupPrefix??st),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Xo=async(e,t,n,r,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.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 d={authorization:`Bearer ${r}`,"content-type":"application/json"},f=e.backupTables;let h=0,m=0,b=[];await Qo(e,t,d,f,I=>{const E=Wo.encode(`${JSON.stringify(I)}
2
2
  `);if(h+=1,m+=E.byteLength,m>Ct)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ct)}-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});b.push(E)},n);const S=ot(e.backupPrefix??st),k=new Date(s.scheduledTime).toISOString(),w=Br(S,k),g=Jo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const O={bytes:m,createdAt:k,cron:s.cron,file:w,id:k,rows:h,scheduledTime:s.scheduledTime,sha256:y,...f?{tables:f.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(O,void 0,2)}
3
3
  `,{customMetadata:{[_n]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(i,S,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,bn),H=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${H>0?` (+${String(H)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Zo=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,s=e.backupRetain;if(r===void 0||s===void 0||!Number.isInteger(s)||s<=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 Yo(n,ot(e.backupPrefix??st),s,r,t)},es="/_lunora/admin/backup/retention",ts="/_lunora/admin/backup/prune",ns=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(f,h)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${h} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),s(f,"retention preview"),Response.json(await qo(t),{headers:{"cache-control":"no-store"}})),d=async f=>{M(f,"POST","Backup-prune"),s(f,"prune");const{confirm:h}=await n(f);if(!Array.isArray(h)||h.some(m=>typeof m!="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 Zo(t,h),{headers:{"cache-control":"no-store"}})};return{[ts]:d,[es]:i}},xt=500,rs=(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,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,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}},os=(e,t)=>{if(e.length>xt)throw new c(`RPC batch exceeds the ${String(xt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,i]of e.entries()){const{entry:d,shardKey:f}=rs(i,s,t);if(r.has(d.id))throw new c(`batch call id ${String(d.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(d.id);const h=n.get(f)??[];h.push(d),n.set(f,h)}return n},ss="/_lunora/admin/export",as="/_lunora/admin/import",is="/_lunora/admin/sync",cs="/_lunora/admin/connector/sync",ds="/_lunora/admin/apply",us="/_lunora/admin/export-tap/run",ls=new TextEncoder,hs=async e=>{const n=await ne(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 s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fs=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:d,assertAdmin:f,resolveForwardContext:h,shardDO:m,prepareExportRows:b,streamingImport:T,syncGlobals:S}=e,k=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await hs(E),{headers:F}=await h(E,H),q=await b(F,U.tables),W=new ReadableStream({async pull(z){try{for await(const V of q)z.enqueue(ls.encode(`${JSON.stringify(V)}
4
4
  `));z.close()}catch(V){z.error(V)}}});return new Response(W,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},q=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},W=typeof U.limit=="number"?U.limit:void 0,z=typeof U.globalCursor=="number"?U.globalCursor:0,V=Qe(U.tables),{headers:re}=await h(E,H),Q=V??i(),ce=await d.orchestrateCdcSync(m,{cursors:F,defaultShardKey:n,epochs:q,headers:re,limit:W,tables:Q}),$=S?await S({limit:W,sinceSeq:z}):void 0;return Response.json({global:$,shards:ce.shards},{status:200})},g=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),F=Kr(U.cursor),q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables),{headers:z}=await h(E,H),V=W??i(),re=await d.orchestrateCdcSync(m,{cursors:F.s,defaultShardKey:n,headers:z,limit:q,tables:V}),Q=[],ce={...F.s};let $=!1;for(const se of re.shards)$=Rt(Q,se.changes??[],Gr(q))||$,ce[se.shardKey]=se.cursor;let oe=F.g;if(S){const se=await S({limit:q,sinceSeq:F.g});$=Rt(Q,se.changes,q)||$,oe=se.cursor}const Be=Fr({g:oe,s:ce,v:1}),xe={changes:Q,hasMore:$,nextCursor:Be};return Response.json(xe,{status:200})},y=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const U=await ee(E),q=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),W=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:z}=await h(E,H),V=await d.orchestrateApplyCdc(m,{batches:q,headers:z}),re=W.length>0&&t?await t({changes:W}):0;return Response.json({applied:V.applied+re,failed:V.failed,ok:V.ok},{status:200})},O=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;f(E);const{headers:U}=await h(E,H),F=await T(E,U);return Response.json(F,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},I=async(E,H)=>{const L=me(E,["POST"]);if(L)return L;if(f(E),s===void 0||Object.keys(s).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 U=await ee(E),F=typeof U.sink=="string"?U.sink:void 0,q=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,W=Qe(U.tables);if(F===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const z=s[F];if(z===void 0)throw new c(`Export-tap sink "${F}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(E,H),re=W??i(),Q=await $r({coordinator:d,cursorStore:r,defaultShardKey:n,headers:V,limit:q,shardDO:m,sink:z,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[ds]:y,[cs]:g,[ss]:k,[us]:I,[as]:O,[is]:w}},ps=(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}},ms=(e,t,n,r,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,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}},ws=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],i=new Map;let d=0,f=0;const h=e.body.getReader(),m=new TextDecoder;let b="",T=0;const S=k=>{f+=1;const w=k.trim();if(w.length===0)return;d+=1;const g=ps(w,f);if(!g.ok){r.push(g.error);return}const{doc:y,table:O}=g,I=t.resolveTableSharding?.(O);if(I?.mode.kind==="global"){s.push({doc:y,line:f,table:O});return}const E=ms(y,O,I,n,f);if(!E.ok){r.push(E.error);return}const H=i.get(E.shardKey);H?H.rows.push({doc:y,table:O}):i.set(E.shardKey,{rows:[{doc:y,table:O}],shardKey:E.shardKey,startLine:f})};for(;;){const{done:k,value:w}=await h.read();if(k)break;if(w&&(T+=w.byteLength,T>sn))throw await h.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
@@ -1 +1 @@
1
- import{toErrorBody as I}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-D4vryLhj.mjs";const ke=r=>({listShardKeys(e){return r[e]??[]}}),be=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},B=0,D=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?B:typeof r=="number"?D:J,O=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===B?0:s===D?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=I(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],T=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?k(t.score,n.score):k(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},pe=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return ye(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Ke=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},_e=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:pe(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await T(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await T(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{be as createDefaultShardRegistry,_e as createQueryCoordinator,ke as createStaticShardRegistry,Ke as pruneShardRegistry};
1
+ import{toErrorBody as D}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-D4vryLhj.mjs";const Ke=r=>({listShardKeys(e){return r[e]??[]}}),_e=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},I=0,B=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,T=r=>r==null?I:typeof r=="number"?B:J,O=(r,e)=>{const s=T(r),o=T(e);return s!==o?s<o?-1:1:s===I?0:s===B?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=D(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],E=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e,s)=>{let o=0,t=r.length;for(;o<t;){const n=Math.floor((o+t)/2),a=r[n];a!==void 0&&s(e,a)<0?t=n:o=n+1}return o},pe=(r,e,s)=>{const o=[];for(const t of r){const n=ye(o,t,s);n<e&&(o.splice(n,0,t),o.length>e&&o.pop())}return o},me=(r,e)=>{const s=[];for(const a of r)if(Array.isArray(a))for(const c of a){if(c===null||typeof c!="object")continue;const d=c[e.by],i=typeof d=="number"&&Number.isFinite(d)?d:Number.NEGATIVE_INFINITY;s.push({row:c,score:i})}const o=e.direction??"desc",t=(a,c)=>o==="asc"?k(a.score,c.score):k(c.score,a.score),{k:n}=e;return!Number.isInteger(n)||n<0||2*n>=s.length?(s.sort(t),s.slice(0,n).map(a=>a.row)):pe(s,n,t).map(a=>a.row)},ge=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return me(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Re=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},Ae=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:ge(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await E(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await E(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{_e as createDefaultShardRegistry,Ae as createQueryCoordinator,Ke as createStaticShardRegistry,Re as pruneShardRegistry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.205",
3
+ "version": "1.0.0-alpha.206",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",