@lunora/runtime 1.0.0-alpha.54 → 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 +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.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-Cqrg0Dq3.mjs → HEALTH_PATH-CmjJOkwf.mjs} +1 -1
- package/dist/packem_shared/{LOG_ARCHIVE_PATH-CuHKuDCS.mjs → LOG_ARCHIVE_PATH-5vxNUndx.mjs} +1 -1
- package/dist/packem_shared/{LunoraError-ByasbDmd.mjs → LunoraError-C08OP5Uq.mjs} +1 -1
- package/dist/packem_shared/{argsFromQuery-nMGzM5bK.mjs → argsFromQuery-Cp8uiYaU.mjs} +1 -1
- 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-CdYCKy9v.mjs → createCrossShardRelationCapabilities-BokiysHJ.mjs} +1 -1
- package/dist/packem_shared/{createQueryCoordinator-D7NpIHuQ.mjs → createQueryCoordinator-NT5oasVP.mjs} +1 -1
- package/dist/packem_shared/{decorateResponse-DBIWsRSZ.mjs → decorateResponse-C6TZSzID.mjs} +1 -1
- package/dist/packem_shared/{method-guard-rzvo19pa.mjs → method-guard-CfF0J5OT.mjs} +1 -1
- package/dist/packem_shared/{rest-routes-BqldHiaH.mjs → rest-routes--GsO-U9C.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/composeWorker--WeDfW17.mjs +0 -6
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;
|
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;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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};
|
|
@@ -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};
|
|
@@ -1 +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-
|
|
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};
|
|
@@ -1 +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-
|
|
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};
|
|
@@ -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-pdXOyDU4.mjs";import{LunoraError as o}from"./LunoraError-
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as E,a as C}from"./base64-DPPVK6s_.mjs";import{LunoraError as A}from"./LunoraError-ByasbDmd.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};
|
|
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};
|
|
@@ -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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as t}from"./LunoraError-
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as A,a as E}from"./rest-cache-5unAzdFN.mjs";import{LunoraError as u}from"./LunoraError-
|
|
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};
|
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,6 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as pr,toErrorBody as fr}from"@lunora/errors";import{d as Rt}from"./evict-oldest-C2XU6HBR.mjs";import{NOOP_EXECUTION_CONTEXT as mr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{f as wr,u as gr}from"./identity-header-pdXOyDU4.mjs";import{O as Te,m as yr,A as br,R as _r,d as Rr,i as Er,s as Sr}from"./otlp-resource-B-ByO9qo.mjs";import{h as ee,f as ye,i as Et,E as Or,w as St,e as Ot,b as Tr}from"./rest-routes-BqldHiaH.mjs";import{LunoraError as i,toErrorResponse as Je}from"./LunoraError-ByasbDmd.mjs";import{runExportTap as vr}from"./createKvCursorStore-C24tEuYk.mjs";import{t as we,r as L}from"./method-guard-rzvo19pa.mjs";import{buildHealthRoutes as Ar,durableObjectProbe as kr,d1Probe as Ir,presenceProbe as Ne}from"./HEALTH_PATH-Cqrg0Dq3.mjs";import{wrapResolverWithContract as Dr}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{composeIdentityResolvers as jo,routeIdentityResolvers as xo}from"./composeIdentityResolvers-DwE0Jbww.mjs";import{buildLogArchiveAdminRoutes as Pr}from"./LOG_ARCHIVE_PATH-CuHKuDCS.mjs";import{o as Ur,f as Ve,a as ce}from"./observability-DWlkDJJw.mjs";import{resolveShard as ve,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-DBIWsRSZ.mjs";const Cr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const r={...t,bucketName:"default"};return r.bucket=()=>r,r},Tt="__lunoraBranch",jr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,Tt),xr=`may not contain the reserved workflow branch-marker key ("${Tt}")`,Fe=(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,u=o<t.length?t.charCodeAt(o):0;n|=d^u}return n===0},Ge=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,vt=async e=>{const t=Ce.get(e);if(t)return t;Rt(Ce,Kr);const r=crypto.subtle.importKey("raw",Ge.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]);return Ce.set(e,r),r},At=async(e,t)=>{const r=await vt(e),n=await crypto.subtle.sign("HMAC",r,Ge.encode(t));return $r(new Uint8Array(n))},Fr=async(e,t,r)=>{const n=await vt(e);return crypto.subtle.verify("HMAC",n,r,Ge.encode(t))},Gr="::relay::",Qr=(e,t)=>`${e}${Gr}${String(t)}`,kt="v1",Mr=6e4,zr=async(e,t={})=>{const r=(t.now??Date.now())+(t.ttlMs??Mr),n=`${kt}.${String(r)}`,o=await At(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,u]=n;if(o!==kt||u.length===0)return!1;const h=Number(d);if(!Number.isFinite(h)||h<=r)return!1;let w;try{w=Lr(u)}catch{return!1}return Fr(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 i(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return r},le=(e,t)=>{const r=e(t);if(r===void 0)throw new i(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return r},It=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,je=(e,t)=>{const r=e[t];return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0},et=e=>{const t=It(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new i("`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 i("`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:je(e,"data"),email:U(e,"email"),name:U(e,"name"),password:te(e,"password"),role:It(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 i("`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:je(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:je(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 i)throw d;const u=d,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new i("auth admin operation failed",{code:h,status:Hr[h]??500})}},r=async(o,d)=>{if(e.assertAdmin(o),o.method!==d.http)throw new i(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new i("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[d.method];if(h===void 0)throw new i(`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]=u=>r(u,d);return n},Yr="__lunora_admin__:getAuthAuditLog",rt=e=>typeof e=="string"&&e!==""?e:void 0,nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Xr=e=>async(t,r)=>{e.assertAdmin(t);const n=e.getReader();if(n===void 0)throw new i("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const o=rt(r.actorId),d=rt(r.event),u=nt(r.sinceSeq),h=nt(r.limit),w={...o===void 0?{}:{actorId:o},...d===void 0?{}:{event:d},...u===void 0?{}:{sinceSeq:u},...h===void 0?{}:{limit:h}};let R;try{R=await n.read(w)}catch(b){throw b instanceof i?b:(console.error("[lunora] auth audit read failed:",b),new i("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const I={entries:R};return Response.json(I,{headers:{"content-type":"application/json"},status:200})},at=500,Zr=(e,t,r)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new i("each batch call must be an object",{code:"BAD_REQUEST",status:400});const n=e;if(typeof n.functionPath!="string")throw new i("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 i("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 i("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}},en=(e,t)=>{if(e.length>at)throw new i(`RPC batch exceeds the ${String(at)}-call limit`,{code:"BAD_REQUEST",status:400});const r=new Map;for(const[n,o]of e.entries()){const{entry:d,shardKey:u}=Zr(o,n,t),h=r.get(u)??[];h.push(d),r.set(u,h)}return r},tn=new TextEncoder,rn=e=>{const t=JSON.stringify(e),r=tn.encode(t);let n="";for(const o of r)n+=String.fromCodePoint(o);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},nn=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:{},u={};for(const[h,w]of Object.entries(d))typeof w=="number"&&Number.isFinite(w)&&(u[h]=w);return{g:typeof o.g=="number"&&Number.isFinite(o.g)?o.g:0,s:u,v:1}}catch{return t}},an=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}},ot=(e,t,r)=>{for(const n of t)e.push(an(n));return r!==void 0&&t.length>=r},on="/_lunora/admin/export",sn="/_lunora/admin/import",cn="/_lunora/admin/sync",dn="/_lunora/admin/connector/sync",un="/_lunora/admin/apply",ln="/_lunora/admin/export-tap/run",hn=new TextEncoder,pn=async e=>{const t=await ye(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new i("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 i("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(n)}return{tables:r}},xe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,fn=e=>{const{applyGlobals:t,exportCursorStore:r,exportSinks:n,knownTables:o,queryCoordinator:d,assertAdmin:u,requireAdminOption:h,resolveForwardContext:w,shardDO:R,streamExportRows:I,streamingImport:b,syncGlobals:k}=e,p=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),P=await pn(v),{headers:Q}=await w(v,x),M=new ReadableStream({async pull(B){const K=X=>{B.enqueue(hn.encode(`${JSON.stringify(X)}
|
|
2
|
-
`))};try{await I(G,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(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),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=xe(P.tables),{headers:X}=await w(v,x),J=K??o(),ne=await G.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})},E=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),Q=nn(P.cursor),M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=xe(P.tables),{headers:K}=await w(v,x),X=B??o(),J=await G.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=ot(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=ot(ne,se.changes,M)||ae,pe=se.cursor}const be=rn({g:pe,s:he,v:1}),Ae={changes:ne,hasMore:ae,nextCursor:be};return Response.json(Ae,{status:200})},_=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,d,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),P=await ee(v),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(v,x),K=await G.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(v,x)=>{const j=we(v,["POST"]);if(j)return j;u(v);const{headers:G}=await w(v,x),P=await b(v,G);return Response.json(P,{headers:{"content-type":"application/json"},status:200})},N=async(v,x)=>{const j=we(v,["POST"]);if(j)return j;const G=h(v,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 i("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const P=await ee(v),Q=typeof P.sink=="string"?P.sink:void 0,M=typeof P.limit=="number"&&P.limit>0?P.limit:void 0,B=xe(P.tables);if(Q===void 0)throw new i("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const K=n[Q];if(K===void 0)throw new i(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:X}=await w(v,x),J=B??o(),ne=await vr({coordinator:G,cursorStore:r,headers:X,limit:M,shardDO:R,sink:K,tables:J});return Response.json(ne,{headers:{"content-type":"application/json"},status:200})};return{[un]:_,[dn]:E,[on]:p,[ln]:N,[sn]:T,[cn]:g}},mn=(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}},wn=async(e,t,r,n,o,d)=>{if(r!==void 0&&n.length===0)return;const u=await e.orchestrateExport(d,{args:{tables:n},headers:t,tables:n});for(const h of u.shards)if(!h.error)for(const w of h.rows??[])o(w)},st=async(e,t,r,n,o,d)=>{const{globalTables:u,shardLocalTables:h}=mn(e,n);await wn(t,r,n,h,o,d);const w=e.exportGlobals;if((n===void 0||u.length>0)&&w)for await(const R of w({tables:u}))o(R)},gn=(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}},yn=(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}},bn=async(e,t,r)=>{if(!e.body)throw new i("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const n=[],o=[],d=new Map;let u=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;u+=1;const E=gn(g,h);if(!E.ok){n.push(E.error);return}const{doc:_,table:T}=E,N=t.resolveTableSharding?.(T);if(N?.mode.kind==="global"){o.push({doc:_,line:h,table:T});return}const v=yn(_,T,N,r,h);if(!v.ok){n.push(v.error);return}const x=d.get(v.shardKey);x?x.rows.push({doc:_,table:T}):d.set(v.shardKey,{rows:[{doc:_,table:T}],shardKey:v.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 i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});I+=R.decode(g,{stream:!0});let E=I.indexOf(`
|
|
3
|
-
`);for(;E!==-1;){const _=I.slice(0,E);I=I.slice(E+1),k(_),E=I.indexOf(`
|
|
4
|
-
`)}}return I.length>0&&k(I),{errors:n,globalRows:o,perShard:d,received:u}},it=(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},_n=async(e,t,r,n)=>{const o=t.defaultShardKey??"__root__",{errors:d,globalRows:u,perShard:h,received:w}=await bn(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 i("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const k=await b.orchestrateImport(n,{batches:[...h.values()],headers:r});it(R,k)}if(u.length>0)if(t.importGlobals){const b=u[0]?.line??1,k=await t.importGlobals({rows:u,startLine:b});it(R,k)}else for(const b of u)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",Rn=(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??{},u={kind:o,name:e,optional:n};if(o==="id"&&typeof d.tableName=="string"&&(u.table=d.tableName),o==="array"){const h=$e(Be(d.inner));h!=="unknown"&&(u.element=h)}return u},En=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,r])=>Rn(t,r)).toSorted((t,r)=>t.name.localeCompare(r.name)),Sn="/_lunora/admin/functions",On="/_lunora/admin/cron-jobs",Tn="/_lunora/admin/openapi",vn="/_lunora/admin/openrpc",An="/_lunora/admin/global/tables",kn="/_lunora/admin/global/table",In="/_lunora/admin/global/facet",ct=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},Dn=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:{}}),Pn=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"}),Un=e=>{const{assertAdmin:t,options:r,parsePaging:n,queryParameter:o,requireAdminOption:d}=e,u=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"}),E=Object.entries(g).flatMap(([_,T])=>T.visibility==="internal"||T.kind==="stream"?[]:[{args:En(T.args),kind:T.kind,path:_}]).toSorted((_,T)=>_.path.localeCompare(T.path));return Response.json({functions:E},{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"}),E=Object.entries(g).flatMap(([_,T])=>T.map(N=>({args:N.args,cron:_,functionPath:N.functionPath,name:N.name,shardKey:N.shardKey,workflow:N.workflow}))).toSorted((_,T)=>_.name.localeCompare(T.name));return Response.json({jobs:E},{headers:{"content-type":"application/json"},status:200})},w=p=>(L(p,"GET","OpenAPI"),t(p),Response.json(r.openApiSpec??Dn,{headers:{"content-type":"application/json"},status:200})),R=p=>(L(p,"GET","OpenRPC"),t(p),Response.json(r.openRpcSpec??Pn,{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"}),E=new URL(p.url),_=o(E,"table");if(_===void 0)throw new i("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const T=await g.readTablePage({...n(p),filters:ct(o(E,"filters")),table:_});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"}),E=new URL(p.url),_=o(E,"table"),T=o(E,"column");if(_===void 0||T===void 0)throw new i("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const N=o(E,"limit"),v=N===void 0?void 0:Number(N),x=await g.facetColumn({column:T,filters:ct(o(E,"filters")),limit:v!==void 0&&Number.isFinite(v)?v:void 0,table:_});return Response.json(x,{headers:{"content-type":"application/json"},status:200})};return{[On]:h,[Sn]:u,[In]:k,[kn]:b,[An]:I,[Tn]:w,[vn]:R}},Nn="/_lunora/admin/kv/namespaces",qn="/_lunora/admin/kv/keys",Dt="/_lunora/admin/kv/value",Pt=32*1048576,dt=60,Cn=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")??"",E=p.searchParams.get("key")??"";if(g==="")throw new i(`KV-value ${k} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(E==="")throw new i(`KV-value ${k} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:E,namespace:g}},u=async(b,k)=>{if(!(await b.listNamespaces()).some(p=>p.binding===k))throw new i(`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 i("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const E=p.searchParams.get("prefix")??void 0,_=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 i("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const v=N===void 0?void 0:Math.min(N,1e3);return await u(k,g),o(await k.listKeys({cursor:_,limit:v,namespace:g,prefix:E}))},R={DELETE:async b=>{const k=n(b),p=d(b,"DELETE");return await u(k,p.namespace),await k.deleteKey(p),o({deleted:!0})},GET:async b=>{const k=n(b),p=d(b,"GET");return await u(k,p.namespace),o(await k.getValue(p))},PUT:async b=>{const k=n(b),p=await t(b,Pt);if(typeof p.namespace!="string"||p.namespace==="")throw new i("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof p.key!="string"||p.key==="")throw new i("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof p.value!="string")throw new i("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<dt))throw new i("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const g=Math.floor(Date.now()/1e3)+dt;if(p.expiration!==void 0&&(typeof p.expiration!="number"||!Number.isInteger(p.expiration)||p.expiration<g))throw new i("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(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 i("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return k(b)};return{[Nn]:h,[qn]:w,[Dt]:I}},jn="/_lunora/migrate",xn="/_lunora/admin/pitr",Bn="/_lunora/admin/rank",$n="/_lunora/admin/rankpage",Ln="/_lunora/admin/shard-traffic",Kn=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Fn=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Gn=async e=>{const t=await ye(e,"Migration")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.functionPath!="string"||!Kn.has(t.functionPath))throw new i("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,table:t.table}},Qn=async e=>{const t=await ye(e,"Rank")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof t.index!="string"||t.index.length===0)throw new i("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof t.partitionKey!="string")throw new i("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof t.rowId!="string"||t.rowId.length===0)throw new i("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(t.sortValues))throw new i("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}},Mn=e=>{if(e!==void 0){if(!Array.isArray(e)||e.some(t=>t!=="asc"&&t!=="desc"))throw new i('Rank page request `directions` must be an array of "asc"|"desc"',{code:"BAD_REQUEST",status:400});return e}},zn=e=>{if(typeof e.table!="string"||e.table.length===0)throw new i("Rank page request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof e.index!="string"||e.index.length===0)throw new i("Rank page request is missing `index`",{code:"BAD_REQUEST",status:400});if(e.partitionKey!==void 0&&typeof e.partitionKey!="string")throw new i("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 i("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 i("Rank page request `cursor` must be a string or null",{code:"BAD_REQUEST",status:400})},Wn=async e=>{const t=await ye(e,"Rank page")??{};zn(t);const r=Mn(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}},Hn=async e=>{const t=await ye(e,"Shard-traffic")??{};if(typeof t.table!="string"||t.table.length===0)throw new i("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:t.table}},Jn=async e=>{const t=await ee(e);if(typeof t.functionPath!="string"||!Fn.has(t.functionPath))throw new i("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 i("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:t.args??{},functionPath:t.functionPath,shardKey:t.shardKey}},Vn=e=>{const{defaultShard:t,forwardToShard:r,isAdmin:n,queryCoordinator:o,resolveForwardContext:d,shardDO:u}=e,h=(p,g)=>{if(p.method!=="POST")throw new i(`${g} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!n(p))throw new i("Admin auth required",{code:"FORBIDDEN",status:403});if(!o)throw new i(`${g} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return o},w=async(p,g)=>{const E=h(p,"Migration"),_=await Gn(p),{headers:T}=await d(p,g),N=await E.orchestrateMigration(u,{args:_.args,functionPath:_.functionPath,headers:T,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},R=async(p,g)=>{const E=h(p,"Rank"),_=await Qn(p),{headers:T}=await d(p,g),N=await E.orchestrateRank(u,{headers:T,index:_.index,partitionKey:_.partitionKey,rowId:_.rowId,sortValues:_.sortValues,table:_.table});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},I=async(p,g)=>{const E=h(p,"Rank page"),_=await Wn(p),{headers:T}=await d(p,g),N=await E.orchestrateRankPage(u,{..._,headers:T});return Response.json(N,{headers:{"content-type":"application/json"},status:200})},b=async(p,g)=>{const E=h(p,"Shard-traffic"),_=await Hn(p),{headers:T}=await d(p,g),N=await E.orchestrateShardTraffic(u,{headers:T,table:_.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 i("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const E=await Jn(p),{headers:_}=await d(p,g),T=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:E.args,functionPath:E.functionPath}),headers:_,method:"POST"});return r(u,E.shardKey??t,T)};return{[jn]:w,[xn]:k,[Bn]:R,[$n]:I,[Ln]:b}},Yn=1,Xn=0,Zn=32,ea=512,ta=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,ra=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ea)return;const r=t.split(",");if(!(r.length>Zn)){for(const n of r)if(!ta.test(n.trim()))return;return t}},na=e=>{const t=br(e.headers.get("traceparent"));if(t===void 0)return;const r=ra(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...r===void 0?{}:{traceState:r}}},aa=(e,t={})=>{const r=na(e),n=t.trustInbound===!0?r:void 0,o=Te(8),d=n?.traceId??Te(16),u=Ur(t.sampling,n===void 0?o:d),h=u.isTraced&&(n===void 0||n.sampled);return{decision:u,ignoredUpstream:r!==void 0&&n===void 0,trace:{sampled:h,spanId:o,traceFlags:h?Yn:Xn,traceId:d,...n?.parentSpanId===void 0?{}:{parentSpanId:n.parentSpanId},...n?.traceState===void 0?{}:{traceState:n.traceState}}}},oa=(e,t)=>{t.traceparent=yr(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},sa=(e,t)=>{let r;return()=>{if(r===void 0){const n=Sr(e),o=t===void 0?void 0:t.cf;r=_r(Er(n),Rr(n,o))}return r}},ia="/_lunora/admin/scheduled",ca="/_lunora/admin/scheduled/status",da="/_lunora/admin/scheduled/ws",ua="/_lunora/admin/scheduled/cancel",la="/_lunora/admin/scheduled/dead",ha="/_lunora/admin/scheduled/dead/retry",pa="/_lunora/admin/scheduled/dead/cancel",fa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:r,resolveSchedulerStub:n,schedulerInstanceName:o}=e,d=(w,R)=>I=>{if(I.method!=="GET")throw new i(`${R} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});return n(I).fetch(new Request(`https://scheduler.internal${w}`,{method:"GET"}))},u=(w,R,I=R)=>async b=>{if(b.method!=="POST")throw new i(`${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 i(`${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 i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(w))throw new i("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const R=r();return ve(R,o).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ua]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[pa]:u("/dead/cancel","Scheduled dead-letter action"),[la]:d("/dead","Scheduled dead-letter"),[ha]:u("/dead/retry","Scheduled dead-letter action"),[ia]:d("/list","Scheduled-list"),[ca]:d("/status","Scheduler-status"),[da]:h}},Ut="/_lunora/admin/storage",ma="/_lunora/admin/storage/url",wa="/_lunora/admin/storage/buckets",ga=10080*60,Nt=32*1048576,ya=new Set(["GET","PUT"]),ba=e=>{const t=new Uint8Array(e);let r="";for(const n of t)r+=n.toString(16).padStart(2,"0");return r},_a=e=>{const{assertAdmin:t,parsePaging:r,queryParameter:n,readBodyBytes:o,requireAdminOption:d,storage:u}=e,h=g=>{const E=n(g,"key");if(E===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return E},w=async g=>{const E=d(g,u.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),_=new URL(g.url),T=await E(n(_,"prefix"),{bucket:n(_,"bucket"),cursor:n(_,"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:u.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),I=async g=>{const E=d(g,u.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),_=new URL(g.url),T=h(_);return await E(T,{bucket:n(_,"bucket")}),Response.json({deleted:!0,key:T},{headers:{"content-type":"application/json"},status:200})},b=async g=>{const E=d(g,u.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),_=new URL(g.url),T=h(_),N=await o(g,Nt),v=g.headers.get("content-type"),x=v===null||v===""?void 0:v,j=n(_,"expectedSha256"),G=n(_,"expectedSize");let P;if(j!==void 0||G!==void 0){const M=await crypto.subtle.digest("SHA-256",N);P=ba(M);const B=G!==void 0&&N.byteLength!==Number(G),K=j!==void 0&&P!==j.toLowerCase();if(B||K)throw new i("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const Q=await E(T,N,{bucket:n(_,"bucket"),contentType:x});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 i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},p=async g=>{L(g,"GET","Storage URL");const E=d(g,u.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),_=new URL(g.url),T=h(_),N=Number(n(_,"expiresIn")??""),v=Number.isFinite(N)&&N>0?Math.min(N,ga):void 0,x=n(_,"method");if(x!==void 0&&!ya.has(x))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const j=x,G=n(_,"contentType"),P=await E(T,{bucket:n(_,"bucket"),contentType:G,expiresInSeconds:v,method:j});return Response.json({key:T,url:P},{headers:{"content-type":"application/json"},status:200})};return{[wa]:R,[Ut]:k,[ma]:p}},Ra=(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},ut={mtls:e=>Ra(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ea=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ut,e)?ut[e]:void 0)??(()=>!1),Sa=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.'))}},Oa="/_lunora/admin/vector/indexes",Ta="/_lunora/admin/vector/query",va=e=>{const{readJsonBody:t,requireAdminOption:r}=e,n=async d=>{L(d,"GET","Vector-indexes");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},o=async d=>{L(d,"POST","Vector-query");const u=r(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new i("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 i("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof h.text!="string"||h.text==="")throw new i("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 i("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const w=await u.queryIndex({name:h.name,text:h.text,topK:h.topK});return Response.json(w,{headers:{"content-type":"application/json"},status:200})};return{[Oa]:n,[Ta]:o}},Aa="/_lunora/admin/workflows/instances",ka="/_lunora/admin/workflows/instance",Ia="/_lunora/admin/workflows/status",Da={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Pa=e=>e!==null&&Object.hasOwn(Da,e)?e:void 0,lt=(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 i(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return r},ht=()=>{throw new i("Workflow inspection is unconfigured. Set CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN in your .dev.vars to enable it.",{code:"WORKFLOWS_NOT_CONFIGURED",status:501})},Ua=e=>{const{assertAdmin:t,resolveWorkflowsClient:r}=e,n=async(u,h,w)=>{L(u,"GET","Workflows instances"),t(u);const R=r(h);if(!R)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const I=Le(w,"name"),b=Pa(w.searchParams.get("status"));return Response.json(await R.listInstances({page:lt(w,"page"),perPage:lt(w,"perPage"),status:b,workflowName:I}))},o=async(u,h,w)=>{L(u,"GET","Workflows instance"),t(u);const R=r(h);return R?Response.json(await R.getInstance({instanceId:Le(w,"id"),workflowName:Le(w,"name")})):ht()},d=async(u,h)=>{L(u,"POST","Workflows status"),t(u);const w=r(h);if(!w)return ht();const R=await u.json().catch(()=>{});if(typeof R?.name!="string"||R.name===""||typeof R.id!="string"||R.id==="")throw new i("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 i("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{[ka]:o,[Aa]:n,[Ia]:d}},Na={[Dt]:Pt,[Ut]:Nt},qa=new TextEncoder,pt="/_lunora/rpc",Ca="/_lunora/rpc-batch",ja="/_lunora/ws",Re=(e,t,r)=>({resourceAttributes:sa(e,t),...r===void 0?{}:{waitUntil:r}}),ft=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},mt=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}},wt="/_lunora/voice/",xa="/_lunora/scheduler/dispatch",Ba="/_lunora/admin/cron-jobs/run",$a="/_lunora/admin/ws-token",La="/_lunora/admin/",Ka="/_lunora/migrate",Fa="/_lunora/status",Ga=e=>e.startsWith(La)||e===Ka,Qa=new Set(["1","enabled","on","true","yes"]),Ma=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}}},za="/api/auth",Wa="__lunora_admin__:recordAuthEvent",Ha="__lunora_admin__:listPushSubscriptions",Ja=["/sign-in","/sign-up","/callback"],Va=(e,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${r}/`))return!1;const n=e.slice(r.length);return Ja.some(o=>n===o||n.startsWith(`${o}/`))},Ee=(e,t,r,n)=>{const o=pr(r),d=o?r.code:"INTERNAL_SERVER_ERROR",u=o?r.status:500,h=r instanceof Error?r.message:String(r);return{durationMs:t,error:{code:d,message:h,status:u},functionPath:e,ok:!1,...n.fanOut?{fanOut:{failed:0,shards:0,table:n.fanOut.table}}:{},...n.shardKey?{shardKey:n.shardKey}:{}}},Ya=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},gt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,Xa=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"),u=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),u&&(n["x-d1-bookmark"]=u),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"]=wr(b.userId);const k=Ya(b);k!==void 0&&(n["x-lunora-identity-exp"]=String(k));const{userId:p,...g}=b,E=Object.keys(g).length>0?g:null;return E&&(n["x-lunora-identity"]=gr(E)),{claims:E,headers:n,identity:b,userId:p}},Za=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),eo=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new i("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 i("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new i("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const r=t.merge;if(typeof r.kind!="string"||!Za.has(r.kind))throw new i("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 i("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 i("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},to=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},yt=(e,t)=>{const r=t.functions?.[e.functionPath]?.x402;if(r){if(e.fanOut)throw new i("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new i(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return r}},ro=async e=>{const t=await St(e);let r;try{r=JSON.parse(t)}catch{throw new i("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!r||typeof r!="object"||typeof r.functionPath!="string")throw new i("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const n=r;if(n.args!==void 0&&Ot(n.args,"RPC"),n.shardKey!==void 0&&typeof n.shardKey!="string")throw new i("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const o=r,d=eo(o.fanOut),u=o.args??{};if(d&&o.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==d.table)throw new i("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=d.table}return{args:u,fanOut:d,functionPath:o.functionPath,shardKey:o.shardKey}},oe=async(e,t,r)=>ve(e,t).fetch(r),Se=new Map,no=5e3,ao=4096,oo=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 ve(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const u=(await d.json()).relayCount;typeof u=="number"&&u>0&&(o=Math.floor(u))}}catch{o=0}return Rt(Se,ao),Se.set(t,{expiresMs:r+no,relayCount:o}),o},so=(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"}),io=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp"],bt=(e,t)=>{for(const r of io){e.delete(r);const n=t[r];n!==void 0&&e.set(r,n)}},co=async(e,t,r)=>e.length===0||r.length===0?!1:Fe(await At(e,t),r),_t=(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:Fe(t,o.join(" ").trim())},uo=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:Fe(t,n)},lo=(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)},qt=e=>{const t=Ea(e.trustInboundTraceContext),r=Sa(e.trustInboundTraceContext),n=e.defaultShardKey??"__root__",o=Dr(e.resolveIdentity,e.identity),d=Ye(e.shardDO,e.jurisdiction),u=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 c=s.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof c=="string"&&c.length>0&&(R=Qa.has(c.trim().toLowerCase()))}if(h!==void 0||e.adminToken!==void 0)return;const l=s.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(h=l)},k=new WeakSet,p=a=>_t(a,w())||k.has(a),g=async(a,s)=>{const l=await de(a,s,e.resolveIdentity);if(k.has(a)&&l.headers.authorization===void 0){const c=w();c!==void 0&&(l.headers.authorization=`Bearer ${c}`)}return l};let E=!1;const _=a=>{if(!e.allowUnauthenticatedShardAccess){const s=a==="fan-out"?"authorizeFanOut":"authorizeShard";throw new i(`${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})}E||(E=!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,l=!0)=>{if(e.authorizeShard){if(!await e.authorizeShard(a,s))throw new i("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else l&&s!==n&&_("shard")},N=Vn({defaultShard:n,forwardToShard:oe,isAdmin:p,queryCoordinator:e.queryCoordinator,resolveForwardContext:g,shardDO:d}),v=async(a,s,l,c,m)=>{await T(null,l,!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),c!==void 0&&c.length>0&&(y["x-lunora-mutation-id"]=c),oe(d,l,Oe(a,s,y))},x=async(a,s,l,c)=>{const m=l?.[a];if(!m||typeof m.create!="function")throw new i(`${c} targets workflow binding "${a}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(jr(s))throw new i(`${c} params ${xr}`,{code:"BAD_REQUEST",status:400});await m.create({params:s})},j=async(a,s)=>{if(a.workflow){await x(a.workflow,a.args??{},s,`cron job "${a.name}"`);return}if(a.functionPath===void 0)throw new i(`cron job "${a.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const l=await v(a.functionPath,a.args??{},a.shardKey??n);if(!l.ok)throw new i(`cron job "${a.name}" (${a.functionPath}) failed with shard status ${String(l.status)}`,{code:"CRON_JOB_FAILED",status:500})},G=async(a,s,l,c)=>{const m=e.cronJobs?.[a];if(m)for(const y of m)try{await j(y,s)}catch(A){l.push(c(A))}},P=async(a,s)=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});if(L(a,"POST","cron-jobs run"),!e.cronJobs)throw new i("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ee(a),c=typeof l.name=="string"?l.name:"";if(c==="")throw new i("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(y=>y.name===c);if(!m)throw new i(`no cron job named "${c}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await j(m,s),Response.json({name:c,ran:!0},{status:200})},Q=async a=>{const s=typeof a.pool=="string"&&a.pool.length>0?a.pool:void 0;if(!s||!u||typeof a.id!="string")return;const l=typeof a.instanceName=="string"&&a.instanceName.length>0?a.instanceName:"default";try{await u.get(u.idFromName(l)).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 l=await St(a),c=s??{},m=typeof c.LUNORA_SCHEDULER_SECRET=="string"?c.LUNORA_SCHEDULER_SECRET:void 0,y=e.adminToken??(typeof c.LUNORA_ADMIN_TOKEN=="string"?c.LUNORA_ADMIN_TOKEN:void 0),A=a.headers.get("x-lunora-scheduler-signature");let f=!1;if(A&&m?f=await co(m,l,A):y&&(f=_t(a,y)),!f)throw new i("Scheduler dispatch requires a valid signature or admin bearer",{code:"FORBIDDEN",status:403});let S;try{S=JSON.parse(l)}catch{throw new i("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 x(O.workflow,q,s,"scheduled workflow"),Response.json({ok:!0},{status:200});if(typeof O.functionPath!="string"||O.functionPath.length===0)throw new i("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=Ma(a),Z=await v(O.functionPath,q,C,$,V);return await Q(O),Z},B=a=>{if(!p(a))throw new i("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},K=(a,s,l)=>{if(B(a),s===void 0)throw new i(l.message,{code:l.code,status:400});return s},X=Xr({assertAdmin:B,getReader:()=>e.authAuditReader}),J=async(a,s)=>{B(a);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({subscriptions:[]},{headers:{"content-type":"application/json"},status:200});const c=s?.kind,m=s?.userId,y=s?.limit,A=c==="fcm"||c==="web-push"?c: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 l.list({kind:A,limit:O,userId:f})).filter(C=>A!==void 0&&C.kind!==A?!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===Yr)return X(a,s.args??{});if(s.functionPath===Ha)return J(a,s.args)}},he=fn({applyGlobals:e.applyGlobals,assertAdmin:B,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,knownTables:()=>[],queryCoordinator:e.queryCoordinator,requireAdminOption:K,resolveForwardContext:g,shardDO:d,streamExportRows:(a,s,l,c)=>st(e,a,s,l,c,d),streamingImport:(a,s)=>_n(a,e,s,d),syncGlobals:e.syncGlobals}),ae=(a,s)=>{const l=a.searchParams.get(s);return l===null||l===""?void 0:l},pe=a=>{const s=new URL(a.url),l=s.searchParams.get("limit"),c=s.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),y=c===null?void 0:Number.parseInt(c,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(u===void 0)throw new i("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Ae=fa({checkWsAdmin:async a=>p(a)||uo(a,w(),I()),requireSchedulerNamespace:be,resolveSchedulerStub:a=>(B(a),ve(be(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),se=Ua({assertAdmin:B,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Ct=_a({assertAdmin:B,parsePaging:pe,queryParameter:ae,readBodyBytes:Tr,requireAdminOption:K,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),jt=va({readJsonBody:ee,requireAdminOption:K,vectorIntrospector:e.vectorIntrospector}),xt=Cn({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:K}),Bt=Pr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:K}),$t=Un({assertAdmin:B,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:pe,queryParameter:ae,requireAdminOption:K}),Lt=a=>{const s=[],l=d??a?.SHARD;if(l!==void 0&&s.push(kr("durable-object:default",l,n)),e.health?.disableBindingProbes!==!0)for(const[c,m]of Object.entries(a??{})){const y=lo(c,m);y!==void 0&&s.push(y)}for(const c of e.health?.probes??[])s.push(c);return s},Kt=Ar({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:p,resolveProbes:Lt}),Ft=a=>{const s=e.schedulerInstanceName??"default",l=()=>a.get(a.idFromName(s)),c=async(f,S)=>{const O=await l().fetch(new Request(`https://scheduler.internal${f}`,S));if(!O.ok)throw new i(`ctx.scheduler: SchedulerDO ${f} failed (${String(O.status)}): ${await O.text()}`,{code:"INTERNAL",status:500});return await O.json()},m=async(f,S)=>await c(f,{body:JSON.stringify(S),headers:{"content-type":"application/json"},method:"POST"}),y=f=>{const S=f;if(S==null)throw new i("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 i("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})},A=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 c(`/get?id=${encodeURIComponent(f)}`,{method:"GET"}),list:async()=>await c("/list",{method:"GET"}),runAfter:async(f,S,O)=>{if(!Number.isFinite(f)||f<0)throw new i("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"BAD_REQUEST",status:400});return await A(Date.now()+f,S,O)},runAt:async(f,S,O)=>{if(!Number.isFinite(f))throw new i("ctx.scheduler.runAt: `timestampMs` must be a finite epoch-millisecond number",{code:"BAD_REQUEST",status:400});return await A(f,S,O)}}},Gt=async(a,s,l)=>{const{claims:c,headers:m,userId:y}=await de(a,s,o),A=async(f,S={})=>{const O=f.__lunoraRef;if(typeof O!="string")throw new i("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 i($.error.message??"shard RPC failed",{code:$.error.code??"INTERNAL",status:C.status});return $.result};return{auth:{getIdentity:()=>Promise.resolve(c),userId:y},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),runAction:A,runMutation:A,runQuery:A,...u===void 0?{}:{scheduler:Ft(u)},...e.storage===void 0?{}:{storage:Cr(e.storage(s))}}},Qt=async(a,s,l)=>{if(!e.httpRouter)return;const c=await Gt(a,s,l);try{return await e.httpRouter.fetch(a,{...s,__lunoraCtx:c},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Mt=async(a,s,l)=>{if(a.headers.get("Upgrade")!=="websocket")throw new i("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const c=Ze(a,ie);if(c)return c;const m=l.searchParams.get("shard")??n,{headers:y,identity:A}=await de(a,s,o);await T(A,m);const f=new Headers(a.headers),S=[...f.keys()];for(const q of S)q.startsWith("x-lunora-")&&f.delete(q);bt(f,y);const O=so(s,e.shardDO);if(O!==void 0){f.set("x-lunora-shard-binding",O);const q=await oo(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}))},zt=async(a,s,l)=>{const{voiceAgents:c}=e;if(c===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(l.pathname.slice(wt.length))}catch{return new Response("Unknown voice agent",{status:404})}const A=Object.hasOwn(c,y)?c[y]:void 0;if(A===void 0)return new Response("Unknown voice agent",{status:404});const f=l.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 _("shard");const q=new Headers(a.headers);return bt(q,S),oe(A,f,new Request(a,{headers:q}))},Wt=async(a,s,l)=>{if(e.authorizeFanOut){if(!await e.authorizeFanOut(l,a.table,s))throw new i("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(s.startsWith("__lunora_relation__:"))throw new i("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 i("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});_("fan-out")},_e=async(a,s)=>{if(!(!a.fanOut&&a.functionPath.startsWith("__lunora_admin__:"))){if(a.fanOut){await Wt(a.fanOut,a.functionPath,s);return}await T(s,a.shardKey??n)}},ke=async(a,s,l,c,m,y)=>{const A=Date.now(),{observability:f,sampling:S}=e,O=Ke(a),{decision:q,ignoredUpstream:C,trace:$}=aa(a,{...S===void 0?{}:{sampling:S},trustInbound:t(a)});C&&r();const V={...m,"x-lunora-sample-errors":q.keepErrors?"1":"0"};oa($,V);const Z=Oe(s,l,V);try{const F=await oe(d,c,Z);return ce(f,{...O,...mt($),durationMs:Date.now()-A,functionPath:s,ok:F.ok,shardKey:c,...F.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(F.status)}`,status:F.status}}},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),F}catch(F){throw ce(f,{...O,...mt($),...Ee(s,Date.now()-A,F,{shardKey:c})},y,void 0,{isTraced:$.sampled,keepErrors:q.keepErrors}),F}},Ht=a=>{if(a.fanOut&&a.shardKey)throw new i("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(!a.fanOut&&a.functionPath.startsWith("__lunora_relation__:"))throw new i("`__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 i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Jt=async(a,s,l)=>{L(a,"POST","RPC");const c=await ro(a);to(s,c),Ht(c);const m=await ne(a,c);if(m!==void 0)return m;const{headers:y,identity:A}=await de(a,s,o);await _e(c,A);const f=yt(c,e);{const S=Date.now(),{observability:O}=e,q=Ke(a),C=Re(s,a,l&&(Z=>l.waitUntil?.(Z)));if(c.fanOut){const Z=e.queryCoordinator;if(!Z)throw new i("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const F=await Z.fanOut(d,{args:c.args??{},fanOut:c.fanOut,functionPath:c.functionPath,headers:y});return ce(O,{durationMs:Date.now()-S,fanOut:{failed:F.failed,shards:F.ok+F.failed,table:c.fanOut.table},functionPath:c.functionPath,...q,ok:!0},C),Response.json(F,{headers:{"content-type":"application/json"},status:200})}catch(F){throw ce(O,{...Ee(c.functionPath,Date.now()-S,F,{fanOut:{table:c.fanOut.table}}),...q},C),F}}const $=c.shardKey??n,V=()=>ke(a,c.functionPath,c.args??{},$,y,C);return f&&e.x402Charge?e.x402Charge(a,{functionPath:c.functionPath,price:f.price},V,ft(l)):V()}},Vt=async(a,s,l)=>{L(a,"POST","RPC batch");const c=await ee(a),{calls:m}=c;if(!Array.isArray(m))throw new i("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:y,identity:A}=await de(a,s,o),f=en(m,n);for(const z of f.values())for(const W of z)if(e.functions?.[W.functionPath]?.x402)throw new i(`paid (\`.x402\`) function "${W.functionPath}" cannot be called in a batch; dispatch it individually over ${pt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...f.entries()].flatMap(([z,W])=>W.map(re=>_e({functionPath:re.functionPath,shardKey:z},A))));const{observability:S}=e,O=Re(s,a,l&&(z=>l.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))},F=(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}=fr(Y,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});Z(W,502,He.code,He.message,hr=>({...Ee(hr.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:[],ur=new Map(Pe.map(Y=>[Y.id,Y.status??H.status])),lr=new Set(Pe.map(Y=>Y.id));F(W,z,me,ur,H.status),C.push(...Pe);for(const Y of W)lr.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})},Yt=async(a,s,l,c={},m={})=>{try{const y=l.__lunoraRef;if(typeof y!="string")throw new i("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});const{headers:A,identity:f}=await de(a,s,o);await _e({functionPath:y,shardKey:m.shardKey},f);const S=m.shardKey??n,O=Re(s,a,m.waitUntil);return await ke(a,y,c,S,A,O)}catch(y){return Je(y)}},Xt=1e3,Zt=async(a,s)=>{const l=e.backupRetain;if(l===void 0||l<=0)return;const c=[];let m;for(let A=0;A<Xt;A+=1){const f=await a.list({cursor:m,prefix:s});for(const S of f.objects)S.key.endsWith(".manifest.json")&&c.push(S.key);if(!f.truncated||f.cursor===void 0)break;m=f.cursor}const y=c.toSorted((A,f)=>f.localeCompare(A)).slice(l);await Promise.all(y.flatMap(A=>{const f=A.slice(0,-14);return[a.delete(A),a.delete(f)]}))},er=async a=>{const s=e.backupStore,l=e.queryCoordinator;if(!s)throw new i("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!l)throw new i("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const c=w();if(!c||c.length===0)throw new i("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 ${c}`,"content-type":"application/json"},y=e.backupTables;let A=0,f=0;const S=[];await st(e,l,m,y,Z=>{const F=`${JSON.stringify(Z)}
|
|
5
|
-
`;A+=1,f+=qa.encode(F).byteLength,S.push(F)},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:A,scheduledTime:a.scheduledTime,...y?{tables:y.join(",")}:{}};await s.put($,`${JSON.stringify(V,void 0,2)}
|
|
6
|
-
`,{httpMetadata:{contentType:"application/json"}}),await Zt(s,O)},Qe=async(a,s,l)=>{const{observability:c}=e,m=Date.now(),y=Te(16),A=Te(8),f=gt(s);try{const S=await l();return ce(c,{durationMs:Date.now()-m,functionPath:a,ok:!0,spanId:A,traceId:y},f),S}catch(S){throw ce(c,{...Ee(a,Date.now()-m,S,{}),spanId:A,traceId:y},f),S}finally{Ve(c,f)}},tr=async(a,s,l)=>{b(s);const c=[],m=f=>f instanceof Error?f:new Error(String(f)),y=e.crons?.[a.cron];if(y)try{await y(a,s,l)}catch(f){c.push(m(f))}if(await G(a.cron,s,c,m),e.backupStore&&e.backupCron!==void 0&&e.backupCron===a.cron)try{await er(a)}catch(f){c.push(m(f))}const[A]=c;if(c.length===1&&A)throw A;if(c.length>1)throw new AggregateError(c,`scheduled("${a.cron}") had ${String(c.length)} failure(s)`)},rr=async(a,s)=>{try{const l=a??{},c=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!c||c.length===0)return;await oe(d,n,Oe(Wa,{outcome:s},{authorization:`Bearer ${c}`,"content-type":"application/json"}))}catch{}},nr=async(a,s,l,c)=>{if(!e.authHandler)return;const m=await e.authHandler(a);if(!m)return;const y=e.authBasePath??za;return Va(l.pathname,y)&&c.waitUntil?.(rr(s,m.status>=400?"fail":"ok")),m},ar=async({args:a,env:s,functionPath:l,request:c,shardKey:m,waitUntil:y})=>{Ot(a,"REST");const A={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:f,identity:S}=await de(c,s,o);await _e(A,S);const O=m??n,q=Re(s,c,y),C=()=>ke(c,l,a,O,f,q),$=yt(A,e);return $&&e.x402Charge?e.x402Charge(c,{functionPath:l,price:$.price},C,ft({waitUntil:y})):C()},or=Or({functions:e.functions??{},invoke:ar,readJsonBody:ee,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ie=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,sr={[Fa]: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"}}),[ja]:(a,s,l)=>Mt(a,s,l),[pt]:(a,s,l,c)=>Jt(a,s,c),[Ca]:(a,s,l,c)=>Vt(a,s,c),[xa]:(a,s)=>M(a,s),[Ba]:(a,s)=>P(a,s),[$a]:async a=>{L(a,"POST","ws-token"),B(a);const s=w();if(s===void 0)throw new i("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await zr(s);return Response.json(l,{headers:{"cache-control":"no-store"}})},...N,...he,...Ae,...se,...Ct,...jt,...xt,...Bt,...$t,...Kt,...or,...Vr({assertAdmin:B,getAuthAdmin:()=>e.authAdmin,parsePaging:pe,queryParameter:ae,readJsonBody:ee})};let ie=Xe(e.security),Me=!1;const ir=a=>{Me||(Me=!0,ie=Xe(e.security,a??{}))},cr=async(a,s)=>{if(!(e.adminGate===void 0||!Ga(s)))try{await e.adminGate(a)&&k.add(a)}catch{}},dr=async(a,s,l)=>{const c=new URL(a.url);if(a.method==="POST"||a.method==="PUT"){const f=Number(a.headers.get("content-length")??""),S=Na[c.pathname]??Et;if(Number.isFinite(f)&&f>S)throw new i("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})}const m=await nr(a,s,c,l);if(m)return m;if(Ie){const f=`${a.method} ${c.pathname}`,S=Ie[f]??Ie[c.pathname];if(S)return S(a,s,l)}const y=sr[c.pathname];return y?(await cr(a,c.pathname),y(a,s,c,l)):e.voiceAgents!==void 0&&c.pathname.startsWith(wt)?zt(a,s,c):await Qt(a,s,l)||new Response("Not found",{status:404})};return{async fetch(a,s,l){e.passThroughOnException&&l.passThroughOnException?.(),ir(s),b(s);const c=Nr(a,ie);if(c)return c;const m=qr(a,ie);if(m)return qe(m,a,ie);try{const y=await dr(a,s,l);return qe(y,a,ie)}catch(y){return qe(Je(y),a,ie)}finally{Ve(e.observability,gt(l))}},async queue(a,s,l){await Qe(`queue:${Xa(a)}`,l,async()=>{await e.queue?.(a,s,l)})},async scheduled(a,s,l){await Qe(`cron:${a.cron}`,l,async()=>{await tr(a,s,l)})},serverQuery:Yt}},ho=e=>qt(e),po=e=>typeof e=="function"?{fetch:e}:e,fo=e=>!!(e.crons??e.cronJobs??e.backupCron),Po=(e,t)=>{const r=po(e),n=typeof e=="object"&&typeof e.scheduled=="function"?e.scheduled:void 0,o=u=>{const h=ho({...u,httpRouter:r});return n!==void 0&&!fo(u)?{...h,scheduled:async(w,R,I)=>{await n(w,R,I)}}:h};if(typeof t!="function")return o(t);const d=t;return{fetch:(u,h,w)=>o(d(h)).fetch(u,h,w),queue:(u,h,w)=>o(d(h)).queue?.(u,h,w)??Promise.resolve(),scheduled:(u,h,w)=>o(d(h)).scheduled(u,h,w),serverQuery:(u,h,w,R,I)=>o(d(h)).serverQuery(u,h,w,R,I)}},mo=(e,t)=>{if(typeof e=="function")return e(t);const r=e.shardDO??t?.SHARD;if(!r)throw new i("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:r}},Uo=(e={})=>(t,r,n)=>qt(mo(e,r)).fetch(t,r,n??mr),No=e=>e;export{Yr as GET_AUTH_AUDIT_LOG_OP,mr as NOOP_EXECUTION_CONTEXT,jo as composeIdentityResolvers,ho as composeWorker,Uo as createLunoraHandler,qt as createWorker,No as defineRpcEnvelope,oo as probeRelayCount,mo as resolveLunoraOptions,xo as routeIdentityResolvers,Po as withFrameworkWorker};
|