@lunora/runtime 1.0.0-alpha.156 → 1.0.0-alpha.158

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