@lunora/runtime 1.0.0-alpha.147 → 1.0.0-alpha.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2691,7 +2691,11 @@ interface SecurityHeadersOptions {
2691
2691
  interface CorsOptions {
2692
2692
  /** Echo `Access-Control-Allow-Credentials: true`. Incompatible with a `*` allowlist. */
2693
2693
  allowCredentials?: boolean;
2694
- /** Request headers permitted on the actual request (preflight `Allow-Headers`). */
2694
+ /**
2695
+ * Extra request headers permitted on the actual request (preflight
2696
+ * `Allow-Headers`). Always added to the headers `@lunora/client` sends on
2697
+ * its own, which cannot be removed.
2698
+ */
2695
2699
  allowedHeaders?: string[];
2696
2700
  /** Methods permitted cross-origin (preflight `Allow-Methods`). */
2697
2701
  allowedMethods?: string[];
@@ -3916,8 +3920,9 @@ interface WorkerOptions {
3916
3920
  * Restrict every Durable Object this worker reaches — shard DOs, the
3917
3921
  * scheduler DO, the fan-out coordinator, subscriptions — to a Cloudflare
3918
3922
  * data-residency jurisdiction (`"eu"`, `"us"`, `"fedramp"`). The runtime
3919
- * derives a jurisdiction-pinned subnamespace from {@link WorkerOptions.shardDO}
3920
- * and {@link WorkerOptions.schedulerDO} once, so all routing inherits it.
3923
+ * derives a jurisdiction-pinned subnamespace from {@link WorkerOptions.shardDO},
3924
+ * {@link WorkerOptions.schedulerDO}, and each {@link WorkerOptions.voiceAgents}
3925
+ * namespace once, so all routing inherits it.
3921
3926
  *
3922
3927
  * Fail-closed: if the bound namespace does not expose `.jurisdiction()`
3923
3928
  * (an older `@cloudflare/workers-types`), the worker throws rather than
package/dist/index.d.ts CHANGED
@@ -2691,7 +2691,11 @@ interface SecurityHeadersOptions {
2691
2691
  interface CorsOptions {
2692
2692
  /** Echo `Access-Control-Allow-Credentials: true`. Incompatible with a `*` allowlist. */
2693
2693
  allowCredentials?: boolean;
2694
- /** Request headers permitted on the actual request (preflight `Allow-Headers`). */
2694
+ /**
2695
+ * Extra request headers permitted on the actual request (preflight
2696
+ * `Allow-Headers`). Always added to the headers `@lunora/client` sends on
2697
+ * its own, which cannot be removed.
2698
+ */
2695
2699
  allowedHeaders?: string[];
2696
2700
  /** Methods permitted cross-origin (preflight `Allow-Methods`). */
2697
2701
  allowedMethods?: string[];
@@ -3916,8 +3920,9 @@ interface WorkerOptions {
3916
3920
  * Restrict every Durable Object this worker reaches — shard DOs, the
3917
3921
  * scheduler DO, the fan-out coordinator, subscriptions — to a Cloudflare
3918
3922
  * data-residency jurisdiction (`"eu"`, `"us"`, `"fedramp"`). The runtime
3919
- * derives a jurisdiction-pinned subnamespace from {@link WorkerOptions.shardDO}
3920
- * and {@link WorkerOptions.schedulerDO} once, so all routing inherits it.
3923
+ * derives a jurisdiction-pinned subnamespace from {@link WorkerOptions.shardDO},
3924
+ * {@link WorkerOptions.schedulerDO}, and each {@link WorkerOptions.voiceAgents}
3925
+ * namespace once, so all routing inherits it.
3921
3926
  *
3922
3927
  * Fail-closed: if the bound namespace does not expose `.jurisdiction()`
3923
3928
  * (an older `@cloudflare/workers-types`), the worker throws rather than
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-Rz0K7vP7.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-D_S3beMO.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-DQGhbG0p.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-DmBN4_ut.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-D3__w6LU.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpbO5QEx.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-Y2sCM0w1.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-I984JFkv.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-KGQR1LvR.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
1
+ import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as x,createLunoraHandler as S,createWorker as l,defineRpcEnvelope as u,resolveLunoraOptions as _,withFrameworkWorker as d}from"./packem_shared/composeWorker-DhuQyLPf.mjs";import{createCrossShardRelationCapabilities as y}from"./packem_shared/createCrossShardRelationCapabilities-zmhkc6GE.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as O,SHARD_REGISTRY_DO_NAME as b,createDynamicShardRegistry as A}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as T,toErrorResponse as h}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as P,a as g,d as v,r as I,b as D,s as M,w as F}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as G,HEALTH_READY_PATH as K,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-BlkElAL2.mjs";import{D as pe,c as ce}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as fe,createStaticShardRegistry as Ee}from"./packem_shared/createQueryCoordinator-D3__w6LU.mjs";import{applyJurisdiction as xe,resolveShard as Se}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as _e,b as de}from"./packem_shared/rest-cache-D1BlbZb1.mjs";import{a as ye,b as Ce,c as Oe,r as be}from"./packem_shared/rest-routes-CpbO5QEx.mjs";import{decorateResponse as Le,enforceOrigin as Te,handleCorsPreflight as he,resolveSecurity as He}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as ge}from"./packem_shared/createShardClient-BUPdMJLO.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ie}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-KGQR1LvR.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Me}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ne}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ke,routeIdentityResolvers as Ue}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,O as DEFAULT_REGISTRY_CACHE_TTL_MS,G as HEALTH_PATH,K as HEALTH_READY_PATH,Me as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,T as LunoraError,Ne as NOOP_EXECUTION_CONTEXT,b as SHARD_REGISTRY_DO_NAME,Ie as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,xe as applyJurisdiction,ue as applyRestCache,ye as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ke as composeIdentityResolvers,x as composeWorker,oe as consoleSink,y as createCrossShardRelationCapabilities,A as createDynamicShardRegistry,P as createKvCursorStore,S as createLunoraHandler,g as createMemoryCursorStore,ce as createPipelineLogReader,fe as createQueryCoordinator,Oe as createRestRateLimit,ge as createShardClient,Ee as createStaticShardRegistry,l as createWorker,B as d1Probe,Le as decorateResponse,v as defineExportSink,u as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,Te as enforceOrigin,he as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,I as r2Sink,_e as requestCarriesCredentials,j as resolveLogArchiveFromEnv,_ as resolveLunoraOptions,He as resolveSecurity,Se as resolveShard,de as restCacheHeaders,be as restSurfaceFromRegistry,Ue as routeIdentityResolvers,D as runExportTap,M as sanitizeChange,se as sentrySink,f as toAirbyteMessages,h as toErrorResponse,E as toFivetranResponse,F as webhookExportSink,ie as webhookSink,d as withFrameworkWorker};
@@ -1 +1 @@
1
- import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as l,L as y,o as $,c as S,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-JKBCWf6c.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,c,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},h=async()=>{a();const p=t;t=[];const d=n;c=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{d?.()}},m=p=>{c===void 0&&(c=new Promise(d=>{n=d}),s=setTimeout(()=>{h()},o)),p?.(c)};return{add:(p,d)=>{for(t.push(p);t.length>e;)t.shift();m(d),t.length>=e&&h()},flush:async p=>{if(t.length===0){a();return}const d=h();return p?.(d),d},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,R=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=R(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",c=!0;for(const n of t){const a=o[n];a!==void 0&&(c?c=!1:s+=",",s+=B(n),s+=":",s+=R(a))}return s+"}"},dr=1,ur=0,lr=(r,e)=>{const o=[l(y.functionPath,r.functionPath),l(y.ok,r.ok)];r.method!==void 0&&o.push(l("http.request.method",r.method)),r.path!==void 0&&o.push(l("url.path",r.path)),o.push(l("http.route",r.functionPath)),r.scheme!==void 0&&o.push(l("url.scheme",r.scheme)),r.host!==void 0&&o.push(l("server.address",r.host)),r.port!==void 0&&o.push(l("server.port",r.port)),r.userAgent!==void 0&&o.push(l("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(l(y.shardKey,r.shardKey)),o.push(l("http.response.status_code",r.error?.status??200)),r.error&&o.push(l(y.errorType,r.error.code),l("lunora.error_status",r.error.status)),r.fanOut&&o.push(l("lunora.fanout.table",r.fanOut.table),l("lunora.fanout.shards",r.fanOut.shards),l("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:S(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[l("exception.type",r.error.code),l("exception.message",r.error.message)],name:"exception",timeUnixNano:S(e)}]),t},M=(r,e)=>{const o=new Map([[y.functionPath,l(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,l(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,l(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,l(y.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,l(t,W(s)));return[...o.values()]},pr=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),flags:r.sampled===!1?ur:dr,kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,c])=>[s,W(c)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},fr=r=>{const e=S(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:e,traceId:r.traceId}],s={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[s]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[s],isMonotonic:!0}}},mr=r=>{const e={attributes:M({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(l("event.name",r.eventName))),e},hr=1024,C=5;let A=0;const yr=(r,e)=>{if(A>=C)return;A+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},gr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},G=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:c}=new TextEncoder().encode(s),n=(c<hr?fetch(r,{body:s,headers:o,method:"POST"}):gr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||yr(r,a.status)},()=>{});t?.(n),await n}catch{}},br=(r,e,o,t)=>{G(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,kr=r=>r.kind==="metric"?void 0:r.event.traceId,Sr=r=>{const e=Map.groupBy(r,t=>kr(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},J=5,Ir=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=Sr(r),c=[...s];let n=0,a;for(const[h,m]of t){let p;try{p=e({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(a=d),p=!0}p&&c.push(...m)}return n>0&&o(a,n),c},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Tr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:lr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:pr(s)}}if(r.kind==="log"){const s=P(o?Tr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:mr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:fr(t)}},wr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Nr=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Lr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:c}=r,n=z({"content-type":"application/json"},e),a=(h,m)=>{try{const p=fetch(c,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(h,m)=>{const p=P(h,s);p!==void 0&&a(p,m)},onRpc:(h,m)=>{if(O(h,o))return;const p=P(h,t);p!==void 0&&a(p,m)}}},Ar=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Rr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Mr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(c[a]=t[a]);const n=e.send([c]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},_r=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:c,onlyErrors:n,postProcessor:a,resourceAttributes:h,serviceNamespace:m,serviceVersion:p,tailSampler:d,token:X}=r,_=r.serviceName??"lunora",x=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const U={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},D=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const i=D.get(u);if(i!==void 0)return i;const f=er(u.resourceAttributes(),U);return D.set(u,f),f};let I=s;for(;I.endsWith("/");)I=I.slice(0,-1);const F={logs:{url:`${I}/v1/logs`,wrap:or},metrics:{url:`${I}/v1/metrics`,wrap:tr},spans:{url:`${I}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},c,X);let L=0;const q=(u,i)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},Y=async u=>{const i=Ir(u,d,q),f=new Map;for(const g of i){const b=H(g,a,x);if(b===void 0)continue;const N=R(g.resource);let w=f.get(N);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(N,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:N,wrap:w}=F[b];T.push(G(N,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(e===!1){const u=(i,f)=>{const T=H(i,a,x);if(T!==void 0){const{url:g,wrap:b}=F[T.bucket];br(g,b(T.encoded,"@lunora/runtime",_,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const E=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:u=>{E.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{E.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{E.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||E.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{E.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},xr=(...r)=>{const e=(t,s)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,s)}catch{}}},o={};for(const t of r)for(const s of wr)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Rr as analyticsEngineSink,xr as combineSinks,Nr as consoleSink,_r as otlpSink,Mr as pipelineLogSink,Ar as sentrySink,Lr as webhookSink};
1
+ import{LunoraError as Z}from"@lunora/errors";import{redactArgs as j}from"@lunora/observability";import{e as l,L as y,o as $,c as S,O as V,f as Q,g as v,h as z,w as rr,i as tr,j as or,m as er}from"./otlp-resource-BI3MvjSy.mjs";const sr=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},W=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:sr(r),nr=512,ir=200,ar=r=>{const e=r.maxItems??nr,o=r.maxDelayMs??ir;let t=[],s,c,n;const a=()=>{s!==void 0&&(clearTimeout(s),s=void 0)},h=async()=>{a();const p=t;t=[];const d=n;c=void 0,n=void 0;try{p.length>0&&await r.export(p)}catch{}finally{d?.()}},m=p=>{c===void 0&&(c=new Promise(d=>{n=d}),s=setTimeout(()=>{h()},o)),p?.(c)};return{add:(p,d)=>{for(t.push(p);t.length>e;)t.shift();m(d),t.length>=e&&h()},flush:async p=>{if(t.length===0){a();return}const d=h();return p?.(d),d},get size(){return t.length}}},cr=/["\\\u0000-\u001F\uD800-\uDFFF]/,B=r=>cr.test(r)?JSON.stringify(r):`"${r}"`,R=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(typeof r=="string")return B(r);if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r)){let n="[";for(let a=0;a<r.length;a++)a>0&&(n+=","),n+=R(r[a]);return n+"]"}const e=Object.getPrototypeOf(r);if(e!==null&&e!==Object.prototype){const n=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=r,t=Object.keys(o).sort();let s="{",c=!0;for(const n of t){const a=o[n];a!==void 0&&(c?c=!1:s+=",",s+=B(n),s+=":",s+=R(a))}return s+"}"},dr=1,ur=0,lr=(r,e)=>{const o=[l(y.functionPath,r.functionPath),l(y.ok,r.ok)];r.method!==void 0&&o.push(l("http.request.method",r.method)),r.path!==void 0&&o.push(l("url.path",r.path)),o.push(l("http.route",r.functionPath)),r.scheme!==void 0&&o.push(l("url.scheme",r.scheme)),r.host!==void 0&&o.push(l("server.address",r.host)),r.port!==void 0&&o.push(l("server.port",r.port)),r.userAgent!==void 0&&o.push(l("user_agent.original",r.userAgent)),r.shardKey!==void 0&&o.push(l(y.shardKey,r.shardKey)),o.push(l("http.response.status_code",r.error?.status??200)),r.error&&o.push(l(y.errorType,r.error.code),l("lunora.error_status",r.error.status)),r.fanOut&&o.push(l("lunora.fanout.table",r.fanOut.table),l("lunora.fanout.shards",r.fanOut.shards),l("lunora.fanout.failed",r.fanOut.failed));const t={attributes:o,endTimeUnixNano:S(e),kind:V.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??$(8),startTimeUnixNano:S(e-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??$(16)};return r.traceFlags!==void 0&&(t.flags=r.traceFlags),r.error&&(t.events=[{attributes:[l("exception.type",r.error.code),l("exception.message",r.error.message)],name:"exception",timeUnixNano:S(e)}]),t},M=(r,e)=>{const o=new Map([[y.functionPath,l(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&o.set(y.shardKey,l(y.shardKey,r.shardKey)),r.userId!==void 0&&o.set(y.userId,l(y.userId,r.userId)),r.errorType!==void 0&&o.set(y.errorType,l(y.errorType,r.errorType));for(const[t,s]of Object.entries(e??{}))o.set(t,l(t,W(s)));return[...o.values()]},pr=r=>{const e={attributes:M({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),flags:r.sampled===!1?ur:dr,kind:V[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},o=t=>v(Object.fromEntries(Object.entries(t??{}).map(([s,c])=>[s,W(c)])));return r.events!==void 0&&r.events.length>0&&(e.events=r.events.map(t=>({attributes:o(t.attributes),name:t.name,timeUnixNano:S(t.ts)}))),r.links!==void 0&&r.links.length>0&&(e.links=r.links.map(t=>({attributes:o(t.attributes),spanId:t.spanId,traceId:t.traceId}))),e},fr=r=>{const e=S(r.ts),o=M({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),t=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:e,traceId:r.traceId}],s={asDouble:r.value,attributes:o,...t===void 0?{}:{exemplars:t},timeUnixNano:e};return r.kind==="gauge"?{gauge:{dataPoints:[s]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...t===void 0?{}:{exemplars:t},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:e}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[s],isMonotonic:!0}}},mr=r=>{const e={attributes:M({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:Q[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(e.traceId=r.traceId),r.spanId!==void 0&&(e.spanId=r.spanId),r.eventName!==void 0&&(e.eventName=r.eventName,e.attributes.push(l("event.name",r.eventName))),e},hr=1024,C=5;let A=0;const yr=(r,e)=>{if(A>=C)return;A+=1;let o;try{o=new URL(r).host}catch{o="<unparseable endpoint>"}const t=A===C?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(e)}; the batch is DROPPED (there is no retry).${t}`)},gr=async r=>{const e=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(e).arrayBuffer()},G=async(r,e,o,t)=>{try{const s=JSON.stringify(e),{byteLength:c}=new TextEncoder().encode(s),n=(c<hr?fetch(r,{body:s,headers:o,method:"POST"}):gr(s).then(a=>fetch(r,{body:a,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(a=>{a.ok||yr(r,a.status)},()=>{});t?.(n),await n}catch{}},br=(r,e,o,t)=>{G(r,e,o,t?.waitUntil).catch(()=>{})},O=(r,e)=>e===!0&&r.ok,kr=r=>r.kind==="metric"?void 0:r.event.traceId,Sr=r=>{const e=Map.groupBy(r,t=>kr(t)),o=e.get(void 0)??[];return e.delete(void 0),{byTrace:e,untraced:o}},J=5,Ir=(r,e,o)=>{if(e===void 0)return r;const{byTrace:t,untraced:s}=Sr(r),c=[...s];let n=0,a;for(const[h,m]of t){let p;try{p=e({logs:m.filter(d=>d.kind==="log").map(d=>d.event),rpc:m.filter(d=>d.kind==="rpc").map(d=>d.event),spans:m.filter(d=>d.kind==="span").map(d=>d.event),traceId:h})}catch(d){n+=1,n===1&&(a=d),p=!0}p&&c.push(...m)}return n>0&&o(a,n),c},P=(r,e)=>{if(e===void 0)return r;try{return e(r)??void 0}catch{return}},Tr=r=>({...r,...r.fields===void 0?{}:{fields:j(r.fields)},message:j(r.message)}),H=(r,e,o)=>{if(r.kind==="rpc"){const s=P(r.event,e?.rpc);return s===void 0?void 0:{bucket:"spans",encoded:lr(s,r.endMs)}}if(r.kind==="span"){const s=P(r.event,e?.span);return s===void 0?void 0:{bucket:"spans",encoded:pr(s)}}if(r.kind==="log"){const s=P(o?Tr(r.event):r.event,e?.log);return s===void 0?void 0:{bucket:"logs",encoded:mr(s)}}const t=P(r.event,e?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:fr(t)}},wr=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Nr=(r={})=>{const{onlyErrors:e}=r;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{O(o,e)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const t=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,t,o.functionPath)}}},Lr=r=>{const{headers:e,onlyErrors:o,transform:t,transformLog:s,url:c}=r,n=z({"content-type":"application/json"},e),a=(h,m)=>{try{const p=fetch(c,{body:JSON.stringify(h),headers:n,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(p)}catch{}};return{onLog:(h,m)=>{const p=P(h,s);p!==void 0&&a(p,m)},onRpc:(h,m)=>{if(O(h,o))return;const p=P(h,t);p!==void 0&&a(p,m)}}},Ar=r=>{const{capture:e,captureLog:o}=r;if(typeof e!="function")throw new TypeError("sentrySink requires a `capture` callback — wire your own Sentry client, e.g. `sentrySink({ capture: (event) => Sentry.captureMessage(event.name) })`. There is no `dsn` option; the runtime bundles no Sentry client.");const t=r.onlyErrors??!0;return{onLog:o?s=>{try{o(s)}catch{}}:void 0,onRpc:s=>{if(!O(s,t))try{e(s)}catch{}}}},Rr=r=>{const{dataset:e,onlyErrors:o}=r;return{onRpc:t=>{if(!O(t,o))try{e.writeDataPoint({blobs:[t.functionPath,t.ok?"ok":"error",t.shardKey??"",t.error?.code??"",t.fanOut?.table??""],doubles:[t.durationMs,t.ok?0:1,t.fanOut?.shards??0,t.fanOut?.failed??0],indexes:[t.functionPath]})}catch{}}}},Mr=r=>{const{pipeline:e,serializeFields:o}=r;return{onLog:(t,s)=>{try{const c={functionPath:t.functionPath,level:t.level,message:t.message,ts:t.ts};t.fields&&(c.fields=o===!0?JSON.stringify(t.fields):t.fields);for(const a of["shardKey","userId","traceId","spanId"])t[a]!==void 0&&(c[a]=t[a]);const n=e.send([c]).catch(()=>{});s?.waitUntil&&s.waitUntil(n)}catch{}}}},_r=r=>{const{batch:e,deploymentEnvironment:o,detectResources:t,endpoint:s,headers:c,onlyErrors:n,postProcessor:a,resourceAttributes:h,serviceNamespace:m,serviceVersion:p,tailSampler:d,token:X}=r,_=r.serviceName??"lunora",x=r.redactLogs??!0;if(e!==!1&&e?.maxItems!==void 0&&(!Number.isInteger(e.maxItems)||e.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(e.maxItems)}.`);const U={...p===void 0?{}:{"service.version":p},...m===void 0?{}:{"service.namespace":m},...o===void 0?{}:{"deployment.environment":o},...h},D=new WeakMap,k=u=>{if(t!==!0||u?.resourceAttributes===void 0)return U;const i=D.get(u);if(i!==void 0)return i;const f=er(u.resourceAttributes(),U);return D.set(u,f),f};let I=s;for(;I.endsWith("/");)I=I.slice(0,-1);const F={logs:{url:`${I}/v1/logs`,wrap:or},metrics:{url:`${I}/v1/metrics`,wrap:tr},spans:{url:`${I}/v1/traces`,wrap:rr}},K=z({"content-type":"application/json"},c,X);let L=0;const q=(u,i)=>{if(L>=J)return;L+=1;const f=L===J?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(i)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},Y=async u=>{const i=Ir(u,d,q),f=new Map;for(const g of i){const b=H(g,a,x);if(b===void 0)continue;const N=R(g.resource);let w=f.get(N);w===void 0&&(w={logs:[],metrics:[],resource:g.resource,spans:[]},f.set(N,w)),w[b.bucket].push(b.encoded)}const T=[];for(const[,g]of f)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:N,wrap:w}=F[b];T.push(G(N,w(g[b],"@lunora/runtime",_,g.resource),K))}await Promise.all(T)};if(e===!1){const u=(i,f)=>{const T=H(i,a,x);if(T!==void 0){const{url:g,wrap:b}=F[T.bucket];br(g,b(T.encoded,"@lunora/runtime",_,i.resource),K,f)}};return{onLog:(i,f)=>{u({event:i,kind:"log",resource:k(f)},f)},onMetric:(i,f)=>{u({event:i,kind:"metric",resource:k(f)},f)},onRpc:(i,f)=>{O(i,n)||u({endMs:Date.now(),event:i,kind:"rpc",resource:k(f)},f)},onSpan:(i,f)=>{u({event:i,kind:"span",resource:k(f)},f)}}}const E=ar({export:Y,...e?.maxDelayMs===void 0?{}:{maxDelayMs:e.maxDelayMs},...e?.maxItems===void 0?{}:{maxItems:e.maxItems}});return{flush:u=>{E.flush(u?.waitUntil).catch(()=>{})},onLog:(u,i)=>{E.add({event:u,kind:"log",resource:k(i)},i?.waitUntil)},onMetric:(u,i)=>{E.add({event:u,kind:"metric",resource:k(i)},i?.waitUntil)},onRpc:(u,i)=>{O(u,n)||E.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(i)},i?.waitUntil)},onSpan:(u,i)=>{E.add({event:u,kind:"span",resource:k(i)},i?.waitUntil)}}},xr=(...r)=>{const e=(t,s)=>{for(const c of r){const n=c[t];if(n)try{n.apply(c,s)}catch{}}},o={};for(const t of r)for(const s of wr)o[s]===void 0&&t[s]!==void 0&&(o[s]=t[s]);return{...o,flush:t=>{e("flush",[t])},onLog:(t,s)=>{e("onLog",[t,s])},onMetric:(t,s)=>{e("onMetric",[t,s])},onRpc:(t,s)=>{e("onRpc",[t,s])},onSpan:(t,s)=>{e("onSpan",[t,s])}}};export{Rr as analyticsEngineSink,xr as combineSinks,Nr as consoleSink,_r as otlpSink,Mr as pipelineLogSink,Ar as sentrySink,Lr as webhookSink};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as sr,toErrorBody as ar}from"@lunora/errors";import{e as Zt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as ir}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as cr,f as dr}from"./base64-Bl1_r2k1.mjs";import{e as ur,a as lr,E as gt,d as hr}from"./identity-header-BtkOCFcS.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as en,p as fr,m as pr,d as mr,a as wr,r as gr}from"./otlp-resource-BI3MvjSy.mjs";import{r as yr,f as Et,a as ue,S as _t}from"./observability-DgurIZIR.mjs";import{e as Ne,d as Xe,a as br}from"./wire-codec-BLvSm5Mn.mjs";import{d as ne,e as ae,M as tn,b as Er,f as _r,g as nn,t as Rr,h as rn}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as c,toErrorResponse as Rt}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as rt,BACKUP_KEY_PREFIX as ot,isBackupManifestKey as Sr,backupObjectKeyOfManifest as on,backupObjectKey as Ar,backupManifestKey as Tr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Or,buildStorageAdminRoutes as vr,STORAGE_UPLOAD_MAX_BODY_BYTES as kr,STORAGE_PATH as Ir}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-KGQR1LvR.mjs";import{b as Pr,e as Dr,f as St,g as Nr,h as Ur}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Cr,durableObjectProbe as Br,d1Probe as xr,presenceProbe as Me}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Hr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as ui,routeIdentityResolvers as li}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Lr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{resolveShard as ye,applyJurisdiction as Ke}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as At,handleCorsPreflight as jr,enforceOrigin as $r,decorateResponse as Fe,enforceWebSocketOrigin as Tt}from"./decorateResponse-CRrFNW1v.mjs";const Mr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},sn="__lunoraBranch",Kr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,sn),Fr=`may not contain the reserved workflow branch-marker key ("${sn}")`,Gr=async e=>{const t=[];let n;for(;;){const o=await e(n);if(t.push(...Array.isArray(o.records)?o.records:[]),o.truncated!==!0||typeof o.cursor!="string"||o.cursor.length===0)return t;if(o.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=o.cursor}},st=(e,t)=>{const n=Math.max(e.length,t.length);let o=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,u=s<t.length?t.charCodeAt(s):0;o|=i^u}return o===0},Qr=/already[\s_-]?exists/iu,Wr=e=>Qr.test(e instanceof Error?e.message:String(e)),zr=(e,t,n,o)=>{const s=e.get(t);if(s!==void 0)return s;Zt(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},at=new TextEncoder,Vr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Vr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const qr=64,Jr=new Map,an=async e=>zr(Jr,e,async()=>crypto.subtle.importKey("raw",at.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),qr),cn=async(e,t)=>{const n=await an(e),o=await crypto.subtle.sign("HMAC",n,at.encode(t));return cr(new Uint8Array(o))},Yr=async(e,t,n)=>{const o=await an(e);return crypto.subtle.verify("HMAC",o,n,at.encode(t))},Xr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Xr);const Zr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),eo=-100,to=15,no=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Zr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>to?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<eo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:no(t)},Ze="::relay::",ro=(e,t)=>`${e}${Ze}${String(t)}`,et="::replica::",oo=(e,t)=>`${e}${et}${t}`,so=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},ao=new Set(["1","enabled","on","true","yes"]),io=new Set(["0","disabled","false","no","off"]),co=(e,t)=>{const n=(e??"").trim().toLowerCase();return ao.has(n)?!0:io.has(n)?!1:t},dn="v1",uo=6e4,lo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??uo),o=`${dn}.${String(n)}`,s=await cn(e,o);return{expiresAtMs:n,token:`${o}.${s}`}},ho=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[s,i,u]=o;if(s!==dn||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let p;try{p=dr(u)}catch{return!1}return Yr(e,`${s}.${i}`,p)},D="/_lunora/admin/auth",fo={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},U=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},un=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},oe=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ge=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=un(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},kt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[o,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[o]=s);return n},po={[`${D}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${D}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${D}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${D}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${D}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${D}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${D}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${D}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${D}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${D}/sign-up-invitations/create`]:{build:({body:e})=>({email:U(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:oe(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${D}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:U(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${D}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${D}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${D}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${D}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${D}/users/create`]:{build:({body:e})=>({data:Ge(e,"data"),email:U(e,"email"),name:U(e,"name"),password:oe(e,"password"),role:un(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:vt(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:oe(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:oe(e,"logo"),metadata:Ge(e,"metadata"),name:U(e,"name"),ownerId:oe(e,"ownerId"),slug:oe(e,"slug")}),http:"POST",method:"createOrganization"},[`${D}/organizations/update`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Ge(e,"metadata"),name:oe(e,"name"),organizationId:U(e,"organizationId"),slug:oe(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:oe(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${D}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:oe(e,"inviterId"),organizationId:U(e,"organizationId"),role:oe(e,"role")}),http:"POST",method:"inviteMember"},[`${D}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${D}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${D}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${D}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${D}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${D}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${D}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:kt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${D}/organizations/roles/update`]:{build:({body:e})=>({permission:kt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${D}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},mo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const u=i,h=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:h,status:fo[h]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const h=u[i.method];if(h===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(s.url),f={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:T=>e.queryParameter(p,T)},g=i.build(f),S=await t(()=>h(g));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},o={};for(const[s,i]of Object.entries(po))o[s]=u=>n(u,i);return o},It="__lunora_admin__:getAuthAuditLog",Pt=e=>typeof e=="string"&&e!==""?e:void 0,Dt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,wo=e=>async(n,o)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=Pt(o.actorId),u=Pt(o.event),h=Dt(o.sinceSeq),p=Dt(o.limit),f={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...p===void 0?{}:{limit:p}};let g;try{g=await s.read(f)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:g};return Response.json({result:Ne(S)},{headers:{"content-type":"application/json"},status:200})},go=(e,t)=>{const n=[],o=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?o.push(s):n.push(s);return{globalTables:o,shardLocalTables:n}},yo=async(e,t,n,o,s,i,u)=>{if(n!==void 0&&o.length===0)return;const h=await e.orchestrateExport(i,{args:{tables:o},defaultShardKey:u,headers:t,tables:o}),p=h.shards.filter(f=>f.error);if(p.length>0){const f=p.map(g=>`${g.shardKey}: ${g.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(p.length)} of ${String(h.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}for(const f of h.shards)for(const g of f.rows??[])s(g)},ln=async(e,t,n,o,s,i)=>{const u=o??e.listSchemaTables?.();o===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:h,shardLocalTables:p}=go(e,u);await yo(t,n,u,p,s,i,e.defaultShardKey??"__root__");const f=e.exportGlobals;if((o===void 0||h.length>0)&&f)for await(const S of f({tables:h}))s(S)},bo=new TextEncoder,Eo=1e3,hn=10,_o=200,Nt=8,fn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,hn).map(o=>on(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Ro=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let o=0;for(const s of e)n.set(s,o),o+=s.byteLength;return n},it=async(e,t,n,o)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let u=0;u<Eo;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of h.objects)Sr(p.key)&&p.customMetadata?.[fn]===o&&s.push(p.key);if(!h.truncated||h.cursor===void 0)break;i=h.cursor}return{eligible:s.length,stale:s.toSorted((u,h)=>h.localeCompare(u)).slice(n)}},So=async(e,t,n,o,s)=>{const{stale:i}=await it(e,t,n,o),u=new Set(s),h=i.filter(w=>u.has(w)),p=h.slice(0,_o),f=i.length-p.length,g=s.length-h.length;if(p.length===0)return{deleted:[],failed:[],ignored:g,remaining:f};const S=[],T=[];for(let w=0;w<p.length;w+=Nt){const b=await Promise.allSettled(p.slice(w,w+Nt).map(async R=>(await e.delete(on(R)),await e.delete(R),R)));for(const[R,y]of b.entries())y.status==="fulfilled"?S.push(y.value):T.push(p[w+R])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ct(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ct(T)}`),{deleted:S,failed:T,ignored:g,remaining:f}},Ao=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=rt(e.backupPrefix??ot),o=e.backupCron,{eligible:s,stale:i}=o===void 0?{eligible:0,stale:[]}:await it(t,n,e.backupRetain,o);return{cron:o,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},To=async(e,t,n,o)=>{const s=e.backupStore,i=e.queryCoordinator;if(!s)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},h=e.backupTables;let p=0,f=0,g=[];await ln(e,i,u,h,I=>{const j=bo.encode(`${JSON.stringify(I)}
2
+ `);if(p+=1,f+=j.byteLength,f>Ut)throw new c(`scheduled backup reached ${String(f)} bytes of NDJSON, past the ${String(Ut)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});g.push(j)},t);const T=rt(e.backupPrefix??ot),w=new Date(o.scheduledTime).toISOString(),b=Ar(T,w),R=Ro(g,f);g=[];const y=Or(await crypto.subtle.digest("SHA-256",R));await s.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:f,createdAt:w,cron:o.cron,file:b,id:w,rows:p,scheduledTime:o.scheduledTime,sha256:y,...h?{tables:h.join(",")}:{}};await s.put(Tr(b),`${JSON.stringify(v,void 0,2)}
3
+ `,{customMetadata:{[fn]:o.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await it(s,T,e.backupRetain,o.cron);if(I.length>0){const j=I.slice(0,hn),k=I.length-j.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${j.join(", ")}${k>0?` (+${String(k)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,I)}},Oo=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const o=e.backupCron,s=e.backupRetain;if(o===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return So(n,rt(e.backupPrefix??ot),s,o,t)},vo="/_lunora/admin/backup/retention",ko="/_lunora/admin/backup/prune",Io=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,s=(h,p)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async h=>(M(h,"GET","Backup-retention"),s(h,"retention preview"),Response.json(await Ao(t),{headers:{"cache-control":"no-store"}})),u=async h=>{M(h,"POST","Backup-prune"),s(h,"prune");const{confirm:p}=await n(h);if(!Array.isArray(p)||p.some(f=>typeof f!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Oo(t,p),{headers:{"cache-control":"no-store"}})};return{[ko]:u,[vo]:i}},Bt=500,Po=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const o=e;if(typeof o.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(o.functionPath.startsWith("__lunora_relation__:")||o.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(o.args!==void 0&&(typeof o.args!="object"||o.args===null||Array.isArray(o.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(o.id!==void 0&&typeof o.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:o.args===void 0?{}:o.args,baselineSeq:typeof o.baselineSeq=="number"?o.baselineSeq:void 0,clientId:typeof o.clientId=="string"?o.clientId:void 0,clientSeq:typeof o.clientSeq=="number"?o.clientSeq:void 0,functionPath:o.functionPath,id:typeof o.id=="number"?o.id:t,mutationId:typeof o.mutationId=="string"?o.mutationId:void 0},shardKey:typeof o.shardKey=="string"?o.shardKey:n}},Do=(e,t)=>{if(e.length>Bt)throw new c(`RPC batch exceeds the ${String(Bt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,o=new Set;for(const[s,i]of e.entries()){const{entry:u,shardKey:h}=Po(i,s,t);if(o.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});o.add(u.id);const p=n.get(h)??[];p.push(u),n.set(h,p)}return n},No="/_lunora/admin/export",Uo="/_lunora/admin/import",Co="/_lunora/admin/sync",Bo="/_lunora/admin/connector/sync",xo="/_lunora/admin/apply",Ho="/_lunora/admin/export-tap/run",Lo=new TextEncoder,jo=async e=>{const n=await ae(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const o=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});o.push(s)}return{tables:o}},Qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,$o=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:s,knownTables:i,queryCoordinator:u,assertAdmin:h,requireAdminOption:p,resolveForwardContext:f,shardDO:g,streamExportRows:S,streamingImport:T,syncGlobals:w}=e,b=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const J=p(k,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await jo(k),{headers:Q}=await f(k,K),z=new ReadableStream({async pull(V){const Z=W=>{V.enqueue(Lo.encode(`${JSON.stringify(W)}
4
+ `))};try{await S(J,Q,C.tables,Z),V.close()}catch(W){V.error(W)}}});return new Response(z,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const J=p(k,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await ne(k),Q=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},z=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},V=typeof C.limit=="number"?C.limit:void 0,Z=typeof C.globalCursor=="number"?C.globalCursor:0,W=Qe(C.tables),{headers:se}=await f(k,K),L=W??i(),re=await J.orchestrateCdcSync(g,{cursors:Q,defaultShardKey:n,epochs:z,headers:se,limit:V,tables:L}),ie=w?await w({limit:V,sinceSeq:Z}):void 0;return Response.json({global:ie,shards:re.shards},{status:200})},y=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const J=p(k,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await ne(k),Q=Dr(C.cursor),z=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables),{headers:Z}=await f(k,K),W=V??i(),se=await J.orchestrateCdcSync(g,{cursors:Q.s,defaultShardKey:n,headers:Z,limit:z,tables:W}),L=[],re={...Q.s};let ie=!1;for(const ce of se.shards)ie=St(L,ce.changes??[],Ur(z))||ie,re[ce.shardKey]=ce.cursor;let _e=Q.g;if(w){const ce=await w({limit:z,sinceSeq:Q.g});ie=St(L,ce.changes,z)||ie,_e=ce.cursor}const Re=Nr({g:_e,s:re,v:1}),Ce={changes:L,hasMore:ie,nextCursor:Re};return Response.json(Ce,{status:200})},v=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const J=p(k,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await ne(k),z=(Array.isArray(C.batches)?C.batches:[]).map(L=>L).filter(L=>L!==null&&typeof L=="object"&&typeof L.shardKey=="string"&&Array.isArray(L.changes)),V=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:Z}=await f(k,K),W=await J.orchestrateApplyCdc(g,{batches:z,headers:Z}),se=V.length>0&&t?await t({changes:V}):0;return Response.json({applied:W.applied+se,failed:W.failed,ok:W.ok},{status:200})},I=async(k,K)=>{const $=we(k,["POST"]);if($)return $;h(k);const{headers:J}=await f(k,K),C=await T(k,J);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},j=async(k,K)=>{const $=we(k,["POST"]);if($)return $;const J=p(k,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(s===void 0||Object.keys(s).length===0||o===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(k),Q=typeof C.sink=="string"?C.sink:void 0,z=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,V=Qe(C.tables);if(Q===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Z=s[Q];if(Z===void 0)throw new c(`Export-tap sink "${Q}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:W}=await f(k,K),se=V??i(),L=await Pr({coordinator:J,cursorStore:o,defaultShardKey:n,headers:W,limit:z,shardDO:g,sink:Z,tables:se});return Response.json(L,{headers:{"content-type":"application/json"},status:200})};return{[xo]:v,[Bo]:y,[No]:b,[Ho]:j,[Uo]:I,[Co]:R}},Mo=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const o=n;return typeof o.table!="string"||o.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!o.doc||typeof o.doc!="object"||Array.isArray(o.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:o.table},ok:!1}:{doc:o.doc,ok:!0,table:o.table}},Ko=(e,t,n,o,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:o}},Fo=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const o=[],s=[],i=new Map;let u=0,h=0;const p=e.body.getReader(),f=new TextDecoder;let g="",S=0;const T=w=>{h+=1;const b=w.trim();if(b.length===0)return;u+=1;const R=Mo(b,h);if(!R.ok){o.push(R.error);return}const{doc:y,table:v}=R,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){s.push({doc:y,line:h,table:v});return}const j=Ko(y,v,I,n,h);if(!j.ok){o.push(j.error);return}const k=i.get(j.shardKey);k?k.rows.push({doc:y,table:v}):i.set(j.shardKey,{rows:[{doc:y,table:v}],shardKey:j.shardKey,startLine:h})};for(;;){const{done:w,value:b}=await p.read();if(w)break;if(b&&(S+=b.byteLength,S>tn))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});g+=f.decode(b,{stream:!0});let R=g.indexOf(`
5
+ `);for(;R!==-1;){const y=g.slice(0,R);g=g.slice(R+1),T(y),R=g.indexOf(`
6
+ `)}}return g.length>0&&T(g),{errors:o,globalRows:s,perShard:i,received:u}},Go=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),xt=(e,t)=>{for(const[n,o]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+o;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Qo=async(e,t,n,o)=>{const s=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:h,received:p}=await Fo(e,t,s),f={conflicts:0,errors:i,failed:[],inserted:{}},g=[];if(t.resolveTableSharding===void 0&&h.size>0&&g.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),h.size>0){const S=t.queryCoordinator;if(!S)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(o,{batches:[...h.values()],headers:n});xt(f,T),f.failed.push(...Go(T.shards))}if(u.length>0)if(t.importGlobals){const S=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:S});xt(f,T)}else for(const S of u)f.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:f.conflicts,errors:f.errors,failed:f.failed,inserted:f.inserted,received:p,...g.length>0?{warnings:g}:{}}},We=e=>typeof e=="object"&&e!==null?e:{},ze=e=>typeof e.kind=="string"?e.kind:"unknown",Wo=(e,t)=>{let n=We(t),o=!1;ze(n)==="optional"&&(o=!0,n=We(n._meta?.inner));const s=ze(n),i=n._meta??{},u={kind:s,name:e,optional:o};if(s==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),s==="array"){const h=ze(We(i.inner));h!=="unknown"&&(u.element=h)}return u},zo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Wo(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Vo="/_lunora/admin/functions",qo="/_lunora/admin/cron-jobs",Jo="/_lunora/admin/openapi",Yo="/_lunora/admin/openrpc",Xo="/_lunora/admin/global/tables",Zo="/_lunora/admin/global/table",es="/_lunora/admin/global/facet",Ht=e=>{if(e===void 0||e==="")return;let t;try{t=Xe(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(o=>{if(typeof o!="object"||o===null||typeof o.column!="string")return[];const{column:s,value:i}=o;return[{column:s,value:i}]});return n.length===0?void 0:n},ts=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:{}}),ns=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"}),rs=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:s,requireAdminOption:i}=e,u=w=>{M(w,"GET","Functions");const b=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([y,v])=>v.visibility==="internal"||v.kind==="stream"?[]:[{args:zo(v.args),kind:v.kind,path:y}]).toSorted((y,v)=>y.path.localeCompare(v.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},h=w=>{M(w,"GET","Cron-jobs");const b=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([y,v])=>v.map(I=>({args:I.args,cron:y,functionPath:I.functionPath,name:I.name,shardKey:I.shardKey,workflow:I.workflow}))).toSorted((y,v)=>y.name.localeCompare(v.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??ts,{headers:{"content-type":"application/json"},status:200})),f=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??ns,{headers:{"content-type":"application/json"},status:200})),g=async w=>{M(w,"GET","Global-tables");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{M(w,"GET","Global-table");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),y=s(R,"table");if(y===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const v=await b.readTablePage({...o(w),filters:Ht(s(R,"filters")),table:y});return Response.json(v,{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-facet");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),y=s(R,"table"),v=s(R,"column");if(y===void 0||v===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const I=s(R,"limit"),j=I===void 0?void 0:Number(I),k=await b.facetColumn({column:v,filters:Ht(s(R,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:y});return Response.json(k,{headers:{"content-type":"application/json"},status:200})};return{[qo]:h,[Vo]:u,[es]:T,[Zo]:S,[Xo]:g,[Jo]:p,[Yo]:f}},os="/_lunora/admin/kv/namespaces",ss="/_lunora/admin/kv/keys",pn="/_lunora/admin/kv/value",mn=32*1048576,Lt=60,as=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,R)=>{const y=new URL(b.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},u=async(b,R)=>{if(!(await b.listNamespaces()).some(v=>v.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},h=async b=>(M(b,"GET","KV-namespaces"),s({namespaces:await o(b).listNamespaces()})),p=async b=>{M(b,"GET","KV-keys");const R=o(b),y=new URL(b.url),v=y.searchParams.get("namespace")??"";if(v==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const I=y.searchParams.get("prefix")??void 0,j=y.searchParams.get("cursor")??void 0,k=y.searchParams.get("limit"),K=k===null?void 0:Number.parseInt(k,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(R,v),s(await R.listKeys({cursor:j,limit:$,namespace:v,prefix:I}))},T={DELETE:async b=>{const R=o(b),y=i(b,"DELETE");return await u(R,y.namespace),await R.deleteKey(y),s({deleted:!0})},GET:async b=>{const R=o(b),y=i(b,"GET");return await u(R,y.namespace),s(await R.getValue(y))},PUT:async b=>{const R=o(b),y=await t(b,mn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<Lt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Lt;if(y.expiration!==void 0&&(typeof y.expiration!="number"||!Number.isInteger(y.expiration)||y.expiration<v))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,y.namespace),await R.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),s({ok:!0})}},w=b=>{const R=T[b.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[os]:h,[ss]:p,[pn]:w}},is="/_lunora/migrate",cs="/_lunora/admin/pitr",ds="/_lunora/admin/rank",us="/_lunora/admin/rankpage",ls="/_lunora/admin/shard-traffic",hs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),fs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),ps=async e=>{const n=await ae(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!hs.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},ms=async e=>{const n=await ae(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},ws=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}},gs=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})},ys=async e=>{const n=await ae(e,"Rank page")??{};gs(n);const o=ws(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:o,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},bs=async e=>{const n=await ae(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},Es=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!fs.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},_s=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:s,resolveForwardContext:i,shardDO:u}=e,h=(w,b)=>{if(w.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(w))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new c(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return s},p=async(w,b)=>{const R=h(w,"Migration"),y=await ps(w),{headers:v}=await i(w,b),I=await R.orchestrateMigration(u,{args:y.args,defaultShardKey:t,functionPath:y.functionPath,headers:v,table:y.table});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},f=async(w,b)=>{const R=h(w,"Rank"),y=await ms(w),{headers:v}=await i(w,b),I=await R.orchestrateRank(u,{headers:v,index:y.index,partitionKey:y.partitionKey,rowId:y.rowId,sortValues:y.sortValues,table:y.table});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},g=async(w,b)=>{const R=h(w,"Rank page"),y=await ys(w),{headers:v}=await i(w,b),I=await R.orchestrateRankPage(u,{...y,headers:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},S=async(w,b)=>{const R=h(w,"Shard-traffic"),y=await bs(w),{headers:v}=await i(w,b),I=await R.orchestrateShardTraffic(u,{headers:v,table:y.table});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},T=async(w,b)=>{if(M(w,"POST","PITR"),!o(w))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await Es(w),{headers:y}=await i(w,b),v=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:y,method:"POST"});return n(u,R.shardKey??t,v)};return{[is]:p,[cs]:T,[ds]:f,[us]:g,[ls]:S}},Rs=1,Ss=0,As=32,Ts=512,Os=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,vs=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Ts)return;const n=t.split(",");if(!(n.length>As)){for(const o of n)if(!Os.test(o.trim()))return;return t}},ks=e=>{const t=fr(e.headers.get("traceparent"));if(t===void 0)return;const n=vs(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=ks(e),o=t.trustInbound===!0?n:void 0,s=ge(8),i=o?.traceId??ge(16),u=yr(t.sampling,o===void 0?s:i),h=u.isTraced&&(o===void 0||o.sampled);return{decision:u,ignoredUpstream:n!==void 0&&o===void 0,trace:{sampled:h,spanId:s,traceFlags:h?Rs:Ss,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},$t=(e,t)=>{t.traceparent=en(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Is=(e,t)=>{let n;return()=>{if(n===void 0){const o=gr(e),s=t===void 0?void 0:t.cf;n=pr(wr(o),mr(o,s))}return n}},Ps="/_lunora/admin/scheduled",Ds="/_lunora/admin/scheduled/status",Ns="/_lunora/admin/scheduled/ws",Us="/_lunora/admin/scheduled/cancel",Cs="/_lunora/admin/scheduled/dead",Bs="/_lunora/admin/scheduled/dead/retry",xs="/_lunora/admin/scheduled/dead/cancel",Hs="/_lunora/admin/scheduled/pool/release",Ls=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:s}=e,i=(f,g)=>S=>{if(S.method!=="GET")throw new c(`${g} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),w=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${f}${w}`,{method:"GET"}))},u=(f,g,S=g)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const w=o(T),b=await ae(T,g);if(typeof b?.id!="string"||b.id==="")throw new c(`${g} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return w.fetch(new Request(`https://scheduler.internal${f}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async f=>{if(f.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const g=o(f),S=await ae(f,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return g.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async f=>{if(f.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(f))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const g=n();return ye(g,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Us]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[xs]:u("/dead/cancel","Scheduled dead-letter action"),[Cs]:i("/dead","Scheduled dead-letter"),[Bs]:u("/dead/retry","Scheduled dead-letter action"),[Ps]:i("/list","Scheduled-list"),[Hs]:h,[Ds]:i("/status","Scheduler-status"),[Ns]:p}},js="/_lunora/scheduled",wn="/_lunora/queue",gn=16*1048576,$s=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,s=async(u,h,p)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const f=await ae(u,"Scheduled tick"),g=typeof f?.cron=="string"?f.cron:"";if(g==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:g,noRetry:()=>{},scheduledTime:Date.now()},h,p),Response.json({cron:g,ok:!0})},i=async(u,h,p)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!o)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const f=await ae(u,"Queue dispatch",gn);if(!Array.isArray(f?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const g=typeof f.queue=="string"?f.queue:"",S=f.messages.filter(w=>typeof w=="object"&&w!==null&&typeof w.id=="string").map(w=>({body:w.body,id:w.id})),T=await o({messages:S,queue:g},h,p);return Response.json({retry:T?.retry??[]})};return{[wn]:i,[js]:s}},Ms=(e,...t)=>{let n=e.cf;for(const o of t){if(typeof n!="object"||n===null)return;n=n[o]}return typeof n=="string"?n:void 0},tt={mtls:e=>Ms(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ks=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(tt,e)?tt[e]:void 0)??(()=>!1),Fs=e=>typeof e=="string"&&Object.hasOwn(tt,e),Gs=e=>{const t=Fs(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return o=>{n||t!==void 0&&o.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Qs="/_lunora/admin/vector/indexes",Ws="/_lunora/admin/vector/query",zs=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=async i=>{M(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const f=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[Qs]:o,[Ws]:s}},Vs="/_lunora/admin/workflows/instances",qs="/_lunora/admin/workflows/instance",Js="/_lunora/admin/workflows/status",Ys={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Xs=e=>e!==null&&Object.hasOwn(Ys,e)?e:void 0,Mt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const o=Number(n);return Number.isInteger(o)&&o>0?o:void 0},Ve=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Kt=()=>{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})},Zs=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,p)=>{M(u,"GET","Workflows instances"),t(u);const f=n(h);if(!f)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const g=Ve(p,"name"),S=Xs(p.searchParams.get("status"));return Response.json(await f.listInstances({page:Mt(p,"page"),perPage:Mt(p,"perPage"),status:S,workflowName:g}))},s=async(u,h,p)=>{M(u,"GET","Workflows instance"),t(u);const f=n(h);return f?Response.json(await f.getInstance({instanceId:Ve(p,"id"),workflowName:Ve(p,"name")})):Kt()},i=async(u,h)=>{M(u,"POST","Workflows status"),t(u);const p=n(h);if(!p)return Kt();const f=await ae(u,"Workflows status");if(typeof f?.name!="string"||f.name===""||typeof f.id!="string"||f.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:g}=f;if(g!=="pause"&&g!=="resume"&&g!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:g,instanceId:f.id,workflowName:f.name}))};return{[qs]:s,[Vs]:o,[Js]:i}},ea={[pn]:mn,[wn]:gn,[Ir]:kr},Ft="/_lunora/rpc",ta="/_lunora/rpc-batch",na="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:Is(e,t),...n===void 0?{}:{waitUntil:n}}),qe=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Gt=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Je=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let o;try{o=new URL(e.url)}catch{return{method:t,userAgent:n}}const s=o.port===""?void 0:Number(o.port);return{host:o.hostname,method:t,path:o.pathname,port:Number.isNaN(s)?void 0:s,scheme:o.protocol.replace(":",""),userAgent:n}},Qt="/_lunora/voice/",ra="/_lunora/scheduler/dispatch",oa="/_lunora/admin/cron-jobs/run",sa="/_lunora/admin/ws-token",aa="/_lunora/admin/",Ue="/_lunora/",ia="/_lunora/migrate",ca="/_lunora/status",da=e=>e.startsWith(aa)||e===ia,ua="__lunora_relation__:",ve=e=>{if(e.startsWith(ua))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},ke=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=hr(n);if(o===void 0)throw new c(`malformed ${gt} header`,{code:"BAD_REQUEST",status:400});if(o.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},la=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},zt="/api/auth",ha="__lunora_admin__:recordAuthEvent",fa="__lunora_admin__:listPushSubscriptions",pa=["/sign-in","/sign-up","/callback"],ma=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return pa.some(s=>o===s||o.startsWith(`${s}/`))},wa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ie=(e,t,n,o)=>{const s=sr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",u=s?n.status:500,h=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:h,status:u},functionPath:e,ok:!1,...o.fanOut?{fanOut:{failed:0,shards:0,table:o.fanOut.table}}:{},...o.shardKey?{shardKey:o.shardKey}:{}}},ga=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Vt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,ya=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},nt=new WeakMap,ba=async(e,t,n,o,s=nt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),p=e.headers.get("x-d1-bookmark"),f=e.headers.get("x-lunora-mutation-id"),g=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");u&&(i.authorization=u),h&&(i.cookie=h),p&&(i["x-d1-bookmark"]=p),f&&(i["x-lunora-mutation-id"]=f),g&&(i["x-lunora-client-id"]=g),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const w=Rr(e.headers,o);if(w&&(i["x-lunora-client-ip"]=w),!n)return{claims:null,headers:i,identity:null,userId:null};const b=await n(e,t,s);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=ur(b.userId);const R=ga(b);R!==void 0&&(i["x-lunora-identity-exp"]=String(R));const{userId:y,...v}=b,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=lr(I)),{claims:I,headers:i,identity:b,userId:y}},Ea=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),_a=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!Ea.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},Ra=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Ye=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},Sa=async e=>{const t=await rn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&nn(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=_a(s.fanOut),u=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const h=u.table;if(typeof h=="string"&&h!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Pe=new Map,Aa=5e3,Ta=4096,Oa=async(e,t)=>{const n=Date.now(),o=Pe.get(t);if(o!==void 0&&o.expiresMs>n)return o.relayCount;o!==void 0&&Pe.delete(t);let s=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const h=(await i.json()).relayCount;typeof h=="number"&&h>0&&(s=Math.floor(h))}}catch{s=0}return Zt(Pe,Ta),Pe.set(t,{expiresMs:n+Aa,relayCount:s}),s},qt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},De=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),va=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],ka=(e,t)=>{for(const n of va){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Jt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const s of o)s.startsWith("x-lunora-")&&n.delete(s);return ka(n,t),n},Ia=async(e,t,n)=>e.length===0||n.length===0?!1:st(await cn(e,t),n),Yt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...s]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:st(t,s.join(" ").trim())},Xt=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await ho(t,o)?!0:n?!1:st(t,o)},Pa=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return xr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Me(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Me(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Me(`hyperdrive:${e}`,!0)},Da=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ue))throw new c(`route "${t}" is under the reserved ${Ue} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},Na=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},yn=e=>{Na(e);const t=Ks(e.trustInboundTraceContext),n=Gs(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",s=Hr(e.resolveIdentity,e.identity),i=Ke(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),h=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,a])=>[r,Ke(a,e.jurisdiction)]));let p=!1;const f=r=>{if(r===void 0||e.jurisdiction===void 0)return r;p||(p=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},g=async(r,a,l,d=e.shardRegion?.(a))=>ye(r,a,f(d)).fetch(l);let S;const T=()=>e.adminToken??S;let w;const b=()=>e.requireEphemeralWsToken??w??!0;let R;const y=r=>{const a=r??{};if(R??=qt(r,e.shardDO),w===void 0&&e.requireEphemeralWsToken===void 0){const d=a.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(w=co(d,!0))}if(S!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(S=l)},v=new WeakSet,I=r=>Yt(r,T())||v.has(r),j=async r=>{if(!(e.adminGate===void 0||v.has(r)))try{await ke(e.adminGate(r,nt.get(r)))&&v.add(r)}catch{}},k=async(r,a,l,d)=>{const m=await ba(r,a,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(m.headers[bt]=yt),m},K=async(r,a)=>{const l=await k(r,a,e.resolveIdentity);if(v.has(r)&&l.headers.authorization===void 0){const d=T();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let $=!1,J=!1;const C=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},Q=r=>{if(!e.allowUnauthenticatedShardAccess){const a=r==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${r} access is default-denied: configure \`${a}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${r} access (relying solely on per-row RLS).`,{code:r==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}$||($=!0,console.warn([`[lunora] SECURITY: serving ${r} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},z=async(r,a,l=!1)=>{if(a.includes(Ze)||a.includes(et))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await ke(e.authorizeShard({identity:r,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==o&&Q("shard")},V=_s({defaultShard:o,forwardToShard:g,isAdmin:I,queryCoordinator:e.queryCoordinator,resolveForwardContext:K,shardDO:i}),Z=async(r,a,l,d,m,E)=>{ve(r);const O={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(O["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(O["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(O["x-lunora-mutation-id"]=d),E!==void 0&&E.length>0&&(O.traceparent=E),g(i,l,De(r,a,O))},W=async(r,a,l,d,m)=>{const E=l?.[r];if(!E||typeof E.create!="function")throw new c(`${d} targets workflow binding "${r}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Kr(a))throw new c(`${d} params ${Fr}`,{code:"BAD_REQUEST",status:400});try{await E.create(m===void 0?{params:a}:{id:m,params:a})}catch(O){if(!Wr(O))throw O}},se=async(r,a,l)=>{if(r.workflow){await W(r.workflow,r.args??{},a,`cron job "${r.name}"`);return}if(r.functionPath===void 0)throw new c(`cron job "${r.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await Z(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},L=r=>{if(!I(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},re=(r,a,l)=>{if(L(r),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},ie=async(r,a,l,d,m)=>{const E=e.cronJobs?.[r];if(!E)return 0;for(const O of E)try{await se(O,a,m)}catch(P){l.push(d(P))}return E.length},_e=async(r,a)=>{if(L(r),M(r,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ne(r),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(E=>E.name===d);if(!m)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await se(m,a),Response.json({name:d,ran:!0},{status:200})},Re=async r=>{const a=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!a||!u||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Ce=async(r,a)=>{M(r,"POST","Scheduler dispatch");const l=await rn(r),d=a??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,E=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),O=r.headers.get("x-lunora-scheduler-signature");let P=!1;if(O&&m?P=await Ia(m,l,O):E&&(P=Yt(r,E)),!P)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=N??{},A=_.args??{},B=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await W(_.workflow,A,a,"scheduled workflow",B),await Re(_),Response.json({ok:!0},{status:200});if(typeof _.functionPath!="string"||_.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,q=la(r),H=await Z(_.functionPath,A,x,B,q,r.headers.get("traceparent")??void 0);return await Re(_),H},ce=wo({assertAdmin:L,getReader:()=>e.authAuditReader}),bn=async(r,a)=>{L(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ne({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=a?.kind,m=a?.userId,E=a?.limit,O=d==="fcm"||d==="web-push"?d:void 0,P=typeof m=="string"&&m!==""?m:void 0,N=typeof E=="number"&&Number.isFinite(E)?Math.trunc(E):0,_=N>0?Math.min(N,1e3):1e3,B=(await l.list({kind:O,limit:_,userId:P})).filter(x=>O!==void 0&&x.kind!==O?!1:P===void 0||(x.userId??null)===P).map(({keys:x,token:q,...H})=>H);return Response.json({result:Ne({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},En=async(r,a)=>{if(!a.fanOut&&!(a.functionPath!==It&&a.functionPath!==fa))return await j(r),a.functionPath===It?ce(r,a.args??{}):bn(r,a.args)},_n=$o({applyGlobals:e.applyGlobals,assertAdmin:L,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:re,resolveForwardContext:K,shardDO:i,streamExportRows:(r,a,l,d)=>ln(e,r,a,l,d,i),streamingImport:(r,a)=>Qo(r,e,a,i),syncGlobals:e.syncGlobals}),Be=(r,a)=>{const l=r.searchParams.get(a);return l===null||l===""?void 0:l},xe=r=>{const a=new URL(r.url),l=a.searchParams.get("limit"),d=a.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),E=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:E!==void 0&&Number.isFinite(E)&&E>=0?E:void 0}},ct=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},Rn=Ls({checkWsAdmin:async r=>I(r)||Xt(r,T(),b()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(L(r),ye(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Sn=Zs({assertAdmin:L,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),An=vr({assertAdmin:L,parsePaging:xe,queryParameter:Be,readBodyBytes:_r,requireAdminOption:re,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Tn=Io({options:e,readJsonBody:ne,requireAdminOption:re}),On=zs({readJsonBody:ne,requireAdminOption:re,vectorIntrospector:e.vectorIntrospector}),vn=as({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:re}),kn=Lr({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:re}),In=rs({assertAdmin:L,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:xe,queryParameter:Be,requireAdminOption:re}),Pn=r=>{const a=[],l=i??r?.SHARD;if(l!==void 0&&a.push(Br("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(r??{})){const E=Pa(d,m);E!==void 0&&a.push(E)}for(const d of e.health?.probes??[])a.push(d);return a},Dn=Cr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:I,resolveProbes:Pn}),Nn=r=>{const a=_=>"args"in _?{..._,args:Xe(_.args)}:_,l=e.schedulerInstanceName??"default",d=()=>ye(r,l),m=async(_,A)=>{const B=await d().fetch(new Request(`https://scheduler.internal${_}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${_} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},E=async(_,A)=>await m(_,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),O=_=>{const A=_;if(A==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},P=async()=>(await Gr(async A=>m(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>a(A)),N=async(_,A,B={})=>{const x=O(A),{id:q}=await E("/schedule",{args:br("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:_,...x});return q};return{cancel:async _=>await E("/cancel",{id:_}),get:async _=>{const A=await m(`/get?id=${encodeURIComponent(_)}`,{method:"GET"});return A.record===void 0?null:a(A.record)},list:P,runAfter:async(_,A,B)=>{if(!Number.isFinite(_)||_<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+_,A,B)},runAt:async(_,A,B)=>{if(!Number.isFinite(_))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(_,A,B)}}},Un=async(r,a,l)=>{const{claims:d,headers:m,userId:E}=await k(r,a,s),O=Ee(a,r,_=>l.waitUntil?.(_)),P=_=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(x);const q=await Ae(r,x,Ne(B),_,{...m,"x-lunora-system":"1"},O),H=await q.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:q.status});return Xe(H.result)},N=P(o);return{auth:{getIdentity:()=>Promise.resolve(d),userId:E},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:_=>{const A=P(_);return{runAction:A,runMutation:A,runQuery:A}},runAction:N,runMutation:N,runQuery:N,...u===void 0?{}:{scheduler:Nn(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:Mr(e.storage(a))}}},Cn=async(r,a,l)=>{if(!e.httpRouter)return;const d=await Un(r,a,l);try{return await e.httpRouter.fetch(r,{...a,__lunoraCtx:d},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Bn=async(r,a,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=Tt(r,de);if(d)return d;const m=l.searchParams.get("shard")??o,{headers:E,identity:O}=await k(r,a,s),P=I(r)||await Xt(r,T(),b());await z(O,m,P);const N=Jt(r,E),_=qt(a,e.shardDO);if(_!==void 0){N.set("x-lunora-shard-binding",_);const A=await Oa(i,m);if(A>0){const B=ro(m,Math.floor(Math.random()*A));return g(i,B,new Request(r,{headers:N}),Ot(r))}}return g(i,m,new Request(r,{headers:N}))},xn=async(r,a,l)=>{if(h===void 0)return new Response("Not found",{status:404});if(r.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const d=Tt(r,de);if(d)return d;let m;try{m=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const E=Object.hasOwn(h,m)?h[m]:void 0;if(E===void 0)return new Response("Unknown voice agent",{status:404});const O=l.searchParams.get("threadKey");if(O===null||O.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:N}=await k(r,a,s);if(e.authorizeShard){if(!await ke(e.authorizeShard({identity:N,shardKey:O})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else Q("shard");const _=Jt(r,P);return g(E,O,new Request(r,{headers:_}))},Hn=async(r,a,l)=>{if(e.authorizeFanOut){if(!await ke(e.authorizeFanOut(l,r.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});Q("fan-out")},Se=async(r,a)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Hn(r.fanOut,r.functionPath,a);return}await z(a,r.shardKey??o)}},Ln=(r,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){C();return}if(e.functions[a]?.kind!=="query"||l.includes(et)||l.includes(Ze))return;const d=Ot(r);return d===void 0?void 0:{name:oo(l,d),region:d}},jn=async(r,a,l,d,m)=>{const E=Ln(r,a,d);if(E!==void 0){const O={...m,"x-lunora-replica-read":"1",...R===void 0?{}:{"x-lunora-shard-binding":R}},P=so(r.headers.get("x-lunora-min-seq"));P!==void 0&&(O["x-lunora-min-seq"]=String(P));const N=await g(i,E.name,De(a,l,O),E.region);if(N.status!==421)return N}return g(i,d,De(a,l,m))},Ae=async(r,a,l,d,m,E)=>{const O=Date.now(),{observability:P,sampling:N}=e,_=Je(r),{decision:A,ignoredUpstream:B,trace:x}=jt(r,{...N===void 0?{}:{sampling:N},trustInbound:t(r)});B&&n(r);const q={...m,[_t]:A.keepErrors?"1":"0"};$t(x,q);try{const H=await jn(r,a,l,d,q);ue(P,{..._,...Gt(x),durationMs:Date.now()-O,functionPath:a,ok:H.ok,shardKey:d,...H.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(H.status)}`,status:H.status}}},E,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const ee=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return ee.headers.set("x-lunora-shard-key",d),ee}catch(H){throw ue(P,{..._,...Gt(x),...Ie(a,Date.now()-O,H,{shardKey:d})},E,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),H}},$n=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(r.fanOut||ve(r.functionPath),r.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Mn=async(r,a,l)=>{M(r,"POST","RPC");const d=await Sa(r);Ra(a,d),$n(d);const m=await En(r,d);if(m!==void 0)return m;const{headers:E,identity:O}=await k(r,a,s);Wt(r,O),await Se(d,O);const P=Ye(d,e);{const N=Date.now(),{observability:_}=e,A=Je(r),B=Ee(a,r,l&&(H=>l.waitUntil?.(H)));if(d.fanOut){const H=e.queryCoordinator;if(!H)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const ee=await H.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:E});return ue(_,{durationMs:Date.now()-N,fanOut:{failed:ee.failed,shards:ee.ok+ee.failed,table:d.fanOut.table},functionPath:d.functionPath,...A,ok:!0},B),Response.json(ee,{headers:{"content-type":"application/json"},status:200})}catch(ee){throw ue(_,{...Ie(d.functionPath,Date.now()-N,ee,{fanOut:{table:d.fanOut.table}}),...A},B),ee}}const x=d.shardKey??o,q=()=>Ae(r,d.functionPath,d.args??{},x,E,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:d.functionPath,price:P.price},q,qe(l)):q()}},Kn=async(r,a,l)=>{M(r,"POST","RPC batch");const d=await ne(r),{calls:m}=d;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:E,identity:O}=await k(r,a,s);Wt(r,O);const P=Do(m,o);for(const F of P.values())for(const G of F)if(e.functions?.[G.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${G.functionPath}" cannot be called in a batch; dispatch it individually over ${Ft}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([F,G])=>G.map(te=>Se({args:te.args,functionPath:te.functionPath,shardKey:F},O))));const{observability:N,sampling:_}=e,A=Ee(a,r,l&&(F=>l.waitUntil?.(F))),B=Je(r),{decision:x,ignoredUpstream:q,trace:H}=jt(r,{..._===void 0?{}:{sampling:_},trustInbound:t(r)});q&&n(r);const ee={isTraced:H.sampled,keepErrors:x.keepErrors},er=F=>{const G={...E,"content-type":"application/json",[_t]:x.keepErrors?"1":"0"};return $t({...H,spanId:F},G),G},He=F=>({parentSpanId:F,spanId:ge(8),traceFlags:H.traceFlags,traceId:H.traceId}),Oe=[],Le=[],ht=(F,G,te,le)=>({body:{error:{code:te,message:le}},id:F.id,status:G}),ft=(F,G,te,le,fe)=>{for(const Y of F)ue(N,fe(Y),A,void 0,ee),Oe.push(ht(Y,G,te,le))},tr=(F,G,te,le,fe,Y)=>{for(const be of F){const pe=fe.get(be.id)??Y,me=pe<400;ue(N,{durationMs:le,functionPath:be.functionPath,...B,...He(te),ok:me,shardKey:G,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},A,void 0,ee)}};await Promise.all([...P.entries()].map(async([F,G])=>{const te=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:G}),headers:new Headers(er(te)),method:"POST"}),fe=Date.now();let Y;try{Y=await g(i,F,le)}catch(X){const $e=Date.now()-fe,{body:wt}=ar(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(G,502,wt.code,wt.message,or=>({...Ie(or.functionPath,$e,X,{shardKey:F}),...B,...He(te)}));return}const be=Date.now()-fe,pe=Y.headers.get("x-d1-bookmark");pe&&Le.push(pe);let me;try{me=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;ft(G,Y.status,"SHARD_ERROR",X,$e=>({durationMs:be,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:$e.functionPath,...B,...He(te),ok:!1,shardKey:F}));return}const je=Array.isArray(me.results)?me.results:[],nr=new Map(je.map(X=>[X.id,X.status??Y.status])),rr=new Set(je.map(X=>X.id));tr(G,F,te,be,nr,Y.status),Oe.push(...je);for(const X of G)rr.has(X.id)||Oe.push(ht(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=Le;return Le.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Fn=async(r,a,l,d={},m={})=>{try{const E=l.__lunoraRef;if(typeof E!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(E);const{headers:O,identity:P}=await k(r,a,s,m.context),N={args:d,functionPath:E,shardKey:m.shardKey};await Se(N,P);const _=m.shardKey??o,A=Ee(a,r,m.waitUntil),B=()=>Ae(r,E,d,_,O,A),x=Ye(N,e);return x&&e.x402Charge?await e.x402Charge(r,{functionPath:E,price:x.price},B,qe(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await B()}catch(E){return Rt(E)}},dt=async(r,a,l)=>{const{observability:d}=e,m=Date.now(),E=ge(16),O=ge(8),P=Vt(a),N=en(E,O,!0);try{const _=await l(N);return ue(d,{durationMs:Date.now()-m,functionPath:r,ok:!0,spanId:O,traceId:E},P),_}catch(_){throw ue(d,{...Ie(r,Date.now()-m,_,{}),spanId:O,traceId:E},P),_}finally{Et(d,P)}},ut=async(r,a,l,d)=>{y(a);const m=[],E=A=>A instanceof Error?A:new Error(String(A)),O=e.crons?.[r.cron];if(O)try{await O(r,a,l)}catch(A){m.push(E(A))}const P=await ie(r.cron,a,m,E,d),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(N)try{await To(e,i,T(),r)}catch(A){m.push(E(A))}if(!O&&P===0&&!N){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${r.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[_]=m;if(m.length===1&&_)throw _;if(m.length>1)throw new AggregateError(m,`scheduled("${r.cron}") had ${String(m.length)} failure(s)`)},Gn=$s({assertAdmin:L,dispatchScheduled:ut,queueHandler:e.queueHandler}),Qn=async(r,a)=>{try{const l=r??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await g(i,o,De(ha,{outcome:a},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Wn=async(r,a,l,d)=>{if(!e.authHandler)return;const m=await e.authHandler(r);if(!m)return;const E=e.authBasePath??zt;return ma(l.pathname,E)&&d.waitUntil?.(Qn(a,m.status>=400?"fail":"ok")),m},zn=async({args:r,env:a,functionPath:l,request:d,shardKey:m,waitUntil:E})=>{nn(r,"REST");const O={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:P,identity:N}=await k(d,a,s);await Se(O,N);const _=m??o,A=Ee(a,d,E),B=()=>Ae(d,l,r,_,P,A),x=Ye(O,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},B,qe({waitUntil:E})):B()},Vn=Er({functions:e.functions??{},invoke:zn,readJsonBody:ne,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Te=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;Da(Te);const qn={[ca]:r=>r.method!=="GET"&&r.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[na]:(r,a,l)=>Bn(r,a,l),[Ft]:(r,a,l,d)=>Mn(r,a,d),[ta]:(r,a,l,d)=>Kn(r,a,d),[ra]:(r,a)=>Ce(r,a),[oa]:(r,a)=>_e(r,a),[sa]:async r=>{M(r,"POST","ws-token"),L(r);const a=T();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await lo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...V,..._n,...Rn,...Sn,...An,...Tn,...On,...vn,...kn,...In,...Dn,...Vn,...mo({assertAdmin:L,getAuthAdmin:()=>e.authAdmin,parsePaging:xe,queryParameter:Be,readJsonBody:ne})};let de=At(e.security),lt=!1;const Jn=r=>{lt||(lt=!0,de=At(e.security,r??{}))},Yn=async(r,a)=>{da(a)&&await j(r)},Xn=(r,a)=>{if(!(a.pathname.startsWith(Ue)||e.authHandler!==void 0&&wa(a.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const d=Number(r.headers.get("content-length")??""),m=ea[a.pathname]??tn;if(Number.isFinite(d)&&d>m)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},Zn=async(r,a,l)=>{nt.set(r,l);const d=new URL(r.url);Xn(r,d);const m=await Wn(r,a,d,l);if(m)return m;if(Te){const N=`${r.method} ${d.pathname}`,_=Te[N]??Te[d.pathname];if(_)return _(r,a,l)}const E=Gn[d.pathname];if(E)return E(r,a,l);const O=qn[d.pathname];if(O)return await Yn(r,d.pathname),O(r,a,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Qt))return xn(r,a,d);if(d.pathname.startsWith(Ue))return new Response("Not found",{status:404});const P=await Cn(r,a,l);return P||new Response("Not found",{status:404})};return{async fetch(r,a,l){e.passThroughOnException&&l.passThroughOnException?.(),Jn(a),y(a);const d=jr(r,de);if(d)return d;const m=$r(r,de);if(m)return Fe(m,r,de);try{const E=await Zn(r,a,l);return Fe(E,r,de)}catch(E){return Fe(Rt(E),r,de)}finally{Et(e.observability,Vt(l))}},async queue(r,a,l){await dt(`queue:${ya(r)}`,l,async d=>{await e.queue?.(r,a,l,{traceparent:d})})},async scheduled(r,a,l){await dt(`cron:${r.cron}`,l,async d=>{await ut(r,a,l,d)})},serverQuery:Fn}},Ua=e=>yn(e),Ca=e=>typeof e=="function"?{fetch:e}:e,Ba=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,xa=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},si=(e,t)=>{const n=Ca(e),{email:o,queue:s,scheduled:i}=xa(e),u=p=>{const g={...Ua({...p,httpRouter:n})};return i!==void 0&&!Ba(p)&&(g.scheduled=async(S,T,w)=>{await i(S,T,w)}),s!==void 0&&p.queue===void 0&&(g.queue=async(S,T,w)=>{await s(S,T,w)}),o!==void 0&&(g.email=async(S,T,w)=>{await o(S,T,w)}),g};if(typeof t!="function")return u(t);const h=t;return{fetch:(p,f,g)=>u(h(f)).fetch(p,f,g),queue:(p,f,g)=>u(h(f)).queue?.(p,f,g)??Promise.resolve(),scheduled:(p,f,g)=>u(h(f)).scheduled(p,f,g),serverQuery:(p,f,g,S,T)=>u(h(f)).serverQuery(p,f,g,S,T),...o===void 0?{}:{email:(p,f,g)=>u(h(f)).email?.(p,f,g)??Promise.resolve()}}},Ha=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},ai=(e={})=>(t,n,o)=>yn(Ha(e,n)).fetch(t,n,o??ir),ii=e=>e;export{It as GET_AUTH_AUDIT_LOG_OP,ir as NOOP_EXECUTION_CONTEXT,ui as composeIdentityResolvers,Ua as composeWorker,ai as createLunoraHandler,yn as createWorker,ii as defineRpcEnvelope,Oa as probeRelayCount,Ha as resolveLunoraOptions,li as routeIdentityResolvers,si as withFrameworkWorker};
@@ -1 +1 @@
1
- import{e as c,a as u}from"./identity-header-C4Z5pldl.mjs";import{d as f}from"./wire-codec-BLvSm5Mn.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
1
+ import{e as c,a as u}from"./identity-header-BtkOCFcS.mjs";import{d as f}from"./wire-codec-BLvSm5Mn.mjs";import{LunoraError as s}from"./LunoraError-DksAgIpa.mjs";const l="/_lunora/rpc",h=e=>{const a={"content-type":"application/json"};return e.userId!==void 0&&e.userId.length>0&&(a["x-lunora-userid"]=c(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=u(e.identity)),a},d=async(e,a,o)=>{const t=await(e.fetch??globalThis.fetch)(new Request(`${e.origin}${l}`,{body:JSON.stringify(a),headers:h(e),method:"POST"}));if(!t.ok)throw new s(`cross-shard relation ${o} failed: worker returned ${String(t.status)}`);const r=await t.json();if(typeof r.failed=="number"&&r.failed>0){const i=(typeof r.ok=="number"?r.ok:0)+r.failed;throw new s(`cross-shard relation ${o} failed on ${String(r.failed)} of ${String(i)} shard(s) — refusing to return a partial result`)}return f(r.data)},_=e=>({crossShardCounter:async(n,t)=>{const r=await d(e,{args:{table:n,where:t},fanOut:{merge:{kind:"sum"},table:n},functionPath:"__lunora_relation__:count"},"count");return typeof r=="number"?r:0},crossShardReader:async(n,t)=>{const r=await d(e,{args:{...t,table:n},fanOut:{merge:{kind:"concat"},table:n},functionPath:"__lunora_relation__:read"},"read");return{continueCursor:null,isDone:!0,page:Array.isArray(r)?r:[]}}});export{_ as createCrossShardRelationCapabilities};
@@ -1 +1 @@
1
- import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-C4Z5pldl.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-BLvSm5Mn.mjs";import{applyJurisdiction as g,resolveShard as L}from"./applyJurisdiction-C0ddU7Tg.mjs";const A=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},E=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},x=(e,t={})=>{const l=g(e,t.jurisdiction),m=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const i=A(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const a={"content-type":"application/json"};m&&(a[p]=w,a["x-lunora-system"]="1"),t.as&&(a["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(a["x-lunora-identity"]=I(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(a["x-lunora-mutation-id"]=o.mutationId);const s=await L(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:N(y??{}),functionPath:i}),headers:a,method:"POST"})),u=s.statusText?` ${s.statusText}`:"";let d;try{d=await s.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(s.status)}${u})`)}if("error"in d)throw E(d.error);if(!s.ok)throw new n("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(s.status)}${u})`);return f(d.result)},forShard:r=>c({shardKey:r})}};export{x as createShardClient};
1
+ import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-BtkOCFcS.mjs";import{O as w,a as p}from"./origin-paywall-B6eOO67m.mjs";import{e as N,d as f}from"./wire-codec-BLvSm5Mn.mjs";import{applyJurisdiction as g,resolveShard as L}from"./applyJurisdiction-C0ddU7Tg.mjs";const A=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},E=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),t},x=(e,t={})=>{const l=g(e,t.jurisdiction),m=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,y,o)=>{const i=A(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const a={"content-type":"application/json"};m&&(a[p]=w,a["x-lunora-system"]="1"),t.as&&(a["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(a["x-lunora-identity"]=I(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(a["x-lunora-mutation-id"]=o.mutationId);const s=await L(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:N(y??{}),functionPath:i}),headers:a,method:"POST"})),u=s.statusText?` ${s.statusText}`:"";let d;try{d=await s.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(s.status)}${u})`)}if("error"in d)throw E(d.error);if(!s.ok)throw new n("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(s.status)}${u})`);return f(d.result)},forShard:r=>c({shardKey:r})}};export{x as createShardClient};
@@ -0,0 +1 @@
1
+ import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const E=new Set(["0","disabled","false","no","off"]),y=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=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 o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,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 a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:[...new Set([...u,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},x=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return x.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},w=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),h=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} 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:o}},{headers:{"content-type":"application/json"},status:403}),X=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin state-changing request",r,s)},F=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&w(r,s,o)))return h("cross-origin websocket upgrade",r,s)},P=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",P.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},T=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=T(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,X as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
@@ -0,0 +1 @@
1
+ import{e as a,a as s,f}from"./observability-DgurIZIR.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
@@ -0,0 +1 @@
1
+ import{t as o,f as s}from"./base64-Bl1_r2k1.mjs";const d=new TextDecoder,c=new TextEncoder,n="=",a=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},E=e=>o(c.encode(JSON.stringify(e))),i=e=>{if(e)try{const t=e[0]==="{"?e:d.decode(s(e)),r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r))return r}catch{}},u=e=>!e.startsWith(n)&&a(e)?e:`${n}${o(c.encode(e))}`,x="x-lunora-expect-subject",y=e=>{const t=i(e)?.subject;return t===null||typeof t=="string"?{subject:t}:void 0};export{x as E,E as a,y as d,u as e};
@@ -0,0 +1 @@
1
+ const u="x-lunora-sample-errors";const c=r=>{const t=Number.parseInt(r.slice(-8),16);return Number.isFinite(t)?t/4294967296:0},n=(r,t=1)=>{const e=Number.isFinite(t)?t:1;return e>=1?!0:e<=0?!1:c(r)<e},E=(r,t)=>({isTraced:n(t,r?.headRate??1),keepErrors:r?.alwaysSampleErrors??!0}),i=(r,t)=>r.isTraced||r.keepErrors&&t,A=(r,t,e,o,a)=>{if(!r?.onRpc)return;const s=a??(o!==void 0&&t.traceId!==void 0?E(o,t.traceId):void 0);if(!(s!==void 0&&!i(s,!t.ok)))try{r.onRpc(t,e)}catch{}},T=(r,t,e)=>{if(r?.onLog)try{r.onLog(t,e)}catch{}},R=(r,t)=>{if(r?.flush)try{r.flush(t)}catch{}};export{u as S,A as a,T as e,R as f,E as r};
@@ -0,0 +1 @@
1
+ const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const m=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),m(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=m(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),v=n.get(g);v===void 0?(n.set(g,c),o[c]=i):o[v]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],C={client:3,consumer:5,internal:1,producer:4,server:2},L=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{L,C as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.147",
3
+ "version": "1.0.0-alpha.149",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/bindings": "1.0.0-alpha.74",
50
- "@lunora/errors": "1.0.0-alpha.41",
51
- "@lunora/observability": "1.0.0-alpha.96",
49
+ "@lunora/bindings": "1.0.0-alpha.76",
50
+ "@lunora/errors": "1.0.0-alpha.43",
51
+ "@lunora/observability": "1.0.0-alpha.98",
52
52
  "@lunora/platform": "1.0.0-alpha.39"
53
53
  },
54
54
  "peerDependencies": {
@@ -1,6 +0,0 @@
1
- import{isLunoraError as nr,toErrorBody as rr}from"@lunora/errors";import{e as Yt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as or}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as sr,f as ar}from"./base64-Bl1_r2k1.mjs";import{e as ir,a as cr}from"./identity-header-C4Z5pldl.mjs";import{O as wt,a as gt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as Xt,p as dr,m as ur,d as lr,a as hr,r as fr}from"./otlp-resource-JKBCWf6c.mjs";import{r as pr,f as yt,a as de,S as bt}from"./observability-DQGhbG0p.mjs";import{e as De,d as Ye,a as mr}from"./wire-codec-BLvSm5Mn.mjs";import{d as re,e as se,M as Zt,b as wr,f as gr,g as en,t as yr,h as tn}from"./rest-routes-CpbO5QEx.mjs";import{LunoraError as c,toErrorResponse as _t}from"./LunoraError-DksAgIpa.mjs";import{a as M,m as we}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as nt,BACKUP_KEY_PREFIX as rt,isBackupManifestKey as br,backupObjectKeyOfManifest as nn,backupObjectKey as _r,backupManifestKey as Er}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Rr,buildStorageAdminRoutes as Sr,STORAGE_UPLOAD_MAX_BODY_BYTES as Ar,STORAGE_PATH as Tr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-KGQR1LvR.mjs";import{b as Or,e as vr,f as Et,g as kr,h as Ir}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Pr,durableObjectProbe as Dr,d1Probe as Nr,presenceProbe as Me}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Ur}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as ai,routeIdentityResolvers as ii}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Cr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{resolveShard as ye,applyJurisdiction as Rt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as St,handleCorsPreflight as Br,enforceOrigin as xr,decorateResponse as Ke,enforceWebSocketOrigin as At}from"./decorateResponse-Y2sCM0w1.mjs";const Hr=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},rn="__lunoraBranch",Lr=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,rn),$r=`may not contain the reserved workflow branch-marker key ("${rn}")`,jr=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},ot=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const i=s<e.length?e.charCodeAt(s):0,u=s<t.length?t.charCodeAt(s):0;r|=i^u}return r===0},Mr=/already[\s_-]?exists/iu,Kr=e=>Mr.test(e instanceof Error?e.message:String(e)),Fr=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;Yt(e,r);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},st=new TextEncoder,Gr=Array.from({length:32},(e,t)=>t);new RegExp(`[${Gr.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Qr=64,Wr=new Map,on=async e=>Fr(Wr,e,async()=>crypto.subtle.importKey("raw",st.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Qr),sn=async(e,t)=>{const n=await on(e),r=await crypto.subtle.sign("HMAC",n,st.encode(t));return sr(new Uint8Array(r))},zr=async(e,t,n)=>{const r=await on(e);return crypto.subtle.verify("HMAC",r,n,st.encode(t))},Vr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Vr);const qr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Jr=-100,Yr=15,Xr=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&qr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Yr?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Jr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Tt=e=>{const t=e.cf;return t===void 0?void 0:Xr(t)},Xe="::relay::",Zr=(e,t)=>`${e}${Xe}${String(t)}`,Ze="::replica::",eo=(e,t)=>`${e}${Ze}${t}`,to=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},no=new Set(["1","enabled","on","true","yes"]),ro=new Set(["0","disabled","false","no","off"]),oo=(e,t)=>{const n=(e??"").trim().toLowerCase();return no.has(n)?!0:ro.has(n)?!1:t},an="v1",so=6e4,ao=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??so),r=`${an}.${String(n)}`,s=await sn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},io=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,i,u]=r;if(s!==an||u.length===0)return!1;const f=Number(i);if(!Number.isFinite(f)||f<=n)return!1;let p;try{p=ar(u)}catch{return!1}return zr(e,`${s}.${i}`,p)},I="/_lunora/admin/auth",co={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},U=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},le=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},cn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},oe=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Fe=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Ot=e=>{const t=cn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},vt=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(i=>typeof i=="string")&&(n[r]=s);return n},uo={[`${I}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${I}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${I}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${I}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${I}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${I}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${I}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listMembers"},[`${I}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${I}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${I}/sign-up-invitations/create`]:{build:({body:e})=>({email:U(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:oe(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${I}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:U(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${I}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${I}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listTeams"},[`${I}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:le(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${I}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:le(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${I}/users/create`]:{build:({body:e})=>({data:Fe(e,"data"),email:U(e,"email"),name:U(e,"name"),password:oe(e,"password"),role:cn(e.role)}),http:"POST",method:"createUser"},[`${I}/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"},[`${I}/users/role`]:{build:({body:e})=>({role:Ot(e),userId:U(e,"userId")}),http:"POST",method:"setRole"},[`${I}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:oe(e,"reason"),userId:U(e,"userId")}),http:"POST",method:"banUser"},[`${I}/users/unban`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"unbanUser"},[`${I}/users/password`]:{build:({body:e})=>({newPassword:U(e,"newPassword"),userId:U(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${I}/users/remove`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${I}/users/impersonate`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"impersonateUser"},[`${I}/sessions/revoke`]:{build:({body:e})=>({sessionId:U(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${I}/sessions/revoke-all`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${I}/accounts/unlink`]:{build:({body:e})=>({accountId:U(e,"accountId"),userId:U(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${I}/two-factor/disable`]:{build:({body:e})=>({userId:U(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${I}/passkeys/delete`]:{build:({body:e})=>({passkeyId:U(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${I}/organizations/members/remove`]:{build:({body:e})=>({memberId:U(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${I}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:U(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${I}/organizations/create`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Fe(e,"metadata"),name:U(e,"name"),ownerId:oe(e,"ownerId"),slug:oe(e,"slug")}),http:"POST",method:"createOrganization"},[`${I}/organizations/update`]:{build:({body:e})=>({logo:oe(e,"logo"),metadata:Fe(e,"metadata"),name:oe(e,"name"),organizationId:U(e,"organizationId"),slug:oe(e,"slug")}),http:"POST",method:"updateOrganization"},[`${I}/organizations/remove`]:{build:({body:e})=>({organizationId:U(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${I}/organizations/members/add`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),role:oe(e,"role"),userId:U(e,"userId")}),http:"POST",method:"addMember"},[`${I}/organizations/members/invite`]:{build:({body:e})=>({email:U(e,"email"),inviterId:oe(e,"inviterId"),organizationId:U(e,"organizationId"),role:oe(e,"role")}),http:"POST",method:"inviteMember"},[`${I}/organizations/members/role`]:{build:({body:e})=>({memberId:U(e,"memberId"),role:Ot(e)}),http:"POST",method:"updateMemberRole"},[`${I}/organizations/teams/create`]:{build:({body:e})=>({name:U(e,"name"),organizationId:U(e,"organizationId")}),http:"POST",method:"createTeam"},[`${I}/organizations/teams/update`]:{build:({body:e})=>({name:U(e,"name"),teamId:U(e,"teamId")}),http:"POST",method:"updateTeam"},[`${I}/organizations/teams/remove`]:{build:({body:e})=>({teamId:U(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${I}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:U(e,"teamId"),userId:U(e,"userId")}),http:"POST",method:"addTeamMember"},[`${I}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:U(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${I}/organizations/roles/create`]:{build:({body:e})=>({organizationId:U(e,"organizationId"),permission:vt(e),role:U(e,"role")}),http:"POST",method:"createOrgRole"},[`${I}/organizations/roles/update`]:{build:({body:e})=>({permission:vt(e),roleId:U(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${I}/organizations/roles/remove`]:{build:({body:e})=>({roleId:U(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},lo=e=>{const t=async s=>{try{return await s()}catch(i){if(i instanceof c)throw i;const u=i,f=typeof u.code=="string"?u.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",i),new c("auth admin operation failed",{code:f,status:co[f]??500})}},n=async(s,i)=>{if(e.assertAdmin(s),s.method!==i.http)throw new c(`Auth admin endpoint requires ${i.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const u=e.getAuthAdmin();if(u===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const f=u[i.method];if(f===void 0)throw new c(`auth admin does not support \`${i.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const p=new URL(s.url),h={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:T=>e.queryParameter(p,T)},y=i.build(h),S=await t(()=>f(y));return Response.json(i.returns==="void"?{ok:!0}:S,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,i]of Object.entries(uo))r[s]=u=>n(u,i);return r},kt="__lunora_admin__:getAuthAuditLog",It=e=>typeof e=="string"&&e!==""?e:void 0,Pt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,ho=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const i=It(r.actorId),u=It(r.event),f=Pt(r.sinceSeq),p=Pt(r.limit),h={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...f===void 0?{}:{sinceSeq:f},...p===void 0?{}:{limit:p}};let y;try{y=await s.read(h)}catch(T){throw T instanceof c?T:(console.error("[lunora] auth audit read failed:",T),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const S={entries:y};return Response.json({result:De(S)},{headers:{"content-type":"application/json"},status:200})},fo=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},po=async(e,t,n,r,s,i,u)=>{if(n!==void 0&&r.length===0)return;const f=await e.orchestrateExport(i,{args:{tables:r},defaultShardKey:u,headers:t,tables:r}),p=f.shards.filter(h=>h.error);if(p.length>0){const h=p.map(y=>`${y.shardKey}: ${y.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(p.length)} of ${String(f.shards.length)} shard(s) — ${h}`,{code:"EXPORT_SHARD_FAILED",status:502})}for(const h of f.shards)for(const y of h.rows??[])s(y)},dn=async(e,t,n,r,s,i)=>{const u=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:f,shardLocalTables:p}=fo(e,u);await po(t,n,u,p,s,i,e.defaultShardKey??"__root__");const h=e.exportGlobals;if((r===void 0||f.length>0)&&h)for await(const S of h({tables:f}))s(S)},mo=new TextEncoder,wo=1e3,un=10,go=200,Dt=8,ln="lunoraBackupCron",Nt=24*1048576,Ut=e=>{const t=e.slice(0,un).map(r=>nn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},yo=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},at=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let i;for(let u=0;u<wo;u+=1){const f=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const p of f.objects)br(p.key)&&p.customMetadata?.[ln]===r&&s.push(p.key);if(!f.truncated||f.cursor===void 0)break;i=f.cursor}return{eligible:s.length,stale:s.toSorted((u,f)=>f.localeCompare(u)).slice(n)}},bo=async(e,t,n,r,s)=>{const{stale:i}=await at(e,t,n,r),u=new Set(s),f=i.filter(w=>u.has(w)),p=f.slice(0,go),h=i.length-p.length,y=s.length-f.length;if(p.length===0)return{deleted:[],failed:[],ignored:y,remaining:h};const S=[],T=[];for(let w=0;w<p.length;w+=Dt){const b=await Promise.allSettled(p.slice(w,w+Dt).map(async R=>(await e.delete(nn(R)),await e.delete(R),R)));for(const[R,g]of b.entries())g.status==="fulfilled"?S.push(g.value):T.push(p[w+R])}return S.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(S.length)}: ${Ut(S)}`),T.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(T.length)}: ${Ut(T)}`),{deleted:S,failed:T,ignored:y,remaining:h}},_o=async e=>{const t=e.backupStore;if(!t)throw new c("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const n=nt(e.backupPrefix??rt),r=e.backupCron,{eligible:s,stale:i}=r===void 0?{eligible:0,stale:[]}:await at(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Eo=async(e,t,n,r)=>{const s=e.backupStore,i=e.queryCoordinator;if(!s)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!i)throw new c("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!n||n.length===0)throw new c("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const u={authorization:`Bearer ${n}`,"content-type":"application/json"},f=e.backupTables;let p=0,h=0,y=[];await dn(e,i,u,f,D=>{const L=mo.encode(`${JSON.stringify(D)}
2
- `);if(p+=1,h+=L.byteLength,h>Nt)throw new c(`scheduled backup reached ${String(h)} bytes of NDJSON, past the ${String(Nt)}-byte limit for a snapshot assembled inside a Worker — nothing was written. Narrow it with \`backupTables\`, or take this snapshot off-platform with \`lunora backup create --bucket\`.`,{code:"BACKUP_TOO_LARGE",status:507});y.push(L)},t);const T=nt(e.backupPrefix??rt),w=new Date(r.scheduledTime).toISOString(),b=_r(T,w),R=yo(y,h);y=[];const g=Rr(await crypto.subtle.digest("SHA-256",R));await s.put(b,R,{httpMetadata:{contentType:"application/x-ndjson"},sha256:g});const O={bytes:h,createdAt:w,cron:r.cron,file:b,id:w,rows:p,scheduledTime:r.scheduledTime,sha256:g,...f?{tables:f.join(",")}:{}};await s.put(Er(b),`${JSON.stringify(O,void 0,2)}
3
- `,{customMetadata:{[ln]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await at(s,T,e.backupRetain,r.cron);if(D.length>0){const L=D.slice(0,un),P=D.length-L.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${L.join(", ")}${P>0?` (+${String(P)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Ro=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,s=e.backupRetain;if(r===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return bo(n,nt(e.backupPrefix??rt),s,r,t)},So="/_lunora/admin/backup/retention",Ao="/_lunora/admin/backup/prune",To=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(f,p)=>{r(f,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${p} requires a \`backupStore\` on the worker`})},i=async f=>(M(f,"GET","Backup-retention"),s(f,"retention preview"),Response.json(await _o(t),{headers:{"cache-control":"no-store"}})),u=async f=>{M(f,"POST","Backup-prune"),s(f,"prune");const{confirm:p}=await n(f);if(!Array.isArray(p)||p.some(h=>typeof h!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Ro(t,p),{headers:{"cache-control":"no-store"}})};return{[Ao]:u,[So]:i}},Ct=500,Oo=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},vo=(e,t)=>{if(e.length>Ct)throw new c(`RPC batch exceeds the ${String(Ct)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,i]of e.entries()){const{entry:u,shardKey:f}=Oo(i,s,t);if(r.has(u.id))throw new c(`batch call id ${String(u.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(u.id);const p=n.get(f)??[];p.push(u),n.set(f,p)}return n},ko="/_lunora/admin/export",Io="/_lunora/admin/import",Po="/_lunora/admin/sync",Do="/_lunora/admin/connector/sync",No="/_lunora/admin/apply",Uo="/_lunora/admin/export-tap/run",Co=new TextEncoder,Bo=async e=>{const n=await se(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},Ge=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,xo=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:i,queryCoordinator:u,assertAdmin:f,requireAdminOption:p,resolveForwardContext:h,shardDO:y,streamExportRows:S,streamingImport:T,syncGlobals:w}=e,b=async(P,K)=>{const $=we(P,["POST"]);if($)return $;const Z=p(P,u,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),C=await Bo(P),{headers:W}=await h(P,K),J=new ReadableStream({async pull(z){const ee=V=>{z.enqueue(Co.encode(`${JSON.stringify(V)}
4
- `))};try{await S(Z,W,C.tables,ee),z.close()}catch(V){z.error(V)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},R=async(P,K)=>{const $=we(P,["POST"]);if($)return $;const Z=p(P,u,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),C=await re(P),W=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},J=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},z=typeof C.limit=="number"?C.limit:void 0,ee=typeof C.globalCursor=="number"?C.globalCursor:0,V=Ge(C.tables),{headers:F}=await h(P,K),j=V??i(),he=await Z.orchestrateCdcSync(y,{cursors:W,defaultShardKey:n,epochs:J,headers:F,limit:z,tables:j}),ae=w?await w({limit:z,sinceSeq:ee}):void 0;return Response.json({global:ae,shards:he.shards},{status:200})},g=async(P,K)=>{const $=we(P,["POST"]);if($)return $;const Z=p(P,u,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),C=await re(P),W=vr(C.cursor),J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,z=Ge(C.tables),{headers:ee}=await h(P,K),V=z??i(),F=await Z.orchestrateCdcSync(y,{cursors:W.s,defaultShardKey:n,headers:ee,limit:J,tables:V}),j=[],he={...W.s};let ae=!1;for(const ie of F.shards)ae=Et(j,ie.changes??[],Ir(J))||ae,he[ie.shardKey]=ie.cursor;let be=W.g;if(w){const ie=await w({limit:J,sinceSeq:W.g});ae=Et(j,ie.changes,J)||ae,be=ie.cursor}const Ue=kr({g:be,s:he,v:1}),Ce={changes:j,hasMore:ae,nextCursor:Ue};return Response.json(Ce,{status:200})},O=async(P,K)=>{const $=we(P,["POST"]);if($)return $;const Z=p(P,u,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),C=await re(P),J=(Array.isArray(C.batches)?C.batches:[]).map(j=>j).filter(j=>j!==null&&typeof j=="object"&&typeof j.shardKey=="string"&&Array.isArray(j.changes)),z=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:ee}=await h(P,K),V=await Z.orchestrateApplyCdc(y,{batches:J,headers:ee}),F=z.length>0&&t?await t({changes:z}):0;return Response.json({applied:V.applied+F,failed:V.failed,ok:V.ok},{status:200})},D=async(P,K)=>{const $=we(P,["POST"]);if($)return $;f(P);const{headers:Z}=await h(P,K),C=await T(P,Z);return Response.json(C,{headers:{"content-type":"application/json"},status:C.failed.length>0?207:200})},L=async(P,K)=>{const $=we(P,["POST"]);if($)return $;const Z=p(P,u,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(s===void 0||Object.keys(s).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await re(P),W=typeof C.sink=="string"?C.sink:void 0,J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,z=Ge(C.tables);if(W===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const ee=s[W];if(ee===void 0)throw new c(`Export-tap sink "${W}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:V}=await h(P,K),F=z??i(),j=await Or({coordinator:Z,cursorStore:r,defaultShardKey:n,headers:V,limit:J,shardDO:y,sink:ee,tables:F});return Response.json(j,{headers:{"content-type":"application/json"},status:200})};return{[No]:O,[Do]:g,[ko]:b,[Uo]:L,[Io]:D,[Po]:R}},Ho=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},Lo=(e,t,n,r,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const i=e[n.mode.field];return i==null?{error:{code:"BAD_ROW",line:s,message:`row missing shard field "${n.mode.field}" for table "${t}"`,table:t},ok:!1}:{ok:!0,shardKey:typeof i=="string"?i:JSON.stringify(i)}}return{ok:!0,shardKey:r}},$o=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],i=new Map;let u=0,f=0;const p=e.body.getReader(),h=new TextDecoder;let y="",S=0;const T=w=>{f+=1;const b=w.trim();if(b.length===0)return;u+=1;const R=Ho(b,f);if(!R.ok){r.push(R.error);return}const{doc:g,table:O}=R,D=t.resolveTableSharding?.(O);if(D?.mode.kind==="global"){s.push({doc:g,line:f,table:O});return}const L=Lo(g,O,D,n,f);if(!L.ok){r.push(L.error);return}const P=i.get(L.shardKey);P?P.rows.push({doc:g,table:O}):i.set(L.shardKey,{rows:[{doc:g,table:O}],shardKey:L.shardKey,startLine:f})};for(;;){const{done:w,value:b}=await p.read();if(w)break;if(b&&(S+=b.byteLength,S>Zt))throw await p.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});y+=h.decode(b,{stream:!0});let R=y.indexOf(`
5
- `);for(;R!==-1;){const g=y.slice(0,R);y=y.slice(R+1),T(g),R=y.indexOf(`
6
- `)}}return y.length>0&&T(y),{errors:r,globalRows:s,perShard:i,received:u}},jo=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),Bt=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts},Mo=async(e,t,n,r)=>{const s=t.defaultShardKey??"__root__",{errors:i,globalRows:u,perShard:f,received:p}=await $o(e,t,s),h={conflicts:0,errors:i,failed:[],inserted:{}},y=[];if(t.resolveTableSharding===void 0&&f.size>0&&y.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"),f.size>0){const S=t.queryCoordinator;if(!S)throw new c("Import endpoint requires a `queryCoordinator` on the worker",{code:"BAD_REQUEST",status:400});const T=await S.orchestrateImport(r,{batches:[...f.values()],headers:n});Bt(h,T),h.failed.push(...jo(T.shards))}if(u.length>0)if(t.importGlobals){const S=u[0]?.line??1,T=await t.importGlobals({rows:u,startLine:S});Bt(h,T)}else for(const S of u)h.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:S.line,message:`row targets global table "${S.table}" but no \`importGlobals\` is configured`,table:S.table});return{conflicts:h.conflicts,errors:h.errors,failed:h.failed,inserted:h.inserted,received:p,...y.length>0?{warnings:y}:{}}},Qe=e=>typeof e=="object"&&e!==null?e:{},We=e=>typeof e.kind=="string"?e.kind:"unknown",Ko=(e,t)=>{let n=Qe(t),r=!1;We(n)==="optional"&&(r=!0,n=Qe(n._meta?.inner));const s=We(n),i=n._meta??{},u={kind:s,name:e,optional:r};if(s==="id"&&typeof i.tableName=="string"&&(u.table=i.tableName),s==="array"){const f=We(Qe(i.inner));f!=="unknown"&&(u.element=f)}return u},Fo=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>Ko(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Go="/_lunora/admin/functions",Qo="/_lunora/admin/cron-jobs",Wo="/_lunora/admin/openapi",zo="/_lunora/admin/openrpc",Vo="/_lunora/admin/global/tables",qo="/_lunora/admin/global/table",Jo="/_lunora/admin/global/facet",xt=e=>{if(e===void 0||e==="")return;let t;try{t=Ye(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:s,value:i}=r;return[{column:s,value:i}]});return n.length===0?void 0:n},Yo=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:{}}),Xo=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"}),Zo=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:s,requireAdminOption:i}=e,u=w=>{M(w,"GET","Functions");const b=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.visibility==="internal"||O.kind==="stream"?[]:[{args:Fo(O.args),kind:O.kind,path:g}]).toSorted((g,O)=>g.path.localeCompare(O.path));return Response.json({functions:R},{headers:{"content-type":"application/json"},status:200})},f=w=>{M(w,"GET","Cron-jobs");const b=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),R=Object.entries(b).flatMap(([g,O])=>O.map(D=>({args:D.args,cron:g,functionPath:D.functionPath,name:D.name,shardKey:D.shardKey,workflow:D.workflow}))).toSorted((g,O)=>g.name.localeCompare(O.name));return Response.json({jobs:R},{headers:{"content-type":"application/json"},status:200})},p=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Yo,{headers:{"content-type":"application/json"},status:200})),h=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Xo,{headers:{"content-type":"application/json"},status:200})),y=async w=>{M(w,"GET","Global-tables");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await b.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async w=>{M(w,"GET","Global-table");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=s(R,"table");if(g===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const O=await b.readTablePage({...r(w),filters:xt(s(R,"filters")),table:g});return Response.json(O,{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-facet");const b=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),R=new URL(w.url),g=s(R,"table"),O=s(R,"column");if(g===void 0||O===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const D=s(R,"limit"),L=D===void 0?void 0:Number(D),P=await b.facetColumn({column:O,filters:xt(s(R,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:g});return Response.json(P,{headers:{"content-type":"application/json"},status:200})};return{[Qo]:f,[Go]:u,[Jo]:T,[qo]:S,[Vo]:y,[Wo]:p,[zo]:h}},es="/_lunora/admin/kv/namespaces",ts="/_lunora/admin/kv/keys",hn="/_lunora/admin/kv/value",fn=32*1048576,Ht=60,ns=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=b=>n(b,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=b=>Response.json(b,{headers:{"content-type":"application/json"},status:200}),i=(b,R)=>{const g=new URL(b.url),O=g.searchParams.get("namespace")??"",D=g.searchParams.get("key")??"";if(O==="")throw new c(`KV-value ${R} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(D==="")throw new c(`KV-value ${R} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:D,namespace:O}},u=async(b,R)=>{if(!(await b.listNamespaces()).some(O=>O.binding===R))throw new c(`Unknown KV namespace binding \`${R}\``,{code:"NOT_FOUND",status:404})},f=async b=>(M(b,"GET","KV-namespaces"),s({namespaces:await r(b).listNamespaces()})),p=async b=>{M(b,"GET","KV-keys");const R=r(b),g=new URL(b.url),O=g.searchParams.get("namespace")??"";if(O==="")throw new c("KV-keys request requires a `namespace` query parameter",{code:"BAD_REQUEST",status:400});const D=g.searchParams.get("prefix")??void 0,L=g.searchParams.get("cursor")??void 0,P=g.searchParams.get("limit"),K=P===null?void 0:Number.parseInt(P,10);if(K!==void 0&&(!Number.isInteger(K)||K<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const $=K===void 0?void 0:Math.min(K,1e3);return await u(R,O),s(await R.listKeys({cursor:L,limit:$,namespace:O,prefix:D}))},T={DELETE:async b=>{const R=r(b),g=i(b,"DELETE");return await u(R,g.namespace),await R.deleteKey(g),s({deleted:!0})},GET:async b=>{const R=r(b),g=i(b,"GET");return await u(R,g.namespace),s(await R.getValue(g))},PUT:async b=>{const R=r(b),g=await t(b,fn);if(typeof g.namespace!="string"||g.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof g.key!="string"||g.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof g.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(g.expirationTtl!==void 0&&(typeof g.expirationTtl!="number"||!Number.isInteger(g.expirationTtl)||g.expirationTtl<Ht))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const O=Math.floor(Date.now()/1e3)+Ht;if(g.expiration!==void 0&&(typeof g.expiration!="number"||!Number.isInteger(g.expiration)||g.expiration<O))throw new c("KV-value PUT `expiration` must be a Unix-seconds timestamp at least 60 seconds in the future",{code:"BAD_REQUEST",status:400});return await u(R,g.namespace),await R.putValue({expiration:g.expiration,expirationTtl:g.expirationTtl,key:g.key,metadata:g.metadata,namespace:g.namespace,value:g.value}),s({ok:!0})}},w=b=>{const R=T[b.method];if(!R)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return R(b)};return{[es]:f,[ts]:p,[hn]:w}},rs="/_lunora/migrate",os="/_lunora/admin/pitr",ss="/_lunora/admin/rank",as="/_lunora/admin/rankpage",is="/_lunora/admin/shard-traffic",cs=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),ds=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),us=async e=>{const n=await se(e,"Migration")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Migration request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.functionPath!="string"||!cs.has(n.functionPath))throw new c("Migration request `functionPath` must be a migration admin op",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,table:n.table}},ls=async e=>{const n=await se(e,"Rank")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Rank request is missing `table`",{code:"BAD_REQUEST",status:400});if(typeof n.index!="string"||n.index.length===0)throw new c("Rank request is missing `index`",{code:"BAD_REQUEST",status:400});if(typeof n.partitionKey!="string")throw new c("Rank request `partitionKey` must be a string",{code:"BAD_REQUEST",status:400});if(typeof n.rowId!="string"||n.rowId.length===0)throw new c("Rank request is missing `rowId`",{code:"BAD_REQUEST",status:400});if(!Array.isArray(n.sortValues))throw new c("Rank request `sortValues` must be an array",{code:"BAD_REQUEST",status:400});return{index:n.index,partitionKey:n.partitionKey,rowId:n.rowId,sortValues:n.sortValues,table:n.table}},hs=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}},fs=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})},ps=async e=>{const n=await se(e,"Rank page")??{};fs(n);const r=hs(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},ms=async e=>{const n=await se(e,"Shard-traffic")??{};if(typeof n.table!="string"||n.table.length===0)throw new c("Shard-traffic request is missing `table`",{code:"BAD_REQUEST",status:400});return{table:n.table}},ws=async e=>{const n=await re(e);if(typeof n.functionPath!="string"||!ds.has(n.functionPath))throw new c("PITR request `functionPath` must be a PITR admin op",{code:"BAD_REQUEST",status:400});if(n.shardKey!==void 0&&typeof n.shardKey!="string")throw new c("PITR `shardKey` must be a string",{code:"BAD_REQUEST",status:400});return{args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}},gs=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:s,resolveForwardContext:i,shardDO:u}=e,f=(w,b)=>{if(w.method!=="POST")throw new c(`${b} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))throw new c("Admin auth required",{code:"FORBIDDEN",status:403});if(!s)throw new c(`${b} endpoint requires a \`queryCoordinator\` on the worker`,{code:"BAD_REQUEST",status:400});return s},p=async(w,b)=>{const R=f(w,"Migration"),g=await us(w),{headers:O}=await i(w,b),D=await R.orchestrateMigration(u,{args:g.args,defaultShardKey:t,functionPath:g.functionPath,headers:O,table:g.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},h=async(w,b)=>{const R=f(w,"Rank"),g=await ls(w),{headers:O}=await i(w,b),D=await R.orchestrateRank(u,{headers:O,index:g.index,partitionKey:g.partitionKey,rowId:g.rowId,sortValues:g.sortValues,table:g.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},y=async(w,b)=>{const R=f(w,"Rank page"),g=await ps(w),{headers:O}=await i(w,b),D=await R.orchestrateRankPage(u,{...g,headers:O});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},S=async(w,b)=>{const R=f(w,"Shard-traffic"),g=await ms(w),{headers:O}=await i(w,b),D=await R.orchestrateShardTraffic(u,{headers:O,table:g.table});return Response.json(D,{headers:{"content-type":"application/json"},status:200})},T=async(w,b)=>{if(M(w,"POST","PITR"),!r(w))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const R=await ws(w),{headers:g}=await i(w,b),O=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:R.args,functionPath:R.functionPath}),headers:g,method:"POST"});return n(u,R.shardKey??t,O)};return{[rs]:p,[os]:T,[ss]:h,[as]:y,[is]:S}},ys=1,bs=0,_s=32,Es=512,Rs=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Ss=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>Es)return;const n=t.split(",");if(!(n.length>_s)){for(const r of n)if(!Rs.test(r.trim()))return;return t}},As=e=>{const t=dr(e.headers.get("traceparent"));if(t===void 0)return;const n=Ss(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Lt=(e,t={})=>{const n=As(e),r=t.trustInbound===!0?n:void 0,s=ge(8),i=r?.traceId??ge(16),u=pr(t.sampling,r===void 0?s:i),f=u.isTraced&&(r===void 0||r.sampled);return{decision:u,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:f,spanId:s,traceFlags:f?ys:bs,traceId:i,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState}}}},$t=(e,t)=>{t.traceparent=Xt(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},Ts=(e,t)=>{let n;return()=>{if(n===void 0){const r=fr(e),s=t===void 0?void 0:t.cf;n=ur(hr(r),lr(r,s))}return n}},Os="/_lunora/admin/scheduled",vs="/_lunora/admin/scheduled/status",ks="/_lunora/admin/scheduled/ws",Is="/_lunora/admin/scheduled/cancel",Ps="/_lunora/admin/scheduled/dead",Ds="/_lunora/admin/scheduled/dead/retry",Ns="/_lunora/admin/scheduled/dead/cancel",Us="/_lunora/admin/scheduled/pool/release",Cs=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,i=(h,y)=>S=>{if(S.method!=="GET")throw new c(`${y} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),w=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return r(S).fetch(new Request(`https://scheduler.internal${h}${w}`,{method:"GET"}))},u=(h,y,S=y)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const w=r(T),b=await se(T,y);if(typeof b?.id!="string"||b.id==="")throw new c(`${y} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return w.fetch(new Request(`https://scheduler.internal${h}`,{body:JSON.stringify({id:b.id}),headers:{"content-type":"application/json"},method:"POST"}))},f=async h=>{if(h.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const y=r(h),S=await se(h,"Scheduled pool-release");if(typeof S?.pool!="string"||S.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const T=typeof S.id=="string"&&S.id!==""?S.id:void 0;return y.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(T===void 0?{pool:S.pool}:{id:T,pool:S.pool}),headers:{"content-type":"application/json"},method:"POST"}))},p=async h=>{if(h.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(h))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const y=n();return ye(y,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[Is]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Ns]:u("/dead/cancel","Scheduled dead-letter action"),[Ps]:i("/dead","Scheduled dead-letter"),[Ds]:u("/dead/retry","Scheduled dead-letter action"),[Os]:i("/list","Scheduled-list"),[Us]:f,[vs]:i("/status","Scheduler-status"),[ks]:p}},Bs="/_lunora/scheduled",pn="/_lunora/queue",mn=16*1048576,xs=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,s=async(u,f,p)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const h=await se(u,"Scheduled tick"),y=typeof h?.cron=="string"?h.cron:"";if(y==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:y,noRetry:()=>{},scheduledTime:Date.now()},f,p),Response.json({cron:y,ok:!0})},i=async(u,f,p)=>{if(t(u),u.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const h=await se(u,"Queue dispatch",mn);if(!Array.isArray(h?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const y=typeof h.queue=="string"?h.queue:"",S=h.messages.filter(w=>typeof w=="object"&&w!==null&&typeof w.id=="string").map(w=>({body:w.body,id:w.id})),T=await r({messages:S,queue:y},f,p);return Response.json({retry:T?.retry??[]})};return{[pn]:i,[Bs]:s}},Hs=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},et={mtls:e=>Hs(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ls=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),$s=e=>typeof e=="string"&&Object.hasOwn(et,e),js=e=>{const t=$s(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return r=>{n||t!==void 0&&r.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Ms="/_lunora/admin/vector/indexes",Ks="/_lunora/admin/vector/query",Fs=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async i=>{M(i,"GET","Vector-indexes");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await u.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async i=>{M(i,"POST","Vector-query");const u=n(i,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(u.queryIndex===void 0)throw new c("vector index querying is not enabled on this worker",{code:"VECTOR_QUERY_UNSUPPORTED",status:400});const p=await t(i);if(typeof p.name!="string"||p.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof p.text!="string"||p.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(p.topK!==void 0&&(typeof p.topK!="number"||!Number.isInteger(p.topK)||p.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const h=await u.queryIndex({name:p.name,text:p.text,topK:p.topK});return Response.json(h,{headers:{"content-type":"application/json"},status:200})};return{[Ms]:r,[Ks]:s}},Gs="/_lunora/admin/workflows/instances",Qs="/_lunora/admin/workflows/instance",Ws="/_lunora/admin/workflows/status",zs={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Vs=e=>e!==null&&Object.hasOwn(zs,e)?e:void 0,jt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},ze=(e,t)=>{const n=e.searchParams.get(t);if(n===null||n==="")throw new c(`Workflows admin endpoint requires a \`${t}\` query parameter`,{code:"BAD_REQUEST",status:400});return n},Mt=()=>{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})},qs=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(u,f,p)=>{M(u,"GET","Workflows instances"),t(u);const h=n(f);if(!h)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const y=ze(p,"name"),S=Vs(p.searchParams.get("status"));return Response.json(await h.listInstances({page:jt(p,"page"),perPage:jt(p,"perPage"),status:S,workflowName:y}))},s=async(u,f,p)=>{M(u,"GET","Workflows instance"),t(u);const h=n(f);return h?Response.json(await h.getInstance({instanceId:ze(p,"id"),workflowName:ze(p,"name")})):Mt()},i=async(u,f)=>{M(u,"POST","Workflows status"),t(u);const p=n(f);if(!p)return Mt();const h=await se(u,"Workflows status");if(typeof h?.name!="string"||h.name===""||typeof h.id!="string"||h.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:y}=h;if(y!=="pause"&&y!=="resume"&&y!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await p.setInstanceStatus({action:y,instanceId:h.id,workflowName:h.name}))};return{[Qs]:s,[Gs]:r,[Ws]:i}},Js={[hn]:fn,[pn]:mn,[Tr]:Ar},Kt="/_lunora/rpc",Ys="/_lunora/rpc-batch",Xs="/_lunora/ws",Ee=(e,t,n)=>({resourceAttributes:Ts(e,t),...n===void 0?{}:{waitUntil:n}}),Ve=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},Ft=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),qe=e=>{const{method:t}=e,n=e.headers.get("user-agent")??void 0;let r;try{r=new URL(e.url)}catch{return{method:t,userAgent:n}}const s=r.port===""?void 0:Number(r.port);return{host:r.hostname,method:t,path:r.pathname,port:Number.isNaN(s)?void 0:s,scheme:r.protocol.replace(":",""),userAgent:n}},Gt="/_lunora/voice/",Zs="/_lunora/scheduler/dispatch",ea="/_lunora/admin/cron-jobs/run",ta="/_lunora/admin/ws-token",na="/_lunora/admin/",Ne="/_lunora/",ra="/_lunora/migrate",oa="/_lunora/status",sa=e=>e.startsWith(na)||e===ra,aa="__lunora_relation__:",Oe=e=>{if(e.startsWith(aa))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},ve=async e=>await e===!0,ia=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},Qt="/api/auth",ca="__lunora_admin__:recordAuthEvent",da="__lunora_admin__:listPushSubscriptions",ua=["/sign-in","/sign-up","/callback"],la=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return ua.some(s=>r===s||r.startsWith(`${s}/`))},ha=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,r)=>{const s=nr(n),i=s?n.code:"INTERNAL_SERVER_ERROR",u=s?n.status:500,f=n instanceof Error?n.message:String(n);return{durationMs:t,error:{code:i,message:f,status:u},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},fa=e=>{const{exp:t,expiresAtMs:n}=e;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof t=="number"&&Number.isFinite(t))return t*1e3},Wt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,pa=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,ma=async(e,t,n,r,s=tt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),f=e.headers.get("cookie"),p=e.headers.get("x-d1-bookmark"),h=e.headers.get("x-lunora-mutation-id"),y=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),T=e.headers.get("x-lunora-base-seq");u&&(i.authorization=u),f&&(i.cookie=f),p&&(i["x-d1-bookmark"]=p),h&&(i["x-lunora-mutation-id"]=h),y&&(i["x-lunora-client-id"]=y),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const w=yr(e.headers,r);if(w&&(i["x-lunora-client-ip"]=w),!n)return{claims:null,headers:i,identity:null,userId:null};const b=await n(e,t,s);if(!b||typeof b.userId!="string"||b.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=ir(b.userId);const R=fa(b);R!==void 0&&(i["x-lunora-identity-exp"]=String(R));const{userId:g,...O}=b,D=Object.keys(O).length>0?O:null;return D&&(i["x-lunora-identity"]=cr(D)),{claims:D,headers:i,identity:b,userId:g}},wa=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),ga=e=>{if(e===void 0)return;if(!e||typeof e!="object")throw new c("RPC `fanOut` must be an object",{code:"BAD_REQUEST",status:400});const t=e;if(typeof t.table!="string"||t.table.length===0)throw new c("RPC `fanOut.table` must be a non-empty string",{code:"BAD_REQUEST",status:400});if(!t.merge||typeof t.merge!="object")throw new c("RPC `fanOut.merge` must be an object",{code:"BAD_REQUEST",status:400});const n=t.merge;if(typeof n.kind!="string"||!wa.has(n.kind))throw new c("RPC `fanOut.merge.kind` is not a recognized merge strategy",{code:"BAD_REQUEST",status:400});if(n.kind==="topK"){if(typeof n.k!="number"||!Number.isInteger(n.k)||n.k<0)throw new c("RPC `fanOut.merge.k` must be a non-negative integer",{code:"BAD_REQUEST",status:400});if(typeof n.by!="string"||n.by.length===0)throw new c("RPC `fanOut.merge.by` must be a non-empty string",{code:"BAD_REQUEST",status:400})}return t},ya=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},Je=(e,t)=>{if(t.functions===void 0)return;const n=t.functions[e.functionPath]?.x402;if(n){if(e.fanOut)throw new c("a paid (`.x402`) function cannot be fanned out",{code:"BAD_REQUEST",status:400});if(!t.x402Charge)throw new c(`function "${e.functionPath}" is marked paid (.x402) but no x402Charge gate is configured on the worker`,{code:"MISCONFIGURED",status:500});return n}},ba=async e=>{const t=await tn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&en(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=ga(s.fanOut),u=s.args??{};if(i&&s.functionPath.startsWith("__lunora_relation__:")){const f=u.table;if(typeof f=="string"&&f!==i.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});u.table=i.table}return{args:u,fanOut:i,functionPath:s.functionPath,shardKey:s.shardKey}},Ie=new Map,_a=5e3,Ea=4096,Ra=async(e,t)=>{const n=Date.now(),r=Ie.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Ie.delete(t);let s=0;try{const i=await ye(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(i.ok){const f=(await i.json()).relayCount;typeof f=="number"&&f>0&&(s=Math.floor(f))}}catch{s=0}return Yt(Ie,Ea),Ie.set(t,{expiresMs:n+_a,relayCount:s}),s},zt=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},Pe=(e,t,n)=>new Request("https://shard.internal/rpc",{body:JSON.stringify({args:t,functionPath:e}),headers:n,method:"POST"}),Sa=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Aa=(e,t)=>{for(const n of Sa){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Vt=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return Aa(n,t),n},Ta=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await sn(e,t),n),qt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:ot(t,s.join(" ").trim())},Jt=async(e,t,n)=>{if(!t||t.length===0)return!1;const r=new URL(e.url).searchParams.get("token");return r===null?!1:await io(t,r)?!0:n?!1:ot(t,r)},Oa=(e,t)=>{if(t===null||typeof t!="object"&&typeof t!="function")return;const n=t;if(typeof n.prepare=="function"&&typeof n.batch=="function"&&typeof n.dump=="function")return Nr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Me(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Me(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Me(`hyperdrive:${e}`,!0)},va=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(Ne))throw new c(`route "${t}" is under the reserved ${Ne} prefix, which the framework owns. App routes registered there shadow the internal endpoint AND its admin gate — pick a path outside the prefix.`,{code:"MISCONFIGURED",status:500})},ka=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},wn=e=>{ka(e);const t=Ls(e.trustInboundTraceContext),n=js(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=Ur(e.resolveIdentity,e.identity),i=Rt(e.shardDO,e.jurisdiction),u=e.schedulerDO===void 0?void 0:Rt(e.schedulerDO,e.jurisdiction);let f=!1;const p=o=>{if(o===void 0||e.jurisdiction===void 0)return o;f||(f=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},h=async(o,a,l,d=e.shardRegion?.(a))=>ye(o,a,p(d)).fetch(l);let y;const S=()=>e.adminToken??y;let T;const w=()=>e.requireEphemeralWsToken??T??!0;let b;const R=o=>{const a=o??{};if(b??=zt(o,e.shardDO),T===void 0&&e.requireEphemeralWsToken===void 0){const d=a.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN;typeof d=="string"&&d.length>0&&(T=oo(d,!0))}if(y!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(y=l)},g=new WeakSet,O=o=>qt(o,S())||g.has(o),D=async o=>{if(!(e.adminGate===void 0||g.has(o)))try{await ve(e.adminGate(o,tt.get(o)))&&g.add(o)}catch{}},L=async(o,a,l,d)=>{const m=await ma(o,a,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(m.headers[gt]=wt),m},P=async(o,a)=>{const l=await L(o,a,e.resolveIdentity);if(g.has(o)&&l.headers.authorization===void 0){const d=S();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let K=!1,$=!1;const Z=()=>{$||($=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},C=o=>{if(!e.allowUnauthenticatedShardAccess){const a=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${a}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}K||(K=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},W=async(o,a,l=!1)=>{if(a.includes(Xe)||a.includes(Ze))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await ve(e.authorizeShard({identity:o,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==r&&C("shard")},J=gs({defaultShard:r,forwardToShard:h,isAdmin:O,queryCoordinator:e.queryCoordinator,resolveForwardContext:P,shardDO:i}),z=async(o,a,l,d,m,_)=>{Oe(o);const v={"content-type":"application/json",[gt]:wt,"x-lunora-system":"1"};return m?.userId!==void 0&&m.userId.length>0&&(v["x-lunora-userid"]=m.userId),m?.identity!==void 0&&m.identity.length>0&&(v["x-lunora-identity"]=m.identity),d!==void 0&&d.length>0&&(v["x-lunora-mutation-id"]=d),_!==void 0&&_.length>0&&(v.traceparent=_),h(i,l,Pe(o,a,v))},ee=async(o,a,l,d,m)=>{const _=l?.[o];if(!_||typeof _.create!="function")throw new c(`${d} targets workflow binding "${o}", which is not bound on env`,{code:"CRON_JOB_FAILED",status:500});if(Lr(a))throw new c(`${d} params ${$r}`,{code:"BAD_REQUEST",status:400});try{await _.create(m===void 0?{params:a}:{id:m,params:a})}catch(v){if(!Kr(v))throw v}},V=async(o,a,l)=>{if(o.workflow){await ee(o.workflow,o.args??{},a,`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const d=await z(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!d.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(d.status)}`,{code:"CRON_JOB_FAILED",status:500})},F=o=>{if(!O(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},j=(o,a,l)=>{if(F(o),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},he=async(o,a,l,d,m)=>{const _=e.cronJobs?.[o];if(!_)return 0;for(const v of _)try{await V(v,a,m)}catch(k){l.push(d(k))}return _.length},ae=async(o,a)=>{if(F(o),M(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await re(o),d=typeof l.name=="string"?l.name:"";if(d==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const m=Object.values(e.cronJobs).flat().find(_=>_.name===d);if(!m)throw new c(`no cron job named "${d}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await V(m,a),Response.json({name:d,ran:!0},{status:200})},be=async o=>{const a=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!a||!u||typeof o.id!="string")return;const l=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await ye(u,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Ue=async(o,a)=>{M(o,"POST","Scheduler dispatch");const l=await tn(o),d=a??{},m=typeof d.LUNORA_SCHEDULER_SECRET=="string"?d.LUNORA_SCHEDULER_SECRET:void 0,_=e.adminToken??(typeof d.LUNORA_ADMIN_TOKEN=="string"?d.LUNORA_ADMIN_TOKEN:void 0),v=o.headers.get("x-lunora-scheduler-signature");let k=!1;if(v&&m?k=await Ta(m,l,v):_&&(k=qt(o,_)),!k)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const E=N??{},A=E.args??{},B=typeof E.id=="string"&&E.id.length>0?E.id:void 0;if(typeof E.workflow=="string"&&E.workflow.length>0)return await ee(E.workflow,A,a,"scheduled workflow",B),await be(E),Response.json({ok:!0},{status:200});if(typeof E.functionPath!="string"||E.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof E.shardKey=="string"&&E.shardKey.length>0?E.shardKey:r,q=ia(o),H=await z(E.functionPath,A,x,B,q,o.headers.get("traceparent")??void 0);return await be(E),H},Ce=ho({assertAdmin:F,getReader:()=>e.authAuditReader}),ie=async(o,a)=>{F(o);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:De({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=a?.kind,m=a?.userId,_=a?.limit,v=d==="fcm"||d==="web-push"?d:void 0,k=typeof m=="string"&&m!==""?m:void 0,N=typeof _=="number"&&Number.isFinite(_)?Math.trunc(_):0,E=N>0?Math.min(N,1e3):1e3,B=(await l.list({kind:v,limit:E,userId:k})).filter(x=>v!==void 0&&x.kind!==v?!1:k===void 0||(x.userId??null)===k).map(({keys:x,token:q,...H})=>H);return Response.json({result:De({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},gn=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==kt&&a.functionPath!==da))return await D(o),a.functionPath===kt?Ce(o,a.args??{}):ie(o,a.args)},yn=xo({applyGlobals:e.applyGlobals,assertAdmin:F,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:e.queryCoordinator,requireAdminOption:j,resolveForwardContext:P,shardDO:i,streamExportRows:(o,a,l,d)=>dn(e,o,a,l,d,i),streamingImport:(o,a)=>Mo(o,e,a,i),syncGlobals:e.syncGlobals}),Be=(o,a)=>{const l=o.searchParams.get(a);return l===null||l===""?void 0:l},xe=o=>{const a=new URL(o.url),l=a.searchParams.get("limit"),d=a.searchParams.get("offset"),m=l===null?void 0:Number.parseInt(l,10),_=d===null?void 0:Number.parseInt(d,10);return{limit:m!==void 0&&Number.isFinite(m)&&m>=0?m:void 0,offset:_!==void 0&&Number.isFinite(_)&&_>=0?_:void 0}},it=()=>{if(u===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return u},bn=Cs({checkWsAdmin:async o=>O(o)||Jt(o,S(),w()),requireSchedulerNamespace:it,resolveSchedulerStub:o=>(F(o),ye(it(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),_n=qs({assertAdmin:F,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),En=Sr({assertAdmin:F,parsePaging:xe,queryParameter:Be,readBodyBytes:gr,requireAdminOption:j,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Rn=To({options:e,readJsonBody:re,requireAdminOption:j}),Sn=Fs({readJsonBody:re,requireAdminOption:j,vectorIntrospector:e.vectorIntrospector}),An=ns({kvIntrospector:e.kvIntrospector,readJsonBody:re,requireAdminOption:j}),Tn=Cr({logArchive:e.logArchive,readJsonBody:re,requireAdminOption:j}),On=Zo({assertAdmin:F,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:xe,queryParameter:Be,requireAdminOption:j}),vn=o=>{const a=[],l=i??o?.SHARD;if(l!==void 0&&a.push(Dr("durable-object:default",l,r)),e.health?.disableBindingProbes!==!0)for(const[d,m]of Object.entries(o??{})){const _=Oa(d,m);_!==void 0&&a.push(_)}for(const d of e.health?.probes??[])a.push(d);return a},kn=Pr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:O,resolveProbes:vn}),In=o=>{const a=E=>"args"in E?{...E,args:Ye(E.args)}:E,l=e.schedulerInstanceName??"default",d=()=>ye(o,l),m=async(E,A)=>{const B=await d().fetch(new Request(`https://scheduler.internal${E}`,A));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${E} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},_=async(E,A)=>await m(E,{body:JSON.stringify(A),headers:{"content-type":"application/json"},method:"POST"}),v=E=>{const A=E;if(A==null)throw new c("ctx.scheduler: target is required — pass a reference from the generated `internal` / `workflows` / `agents`",{code:"BAD_REQUEST",status:400});if(typeof A.binding=="string"&&A.binding.length>0)return{workflow:A.binding};if(typeof A.__lunoraRef=="string")return{functionPath:A.__lunoraRef};throw new c("ctx.scheduler: expected a reference from the generated `internal` / `workflows` / `agents` — a bare function-path string is refused here, because an HTTP action can be reached unauthenticated",{code:"BAD_REQUEST",status:400})},k=async()=>(await jr(async A=>m(A===void 0?"/list":`/list?cursor=${encodeURIComponent(A)}`,{method:"GET"}))).map(A=>a(A)),N=async(E,A,B={})=>{const x=v(A),{id:q}=await _("/schedule",{args:mr("ctx.scheduler",String(x.functionPath??x.workflow),B),scheduledFor:E,...x});return q};return{cancel:async E=>await _("/cancel",{id:E}),get:async E=>{const A=await m(`/get?id=${encodeURIComponent(E)}`,{method:"GET"});return A.record===void 0?null:a(A.record)},list:k,runAfter:async(E,A,B)=>{if(!Number.isFinite(E)||E<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+E,A,B)},runAt:async(E,A,B)=>{if(!Number.isFinite(E))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(E,A,B)}}},Pn=async(o,a,l)=>{const{claims:d,headers:m,userId:_}=await L(o,a,s),v=Ee(a,o,E=>l.waitUntil?.(E)),k=E=>async(A,B={})=>{const x=A.__lunoraRef;if(typeof x!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Oe(x);const q=await Se(o,x,De(B),E,{...m,"x-lunora-system":"1"},v),H=await q.json();if(H.error)throw new c(H.error.message??"shard RPC failed",{code:H.error.code??"INTERNAL",status:q.status});return Ye(H.result)},N=k(r);return{auth:{getIdentity:()=>Promise.resolve(d),userId:_},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:E=>{const A=k(E);return{runAction:A,runMutation:A,runQuery:A}},runAction:N,runMutation:N,runQuery:N,...u===void 0?{}:{scheduler:In(u)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:Hr(e.storage(a))}}},Dn=async(o,a,l)=>{if(!e.httpRouter)return;const d=await Pn(o,a,l);try{return await e.httpRouter.fetch(o,{...a,__lunoraCtx:d},l)}catch(m){return console.error("[lunora] httpRouter (SSR) handler threw:",m),new Response("Internal Server Error",{status:500})}},Nn=async(o,a,l)=>{if(o.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=At(o,ce);if(d)return d;const m=l.searchParams.get("shard")??r,{headers:_,identity:v}=await L(o,a,s),k=O(o)||await Jt(o,S(),w());await W(v,m,k);const N=Vt(o,_),E=zt(a,e.shardDO);if(E!==void 0){N.set("x-lunora-shard-binding",E);const A=await Ra(i,m);if(A>0){const B=Zr(m,Math.floor(Math.random()*A));return h(i,B,new Request(o,{headers:N}),Tt(o))}}return h(i,m,new Request(o,{headers:N}))},Un=async(o,a,l)=>{const{voiceAgents:d}=e;if(d===void 0)return new Response("Not found",{status:404});if(o.headers.get("Upgrade")!=="websocket")return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const m=At(o,ce);if(m)return m;let _;try{_=decodeURIComponent(l.pathname.slice(Gt.length))}catch{return new Response("Unknown voice agent",{status:404})}const v=Object.hasOwn(d,_)?d[_]:void 0;if(v===void 0)return new Response("Unknown voice agent",{status:404});const k=l.searchParams.get("threadKey");if(k===null||k.length===0)return new Response("Missing threadKey",{status:400});const{headers:N,identity:E}=await L(o,a,s);if(e.authorizeShard){if(!await ve(e.authorizeShard({identity:E,shardKey:k})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else C("shard");const A=Vt(o,N);return h(v,k,new Request(o,{headers:A}))},Cn=async(o,a,l)=>{if(e.authorizeFanOut){if(!await ve(e.authorizeFanOut(l,o.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});C("fan-out")},Re=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await Cn(o.fanOut,o.functionPath,a);return}await W(a,o.shardKey??r)}},Bn=(o,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Z();return}if(e.functions[a]?.kind!=="query"||l.includes(Ze)||l.includes(Xe))return;const d=Tt(o);return d===void 0?void 0:{name:eo(l,d),region:d}},xn=async(o,a,l,d,m)=>{const _=Bn(o,a,d);if(_!==void 0){const v={...m,"x-lunora-replica-read":"1",...b===void 0?{}:{"x-lunora-shard-binding":b}},k=to(o.headers.get("x-lunora-min-seq"));k!==void 0&&(v["x-lunora-min-seq"]=String(k));const N=await h(i,_.name,Pe(a,l,v),_.region);if(N.status!==421)return N}return h(i,d,Pe(a,l,m))},Se=async(o,a,l,d,m,_)=>{const v=Date.now(),{observability:k,sampling:N}=e,E=qe(o),{decision:A,ignoredUpstream:B,trace:x}=Lt(o,{...N===void 0?{}:{sampling:N},trustInbound:t(o)});B&&n(o);const q={...m,[bt]:A.keepErrors?"1":"0"};$t(x,q);try{const H=await xn(o,a,l,d,q);de(k,{...E,...Ft(x),durationMs:Date.now()-v,functionPath:a,ok:H.ok,shardKey:d,...H.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(H.status)}`,status:H.status}}},_,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors});const te=new Response(H.body,{headers:H.headers,status:H.status,statusText:H.statusText});return te.headers.set("x-lunora-shard-key",d),te}catch(H){throw de(k,{...E,...Ft(x),...ke(a,Date.now()-v,H,{shardKey:d})},_,void 0,{isTraced:x.sampled,keepErrors:A.keepErrors}),H}},Hn=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});if(o.fanOut||Oe(o.functionPath),o.fanOut&&!e.queryCoordinator)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400})},Ln=async(o,a,l)=>{M(o,"POST","RPC");const d=await ba(o);ya(a,d),Hn(d);const m=await gn(o,d);if(m!==void 0)return m;const{headers:_,identity:v}=await L(o,a,s);await Re(d,v);const k=Je(d,e);{const N=Date.now(),{observability:E}=e,A=qe(o),B=Ee(a,o,l&&(H=>l.waitUntil?.(H)));if(d.fanOut){const H=e.queryCoordinator;if(!H)throw new c("RPC envelope set `fanOut` but no `queryCoordinator` is configured on the worker",{code:"BAD_REQUEST",status:400});try{const te=await H.fanOut(i,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:_});return de(E,{durationMs:Date.now()-N,fanOut:{failed:te.failed,shards:te.ok+te.failed,table:d.fanOut.table},functionPath:d.functionPath,...A,ok:!0},B),Response.json(te,{headers:{"content-type":"application/json"},status:200})}catch(te){throw de(E,{...ke(d.functionPath,Date.now()-N,te,{fanOut:{table:d.fanOut.table}}),...A},B),te}}const x=d.shardKey??r,q=()=>Se(o,d.functionPath,d.args??{},x,_,B);return k&&e.x402Charge?e.x402Charge(o,{functionPath:d.functionPath,price:k.price},q,Ve(l)):q()}},$n=async(o,a,l)=>{M(o,"POST","RPC batch");const d=await re(o),{calls:m}=d;if(!Array.isArray(m))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:_,identity:v}=await L(o,a,s),k=vo(m,r);for(const G of k.values())for(const Q of G)if(e.functions?.[Q.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${Q.functionPath}" cannot be called in a batch; dispatch it individually over ${Kt}`,{code:"BAD_REQUEST",status:400});await Promise.all([...k.entries()].flatMap(([G,Q])=>Q.map(ne=>Re({args:ne.args,functionPath:ne.functionPath,shardKey:G},v))));const{observability:N,sampling:E}=e,A=Ee(a,o,l&&(G=>l.waitUntil?.(G))),B=qe(o),{decision:x,ignoredUpstream:q,trace:H}=Lt(o,{...E===void 0?{}:{sampling:E},trustInbound:t(o)});q&&n(o);const te={isTraced:H.sampled,keepErrors:x.keepErrors},Yn=G=>{const Q={..._,"content-type":"application/json",[bt]:x.keepErrors?"1":"0"};return $t({...H,spanId:G},Q),Q},He=G=>({parentSpanId:G,spanId:ge(8),traceFlags:H.traceFlags,traceId:H.traceId}),Te=[],Le=[],lt=(G,Q,ne,ue)=>({body:{error:{code:ne,message:ue}},id:G.id,status:Q}),ht=(G,Q,ne,ue,fe)=>{for(const Y of G)de(N,fe(Y),A,void 0,te),Te.push(lt(Y,Q,ne,ue))},Xn=(G,Q,ne,ue,fe,Y)=>{for(const _e of G){const pe=fe.get(_e.id)??Y,me=pe<400;de(N,{durationMs:ue,functionPath:_e.functionPath,...B,...He(ne),ok:me,shardKey:Q,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},A,void 0,te)}};await Promise.all([...k.entries()].map(async([G,Q])=>{const ne=ge(8),ue=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:Q}),headers:new Headers(Yn(ne)),method:"POST"}),fe=Date.now();let Y;try{Y=await h(i,G,ue)}catch(X){const je=Date.now()-fe,{body:mt}=rr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ht(Q,502,mt.code,mt.message,tr=>({...ke(tr.functionPath,je,X,{shardKey:G}),...B,...He(ne)}));return}const _e=Date.now()-fe,pe=Y.headers.get("x-d1-bookmark");pe&&Le.push(pe);let me;try{me=await Y.json()}catch{const X=`shard batch returned a non-JSON response (${String(Y.status)})`;ht(Q,Y.status,"SHARD_ERROR",X,je=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:Y.status},functionPath:je.functionPath,...B,...He(ne),ok:!1,shardKey:G}));return}const $e=Array.isArray(me.results)?me.results:[],Zn=new Map($e.map(X=>[X.id,X.status??Y.status])),er=new Set($e.map(X=>X.id));Xn(Q,G,ne,_e,Zn,Y.status),Te.push(...$e);for(const X of Q)er.has(X.id)||Te.push(lt(X,Y.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const ft={"content-type":"application/json"},[pt]=Le;return Le.length===1&&pt!==void 0&&(ft["x-d1-bookmark"]=pt),Response.json({results:Te},{headers:ft,status:200})},jn=async(o,a,l,d={},m={})=>{try{const _=l.__lunoraRef;if(typeof _!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Oe(_);const{headers:v,identity:k}=await L(o,a,s,m.context),N={args:d,functionPath:_,shardKey:m.shardKey};await Re(N,k);const E=m.shardKey??r,A=Ee(a,o,m.waitUntil),B=()=>Se(o,_,d,E,v,A),x=Je(N,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:_,price:x.price},B,Ve(m.waitUntil?{waitUntil:m.waitUntil}:m.context)):await B()}catch(_){return _t(_)}},ct=async(o,a,l)=>{const{observability:d}=e,m=Date.now(),_=ge(16),v=ge(8),k=Wt(a),N=Xt(_,v,!0);try{const E=await l(N);return de(d,{durationMs:Date.now()-m,functionPath:o,ok:!0,spanId:v,traceId:_},k),E}catch(E){throw de(d,{...ke(o,Date.now()-m,E,{}),spanId:v,traceId:_},k),E}finally{yt(d,k)}},dt=async(o,a,l,d)=>{R(a);const m=[],_=A=>A instanceof Error?A:new Error(String(A)),v=e.crons?.[o.cron];if(v)try{await v(o,a,l)}catch(A){m.push(_(A))}const k=await he(o.cron,a,m,_,d),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(N)try{await Eo(e,i,S(),o)}catch(A){m.push(_(A))}if(!v&&k===0&&!N){const A=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${A.length===0?"(none)":A.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[E]=m;if(m.length===1&&E)throw E;if(m.length>1)throw new AggregateError(m,`scheduled("${o.cron}") had ${String(m.length)} failure(s)`)},Mn=xs({assertAdmin:F,dispatchScheduled:dt,queueHandler:e.queueHandler}),Kn=async(o,a)=>{try{const l=o??{},d=e.adminToken??(typeof l.LUNORA_ADMIN_TOKEN=="string"?l.LUNORA_ADMIN_TOKEN:void 0);if(!d||d.length===0)return;await h(i,r,Pe(ca,{outcome:a},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},Fn=async(o,a,l,d)=>{if(!e.authHandler)return;const m=await e.authHandler(o);if(!m)return;const _=e.authBasePath??Qt;return la(l.pathname,_)&&d.waitUntil?.(Kn(a,m.status>=400?"fail":"ok")),m},Gn=async({args:o,env:a,functionPath:l,request:d,shardKey:m,waitUntil:_})=>{en(o,"REST");const v={functionPath:l,...m===void 0?{}:{shardKey:m}},{headers:k,identity:N}=await L(d,a,s);await Re(v,N);const E=m??r,A=Ee(a,d,_),B=()=>Se(d,l,o,E,k,A),x=Je(v,e);return x&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:x.price},B,Ve({waitUntil:_})):B()},Qn=wr({functions:e.functions??{},invoke:Gn,readJsonBody:re,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ae=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;va(Ae);const Wn={[oa]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Xs]:(o,a,l)=>Nn(o,a,l),[Kt]:(o,a,l,d)=>Ln(o,a,d),[Ys]:(o,a,l,d)=>$n(o,a,d),[Zs]:(o,a)=>Ue(o,a),[ea]:(o,a)=>ae(o,a),[ta]:async o=>{M(o,"POST","ws-token"),F(o);const a=S();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const l=await ao(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...J,...yn,...bn,..._n,...En,...Rn,...Sn,...An,...Tn,...On,...kn,...Qn,...lo({assertAdmin:F,getAuthAdmin:()=>e.authAdmin,parsePaging:xe,queryParameter:Be,readJsonBody:re})};let ce=St(e.security),ut=!1;const zn=o=>{ut||(ut=!0,ce=St(e.security,o??{}))},Vn=async(o,a)=>{sa(a)&&await D(o)},qn=(o,a)=>{if(!(a.pathname.startsWith(Ne)||e.authHandler!==void 0&&ha(a.pathname,e.authBasePath??Qt))||o.method!=="POST"&&o.method!=="PUT")return;const d=Number(o.headers.get("content-length")??""),m=Js[a.pathname]??Zt;if(Number.isFinite(d)&&d>m)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},Jn=async(o,a,l)=>{tt.set(o,l);const d=new URL(o.url);qn(o,d);const m=await Fn(o,a,d,l);if(m)return m;if(Ae){const N=`${o.method} ${d.pathname}`,E=Ae[N]??Ae[d.pathname];if(E)return E(o,a,l)}const _=Mn[d.pathname];if(_)return _(o,a,l);const v=Wn[d.pathname];if(v)return await Vn(o,d.pathname),v(o,a,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Gt))return Un(o,a,d);if(d.pathname.startsWith(Ne))return new Response("Not found",{status:404});const k=await Dn(o,a,l);return k||new Response("Not found",{status:404})};return{async fetch(o,a,l){e.passThroughOnException&&l.passThroughOnException?.(),zn(a),R(a);const d=Br(o,ce);if(d)return d;const m=xr(o,ce);if(m)return Ke(m,o,ce);try{const _=await Jn(o,a,l);return Ke(_,o,ce)}catch(_){return Ke(_t(_),o,ce)}finally{yt(e.observability,Wt(l))}},async queue(o,a,l){await ct(`queue:${pa(o)}`,l,async d=>{await e.queue?.(o,a,l,{traceparent:d})})},async scheduled(o,a,l){await ct(`cron:${o.cron}`,l,async d=>{await dt(o,a,l,d)})},serverQuery:jn}},Ia=e=>wn(e),Pa=e=>typeof e=="function"?{fetch:e}:e,Da=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,Na=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},ti=(e,t)=>{const n=Pa(e),{email:r,queue:s,scheduled:i}=Na(e),u=p=>{const y={...Ia({...p,httpRouter:n})};return i!==void 0&&!Da(p)&&(y.scheduled=async(S,T,w)=>{await i(S,T,w)}),s!==void 0&&p.queue===void 0&&(y.queue=async(S,T,w)=>{await s(S,T,w)}),r!==void 0&&(y.email=async(S,T,w)=>{await r(S,T,w)}),y};if(typeof t!="function")return u(t);const f=t;return{fetch:(p,h,y)=>u(f(h)).fetch(p,h,y),queue:(p,h,y)=>u(f(h)).queue?.(p,h,y)??Promise.resolve(),scheduled:(p,h,y)=>u(f(h)).scheduled(p,h,y),serverQuery:(p,h,y,S,T)=>u(f(h)).serverQuery(p,h,y,S,T),...r===void 0?{}:{email:(p,h,y)=>u(f(h)).email?.(p,h,y)??Promise.resolve()}}},Ua=(e,t)=>{if(typeof e=="function")return e(t);const n=e.shardDO??t?.SHARD;if(!n)throw new c("@lunora/runtime: no shard Durable Object namespace found. Bind `SHARD` in wrangler.jsonc, or pass `createLunoraHandler({ shardDO: env.MY_SHARD })`.");return{...e,shardDO:n}},ni=(e={})=>(t,n,r)=>wn(Ua(e,n)).fetch(t,n,r??or),ri=e=>e;export{kt as GET_AUTH_AUDIT_LOG_OP,or as NOOP_EXECUTION_CONTEXT,ai as composeIdentityResolvers,Ia as composeWorker,ni as createLunoraHandler,wn as createWorker,ri as defineRpcEnvelope,Ra as probeRelayCount,Ua as resolveLunoraOptions,ii as routeIdentityResolvers,ti as withFrameworkWorker};
@@ -1 +0,0 @@
1
- import{LunoraError as O}from"./LunoraError-DksAgIpa.mjs";const y=new Set(["0","disabled","false","no","off"]),E=new Set(["1","enabled","on","true","yes"]),d=e=>typeof e=="string"&&y.has(e.trim().toLowerCase()),S=e=>typeof e=="string"&&E.has(e.trim().toLowerCase()),L="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",A=e=>{const o=["base-uri 'none'","object-src 'none'"];return e==="DENY"?o.push("frame-ancestors 'none'"):e==="SAMEORIGIN"&&o.push("frame-ancestors 'self'"),o.join("; ")},b="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",u=["Authorization","Content-Type","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],f=["DELETE","GET","HEAD","PATCH","POST","PUT"],C=31536e3,v=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??C,r=o.includeSubDomains??!0;return`max-age=${String(s)}${r?"; includeSubDomains":""}${o.preload?"; preload":""}`},D=(e,o)=>{if(e!==!1)return typeof e=="string"?{htmlValue:e,value:e}:{htmlValue:o,value:L}},_=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 o=e===void 0||e===!0?{}:e,s=o.frameOptions===!1?void 0:o.frameOptions??"SAMEORIGIN";return{coop:"same-origin",csp:D(o.csp,A(s)),enabled:!0,frameOptions:s,hsts:R(o.hsts),permissionsPolicy:o.permissionsPolicy===!1?void 0:o.permissionsPolicy??b,referrerPolicy:o.referrerPolicy===!1?void 0:o.referrerPolicy??"strict-origin-when-cross-origin"}},N=e=>{const o={allowCredentials:!1,allowedHeaders:u,allowedMethods:f,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return o;const s=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const a=m=>r(m)===!0;t=a,n=a,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 a=r;if(a.includes("*")&&s)throw new O('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=i=>a.includes("*")||a.includes(i),n=i=>a.includes(i)}return{allowCredentials:s,allowedHeaders:e.allowedHeaders??u,allowedMethods:e.allowedMethods??f,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},H=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const o=e===void 0||e===!0?{}:e;return{allowLoopback:o.allowLoopback??!0,enabled:!0,trustedOrigins:o.trustedOrigins??[]}},I=e=>{const o=e?.LUNORA_ALLOWED_ORIGINS;if(typeof o!="string")return;const s=o.split(",").map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:{allowCredentials:!s.includes("*")&&S(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:s}},j=(e,o)=>{const s=e?.headers??(d(o?.LUNORA_SECURITY_HEADERS)?!1:void 0),r=e?.csrf??(d(o?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??I(o);return{cors:N(t),csrf:H(r),headers:_(s)}},P=new Set(["127.0.0.1","::1","[::1]","localhost"]),p=e=>{try{return P.has(new URL(e).hostname)}catch{return!1}},c=e=>{if(e)try{return new URL(e).origin}catch{return}},h=(e,o,s)=>e===o||s.csrf.trustedOrigins.includes(e)||s.csrf.allowLoopback&&p(o)&&p(e)?!0:s.cors.enabled&&s.cors.isExplicitlyAllowed(e),w=(e,o,s)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:s,message:`${e} rejected: Origin ${o===void 0?"was missing":`"${o}"`} 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:o}},{headers:{"content-type":"application/json"},status:403}),F=(e,o)=>{if(!o.csrf.enabled||v.has(e.method)||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"))??c(e.headers.get("referer"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin state-changing request",r,s)},X=(e,o)=>{if(!o.csrf.enabled||!e.headers.get("cookie"))return;const s=new URL(e.url).origin,r=c(e.headers.get("origin"));if(!(r!==void 0&&h(r,s,o)))return w("cross-origin websocket upgrade",r,s)},T=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Shard-Key"],g=(e,o)=>{const s=new Headers;return s.set("access-control-allow-origin",e),s.set("access-control-expose-headers",T.join(", ")),s.append("vary","Origin"),o.allowCredentials&&s.set("access-control-allow-credentials","true"),s},B=(e,o)=>{if(!o.cors.enabled||e.method!=="OPTIONS")return;const s=e.headers.get("origin");if(!s||!e.headers.get("access-control-request-method")||!o.cors.isAllowed(s))return;const r=g(s,o.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",o.cors.allowedMethods.join(", "));let n;if(t===null)n=o.cors.allowedHeaders.join(", ");else{const a=new Set(o.cors.allowedHeaders.map(i=>i.toLowerCase()));n=t.split(",").map(i=>i.trim()).filter(i=>i.length>0&&a.has(i.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(o.cors.maxAge)),new Response(null,{headers:r,status:204})},x=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),l=(e,o,s)=>{e.has(o)||e.set(o,s)},k=(e,o,s,r)=>{if(r.hsts!==void 0&&new URL(o.url).protocol==="https:"&&l(e,"strict-transport-security",r.hsts),l(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&l(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&l(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&l(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&l(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0){const t=x(s)?r.csp.htmlValue:r.csp.value;t!==void 0&&l(e,"content-security-policy",t)}},U=(e,o,s)=>{const r=o.headers.get("origin");if(!(!r||!s.isAllowed(r)))for(const[t,n]of g(r,s).entries())t==="vary"?e.append("vary",n):l(e,t,n)},V=(e,o,s)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return s.headers.enabled&&k(r,o,e,s.headers),s.cors.enabled&&U(r,o,s.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{V as decorateResponse,F as enforceOrigin,X as enforceWebSocketOrigin,B as handleCorsPreflight,j as resolveSecurity};
@@ -1 +0,0 @@
1
- import{e as a,a as s,f}from"./observability-DQGhbG0p.mjs";export{a as emitLogEvent,s as emitRpcEvent,f as flushSink};
@@ -1 +0,0 @@
1
- import{t as r}from"./base64-Bl1_r2k1.mjs";new TextDecoder;const o=new TextEncoder,n="=",c=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},a=e=>r(o.encode(JSON.stringify(e))),d=e=>!e.startsWith(n)&&c(e)?e:`${n}${r(o.encode(e))}`;export{a,d as e};
@@ -1 +0,0 @@
1
- const i="x-lunora-sample-errors";const n=t=>{const r=Number.parseInt(t.slice(-8),16);return Number.isFinite(r)?r/4294967296:0},a=(t,r=1)=>r>=1?!0:r<=0?!1:n(t)<r,E=(t,r)=>({isTraced:a(r,t?.headRate??1),keepErrors:t?.alwaysSampleErrors??!0}),u=(t,r)=>t.isTraced||t.keepErrors&&r,T=(t,r,e,o,c)=>{if(!t?.onRpc)return;const s=c??(o!==void 0&&r.traceId!==void 0?E(o,r.traceId):void 0);if(!(s!==void 0&&!u(s,!r.ok)))try{t.onRpc(r,e)}catch{}},A=(t,r,e)=>{if(t?.onLog)try{t.onLog(r,e)}catch{}},l=(t,r)=>{if(t?.flush)try{t.flush(r)}catch{}};export{i as S,T as a,A as e,l as f,E as r};
@@ -1 +0,0 @@
1
- const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,v=new Uint8Array(l);let a=l;const O=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=A[e[r+n]];return o},T=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),O(t,0,e)}a+e>l&&(crypto.getRandomValues(v),a=0);const r=O(v,a,e);return a+=e,r},u=/^[0-9a-f]+$/,S=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,I=e=>{if(e==null)return;const r=e.trim().toLowerCase().split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},_=(e,r)=>typeof r=="boolean"?{key:e,value:{boolValue:r}}:typeof r=="number"?Number.isFinite(r)?Number.isSafeInteger(r)?{key:e,value:{intValue:String(r)}}:{key:e,value:{doubleValue:r}}:{key:e,value:{stringValue:String(r)}}:{key:e,value:{stringValue:r}},b=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>_(r,t)),C=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),m=n.get(g);m===void 0?(n.set(g,c),o[c]=i):o[m]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],L={client:3,consumer:5,internal:1,producer:4,server:2},h=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),p=(e,r)=>{const t={"service.name":e};for(const[o,n]of Object.entries(r??{}))t[o]=n;return Object.entries(t).map(([o,n])=>_(o,n))},V=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),M=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),y=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),E="CF_VERSION_METADATA",d=(e,r)=>{if(typeof e!="object"||e===null)return;const t=e[r];return typeof t=="string"&&t.length>0?t:void 0},w=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===E)return d(t,"tag")??d(t,"id")},D=e=>{const r={},t=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");t!==void 0&&(r["service.version"]=t);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(r["deployment.environment"]=o),r},x=(e,r)=>{if(!(r!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=d(r,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},F=(...e)=>{const r={};for(const t of e)if(t!==void 0)for(const[o,n]of Object.entries(t))r[o]=n;return r};export{h as L,L as O,D as a,S as b,N as c,x as d,_ as e,R as f,b as g,C as h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};