@lunora/runtime 1.0.0-alpha.25 → 1.0.0-alpha.250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +120 -0
- package/README.md +52 -10
- package/dist/index.d.mts +4501 -1612
- package/dist/index.d.ts +4501 -1612
- package/dist/index.mjs +1 -16
- package/dist/packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-gYMhXLzO.mjs +1 -0
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs +2 -0
- package/dist/packem_shared/HEALTH_PATH-B8ndDG3s.mjs +1 -0
- package/dist/packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs +1 -0
- package/dist/packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs +1 -0
- package/dist/packem_shared/LunoraError-PkZWF-_g.mjs +1 -0
- package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs +1 -0
- package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs +1 -0
- package/dist/packem_shared/analyticsEngineSink-s5j-3P1X.mjs +1 -0
- package/dist/packem_shared/applyJurisdiction-DKQE8kOA.mjs +1 -0
- package/dist/packem_shared/applyRestCache-CEcBz3qq.mjs +1 -0
- package/dist/packem_shared/argsFromQuery-C8Ox3sr1.mjs +1 -0
- package/dist/packem_shared/base64-Bl1_r2k1.mjs +1 -0
- package/dist/packem_shared/composeIdentityResolvers-CpdHuDyk.mjs +1 -0
- package/dist/packem_shared/composeWorker-jYTQNYlU.mjs +6 -0
- package/dist/packem_shared/createCrossShardRelationCapabilities-DRYvyR4Y.mjs +1 -0
- package/dist/packem_shared/createKvCursorStore-Bkn5pilz.mjs +1 -0
- package/dist/packem_shared/createQueryCoordinator-D3Pz-Jdr.mjs +1 -0
- package/dist/packem_shared/createShardClient-rKSKWKAG.mjs +1 -0
- package/dist/packem_shared/declareAppJurisdiction-DEba2p42.mjs +1 -0
- package/dist/packem_shared/decorateResponse-CdelJSUs.mjs +1 -0
- package/dist/packem_shared/emitLogEvent-CdybnWG8.mjs +1 -0
- package/dist/packem_shared/enrichSink-44NOapaE.mjs +1 -0
- package/dist/packem_shared/error-detail-C46mdOTW.mjs +1 -0
- package/dist/packem_shared/export-tap-C2B_SATf.mjs +3 -0
- package/dist/packem_shared/identity-header-ByHiZBcH.mjs +1 -0
- package/dist/packem_shared/memoize-identity-DFkwm3x6.mjs +1 -0
- package/dist/packem_shared/memoizeIdentity-C4BJchsg.mjs +1 -0
- package/dist/packem_shared/method-guard-8Jo4Q8uS.mjs +1 -0
- package/dist/packem_shared/observability-9slk__Gi.mjs +1 -0
- package/dist/packem_shared/observability-sinks-lLKqc_rV.mjs +4 -0
- package/dist/packem_shared/origin-paywall-B6eOO67m.mjs +1 -0
- package/dist/packem_shared/otlp-resource-Ch_8_U0e.mjs +1 -0
- package/dist/packem_shared/parseStackFrames-CZddjveh.mjs +2 -0
- package/dist/packem_shared/pipeline-log-reader-C-nuWG_e.mjs +1 -0
- package/dist/packem_shared/portable-json-CSq6T1AU.mjs +1 -0
- package/dist/packem_shared/rest-cache-CmHN871W.mjs +1 -0
- package/dist/packem_shared/rest-routes-CDQ1F7kI.mjs +1 -0
- package/dist/packem_shared/toAirbyteMessages-DY0vsuEn.mjs +1 -0
- package/package.json +10 -2
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-B3pA7aXp.mjs +0 -79
- package/dist/packem_shared/LunoraError-Bpb9EFJ3.mjs +0 -22
- package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-CCTu0Bf1.mjs +0 -8
- package/dist/packem_shared/analyticsEngineSink-BpJlA7e9.mjs +0 -275
- package/dist/packem_shared/applyJurisdiction-BkZtTkct.mjs +0 -20
- package/dist/packem_shared/composeIdentityResolvers-XGjO7V1J.mjs +0 -55
- package/dist/packem_shared/composeWorker-CxwkPZUl.mjs +0 -3170
- package/dist/packem_shared/createCrossShardRelationCapabilities-CbcWjkAn.mjs +0 -63
- package/dist/packem_shared/createQueryCoordinator-DNCJzOZE.mjs +0 -847
- package/dist/packem_shared/decorateResponse-DRWQFNhF.mjs +0 -273
- package/dist/packem_shared/emitLogEvent-pEdtqAK8.mjs +0 -20
- package/dist/packem_shared/toAirbyteMessages-DrHdplb4.mjs +0 -39
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { composeWorker, createLunoraHandler, createWorker, defineRpcEnvelope, resolveLunoraOptions, withFrameworkWorker } from './packem_shared/composeWorker-CxwkPZUl.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, otlpSink, sentrySink, webhookSink } from './packem_shared/analyticsEngineSink-BpJlA7e9.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-DRWQFNhF.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 p,backupObjectKeyOfManifest as n,isBackupManifestEntry as c,isBackupManifestKey as m,normalizeBackupPrefix as f}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as x,toFivetranResponse as R}from"./packem_shared/toAirbyteMessages-DY0vsuEn.mjs";import{composeWorker as l,createLunoraHandler as d,createWorker as u,defineRpcEnvelope as _,resolveLunoraOptions as k,withFrameworkWorker as b}from"./packem_shared/composeWorker-jYTQNYlU.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-DRYvyR4Y.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-w_RLPiwj.mjs";import{parseStackFrames as H,toError as P}from"./packem_shared/parseStackFrames-CZddjveh.mjs";import{LunoraError as v,toErrorResponse as I}from"./packem_shared/LunoraError-PkZWF-_g.mjs";import{c as F,a as M,d as N,r as G,b as K,s as U,w}from"./packem_shared/export-tap-C2B_SATf.mjs";import{HEALTH_PATH as Y,HEALTH_READY_PATH as z,buildHealthRoutes as X,d1Probe as j,durableObjectProbe as V,presenceProbe as W}from"./packem_shared/HEALTH_PATH-B8ndDG3s.mjs";import{LOG_ARCHIVE_PATH as J,resolveLogArchiveFromEnv as Q}from"./packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{m as $,a as ee}from"./packem_shared/memoize-identity-DFkwm3x6.mjs";import{e as oe,a as te}from"./packem_shared/observability-9slk__Gi.mjs";import{enrichSink as se,filterSink as ie}from"./packem_shared/enrichSink-44NOapaE.mjs";import{a as ne,c as ce,b as me,o as fe,p as Ee,w as xe}from"./packem_shared/observability-sinks-lLKqc_rV.mjs";import{D as Se,c as le}from"./packem_shared/pipeline-log-reader-C-nuWG_e.mjs";import{createQueryCoordinator as ue,createStaticShardRegistry as _e}from"./packem_shared/createQueryCoordinator-D3Pz-Jdr.mjs";import{applyJurisdiction as be,resolveShard as ye}from"./packem_shared/applyJurisdiction-DKQE8kOA.mjs";import{a as Oe,r as Ae,b as Le}from"./packem_shared/rest-cache-CmHN871W.mjs";import{a as he,b as He,c as Pe,r as ge}from"./packem_shared/rest-routes-CDQ1F7kI.mjs";import{decorateResponse as Ie,enforceOrigin as De,handleCorsPreflight as Fe,resolveSecurity as Me}from"./packem_shared/decorateResponse-CdelJSUs.mjs";import{createShardClient as Ge}from"./packem_shared/createShardClient-rKSKWKAG.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Be}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as ze}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as je,routeIdentityResolvers as Ve}from"./packem_shared/composeIdentityResolvers-CpdHuDyk.mjs";const e="0.0.0";export{s as BACKUP_KEY_PREFIX,Se as DEFAULT_LOG_COLUMNS,A as DEFAULT_REGISTRY_CACHE_TTL_MS,Y as HEALTH_PATH,z as HEALTH_READY_PATH,Be as LOG_ARCHIVE_NOT_CONFIGURED,J as LOG_ARCHIVE_PATH,v as LunoraError,ze as NOOP_EXECUTION_CONTEXT,L as SHARD_REGISTRY_DO_NAME,Ue as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ne as analyticsEngineSink,be as applyJurisdiction,Oe as applyRestCache,he as argsFromQuery,i as backupManifestKey,p as backupObjectKey,n as backupObjectKeyOfManifest,X as buildHealthRoutes,He as buildRestRoutes,ce as combineSinks,je as composeIdentityResolvers,l as composeWorker,me as consoleSink,C as createCrossShardRelationCapabilities,T as createDynamicShardRegistry,F as createKvCursorStore,d as createLunoraHandler,M as createMemoryCursorStore,le as createPipelineLogReader,ue as createQueryCoordinator,Pe as createRestRateLimit,Ge as createShardClient,_e as createStaticShardRegistry,u as createWorker,j as d1Probe,t as declareAppJurisdiction,Ie as decorateResponse,N as defineExportSink,_ as defineRpcEnvelope,V as durableObjectProbe,oe as emitLogEvent,te as emitRpcEvent,De as enforceOrigin,se as enrichSink,ie as filterSink,Fe as handleCorsPreflight,c as isBackupManifestEntry,m as isBackupManifestKey,$ as memoizeIdentity,ee as memoizeIdentityPerRequest,f as normalizeBackupPrefix,fe as otlpSink,H as parseStackFrames,Ee as pipelineLogSink,W as presenceProbe,G as r2Sink,Ae as requestCarriesCredentials,Q as resolveLogArchiveFromEnv,k as resolveLunoraOptions,Me as resolveSecurity,ye as resolveShard,Le as restCacheHeaders,ge as restSurfaceFromRegistry,Ve as routeIdentityResolvers,K as runExportTap,U as sanitizeChange,x as toAirbyteMessages,P as toError,I as toErrorResponse,R as toFivetranResponse,w as webhookExportSink,xe as webhookSink,b 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,2 @@
|
|
|
1
|
+
import{siblingSecretOf as f,RELAY_SIGNATURE_HEADER as l,signSiblingBody as R}from"@lunora/shard-engine";import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";import{applyJurisdiction as m,resolveShard as S}from"./applyJurisdiction-DKQE8kOA.mjs";const _=(e,i,a)=>{const{pathname:c,search:o}=new URL(i);return`${e.toUpperCase()} ${c}${o}
|
|
2
|
+
${a}`},E="__lunora_shard_registry__",A=3e4,T="https://shard-registry.internal",$=e=>typeof e.register!="function"&&"idFromName"in e&&typeof e.idFromName=="function",w=async e=>await e.json(),N=e=>{const i=e.instanceName??E,a=m(e.namespace,e.jurisdiction),c=()=>S(a,i),o=async(t,r,n)=>{const y=f(e.env);if(y===void 0)throw new g("the shard registry requires LUNORA_RELAY_SECRET; set it on the worker and every Durable Object",{code:"RELAY_MISCONFIGURED"});const h=`${T}${r}`,u=n===void 0?void 0:JSON.stringify(n),p={[l]:await R(y,_(t,h,u??""))};return u!==void 0&&(p["content-type"]="application/json"),c().fetch(new Request(h,{body:u,headers:p,method:t}))},s=async(t,r)=>o("POST",t,r),d=async t=>o("GET",t);return{async list(t){const r=await d(`/list?table=${encodeURIComponent(t)}`);if(!r.ok)throw new g(`shard registry /list returned ${String(r.status)}`);const{shardKeys:n}=await w(r);return n},async register(t,r){const n=await s("/register",{shardKey:r,table:t});if(!n.ok)throw new g(`shard registry /register returned ${String(n.status)}`)},async snapshot(){const t=await d("/snapshot");if(!t.ok)throw new g(`shard registry /snapshot returned ${String(t.status)}`);const{tables:r}=await w(t);return r},async unregister(t,r){const n=await s("/unregister",{shardKey:r,table:t});if(!n.ok)throw new g(`shard registry /unregister returned ${String(n.status)}`)}}},v=e=>({list:async i=>e.listShardKeys(i),register:async(i,a)=>e.register(i,a),snapshot:async()=>e.snapshot(),unregister:async(i,a)=>e.unregister(i,a)}),U=e=>{const i=e.cacheTtlMs??A,a=new Map,c=new Map,o=$(e.namespace)?N({...e,namespace:e.namespace}):v(e.namespace);return{invalidate(s){s===void 0?(a.clear(),c.clear()):(a.delete(s),c.delete(s))},async listShardKeys(s){const d=Date.now(),t=a.get(s);if(t&&t.expiresAt>d)return t.shardKeys;const r=c.get(s);if(r)return r;const n=o.list(s);i>0&&c.set(s,n);try{const y=await n;return i>0&&c.get(s)===n&&a.set(s,{expiresAt:d+i,shardKeys:y}),y}finally{c.get(s)===n&&c.delete(s)}},async register(s,d){await o.register(s,d),a.delete(s),c.delete(s)},async snapshot(){return o.snapshot()},async unregister(s,d){await o.unregister(s,d),a.delete(s),c.delete(s)}}};export{A as DEFAULT_REGISTRY_CACHE_TTL_MS,E as SHARD_REGISTRY_DO_NAME,U as createDynamicShardRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"./LunoraError-PkZWF-_g.mjs";import{m as A}from"./method-guard-8Jo4Q8uS.mjs";import{resolveShard as R}from"./applyJurisdiction-DKQE8kOA.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-PkZWF-_g.mjs";import{a as R}from"./method-guard-8Jo4Q8uS.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,internal:r?.internal,status:r?.status,why:r?.why})}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-PkZWF-_g.mjs";import{a as O}from"./method-guard-8Jo4Q8uS.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"./otlp-resource-Ch_8_U0e.mjs";import{S as a,a as s,c as S,b as e,o as k,p,w as c}from"./observability-sinks-lLKqc_rV.mjs";export{a as SINK_CONFIG_FIELDS,s as analyticsEngineSink,S as combineSinks,e as consoleSink,k as otlpSink,p as pipelineLogSink,c as webhookSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LUNORA_ROLE_PREFIX as d,resolveShard as f}from"@lunora/platform";import{LunoraError as m}from"./LunoraError-PkZWF-_g.mjs";const a=new WeakMap,n=e=>e===void 0?void 0:{locationHint:e},p=e=>typeof e.idFromName=="function",u=e=>{if(!p(e))return e;const o=e,i=a.get(e);if(i!==void 0)return i;const s=typeof o.jurisdiction=="function"?r=>u(o.jurisdiction(r)):void 0,c=typeof o.getByName=="function"?{get:(r,t)=>o.get(r,n(t)),getByName:(r,t)=>o.getByName(r,n(t)),idForName:r=>o.idFromName(r),jurisdiction:s}:{get:(r,t)=>o.get(r,n(t)),idForName:r=>o.idFromName(r),jurisdiction:s};return a.set(e,c),c},g=(e,o)=>{if(o===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/runtime: Durable Object namespace does not support jurisdiction("${o}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(o)},h=(e,o,i)=>{if(o.startsWith(d))throw new m(`shard key "${o}" uses the reserved "${d}" prefix`,{code:"BAD_REQUEST",status:400});return f(u(e),o,i)};export{g as applyJurisdiction,h 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-CDQ1F7kI.mjs";import"./rest-cache-CmHN871W.mjs";import"./LunoraError-PkZWF-_g.mjs";import"./method-guard-8Jo4Q8uS.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-PkZWF-_g.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 kr}from"@lunora/errors";import{encodeWire as be,decodeWire as et,encodeArgsOrThrow as Dr}from"@lunora/wire";import{d as Rt,E as Et,a as Nr,b as Ur,W as St}from"./error-detail-C46mdOTW.mjs";import{e as fn,b as Cr}from"./memoize-identity-DFkwm3x6.mjs";import{NOOP_EXECUTION_CONTEXT as Br}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{i as xr,e as Lr,E as At,d as Hr}from"./identity-header-ByHiZBcH.mjs";import{O as pn,a as mn}from"./origin-paywall-B6eOO67m.mjs";import{o as _e,b as wn,p as jr,m as Mr,d as $r,a as Fr,r as Gr}from"./otlp-resource-Ch_8_U0e.mjs";import{r as Kr,f as Tt,a as ue,S as vt}from"./observability-9slk__Gi.mjs";import{t as Qr,f as gn}from"./base64-Bl1_r2k1.mjs";import{d as ne,e as oe,M as yn,b as Wr,f as zr,g as bn,w as Vr,h as _n,t as Jr}from"./rest-routes-CDQ1F7kI.mjs";import{LunoraError as c,toErrorResponse as Ot}from"./LunoraError-PkZWF-_g.mjs";import{a as $,m as ye}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as at,BACKUP_KEY_PREFIX as it,isBackupManifestKey as Yr,backupObjectKeyOfManifest as Rn,backupObjectKey as Xr,backupManifestKey as qr}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Zr,buildStorageAdminRoutes as eo,STORAGE_UPLOAD_MAX_BODY_BYTES as to,STORAGE_PATH as no}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-DiZho96u.mjs";import{b as ro,e as oo,f as It,g as so,h as ao}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as io,durableObjectProbe as co,d1Probe as uo,presenceProbe as Ge}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as lo}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as ac,routeIdentityResolvers as ic}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as ho}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as fo,createQueryCoordinator as po,createDefaultShardRegistry as mo}from"./createQueryCoordinator-D3Pz-Jdr.mjs";import{resolveShard as Re,applyJurisdiction as Ke}from"./applyJurisdiction-DKQE8kOA.mjs";import{resolveSecurity as Pt,handleCorsPreflight as wo,enforceOrigin as go,decorateResponse as Qe,enforceWebSocketOrigin as kt}from"./decorateResponse-CdelJSUs.mjs";const yo=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},En="__lunoraBranch",bo=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,En),_o=`may not contain the reserved workflow branch-marker key ("${En}")`,Ro=async e=>{const t=[];let n;for(;;){const r=await e(n);if(t.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return t;if(r.cursor===n)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");n=r.cursor}},Eo=/already[\s_-]?exists/iu,So=e=>Eo.test(e instanceof Error?e.message:String(e)),Ao="/_lunora/live/publish",To="cf-ray",vo="x-lunora-ray-id",Oo=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Io=e=>e==null?void 0:Oo.exec(e.trim())?.[1]?.toLowerCase(),Po=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(Po);const ko=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Do=-100,No=15,Uo=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&ko.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>No?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Do?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},Dt=e=>{const t=e.cf;return t===void 0?void 0:Uo(t)},tt="::relay::",Co=(e,t)=>`${e}${tt}${String(t)}`,nt="::replica::",Bo=(e,t)=>`${e}${nt}${t}`,xo=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},Sn=(e,t)=>{const n=Math.max(e.length,t.length);let r=e.length^t.length;for(let s=0;s<n;s+=1){const d=s<e.length?e.charCodeAt(s):0,i=s<t.length?t.charCodeAt(s):0;r|=d^i}return r===0},Lo=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;fn(e,r);const d=n().catch(i=>{throw e.get(t)===d&&e.delete(t),i});return e.set(t,d),d},Ho=new TextEncoder,jo=64,Mo=new Map,An=async e=>Lo(Mo,e,async()=>crypto.subtle.importKey("raw",Ho.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),jo),Tn=new TextEncoder,$o=Array.from({length:32},(e,t)=>t);new RegExp(`[${$o.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const vn=async(e,t)=>{const n=await An(e),r=await crypto.subtle.sign("HMAC",n,Tn.encode(t));return Qr(new Uint8Array(r))},Fo=async(e,t,n)=>{const r=await An(e);return crypto.subtle.verify("HMAC",r,n,Tn.encode(t))},Go="/_lunora/scheduler/dispatch",Ko="__lunora_relation__:",Qo=e=>e.startsWith(Ko),On=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[r,...s]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:Sn(t,s.join(" ").trim())},Wo=async(e,t,n)=>{const r=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:s}=n;return r!==null&&r.length>0&&s!==void 0&&s.length>0?Sn(await vn(s,t),r):On(e,n.adminToken)},zo=({forwardedIdentity:e,mutationId:t,traceparent:n})=>{const r={"content-type":"application/json",[mn]:pn,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),n!==void 0&&n.length>0&&(r.traceparent=n),r},Vo=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}}},Jo=(e,t,n)=>e?.[n]??t?.[n],Yo=(e,t,n,r)=>{const s=Jo(e,t,n);if(!(typeof s!="object"||s===null))return r.every(d=>typeof s[d]=="function")?s:void 0},In="v1",Xo=6e4,qo=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Xo),r=`${In}.${String(n)}`,s=await vn(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Zo=async(e,t,n=Date.now())=>{if(e.length===0||t.length===0)return!1;const r=t.split(".");if(r.length!==3)return!1;const[s,d,i]=r;if(s!==In||i.length===0)return!1;const p=Number(d);if(!Number.isFinite(p)||p<=n)return!1;let f;try{f=gn(i)}catch{return!1}return Fo(e,`${s}.${d}`,f)},U="/_lunora/admin/auth",es={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},B=(e,t)=>{const n=e[t];if(typeof n!="string"||n==="")throw new c(`\`${t}\` is required`,{code:"BAD_REQUEST",status:400});return n},we=(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},Pn=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(t=>typeof t=="string"))return e},re=(e,t)=>typeof e[t]=="string"?e[t]:void 0,We=(e,t)=>{const n=e[t];return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0},Nt=e=>{const t=Pn(e.role);if(t===void 0||typeof t=="string"&&t.trim()==="")throw new c("`role` is required",{code:"BAD_REQUEST",status:400});return t},Ut=e=>{const t=e.permission;if(typeof t!="object"||t===null||Array.isArray(t))throw new c("`permission` object is required",{code:"BAD_REQUEST",status:400});const n={};for(const[r,s]of Object.entries(t))Array.isArray(s)&&s.every(d=>typeof d=="string")&&(n[r]=s);return n},ts={[`${U}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${U}/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"},[`${U}/sessions`]:{build:({paging:e,query:t})=>({...e,userId:t("userId")}),http:"GET",method:"listSessions"},[`${U}/accounts`]:{build:({query:e})=>({userId:we(e,"userId")}),http:"GET",method:"listAccounts"},[`${U}/passkeys`]:{build:({query:e})=>({userId:we(e,"userId")}),http:"GET",method:"listPasskeys"},[`${U}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${U}/organizations/members`]:{build:({paging:e,query:t})=>({...e,organizationId:we(t,"organizationId")}),http:"GET",method:"listMembers"},[`${U}/organizations/invitations`]:{build:({paging:e,query:t})=>({...e,organizationId:we(t,"organizationId")}),http:"GET",method:"listInvitations"},[`${U}/sign-up-invitations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listSignUpInvitations"},[`${U}/sign-up-invitations/create`]:{build:({body:e})=>({email:B(e,"email"),expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,invitedBy:re(e,"invitedBy")}),http:"POST",method:"createSignUpInvitation"},[`${U}/sign-up-invitations/revoke`]:{build:({body:e})=>({email:B(e,"email")}),http:"POST",method:"revokeSignUpInvitation",returns:"void"},[`${U}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${U}/organizations/teams`]:{build:({paging:e,query:t})=>({...e,organizationId:we(t,"organizationId")}),http:"GET",method:"listTeams"},[`${U}/organizations/teams/members`]:{build:({paging:e,query:t})=>({...e,teamId:we(t,"teamId")}),http:"GET",method:"listTeamMembers"},[`${U}/organizations/roles`]:{build:({paging:e,query:t})=>({...e,organizationId:we(t,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${U}/users/create`]:{build:({body:e})=>({data:We(e,"data"),email:B(e,"email"),name:B(e,"name"),password:re(e,"password"),role:Pn(e.role)}),http:"POST",method:"createUser"},[`${U}/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:B(e,"userId")}},http:"POST",method:"updateUser"},[`${U}/users/role`]:{build:({body:e})=>({role:Nt(e),userId:B(e,"userId")}),http:"POST",method:"setRole"},[`${U}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:B(e,"userId")}),http:"POST",method:"banUser"},[`${U}/users/unban`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"unbanUser"},[`${U}/users/password`]:{build:({body:e})=>({newPassword:B(e,"newPassword"),userId:B(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${U}/users/remove`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${U}/users/impersonate`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"impersonateUser"},[`${U}/sessions/revoke`]:{build:({body:e})=>({sessionId:B(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${U}/sessions/revoke-all`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${U}/accounts/unlink`]:{build:({body:e})=>({accountId:B(e,"accountId"),userId:B(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${U}/two-factor/disable`]:{build:({body:e})=>({userId:B(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${U}/passkeys/delete`]:{build:({body:e})=>({passkeyId:B(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${U}/organizations/members/remove`]:{build:({body:e})=>({memberId:B(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${U}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:B(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${U}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:We(e,"metadata"),name:B(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${U}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:We(e,"metadata"),name:re(e,"name"),organizationId:B(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${U}/organizations/remove`]:{build:({body:e})=>({organizationId:B(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${U}/organizations/members/add`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),role:re(e,"role"),userId:B(e,"userId")}),http:"POST",method:"addMember"},[`${U}/organizations/members/invite`]:{build:({body:e})=>({email:B(e,"email"),inviterId:re(e,"inviterId"),organizationId:B(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${U}/organizations/members/role`]:{build:({body:e})=>({memberId:B(e,"memberId"),role:Nt(e)}),http:"POST",method:"updateMemberRole"},[`${U}/organizations/teams/create`]:{build:({body:e})=>({name:B(e,"name"),organizationId:B(e,"organizationId")}),http:"POST",method:"createTeam"},[`${U}/organizations/teams/update`]:{build:({body:e})=>({name:B(e,"name"),teamId:B(e,"teamId")}),http:"POST",method:"updateTeam"},[`${U}/organizations/teams/remove`]:{build:({body:e})=>({teamId:B(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${U}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:B(e,"teamId"),userId:B(e,"userId")}),http:"POST",method:"addTeamMember"},[`${U}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:B(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${U}/organizations/roles/create`]:{build:({body:e})=>({organizationId:B(e,"organizationId"),permission:Ut(e),role:B(e,"role")}),http:"POST",method:"createOrgRole"},[`${U}/organizations/roles/update`]:{build:({body:e})=>({permission:Ut(e),roleId:B(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${U}/organizations/roles/remove`]:{build:({body:e})=>({roleId:B(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},ns=e=>{const t=async s=>{try{return await s()}catch(d){if(d instanceof c)throw d;const i=d,p=typeof i.code=="string"?i.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",d),new c("auth admin operation failed",{code:p,status:es[p]??500})}},n=async(s,d)=>{if(e.assertAdmin(s),s.method!==d.http)throw new c(`Auth admin endpoint requires ${d.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const i=e.getAuthAdmin();if(i===void 0)throw new c("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const p=i[d.method];if(p===void 0)throw new c(`auth admin does not support \`${d.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(s.url),m={body:d.http==="POST"?await e.readJsonBody(s):{},paging:e.parsePaging(s),query:S=>e.queryParameter(f,S)},_=d.build(m),T=await t(()=>p(_));return Response.json(d.returns==="void"?{ok:!0}:T,{headers:{"cache-control":"no-store","content-type":"application/json"},status:200})},r={};for(const[s,d]of Object.entries(ts))r[s]=i=>n(i,d);return r},Ct="__lunora_admin__:getAuthAuditLog",Bt=e=>typeof e=="string"&&e!==""?e:void 0,xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,rs=e=>async(n,r)=>{e.assertAdmin(n);const s=e.getReader();if(s===void 0)throw new c("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const d=Bt(r.actorId),i=Bt(r.event),p=xt(r.sinceSeq),f=xt(r.limit),m={...d===void 0?{}:{actorId:d},...i===void 0?{}:{event:i},...p===void 0?{}:{sinceSeq:p},...f===void 0?{}:{limit:f}};let _;try{_=await s.read(m)}catch(S){throw S instanceof c?S:(console.error("[lunora] auth audit read failed:",S),new c("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const T={entries:_};return Response.json({result:be(T)},{headers:{"content-type":"application/json"},status:200})},rt="__lunora_admin__:copyAuthToJurisdiction",kn="__lunora_admin__:purgeUnpinnedAuth",os=e=>async(t,n,r)=>{if(n!==rt&&n!==kn)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 d=n===rt?await s.copy({force:r.force===!0}):await s.purge();return Response.json({result:be(d)},{headers:{"content-type":"application/json"},status:200})},ss=(e,t)=>{const n=[],r=[];if(t&&t.length>0)for(const s of t)e.resolveTableSharding?.(s)?.mode.kind==="global"?r.push(s):n.push(s);return{globalTables:r,shardLocalTables:n}},as=async(e,t,n,r,s,d)=>{if(n!==void 0&&r.length===0)return[];const i=await e.orchestrateExport(s,{args:{tables:r},defaultShardKey:d,headers:t,tables:r}),p=i.shards.filter(f=>f.error);if(p.length>0){const f=p.map(m=>`${m.shardKey}: ${m.error?.message??"unknown error"}`).join("; ");throw new c(`export failed on ${String(p.length)} of ${String(i.shards.length)} shard(s) — ${f}`,{code:"EXPORT_SHARD_FAILED",status:502})}return i.shards.flatMap(f=>f.rows??[])},Dn=async(e,t,n,r,s)=>{const d=r??e.listSchemaTables?.();r===void 0&&e.listSchemaTables===void 0&&console.warn("[lunora] export: no table list available (`listSchemaTables` is unset and no `tables` were named), so only the default shard is reachable. A `.shardBy()` deployment's other shards will be missing from this export. Name the tables explicitly, or regenerate the worker so codegen supplies the list.");const{globalTables:i,shardLocalTables:p}=ss(e,d),f=await as(t,n,d,p,s,e.defaultShardKey??"__root__"),m=e.exportGlobals,_=r===void 0||i.length>0;return(async function*(){yield*f,_&&m&&(yield*m({tables:i}))})()},is=async(e,t,n,r,s,d)=>{for await(const i of await Dn(e,t,n,r,d))s(i)},cs=new TextEncoder,ds=1e3,Nn=10,us=200,Lt=8,Un="lunoraBackupCron",Ht=24*1048576,jt=e=>{const t=e.slice(0,Nn).map(r=>Rn(r)),n=e.length-t.length;return`${t.join(", ")}${n>0?` (+${String(n)} more)`:""}`},ls=(e,t)=>{const n=new Uint8Array(new ArrayBuffer(t));let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n},ct=async(e,t,n,r)=>{if(n===void 0||!Number.isInteger(n)||n<=0)return{eligible:0,stale:[]};const s=[];let d;for(let i=0;i<ds;i+=1){const p=await e.list({cursor:d,include:["customMetadata"],prefix:t});for(const f of p.objects)Yr(f.key)&&f.customMetadata?.[Un]===r&&s.push(f.key);if(!p.truncated||p.cursor===void 0)break;d=p.cursor}return{eligible:s.length,stale:s.toSorted((i,p)=>p.localeCompare(i)).slice(n)}},hs=async(e,t,n,r,s)=>{const{stale:d}=await ct(e,t,n,r),i=new Set(s),p=d.filter(I=>i.has(I)),f=p.slice(0,us),m=d.length-f.length,_=s.length-p.length;if(f.length===0)return{deleted:[],failed:[],ignored:_,remaining:m};const T=[],S=[];for(let I=0;I<f.length;I+=Lt){const g=await Promise.allSettled(f.slice(I,I+Lt).map(async w=>(await e.delete(Rn(w)),await e.delete(w),w)));for(const[w,y]of g.entries())y.status==="fulfilled"?T.push(y.value):S.push(f[I+w])}return T.length>0&&console.info(`[lunora] backup prune kept the newest ${String(n)} and deleted ${String(T.length)}: ${jt(T)}`),S.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(S.length)}: ${jt(S)}`),{deleted:T,failed:S,ignored:_,remaining:m}},fs=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=at(e.backupPrefix??it),r=e.backupCron,{eligible:s,stale:d}=r===void 0?{eligible:0,stale:[]}:await ct(t,n,e.backupRetain,r);return{cron:r,eligible:s,keep:e.backupRetain??0,prefix:n,wouldDelete:d}},ps=async(e,t,n,r,s)=>{const d=e.backupStore;if(!d)throw new c("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!r||r.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 i={authorization:`Bearer ${r}`,"content-type":"application/json"},p=e.backupTables;let f=0,m=0,_=[];await is(e,t,i,p,P=>{const E=cs.encode(`${JSON.stringify(P)}
|
|
2
|
+
`);if(f+=1,m+=E.byteLength,m>Ht)throw new c(`scheduled backup reached ${String(m)} bytes of NDJSON, past the ${String(Ht)}-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});_.push(E)},n);const S=at(e.backupPrefix??it),I=new Date(s.scheduledTime).toISOString(),g=Xr(S,I),w=ls(_,m);_=[];const y=Zr(await crypto.subtle.digest("SHA-256",w));await d.put(g,w,{httpMetadata:{contentType:"application/x-ndjson"},sha256:y});const v={bytes:m,createdAt:I,cron:s.cron,file:g,id:I,rows:f,scheduledTime:s.scheduledTime,sha256:y,...p?{tables:p.join(",")}:{}};await d.put(qr(g),`${JSON.stringify(v,void 0,2)}
|
|
3
|
+
`,{customMetadata:{[Un]:s.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:P}=await ct(d,S,e.backupRetain,s.cron);if(P.length>0){const E=P.slice(0,Nn),L=P.length-E.length;console.info(`[lunora] backup retention: ${String(P.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${E.join(", ")}${L>0?` (+${String(L)} more)`:""}`)}}catch(P){console.warn(`[lunora] backup ${g} was written, but the retention report failed:`,P)}},ms=async(e,t)=>{const n=e.backupStore;if(!n)throw new c("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,s=e.backupRetain;if(r===void 0||s===void 0||!Number.isInteger(s)||s<=0)throw new c("backup prune needs a retention window: set `backupRetain` (and `backupCron`, which decides whose snapshots retention owns) on the worker. Without one there is nothing past the window to remove.",{code:"BACKUP_RETENTION_NOT_CONFIGURED",status:400});return hs(n,at(e.backupPrefix??it),s,r,t)},ws="/_lunora/admin/backup/retention",gs="/_lunora/admin/backup/prune",ys=e=>{const{options:t,readJsonBody:n,requireAdminOption:r}=e,s=(p,f)=>{r(p,t.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},d=async p=>($(p,"GET","Backup-retention"),s(p,"retention preview"),Response.json(await fs(t),{headers:{"cache-control":"no-store"}})),i=async p=>{$(p,"POST","Backup-prune"),s(p,"prune");const{confirm:f}=await n(p);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 ms(t,f),{headers:{"cache-control":"no-store"}})};return{[gs]:i,[ws]:d}},Mt=500,bs=(e,t,n)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new c("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new c("each batch call needs a string `functionPath`",{code:"BAD_REQUEST",status:400});if(r.functionPath.startsWith("__lunora_relation__:")||r.functionPath.startsWith("__lunora_admin__"))throw new c("reserved function path cannot be batched",{code:"FORBIDDEN",status:403});if(r.args!==void 0&&(typeof r.args!="object"||r.args===null||Array.isArray(r.args)))throw new c("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});if(r.id!==void 0&&typeof r.id!="number")throw new c("each batch call `id` must be a number",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,baselineSeq:typeof r.baselineSeq=="number"?r.baselineSeq:void 0,clientId:typeof r.clientId=="string"?r.clientId:void 0,clientSeq:typeof r.clientSeq=="number"?r.clientSeq:void 0,functionPath:r.functionPath,id:typeof r.id=="number"?r.id:t,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:n}},_s=(e,t)=>{if(e.length>Mt)throw new c(`RPC batch exceeds the ${String(Mt)}-call limit`,{code:"BAD_REQUEST",status:400});const n=new Map,r=new Set;for(const[s,d]of e.entries()){const{entry:i,shardKey:p}=bs(d,s,t);if(r.has(i.id))throw new c(`batch call id ${String(i.id)} is used twice; ids must be distinct`,{code:"BAD_REQUEST",status:400});r.add(i.id);const f=n.get(p)??[];f.push(i),n.set(p,f)}return n},Rs="/_lunora/admin/export",Es="/_lunora/admin/import",Ss="/_lunora/admin/sync",As="/_lunora/admin/connector/sync",Ts="/_lunora/admin/apply",vs="/_lunora/admin/export-tap/run",Os=new TextEncoder,Is=async e=>{const n=await oe(e,"Export")??{};if(n.tables===void 0)return{tables:void 0};if(!Array.isArray(n.tables))throw new c("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const s of n.tables){if(typeof s!="string"||s.length===0)throw new c("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(s)}return{tables:r}},ze=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0,Ps=e=>{const{applyGlobals:t,defaultShardKey:n,exportCursorStore:r,exportSinks:s,knownTables:d,queryCoordinator:i,assertAdmin:p,resolveForwardContext:f,shardDO:m,prepareExportRows:_,streamingImport:T,syncGlobals:S}=e,I=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;p(E);const C=await Is(E),{headers:z}=await f(E,L),J=await _(z,C.tables),Q=new ReadableStream({async pull(F){try{for await(const Y of J)F.enqueue(Os.encode(`${JSON.stringify(Y)}
|
|
4
|
+
`));F.close()}catch(Y){F.error(Y)}}});return new Response(Q,{headers:{"content-type":"application/x-ndjson"},status:200})},g=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;p(E);const C=await ne(E),z=typeof C.cursors=="object"&&C.cursors!==null?C.cursors:{},J=typeof C.epochs=="object"&&C.epochs!==null?C.epochs:{},Q=typeof C.limit=="number"?C.limit:void 0,F=typeof C.globalCursor=="number"?C.globalCursor:0,Y=ze(C.tables),{headers:se}=await f(E,L),X=Y??d(),le=await i.orchestrateCdcSync(m,{cursors:z,defaultShardKey:n,epochs:J,headers:se,limit:Q,tables:X}),ae=S?await S({limit:Q,sinceSeq:F}):void 0;return Response.json({global:ae,shards:le.shards},{status:200})},w=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;p(E);const C=await ne(E),z=oo(C.cursor),J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,Q=ze(C.tables),{headers:F}=await f(E,L),Y=Q??d(),se=await i.orchestrateCdcSync(m,{cursors:z.s,defaultShardKey:n,headers:F,limit:J,tables:Y}),X=[],le={...z.s};let ae=!1;for(const ce of se.shards)ae=It(X,ce.changes??[],ao(J))||ae,le[ce.shardKey]=ce.cursor;let q=z.g;if(S){const ce=await S({limit:J,sinceSeq:z.g});ae=It(X,ce.changes,J)||ae,q=ce.cursor}const ie=so({g:q,s:le,v:1}),je={changes:X,hasMore:ae,nextCursor:ie};return Response.json(je,{status:200})},y=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;p(E);const C=await ne(E),J=(Array.isArray(C.batches)?C.batches:[]).map(X=>X).filter(X=>X!==null&&typeof X=="object"&&typeof X.shardKey=="string"&&Array.isArray(X.changes)),Q=Array.isArray(C.globalChanges)?C.globalChanges:[],{headers:F}=await f(E,L),Y=await i.orchestrateApplyCdc(m,{batches:J,headers:F}),se=Q.length>0&&t?await t({changes:Q}):0;return Response.json({applied:Y.applied+se,failed:Y.failed,ok:Y.ok},{status:200})},v=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;p(E);const{headers:C}=await f(E,L),{searchParams:z}=new URL(E.url),J=z.get("dryRun")==="true",Q=z.get("onConflict")??"skip";if(Q!=="replace"&&Q!=="skip")throw new c(`onConflict must be "skip" or "replace", got ${JSON.stringify(Q)}`,{code:"BAD_REQUEST",status:400});const F=await T(E,C,J,Q),Y={...F,...J?{dryRun:!0}:{},...Q==="replace"?{onConflict:"replace"}:{}};return Response.json(Y,{headers:{"content-type":"application/json"},status:F.failed.length>0?207:200})},P=async(E,L)=>{const H=ye(E,["POST"]);if(H)return H;if(p(E),s===void 0||Object.keys(s).length===0||r===void 0)throw new c("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const C=await ne(E),z=typeof C.sink=="string"?C.sink:void 0,J=typeof C.limit=="number"&&C.limit>0?C.limit:void 0,Q=ze(C.tables);if(z===void 0)throw new c("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const F=s[z];if(F===void 0)throw new c(`Export-tap sink "${z}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:Y}=await f(E,L),se=Q??d(),X=await ro({coordinator:i,cursorStore:r,defaultShardKey:n,headers:Y,limit:J,shardDO:m,sink:F,tables:se});return Response.json(X,{headers:{"content-type":"application/json"},status:200})};return{[Ts]:y,[As]:w,[Rs]:I,[vs]:P,[Es]:v,[Ss]:g}},ks=(e,t)=>{let n;try{n=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:t,message:"line is not valid JSON",table:""},ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{error:{code:"BAD_ROW",line:t,message:"row must be a JSON object",table:""},ok:!1};const r=n;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:t,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:t,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},Ds=(e,t,n,r,s)=>{if(n?.mode.kind==="shardBy"&&typeof n.mode.field=="string"){const d=e[n.mode.field];return d==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 d=="string"?d:JSON.stringify(d)}}return{ok:!0,shardKey:r}},Ns=async(e,t,n)=>{if(!e.body)throw new c("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],s=[],d=new Map;let i=0,p=0;const f=e.body.getReader(),m=new TextDecoder;let _="",T=0;const S=I=>{p+=1;const g=I.trim();if(g.length===0)return;i+=1;const w=ks(g,p);if(!w.ok){r.push(w.error);return}const{doc:y,table:v}=w,P=t.resolveTableSharding?.(v);if(P?.mode.kind==="global"){s.push({doc:y,line:p,table:v});return}const E=Ds(y,v,P,n,p);if(!E.ok){r.push(E.error);return}const L=d.get(E.shardKey);L?L.rows.push({doc:y,table:v}):d.set(E.shardKey,{rows:[{doc:y,table:v}],shardKey:E.shardKey,startLine:p})};for(;;){const{done:I,value:g}=await f.read();if(I)break;if(g&&(T+=g.byteLength,T>yn))throw await f.cancel().catch(()=>{}),new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});_+=m.decode(g,{stream:!0});let w=_.indexOf(`
|
|
5
|
+
`);for(;w!==-1;){const y=_.slice(0,w);_=_.slice(w+1),S(y),w=_.indexOf(`
|
|
6
|
+
`)}}return _.length>0&&S(_),{errors:r,globalRows:s,perShard:d,received:i}},Us=e=>e.flatMap(t=>t.error?[{message:t.error.message,shardKey:t.shardKey,timedOut:t.error.timedOut}]:[]),$t=(e,t)=>{for(const[n,r]of Object.entries(t.inserted))e.inserted[n]=(e.inserted[n]??0)+r;for(const n of t.errors)e.errors.push({...n});e.conflicts+=t.conflicts,e.replaced+=t.replaced??0},Ft=(e,t,n,r)=>{for(const s of t)e.errors.push({code:n,line:s.line,message:`row targets global table "${s.table}" but ${r}`,table:s.table})},Cs=async(e,t,n,r,s,d,i)=>{const p=t.defaultShardKey??"__root__",{errors:f,globalRows:m,perShard:_,received:T}=await Ns(e,t,p);if(i==="replace"&&m.length>0&&(t.importGlobals===void 0||t.importGlobalsSupportsReplace!==!0))throw new c("onConflict=replace: global rows are present but no `importGlobals` that can overwrite existing rows is configured, so nothing was imported",{code:"BAD_REQUEST",status:400});const S={conflicts:0,errors:f,failed:[],inserted:{},replaced:0},I=[];if(t.resolveTableSharding===void 0&&_.size>0&&I.push("no `resolveTableSharding` is configured, so every row was routed to the default shard and no row could be recognised as `.global()` — correct for a single-shard app, silent misplacement for a sharded one"),_.size>0){const g=await n.orchestrateImport(s,{batches:[..._.values()],dryRun:d,headers:r,onConflict:i});$t(S,g),S.failed.push(...Us(g.shards))}if(m.length>0)if(!t.importGlobals)Ft(S,m,"GLOBAL_NOT_CONFIGURED","no `importGlobals` is configured");else if(d&&t.importGlobalsSupportsDryRun!==!0)Ft(S,m,"GLOBAL_DRY_RUN_UNSUPPORTED","the configured `importGlobals` cannot check rows without writing them");else{const g=m[0]?.line??1,w=await t.importGlobals({dryRun:d,onConflict:i,rows:m,startLine:g});$t(S,w)}return{conflicts:S.conflicts,errors:S.errors,failed:S.failed,inserted:S.inserted,received:T,replaced:S.replaced,...I.length>0?{warnings:I}:{}}},Bs=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Le=e=>typeof e=="object"&&e!==null?e:{},Cn=e=>{const t=Le(e)._meta??{};if(t.sensitive===!0)return!0;const n=Array.isArray(t.members)?t.members:[],r=typeof t.shape=="object"&&t.shape!==null?Object.values(t.shape):[];return[t.inner,t.keyValidator,t.valueValidator,...n,...r].some(s=>typeof s=="object"&&s!==null&&Cn(s))},Ve=e=>typeof e.kind=="string"?e.kind:"unknown",xs=(e,t)=>{let n=Le(t),r=!1;Ve(n)==="optional"&&(r=!0,n=Le(n._meta?.inner));const s=Ve(n),d=n._meta??{},i={kind:s,name:e,optional:r};if(Cn(t)&&(i.sensitive=!0),s==="id"&&typeof d.tableName=="string"&&(i.table=d.tableName),s==="array"){const p=Ve(Le(d.inner));p!=="unknown"&&(i.element=p)}return i},Ls=e=>typeof e!="object"||e===null?[]:Object.entries(e).map(([t,n])=>xs(t,n)).toSorted((t,n)=>t.name.localeCompare(n.name)),Hs="/_lunora/admin/functions",js="/_lunora/admin/cron-jobs",Ms="/_lunora/admin/architecture",$s="/_lunora/admin/openapi",Fs="/_lunora/admin/openrpc",Gs="/_lunora/admin/global/tables",Ks="/_lunora/admin/global/table",Qs="/_lunora/admin/global/facet",Gt=e=>{if(e===void 0||e==="")return;let t;try{t=et(JSON.parse(e))}catch{return}if(!Array.isArray(t))return;const n=t.flatMap(r=>{if(typeof r!="object"||r===null||typeof r.column!="string")return[];const{column:s,operator:d,path:i,value:p}=r;return[{column:s,value:p,...d===void 0?{}:{operator:d},...i===void 0?{}:{path:i}}]});return n.length===0?void 0:n},Ws=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:{}}),zs=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"}),Vs=e=>{const{assertAdmin:t,options:n,parsePaging:r,queryParameter:s,requireAdminOption:d}=e,i=g=>{$(g,"GET","Functions");const w=d(g,n.functions,{code:"FUNCTIONS_NOT_CONFIGURED",message:"functions endpoint requires a `functions` registry on the worker"}),y=Object.entries(w).flatMap(([v,P])=>P.visibility==="internal"||P.kind==="stream"?[]:[{args:[...P.argumentDescriptors??Ls(P.args)],kind:P.kind,path:v}]).toSorted((v,P)=>v.path.localeCompare(P.path));return Response.json({functions:y},{headers:{"content-type":"application/json"},status:200})},p=g=>{$(g,"GET","Cron-jobs");const w=d(g,n.cronJobs,{code:"CRON_JOBS_NOT_CONFIGURED",message:"cron-jobs endpoint requires a `cronJobs` map on the worker"}),y=Object.entries(w).flatMap(([v,P])=>P.map(E=>({args:E.args,cron:v,functionPath:E.functionPath,name:E.name,shardKey:E.shardKey,workflow:E.workflow}))).toSorted((v,P)=>v.name.localeCompare(P.name));return Response.json({jobs:y},{headers:{"content-type":"application/json"},status:200})},f=g=>($(g,"GET","Architecture"),t(g),Response.json(n.architecture??Bs,{headers:{"content-type":"application/json"},status:200})),m=g=>($(g,"GET","OpenAPI"),t(g),Response.json(n.openApiSpec??Ws,{headers:{"content-type":"application/json"},status:200})),_=g=>($(g,"GET","OpenRPC"),t(g),Response.json(n.openRpcSpec??zs,{headers:{"content-type":"application/json"},status:200})),T=async g=>{$(g,"GET","Global-tables");const w=d(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"});return Response.json(await w.listTables(),{headers:{"content-type":"application/json"},status:200})},S=async g=>{$(g,"GET","Global-table");const w=d(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(g.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 P=await w.readTablePage({...r(g),filters:Gt(s(y,"filters")),table:v});return Response.json(P,{headers:{"content-type":"application/json"},status:200})},I=async g=>{$(g,"GET","Global-facet");const w=d(g,n.globalIntrospector,{code:"GLOBALS_NOT_CONFIGURED",message:"global endpoints require a `globalIntrospector` on the worker"}),y=new URL(g.url),v=s(y,"table"),P=s(y,"column");if(v===void 0||P===void 0)throw new c("Global-facet endpoint requires `table` and `column` query params",{code:"BAD_REQUEST",status:400});const E=s(y,"limit"),L=E===void 0?void 0:Number(E),H=await w.facetColumn({column:P,filters:Gt(s(y,"filters")),limit:L!==void 0&&Number.isFinite(L)?L:void 0,table:v});return Response.json(H,{headers:{"content-type":"application/json"},status:200})};return{[js]:p,[Hs]:i,[Qs]:I,[Ks]:S,[Gs]:T,[Ms]:f,[$s]:m,[Fs]:_}},Js="/_lunora/admin/kv/namespaces",Ys="/_lunora/admin/kv/keys",Bn="/_lunora/admin/kv/value",xn=32*1048576,Kt=60,Xs=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=g=>n(g,e.kvIntrospector,{code:"KV_NOT_CONFIGURED",message:"KV endpoints require a `kvIntrospector` on the worker"}),s=g=>Response.json(g,{headers:{"content-type":"application/json"},status:200}),d=(g,w)=>{const y=new URL(g.url),v=y.searchParams.get("namespace")??"",P=y.searchParams.get("key")??"";if(v==="")throw new c(`KV-value ${w} request requires a \`namespace\` query parameter`,{code:"BAD_REQUEST",status:400});if(P==="")throw new c(`KV-value ${w} request requires a \`key\` query parameter`,{code:"BAD_REQUEST",status:400});return{key:P,namespace:v}},i=async(g,w)=>{if(!(await g.listNamespaces()).some(v=>v.binding===w))throw new c(`Unknown KV namespace binding \`${w}\``,{code:"NOT_FOUND",status:404})},p=async g=>($(g,"GET","KV-namespaces"),s({namespaces:await r(g).listNamespaces()})),f=async g=>{$(g,"GET","KV-keys");const w=r(g),y=new URL(g.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 P=y.searchParams.get("prefix")??void 0,E=y.searchParams.get("cursor")??void 0,L=y.searchParams.get("limit"),H=L===null?void 0:Number.parseInt(L,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 C=H===void 0?void 0:Math.min(H,1e3);return await i(w,v),s(await w.listKeys({cursor:E,limit:C,namespace:v,prefix:P}))},S={DELETE:async g=>{const w=r(g),y=d(g,"DELETE");return await i(w,y.namespace),await w.deleteKey(y),s({deleted:!0})},GET:async g=>{const w=r(g),y=d(g,"GET");return await i(w,y.namespace),s(await w.getValue(y))},PUT:async g=>{const w=r(g),y=await t(g,xn);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<Kt))throw new c("KV-value PUT `expirationTtl` must be an integer ≥ 60",{code:"BAD_REQUEST",status:400});const v=Math.floor(Date.now()/1e3)+Kt;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 i(w,y.namespace),await w.putValue({expiration:y.expiration,expirationTtl:y.expirationTtl,key:y.key,metadata:y.metadata,namespace:y.namespace,value:y.value}),s({ok:!0})}},I=g=>{const w=S[g.method];if(!w)throw new c("KV-value endpoint requires GET, PUT, or DELETE",{code:"METHOD_NOT_ALLOWED",status:405});return w(g)};return{[Js]:p,[Ys]:f,[Bn]:I}},qs="/_lunora/migrate",Zs="/_lunora/admin/pitr",ea="/_lunora/admin/rank",ta="/_lunora/admin/rankpage",na="/_lunora/admin/shard-registry/prune",ra="/_lunora/admin/shard-traffic",oa=new Set(["__lunora_admin__:migrationStatus","__lunora_admin__:runMigration"]),sa=new Set(["__lunora_admin__:getPitrBookmark","__lunora_admin__:pitrRestore"]),aa=async e=>{const n=await oe(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"||!oa.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}},ia=async e=>{const n=await oe(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}},ca=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}},da=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})},ua=async e=>{const n=await oe(e,"Rank page")??{};da(n);const r=ca(n.directions);return{cursor:typeof n.cursor=="string"?n.cursor:null,directions:r,index:n.index,partitionKey:typeof n.partitionKey=="string"?n.partitionKey:void 0,table:n.table,take:typeof n.take=="number"?n.take:void 0}},la=async e=>{const n=await oe(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}},ha=async e=>{const n=await oe(e,"Shard-registry prune")??{};if(n.tables!==void 0&&!(Array.isArray(n.tables)&&n.tables.every(r=>typeof r=="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}},fa=async e=>{const n=await ne(e);if(typeof n.functionPath!="string"||!sa.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}},pa=e=>{const{defaultShard:t,forwardToShard:n,isAdmin:r,queryCoordinator:s,resolveForwardContext:d,shardDO:i,shardedTables:p}=e,f=(w,y)=>{if(w.method!=="POST")throw new c(`${y} endpoint requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});if(!r(w))throw new c("Admin auth required",{code:"FORBIDDEN",status:403})},m=async(w,y)=>{f(w,"Migration");const v=await aa(w),{headers:P}=await d(w,y),E=await s.orchestrateMigration(i,{args:v.args,defaultShardKey:t,functionPath:v.functionPath,headers:P,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},_=async(w,y)=>{f(w,"Rank");const v=await ia(w),{headers:P}=await d(w,y),E=await s.orchestrateRank(i,{headers:P,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})},T=async(w,y)=>{f(w,"Rank page");const v=await ua(w),{headers:P}=await d(w,y),E=await s.orchestrateRankPage(i,{...v,headers:P});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},S=async(w,y)=>{f(w,"Shard-traffic");const v=await la(w),{headers:P}=await d(w,y),E=await s.orchestrateShardTraffic(i,{headers:P,table:v.table});return Response.json(E,{headers:{"content-type":"application/json"},status:200})},I=async(w,y)=>{f(w,"Shard-registry prune");const v=await ha(w),P=p(),E=(v.tables??[]).filter(C=>!P.includes(C));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:L}=await d(w,y),H=await fo(s.registry,i,{dryRun:v.dryRun,headers:L,tables:v.tables??P});return Response.json(H,{status:H.failed.length>0?207:200})},g=async(w,y)=>{if($(w,"POST","PITR"),!r(w))throw new c("admin PITR endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403});const v=await fa(w),{headers:P}=await d(w,y),E=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:v.args,functionPath:v.functionPath}),headers:P,method:"POST"});return n(i,v.shardKey??t,E)};return{[qs]:m,[Zs]:g,[ea]:_,[ta]:T,[na]:I,[ra]:S}},ma=1,wa=0,ga=32,ya=512,ba=/^[a-z][\d_a-z*/-]{0,255}(?:@[a-z][\d_a-z*/-]{0,13})?=[\u0020-\u002B\u002D-\u003C\u003E-\u007E]{1,256}$/,_a=e=>{if(e==null)return;const t=e.trim();if(t.length===0||t.length>ya)return;const n=t.split(",");if(!(n.length>ga)){for(const r of n)if(!ba.test(r.trim()))return;return t}},Ra=e=>{const t=jr(e.headers.get("traceparent"));if(t===void 0)return;const n=_a(e.headers.get("tracestate"));return{parentSpanId:t.parentSpanId,sampled:t.sampled,traceId:t.traceId,...n===void 0?{}:{traceState:n}}},Qt=(e,t={})=>{const n=Ra(e),r=t.trustInbound===!0?n:void 0,s=_e(8),d=r?.traceId??_e(16),i=Kr(t.sampling,r===void 0?s:d),{rayId:p}=t,f=i.isTraced&&(r===void 0||r.sampled);return{decision:i,ignoredUpstream:n!==void 0&&r===void 0,trace:{sampled:f,spanId:s,traceFlags:f?ma:wa,traceId:d,...r?.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},...r?.traceState===void 0?{}:{traceState:r.traceState},...p===void 0?{}:{rayId:p}}}},Wt=(e,t)=>{t.traceparent=wn(e.traceId,e.spanId,e.sampled),e.traceState!==void 0&&(t.tracestate=e.traceState),e.rayId!==void 0&&(t[vo]=e.rayId)},Ea=(e,t)=>{let n;return()=>{if(n===void 0){const r=Gr(e),s=t===void 0?void 0:t.cf;n=Mr(Fr(r),$r(r,s))}return n}},Sa="/_lunora/admin/scheduled",Aa="/_lunora/admin/scheduled/status",Ta="/_lunora/admin/scheduled/ws",va="/_lunora/admin/scheduled/cancel",Oa="/_lunora/admin/scheduled/dead",Ia="/_lunora/admin/scheduled/dead/retry",Pa="/_lunora/admin/scheduled/dead/cancel",ka="/_lunora/admin/scheduled/pool/release",Da=e=>{const{checkWsAdmin:t,requireSchedulerNamespace:n,resolveSchedulerStub:r,schedulerInstanceName:s}=e,d=(m,_)=>T=>{if(T.method!=="GET")throw new c(`${_} endpoint requires GET`,{code:"METHOD_NOT_ALLOWED",status:405});const S=new URL(T.url).searchParams.get("cursor"),I=S===null||S===""?"":`?cursor=${encodeURIComponent(S)}`;return r(T).fetch(new Request(`https://scheduler.internal${m}${I}`,{method:"GET"}))},i=(m,_,T=_)=>async S=>{if(S.method!=="POST")throw new c(`${T} requires POST`,{code:"METHOD_NOT_ALLOWED",status:405});const I=r(S),g=await oe(S,_);if(typeof g?.id!="string"||g.id==="")throw new c(`${_} requires a string \`id\``,{code:"BAD_REQUEST",status:400});return I.fetch(new Request(`https://scheduler.internal${m}`,{body:JSON.stringify({id:g.id}),headers:{"content-type":"application/json"},method:"POST"}))},p=async m=>{if(m.method!=="POST")throw new c("Scheduled pool-release endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const _=r(m),T=await oe(m,"Scheduled pool-release");if(typeof T?.pool!="string"||T.pool==="")throw new c("Scheduled pool-release requires a string `pool`",{code:"BAD_REQUEST",status:400});const S=typeof T.id=="string"&&T.id!==""?T.id:void 0;return _.fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify(S===void 0?{pool:T.pool}:{id:S,pool:T.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 _=n();return Re(_,s).fetch(new Request("https://scheduler.internal/ws",{headers:{Upgrade:"websocket"}}))};return{[va]:i("/cancel","Scheduled-cancel","Scheduled-cancel endpoint"),[Pa]:i("/dead/cancel","Scheduled dead-letter action"),[Oa]:d("/dead","Scheduled dead-letter"),[Ia]:i("/dead/retry","Scheduled dead-letter action"),[Sa]:d("/list","Scheduled-list"),[ka]:p,[Aa]:d("/status","Scheduler-status"),[Ta]:f}},Na="/_lunora/scheduled",Ln="/_lunora/queue",Hn=16*1048576,Ua=e=>{const{assertAdmin:t,dispatchScheduled:n,queueHandler:r}=e,s=async(i,p,f)=>{if(t(i),i.method!=="POST")throw new c("scheduled tick endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});const m=await oe(i,"Scheduled tick"),_=typeof m?.cron=="string"?m.cron:"";if(_==="")throw new c("scheduled tick requires a `cron` expression",{code:"BAD_REQUEST",status:400});return await n({cron:_,noRetry:()=>{},scheduledTime:Date.now()},p,f),Response.json({cron:_,ok:!0})},d=async(i,p,f)=>{if(t(i),i.method!=="POST")throw new c("queue dispatch endpoint requires POST",{code:"METHOD_NOT_ALLOWED",status:405});if(!r)throw new c("no queueHandler configured",{code:"BAD_REQUEST",status:400});const m=await oe(i,"Queue dispatch",Hn);if(!Array.isArray(m?.messages))throw new c("queue dispatch requires a `messages` array",{code:"BAD_REQUEST",status:400});const _=typeof m.queue=="string"?m.queue:"",T=m.messages.filter(I=>typeof I=="object"&&I!==null&&typeof I.id=="string").map(I=>({body:I.body,id:I.id})),S=await r({messages:T,queue:_},p,f);return Response.json({retry:S?.retry??[]})};return{[Ln]:d,[Na]:s}},Ca=(e,...t)=>{let n=e.cf;for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return typeof n=="string"?n:void 0},ot={mtls:e=>Ca(e,"tlsClientAuth","certVerified")==="SUCCESS"},Ba=e=>e===void 0||e===!1?()=>!1:e===!0?()=>!0:typeof e=="function"?e:(Object.hasOwn(ot,e)?ot[e]:void 0)??(()=>!1),xa=e=>typeof e=="string"&&Object.hasOwn(ot,e),La=e=>{const t=xa(e)?e:void 0;if(e!==void 0&&t===void 0)return()=>{};let n=!1;return r=>{n||t!==void 0&&r.cf!==void 0||(n=!0,console.warn(t===void 0?'[lunora] Ignored an inbound `traceparent`, so this request starts a new trace instead of joining the caller\'s. That is the safe default: the header is caller-supplied, and trusting it lets any client choose which trace its spans and logs join. If this worker sits behind a gateway, service mesh, or Cloudflare Access that sets `traceparent` itself, set `trustInboundTraceContext: true` on createWorker() (or `"mtls"` to trust only edge-verified client certificates). Set it to `false` to keep this behaviour and silence this message.':`[lunora] \`trustInboundTraceContext: "${t}"\` cannot be satisfied on this host: the request carries no platform-injected \`cf\` metadata, which is what that signal reads, so every inbound \`traceparent\` is ignored and this request starts a new trace. Off Cloudflare, trust the upstream some other way — \`trustInboundTraceContext: true\` when nothing untrusted can reach this worker, or a predicate that verifies whatever your own front door sets. Set it to \`false\` to keep this behaviour and silence this message.`))}},Ha="/_lunora/admin/vector/indexes",ja="/_lunora/admin/vector/query",Ma=e=>{const{readJsonBody:t,requireAdminOption:n}=e,r=async d=>{$(d,"GET","Vector-indexes");const i=n(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});return Response.json({indexes:await i.listIndexes()},{headers:{"content-type":"application/json"},status:200})},s=async d=>{$(d,"POST","Vector-query");const i=n(d,e.vectorIntrospector,{code:"VECTORS_NOT_CONFIGURED",message:"vector endpoints require a `vectorIntrospector` on the worker"});if(i.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(d);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 i.queryIndex({name:f.name,text:f.text,topK:f.topK});return Response.json(m,{headers:{"content-type":"application/json"},status:200})};return{[Ha]:r,[ja]:s}},$a="/_lunora/admin/workflows/instances",Fa="/_lunora/admin/workflows/instance",Ga="/_lunora/admin/workflows/status",Ka={complete:!0,errored:!0,paused:!0,queued:!0,rollingBack:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},Qa=e=>e!==null&&Object.hasOwn(Ka,e)?e:void 0,zt=(e,t)=>{const n=e.searchParams.get(t);if(n===null)return;const r=Number(n);return Number.isInteger(r)&&r>0?r:void 0},Je=(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},Vt=()=>{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})},Wa=e=>{const{assertAdmin:t,resolveWorkflowsClient:n}=e,r=async(i,p,f)=>{$(i,"GET","Workflows instances"),t(i);const m=n(p);if(!m)return Response.json({configured:!1,instances:[],page:1,perPage:0,totalCount:0});const _=Je(f,"name"),T=Qa(f.searchParams.get("status"));return Response.json(await m.listInstances({page:zt(f,"page"),perPage:zt(f,"perPage"),status:T,workflowName:_}))},s=async(i,p,f)=>{$(i,"GET","Workflows instance"),t(i);const m=n(p);return m?Response.json(await m.getInstance({instanceId:Je(f,"id"),workflowName:Je(f,"name")})):Vt()},d=async(i,p)=>{$(i,"POST","Workflows status"),t(i);const f=n(p);if(!f)return Vt();const m=await oe(i,"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:_}=m;if(_!=="pause"&&_!=="restart"&&_!=="resume"&&_!=="terminate")throw new c("Workflows status action must be one of: pause, restart, resume, terminate",{code:"BAD_REQUEST",status:400});return Response.json(await f.setInstanceStatus({action:_,instanceId:m.id,workflowName:m.name}))};return{[Fa]:s,[$a]:r,[Ga]:d}},Jt="lunora",st="lunora.bearer.",za=/^[!-~]+$/u,Va=e=>{if(e.startsWith(st))try{const t=new TextDecoder("utf-8",{fatal:!0}).decode(gn(e.slice(st.length)));return za.test(t)?t:void 0}catch{return}},Yt=e=>{const t=(e.headers.get("sec-websocket-protocol")??"").split(",").map(r=>r.trim()).filter(r=>r.length>0);let n;for(const r of t)n??=Va(r);return{forwarded:t.filter(r=>!r.startsWith(st)),token:n}},Xt=(e,t)=>{if(t.token===void 0||e.headers.has("authorization"))return e;const n=new Headers(e.headers);return n.set("authorization",`Bearer ${t.token}`),new Request(e,{headers:n})},qt=(e,t)=>{const n=new Headers(e);return t.forwarded.length>0?n.set("sec-websocket-protocol",t.forwarded.join(", ")):n.delete("sec-websocket-protocol"),n},Zt=(e,t)=>{const{webSocket:n}=t;if(t.status!==101||!n||!e.forwarded.includes(Jt))return t;const r=new Headers(t.headers);r.set("sec-websocket-protocol",Jt);const s={headers:r,status:101,webSocket:n};return new Response(null,s)},Ja={[Bn]:xn,[Ln]:Hn,[no]:to},Ya="https://queue.lunora.internal",en=()=>({publish:()=>Promise.reject(new c("ctx.live.publish is unavailable: this worker does not serve live streams",{code:"LIVE_STREAMS_UNSUPPORTED",status:501}))}),Xa=async(e,t)=>{const n=new c(`ctx.live.publish to "${t}" failed with HTTP ${String(e.status)}`,{code:"INTERNAL",status:e.status>=400?e.status:500});let r;try{r=await e.json()}catch{return n}const s=r?.error;return typeof s?.code!="string"||e.status<400?n:new c(typeof s.message=="string"?s.message:`ctx.live.publish to "${t}" was refused`,{code:s.code,status:e.status})},tn="/_lunora/rpc",qa="/_lunora/rpc-batch",Za="/_lunora/ws",ve=(e,t,n)=>({resourceAttributes:Ea(e,t),...n===void 0?{}:{waitUntil:n}}),Ye=e=>e?.waitUntil?{waitUntil:t=>e.waitUntil?.(t)}:{},nn=e=>({spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId,...e.parentSpanId===void 0?{}:{parentSpanId:e.parentSpanId}}),Xe=(e,t)=>{const{method:n}=e,r=e.headers.get("user-agent")??void 0,s=Io(e.headers.get(To)),d=s===void 0?{}:{rayId:s};let i;try{i=t??new URL(e.url)}catch{return{method:n,...d,userAgent:r}}const p=i.port===""?void 0:Number(i.port);return{host:i.hostname,method:n,path:i.pathname,port:Number.isNaN(p)?void 0:p,...d,scheme:i.protocol.replace(":",""),userAgent:r}},rn="/_lunora/voice/",ei="/_lunora/admin/cron-jobs/run",ti="/_lunora/admin/ws-token",ni="/_lunora/admin/",He="/_lunora/",ri="/_lunora/migrate",oi="/_lunora/status",si=e=>e.startsWith(ni)||e===ri,Ne=e=>{if(Qo(e))throw new c("`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard",{code:"FORBIDDEN",status:403})},Ue=async e=>await e===!0,on=(e,t)=>{const n=e.headers.get(At);if(n===null)return;const r=Hr(n);if(r===void 0)throw new c(`malformed ${At} header`,{code:"BAD_REQUEST",status:400});if(r.subject!==(t?.userId??null))throw new c("the session changed since this write was queued",{code:"IDENTITY_MISMATCH",status:409})},sn="/api/auth",ai="__lunora_admin__:recordAuthEvent",an="__lunora_admin__:listPushSubscriptions",ii=["/sign-in","/sign-up","/callback"],ci=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;if(!e.startsWith(`${n}/`))return!1;const r=e.slice(n.length);return ii.some(s=>r===s||r.startsWith(`${s}/`))},cn=(e,t)=>{const n=t.endsWith("/")?t.slice(0,-1):t;return e===n||e.startsWith(`${n}/`)},Ce=(e,t,n,r)=>{const s=Pr(n),d=s?n.code:"INTERNAL_SERVER_ERROR",i=s?n.status:500,{message:p,name:f,stack:m}=Nr(n),_=Ur(n,{capped:!1});return{durationMs:t,error:{code:d,message:p,name:f,status:i,...m===void 0?{}:{stack:m},..._===void 0?{}:{internal:_}},functionPath:e,ok:!1,...r.fanOut?{fanOut:{failed:0,shards:0,table:r.fanOut.table}}:{},...r.shardKey?{shardKey:r.shardKey}:{}}},jn=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},Mn=({identity:e})=>e!==null&&xr(jn(e)),di=e=>{if(Mn(e))throw new c("authentication token expired",{code:"TOKEN_EXPIRED",status:401});return e},ui=e=>{if(!Mn(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}},dn=e=>e.waitUntil?{waitUntil:t=>{e.waitUntil?.(t)}}:void 0,li=e=>{const t=e?.queue;return typeof t=="string"&&t.length>0?t:"unknown"},Oe=new WeakMap,hi=async(e,t,n,r,s=Oe.get(e),d=new URL(e.url).origin)=>{const i={"content-type":"application/json"},p=e.headers.get("authorization"),f=e.headers.get("cookie"),m=e.headers.get("x-d1-bookmark"),_=e.headers.get("x-lunora-mutation-id"),T=e.headers.get("x-lunora-client-id"),S=e.headers.get("x-lunora-client-seq"),I=e.headers.get("x-lunora-base-seq");p&&(i.authorization=p),f&&(i.cookie=f),m&&(i["x-d1-bookmark"]=m),_&&(i["x-lunora-mutation-id"]=_),T&&(i["x-lunora-client-id"]=T),S&&(i["x-lunora-client-seq"]=S),I&&(i["x-lunora-base-seq"]=I);const g=Jr(e.headers,r);if(g&&(i["x-lunora-client-ip"]=g),i["x-lunora-origin"]=d,!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"]=Lr(w.userId);const y=jn(w);y!==void 0&&(i["x-lunora-identity-exp"]=String(y));const{userId:v,...P}=w,E=Object.keys(P).length>0?P:null;return E&&(i["x-lunora-identity"]=Cr(E)),{claims:E,headers:i,identity:w,userId:v}},fi=new Set(["concat","first","groupBy","max","min","rank","sum","topK"]),pi=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"||!fi.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},mi=(e,t)=>{e?.LUNORA_DEBUG_RPC&&console.warn(`[lunora:rpc] ${t.fanOut?"fan-out":`shard=${t.shardKey??"(root)"}`} ${t.functionPath}`)},qe=(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}},wi=new Set(["args","functionPath","shardKey"]),gi=(e,t)=>t===void 0&&Object.keys(e).every(n=>wi.has(n)),yi=async e=>{const t=await _n(e);let n;try{n=JSON.parse(t)}catch{throw new c("RPC body must be valid JSON",{code:"BAD_REQUEST",status:400})}if(!n||typeof n!="object"||typeof n.functionPath!="string")throw new c("RPC envelope is missing `functionPath`",{code:"BAD_REQUEST",status:400});const r=n;if(r.args!==void 0&&bn(r.args,"RPC"),r.shardKey!==void 0&&typeof r.shardKey!="string")throw new c("RPC `shardKey` must be a string",{code:"BAD_REQUEST",status:400});const s=n,d=pi(s.fanOut),i=s.args??{};if(d&&s.functionPath.startsWith("__lunora_relation__:")){const p=i.table;if(typeof p=="string"&&p!==d.table)throw new c("RPC `args.table` must match the authorized `fanOut.table` for a relation fan-out",{code:"BAD_REQUEST",status:400});i.table=d.table}return{args:i,fanOut:d,forwardBody:gi(n,d)?t:void 0,functionPath:s.functionPath,shardKey:s.shardKey}},Be=new Map,bi=5e3,_i=4096,Ri=async(e,t)=>{const n=Date.now(),r=Be.get(t);if(r!==void 0&&r.expiresMs>n)return r.relayCount;r!==void 0&&Be.delete(t);let s=0;try{const d=await Re(e,t).fetch(new Request("https://shard.internal/_lunora/route"));if(d.ok){const i=await d.json();typeof i.relayCount=="number"&&i.relayCount>0&&(s=Math.floor(i.relayCount))}}catch{s=0}return fn(Be,_i),Be.set(t,{expiresMs:n+bi,relayCount:s}),s},un=(e,t)=>{if(!(e===null||typeof e!="object"))return Object.entries(e).find(([,n])=>n===t)?.[0]},xe=(e,t,n,r=JSON.stringify({args:t,functionPath:e}))=>new Request("https://shard.internal/rpc",{body:r,headers:n,method:"POST"}),Ei=["x-lunora-userid","x-lunora-identity","x-lunora-identity-exp","x-lunora-client-ip"],Si=(e,t)=>{for(const n of Ei){e.delete(n);const r=t[n];r!==void 0&&e.set(n,r)}},Ze=e=>e.headers.get("Upgrade")?.toLowerCase()==="websocket",ln=(e,t)=>{const n=new Headers(e.headers),r=[...n.keys()];for(const s of r)s.startsWith("x-lunora-")&&n.delete(s);return Si(n,t),n},hn=async(e,t)=>{if(!t||t.length===0)return!1;const n=new URL(e.url).searchParams.get("token");return n===null?!1:Zo(t,n)},Ai=(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 uo(`d1:${e}`,t);if(typeof n.list=="function"&&typeof n.head=="function"&&typeof n.createMultipartUpload=="function")return Ge(`r2:${e}`,!0);if(typeof n.send=="function"&&typeof n.sendBatch=="function"&&typeof n.get!="function")return Ge(`queue:${e}`,!0);if(typeof n.connectionString=="string")return Ge(`hyperdrive:${e}`,!0)},Ti=e=>{for(const t of Object.keys(e??{}))if(t.slice(t.indexOf(" ")+1).startsWith(He))throw new c(`route "${t}" is under the reserved ${He} 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})},vi=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})},$n=e=>{vi(e);const t=Ba(e.trustInboundTraceContext),n=La(e.trustInboundTraceContext),r=e.defaultShardKey??"__root__",s=e.queryCoordinator??po({registry:mo(e.resolveTableSharding,r)}),d=lo(e.resolveIdentity,e.identity),i=Ke(e.shardDO,e.jurisdiction),p=e.schedulerDO===void 0?void 0:Ke(e.schedulerDO,e.jurisdiction),f=e.voiceAgents===void 0?void 0:Object.fromEntries(Object.entries(e.voiceAgents).map(([o,a])=>[o,Ke(a,e.jurisdiction)]));let m=!1;const _=o=>{if(o===void 0||e.jurisdiction===void 0)return o;m||(m=!0,console.warn(`[lunora] jurisdiction "${e.jurisdiction}" pins placement, so region hints (\`shardRegion\`, replica and relay placement) are not sent. Residency wins.`))},T=async(o,a,u,l=e.shardRegion?.(a))=>Re(o,a,_(l)).fetch(u);let S;const I=()=>e.adminToken??S;let g;const w=o=>{const a=o??{};if(g??=un(o,e.shardDO),S!==void 0||e.adminToken!==void 0)return;const u=a.LUNORA_ADMIN_TOKEN;typeof u=="string"&&u.length>0&&(S=u)},y=new WeakSet,v=o=>On(o,I())||y.has(o),P=async o=>{if(!(e.adminGate===void 0||y.has(o)))try{await Ue(e.adminGate(o,Oe.get(o)))&&y.add(o)}catch{}},E=async(o,a,u,l={})=>{const h=await hi(o,a,u,e.trustedClientIpHeader,l.executionContext,l.url?.origin);return e.functions!==void 0&&(h.headers[mn]=pn),h},L=async(o,a,u,l)=>di(await E(o,a,u,l)),H=async(o,a)=>{const u=await E(o,a,e.resolveIdentity);if(y.has(o)&&u.headers.authorization===void 0){const l=I();l!==void 0&&(u.headers.authorization=`Bearer ${l}`)}return u};let C=!1,z=!1;const J=()=>{z||(z=!0,console.warn("[lunora] `replicaReads: true` has no effect without `functions` — read eligibility is decided from the function registry."))},Q=o=>{if(!e.allowUnauthenticatedShardAccess){const a=o==="fan-out"?"authorizeFanOut":"authorizeShard";throw new c(`${o} access is default-denied: configure \`${a}\` on the worker, or set \`allowUnauthenticatedShardAccess: true\` to explicitly allow unauthenticated ${o} access (relying solely on per-row RLS).`,{code:o==="fan-out"?"FORBIDDEN_FANOUT":"FORBIDDEN_SHARD",status:403})}C||(C=!0,console.warn([`[lunora] SECURITY: serving ${o} access with \`allowUnauthenticatedShardAccess: true\` and no \`authorizeShard\`/\`authorizeFanOut\` — `,"any caller (including unauthenticated ones) can target any shard / fan out across the table. ","This is safe only if every table is protected by per-row RLS. Configure `authorizeShard`/`authorizeFanOut` to gate it."].join("")))},F=async(o,a,u=!1)=>{if(a.includes(tt)||a.includes(nt))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403});if(!u)if(e.authorizeShard){if(!await Ue(e.authorizeShard({identity:o,shardKey:a})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else a!==r&&Q("shard")},Y=pa({defaultShard:r,forwardToShard:T,isAdmin:v,queryCoordinator:s,resolveForwardContext:H,shardDO:i,shardedTables:()=>(e.listSchemaTables?.()??[]).filter(o=>e.resolveTableSharding?.(o)?.mode.kind==="shardBy")}),se=async(o,a,u,l,h)=>{const{__lunoraLive:b,topic:A}=a,D=l?.shardKey??r;h==="trusted"?await F(null,D,!0):D!==r&&await F(h.identity,D);const N=await T(i,D,new Request(new URL(Ao,o),{body:JSON.stringify({data:be(u??null),stream:b,topic:A}),headers:{"content-type":"application/json"},method:"POST"}));if(!N.ok)throw await Xa(N,A)},X=async(o,a,u,l,h,b)=>{Ne(o);const A=zo({forwardedIdentity:h,mutationId:l,traceparent:b});return T(i,u,xe(o,a,A))},le=async(o,a,u,l,h)=>{const b=Yo(u.env,u.context?.exports,o,["create"]);if(b===void 0)throw new c(`${l} targets workflow "${o}", which is on neither ctx.exports nor env`,{code:"CRON_JOB_FAILED",status:500});if(bo(a))throw new c(`${l} params ${_o}`,{code:"BAD_REQUEST",status:400});try{await b.create(h===void 0?{params:a}:{id:h,params:a})}catch(A){if(!So(A))throw A}},ae=async(o,a,u,l)=>{if(o.workflow){await le(o.workflow,o.args??{},{context:u,env:a},`cron job "${o.name}"`);return}if(o.functionPath===void 0)throw new c(`cron job "${o.name}" has neither a function target nor a workflow target`,{code:"CRON_JOB_FAILED",status:500});const h=await X(o.functionPath,o.args??{},o.shardKey??r,void 0,void 0,l);if(!h.ok)throw new c(`cron job "${o.name}" (${o.functionPath}) failed with shard status ${String(h.status)}`,{code:"CRON_JOB_FAILED",status:500})},q=o=>{if(!v(o))throw new c("admin endpoint requires a valid admin bearer",{code:"ADMIN_FORBIDDEN",status:403})},ie=(o,a,u)=>{if(q(o),a===void 0)throw new c(u.message,{code:u.code,status:400});return a},je=async(o,a,u,l,h,b)=>{const A=e.cronJobs?.[o];if(!A)return 0;for(const D of A)try{await ae(D,a,u,b)}catch(N){l.push(h(N))}return A.length},ce=async(o,a,u)=>{if(q(o),$(o,"POST","cron-jobs run"),!e.cronJobs)throw new c("cron-jobs run endpoint requires a `cronJobs` map on the worker",{code:"CRON_JOBS_NOT_CONFIGURED",status:400});const l=await ne(o),h=typeof l.name=="string"?l.name:"";if(h==="")throw new c("cron-jobs run endpoint requires a job `name`",{code:"BAD_REQUEST",status:400});const b=Object.values(e.cronJobs).flat().find(A=>A.name===h);if(!b)throw new c(`no cron job named "${h}" is registered`,{code:"CRON_JOB_NOT_FOUND",status:404});return await ae(b,a,u),Response.json({name:h,ran:!0},{status:200})},dt=async o=>{const a=typeof o.pool=="string"&&o.pool.length>0?o.pool:void 0;if(!a||!p||typeof o.id!="string")return;const u=typeof o.instanceName=="string"&&o.instanceName.length>0?o.instanceName:"default";try{await Re(p,u).fetch(new Request("https://scheduler.internal/complete",{body:JSON.stringify({id:o.id,pool:a}),headers:{"content-type":"application/json"},method:"POST"}))}catch{}},Fn=async(o,a,u)=>{$(o,"POST","Scheduler dispatch");const l=await _n(o),h=a??{},b=typeof h.LUNORA_SCHEDULER_SECRET=="string"?h.LUNORA_SCHEDULER_SECRET:void 0,A=e.adminToken??(typeof h.LUNORA_ADMIN_TOKEN=="string"?h.LUNORA_ADMIN_TOKEN:void 0);if(!await Wo(o,l,{adminToken:A,schedulerSecret:b}))throw new c("Scheduler dispatch requires a valid signature or admin bearer",{code:"DISPATCH_UNAUTHENTICATED",status:403});let N;try{N=JSON.parse(l)}catch{throw new c("Scheduler dispatch body must be valid JSON",{code:"BAD_REQUEST",status:400})}const R=N??{},O=R.args??{},k=typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(typeof R.workflow=="string"&&R.workflow.length>0)return await le(R.workflow,O,{context:u,env:a},"scheduled workflow",k),await dt(R),Response.json({ok:!0},{status:200});if(typeof R.functionPath!="string"||R.functionPath.length===0)throw new c("Scheduler dispatch is missing `functionPath`",{code:"BAD_REQUEST",status:400});const x=typeof R.shardKey=="string"&&R.shardKey.length>0?R.shardKey:r,M=Vo(o),G=await X(R.functionPath,O,x,k,M,o.headers.get("traceparent")??void 0);return await dt(R),G},Gn=rs({assertAdmin:q,getReader:()=>e.authAuditReader}),Kn=os({assertAdmin:q,getMove:()=>e.authJurisdictionMove}),Qn=async(o,a)=>{q(o);const u=e.notifySubscriptionStore;if(u===void 0)return Response.json({result:be({subscriptions:[]})},{headers:{"content-type":"application/json"},status:200});const l=a?.kind,h=a?.userId,b=a?.limit,A=l==="fcm"||l==="web-push"?l:void 0,D=typeof h=="string"&&h!==""?h:void 0,N=typeof b=="number"&&Number.isFinite(b)?Math.trunc(b):0,R=N>0?Math.min(N,1e3):1e3,k=(await u.list({kind:A,limit:R,userId:D})).filter(x=>A!==void 0&&x.kind!==A?!1:D===void 0||(x.userId??null)===D).map(({keys:x,token:M,...G})=>G);return Response.json({result:be({subscriptions:k})},{headers:{"content-type":"application/json"},status:200})},Wn=async(o,a)=>{if(!a.fanOut&&!(a.functionPath!==Ct&&a.functionPath!==an&&a.functionPath!==rt&&a.functionPath!==kn))return await P(o),a.functionPath===Ct?Gn(o,a.args??{}):a.functionPath===an?Qn(o,a.args):Kn(o,a.functionPath,a.args??{})},zn=Ps({applyGlobals:e.applyGlobals,assertAdmin:q,exportCursorStore:e.exportCursorStore,exportSinks:e.exportSinks,defaultShardKey:r,knownTables:()=>[...e.listSchemaTables?.()??[]],queryCoordinator:s,resolveForwardContext:H,shardDO:i,prepareExportRows:async(o,a)=>Dn(e,s,o,a,i),streamingImport:(o,a,u,l)=>Cs(o,e,s,a,i,u,l),syncGlobals:e.syncGlobals}),Me=(o,a)=>{const u=o.searchParams.get(a);return u===null||u===""?void 0:u},$e=o=>{const a=new URL(o.url),u=a.searchParams.get("limit"),l=a.searchParams.get("offset"),h=u===null?void 0:Number.parseInt(u,10),b=l===null?void 0:Number.parseInt(l,10);return{limit:h!==void 0&&Number.isFinite(h)&&h>=0?h:void 0,offset:b!==void 0&&Number.isFinite(b)&&b>=0?b:void 0}},ut=()=>{if(p===void 0)throw new c("scheduled endpoints require a `schedulerDO` namespace on the worker",{code:"SCHEDULER_NOT_CONFIGURED",status:400});return p},Vn=Da({checkWsAdmin:async o=>v(o)||hn(o,I()),requireSchedulerNamespace:ut,resolveSchedulerStub:o=>(q(o),Re(ut(),e.schedulerInstanceName??"default")),schedulerInstanceName:e.schedulerInstanceName??"default"}),Jn=Wa({assertAdmin:q,resolveWorkflowsClient:e.workflowsClient??(()=>{})}),Yn=eo({assertAdmin:q,parsePaging:$e,queryParameter:Me,readBodyBytes:zr,requireAdminOption:ie,storage:{storageBuckets:e.storageBuckets,storageDelete:e.storageDelete,storageDownload:e.storageDownload,storageList:e.storageList,storageSignedUrl:e.storageSignedUrl,storageUpload:e.storageUpload}}),Xn=ys({options:e,readJsonBody:ne,requireAdminOption:ie}),qn=Ma({readJsonBody:ne,requireAdminOption:ie,vectorIntrospector:e.vectorIntrospector}),Zn=Xs({kvIntrospector:e.kvIntrospector,readJsonBody:ne,requireAdminOption:ie}),er=ho({logArchive:e.logArchive,readJsonBody:ne,requireAdminOption:ie}),tr=Vs({assertAdmin:q,options:{cronJobs:e.cronJobs,functions:e.functions,globalIntrospector:e.globalIntrospector,architecture:e.architecture,openApiSpec:e.openApiSpec,openRpcSpec:e.openRpcSpec},parsePaging:$e,queryParameter:Me,requireAdminOption:ie}),nr=o=>{const a=[],u=i??o?.SHARD;if(u!==void 0&&a.push(co("durable-object:default",u,r)),e.health?.disableBindingProbes!==!0)for(const[l,h]of Object.entries(o??{})){const b=Ai(l,h);b!==void 0&&a.push(b)}for(const l of e.health?.probes??[])a.push(l);return a},rr=io({appName:e.health?.appName,appVersion:e.health?.appVersion,auth:e.health?.auth??"public",cacheTtlMs:e.health?.cacheTtlMs,isAdmin:v,resolveProbes:nr}),or=o=>{const a=R=>"args"in R?{...R,args:et(R.args)}:R,u=e.schedulerInstanceName??"default",l=()=>Re(o,u),h=async(R,O)=>{const k=await l().fetch(new Request(`https://scheduler.internal${R}`,O));if(!k.ok)throw new c(`ctx.scheduler: SchedulerDO ${R} failed (${String(k.status)}): ${await k.text()}`,{code:"INTERNAL",status:500});return await k.json()},b=async(R,O)=>await h(R,{body:JSON.stringify(O),headers:{"content-type":"application/json"},method:"POST"}),A=R=>{const O=R;if(O==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 O.binding=="string"&&O.binding.length>0)return{workflow:O.binding};if(typeof O.__lunoraRef=="string")return{functionPath:O.__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})},D=async()=>(await Ro(async O=>h(O===void 0?"/list":`/list?cursor=${encodeURIComponent(O)}`,{method:"GET"}))).map(O=>a(O)),N=async(R,O,k={})=>{const x=A(O),{id:M}=await b("/schedule",{args:Dr("ctx.scheduler",String(x.functionPath??x.workflow),k),scheduledFor:Math.ceil(R),...x});return M};return{cancel:async R=>await b("/cancel",{id:R}),get:async R=>{const O=await h(`/get?id=${encodeURIComponent(R)}`,{method:"GET"});return O.record===void 0?null:a(O.record)},list:D,runAfter:async(R,O,k)=>{if(!Number.isFinite(R)||R<0)throw new c("ctx.scheduler.runAfter: `delayMs` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(Date.now()+R,O,k)},runAt:async(R,O,k)=>{if(!Number.isFinite(R))throw new c("ctx.scheduler.runAt: `date` must be a non-negative finite number",{code:"INVALID_INPUT",status:400});return await N(R,O,k)}}},sr=async(o,a,u)=>{const{claims:l,headers:h,identity:b,userId:A}=ui(await E(o,a,d)),D=ve(a,o,k=>u.waitUntil?.(k)),N=k=>async(x,M={})=>{const G=x.__lunoraRef;if(typeof G!="string")throw new c("ctx.run*: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ne(G),k!==r&&await F(b,k);const j=await Pe(o,G,be(M),k,{...h,"x-lunora-system":"1"},D),K=await j.json();if(K.error)throw new c(K.error.message??"shard RPC failed",{code:K.error.code??"INTERNAL",status:j.status});return et(K.result)},R=N(r),O=async(k,x,M={})=>{k!==void 0&&k!==r&&await F(b,k);const G=new Headers;for(const[j,K]of Object.entries(M.headers??{}))j.toLowerCase().startsWith("x-lunora-")||G.set(j,K);for(const[j,K]of Object.entries(h))G.set(j,K);return T(i,k??r,new Request(new URL(x,o.url),{headers:G,method:M.method??"GET",...M.body===void 0?{}:{body:M.body}}))};return{auth:{getIdentity:()=>Promise.resolve(l),userId:A},cache:u.cache,fetch:globalThis.fetch.bind(globalThis),fetchShard:O,forShard:k=>{const x=N(k);return{runAction:x,runMutation:x,runQuery:x}},live:e.liveStreams===!1?en():{publish:(k,x,M)=>se(o.url,k,x,M,{identity:b})},runAction:R,runMutation:R,runQuery:R,...p===void 0?{}:{scheduler:or(p)},...u.waitUntil===void 0?{}:{waitUntil:u.waitUntil.bind(u)},...e.storage===void 0?{}:{storage:yo(e.storage(a,new URL(o.url).origin))}}},ar=async(o,a,u)=>{if(!e.httpRouter)return;const l=await sr(o,a,u);try{return await e.httpRouter.fetch(o,{...a,__lunoraCtx:l},u)}catch(h){return console.error("[lunora] httpRouter (SSR) handler threw:",h),new Response("Internal Server Error",{status:500})}},lt=new Set(Object.values(e.functions??{}).flatMap(o=>o.lifecycle==="socket"&&typeof o.socketPath=="string"?[o.socketPath]:[])),ht=async(o,a,u)=>{if(!Ze(o))throw new c("WebSocket upgrade header missing",{code:"BAD_REQUEST",status:426});const l=kt(o,de);if(l)return l;const h=u.searchParams.get("shard")??r,b=Yt(o),{headers:A,identity:D}=await E(Xt(o,b),a,d,{executionContext:Oe.get(o)}),N=v(o)||await hn(o,I());await F(D,h,N);const R=qt(ln(o,A),b),O=un(a,e.shardDO);let k=h,x;if(O!==void 0){R.set("x-lunora-shard-binding",O);const M=lt.has(u.pathname)?0:await Ri(i,h);M>0&&(k=Co(h,Math.floor(Math.random()*M)),x=Dt(o))}return Zt(b,await T(i,k,new Request(o,{headers:R}),x))},ir=async(o,a,u)=>{if(f===void 0)return new Response("Not found",{status:404});if(!Ze(o))return new Response("Expected a WebSocket upgrade",{headers:{allow:"GET"},status:426});const l=kt(o,de);if(l)return l;let h;try{h=decodeURIComponent(u.pathname.slice(rn.length))}catch{return new Response("Unknown voice agent",{status:404})}const b=Object.hasOwn(f,h)?f[h]:void 0;if(b===void 0)return new Response("Unknown voice agent",{status:404});const A=u.searchParams.get("threadKey");if(A===null||A.length===0)return new Response("Missing threadKey",{status:400});const D=Yt(o),{headers:N,identity:R}=await E(Xt(o,D),a,d,{executionContext:Oe.get(o)});if(e.authorizeShard){if(!await Ue(e.authorizeShard({identity:R,shardKey:A})))throw new c("Forbidden shard",{code:"FORBIDDEN_SHARD",status:403})}else Q("shard");const O=qt(ln(o,N),D);return Zt(D,await T(b,A,new Request(o,{headers:O})))},cr=async(o,a,u)=>{if(e.authorizeFanOut){if(!await Ue(e.authorizeFanOut(u,o.table,a)))throw new c("Forbidden fan-out",{code:"FORBIDDEN_FANOUT",status:403});return}if(a.startsWith("__lunora_relation__:"))throw new c("reverse cross-backend relation reads (`__lunora_relation__:*`) require `authorizeFanOut` to be configured on the worker",{code:"FORBIDDEN_FANOUT",status:403});if(e.authorizeShard)throw new c("Fan-out requires `authorizeFanOut` to be configured on the worker when `authorizeShard` is set",{code:"FORBIDDEN_FANOUT",status:403});Q("fan-out")},Ie=async(o,a)=>{if(!(!o.fanOut&&o.functionPath.startsWith("__lunora_admin__:"))){if(o.fanOut){await cr(o.fanOut,o.functionPath,a);return}await F(a,o.shardKey??r)}},dr=(o,a,u)=>{if(e.replicaReads!==!0)return;if(e.functions===void 0){J();return}if(e.functions[a]?.kind!=="query"||u.includes(nt)||u.includes(tt))return;const l=Dt(o);return l===void 0?void 0:{name:Bo(u,l),region:l}},ur=async(o,a,u,l,h,b)=>{const A=dr(o,a,l);if(A!==void 0){const D={...h,"x-lunora-replica-read":"1",...g===void 0?{}:{"x-lunora-shard-binding":g}},N=xo(o.headers.get("x-lunora-min-seq"));N!==void 0&&(D["x-lunora-min-seq"]=String(N));const R=await T(i,A.name,xe(a,u,D,b),A.region);if(R.status!==421)return R}return T(i,l,xe(a,u,h,b))},Pe=async(o,a,u,l,h,b,A={})=>{const D=Date.now(),{observability:N,sampling:R}=e,O=Xe(o,A.url),{decision:k,ignoredUpstream:x,trace:M}=Qt(o,{...O.rayId===void 0?{}:{rayId:O.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(o)});x&&n(o);const G={...h,[vt]:k.keepErrors?"1":"0",[St]:"1"};Wt(M,G);try{const j=await ur(o,a,u,l,G,A.forwardBody),K=Rt(j.headers.get(Et));ue(N,{...O,...nn(M),durationMs:Date.now()-D,functionPath:a,ok:j.ok,shardKey:l,...j.ok?{}:{error:{...K,code:K?.code??"SHARD_ERROR",message:K?.message??`shard returned ${String(j.status)}`,status:j.status}}},b,void 0,{isTraced:M.sampled,keepErrors:k.keepErrors});const he=new Response(j.body,{headers:j.headers,status:j.status,statusText:j.statusText});return he.headers.set("x-lunora-shard-key",l),he.headers.delete(Et),he}catch(j){throw ue(N,{...O,...nn(M),...Ce(a,Date.now()-D,j,{shardKey:l})},b,void 0,{isTraced:M.sampled,keepErrors:k.keepErrors}),j}},lr=o=>{if(o.fanOut&&o.shardKey)throw new c("RPC envelope cannot set both `shardKey` and `fanOut`",{code:"BAD_REQUEST",status:400});o.fanOut||Ne(o.functionPath)},hr=async(o,a,u,l)=>{$(o,"POST","RPC");const h=await yi(o),b={forwardBody:h.forwardBody,url:l};mi(a,h),lr(h);const A=await Wn(o,h);if(A!==void 0)return A;const{headers:D,identity:N}=await L(o,a,d,b);on(o,N),await Ie(h,N);const R=qe(h,e);{const O=Date.now(),{observability:k}=e,x=ve(a,o,u&&(j=>u.waitUntil?.(j)));if(h.fanOut){const j=Xe(o,l);try{const K=await s.fanOut(i,{args:h.args??{},fanOut:h.fanOut,functionPath:h.functionPath,headers:D});return ue(k,{durationMs:Date.now()-O,fanOut:{failed:K.failed,shards:K.ok+K.failed,table:h.fanOut.table},functionPath:h.functionPath,...j,ok:!0},x),Response.json(K,{headers:{"content-type":"application/json"},status:200})}catch(K){throw ue(k,{...Ce(h.functionPath,Date.now()-O,K,{fanOut:{table:h.fanOut.table}}),...j},x),K}}const M=h.shardKey??r,G=()=>Pe(o,h.functionPath,h.args??{},M,D,x,b);return R&&e.x402Charge?e.x402Charge(o,{functionPath:h.functionPath,price:R.price},G,Ye(u)):G()}},fr=async(o,a,u)=>{$(o,"POST","RPC batch");const l=await ne(o),{calls:h}=l;if(!Array.isArray(h))throw new c("RPC batch `calls` must be an array",{code:"BAD_REQUEST",status:400});const{headers:b,identity:A}=await L(o,a,d);on(o,A);const D=_s(h,r);for(const W of D.values())for(const V of W)if(e.functions?.[V.functionPath]?.x402)throw new c(`paid (\`.x402\`) function "${V.functionPath}" cannot be called in a batch; dispatch it individually over ${tn}`,{code:"BAD_REQUEST",status:400});await Promise.all([...D.entries()].flatMap(([W,V])=>V.map(ee=>Ie({args:ee.args,functionPath:ee.functionPath,shardKey:W},A))));const{observability:N,sampling:R}=e,O=ve(a,o,u&&(W=>u.waitUntil?.(W))),k=Xe(o),{decision:x,ignoredUpstream:M,trace:G}=Qt(o,{...k.rayId===void 0?{}:{rayId:k.rayId},...R===void 0?{}:{sampling:R},trustInbound:t(o)});M&&n(o);const j={isTraced:G.sampled,keepErrors:x.keepErrors},K=W=>{const V={...b,"content-type":"application/json",[vt]:x.keepErrors?"1":"0",[St]:"1"};return Wt({...G,spanId:W},V),V},he=W=>({parentSpanId:W,spanId:_e(8),traceFlags:G.traceFlags,traceId:G.traceId}),De=[],Fe=[],wt=(W,V,ee,fe)=>({body:{error:{code:ee,message:fe}},id:W.id,status:V}),gt=(W,V,ee,fe,ge)=>{for(const te of W)ue(N,ge(te),O,void 0,j),De.push(wt(te,V,ee,fe))},Or=(W,V,ee,fe,ge,te)=>{for(const Ee of W){const Se=ge.get(Ee.id),pe=Se?.status??te,me=pe<400,Ae=me?void 0:Rt(Se?.errorDetail);ue(N,{durationMs:fe,functionPath:Ee.functionPath,...k,...he(ee),ok:me,shardKey:V,...me?{}:{error:{...Ae,code:Ae?.code??"SHARD_ERROR",message:Ae?.message??`batched call returned ${String(pe)}`,status:pe}}},O,void 0,j)}};await Promise.all([...D.entries()].map(async([W,V])=>{const ee=_e(8),fe=new Request("https://shard.internal/rpc-batch",{body:JSON.stringify({calls:V}),headers:new Headers(K(ee)),method:"POST"}),ge=Date.now();let te;try{te=await T(i,W,fe)}catch(Z){const Te=Date.now()-ge,{body:_t}=kr(Z,{fallbackCode:"SHARD_UNAVAILABLE",redactedMessage:"shard unavailable"});gt(V,502,_t.code,_t.message,Ir=>({...Ce(Ir.functionPath,Te,Z,{shardKey:W}),...k,...he(ee)}));return}const Ee=Date.now()-ge,Se=te.headers.get("x-d1-bookmark");Se&&Fe.push(Se);let pe;try{pe=await te.json()}catch{const Z=`shard batch returned a non-JSON response (${String(te.status)})`;gt(V,te.status,"SHARD_UNAVAILABLE",Z,Te=>({durationMs:Ee,error:{code:"SHARD_UNAVAILABLE",message:Z,status:te.status},functionPath:Te.functionPath,...k,...he(ee),ok:!1,shardKey:W}));return}const me=Array.isArray(pe.results)?pe.results:[],Ae=new Set(me.map(Z=>Z.id));Or(V,W,ee,Ee,new Map(me.map(Z=>[Z.id,Z])),te.status),De.push(...me.map(({errorDetail:Z,...Te})=>Te));for(const Z of V)Ae.has(Z.id)||De.push(wt(Z,te.status,"SHARD_UNAVAILABLE",`shard batch omitted result for call ${String(Z.id)}`))}));const yt={"content-type":"application/json"},[bt]=Fe;return Fe.length===1&&bt!==void 0&&(yt["x-d1-bookmark"]=bt),Response.json({results:De},{headers:yt,status:200})},pr=async(o,a,u,l={},h={})=>{try{const b=u.__lunoraRef;if(typeof b!="string")throw new c("serverQuery: expected a function reference from the generated `api`",{code:"BAD_REQUEST",status:400});Ne(b);const{headers:A,identity:D}=await L(o,a,d,{executionContext:h.context}),N={args:l,functionPath:b,shardKey:h.shardKey};await Ie(N,D);const R=h.shardKey??r,O=ve(a,o,h.waitUntil),k=()=>Pe(o,b,l,R,A,O),x=qe(N,e);return x&&e.x402Charge?await e.x402Charge(o,{functionPath:b,price:x.price},k,Ye(h.waitUntil?{waitUntil:h.waitUntil}:h.context)):await k()}catch(b){return Ot(b)}},ft=async(o,a,u)=>{const{observability:l}=e,h=Date.now(),b=_e(16),A=_e(8),D=dn(a),N=wn(b,A,!0);try{const R=await u(N);return ue(l,{durationMs:Date.now()-h,functionPath:o,ok:!0,spanId:A,traceId:b},D),R}catch(R){throw ue(l,{...Ce(o,Date.now()-h,R,{}),spanId:A,traceId:b},D),R}finally{Tt(l,D)}},pt=async(o,a,u,l)=>{w(a);const h=[],b=O=>O instanceof Error?O:new Error(String(O)),A=e.crons?.[o.cron];if(A)try{await A(o,a,u)}catch(O){h.push(b(O))}const D=await je(o.cron,a,u,h,b,l),N=!!e.backupStore&&e.backupCron!==void 0&&e.backupCron===o.cron;if(N)try{await ps(e,s,i,I(),o)}catch(O){h.push(b(O))}if(!A&&D===0&&!N){const O=[...new Set([...Object.keys(e.crons??{}),...Object.keys(e.cronJobs??{})])];console.warn(`[lunora] scheduled("${o.cron}") fired but no cron handler is registered for that expression. Registered: ${O.length===0?"(none)":O.join(", ")}. Check that \`triggers.crons\` in wrangler.jsonc matches the app's cron definitions.`)}const[R]=h;if(h.length===1&&R)throw R;if(h.length>1)throw new AggregateError(h,`scheduled("${o.cron}") had ${String(h.length)} failure(s)`)},mr=Ua({assertAdmin:q,dispatchScheduled:pt,queueHandler:e.queueHandler}),wr=async(o,a)=>{try{const u=o??{},l=e.adminToken??(typeof u.LUNORA_ADMIN_TOKEN=="string"?u.LUNORA_ADMIN_TOKEN:void 0);if(!l||l.length===0)return;await T(i,r,xe(ai,{outcome:a},{authorization:`Bearer ${l}`,"content-type":"application/json"}))}catch{}},gr=async(o,a,u,l)=>{if(!e.authHandler)return;const h=e.authBasePath??sn,b=cn(u.pathname,h)?Vr(o):void 0;let A;try{A=await e.authHandler(b?.request??o)}catch(D){throw b?.overflowed()?new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413}):D}if(b?.overflowed())throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});if(A)return ci(u.pathname,h)&&l.waitUntil?.(wr(a,A.status>=400?"fail":"ok")),A},yr=async({args:o,env:a,functionPath:u,request:l,shardKey:h,waitUntil:b})=>{bn(o,"REST");const A={functionPath:u,...h===void 0?{}:{shardKey:h}},{headers:D,identity:N}=await L(l,a,d);await Ie(A,N);const R=h??r,O=ve(a,l,b),k=()=>Pe(l,u,o,R,D,O),x=qe(A,e);return x&&e.x402Charge?e.x402Charge(l,{functionPath:u,price:x.price},k,Ye({waitUntil:b})):k()},br=Wr({functions:e.functions??{},invoke:yr,readJsonBody:ne,edgeCache:e.restEdgeCache,...e.restRateLimit?{rateLimit:e.restRateLimit}:{}}),ke=e.routes!==void 0&&Object.keys(e.routes).length>0?e.routes:void 0,_r=new Set(e.liveStreamRoutes),Rr=(o,a)=>{if(!ke)return;const u=`${o.method} ${a.pathname}`;if(!_r.has(u))return ke[u]??ke[a.pathname]};Ti(ke);const Er={[oi]:o=>o.method!=="GET"&&o.method!=="HEAD"?new Response(void 0,{headers:{allow:"GET, HEAD"},status:405}):Response.json({ok:!0},{headers:{"cache-control":"no-store"}}),[Za]:(o,a,u)=>ht(o,a,u),[tn]:(o,a,u,l)=>hr(o,a,l,u),[qa]:(o,a,u,l)=>fr(o,a,l),[Go]:(o,a,u,l)=>Fn(o,a,l),[ei]:(o,a,u,l)=>ce(o,a,l),[ti]:async o=>{$(o,"POST","ws-token"),q(o);const a=I();if(a===void 0)throw new c("ws-token minting requires a configured admin token",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const u=await qo(a);return Response.json(u,{headers:{"cache-control":"no-store"}})},...Y,...zn,...Vn,...Jn,...Yn,...Xn,...qn,...Zn,...er,...tr,...rr,...br,...ns({assertAdmin:q,getAuthAdmin:()=>e.authAdmin,parsePaging:$e,queryParameter:Me,readJsonBody:ne})};let de=Pt(e.security),mt=!1;const Sr=o=>{mt||(mt=!0,de=Pt(e.security,o??{}))},Ar=async(o,a)=>{si(a)&&await P(o)},Tr=(o,a)=>{if(!(a.pathname.startsWith(He)||e.authHandler!==void 0&&cn(a.pathname,e.authBasePath??sn))||o.method!=="POST"&&o.method!=="PUT")return;const l=Number(o.headers.get("content-length")??""),h=Ja[a.pathname]??yn;if(Number.isFinite(l)&&l>h)throw new c("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})},vr=async(o,a,u)=>{Oe.set(o,u);const l=new URL(o.url);Tr(o,l);const h=await gr(o,a,l,u);if(h)return h;if(lt.has(l.pathname)&&o.method==="GET"&&Ze(o))return ht(o,a,l);const b=Rr(o,l);if(b)return b(o,a,u);const A=mr[l.pathname];if(A)return A(o,a,u);const D=Er[l.pathname];if(D)return await Ar(o,l.pathname),D(o,a,l,u);if(e.voiceAgents!==void 0&&l.pathname.startsWith(rn))return ir(o,a,l);if(l.pathname.startsWith(He))return new Response("Not found",{status:404});const N=await ar(o,a,u);if(N&&N.status!==404)return N;const R=await e.authDiscoveryHandler?.(o);return R?(await N?.body?.cancel(),R):N??new Response("Not found",{status:404})};return{async fetch(o,a,u){e.passThroughOnException&&u.passThroughOnException?.(),Sr(a),w(a);const l=wo(o,de);if(l)return l;const h=go(o,de);if(h)return Qe(h,o,de);try{const b=await vr(o,a,u);return Qe(b,o,de)}catch(b){return Qe(Ot(b),o,de)}finally{Tt(e.observability,dn(u))}},async queue(o,a,u){await ft(`queue:${li(o)}`,u,async l=>{const h=e.liveStreams===!1?en():{publish:(b,A,D)=>se(Ya,b,A,D,"trusted")};await e.queue?.(o,a,u,{traceparent:l},h,e.queueFetchImpl)})},async scheduled(o,a,u){await ft(`cron:${o.cron}`,u,async l=>{await pt(o,a,u,l)})},serverQuery:pr}},Oi=e=>$n(e),Ii=e=>typeof e=="function"?{fetch:e}:e,Pi=e=>!!e.backupCron||Object.keys(e.crons??{}).length>0||Object.keys(e.cronJobs??{}).length>0,ki=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}:{}},tc=(e,t)=>{const n=Ii(e),{email:r,queue:s,scheduled:d}=ki(e),i=f=>{const _={...Oi({...f,httpRouter:n})};return d!==void 0&&!Pi(f)&&(_.scheduled=async(T,S,I)=>{await d(T,S,I)}),s!==void 0&&f.queue===void 0&&(_.queue=async(T,S,I)=>{await s(T,S,I)}),r!==void 0&&(_.email=async(T,S,I)=>{await r(T,S,I)}),_};if(typeof t!="function")return i(t);const p=t;return{fetch:(f,m,_)=>i(p(m)).fetch(f,m,_),queue:(f,m,_)=>i(p(m)).queue?.(f,m,_)??Promise.resolve(),scheduled:(f,m,_)=>i(p(m)).scheduled(f,m,_),serverQuery:(f,m,_,T,S)=>i(p(m)).serverQuery(f,m,_,T,S),...r===void 0?{}:{email:(f,m,_)=>i(p(m)).email?.(f,m,_)??Promise.resolve()}}},Di=(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}},nc=(e={})=>(t,n,r)=>$n(Di(e,n)).fetch(t,n,r??Br),rc=e=>e;export{rt as COPY_AUTH_TO_JURISDICTION_OP,Ct as GET_AUTH_AUDIT_LOG_OP,Br as NOOP_EXECUTION_CONTEXT,kn as PURGE_UNPINNED_AUTH_OP,ac as composeIdentityResolvers,Oi as composeWorker,nc as createLunoraHandler,$n as createWorker,rc as defineRpcEnvelope,Ri as probeRelayCount,Di as resolveLunoraOptions,ic as routeIdentityResolvers,tc as withFrameworkWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{decodeWire as c}from"@lunora/wire";import{e as u,a as f}from"./identity-header-ByHiZBcH.mjs";import{LunoraError as s}from"./LunoraError-PkZWF-_g.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"]=u(e.userId)),e.identity!==void 0&&(a["x-lunora-identity"]=f(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 c(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-C2B_SATf.mjs";import"./portable-json-CSq6T1AU.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 B,a as F}from"./base64-Bl1_r2k1.mjs";import{LunoraError as v}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as L}from"./applyJurisdiction-DKQE8kOA.mjs";const Ke=r=>({listShardKeys(e){return r[e]??[]}}),_e=(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,V=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=V(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)}},H=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}},G=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=H(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}},D=0,U=1,J=2,k=(r,e)=>r<e?-1:r>e?1:0,T=r=>r==null?D:typeof r=="number"?U:J,O=(r,e)=>{const s=T(r),o=T(e);return s!==o?s<o?-1:1:s===D?0:s===U?k(r,e):k(String(r),String(e))},Y=(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)},Q=r=>F(new TextEncoder().encode(JSON.stringify(r))),W=r=>{try{const e=JSON.parse(new TextDecoder().decode(B(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||Y(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?Q({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,c=0;for(const d of r){if(d.kind==="err"){c+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}a+=1;const i=y(d.value),u=i?.inserted??{};for(const[h,p]of Object.entries(u))s[h]=(s[h]??0)+p;const l=i?.errors;Array.isArray(l)&&o.push(...l),t+=i?.conflicts??0,n+=i?.replaced??0,e.push({result:{conflicts:i?.conflicts??0,errors:i?.errors??[],inserted:u,replaced:i?.replaced??0},shardKey:d.shardKey})}return{conflicts:t,errors:o,failed:c,inserted:s,ok:a,replaced: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=L(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 h=await ae(u),p=`shard "${e}" returned ${String(u.status)}`;return{code:h?.code??"SHARD_HTTP_ERROR",kind:"err",message:h===void 0||h.message.length===0?p:`${p}: ${h.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],E=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,s)=>{let o=0,t=r.length;for(;o<t;){const n=Math.floor((o+t)/2),a=r[n];a!==void 0&&s(e,a)<0?t=n:o=n+1}return o},pe=(r,e,s)=>{const o=[];for(const t of r){const n=ye(o,t,s);n<e&&(o.splice(n,0,t),o.length>e&&o.pop())}return o},me=(r,e)=>{const s=[];for(const a of r)if(Array.isArray(a))for(const c of a){if(c===null||typeof c!="object")continue;const d=c[e.by],i=typeof d=="number"&&Number.isFinite(d)?d:Number.NEGATIVE_INFINITY;s.push({row:c,score:i})}const o=e.direction??"desc",t=(a,c)=>o==="asc"?k(a.score,c.score):k(c.score,a.score),{k:n}=e;return!Number.isInteger(n)||n<0||2*n>=s.length?(s.sort(t),s.slice(0,n).map(a=>a.row)):pe(s,n,t).map(a=>a.row)},ge=(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 me(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Re=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}},Ae=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:ge(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const n=await E(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 E(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=async(d,i)=>g(o,d,m({args:i,functionPath:"__lunora_admin__:importShard",headers:t.headers}),s),c=await w(n,e,async d=>{if(t.dryRun===!0){const i=await a(d.shardKey,{dryRun:!0,rows:[],startLine:1});if(i.kind==="err")return i;if(y(i.value)?.dryRun!==!0)return{code:"SHARD_DRY_RUN_UNSUPPORTED",kind:"err",message:`shard "${d.shardKey}" cannot check rows without writing them`,shardKey:d.shardKey,timedOut:!1}}return a(d.shardKey,{dryRun:t.dryRun===!0,onConflict:t.onConflict??"skip",rows:[...d.rows],startLine:d.startLine??1})});return ne(c)},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 G(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 f=>{const C=d.perShard[f],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,f,m({args:R,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(b.kind==="err")return{error:{message:b.message,timedOut:b.timedOut},shardKey:f};const A=X(y(b.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:f}}),u=[];let l=0,h=0,p;for(const f of i){if(f.error){h+=1;continue}l+=1,p===void 0&&f.directions&&f.directions.length>0&&(p=f.directions),u.push({hasMore:f.hasMore??!1,head:0,rows:f.rows??[],shardKey:f.shardKey})}const _=q(u,a,p??c,d.perShard);return{continueCursor:_.nextCursor,failed:h,isDone:_.isDone,ok:l,page:_.page,partial:h>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{_e as createDefaultShardRegistry,Ae as createQueryCoordinator,Ke as createStaticShardRegistry,Re as pruneShardRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{encodeWire as w,decodeWire as f}from"@lunora/wire";import{e as S,a as I}from"./identity-header-ByHiZBcH.mjs";import{O as p,a as g}from"./origin-paywall-B6eOO67m.mjs";import{applyJurisdiction as N,resolveShard as L}from"./applyJurisdiction-DKQE8kOA.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)),typeof e.why=="string"&&(t.why=e.why),t},x=(e,t={})=>{const l=N(e,t.jurisdiction),y=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,m,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"};y&&(a[g]=p,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:w(m??{}),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-PkZWF-_g.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","Last-Event-ID","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"],v=31536e3,C=new Set(["GET","HEAD","OPTIONS"]),R=e=>{if(e===!1)return;const o=e===void 0||e===!0?{}:e,s=o.maxAge??v,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}},X=(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}),j=(e,o)=>{if(!o.csrf.enabled||C.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-Live-Connection","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,j as enforceOrigin,F as enforceWebSocketOrigin,B as handleCorsPreflight,X as resolveSecurity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./error-detail-C46mdOTW.mjs";import{e as i,a as m,f as o}from"./observability-9slk__Gi.mjs";export{i as emitLogEvent,m as emitRpcEvent,o as flushSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{redactArgs as h,redactCredentials as b}from"@lunora/observability";import{S as y,n as O}from"./observability-sinks-lLKqc_rV.mjs";const f=t=>{try{t()}catch{}},u=(t,n)=>{const r={};for(const o of y)t[o]!==void 0&&(r[o]=t[o]);return t.flush&&(r.flush=o=>{f(()=>t.flush?.(o))}),t.onLog&&(r.onLog=(o,e)=>{const c=n.log===void 0?o:n.log(o);c!==void 0&&f(()=>t.onLog?.(c,e))}),t.onMetric&&(r.onMetric=(o,e)=>{const c=n.metric===void 0?o:n.metric(o);c!==void 0&&f(()=>t.onMetric?.(c,e))}),t.onRpc&&(r.onRpc=(o,e)=>{const c=n.rpc===void 0?o:n.rpc(o);c!==void 0&&f(()=>t.onRpc?.(c,e))}),t.onSpan&&(r.onSpan=(o,e)=>{const c=n.span===void 0?o:n.span(o);c!==void 0&&f(()=>t.onSpan?.(c,e))}),r},l=5;let a=0;const S=t=>{if(a>=l)return;a+=1;const n=a===l?" Further enricher failures are silenced until the isolate restarts.":"";try{console.error(`[lunora:observability] enrichSink's enricher threw; delivering the event without its extra attributes.${n}`,t instanceof Error?t.name:typeof t)}catch{}},j=(t,n)=>{if(t instanceof Error)return n({...Object.fromEntries(Object.entries(t)),message:t.message,name:t.name});const r=Reflect.get(t,"toJSON");if(typeof r=="function"){const e=r.call(t);return e!==t?n(e):Object.fromEntries(Object.entries(t).map(([c,s])=>[c,n(s)]))}if(Array.isArray(t))return t.map(e=>n(e));const o=Object.getPrototypeOf(t);return o!==Object.prototype&&o!==null?t:Object.fromEntries(Object.entries(t).map(([e,c])=>[e,n(c)]))},x=()=>({ancestors:new WeakSet,copies:new WeakMap}),g=(t,n=x())=>{if(typeof t=="symbol"||typeof t=="function")return String(t);if(typeof t!="object"||t===null)return t;if(!n.ancestors.has(t)){if(n.copies.has(t))return n.copies.get(t);n.ancestors.add(t);try{const r=j(t,o=>g(o,n));return n.copies.set(t,r),r}finally{n.ancestors.delete(t)}}},d=(t,n,r)=>{try{const o=t(g(n),r),e=o===void 0?void 0:Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0)),c=e===void 0?void 0:g(e),s=r==="log"?h(c):b(c);return O(s)}catch(o){S(o);return}},A=(t,n)=>u(t,{log:r=>{const o=d(n,r,"log");return o===void 0?r:{...r,fields:{...o,...r.fields}}},metric:r=>{const o=d(n,r,"metric");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},rpc:r=>{const o=d(n,r,"rpc");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}},span:r=>{const o=d(n,r,"span");return o===void 0?r:{...r,attributes:{...o,...r.attributes}}}}),m=(t,n)=>{const r=t.split("*");if(r.length===1)return n===t;const o=r[0]??"",e=r.at(-1)??"";if(n.length<o.length+e.length||!n.startsWith(o)||!n.endsWith(e))return!1;const c=n.length-e.length;let s=o.length;for(const i of r.slice(1,-1)){const p=n.indexOf(i,s);if(p===-1||p+i.length>c)return!1;s=p+i.length}return s<=c},E=(t,n)=>n.exclude?.some(r=>m(r,t))?!1:n.include===void 0||n.include.length===0||n.include.some(r=>m(r,t)),L=(t,n)=>{const r=o=>E(o.functionPath,n)?o:void 0;return u(t,{log:r,metric:r,rpc:r,span:r})};export{A as enrichSink,L as filterSink,m as globMatch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a="x-lunora-want-error-detail",c="x-lunora-error-detail";const d=t=>{if(!(t instanceof Error))return{message:String(t),name:typeof t};const{code:n}=t;return{...typeof n=="string"?{code:n}:{},message:t.message,name:t.name,...t.stack===void 0?{}:{stack:t.stack.slice(0,8192)}}},s=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);const i=(t,n)=>n instanceof Error?{...n,message:n.message,name:n.name}:n,E=(t,{capped:n=!0}={})=>{if(t instanceof Error)try{const{internal:e}=t;if(!s(e))return;const r=JSON.stringify(e,i);if(n&&r.length>16384)return;const o=JSON.parse(r);return s(o)?o:void 0}catch{return}},f=t=>{try{const n=JSON.parse(JSON.stringify(t,i));return s(n)?n:void 0}catch{return}},p=t=>{if(t!=null)try{const n=JSON.parse(decodeURIComponent(t));if(typeof n?.message!="string"||typeof n.name!="string")return;const{internal:e,...r}=n;return s(e)?{...r,internal:e}:r}catch{return}};export{c as E,a as W,d as a,E as b,p as d,f as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-CSq6T1AU.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},i=e=>r(c.encode(e)),u=e=>i(JSON.stringify(e)),f=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{}},y=e=>!e.startsWith(o)&&a(e)?e:`${o}${r(c.encode(e))}`,p=e=>typeof e=="number"&&Date.now()>=e,x="x-lunora-expect-subject",b=e=>{const t=f(e)?.subject;return t===null||typeof t=="string"?{subject:t}:void 0};export{x as E,u as a,i as b,b as d,y as e,p as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as p}from"./identity-header-ByHiZBcH.mjs";const h=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)},_=n=>{const e=new WeakMap;return(t,r,l)=>{const o=e.get(t);if(o)return o;const i=Promise.resolve(n(t,r,l));return e.set(t,i),i}},I=5e3,g=500,x=32,T=n=>{const e=n.headers.get("cookie")??"",t=n.headers.get("authorization")??"";if(!(e===""&&t===""))return`${t}\0${e}`},R=n=>{if(!n)return;const{exp:e,expiresAtMs:t}=n;return typeof t=="number"&&Number.isFinite(t)?t:typeof e=="number"&&Number.isFinite(e)?e*1e3:void 0},D=(n,e={})=>{const t=e.ttlMs??I,r=Math.max(1,e.maxEntries??g),l=e.cacheKey??T,o=_(n);if(t<=0)return o;const i=new Map;return(E,M,y)=>{const s=l(E);if(s===void 0||y?.access!==void 0)return o(E,M,y);const m=Date.now(),a=i.get(s);if(a&&a.expiresAt>m)return a.value;if(a&&i.delete(s),i.size>=r){let c=0;for(const[d,A]of i){if(c>=x)break;c+=1,A.expiresAt<=m&&i.delete(d)}}const u=Promise.resolve(o(E,M,y)),f={expiresAt:m+t,value:u};return u.then(c=>{if(c===null){i.get(s)===f&&i.delete(s);return}const d=R(c);d!==void 0&&d<f.expiresAt&&(f.expiresAt=d)}).catch(()=>{i.get(s)?.value===u&&i.delete(s)}),i.delete(s),h(i,r),i.set(s,f),u}},v=new Map,b=256,k=2048,N=n=>{const e=JSON.stringify(n);if(e.length>k)return p(e);const t=v.get(e);if(t!==void 0)return t;const r=p(e);return h(v,b),v.set(e,r),r};export{_ as a,N as b,h as e,D as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as i,a as o,b as a}from"./memoize-identity-DFkwm3x6.mjs";import"./identity-header-ByHiZBcH.mjs";export{i as memoizeIdentity,o as memoizeIdentityPerRequest,a as memoizedIdentityHeader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"./LunoraError-PkZWF-_g.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
|
+
import{redactCredentials as s}from"@lunora/observability";import{t as i}from"./error-detail-C46mdOTW.mjs";const h="x-lunora-sample-errors",o=1,u=r=>{const t=Number.parseInt(r.slice(-8),16);return Number.isFinite(t)?t/4294967296:0},d=(r,t=o)=>{const e=Number.isFinite(t)?t:o;return e>=1?!0:e<=0?!1:u(r)<e},l=(r,t)=>({isTraced:d(t,r?.headRate??o),keepErrors:r?.alwaysSampleErrors??!0}),p=(r,t)=>r.isTraced||r.keepErrors&&t,E=r=>{const t=i(r);return t===void 0?void 0:s(t)},f=r=>{if(r.error===void 0)return r;let t;try{t=r.error.internal}catch{const e=Object.getOwnPropertyDescriptors(r.error);return delete e.internal,{...r,error:Object.create(Object.getPrototypeOf(r.error),e)}}return t===void 0?r:{...r,error:{...r.error,internal:E(t)}}},T=(r,t,e,n,c)=>{if(!r?.onRpc)return;const a=c??(n!==void 0&&t.traceId!==void 0?l(n,t.traceId):void 0);if(!(a!==void 0&&!p(a,!t.ok)))try{r.onRpc(f(t),e)}catch{}},S=(r,t,e)=>{if(r?.onLog)try{r.onLog(t,e)}catch{}},y=(r,t)=>{if(r?.flush)try{r.flush(t)}catch{}};export{h as S,T as a,S as e,y as f,l as r};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{LunoraError as Z}from"@lunora/errors";import{redactCredentials as Q,redactArgs as N}from"@lunora/observability";import{stableStringify as v}from"@lunora/wire";import{e as c,L as m,c as H,o as j,f as I,O as z,g as rr,h as J,w as tr,i as or,j as sr,m as er}from"./otlp-resource-Ch_8_U0e.mjs";import{t as ar}from"./error-detail-C46mdOTW.mjs";const nr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return String(r);try{return JSON.stringify(r)??String(r)}catch{return String(r)}},R=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:nr(r),ir=(r,s,t)=>{Object.defineProperty(r,s,{configurable:!0,enumerable:!0,value:t,writable:!0})},Dr=(r,s)=>{if(r===void 0&&s===void 0)return;const t={};if(r!==void 0)for(const[o,e]of Object.entries(r))ir(t,o,R(e));return Object.keys(t).length===0?void 0:t},cr=512,dr=200,ur=r=>{const s=r.maxItems??cr,t=r.maxDelayMs??dr;let o=[],e,i,a;const p=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},g=async()=>{p();const l=o;o=[];const d=a;i=void 0,a=void 0;try{l.length>0&&await r.export(l)}catch{}finally{d?.()}},h=l=>{i===void 0&&(i=new Promise(d=>{a=d}),e=setTimeout(()=>{g()},t)),l?.(i)};return{add:(l,d)=>{for(o.push(l);o.length>s;)o.shift();h(d),o.length>=s&&g()},flush:async l=>{if(o.length===0){p();return}const d=g();return l?.(d),d},get size(){return o.length}}},lr=1,pr=0,fr=new Set(["cloudflare.ray_id","error.type","http.request.method","http.response.status_code","http.route","lunora.error_status","lunora.fanout.failed","lunora.fanout.shards","lunora.fanout.table","lunora.function_path","lunora.ok","lunora.shard_key","server.address","server.port","url.path","url.scheme","user_agent.original"]),mr={errorType:m.errorType,functionPath:m.functionPath,rayId:m.rayId,shardKey:m.shardKey,userId:m.userId},hr=r=>{const s=ar(r);return s===void 0?[]:[c("lunora.error.internal",JSON.stringify(Q(s)))]},G=(r,s,t,o)=>[c("exception.type",r),c("exception.message",s),...t===void 0?[]:[c("exception.stacktrace",t)],...o===void 0?[]:hr(o)],gr=(r,s)=>{const t=[c(m.functionPath,r.functionPath),c(m.ok,r.ok)];if(r.method!==void 0&&t.push(c("http.request.method",r.method)),r.path!==void 0&&t.push(c("url.path",r.path)),t.push(c("http.route",r.functionPath)),r.scheme!==void 0&&t.push(c("url.scheme",r.scheme)),r.host!==void 0&&t.push(c("server.address",r.host)),r.port!==void 0&&t.push(c("server.port",r.port)),r.userAgent!==void 0&&t.push(c("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(c(m.shardKey,r.shardKey)),r.rayId!==void 0&&t.push(c(m.rayId,r.rayId)),t.push(c("http.response.status_code",r.error?.status??200)),r.error&&t.push(c(m.errorType,r.error.code),c("lunora.error_status",r.error.status)),r.fanOut&&t.push(c("lunora.fanout.table",r.fanOut.table),c("lunora.fanout.shards",r.fanOut.shards),c("lunora.fanout.failed",r.fanOut.failed)),r.attributes!==void 0){const e=new Set([...fr,...t.map(a=>a.key)]),i=H(Object.fromEntries(Object.entries(r.attributes).map(([a,p])=>[a,R(p)])));t.push(...i.filter(a=>!e.has(a.key)))}const o={attributes:t,endTimeUnixNano:I(s),kind:z.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:I(s-r.durationMs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId??j(16)};return r.traceFlags!==void 0&&(o.flags=r.traceFlags),r.error&&(o.events=[{attributes:G(r.error.code,r.error.message,r.error.stack,r.error.internal),name:"exception",timeUnixNano:I(s)}]),o},x=(r,s)=>{const t=new Map,o=new Set(Object.keys(r).map(e=>mr[e]));for(const[e,i]of Object.entries(s??{}))o.has(e)||t.set(e,c(e,R(i)));return t.set(m.functionPath,c(m.functionPath,r.functionPath)),r.shardKey!==void 0&&t.set(m.shardKey,c(m.shardKey,r.shardKey)),r.userId!==void 0&&t.set(m.userId,c(m.userId,r.userId)),r.rayId!==void 0&&t.set(m.rayId,c(m.rayId,r.rayId)),r.errorType!==void 0&&t.set(m.errorType,c(m.errorType,r.errorType)),[...t.values()]},yr=r=>{const s={attributes:x({errorType:r.error?.type,functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:I(r.startTs+r.durationMs),flags:r.sampled===!1?pr:lr,kind:z[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:I(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>H(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,R(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:I(o.ts)}))),r.links!==void 0&&r.links.length>0&&(s.links=r.links.map(o=>({attributes:t(o.attributes),spanId:o.spanId,traceId:o.traceId}))),s},br=r=>{const s=I(r.ts),t=x({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o=r.traceId===void 0?void 0:[{asDouble:r.value,timeUnixNano:s,traceId:r.traceId}],e={asDouble:r.value,attributes:t,...o===void 0?{}:{exemplars:o},timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[e]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",...o===void 0?{}:{exemplars:o},explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},kr=r=>{const s={attributes:x({functionPath:r.functionPath,rayId:r.rayId,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:rr[r.level],severityText:r.level.toUpperCase(),timeUnixNano:I(r.ts)};if(r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.error!==void 0){const t=G(r.error.name,r.error.message,r.error.stack,r.error.internal),o=new Set(t.map(e=>e.key));s.attributes=[...s.attributes.filter(e=>!o.has(e.key)),...t]}return r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes=[...s.attributes.filter(t=>t.key!=="event.name"),c("event.name",r.eventName)]),s},Ir=1024,B=5;let _=0;const Sr=(r,s)=>{if(_>=B)return;_+=1;let t;try{t=new URL(r).host}catch{t="<unparseable endpoint>"}const o=_===B?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${t} rejected the export with HTTP ${String(s)}; the batch is DROPPED (there is no retry).${o}`)},Tr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},W=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),a=(i<Ir?fetch(r,{body:e,headers:t,method:"POST"}):Tr(e).then(p=>fetch(r,{body:p,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(p=>{p.ok||Sr(r,p.status)},()=>{});o?.(a),await a}catch{}},Pr=(r,s,t,o)=>{W(r,s,t,o?.waitUntil).catch(()=>{})},E=(r,s)=>s===!0&&r.ok,wr=r=>r.kind==="metric"?void 0:r.event.traceId,Or=r=>{const s=Map.groupBy(r,o=>wr(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},C=5,Er=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=Or(r),i=[...e];let a=0,p;for(const[g,h]of o){let l;try{l=s({logs:h.filter(d=>d.kind==="log").map(d=>d.event),rpc:h.filter(d=>d.kind==="rpc").map(d=>d.event),spans:h.filter(d=>d.kind==="span").map(d=>d.event),traceId:g})}catch(d){a+=1,a===1&&(p=d),l=!0}l&&i.push(...h)}return a>0&&t(p,a),i},w=(r,s)=>{let t;try{t=s===void 0?r:s(r)}catch{t=void 0}return t??void 0},Lr=r=>{const s=N(r.message);if(r.stack===void 0)return{...r,message:s};const t=`: ${r.message}`,o=r.stack.indexOf(t),i=r.message!==""&&o!==-1&&!r.stack.slice(0,o).includes(`
|
|
2
|
+
`)?r.stack.slice(o+t.length):r.stack.split(`
|
|
3
|
+
`).filter(a=>a.trimStart().startsWith("at ")).map(a=>`
|
|
4
|
+
${a}`).join("");return{...r,message:s,stack:`${r.name}: ${s}${i}`}},Rr=r=>({...r,...r.error===void 0?{}:{error:Lr(r.error)},...r.fields===void 0?{}:{fields:N(r.fields)},message:N(r.message)}),V=(r,s,t)=>{if(r.kind==="rpc"){const e=w(r.event,s?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:gr(e,r.endMs)}}if(r.kind==="span"){const e=w(r.event,s?.span);return e===void 0?void 0:{bucket:"spans",encoded:yr(e)}}if(r.kind==="log"){const e=w(t?Rr(r.event):r.event,s?.log);return e===void 0?void 0:{bucket:"logs",encoded:kr(e)}}const o=w(r.event,s?.metric);return o===void 0?void 0:{bucket:"metrics",encoded:br(o)}},Ar=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],Fr=(r={})=>{const{onlyErrors:s}=r;return{onLog:t=>{t.level==="error"||t.level==="fatal"?console.error("[lunora:log]",t.functionPath,t.message):console.log("[lunora:log]",t.functionPath,t.message)},onMetric:t=>{console.log("[lunora:metric]",`${t.name}=${String(t.value)}`,t.kind,t.functionPath)},onRpc:t=>{E(t,s)||(t.ok?console.log("[lunora:rpc]",t):console.error("[lunora:rpc]",t))},onSpan:t=>{const o=t.ok?"ok":`error ${t.error?.type??""}`.trim();console.log("[lunora:span]",t.name,`${String(t.durationMs)}ms`,o,t.functionPath)}}},Kr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,a=J({"content-type":"application/json"},s),p=(g,h)=>{try{const l=fetch(i,{body:JSON.stringify(g),headers:a,method:"POST"}).catch(()=>{});h?.waitUntil&&h.waitUntil(l)}catch{}};return{onLog:(g,h)=>{const l=w(g,e);l!==void 0&&p(l,h)},onRpc:(g,h)=>{if(E(g,t))return;const l=w(g,o);l!==void 0&&p(l,h)}}},$r=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!E(o,t))try{s.writeDataPoint({blobs:[o.functionPath,o.ok?"ok":"error",o.shardKey??"",o.error?.code??"",o.fanOut?.table??""],doubles:[o.durationMs,o.ok?0:1,o.fanOut?.shards??0,o.fanOut?.failed??0],indexes:[o.functionPath]})}catch{}}}},jr=r=>{const{pipeline:s,serializeFields:t}=r;return{onLog:(o,e)=>{try{const i={functionPath:o.functionPath,level:o.level,message:o.message,ts:o.ts};o.fields&&(i.fields=t===!0?JSON.stringify(o.fields):o.fields);for(const p of["shardKey","userId","traceId","spanId"])o[p]!==void 0&&(i[p]=o[p]);const a=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(a)}catch{}}}},Br=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:a,postProcessor:p,resourceAttributes:g,serviceNamespace:h,serviceVersion:l,tailSampler:d,token:X}=r,M=r.serviceName??"lunora",U=r.redactLogs??!0;if(s!==!1&&s?.maxItems!==void 0&&(!Number.isInteger(s.maxItems)||s.maxItems<1))throw new Z("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(s.maxItems)}.`);const D={...l===void 0?{}:{"service.version":l},...h===void 0?{}:{"service.namespace":h},...t===void 0?{}:{"deployment.environment":t},...g},F=new WeakMap,k=u=>{if(o!==!0||u?.resourceAttributes===void 0)return D;const n=F.get(u);if(n!==void 0)return n;const f=er(u.resourceAttributes(),D);return F.set(u,f),f};let S=e;for(;S.endsWith("/");)S=S.slice(0,-1);const K={logs:{url:`${S}/v1/logs`,wrap:sr},metrics:{url:`${S}/v1/metrics`,wrap:or},spans:{url:`${S}/v1/traces`,wrap:tr}},$=J({"content-type":"application/json"},i,X);let A=0;const Y=(u,n)=>{if(A>=C)return;A+=1;const f=A===C?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(n)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${f}`,u)},q=async u=>{const n=Er(u,d,Y),f=new Map;for(const y of n){const b=V(y,p,U);if(b===void 0)continue;const L=v(y.resource);let P=f.get(L);P===void 0&&(P={logs:[],metrics:[],resource:y.resource,spans:[]},f.set(L,P)),P[b.bucket].push(b.encoded)}const T=[];for(const[,y]of f)for(const b of["spans","logs","metrics"])if(y[b].length>0){const{url:L,wrap:P}=K[b];T.push(W(L,P(y[b],"@lunora/runtime",M,y.resource),$))}await Promise.all(T)};if(s===!1){const u=(n,f)=>{const T=V(n,p,U);if(T!==void 0){const{url:y,wrap:b}=K[T.bucket];Pr(y,b(T.encoded,"@lunora/runtime",M,n.resource),$,f)}};return{onLog:(n,f)=>{u({event:n,kind:"log",resource:k(f)},f)},onMetric:(n,f)=>{u({event:n,kind:"metric",resource:k(f)},f)},onRpc:(n,f)=>{E(n,a)||u({endMs:Date.now(),event:n,kind:"rpc",resource:k(f)},f)},onSpan:(n,f)=>{u({event:n,kind:"span",resource:k(f)},f)}}}const O=ur({export:q,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:u=>{O.flush(u?.waitUntil).catch(()=>{})},onLog:(u,n)=>{O.add({event:u,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(u,n)=>{O.add({event:u,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(u,n)=>{E(u,a)||O.add({endMs:Date.now(),event:u,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(u,n)=>{O.add({event:u,kind:"span",resource:k(n)},n?.waitUntil)}}},Cr=(...r)=>{const s=(o,e)=>{for(const i of r){const a=i[o];if(a)try{a.apply(i,e)}catch{}}},t={};for(const o of r)for(const e of Ar)t[e]===void 0&&o[e]!==void 0&&(t[e]=o[e]);return{...t,flush:o=>{s("flush",[o])},onLog:(o,e)=>{s("onLog",[o,e])},onMetric:(o,e)=>{s("onMetric",[o,e])},onRpc:(o,e)=>{s("onRpc",[o,e])},onSpan:(o,e)=>{s("onSpan",[o,e])}}};export{Ar as S,$r as a,Fr as b,Cr as c,Dr as n,Br as o,jr as p,Kr as w};
|
|
@@ -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",rayId:"cloudflare.ray_id",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,b as c,x as d,_ as e,N as f,R as g,h,y as i,M as j,F as m,T as o,I as p,w as r,V as w};
|