@lunora/runtime 1.0.0-alpha.17 → 1.0.0-alpha.171

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.
Files changed (55) hide show
  1. package/LICENSE.md +126 -0
  2. package/README.md +59 -0
  3. package/dist/index.d.mts +4414 -1542
  4. package/dist/index.d.ts +4414 -1542
  5. package/dist/index.mjs +1 -16
  6. package/dist/packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs +1 -0
  7. package/dist/packem_shared/DEFAULT_LOG_COLUMNS-gYMhXLzO.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BSKqUsWS.mjs +1 -0
  9. package/dist/packem_shared/HEALTH_PATH-D0i8LhwT.mjs +1 -0
  10. package/dist/packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs +1 -0
  11. package/dist/packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs +1 -0
  12. package/dist/packem_shared/LunoraError-DksAgIpa.mjs +1 -0
  13. package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs +1 -0
  14. package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs +1 -0
  15. package/dist/packem_shared/analyticsEngineSink-BlkElAL2.mjs +1 -0
  16. package/dist/packem_shared/applyJurisdiction-C0ddU7Tg.mjs +1 -0
  17. package/dist/packem_shared/applyRestCache-CEcBz3qq.mjs +1 -0
  18. package/dist/packem_shared/argsFromQuery-CGTSmiBb.mjs +1 -0
  19. package/dist/packem_shared/base64-Bl1_r2k1.mjs +1 -0
  20. package/dist/packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs +1 -0
  21. package/dist/packem_shared/composeWorker-BDBzY5pl.mjs +6 -0
  22. package/dist/packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs +1 -0
  23. package/dist/packem_shared/createKvCursorStore-DQXTTD0l.mjs +1 -0
  24. package/dist/packem_shared/createQueryCoordinator-BkZPoV26.mjs +1 -0
  25. package/dist/packem_shared/createShardClient-BrzRLSs9.mjs +1 -0
  26. package/dist/packem_shared/declareAppJurisdiction-DEba2p42.mjs +1 -0
  27. package/dist/packem_shared/decorateResponse-CRrFNW1v.mjs +1 -0
  28. package/dist/packem_shared/emitLogEvent-C4keuLS-.mjs +1 -0
  29. package/dist/packem_shared/evict-oldest-BNXsKx4s.mjs +1 -0
  30. package/dist/packem_shared/export-tap-CAyZ2TWC.mjs +3 -0
  31. package/dist/packem_shared/identity-header-pR617HTs.mjs +1 -0
  32. package/dist/packem_shared/memoizeIdentity-DnOj3QRi.mjs +1 -0
  33. package/dist/packem_shared/method-guard-BG_vJNTl.mjs +1 -0
  34. package/dist/packem_shared/observability-DgurIZIR.mjs +1 -0
  35. package/dist/packem_shared/origin-paywall-B6eOO67m.mjs +1 -0
  36. package/dist/packem_shared/otlp-resource-BI3MvjSy.mjs +1 -0
  37. package/dist/packem_shared/pipeline-log-reader-C-nuWG_e.mjs +1 -0
  38. package/dist/packem_shared/portable-json-BSCiOfqE.mjs +1 -0
  39. package/dist/packem_shared/rest-cache-CmHN871W.mjs +1 -0
  40. package/dist/packem_shared/rest-routes-D3ShCTHh.mjs +1 -0
  41. package/dist/packem_shared/toAirbyteMessages-2d_iJXPf.mjs +1 -0
  42. package/dist/packem_shared/wire-codec-BLvSm5Mn.mjs +1 -0
  43. package/package.json +9 -2
  44. package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-B3pA7aXp.mjs +0 -79
  45. package/dist/packem_shared/LunoraError-Bpb9EFJ3.mjs +0 -22
  46. package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-CCTu0Bf1.mjs +0 -8
  47. package/dist/packem_shared/analyticsEngineSink-DqEvrQs0.mjs +0 -141
  48. package/dist/packem_shared/applyJurisdiction-BkZtTkct.mjs +0 -20
  49. package/dist/packem_shared/composeIdentityResolvers-XGjO7V1J.mjs +0 -55
  50. package/dist/packem_shared/composeWorker-DU8vDrgA.mjs +0 -2924
  51. package/dist/packem_shared/createCrossShardRelationCapabilities-CbcWjkAn.mjs +0 -63
  52. package/dist/packem_shared/createQueryCoordinator-DNCJzOZE.mjs +0 -847
  53. package/dist/packem_shared/decorateResponse-CsZc49QC.mjs +0 -266
  54. package/dist/packem_shared/emitLogEvent-pEdtqAK8.mjs +0 -20
  55. package/dist/packem_shared/toAirbyteMessages-DrHdplb4.mjs +0 -39
package/dist/index.mjs CHANGED
@@ -1,16 +1 @@
1
- export { toAirbyteMessages, toFivetranResponse } from './packem_shared/toAirbyteMessages-DrHdplb4.mjs';
2
- export { composeWorker, createLunoraHandler, createWorker, defineRpcEnvelope, resolveLunoraOptions, withFrameworkWorker } from './packem_shared/composeWorker-DU8vDrgA.mjs';
3
- export { createCrossShardRelationCapabilities } from './packem_shared/createCrossShardRelationCapabilities-CbcWjkAn.mjs';
4
- export { DEFAULT_REGISTRY_CACHE_TTL_MS, SHARD_REGISTRY_DO_NAME, createDynamicShardRegistry } from './packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-B3pA7aXp.mjs';
5
- export { LunoraError, toErrorResponse } from './packem_shared/LunoraError-Bpb9EFJ3.mjs';
6
- export { emitLogEvent, emitRpcEvent } from './packem_shared/emitLogEvent-pEdtqAK8.mjs';
7
- export { analyticsEngineSink, combineSinks, consoleSink, sentrySink, webhookSink } from './packem_shared/analyticsEngineSink-DqEvrQs0.mjs';
8
- export { createQueryCoordinator, createStaticShardRegistry, mergeStrategyForAggregate } from './packem_shared/createQueryCoordinator-DNCJzOZE.mjs';
9
- export { applyJurisdiction, resolveShard } from './packem_shared/applyJurisdiction-BkZtTkct.mjs';
10
- export { decorateResponse, enforceOrigin, handleCorsPreflight, resolveSecurity } from './packem_shared/decorateResponse-CsZc49QC.mjs';
11
- export { NOOP_EXECUTION_CONTEXT } from './packem_shared/NOOP_EXECUTION_CONTEXT-CCTu0Bf1.mjs';
12
- export { composeIdentityResolvers, routeIdentityResolvers } from './packem_shared/composeIdentityResolvers-XGjO7V1J.mjs';
13
-
14
- const VERSION = "0.0.0";
15
-
16
- export { VERSION };
1
+ import{declareAppJurisdiction as t}from"./packem_shared/declareAppJurisdiction-DEba2p42.mjs";import{BACKUP_KEY_PREFIX as s,backupManifestKey as i,backupObjectKey as n,backupObjectKeyOfManifest as p,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as R,toFivetranResponse as x}from"./packem_shared/toAirbyteMessages-2d_iJXPf.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as y}from"./packem_shared/composeWorker-BDBzY5pl.mjs";import{createCrossShardRelationCapabilities as O}from"./packem_shared/createCrossShardRelationCapabilities-BiXSW10v.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as L,createDynamicShardRegistry as T}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-BSKqUsWS.mjs";import{LunoraError as H,toErrorResponse as P}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{c as v,a as I,d as D,r as M,b as F,s as N,w as G}from"./packem_shared/export-tap-CAyZ2TWC.mjs";import{HEALTH_PATH as U,HEALTH_READY_PATH as B,buildHealthRoutes as Y,d1Probe as w,durableObjectProbe as z,presenceProbe as X}from"./packem_shared/HEALTH_PATH-D0i8LhwT.mjs";import{LOG_ARCHIVE_PATH as V,resolveLogArchiveFromEnv as W}from"./packem_shared/LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{memoizeIdentity as J,memoizeIdentityPerRequest as Q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as $,a as ee}from"./packem_shared/observability-DgurIZIR.mjs";import{analyticsEngineSink as oe,combineSinks as te,consoleSink as ae,otlpSink as se,pipelineLogSink as ie,sentrySink as ne,webhookSink as pe}from"./packem_shared/analyticsEngineSink-BlkElAL2.mjs";import{D as me,c as fe}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as Re,createStaticShardRegistry as xe}from"./packem_shared/createQueryCoordinator-BkZPoV26.mjs";import{applyJurisdiction as le,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as _e,r as ke,b as ye}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as Oe,b as be,c as Ae,r as Le}from"./packem_shared/rest-routes-D3ShCTHh.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Pe,resolveSecurity as ge}from"./packem_shared/decorateResponse-CRrFNW1v.mjs";import{createShardClient as Ie}from"./packem_shared/createShardClient-BrzRLSs9.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ne}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ke}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Be,routeIdentityResolvers as Ye}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,me as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,U as HEALTH_PATH,B as HEALTH_READY_PATH,Ne as LOG_ARCHIVE_NOT_CONFIGURED,V as LOG_ARCHIVE_PATH,H as LunoraError,Ke as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,oe as analyticsEngineSink,le as applyJurisdiction,_e as applyRestCache,Oe as argsFromQuery,i as backupManifestKey,n as backupObjectKey,p as backupObjectKeyOfManifest,Y as buildHealthRoutes,be as buildRestRoutes,te as combineSinks,Be as composeIdentityResolvers,l as composeWorker,ae as consoleSink,O as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,v as createKvCursorStore,d as createLunoraHandler,I as createMemoryCursorStore,fe as createPipelineLogReader,Re as createQueryCoordinator,Ae as createRestRateLimit,Ie as createShardClient,xe as createStaticShardRegistry,u as createWorker,w as d1Probe,t as declareAppJurisdiction,he as decorateResponse,D as defineExportSink,_ as defineRpcEnvelope,z as durableObjectProbe,$ as emitLogEvent,ee as emitRpcEvent,He as enforceOrigin,Pe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,J as memoizeIdentity,Q as memoizeIdentityPerRequest,f as normalizeBackupPrefix,se as otlpSink,ie as pipelineLogSink,X as presenceProbe,M as r2Sink,ke as requestCarriesCredentials,W as resolveLogArchiveFromEnv,k as resolveLunoraOptions,ge as resolveSecurity,de as resolveShard,ye as restCacheHeaders,Le as restSurfaceFromRegistry,Ye as routeIdentityResolvers,F as runExportTap,N as sanitizeChange,ne as sentrySink,R as toAirbyteMessages,P as toErrorResponse,x as toFivetranResponse,G as webhookExportSink,pe as webhookSink,y as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ const e="backups/",c=t=>t===""||t.endsWith("/")?t:`${t}/`,n=".manifest.json",o=(t,s)=>`${c(t)}lunora-backup-${s.replaceAll(/[.:]/gu,"-")}.ndjson`,a=t=>`${t}${n}`,i=t=>t.endsWith(n),p=t=>t.slice(0,-n.length),b=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string";export{e as BACKUP_KEY_PREFIX,a as backupManifestKey,o as backupObjectKey,p as backupObjectKeyOfManifest,b as isBackupManifestEntry,i as isBackupManifestKey,c as normalizeBackupPrefix};
@@ -0,0 +1 @@
1
+ import{D as r,c as L}from"./pipeline-log-reader-C-nuWG_e.mjs";export{r as DEFAULT_LOG_COLUMNS,L as createPipelineLogReader};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";import{applyJurisdiction as S,resolveShard as _}from"./applyJurisdiction-C0ddU7Tg.mjs";const l="__lunora_shard_registry__",f=3e4,y="https://shard-registry.internal",g=async r=>await r.json(),T=r=>{const p=r.instanceName??l,i=r.cacheTtlMs??f,n=new Map,w=S(r.namespace,r.jurisdiction),c=()=>_(w,p),d=async(e,t)=>c().fetch(new Request(`${y}${e}`,{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST"})),h=async e=>c().fetch(new Request(`${y}${e}`,{method:"GET"}));return{invalidate(e){e===void 0?n.clear():n.delete(e)},async listShardKeys(e){const t=Date.now(),s=n.get(e);if(s&&s.expiresAt>t)return s.shardKeys;const o=await h(`/list?table=${encodeURIComponent(e)}`);if(!o.ok)throw new a(`shard registry /list returned ${String(o.status)}`);const{shardKeys:u}=await g(o);return i>0&&n.set(e,{expiresAt:t+i,shardKeys:u}),u},async register(e,t){const s=await d("/register",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /register returned ${String(s.status)}`);n.delete(e)},async snapshot(){const e=await h("/snapshot");if(!e.ok)throw new a(`shard registry /snapshot returned ${String(e.status)}`);const{tables:t}=await g(e);return t},async unregister(e,t){const s=await d("/unregister",{shardKey:t,table:e});if(!s.ok)throw new a(`shard registry /unregister returned ${String(s.status)}`);n.delete(e)}}};export{f as DEFAULT_REGISTRY_CACHE_TTL_MS,l as SHARD_REGISTRY_DO_NAME,T as createDynamicShardRegistry};
@@ -0,0 +1 @@
1
+ import{LunoraError as T}from"./LunoraError-DksAgIpa.mjs";import{m as A}from"./method-guard-BG_vJNTl.mjs";import{resolveShard as R}from"./applyJurisdiction-C0ddU7Tg.mjs";const H="/_lunora/health",C="/_lunora/health/ready",N=t=>t==="liveness"?["liveness"]:t==="readiness"?["readiness"]:["liveness","readiness"];class P{#e=new Map;addChecker(e,s,r){this.#e.set(e,{run:s,types:r.type})}async getReport(e){const s=[...this.#e].filter(([,a])=>e===void 0||a.types.includes(e)),r=await Promise.all(s.map(async([a,o])=>[a,await o.run()]));return{healthy:r.every(([,a])=>a.health.healthy),report:Object.fromEntries(r)}}}const S=t=>{const e=new P,s=new Set;for(const r of t)r.critical&&s.add(r.name),e.addChecker(r.name,async()=>{let a;try{a=await r.check()}catch(o){a={healthy:!1,message:o instanceof Error?o.message:"probe failed"}}return{health:{healthy:a.healthy,...a.message===void 0?{}:{message:a.message}}}},{type:N(r.kind)});return{criticalNames:s,registry:e}},_=(t,e)=>{const s=t.includes(":")?t.slice(0,t.indexOf(":")):"probe",r=(e.get(s)??0)+1;return e.set(s,r),r===1?s:`${s}#${String(r)}`},j=(t,e)=>t?"unhealthy":e?"degraded":"healthy",M=(t,e,s,r,a)=>{const o=[];let u=!1,d=!1;const y=new Map;for(const[h,c]of Object.entries(t)){const n=e.has(h),i=c.health.healthy;d=d||!i,u=u||!i&&n;const l=s==="admin"?h:_(h,y);o.push({critical:n,...s==="admin"&&c.health.message!==void 0?{message:c.health.message}:{},name:l,status:i?"up":"down"})}return o.sort((h,c)=>h.name<c.name?-1:+(h.name>c.name)),{anyCriticalDown:u,body:{appName:r,appVersion:a,checks:o,status:j(u,d),timestamp:new Date().toISOString()}}},G=t=>{const{appName:e="lunora",appVersion:s="0.0.0",auth:r="public",cacheTtlMs:a,isAdmin:o,resolveProbes:u}=t,d=n=>a!==void 0?a:n==="readiness"?0:r==="public"?5e3:0,y={},h=n=>{if(r==="admin"&&!o(n))throw new T("health endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},c=async(n,i,l)=>{const p=A(n,["GET","HEAD"]);if(p)return p;h(n);const f=d(l);if(f>0){const m=y[l];if(m!==void 0&&Date.now()<m.expiresAt)return Response.json(m.body,{headers:{"cache-control":"no-store"},status:m.down?503:200})}const{criticalNames:b,registry:v}=S(u(i)),{healthy:E,report:k}=await v.getReport(l==="readiness"?"readiness":void 0),{anyCriticalDown:D,body:g}=M(k,b,r,e,s),w=l==="readiness"?!E:D;return f>0&&(y[l]={body:g,down:w,expiresAt:Date.now()+f}),Response.json(g,{headers:{"cache-control":"no-store"},status:w?503:200})};return{[H]:(n,i)=>c(n,i,"aggregate"),[C]:(n,i)=>c(n,i,"readiness")}},I=(t,e,s)=>({check:async()=>{try{return await R(e,s).fetch(new Request("https://shard.internal/_lunora/status",{method:"GET"})),{healthy:!0}}catch{return{healthy:!1,message:"durable object unreachable"}}},critical:!0,name:t}),q=(t,e)=>({check:async()=>{try{return await e.prepare("SELECT 1").first(),{healthy:!0}}catch{return{healthy:!1,message:"d1 query failed"}}},critical:!0,name:t}),B=(t,e)=>({check:()=>e?{healthy:!0}:{healthy:!1,message:"binding not configured"},critical:!1,name:t});export{H as HEALTH_PATH,C as HEALTH_READY_PATH,G as buildHealthRoutes,q as d1Probe,I as durableObjectProbe,B as presenceProbe};
@@ -0,0 +1 @@
1
+ const O="LOG_ARCHIVE_NOT_CONFIGURED";export{O as LOG_ARCHIVE_NOT_CONFIGURED};
@@ -0,0 +1 @@
1
+ import{createR2Sql as h}from"@lunora/bindings/r2sql";import{LOG_ARCHIVE_NOT_CONFIGURED as l}from"./LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{L,c as A}from"./pipeline-log-reader-C-nuWG_e.mjs";import{LunoraError as _}from"./LunoraError-DksAgIpa.mjs";import{a as R}from"./method-guard-BG_vJNTl.mjs";const v="/_lunora/admin/logs/archive",m="LUNORA_LOG_ARCHIVE_TABLE",C="LUNORA_LOG_ARCHIVE_NAMESPACE",V=e=>{if(typeof e!="object"||e===null)return;const o=e,s=o[m];if(typeof s!="string"||s==="")return;const n=o[C];return{table:s,...typeof n=="string"&&n!==""?{namespace:n}:{}}},T=new Set(L),O=e=>typeof e=="string"&&e!==""?e:void 0,S=(e,o)=>{if(e!==void 0){if(typeof e!="string"||!T.has(e))throw new _(`logs archive: invalid \`${o}\` — expected one of ${L.join(", ")}`,{code:"BAD_REQUEST",status:400});return e}},p=(e,o)=>{if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))throw new _(`logs archive: invalid \`${o}\` — expected a finite number`,{code:"BAD_REQUEST",status:400});return e}},b=e=>{const o={},s=r=>{const t=O(e[r]);t!==void 0&&(o[r]=t)},n=r=>{const t=S(e[r],r);t!==void 0&&(o[r]=t)},i=r=>{const t=p(e[r],r);t!==void 0&&(o[r]=t)};s("functionPath"),s("functionPathPrefix"),s("traceId"),s("shardKey"),s("userId"),n("level"),n("minLevel"),i("sinceTs"),i("untilTs"),i("limit");const c=e.cursor;if(typeof c=="object"&&c!==null){const r=c,t=p(r.ts,"cursor.ts");if(t!==void 0){const a=r.seen;if(a!==void 0&&(!Array.isArray(a)||a.some(d=>typeof d!="string")))throw new _("logs archive: invalid `cursor.seen` — expected an array of strings",{code:"BAD_REQUEST",status:400});const u=a;o.cursor=u===void 0||u.length===0?{ts:t}:{seen:u,ts:t}}}return o},y=e=>{const o=e.R2_SQL_ACCOUNT_ID??e.CLOUDFLARE_ACCOUNT_ID,s=e.R2_SQL_TOKEN,n=e.R2_SQL_BUCKET,i=[];if((o===void 0||o==="")&&i.push("R2_SQL_ACCOUNT_ID"),(s===void 0||s==="")&&i.push("R2_SQL_TOKEN"),(n===void 0||n==="")&&i.push("R2_SQL_BUCKET"),i.length>0)throw new _(`log archive not configured (missing ${i.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET must be set — see the observability docs.`,{code:l,status:400});return{accountId:o,apiToken:s,bucket:n}},B=e=>{const{createReader:o=A,readJsonBody:s,requireAdminOption:n}=e,i=async(c,r)=>{R(c,"POST","Log-archive");const t=n(c,e.logArchive,{code:l,message:"log archive requires a `logArchive` config (an R2 Data Catalog table) on the worker — see the observability docs"}),{accountId:a,apiToken:u,bucket:d}=y(r??{}),g=b(await s(c)),E=h({accountId:a,apiToken:u,bucket:d}),f=await o(E,{columnMap:t.columnMap,namespace:t.namespace,table:t.table}).query(g);return Response.json(f,{headers:{"content-type":"application/json"},status:200})};return{[v]:i}};export{l as LOG_ARCHIVE_NOT_CONFIGURED,v as LOG_ARCHIVE_PATH,B as buildLogArchiveAdminRoutes,V as resolveLogArchiveFromEnv};
@@ -0,0 +1 @@
1
+ import{LunoraError as t,toErrorBody as a}from"@lunora/errors";const n=e=>{const{body:o,redacted:r,status:s}=a(e,{fallbackCode:"INTERNAL",redactedMessage:"Internal error"});return r&&console.error("[lunora] internal error:",e),Response.json({error:o},{headers:{"content-type":"application/json"},status:s})};class u extends t{constructor(o,r){super(r?.code??"INTERNAL",o,{cause:r?.cause,status:r?.status})}toResponse(){return n(this)}}export{u as LunoraError,n as toErrorResponse};
@@ -0,0 +1 @@
1
+ const t={passThroughOnException:()=>{},waitUntil:()=>{}};export{t as NOOP_EXECUTION_CONTEXT};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"./LunoraError-DksAgIpa.mjs";import{a as O}from"./method-guard-BG_vJNTl.mjs";const j="/_lunora/admin/storage",P="/_lunora/admin/storage/object",B="/_lunora/admin/storage/url",C="/_lunora/admin/storage/buckets",v=10080*60,I=32*1048576,M=new Set(["GET","PUT"]),x=E=>{const w=new Uint8Array(E);let T="";for(const s of w)T+=s.toString(16).padStart(2,"0");return T},z=E=>{const{assertAdmin:w,parsePaging:T,queryParameter:s,readBodyBytes:R,requireAdminOption:d,storage:r}=E,h=e=>{const o=s(e,"key");if(o===void 0)throw new i("Storage endpoint requires a `key` query parameter",{code:"BAD_REQUEST",status:400});return o},u=e=>{const o=s(e,"bucket"),t=r.storageBuckets;if(o===void 0||t===void 0||t.length===0)return o;if(!t.includes(o))throw new i(`Unknown storage bucket \`${o}\``,{code:"NOT_FOUND",status:404});return o},U=async e=>{const o=d(e,r.storageList,{code:"STORAGE_NOT_CONFIGURED",message:"storage endpoint requires a `storageList` function on the worker"}),t=new URL(e.url),n=await o(s(t,"prefix"),{bucket:u(t),cursor:s(t,"cursor"),...T(e)});return Response.json(n,{headers:{"content-type":"application/json"},status:200})},m=e=>(O(e,"GET","Storage-buckets"),w(e),Response.json({buckets:r.storageBuckets??[]},{headers:{"content-type":"application/json"},status:200})),A=async e=>{const o=d(e,r.storageDelete,{code:"STORAGE_DELETE_NOT_CONFIGURED",message:"storage delete requires a `storageDelete` function on the worker"}),t=new URL(e.url),n=h(t);return await o(n,{bucket:u(t)}),Response.json({deleted:!0,key:n},{headers:{"content-type":"application/json"},status:200})},k=async e=>{const o=d(e,r.storageUpload,{code:"STORAGE_UPLOAD_NOT_CONFIGURED",message:"storage upload requires a `storageUpload` function on the worker"}),t=new URL(e.url),n=h(t),a=u(t),g=await R(e,I),c=e.headers.get("content-type"),_=c===null||c===""?void 0:c,l=s(t,"expectedSha256"),p=s(t,"expectedSize");let S;if(l!==void 0||p!==void 0){const L=await crypto.subtle.digest("SHA-256",g);S=x(L);const N=p!==void 0&&g.byteLength!==Number(p),f=l!==void 0&&S!==l.toLowerCase();if(N||f)throw new i("Upload failed verification — the body did not match the declared size or SHA-256 checksum, so nothing was written",{code:"STORAGE_CHECKSUM_MISMATCH",status:400})}const y=await o(n,g,{bucket:a,contentType:_,sha256:S});return Response.json(S===void 0?y:{...y,sha256:S},{headers:{"content-type":"application/json"},status:200})},b=async e=>{switch(e.method){case"DELETE":return A(e);case"GET":return U(e);case"POST":case"PUT":return k(e);default:throw new i("Storage endpoint requires GET, PUT, POST, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405})}},D=async e=>{O(e,"GET","Storage-object");const o=d(e,r.storageDownload,{code:"STORAGE_DOWNLOAD_NOT_CONFIGURED",message:"storage download requires a `storageDownload` function on the worker"}),t=new URL(e.url),n=h(t),a=await o(n,{bucket:u(t)});if(!a?.body)throw new i(`No object at key ${n}`,{code:"STORAGE_OBJECT_NOT_FOUND",status:404});return new Response(a.body,{headers:{"content-disposition":"attachment","content-type":a.httpMetadata?.contentType??"application/octet-stream","x-content-type-options":"nosniff",...a.size===void 0?{}:{"content-length":String(a.size)}},status:200})},G=async e=>{O(e,"GET","Storage URL");const o=d(e,r.storageSignedUrl,{code:"STORAGE_URL_NOT_CONFIGURED",message:"storage URL endpoint requires a `storageSignedUrl` function on the worker"}),t=new URL(e.url),n=h(t),a=Number(s(t,"expiresIn")??""),g=Number.isFinite(a)&&a>0?Math.min(a,v):void 0,c=s(t,"method");if(c!==void 0&&!M.has(c))throw new i("Storage URL `method` must be GET or PUT",{code:"BAD_REQUEST",status:400});const _=c,l=s(t,"contentType"),p=await o(n,{bucket:u(t),contentType:l,expiresInSeconds:g,method:_,origin:t.origin});return Response.json({key:n,url:p},{headers:{"content-type":"application/json"},status:200})};return{[C]:m,[P]:D,[j]:b,[B]:G}};export{C as STORAGE_BUCKETS_PATH,j as STORAGE_PATH,I as STORAGE_UPLOAD_MAX_BODY_BYTES,B as STORAGE_URL_PATH,z as buildStorageAdminRoutes,x as toHex};
@@ -0,0 +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-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 @@
1
+ import{resolveShard as u}from"@lunora/platform";const s=new WeakMap,n=o=>o===void 0?void 0:{locationHint:o},f=o=>typeof o.idFromName=="function",a=o=>{if(!f(o))return o;const e=o,i=s.get(o);if(i!==void 0)return i;const c=typeof e.jurisdiction=="function"?r=>a(e.jurisdiction(r)):void 0,d=typeof e.getByName=="function"?{get:(r,t)=>e.get(r,n(t)),getByName:(r,t)=>e.getByName(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c}:{get:(r,t)=>e.get(r,n(t)),idForName:r=>e.idFromName(r),jurisdiction:c};return s.set(o,d),d},y=(o,e)=>{if(e===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${e}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(e)},p=(o,e,i)=>u(a(o),e,i);export{y as applyJurisdiction,p as resolveShard};
@@ -0,0 +1 @@
1
+ import{a as s,e as r,r as t,b as c}from"./rest-cache-CmHN871W.mjs";export{s as applyRestCache,r as effectiveRestScope,t as requestCarriesCredentials,c as restCacheHeaders};
@@ -0,0 +1 @@
1
+ import{a as o,b as i,c as m,r as R}from"./rest-routes-D3ShCTHh.mjs";import"./rest-cache-CmHN871W.mjs";import"./LunoraError-DksAgIpa.mjs";import"./method-guard-BG_vJNTl.mjs";export{o as argsFromQuery,i as buildRestRoutes,m as createRestRateLimit,R as restSurfaceFromRegistry};
@@ -0,0 +1 @@
1
+ const s=t=>{let n="";for(let a=0;a<t.length;a+=32768)n+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(n)},l=t=>{const n=atob(t),r=new Uint8Array(n.length);for(let a=0;a<n.length;a+=1)r[a]=n.codePointAt(a)??0;return r},o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",h=t=>{let n="",r=0;const a=t.length-2;for(;r<a;r+=3){const e=t[r]<<16|t[r+1]<<8|t[r+2];n+=o.charAt(e>>18&63)+o.charAt(e>>12&63)+o.charAt(e>>6&63)+o.charAt(e&63)}const c=t.length-r;if(c===1){const e=t[r]<<16;n+=o.charAt(e>>18&63)+o.charAt(e>>12&63)}else if(c===2){const e=t[r]<<16|t[r+1]<<8;n+=o.charAt(e>>18&63)+o.charAt(e>>12&63)+o.charAt(e>>6&63)}return n},i=t=>{const n=t.replaceAll("-","+").replaceAll("_","/"),r=n+"=".repeat((4-n.length%4)%4);return l(r)};export{s as a,l as b,i as f,h as t};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"./LunoraError-DksAgIpa.mjs";const u=(t,o={})=>{const r=o.onError??"fail-closed";return async(n,c,e)=>{for(const s of t){let i;try{i=await s(n,c,e)}catch(l){if(r==="skip")continue;throw l}if(i)return i}return null}},f=t=>{const o=Object.keys(t).filter(r=>r!=="*").toSorted((r,n)=>n.length-r.length);return(r,n,c)=>{const{pathname:e}=new URL(r.url),s=o.find(l=>e===l||e.startsWith(l.endsWith("/")?l:`${l}/`)),i=s===void 0?t["*"]:t[s];return i===void 0?null:i(r,n,c)}},h=(t,o)=>o===void 0||t===void 0?t:async(r,n,c)=>{const e=await t(r,n,c);if(!e)return e;const s=o.validate(e);if(s.ok)return e;if(o.onInvalid==="reject")throw new a(`identity claims failed the declared contract: ${s.error}`,{code:"UNAUTHENTICATED",status:401});return null};export{u as composeIdentityResolvers,f as routeIdentityResolvers,h as wrapResolverWithContract};
@@ -0,0 +1,6 @@
1
+ import{isLunoraError as pr,toErrorBody as mr}from"@lunora/errors";import{e as tn}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as wr}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{t as gr,f as yr}from"./base64-Bl1_r2k1.mjs";import{i as br,e as _r,a as Rr,E as gt,d as Er}from"./identity-header-pR617HTs.mjs";import{O as yt,a as bt}from"./origin-paywall-B6eOO67m.mjs";import{o as ge,b as nn,p as Sr,m as Tr,d as Ar,a as Or,r as vr}from"./otlp-resource-BI3MvjSy.mjs";import{r as Ir,f as _t,a as ce,S as Rt}from"./observability-DgurIZIR.mjs";import{e as Ee,d as Ye,a as kr}from"./wire-codec-BLvSm5Mn.mjs";import{d as ee,e as ne,M as rn,b as Pr,f as Dr,g as on,w as Nr,h as sn,t as Ur}from"./rest-routes-D3ShCTHh.mjs";import{LunoraError as c,toErrorResponse as Et}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 Cr,backupObjectKeyOfManifest as an,backupObjectKey as Br,backupManifestKey as xr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Hr,buildStorageAdminRoutes as Lr,STORAGE_UPLOAD_MAX_BODY_BYTES as jr,STORAGE_PATH as Mr}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BIiV5kqV.mjs";import{b as $r,e as Kr,f as St,g as Fr,h as Gr}from"./export-tap-CAyZ2TWC.mjs";import{buildHealthRoutes as Qr,durableObjectProbe as Wr,d1Probe as zr,presenceProbe as je}from"./HEALTH_PATH-D0i8LhwT.mjs";import{wrapResolverWithContract as Vr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as Ni,routeIdentityResolvers as Ui}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as Jr}from"./LOG_ARCHIVE_PATH-Hmjpz_Ko.mjs";import{pruneShardRegistry as Yr,createQueryCoordinator as qr,createDefaultShardRegistry as Xr}from"./createQueryCoordinator-BkZPoV26.mjs";import{resolveShard as ye,applyJurisdiction as Me}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as Tt,handleCorsPreflight as Zr,enforceOrigin as eo,decorateResponse as $e,enforceWebSocketOrigin as At}from"./decorateResponse-CRrFNW1v.mjs";const to=e=>{const t=e??{};if(typeof t.bucket=="function")return t;const n=t.bucketName,s={...t,bucketName:typeof n=="string"&&n!==""?n:"default"};return s.bucket=()=>s,s},cn="__lunoraBranch",no=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,cn),ro=`may not contain the reserved workflow branch-marker key ("${cn}")`,oo=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}},ot=(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},so=/already[\s_-]?exists/iu,ao=e=>so.test(e instanceof Error?e.message:String(e)),io=(e,t,n,o)=>{const s=e.get(t);if(s!==void 0)return s;tn(e,o);const i=n().catch(u=>{throw e.get(t)===i&&e.delete(t),u});return e.set(t,i),i},st=new TextEncoder,co=Array.from({length:32},(e,t)=>t);new RegExp(`[${co.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const uo=64,lo=new Map,dn=async e=>io(lo,e,async()=>crypto.subtle.importKey("raw",st.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),uo),un=async(e,t)=>{const n=await dn(e),o=await crypto.subtle.sign("HMAC",n,st.encode(t));return gr(new Uint8Array(o))},ho=async(e,t,n)=>{const o=await dn(e);return crypto.subtle.verify("HMAC",o,n,st.encode(t))},fo=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(fo);const po=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),mo=-100,wo=15,go=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&po.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>wo?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<mo?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Ot=e=>{const t=e.cf;return t===void 0?void 0:go(t)},qe="::relay::",yo=(e,t)=>`${e}${qe}${String(t)}`,Xe="::replica::",bo=(e,t)=>`${e}${Xe}${t}`,_o=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Ro=(e,t,n)=>e?.[n]??t?.[n],Eo=(e,t,n,o)=>{const s=Ro(e,t,n);if(!(typeof s!="object"||s===null))return o.every(i=>typeof s[i]=="function")?s:void 0},So=new Set(["1","enabled","on","true","yes"]),To=new Set(["0","disabled","false","no","off"]),Ao=(e,t)=>{const n=(e??"").trim().toLowerCase();return So.has(n)?!0:To.has(n)?!1:t},ln="v1",Oo=6e4,vo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Oo),o=`${ln}.${String(n)}`,s=await un(e,o);return{expiresAtMs:n,token:`${o}.${s}`}},Io=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const o=t.split(".");if(o.length!==3)return!1;const[s,i,u]=o;if(s!==ln||u.length===0)return!1;const h=Number(i);if(!Number.isFinite(h)||h<=n)return!1;let f;try{f=yr(u)}catch{return!1}return ho(e,`${s}.${i}`,f)},N="/_lunora/admin/auth",ko={INVITER_REQUIRED:400,ORG_SLUG_INVALID:400,ORG_SLUG_TAKEN:409,PASSWORD_TOO_LONG:400,PASSWORD_TOO_SHORT:400,USER_ALREADY_EXISTS:409,USER_NOT_FOUND:404},C=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},he=(e,t)=>{const n=e(t);if(n===void 0)throw new c(`\`${t}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return n},hn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},te=(e,t)=>typeof e[t]=="string"?e[t]:void 0,Ke=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},vt=e=>{const t=hn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},It=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={[`${N}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${N}/users`]:{build:({paging:e,query:t})=>{const n=t("sortDirection");return{...e,filterField:t("filterField"),filterValue:t("filterValue"),search:t("search"),searchField:t("searchField"),sortBy:t("sortBy"),sortDirection:n==="asc"||n==="desc"?n:void 0}},http:"GET",method:"listUsers"},[`${N}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${N}/accounts`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listAccounts"},[`${N}/passkeys`]:{build:({query:e})=>({userId:he(e,"userId")}),http:"GET",method:"listPasskeys"},[`${N}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${N}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listMembers"},[`${N}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${N}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${N}/sign-up-invitations/create`]:{build:({body:e})=>({email:C(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:te(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${N}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:C(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${N}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${N}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listTeams"},[`${N}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:he(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${N}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:he(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${N}/users/create`]:{build:({body:e})=>({data:Ke(e,"data"),email:C(e,"email"),name:C(e,"name"),password:te(e,"password"),role:hn(e.role)}),http:"POST",method:"createUser"},[`${N}/users/update`]:{build:({body:e})=>{const{data:t}=e;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:t,userId:C(e,"userId")}},http:"POST",method:"updateUser"},[`${N}/users/role`]:{build:({body:e})=>({role:vt(e),userId:C(e,"userId")}),http:"POST",method:"setRole"},[`${N}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:te(e,"reason"),userId:C(e,"userId")}),http:"POST",method:"banUser"},[`${N}/users/unban`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"unbanUser"},[`${N}/users/password`]:{build:({body:e})=>({newPassword:C(e,"newPassword"),userId:C(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${N}/users/remove`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${N}/users/impersonate`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"impersonateUser"},[`${N}/sessions/revoke`]:{build:({body:e})=>({sessionId:C(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${N}/sessions/revoke-all`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${N}/accounts/unlink`]:{build:({body:e})=>({accountId:C(e,"accountId"),userId:C(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${N}/two-factor/disable`]:{build:({body:e})=>({userId:C(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${N}/passkeys/delete`]:{build:({body:e})=>({passkeyId:C(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${N}/organizations/members/remove`]:{build:({body:e})=>({memberId:C(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${N}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:C(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${N}/organizations/create`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:C(e,"name"),ownerId:te(e,"ownerId"),slug:te(e,"slug")}),http:"POST",method:"createOrganization"},[`${N}/organizations/update`]:{build:({body:e})=>({logo:te(e,"logo"),metadata:Ke(e,"metadata"),name:te(e,"name"),organizationId:C(e,"organizationId"),slug:te(e,"slug")}),http:"POST",method:"updateOrganization"},[`${N}/organizations/remove`]:{build:({body:e})=>({organizationId:C(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${N}/organizations/members/add`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),role:te(e,"role"),userId:C(e,"userId")}),http:"POST",method:"addMember"},[`${N}/organizations/members/invite`]:{build:({body:e})=>({email:C(e,"email"),inviterId:te(e,"inviterId"),organizationId:C(e,"organizationId"),role:te(e,"role")}),http:"POST",method:"inviteMember"},[`${N}/organizations/members/role`]:{build:({body:e})=>({memberId:C(e,"memberId"),role:vt(e)}),http:"POST",method:"updateMemberRole"},[`${N}/organizations/teams/create`]:{build:({body:e})=>({name:C(e,"name"),organizationId:C(e,"organizationId")}),http:"POST",method:"createTeam"},[`${N}/organizations/teams/update`]:{build:({body:e})=>({name:C(e,"name"),teamId:C(e,"teamId")}),http:"POST",method:"updateTeam"},[`${N}/organizations/teams/remove`]:{build:({body:e})=>({teamId:C(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${N}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:C(e,"teamId"),userId:C(e,"userId")}),http:"POST",method:"addTeamMember"},[`${N}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:C(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${N}/organizations/roles/create`]:{build:({body:e})=>({organizationId:C(e,"organizationId"),permission:It(e),role:C(e,"role")}),http:"POST",method:"createOrgRole"},[`${N}/organizations/roles/update`]:{build:({body:e})=>({permission:It(e),roleId:C(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${N}/organizations/roles/remove`]:{build:({body:e})=>({roleId:C(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Do=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:ko[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 f=new URL(s.url),m={body:i.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:T=>e.queryParameter(f,T)},b=i.build(m),S=await t(()=>h(b));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},kt="__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,No=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),f=Dt(o.limit),m={...i===void 0?{}:{actorId:i},...u===void 0?{}:{event:u},...h===void 0?{}:{sinceSeq:h},...f===void 0?{}:{limit:f}};let b;try{b=await s.read(m)}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:b};return Response.json({result:Ee(S)},{headers:{"content-type":"application/json"},status:200})},Ze="__lunora_admin__:copyAuthToJurisdiction",fn="__lunora_admin__:purgeUnpinnedAuth",Uo=e=>async(t,n,o)=>{if(n!==Ze&&n!==fn)return;e.assertAdmin(t);const s=e.getMove();if(s===void 0)throw new c("moving auth into the jurisdiction needs DO-backed auth pinned with `.jurisdiction(…, { pinAuth: true })`",{code:"AUTH_MOVE_NOT_CONFIGURED",status:400});const i=n===Ze?await s.copy({force:o.force===!0}):await s.purge();return Response.json({result:Ee(i)},{headers:{"content-type":"application/json"},status:200})},Co=(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}},Bo=async(e,t,n,o,s,i)=>{if(n!==void 0&&o.length===0)return[];const u=await e.orchestrateExport(s,{args:{tables:o},defaultShardKey:i,headers:t,tables:o}),h=u.shards.filter(f=>f.error);if(h.length>0){const f=h.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(h.length)} of ${String(u.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}return u.shards.flatMap(f=>f.rows??[])},pn=async(e,t,n,o,s)=>{const i=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:u,shardLocalTables:h}=Co(e,i),f=await Bo(t,n,i,h,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,b=o===void 0||u.length>0;return(async function*(){yield*f,b&&m&&(yield*m({tables:u}))})()},xo=async(e,t,n,o,s,i)=>{for await(const u of await pn(e,t,n,o,i))s(u)},Ho=new TextEncoder,Lo=1e3,mn=10,jo=200,Nt=8,wn="lunoraBackupCron",Ut=24*1048576,Ct=e=>{const t=e.slice(0,mn).map(o=>an(o)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},Mo=(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},at=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<Lo;u+=1){const h=await e.list({cursor:i,include:["customMetadata"],prefix:t});for(const f of h.objects)Cr(f.key)&&f.customMetadata?.[wn]===o&&s.push(f.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)}},$o=async(e,t,n,o,s)=>{const{stale:i}=await at(e,t,n,o),u=new Set(s),h=i.filter(k=>u.has(k)),f=h.slice(0,jo),m=i.length-f.length,b=s.length-h.length;if(f.length===0)return{deleted:[],failed:[],ignored:b,remaining:m};const S=[],T=[];for(let k=0;k<f.length;k+=Nt){const w=await Promise.allSettled(f.slice(k,k+Nt).map(async g=>(await e.delete(an(g)),await e.delete(g),g)));for(const[g,y]of w.entries())y.status==="fulfilled"?S.push(y.value):T.push(f[k+g])}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:b,remaining:m}},Ko=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),o=e.backupCron,{eligible:s,stale:i}=o===void 0?{eligible:0,stale:[]}:await at(t,n,e.backupRetain,o);return{cron:o,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:i}},Fo=async(e,t,n,o,s)=>{const i=e.backupStore;if(!i)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!o||o.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 ${o}`,"content-type":"application/json"},h=e.backupTables;let f=0,m=0,b=[];await xo(e,t,u,h,I=>{const E=Ho.encode(`${JSON.stringify(I)}
2
+ `);if(f+=1,m+=E.byteLength,m>Ut)throw new c(`scheduled backup reached ${String(m)} 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});b.push(E)},n);const T=nt(e.backupPrefix??rt),k=new Date(s.scheduledTime).toISOString(),w=Br(T,k),g=Mo(b,m);b=[];const y=Hr(await crypto.subtle.digest("SHA-256",g));await i.put(w,g,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:k,cron:s.cron,file:w,id:k,rows:f,scheduledTime:s.scheduledTime,sha256:y,...h?{tables:h.join(",")}:{}};await i.put(xr(w),`${JSON.stringify(v,void 0,2)}
3
+ `,{customMetadata:{[wn]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:I}=await at(i,T,e.backupRetain,s.cron);if(I.length>0){const E=I.slice(0,mn),j=I.length-E.length;console.info(`[lunora] backup retention: ${String(I.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${j>0?` (+${String(j)} more)`:""}`)}}catch(I){console.warn(`[lunora] backup ${w} was written, but the retention report failed:`,I)}},Go=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 $o(n,nt(e.backupPrefix??rt),s,o,t)},Qo="/_lunora/admin/backup/retention",Wo="/_lunora/admin/backup/prune",zo=e=>{const{options:t,readJsonBody:n,requireAdminOption:o}=e,s=(h,f)=>{o(h,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},i=async h=>(M(h,"GET","Backup-retention"),s(h,"retention preview"),Response.json(await Ko(t),{headers:{"cache-control":"no-store"}})),u=async h=>{M(h,"POST","Backup-prune"),s(h,"prune");const{confirm:f}=await n(h);if(!Array.isArray(f)||f.some(m=>typeof m!="string"))throw new c("backup prune requires a `confirm` array of the sidecar keys to remove — read them from `GET /_lunora/admin/backup/retention` and pass back the ones you mean to delete",{code:"BAD_REQUEST",status:400});return Response.json(await Go(t,f),{headers:{"cache-control":"no-store"}})};return{[Wo]:u,[Qo]:i}},Bt=500,Vo=(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}},Jo=(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}=Vo(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 f=n.get(h)??[];f.push(u),n.set(h,f)}return n},Yo="/_lunora/admin/export",qo="/_lunora/admin/import",Xo="/_lunora/admin/sync",Zo="/_lunora/admin/connector/sync",es="/_lunora/admin/apply",ts="/_lunora/admin/export-tap/run",ns=new TextEncoder,rs=async e=>{const n=await ne(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const 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}},Fe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,os=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:o,exportSinks:s,knownTables:i,queryCoordinator:u,assertAdmin:h,resolveForwardContext:f,shardDO:m,prepareExportRows:b,streamingImport:S,syncGlobals:T}=e,k=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await rs(E),{headers:K}=await f(E,j),W=await b(K,U.tables),J=new ReadableStream({async pull(Y){try{for await(const G of W)Y.enqueue(ns.encode(`${JSON.stringify(G)}
4
+ `));Y.close()}catch(G){Y.error(G)}}});return new Response(J,{headers:{"content-type":"application/x-ndjson"},status:200})},w=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),K=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},W=typeof U.epochs=="object"&&U.epochs!==null?U.epochs:{},J=typeof U.limit=="number"?U.limit:void 0,Y=typeof U.globalCursor=="number"?U.globalCursor:0,G=Fe(U.tables),{headers:re}=await f(E,j),Q=G??i(),de=await u.orchestrateCdcSync(m,{cursors:K,defaultShardKey:n,epochs:W,headers:re,limit:J,tables:Q}),oe=T?await T({limit:J,sinceSeq:Y}):void 0;return Response.json({global:oe,shards:de.shards},{status:200})},g=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),K=Kr(U.cursor),W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables),{headers:Y}=await f(E,j),G=J??i(),re=await u.orchestrateCdcSync(m,{cursors:K.s,defaultShardKey:n,headers:Y,limit:W,tables:G}),Q=[],de={...K.s};let oe=!1;for(const ae of re.shards)oe=St(Q,ae.changes??[],Gr(W))||oe,de[ae.shardKey]=ae.cursor;let be=K.g;if(T){const ae=await T({limit:W,sinceSeq:K.g});oe=St(Q,ae.changes,W)||oe,be=ae.cursor}const z=Fr({g:be,s:de,v:1}),se={changes:Q,hasMore:oe,nextCursor:z};return Response.json(se,{status:200})},y=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const U=await ee(E),W=(Array.isArray(U.batches)?U.batches:[]).map(Q=>Q).filter(Q=>Q!==null&&typeof Q=="object"&&typeof Q.shardKey=="string"&&Array.isArray(Q.changes)),J=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:Y}=await f(E,j),G=await u.orchestrateApplyCdc(m,{batches:W,headers:Y}),re=J.length>0&&t?await t({changes:J}):0;return Response.json({applied:G.applied+re,failed:G.failed,ok:G.ok},{status:200})},v=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;h(E);const{headers:U}=await f(E,j),K=await S(E,U);return Response.json(K,{headers:{"content-type":"application/json"},status:K.failed.length>0?207:200})},I=async(E,j)=>{const H=we(E,["POST"]);if(H)return H;if(h(E),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 U=await ee(E),K=typeof U.sink=="string"?U.sink:void 0,W=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,J=Fe(U.tables);if(K===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const Y=s[K];if(Y===void 0)throw new c(`Export-tap sink "${K}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:G}=await f(E,j),re=J??i(),Q=await $r({coordinator:u,cursorStore:o,defaultShardKey:n,headers:G,limit:W,shardDO:m,sink:Y,tables:re});return Response.json(Q,{headers:{"content-type":"application/json"},status:200})};return{[es]:y,[Zo]:g,[Yo]:k,[ts]:I,[qo]:v,[Xo]:w}},ss=(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}},as=(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}},is=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 f=e.body.getReader(),m=new TextDecoder;let b="",S=0;const T=k=>{h+=1;const w=k.trim();if(w.length===0)return;u+=1;const g=ss(w,h);if(!g.ok){o.push(g.error);return}const{doc:y,table:v}=g,I=t.resolveTableSharding?.(v);if(I?.mode.kind==="global"){s.push({doc:y,line:h,table:v});return}const E=as(y,v,I,n,h);if(!E.ok){o.push(E.error);return}const j=i.get(E.shardKey);j?j.rows.push({doc:y,table:v}):i.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:h})};for(;;){const{done:k,value:w}=await f.read();if(k)break;if(w&&(S+=w.byteLength,S>rn))throw await f.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});b+=m.decode(w,{stream:!0});let g=b.indexOf(`
5
+ `);for(;g!==-1;){const y=b.slice(0,g);b=b.slice(g+1),T(y),g=b.indexOf(`
6
+ `)}}return b.length>0&&T(b),{errors:o,globalRows:s,perShard:i,received:u}},cs=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},ds=async(e,t,n,o,s)=>{const i=t.defaultShardKey??"__root__",{errors:u,globalRows:h,perShard:f,received:m}=await is(e,t,i),b={conflicts:0,errors:u,failed:[],inserted:{}},S=[];if(t.resolveTableSharding===void 0&&f.size>0&&S.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 T=await n.orchestrateImport(s,{batches:[...f.values()],headers:o});xt(b,T),b.failed.push(...cs(T.shards))}if(h.length>0)if(t.importGlobals){const T=h[0]?.line??1,k=await t.importGlobals({rows:h,startLine:T});xt(b,k)}else for(const T of h)b.errors.push({code:"GLOBAL_NOT_CONFIGURED",line:T.line,message:`row targets global table "${T.table}" but no \`importGlobals\` is configured`,table:T.table});return{conflicts:b.conflicts,errors:b.errors,failed:b.failed,inserted:b.inserted,received:m,...S.length>0?{warnings:S}:{}}},us=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=e=>typeof e=="object"&&e!==null?e:{},Qe=e=>typeof e.kind=="string"?e.kind:"unknown",ls=(e,t)=>{let n=Ge(t),o=!1;Qe(n)==="optional"&&(o=!0,n=Ge(n._meta?.inner));const s=Qe(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=Qe(Ge(i.inner));h!=="unknown"&&(u.element=h)}return u},hs=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>ls(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),fs="/_lunora/admin/functions",ps="/_lunora/admin/cron-jobs",ms="/_lunora/admin/architecture",ws="/_lunora/admin/openapi",gs="/_lunora/admin/openrpc",ys="/_lunora/admin/global/tables",bs="/_lunora/admin/global/table",_s="/_lunora/admin/global/facet",Ht=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(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},Rs=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:{}}),Es=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"}),Ss=e=>{const{assertAdmin:t,options:n,parsePaging:o,queryParameter:s,requireAdminOption:i}=e,u=w=>{M(w,"GET","Functions");const g=i(w,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.visibility==="internal"||I.kind==="stream"?[]:[{args:hs(I.args),kind:I.kind,path:v}]).toSorted((v,I)=>v.path.localeCompare(I.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},h=w=>{M(w,"GET","Cron-jobs");const g=i(w,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(g).flatMap(([v,I])=>I.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,I)=>v.name.localeCompare(I.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},f=w=>(M(w,"GET","Architecture"),t(w),Response.json(n.architecture??us,{headers:{"content-type":"application/json"},status:200})),m=w=>(M(w,"GET","OpenAPI"),t(w),Response.json(n.openApiSpec??Rs,{headers:{"content-type":"application/json"},status:200})),b=w=>(M(w,"GET","OpenRPC"),t(w),Response.json(n.openRpcSpec??Es,{headers:{"content-type":"application/json"},status:200})),S=async w=>{M(w,"GET","Global-tables");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await g.listTables(),{headers:{"content-type":"application/json"},status:200})},T=async w=>{M(w,"GET","Global-table");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=s(y,"table");if(v===void 0)throw new c("Global-table endpoint requires a `table` query param",{code:"BAD_REQUEST",status:400});const I=await g.readTablePage({...o(w),filters:Ht(s(y,"filters")),table:v});return Response.json(I,{headers:{"content-type":"application/json"},status:200})},k=async w=>{M(w,"GET","Global-facet");const g=i(w,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(w.url),v=s(y,"table"),I=s(y,"column");if(v===void 0||I===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(y,"limit"),j=E===void 0?void 0:Number(E),H=await g.facetColumn({column:I,filters:Ht(s(y,"filters")),limit:j!==void 0&&Number.isFinite(j)?j:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[ps]:h,[fs]:u,[_s]:k,[bs]:T,[ys]:S,[ms]:f,[ws]:m,[gs]:b}},Ts="/_lunora/admin/kv/namespaces",As="/_lunora/admin/kv/keys",gn="/_lunora/admin/kv/value",yn=32*1048576,Lt=60,Os=e=>{const{readJsonBody:t,requireAdminOption:n}=e,o=w=>n(w,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=w=>Response.json(w,{headers:{"content-type":"application/json"},status:200}),i=(w,g)=>{const y=new URL(w.url),v=y.searchParams.get("namespace")??"",I=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${g} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(I==="")throw new c(`KV-value ${g} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:I,namespace:v}},u=async(w,g)=>{if(!(await w.listNamespaces()).some(v=>v.binding===g))throw new c(`Unknown KV namespace binding \`${g}\``,{code:"NOT_FOUND",status:404})},h=async w=>(M(w,"GET","KV-namespaces"),s({namespaces:await o(w).listNamespaces()})),f=async w=>{M(w,"GET","KV-keys");const g=o(w),y=new URL(w.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,E=y.searchParams.get("cursor")??void 0,j=y.searchParams.get("limit"),H=j===null?void 0:Number.parseInt(j,10);if(H!==void 0&&(!Number.isInteger(H)||H<1))throw new c("KV-keys `limit` must be a positive integer",{code:"BAD_REQUEST",status:400});const U=H===void 0?void 0:Math.min(H,1e3);return await u(g,v),s(await g.listKeys({cursor:E,limit:U,namespace:v,prefix:I}))},T={DELETE:async w=>{const g=o(w),y=i(w,"DELETE");return await u(g,y.namespace),await g.deleteKey(y),s({deleted:!0})},GET:async w=>{const g=o(w),y=i(w,"GET");return await u(g,y.namespace),s(await g.getValue(y))},PUT:async w=>{const g=o(w),y=await t(w,yn);if(typeof y.namespace!="string"||y.namespace==="")throw new c("KV-value PUT request requires a `namespace` string",{code:"BAD_REQUEST",status:400});if(typeof y.key!="string"||y.key==="")throw new c("KV-value PUT request requires a `key` string",{code:"BAD_REQUEST",status:400});if(typeof y.value!="string")throw new c("KV-value PUT request requires a `value` string",{code:"BAD_REQUEST",status:400});if(y.expirationTtl!==void 0&&(typeof y.expirationTtl!="number"||!Number.isInteger(y.expirationTtl)||y.expirationTtl<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(g,y.namespace),await g.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),s({ok:!0})}},k=w=>{const g=T[w.method];if(!g)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return g(w)};return{[Ts]:h,[As]:f,[gn]:k}},vs="/_lunora/migrate",Is="/_lunora/admin/pitr",ks="/_lunora/admin/rank",Ps="/_lunora/admin/rankpage",Ds="/_lunora/admin/shard-registry/prune",Ns="/_lunora/admin/shard-traffic",Us=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),Cs=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),Bs=async e=>{const n=await ne(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"||!Us.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}},xs=async e=>{const n=await ne(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}},Ls=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})},js=async e=>{const n=await ne(e,"Rank page")??{};Ls(n);const o=Hs(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}},Ms=async e=>{const n=await ne(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}},$s=async e=>{const n=await ne(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(o=>typeof o=="string")))throw new c("Shard-registry prune `tables` must be an array of table names",{code:"BAD_REQUEST",status:400});return{dryRun:n.dryRun===!0,tables:n.tables}},Ks=async e=>{const n=await ee(e);if(typeof n.functionPath!="string"||!Cs.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}},Fs=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:o,queryCoordinator:s,resolveForwardContext:i,shardDO:u,shardedTables:h}=e,f=(g,y)=>{if(g.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!o(g))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(g,y)=>{f(g,"Migration");const v=await Bs(g),{headers:I}=await i(g,y),E=await s.orchestrateMigration(u,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},b=async(g,y)=>{f(g,"Rank");const v=await xs(g),{headers:I}=await i(g,y),E=await s.orchestrateRank(u,{headers:I,index:v.index,partitionKey:v.partitionKey,rowId:v.rowId,sortValues:v.sortValues,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(g,y)=>{f(g,"Rank page");const v=await js(g),{headers:I}=await i(g,y),E=await s.orchestrateRankPage(u,{...v,headers:I});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},T=async(g,y)=>{f(g,"Shard-traffic");const v=await Ms(g),{headers:I}=await i(g,y),E=await s.orchestrateShardTraffic(u,{headers:I,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},k=async(g,y)=>{f(g,"Shard-registry prune");const v=await $s(g),I=h(),E=(v.tables??[]).filter(U=>!I.includes(U));if(E.length>0)throw new c(`Shard-registry prune names tables that are not \`.shardBy()\`: ${E.join(", ")}`,{code:"BAD_REQUEST",status:400});const{headers:j}=await i(g,y),H=await Yr(s.registry,u,{dryRun:v.dryRun,headers:j,tables:v.tables??I});return Response.json(H,{status:H.failed.length>0?207:200})},w=async(g,y)=>{if(M(g,"POST","PITR"),!o(g))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await Ks(g),{headers:I}=await i(g,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:I,method:"POST"});return n(u,v.shardKey??t,E)};return{[vs]:m,[Is]:w,[ks]:b,[Ps]:S,[Ds]:k,[Ns]:T}},Gs=1,Qs=0,Ws=32,zs=512,Vs=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,Js=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>zs)return;const n=t.split(",");if(!(n.length>Ws)){for(const o of n)if(!Vs.test(o.trim()))return;return t}},Ys=e=>{const t=Sr(e.headers.get("traceparent"));if(t===void 0)return;const n=Js(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},jt=(e,t={})=>{const n=Ys(e),o=t.trustInbound===!0?n:void 0,s=ge(8),i=o?.traceId??ge(16),u=Ir(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?Gs:Qs,traceId:i,...o?.parentSpanId===void 0?{}:{parentSpanId:o.parentSpanId},...o?.traceState===void 0?{}:{traceState:o.traceState}}}},Mt=(e,t)=>{t.traceparent=nn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState)},qs=(e,t)=>{let n;return()=>{if(n===void 0){const o=vr(e),s=t===void 0?void 0:t.cf;n=Tr(Or(o),Ar(o,s))}return n}},Xs="/_lunora/admin/scheduled",Zs="/_lunora/admin/scheduled/status",ea="/_lunora/admin/scheduled/ws",ta="/_lunora/admin/scheduled/cancel",na="/_lunora/admin/scheduled/dead",ra="/_lunora/admin/scheduled/dead/retry",oa="/_lunora/admin/scheduled/dead/cancel",sa="/_lunora/admin/scheduled/pool/release",aa=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:o,schedulerInstanceName:s}=e,i=(m,b)=>S=>{if(S.method!=="GET")throw new c(`${b} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const T=new URL(S.url).searchParams.get("cursor"),k=T===null||T===""?"":`?cursor=${encodeURIComponent(T)}`;return o(S).fetch(new Request(`https://scheduler.internal${m}${k}`,{method:"GET"}))},u=(m,b,S=b)=>async T=>{if(T.method!=="POST")throw new c(`${S} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const k=o(T),w=await ne(T,b);if(typeof w?.id!="string"||w.id==="")throw new c(`${b} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return k.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:w.id}),headers:{"content-type":"application/json"},method:"POST"}))},h=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const b=o(m),S=await ne(m,"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 b.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"}))},f=async m=>{if(m.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});if(!await t(m))throw new c("admin authorization required",{code:"ADMIN_FORBIDDEN",status:403});const b=n();return ye(b,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[ta]:u("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[oa]:u("/dead/cancel","Scheduled dead-letter action"),[na]:i("/dead","Scheduled dead-letter"),[ra]:u("/dead/retry","Scheduled dead-letter action"),[Xs]:i("/list","Scheduled-list"),[sa]:h,[Zs]:i("/status","Scheduler-status"),[ea]:f}},ia="/_lunora/scheduled",bn="/_lunora/queue",_n=16*1048576,ca=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:o}=e,s=async(u,h,f)=>{if(t(u),u.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await ne(u,"Scheduled tick"),b=typeof m?.cron=="string"?m.cron:"";if(b==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:b,noRetry:()=>{},scheduledTime:Date.now()},h,f),Response.json({cron:b,ok:!0})},i=async(u,h,f)=>{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 m=await ne(u,"Queue dispatch",_n);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const b=typeof m.queue=="string"?m.queue:"",S=m.messages.filter(k=>typeof k=="object"&&k!==null&&typeof k.id=="string").map(k=>({body:k.body,id:k.id})),T=await o({messages:S,queue:b},h,f);return Response.json({retry:T?.retry??[]})};return{[bn]:i,[ia]:s}},da=(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},et={mtls:e=>da(e,"tlsClientAuth","certVerified")==="SUCCESS"},ua=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(et,e)?et[e]:void 0)??(()=>!1),la=e=>typeof e=="string"&&Object.hasOwn(et,e),ha=e=>{const t=la(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.`))}},fa="/_lunora/admin/vector/indexes",pa="/_lunora/admin/vector/query",ma=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 f=await t(i);if(typeof f.name!="string"||f.name==="")throw new c("Vector-query request requires a `name` string",{code:"BAD_REQUEST",status:400});if(typeof f.text!="string"||f.text==="")throw new c("Vector-query request requires a `text` string",{code:"BAD_REQUEST",status:400});if(f.topK!==void 0&&(typeof f.topK!="number"||!Number.isInteger(f.topK)||f.topK<1))throw new c("Vector-query `topK` must be a positive integer",{code:"BAD_REQUEST",status:400});const m=await u.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[fa]:o,[pa]:s}},wa="/_lunora/admin/workflows/instances",ga="/_lunora/admin/workflows/instance",ya="/_lunora/admin/workflows/status",ba={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},_a=e=>e!==null&&Object.hasOwn(ba,e)?e:void 0,$t=(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},We=(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})},Ra=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,o=async(u,h,f)=>{M(u,"GET","Workflows instances"),t(u);const m=n(h);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const b=We(f,"name"),S=_a(f.searchParams.get("status"));return Response.json(await m.listInstances({page:$t(f,"page"),perPage:$t(f,"perPage"),status:S,workflowName:b}))},s=async(u,h,f)=>{M(u,"GET","Workflows instance"),t(u);const m=n(h);return m?Response.json(await m.getInstance({instanceId:We(f,"id"),workflowName:We(f,"name")})):Kt()},i=async(u,h)=>{M(u,"POST","Workflows status"),t(u);const f=n(h);if(!f)return Kt();const m=await ne(u,"Workflows status");if(typeof m?.name!="string"||m.name===""||typeof m.id!="string"||m.id==="")throw new c("Workflows status action requires string `name` and `id`",{code:"BAD_REQUEST",status:400});const{action:b}=m;if(b!=="pause"&&b!=="resume"&&b!=="terminate")throw new c("Workflows status action must be one of: pause, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:b,instanceId:m.id,workflowName:m.name}))};return{[ga]:s,[wa]:o,[ya]:i}},Ea={[gn]:yn,[bn]:_n,[Mr]:jr},Ft="/_lunora/rpc",Sa="/_lunora/rpc-batch",Ta="/_lunora/ws",Re=(e,t,n)=>({resourceAttributes:qs(e,t),...n===void 0?{}:{waitUntil:n}}),ze=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}}),Ve=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/",Aa="/_lunora/scheduler/dispatch",Oa="/_lunora/admin/cron-jobs/run",va="/_lunora/admin/ws-token",Ia="/_lunora/admin/",Ne="/_lunora/",ka="/_lunora/migrate",Pa="/_lunora/status",Da=e=>e.startsWith(Ia)||e===ka,Na="__lunora_relation__:",ve=e=>{if(e.startsWith(Na))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ie=async e=>await e===!0,Wt=(e,t)=>{const n=e.headers.get(gt);if(n===null)return;const o=Er(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})},Ua=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",Ca="__lunora_admin__:recordAuthEvent",Vt="__lunora_admin__:listPushSubscriptions",Ba=["/sign-in","/sign-up","/callback"],xa=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const o=e.slice(n.length);return Ba.some(s=>o===s||o.startsWith(`${s}/`))},Jt=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},ke=(e,t,n,o)=>{const s=pr(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}:{}}},Rn=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},En=({identity:e})=>e!==null&&br(Rn(e)),Ha=e=>{if(En(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},La=e=>{if(!En(e))return e;const t={...e.headers};return delete t["x-lunora-identity"],delete t["x-lunora-identity-exp"],delete t["x-lunora-userid"],{claims:null,headers:t,identity:null,userId:null}},Yt=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,ja=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},tt=new WeakMap,Ma=async(e,t,n,o,s=tt.get(e))=>{const i={"content-type":"application/json"},u=e.headers.get("authorization"),h=e.headers.get("cookie"),f=e.headers.get("x-d1-bookmark"),m=e.headers.get("x-lunora-mutation-id"),b=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),f&&(i["x-d1-bookmark"]=f),m&&(i["x-lunora-mutation-id"]=m),b&&(i["x-lunora-client-id"]=b),S&&(i["x-lunora-client-seq"]=S),T&&(i["x-lunora-base-seq"]=T);const k=Ur(e.headers,o);if(k&&(i["x-lunora-client-ip"]=k),i["x-lunora-origin"]=new URL(e.url).origin,!n)return{claims:null,headers:i,identity:null,userId:null};const w=await n(e,t,s);if(!w||typeof w.userId!="string"||w.userId.length===0)return{claims:null,headers:i,identity:null,userId:null};i["x-lunora-userid"]=_r(w.userId);const g=Rn(w);g!==void 0&&(i["x-lunora-identity-exp"]=String(g));const{userId:y,...v}=w,I=Object.keys(v).length>0?v:null;return I&&(i["x-lunora-identity"]=Rr(I)),{claims:I,headers:i,identity:w,userId:y}},$a=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),Ka=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"||!$a.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},Fa=(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}},Ga=async e=>{const t=await sn(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const o=n;if(o.args!==void 0&&on(o.args,"RPC"),o.shardKey!==void 0&&typeof o.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,i=Ka(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,Qa=5e3,Wa=4096,za=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 tn(Pe,Wa),Pe.set(t,{expiresMs:n+Qa,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"],Ja=(e,t)=>{for(const n of Va){e.delete(n);const o=t[n];o!==void 0&&e.set(n,o)}},Xt=(e,t)=>{const n=new Headers(e.headers),o=[...n.keys()];for(const s of o)s.startsWith("x-lunora-")&&n.delete(s);return Ja(n,t),n},Ya=async(e,t,n)=>e.length===0||n.length===0?!1:ot(await un(e,t),n),Zt=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[o,...s]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:ot(t,s.join(" ").trim())},en=async(e,t,n)=>{if(!t||t.length===0)return!1;const o=new URL(e.url).searchParams.get("token");return o===null?!1:await Io(t,o)?!0:n?!1:ot(t,o)},qa=(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 zr(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return je(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return je(`queue:${e}`,!0);if(typeof n.connectionString=="string")return je(`hyperdrive:${e}`,!0)},Xa=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})},Za=e=>{if(e.x402Charge!==void 0&&e.functions===void 0)throw new c("`x402Charge` requires `functions`: paid (.x402) procedures are read from the function registry, so without it every paid procedure would dispatch FREE. Build the worker with `defineApp()` (which supplies the registry) or pass `functions` explicitly.",{code:"MISCONFIGURED",status:500})},Sn=e=>{Za(e);const t=ua(e.trustInboundTraceContext),n=ha(e.trustInboundTraceContext),o=e.defaultShardKey??"__root__",s=e.queryCoordinator??qr({registry:Xr(e.resolveTableSharding,o)}),i=Vr(e.resolveIdentity,e.identity),u=Me(e.shardDO,e.jurisdiction),h=e.schedulerDO===void 0?void 0:Me(e.schedulerDO,e.jurisdiction),f=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([r,a])=>[r,Me(a,e.jurisdiction)]));let m=!1;const b=r=>{if(r===void 0||e.jurisdiction===void 0)return r;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},S=async(r,a,l,d=e.shardRegion?.(a))=>ye(r,a,b(d)).fetch(l);let T;const k=()=>e.adminToken??T;let w;const g=()=>e.requireEphemeralWsToken??w??!0;let y;const v=r=>{const a=r??{};if(y??=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=Ao(d,!0))}if(T!==void 0||e.adminToken!==void 0)return;const l=a.LUNORA_ADMIN_TOKEN;typeof l=="string"&&l.length>0&&(T=l)},I=new WeakSet,E=r=>Zt(r,k())||I.has(r),j=async r=>{if(!(e.adminGate===void 0||I.has(r)))try{await Ie(e.adminGate(r,tt.get(r)))&&I.add(r)}catch{}},H=async(r,a,l,d)=>{const p=await Ma(r,a,l,e.trustedClientIpHeader,d);return e.functions!==void 0&&(p.headers[bt]=yt),p},U=async(r,a,l,d)=>Ha(await H(r,a,l,d)),K=async(r,a)=>{const l=await H(r,a,e.resolveIdentity);if(I.has(r)&&l.headers.authorization===void 0){const d=k();d!==void 0&&(l.headers.authorization=`Bearer ${d}`)}return l};let W=!1,J=!1;const Y=()=>{J||(J=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},G=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})}W||(W=!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("")))},re=async(r,a,l=!1)=>{if(a.includes(qe)||a.includes(Xe))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!l)if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:r,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==o&&G("shard")},Q=Fs({defaultShard:o,forwardToShard:S,isAdmin:E,queryCoordinator:s,resolveForwardContext:K,shardDO:u,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(r=>e.resolveTableSharding?.(r)?.mode.kind==="shardBy")}),de=async(r,a,l,d,p,R)=>{ve(r);const A={"content-type":"application/json",[bt]:yt,"x-lunora-system":"1"};return p?.userId!==void 0&&p.userId.length>0&&(A["x-lunora-userid"]=p.userId),p?.identity!==void 0&&p.identity.length>0&&(A["x-lunora-identity"]=p.identity),d!==void 0&&d.length>0&&(A["x-lunora-mutation-id"]=d),R!==void 0&&R.length>0&&(A.traceparent=R),S(u,l,De(r,a,A))},oe=async(r,a,l,d,p)=>{const R=Eo(l.env,l.context?.exports,r,["create"]);if(R===void 0)throw new c(`${d} targets workflow "${r}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(no(a))throw new c(`${d} params ${ro}`,{code:"BAD_REQUEST",status:400});try{await R.create(p===void 0?{params:a}:{id:p,params:a})}catch(A){if(!ao(A))throw A}},be=async(r,a,l,d)=>{if(r.workflow){await oe(r.workflow,r.args??{},{context:l,env: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 p=await de(r.functionPath,r.args??{},r.shardKey??o,void 0,void 0,d);if(!p.ok)throw new c(`cron job "${r.name}" (${r.functionPath}) failed with shard status ${String(p.status)}`,{code:"CRON_JOB_FAILED",status:500})},z=r=>{if(!E(r))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},se=(r,a,l)=>{if(z(r),a===void 0)throw new c(l.message,{code:l.code,status:400});return a},ae=async(r,a,l,d,p,R)=>{const A=e.cronJobs?.[r];if(!A)return 0;for(const P of A)try{await be(P,a,l,R)}catch(D){d.push(p(D))}return A.length},Tn=async(r,a,l)=>{if(z(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 d=await ee(r),p=typeof d.name=="string"?d.name:"";if(p==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const R=Object.values(e.cronJobs).flat().find(A=>A.name===p);if(!R)throw new c(`no cron job named "${p}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await be(R,a,l),Response.json({name:p,ran:!0},{status:200})},it=async r=>{const a=typeof r.pool=="string"&&r.pool.length>0?r.pool:void 0;if(!a||!h||typeof r.id!="string")return;const l=typeof r.instanceName=="string"&&r.instanceName.length>0?r.instanceName:"default";try{await ye(h,l).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:r.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},An=async(r,a,l)=>{M(r,"POST","Scheduler dispatch");const d=await sn(r),p=a??{},R=typeof p.LUNORA_SCHEDULER_SECRET=="string"?p.LUNORA_SCHEDULER_SECRET:void 0,A=e.adminToken??(typeof p.LUNORA_ADMIN_TOKEN=="string"?p.LUNORA_ADMIN_TOKEN:void 0),P=r.headers.get("x-lunora-scheduler-signature");let D=!1;if(P&&R?D=await Ya(R,d,P):A&&(D=Zt(r,A)),!D)throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let O;try{O=JSON.parse(d)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const _=O??{},B=_.args??{},L=typeof _.id=="string"&&_.id.length>0?_.id:void 0;if(typeof _.workflow=="string"&&_.workflow.length>0)return await oe(_.workflow,B,{context:l,env:a},"scheduled workflow",L),await it(_),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 V=typeof _.shardKey=="string"&&_.shardKey.length>0?_.shardKey:o,x=Ua(r),ue=await de(_.functionPath,B,V,L,x,r.headers.get("traceparent")??void 0);return await it(_),ue},On=No({assertAdmin:z,getReader:()=>e.authAuditReader}),vn=Uo({assertAdmin:z,getMove:()=>e.authJurisdictionMove}),In=async(r,a)=>{z(r);const l=e.notifySubscriptionStore;if(l===void 0)return Response.json({result:Ee({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const d=a?.kind,p=a?.userId,R=a?.limit,A=d==="fcm"||d==="web-push"?d:void 0,P=typeof p=="string"&&p!==""?p:void 0,D=typeof R=="number"&&Number.isFinite(R)?Math.trunc(R):0,O=D>0?Math.min(D,1e3):1e3,B=(await l.list({kind:A,limit:O,userId:P})).filter(L=>A!==void 0&&L.kind!==A?!1:P===void 0||(L.userId??null)===P).map(({keys:L,token:V,...x})=>x);return Response.json({result:Ee({subscriptions:B})},{headers:{"content-type":"application/json"},status:200})},kn=async(r,a)=>{if(!a.fanOut&&!(a.functionPath!==kt&&a.functionPath!==Vt&&a.functionPath!==Ze&&a.functionPath!==fn))return await j(r),a.functionPath===kt?On(r,a.args??{}):a.functionPath===Vt?In(r,a.args):vn(r,a.functionPath,a.args??{})},Pn=os({applyGlobals:e.applyGlobals,assertAdmin:z,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:o,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:K,shardDO:u,prepareExportRows:async(r,a)=>pn(e,s,r,a,u),streamingImport:(r,a)=>ds(r,e,s,a,u),syncGlobals:e.syncGlobals}),Ue=(r,a)=>{const l=r.searchParams.get(a);return l===null||l===""?void 0:l},Ce=r=>{const a=new URL(r.url),l=a.searchParams.get("limit"),d=a.searchParams.get("offset"),p=l===null?void 0:Number.parseInt(l,10),R=d===null?void 0:Number.parseInt(d,10);return{limit:p!==void 0&&Number.isFinite(p)&&p>=0?p:void 0,offset:R!==void 0&&Number.isFinite(R)&&R>=0?R:void 0}},ct=()=>{if(h===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return h},Dn=aa({checkWsAdmin:async r=>E(r)||en(r,k(),g()),requireSchedulerNamespace:ct,resolveSchedulerStub:r=>(z(r),ye(ct(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Nn=Ra({assertAdmin:z,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Un=Lr({assertAdmin:z,parsePaging:Ce,queryParameter:Ue,readBodyBytes:Dr,requireAdminOption:se,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Cn=zo({options:e,readJsonBody:ee,requireAdminOption:se}),Bn=ma({readJsonBody:ee,requireAdminOption:se,vectorIntrospector:e.vectorIntrospector}),xn=Os({kvIntrospector:e.kvIntrospector,readJsonBody:ee,requireAdminOption:se}),Hn=Jr({logArchive:e.logArchive,readJsonBody:ee,requireAdminOption:se}),Ln=Ss({assertAdmin:z,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:Ce,queryParameter:Ue,requireAdminOption:se}),jn=r=>{const a=[],l=u??r?.SHARD;if(l!==void 0&&a.push(Wr("durable-object:default",l,o)),e.health?.disableBindingProbes!==!0)for(const[d,p]of Object.entries(r??{})){const R=qa(d,p);R!==void 0&&a.push(R)}for(const d of e.health?.probes??[])a.push(d);return a},Mn=Qr({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:E,resolveProbes:jn}),$n=r=>{const a=O=>"args"in O?{...O,args:Ye(O.args)}:O,l=e.schedulerInstanceName??"default",d=()=>ye(r,l),p=async(O,_)=>{const B=await d().fetch(new Request(`https://scheduler.internal${O}`,_));if(!B.ok)throw new c(`ctx.scheduler: SchedulerDO ${O} failed (${String(B.status)}): ${await B.text()}`,{code:"INTERNAL",status:500});return await B.json()},R=async(O,_)=>await p(O,{body:JSON.stringify(_),headers:{"content-type":"application/json"},method:"POST"}),A=O=>{const _=O;if(_==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 _.binding=="string"&&_.binding.length>0)return{workflow:_.binding};if(typeof _.__lunoraRef=="string")return{functionPath:_.__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 oo(async _=>p(_===void 0?"/list":`/list?cursor=${encodeURIComponent(_)}`,{method:"GET"}))).map(_=>a(_)),D=async(O,_,B={})=>{const L=A(_),{id:V}=await R("/schedule",{args:kr("ctx.scheduler",String(L.functionPath??L.workflow),B),scheduledFor:Math.ceil(O),...L});return V};return{cancel:async O=>await R("/cancel",{id:O}),get:async O=>{const _=await p(`/get?id=${encodeURIComponent(O)}`,{method:"GET"});return _.record===void 0?null:a(_.record)},list:P,runAfter:async(O,_,B)=>{if(!Number.isFinite(O)||O<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(Date.now()+O,_,B)},runAt:async(O,_,B)=>{if(!Number.isFinite(O))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await D(O,_,B)}}},Kn=async(r,a,l)=>{const{claims:d,headers:p,userId:R}=La(await H(r,a,i)),A=Re(a,r,O=>l.waitUntil?.(O)),P=O=>async(_,B={})=>{const L=_.__lunoraRef;if(typeof L!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(L);const V=await Te(r,L,Ee(B),O,{...p,"x-lunora-system":"1"},A),x=await V.json();if(x.error)throw new c(x.error.message??"shard RPC failed",{code:x.error.code??"INTERNAL",status:V.status});return Ye(x.result)},D=P(o);return{auth:{getIdentity:()=>Promise.resolve(d),userId:R},cache:l.cache,fetch:globalThis.fetch.bind(globalThis),forShard:O=>{const _=P(O);return{runAction:_,runMutation:_,runQuery:_}},runAction:D,runMutation:D,runQuery:D,...h===void 0?{}:{scheduler:$n(h)},...l.waitUntil===void 0?{}:{waitUntil:l.waitUntil.bind(l)},...e.storage===void 0?{}:{storage:to(e.storage(a,new URL(r.url).origin))}}},Fn=async(r,a,l)=>{if(!e.httpRouter)return;const d=await Kn(r,a,l);try{return await e.httpRouter.fetch(r,{...a,__lunoraCtx:d},l)}catch(p){return console.error("[lunora] httpRouter (SSR) handler threw:",p),new Response("Internal Server Error",{status:500})}},Gn=async(r,a,l)=>{if(r.headers.get("Upgrade")!=="websocket")throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const d=At(r,ie);if(d)return d;const p=l.searchParams.get("shard")??o,{headers:R,identity:A}=await H(r,a,i),P=E(r)||await en(r,k(),g());await re(A,p,P);const D=Xt(r,R),O=qt(a,e.shardDO);if(O!==void 0){D.set("x-lunora-shard-binding",O);const _=await za(u,p);if(_>0){const B=yo(p,Math.floor(Math.random()*_));return S(u,B,new Request(r,{headers:D}),Ot(r))}}return S(u,p,new Request(r,{headers:D}))},Qn=async(r,a,l)=>{if(f===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=At(r,ie);if(d)return d;let p;try{p=decodeURIComponent(l.pathname.slice(Qt.length))}catch{return new Response("Unknown voice agent",{status:404})}const R=Object.hasOwn(f,p)?f[p]:void 0;if(R===void 0)return new Response("Unknown voice agent",{status:404});const A=l.searchParams.get("threadKey");if(A===null||A.length===0)return new Response("Missing threadKey",{status:400});const{headers:P,identity:D}=await H(r,a,i);if(e.authorizeShard){if(!await Ie(e.authorizeShard({identity:D,shardKey:A})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else G("shard");const O=Xt(r,P);return S(R,A,new Request(r,{headers:O}))},Wn=async(r,a,l)=>{if(e.authorizeFanOut){if(!await Ie(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});G("fan-out")},Se=async(r,a)=>{if(!(!r.fanOut&&r.functionPath.startsWith("__lunora_admin__:"))){if(r.fanOut){await Wn(r.fanOut,r.functionPath,a);return}await re(a,r.shardKey??o)}},zn=(r,a,l)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){Y();return}if(e.functions[a]?.kind!=="query"||l.includes(Xe)||l.includes(qe))return;const d=Ot(r);return d===void 0?void 0:{name:bo(l,d),region:d}},Vn=async(r,a,l,d,p)=>{const R=zn(r,a,d);if(R!==void 0){const A={...p,"x-lunora-replica-read":"1",...y===void 0?{}:{"x-lunora-shard-binding":y}},P=_o(r.headers.get("x-lunora-min-seq"));P!==void 0&&(A["x-lunora-min-seq"]=String(P));const D=await S(u,R.name,De(a,l,A),R.region);if(D.status!==421)return D}return S(u,d,De(a,l,p))},Te=async(r,a,l,d,p,R)=>{const A=Date.now(),{observability:P,sampling:D}=e,O=Ve(r),{decision:_,ignoredUpstream:B,trace:L}=jt(r,{...D===void 0?{}:{sampling:D},trustInbound:t(r)});B&&n(r);const V={...p,[Rt]:_.keepErrors?"1":"0"};Mt(L,V);try{const x=await Vn(r,a,l,d,V);ce(P,{...O,...Gt(L),durationMs:Date.now()-A,functionPath:a,ok:x.ok,shardKey:d,...x.ok?{}:{error:{code:"SHARD_ERROR",message:`shard returned ${String(x.status)}`,status:x.status}}},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors});const ue=new Response(x.body,{headers:x.headers,status:x.status,statusText:x.statusText});return ue.headers.set("x-lunora-shard-key",d),ue}catch(x){throw ce(P,{...O,...Gt(L),...ke(a,Date.now()-A,x,{shardKey:d})},R,void 0,{isTraced:L.sampled,keepErrors:_.keepErrors}),x}},Jn=r=>{if(r.fanOut&&r.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});r.fanOut||ve(r.functionPath)},Yn=async(r,a,l)=>{M(r,"POST","RPC");const d=await Ga(r);Fa(a,d),Jn(d);const p=await kn(r,d);if(p!==void 0)return p;const{headers:R,identity:A}=await U(r,a,i);Wt(r,A),await Se(d,A);const P=Je(d,e);{const D=Date.now(),{observability:O}=e,_=Ve(r),B=Re(a,r,l&&(x=>l.waitUntil?.(x)));if(d.fanOut)try{const x=await s.fanOut(u,{args:d.args??{},fanOut:d.fanOut,functionPath:d.functionPath,headers:R});return ce(O,{durationMs:Date.now()-D,fanOut:{failed:x.failed,shards:x.ok+x.failed,table:d.fanOut.table},functionPath:d.functionPath,..._,ok:!0},B),Response.json(x,{headers:{"content-type":"application/json"},status:200})}catch(x){throw ce(O,{...ke(d.functionPath,Date.now()-D,x,{fanOut:{table:d.fanOut.table}}),..._},B),x}const L=d.shardKey??o,V=()=>Te(r,d.functionPath,d.args??{},L,R,B);return P&&e.x402Charge?e.x402Charge(r,{functionPath:d.functionPath,price:P.price},V,ze(l)):V()}},qn=async(r,a,l)=>{M(r,"POST","RPC batch");const d=await ee(r),{calls:p}=d;if(!Array.isArray(p))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:R,identity:A}=await U(r,a,i);Wt(r,A);const P=Jo(p,o);for(const $ of P.values())for(const F of $)if(e.functions?.[F.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${F.functionPath}" cannot be called in a batch; dispatch it individually over ${Ft}`,{code:"BAD_REQUEST",status:400});await Promise.all([...P.entries()].flatMap(([$,F])=>F.map(Z=>Se({args:Z.args,functionPath:Z.functionPath,shardKey:$},A))));const{observability:D,sampling:O}=e,_=Re(a,r,l&&($=>l.waitUntil?.($))),B=Ve(r),{decision:L,ignoredUpstream:V,trace:x}=jt(r,{...O===void 0?{}:{sampling:O},trustInbound:t(r)});V&&n(r);const ue={isTraced:x.sampled,keepErrors:L.keepErrors},dr=$=>{const F={...R,"content-type":"application/json",[Rt]:L.keepErrors?"1":"0"};return Mt({...x,spanId:$},F),F},Be=$=>({parentSpanId:$,spanId:ge(8),traceFlags:x.traceFlags,traceId:x.traceId}),Oe=[],xe=[],ht=($,F,Z,le)=>({body:{error:{code:Z,message:le}},id:$.id,status:F}),ft=($,F,Z,le,fe)=>{for(const q of $)ce(D,fe(q),_,void 0,ue),Oe.push(ht(q,F,Z,le))},ur=($,F,Z,le,fe,q)=>{for(const _e of $){const pe=fe.get(_e.id)??q,me=pe<400;ce(D,{durationMs:le,functionPath:_e.functionPath,...B,...Be(Z),ok:me,shardKey:F,...me?{}:{error:{code:"SHARD_ERROR",message:`batched call returned ${String(pe)}`,status:pe}}},_,void 0,ue)}};await Promise.all([...P.entries()].map(async([$,F])=>{const Z=ge(8),le=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:F}),headers:new Headers(dr(Z)),method:"POST"}),fe=Date.now();let q;try{q=await S(u,$,le)}catch(X){const Le=Date.now()-fe,{body:wt}=mr(X,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});ft(F,502,wt.code,wt.message,fr=>({...ke(fr.functionPath,Le,X,{shardKey:$}),...B,...Be(Z)}));return}const _e=Date.now()-fe,pe=q.headers.get("x-d1-bookmark");pe&&xe.push(pe);let me;try{me=await q.json()}catch{const X=`shard batch returned a non-JSON response (${String(q.status)})`;ft(F,q.status,"SHARD_ERROR",X,Le=>({durationMs:_e,error:{code:"SHARD_ERROR",message:X,status:q.status},functionPath:Le.functionPath,...B,...Be(Z),ok:!1,shardKey:$}));return}const He=Array.isArray(me.results)?me.results:[],lr=new Map(He.map(X=>[X.id,X.status??q.status])),hr=new Set(He.map(X=>X.id));ur(F,$,Z,_e,lr,q.status),Oe.push(...He);for(const X of F)hr.has(X.id)||Oe.push(ht(X,q.status,"SHARD_ERROR",`shard batch omitted result for call ${String(X.id)}`))}));const pt={"content-type":"application/json"},[mt]=xe;return xe.length===1&&mt!==void 0&&(pt["x-d1-bookmark"]=mt),Response.json({results:Oe},{headers:pt,status:200})},Xn=async(r,a,l,d={},p={})=>{try{const R=l.__lunoraRef;if(typeof R!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});ve(R);const{headers:A,identity:P}=await U(r,a,i,p.context),D={args:d,functionPath:R,shardKey:p.shardKey};await Se(D,P);const O=p.shardKey??o,_=Re(a,r,p.waitUntil),B=()=>Te(r,R,d,O,A,_),L=Je(D,e);return L&&e.x402Charge?await e.x402Charge(r,{functionPath:R,price:L.price},B,ze(p.waitUntil?{waitUntil:p.waitUntil}:p.context)):await B()}catch(R){return Et(R)}},dt=async(r,a,l)=>{const{observability:d}=e,p=Date.now(),R=ge(16),A=ge(8),P=Yt(a),D=nn(R,A,!0);try{const O=await l(D);return ce(d,{durationMs:Date.now()-p,functionPath:r,ok:!0,spanId:A,traceId:R},P),O}catch(O){throw ce(d,{...ke(r,Date.now()-p,O,{}),spanId:A,traceId:R},P),O}finally{_t(d,P)}},ut=async(r,a,l,d)=>{v(a);const p=[],R=_=>_ instanceof Error?_:new Error(String(_)),A=e.crons?.[r.cron];if(A)try{await A(r,a,l)}catch(_){p.push(R(_))}const P=await ae(r.cron,a,l,p,R,d),D=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===r.cron;if(D)try{await Fo(e,s,u,k(),r)}catch(_){p.push(R(_))}if(!A&&P===0&&!D){const _=[...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: ${_.length===0?"(none)":_.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[O]=p;if(p.length===1&&O)throw O;if(p.length>1)throw new AggregateError(p,`scheduled("${r.cron}") had ${String(p.length)} failure(s)`)},Zn=ca({assertAdmin:z,dispatchScheduled:ut,queueHandler:e.queueHandler}),er=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 S(u,o,De(Ca,{outcome:a},{authorization:`Bearer ${d}`,"content-type":"application/json"}))}catch{}},tr=async(r,a,l,d)=>{if(!e.authHandler)return;const p=e.authBasePath??zt,R=Jt(l.pathname,p)?Nr(r):void 0;let A;try{A=await e.authHandler(R?.request??r)}catch(P){throw R?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):P}if(R?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(A)return xa(l.pathname,p)&&d.waitUntil?.(er(a,A.status>=400?"fail":"ok")),A},nr=async({args:r,env:a,functionPath:l,request:d,shardKey:p,waitUntil:R})=>{on(r,"REST");const A={functionPath:l,...p===void 0?{}:{shardKey:p}},{headers:P,identity:D}=await U(d,a,i);await Se(A,D);const O=p??o,_=Re(a,d,R),B=()=>Te(d,l,r,O,P,_),L=Je(A,e);return L&&e.x402Charge?e.x402Charge(d,{functionPath:l,price:L.price},B,ze({waitUntil:R})):B()},rr=Pr({functions:e.functions??{},invoke:nr,readJsonBody:ee,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),Ae=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0;Xa(Ae);const or={[Pa]: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"}}),[Ta]:(r,a,l)=>Gn(r,a,l),[Ft]:(r,a,l,d)=>Yn(r,a,d),[Sa]:(r,a,l,d)=>qn(r,a,d),[Aa]:(r,a,l,d)=>An(r,a,d),[Oa]:(r,a,l,d)=>Tn(r,a,d),[va]:async r=>{M(r,"POST","ws-token"),z(r);const a=k();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 vo(a);return Response.json(l,{headers:{"cache-control":"no-store"}})},...Q,...Pn,...Dn,...Nn,...Un,...Cn,...Bn,...xn,...Hn,...Ln,...Mn,...rr,...Do({assertAdmin:z,getAuthAdmin:()=>e.authAdmin,parsePaging:Ce,queryParameter:Ue,readJsonBody:ee})};let ie=Tt(e.security),lt=!1;const sr=r=>{lt||(lt=!0,ie=Tt(e.security,r??{}))},ar=async(r,a)=>{Da(a)&&await j(r)},ir=(r,a)=>{if(!(a.pathname.startsWith(Ne)||e.authHandler!==void 0&&Jt(a.pathname,e.authBasePath??zt))||r.method!=="POST"&&r.method!=="PUT")return;const d=Number(r.headers.get("content-length")??""),p=Ea[a.pathname]??rn;if(Number.isFinite(d)&&d>p)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},cr=async(r,a,l)=>{tt.set(r,l);const d=new URL(r.url);ir(r,d);const p=await tr(r,a,d,l);if(p)return p;if(Ae){const O=`${r.method} ${d.pathname}`,_=Ae[O]??Ae[d.pathname];if(_)return _(r,a,l)}const R=Zn[d.pathname];if(R)return R(r,a,l);const A=or[d.pathname];if(A)return await ar(r,d.pathname),A(r,a,d,l);if(e.voiceAgents!==void 0&&d.pathname.startsWith(Qt))return Qn(r,a,d);if(d.pathname.startsWith(Ne))return new Response("Not found",{status:404});const P=await Fn(r,a,l);if(P&&P.status!==404)return P;const D=await e.authDiscoveryHandler?.(r);return D?(await P?.body?.cancel(),D):P??new Response("Not found",{status:404})};return{async fetch(r,a,l){e.passThroughOnException&&l.passThroughOnException?.(),sr(a),v(a);const d=Zr(r,ie);if(d)return d;const p=eo(r,ie);if(p)return $e(p,r,ie);try{const R=await cr(r,a,l);return $e(R,r,ie)}catch(R){return $e(Et(R),r,ie)}finally{_t(e.observability,Yt(l))}},async queue(r,a,l){await dt(`queue:${ja(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:Xn}},ei=e=>Sn(e),ti=e=>typeof e=="function"?{fetch:e}:e,ni=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ri=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}:{}},vi=(e,t)=>{const n=ti(e),{email:o,queue:s,scheduled:i}=ri(e),u=f=>{const b={...ei({...f,httpRouter:n})};return i!==void 0&&!ni(f)&&(b.scheduled=async(S,T,k)=>{await i(S,T,k)}),s!==void 0&&f.queue===void 0&&(b.queue=async(S,T,k)=>{await s(S,T,k)}),o!==void 0&&(b.email=async(S,T,k)=>{await o(S,T,k)}),b};if(typeof t!="function")return u(t);const h=t;return{fetch:(f,m,b)=>u(h(m)).fetch(f,m,b),queue:(f,m,b)=>u(h(m)).queue?.(f,m,b)??Promise.resolve(),scheduled:(f,m,b)=>u(h(m)).scheduled(f,m,b),serverQuery:(f,m,b,S,T)=>u(h(m)).serverQuery(f,m,b,S,T),...o===void 0?{}:{email:(f,m,b)=>u(h(m)).email?.(f,m,b)??Promise.resolve()}}},oi=(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}},Ii=(e={})=>(t,n,o)=>Sn(oi(e,n)).fetch(t,n,o??wr),ki=e=>e;export{Ze as COPY_AUTH_TO_JURISDICTION_OP,kt as GET_AUTH_AUDIT_LOG_OP,wr as NOOP_EXECUTION_CONTEXT,fn as PURGE_UNPINNED_AUTH_OP,Ni as composeIdentityResolvers,ei as composeWorker,Ii as createLunoraHandler,Sn as createWorker,ki as defineRpcEnvelope,za as probeRelayCount,oi as resolveLunoraOptions,Ui as routeIdentityResolvers,vi as withFrameworkWorker};
@@ -0,0 +1 @@
1
+ import{e as c,a as u}from"./identity-header-pR617HTs.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};
@@ -0,0 +1 @@
1
+ import{c as o,a as s,d as t,r as i,b as n,s as p,w as S}from"./export-tap-CAyZ2TWC.mjs";import"./portable-json-BSCiOfqE.mjs";export{o as createKvCursorStore,s as createMemoryCursorStore,t as defineExportSink,i as r2Sink,n as runExportTap,p as sanitizeChange,S as webhookExportSink};
@@ -0,0 +1 @@
1
+ import{toErrorBody as I}from"@lunora/errors";import{b as U,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-DksAgIpa.mjs";import{resolveShard as V}from"./applyJurisdiction-C0ddU7Tg.mjs";const ke=r=>({listShardKeys(e){return r[e]??[]}}),be=(r,e)=>({listShardKeys(s){if(r===void 0)throw new v(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new v(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),P=16,x=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,L=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},$=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,n=0,a=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=L(i);t+=u.changed,n+=u.processed,a||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:n,shards:e,status:$(c,a||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},H=r=>{const e=[];let s=0,o=0,t=0,n=0;for(const a of r){if(a.kind==="err"){o+=1,e.push({error:{message:a.message,timedOut:a.timedOut},shardKey:a.shardKey});continue}s+=1;const c=G(y(a.value));t+=c.before,n+=c.total,e.push({result:c,shardKey:a.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:n}},B=0,D=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?B:typeof r=="number"?D:J,O=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===B?0:s===D?k(r,e):k(String(r),String(e))},Q=(r,e,s)=>{const o=O(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let n=0;n<t;n+=1){const a=O(r.sortValues[n],e.sortValues[n]);if(a!==0)return s[n]==="desc"?-a:a}return O(r.rowId,e.rowId)},Y=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(U(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},X=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},Z=(r,e)=>{let s=!1;const o=new Set;for(const n of r)o.add(n.shardKey),(n.head<n.rows.length||n.hasMore)&&(s=!0);const t={...e};for(const n of Object.keys(e))o.has(n)||(s=!0);return s?Y({perShard:t}):null},q=(r,e,s,o)=>{const t=[],n={...o};for(;t.length<e;){const c=z(r,s);if(c===void 0)break;t.push(c.row.doc),n[c.slice.shardKey]=c.row.key,c.slice.head+=1}const a=Z(r,n);return{isDone:a===null,nextCursor:a,page:t}},ee=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const n=y(t.value),a=Array.isArray(n?.rows)?n.rows:[];e.push({rows:a,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},re=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:n,sinceSeq:a}of r){if(t.kind==="err"){o+=1,e.push({cursor:a,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...n===void 0?{}:{epoch:n}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:a,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:n;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},te=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const n=y(t.value);o+=typeof n?.applied=="number"?n.applied:0}return{applied:o,failed:s,ok:e}},se=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},oe=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:se(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ne=r=>{const e=[],s={},o=[];let t=0,n=0,a=0;for(const c of r){if(c.kind==="err"){a+=1,e.push({error:{message:c.message,timedOut:c.timedOut},shardKey:c.shardKey});continue}n+=1;const d=y(c.value),i=d?.inserted??{};for(const[l,f]of Object.entries(i))s[l]=(s[l]??0)+f;const u=d?.errors;Array.isArray(u)&&o.push(...u),t+=d?.conflicts??0,e.push({result:{conflicts:d?.conflicts??0,errors:d?.errors??[],inserted:i},shardKey:c.shardKey})}return{conflicts:t,errors:o,failed:a,inserted:s,ok:n,shards:e}},m=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers}}),ae=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),n=new AbortController,a=new Request("https://shard.internal/rpc",{body:s.body,headers:s.headers,method:"POST",signal:n.signal});let c;const d=new Promise(u=>{c=setTimeout(()=>{try{n.abort()}catch{}u({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),i=(async()=>{try{const u=await t.fetch(a);if(!u.ok){const f=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:f?.code??"SHARD_HTTP_ERROR",kind:"err",message:f===void 0||f.message.length===0?p:`${p}: ${f.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(u){const{body:l}=I(u,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:l.code,kind:"err",message:`shard "${e}" failed: ${l.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([i,d])}finally{c!==void 0&&clearTimeout(c)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const n=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},a=Math.min(e,r.length);return await Promise.all(Array.from({length:a},()=>n())),o},K=(r,e)=>r.length>0||e===null?r:[e],T=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>K(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},S=async(r,e,s,o,t)=>{const n=m(s);return w(e,o,async a=>g(r,a,n,t))},ce=r=>{const e={};for(const s of Object.keys(r).toSorted(k))e[s]=r[s]??null;return JSON.stringify(e)},ie=r=>r.flatMap(e=>Array.isArray(e)?e:[]),de=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},ue=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,n=ce(o),a=r.get(n);if(!a){r.set(n,{key:o,value:t});return}if(a.value===null){a.value=t;return}t!==null&&(a.value=de(a.value,t,s))},le=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)ue(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},he=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},fe=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},ye=(r,e)=>{const s=[];for(const t of r)if(Array.isArray(t))for(const n of t){if(n===null||typeof n!="object")continue;const a=n[e.by],c=typeof a=="number"&&Number.isFinite(a)?a:Number.NEGATIVE_INFINITY;s.push({row:n,score:c})}const o=e.direction??"desc";return s.sort((t,n)=>o==="asc"?k(t.score,n.score):k(n.score,t.score)),s.slice(0,e.k).map(t=>t.row)},pe=(r,e)=>{switch(e.kind){case"concat":return ie(r);case"first":return r[0];case"groupBy":return le(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return fe(r);case"sum":return he(r);case"topK":return ye(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Ke=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const n=await w([...o],P,async([i,u])=>({outcome:await g(e,i,m({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),x),tables:u})),a=[],c=[],d=[];for(const{outcome:i,tables:u}of n){if(i.kind==="err"){a.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:a,kept:c,released:d}},_e=r=>{const e=r.maxConcurrency??P,s=r.perShardTimeoutMs??x;if(e<1)throw new v("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const n=await r.registry.listShardKeys(t.fanOut.table),a=await S(o,n,t,e,s),c=[],d=[];for(const i of a)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:pe(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await T(r.registry,t.tables,t.defaultShardKey),a=K(n,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await S(o,a,c,e,s);return ee(d)},async orchestrateCdcSync(o,t){const n=K(await T(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),a=t.cursors??{},c=t.epochs??{},d=await w(n,e,async i=>{const u=a[i]??0,l=c[i];return{outcome:await g(o,i,m({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return re(d)},async orchestrateImport(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{rows:[...c.rows],startLine:c.startLine??1},functionPath:"__lunora_admin__:importShard",headers:t.headers}),s));return ne(a)},async orchestrateApplyCdc(o,t){const{batches:n}=t,a=await w(n,e,async c=>g(o,c.shardKey,m({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return te(a)},async orchestrateMigration(o,t){const n=K(await r.registry.listShardKeys(t.table),t.defaultShardKey),a=await S(o,n,t,e,s);return j(a)},async orchestrateRank(o,t){const n=await r.registry.listShardKeys(t.table),a={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await S(o,n,a,e,s);return H(c)},async orchestrateRankPage(o,t){const n=await r.registry.listShardKeys(t.table),a=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?W(t.cursor):{perShard:{}},i=await w(n,e,async h=>{const C=d.perShard[h],R={index:t.index,table:t.table,take:a};t.partitionKey!==void 0&&(R.partitionKey=t.partitionKey),C!==void 0&&(R.after=C);const b=await g(o,h,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:h};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:h}}),u=[];let l=0,f=0,p;for(const h of i){if(h.error){f+=1;continue}l+=1,p===void 0&&h.directions&&h.directions.length>0&&(p=h.directions),u.push({hasMore:h.hasMore??!1,head:0,rows:h.rows??[],shardKey:h.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:f,isDone:_.isDone,ok:l,page:_.page,partial:f>0,shards:i}},async orchestrateShardTraffic(o,t){const n=await r.registry.listShardKeys(t.table),a={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await S(o,n,a,e,s);return oe(c)},registry:r.registry}};export{be as createDefaultShardRegistry,_e as createQueryCoordinator,ke as createStaticShardRegistry,Ke as pruneShardRegistry};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";import{e as S,a as I}from"./identity-header-pR617HTs.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
+ const o=Symbol.for("lunora:app-jurisdiction"),r=globalThis,i=t=>{const e=r[o];if(e!==void 0&&e!==t)throw new TypeError(`lunora: the app jurisdiction is already "${e}"; refusing to redeclare it as "${t}".`);r[o]=t},s=()=>r[o],n=()=>{delete r[o]};export{i as declareAppJurisdiction,s as getAppJurisdiction,n as resetAppJurisdiction};
@@ -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
+ const i=(e,s)=>{if(e.size<s)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)};export{i as e};
@@ -0,0 +1,3 @@
1
+ import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-BSCiOfqE.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
2
+ `)}
3
+ `,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
@@ -0,0 +1 @@
1
+ import{t as r,f as s}from"./base64-Bl1_r2k1.mjs";const d=new TextDecoder,c=new TextEncoder,o="=",a=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},E=e=>r(c.encode(JSON.stringify(e))),i=e=>{if(e)try{const t=e[0]==="{"?e:d.decode(s(e)),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},u=e=>!e.startsWith(o)&&a(e)?e:`${o}${r(c.encode(e))}`,y=e=>typeof e=="number"&&Date.now()>=e,p="x-lunora-expect-subject",x=e=>{const t=i(e)?.subject;return t===null||typeof t=="string"?{subject:t}:void 0};export{p as E,E as a,x as d,u as e,y as i};
@@ -0,0 +1 @@
1
+ import{e as v}from"./evict-oldest-BNXsKx4s.mjs";const g=o=>{const e=new WeakMap;return(n,i,a)=>{const s=e.get(n);if(s)return s;const t=Promise.resolve(o(n,i,a));return e.set(n,t),t}},f=5e3,p=500,y=o=>{const e=o.headers.get("cookie")??"",n=o.headers.get("authorization")??"";if(!(e===""&&n===""))return`${n}\0${e}`},M=(o,e={})=>{const n=e.ttlMs??f,i=Math.max(1,e.maxEntries??p),a=e.cacheKey??y,s=g(o),t=new Map;return(d,h,l)=>{const r=a(d);if(r===void 0||l?.access!==void 0)return s(d,h,l);const m=Date.now(),u=t.get(r);if(u&&u.expiresAt>m)return u.value;const c=Promise.resolve(s(d,h,l));return c.catch(()=>{t.get(r)?.value===c&&t.delete(r)}),t.delete(r),v(t,i),t.set(r,{expiresAt:m+n,value:c}),c}};export{M as memoizeIdentity,g as memoizeIdentityPerRequest};
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"./LunoraError-DksAgIpa.mjs";const n=(e,o)=>o.includes(e.method)?void 0:new Response(void 0,{headers:{allow:o.join(", ")},status:405}),a=(e,o,s)=>{if(e.method!==o)throw new t(`${s} endpoint requires ${o}`,{code:"METHOD_NOT_ALLOWED",status:405})};export{a,n as m};
@@ -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 a="x-lunora-paywall",A="1";export{A as O,a};
@@ -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};
@@ -0,0 +1 @@
1
+ import{raw as n,desc as F,sql as r}from"@lunora/bindings/r2sql";const u=["trace","debug","log","info","warn","error","fatal"],T={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},N=500,w=1e4,_=e=>e===void 0||!Number.isFinite(e)?N:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),L=e=>e==null?"":String(e),U=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},S=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,l=0;for(const v of s){const I=v.codePointAt(0)??0;t=(t*31+I)%2147483647,l=(l*131+I)%4294967291}return`${t.toString(36)}.${l.toString(36)}`},y=(e,s,t,l)=>{if(s.sinceTs!==void 0&&e.where(r`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(r`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(r`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const v=u.indexOf(s.minLevel),I=v===-1?[...u]:u.slice(v);e.where(r`${n(t.level)} IN ${I}`)}s.functionPath!==void 0&&e.where(r`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(r`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(r`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(r`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(r`${n(t.userId)} = ${s.userId}`),l!==void 0&&e.where(r`${n(t.ts)} <= ${l}`)},G=T,J=(e,s)=>{const t={...T,...s.columnMap},l=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,v=a=>{const c={functionPath:L(a[t.functionPath]),level:L(a[t.level]),message:L(a[t.message]),ts:D(a[t.ts])},o=a[t.fields];o!=null&&(c.fields=U(o));for(const d of["shardKey","userId","traceId","spanId"]){const i=a[t[d]];i!=null&&(c[d]=L(i))}return c},I=async(a,c,o)=>{const d=e.from(l).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));y(d,a,t,c),d.orderBy(F(n(t.ts))).limit(o);const{rows:i}=await d.run();return i},A=async(a,c,o,d)=>{const i=await I(a,c,d),$=[];for(const P of i){const f=v(P);o!==void 0&&c!==void 0&&f.ts===c&&o.has(S(f))||$.push(f)}return{decoded:$,truncated:i.length>=d}};return{query:async(a={})=>{const c=_(a.limit),{cursor:o}=a,d=o?.ts,i=o?.seen!==void 0&&o.seen.length>0?new Set(o.seen):void 0,$=Math.min(c+1,w),P=3;let f=[],m=!1;for(let h=0;h<P;h+=1){const K=Math.min($*2**h,w),O=await A(a,d,i,K);if(f=O.decoded,m=O.truncated,f.length>c||!m||K>=w)break}const R=f.length>c,g=R?f.slice(0,c):f,M=g.at(-1);if(M===void 0||!(R||m))return{rows:g};const p=M.ts,E=g.filter(h=>h.ts===p).map(h=>S(h)),x=[...d===p&&o?.seen!==void 0?o.seen:[],...E];return{nextCursor:x.length>0?{seen:x,ts:p}:{ts:p},rows:g}}}};export{G as D,u as L,J as c};
@@ -0,0 +1 @@
1
+ import{a as i}from"./base64-Bl1_r2k1.mjs";import{d as f,i as s}from"./wire-codec-BLvSm5Mn.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
@@ -0,0 +1 @@
1
+ const m="/_lunora/rest",v=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],d=["x-d1-bookmark","x-lunora-shard-key"],h=e=>[...v,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const s of a?.split(",")??[]){const n=s.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},l=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},p=e=>e.scope==="public"?c(e.vary,...h(e),...d):c(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},g=e=>{const t=f(e);if(t!==void 0)return`${m}/${t.namespace}/${t.name}`},E=e=>e==="query"?"GET":"POST",b=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const s=f(a.functionPath),n=g(a.functionPath);s===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:E(a.kind),name:s.name,namespace:s.namespace,path:n})}return t.sort((a,s)=>a.path<s.path?-1:+(a.path>s.path)),t},R=(e,t,a)=>a?.access!==void 0||h(t).some(s=>e.headers.has(s)),x=(e,t,a)=>e.scope==="public"&&!R(t,e,a)?"public":"private",S=(e,t,a,s)=>{if(t.method!=="GET"||a<200||a>299)return;const n={"cache-control":l(e,x(e,t,s))};e.tag!==void 0&&e.tag!==""&&(n["cache-tag"]=e.tag);const r=p(e);return r!==void 0&&(n.vary=r),n},C=(e,t,a,s)=>{if(t===void 0)return e;const n=S(t,a,e.status,s);if(n===void 0)return e;const r=new Response(e.body,e);for(const[i,o]of Object.entries(n))r.headers.set(i,i==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{C as a,S as b,u as c,p as d,x as e,b as f,R as r};
@@ -0,0 +1 @@
1
+ import{c as O,d as k,e as P,a as B,f as j}from"./rest-cache-CmHN871W.mjs";import{LunoraError as h}from"./LunoraError-DksAgIpa.mjs";import{m as D}from"./method-guard-BG_vJNTl.mjs";const p=1048576,L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),x=async(e,r=p)=>{if(!e.body)return"";const t=e.body.getReader(),o=new TextDecoder;let n=0,c="";for(;;){const{done:s,value:a}=await t.read();if(s)break;if(a){if(n+=a.byteLength,n>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});c+=o.decode(a,{stream:!0})}}return c+=o.decode(),c},te=async(e,r=p)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),o=[];let n=0;for(;;){const{done:a,value:i}=await t.read();if(a)break;if(i){if(n+=i.byteLength,n>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o.push(i)}}const c=new Uint8Array(n);let s=0;for(const a of o)c.set(a,s),s+=a.byteLength;return c.buffer},re=(e,r=p)=>{const t=e.body;let o=!1;if(t===null)return{overflowed:()=>o,request:e};let n,c=0;const s=new ReadableStream({cancel:async a=>{await(n??t).cancel(a)},pull:async a=>{n??=t.getReader();const{done:i,value:d}=await n.read();if(i){a.close();return}if(c+=d.byteLength,c>r){o=!0,a.error(new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})),n.cancel().catch(()=>{});return}a.enqueue(d)}},{highWaterMark:0});return{overflowed:()=>o,request:new Request(e,{body:s,duplex:"half"})}},C=async(e,r,t=p)=>{try{const o=await x(e,t);return o===""?{}:JSON.parse(o)}catch(o){throw o instanceof h?o:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},ae=async(e,r=p)=>{const t=await C(e,"Request",r);if(!L(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},U=(e,r)=>{if(!L(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},G=/^[\d.:a-f]+$/iu,I=e=>{const r=e.indexOf("%"),t=r===-1?e:e.slice(0,r);if(!t.includes(":")||!G.test(t))return e;let o;try{o=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return e}const[n="",c]=o.split("::"),s=n===""?[]:n.split(":"),a=c===void 0||c===""?[]:c.split(":"),i=[...s,...Array.from({length:8-s.length-a.length},()=>"0"),...a].map(d=>Number.parseInt(d,16));if(i.slice(0,5).every(d=>d===0)&&i[5]===65535){const[d=0,u=0]=i.slice(6);return[d>>8,d&255,u>>8,u&255].join(".")}return`${i.slice(0,4).map(d=>d.toString(16)).join(":")}::/64`},g="__lunora_vary",N="x-lunora-edge-cache",M=["x-d1-bookmark","x-lunora-shard-key"],$=()=>{try{return globalThis.caches?.default}catch{return}},S=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),H=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:S(t).every(o=>o!=="*"&&r.includes(o))},K=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||O(e.maxAge)<=0)return;const t=()=>r??$(),o=S(k(e)??""),n=s=>{const a=new URL(s.url);return a.searchParams.delete(g),o.length>0&&a.searchParams.set(g,o.map(i=>`${i}=${s.headers.get(i)??""}`).join("\0")),new Request(a.toString(),{method:"GET"})},c=(s,a)=>s.method==="GET"&&P(e,s,a)==="public";return{lookup:async(s,a)=>{const i=t();if(i===void 0||!c(s,a))return;let d;try{d=await i.match(n(s))}catch{return}if(d===void 0)return;const u=new Response(d.body,d);return u.headers.set(N,"hit"),u},store:(s,a,i)=>{const d=t();if(d===void 0||!c(a,i)||s.status!==200||s.headers.has("set-cookie")||s.headers.has("payment-response")||s.headers.has("x-payment-response")||!H(s,o))return s;try{const u=new Response(s.clone().body,s);for(const l of M)u.headers.delete(l);const f=Promise.resolve(d.put(n(a),u)).catch(()=>{});i?.waitUntil&&i.waitUntil(f)}catch{}return s}}},Y=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",F=(e,r)=>{if(Y())return e.get("cf-connecting-ip")??void 0;if(r===void 0)return;const t=e.get(r)?.trim();return t===void 0||t===""||t.includes(",")?void 0:t},J=(e,r)=>{if(r.x402!==void 0&&r.expose?.cache?.scope==="public")throw new h(`REST route "${e}" is paid (.x402) but declares \`cache: { scope: "public" }\`: a shared cache would replay the paid response to callers who never paid. Use \`scope: "private"\` or drop the cache policy.`,{code:"MISCONFIGURED",status:500})},Q=e=>j(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),W=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const o=r.headers.get("x-lunora-shard-key");return o===null||o===""?void 0:o},V=e=>{const r=Object.create(null);for(const[t,o]of e.searchParams.entries())if(!(t==="shardKey"||t===g))try{r[t]=JSON.parse(o)}catch{r[t]=o}return r},oe=e=>{const{edgeCache:r,functions:t,invoke:o,rateLimit:n,readJsonBody:c}=e,s={};for(const a of Q(t)){const i=a.kind==="query"?["GET","POST"]:["POST"],d=t[a.functionPath];J(a.functionPath,d);const u=d.expose?.cache,f=K(u,r);s[a.path]=async(l,T,z,y)=>{const R=D(l,i);if(R)return R;const v=new URL(l.url);if(n){const m=await n(l,a.functionPath);if(m)return m}const b=await f?.lookup(l,y);if(b)return b;let w;l.method==="GET"?w=V(v):w=l.body===null?{}:await c(l),U(w,"REST");const E=W(v,l),_=await o({args:w,env:T,functionPath:a.functionPath,request:l,...E===void 0?{}:{shardKey:E},...y?.waitUntil===void 0?{}:{waitUntil:m=>y.waitUntil?.(m)}}),A=B(_,u,l,y);return f?f.store(A,l,y):A}}return s},X=()=>Response.json({error:{code:"INTERNAL",message:"REST rate limit: no caller key could be resolved. Declare `trustedClientIpHeader` (a header your proxy stamps and callers cannot write), or pass `key` to identify callers by something unforgeable."}},{headers:{"content-type":"application/json"},status:500}),se=(e,r)=>async(t,o)=>{let n;if(r.key)n=r.key(t,o);else{const a=F(t.headers,r.trustedClientIpHeader);n=a===void 0?void 0:I(a)}if(n===void 0||n==="")return X();const c=await e.limit(r.name,{key:n});if(c.ok)return;if(c.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const s=Math.max(1,Math.ceil(c.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(s)},status:429})};export{p as M,V as a,oe as b,se as c,ae as d,C as e,te as f,U as g,x as h,Q as r,F as t,re as w};
@@ -0,0 +1 @@
1
+ import{t as b}from"./portable-json-BSCiOfqE.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};