@lunora/runtime 1.0.0-alpha.276 → 1.0.0-alpha.278

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -2795,7 +2795,7 @@ declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnTy
2795
2795
  /**
2796
2796
  * Decode GET args from the query string. Each value is parsed as JSON when it
2797
2797
  * looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
2798
- * array), else kept as a string. `shardKey` (routing) and `__lunora_vary` (the
2798
+ * array), else kept as a string. `shardKey` (routing) and `__lunora_key` (the
2799
2799
  * edge cache key) are reserved and excluded.
2800
2800
  */
2801
2801
  declare const argsFromQuery: (url: URL) => Record<string, unknown>;
package/dist/index.d.ts CHANGED
@@ -2795,7 +2795,7 @@ declare const restSurfaceFromRegistry: (functions: RestRegistryLike) => ReturnTy
2795
2795
  /**
2796
2796
  * Decode GET args from the query string. Each value is parsed as JSON when it
2797
2797
  * looks like a JSON scalar/array/object (so `?limit=10` → number, `?ids=[1,2]` →
2798
- * array), else kept as a string. `shardKey` (routing) and `__lunora_vary` (the
2798
+ * array), else kept as a string. `shardKey` (routing) and `__lunora_key` (the
2799
2799
  * edge cache key) are reserved and excluded.
2800
2800
  */
2801
2801
  declare const argsFromQuery: (url: URL) => Record<string, unknown>;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
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-DGFf9fxj.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-Bm04PAy7.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-DzVUB2rt.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-CaQF9cds.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-Dar1gB9v.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.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};
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-C8G5gcXC.mjs";import{createCrossShardRelationCapabilities as C}from"./packem_shared/createCrossShardRelationCapabilities-Bm04PAy7.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-DzVUB2rt.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-BLCB5VpU.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-CRKDJlAP.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-CaQF9cds.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-Br05k63D.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-Dar1gB9v.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Ue}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.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};
@@ -1 +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};
1
+ import"./otlp-resource-BBR8xs6m.mjs";import{S as a,a as s,c as S,b as e,o as k,p,w as c}from"./observability-sinks-CRKDJlAP.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};
@@ -1 +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};
1
+ import{a as o,b as i,c as m,r as R}from"./rest-routes-Br05k63D.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};
@@ -1,4 +1,4 @@
1
- import{isLunoraError as Er,toErrorBody as cs}from"@lunora/errors";import{encodeWire as le,decodeWire as rt,encodeArgsOrThrow as ds}from"@lunora/wire";import{t as Ht,f as Ft}from"./base64-Bl1_r2k1.mjs";import{e as ot,b as us}from"./memoize-identity-DzVUB2rt.mjs";import{d as hn,E as fn,a as ls,b as hs,W as pn}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as fs}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as ps,a as ms,i as ws,e as gs,E as mn,b as ys}from"./identity-header-CG1FNe-S.mjs";import{O as Ar,a as Tr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ne,b as Sr,p as _s,m as bs,d as Es,a as As,r as Ts}from"./otlp-resource-Ch_8_U0e.mjs";import{r as Ss,f as wn,a as me,S as gn}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as yn}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as fe,applyJurisdiction as Qe}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ne,e as se,M as Rr,b as Rs,f as vs,g as vr,w as Os,h as Or,t as Ns}from"./rest-routes-CDQ1F7kI.mjs";import{a as F,m as Oe}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Kt,BACKUP_KEY_PREFIX as Gt,isBackupManifestKey as Is,backupObjectKeyOfManifest as Nr,backupObjectKey as ks,backupManifestKey as Ds}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Ps,buildStorageAdminRoutes as Us,STORAGE_UPLOAD_MAX_BODY_BYTES as Cs,STORAGE_PATH as Ls}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as xs,e as Bs,f as _n,g as $s,h as Ms}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as js,durableObjectProbe as Hs,d1Probe as Fs,presenceProbe as bt}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Ks}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Vl,routeIdentityResolvers as zl}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Gs}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as Ws,createQueryCoordinator as Qs,createDefaultShardRegistry as Vs,refreshShardHeadersPerCall as zs,refreshedShardHeaders as Js}from"./createQueryCoordinator-CaQF9cds.mjs";import{resolveSecurity as bn,handleCorsPreflight as Ys,enforceOrigin as Xs,decorateResponse as Et,enforceWebSocketOrigin as En}from"./decorateResponse-CdelJSUs.mjs";const qs=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;ot(e,r);const a=n().catch(c=>{throw e.get(t)===a&&e.delete(t),c});return e.set(t,a),a},Zs=new TextEncoder,ea=64,ta=new Map,Ir=async e=>qs(ta,e,async()=>crypto.subtle.importKey("raw",Zs.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ea),kr=new TextEncoder,na=Array.from({length:32},(e,t)=>t);new RegExp(`[${na.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const pt=async(e,t)=>{const n=await Ir(e),r=await crypto.subtle.sign("HMAC",n,kr.encode(t));return Ht(new Uint8Array(r))},Dr=async(e,t,n)=>{const r=await Ir(e);return crypto.subtle.verify("HMAC",r,n,kr.encode(t))},Pr="lnat",ra="__lunora_admin_revocations__",oa=/^[a-z0-9][a-z0-9_-]{0,63}$/u,sa=/^[\w-]{43}$/u,tt="x-lunora-admin-signal",aa="as1",ia=6e4,ca=5e3,Ur=e=>oa.test(e),da=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Pr)return;const[,n,r]=t;return Ur(n)&&sa.test(r)?{name:n,secret:r}:void 0},Cr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:da(t[1])},ua=e=>{const t=Ht(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Pr}.${e}.${t}`}},Lr=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),la=async(e,t,n=Date.now(),r=Number.POSITIVE_INFINITY)=>{const s=`${aa}.${String(Math.floor(Math.min(n+ia,r)))}.${t}`;return`${s}.${await pt(e,s)}`},Ct=["disabled","schema","schema_and_log","schema_and_log_and_data"],ha="schema",fa=e=>e==null||e===""?ha:typeof e=="string"&&Ct.includes(e)?e:"disabled",pa=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},xr="__lunoraBranch",ma=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,xr),wa=`may not contain the reserved workflow branch-marker key ("${xr}")`,ga=new Set(["exp","expiresAtMs","iat","jti","nbf"]),Lt=e=>Array.isArray(e)?`[${e.map(t=>Lt(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Lt(r)}`).join(",")}}`:JSON.stringify(e)??"null",ya=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!ga.has(n)));return Object.keys(t).length===0?"":Lt(t)},_a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),de=(e,t)=>e>>>t|e<<32-t,ba=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(e.length*8/2**32)),r.setUint32(n.length-4,e.length*8>>>0);const s=new Uint32Array(64);for(let u=0;u<n.length;u+=64){for(let A=0;A<16;A+=1)s[A]=r.getUint32(u+A*4);for(let A=16;A<64;A+=1){const T=s[A-15],I=s[A-2],_=de(T,7)^de(T,18)^T>>>3,D=de(I,17)^de(I,19)^I>>>10;s[A]=s[A-16]+_+s[A-7]+D>>>0}let[i,m,g,b,f,N,y,E]=t;for(let A=0;A<64;A+=1){const T=de(f,6)^de(f,11)^de(f,25),I=f&N^~f&y,_=E+T+I+_a[A]+s[A]>>>0,D=de(i,2)^de(i,13)^de(i,22),v=i&m^i&g^m&g,C=D+v>>>0;E=y,y=N,N=f,f=b+_>>>0,b=g,g=m,m=i,i=_+C>>>0}[i,m,g,b,f,N,y,E].forEach((A,T)=>{t[T]=t[T]+A>>>0})}const a=new Uint8Array(32),c=new DataView(a.buffer);return t.forEach((u,i)=>{c.setUint32(i*4,u)}),a},Ea=(e,t)=>Ht(ba(new TextEncoder().encode(`${JSON.stringify(e??null)}|${ya(t)}`)).subarray(0,16)),Aa=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}},Ta=/already[\s_-]?exists/iu,Sa=e=>Ta.test(e instanceof Error?e.message:String(e)),Ra="/_lunora/live/publish",va="cf-ray",Oa="x-lunora-ray-id",Na=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Ia=e=>e==null?void 0:Na.exec(e.trim())?.[1]?.toLowerCase(),ka=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(ka);const Da=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Pa=-100,Ua=15,Ca=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Da.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ua?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Pa?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},An=e=>{const t=e.cf;return t===void 0?void 0:Ca(t)},st="::relay::",La=(e,t)=>`${e}${st}${String(t)}`,at="::replica::",xa=(e,t)=>`${e}${at}${t}`,Ba=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},$a=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Br=(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 a=s<e.length?e.charCodeAt(s):0,c=s<t.length?t.charCodeAt(s):0;r|=a^c}return r===0},Ma="/_lunora/scheduler/dispatch",ja="__lunora_relation__:",Ha=e=>e.startsWith(ja),$r="agents:agentRun",Fa=(e,t,n)=>e===$r&&t!==n,Ka=`\`${$r}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,it=(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:Br(t,s.join(" ").trim())},Ga=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?Br(await pt(s,t),r):it(e,n.adminToken)},Tn="/_lunora/ws/reauth",Wa="/_lunora/claims",Qa="x-lunora-scheduled-for",Va=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:r})=>{const s={"content-type":"application/json",[Tr]:Ar,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(s["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(s["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(s["x-lunora-mutation-id"]=t),r!==void 0&&r.length>0&&(s.traceparent=r),n!==void 0&&Number.isFinite(n)&&(s[Qa]=String(Math.trunc(n))),s},za=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}}},Ja=(e,t,n)=>e?.[n]??t?.[n],Ya=(e,t,n,r)=>{const s=Ja(e,t,n);if(!(typeof s!="object"||s===null))return r.every(a=>typeof s[a]=="function")?s:void 0},Mr="v1",Xa=6e4,qa=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Xa),r=`${Mr}.${String(n)}`,s=await pt(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Za=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,a,c]=r;if(s!==Mr||c.length===0)return!1;const u=Number(a);if(!Number.isFinite(u)||u<=n)return!1;let i;try{i=Ft(c)}catch{return!1}return Dr(e,`${s}.${a}`,i)},ei="https://admin-revocations.internal",ti=(e,t)=>{const n=async(r,s)=>{const a=t();if(a===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const c=await fe(e,ra).fetch(new Request(`${ei}${r}`,{...s,headers:{authorization:`Bearer ${a}`,"content-type":"application/json"}}));if(!c.ok)throw new l(`admin revocation store answered ${String(c.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return c};return{revoke:async(r,s)=>{await n("/revoke",{body:JSON.stringify({createdAt:s,name:r}),method:"POST"})},isRevoked:async(r,s)=>{const u=(await(await n(`/revoked?name=${encodeURIComponent(r)}&createdAt=${String(s)}`,{method:"GET"})).json())?.revoked;if(typeof u!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return u},latestRevoked:async r=>{const c=(await(await n(`/latest?name=${encodeURIComponent(r)}`,{method:"GET"})).json())?.latest;if(c!==null){if(typeof c!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return c}}}},ni="/_lunora/admin/tokens",ri="__lunora_admin__:createAdminToken",Sn="__lunora_admin__:listAdminTokens",oi="__lunora_admin__:revokeAdminToken",At={"cache-control":"no-store"},Rn=e=>{if(typeof e!="string"||!Ur(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},si=e=>{const t=e.now??Date.now,n=async a=>{const c=await e.readJsonBody(a),u=Rn(c.name),{expiresAt:i}=c;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:m,token:g}=ua(u),b=await e.revocations.latestRevoked(u),f=b===void 0?t():Math.max(t(),b+1),N=await e.callStore(ri,{createdAt:f,digest:await Lr(m),expiresAt:i,name:u});return e.evict(u),Response.json({...N,token:g},{headers:At,status:201})},r=async()=>{const{revocations:a}=e;if(a===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:c}=await e.callStore(Sn,{}),u=await Promise.all(c.map(async i=>await a.isRevoked(i.name,i.createdAt)?{...i,revoked:!0}:i));return Response.json({tokens:u},{headers:At})},s=async a=>{const c=Rn(new URL(a.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:u}=await e.callStore(Sn,{}),i=u.find(m=>m.name===c);if(i===void 0)throw new l(`no admin token named "${c}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(c,i.createdAt),await e.callStore(oi,{createdAt:i.createdAt,name:c})}finally{e.evict(c)}return Response.json({revoked:!0},{headers:At})};return{[ni]:async a=>(e.assertRootAdmin(a),a.method==="GET"?r():a.method==="POST"?n(a):a.method==="DELETE"?s(a):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},ai=3e4,ii=5e3,ci=1024,vn=20,On=1e3,di=5e3,ui=1024,li=({listNames:e,lookup:t,now:n=Date.now})=>{const r=new Map,s=new Map,a=new Map,c=new Map,u=new Map;let i=vn,m=n();const g=()=>{const _=n()-m,D=Math.floor(_/On);return D>0&&(i=Math.min(vn,i+D),m+=D*On),i<=0?!1:(i-=1,!0)},b=(_,D)=>{for(const[v,C]of _)C.name===D&&_.delete(v)},f=_=>{u.has(_)||(ot(u,ui),u.set(_,!0))};let N=Number.NEGATIVE_INFINITY,y;const E=()=>y!==void 0?y:e===void 0||n()-N<di?Promise.resolve():(N=n(),y=(async()=>{try{for(const _ of await e())f(_)}catch{}finally{y=void 0}})(),y),A=async _=>(await E(),u.has(_)),T=(_,D,v)=>{const C=t(_,D);c.set(v,C);const M=()=>{c.get(v)===C&&c.delete(v)};return C.finally(M).catch(()=>{}),C},I=(_,D,v,C)=>{C?f(_):u.delete(_),ot(s,ci),s.set(C?D:v,{name:_,until:n()+ii})};return{evict:_=>{b(r,_),b(s,_),u.delete(_);for(const D of c.keys())D.startsWith(`${_}\0`)&&c.delete(D);a.set(_,(a.get(_)??0)+1)},verify:async _=>{const D=Cr(_);if(D===void 0)return;const{name:v}=D,C=await Lr(D.secret),M=`${v}\0${C}`,j=`${v}\0*`,G=r.get(M);if(G!==void 0&&G.until>n())return G;if((s.get(j)?.until??0)>n()||(s.get(M)?.until??0)>n())return;r.delete(M),s.delete(M),s.delete(j);const z=a.get(v);let Q=c.get(M);if(Q===void 0){if(!(u.has(v)||g())&&!await A(v))return;Q=T(v,C,M)}const Y=await Q;if(a.get(v)!==z)return;if(!Y.live){if(Y.transient===!0)return;I(v,M,j,Y.nameKnown);return}const X=Math.min(n()+ai,Y.expiresAt??Number.POSITIVE_INFINITY);if(X<=n())return;f(v);const ce={name:v,until:X,...Y.expiresAt===void 0?{}:{expiresAt:Y.expiresAt}};return r.set(M,ce),ce}}},hi="x",Nn=" ",fi={'"':'"',"'":"'","[":"]","`":"`"},jr=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
1
+ import{isLunoraError as Er,toErrorBody as cs}from"@lunora/errors";import{encodeWire as le,decodeWire as rt,encodeArgsOrThrow as ds}from"@lunora/wire";import{t as Ht,f as Ft}from"./base64-Bl1_r2k1.mjs";import{e as ot,b as us}from"./memoize-identity-DzVUB2rt.mjs";import{d as hn,E as fn,a as ls,b as hs,W as pn}from"./error-detail-C46mdOTW.mjs";import{NOOP_EXECUTION_CONTEXT as fs}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{d as ps,a as ms,i as ws,e as gs,E as mn,b as ys}from"./identity-header-CG1FNe-S.mjs";import{O as Ar,a as Tr}from"./origin-paywall-B6eOO67m.mjs";import{o as Ne,b as Sr,p as _s,m as bs,d as Es,a as As,r as Ts}from"./otlp-resource-BBR8xs6m.mjs";import{r as Ss,f as wn,a as me,S as gn}from"./observability-9slk__Gi.mjs";import{LunoraError as l,toErrorResponse as yn}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as fe,applyJurisdiction as Qe}from"./applyJurisdiction-DKQE8kOA.mjs";import{d as ne,e as se,M as Rr,b as Rs,f as vs,g as vr,w as Os,h as Or,t as Ns}from"./rest-routes-Br05k63D.mjs";import{a as F,m as Oe}from"./method-guard-8Jo4Q8uS.mjs";import{normalizeBackupPrefix as Kt,BACKUP_KEY_PREFIX as Gt,isBackupManifestKey as Is,backupObjectKeyOfManifest as Nr,backupObjectKey as ks,backupManifestKey as Ds}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Ps,buildStorageAdminRoutes as Us,STORAGE_UPLOAD_MAX_BODY_BYTES as Cs,STORAGE_PATH as Ls}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs";import{b as xs,e as Bs,f as _n,g as $s,h as Ms}from"./export-tap-C2B_SATf.mjs";import{buildHealthRoutes as js,durableObjectProbe as Hs,d1Probe as Fs,presenceProbe as bt}from"./HEALTH_PATH-B8ndDG3s.mjs";import{wrapResolverWithContract as Ks}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{composeIdentityResolvers as Vl,routeIdentityResolvers as zl}from"./composeIdentityResolvers-CpdHuDyk.mjs";import{buildLogArchiveAdminRoutes as Gs}from"./LOG_ARCHIVE_PATH-dTuCzfyj.mjs";import{pruneShardRegistry as Ws,createQueryCoordinator as Qs,createDefaultShardRegistry as Vs,refreshShardHeadersPerCall as zs,refreshedShardHeaders as Js}from"./createQueryCoordinator-CaQF9cds.mjs";import{resolveSecurity as bn,handleCorsPreflight as Ys,enforceOrigin as Xs,decorateResponse as Et,enforceWebSocketOrigin as En}from"./decorateResponse-CdelJSUs.mjs";const qs=(e,t,n,r)=>{const s=e.get(t);if(s!==void 0)return s;ot(e,r);const a=n().catch(c=>{throw e.get(t)===a&&e.delete(t),c});return e.set(t,a),a},Zs=new TextEncoder,ea=64,ta=new Map,Ir=async e=>qs(ta,e,async()=>crypto.subtle.importKey("raw",Zs.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ea),kr=new TextEncoder,na=Array.from({length:32},(e,t)=>t);new RegExp(`[${na.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const pt=async(e,t)=>{const n=await Ir(e),r=await crypto.subtle.sign("HMAC",n,kr.encode(t));return Ht(new Uint8Array(r))},Dr=async(e,t,n)=>{const r=await Ir(e);return crypto.subtle.verify("HMAC",r,n,kr.encode(t))},Pr="lnat",ra="__lunora_admin_revocations__",oa=/^[a-z0-9][a-z0-9_-]{0,63}$/u,sa=/^[\w-]{43}$/u,tt="x-lunora-admin-signal",aa="as1",ia=6e4,ca=5e3,Ur=e=>oa.test(e),da=e=>{const t=e.split(".");if(t.length!==3||t[0]!==Pr)return;const[,n,r]=t;return Ur(n)&&sa.test(r)?{name:n,secret:r}:void 0},Cr=e=>{const t=e?/^bearer\s+(\S+)\s*$/iu.exec(e):void 0;return t?.[1]===void 0?void 0:da(t[1])},ua=e=>{const t=Ht(crypto.getRandomValues(new Uint8Array(32)));return{secret:t,token:`${Pr}.${e}.${t}`}},Lr=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join(""),la=async(e,t,n=Date.now(),r=Number.POSITIVE_INFINITY)=>{const s=`${aa}.${String(Math.floor(Math.min(n+ia,r)))}.${t}`;return`${s}.${await pt(e,s)}`},Ct=["disabled","schema","schema_and_log","schema_and_log_and_data"],ha="schema",fa=e=>e==null||e===""?ha:typeof e=="string"&&Ct.includes(e)?e:"disabled",pa=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},xr="__lunoraBranch",ma=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,xr),wa=`may not contain the reserved workflow branch-marker key ("${xr}")`,ga=new Set(["exp","expiresAtMs","iat","jti","nbf"]),Lt=e=>Array.isArray(e)?`[${e.map(t=>Lt(t)).join(",")}]`:typeof e=="object"&&e!==null?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Lt(r)}`).join(",")}}`:JSON.stringify(e)??"null",ya=e=>{const t=Object.fromEntries(Object.entries(e??{}).filter(([n])=>!ga.has(n)));return Object.keys(t).length===0?"":Lt(t)},_a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),de=(e,t)=>e>>>t|e<<32-t,ba=e=>{const t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array(Math.ceil((e.length+9)/64)*64);n.set(e),n[e.length]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(e.length*8/2**32)),r.setUint32(n.length-4,e.length*8>>>0);const s=new Uint32Array(64);for(let u=0;u<n.length;u+=64){for(let A=0;A<16;A+=1)s[A]=r.getUint32(u+A*4);for(let A=16;A<64;A+=1){const T=s[A-15],I=s[A-2],_=de(T,7)^de(T,18)^T>>>3,D=de(I,17)^de(I,19)^I>>>10;s[A]=s[A-16]+_+s[A-7]+D>>>0}let[i,m,g,b,f,N,y,E]=t;for(let A=0;A<64;A+=1){const T=de(f,6)^de(f,11)^de(f,25),I=f&N^~f&y,_=E+T+I+_a[A]+s[A]>>>0,D=de(i,2)^de(i,13)^de(i,22),v=i&m^i&g^m&g,C=D+v>>>0;E=y,y=N,N=f,f=b+_>>>0,b=g,g=m,m=i,i=_+C>>>0}[i,m,g,b,f,N,y,E].forEach((A,T)=>{t[T]=t[T]+A>>>0})}const a=new Uint8Array(32),c=new DataView(a.buffer);return t.forEach((u,i)=>{c.setUint32(i*4,u)}),a},Ea=(e,t)=>Ht(ba(new TextEncoder().encode(`${JSON.stringify(e??null)}|${ya(t)}`)).subarray(0,16)),Aa=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}},Ta=/already[\s_-]?exists/iu,Sa=e=>Ta.test(e instanceof Error?e.message:String(e)),Ra="/_lunora/live/publish",va="cf-ray",Oa="x-lunora-ray-id",Na=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,Ia=e=>e==null?void 0:Na.exec(e.trim())?.[1]?.toLowerCase(),ka=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(ka);const Da=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),Pa=-100,Ua=15,Ca=e=>{const t=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&Da.has(e.country)?"me":"apac";case"EU":return Number.isFinite(t)&&t>Ua?"eeur":"weur";case"NA":return Number.isFinite(t)&&t<Pa?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},An=e=>{const t=e.cf;return t===void 0?void 0:Ca(t)},st="::relay::",La=(e,t)=>`${e}${st}${String(t)}`,at="::replica::",xa=(e,t)=>`${e}${at}${t}`,Ba=e=>{if(e==null||!/^\d+$/.test(e))return;const t=Number.parseInt(e,10);return Number.isSafeInteger(t)&&t>0?t:void 0},$a=(e,t)=>{const n={...e};return delete n.shardKey,t!==void 0&&(n.shardKey=t),n},Br=(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 a=s<e.length?e.charCodeAt(s):0,c=s<t.length?t.charCodeAt(s):0;r|=a^c}return r===0},Ma="/_lunora/scheduler/dispatch",ja="__lunora_relation__:",Ha=e=>e.startsWith(ja),$r="agents:agentRun",Fa=(e,t,n)=>e===$r&&t!==n,Ka=`\`${$r}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,it=(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:Br(t,s.join(" ").trim())},Ga=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?Br(await pt(s,t),r):it(e,n.adminToken)},Tn="/_lunora/ws/reauth",Wa="/_lunora/claims",Qa="x-lunora-scheduled-for",Va=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:r})=>{const s={"content-type":"application/json",[Tr]:Ar,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(s["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(s["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(s["x-lunora-mutation-id"]=t),r!==void 0&&r.length>0&&(s.traceparent=r),n!==void 0&&Number.isFinite(n)&&(s[Qa]=String(Math.trunc(n))),s},za=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}}},Ja=(e,t,n)=>e?.[n]??t?.[n],Ya=(e,t,n,r)=>{const s=Ja(e,t,n);if(!(typeof s!="object"||s===null))return r.every(a=>typeof s[a]=="function")?s:void 0},Mr="v1",Xa=6e4,qa=async(e,t={})=>{const n=(t.now??Date.now())+(t.ttlMs??Xa),r=`${Mr}.${String(n)}`,s=await pt(e,r);return{expiresAtMs:n,token:`${r}.${s}`}},Za=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,a,c]=r;if(s!==Mr||c.length===0)return!1;const u=Number(a);if(!Number.isFinite(u)||u<=n)return!1;let i;try{i=Ft(c)}catch{return!1}return Dr(e,`${s}.${a}`,i)},ei="https://admin-revocations.internal",ti=(e,t)=>{const n=async(r,s)=>{const a=t();if(a===void 0)throw new l("named admin tokens require a configured LUNORA_ADMIN_TOKEN, which signs them",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const c=await fe(e,ra).fetch(new Request(`${ei}${r}`,{...s,headers:{authorization:`Bearer ${a}`,"content-type":"application/json"}}));if(!c.ok)throw new l(`admin revocation store answered ${String(c.status)}`,{code:"SHARD_UNAVAILABLE",status:503});return c};return{revoke:async(r,s)=>{await n("/revoke",{body:JSON.stringify({createdAt:s,name:r}),method:"POST"})},isRevoked:async(r,s)=>{const u=(await(await n(`/revoked?name=${encodeURIComponent(r)}&createdAt=${String(s)}`,{method:"GET"})).json())?.revoked;if(typeof u!="boolean")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return u},latestRevoked:async r=>{const c=(await(await n(`/latest?name=${encodeURIComponent(r)}`,{method:"GET"})).json())?.latest;if(c!==null){if(typeof c!="number")throw new l("admin revocation store answered garbage",{code:"SHARD_UNAVAILABLE",status:503});return c}}}},ni="/_lunora/admin/tokens",ri="__lunora_admin__:createAdminToken",Sn="__lunora_admin__:listAdminTokens",oi="__lunora_admin__:revokeAdminToken",At={"cache-control":"no-store"},Rn=e=>{if(typeof e!="string"||!Ur(e))throw new l("admin token `name` must match /^[a-z0-9][a-z0-9_-]{0,63}$/",{code:"BAD_REQUEST",status:400});return e},si=e=>{const t=e.now??Date.now,n=async a=>{const c=await e.readJsonBody(a),u=Rn(c.name),{expiresAt:i}=c;if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||i<=t()))throw new l("admin token `expiresAt` must be a future epoch-ms number",{code:"BAD_REQUEST",status:400});if(e.revocations===void 0)throw new l('named admin tokens need the ADMIN_REVOCATIONS Durable Object binding; export AdminRevocationDO from the worker entry (`export { AdminRevocationDO } from "./lunora/_generated/adminRevocations.js"`) and bind it',{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{secret:m,token:g}=ua(u),b=await e.revocations.latestRevoked(u),f=b===void 0?t():Math.max(t(),b+1),N=await e.callStore(ri,{createdAt:f,digest:await Lr(m),expiresAt:i,name:u});return e.evict(u),Response.json({...N,token:g},{headers:At,status:201})},r=async()=>{const{revocations:a}=e;if(a===void 0)throw new l("no admin revocation store is bound, so named admin tokens are refused; export AdminRevocationDO and bind ADMIN_REVOCATIONS",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:c}=await e.callStore(Sn,{}),u=await Promise.all(c.map(async i=>await a.isRevoked(i.name,i.createdAt)?{...i,revoked:!0}:i));return Response.json({tokens:u},{headers:At})},s=async a=>{const c=Rn(new URL(a.url).searchParams.get("name")??void 0);if(e.revocations===void 0)throw new l("no admin revocation store is bound, so no named admin token can exist",{code:"ADMIN_TOKEN_NOT_CONFIGURED",status:400});const{tokens:u}=await e.callStore(Sn,{}),i=u.find(m=>m.name===c);if(i===void 0)throw new l(`no admin token named "${c}"`,{code:"NOT_FOUND",status:404});try{await e.revocations.revoke(c,i.createdAt),await e.callStore(oi,{createdAt:i.createdAt,name:c})}finally{e.evict(c)}return Response.json({revoked:!0},{headers:At})};return{[ni]:async a=>(e.assertRootAdmin(a),a.method==="GET"?r():a.method==="POST"?n(a):a.method==="DELETE"?s(a):new Response(void 0,{headers:{allow:"GET, POST, DELETE"},status:405}))}},ai=3e4,ii=5e3,ci=1024,vn=20,On=1e3,di=5e3,ui=1024,li=({listNames:e,lookup:t,now:n=Date.now})=>{const r=new Map,s=new Map,a=new Map,c=new Map,u=new Map;let i=vn,m=n();const g=()=>{const _=n()-m,D=Math.floor(_/On);return D>0&&(i=Math.min(vn,i+D),m+=D*On),i<=0?!1:(i-=1,!0)},b=(_,D)=>{for(const[v,C]of _)C.name===D&&_.delete(v)},f=_=>{u.has(_)||(ot(u,ui),u.set(_,!0))};let N=Number.NEGATIVE_INFINITY,y;const E=()=>y!==void 0?y:e===void 0||n()-N<di?Promise.resolve():(N=n(),y=(async()=>{try{for(const _ of await e())f(_)}catch{}finally{y=void 0}})(),y),A=async _=>(await E(),u.has(_)),T=(_,D,v)=>{const C=t(_,D);c.set(v,C);const M=()=>{c.get(v)===C&&c.delete(v)};return C.finally(M).catch(()=>{}),C},I=(_,D,v,C)=>{C?f(_):u.delete(_),ot(s,ci),s.set(C?D:v,{name:_,until:n()+ii})};return{evict:_=>{b(r,_),b(s,_),u.delete(_);for(const D of c.keys())D.startsWith(`${_}\0`)&&c.delete(D);a.set(_,(a.get(_)??0)+1)},verify:async _=>{const D=Cr(_);if(D===void 0)return;const{name:v}=D,C=await Lr(D.secret),M=`${v}\0${C}`,j=`${v}\0*`,G=r.get(M);if(G!==void 0&&G.until>n())return G;if((s.get(j)?.until??0)>n()||(s.get(M)?.until??0)>n())return;r.delete(M),s.delete(M),s.delete(j);const z=a.get(v);let Q=c.get(M);if(Q===void 0){if(!(u.has(v)||g())&&!await A(v))return;Q=T(v,C,M)}const Y=await Q;if(a.get(v)!==z)return;if(!Y.live){if(Y.transient===!0)return;I(v,M,j,Y.nameKnown);return}const X=Math.min(n()+ai,Y.expiresAt??Number.POSITIVE_INFINITY);if(X<=n())return;f(v);const ce={name:v,until:X,...Y.expiresAt===void 0?{}:{expiresAt:Y.expiresAt}};return r.set(M,ce),ce}}},hi="x",Nn=" ",fi={'"':'"',"'":"'","[":"]","`":"`"},jr=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
2
2
  `;)n+=1;return n},Hr=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},pi=e=>{const t=e.split("");let n=0;for(;n<e.length;){const r=e[n]??"",s=fi[r];if(r==="-"&&e[n+1]==="-"){const a=jr(e,n);t.fill(Nn,n,a),n=a}else if(r==="/"&&e[n+1]==="*"){const a=Hr(e,n);if(a===-1)return;t.fill(Nn,n,a),n=a}else if(s!==void 0){let a=n+1;for(;a<e.length;)if(e[a]!==s)a+=1;else if(s!=="]"&&e[a+1]===s)a+=2;else break;if(a>=e.length)return;t.fill(hi,n,a+1),n=a+1}else n+=1}for(let r=0;r<e.length;r+=1)e[r]===`
3
3
  `&&(t[r]=`
4
4
  `);return t.join("")},mi="__lunora_admin_tokens__",Wt=new Set([mi,"dbstat","sqlite_dbpage"]),Fr="pragma_",wi=e=>/[\p{L}_]/u.test(e)||(e.codePointAt(0)??0)>127,gi=e=>/[\p{L}\p{N}_$]/u.test(e)||(e.codePointAt(0)??0)>127,yi=/^pragma_\w+$/u,_i=e=>Wt.has(e)||yi.test(e)?e:void 0,In=e=>{if(Wt.has(e)||e.startsWith(Fr))return e},kn=(e,t,n)=>{let r="",s=t+1;for(;s<e.length;){const a=e[s];if(a===n){if(n!=="]"&&e[s+1]===n){r+=n,s+=2;continue}return{end:s+1,text:r}}r+=a,s+=1}},Dn={'"':'"',"`":"`","[":"]"},Tt=e=>{const t=e.toLowerCase().replaceAll(/["'`[\]]/gu,"");for(const n of Wt)if(t.includes(n))return n;return/\bpragma_/u.test(t)?Fr:void 0},bi=e=>{let t=0;for(;t<e.length;){const n=e[t];if(/\s/u.test(n))t+=1;else if(n==="-"&&e[t+1]==="-"){const r=e.indexOf(`
@@ -1 +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};
1
+ import{redactArgs as h,redactCredentials as b}from"@lunora/observability";import{S as y,n as O}from"./observability-sinks-CRKDJlAP.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};
@@ -1,4 +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(`
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-BBR8xs6m.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
2
  `)?r.stack.slice(o+t.length):r.stack.split(`
3
3
  `).filter(a=>a.trimStart().startsWith("at ")).map(a=>`
4
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
+ import{s as d,V as _}from"./worker-version-B-qCFtEJ.mjs";const N={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},b=e=>`${String(Math.round(e))}000000`,R=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,O=new Uint8Array(l);let a=l;const v=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=R[e[r+n]];return o},S=e=>{if(e>l){const t=new Uint8Array(e);return crypto.getRandomValues(t),v(t,0,e)}a+e>l&&(crypto.getRandomValues(O),a=0);const r=v(O,a,e);return a+=e,r},u=/^[0-9a-f]+$/,I=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,T=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=(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}},L=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>E(r,t)),h=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const g=c.toLowerCase(),m=n.get(g);m===void 0?(n.set(g,c),o[c]=i):o[m]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(r??{}))s(c,i);return t!==void 0&&t.length>0&&s("authorization",`Bearer ${t}`),o},f=e=>Array.isArray(e)?e:[e],V={client:3,consumer:5,internal:1,producer:4,server:2},C=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])=>E(o,n))},M=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:p(t,o)},scopeSpans:[{scope:{name:r},spans:f(e)}]}]}),y=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:p(t,o)},scopeLogs:[{logRecords:f(e),scope:{name:r}}]}]}),w=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:p(t,o)},scopeMetrics:[{metrics:f(e),scope:{name:r}}]}]}),j=e=>r=>{const t=e?.[r];if(typeof t=="string")return t.length>0?t:void 0;if(r===_)return d(t,"tag")??d(t,"id")},x=e=>{const r={},t=e("SERVICE_VERSION")??e(_)??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},D=(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},H=(...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{C as L,V as O,x as a,I as b,L as c,D as d,E as e,b as f,N as g,h,w as i,y as j,H as m,S as o,T as p,j as r,M as w};
@@ -0,0 +1 @@
1
+ import{c as O,d as P,e as B,a as x,f as D}from"./rest-cache-CmHN871W.mjs";import{LunoraError as h}from"./LunoraError-PkZWF-_g.mjs";import{m as j}from"./method-guard-8Jo4Q8uS.mjs";import{w as C}from"./worker-version-B-qCFtEJ.mjs";const U=async(e,r)=>{if(!e.body)return"";const t=e.body.getReader(),o=new TextDecoder;let n=0,c="";for(;;){const{done:i,value:a}=await t.read();if(i)break;if(a){if(n+=a.byteLength,n>r)return await t.cancel().catch(()=>{}),null;c+=o.decode(a,{stream:!0})}}return c+=o.decode(),c},f=1048576,T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=async(e,r=f)=>{const t=await U(e,r);if(t===null)throw new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});return t},ne=async(e,r=f)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),o=[];let n=0;for(;;){const{done:a,value:d}=await t.read();if(a)break;if(d){if(n+=d.byteLength,n>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o.push(d)}}const c=new Uint8Array(n);let i=0;for(const a of o)c.set(a,i),i+=a.byteLength;return c.buffer},ce=(e,r=f)=>{const t=e.body;let o=!1;if(t===null)return{overflowed:()=>o,request:e};let n,c=0;const i=new ReadableStream({cancel:async a=>{await(n??t).cancel(a)},pull:async a=>{n??=t.getReader();const{done:d,value:s}=await n.read();if(d){a.close();return}if(c+=s.byteLength,c>r){o=!0,a.error(new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})),n.cancel().catch(()=>{});return}a.enqueue(s)}},{highWaterMark:0});return{overflowed:()=>o,request:new Request(e,{body:i,duplex:"half"})}},G=async(e,r,t=f)=>{try{const o=await I(e,t);return o===""?{}:JSON.parse(o)}catch(o){throw o instanceof h?o:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},ie=async(e,r=f)=>{const t=await G(e,"Request",r);if(!T(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},N=(e,r)=>{if(!T(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},M=/^[\d.:a-f]+$/iu,$=e=>{const r=e.indexOf("%"),t=r===-1?e:e.slice(0,r);if(!t.includes(":")||!M.test(t))return e;let o;try{o=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return e}const[n="",c]=o.split("::"),i=n===""?[]:n.split(":"),a=c===void 0||c===""?[]:c.split(":"),d=[...i,...Array.from({length:8-i.length-a.length},()=>"0"),...a].map(s=>Number.parseInt(s,16));if(d.slice(0,5).every(s=>s===0)&&d[5]===65535){const[s=0,u=0]=d.slice(6);return[s>>8,s&255,u>>8,u&255].join(".")}return`${d.slice(0,4).map(s=>s.toString(16)).join(":")}::/64`},R="__lunora_key",K="x-lunora-edge-cache",Y=["x-d1-bookmark","x-lunora-shard-key"],H=()=>{try{return globalThis.caches?.default}catch{return}},F=":deploy",_=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),J=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:_(t).every(o=>o!=="*"&&r.includes(o))},Q=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||O(e.maxAge)<=0)return;const t=_(P(e)??""),o=(n,c)=>{const i=new URL(n.url);i.searchParams.delete(R),i.searchParams.sort();const a=C(c),d=[...a===void 0?[]:[`${F}=${a}`],...t.map(s=>`${s}=${n.headers.get(s)??""}`)];return d.length>0&&i.searchParams.set(R,d.join("\0")),new Request(i.toString(),{method:"GET"})};return{forRequest:(n,c,i)=>{const a=r??H();if(a===void 0||n.method!=="GET"||B(e,n,i)!=="public")return;let d;try{d=o(n,c)}catch{return}return{lookup:async()=>{let s;try{s=await a.match(d)}catch{return}if(s===void 0)return;const u=new Response(s.body,s);return u.headers.set(K,"hit"),u},store:s=>{if(s.status!==200||s.headers.has("set-cookie")||s.headers.has("payment-response")||s.headers.has("x-payment-response")||!J(s,t))return s;try{const u=new Response(s.clone().body,s);for(const l of Y)u.headers.delete(l);const w=Promise.resolve(a.put(d,u)).catch(()=>{});i?.waitUntil&&i.waitUntil(w)}catch{}return s}}}}},W=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",V=(e,r)=>{if(W())return e.get("cf-connecting-ip")??void 0;if(r===void 0)return;const t=e.get(r)?.trim();return t===void 0||t===""||t.includes(",")?void 0:t},X=(e,r)=>{if(r.x402!==void 0&&r.expose?.cache?.scope==="public")throw new h(`REST route "${e}" is paid (.x402) but declares \`cache: { scope: "public" }\`: a shared cache would replay the paid response to callers who never paid. Use \`scope: "private"\` or drop the cache policy.`,{code:"MISCONFIGURED",status:500})},z=e=>D(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),Z=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const o=r.headers.get("x-lunora-shard-key");return o===null||o===""?void 0:o},q=e=>{const r=Object.create(null);for(const[t,o]of e.searchParams.entries())if(!(t==="shardKey"||t===R))try{r[t]=JSON.parse(o)}catch{r[t]=o}return r},de=e=>{const{edgeCache:r,functions:t,invoke:o,rateLimit:n,readJsonBody:c}=e,i={};for(const a of z(t)){const d=a.kind==="query"?["GET","POST"]:["POST"],s=t[a.functionPath];X(a.functionPath,s);const u=s.expose?.cache,w=Q(u,r);i[a.path]=async(l,v,te,y)=>{const b=j(l,d);if(b)return b;const E=new URL(l.url);if(n){const m=await n(l,a.functionPath);if(m)return m}const g=w?.forRequest(l,v,y),A=await g?.lookup();if(A)return A;let p;l.method==="GET"?p=q(E):p=l.body===null?{}:await c(l),N(p,"REST");const L=Z(E,l),k=await o({args:p,env:v,functionPath:a.functionPath,request:l,...L===void 0?{}:{shardKey:L},...y?.waitUntil===void 0?{}:{waitUntil:m=>y.waitUntil?.(m)}}),S=x(k,u,l,y);return g?g.store(S):S}}return i},ee=()=>Response.json({error:{code:"INTERNAL",message:"REST rate limit: no caller key could be resolved. Declare `trustedClientIpHeader` (a header your proxy stamps and callers cannot write), or pass `key` to identify callers by something unforgeable."}},{headers:{"content-type":"application/json"},status:500}),le=(e,r)=>async(t,o)=>{let n;if(r.key)n=r.key(t,o);else{const a=V(t.headers,r.trustedClientIpHeader);n=a===void 0?void 0:$(a)}if(n===void 0||n==="")return ee();const c=await e.limit(r.name,{key:n});if(c.ok)return;if(c.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const i=Math.max(1,Math.ceil(c.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(i)},status:429})};export{f as M,q as a,de as b,le as c,ie as d,G as e,ne as f,N as g,I as h,z as r,V as t,ce as w};
@@ -0,0 +1 @@
1
+ const n="CF_VERSION_METADATA",e=(r,o)=>{if(typeof r!="object"||r===null)return;const t=r[o];return typeof t=="string"&&t.length>0?t:void 0},s=r=>{if(!(typeof r!="object"||r===null))return e(r[n],"id")};export{n as V,e as s,s as w};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/runtime",
3
- "version": "1.0.0-alpha.276",
3
+ "version": "1.0.0-alpha.278",
4
4
  "description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},N=e=>`${String(Math.round(e))}000000`,A=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,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};
@@ -1 +0,0 @@
1
- import{c as O,d as k,e as P,a as B,f as j}from"./rest-cache-CmHN871W.mjs";import{LunoraError as h}from"./LunoraError-PkZWF-_g.mjs";import{m as x}from"./method-guard-8Jo4Q8uS.mjs";const D=async(e,r)=>{if(!e.body)return"";const t=e.body.getReader(),o=new TextDecoder;let s=0,c="";for(;;){const{done:n,value:a}=await t.read();if(n)break;if(a){if(s+=a.byteLength,s>r)return await t.cancel().catch(()=>{}),null;c+=o.decode(a,{stream:!0})}}return c+=o.decode(),c},p=1048576,L=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),C=async(e,r=p)=>{const t=await D(e,r);if(t===null)throw new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});return t},re=async(e,r=p)=>{if(!e.body)return new ArrayBuffer(0);const t=e.body.getReader(),o=[];let s=0;for(;;){const{done:a,value:i}=await t.read();if(a)break;if(i){if(s+=i.byteLength,s>r)throw await t.cancel().catch(()=>{}),new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});o.push(i)}}const c=new Uint8Array(s);let n=0;for(const a of o)c.set(a,n),n+=a.byteLength;return c.buffer},ae=(e,r=p)=>{const t=e.body;let o=!1;if(t===null)return{overflowed:()=>o,request:e};let s,c=0;const n=new ReadableStream({cancel:async a=>{await(s??t).cancel(a)},pull:async a=>{s??=t.getReader();const{done:i,value:d}=await s.read();if(i){a.close();return}if(c+=d.byteLength,c>r){o=!0,a.error(new h("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413})),s.cancel().catch(()=>{});return}a.enqueue(d)}},{highWaterMark:0});return{overflowed:()=>o,request:new Request(e,{body:n,duplex:"half"})}},U=async(e,r,t=p)=>{try{const o=await C(e,t);return o===""?{}:JSON.parse(o)}catch(o){throw o instanceof h?o:new h(`${r} body must be valid JSON`,{code:"BAD_REQUEST",status:400})}},oe=async(e,r=p)=>{const t=await U(e,"Request",r);if(!L(t))throw new h("Request body must be an object",{code:"BAD_REQUEST",status:400});return t},G=(e,r)=>{if(!L(e))throw new h(`${r} \`args\` must be an object`,{code:"BAD_REQUEST",status:400})},I=/^[\d.:a-f]+$/iu,N=e=>{const r=e.indexOf("%"),t=r===-1?e:e.slice(0,r);if(!t.includes(":")||!I.test(t))return e;let o;try{o=new URL(`http://[${t}]/`).hostname.slice(1,-1)}catch{return e}const[s="",c]=o.split("::"),n=s===""?[]:s.split(":"),a=c===void 0||c===""?[]:c.split(":"),i=[...n,...Array.from({length:8-n.length-a.length},()=>"0"),...a].map(d=>Number.parseInt(d,16));if(i.slice(0,5).every(d=>d===0)&&i[5]===65535){const[d=0,u=0]=i.slice(6);return[d>>8,d&255,u>>8,u&255].join(".")}return`${i.slice(0,4).map(d=>d.toString(16)).join(":")}::/64`},g="__lunora_vary",M="x-lunora-edge-cache",$=["x-d1-bookmark","x-lunora-shard-key"],H=()=>{try{return globalThis.caches?.default}catch{return}},S=e=>e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!==""),K=(e,r)=>{const t=e.headers.get("vary");return t===null?!0:S(t).every(o=>o!=="*"&&r.includes(o))},Y=(e,r)=>{if(e===void 0||r===null||e.scope!=="public"||O(e.maxAge)<=0)return;const t=()=>r??H(),o=S(k(e)??""),s=n=>{const a=new URL(n.url);return a.searchParams.delete(g),o.length>0&&a.searchParams.set(g,o.map(i=>`${i}=${n.headers.get(i)??""}`).join("\0")),new Request(a.toString(),{method:"GET"})},c=(n,a)=>n.method==="GET"&&P(e,n,a)==="public";return{lookup:async(n,a)=>{const i=t();if(i===void 0||!c(n,a))return;let d;try{d=await i.match(s(n))}catch{return}if(d===void 0)return;const u=new Response(d.body,d);return u.headers.set(M,"hit"),u},store:(n,a,i)=>{const d=t();if(d===void 0||!c(a,i)||n.status!==200||n.headers.has("set-cookie")||n.headers.has("payment-response")||n.headers.has("x-payment-response")||!K(n,o))return n;try{const u=new Response(n.clone().body,n);for(const l of $)u.headers.delete(l);const f=Promise.resolve(d.put(s(a),u)).catch(()=>{});i?.waitUntil&&i.waitUntil(f)}catch{}return n}}},F=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",J=(e,r)=>{if(F())return e.get("cf-connecting-ip")??void 0;if(r===void 0)return;const t=e.get(r)?.trim();return t===void 0||t===""||t.includes(",")?void 0:t},Q=(e,r)=>{if(r.x402!==void 0&&r.expose?.cache?.scope==="public")throw new h(`REST route "${e}" is paid (.x402) but declares \`cache: { scope: "public" }\`: a shared cache would replay the paid response to callers who never paid. Use \`scope: "private"\` or drop the cache policy.`,{code:"MISCONFIGURED",status:500})},W=e=>j(Object.entries(e).map(([r,t])=>({exposure:t.expose,functionPath:r,kind:t.kind}))),V=(e,r)=>{const t=e.searchParams.get("shardKey");if(t!==null&&t!=="")return t;const o=r.headers.get("x-lunora-shard-key");return o===null||o===""?void 0:o},X=e=>{const r=Object.create(null);for(const[t,o]of e.searchParams.entries())if(!(t==="shardKey"||t===g))try{r[t]=JSON.parse(o)}catch{r[t]=o}return r},ne=e=>{const{edgeCache:r,functions:t,invoke:o,rateLimit:s,readJsonBody:c}=e,n={};for(const a of W(t)){const i=a.kind==="query"?["GET","POST"]:["POST"],d=t[a.functionPath];Q(a.functionPath,d);const u=d.expose?.cache,f=Y(u,r);n[a.path]=async(l,T,Z,y)=>{const R=x(l,i);if(R)return R;const v=new URL(l.url);if(s){const m=await s(l,a.functionPath);if(m)return m}const b=await f?.lookup(l,y);if(b)return b;let w;l.method==="GET"?w=X(v):w=l.body===null?{}:await c(l),G(w,"REST");const E=V(v,l),_=await o({args:w,env:T,functionPath:a.functionPath,request:l,...E===void 0?{}:{shardKey:E},...y?.waitUntil===void 0?{}:{waitUntil:m=>y.waitUntil?.(m)}}),A=B(_,u,l,y);return f?f.store(A,l,y):A}}return n},z=()=>Response.json({error:{code:"INTERNAL",message:"REST rate limit: no caller key could be resolved. Declare `trustedClientIpHeader` (a header your proxy stamps and callers cannot write), or pass `key` to identify callers by something unforgeable."}},{headers:{"content-type":"application/json"},status:500}),se=(e,r)=>async(t,o)=>{let s;if(r.key)s=r.key(t,o);else{const a=J(t.headers,r.trustedClientIpHeader);s=a===void 0?void 0:N(a)}if(s===void 0||s==="")return z();const c=await e.limit(r.name,{key:s});if(c.ok)return;if(c.reason==="deny")return Response.json({error:{code:"FORBIDDEN",message:"Request denied"}},{headers:{"content-type":"application/json"},status:403});const n=Math.max(1,Math.ceil(c.retryAfter/1e3));return Response.json({error:{code:"RATE_LIMITED",message:"Rate limit exceeded"}},{headers:{"content-type":"application/json","retry-after":String(n)},status:429})};export{p as M,X as a,ne as b,se as c,oe as d,U as e,re as f,G as g,C as h,W as r,J as t,ae as w};