@lunora/runtime 1.0.0-alpha.53 → 1.0.0-alpha.55
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 +14 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{DEFAULT_LOG_COLUMNS-B0imn1l0.mjs → DEFAULT_LOG_COLUMNS-CzsNuTZj.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_REGISTRY_CACHE_TTL_MS-BclNO0yc.mjs → DEFAULT_REGISTRY_CACHE_TTL_MS-CXdcx3iw.mjs} +1 -1
- package/dist/packem_shared/GET_AUTH_AUDIT_LOG_OP-CS_7Hcs1.mjs +1 -0
- package/dist/packem_shared/{HEALTH_PATH-BpCNEAIa.mjs → HEALTH_PATH-CmjJOkwf.mjs} +1 -1
- package/dist/packem_shared/LOG_ARCHIVE_PATH-5vxNUndx.mjs +1 -0
- package/dist/packem_shared/{LunoraError-ByasbDmd.mjs → LunoraError-C08OP5Uq.mjs} +1 -1
- package/dist/packem_shared/analyticsEngineSink-iIRy11I9.mjs +1 -0
- package/dist/packem_shared/argsFromQuery-Cp8uiYaU.mjs +1 -0
- package/dist/packem_shared/base64-DPPVK6s_.mjs +1 -0
- package/dist/packem_shared/{composeIdentityResolvers-DwE0Jbww.mjs → composeIdentityResolvers-DlBbYmBJ.mjs} +1 -1
- package/dist/packem_shared/composeWorker-DCZ854Rw.mjs +6 -0
- package/dist/packem_shared/{createCrossShardRelationCapabilities-Cr8V1uO_.mjs → createCrossShardRelationCapabilities-BokiysHJ.mjs} +1 -1
- package/dist/packem_shared/createQueryCoordinator-NT5oasVP.mjs +1 -0
- package/dist/packem_shared/createShardClient-D4mXb3vL.mjs +1 -0
- package/dist/packem_shared/{decorateResponse-DBIWsRSZ.mjs → decorateResponse-C6TZSzID.mjs} +1 -1
- package/dist/packem_shared/emitLogEvent-BxJ6jRKW.mjs +1 -0
- package/dist/packem_shared/evict-oldest-C2XU6HBR.mjs +1 -0
- package/dist/packem_shared/identity-header-pdXOyDU4.mjs +1 -0
- package/dist/packem_shared/memoizeIdentity-CX3xEPYw.mjs +1 -0
- package/dist/packem_shared/method-guard-CfF0J5OT.mjs +1 -0
- package/dist/packem_shared/observability-DWlkDJJw.mjs +1 -0
- package/dist/packem_shared/pipeline-log-reader-FF1V32O2.mjs +1 -0
- package/dist/packem_shared/rest-routes--GsO-U9C.mjs +1 -0
- package/dist/packem_shared/toAirbyteMessages-DTk8e2f9.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/LOG_ARCHIVE_PATH-DGsEec3K.mjs +0 -1
- package/dist/packem_shared/analyticsEngineSink-CUWYuLHs.mjs +0 -1
- package/dist/packem_shared/argsFromQuery-7qqVUiD7.mjs +0 -1
- package/dist/packem_shared/composeWorker-BieBiNab.mjs +0 -6
- package/dist/packem_shared/createQueryCoordinator-DQ7dkxS6.mjs +0 -1
- package/dist/packem_shared/createShardClient-gC6COZNn.mjs +0 -1
- package/dist/packem_shared/emitLogEvent-BcdChmSV.mjs +0 -1
- package/dist/packem_shared/identity-header-CDgIrYAz.mjs +0 -1
- package/dist/packem_shared/memoizeIdentity-CZGtDc4H.mjs +0 -1
- package/dist/packem_shared/method-guard-BbuR0VfS.mjs +0 -1
- package/dist/packem_shared/observability-DYnm-d4g.mjs +0 -1
- package/dist/packem_shared/pipeline-log-reader-DU_CCGDA.mjs +0 -1
- package/dist/packem_shared/rest-routes-BJLWmBgK.mjs +0 -1
- package/dist/packem_shared/toAirbyteMessages-DBTuFjb5.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -2769,6 +2769,13 @@ interface StorageObject {
|
|
|
2769
2769
|
contentType?: string;
|
|
2770
2770
|
};
|
|
2771
2771
|
key: string;
|
|
2772
|
+
/**
|
|
2773
|
+
* Lowercase-hex SHA-256, when the object was written with one. R2 reports a
|
|
2774
|
+
* checksum only if the writer supplied it, so this is absent for objects
|
|
2775
|
+
* uploaded before that was wired up — consumers must treat "absent" as "not
|
|
2776
|
+
* reported", never as "does not match".
|
|
2777
|
+
*/
|
|
2778
|
+
sha256?: string;
|
|
2772
2779
|
size: number;
|
|
2773
2780
|
}
|
|
2774
2781
|
/**
|
|
@@ -2881,6 +2888,7 @@ type StorageDeleteFunction = (key: string, options?: {
|
|
|
2881
2888
|
type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
2882
2889
|
bucket?: string;
|
|
2883
2890
|
contentType?: string;
|
|
2891
|
+
sha256?: string;
|
|
2884
2892
|
}) => Promise<{
|
|
2885
2893
|
etag?: string;
|
|
2886
2894
|
key: string;
|
|
@@ -2892,11 +2900,17 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
|
2892
2900
|
* Mints a (signed or public) URL for one object so the admin file browser can
|
|
2893
2901
|
* offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
|
|
2894
2902
|
* a share-link lifetime (the host clamps it); `bucket` selects a named bucket.
|
|
2903
|
+
* `method` and `contentType` are forwarded to the underlying signer and let the
|
|
2904
|
+
* caller mint a presigned PUT URL for large-blob uploads that bypass the
|
|
2905
|
+
* worker's body-size cap (the importer uses this for Convex storage blobs
|
|
2906
|
+
* above the 1 MiB limit).
|
|
2895
2907
|
* Structurally compatible with `@lunora/storage`'s `Storage["getSignedUrl"]`.
|
|
2896
2908
|
*/
|
|
2897
2909
|
type StorageSignedUrlFunction = (key: string, options?: {
|
|
2898
2910
|
bucket?: string;
|
|
2911
|
+
contentType?: string;
|
|
2899
2912
|
expiresInSeconds?: number;
|
|
2913
|
+
method?: "GET" | "PUT";
|
|
2900
2914
|
}) => Promise<string> | string;
|
|
2901
2915
|
/** One `.global()` table plus its row count. Mirrors `@lunora/d1`'s `GlobalTableInfo`. */
|
|
2902
2916
|
interface GlobalTableInfo {
|
package/dist/index.d.ts
CHANGED
|
@@ -2769,6 +2769,13 @@ interface StorageObject {
|
|
|
2769
2769
|
contentType?: string;
|
|
2770
2770
|
};
|
|
2771
2771
|
key: string;
|
|
2772
|
+
/**
|
|
2773
|
+
* Lowercase-hex SHA-256, when the object was written with one. R2 reports a
|
|
2774
|
+
* checksum only if the writer supplied it, so this is absent for objects
|
|
2775
|
+
* uploaded before that was wired up — consumers must treat "absent" as "not
|
|
2776
|
+
* reported", never as "does not match".
|
|
2777
|
+
*/
|
|
2778
|
+
sha256?: string;
|
|
2772
2779
|
size: number;
|
|
2773
2780
|
}
|
|
2774
2781
|
/**
|
|
@@ -2881,6 +2888,7 @@ type StorageDeleteFunction = (key: string, options?: {
|
|
|
2881
2888
|
type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
2882
2889
|
bucket?: string;
|
|
2883
2890
|
contentType?: string;
|
|
2891
|
+
sha256?: string;
|
|
2884
2892
|
}) => Promise<{
|
|
2885
2893
|
etag?: string;
|
|
2886
2894
|
key: string;
|
|
@@ -2892,11 +2900,17 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
|
|
|
2892
2900
|
* Mints a (signed or public) URL for one object so the admin file browser can
|
|
2893
2901
|
* offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
|
|
2894
2902
|
* a share-link lifetime (the host clamps it); `bucket` selects a named bucket.
|
|
2903
|
+
* `method` and `contentType` are forwarded to the underlying signer and let the
|
|
2904
|
+
* caller mint a presigned PUT URL for large-blob uploads that bypass the
|
|
2905
|
+
* worker's body-size cap (the importer uses this for Convex storage blobs
|
|
2906
|
+
* above the 1 MiB limit).
|
|
2895
2907
|
* Structurally compatible with `@lunora/storage`'s `Storage["getSignedUrl"]`.
|
|
2896
2908
|
*/
|
|
2897
2909
|
type StorageSignedUrlFunction = (key: string, options?: {
|
|
2898
2910
|
bucket?: string;
|
|
2911
|
+
contentType?: string;
|
|
2899
2912
|
expiresInSeconds?: number;
|
|
2913
|
+
method?: "GET" | "PUT";
|
|
2900
2914
|
}) => Promise<string> | string;
|
|
2901
2915
|
/** One `.global()` table plus its row count. Mirrors `@lunora/d1`'s `GlobalTableInfo`. */
|
|
2902
2916
|
interface GlobalTableInfo {
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-
|
|
1
|
+
import{toAirbyteMessages as t,toFivetranResponse as a}from"./packem_shared/toAirbyteMessages-DTk8e2f9.mjs";import{composeWorker as i,createLunoraHandler as n,createWorker as p,defineRpcEnvelope as m,resolveLunoraOptions as c,withFrameworkWorker as R}from"./packem_shared/composeWorker-DCZ854Rw.mjs";import{createCrossShardRelationCapabilities as S}from"./packem_shared/createCrossShardRelationCapabilities-BokiysHJ.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as f,SHARD_REGISTRY_DO_NAME as l,createDynamicShardRegistry as x}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-CXdcx3iw.mjs";import{LunoraError as y,toErrorResponse as C}from"./packem_shared/LunoraError-C08OP5Uq.mjs";import{createKvCursorStore as g,createMemoryCursorStore as u,defineExportSink as T,r2Sink as A,runExportTap as h,sanitizeChange as k,webhookExportSink as O}from"./packem_shared/createKvCursorStore-C24tEuYk.mjs";import{HEALTH_PATH as v,HEALTH_READY_PATH as I,buildHealthRoutes as b,d1Probe as F,durableObjectProbe as P,presenceProbe as D}from"./packem_shared/HEALTH_PATH-CmjJOkwf.mjs";import{LOG_ARCHIVE_PATH as G,resolveLogArchiveFromEnv as U}from"./packem_shared/LOG_ARCHIVE_PATH-5vxNUndx.mjs";import{memoizeIdentity as w,memoizeIdentityPerRequest as z}from"./packem_shared/memoizeIdentity-CX3xEPYw.mjs";import{e as W,a as Y}from"./packem_shared/observability-DWlkDJJw.mjs";import{analyticsEngineSink as K,combineSinks as Q,consoleSink as X,otlpSink as j,pipelineLogSink as J,sentrySink as B,webhookSink as Z}from"./packem_shared/analyticsEngineSink-iIRy11I9.mjs";import{D as ee,a as re,c as oe}from"./packem_shared/pipeline-log-reader-FF1V32O2.mjs";import{createQueryCoordinator as ae,createStaticShardRegistry as se,mergeStrategyForAggregate as ie}from"./packem_shared/createQueryCoordinator-NT5oasVP.mjs";import{applyJurisdiction as pe,resolveShard as me}from"./packem_shared/applyJurisdiction-8bzZjAPR.mjs";import{R as Re,d as Ee,o as Se}from"./packem_shared/rest-cache-5unAzdFN.mjs";import{g as fe,E as le,U as xe,p as _e,y as ye}from"./packem_shared/rest-routes--GsO-U9C.mjs";import{decorateResponse as Le,enforceOrigin as ge,handleCorsPreflight as ue,resolveSecurity as Te}from"./packem_shared/decorateResponse-C6TZSzID.mjs";import{createShardClient as he}from"./packem_shared/createShardClient-D4mXb3vL.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Oe}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ve}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as be,routeIdentityResolvers as Fe}from"./packem_shared/composeIdentityResolvers-DlBbYmBJ.mjs";const e="0.0.0";export{ee as DEFAULT_LOG_COLUMNS,re as DEFAULT_LOG_LIMIT,f as DEFAULT_REGISTRY_CACHE_TTL_MS,v as HEALTH_PATH,I as HEALTH_READY_PATH,Oe as LOG_ARCHIVE_NOT_CONFIGURED,G as LOG_ARCHIVE_PATH,y as LunoraError,ve as NOOP_EXECUTION_CONTEXT,l as SHARD_REGISTRY_DO_NAME,e as VERSION,K as analyticsEngineSink,pe as applyJurisdiction,Re as applyRestCache,fe as argsFromQuery,b as buildHealthRoutes,le as buildRestRoutes,Q as combineSinks,be as composeIdentityResolvers,i as composeWorker,X as consoleSink,S as createCrossShardRelationCapabilities,x as createDynamicShardRegistry,g as createKvCursorStore,n as createLunoraHandler,u as createMemoryCursorStore,oe as createPipelineLogReader,ae as createQueryCoordinator,xe as createRestRateLimit,he as createShardClient,se as createStaticShardRegistry,p as createWorker,F as d1Probe,Le as decorateResponse,T as defineExportSink,m as defineRpcEnvelope,P as durableObjectProbe,W as emitLogEvent,Y as emitRpcEvent,ge as enforceOrigin,ue as handleCorsPreflight,w as memoizeIdentity,z as memoizeIdentityPerRequest,ie as mergeStrategyForAggregate,j as otlpSink,J as pipelineLogSink,D as presenceProbe,A as r2Sink,_e as readShardKey,Ee as requestCarriesCredentials,U as resolveLogArchiveFromEnv,c as resolveLunoraOptions,Te as resolveSecurity,me as resolveShard,Se as restCacheHeaders,ye as restSurfaceFromRegistry,Fe as routeIdentityResolvers,h as runExportTap,k as sanitizeChange,B as sentrySink,t as toAirbyteMessages,C as toErrorResponse,a as toFivetranResponse,O as webhookExportSink,Z as webhookSink,R as withFrameworkWorker};
|
package/dist/packem_shared/{DEFAULT_LOG_COLUMNS-B0imn1l0.mjs → DEFAULT_LOG_COLUMNS-CzsNuTZj.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/bindings/r2sql";import{D as r,a as o,c as _}from"./pipeline-log-reader-
|
|
1
|
+
import"@lunora/bindings/r2sql";import{D as r,a as o,c as _}from"./pipeline-log-reader-FF1V32O2.mjs";export{r as DEFAULT_LOG_COLUMNS,o as DEFAULT_LOG_LIMIT,_ as createPipelineLogReader};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"./LunoraError-
|
|
1
|
+
import{LunoraError as n}from"./LunoraError-C08OP5Uq.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-8bzZjAPR.mjs";const m="__lunora_shard_registry__",f=3e4,g="https://shard-registry.internal",l=async r=>await r.json(),T=r=>{const w=r.instanceName??m,o=r.cacheTtlMs??f,a=new Map,p=S(r.namespace,r.jurisdiction);let c;const d=()=>(c??=_(p,w),c),h=async(t,e)=>d().fetch(new Request(`${g}${t}`,{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"})),y=async t=>d().fetch(new Request(`${g}${t}`,{method:"GET"}));return{invalidate(t){t===void 0?a.clear():a.delete(t)},async listShardKeys(t){const e=Date.now(),s=a.get(t);if(s&&s.expiresAt>e)return s.shardKeys;const i=await y(`/list?table=${encodeURIComponent(t)}`);if(!i.ok)throw new n(`shard registry /list returned ${String(i.status)}`);const{shardKeys:u}=await l(i);return o>0&&a.set(t,{expiresAt:e+o,shardKeys:u}),u},async register(t,e){const s=await h("/register",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /register returned ${String(s.status)}`);a.delete(t)},async snapshot(){const t=await y("/snapshot");if(!t.ok)throw new n(`shard registry /snapshot returned ${String(t.status)}`);const{tables:e}=await l(t);return e},async unregister(t,e){const s=await h("/unregister",{shardKey:e,table:t});if(!s.ok)throw new n(`shard registry /unregister returned ${String(s.status)}`);a.delete(t)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,m as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"./LunoraError-C08OP5Uq.mjs";const p="__lunora_admin__:getAuthAuditLog",c=t=>typeof t=="string"&&t!==""?t:void 0,A=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0,v=t=>async(_,e)=>{t.assertAdmin(_);const a=t.getReader();if(a===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const r=c(e.actorId),n=c(e.event),s=A(e.sinceSeq),d=A(e.limit),h={...r===void 0?{}:{actorId:r},...n===void 0?{}:{event:n},...s===void 0?{}:{sinceSeq:s},...d===void 0?{}:{limit:d}};let u;try{u=await a.read(h)}catch(o){throw o instanceof i?o:(console.error("[lunora] auth audit read failed:",o),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const l={entries:u};return Response.json(l,{headers:{"content-type":"application/json"},status:200})};export{p as GET_AUTH_AUDIT_LOG_OP,v as buildGetAuthAuditLog};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"./LunoraError-
|
|
1
|
+
import{LunoraError as k}from"./LunoraError-C08OP5Uq.mjs";import{t as H}from"./method-guard-CfF0J5OT.mjs";import{resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const T="/_lunora/health",P="/_lunora/health/ready",_=a=>a==="liveness"?["liveness"]:a==="readiness"?["readiness"]:["liveness","readiness"];class j{#e=new Map;addChecker(e,s,t){this.#e.set(e,{run:s,types:t.type})}async getReport(e){const s=[...this.#e].filter(([,r])=>e===void 0||r.types.includes(e)),t=await Promise.all(s.map(async([r,o])=>[r,await o.run()]));return{healthy:t.every(([,r])=>r.health.healthy),report:Object.fromEntries(t)}}}const N=a=>{const e=new j,s=new Set;for(const t of a)t.critical&&s.add(t.name),e.addChecker(t.name,async()=>{let r;try{r=await t.check()}catch(o){r={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:r.healthy,...r.message===void 0?{}:{message:r.message}}}},{type:_(t.kind)});return{criticalNames:s,registry:e}},S=(a,e)=>{const s=a.includes(":")?a.slice(0,a.indexOf(":")):"probe",t=(e.get(s)??0)+1;return e.set(s,t),t===1?s:`${s}#${String(t)}`},C=(a,e)=>a?"unhealthy":e?"degraded":"healthy",O=(a,e,s,t,r)=>{const o=[];let d=!1,u=!1;const m=new Map;for(const[h,c]of Object.entries(a)){const n=e.has(h),i=c.health.healthy;u=u||!i,d=d||!i&&n;const l=s==="admin"?h:S(h,m);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name.localeCompare(c.name)),{anyCriticalDown:d,body:{appName:t,appVersion:r,checks:o,status:C(d,u),timestamp:new Date().toISOString()}}},q=a=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:t="public",cacheTtlMs:r,isAdmin:o,resolveProbes:d}=a,u=n=>r!==void 0?r:n==="readiness"?0:t==="public"?5e3:0,m={},h=n=>{if(t==="admin"&&!o(n))throw new k("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const f=H(n,["GET","HEAD"]);if(f)return f;h(n);const y=u(l);if(y>0){const p=m[l];if(p!==void 0&&Date.now()<p.expiresAt)return Response.json(p.body,{headers:{"cache-control":"no-store"},status:p.down?503:200})}const{criticalNames:w,registry:v}=N(d(i)),{healthy:E,report:A}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=O(A,w,t,e,s),b=l==="readiness"?!E:D;return y>0&&(m[l]={body:g,down:b,expiresAt:Date.now()+y}),Response.json(g,{headers:{"cache-control":"no-store"},status:b?503:200})};return{[T]:(n,i)=>c(n,i,"aggregate"),[P]:(n,i)=>c(n,i,"readiness")}},I=(a,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:a}),$=(a,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:a}),B=(a,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:a});export{T as HEALTH_PATH,P as HEALTH_READY_PATH,q as buildHealthRoutes,$ as d1Probe,I as durableObjectProbe,B as presenceProbe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createR2Sql as f}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as _}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as l,c as h}from"./pipeline-log-reader-FF1V32O2.mjs";import{LunoraError as c}from"./LunoraError-C08OP5Uq.mjs";import{r as E}from"./method-guard-CfF0J5OT.mjs";const g="/_lunora/admin/logs/archive",A="LUNORA_LOG_ARCHIVE_TABLE",T="LUNORA_LOG_ARCHIVE_NAMESPACE",Q=e=>{if(typeof e!="object"||e===null)return;const t=e,o=t[A];if(typeof o!="string"||o==="")return;const n=t[T];return{table:o,...typeof n=="string"&&n!==""?{namespace:n}:{}}},O=new Set(l),b=e=>typeof e=="string"&&e!==""?e:void 0,C=(e,t)=>{if(e!==void 0){if(typeof e!="string"||!O.has(e))throw new c(`logs archive: invalid \`${t}\` — expected one of ${l.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},u=(e,t)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new c(`logs archive: invalid \`${t}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},I=e=>{const t={},o=r=>{const i=b(e[r]);i!==void 0&&(t[r]=i)},n=r=>{const i=C(e[r],r);i!==void 0&&(t[r]=i)},s=r=>{const i=u(e[r],r);i!==void 0&&(t[r]=i)};o("functionPath"),o("functionPathPrefix"),o("traceId"),o("shardKey"),o("userId"),n("level"),n("minLevel"),s("sinceTs"),s("untilTs"),s("limit");const a=e.cursor;if(typeof a=="object"&&a!==null){const r=u(a.ts,"cursor.ts");r!==void 0&&(t.cursor={ts:r})}return t},S=e=>{const t=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,o=e.R2_SQL_TOKEN,n=e.R2_SQL_BUCKET,s=[];if((t===void 0||t==="")&&s.push("R2_SQL_ACCOUNT_ID"),(o===void 0||o==="")&&s.push("R2_SQL_TOKEN"),(n===void 0||n==="")&&s.push("R2_SQL_BUCKET"),s.length>0)throw new c(`log archive not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:_,status:400});return{accountId:t,apiToken:o,bucket:n}},P=e=>{const{createReader:t=h,readJsonBody:o,requireAdminOption:n}=e,s=async(a,r)=>{E(a,"POST","Log-archive");const i=n(a,e.logArchive,{code:_,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:d,apiToken:p,bucket:m}=S(r??{}),v=I(await o(a)),L=f({accountId:d,apiToken:p,bucket:m}),R=await t(L,{columnMap:i.columnMap,namespace:i.namespace,table:i.table}).query(v);return Response.json(R,{headers:{"content-type":"application/json"},status:200})};return{[g]:s}};export{_ as LOG_ARCHIVE_NOT_CONFIGURED,g as LOG_ARCHIVE_PATH,P as buildLogArchiveAdminRoutes,Q as resolveLogArchiveFromEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{toErrorBody as t,LunoraError as n}from"@lunora/errors";const a=e=>{const{body:o,redacted:r,status:s}=t(e,{fallbackCode:"INTERNAL",redactedMessage:"Internal error"});return r&&console.error("[lunora] internal error:",e),Response.json({error:o},{headers:{"content-type":"application/json"},status:s})};class u extends n{constructor(o,r){super(r?.code??"INTERNAL",o,{cause:r?.cause,status:r?.status})}toResponse(){return a(this)}}export{u as LunoraError,a as toErrorResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as u,O as E,V as A,f as k,b as _,w as v,a as q,y as B,R as G,h as Q,S as H,L as X}from"./otlp-resource-B-ByO9qo.mjs";const Y=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},F=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:Y(e),Z=e=>{const r=e.maxItems??512,n=e.maxDelayMs??200;let t=[],o,a,p;const h=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},m=async()=>{h();const d=t;t=[];const i=p;a=void 0,p=void 0;try{d.length>0&&await e.export(d)}catch{}finally{i?.()}},f=d=>{a===void 0&&(a=new Promise(i=>{p=i}),o=setTimeout(()=>{m()},n)),d?.(a)};return{add:(d,i)=>{for(t.push(d);t.length>r;)t.shift();f(i),t.length>=r&&m()},flush:async d=>{if(t.length===0){h();return}const i=m();return d?.(i),i},get size(){return t.length}}},ee=(e,r)=>e<r?-1:e>r?1:0,$=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(a=>$(a)).join(",")}]`;const r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype){const a=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,t=Object.keys(n).toSorted(ee),o=[];for(const a of t){const p=n[a];p!==void 0&&o.push(`${JSON.stringify(a)}:${$(p)}`)}return`{${o.join(",")}}`},ne=(e,r)=>{const n=[u(v.functionPath,e.functionPath),u(v.ok,e.ok)];e.method!==void 0&&n.push(u("http.request.method",e.method)),e.path!==void 0&&n.push(u("url.path",e.path)),n.push(u("http.route",e.functionPath)),e.scheme!==void 0&&n.push(u("url.scheme",e.scheme)),e.host!==void 0&&n.push(u("server.address",e.host)),e.port!==void 0&&n.push(u("server.port",e.port)),e.userAgent!==void 0&&n.push(u("user_agent.original",e.userAgent)),e.shardKey!==void 0&&n.push(u(v.shardKey,e.shardKey)),n.push(u("http.response.status_code",e.error?.status??200)),e.error&&n.push(u(v.errorType,e.error.code),u("lunora.error_status",e.error.status)),e.fanOut&&n.push(u("lunora.fanout.table",e.fanOut.table),u("lunora.fanout.shards",e.fanOut.shards),u("lunora.fanout.failed",e.fanOut.failed));const t={attributes:n,endTimeUnixNano:k(r),kind:A.server,name:e.functionPath,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId},spanId:e.spanId??E(8),startTimeUnixNano:k(r-e.durationMs),status:e.ok?{code:1}:{code:2,message:e.error?.message??""},traceId:e.traceId??E(16)};return e.traceFlags!==void 0&&(t.flags=e.traceFlags),e.error&&(t.events=[{attributes:[u("exception.type",e.error.code),u("exception.message",e.error.message)],name:"exception",timeUnixNano:k(r)}]),t},M=(e,r)=>{const n=new Map([[v.functionPath,u(v.functionPath,e.functionPath)]]);e.shardKey!==void 0&&n.set(v.shardKey,u(v.shardKey,e.shardKey)),e.userId!==void 0&&n.set(v.userId,u(v.userId,e.userId)),e.errorType!==void 0&&n.set(v.errorType,u(v.errorType,e.errorType));for(const[t,o]of Object.entries(r??{}))n.set(t,u(t,F(o)));return[...n.values()]},te=e=>{const r={attributes:M({errorType:e.error?.type,functionPath:e.functionPath,shardKey:e.shardKey,userId:e.userId},e.attributes),endTimeUnixNano:k(e.startTs+e.durationMs),kind:A[e.kind??"internal"],name:e.name,parentSpanId:e.parentSpanId,spanId:e.spanId,startTimeUnixNano:k(e.startTs),status:e.ok?{code:1}:{code:2,message:e.error?.message??""},traceId:e.traceId},n=t=>q(Object.fromEntries(Object.entries(t??{}).map(([o,a])=>[o,F(a)])));return e.events!==void 0&&e.events.length>0&&(r.events=e.events.map(t=>({attributes:n(t.attributes),name:t.name,timeUnixNano:k(t.ts)}))),e.links!==void 0&&e.links.length>0&&(r.links=e.links.map(t=>({attributes:n(t.attributes),spanId:t.spanId,traceId:t.traceId}))),r},re=e=>{const r=k(e.ts),n=M({functionPath:e.functionPath,shardKey:e.shardKey},e.attributes),t={asDouble:e.value,attributes:n,timeUnixNano:r};return e.kind==="gauge"?{gauge:{dataPoints:[t]},name:e.name}:e.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:n,bucketCounts:["1"],count:"1",explicitBounds:[],max:e.value,min:e.value,sum:e.value,timeUnixNano:r}]},name:e.name}:{name:e.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},oe=e=>{const r={attributes:M({functionPath:e.functionPath,shardKey:e.shardKey,userId:e.userId},e.fields),body:{stringValue:e.message},severityNumber:_[e.level],severityText:e.level.toUpperCase(),timeUnixNano:k(e.ts)};return e.traceId!==void 0&&(r.traceId=e.traceId),e.spanId!==void 0&&(r.spanId=e.spanId),e.eventName!==void 0&&(r.eventName=e.eventName,r.attributes.push(u("event.name",e.eventName))),r},se=1024,ae=async e=>{const r=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(r).arrayBuffer()},V=async(e,r,n,t)=>{try{const o=JSON.stringify(r),{byteLength:a}=new TextEncoder().encode(o),p=(a<se?fetch(e,{body:o,headers:n,method:"POST"}):ae(o).then(h=>fetch(e,{body:h,headers:{...n,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});t?.(p),await p}catch{}},ie=(e,r,n,t)=>{V(e,r,n,t?.waitUntil).catch(()=>{})},O=(e,r)=>r===!0&&e.ok,ce=e=>e.kind==="metric"?void 0:e.event.traceId,ue=e=>{const r=Map.groupBy(e,t=>ce(t)),n=r.get(void 0)??[];return r.delete(void 0),{byTrace:r,untraced:n}},D=5,de=(e,r,n)=>{if(r===void 0)return e;const{byTrace:t,untraced:o}=ue(e),a=[...o];let p=0,h;for(const[m,f]of t){let d;try{d=r({logs:f.filter(i=>i.kind==="log").map(i=>i.event),rpc:f.filter(i=>i.kind==="rpc").map(i=>i.event),spans:f.filter(i=>i.kind==="span").map(i=>i.event),traceId:m})}catch(i){p+=1,p===1&&(h=i),d=!0}d&&a.push(...f)}return p>0&&n(h,p),a},P=(e,r)=>{if(r===void 0)return e;try{return r(e)??void 0}catch{return}},J=(e,r)=>{if(e.kind==="rpc"){const t=P(e.event,r?.rpc);return t===void 0?void 0:{bucket:"spans",encoded:ne(t,e.endMs)}}if(e.kind==="span"){const t=P(e.event,r?.span);return t===void 0?void 0:{bucket:"spans",encoded:te(t)}}if(e.kind==="log"){const t=P(e.event,r?.log);return t===void 0?void 0:{bucket:"logs",encoded:oe(t)}}const n=P(e.event,r?.metric);return n===void 0?void 0:{bucket:"metrics",encoded:re(n)}},pe=(e={})=>{const{onlyErrors:r}=e;return{onLog:n=>{n.level==="error"||n.level==="fatal"?console.error("[lunora:log]",n.functionPath,n.message):console.log("[lunora:log]",n.functionPath,n.message)},onMetric:n=>{console.log("[lunora:metric]",`${n.name}=${String(n.value)}`,n.kind,n.functionPath)},onRpc:n=>{O(n,r)||(n.ok?console.log("[lunora:rpc]",n):console.error("[lunora:rpc]",n))},onSpan:n=>{const t=n.ok?"ok":`error ${n.error?.type??""}`.trim();console.log("[lunora:span]",n.name,`${String(n.durationMs)}ms`,t,n.functionPath)}}},he=e=>{const{headers:r,onlyErrors:n,transform:t,transformLog:o,url:a}=e,p=B({"content-type":"application/json"},r),h=(m,f)=>{try{const d=fetch(a,{body:JSON.stringify(m),headers:p,method:"POST"}).catch(()=>{});f?.waitUntil&&f.waitUntil(d)}catch{}};return{onLog:(m,f)=>{const d=P(m,o);d!==void 0&&h(d,f)},onRpc:(m,f)=>{if(O(m,n))return;const d=P(m,t);d!==void 0&&h(d,f)}}},fe=e=>{const{capture:r,captureLog:n}=e,t=e.onlyErrors??!0;return{onLog:n?o=>{try{n(o)}catch{}}:void 0,onRpc:o=>{if(!O(o,t))try{r(o)}catch{}}}},me=e=>{const{dataset:r,onlyErrors:n}=e;return{onRpc:t=>{if(!O(t,n))try{r.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},ve=e=>{const{pipeline:r,serializeFields:n}=e;return{onLog:(t,o)=>{try{const a={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(a.fields=n===!0?JSON.stringify(t.fields):t.fields);for(const h of["shardKey","userId","traceId","spanId"])t[h]!==void 0&&(a[h]=t[h]);const p=r.send([a]).catch(()=>{});o?.waitUntil&&o.waitUntil(p)}catch{}}}},ge=e=>{const{batch:r,deploymentEnvironment:n,detectResources:t,endpoint:o,headers:a,onlyErrors:p,postProcessor:h,resourceAttributes:m,serviceNamespace:f,serviceVersion:d,tailSampler:i,token:z}=e,U=e.serviceName??"lunora",K={...d===void 0?{}:{"service.version":d},...f===void 0?{}:{"service.namespace":f},...n===void 0?{}:{"deployment.environment":n},...m},L=new WeakMap,b=c=>{if(t!==!0||c?.resourceAttributes===void 0)return K;const s=L.get(c);if(s!==void 0)return s;const l=G(c.resourceAttributes(),K);return L.set(c,l),l};let S=o;for(;S.endsWith("/");)S=S.slice(0,-1);const R={logs:{url:`${S}/v1/logs`,wrap:X},metrics:{url:`${S}/v1/metrics`,wrap:H},spans:{url:`${S}/v1/traces`,wrap:Q}},j=B({"content-type":"application/json"},a,z);let N=0;const C=(c,s)=>{if(N>=D)return;N+=1;const l=N===D?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(s)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${l}`,c)},W=async c=>{const s=de(c,i,C),l=new Map;for(const g of s){const y=J(g,h);if(y===void 0)continue;const T=$(g.resource);let I=l.get(T);I===void 0&&(I={logs:[],metrics:[],resource:g.resource,spans:[]},l.set(T,I)),I[y.bucket].push(y.encoded)}const w=[];for(const[,g]of l)for(const y of["spans","logs","metrics"])if(g[y].length>0){const{url:T,wrap:I}=R[y];w.push(V(T,I(g[y],"@lunora/runtime",U,g.resource),j))}await Promise.all(w)};if(r===!1){const c=(s,l)=>{const w=J(s,h);if(w!==void 0){const{url:g,wrap:y}=R[w.bucket];ie(g,y(w.encoded,"@lunora/runtime",U,s.resource),j,l)}};return{onLog:(s,l)=>{c({event:s,kind:"log",resource:b(l)},l)},onMetric:(s,l)=>{c({event:s,kind:"metric",resource:b(l)},l)},onRpc:(s,l)=>{O(s,p)||c({endMs:Date.now(),event:s,kind:"rpc",resource:b(l)},l)},onSpan:(s,l)=>{c({event:s,kind:"span",resource:b(l)},l)}}}const x=Z({export:W,...r?.maxDelayMs===void 0?{}:{maxDelayMs:r.maxDelayMs},...r?.maxItems===void 0?{}:{maxItems:r.maxItems}});return{flush:c=>{x.flush(c?.waitUntil).catch(()=>{})},onLog:(c,s)=>{x.add({event:c,kind:"log",resource:b(s)},s?.waitUntil)},onMetric:(c,s)=>{x.add({event:c,kind:"metric",resource:b(s)},s?.waitUntil)},onRpc:(c,s)=>{O(c,p)||x.add({endMs:Date.now(),event:c,kind:"rpc",resource:b(s)},s?.waitUntil)},onSpan:(c,s)=>{x.add({event:c,kind:"span",resource:b(s)},s?.waitUntil)}}},ye=(...e)=>{const r=(n,t)=>{for(const o of e){const a=o[n];if(a)try{a.apply(o,t)}catch{}}};return{flush:n=>{r("flush",[n])},onLog:(n,t)=>{r("onLog",[n,t])},onMetric:(n,t)=>{r("onMetric",[n,t])},onRpc:(n,t)=>{r("onRpc",[n,t])},onSpan:(n,t)=>{r("onSpan",[n,t])}}};export{me as analyticsEngineSink,ye as combineSinks,pe as consoleSink,ge as otlpSink,ve as pipelineLogSink,fe as sentrySink,he as webhookSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./rest-cache-5unAzdFN.mjs";import{g as t,E as o,U as i,p as m,y as R}from"./rest-routes--GsO-U9C.mjs";import"./method-guard-CfF0J5OT.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},o=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let l=0;l<e.length;l+=1)r[l]=e.codePointAt(l)??0;return r},a=t=>n(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");export{n as a,a as l,o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"./LunoraError-
|
|
1
|
+
import{LunoraError as c}from"./LunoraError-C08OP5Uq.mjs";const u=(r,n={})=>{const t=n.onError??"fail-closed";return async(o,e)=>{for(const i of r){let s;try{s=await i(o,e)}catch(a){if(t==="skip")continue;throw a}if(s)return s}return null}},d=r=>{const n=Object.keys(r).filter(t=>t!=="*").toSorted((t,o)=>o.length-t.length);return(t,o)=>{const{pathname:e}=new URL(t.url),i=n.find(a=>e===a||e.startsWith(a.endsWith("/")?a:`${a}/`)),s=i===void 0?r["*"]:r[i];return s===void 0?null:s(t,o)}},f=(r,n)=>n===void 0||r===void 0?r:async(t,o)=>{const e=await r(t,o);if(!e)return e;const i=n.validate(e);if(i.ok)return e;if(n.onInvalid==="reject")throw new c(`identity claims failed the declared contract: ${i.error}`,{code:"UNAUTHENTICATED",status:401});return null};export{u as composeIdentityResolvers,d as routeIdentityResolvers,f as wrapResolverWithContract};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{isLunoraError as lr,toErrorBody as hr}from"@lunora/errors";import{d as bt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as pr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as fr,u as mr}from"./identity-header-pdXOyDU4.mjs";import{O as Te,m as wr,A as gr,R as yr,d as br,i as Er,s as Rr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as _r,w as Rt,e as _t,b as Sr}from"./rest-routes--GsO-U9C.mjs";import{LunoraError as c,toErrorResponse as Je}from"./LunoraError-C08OP5Uq.mjs";import{GET_AUTH_AUDIT_LOG_OP as Or,buildGetAuthAuditLog as Tr}from"./GET_AUTH_AUDIT_LOG_OP-CS_7Hcs1.mjs";import{runExportTap as Ar}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-CfF0J5OT.mjs";import{buildHealthRoutes as vr,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-CmjJOkwf.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{composeIdentityResolvers as Co,routeIdentityResolvers as xo}from"./composeIdentityResolvers-DlBbYmBJ.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-5vxNUndx.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as Ae,applyJurisdiction as Ye}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Xe,handleCorsPreflight as Nr,enforceOrigin as qr,decorateResponse as qe,enforceWebSocketOrigin as Ze}from"./decorateResponse-C6TZSzID.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},St="__lunoraBranch",xr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,St),jr=`may not contain the reserved workflow branch-marker key ("${St}")`,Ge=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let o=0;o<r;o+=1){const d=o<e.length?e.charCodeAt(o):0,l=o<t.length?t.charCodeAt(o):0;n|=d^l}return n===0},Fe=new TextEncoder,Br=Array.from({length:32},(e,t)=>t);new RegExp(`[${Br.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const $r=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Lr=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},Kr=64,Ce=new Map,Ot=async e=>{const t=Ce.get(e);if(t)return t;bt(Ce,Kr);const r=crypto.subtle.importKey("raw",Fe.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},Tt=async(e,t)=>{const r=await Ot(e),n=await crypto.subtle.sign("HMAC",r,Fe.encode(t));return $r(new Uint8Array(n))},Gr=async(e,t,r)=>{const n=await Ot(e);return crypto.subtle.verify("HMAC",n,r,Fe.encode(t))},Fr="::relay::",Qr=(e,t)=>`${e}${Fr}${String(t)}`,At="v1",Mr=6e4,zr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Mr),n=`${At}.${String(r)}`,o=await Tt(e,n);return{expiresAtMs:r,token:`${n}.${o}`}},Wr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[o,d,l]=n;if(o!==At||l.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(l)}catch{return!1}return Gr(e,`${o}.${d}`,w)},D="/_lunora/admin/auth",Hr={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 r=e[t];if(typeof r!="string"||r==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},vt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,xe=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=vt(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},tt=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 r={};for(const[n,o]of Object.entries(t))Array.isArray(o)&&o.every(d=>typeof d=="string")&&(r[n]=o);return r},Jr={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:le(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:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:vt(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:et(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:te(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:te(e,"logo"),metadata:xe(e,"metadata"),name:U(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:xe(e,"metadata"),name:te(e,"name"),organizationId:U(e,"organizationId"),slug:te(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:te(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:te(e,"inviterId"),organizationId:U(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:et(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:tt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:tt(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"}},Vr=e=>{const t=async o=>{try{return await o()}catch(d){if(d instanceof c)throw d;const l=d,h=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new c("auth admin operation failed",{code:h,status:Hr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new c(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=l[d.method];if(h===void 0)throw new c(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const w=new URL(o.url),R={body:d.http==="POST"?await e.readJsonBody(o):{},paging:e.parsePaging(o),query:k=>e.queryParameter(w,k)},I=d.build(R),b=await t(()=>h(I));return Response.json(d.returns==="void"?{ok:!0}:b,{headers:{"content-type":"application/json"},status:200})},n={};for(const[o,d]of Object.entries(Jr))n[o]=l=>r(l,d);return n},rt=500,Yr=(e,t,r)=>{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 n=e;if(typeof n.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},Xr=(e,t)=>{if(e.length>rt)throw new c(`RPC batch exceeds the ${String(rt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:l}=Yr(o,n,t),h=r.get(l)??[];h.push(d),r.set(l,h)}return r},Zr=new TextEncoder,en=e=>{const t=JSON.stringify(e),r=Zr.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},tn=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const o=JSON.parse(new TextDecoder().decode(n)),d=o.s&&typeof o.s=="object"?o.s:{},l={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(l[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:l,v:1}}catch{return t}},rn=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",o=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(o===void 0?{}:{_id:o}),op:n,table:t}},nt=(e,t,r)=>{for(const n of t)e.push(rn(n));return r!==void 0&&t.length>=r},nn="/_lunora/admin/export",an="/_lunora/admin/import",on="/_lunora/admin/sync",sn="/_lunora/admin/connector/sync",cn="/_lunora/admin/apply",dn="/_lunora/admin/export-tap/run",un=new TextEncoder,ln=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const n of t.tables){if(typeof n!="string"||n.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},je=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,hn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:l,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await ln(A),{headers:Q}=await w(A,j),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(un.encode(`${JSON.stringify(X)}
|
|
2
|
+
`))};try{await I(F,Q,P.tables,K),B.close()}catch(X){B.error(X)}}});return new Response(M,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=typeof P.cursors=="object"&&P.cursors!==null?P.cursors:{},M=typeof P.limit=="number"?P.limit:void 0,B=typeof P.globalCursor=="number"?P.globalCursor:0,K=je(P.tables),{headers:X}=await w(A,j),J=K??o(),ne=await F.orchestrateCdcSync(R,{cursors:Q,headers:X,limit:M,tables:J}),he=k?await k({limit:M,sinceSeq:B}):void 0;return Response.json({global:he,shards:ne.shards},{status:200})},_=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=tn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables),{headers:K}=await w(A,j),X=B??o(),J=await F.orchestrateCdcSync(R,{cursors:Q.s,headers:K,limit:M,tables:X}),ne=[],he={...Q.s};let ae=!1;for(const se of J.shards)ae=nt(ne,se.changes??[],M)||ae,he[se.shardKey]=se.cursor;let pe=Q.g;if(k){const se=await k({limit:M,sinceSeq:Q.g});ae=nt(ne,se.changes,M)||ae,pe=se.cursor}const be=en({g:pe,s:he,v:1}),ve={changes:ne,hasMore:ae,nextCursor:be};return Response.json(ve,{status:200})},E=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(A),Q=(Array.isArray(P.batches)?P.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),M=Array.isArray(P.globalChanges)?P.globalChanges:[],{headers:B}=await w(A,j),K=await F.orchestrateApplyCdc(R,{batches:Q,headers:B}),X=M.length>0&&t?await t({changes:M}):0;return Response.json({applied:K.applied+X,failed:K.failed,ok:K.ok},{status:200})},T=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;l(A);const{headers:F}=await w(A,j),P=await b(A,F);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(A,j)=>{const x=we(A,["POST"]);if(x)return x;const F=h(A,d,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(A),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=je(P.tables);if(Q===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new c(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(A,j),J=B??o(),ne=await Ar({coordinator:F,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[cn]:E,[sn]:_,[nn]:p,[dn]:N,[an]:T,[on]:g}},pn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const o of t)e.resolveTableSharding?.(o)?.mode.kind==="global"?n.push(o):r.push(o);return{globalTables:n,shardLocalTables:r}},fn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const l=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of l.shards)if(!h.error)for(const w of h.rows??[])o(w)},at=async(e,t,r,n,o,d)=>{const{globalTables:l,shardLocalTables:h}=pn(e,n);await fn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||l.length>0)&&w)for await(const R of w({tables:l}))o(R)},mn=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},wn=(e,t,r,n,o)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const d=e[r.mode.field];return d==null?{error:{code:"BAD_ROW",line:o,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:n}},gn=async(e,t,r)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let l=0,h=0;const w=e.body.getReader(),R=new TextDecoder;let I="",b=0;const k=p=>{h+=1;const g=p.trim();if(g.length===0)return;l+=1;const _=mn(g,h);if(!_.ok){n.push(_.error);return}const{doc:E,table:T}=_,N=t.resolveTableSharding?.(T);if(N?.mode.kind==="global"){o.push({doc:E,line:h,table:T});return}const A=wn(E,T,N,r,h);if(!A.ok){n.push(A.error);return}const j=d.get(A.shardKey);j?j.rows.push({doc:E,table:T}):d.set(A.shardKey,{rows:[{doc:E,table:T}],shardKey:A.shardKey,startLine:h})};for(;;){const{done:p,value:g}=await w.read();if(p)break;if(g&&(b+=g.byteLength,b>Et))throw await w.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let _=I.indexOf(`
|
|
3
|
+
`);for(;_!==-1;){const E=I.slice(0,_);I=I.slice(_+1),k(E),_=I.indexOf(`
|
|
4
|
+
`)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:l}},ot=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},yn=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:l,perShard:h,received:w}=await gn(e,t,o),R={conflicts:0,errors:d,inserted:{}},I=[];if(t.resolveTableSharding===void 0&&h.size>0&&I.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 b=t.queryCoordinator;if(!b)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});ot(R,k)}if(l.length>0)if(t.importGlobals){const b=l[0]?.line??1,k=await t.importGlobals({rows:l,startLine:b});ot(R,k)}else for(const b of l)R.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:b.line,message:`row targets global table "${b.table}" but no \`importGlobals\` is configured`,table:b.table});return{conflicts:R.conflicts,errors:R.errors,inserted:R.inserted,received:w,...I.length>0?{warnings:I}:{}}},Be=e=>typeof e=="object"&&e!==null?e:{},$e=e=>typeof e.kind=="string"?e.kind:"unknown",bn=(e,t)=>{let r=Be(t),n=!1;$e(r)==="optional"&&(n=!0,r=Be(r._meta?.inner));const o=$e(r),d=r._meta??{},l={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(l.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(l.element=h)}return l},En=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>bn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Rn="/_lunora/admin/functions",_n="/_lunora/admin/cron-jobs",Sn="/_lunora/admin/openapi",On="/_lunora/admin/openrpc",Tn="/_lunora/admin/global/tables",An="/_lunora/admin/global/table",vn="/_lunora/admin/global/facet",st=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:o,value:d}=n;return[{column:o,value:d}]});return r.length===0?void 0:r},kn=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:{}}),In=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"}),Dn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,l=p=>{L(p,"GET","Functions");const g=d(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(g).flatMap(([E,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:En(T.args),kind:T.kind,path:E}]).toSorted((E,T)=>E.path.localeCompare(T.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=p=>{L(p,"GET","Cron-jobs");const g=d(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(g).flatMap(([E,T])=>T.map(N=>({args:N.args,cron:E,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((E,T)=>E.name.localeCompare(T.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??kn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??In,{headers:{"content-type":"application/json"},status:200})),I=async p=>{L(p,"GET","Global-tables");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},b=async p=>{L(p,"GET","Global-table");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),E=o(_,"table");if(E===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await g.readTablePage({...n(p),filters:st(o(_,"filters")),table:E});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},k=async p=>{L(p,"GET","Global-facet");const g=d(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),E=o(_,"table"),T=o(_,"column");if(E===void 0||T===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(_,"limit"),A=N===void 0?void 0:Number(N),j=await g.facetColumn({column:T,filters:st(o(_,"filters")),limit:A!==void 0&&Number.isFinite(A)?A:void 0,table:E});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[_n]:h,[Rn]:l,[vn]:k,[An]:b,[Tn]:I,[Sn]:w,[On]:R}},Pn="/_lunora/admin/kv/namespaces",Un="/_lunora/admin/kv/keys",kt="/_lunora/admin/kv/value",It=32*1048576,it=60,Nn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=b=>r(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),o=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),d=(b,k)=>{const p=new URL(b.url),g=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(g==="")throw new c(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new c(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:g}},l=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new c(`Unknown KV namespace binding \`${k}\``,{code:"NOT_FOUND",status:404})},h=async b=>(L(b,"GET","KV-namespaces"),o({namespaces:await n(b).listNamespaces()})),w=async b=>{L(b,"GET","KV-keys");const k=n(b),p=new URL(b.url),g=p.searchParams.get("namespace")??"";if(g==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,E=p.searchParams.get("cursor")??void 0,T=p.searchParams.get("limit"),N=T===null?void 0:Number.parseInt(T,10);if(N!==void 0&&(!Number.isInteger(N)||N<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const A=N===void 0?void 0:Math.min(N,1e3);return await l(k,g),o(await k.listKeys({cursor:E,limit:A,namespace:g,prefix:_}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await l(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await l(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,It);if(typeof p.namespace!="string"||p.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<it))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+it;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))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 l(k,p.namespace),await k.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),o({ok:!0})}},I=b=>{const k=R[b.method];if(!k)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[Pn]:h,[Un]:w,[kt]:I}},qn="/_lunora/migrate",Cn="/_lunora/admin/pitr",xn="/_lunora/admin/rank",jn="/_lunora/admin/rankpage",Bn="/_lunora/admin/shard-traffic",$n=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Ln=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Kn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!$n.has(t.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Gn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:t.sortValues,table:t.table}},Fn=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}},Qn=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})},Mn=async e=>{const t=await ye(e,"Rank page")??{};Qn(t);const r=Fn(t.directions);return{cursor:typeof t.cursor=="string"?t.cursor:null,directions:r,index:t.index,partitionKey:typeof t.partitionKey=="string"?t.partitionKey:void 0,table:t.table,take:typeof t.take=="number"?t.take:void 0}},zn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Wn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Ln.has(t.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Hn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:l}=e,h=(p,g)=>{if(p.method!=="POST")throw new c(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new c(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const _=h(p,"Migration"),E=await Kn(p),{headers:T}=await d(p,g),N=await _.orchestrateMigration(l,{args:E.args,functionPath:E.functionPath,headers:T,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const _=h(p,"Rank"),E=await Gn(p),{headers:T}=await d(p,g),N=await _.orchestrateRank(l,{headers:T,index:E.index,partitionKey:E.partitionKey,rowId:E.rowId,sortValues:E.sortValues,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const _=h(p,"Rank page"),E=await Mn(p),{headers:T}=await d(p,g),N=await _.orchestrateRankPage(l,{...E,headers:T});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const _=h(p,"Shard-traffic"),E=await zn(p),{headers:T}=await d(p,g),N=await _.orchestrateShardTraffic(l,{headers:T,table:E.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},k=async(p,g)=>{if(L(p,"POST","PITR"),!n(p))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const _=await Wn(p),{headers:E}=await d(p,g),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:_.args,functionPath:_.functionPath}),headers:E,method:"POST"});return r(l,_.shardKey??t,T)};return{[qn]:w,[Cn]:k,[xn]:R,[jn]:I,[Bn]:b}},Jn=1,Vn=0,Yn=32,Xn=512,Zn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ea=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Xn)return;const r=t.split(",");if(!(r.length>Yn)){for(const n of r)if(!Zn.test(n.trim()))return;return t}},ta=e=>{const t=gr(e.headers.get("traceparent"));if(t===void 0)return;const r=ea(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},ra=(e,t={})=>{const r=ta(e),n=t.trustInbound===!0?r:void 0,o=Te(8),d=n?.traceId??Te(16),l=Ur(t.sampling,n===void 0?o:d),h=l.isTraced&&(n===void 0||n.sampled);return{decision:l,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?Jn:Vn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},na=(e,t)=>{t.traceparent=wr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},aa=(e,t)=>{let r;return()=>{if(r===void 0){const n=Rr(e),o=t===void 0?void 0:t.cf;r=yr(Er(n),br(n,o))}return r}},oa="/_lunora/admin/scheduled",sa="/_lunora/admin/scheduled/status",ia="/_lunora/admin/scheduled/ws",ca="/_lunora/admin/scheduled/cancel",da="/_lunora/admin/scheduled/dead",ua="/_lunora/admin/scheduled/dead/retry",la="/_lunora/admin/scheduled/dead/cancel",ha=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new c(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},l=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new c(`${I} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=n(b),p=await b.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new c(`${R} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${w}`,{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async w=>{if(w.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return Ae(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ca]:l("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[la]:l("/dead/cancel","Scheduled dead-letter action"),[da]:d("/dead","Scheduled dead-letter"),[ua]:l("/dead/retry","Scheduled dead-letter action"),[oa]:d("/list","Scheduled-list"),[sa]:d("/status","Scheduler-status"),[ia]:h}},Dt="/_lunora/admin/storage",pa="/_lunora/admin/storage/url",fa="/_lunora/admin/storage/buckets",ma=10080*60,Pt=32*1048576,wa=new Set(["GET","PUT"]),ga=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},ya=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:l}=e,h=g=>{const _=n(g,"key");if(_===void 0)throw new c("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},w=async g=>{const _=d(g,l.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),E=new URL(g.url),T=await _(n(E,"prefix"),{bucket:n(E,"bucket"),cursor:n(E,"cursor"),...r(g)});return Response.json(T,{headers:{"content-type":"application/json"},status:200})},R=g=>(L(g,"GET","Storage-buckets"),t(g),Response.json({buckets:l.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const _=d(g,l.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),E=new URL(g.url),T=h(E);return await _(T,{bucket:n(E,"bucket")}),Response.json({deleted:!0,key:T},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const _=d(g,l.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),E=new URL(g.url),T=h(E),N=await o(g,Pt),A=g.headers.get("content-type"),j=A===null||A===""?void 0:A,x=n(E,"expectedSha256"),F=n(E,"expectedSize");let P;if(x!==void 0||F!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=ga(M);const B=F!==void 0&&N.byteLength!==Number(F),K=x!==void 0&&P!==x.toLowerCase();if(B||K)throw new c("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 Q=await _(T,N,{bucket:n(E,"bucket"),contentType:j,sha256:P});return Response.json(P===void 0?Q:{...Q,sha256:P},{headers:{"content-type":"application/json"},status:200})},k=async g=>{switch(g.method){case"DELETE":return I(g);case"GET":return w(g);case"POST":case"PUT":return b(g);default:throw new c("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const _=d(g,l.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),E=new URL(g.url),T=h(E),N=Number(n(E,"expiresIn")??""),A=Number.isFinite(N)&&N>0?Math.min(N,ma):void 0,j=n(E,"method");if(j!==void 0&&!wa.has(j))throw new c("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const x=j,F=n(E,"contentType"),P=await _(T,{bucket:n(E,"bucket"),contentType:F,expiresInSeconds:A,method:x});return Response.json({key:T,url:P},{headers:{"content-type":"application/json"},status:200})};return{[fa]:R,[Dt]:k,[pa]:p}},ba=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},ct={mtls:e=>ba(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ct,e)?ct[e]:void 0)??(()=>!1),Ra=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},_a="/_lunora/admin/vector/indexes",Sa="/_lunora/admin/vector/query",Oa=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const l=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await l.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const l=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(l.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(d);if(typeof h.name!="string"||h.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await l.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[_a]:n,[Sa]:o}},Ta="/_lunora/admin/workflows/instances",Aa="/_lunora/admin/workflows/instance",va="/_lunora/admin/workflows/status",ka={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Ia=e=>e!==null&&Object.hasOwn(ka,e)?e:void 0,dt=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Le=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ut=()=>{throw new c("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Da=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(l,h,w)=>{L(l,"GET","Workflows instances"),t(l);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=Ia(w.searchParams.get("status"));return Response.json(await R.listInstances({page:dt(w,"page"),perPage:dt(w,"perPage"),status:b,workflowName:I}))},o=async(l,h,w)=>{L(l,"GET","Workflows instance"),t(l);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ut()},d=async(l,h)=>{L(l,"POST","Workflows status"),t(l);const w=r(h);if(!w)return ut();const R=await l.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:I}=R;if(I!=="pause"&&I!=="resume"&&I!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await w.setInstanceStatus({action:I,instanceId:R.id,workflowName:R.name}))};return{[Aa]:o,[Ta]:n,[va]:d}},Pa={[kt]:It,[Dt]:Pt},Ua=new TextEncoder,lt="/_lunora/rpc",Na="/_lunora/rpc-batch",qa="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:aa(e,t),...r===void 0?{}:{waitUntil:r}}),ht=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},pt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Ke=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const o=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(o)?void 0:o,scheme:n.protocol.replace(":",""),userAgent:r}},ft="/_lunora/voice/",Ca="/_lunora/scheduler/dispatch",xa="/_lunora/admin/cron-jobs/run",ja="/_lunora/admin/ws-token",Ba="/_lunora/admin/",$a="/_lunora/migrate",La="/_lunora/status",Ka=e=>e.startsWith(Ba)||e===$a,Ga=new Set(["1","enabled","on","true","yes"]),Fa=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Qa="/api/auth",Ma="__lunora_admin__:recordAuthEvent",za="__lunora_admin__:listPushSubscriptions",Wa=["/sign-in","/sign-up","/callback"],Ha=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Wa.some(o=>n===o||n.startsWith(`${o}/`))},_e=(e,t,r,n)=>{const o=lr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",l=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:l},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ja=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},mt=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"},de=async(e,t,r)=>{const n={"content-type":"application/json"},o=e.headers.get("authorization"),d=e.headers.get("cookie"),l=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),w=e.headers.get("x-lunora-client-id"),R=e.headers.get("x-lunora-client-seq");o&&(n.authorization=o),d&&(n.cookie=d),l&&(n["x-d1-bookmark"]=l),h&&(n["x-lunora-mutation-id"]=h),w&&(n["x-lunora-client-id"]=w),R&&(n["x-lunora-client-seq"]=R);const I=e.headers.get("cf-connecting-ip");if(I&&(n["x-lunora-client-ip"]=I),!r)return{claims:null,headers:n,identity:null,userId:null};const b=await r(e,t);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=fr(b.userId);const k=Ja(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,_=Object.keys(g).length>0?g:null;return _&&(n["x-lunora-identity"]=mr(_)),{claims:_,headers:n,identity:b,userId:p}},Ya=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Xa=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 r=t.merge;if(typeof r.kind!="string"||!Ya.has(r.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Za=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},wt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new 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 r}},eo=async e=>{const t=await Rt(e);let r;try{r=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&_t(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=Xa(o.fanOut),l=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=l.table;if(typeof h=="string"&&h!==d.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});l.table=d.table}return{args:l,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>Ae(e,t).fetch(r),Se=new Map,to=5e3,ro=4096,no=async(e,t)=>{const r=Date.now(),n=Se.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Se.delete(t);let o=0;try{const d=await Ae(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const l=(await d.json()).relayCount;typeof l=="number"&&l>0&&(o=Math.floor(l))}}catch{o=0}return bt(Se,ro),Se.set(t,{expiresMs:r+to,relayCount:o}),o},ao=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,r])=>r===t)?.[0]},Oe=(e,t,r)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:r,method:"POST"}),oo=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],gt=(e,t)=>{for(const r of oo){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},so=async(e,t,r)=>e.length===0||r.length===0?!1:Ge(await Tt(e,t),r),yt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...o]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:Ge(t,o.join(" ").trim())},io=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await Wr(t,n)?!0:r?!1:Ge(t,n)},co=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Ir(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Ne(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Ne(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Ne(`hyperdrive:${e}`,!0)},Ut=e=>{const t=Ea(e.trustInboundTraceContext),r=Ra(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),l=e.schedulerDO===void 0?void 0:Ye(e.schedulerDO,e.jurisdiction);let h;const w=()=>e.adminToken??h;let R;const I=()=>e.requireEphemeralWsToken??R??!1,b=a=>{const s=a??{};if(R===void 0&&e.requireEphemeralWsToken===void 0){const i=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof i=="string"&&i.length>0&&(R=Ga.has(i.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const u=s.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(h=u)},k=new WeakSet,p=a=>yt(a,w())||k.has(a),g=async(a,s)=>{const u=await de(a,s,e.resolveIdentity);if(k.has(a)&&u.headers.authorization===void 0){const i=w();i!==void 0&&(u.headers.authorization=`Bearer ${i}`)}return u};let _=!1;const E=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${a} access is default-denied: configure \`${s}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${a} access (relying solely on per-row RLS).`,{code:a==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${a} 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("")))},T=async(a,s,u=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else u&&s!==n&&E("shard")},N=Hn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),A=async(a,s,u,i,m)=>{await T(null,u,!1);const y={"content-type":"application/json","x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(y["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(y["x-lunora-identity"]=m.identity),i!==void 0&&i.length>0&&(y["x-lunora-mutation-id"]=i),oe(d,u,Oe(a,s,y))},j=async(a,s,u,i)=>{const m=u?.[a];if(!m||typeof m.create!="function")throw new c(`${i} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(xr(s))throw new c(`${i} params ${jr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},x=async(a,s)=>{if(a.workflow){await j(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new c(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const u=await A(a.functionPath,a.args??{},a.shardKey??n);if(!u.ok)throw new c(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(u.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=async(a,s,u,i)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await x(y,s)}catch(v){u.push(i(v))}},P=async(a,s)=>{if(!p(a))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"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 u=await ee(a),i=typeof u.name=="string"?u.name:"";if(i==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===i);if(!m)throw new c(`no cron job named "${i}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await x(m,s),Response.json({name:i,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!l||typeof a.id!="string")return;const u=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await l.get(l.idFromName(u)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:a.id,pool:s}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},M=async(a,s)=>{L(a,"POST","Scheduler dispatch");const u=await Rt(a),i=s??{},m=typeof i.LUNORA_SCHEDULER_SECRET=="string"?i.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof i.LUNORA_ADMIN_TOKEN=="string"?i.LUNORA_ADMIN_TOKEN:void 0),v=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(v&&m?f=await so(m,u,v):y&&(f=yt(a,y)),!f)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(u)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const O=S??{},q=O.args??{};if(typeof O.workflow=="string"&&O.workflow.length>0)return await j(O.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const C=typeof O.shardKey=="string"&&O.shardKey.length>0?O.shardKey:n,$=typeof O.id=="string"&&O.id.length>0?O.id:void 0,V=Fa(a),Z=await A(O.functionPath,q,C,$,V);return await Q(O),Z},B=a=>{if(!p(a))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,u)=>{if(B(a),s===void 0)throw new c(u.message,{code:u.code,status:400});return s},X=Tr({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const i=s?.kind,m=s?.userId,y=s?.limit,v=i==="fcm"||i==="web-push"?i:void 0,f=typeof m=="string"&&m!==""?m:void 0,S=typeof y=="number"&&Number.isFinite(y)?Math.trunc(y):0,O=S>0?Math.min(S,1e3):1e3,q=(await u.list({kind:v,limit:O,userId:f})).filter(C=>v!==void 0&&C.kind!==v?!1:f===void 0||(C.userId??null)===f).map(({keys:C,token:$,...V})=>V);return Response.json({subscriptions:q},{headers:{"content-type":"application/json"},status:200})},ne=async(a,s)=>{if(!s.fanOut){if(s.functionPath===Or)return X(a,s.args??{});if(s.functionPath===za)return J(a,s.args)}},he=hn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,u,i)=>at(e,a,s,u,i,d),streamingImport:(a,s)=>yn(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const u=a.searchParams.get(s);return u===null||u===""?void 0:u},pe=a=>{const s=new URL(a.url),u=s.searchParams.get("limit"),i=s.searchParams.get("offset"),m=u===null?void 0:Number.parseInt(u,10),y=i===null?void 0:Number.parseInt(i,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:y!==void 0&&Number.isFinite(y)&&y>=0?y:void 0}},be=()=>{if(l===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return l},ve=ha({checkWsAdmin:async a=>p(a)||io(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),Ae(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Da({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Nt=ya({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Sr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),qt=Oa({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),Ct=Nn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),xt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),jt=Dn({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Bt=a=>{const s=[],u=d??a?.SHARD;if(u!==void 0&&s.push(kr("durable-object:default",u,n)),e.health?.disableBindingProbes!==!0)for(const[i,m]of Object.entries(a??{})){const y=co(i,m);y!==void 0&&s.push(y)}for(const i of e.health?.probes??[])s.push(i);return s},$t=vr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Bt}),Lt=a=>{const s=e.schedulerInstanceName??"default",u=()=>a.get(a.idFromName(s)),i=async(f,S)=>{const O=await u().fetch(new Request(`https://scheduler.internal${f}`,S));if(!O.ok)throw new c(`ctx.scheduler: SchedulerDO ${f} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(f,S)=>await i(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==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 S.binding=="string"&&S.binding.length>0)return{workflow:S.binding};if(typeof S.__lunoraRef=="string")return{functionPath:S.__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})},v=async(f,S,O={})=>{const{id:q}=await m("/schedule",{args:O,scheduledFor:f,...y(S)});return q};return{cancel:async f=>await m("/cancel",{id:f}),get:async f=>await i(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await i("/list",{method:"GET"}),runAfter:async(f,S,O)=>{if(!Number.isFinite(f)||f<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await v(Date.now()+f,S,O)},runAt:async(f,S,O)=>{if(!Number.isFinite(f))throw new c("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await v(f,S,O)}}},Kt=async(a,s,u)=>{const{claims:i,headers:m,userId:y}=await de(a,s,o),v=async(f,S={})=>{const O=f.__lunoraRef;if(typeof O!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const q=Oe(O,S,{...m,"x-lunora-system":"1"}),C=await oe(d,n,q),$=await C.json();if($.error)throw new c($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(i),userId:y},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),runAction:v,runMutation:v,runQuery:v,...l===void 0?{}:{scheduler:Lt(l)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Gt=async(a,s,u)=>{if(!e.httpRouter)return;const i=await Kt(a,s,u);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:i},u)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Ft=async(a,s,u)=>{if(a.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const i=Ze(a,ie);if(i)return i;const m=u.searchParams.get("shard")??n,{headers:y,identity:v}=await de(a,s,o);await T(v,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);gt(f,y);const O=ao(s,e.shardDO);if(O!==void 0){f.set("x-lunora-shard-binding",O);const q=await no(d,m);if(q>0){const C=Qr(m,Math.floor(Math.random()*q));return oe(d,C,new Request(a,{headers:f}))}}return oe(d,m,new Request(a,{headers:f}))},Qt=async(a,s,u)=>{const{voiceAgents:i}=e;if(i===void 0)return new Response("Not found",{status:404});if(a.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=Ze(a,ie);if(m)return m;let y;try{y=decodeURIComponent(u.pathname.slice(ft.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(i,y)?i[y]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const f=u.searchParams.get("threadKey");if(f===null||f.length===0)return new Response("Missing threadKey",{status:400});const{headers:S,identity:O}=await de(a,s,o);if(e.authorizeShard){if(!await e.authorizeShard(O,f))return new Response("Forbidden",{status:403})}else E("shard");const q=new Headers(a.headers);return gt(q,S),oe(v,f,new Request(a,{headers:q}))},Mt=async(a,s,u)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(u,a.table,s))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});E("fan-out")},Ee=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Mt(a.fanOut,a.functionPath,s);return}await T(s,a.shardKey??n)}},ke=async(a,s,u,i,m,y)=>{const v=Date.now(),{observability:f,sampling:S}=e,O=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=ra(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};na($,V);const Z=Oe(s,u,V);try{const G=await oe(d,i,Z);return ce(f,{...O,...pt($),durationMs:Date.now()-v,functionPath:s,ok:G.ok,shardKey:i,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}catch(G){throw ce(f,{...O,...pt($),..._e(s,Date.now()-v,G,{shardKey:i})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),G}},zt=a=>{if(a.fanOut&&a.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(a.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Wt=async(a,s,u)=>{L(a,"POST","RPC");const i=await eo(a);Za(s,i),zt(i);const m=await ne(a,i);if(m!==void 0)return m;const{headers:y,identity:v}=await de(a,s,o);await Ee(i,v);const f=wt(i,e);{const S=Date.now(),{observability:O}=e,q=Ke(a),C=Re(s,a,u&&(Z=>u.waitUntil?.(Z)));if(i.fanOut){const Z=e.queryCoordinator;if(!Z)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await Z.fanOut(d,{args:i.args??{},fanOut:i.fanOut,functionPath:i.functionPath,headers:y});return ce(O,{durationMs:Date.now()-S,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:i.fanOut.table},functionPath:i.functionPath,...q,ok:!0},C),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw ce(O,{..._e(i.functionPath,Date.now()-S,G,{fanOut:{table:i.fanOut.table}}),...q},C),G}}const $=i.shardKey??n,V=()=>ke(a,i.functionPath,i.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:i.functionPath,price:f.price},V,ht(u)):V()}},Ht=async(a,s,u)=>{L(a,"POST","RPC batch");const i=await ee(a),{calls:m}=i;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:v}=await de(a,s,o),f=Xr(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${lt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>Ee({functionPath:re.functionPath,shardKey:z},v))));const{observability:S}=e,O=Re(s,a,u&&(z=>u.waitUntil?.(z))),q=Ke(a),C=[],$=[],V=(z,W,re,ue)=>({body:{error:{code:re,message:ue}},id:z.id,status:W}),Z=(z,W,re,ue,fe)=>{for(const H of z)ce(S,fe(H),O),C.push(V(H,W,re,ue))},G=(z,W,re,ue,fe)=>{for(const H of z){const me=ue.get(H.id)??fe,ge=me<400;ce(S,{durationMs:re,functionPath:H.functionPath,...q,ok:ge,shardKey:W,...ge?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(me)}`,status:me}}},O)}};await Promise.all([...f.entries()].map(async([z,W])=>{const re=new Headers(y);re.set("content-type","application/json");const ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:W}),headers:re,method:"POST"}),fe=Date.now();let H;try{H=await oe(d,z,ue)}catch(Y){const Ue=Date.now()-fe,{body:He}=hr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,ur=>({..._e(ur.functionPath,Ue,Y,{shardKey:z}),...q}));return}const me=Date.now()-fe,ge=H.headers.get("x-d1-bookmark");ge&&$.push(ge);let De;try{De=await H.json()}catch{const Y=`shard batch returned a non-JSON response (${String(H.status)})`;Z(W,H.status,"SHARD_ERROR",Y,Ue=>({durationMs:me,error:{code:"SHARD_ERROR",message:Y,status:H.status},functionPath:Ue.functionPath,...q,ok:!1,shardKey:z}));return}const Pe=Array.isArray(De.results)?De.results:[],cr=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),dr=new Set(Pe.map(Y=>Y.id));G(W,z,me,cr,H.status),C.push(...Pe);for(const Y of W)dr.has(Y.id)||C.push(V(Y,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(Y.id)}`))}));const ze={"content-type":"application/json"},[We]=$;return $.length===1&&We!==void 0&&(ze["x-d1-bookmark"]=We),Response.json({results:C},{headers:ze,status:200})},Jt=async(a,s,u,i={},m={})=>{try{const y=u.__lunoraRef;if(typeof y!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:v,identity:f}=await de(a,s,o);await Ee({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,O=Re(s,a,m.waitUntil);return await ke(a,y,i,S,v,O)}catch(y){return Je(y)}},Vt=1e3,Yt=async(a,s)=>{const u=e.backupRetain;if(u===void 0||u<=0)return;const i=[];let m;for(let v=0;v<Vt;v+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&i.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=i.toSorted((v,f)=>f.localeCompare(v)).slice(u);await Promise.all(y.flatMap(v=>{const f=v.slice(0,-14);return[a.delete(v),a.delete(f)]}))},Xt=async a=>{const s=e.backupStore,u=e.queryCoordinator;if(!s)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!u)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const i=w();if(!i||i.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 m={authorization:`Bearer ${i}`,"content-type":"application/json"},y=e.backupTables;let v=0,f=0;const S=[];await at(e,u,m,y,Z=>{const G=`${JSON.stringify(Z)}
|
|
5
|
+
`;v+=1,f+=Ua.encode(G).byteLength,S.push(G)},d);const O=e.backupPrefix??"backups/",q=new Date(a.scheduledTime).toISOString(),C=`${O}lunora-backup-${q.replaceAll(/[.:]/gu,"-")}.ndjson`,$=`${C}.manifest.json`;await s.put(C,new Blob(S,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const V={bytes:f,createdAt:q,cron:a.cron,file:C,id:q,rows:v,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
|
|
6
|
+
`,{httpMetadata:{contentType:"application/json"}}),await Yt(s,O)},Qe=async(a,s,u)=>{const{observability:i}=e,m=Date.now(),y=Te(16),v=Te(8),f=mt(s);try{const S=await u();return ce(i,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:v,traceId:y},f),S}catch(S){throw ce(i,{..._e(a,Date.now()-m,S,{}),spanId:v,traceId:y},f),S}finally{Ve(i,f)}},Zt=async(a,s,u)=>{b(s);const i=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,u)}catch(f){i.push(m(f))}if(await F(a.cron,s,i,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await Xt(a)}catch(f){i.push(m(f))}const[v]=i;if(i.length===1&&v)throw v;if(i.length>1)throw new AggregateError(i,`scheduled("${a.cron}") had ${String(i.length)} failure(s)`)},er=async(a,s)=>{try{const u=a??{},i=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!i||i.length===0)return;await oe(d,n,Oe(Ma,{outcome:s},{authorization:`Bearer ${i}`,"content-type":"application/json"}))}catch{}},tr=async(a,s,u,i)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??Qa;return Ha(u.pathname,y)&&i.waitUntil?.(er(s,m.status>=400?"fail":"ok")),m},rr=async({args:a,env:s,functionPath:u,request:i,shardKey:m,waitUntil:y})=>{_t(a,"REST");const v={functionPath:u,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(i,s,o);await Ee(v,S);const O=m??n,q=Re(s,i,y),C=()=>ke(i,u,a,O,f,q),$=wt(v,e);return $&&e.x402Charge?e.x402Charge(i,{functionPath:u,price:$.price},C,ht({waitUntil:y})):C()},nr=_r({functions:e.functions??{},invoke:rr,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,ar={[La]:a=>a.method!=="GET"&&a.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[qa]:(a,s,u)=>Ft(a,s,u),[lt]:(a,s,u,i)=>Wt(a,s,i),[Na]:(a,s,u,i)=>Ht(a,s,i),[Ca]:(a,s)=>M(a,s),[xa]:(a,s)=>P(a,s),[ja]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await zr(s);return Response.json(u,{headers:{"cache-control":"no-store"}})},...N,...he,...ve,...se,...Nt,...qt,...Ct,...xt,...jt,...$t,...nr,...Vr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const or=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},sr=async(a,s)=>{if(!(e.adminGate===void 0||!Ka(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},ir=async(a,s,u)=>{const i=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=Pa[i.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await tr(a,s,i,u);if(m)return m;if(Ie){const f=`${a.method} ${i.pathname}`,S=Ie[f]??Ie[i.pathname];if(S)return S(a,s,u)}const y=ar[i.pathname];return y?(await sr(a,i.pathname),y(a,s,i,u)):e.voiceAgents!==void 0&&i.pathname.startsWith(ft)?Qt(a,s,i):await Gt(a,s,u)||new Response("Not found",{status:404})};return{async fetch(a,s,u){e.passThroughOnException&&u.passThroughOnException?.(),or(s),b(s);const i=Nr(a,ie);if(i)return i;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await ir(a,s,u);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,mt(u))}},async queue(a,s,u){await Qe(`queue:${Va(a)}`,u,async()=>{await e.queue?.(a,s,u)})},async scheduled(a,s,u){await Qe(`cron:${a.cron}`,u,async()=>{await Zt(a,s,u)})},serverQuery:Jt}},uo=e=>Ut(e),lo=e=>typeof e=="function"?{fetch:e}:e,ho=e=>!!(e.crons??e.cronJobs??e.backupCron),Do=(e,t)=>{const r=lo(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=l=>{const h=uo({...l,httpRouter:r});return n!==void 0&&!ho(l)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(l,h,w)=>o(d(h)).fetch(l,h,w),queue:(l,h,w)=>o(d(h)).queue?.(l,h,w)??Promise.resolve(),scheduled:(l,h,w)=>o(d(h)).scheduled(l,h,w),serverQuery:(l,h,w,R,I)=>o(d(h)).serverQuery(l,h,w,R,I)}},po=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)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:r}},Po=(e={})=>(t,r,n)=>Ut(po(e,r)).fetch(t,r,n??pr),Uo=e=>e;export{Or as GET_AUTH_AUDIT_LOG_OP,pr as NOOP_EXECUTION_CONTEXT,Co as composeIdentityResolvers,uo as composeWorker,Po as createLunoraHandler,Ut as createWorker,Uo as defineRpcEnvelope,no as probeRelayCount,po as resolveLunoraOptions,xo as routeIdentityResolvers,Do as withFrameworkWorker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as u,u as d}from"./identity-header-
|
|
1
|
+
import{f as u,u as d}from"./identity-header-pdXOyDU4.mjs";import{LunoraError as o}from"./LunoraError-C08OP5Uq.mjs";const l="/_lunora/rpc",c=r=>{const t={"content-type":"application/json"};return r.userId!==void 0&&r.userId.length>0&&(t["x-lunora-userid"]=u(r.userId)),r.identity!==void 0&&(t["x-lunora-identity"]=d(r.identity)),t},i=async(r,t,a)=>{const e=await(r.fetch??globalThis.fetch)(new Request(`${r.origin}${l}`,{body:JSON.stringify(t),headers:c(r),method:"POST"}));if(!e.ok)throw new o(`cross-shard relation ${a} failed: worker returned ${String(e.status)}`);const n=await e.json();if(typeof n.failed=="number"&&n.failed>0){const s=(typeof n.ok=="number"?n.ok:0)+n.failed;throw new o(`cross-shard relation ${a} failed on ${String(n.failed)} of ${String(s)} shard(s) — refusing to return a partial result`)}return n.data},y=r=>({crossShardCounter:async(t,a)=>{const e=await i(r,{args:{table:t,where:a},fanOut:{merge:{kind:"sum"},table:t},functionPath:"__lunora_relation__:count"},"count");return typeof e=="number"?e:0},crossShardReader:async(t,a)=>{const e=await i(r,{args:{orderBy:a?.orderBy,table:t,where:a?.where,with:a?.with},fanOut:{merge:{kind:"concat"},table:t},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(e)?e:[]}}});export{y as createCrossShardRelationCapabilities};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as E,a as C}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-C08OP5Uq.mjs";import{resolveShard as q}from"./applyJurisdiction-8bzZjAPR.mjs";const me=r=>({listShardKeys(e){return r[e]??[]}}),pe=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new A('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new A('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},B=16,F=5e3,f=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,I=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},D=(r,e)=>r?"failed":e?"in_progress":"completed",R=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const u of r){if(u.kind==="err"){a+=1,e.push({error:{message:u.message,timedOut:u.timedOut},shardKey:u.shardKey});continue}s+=1;const d=f(u.value),c=I(d);t+=c.changed,o+=c.processed,n||=c.status==="in_progress",i||=c.status==="failed",e.push({result:d,shardKey:u.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:D(i,n||a>0)}},V=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},$=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=V(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},T=0,j=1,J=2,b=(r,e)=>r<e?-1:r>e?1:0,M=r=>r==null?T:typeof r=="number"?j:J,O=(r,e)=>{const s=M(r),a=M(e);return s!==a?s<a?-1:1:s===T?0:s===j?b(r,e):b(String(r),String(e))},Q=(r,e,s)=>{const a=O(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=O(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return O(r.rowId,e.rowId)},L=r=>C(new TextEncoder().encode(JSON.stringify(r))),U=r=>{try{const e=JSON.parse(new TextDecoder().decode(E(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},G=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Y=(r,e)=>{let s;for(const a of r){const t=a.rows[a.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:a})}return s},z=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?L({perShard:t}):null},H=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Y(r,s);if(i===void 0)break;t.push(i.row.doc),o[i.slice.shardKey]=i.row.key,i.slice.head+=1}const n=z(r,o);return{isDone:n===null,nextCursor:n,page:t}},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],u=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:u,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,failed:s,ok:e}},ee=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},re=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:ee(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},te=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const u=f(i.value),d=u?.inserted??{};for(const[l,y]of Object.entries(d))s[l]=(s[l]??0)+y;const c=u?.errors;Array.isArray(c)&&a.push(...c),t+=u?.conflicts??0,e.push({result:{conflicts:u?.conflicts??0,errors:u?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,a)=>{const t=q(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const u=new Promise(c=>{i=setTimeout(()=>{try{o.abort()}catch{}c({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const c=await t.fetch(n);if(!c.ok)return{kind:"err",message:`shard "${e}" returned ${String(c.status)}`,shardKey:e,timedOut:!1};const l=await c.json();return{kind:"ok",shardKey:e,value:l}}catch(c){const l=c instanceof Error?c.message:String(c);return{kind:"err",message:`shard "${e}" threw: ${l}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,u])}finally{i!==void 0&&clearTimeout(i)}},w=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const u=r[i];if(i>=r.length||u===void 0)return;a[i]=await s(u,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},P=async(r,e)=>{const s=await Promise.all(e.map(async a=>r.listShardKeys(a)));return[...new Set(s.flat())]},m=async(r,e,s,a,t)=>{const o=p(s);return w(e,a,async n=>g(r,n,o,t))},se=r=>{const e={};for(const s of Object.keys(r).toSorted(b))e[s]=r[s]??null;return JSON.stringify(e)},ae=r=>r.flatMap(e=>Array.isArray(e)?e:[]),oe=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ne=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=se(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=oe(n.value,t,s))},ie=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)ne(s,t,e);return[...s.values()]},N=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},ue=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ce=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},de=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const o of t){if(o===null||typeof o!="object")continue;const n=o[e.by],i=typeof n=="number"&&Number.isFinite(n)?n:Number.NEGATIVE_INFINITY;s.push({row:o,score:i})}const a=e.direction??"desc";return s.sort((t,o)=>a==="asc"?b(t.score,o.score):b(o.score,t.score)),s.slice(0,e.k).map(t=>t.row)},he=(r,e)=>{switch(e.kind){case"concat":return ae(r);case"first":return r[0];case"groupBy":return ie(r,e.op??"sum");case"max":return N(r,Math.max);case"min":return N(r,Math.min);case"rank":return ce(r);case"sum":return ue(r);case"topK":return de(r,e);default:return r}},ge=r=>{const e=r.maxConcurrency??B,s=r.perShardTimeoutMs??F;if(e<1)throw new A("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],u=[];for(const d of n)d.kind==="ok"?i.push(d.value):u.push({message:d.message,shardKey:d.shardKey,timedOut:d.timedOut});return{data:he(i,t.fanOut.merge),errors:u,failed:u.length,ok:i.length}},async orchestrateExport(a,t){const o=await P(r.registry,t.tables),n={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},async orchestrateCdcSync(a,t){const o=await P(r.registry,t.tables),n=t.cursors??{},i=await w(o,e,async u=>{const d=n[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:d},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:d}});return X(i)},async orchestrateImport(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return te(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await w(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return Z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return R(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return $(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],u=t.cursor?U(t.cursor):{perShard:{}},d=await w(o,e,async h=>{const x=u.perShard[h],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),x!==void 0&&(_.after=x);const K=await g(a,h,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(K.kind==="err")return{error:{message:K.message,timedOut:K.timedOut},shardKey:h};const v=G(f(K.value));return{directions:v.directions,hasMore:v.hasMore,rows:v.rows,shardKey:h}}),c=[];let l=0,y=0,k;for(const h of d){if(h.error){y+=1;continue}l+=1,k===void 0&&h.directions&&h.directions.length>0&&(k=h.directions),c.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const S=H(c,n,k??i,u.perShard);return{continueCursor:S.nextCursor,failed:y,isDone:S.isDone,ok:l,page:S.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return re(i)},registry:r.registry}};export{ge as createQueryCoordinator,me as createStaticShardRegistry,pe as mergeStrategyForAggregate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{f as j,u as E}from"./identity-header-pdXOyDU4.mjs";import{a as w,o as O}from"./base64-DPPVK6s_.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const i="$lunora.wire$",m=64,v=1024,g="__proto__",S={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},$={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},I=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",w(n)]:[i,"bytes",w(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!I(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const d=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===g?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn($,a)?$[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===g?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=O(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn(S,e)?S[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===g?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},U=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},x=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=U(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=j(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=E(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"})),A=y.statusText?` ${y.statusText}`:"";let h;try{h=await y.json()}catch{throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${A})`)}if("error"in h)throw x(h.error);if(!y.ok)throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${A})`);return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"./LunoraError-
|
|
1
|
+
import{LunoraError as m}from"./LunoraError-C08OP5Uq.mjs";const y="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",O=e=>{const r=["base-uri 'none'","object-src 'none'"];return e==="DENY"?r.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&r.push("frame-ancestors 'self'"),r.join("; ")},v="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",d=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Mutation-Id"],u=["DELETE","GET","HEAD","PATCH","POST","PUT"],b=31536e3,A=new Set(["GET","HEAD","OPTIONS"]),L=e=>{if(e===!1)return;const r=e===void 0||e===!0?{}:e,s=r.maxAge??b,o=r.includeSubDomains??!0;return`max-age=${String(s)}${o?"; includeSubDomains":""}${r.preload?"; preload":""}`},R=(e,r)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:r,value:y}},S=e=>{if(e===!1)return{coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0};const r=e===void 0||e===!0?{}:e,s=r.frameOptions===!1?void 0:r.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:R(r.csp,O(s)),enabled:!0,frameOptions:s,hsts:L(r.hsts),permissionsPolicy:r.permissionsPolicy===!1?void 0:r.permissionsPolicy??v,referrerPolicy:r.referrerPolicy===!1?void 0:r.referrerPolicy??"strict-origin-when-cross-origin"}},E=e=>{const r={allowCredentials:!1,allowedHeaders:d,allowedMethods:u,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return r;const s=e.allowCredentials??!1,o=e.allowedOrigins;let t,i;if(typeof o=="function")t=o,i=o,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${s?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`);else{const l=o;if(l.includes("*")&&s)throw new m('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=n=>l.includes("*")||l.includes(n),i=n=>l.includes(n)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??d,allowedMethods:e.allowedMethods??u,enabled:!0,isAllowed:t,isExplicitlyAllowed:i,maxAge:e.maxAge??600}},C=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const r=e===void 0||e===!0?{}:e;return{allowLoopback:r.allowLoopback??!0,enabled:!0,trustedOrigins:r.trustedOrigins??[]}},x=new Set(["0","disabled","false","no","off"]),I=new Set(["1","enabled","on","true","yes"]),f=e=>typeof e=="string"&&x.has(e.trim().toLowerCase()),P=e=>typeof e=="string"&&I.has(e.trim().toLowerCase()),k=e=>{const r=e?.LUNORA_ALLOWED_ORIGINS;if(typeof r!="string")return;const s=r.split(",").map(o=>o.trim()).filter(o=>o.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&P(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},H=(e,r)=>{const s=e?.headers??(f(r?.LUNORA_SECURITY_HEADERS)?!1:void 0),o=e?.csrf??(f(r?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??k(r);return{cors:E(t),csrf:C(o),headers:S(s)}},N=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return N.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,r,s)=>e===r||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(r)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),g=(e,r,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${r===void 0?"was missing":`"${r}"`} is not trusted (this worker serves "${s}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:r}},{headers:{"content-type":"application/json"},status:403}),j=(e,r)=>{if(!r.csrf.enabled||A.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin state-changing request",o,s)},$=(e,r)=>{if(!r.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,o=c(e.headers.get("origin"));if(!(o!==void 0&&h(o,s,r)))return g("cross-origin websocket upgrade",o,s)},w=(e,r)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.append("vary","Origin"),r.allowCredentials&&s.set("access-control-allow-credentials","true"),s},M=(e,r)=>{if(!r.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!r.cors.isAllowed(s))return;const o=w(s,r.cors),t=e.headers.get("access-control-request-headers");o.set("access-control-allow-methods",r.cors.allowedMethods.join(", "));let i;if(t===null)i=r.cors.allowedHeaders.join(", ");else{const l=new Set(r.cors.allowedHeaders.map(n=>n.toLowerCase()));i=t.split(",").map(n=>n.trim()).filter(n=>n.length>0&&l.has(n.toLowerCase())).join(", ")}return o.set("access-control-allow-headers",i),o.set("access-control-max-age",String(r.cors.maxAge)),new Response(null,{headers:o,status:204})},D=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),a=(e,r,s)=>{e.has(r)||e.set(r,s)},T=(e,r,s,o)=>{if(o.hsts!==void 0&&new URL(r.url).protocol==="https:"&&a(e,"strict-transport-security",o.hsts),a(e,"x-content-type-options","nosniff"),o.frameOptions!==void 0&&a(e,"x-frame-options",o.frameOptions),o.referrerPolicy!==void 0&&a(e,"referrer-policy",o.referrerPolicy),o.permissionsPolicy!==void 0&&a(e,"permissions-policy",o.permissionsPolicy),o.coop!==void 0&&a(e,"cross-origin-opener-policy",o.coop),o.csp!==void 0){const t=D(s)?o.csp.htmlValue:o.csp.value;t!==void 0&&a(e,"content-security-policy",t)}},U=(e,r,s)=>{const o=r.headers.get("origin");if(!(!o||!s.isAllowed(o)))for(const[t,i]of w(o,s).entries())t==="vary"?e.append("vary",i):a(e,t,i)},G=(e,r,s)=>{if(e.status===101||e.webSocket)return e;const o=new Headers(e.headers);return s.headers.enabled&&T(o,r,e,s.headers),s.cors.enabled&&U(o,r,s.cors),new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})};export{G as decorateResponse,j as enforceOrigin,$ as enforceWebSocketOrigin,M as handleCorsPreflight,H as resolveSecurity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as a,a as s,f}from"./observability-DWlkDJJw.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=(e,n)=>{if(e.size<n)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)};export{o as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as n}from"./base64-DPPVK6s_.mjs";new TextDecoder;const o=new TextEncoder,t="=",c=e=>{for(let r=0;r<e.length;r+=1)if(e.charCodeAt(r)>255)return!1;return!0},s=e=>n(o.encode(JSON.stringify(e))),d=e=>!e.startsWith(t)&&c(e)?e:`${t}${n(o.encode(e))}`;export{d as f,s as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as v}from"./evict-oldest-C2XU6HBR.mjs";const f=r=>{const e=new WeakMap;return(t,c)=>{const a=e.get(t);if(a)return a;const n=Promise.resolve(r(t,c));return e.set(t,n),n}},h=5e3,p=500,g=r=>{const e=r.headers.get("cookie")??"",t=r.headers.get("authorization")??"";if(!(e===""&&t===""))return`${t}\0${e}`},M=(r,e={})=>{const t=e.ttlMs??h,c=Math.max(1,e.maxEntries??p),a=e.cacheKey??g,n=f(r),o=new Map;return(m,d)=>{const s=a(m);if(s===void 0)return n(m,d);const l=Date.now(),u=o.get(s);if(u&&u.expiresAt>l)return u.value;const i=Promise.resolve(n(m,d));return i.catch(()=>{o.get(s)?.value===i&&o.delete(s)}),o.delete(s),v(o,c),o.set(s,{expiresAt:l+t,value:i}),i}};export{M as memoizeIdentity,f as memoizeIdentityPerRequest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"./LunoraError-C08OP5Uq.mjs";const n=(e,o)=>o.includes(e.method)?void 0:new Response(void 0,{headers:{allow:o.join(", ")},status:405}),d=(e,o,r)=>{if(e.method!==o)throw new t(`${r} endpoint requires ${o}`,{code:"METHOD_NOT_ALLOWED",status:405})};export{d as r,n as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=r=>{const e=Number.parseInt(r.slice(0,8),16);return Number.isFinite(e)?e/4294967296:0},i=(r,e=1)=>e>=1?!0:e<=0?!1:c(r)<e,n=(r,e)=>({isTraced:i(e,r?.headRate??1),keepErrors:r?.alwaysSampleErrors??!0}),d=(r,e)=>r.isTraced||r.keepErrors&&e,f=(r,e,o,s,a)=>{if(!r?.onRpc)return;const t=a??(s!==void 0&&e.traceId!==void 0?n(s,e.traceId):void 0);if(!(t!==void 0&&!d(t,!e.ok)))try{r.onRpc(e,o)}catch{}},u=(r,e,o)=>{if(r?.onLog)try{r.onLog(e,o)}catch{}},p=(r,e)=>{if(r?.flush)try{r.flush(e)}catch{}};export{f as a,u as e,p as f,n as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{raw as n,desc as x,sql as d}from"@lunora/bindings/r2sql";const P=["trace","debug","log","info","warn","error","fatal"],T={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},E=500,w=1e4,A=e=>e===void 0||!Number.isFinite(e)?E:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),g=e=>e==null?"":String(e),F=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},S=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,u=0;for(const h of s){const v=h.codePointAt(0)??0;t=(t*31+v)%2147483647,u=(u*131+v)%4294967291}return`${t.toString(36)}.${u.toString(36)}`},R=(e,s,t,u)=>{if(s.sinceTs!==void 0&&e.where(d`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(d`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(d`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const h=P.indexOf(s.minLevel),v=h===-1?[...P]:P.slice(h);e.where(d`${n(t.level)} IN ${v}`)}s.functionPath!==void 0&&e.where(d`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(d`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(d`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(d`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(d`${n(t.userId)} = ${s.userId}`),u!==void 0&&e.where(d`${n(t.ts)} <= ${u}`)},G=T,U=E,q=(e,s)=>{const t={...T,...s.columnMap},u=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,h=r=>{const o={functionPath:g(r[t.functionPath]),level:g(r[t.level]),message:g(r[t.message]),ts:D(r[t.ts])},a=r[t.fields];a!=null&&(o.fields=F(a));for(const i of["shardKey","userId","traceId","spanId"]){const c=r[t[i]];c!=null&&(o[i]=g(c))}return o},v=async(r,o,a)=>{const i=e.from(u).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));R(i,r,t,o),i.orderBy(x(n(t.ts))).limit(a);const{rows:c}=await i.run();return c},N=async(r,o,a,i)=>{const c=await v(r,o,i),I=[];for(const p of c){const l=h(p);a!==void 0&&o!==void 0&&l.ts===o&&a.has(S(l))||I.push(l)}return{decoded:I,truncated:c.length>=i}};return{query:async(r={})=>{const o=A(r.limit),{cursor:a}=r,i=a?.ts,c=a?.seen!==void 0&&a.seen.length>0?new Set(a.seen):void 0,I=Math.min(o+1,w),p=3;let l=[],y=!1;for(let f=0;f<p;f+=1){const b=Math.min(I*2**f,w),O=await N(r,i,c,b);if(l=O.decoded,y=O.truncated,l.length>o||!y||b>=w)break}const L=l.length>o,$=L?l.slice(0,o):l,K=$.at(-1);if(K===void 0||!(L||y))return{rows:$};const m=K.ts,_=$.filter(f=>f.ts===m).map(f=>S(f)),M=[...i===m&&a?.seen!==void 0?a.seen:[],..._];return{nextCursor:M.length>0?{seen:M,ts:m}:{ts:m},rows:$}}}};export{G as D,P as L,U as a,q as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{R as A,a as E}from"./rest-cache-5unAzdFN.mjs";import{LunoraError as u}from"./LunoraError-C08OP5Uq.mjs";import{t as O}from"./method-guard-CfF0J5OT.mjs";const h=1048576,p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),T=async(e,r=h)=>{if(!e.body)return"";const t=e.body.getReader(),n=new TextDecoder;let s=0,o="";for(;;){const{done:a,value:c}=await t.read();if(a)break;if(c){if(s+=c.byteLength,s>r)throw await t.cancel().catch(()=>{}),new u("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o+=n.decode(c,{stream:!0})}}return o+=n.decode(),o},j=async(e,r=h)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),n=[];let s=0;for(;;){const{done:c,value:d}=await t.read();if(c)break;if(d){if(s+=d.byteLength,s>r)throw await t.cancel().catch(()=>{}),new u("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n.push(d)}}const o=new Uint8Array(s);let a=0;for(const c of n)o.set(c,a),a+=c.byteLength;return o.buffer},k=async(e,r,t=h)=>{try{const n=await T(e,t);return n===""?{}:JSON.parse(n)}catch(n){throw n instanceof u?n:new u(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},B=async(e,r=h)=>{const t=await k(e,"Request",r);if(!p(t))throw new u("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},L=(e,r)=>{if(!p(e))throw new u(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},P=e=>E(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),S=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const n=r.headers.get("x-lunora-shard-key");return n===null||n===""?void 0:n},v=e=>{const r=Object.create(null);for(const[t,n]of e.searchParams.entries())if(t!=="shardKey")try{r[t]=JSON.parse(n)}catch{r[t]=n}return r},D=e=>{const{functions:r,invoke:t,rateLimit:n,readJsonBody:s}=e,o={};for(const a of P(r)){const c=a.kind==="query"?["GET","POST"]:["POST"],d=r[a.functionPath].expose?.cache;o[a.path]=async(i,R,U,l)=>{const w=O(i,c);if(w)return w;const b=new URL(i.url);if(n){const y=await n(i,a.functionPath);if(y)return y}let f;i.method==="GET"?f=v(b):f=i.body===null?{}:await s(i),L(f,"REST");const m=S(b,i),g=await t({args:f,env:R,functionPath:a.functionPath,request:i,...m===void 0?{}:{shardKey:m},...l?.waitUntil===void 0?{}:{waitUntil:y=>l.waitUntil?.(y)}});return A(g,d,i)}}return o},q=(e,r)=>async(t,n)=>{const s=r.key?r.key(t,n):t.headers.get("cf-connecting-ip")??void 0,o=await e.limit(r.name,s===void 0?{}:{key:s});if(o.ok)return;const a=Math.max(1,Math.ceil(o.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(a)},status:429})};export{D as E,q as U,j as b,L as e,k as f,v as g,B as h,h as i,S as p,T as w,P as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const b=(r,a="_id")=>{const o=Object.create(null),t=Object.create(null),s=Object.create(null),n=Object.create(null),p=e=>typeof a=="string"?a:a[e]??"_id",c=(e,u)=>{const l=e[u];if(l)return l;const d=[];return e[u]=d,d};for(const e of r.changes)n[e.table]??={primary_key:[p(e.table)]},e.op==="delete"?c(s,e.table).push(e.doc):e.op==="update"?c(t,e.table).push(e.doc):c(o,e.table).push(e.doc);return{delete:s,hasMore:r.hasMore,insert:o,schema:n,state:{cursor:r.nextCursor},update:t}},h=(r,a=Date.now())=>{const o=[];for(const t of r.changes){const s=t.op==="delete"?{...t.doc,_lunora_deleted:!0}:t.doc;o.push({record:{data:s,emitted_at:a,stream:t.table},type:"RECORD"})}return o.push({state:{data:{cursor:r.nextCursor}},type:"STATE"}),o};export{h as toAirbyteMessages,b as toFivetranResponse};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/runtime",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.55",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
50
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.22",
|
|
50
|
+
"@lunora/errors": "1.0.0-alpha.16",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.6"
|
|
52
52
|
},
|
|
53
53
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as p}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L as m,c as f}from"./pipeline-log-reader-DU_CCGDA.mjs";import{LunoraError as _}from"./LunoraError-ByasbDmd.mjs";const E="/_lunora/admin/logs/archive",A="LUNORA_LOG_ARCHIVE_TABLE",O="LUNORA_LOG_ARCHIVE_NAMESPACE",D=e=>{if(typeof e!="object"||e===null)return;const t=e,o=t[A];if(typeof o!="string"||o==="")return;const i=t[O];return{table:o,...typeof i=="string"&&i!==""?{namespace:i}:{}}},g=new Set(m),b=e=>typeof e=="string"&&e!==""?e:void 0,v=(e,t)=>{if(e!==void 0){if(typeof e!="string"||!g.has(e))throw new _(`logs archive: invalid \`${t}\` — expected one of ${m.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},d=(e,t)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${t}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},C=e=>{const t={},o=r=>{const l=b(e[r]);l!==void 0&&(t[r]=l)};o("functionPath"),o("functionPathPrefix"),o("traceId"),o("shardKey"),o("userId");const i=v(e.level,"level");i!==void 0&&(t.level=i);const n=v(e.minLevel,"minLevel");n!==void 0&&(t.minLevel=n);const s=d(e.sinceTs,"sinceTs");s!==void 0&&(t.sinceTs=s);const u=d(e.untilTs,"untilTs");u!==void 0&&(t.untilTs=u);const a=d(e.limit,"limit");a!==void 0&&(t.limit=a);const c=e.cursor;if(typeof c=="object"&&c!==null){const r=d(c.ts,"cursor.ts");r!==void 0&&(t.cursor={ts:r})}return t},S=e=>{const t=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,o=e.R2_SQL_TOKEN,i=e.R2_SQL_BUCKET,n=[];if((t===void 0||t==="")&&n.push("R2_SQL_ACCOUNT_ID"),(o===void 0||o==="")&&n.push("R2_SQL_TOKEN"),(i===void 0||i==="")&&n.push("R2_SQL_BUCKET"),n.length>0)throw new _(`log archive not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:p,status:400});return{accountId:t,apiToken:o,bucket:i}},U=e=>{const{createReader:t=f,readJsonBody:o,requireAdminOption:i}=e,n=async(s,u)=>{if(s.method!=="POST")throw new _("Log-archive endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const a=i(s,e.logArchive,{code:p,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:c,apiToken:r,bucket:l}=S(u??{}),L=C(await o(s)),T=h({accountId:c,apiToken:r,bucket:l}),R=await t(T,{columnMap:a.columnMap,namespace:a.namespace,table:a.table}).query(L);return Response.json(R,{headers:{"content-type":"application/json"},status:200})};return{[E]:n}};export{p as LOG_ARCHIVE_NOT_CONFIGURED,E as LOG_ARCHIVE_PATH,U as buildLogArchiveAdminRoutes,D as resolveLogArchiveFromEnv};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{V as q,f as k,a as V,O as z,l as d,b as te,w as v,y as G,h as j,S as W,L as C,R as re}from"./otlp-resource-B-ByO9qo.mjs";const oe=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},L=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:oe(e),se=e=>{const r=e.maxItems??512,n=e.maxDelayMs??200;let t=[],o,s,l;const h=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},f=async()=>{h();const c=t;t=[];const u=l;s=void 0,l=void 0;try{c.length>0&&await e.export(c)}catch{}finally{u?.()}},m=c=>{s===void 0&&(s=new Promise(u=>{l=u}),o=setTimeout(()=>{f()},n)),c?.(s)};return{add:(c,u)=>{for(t.push(c);t.length>r;)t.shift();m(u),t.length>=r&&f()},flush:async c=>{if(t.length===0){h();return}const u=f();return c?.(u),u},get size(){return t.length}}},ae=(e,r)=>e<r?-1:e>r?1:0,R=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(s=>R(s)).join(",")}]`;const r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype){const s=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,t=Object.keys(n).toSorted(ae),o=[];for(const s of t){const l=n[s];l!==void 0&&o.push(`${JSON.stringify(s)}:${R(l)}`)}return`{${o.join(",")}}`},H=(e,r)=>{const n=[d(v.functionPath,e.functionPath),d(v.ok,e.ok)];e.method!==void 0&&n.push(d("http.request.method",e.method)),e.path!==void 0&&n.push(d("url.path",e.path)),n.push(d("http.route",e.functionPath)),e.scheme!==void 0&&n.push(d("url.scheme",e.scheme)),e.host!==void 0&&n.push(d("server.address",e.host)),e.port!==void 0&&n.push(d("server.port",e.port)),e.userAgent!==void 0&&n.push(d("user_agent.original",e.userAgent)),e.shardKey!==void 0&&n.push(d(v.shardKey,e.shardKey)),n.push(d("http.response.status_code",e.error?.status??200)),e.error&&n.push(d(v.errorType,e.error.code),d("lunora.error_status",e.error.status)),e.fanOut&&n.push(d("lunora.fanout.table",e.fanOut.table),d("lunora.fanout.shards",e.fanOut.shards),d("lunora.fanout.failed",e.fanOut.failed));const t={attributes:n,endTimeUnixNano:k(r),kind:q.server,name:e.functionPath,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId},spanId:e.spanId??z(8),startTimeUnixNano:k(r-e.durationMs),status:e.ok?{code:1}:{code:2,message:e.error?.message??""},traceId:e.traceId??z(16)};return e.traceFlags!==void 0&&(t.flags=e.traceFlags),e.error&&(t.events=[{attributes:[d("exception.type",e.error.code),d("exception.message",e.error.message)],name:"exception",timeUnixNano:k(r)}]),t},E=(e,r)=>{const n=new Map([[v.functionPath,d(v.functionPath,e.functionPath)]]);e.shardKey!==void 0&&n.set(v.shardKey,d(v.shardKey,e.shardKey)),e.userId!==void 0&&n.set(v.userId,d(v.userId,e.userId)),e.errorType!==void 0&&n.set(v.errorType,d(v.errorType,e.errorType));for(const[t,o]of Object.entries(r??{}))n.set(t,d(t,L(o)));return[...n.values()]},Q=e=>{const r={attributes:E({errorType:e.error?.type,functionPath:e.functionPath,shardKey:e.shardKey,userId:e.userId},e.attributes),endTimeUnixNano:k(e.startTs+e.durationMs),kind:q[e.kind??"internal"],name:e.name,parentSpanId:e.parentSpanId,spanId:e.spanId,startTimeUnixNano:k(e.startTs),status:e.ok?{code:1}:{code:2,message:e.error?.message??""},traceId:e.traceId};return e.events!==void 0&&e.events.length>0&&(r.events=e.events.map(n=>({attributes:V(Object.fromEntries(Object.entries(n.attributes??{}).map(([t,o])=>[t,L(o)]))),name:n.name,timeUnixNano:k(n.ts)}))),e.links!==void 0&&e.links.length>0&&(r.links=e.links.map(n=>({attributes:V(Object.fromEntries(Object.entries(n.attributes??{}).map(([t,o])=>[t,L(o)]))),spanId:n.spanId,traceId:n.traceId}))),r},Y=e=>{const r=k(e.ts),n=E({functionPath:e.functionPath,shardKey:e.shardKey},e.attributes),t={asDouble:e.value,attributes:n,timeUnixNano:r};return e.kind==="gauge"?{gauge:{dataPoints:[t]},name:e.name}:e.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:n,bucketCounts:["1"],count:"1",explicitBounds:[],max:e.value,min:e.value,sum:e.value,timeUnixNano:r}]},name:e.name}:{name:e.name,sum:{aggregationTemporality:1,dataPoints:[t],isMonotonic:!0}}},Z=e=>{const r={attributes:E({functionPath:e.functionPath,shardKey:e.shardKey,userId:e.userId},e.fields),body:{stringValue:e.message},severityNumber:te[e.level],severityText:e.level.toUpperCase(),timeUnixNano:k(e.ts)};return e.traceId!==void 0&&(r.traceId=e.traceId),e.spanId!==void 0&&(r.spanId=e.spanId),e.eventName!==void 0&&(r.eventName=e.eventName,r.attributes.push(d("event.name",e.eventName))),r},ie=1024,ce=async e=>{const r=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(r).arrayBuffer()},U=async(e,r,n,t)=>{try{const o=JSON.stringify(r),{byteLength:s}=new TextEncoder().encode(o),l=(s<ie?fetch(e,{body:o,headers:n,method:"POST"}):ce(o).then(h=>fetch(e,{body:h,headers:{...n,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});t?.(l),await l}catch{}},$=(e,r,n,t)=>{U(e,r,n,t?.waitUntil).catch(()=>{})},P=(e,r)=>r===!0&&e.ok,ue=e=>e.kind==="metric"?void 0:e.event.traceId,de=e=>{const r=new Map,n=[];for(const t of e){const o=ue(t);if(o===void 0){n.push(t);continue}const s=r.get(o);s===void 0?r.set(o,[t]):s.push(t)}return{byTrace:r,untraced:n}},_=5,le=(e,r,n)=>{if(r===void 0)return e;const{byTrace:t,untraced:o}=de(e),s=[...o];let l=0,h;for(const[f,m]of t){let c;try{c=r({logs:m.filter(u=>u.kind==="log").map(u=>u.event),rpc:m.filter(u=>u.kind==="rpc").map(u=>u.event),spans:m.filter(u=>u.kind==="span").map(u=>u.event),traceId:f})}catch(u){l+=1,l===1&&(h=u),c=!0}c&&s.push(...m)}return l>0&&n(h,l),s},b=(e,r)=>{if(r===void 0)return e;try{return r(e)}catch{return}},pe=(e,r)=>{if(e.kind==="rpc"){const t=b(e.event,r?.rpc);return t===void 0?void 0:{bucket:"spans",encoded:H(t,e.endMs)}}if(e.kind==="span"){const t=b(e.event,r?.span);return t===void 0?void 0:{bucket:"spans",encoded:Q(t)}}if(e.kind==="log"){const t=b(e.event,r?.log);return t===void 0?void 0:{bucket:"logs",encoded:Z(t)}}const n=b(e.event,r?.metric);return n===void 0?void 0:{bucket:"metrics",encoded:Y(n)}},fe=(e={})=>{const{onlyErrors:r}=e;return{onLog:n=>{n.level==="error"||n.level==="fatal"?console.error("[lunora:log]",n.functionPath,n.message):console.log("[lunora:log]",n.functionPath,n.message)},onMetric:n=>{console.log("[lunora:metric]",`${n.name}=${String(n.value)}`,n.kind,n.functionPath)},onRpc:n=>{P(n,r)||(n.ok?console.log("[lunora:rpc]",n):console.error("[lunora:rpc]",n))},onSpan:n=>{const t=n.ok?"ok":`error ${n.error?.type??""}`.trim();console.log("[lunora:span]",n.name,`${String(n.durationMs)}ms`,t,n.functionPath)}}},me=e=>{const{headers:r,onlyErrors:n,transform:t,transformLog:o,url:s}=e,l=G({"content-type":"application/json"},r),h=(f,m)=>{try{const c=fetch(s,{body:JSON.stringify(f),headers:l,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(c)}catch{}};return{onLog:(f,m)=>{let c=f;if(o)try{c=o(f)}catch{return}c!=null&&h(c,m)},onRpc:(f,m)=>{if(!P(f,n))try{let c=f;if(t)try{c=t(f)}catch{return}if(c==null)return;h(c,m)}catch{}}}},ve=e=>{const{capture:r,captureLog:n}=e,t=e.onlyErrors??!0;return{onLog:n?o=>{try{n(o)}catch{}}:void 0,onRpc:o=>{if(!P(o,t))try{r(o)}catch{}}}},ye=e=>{const{dataset:r,onlyErrors:n}=e;return{onRpc:t=>{if(!P(t,n))try{r.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},ge=e=>{const{pipeline:r,serializeFields:n}=e;return{onLog:(t,o)=>{try{const s={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(s.fields=n===!0?JSON.stringify(t.fields):t.fields),t.shardKey!==void 0&&(s.shardKey=t.shardKey),t.userId!==void 0&&(s.userId=t.userId),t.traceId!==void 0&&(s.traceId=t.traceId),t.spanId!==void 0&&(s.spanId=t.spanId);const l=r.send([s]).catch(()=>{});o?.waitUntil&&o.waitUntil(l)}catch{}}}},be=e=>{const{batch:r,deploymentEnvironment:n,detectResources:t,endpoint:o,headers:s,onlyErrors:l,postProcessor:h,resourceAttributes:f,serviceNamespace:m,serviceVersion:c,tailSampler:u,token:X}=e,I=e.serviceName??"lunora",J={...c===void 0?{}:{"service.version":c},...m===void 0?{}:{"service.namespace":m},...n===void 0?{}:{"deployment.environment":n},...f},D=new WeakMap,g=i=>{if(t!==!0||i?.resourceAttributes===void 0)return J;const a=D.get(i);if(a!==void 0)return a;const p=re(i.resourceAttributes(),J);return D.set(i,p),p};let O=o;for(;O.endsWith("/");)O=O.slice(0,-1);const M=`${O}/v1/traces`,A=`${O}/v1/logs`,F=`${O}/v1/metrics`,S=G({"content-type":"application/json"},s,X);let K=0;const ee=(i,a)=>{if(K>=_)return;K+=1;const p=K===_?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(a)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${p}`,i)},ne=async i=>{const a=le(i,u,ee),p=new Map;for(const y of a){const w=pe(y,h);if(w===void 0)continue;const B=R(y.resource);let N=p.get(B);N===void 0&&(N={logs:[],metrics:[],resource:y.resource,spans:[]},p.set(B,N)),N[w.bucket].push(w.encoded)}const T=[];for(const[,y]of p){const{resource:w}=y;y.spans.length>0&&T.push(U(M,j(y.spans,"@lunora/runtime",I,w),S)),y.logs.length>0&&T.push(U(A,C(y.logs,"@lunora/runtime",I,w),S)),y.metrics.length>0&&T.push(U(F,W(y.metrics,"@lunora/runtime",I,w),S))}await Promise.all(T)};if(r===!1)return{onLog:(i,a)=>{const p=b(i,h?.log);p!==void 0&&$(A,C(Z(p),"@lunora/runtime",I,g(a)),S,a)},onMetric:(i,a)=>{const p=b(i,h?.metric);p!==void 0&&$(F,W(Y(p),"@lunora/runtime",I,g(a)),S,a)},onRpc:(i,a)=>{if(P(i,l))return;const p=b(i,h?.rpc);p!==void 0&&$(M,j(H(p,Date.now()),"@lunora/runtime",I,g(a)),S,a)},onSpan:(i,a)=>{const p=b(i,h?.span);p!==void 0&&$(M,j(Q(p),"@lunora/runtime",I,g(a)),S,a)}};const x=se({export:ne,...r?.maxDelayMs===void 0?{}:{maxDelayMs:r.maxDelayMs},...r?.maxItems===void 0?{}:{maxItems:r.maxItems}});return{flush:i=>{x.flush(i?.waitUntil).catch(()=>{})},onLog:(i,a)=>{x.add({event:i,kind:"log",resource:g(a)},a?.waitUntil)},onMetric:(i,a)=>{x.add({event:i,kind:"metric",resource:g(a)},a?.waitUntil)},onRpc:(i,a)=>{P(i,l)||x.add({endMs:Date.now(),event:i,kind:"rpc",resource:g(a)},a?.waitUntil)},onSpan:(i,a)=>{x.add({event:i,kind:"span",resource:g(a)},a?.waitUntil)}}},ke=(...e)=>{const r=(n,t)=>{for(const o of e){const s=o[n];if(s)try{s.apply(o,t)}catch{}}};return{flush:n=>{r("flush",[n])},onLog:(n,t)=>{r("onLog",[n,t])},onMetric:(n,t)=>{r("onMetric",[n,t])},onRpc:(n,t)=>{r("onRpc",[n,t])},onSpan:(n,t)=>{r("onSpan",[n,t])}}};export{ye as analyticsEngineSink,ke as combineSinks,fe as consoleSink,be as otlpSink,ge as pipelineLogSink,ve as sentrySink,me as webhookSink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./rest-cache-5unAzdFN.mjs";import{g as t,S as o,U as i,p as m,f as R}from"./rest-routes-BJLWmBgK.mjs";import"./method-guard-BbuR0VfS.mjs";export{t as argsFromQuery,o as buildRestRoutes,i as createRestRateLimit,m as readShardKey,R as restSurfaceFromRegistry};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as or,toErrorBody as ar}from"@lunora/errors";import{NOOP_EXECUTION_CONTEXT as sr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as ir,u as dr}from"./identity-header-CDgIrYAz.mjs";import{O as _e,m as ur,A as cr,R as lr,d as hr,i as pr,s as fr}from"./otlp-resource-B-ByO9qo.mjs";import{b as Z,a as he,d as mt,S as wr,e as yt,w as mr}from"./rest-routes-BJLWmBgK.mjs";import{LunoraError as a,toErrorResponse as ze}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as yr}from"./createKvCursorStore-C24tEuYk.mjs";import{d as me}from"./method-guard-BbuR0VfS.mjs";import{buildHealthRoutes as gr,durableObjectProbe as br,d1Probe as Er,presenceProbe as Pe}from"./HEALTH_PATH-BpCNEAIa.mjs";import{wrapResolverWithContract as Or}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as Ra,routeIdentityResolvers as Aa}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Tr}from"./LOG_ARCHIVE_PATH-DGsEec3K.mjs";import{o as _r,f as We,a as de}from"./observability-DYnm-d4g.mjs";import{resolveShard as Se,applyJurisdiction as He}from"./applyJurisdiction-8bzZjAPR.mjs";import{resolveSecurity as Je,handleCorsPreflight as Sr,enforceOrigin as Rr,decorateResponse as Ne,enforceWebSocketOrigin as Ve}from"./decorateResponse-DBIWsRSZ.mjs";const Ar=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},gt="__lunoraBranch",vr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,gt),Dr=`may not contain the reserved workflow branch-marker key ("${gt}")`,je=(e,t)=>{const r=Math.max(e.length,t.length);let n=e.length^t.length;for(let s=0;s<r;s+=1){const u=s<e.length?e.charCodeAt(s):0,c=s<t.length?t.charCodeAt(s):0;n|=u^c}return n===0},bt=(e,t)=>{if(e.size<t)return;const r=e.keys().next().value;r!==void 0&&e.delete(r)},kr="::relay::",Ir=(e,t)=>`${e}${kr}${String(t)}`,$e=new TextEncoder,Pr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Pr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Nr=e=>{const t=String.fromCodePoint(...e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Ur=e=>{const t=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),r=atob(t),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.codePointAt(s)??0;return n},qr=64,Ue=new Map,Et=async e=>{const t=Ue.get(e);if(t)return t;bt(Ue,qr);const r=crypto.subtle.importKey("raw",$e.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ue.set(e,r),r},xr=async(e,t)=>{const r=await Et(e),n=await crypto.subtle.sign("HMAC",r,$e.encode(t));return Nr(new Uint8Array(n))},Cr=async(e,t,r)=>{const n=await Et(e);return crypto.subtle.verify("HMAC",n,r,$e.encode(t))},Ot="v1",Br=6e4,Lr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Br),n=`${Ot}.${String(r)}`,s=await xr(e,n);return{expiresAtMs:r,token:`${n}.${s}`}},jr=async(e,t,r=Date.now())=>{if(e.length===0||t.length===0)return!1;const n=t.split(".");if(n.length!==3)return!1;const[s,u,c]=n;if(s!==Ot||c.length===0)return!1;const h=Number(u);if(!Number.isFinite(h)||h<=r)return!1;let E;try{E=Ur(c)}catch{return!1}return Cr(e,`${s}.${u}`,E)},k="/_lunora/admin/auth",$r={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},P=(e,t)=>{const r=e[t];if(typeof r!="string"||r==="")throw new a(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new a(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},qe=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ye=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},Xe=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`permission` object is required",{code:"BAD_REQUEST",status:400});const r={};for(const[n,s]of Object.entries(t))Array.isArray(s)&&s.every(u=>typeof u=="string")&&(r[n]=s);return r},Gr={[`${k}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${k}/users`]:{build:({paging:e,query:t})=>{const r=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:r==="asc"||r==="desc"?r:void 0}},http:"GET",method:"listUsers"},[`${k}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${k}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${k}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${k}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${k}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${k}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${k}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${k}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${k}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${k}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${k}/users/create`]:{build:({body:e})=>({data:typeof e.data=="object"&&e.data!==null&&!Array.isArray(e.data)?e.data:void 0,email:P(e,"email"),name:P(e,"name"),password:te(e,"password"),role:qe(e.role)}),http:"POST",method:"createUser"},[`${k}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new a("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:P(e,"userId")}},http:"POST",method:"updateUser"},[`${k}/users/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{role:t,userId:P(e,"userId")}},http:"POST",method:"setRole"},[`${k}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:P(e,"userId")}),http:"POST",method:"banUser"},[`${k}/users/unban`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"unbanUser"},[`${k}/users/password`]:{build:({body:e})=>({newPassword:P(e,"newPassword"),userId:P(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${k}/users/remove`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${k}/users/impersonate`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"impersonateUser"},[`${k}/sessions/revoke`]:{build:({body:e})=>({sessionId:P(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${k}/sessions/revoke-all`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${k}/accounts/unlink`]:{build:({body:e})=>({accountId:P(e,"accountId"),userId:P(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${k}/two-factor/disable`]:{build:({body:e})=>({userId:P(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${k}/passkeys/delete`]:{build:({body:e})=>({passkeyId:P(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${k}/organizations/members/remove`]:{build:({body:e})=>({memberId:P(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${k}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:P(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${k}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ye(e,"metadata"),name:P(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${k}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ye(e,"metadata"),name:te(e,"name"),organizationId:P(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${k}/organizations/remove`]:{build:({body:e})=>({organizationId:P(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${k}/organizations/members/add`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),role:te(e,"role"),userId:P(e,"userId")}),http:"POST",method:"addMember"},[`${k}/organizations/members/invite`]:{build:({body:e})=>({email:P(e,"email"),inviterId:te(e,"inviterId"),organizationId:P(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${k}/organizations/members/role`]:{build:({body:e})=>{const t=qe(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new a("`role` is required",{code:"BAD_REQUEST",status:400});return{memberId:P(e,"memberId"),role:t}},http:"POST",method:"updateMemberRole"},[`${k}/organizations/teams/create`]:{build:({body:e})=>({name:P(e,"name"),organizationId:P(e,"organizationId")}),http:"POST",method:"createTeam"},[`${k}/organizations/teams/update`]:{build:({body:e})=>({name:P(e,"name"),teamId:P(e,"teamId")}),http:"POST",method:"updateTeam"},[`${k}/organizations/teams/remove`]:{build:({body:e})=>({teamId:P(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${k}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:P(e,"teamId"),userId:P(e,"userId")}),http:"POST",method:"addTeamMember"},[`${k}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:P(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${k}/organizations/roles/create`]:{build:({body:e})=>({organizationId:P(e,"organizationId"),permission:Xe(e),role:P(e,"role")}),http:"POST",method:"createOrgRole"},[`${k}/organizations/roles/update`]:{build:({body:e})=>({permission:Xe(e),roleId:P(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${k}/organizations/roles/remove`]:{build:({body:e})=>({roleId:P(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Mr=e=>{const t=async s=>{try{return await s()}catch(u){if(u instanceof a)throw u;const c=u,h=typeof c.code=="string"?c.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",u),new a("auth admin operation failed",{code:h,status:$r[h]??500})}},r=async(s,u)=>{if(e.assertAdmin(s),s.method!==u.http)throw new a(`Auth admin endpoint requires ${u.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const c=e.getAuthAdmin();if(c===void 0)throw new a("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=c[u.method];if(h===void 0)throw new a(`auth admin does not support \`${u.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const E=new URL(s.url),O={body:u.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:g=>e.queryParameter(E,g)},D=u.build(O),f=await t(()=>h(D));return Response.json(u.returns==="void"?{ok:!0}:f,{headers:{"content-type":"application/json"},status:200})},n={};for(const[s,u]of Object.entries(Gr))n[s]=c=>r(c,u);return n},Kr="__lunora_admin__:getAuthAuditLog",Ze=e=>typeof e=="string"&&e!==""?e:void 0,et=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Fr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new a("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s={},u=Ze(r.actorId),c=Ze(r.event),h=et(r.sinceSeq),E=et(r.limit);u!==void 0&&(s.actorId=u),c!==void 0&&(s.event=c),h!==void 0&&(s.sinceSeq=h),E!==void 0&&(s.limit=E);let O;try{O=await n.read(s)}catch(f){throw f instanceof a?f:(console.error("[lunora] auth audit read failed:",f),new a("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const D={entries:O};return Response.json(D,{headers:{"content-type":"application/json"},status:200})},tt=500,Qr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new a("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new a("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(n.functionPath.startsWith("__lunora_relation__:")||n.functionPath.startsWith("__lunora_admin__"))throw new a("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(n.args!==void 0&&(typeof n.args!="object"||n.args===null||Array.isArray(n.args)))throw new a("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:n.args===void 0?{}:n.args,clientId:typeof n.clientId=="string"?n.clientId:void 0,clientSeq:typeof n.clientSeq=="number"?n.clientSeq:void 0,functionPath:n.functionPath,id:typeof n.id=="number"?n.id:t,mutationId:typeof n.mutationId=="string"?n.mutationId:void 0},shardKey:typeof n.shardKey=="string"?n.shardKey:r}},zr=(e,t)=>{if(e.length>tt)throw new a(`RPC batch exceeds the ${String(tt)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,s]of e.entries()){const{entry:u,shardKey:c}=Qr(s,n,t),h=r.get(c)??[];h.push(u),r.set(c,h)}return r},Wr=new TextEncoder,Hr=e=>{const t=JSON.stringify(e),r=Wr.encode(t);let n="";for(const s of r)n+=String.fromCodePoint(s);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Jr=e=>{const t={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return t;try{const r=atob(e.replaceAll("-","+").replaceAll("_","/")),n=new Uint8Array(r.length);for(let h=0;h<r.length;h+=1)n[h]=r.codePointAt(h)??0;const s=JSON.parse(new TextDecoder().decode(n)),u=s.s&&typeof s.s=="object"?s.s:{},c={};for(const[h,E]of Object.entries(u))typeof E=="number"&&Number.isFinite(E)&&(c[h]=E);return{g:typeof s.g=="number"&&Number.isFinite(s.g)?s.g:0,s:c,v:1}}catch{return t}},Vr=e=>{const t=typeof e.table=="string"?e.table:"",r=typeof e.op=="string"?e.op:"",n=r==="delete"||r==="insert"||r==="update"?r:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:n,table:t}},rt=(e,t,r)=>{for(const n of t)e.push(Vr(n));return r!==void 0&&t.length>=r},Yr="/_lunora/admin/export",Xr="/_lunora/admin/import",Zr="/_lunora/admin/sync",en="/_lunora/admin/connector/sync",tn="/_lunora/admin/apply",rn="/_lunora/admin/export-tap/run",nn=new TextEncoder,on=async e=>{let t;try{const s=await he(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Export body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(r.tables===void 0)return{tables:void 0};if(!Array.isArray(r.tables))throw new a("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const n=[];for(const s of r.tables){if(typeof s!="string"||s.length===0)throw new a("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});n.push(s)}return{tables:n}},an=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:s,queryCoordinator:u,assertAdmin:c,requireAdminOption:h,resolveForwardContext:E,shardDO:O,streamExportRows:D,streamingImport:f,syncGlobals:g}=e,p=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await on(v),{headers:K}=await E(v,L),F=new ReadableStream({async pull($){const M=X=>{$.enqueue(nn.encode(`${JSON.stringify(X)}
|
|
2
|
-
`))};try{await D(Y,K,U.tables,M),$.close()}catch(X){$.error(X)}}});return new Response(F,{headers:{"content-type":"application/x-ndjson"},status:200})},y=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},F=typeof U.limit=="number"?U.limit:void 0,$=typeof U.globalCursor=="number"?U.globalCursor:0,M=Array.isArray(U.tables)?U.tables.filter(ee=>typeof ee=="string"):void 0,{headers:X}=await E(v,L),J=M??s(),oe=await Y.orchestrateCdcSync(O,{cursors:K,headers:X,limit:F,tables:J}),se=g?await g({limit:F,sinceSeq:$}):void 0;return Response.json({global:se,shards:oe.shards},{status:200})},_=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=Jr(U.cursor),F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,$=Array.isArray(U.tables)?U.tables.filter(re=>typeof re=="string"):void 0,{headers:M}=await E(v,L),X=$??s(),J=await Y.orchestrateCdcSync(O,{cursors:K.s,headers:M,limit:F,tables:X}),oe=[],se={...K.s};let ee=!1;for(const re of J.shards)ee=rt(oe,re.changes??[],F)||ee,se[re.shardKey]=re.cursor;let pe=K.g;if(g){const re=await g({limit:F,sinceSeq:K.g});ee=rt(oe,re.changes,F)||ee,pe=re.cursor}const ge=Hr({g:pe,s:se,v:1}),Re={changes:oe,hasMore:ee,nextCursor:ge};return Response.json(Re,{status:200})},S=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(v),K=(Array.isArray(U.batches)?U.batches:[]).map(J=>J).filter(J=>J!==null&&typeof J=="object"&&typeof J.shardKey=="string"&&Array.isArray(J.changes)),F=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:$}=await E(v,L),M=await Y.orchestrateApplyCdc(O,{batches:K,headers:$}),X=F.length>0&&t?await t({changes:F}):0;return Response.json({applied:M.applied+X,failed:M.failed,ok:M.ok},{status:200})},I=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;c(v);const{headers:Y}=await E(v,L),U=await f(v,Y);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},C=async(v,L)=>{const j=me(v,["POST"]);if(j)return j;const Y=h(v,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(n===void 0||Object.keys(n).length===0||r===void 0)throw new a("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(v),K=typeof U.sink=="string"?U.sink:void 0,F=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,$=Array.isArray(U.tables)?U.tables.filter(se=>typeof se=="string"):void 0;if(K===void 0)throw new a("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const M=n[K];if(M===void 0)throw new a(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await E(v,L),J=$??s(),oe=await yr({coordinator:Y,cursorStore:r,headers:X,limit:F,shardDO:O,sink:M,tables:J});return Response.json(oe,{headers:{"content-type":"application/json"},status:200})};return{[tn]:S,[en]:_,[Yr]:p,[rn]:C,[Xr]:I,[Zr]:y}},Tt=e=>[],sn=(e,t)=>{const r=[],n=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?n.push(s):r.push(s);return{globalTables:n,shardLocalTables:r}},dn=async(e,t,r,n,s,u,c)=>{if(n!==void 0&&s.length===0)return;const h=n===void 0?[]:s,E=n===void 0?Tt():[],O=h.length>0?h:E,D=await t.orchestrateExport(c,{args:{tables:h},headers:r,tables:O});for(const f of D.shards)if(!f.error)for(const g of f.rows??[])u(g)},nt=async(e,t,r,n,s,u)=>{const{globalTables:c,shardLocalTables:h}=sn(e,n);await dn(e,t,r,n,h,s,u);const E=e.exportGlobals;if((n===void 0||c.length>0)&&E){const O=n===void 0?[]:c;for await(const D of E({tables:O}))s(D)}},un=(e,t)=>{let r;try{r=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!r||typeof r!="object"||Array.isArray(r))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const n=r;return typeof n.table!="string"||n.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:n.table},ok:!1}:{doc:n.doc,ok:!0,table:n.table}},cn=(e,t,r,n,s)=>{if(r?.mode.kind==="shardBy"&&typeof r.mode.field=="string"){const u=e[r.mode.field];return u==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${r.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof u=="string"?u:JSON.stringify(u)}}return{ok:!0,shardKey:n}},ln=async(e,t,r)=>{if(!e.body)throw new a("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],s=[],u=new Map;let c=0,h=0;const E=e.body.getReader(),O=new TextDecoder;let D="",f=0;const g=p=>{h+=1;const y=p.trim();if(y.length===0)return;c+=1;const _=un(y,h);if(!_.ok){n.push(_.error);return}const{doc:S,table:I}=_,C=t.resolveTableSharding?.(I);if(C?.mode.kind==="global"){s.push({doc:S,line:h,table:I});return}const v=cn(S,I,C,r,h);if(!v.ok){n.push(v.error);return}const L=u.get(v.shardKey);L?L.rows.push({doc:S,table:I}):u.set(v.shardKey,{rows:[{doc:S,table:I}],shardKey:v.shardKey,startLine:h})};for(;;){const{done:p,value:y}=await E.read();if(p)break;if(y&&(f+=y.byteLength,f>mt))throw await E.cancel().catch(()=>{}),new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});D+=O.decode(y,{stream:!0});let _=D.indexOf(`
|
|
3
|
-
`);for(;_!==-1;){const S=D.slice(0,_);D=D.slice(_+1),g(S),_=D.indexOf(`
|
|
4
|
-
`)}}return D.length>0&&g(D),{errors:n,globalRows:s,perShard:u,received:c}},ot=(e,t)=>{for(const[r,n]of Object.entries(t.inserted))e.inserted[r]=(e.inserted[r]??0)+n;for(const r of t.errors)e.errors.push({...r});e.conflicts+=t.conflicts},hn=async(e,t,r,n)=>{const s=t.defaultShardKey??"__root__",{errors:u,globalRows:c,perShard:h,received:E}=await ln(e,t,s),O={conflicts:0,errors:u,inserted:{}},D=[];if(t.resolveTableSharding===void 0&&h.size>0&&D.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const f=t.queryCoordinator;if(!f)throw new a("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const g=await f.orchestrateImport(n,{batches:[...h.values()],headers:r});ot(O,g)}if(c.length>0)if(t.importGlobals){const f=c[0]?.line??1,g=await t.importGlobals({rows:c,startLine:f});ot(O,g)}else for(const f of c)O.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:f.line,message:`row targets global table "${f.table}" but no \`importGlobals\` is configured`,table:f.table});return{conflicts:O.conflicts,errors:O.errors,inserted:O.inserted,received:E,...D.length>0?{warnings:D}:{}}},xe=e=>typeof e=="object"&&e!==null?e:{},Ce=e=>typeof e.kind=="string"?e.kind:"unknown",pn=(e,t)=>{let r=xe(t),n=!1;Ce(r)==="optional"&&(n=!0,r=xe(r._meta?.inner));const s=Ce(r),u=r._meta??{},c={kind:s,name:e,optional:n};if(s==="id"&&typeof u.tableName=="string"&&(c.table=u.tableName),s==="array"){const h=Ce(xe(u.inner));h!=="unknown"&&(c.element=h)}return c},fn=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>pn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),wn="/_lunora/admin/functions",mn="/_lunora/admin/cron-jobs",yn="/_lunora/admin/openapi",gn="/_lunora/admin/openrpc",bn="/_lunora/admin/global/tables",En="/_lunora/admin/global/table",On="/_lunora/admin/global/facet",at=e=>{if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t))return;const r=t.flatMap(n=>{if(typeof n!="object"||n===null||typeof n.column!="string")return[];const{column:s,value:u}=n;return[{column:s,value:u}]});return r.length===0?void 0:r},Tn=Object.freeze({info:{description:'No OpenAPI spec is configured on this worker. Run `lunora codegen`, then wire the generated module to `createWorker`: `import { openApiSpec } from "./lunora/_generated/openapi"`.',title:"Lunora API",version:"0.0.0"},openapi:"3.1.0",paths:{}}),_n=Object.freeze({info:{description:'No OpenRPC spec is configured on this worker. Run `lunora codegen --api-spec openrpc` (or `both`), then wire the generated module to `createWorker`: `import { openRpcSpec } from "./lunora/_generated/openrpc"`.',title:"Lunora RPC",version:"0.0.0"},methods:[],openrpc:"1.3.2"}),Sn=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:s,requireAdminOption:u}=e,c=p=>{if(p.method!=="GET")throw new a("Functions endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),_=Object.entries(y).flatMap(([S,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:fn(I.args),kind:I.kind,path:S}]).toSorted((S,I)=>S.path.localeCompare(I.path));return Response.json({functions:_},{headers:{"content-type":"application/json"},status:200})},h=p=>{if(p.method!=="GET")throw new a("Cron-jobs endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),_=Object.entries(y).flatMap(([S,I])=>I.map(C=>({args:C.args,cron:S,functionPath:C.functionPath,name:C.name,shardKey:C.shardKey,workflow:C.workflow}))).toSorted((S,I)=>S.name.localeCompare(I.name));return Response.json({jobs:_},{headers:{"content-type":"application/json"},status:200})},E=p=>{if(p.method!=="GET")throw new a("OpenAPI endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openApiSpec??Tn,{headers:{"content-type":"application/json"},status:200})},O=p=>{if(p.method!=="GET")throw new a("OpenRPC endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(p),Response.json(r.openRpcSpec??_n,{headers:{"content-type":"application/json"},status:200})},D=async p=>{if(p.method!=="GET")throw new a("Global-tables endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await y.listTables(),{headers:{"content-type":"application/json"},status:200})},f=async p=>{if(p.method!=="GET")throw new a("Global-table endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),S=s(_,"table");if(S===void 0)throw new a("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await y.readTablePage({...n(p),filters:at(s(_,"filters")),table:S});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},g=async p=>{if(p.method!=="GET")throw new a("Global-facet endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const y=u(p,r.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),_=new URL(p.url),S=s(_,"table"),I=s(_,"column");if(S===void 0||I===void 0)throw new a("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const C=s(_,"limit"),v=C===void 0?void 0:Number(C),L=await y.facetColumn({column:I,filters:at(s(_,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:S});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[mn]:h,[wn]:c,[On]:g,[En]:f,[bn]:D,[yn]:E,[gn]:O}},Rn="/_lunora/admin/kv/namespaces",An="/_lunora/admin/kv/keys",_t="/_lunora/admin/kv/value",St=32*1048576,st=60,vn=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=f=>r(f,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=f=>Response.json(f,{headers:{"content-type":"application/json"},status:200}),u=(f,g)=>{const p=new URL(f.url),y=p.searchParams.get("namespace")??"",_=p.searchParams.get("key")??"";if(y==="")throw new a(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(_==="")throw new a(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:_,namespace:y}},c=async(f,g)=>{if(!(await f.listNamespaces()).some(p=>p.binding===g))throw new a(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},h=async f=>{if(f.method!=="GET")throw new a("KV-namespaces endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return s({namespaces:await n(f).listNamespaces()})},E=async f=>{if(f.method!=="GET")throw new a("KV-keys endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(f),p=new URL(f.url),y=p.searchParams.get("namespace")??"";if(y==="")throw new a("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const _=p.searchParams.get("prefix")??void 0,S=p.searchParams.get("cursor")??void 0,I=p.searchParams.get("limit"),C=I===null?void 0:Number.parseInt(I,10);if(C!==void 0&&(!Number.isInteger(C)||C<1))throw new a("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=C===void 0?void 0:Math.min(C,1e3);return await c(g,y),s(await g.listKeys({cursor:S,limit:v,namespace:y,prefix:_}))},O={DELETE:async f=>{const g=n(f),p=u(f,"DELETE");return await c(g,p.namespace),await g.deleteKey(p),s({deleted:!0})},GET:async f=>{const g=n(f),p=u(f,"GET");return await c(g,p.namespace),s(await g.getValue(p))},PUT:async f=>{const g=n(f),p=await t(f,St);if(typeof p.namespace!="string"||p.namespace==="")throw new a("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new a("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new a("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(p.expirationTtl!==void 0&&(typeof p.expirationTtl!="number"||!Number.isInteger(p.expirationTtl)||p.expirationTtl<st))throw new a("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const y=Math.floor(Date.now()/1e3)+st;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<y))throw new a("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await c(g,p.namespace),await g.putValue({expiration:p.expiration,expirationTtl:p.expirationTtl,key:p.key,metadata:p.metadata,namespace:p.namespace,value:p.value}),s({ok:!0})}},D=f=>{const g=O[f.method];if(!g)throw new a("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(f)};return{[Rn]:h,[An]:E,[_t]:D}},Dn="/_lunora/migrate",kn="/_lunora/admin/pitr",In="/_lunora/admin/rank",Pn="/_lunora/admin/rankpage",Nn="/_lunora/admin/shard-traffic",Un=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),qn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),xn=async e=>{let t;try{const n=await he(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Migration body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.functionPath!="string"||!Un.has(r.functionPath))throw new a("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:r.args??{},functionPath:r.functionPath,table:r.table}},Cn=async e=>{let t;try{const n=await he(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Rank body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof r.index!="string"||r.index.length===0)throw new a("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof r.partitionKey!="string")throw new a("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof r.rowId!="string"||r.rowId.length===0)throw new a("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(r.sortValues))throw new a("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:r.index,partitionKey:r.partitionKey,rowId:r.rowId,sortValues:r.sortValues,table:r.table}},Bn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new a('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},Ln=e=>{if(typeof e.table!="string"||e.table.length===0)throw new a("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new a("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new a("Rank page request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(e.take!==void 0&&(typeof e.take!="number"||!Number.isFinite(e.take)))throw new a("Rank page request `take` must be a number",{code:"BAD_REQUEST",status:400});if(e.cursor!==void 0&&e.cursor!==null&&typeof e.cursor!="string")throw new a("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},jn=async e=>{let t;try{const s=await he(e);t=s===""?{}:JSON.parse(s)}catch(s){throw s instanceof a?s:new a("Rank page body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};Ln(r);const n=Bn(r.directions);return{cursor:typeof r.cursor=="string"?r.cursor:null,directions:n,index:r.index,partitionKey:typeof r.partitionKey=="string"?r.partitionKey:void 0,table:r.table,take:typeof r.take=="number"?r.take:void 0}},$n=async e=>{let t;try{const n=await he(e);t=n===""?{}:JSON.parse(n)}catch(n){throw n instanceof a?n:new a("Shard-traffic body must be valid JSON",{code:"BAD_REQUEST",status:400})}const r=t??{};if(typeof r.table!="string"||r.table.length===0)throw new a("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:r.table}},Gn=async e=>{const t=await Z(e);if(typeof t.functionPath!="string"||!qn.has(t.functionPath))throw new a("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(t.shardKey!==void 0&&typeof t.shardKey!="string")throw new a("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Mn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:s,resolveForwardContext:u,shardDO:c}=e,h=async(g,p)=>{if(g.method!=="POST")throw new a("Migration endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Migration endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await xn(g),{headers:_}=await u(g,p),S=await s.orchestrateMigration(c,{args:y.args,functionPath:y.functionPath,headers:_,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},E=async(g,p)=>{if(g.method!=="POST")throw new a("Rank endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await Cn(g),{headers:_}=await u(g,p),S=await s.orchestrateRank(c,{headers:_,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},O=async(g,p)=>{if(g.method!=="POST")throw new a("Rank page endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Rank page endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await jn(g),{headers:_}=await u(g,p),S=await s.orchestrateRankPage(c,{...y,headers:_});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},D=async(g,p)=>{if(g.method!=="POST")throw new a("Shard-traffic endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new a("Shard-traffic endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const y=await $n(g),{headers:_}=await u(g,p),S=await s.orchestrateShardTraffic(c,{headers:_,table:y.table});return Response.json(S,{headers:{"content-type":"application/json"},status:200})},f=async(g,p)=>{if(g.method!=="POST")throw new a("PITR endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!n(g))throw new a("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const y=await Gn(g),{headers:_}=await u(g,p),S=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:y.args,functionPath:y.functionPath}),headers:_,method:"POST"});return r(c,y.shardKey??t,S)};return{[Dn]:h,[kn]:f,[In]:E,[Pn]:O,[Nn]:D}},Kn=1,Fn=0,Qn=32,zn=512,Wn=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Hn=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>zn)return;const r=t.split(",");if(!(r.length>Qn)){for(const n of r)if(!Wn.test(n.trim()))return;return t}},Jn=e=>{const t=cr(e.headers.get("traceparent"));if(t===void 0)return;const r=Hn(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},Vn=(e,t={})=>{const r=Jn(e),n=t.trustInbound===!0?r:void 0,s=_e(8),u=n?.traceId??_e(16),c=_r(t.sampling,n===void 0?s:u),h=c.isTraced&&(n===void 0||n.sampled);return{decision:c,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:s,traceFlags:h?Kn:Fn,traceId:u,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},Yn=(e,t)=>{t.traceparent=ur(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Xn=(e,t)=>{let r;return()=>{if(r===void 0){const n=fr(e),s=t===void 0?void 0:t.cf;r=lr(pr(n),hr(n,s))}return r}},Zn="/_lunora/admin/scheduled",eo="/_lunora/admin/scheduled/status",to="/_lunora/admin/scheduled/ws",ro="/_lunora/admin/scheduled/cancel",no="/_lunora/admin/scheduled/dead",oo="/_lunora/admin/scheduled/dead/retry",ao="/_lunora/admin/scheduled/dead/cancel",so=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:s}=e,u=async f=>{if(f.method!=="GET")throw new a("Scheduled-list endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/list",{method:"GET"}))},c=async f=>{if(f.method!=="GET")throw new a("Scheduler-status endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/status",{method:"GET"}))},h=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new a("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=r();return Se(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))},E=async f=>{if(f.method!=="POST")throw new a("Scheduled-cancel endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=n(f),p=await f.json().catch(()=>{});if(typeof p?.id!="string"||p.id==="")throw new a("Scheduled-cancel requires a string `id`",{code:"BAD_REQUEST",status:400});return g.fetch(new Request("https://scheduler.internal/cancel",{body:JSON.stringify({id:p.id}),headers:{"content-type":"application/json"},method:"POST"}))},O=async f=>{if(f.method!=="GET")throw new a("Scheduled dead-letter endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return n(f).fetch(new Request("https://scheduler.internal/dead",{method:"GET"}))},D=f=>async g=>{if(g.method!=="POST")throw new a("Scheduled dead-letter action requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const p=n(g),y=await g.json().catch(()=>{});if(typeof y?.id!="string"||y.id==="")throw new a("Scheduled dead-letter action requires a string `id`",{code:"BAD_REQUEST",status:400});return p.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:y.id}),headers:{"content-type":"application/json"},method:"POST"}))};return{[ro]:E,[ao]:D("/dead/cancel"),[no]:O,[oo]:D("/dead/retry"),[Zn]:u,[eo]:c,[to]:h}},io="/_lunora/admin/storage",uo="/_lunora/admin/storage/url",co="/_lunora/admin/storage/buckets",lo=10080*60,ho=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:s,requireAdminOption:u,storage:c}=e,h=y=>{const _=n(y,"key");if(_===void 0)throw new a("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return _},E=async y=>{const _=u(y,c.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),S=new URL(y.url),I=await _(n(S,"prefix"),{bucket:n(S,"bucket"),cursor:n(S,"cursor"),...r(y)});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},O=y=>{if(y.method!=="GET")throw new a("Storage-buckets endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});return t(y),Response.json({buckets:c.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})},D=async y=>{const _=u(y,c.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),S=new URL(y.url),I=h(S);return await _(I,{bucket:n(S,"bucket")}),Response.json({deleted:!0,key:I},{headers:{"content-type":"application/json"},status:200})},f=async y=>{const _=u(y,c.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),S=new URL(y.url),I=h(S),C=await s(y),v=y.headers.get("content-type"),L=v===null||v===""?void 0:v,j=await _(I,C,{bucket:n(S,"bucket"),contentType:L});return Response.json(j,{headers:{"content-type":"application/json"},status:200})},g=async y=>{switch(y.method){case"DELETE":return D(y);case"GET":return E(y);case"POST":case"PUT":return f(y);default:throw new a("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async y=>{if(y.method!=="GET")throw new a("Storage URL endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const _=u(y,c.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),S=new URL(y.url),I=h(S),C=Number(n(S,"expiresIn")??""),v=Number.isFinite(C)&&C>0?Math.min(C,lo):void 0,L=await _(I,{bucket:n(S,"bucket"),expiresInSeconds:v});return Response.json({key:I,url:L},{headers:{"content-type":"application/json"},status:200})};return{[co]:O,[io]:g,[uo]:p}},po=(e,...t)=>{let r=e.cf;for(const n of t){if(typeof r!="object"||r===null)return;r=r[n]}return typeof r=="string"?r:void 0},fo={mtls:e=>po(e,"tlsClientAuth","certVerified")==="SUCCESS"},wo=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:Object.entries(fo).find(([t])=>t===e)?.[1]??(()=>!1),mo=e=>{if(e!==void 0)return()=>{};let t=!1;return()=>{t||(t=!0,console.warn('[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.'))}},yo="/_lunora/admin/vector/indexes",go="/_lunora/admin/vector/query",bo=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async u=>{if(u.method!=="GET")throw new a("Vector-indexes endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(u,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await c.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async u=>{if(u.method!=="POST")throw new a("Vector-query endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const c=r(u,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(c.queryIndex===void 0)throw new a("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const h=await t(u);if(typeof h.name!="string"||h.name==="")throw new a("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new a("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(h.topK!==void 0&&(typeof h.topK!="number"||!Number.isInteger(h.topK)||h.topK<1))throw new a("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const E=await c.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(E,{headers:{"content-type":"application/json"},status:200})};return{[yo]:n,[go]:s}},Eo="/_lunora/admin/workflows/instances",Oo="/_lunora/admin/workflows/instance",To="/_lunora/admin/workflows/status",_o={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},So=e=>e!==null&&Object.hasOwn(_o,e)?e:void 0,it=(e,t)=>{const r=e.searchParams.get(t);if(r===null)return;const n=Number(r);return Number.isInteger(n)&&n>0?n:void 0},Be=(e,t)=>{const r=e.searchParams.get(t);if(r===null||r==="")throw new a(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},dt=()=>{throw new a("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ro=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(c,h,E)=>{if(c.method!=="GET")throw new a("Workflows instances endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(h);if(!O)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const D=Be(E,"name"),f=So(E.searchParams.get("status"));return Response.json(await O.listInstances({page:it(E,"page"),perPage:it(E,"perPage"),status:f,workflowName:D}))},s=async(c,h,E)=>{if(c.method!=="GET")throw new a("Workflows instance endpoint requires GET",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const O=r(h);return O?Response.json(await O.getInstance({instanceId:Be(E,"id"),workflowName:Be(E,"name")})):dt()},u=async(c,h)=>{if(c.method!=="POST")throw new a("Workflows status endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});t(c);const E=r(h);if(!E)return dt();const O=await c.json().catch(()=>{});if(typeof O?.name!="string"||O.name===""||typeof O.id!="string"||O.id==="")throw new a("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:D}=O;if(D!=="pause"&&D!=="resume"&&D!=="terminate")throw new a("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await E.setInstanceStatus({action:D,instanceId:O.id,workflowName:O.name}))};return{[Oo]:s,[Eo]:n,[To]:u}},Ao=new TextEncoder,ut="/_lunora/rpc",vo="/_lunora/rpc-batch",Do="/_lunora/ws",Ee=(e,t,r)=>({resourceAttributes:Xn(e,t),...r===void 0?{}:{waitUntil:r}}),ct=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},lt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Le=e=>{const{method:t}=e,r=e.headers.get("user-agent")??void 0;let n;try{n=new URL(e.url)}catch{return{method:t,userAgent:r}}const s=n.port===""?void 0:Number(n.port);return{host:n.hostname,method:t,path:n.pathname,port:Number.isNaN(s)?void 0:s,scheme:n.protocol.replace(":",""),userAgent:r}},ht="/_lunora/voice/",ko="/_lunora/scheduler/dispatch",Io="/_lunora/admin/cron-jobs/run",Po="/_lunora/admin/ws-token",No="/_lunora/admin/",Uo="/_lunora/migrate",qo="/_lunora/status",xo=e=>e.startsWith(No)||e===Uo,Co=new Set(["1","enabled","on","true","yes"]),Bo=e=>{const t=e.headers.get("x-lunora-userid"),r=e.headers.get("x-lunora-identity");if(!(t===null&&r===null))return{...r===null?{}:{identity:r},...t===null?{}:{userId:t}}},Lo="/api/auth",jo="__lunora_admin__:recordAuthEvent",$o="__lunora_admin__:listPushSubscriptions",Go=["/sign-in","/sign-up","/callback"],Mo=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Go.some(s=>n===s||n.startsWith(`${s}/`))},Oe=(e,t,r,n)=>{const s=or(r),u=s?r.code:"INTERNAL_SERVER_ERROR",c=s?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:u,message:h,status:c},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ko=e=>{const{exp:t,expiresAtMs:r}=e;if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},pt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Fo=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},ue=async(e,t,r)=>{const n={"content-type":"application/json"},s=e.headers.get("authorization"),u=e.headers.get("cookie"),c=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),E=e.headers.get("x-lunora-client-id"),O=e.headers.get("x-lunora-client-seq");s&&(n.authorization=s),u&&(n.cookie=u),c&&(n["x-d1-bookmark"]=c),h&&(n["x-lunora-mutation-id"]=h),E&&(n["x-lunora-client-id"]=E),O&&(n["x-lunora-client-seq"]=O);const D=e.headers.get("cf-connecting-ip");if(D&&(n["x-lunora-client-ip"]=D),!r)return{claims:null,headers:n,identity:null,userId:null};const f=await r(e,t);if(!f||typeof f.userId!="string"||f.userId.length===0)return{claims:null,headers:n,identity:null,userId:null};n["x-lunora-userid"]=ir(f.userId);const g=Ko(f);g!==void 0&&(n["x-lunora-identity-exp"]=String(g));const{userId:p,...y}=f,_=Object.keys(y).length>0?y:null;return _&&(n["x-lunora-identity"]=dr(_)),{claims:_,headers:n,identity:f,userId:p}},Qo=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),zo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new a("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new a("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new a("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Qo.has(r.kind))throw new a("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(r.kind==="topK"){if(typeof r.k!="number"||!Number.isInteger(r.k)||r.k<0)throw new a("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof r.by!="string"||r.by.length===0)throw new a("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Wo=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},ft=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new a("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new a(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},Ho=async e=>{const t=await he(e);let r;try{r=JSON.parse(t)}catch{throw new a("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new a("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&yt(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new a("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=r,u=zo(s.fanOut),c=s.args??{};if(u&&s.functionPath.startsWith("__lunora_relation__:")){const h=c.table;if(typeof h=="string"&&h!==u.table)throw new a("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});c.table=u.table}return{args:c,fanOut:u,functionPath:s.functionPath,shardKey:s.shardKey}},ae=async(e,t,r)=>Se(e,t).fetch(r),Te=new Map,Jo=5e3,Vo=4096,Yo=async(e,t)=>{const r=Date.now(),n=Te.get(t);if(n!==void 0&&n.expiresMs>r)return n.relayCount;n!==void 0&&Te.delete(t);let s=0;try{const u=await Se(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(u.ok){const c=(await u.json()).relayCount;typeof c=="number"&&c>0&&(s=Math.floor(c))}}catch{s=0}return bt(Te,Vo),Te.set(t,{expiresMs:r+Jo,relayCount:s}),s},Xo=(e,t)=>{if(!(e===null||typeof e!="object")){for(const[r,n]of Object.entries(e))if(n===t)return r}},Zo=async(e,t,r)=>{if(e.length===0||r.length===0)return!1;const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),u=await crypto.subtle.sign("HMAC",s,n.encode(t)),c=new Uint8Array(u);let h="";for(const O of c)h+=String.fromCodePoint(O);const E=btoa(h).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");return je(E,r)},wt=(e,t)=>{if(!t||t.length===0)return!1;const r=e.headers.get("authorization");if(!r)return!1;const[n,...s]=r.split(" ");return n?.toLowerCase()!=="bearer"?!1:je(t,s.join(" ").trim())},ea=async(e,t,r)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:await jr(t,n)?!0:r?!1:je(t,n)},ta=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const r=t;if(typeof r.prepare=="function"&&typeof r.batch=="function"&&typeof r.dump=="function")return Er(`d1:${e}`,t);if(typeof r.list=="function"&&typeof r.head=="function"&&typeof r.createMultipartUpload=="function")return Pe(`r2:${e}`,!0);if(typeof r.send=="function"&&typeof r.sendBatch=="function"&&typeof r.get!="function")return Pe(`queue:${e}`,!0);if(typeof r.connectionString=="string")return Pe(`hyperdrive:${e}`,!0)},Rt=e=>{const t=wo(e.trustInboundTraceContext),r=mo(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",s=Or(e.resolveIdentity,e.identity),u=He(e.shardDO,e.jurisdiction),c=e.schedulerDO===void 0?void 0:He(e.schedulerDO,e.jurisdiction);let h;const E=()=>e.adminToken??h;let O;const D=()=>e.requireEphemeralWsToken??O??!1,f=o=>{const i=o??{};if(O===void 0&&e.requireEphemeralWsToken===void 0){const d=i.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(O=Co.has(d.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const l=i.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},g=new WeakSet,p=o=>wt(o,E())||g.has(o),y=async(o,i)=>{const l=await ue(o,i,e.resolveIdentity);if(g.has(o)&&l.headers.authorization===void 0){const d=E();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let _=!1;const S=o=>{if(!e.allowUnauthenticatedShardAccess){const i=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new a(`${o} access is default-denied: configure \`${i}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}_||(_=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},I=Mn({defaultShard:n,forwardToShard:ae,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:y,shardDO:u}),C=async(o,i,l,d,w)=>{if(e.authorizeShard&&!await e.authorizeShard(null,l))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});const b={"content-type":"application/json","x-lunora-system":"1"};w?.userId!==void 0&&w.userId.length>0&&(b["x-lunora-userid"]=w.userId),w?.identity!==void 0&&w.identity.length>0&&(b["x-lunora-identity"]=w.identity),d!==void 0&&d.length>0&&(b["x-lunora-mutation-id"]=d);const R=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:i,functionPath:o}),headers:b,method:"POST"});return ae(u,l,R)},v=async(o,i,l,d)=>{const w=l?.[o];if(!w||typeof w.create!="function")throw new a(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(vr(i))throw new a(`${d} params ${Dr}`,{code:"BAD_REQUEST",status:400});await w.create({params:i})},L=async(o,i,l)=>v(o,i.args??{},l,`cron job "${i.name}"`),j=async(o,i)=>{if(o.workflow){await L(o.workflow,o,i);return}if(o.functionPath===void 0)throw new a(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await C(o.functionPath,o.args??{},o.shardKey??n);if(!l.ok)throw new a(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},Y=async(o,i,l,d)=>{const w=e.cronJobs?.[o];if(w)for(const b of w)try{await j(b,i)}catch(R){l.push(d(R))}},U=async(o,i)=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(o.method!=="POST")throw new a("cron-jobs run endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!e.cronJobs)throw new a("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await Z(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new a("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const w=Object.values(e.cronJobs).flat().find(b=>b.name===d);if(!w)throw new a(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(w,i),Response.json({name:d,ran:!0},{status:200})},K=async o=>{const i=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!i||!c||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await c.get(c.idFromName(l)).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:i}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},F=async(o,i)=>{if(o.method!=="POST")throw new a("Scheduler dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const l=await he(o),d=i??{},w=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,b=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),R=o.headers.get("x-lunora-scheduler-signature");let m=!1;if(R&&w?m=await Zo(w,l,R):b&&(m=wt(o,b)),!m)throw new a("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let T;try{T=JSON.parse(l)}catch{throw new a("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const A=T??{},N=A.args??{};if(typeof A.workflow=="string"&&A.workflow.length>0)return await v(A.workflow,N,i,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof A.functionPath!="string"||A.functionPath.length===0)throw new a("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const q=typeof A.shardKey=="string"&&A.shardKey.length>0?A.shardKey:n,x=typeof A.id=="string"&&A.id.length>0?A.id:void 0,B=Bo(o),W=await C(A.functionPath,N,q,x,B);return await K(A),W},$=o=>{if(!p(o))throw new a("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},M=(o,i,l)=>{if($(o),i===void 0)throw new a(l.message,{code:l.code,status:400});return i},X=Fr({assertAdmin:$,getReader:()=>e.authAuditReader}),J=async(o,i)=>{$(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const d=i?.kind,w=i?.userId,b=i?.limit,R=d==="fcm"||d==="web-push"?d:void 0,m=typeof w=="string"&&w!==""?w:void 0,T=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,A=T>0?Math.min(T,1e3):1e3,N=(await l.list({kind:R,limit:A,userId:m})).filter(q=>R!==void 0&&q.kind!==R?!1:m===void 0||(q.userId??null)===m).map(({keys:q,token:x,...B})=>B);return Response.json({subscriptions:N},{headers:{"content-type":"application/json"},status:200})},oe=async(o,i)=>{if(!i.fanOut){if(i.functionPath===Kr)return X(o,i.args??{});if(i.functionPath===$o)return J(o,i.args)}},se=an({applyGlobals:e.applyGlobals,assertAdmin:$,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>Tt(),queryCoordinator:e.queryCoordinator,requireAdminOption:M,resolveForwardContext:y,shardDO:u,streamExportRows:(o,i,l,d)=>nt(e,o,i,l,d,u),streamingImport:(o,i)=>hn(o,e,i,u),syncGlobals:e.syncGlobals}),ee=(o,i)=>{const l=o.searchParams.get(i);return l===null||l===""?void 0:l},pe=o=>{const i=new URL(o.url),l=i.searchParams.get("limit"),d=i.searchParams.get("offset"),w=l===null?void 0:Number.parseInt(l,10),b=d===null?void 0:Number.parseInt(d,10);return{limit:w!==void 0&&Number.isFinite(w)&&w>=0?w:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},ge=()=>{if(c===void 0)throw new a("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return c},Re=so({checkWsAdmin:async o=>p(o)||ea(o,E(),D()),requireSchedulerNamespace:ge,resolveSchedulerStub:o=>($(o),Se(ge(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),re=Ro({assertAdmin:$,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),At=ho({assertAdmin:$,parsePaging:pe,queryParameter:ee,readBodyBytes:mr,requireAdminOption:M,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),vt=bo({readJsonBody:Z,requireAdminOption:M,vectorIntrospector:e.vectorIntrospector}),Dt=vn({kvIntrospector:e.kvIntrospector,readJsonBody:Z,requireAdminOption:M}),kt=Tr({logArchive:e.logArchive,readJsonBody:Z,requireAdminOption:M}),It=Sn({assertAdmin:$,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ee,requireAdminOption:M}),Pt=o=>{const i=[],l=u??o?.SHARD;if(l!==void 0&&i.push(br("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[d,w]of Object.entries(o??{})){const b=ta(d,w);b!==void 0&&i.push(b)}for(const d of e.health?.probes??[])i.push(d);return i},Nt=gr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Pt}),Ut=o=>{const i=e.schedulerInstanceName??"default",l=()=>o.get(o.idFromName(i)),d=async(m,T)=>{const A=await l().fetch(new Request(`https://scheduler.internal${m}`,T));if(!A.ok)throw new a(`ctx.scheduler: SchedulerDO ${m} failed (${String(A.status)}): ${await A.text()}`,{code:"INTERNAL",status:500});return await A.json()},w=async(m,T)=>await d(m,{body:JSON.stringify(T),headers:{"content-type":"application/json"},method:"POST"}),b=m=>{const T=m;if(T==null)throw new a("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof T.binding=="string"&&T.binding.length>0)return{workflow:T.binding};if(typeof T.__lunoraRef=="string")return{functionPath:T.__lunoraRef};throw new a("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},R=async(m,T,A={})=>{const{id:N}=await w("/schedule",{args:A,scheduledFor:m,...b(T)});return N};return{cancel:async m=>await w("/cancel",{id:m}),get:async m=>await d(`/get?id=${encodeURIComponent(m)}`,{method:"GET"}),list:async()=>await d("/list",{method:"GET"}),runAfter:async(m,T,A)=>{if(!Number.isFinite(m)||m<0)throw new a("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await R(Date.now()+m,T,A)},runAt:async(m,T,A)=>{if(!Number.isFinite(m))throw new a("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await R(m,T,A)}}},qt=async(o,i,l)=>{const{claims:d,headers:w,userId:b}=await ue(o,i,s),R=async(m,T={})=>{const A=m.__lunoraRef;if(typeof A!="string")throw new a("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const N=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:T,functionPath:A}),headers:{...w,"x-lunora-system":"1"},method:"POST"}),q=await ae(u,n,N),x=await q.json();if(x.error)throw new a(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:q.status});return x.result};return{auth:{getIdentity:()=>Promise.resolve(d),userId:b},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:R,runMutation:R,runQuery:R,...c===void 0?{}:{scheduler:Ut(c)},...e.storage===void 0?{}:{storage:Ar(e.storage(i))}}},xt=async(o,i,l)=>{if(!e.httpRouter)return;const d=await qt(o,i,l);try{return await e.httpRouter.fetch(o,{...i,__lunoraCtx:d},l)}catch(w){return console.error("[lunora] httpRouter (SSR) handler threw:",w),new Response("Internal Server Error",{status:500})}},Ct=async(o,i,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new a("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=Ve(o,ie);if(d)return d;const w=l.searchParams.get("shard")??n,{headers:b,identity:R}=await ue(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(R,w))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else w!==n&&S("shard");const m=new Headers(o.headers),T=[...m.keys()];for(const B of T)B.startsWith("x-lunora-")&&m.delete(B);const A=b["x-lunora-userid"],N=b["x-lunora-identity"],q=b["x-lunora-identity-exp"];A!==void 0&&m.set("x-lunora-userid",A),N!==void 0&&m.set("x-lunora-identity",N),q!==void 0&&m.set("x-lunora-identity-exp",q);const x=Xo(i,e.shardDO);if(x!==void 0){m.set("x-lunora-shard-binding",x);const B=await Yo(u,w);if(B>0){const W=Ir(w,Math.floor(Math.random()*B));return ae(u,W,new Request(o,{headers:m}))}}return ae(u,w,new Request(o,{headers:m}))},Bt=async(o,i,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const w=Ve(o,ie);if(w)return w;let b;try{b=decodeURIComponent(l.pathname.slice(ht.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(d,b)?d[b]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const m=l.searchParams.get("threadKey");if(m===null||m.length===0)return new Response("Missing threadKey",{status:400});const{headers:T,identity:A}=await ue(o,i,s);if(e.authorizeShard){if(!await e.authorizeShard(A,m))return new Response("Forbidden",{status:403})}else S("shard");const N=new Headers(o.headers);N.delete("x-lunora-userid"),N.delete("x-lunora-identity"),N.delete("x-lunora-identity-exp");const q=T["x-lunora-userid"],x=T["x-lunora-identity"],B=T["x-lunora-identity-exp"];return q!==void 0&&N.set("x-lunora-userid",q),x!==void 0&&N.set("x-lunora-identity",x),B!==void 0&&N.set("x-lunora-identity-exp",B),ae(R,m,new Request(o,{headers:N}))},Lt=async(o,i,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,o.table,i))throw new a("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(i.startsWith("__lunora_relation__:"))throw new a("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new a("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});S("fan-out")},be=async(o,i)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Lt(o.fanOut,o.functionPath,i);return}if(e.authorizeShard){const l=o.shardKey??n;if(!await e.authorizeShard(i,l))throw new a("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else o.shardKey!==void 0&&o.shardKey!==n&&S("shard")}},Ae=async(o,i,l,d,w,b)=>{const R=Date.now(),{observability:m,sampling:T}=e,A=Le(o),{decision:N,ignoredUpstream:q,trace:x}=Vn(o,{...T===void 0?{}:{sampling:T},trustInbound:t(o)});q&&r();const B={...w,"x-lunora-sample-errors":N.keepErrors?"1":"0"};Yn(x,B);const W=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:l,functionPath:i}),headers:B,method:"POST"});try{const G=await ae(u,d,W);return de(m,{...A,...lt(x),durationMs:Date.now()-R,functionPath:i,ok:G.ok,shardKey:d,...G.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(G.status)}`,status:G.status}}},b,void 0,{isTraced:x.sampled,keepErrors:N.keepErrors}),G}catch(G){throw de(m,{...A,...lt(x),...Oe(i,Date.now()-R,G,{shardKey:d})},b,void 0,{isTraced:x.sampled,keepErrors:N.keepErrors}),G}},jt=o=>{if(o.fanOut&&o.shardKey)throw new a("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!o.fanOut&&o.functionPath.startsWith("__lunora_relation__:"))throw new a("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403});if(o.fanOut&&!e.queryCoordinator)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},$t=async(o,i,l)=>{if(o.method!=="POST")throw new a("RPC endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const d=await Ho(o);Wo(i,d),jt(d);const w=await oe(o,d);if(w!==void 0)return w;const{headers:b,identity:R}=await ue(o,i,s);await be(d,R);const m=ft(d,e);{const T=Date.now(),{observability:A}=e,N=Le(o),q=Ee(i,o,l&&(W=>l.waitUntil?.(W)));if(d.fanOut){const W=e.queryCoordinator;if(!W)throw new a("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const G=await W.fanOut(u,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:b});return de(A,{durationMs:Date.now()-T,fanOut:{failed:G.failed,shards:G.ok+G.failed,table:d.fanOut.table},functionPath:d.functionPath,...N,ok:!0},q),Response.json(G,{headers:{"content-type":"application/json"},status:200})}catch(G){throw de(A,{...Oe(d.functionPath,Date.now()-T,G,{fanOut:{table:d.fanOut.table}}),...N},q),G}}const x=d.shardKey??n,B=()=>Ae(o,d.functionPath,d.args??{},x,b,q);return m&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:m.price},B,ct(l)):B()}},Gt=async(o,i,l)=>{if(o.method!=="POST")throw new a("RPC batch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const d=await Z(o),{calls:w}=d;if(!Array.isArray(w))throw new a("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:R}=await ue(o,i,s),m=zr(w,n);for(const Q of m.values())for(const z of Q)if(e.functions?.[z.functionPath]?.x402)throw new a(`paid (\`.x402\`) function "${z.functionPath}" cannot be called in a batch; dispatch it individually over ${ut}`,{code:"BAD_REQUEST",status:400});await Promise.all([...m.entries()].flatMap(([Q,z])=>z.map(ne=>be({functionPath:ne.functionPath,shardKey:Q},R))));const{observability:T}=e,A=Ee(i,o,l&&(Q=>l.waitUntil?.(Q))),N=Le(o),q=[],x=[],B=(Q,z,ne,ce)=>({body:{error:{code:ne,message:ce}},id:Q.id,status:z}),W=(Q,z,ne,ce,fe)=>{for(const H of Q)de(T,fe(H),A),q.push(B(H,z,ne,ce))},G=(Q,z,ne,ce,fe)=>{for(const H of Q){const we=ce.get(H.id)??fe,ye=we<400;de(T,{durationMs:ne,functionPath:H.functionPath,...N,ok:ye,shardKey:z,...ye?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(we)}`,status:we}}},A)}};await Promise.all([...m.entries()].map(async([Q,z])=>{const ne=new Headers(b);ne.set("content-type","application/json");const ce=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:z}),headers:ne,method:"POST"}),fe=Date.now();let H;try{H=await ae(u,Q,ce)}catch(V){const Ie=Date.now()-fe,{body:Qe}=ar(V,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});W(z,502,Qe.code,Qe.message,nr=>({...Oe(nr.functionPath,Ie,V,{shardKey:Q}),...N}));return}const we=Date.now()-fe,ye=H.headers.get("x-d1-bookmark");ye&&x.push(ye);let De;try{De=await H.json()}catch{const V=`shard batch returned a non-JSON response (${String(H.status)})`;W(z,H.status,"SHARD_ERROR",V,Ie=>({durationMs:we,error:{code:"SHARD_ERROR",message:V,status:H.status},functionPath:Ie.functionPath,...N,ok:!1,shardKey:Q}));return}const ke=Array.isArray(De.results)?De.results:[],tr=new Map(ke.map(V=>[V.id,V.status??H.status])),rr=new Set(ke.map(V=>V.id));G(z,Q,we,tr,H.status),q.push(...ke);for(const V of z)rr.has(V.id)||q.push(B(V,H.status,"SHARD_ERROR",`shard batch omitted result for call ${String(V.id)}`))}));const Ke={"content-type":"application/json"},[Fe]=x;return x.length===1&&Fe!==void 0&&(Ke["x-d1-bookmark"]=Fe),Response.json({results:q},{headers:Ke,status:200})},Mt=async(o,i,l,d={},w={})=>{try{const b=l.__lunoraRef;if(typeof b!="string")throw new a("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:R,identity:m}=await ue(o,i,s);await be({functionPath:b,shardKey:w.shardKey},m);const T=w.shardKey??n,A=Ee(i,o,w.waitUntil);return await Ae(o,b,d,T,R,A)}catch(b){return ze(b)}},Kt=1e3,Ft=async(o,i)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const d=[];let w;for(let R=0;R<Kt;R+=1){const m=await o.list({cursor:w,prefix:i});for(const T of m.objects)T.key.endsWith(".manifest.json")&&d.push(T.key);if(!m.truncated||m.cursor===void 0)break;w=m.cursor}const b=d.toSorted((R,m)=>m.localeCompare(R)).slice(l);await Promise.all(b.flatMap(R=>{const m=R.slice(0,-14);return[o.delete(R),o.delete(m)]}))},Qt=async o=>{const i=e.backupStore,l=e.queryCoordinator;if(!i)throw new a("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new a("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const d=E();if(!d||d.length===0)throw new a("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const w={authorization:`Bearer ${d}`,"content-type":"application/json"},b=e.backupTables;let R=0,m=0;const T=[];await nt(e,l,w,b,W=>{const G=`${JSON.stringify(W)}
|
|
5
|
-
`;R+=1,m+=Ao.encode(G).byteLength,T.push(G)},u);const A=e.backupPrefix??"backups/",N=new Date(o.scheduledTime).toISOString(),q=`${A}lunora-backup-${N.replaceAll(/[.:]/gu,"-")}.ndjson`,x=`${q}.manifest.json`;await i.put(q,new Blob(T,{type:"application/x-ndjson"}),{httpMetadata:{contentType:"application/x-ndjson"}});const B={bytes:m,createdAt:N,cron:o.cron,file:q,id:N,rows:R,scheduledTime:o.scheduledTime,...b?{tables:b.join(",")}:{}};await i.put(x,`${JSON.stringify(B,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Ft(i,A)},Ge=async(o,i,l)=>{const{observability:d}=e,w=Date.now(),b=_e(16),R=_e(8),m=pt(i);try{const T=await l();return de(d,{durationMs:Date.now()-w,functionPath:o,ok:!0,spanId:R,traceId:b},m),T}catch(T){throw de(d,{...Oe(o,Date.now()-w,T,{}),spanId:R,traceId:b},m),T}finally{We(d,m)}},zt=async(o,i,l)=>{f(i);const d=[],w=m=>m instanceof Error?m:new Error(String(m)),b=e.crons?.[o.cron];if(b)try{await b(o,i,l)}catch(m){d.push(w(m))}if(await Y(o.cron,i,d,w),e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron)try{await Qt(o)}catch(m){d.push(w(m))}const[R]=d;if(d.length===1&&R)throw R;if(d.length>1)throw new AggregateError(d,`scheduled("${o.cron}") had ${String(d.length)} failure(s)`)},Wt=async(o,i)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;const w=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:{outcome:i},functionPath:jo}),headers:{authorization:`Bearer ${d}`,"content-type":"application/json"},method:"POST"});await ae(u,n,w)}catch{}},Ht=async(o,i,l,d)=>{if(!e.authHandler)return;const w=await e.authHandler(o);if(!w)return;const b=e.authBasePath??Lo;return Mo(l.pathname,b)&&d.waitUntil?.(Wt(i,w.status>=400?"fail":"ok")),w},Jt=async({args:o,env:i,functionPath:l,request:d,shardKey:w,waitUntil:b})=>{yt(o,"REST");const R={functionPath:l,...w===void 0?{}:{shardKey:w}},{headers:m,identity:T}=await ue(d,i,s);await be(R,T);const A=w??n,N=Ee(i,d,b),q=()=>Ae(d,l,o,A,m,N),x=ft(R,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},q,ct({waitUntil:b})):q()},Vt=wr({functions:e.functions??{},invoke:Jt,readJsonBody:Z,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ve=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,Yt={[qo]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Do]:(o,i,l)=>Ct(o,i,l),[ut]:(o,i,l,d)=>$t(o,i,d),[vo]:(o,i,l,d)=>Gt(o,i,d),[ko]:(o,i)=>F(o,i),[Io]:(o,i)=>U(o,i),[Po]:async o=>{if(o.method!=="POST")throw new a("ws-token endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});$(o);const i=E();if(i===void 0)throw new a("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await Lr(i);return Response.json(l,{headers:{"cache-control":"no-store"}})},...I,...se,...Re,...re,...At,...vt,...Dt,...kt,...It,...Nt,...Vt,...Mr({assertAdmin:$,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ee,readJsonBody:Z})};let ie=Je(e.security),Me=!1;const Xt=o=>{Me||(Me=!0,ie=Je(e.security,o??{}))},Zt=async(o,i)=>{if(!(e.adminGate===void 0||!xo(i)))try{await e.adminGate(o)&&g.add(o)}catch{}},er=async(o,i,l)=>{const d=new URL(o.url);if(o.method==="POST"||o.method==="PUT"){const m=Number(o.headers.get("content-length")??""),T=d.pathname===_t?St:mt;if(Number.isFinite(m)&&m>T)throw new a("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const w=await Ht(o,i,d,l);if(w)return w;if(ve){const m=`${o.method} ${d.pathname}`,T=ve[m]??ve[d.pathname];if(T)return T(o,i,l)}const b=Yt[d.pathname];return b?(await Zt(o,d.pathname),b(o,i,d,l)):e.voiceAgents!==void 0&&d.pathname.startsWith(ht)?Bt(o,i,d):await xt(o,i,l)||new Response("Not found",{status:404})};return{async fetch(o,i,l){e.passThroughOnException&&l.passThroughOnException?.(),Xt(i),f(i);const d=Sr(o,ie);if(d)return d;const w=Rr(o,ie);if(w)return Ne(w,o,ie);try{const b=await er(o,i,l);return Ne(b,o,ie)}catch(b){return Ne(ze(b),o,ie)}finally{We(e.observability,pt(l))}},async queue(o,i,l){await Ge(`queue:${Fo(o)}`,l,async()=>{await e.queue?.(o,i,l)})},async scheduled(o,i,l){await Ge(`cron:${o.cron}`,l,async()=>{await zt(o,i,l)})},serverQuery:Mt}},ra=e=>Rt(e),na=e=>typeof e=="function"?{fetch:e}:e,oa=e=>!!(e.crons??e.cronJobs??e.backupCron),Ea=(e,t)=>{const r=na(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,s=c=>{const h=ra({...c,httpRouter:r});return n!==void 0&&!oa(c)?{...h,scheduled:async(E,O,D)=>{await n(E,O,D)}}:h};if(typeof t!="function")return s(t);const u=t;return{fetch:(c,h,E)=>s(u(h)).fetch(c,h,E),queue:(c,h,E)=>s(u(h)).queue?.(c,h,E)??Promise.resolve(),scheduled:(c,h,E)=>s(u(h)).scheduled(c,h,E),serverQuery:(c,h,E,O,D)=>s(u(h)).serverQuery(c,h,E,O,D)}},aa=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new a("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Oa=(e={})=>(t,r,n)=>Rt(aa(e,r)).fetch(t,r,n??sr),Ta=e=>e;export{Kr as GET_AUTH_AUDIT_LOG_OP,sr as NOOP_EXECUTION_CONTEXT,Ra as composeIdentityResolvers,ra as composeWorker,Oa as createLunoraHandler,Rt as createWorker,Ta as defineRpcEnvelope,Yo as probeRelayCount,aa as resolveLunoraOptions,Aa as routeIdentityResolvers,Ea as withFrameworkWorker};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as O}from"./LunoraError-ByasbDmd.mjs";import{resolveShard as E}from"./applyJurisdiction-8bzZjAPR.mjs";const he=r=>({listShardKeys(e){return r[e]??[]}}),le=r=>{if(r.kind==="count")return{kind:"sum"};if(r.kind==="scalar"){if(r.op==="count"||r.op==="sum")return{kind:"sum"};if(r.op==="max")return{kind:"max"};if(r.op==="min")return{kind:"min"};throw new O('aggregate({ op: "avg" }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})}const e=r.agg?.op??"count";if(e==="count"||e==="sum")return{kind:"groupBy",op:"sum"};if(e==="max")return{kind:"groupBy",op:"max"};if(e==="min")return{kind:"groupBy",op:"min"};throw new O('groupBy({ agg: { op: "avg" } }) is not supported across shards in v1 — fan out sum + count separately',{code:"BAD_REQUEST",status:400})},T=16,j=5e3,f=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,C=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},q=(r,e)=>r?"failed":e?"in_progress":"completed",F=r=>{const e=[];let s=0,a=0,t=0,o=0,n=!1,i=!1;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}s+=1;const d=f(c.value),u=C(d);t+=u.changed,o+=u.processed,n||=u.status==="in_progress",i||=u.status==="failed",e.push({result:d,shardKey:c.shardKey})}return{changed:t,failed:a,ok:s,processed:o,shards:e,status:q(i,n||a>0)}},B=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},I=r=>{const e=[];let s=0,a=0,t=0,o=0;for(const n of r){if(n.kind==="err"){a+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const i=B(f(n.value));t+=i.before,o+=i.total,e.push({result:i,shardKey:n.shardKey})}return{failed:a,ok:s,partial:a>0,position:t+1,shards:e,total:o}},P=0,N=1,D=2,x=r=>r==null?P:typeof r=="number"?N:D,v=(r,e)=>{const s=x(r),a=x(e);if(s!==a)return s<a?-1:1;if(s===P)return 0;if(s===N){const n=r,i=e;return n<i?-1:n>i?1:0}const t=String(r),o=String(e);return t<o?-1:t>o?1:0},R=(r,e,s)=>{const a=v(r.partitionKey,e.partitionKey);if(a!==0)return a;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let o=0;o<t;o+=1){const n=v(r.sortValues[o],e.sortValues[o]);if(n!==0)return s[o]==="desc"?-n:n}return v(r.rowId,e.rowId)},V=r=>{const e=JSON.stringify(r),s=new TextEncoder().encode(e);let a="";for(const t of s)a+=String.fromCodePoint(t);return btoa(a)},$=r=>{let e;try{const s=atob(r),a=Uint8Array.from(s,t=>t.codePointAt(0)??0);e=new TextDecoder().decode(a)}catch{return{perShard:{}}}try{const s=JSON.parse(e);if(s!==null&&typeof s=="object"&&"perShard"in s){const{perShard:a}=s;if(a!==null&&typeof a=="object")return{perShard:a}}}catch{}return{perShard:{}}},J=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Q=(r,e)=>{let s,a;for(const t of r){const o=t.rows[t.head];o!==void 0&&(a===void 0||R(o.key,a,e)<0)&&(s=t,a=o.key)}return s},U=(r,e)=>{let s=!1;const a=new Set;for(const o of r)a.add(o.shardKey),(o.head<o.rows.length||o.hasMore)&&(s=!0);const t={...e};for(const o of Object.keys(e))a.has(o)||(s=!0);return s?V({perShard:t}):null},L=(r,e,s,a)=>{const t=[],o={...a};for(;t.length<e;){const i=Q(r,s);if(i===void 0)break;const c=i.rows[i.head];c!==void 0&&(t.push(c.doc),o[i.shardKey]=c.key),i.head+=1}const n=U(r,o);return{isDone:n===null,nextCursor:n,page:t}},G=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const o=f(t.value),n=Array.isArray(o?.rows)?o.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},Y=r=>{const e=[];let s=0,a=0;for(const{outcome:t,sinceSeq:o}of r){if(t.kind==="err"){a+=1,e.push({cursor:o,error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=f(t.value),i=Array.isArray(n?.changes)?n.changes:[],c=typeof n?.cursor=="number"?n.cursor:o;e.push({changes:i,cursor:c,shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},z=r=>{let e=0,s=0,a=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const o=f(t.value);a+=typeof o?.applied=="number"?o.applied:0}return{applied:a,failed:s,ok:e}},H=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},W=r=>{const e=[];let s=0,a=0;for(const t of r){if(t.kind==="err"){a+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:H(f(t.value)),shardKey:t.shardKey})}return{failed:a,ok:s,shards:e}},X=r=>{const e=[],s={},a=[];let t=0,o=0,n=0;for(const i of r){if(i.kind==="err"){n+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}o+=1;const c=f(i.value),d=c?.inserted??{};for(const[h,y]of Object.entries(d))s[h]=(s[h]??0)+y;const u=c?.errors;Array.isArray(u)&&a.push(...u),t+=c?.conflicts??0,e.push({result:{conflicts:c?.conflicts??0,errors:c?.errors??[],inserted:d},shardKey:i.shardKey})}return{conflicts:t,errors:a,failed:n,inserted:s,ok:o,shards:e}},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),g=async(r,e,s,a)=>{const t=E(r,e),o=new AbortController,n=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:o.signal});let i;const c=new Promise(u=>{i=setTimeout(()=>{try{o.abort()}catch{}u({kind:"err",message:`shard "${e}" timed out after ${String(a)}ms`,shardKey:e,timedOut:!0})},a)}),d=(async()=>{try{const u=await t.fetch(n);if(!u.ok)return{kind:"err",message:`shard "${e}" returned ${String(u.status)}`,shardKey:e,timedOut:!1};const h=await u.json();return{kind:"ok",shardKey:e,value:h}}catch(u){const h=u instanceof Error?u.message:String(u);return{kind:"err",message:`shard "${e}" threw: ${h}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,c])}finally{i!==void 0&&clearTimeout(i)}},b=async(r,e,s)=>{if(r.length===0)return[];const a=Array.from({length:r.length});let t=0;const o=async()=>{for(;;){const i=t;t+=1;const c=r[i];if(i>=r.length||c===void 0)return;a[i]=await s(c,i)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>o())),a},m=async(r,e,s,a,t)=>{const o=p(s);return b(e,a,async n=>g(r,n,o,t))},Z=(r,e)=>r<e?-1:r>e?1:0,ee=r=>{const e={};for(const s of Object.keys(r).toSorted(Z))e[s]=r[s]??null;return JSON.stringify(e)},re=r=>{const e=[];for(const s of r)Array.isArray(s)&&e.push(...s);return e},te=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},se=(r,e,s)=>{if(e===null||typeof e!="object")return;const a=e.key??{},t=e.value??null,o=ee(a),n=r.get(o);if(!n){r.set(o,{key:a,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=te(n.value,t,s))},ae=(r,e)=>{const s=new Map;for(const a of r)if(Array.isArray(a))for(const t of a)se(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const a of r)typeof a=="number"&&Number.isFinite(a)&&(s=s===null?a:e(s,a));return s},oe=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ne=r=>{let e=0,s=0;for(const a of r){if(a===null||typeof a!="object")continue;const t=a;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ie=(r,e)=>{const s=[];for(const o of r)if(Array.isArray(o))for(const n of o){if(n===null||typeof n!="object")continue;const i=n[e.by],c=typeof i=="number"&&Number.isFinite(i)?i:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const a=e.direction??"desc",t=(o,n)=>o<n?-1:o>n?1:0;return s.sort((o,n)=>a==="asc"?t(o.score,n.score):t(n.score,o.score)),s.slice(0,e.k).map(o=>o.row)},ue=(r,e)=>{switch(e.kind){case"concat":return re(r);case"first":return r[0];case"groupBy":return ae(r,e.op??"sum");case"max":return M(r,(s,a)=>Math.max(s,a));case"min":return M(r,(s,a)=>Math.min(s,a));case"rank":return ne(r);case"sum":return oe(r);case"topK":return ie(r,e);default:return r}},fe=r=>{const e=r.maxConcurrency??T,s=r.perShardTimeoutMs??j;if(e<1)throw new O("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(a,t){const o=await r.registry.listShardKeys(t.fanOut.table),n=await m(a,o,t,e,s),i=[],c=[],d=[];for(const u of n)u.kind==="ok"?(i.push(u.value),c.push(u.shardKey)):d.push({message:u.message,shardKey:u.shardKey,timedOut:u.timedOut});return{data:ue(i,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(a,t){const o=new Set,n=await Promise.all(t.tables.map(async u=>r.registry.listShardKeys(u)));for(const u of n)for(const h of u)o.add(h);const i=[...o],c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await m(a,i,c,e,s);return G(d)},async orchestrateCdcSync(a,t){const o=new Set,n=await Promise.all(t.tables.map(async u=>r.registry.listShardKeys(u)));for(const u of n)for(const h of u)o.add(h);const i=[...o],c=t.cursors??{},d=await b(i,e,async u=>{const h=c[u]??0;return{outcome:await g(a,u,p({args:{limit:t.limit,sinceSeq:h},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceSeq:h}});return Y(d)},async orchestrateImport(a,t){const{batches:o}=t,n=await b(o,e,async i=>g(a,i.shardKey,p({args:{rows:[...i.rows],startLine:i.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return X(n)},async orchestrateApplyCdc(a,t){const{batches:o}=t,n=await b(o,e,async i=>g(a,i.shardKey,p({args:{changes:[...i.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return z(n)},async orchestrateMigration(a,t){const o=await r.registry.listShardKeys(t.table),n=await m(a,o,t,e,s);return F(n)},async orchestrateRank(a,t){const o=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},i=await m(a,o,n,e,s);return I(i)},async orchestrateRankPage(a,t){const o=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),i=t.directions??[],c=t.cursor?$(t.cursor):{perShard:{}},d=await b(o,e,async l=>{const A=c.perShard[l],S={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(S.partitionKey=t.partitionKey),A!==void 0&&(S.after=A);const w=await g(a,l,p({args:S,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(w.kind==="err")return{error:{message:w.message,timedOut:w.timedOut},shardKey:l};const _=J(f(w.value));return{directions:_.directions,hasMore:_.hasMore,rows:_.rows,shardKey:l}}),u=[];let h=0,y=0,K;for(const l of d){if(l.error){y+=1;continue}h+=1,K===void 0&&l.directions&&l.directions.length>0&&(K=l.directions),u.push({hasMore:l.hasMore??!1,head:0,rows:l.rows??[],shardKey:l.shardKey})}const k=L(u,n,K??i,c.perShard);return{continueCursor:k.nextCursor,failed:y,isDone:k.isDone,ok:h,page:k.page,partial:y>0,shards:d}},async orchestrateShardTraffic(a,t){const o=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},i=await m(a,o,n,e,s);return W(i)},registry:r.registry}};export{fe as createQueryCoordinator,he as createStaticShardRegistry,le as mergeStrategyForAggregate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{a as g,o as j,f as E,u as O}from"./identity-header-CDgIrYAz.mjs";import{applyJurisdiction as N,resolveShard as R}from"./applyJurisdiction-8bzZjAPR.mjs";const i="$lunora.wire$",m=64,v=1024,A="__proto__",$={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},S={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},x=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},f=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const l=typeof r;if(l==="bigint")return[i,"bigint",r.toString()];if(l==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(l!=="object")return r;if(r instanceof Date)return[i,"date",f(r.getTime(),t+1)];if(r instanceof Error){const e=r,o={};for(const s of Object.keys(e))e[s]!==void 0&&(o[s]=f(e[s],t+1));const n=[i,"error",e.name,e.message,o];return e.cause!==void 0&&n.push(f(e.cause,t+1)),n}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,o])=>[f(e,t+1),f(o,t+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>f(e,t+1))];if(r instanceof ArrayBuffer)return[i,"bytes",g(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,o=e.constructor.name,n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o==="Uint8Array"?[i,"bytes",g(n)]:[i,"bytes",g(n),o]}if(Array.isArray(r)){const e=r.map(o=>f(o,t+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!x(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const d=r,a={};for(const e of Object.keys(d)){const o=d[e];if(o===void 0)continue;const n=f(o,t+1);e===A?Object.defineProperty(a,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):a[e]=n}return a},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(a=>u(a,t+1));case"bigint":{const a=r[2];if(typeof a!="string"||a.length>v||!/^-?\d+$/.test(a))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(a)}case"date":return new Date(u(r[2],t+1));case"map":return new Map(r[2].map(([a,e])=>[u(a,t+1),u(e,t+1)]));case"set":return new Set(r[2].map(a=>u(a,t+1)));case"url":return new URL(r[2]);case"error":{const a=r[2],e=r[3],o=(Object.hasOwn(S,a)?S[a]:void 0)??Error,n=new o(e);n.name!==a&&Object.defineProperty(n,"name",{configurable:!0,value:a,writable:!0});const s=u(r[4],t+1);for(const c of Object.keys(s))c===A?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:s[c],writable:!0}):n[c]=s[c];return r.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:u(r[5],t+1),writable:!0}),n}case"bytes":{const a=j(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return a.buffer.byteLength===a.byteLength?a.buffer:a.slice().buffer;const o=Object.hasOwn($,e)?$[e]:void 0;return o?new o(a.slice().buffer):a}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(a=>u(a,t+1))}return r.map(a=>u(a,t+1))}const l=r,d={};for(const a of Object.keys(l)){const e=u(l[a],t+1);a===A?Object.defineProperty(d,a,{configurable:!0,enumerable:!0,value:e,writable:!0}):d[a]=e}return d},I=r=>{if(typeof r=="string")return r;const t=r?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new b("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},U=r=>{const t=new b(r.code,r.message);return r.data!==void 0&&(t.data=u(r.data)),t},L=(r,t={})=>{const l=N(r,t.jurisdiction),d=t.system??!0,a=e=>L(r,{...t,...e});return{as:e=>a({as:e}),asSystem:()=>a({as:void 0}),call:async(e,o,n)=>{const s=I(e),c=n?.shardKey??t.shardKey;if(c===void 0||c.length===0)throw new b("INTERNAL",`createShardClient: no shard key for "${s}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const p={"content-type":"application/json"};d&&(p["x-lunora-system"]="1"),t.as&&(p["x-lunora-userid"]=E(t.as.userId),t.as.claims&&(p["x-lunora-identity"]=O(t.as.claims))),n?.mutationId!==void 0&&n.mutationId.length>0&&(p["x-lunora-mutation-id"]=n.mutationId);const y=await R(l,c).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:f(o??{}),functionPath:s}),headers:p,method:"POST"}));let h;try{h=await y.json()}catch{const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard response for "${s}" was not JSON (status ${String(y.status)}${w})`)}if("error"in h)throw U(h.error);if(!y.ok){const w=y.statusText?` ${y.statusText}`:"";throw new b("INTERNAL",`createShardClient: shard call "${s}" failed (status ${String(y.status)}${w})`)}return u(h.result)},forShard:e=>a({shardKey:e})}};export{L as createShardClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as a,a as s,f}from"./observability-DYnm-d4g.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const c=t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},f=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},l=t=>c(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");new TextDecoder;const a=new TextEncoder,o="=",s=t=>{for(let e=0;e<t.length;e+=1)if(t.charCodeAt(e)>255)return!1;return!0},d=t=>l(a.encode(JSON.stringify(t))),h=t=>!t.startsWith(o)&&s(t)?t:`${o}${l(a.encode(t))}`;export{c as a,h as f,f as o,d as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v=s=>{const e=new WeakMap;return(t,c)=>{const a=e.get(t);if(a)return a;const o=Promise.resolve(s(t,c));return e.set(t,o),o}},h=s=>{const e=s.headers.get("cookie")??"",t=s.headers.get("authorization")??"";if(!(e===""&&t===""))return`${t}\0${e}`},p=(s,e={})=>{const t=e.ttlMs??5e3,c=Math.max(1,e.maxEntries??500),a=e.cacheKey??h,o=v(s),r=new Map;return(u,l)=>{const n=a(u);if(n===void 0)return o(u,l);const m=Date.now(),d=r.get(n);if(d&&d.expiresAt>m)return d.value;const i=Promise.resolve(o(u,l));for(i.catch(()=>{r.get(n)?.value===i&&r.delete(n)}),r.delete(n),r.set(n,{expiresAt:m+t,value:i});r.size>c;){const f=r.keys().next();if(f.done===!0)break;r.delete(f.value)}return i}};export{p as memoizeIdentity,v as memoizeIdentityPerRequest};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=(e,o)=>o.includes(e.method)?void 0:new Response(void 0,{headers:{allow:o.join(", ")},status:405});export{s as d};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const c=r=>{const e=Number.parseInt(r.slice(0,8),16);return Number.isFinite(e)?e/4294967296:0},i=(r,e=1)=>e>=1?!0:e<=0?!1:c(r)<e,n=(r,e)=>({isTraced:i(e,r?.headRate??1),keepErrors:r?.alwaysSampleErrors??!0}),a=(r,e)=>r.isTraced||r.keepErrors&&e,f=(r,e,s,t,o)=>{if(r?.onRpc){if(o!==void 0){if(!a(o,!e.ok))return}else if(t!==void 0&&e.traceId!==void 0&&!a(n(t,e.traceId),!e.ok))return;try{r.onRpc(e,s)}catch{}}},u=(r,e,s)=>{if(r?.onLog)try{r.onLog(e,s)}catch{}},d=(r,e)=>{if(r?.flush)try{r.flush(e)}catch{}};export{f as a,u as e,d as f,n as o};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{raw as n,desc as x,sql as d}from"@lunora/bindings/r2sql";const p=["trace","debug","log","info","warn","error","fatal"],E={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},M=500,g=1e4,A=e=>{if(e===void 0||!Number.isFinite(e))return M;const s=Math.floor(e);return s<1?1:s>g?g:s},D=e=>typeof e=="number"?e:Number(e),v=e=>e==null?"":String(e),F=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},T=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,u=0;for(const I of s){const $=I.codePointAt(0)??0;t=(t*31+$)%2147483647,u=(u*131+$)%4294967291}return`${t.toString(36)}.${u.toString(36)}`},R=(e,s,t,u)=>{if(s.sinceTs!==void 0&&e.where(d`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(d`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(d`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const I=p.indexOf(s.minLevel),$=I===-1?[...p]:p.slice(I);e.where(d`${n(t.level)} IN ${$}`)}s.functionPath!==void 0&&e.where(d`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(d`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(d`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(d`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(d`${n(t.userId)} = ${s.userId}`),u!==void 0&&e.where(d`${n(t.ts)} <= ${u}`)},G=E,U=M,q=(e,s)=>{const t={...E,...s.columnMap},u=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,I=r=>{const o={functionPath:v(r[t.functionPath]),level:v(r[t.level]),message:v(r[t.message]),ts:D(r[t.ts])},a=r[t.fields];a!=null&&(o.fields=F(a));const i=r[t.shardKey];i!=null&&(o.shardKey=v(i));const l=r[t.userId];l!=null&&(o.userId=v(l));const h=r[t.traceId];h!=null&&(o.traceId=v(h));const m=r[t.spanId];return m!=null&&(o.spanId=v(m)),o},$=async(r,o,a)=>{const i=e.from(u).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));R(i,r,t,o),i.orderBy(x(n(t.ts))).limit(a);const{rows:l}=await i.run();return l},N=async(r,o,a,i)=>{const l=await $(r,o,i),h=[];for(const m of l){const c=I(m);a!==void 0&&o!==void 0&&c.ts===o&&a.has(T(c))||h.push(c)}return{decoded:h,truncated:l.length>=i}};return{query:async(r={})=>{const o=A(r.limit),{cursor:a}=r,i=a?.ts,l=a?.seen!==void 0&&a.seen.length>0?new Set(a.seen):void 0,h=Math.min(o+1,g),m=3;let c=[],P=!1;for(let f=0;f<m;f+=1){const b=Math.min(h*2**f,g),S=await N(r,i,l,b);if(c=S.decoded,P=S.truncated,c.length>o||!P||b>=g)break}const L=c.length>o,w=L?c.slice(0,o):c,K=w.at(-1);if(K===void 0||!(L||P))return{rows:w};const y=K.ts,_=w.filter(f=>f.ts===y).map(f=>T(f)),O=[...i===y&&a?.seen!==void 0?a.seen:[],..._];return{nextCursor:O.length>0?{seen:O,ts:y}:{ts:y},rows:w}}}};export{G as D,p as L,U as a,q as c};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as A,a as E}from"./rest-cache-5unAzdFN.mjs";import{LunoraError as d}from"./LunoraError-ByasbDmd.mjs";import{d as O}from"./method-guard-BbuR0VfS.mjs";const h=1048576,p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),T=async(t,a=h)=>{if(!t.body)return"";const e=t.body.getReader(),r=new TextDecoder;let s=0,n="";for(;;){const{done:o,value:c}=await e.read();if(o)break;if(c){if(s+=c.byteLength,s>a)throw await e.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});n+=r.decode(c,{stream:!0})}}return n+=r.decode(),n},B=async(t,a=h)=>{if(!t.body)return new ArrayBuffer(0);const e=t.body.getReader(),r=[];let s=0;for(;;){const{done:c,value:u}=await e.read();if(c)break;if(u){if(s+=u.byteLength,s>a)throw await e.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});r.push(u)}}const n=new Uint8Array(s);let o=0;for(const c of r)n.set(c,o),o+=c.byteLength;return n.buffer},D=async(t,a=h)=>{let e;try{const r=await T(t,a);e=r===""?{}:JSON.parse(r)}catch(r){throw r instanceof d?r:new d("Request body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!p(e))throw new d("Request body must be an object",{code:"BAD_REQUEST",status:400});return e},k=(t,a)=>{if(!p(t))throw new d(`${a} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},v=t=>Object.entries(t).map(([a,e])=>({exposure:e.expose,functionPath:a,kind:e.kind})),L=t=>E(v(t)),P=(t,a)=>{const e=t.searchParams.get("shardKey");if(e!==null&&e!=="")return e;const r=a.headers.get("x-lunora-shard-key");return r===null||r===""?void 0:r},S=t=>{const a=Object.create(null);for(const[e,r]of t.searchParams.entries())if(e!=="shardKey")try{a[e]=JSON.parse(r)}catch{a[e]=r}return a},$=t=>{const{functions:a,invoke:e,rateLimit:r,readJsonBody:s}=t,n={};for(const o of L(a)){const c=o.kind==="query"?["GET","POST"]:["POST"],u=a[o.functionPath].expose?.cache;n[o.path]=async(i,R,U,l)=>{const w=O(i,c);if(w)return w;const b=new URL(i.url);if(r){const y=await r(i,o.functionPath);if(y)return y}let f;i.method==="GET"?f=S(b):f=i.body===null?{}:await s(i),k(f,"REST");const m=P(b,i),g=await e({args:f,env:R,functionPath:o.functionPath,request:i,...m===void 0?{}:{shardKey:m},...l?.waitUntil===void 0?{}:{waitUntil:y=>l.waitUntil?.(y)}});return A(g,u,i)}}return n},q=(t,a)=>async(e,r)=>{const s=a.key?a.key(e,r):e.headers.get("cf-connecting-ip")??void 0,n=await t.limit(a.name,s===void 0?{}:{key:s});if(n.ok)return;const o=Math.max(1,Math.ceil(n.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(o)},status:429})};export{$ as S,q as U,T as a,D as b,h as d,k as e,L as f,S as g,P as p,B as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const h=(s,o="_id")=>{const r={},t={},a={},c={},l=e=>typeof o=="string"?o:o[e]??"_id",n=(e,d)=>{const u=e[d];if(u)return u;const p=[];return e[d]=p,p};for(const e of s.changes)c[e.table]??={primary_key:[l(e.table)]},e.op==="delete"?n(a,e.table).push(e.doc):e.op==="update"?n(t,e.table).push(e.doc):n(r,e.table).push(e.doc);return{delete:a,hasMore:s.hasMore,insert:r,schema:c,state:{cursor:s.nextCursor},update:t}},i=(s,o=Date.now())=>{const r=[];for(const t of s.changes){const a=t.op==="delete"?{...t.doc,_lunora_deleted:!0}:t.doc;r.push({record:{data:a,emitted_at:o,stream:t.table},type:"RECORD"})}return r.push({state:{data:{cursor:s.nextCursor}},type:"STATE"}),r};export{i as toAirbyteMessages,h as toFivetranResponse};
|