@lunora/runtime 1.0.0-alpha.75 → 1.0.0-alpha.76
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.mjs +1 -1
- package/dist/packem_shared/{analyticsEngineSink-BgmqAmTM.mjs → analyticsEngineSink-CxWOC73c.mjs} +1 -1
- package/dist/packem_shared/{composeWorker-DFhiNfmF.mjs → composeWorker-DtqXJLCu.mjs} +1 -1
- package/dist/packem_shared/otlp-resource-DeXhb949.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/otlp-resource-B4Yylr0V.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CZimuevO.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-
|
|
1
|
+
import{BACKUP_KEY_PREFIX as t,backupManifestKey as a,backupObjectKey as s,backupObjectKeyOfManifest as i,isBackupManifestEntry as n,isBackupManifestKey as p,normalizeBackupPrefix as c}from"./packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toAirbyteMessages as f,toFivetranResponse as E}from"./packem_shared/toAirbyteMessages-CZimuevO.mjs";import{composeWorker as S,createLunoraHandler as x,createWorker as _,defineRpcEnvelope as d,resolveLunoraOptions as l,withFrameworkWorker as u}from"./packem_shared/composeWorker-DtqXJLCu.mjs";import{createCrossShardRelationCapabilities as k}from"./packem_shared/createCrossShardRelationCapabilities-DgQYQzd1.mjs";import{DEFAULT_REGISTRY_CACHE_TTL_MS as A,SHARD_REGISTRY_DO_NAME as C,createDynamicShardRegistry as L}from"./packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-D5O7elXI.mjs";import{LunoraError as b,toErrorResponse as g}from"./packem_shared/LunoraError-DksAgIpa.mjs";import{createKvCursorStore as H,createMemoryCursorStore as I,defineExportSink as P,r2Sink as v,runExportTap as D,sanitizeChange as F,webhookExportSink as M}from"./packem_shared/createKvCursorStore-kQ8HNv0l.mjs";import{HEALTH_PATH as K,HEALTH_READY_PATH as N,buildHealthRoutes as U,d1Probe as B,durableObjectProbe as Y,presenceProbe as w}from"./packem_shared/HEALTH_PATH-jZsuCmSs.mjs";import{LOG_ARCHIVE_PATH as X,resolveLogArchiveFromEnv as j}from"./packem_shared/LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{memoizeIdentity as W,memoizeIdentityPerRequest as q}from"./packem_shared/memoizeIdentity-DnOj3QRi.mjs";import{e as J,a as Z}from"./packem_shared/observability-vDK-rMbs.mjs";import{analyticsEngineSink as ee,combineSinks as re,consoleSink as oe,otlpSink as te,pipelineLogSink as ae,sentrySink as se,webhookSink as ie}from"./packem_shared/analyticsEngineSink-CxWOC73c.mjs";import{D as pe,a as ce,c as me}from"./packem_shared/pipeline-log-reader-BGrl66P5.mjs";import{createQueryCoordinator as Ee,createStaticShardRegistry as Re,mergeStrategyForAggregate as Se}from"./packem_shared/createQueryCoordinator-CnNyazLX.mjs";import{applyJurisdiction as _e,resolveShard as de}from"./packem_shared/applyJurisdiction-C0ddU7Tg.mjs";import{a as ue,r as ye,b as ke}from"./packem_shared/rest-cache-CPSyD1RD.mjs";import{a as Ae,b as Ce,c as Le,r as Te,d as be}from"./packem_shared/rest-routes-Dq17Zntv.mjs";import{decorateResponse as he,enforceOrigin as He,handleCorsPreflight as Ie,resolveSecurity as Pe}from"./packem_shared/decorateResponse-BuqVnrmc.mjs";import{createShardClient as De}from"./packem_shared/createShardClient-CCncsgTs.mjs";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Me}from"./packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{LOG_ARCHIVE_NOT_CONFIGURED as Ke}from"./packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs";import{NOOP_EXECUTION_CONTEXT as Ue}from"./packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{composeIdentityResolvers as Ye,routeIdentityResolvers as we}from"./packem_shared/composeIdentityResolvers-BHZ4jH8o.mjs";const e="0.0.0";export{t as BACKUP_KEY_PREFIX,pe as DEFAULT_LOG_COLUMNS,ce as DEFAULT_LOG_LIMIT,A as DEFAULT_REGISTRY_CACHE_TTL_MS,K as HEALTH_PATH,N as HEALTH_READY_PATH,Ke as LOG_ARCHIVE_NOT_CONFIGURED,X as LOG_ARCHIVE_PATH,b as LunoraError,Ue as NOOP_EXECUTION_CONTEXT,C as SHARD_REGISTRY_DO_NAME,Me as STORAGE_UPLOAD_MAX_BODY_BYTES,e as VERSION,ee as analyticsEngineSink,_e as applyJurisdiction,ue as applyRestCache,Ae as argsFromQuery,a as backupManifestKey,s as backupObjectKey,i as backupObjectKeyOfManifest,U as buildHealthRoutes,Ce as buildRestRoutes,re as combineSinks,Ye as composeIdentityResolvers,S as composeWorker,oe as consoleSink,k as createCrossShardRelationCapabilities,L as createDynamicShardRegistry,H as createKvCursorStore,x as createLunoraHandler,I as createMemoryCursorStore,me as createPipelineLogReader,Ee as createQueryCoordinator,Le as createRestRateLimit,De as createShardClient,Re as createStaticShardRegistry,_ as createWorker,B as d1Probe,he as decorateResponse,P as defineExportSink,d as defineRpcEnvelope,Y as durableObjectProbe,J as emitLogEvent,Z as emitRpcEvent,He as enforceOrigin,Ie as handleCorsPreflight,n as isBackupManifestEntry,p as isBackupManifestKey,W as memoizeIdentity,q as memoizeIdentityPerRequest,Se as mergeStrategyForAggregate,c as normalizeBackupPrefix,te as otlpSink,ae as pipelineLogSink,w as presenceProbe,v as r2Sink,Te as readShardKey,ye as requestCarriesCredentials,j as resolveLogArchiveFromEnv,l as resolveLunoraOptions,Pe as resolveSecurity,de as resolveShard,ke as restCacheHeaders,be as restSurfaceFromRegistry,we as routeIdentityResolvers,D as runExportTap,F as sanitizeChange,se as sentrySink,f as toAirbyteMessages,g as toErrorResponse,E as toFivetranResponse,M as webhookExportSink,ie as webhookSink,u as withFrameworkWorker};
|
package/dist/packem_shared/{analyticsEngineSink-BgmqAmTM.mjs → analyticsEngineSink-CxWOC73c.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as d,L as y,o as j,c as S,O as $,f as C,g as X,h as B,w as Y,i as q,j as G,m as Z}from"./otlp-resource-B4Yylr0V.mjs";const Q=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},J=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:Q(r),v=512,rr=200,tr=r=>{const s=r.maxItems??v,t=r.maxDelayMs??rr;let o=[],e,i,l;const f=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{f();const u=o;o=[];const a=l;i=void 0,l=void 0;try{u.length>0&&await r.export(u)}catch{}finally{a?.()}},m=u=>{i===void 0&&(i=new Promise(a=>{l=a}),e=setTimeout(()=>{h()},t)),u?.(i)};return{add:(u,a)=>{for(o.push(u);o.length>s;)o.shift();m(a),o.length>=s&&h()},flush:async u=>{if(o.length===0){f();return}const a=h();return u?.(a),a},get size(){return o.length}}},or=(r,s)=>r<s?-1:r>s?1:0,L=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return`[${r.map(i=>L(i)).join(",")}]`;const s=Object.getPrototypeOf(r);if(s!==null&&s!==Object.prototype){const i=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const t=r,o=Object.keys(t).toSorted(or),e=[];for(const i of o){const l=t[i];l!==void 0&&e.push(`${JSON.stringify(i)}:${L(l)}`)}return`{${e.join(",")}}`},sr=(r,s)=>{const t=[d(y.functionPath,r.functionPath),d(y.ok,r.ok)];r.method!==void 0&&t.push(d("http.request.method",r.method)),r.path!==void 0&&t.push(d("url.path",r.path)),t.push(d("http.route",r.functionPath)),r.scheme!==void 0&&t.push(d("url.scheme",r.scheme)),r.host!==void 0&&t.push(d("server.address",r.host)),r.port!==void 0&&t.push(d("server.port",r.port)),r.userAgent!==void 0&&t.push(d("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(d(y.shardKey,r.shardKey)),t.push(d("http.response.status_code",r.error?.status??200)),r.error&&t.push(d(y.errorType,r.error.code),d("lunora.error_status",r.error.status)),r.fanOut&&t.push(d("lunora.fanout.table",r.fanOut.table),d("lunora.fanout.shards",r.fanOut.shards),d("lunora.fanout.failed",r.fanOut.failed));const o={attributes:t,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:S(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:[d("exception.type",r.error.code),d("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),o},R=(r,s)=>{const t=new Map([[y.functionPath,d(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&t.set(y.shardKey,d(y.shardKey,r.shardKey)),r.userId!==void 0&&t.set(y.userId,d(y.userId,r.userId)),r.errorType!==void 0&&t.set(y.errorType,d(y.errorType,r.errorType));for(const[o,e]of Object.entries(s??{}))t.set(o,d(o,J(e)));return[...t.values()]},er=r=>{const s={attributes:R({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>X(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,J(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:S(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},nr=r=>{const s=S(r.ts),t=R({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o={asDouble:r.value,attributes:t,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[o]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[o],isMonotonic:!0}}},ir=r=>{const s={attributes:R({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:C[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(d("event.name",r.eventName))),s},ar=1024,cr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},z=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),l=(i<ar?fetch(r,{body:e,headers:t,method:"POST"}):cr(e).then(f=>fetch(r,{body:f,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});o?.(l),await l}catch{}},dr=(r,s,t,o)=>{z(r,s,t,o?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,ur=r=>r.kind==="metric"?void 0:r.event.traceId,pr=r=>{const s=Map.groupBy(r,o=>ur(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},D=5,lr=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=pr(r),i=[...e];let l=0,f;for(const[h,m]of o){let u;try{u=s({logs:m.filter(a=>a.kind==="log").map(a=>a.event),rpc:m.filter(a=>a.kind==="rpc").map(a=>a.event),spans:m.filter(a=>a.kind==="span").map(a=>a.event),traceId:h})}catch(a){l+=1,l===1&&(f=a),u=!0}u&&i.push(...m)}return l>0&&t(f,l),i},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},F=(r,s)=>{if(r.kind==="rpc"){const o=P(r.event,s?.rpc);return o===void 0?void 0:{bucket:"spans",encoded:sr(o,r.endMs)}}if(r.kind==="span"){const o=P(r.event,s?.span);return o===void 0?void 0:{bucket:"spans",encoded:er(o)}}if(r.kind==="log"){const o=P(r.event,s?.log);return o===void 0?void 0:{bucket:"logs",encoded:ir(o)}}const t=P(r.event,s?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:nr(t)}},mr=(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=>{O(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)}}},hr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,l=B({"content-type":"application/json"},s),f=(h,m)=>{try{const u=fetch(i,{body:JSON.stringify(h),headers:l,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(u)}catch{}};return{onLog:(h,m)=>{const u=P(h,e);u!==void 0&&f(u,m)},onRpc:(h,m)=>{if(O(h,t))return;const u=P(h,o);u!==void 0&&f(u,m)}}},yr=r=>{const{capture:s,captureLog:t}=r,o=r.onlyErrors??!0;return{onLog:t?e=>{try{t(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,o))try{s(e)}catch{}}}},gr=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!O(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{}}}},br=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 f of["shardKey","userId","traceId","spanId"])o[f]!==void 0&&(i[f]=o[f]);const l=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(l)}catch{}}}},kr=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:l,postProcessor:f,resourceAttributes:h,serviceNamespace:m,serviceVersion:u,tailSampler:a,token:H}=r,U=r.serviceName??"lunora",E={...u===void 0?{}:{"service.version":u},...m===void 0?{}:{"service.namespace":m},...t===void 0?{}:{"deployment.environment":t},...h},x=new WeakMap,k=c=>{if(o!==!0||c?.resourceAttributes===void 0)return E;const n=x.get(c);if(n!==void 0)return n;const p=Z(c.resourceAttributes(),E);return x.set(c,p),p};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const K={logs:{url:`${I}/v1/logs`,wrap:G},metrics:{url:`${I}/v1/metrics`,wrap:q},spans:{url:`${I}/v1/traces`,wrap:Y}},_=B({"content-type":"application/json"},i,H);let A=0;const V=(c,n)=>{if(A>=D)return;A+=1;const p=A===D?" 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.${p}`,c)},W=async c=>{const n=lr(c,a,V),p=new Map;for(const g of n){const b=F(g,f);if(b===void 0)continue;const M=L(g.resource);let T=p.get(M);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},p.set(M,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of p)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:M,wrap:T}=K[b];w.push(z(M,T(g[b],"@lunora/runtime",U,g.resource),_))}await Promise.all(w)};if(s===!1){const c=(n,p)=>{const w=F(n,f);if(w!==void 0){const{url:g,wrap:b}=K[w.bucket];dr(g,b(w.encoded,"@lunora/runtime",U,n.resource),_,p)}};return{onLog:(n,p)=>{c({event:n,kind:"log",resource:k(p)},p)},onMetric:(n,p)=>{c({event:n,kind:"metric",resource:k(p)},p)},onRpc:(n,p)=>{O(n,l)||c({endMs:Date.now(),event:n,kind:"rpc",resource:k(p)},p)},onSpan:(n,p)=>{c({event:n,kind:"span",resource:k(p)},p)}}}const N=tr({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:c=>{N.flush(c?.waitUntil).catch(()=>{})},onLog:(c,n)=>{N.add({event:c,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(c,n)=>{N.add({event:c,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(c,n)=>{O(c,l)||N.add({endMs:Date.now(),event:c,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(c,n)=>{N.add({event:c,kind:"span",resource:k(n)},n?.waitUntil)}}},Sr=(...r)=>{const s=(t,o)=>{for(const e of r){const i=e[t];if(i)try{i.apply(e,o)}catch{}}};return{flush:t=>{s("flush",[t])},onLog:(t,o)=>{s("onLog",[t,o])},onMetric:(t,o)=>{s("onMetric",[t,o])},onRpc:(t,o)=>{s("onRpc",[t,o])},onSpan:(t,o)=>{s("onSpan",[t,o])}}};export{gr as analyticsEngineSink,Sr as combineSinks,mr as consoleSink,kr as otlpSink,br as pipelineLogSink,yr as sentrySink,hr as webhookSink};
|
|
1
|
+
import{e as d,L as y,o as j,c as S,O as $,f as C,g as X,h as B,w as Y,i as q,j as G,m as Z}from"./otlp-resource-DeXhb949.mjs";const Q=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}},J=r=>typeof r=="boolean"||typeof r=="number"||typeof r=="string"?r:Q(r),v=512,rr=200,tr=r=>{const s=r.maxItems??v,t=r.maxDelayMs??rr;let o=[],e,i,l;const f=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},h=async()=>{f();const u=o;o=[];const a=l;i=void 0,l=void 0;try{u.length>0&&await r.export(u)}catch{}finally{a?.()}},m=u=>{i===void 0&&(i=new Promise(a=>{l=a}),e=setTimeout(()=>{h()},t)),u?.(i)};return{add:(u,a)=>{for(o.push(u);o.length>s;)o.shift();m(a),o.length>=s&&h()},flush:async u=>{if(o.length===0){f();return}const a=h();return u?.(a),a},get size(){return o.length}}},or=(r,s)=>r<s?-1:r>s?1:0,L=r=>{if(r===void 0)return"null";if(typeof r=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof r=="number"){if(Number.isNaN(r))return"nan";if(r===1/0)return"inf";if(r===-1/0)return"-inf";if(Object.is(r,-0))return"-0"}if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return`[${r.map(i=>L(i)).join(",")}]`;const s=Object.getPrototypeOf(r);if(s!==null&&s!==Object.prototype){const i=r.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${i} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const t=r,o=Object.keys(t).toSorted(or),e=[];for(const i of o){const l=t[i];l!==void 0&&e.push(`${JSON.stringify(i)}:${L(l)}`)}return`{${e.join(",")}}`},sr=(r,s)=>{const t=[d(y.functionPath,r.functionPath),d(y.ok,r.ok)];r.method!==void 0&&t.push(d("http.request.method",r.method)),r.path!==void 0&&t.push(d("url.path",r.path)),t.push(d("http.route",r.functionPath)),r.scheme!==void 0&&t.push(d("url.scheme",r.scheme)),r.host!==void 0&&t.push(d("server.address",r.host)),r.port!==void 0&&t.push(d("server.port",r.port)),r.userAgent!==void 0&&t.push(d("user_agent.original",r.userAgent)),r.shardKey!==void 0&&t.push(d(y.shardKey,r.shardKey)),t.push(d("http.response.status_code",r.error?.status??200)),r.error&&t.push(d(y.errorType,r.error.code),d("lunora.error_status",r.error.status)),r.fanOut&&t.push(d("lunora.fanout.table",r.fanOut.table),d("lunora.fanout.shards",r.fanOut.shards),d("lunora.fanout.failed",r.fanOut.failed));const o={attributes:t,endTimeUnixNano:S(s),kind:$.server,name:r.functionPath,...r.parentSpanId===void 0?{}:{parentSpanId:r.parentSpanId},spanId:r.spanId??j(8),startTimeUnixNano:S(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:[d("exception.type",r.error.code),d("exception.message",r.error.message)],name:"exception",timeUnixNano:S(s)}]),o},R=(r,s)=>{const t=new Map([[y.functionPath,d(y.functionPath,r.functionPath)]]);r.shardKey!==void 0&&t.set(y.shardKey,d(y.shardKey,r.shardKey)),r.userId!==void 0&&t.set(y.userId,d(y.userId,r.userId)),r.errorType!==void 0&&t.set(y.errorType,d(y.errorType,r.errorType));for(const[o,e]of Object.entries(s??{}))t.set(o,d(o,J(e)));return[...t.values()]},er=r=>{const s={attributes:R({errorType:r.error?.type,functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.attributes),endTimeUnixNano:S(r.startTs+r.durationMs),kind:$[r.kind??"internal"],name:r.name,parentSpanId:r.parentSpanId,spanId:r.spanId,startTimeUnixNano:S(r.startTs),status:r.ok?{code:1}:{code:2,message:r.error?.message??""},traceId:r.traceId},t=o=>X(Object.fromEntries(Object.entries(o??{}).map(([e,i])=>[e,J(i)])));return r.events!==void 0&&r.events.length>0&&(s.events=r.events.map(o=>({attributes:t(o.attributes),name:o.name,timeUnixNano:S(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},nr=r=>{const s=S(r.ts),t=R({functionPath:r.functionPath,shardKey:r.shardKey},r.attributes),o={asDouble:r.value,attributes:t,timeUnixNano:s};return r.kind==="gauge"?{gauge:{dataPoints:[o]},name:r.name}:r.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:t,bucketCounts:["1"],count:"1",explicitBounds:[],max:r.value,min:r.value,sum:r.value,timeUnixNano:s}]},name:r.name}:{name:r.name,sum:{aggregationTemporality:1,dataPoints:[o],isMonotonic:!0}}},ir=r=>{const s={attributes:R({functionPath:r.functionPath,shardKey:r.shardKey,userId:r.userId},r.fields),body:{stringValue:r.message},severityNumber:C[r.level],severityText:r.level.toUpperCase(),timeUnixNano:S(r.ts)};return r.traceId!==void 0&&(s.traceId=r.traceId),r.spanId!==void 0&&(s.spanId=r.spanId),r.eventName!==void 0&&(s.eventName=r.eventName,s.attributes.push(d("event.name",r.eventName))),s},ar=1024,cr=async r=>{const s=new Blob([r]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(s).arrayBuffer()},z=async(r,s,t,o)=>{try{const e=JSON.stringify(s),{byteLength:i}=new TextEncoder().encode(e),l=(i<ar?fetch(r,{body:e,headers:t,method:"POST"}):cr(e).then(f=>fetch(r,{body:f,headers:{...t,"content-encoding":"gzip"},method:"POST"}))).then(()=>{},()=>{});o?.(l),await l}catch{}},dr=(r,s,t,o)=>{z(r,s,t,o?.waitUntil).catch(()=>{})},O=(r,s)=>s===!0&&r.ok,ur=r=>r.kind==="metric"?void 0:r.event.traceId,pr=r=>{const s=Map.groupBy(r,o=>ur(o)),t=s.get(void 0)??[];return s.delete(void 0),{byTrace:s,untraced:t}},D=5,lr=(r,s,t)=>{if(s===void 0)return r;const{byTrace:o,untraced:e}=pr(r),i=[...e];let l=0,f;for(const[h,m]of o){let u;try{u=s({logs:m.filter(a=>a.kind==="log").map(a=>a.event),rpc:m.filter(a=>a.kind==="rpc").map(a=>a.event),spans:m.filter(a=>a.kind==="span").map(a=>a.event),traceId:h})}catch(a){l+=1,l===1&&(f=a),u=!0}u&&i.push(...m)}return l>0&&t(f,l),i},P=(r,s)=>{if(s===void 0)return r;try{return s(r)??void 0}catch{return}},F=(r,s)=>{if(r.kind==="rpc"){const o=P(r.event,s?.rpc);return o===void 0?void 0:{bucket:"spans",encoded:sr(o,r.endMs)}}if(r.kind==="span"){const o=P(r.event,s?.span);return o===void 0?void 0:{bucket:"spans",encoded:er(o)}}if(r.kind==="log"){const o=P(r.event,s?.log);return o===void 0?void 0:{bucket:"logs",encoded:ir(o)}}const t=P(r.event,s?.metric);return t===void 0?void 0:{bucket:"metrics",encoded:nr(t)}},mr=(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=>{O(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)}}},hr=r=>{const{headers:s,onlyErrors:t,transform:o,transformLog:e,url:i}=r,l=B({"content-type":"application/json"},s),f=(h,m)=>{try{const u=fetch(i,{body:JSON.stringify(h),headers:l,method:"POST"}).catch(()=>{});m?.waitUntil&&m.waitUntil(u)}catch{}};return{onLog:(h,m)=>{const u=P(h,e);u!==void 0&&f(u,m)},onRpc:(h,m)=>{if(O(h,t))return;const u=P(h,o);u!==void 0&&f(u,m)}}},yr=r=>{const{capture:s,captureLog:t}=r,o=r.onlyErrors??!0;return{onLog:t?e=>{try{t(e)}catch{}}:void 0,onRpc:e=>{if(!O(e,o))try{s(e)}catch{}}}},gr=r=>{const{dataset:s,onlyErrors:t}=r;return{onRpc:o=>{if(!O(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{}}}},br=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 f of["shardKey","userId","traceId","spanId"])o[f]!==void 0&&(i[f]=o[f]);const l=s.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(l)}catch{}}}},kr=r=>{const{batch:s,deploymentEnvironment:t,detectResources:o,endpoint:e,headers:i,onlyErrors:l,postProcessor:f,resourceAttributes:h,serviceNamespace:m,serviceVersion:u,tailSampler:a,token:H}=r,U=r.serviceName??"lunora",E={...u===void 0?{}:{"service.version":u},...m===void 0?{}:{"service.namespace":m},...t===void 0?{}:{"deployment.environment":t},...h},x=new WeakMap,k=c=>{if(o!==!0||c?.resourceAttributes===void 0)return E;const n=x.get(c);if(n!==void 0)return n;const p=Z(c.resourceAttributes(),E);return x.set(c,p),p};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const K={logs:{url:`${I}/v1/logs`,wrap:G},metrics:{url:`${I}/v1/metrics`,wrap:q},spans:{url:`${I}/v1/traces`,wrap:Y}},_=B({"content-type":"application/json"},i,H);let A=0;const V=(c,n)=>{if(A>=D)return;A+=1;const p=A===D?" 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.${p}`,c)},W=async c=>{const n=lr(c,a,V),p=new Map;for(const g of n){const b=F(g,f);if(b===void 0)continue;const M=L(g.resource);let T=p.get(M);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},p.set(M,T)),T[b.bucket].push(b.encoded)}const w=[];for(const[,g]of p)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:M,wrap:T}=K[b];w.push(z(M,T(g[b],"@lunora/runtime",U,g.resource),_))}await Promise.all(w)};if(s===!1){const c=(n,p)=>{const w=F(n,f);if(w!==void 0){const{url:g,wrap:b}=K[w.bucket];dr(g,b(w.encoded,"@lunora/runtime",U,n.resource),_,p)}};return{onLog:(n,p)=>{c({event:n,kind:"log",resource:k(p)},p)},onMetric:(n,p)=>{c({event:n,kind:"metric",resource:k(p)},p)},onRpc:(n,p)=>{O(n,l)||c({endMs:Date.now(),event:n,kind:"rpc",resource:k(p)},p)},onSpan:(n,p)=>{c({event:n,kind:"span",resource:k(p)},p)}}}const N=tr({export:W,...s?.maxDelayMs===void 0?{}:{maxDelayMs:s.maxDelayMs},...s?.maxItems===void 0?{}:{maxItems:s.maxItems}});return{flush:c=>{N.flush(c?.waitUntil).catch(()=>{})},onLog:(c,n)=>{N.add({event:c,kind:"log",resource:k(n)},n?.waitUntil)},onMetric:(c,n)=>{N.add({event:c,kind:"metric",resource:k(n)},n?.waitUntil)},onRpc:(c,n)=>{O(c,l)||N.add({endMs:Date.now(),event:c,kind:"rpc",resource:k(n)},n?.waitUntil)},onSpan:(c,n)=>{N.add({event:c,kind:"span",resource:k(n)},n?.waitUntil)}}},Sr=(...r)=>{const s=(t,o)=>{for(const e of r){const i=e[t];if(i)try{i.apply(e,o)}catch{}}};return{flush:t=>{s("flush",[t])},onLog:(t,o)=>{s("onLog",[t,o])},onMetric:(t,o)=>{s("onMetric",[t,o])},onRpc:(t,o)=>{s("onRpc",[t,o])},onSpan:(t,o)=>{s("onSpan",[t,o])}}};export{gr as analyticsEngineSink,Sr as combineSinks,mr as consoleSink,kr as otlpSink,br as pipelineLogSink,yr as sentrySink,hr as webhookSink};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Dt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{e as Cn,a as Bn}from"./identity-header-JF5q3H5w.mjs";import{o as Se,b as xn,p as Hn,m as Ln,d as Mn,a as jn,r as $n}from"./otlp-resource-B4Yylr0V.mjs";import{e as Ke}from"./wire-codec-D_qTfaaH.mjs";import{e as Z,f as be,M as Nt,b as Kn,g as Fn,h as Ut,i as Ct}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as tt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ge,BACKUP_KEY_PREFIX as Qe,isBackupManifestKey as Gn,backupObjectKeyOfManifest as Bt,backupObjectKey as Qn,backupManifestKey as zn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Wn,buildStorageAdminRoutes as Vn,STORAGE_UPLOAD_MAX_BODY_BYTES as Jn,STORAGE_PATH as qn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Yn}from"./createKvCursorStore-kQ8HNv0l.mjs";import{buildHealthRoutes as Xn,durableObjectProbe as Zn,d1Probe as er,presenceProbe as Ce}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as tr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ss}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as nr}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as rr,f as nt,a as ce}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as rt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ot,handleCorsPreflight as or,enforceOrigin as ar,decorateResponse as Be,enforceWebSocketOrigin as at}from"./decorateResponse-BuqVnrmc.mjs";const sr=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},xt="__lunoraBranch",ir=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,xt),cr=`may not contain the reserved workflow branch-marker key ("${xt}")`,ze=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,l=a<n.length?n.charCodeAt(a):0;r|=s^l}return r===0},dr=(e,n,t,r)=>{const a=e.get(n);if(a!==void 0)return a;Dt(e,r);const s=t().catch(l=>{throw e.get(n)===s&&e.delete(n),l});return e.set(n,s),s},We=new TextEncoder,ur=Array.from({length:32},(e,n)=>n);new RegExp(`[${ur.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const lr=e=>{const n=String.fromCodePoint(...e);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},hr=e=>{const n=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),t=atob(n),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.codePointAt(a)??0;return r},fr=64,pr=new Map,Ht=async e=>dr(pr,e,async()=>crypto.subtle.importKey("raw",We.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),fr),Lt=async(e,n)=>{const t=await Ht(e),r=await crypto.subtle.sign("HMAC",t,We.encode(n));return lr(new Uint8Array(r))},mr=async(e,n,t)=>{const r=await Ht(e);return crypto.subtle.verify("HMAC",r,t,We.encode(n))},wr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(wr);const gr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),yr=-100,br=15,_r=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&gr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>br?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<yr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},st=e=>{const n=e.cf;return n===void 0?void 0:_r(n)},Mt="::relay::",Rr=(e,n)=>`${e}${Mt}${String(n)}`,jt="::replica::",Er=(e,n)=>`${e}${jt}${n}`,Ar=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Sr=new Set(["1","enabled","on","true","yes"]),Tr=new Set(["0","disabled","false","no","off"]),Or=(e,n)=>{const t=(e??"").trim().toLowerCase();return Sr.has(t)?!0:Tr.has(t)?!1:n},$t="v1",vr=6e4,kr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??vr),r=`${$t}.${String(t)}`,a=await Lt(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},Ir=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,l]=r;if(a!==$t||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=t)return!1;let f;try{f=hr(l)}catch{return!1}return mr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Pr={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},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},le=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},Kt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},re=(e,n)=>typeof e[n]=="string"?e[n]:void 0,xe=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},it=e=>{const n=Kt(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},ct=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},Dr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:le(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Kt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:it(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:it(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ct(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ct(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Nr=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new d("auth admin operation failed",{code:u,status:Pr[u]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),g={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=s.build(g),k=await n(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:k,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Dr))r[a]=l=>t(l,s);return r},Ur="__lunora_admin__:getAuthAuditLog",dt=e=>typeof e=="string"&&e!==""?e:void 0,ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cr=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=dt(r.actorId),l=dt(r.event),u=ut(r.sinceSeq),f=ut(r.limit),g={...s===void 0?{}:{actorId:s},...l===void 0?{}:{event:l},...u===void 0?{}:{sinceSeq:u},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(g)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const k={entries:E};return Response.json({result:Ke(k)},{headers:{"content-type":"application/json"},status:200})},Br=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},xr=async(e,n,t,r,a,s)=>{if(t!==void 0&&r.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:r},headers:n,tables:r});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])a(f)},Ft=async(e,n,t,r,a,s)=>{const{globalTables:l,shardLocalTables:u}=Br(e,r);await xr(n,t,r,u,a,s);const f=e.exportGlobals;if((r===void 0||l.length>0)&&f)for await(const E of f({tables:l}))a(E)},Hr=new TextEncoder,Lr=1e3,Gt=10,Mr=200,lt=8,Qt="lunoraBackupCron",ht=24*1048576,ft=e=>{const n=e.slice(0,Gt).map(r=>Bt(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},jr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},Ve=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let l=0;l<Lr;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of u.objects)Gn(f.key)&&f.customMetadata?.[Qt]===r&&a.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:a.length,stale:a.toSorted((l,u)=>u.localeCompare(l)).slice(t)}},$r=async(e,n,t,r,a)=>{const{stale:s}=await Ve(e,n,t,r),l=new Set(a),u=s.filter(w=>l.has(w)),f=u.slice(0,Mr),g=s.length-f.length,E=a.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:g};const k=[],v=[];for(let w=0;w<f.length;w+=lt){const b=await Promise.allSettled(f.slice(w,w+lt).map(async _=>(await e.delete(Bt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?k.push(p.value):v.push(f[w+_])}return k.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(k.length)}: ${ft(k)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${ft(v)}`),{deleted:k,failed:v,ignored:E,remaining:g}},Kr=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Ge(e.backupPrefix??Qe),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await Ve(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Fr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${t}`,"content-type":"application/json"},u=e.backupTables;let f=0,g=0,E=[];await Ft(e,s,l,u,D=>{const T=Hr.encode(`${JSON.stringify(D)}
|
|
1
|
+
import{isLunoraError as Dn,toErrorBody as Nn}from"@lunora/errors";import{e as Dt}from"./evict-oldest-BNXsKx4s.mjs";import{NOOP_EXECUTION_CONTEXT as Un}from"./NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs";import{e as Cn,a as Bn}from"./identity-header-JF5q3H5w.mjs";import{o as Se,b as xn,p as Hn,m as Ln,d as Mn,a as jn,r as $n}from"./otlp-resource-DeXhb949.mjs";import{e as Ke}from"./wire-codec-D_qTfaaH.mjs";import{e as Z,f as be,M as Nt,b as Kn,g as Fn,h as Ut,i as Ct}from"./rest-routes-Dq17Zntv.mjs";import{LunoraError as d,toErrorResponse as tt}from"./LunoraError-DksAgIpa.mjs";import{a as j,m as me}from"./method-guard-BG_vJNTl.mjs";import{normalizeBackupPrefix as Ge,BACKUP_KEY_PREFIX as Qe,isBackupManifestKey as Gn,backupObjectKeyOfManifest as Bt,backupObjectKey as Qn,backupManifestKey as zn}from"./BACKUP_KEY_PREFIX-BOtSu-_3.mjs";import{toHex as Wn,buildStorageAdminRoutes as Vn,STORAGE_UPLOAD_MAX_BODY_BYTES as Jn,STORAGE_PATH as qn}from"./STORAGE_UPLOAD_MAX_BODY_BYTES-BqyO-1l6.mjs";import{runExportTap as Yn}from"./createKvCursorStore-kQ8HNv0l.mjs";import{buildHealthRoutes as Xn,durableObjectProbe as Zn,d1Probe as er,presenceProbe as Ce}from"./HEALTH_PATH-jZsuCmSs.mjs";import{wrapResolverWithContract as tr}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{composeIdentityResolvers as As,routeIdentityResolvers as Ss}from"./composeIdentityResolvers-BHZ4jH8o.mjs";import{buildLogArchiveAdminRoutes as nr}from"./LOG_ARCHIVE_PATH-jgHjdsz2.mjs";import{r as rr,f as nt,a as ce}from"./observability-vDK-rMbs.mjs";import{resolveShard as we,applyJurisdiction as rt}from"./applyJurisdiction-C0ddU7Tg.mjs";import{resolveSecurity as ot,handleCorsPreflight as or,enforceOrigin as ar,decorateResponse as Be,enforceWebSocketOrigin as at}from"./decorateResponse-BuqVnrmc.mjs";const sr=e=>{const n=e??{};if(typeof n.bucket=="function")return n;const t={...n,bucketName:"default"};return t.bucket=()=>t,t},xt="__lunoraBranch",ir=e=>typeof e=="object"&&e!==null&&Object.hasOwn(e,xt),cr=`may not contain the reserved workflow branch-marker key ("${xt}")`,ze=(e,n)=>{const t=Math.max(e.length,n.length);let r=e.length^n.length;for(let a=0;a<t;a+=1){const s=a<e.length?e.charCodeAt(a):0,l=a<n.length?n.charCodeAt(a):0;r|=s^l}return r===0},dr=(e,n,t,r)=>{const a=e.get(n);if(a!==void 0)return a;Dt(e,r);const s=t().catch(l=>{throw e.get(n)===s&&e.delete(n),l});return e.set(n,s),s},We=new TextEncoder,ur=Array.from({length:32},(e,n)=>n);new RegExp(`[${ur.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const lr=e=>{const n=String.fromCodePoint(...e);return btoa(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},hr=e=>{const n=e.replaceAll("-","+").replaceAll("_","/")+"===".slice((e.length+3)%4),t=atob(n),r=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)r[a]=t.codePointAt(a)??0;return r},fr=64,pr=new Map,Ht=async e=>dr(pr,e,async()=>crypto.subtle.importKey("raw",We.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),fr),Lt=async(e,n)=>{const t=await Ht(e),r=await crypto.subtle.sign("HMAC",t,We.encode(n));return lr(new Uint8Array(r))},mr=async(e,n,t)=>{const r=await Ht(e);return crypto.subtle.verify("HMAC",r,t,We.encode(n))},wr=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"];new Set(wr);const gr=new Set(["AE","BH","IL","IQ","IR","JO","KW","LB","OM","PS","QA","SA","SY","TR","YE"]),yr=-100,br=15,_r=e=>{const n=Number(e.longitude??Number.NaN);switch(e.continent){case"AF":return"afr";case"AS":return e.country!==void 0&&gr.has(e.country)?"me":"apac";case"EU":return Number.isFinite(n)&&n>br?"eeur":"weur";case"NA":return Number.isFinite(n)&&n<yr?"wnam":"enam";case"OC":return"oc";case"SA":return"sam";default:return}},st=e=>{const n=e.cf;return n===void 0?void 0:_r(n)},Mt="::relay::",Rr=(e,n)=>`${e}${Mt}${String(n)}`,jt="::replica::",Er=(e,n)=>`${e}${jt}${n}`,Ar=e=>{if(e==null||!/^\d+$/.test(e))return;const n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:void 0},Sr=new Set(["1","enabled","on","true","yes"]),Tr=new Set(["0","disabled","false","no","off"]),Or=(e,n)=>{const t=(e??"").trim().toLowerCase();return Sr.has(t)?!0:Tr.has(t)?!1:n},$t="v1",vr=6e4,kr=async(e,n={})=>{const t=(n.now??Date.now())+(n.ttlMs??vr),r=`${$t}.${String(t)}`,a=await Lt(e,r);return{expiresAtMs:t,token:`${r}.${a}`}},Ir=async(e,n,t=Date.now())=>{if(e.length===0||n.length===0)return!1;const r=n.split(".");if(r.length!==3)return!1;const[a,s,l]=r;if(a!==$t||l.length===0)return!1;const u=Number(s);if(!Number.isFinite(u)||u<=t)return!1;let f;try{f=hr(l)}catch{return!1}return mr(e,`${a}.${s}`,f)},P="/_lunora/admin/auth",Pr={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},N=(e,n)=>{const t=e[n];if(typeof t!="string"||t==="")throw new d(`\`${n}\` is required`,{code:"BAD_REQUEST",status:400});return t},le=(e,n)=>{const t=e(n);if(t===void 0)throw new d(`\`${n}\` query parameter is required`,{code:"BAD_REQUEST",status:400});return t},Kt=e=>{if(typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="string"))return e},re=(e,n)=>typeof e[n]=="string"?e[n]:void 0,xe=(e,n)=>{const t=e[n];return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0},it=e=>{const n=Kt(e.role);if(n===void 0||typeof n=="string"&&n.trim()==="")throw new d("`role` is required",{code:"BAD_REQUEST",status:400});return n},ct=e=>{const n=e.permission;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`permission` object is required",{code:"BAD_REQUEST",status:400});const t={};for(const[r,a]of Object.entries(n))Array.isArray(a)&&a.every(s=>typeof s=="string")&&(t[r]=a);return t},Dr={[`${P}/capabilities`]:{build:()=>({}),http:"GET",method:"capabilities"},[`${P}/users`]:{build:({paging:e,query:n})=>{const t=n("sortDirection");return{...e,filterField:n("filterField"),filterValue:n("filterValue"),search:n("search"),searchField:n("searchField"),sortBy:n("sortBy"),sortDirection:t==="asc"||t==="desc"?t:void 0}},http:"GET",method:"listUsers"},[`${P}/sessions`]:{build:({paging:e,query:n})=>({...e,userId:n("userId")}),http:"GET",method:"listSessions"},[`${P}/accounts`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listAccounts"},[`${P}/passkeys`]:{build:({query:e})=>({userId:le(e,"userId")}),http:"GET",method:"listPasskeys"},[`${P}/organizations`]:{build:({paging:e})=>({...e}),http:"GET",method:"listOrganizations"},[`${P}/organizations/members`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listMembers"},[`${P}/organizations/invitations`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listInvitations"},[`${P}/config`]:{build:()=>({}),http:"GET",method:"config"},[`${P}/organizations/teams`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listTeams"},[`${P}/organizations/teams/members`]:{build:({paging:e,query:n})=>({...e,teamId:le(n,"teamId")}),http:"GET",method:"listTeamMembers"},[`${P}/organizations/roles`]:{build:({paging:e,query:n})=>({...e,organizationId:le(n,"organizationId")}),http:"GET",method:"listOrgRoles"},[`${P}/users/create`]:{build:({body:e})=>({data:xe(e,"data"),email:N(e,"email"),name:N(e,"name"),password:re(e,"password"),role:Kt(e.role)}),http:"POST",method:"createUser"},[`${P}/users/update`]:{build:({body:e})=>{const{data:n}=e;if(typeof n!="object"||n===null||Array.isArray(n))throw new d("`data` object is required",{code:"BAD_REQUEST",status:400});return{data:n,userId:N(e,"userId")}},http:"POST",method:"updateUser"},[`${P}/users/role`]:{build:({body:e})=>({role:it(e),userId:N(e,"userId")}),http:"POST",method:"setRole"},[`${P}/users/ban`]:{build:({body:e})=>({expiresInSeconds:typeof e.expiresInSeconds=="number"?e.expiresInSeconds:void 0,reason:re(e,"reason"),userId:N(e,"userId")}),http:"POST",method:"banUser"},[`${P}/users/unban`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"unbanUser"},[`${P}/users/password`]:{build:({body:e})=>({newPassword:N(e,"newPassword"),userId:N(e,"userId")}),http:"POST",method:"setUserPassword",returns:"void"},[`${P}/users/remove`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"removeUser",returns:"void"},[`${P}/users/impersonate`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"impersonateUser"},[`${P}/sessions/revoke`]:{build:({body:e})=>({sessionId:N(e,"sessionId")}),http:"POST",method:"revokeUserSession",returns:"void"},[`${P}/sessions/revoke-all`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"revokeUserSessions",returns:"void"},[`${P}/accounts/unlink`]:{build:({body:e})=>({accountId:N(e,"accountId"),userId:N(e,"userId")}),http:"POST",method:"unlinkAccount",returns:"void"},[`${P}/two-factor/disable`]:{build:({body:e})=>({userId:N(e,"userId")}),http:"POST",method:"disableTwoFactor",returns:"void"},[`${P}/passkeys/delete`]:{build:({body:e})=>({passkeyId:N(e,"passkeyId")}),http:"POST",method:"deletePasskey",returns:"void"},[`${P}/organizations/members/remove`]:{build:({body:e})=>({memberId:N(e,"memberId")}),http:"POST",method:"removeMember",returns:"void"},[`${P}/organizations/invitations/cancel`]:{build:({body:e})=>({invitationId:N(e,"invitationId")}),http:"POST",method:"cancelInvitation",returns:"void"},[`${P}/organizations/create`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:N(e,"name"),ownerId:re(e,"ownerId"),slug:re(e,"slug")}),http:"POST",method:"createOrganization"},[`${P}/organizations/update`]:{build:({body:e})=>({logo:re(e,"logo"),metadata:xe(e,"metadata"),name:re(e,"name"),organizationId:N(e,"organizationId"),slug:re(e,"slug")}),http:"POST",method:"updateOrganization"},[`${P}/organizations/remove`]:{build:({body:e})=>({organizationId:N(e,"organizationId")}),http:"POST",method:"deleteOrganization",returns:"void"},[`${P}/organizations/members/add`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),role:re(e,"role"),userId:N(e,"userId")}),http:"POST",method:"addMember"},[`${P}/organizations/members/invite`]:{build:({body:e})=>({email:N(e,"email"),inviterId:re(e,"inviterId"),organizationId:N(e,"organizationId"),role:re(e,"role")}),http:"POST",method:"inviteMember"},[`${P}/organizations/members/role`]:{build:({body:e})=>({memberId:N(e,"memberId"),role:it(e)}),http:"POST",method:"updateMemberRole"},[`${P}/organizations/teams/create`]:{build:({body:e})=>({name:N(e,"name"),organizationId:N(e,"organizationId")}),http:"POST",method:"createTeam"},[`${P}/organizations/teams/update`]:{build:({body:e})=>({name:N(e,"name"),teamId:N(e,"teamId")}),http:"POST",method:"updateTeam"},[`${P}/organizations/teams/remove`]:{build:({body:e})=>({teamId:N(e,"teamId")}),http:"POST",method:"removeTeam",returns:"void"},[`${P}/organizations/teams/members/add`]:{build:({body:e})=>({teamId:N(e,"teamId"),userId:N(e,"userId")}),http:"POST",method:"addTeamMember"},[`${P}/organizations/teams/members/remove`]:{build:({body:e})=>({teamMemberId:N(e,"teamMemberId")}),http:"POST",method:"removeTeamMember",returns:"void"},[`${P}/organizations/roles/create`]:{build:({body:e})=>({organizationId:N(e,"organizationId"),permission:ct(e),role:N(e,"role")}),http:"POST",method:"createOrgRole"},[`${P}/organizations/roles/update`]:{build:({body:e})=>({permission:ct(e),roleId:N(e,"roleId")}),http:"POST",method:"updateOrgRole"},[`${P}/organizations/roles/remove`]:{build:({body:e})=>({roleId:N(e,"roleId")}),http:"POST",method:"deleteOrgRole",returns:"void"}},Nr=e=>{const n=async a=>{try{return await a()}catch(s){if(s instanceof d)throw s;const l=s,u=typeof l.code=="string"?l.code:"AUTH_ADMIN_ERROR";throw console.error("[lunora] auth admin operation failed:",s),new d("auth admin operation failed",{code:u,status:Pr[u]??500})}},t=async(a,s)=>{if(e.assertAdmin(a),a.method!==s.http)throw new d(`Auth admin endpoint requires ${s.http}`,{code:"METHOD_NOT_ALLOWED",status:405});const l=e.getAuthAdmin();if(l===void 0)throw new d("auth endpoints require an `authAdmin` on the worker",{code:"AUTH_NOT_CONFIGURED",status:400});const u=l[s.method];if(u===void 0)throw new d(`auth admin does not support \`${s.method}\``,{code:"AUTH_OP_NOT_SUPPORTED",status:400});const f=new URL(a.url),g={body:s.http==="POST"?await e.readJsonBody(a):{},paging:e.parsePaging(a),query:v=>e.queryParameter(f,v)},E=s.build(g),k=await n(()=>u(E));return Response.json(s.returns==="void"?{ok:!0}:k,{headers:{"content-type":"application/json"},status:200})},r={};for(const[a,s]of Object.entries(Dr))r[a]=l=>t(l,s);return r},Ur="__lunora_admin__:getAuthAuditLog",dt=e=>typeof e=="string"&&e!==""?e:void 0,ut=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Cr=e=>async(t,r)=>{e.assertAdmin(t);const a=e.getReader();if(a===void 0)throw new d("the auth/security audit endpoint requires an `authAuditReader` on the worker",{code:"AUTH_AUDIT_NOT_CONFIGURED",status:400});const s=dt(r.actorId),l=dt(r.event),u=ut(r.sinceSeq),f=ut(r.limit),g={...s===void 0?{}:{actorId:s},...l===void 0?{}:{event:l},...u===void 0?{}:{sinceSeq:u},...f===void 0?{}:{limit:f}};let E;try{E=await a.read(g)}catch(v){throw v instanceof d?v:(console.error("[lunora] auth audit read failed:",v),new d("auth audit read failed",{code:"AUTH_AUDIT_READ_FAILED",status:500}))}const k={entries:E};return Response.json({result:Ke(k)},{headers:{"content-type":"application/json"},status:200})},Br=(e,n)=>{const t=[],r=[];if(n&&n.length>0)for(const a of n)e.resolveTableSharding?.(a)?.mode.kind==="global"?r.push(a):t.push(a);return{globalTables:r,shardLocalTables:t}},xr=async(e,n,t,r,a,s)=>{if(t!==void 0&&r.length===0)return;const l=await e.orchestrateExport(s,{args:{tables:r},headers:n,tables:r});for(const u of l.shards)if(!u.error)for(const f of u.rows??[])a(f)},Ft=async(e,n,t,r,a,s)=>{const{globalTables:l,shardLocalTables:u}=Br(e,r);await xr(n,t,r,u,a,s);const f=e.exportGlobals;if((r===void 0||l.length>0)&&f)for await(const E of f({tables:l}))a(E)},Hr=new TextEncoder,Lr=1e3,Gt=10,Mr=200,lt=8,Qt="lunoraBackupCron",ht=24*1048576,ft=e=>{const n=e.slice(0,Gt).map(r=>Bt(r)),t=e.length-n.length;return`${n.join(", ")}${t>0?` (+${String(t)} more)`:""}`},jr=(e,n)=>{const t=new Uint8Array(new ArrayBuffer(n));let r=0;for(const a of e)t.set(a,r),r+=a.byteLength;return t},Ve=async(e,n,t,r)=>{if(t===void 0||!Number.isInteger(t)||t<=0)return{eligible:0,stale:[]};const a=[];let s;for(let l=0;l<Lr;l+=1){const u=await e.list({cursor:s,include:["customMetadata"],prefix:n});for(const f of u.objects)Gn(f.key)&&f.customMetadata?.[Qt]===r&&a.push(f.key);if(!u.truncated||u.cursor===void 0)break;s=u.cursor}return{eligible:a.length,stale:a.toSorted((l,u)=>u.localeCompare(l)).slice(t)}},$r=async(e,n,t,r,a)=>{const{stale:s}=await Ve(e,n,t,r),l=new Set(a),u=s.filter(w=>l.has(w)),f=u.slice(0,Mr),g=s.length-f.length,E=a.length-u.length;if(f.length===0)return{deleted:[],failed:[],ignored:E,remaining:g};const k=[],v=[];for(let w=0;w<f.length;w+=lt){const b=await Promise.allSettled(f.slice(w,w+lt).map(async _=>(await e.delete(Bt(_)),await e.delete(_),_)));for(const[_,p]of b.entries())p.status==="fulfilled"?k.push(p.value):v.push(f[w+_])}return k.length>0&&console.info(`[lunora] backup prune kept the newest ${String(t)} and deleted ${String(k.length)}: ${ft(k)}`),v.length>0&&console.warn(`[lunora] backup prune failed to remove ${String(v.length)}: ${ft(v)}`),{deleted:k,failed:v,ignored:E,remaining:g}},Kr=async e=>{const n=e.backupStore;if(!n)throw new d("backup retention preview requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const t=Ge(e.backupPrefix??Qe),r=e.backupCron,{eligible:a,stale:s}=r===void 0?{eligible:0,stale:[]}:await Ve(n,t,e.backupRetain,r);return{cron:r,eligible:a,keep:e.backupRetain??0,prefix:t,wouldDelete:s}},Fr=async(e,n,t,r)=>{const a=e.backupStore,s=e.queryCoordinator;if(!a)throw new d("scheduled backup requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!s)throw new d("scheduled backup requires a `queryCoordinator` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});if(!t||t.length===0)throw new d("scheduled backup requires an `adminToken` (or `env.LUNORA_ADMIN_TOKEN`) to authenticate the per-shard export gate",{code:"BACKUP_NOT_CONFIGURED",status:500});const l={authorization:`Bearer ${t}`,"content-type":"application/json"},u=e.backupTables;let f=0,g=0,E=[];await Ft(e,s,l,u,D=>{const T=Hr.encode(`${JSON.stringify(D)}
|
|
2
2
|
`);if(f+=1,g+=T.byteLength,g>ht)throw new d(`scheduled backup reached ${String(g)} 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});E.push(T)},n);const v=Ge(e.backupPrefix??Qe),w=new Date(r.scheduledTime).toISOString(),b=Qn(v,w),_=jr(E,g);E=[];const p=Wn(await crypto.subtle.digest("SHA-256",_));await a.put(b,_,{httpMetadata:{contentType:"application/x-ndjson"},sha256:p});const S={bytes:g,createdAt:w,cron:r.cron,file:b,id:w,rows:f,scheduledTime:r.scheduledTime,sha256:p,...u?{tables:u.join(",")}:{}};await a.put(zn(b),`${JSON.stringify(S,void 0,2)}
|
|
3
3
|
`,{customMetadata:{[Qt]:r.cron},httpMetadata:{contentType:"application/json"}});try{const{stale:D}=await Ve(a,v,e.backupRetain,r.cron);if(D.length>0){const T=D.slice(0,Gt),x=D.length-T.length;console.info(`[lunora] backup retention: ${String(D.length)} snapshot(s) past the newest ${String(e.backupRetain)} — run \`lunora backup prune\` to remove them: ${T.join(", ")}${x>0?` (+${String(x)} more)`:""}`)}}catch(D){console.warn(`[lunora] backup ${b} was written, but the retention report failed:`,D)}},Gr=async(e,n)=>{const t=e.backupStore;if(!t)throw new d("backup prune requires a `backupStore` on the worker",{code:"BACKUP_NOT_CONFIGURED",status:500});const r=e.backupCron,a=e.backupRetain;if(r===void 0||a===void 0||!Number.isInteger(a)||a<=0)throw new d("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 $r(t,Ge(e.backupPrefix??Qe),a,r,n)},Qr="/_lunora/admin/backup/retention",zr="/_lunora/admin/backup/prune",Wr=e=>{const{options:n,readJsonBody:t,requireAdminOption:r}=e,a=(u,f)=>{r(u,n.backupStore,{code:"BACKUP_NOT_CONFIGURED",message:`backup ${f} requires a \`backupStore\` on the worker`})},s=async u=>(j(u,"GET","Backup-retention"),a(u,"retention preview"),Response.json(await Kr(n),{headers:{"cache-control":"no-store"}})),l=async u=>{j(u,"POST","Backup-prune"),a(u,"prune");const{confirm:f}=await t(u);if(!Array.isArray(f)||f.some(g=>typeof g!="string"))throw new d("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 Gr(n,f),{headers:{"cache-control":"no-store"}})};return{[zr]:l,[Qr]:s}},pt=500,Vr=(e,n,t)=>{if(typeof e!="object"||e===null||Array.isArray(e))throw new d("each batch call must be an object",{code:"BAD_REQUEST",status:400});const r=e;if(typeof r.functionPath!="string")throw new d("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 d("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 d("each batch call `args` must be an object",{code:"BAD_REQUEST",status:400});return{entry:{args:r.args===void 0?{}:r.args,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:n,mutationId:typeof r.mutationId=="string"?r.mutationId:void 0},shardKey:typeof r.shardKey=="string"?r.shardKey:t}},Jr=(e,n)=>{if(e.length>pt)throw new d(`RPC batch exceeds the ${String(pt)}-call limit`,{code:"BAD_REQUEST",status:400});const t=new Map;for(const[r,a]of e.entries()){const{entry:s,shardKey:l}=Vr(a,r,n),u=t.get(l)??[];u.push(s),t.set(l,u)}return t},qr=new TextEncoder,Yr=e=>{const n=JSON.stringify(e),t=qr.encode(n);let r="";for(const a of t)r+=String.fromCodePoint(a);return btoa(r).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")},Xr=e=>{const n={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return n;try{const t=atob(e.replaceAll("-","+").replaceAll("_","/")),r=new Uint8Array(t.length);for(let u=0;u<t.length;u+=1)r[u]=t.codePointAt(u)??0;const a=JSON.parse(new TextDecoder().decode(r)),s=a.s&&typeof a.s=="object"?a.s:{},l={};for(const[u,f]of Object.entries(s))typeof f=="number"&&Number.isFinite(f)&&(l[u]=f);return{g:typeof a.g=="number"&&Number.isFinite(a.g)?a.g:0,s:l,v:1}}catch{return n}},Zr=e=>{const n=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",r=t==="delete"||t==="insert"||t==="update"?t:"upsert",a=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(a===void 0?{}:{_id:a}),op:r,table:n}},mt=(e,n,t)=>{for(const r of n)e.push(Zr(r));return t!==void 0&&n.length>=t},eo="/_lunora/admin/export",to="/_lunora/admin/import",no="/_lunora/admin/sync",ro="/_lunora/admin/connector/sync",oo="/_lunora/admin/apply",ao="/_lunora/admin/export-tap/run",so=new TextEncoder,io=async e=>{const t=await be(e,"Export")??{};if(t.tables===void 0)return{tables:void 0};if(!Array.isArray(t.tables))throw new d("Export `tables` must be a string array",{code:"BAD_REQUEST",status:400});const r=[];for(const a of t.tables){if(typeof a!="string"||a.length===0)throw new d("Export `tables` entries must be non-empty strings",{code:"BAD_REQUEST",status:400});r.push(a)}return{tables:r}},He=e=>Array.isArray(e)?e.filter(n=>typeof n=="string"):void 0,co=e=>{const{applyGlobals:n,exportCursorStore:t,exportSinks:r,knownTables:a,queryCoordinator:s,assertAdmin:l,requireAdminOption:u,resolveForwardContext:f,shardDO:g,streamExportRows:E,streamingImport:k,syncGlobals:v}=e,w=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export endpoint requires a `queryCoordinator` on the worker"}),U=await io(T),{headers:W}=await f(T,x),K=new ReadableStream({async pull(V){const X=J=>{V.enqueue(so.encode(`${JSON.stringify(J)}
|
|
4
4
|
`))};try{await E($,W,U.tables,X),V.close()}catch(J){V.error(J)}}});return new Response(K,{headers:{"content-type":"application/x-ndjson"},status:200})},b=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=typeof U.cursors=="object"&&U.cursors!==null?U.cursors:{},K=typeof U.limit=="number"?U.limit:void 0,V=typeof U.globalCursor=="number"?U.globalCursor:0,X=He(U.tables),{headers:J}=await f(T,x),ae=X??a(),F=await $.orchestrateCdcSync(g,{cursors:W,headers:J,limit:K,tables:ae}),he=v?await v({limit:K,sinceSeq:V}):void 0;return Response.json({global:he,shards:F.shards},{status:200})},_=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Connector sync endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),W=Xr(U.cursor),K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables),{headers:X}=await f(T,x),J=V??a(),ae=await $.orchestrateCdcSync(g,{cursors:W.s,headers:X,limit:K,tables:J}),F=[],he={...W.s};let G=!1;for(const se of ae.shards)G=mt(F,se.changes??[],K)||G,he[se.shardKey]=se.cursor;let oe=W.g;if(v){const se=await v({limit:K,sinceSeq:W.g});G=mt(F,se.changes,K)||G,oe=se.cursor}const Te=Yr({g:oe,s:he,v:1}),Oe={changes:F,hasMore:G,nextCursor:Te};return Response.json(Oe,{status:200})},p=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Apply endpoint requires a `queryCoordinator` on the worker"}),U=await Z(T),K=(Array.isArray(U.batches)?U.batches:[]).map(F=>F).filter(F=>F!==null&&typeof F=="object"&&typeof F.shardKey=="string"&&Array.isArray(F.changes)),V=Array.isArray(U.globalChanges)?U.globalChanges:[],{headers:X}=await f(T,x),J=await $.orchestrateApplyCdc(g,{batches:K,headers:X}),ae=V.length>0&&n?await n({changes:V}):0;return Response.json({applied:J.applied+ae,failed:J.failed,ok:J.ok},{status:200})},S=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;l(T);const{headers:$}=await f(T,x),U=await k(T,$);return Response.json(U,{headers:{"content-type":"application/json"},status:200})},D=async(T,x)=>{const H=me(T,["POST"]);if(H)return H;const $=u(T,s,{code:"BAD_REQUEST",message:"Export-tap endpoint requires a `queryCoordinator` on the worker"});if(r===void 0||Object.keys(r).length===0||t===void 0)throw new d("Export-tap endpoint requires `exportSinks` + `exportCursorStore` on the worker",{code:"EXPORT_TAP_NOT_CONFIGURED",status:400});const U=await Z(T),W=typeof U.sink=="string"?U.sink:void 0,K=typeof U.limit=="number"&&U.limit>0?U.limit:void 0,V=He(U.tables);if(W===void 0)throw new d("Export-tap `sink` must name a configured sink",{code:"BAD_REQUEST",status:400});const X=r[W];if(X===void 0)throw new d(`Export-tap sink "${W}" is not configured`,{code:"NOT_FOUND",status:404});const{headers:J}=await f(T,x),ae=V??a(),F=await Yn({coordinator:$,cursorStore:t,headers:J,limit:K,shardDO:g,sink:X,tables:ae});return Response.json(F,{headers:{"content-type":"application/json"},status:200})};return{[oo]:p,[ro]:_,[eo]:w,[ao]:D,[to]:S,[no]:b}},uo=(e,n)=>{let t;try{t=JSON.parse(e)}catch{return{error:{code:"BAD_ROW",line:n,message:"line is not valid JSON",table:""},ok:!1}}if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:n,message:"row must be a JSON object",table:""},ok:!1};const r=t;return typeof r.table!="string"||r.table.length===0?{error:{code:"BAD_ROW",line:n,message:"row is missing `table`",table:""},ok:!1}:!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)?{error:{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:r.table},ok:!1}:{doc:r.doc,ok:!0,table:r.table}},lo=(e,n,t,r,a)=>{if(t?.mode.kind==="shardBy"&&typeof t.mode.field=="string"){const s=e[t.mode.field];return s==null?{error:{code:"BAD_ROW",line:a,message:`row missing shard field "${t.mode.field}" for table "${n}"`,table:n},ok:!1}:{ok:!0,shardKey:typeof s=="string"?s:JSON.stringify(s)}}return{ok:!0,shardKey:r}},ho=async(e,n,t)=>{if(!e.body)throw new d("Import endpoint requires a request body",{code:"BAD_REQUEST",status:400});const r=[],a=[],s=new Map;let l=0,u=0;const f=e.body.getReader(),g=new TextDecoder;let E="",k=0;const v=w=>{u+=1;const b=w.trim();if(b.length===0)return;l+=1;const _=uo(b,u);if(!_.ok){r.push(_.error);return}const{doc:p,table:S}=_,D=n.resolveTableSharding?.(S);if(D?.mode.kind==="global"){a.push({doc:p,line:u,table:S});return}const T=lo(p,S,D,t,u);if(!T.ok){r.push(T.error);return}const x=s.get(T.shardKey);x?x.rows.push({doc:p,table:S}):s.set(T.shardKey,{rows:[{doc:p,table:S}],shardKey:T.shardKey,startLine:u})};for(;;){const{done:w,value:b}=await f.read();if(w)break;if(b&&(k+=b.byteLength,k>Nt))throw await f.cancel().catch(()=>{}),new d("Body too large",{code:"PAYLOAD_TOO_LARGE",status:413});E+=g.decode(b,{stream:!0});let _=E.indexOf(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const R={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},A=e=>`${String(Math.round(e))}000000`,_=Array.from({length:256},(e,r)=>r.toString(16).padStart(2,"0")),l=512,m=new Uint8Array(l);let a=l;const v=(e,r,t)=>{let o="";for(let n=0;n<t;n+=1)o+=_[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(m),a=0);const r=v(m,a,e);return a+=e,r},u=/^[0-9a-f]+$/,b=(e,r,t=!0)=>`00-${e}-${r}-${t?"01":"00"}`,N=e=>{if(e==null)return;const r=e.trim().toLowerCase().split("-"),[t,o,n,s]=r;if(!(r.length<4||t===void 0||t.length!==2||!u.test(t)||t==="ff"||t==="00"&&r.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!u.test(s)||o.length!==32||n.length!==16||!u.test(o)||!u.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},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}},T=e=>e===void 0?[]:Object.entries(e).map(([r,t])=>O(r,t)),L=(e,r,t)=>{const o={},n=new Map,s=(c,i)=>{const p=c.toLowerCase(),g=n.get(p);g===void 0?(n.set(p,c),o[c]=i):o[g]=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},d=e=>Array.isArray(e)?e:[e],h={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",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),f=(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(o,n))},I=(e,r,t,o)=>({resourceSpans:[{resource:{attributes:f(t,o)},scopeSpans:[{scope:{name:r},spans:d(e)}]}]}),V=(e,r,t,o)=>({resourceLogs:[{resource:{attributes:f(t,o)},scopeLogs:[{logRecords:d(e),scope:{name:r}}]}]}),M=(e,r,t,o)=>({resourceMetrics:[{resource:{attributes:f(t,o)},scopeMetrics:[{metrics:d(e),scope:{name:r}}]}]}),y=e=>r=>{const t=e?.[r];return typeof t=="string"&&t.length>0?t:void 0},E=(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=>{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=E(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,h as O,w as a,b,A as c,x as d,O as e,R as f,T as g,L as h,M as i,V as j,H as m,S as o,N as p,y as r,I as w};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const v={debug:5,error:17,fatal:21,info:9,log:9,trace:1,warn:13},m=e=>`${String(Math.round(e))}000000`,O=e=>{const t=new Uint8Array(e);crypto.getRandomValues(t);let r="";for(const o of t)r+=o.toString(16).padStart(2,"0");return r},a=/^[0-9a-f]+$/,b=(e,t,r=!0)=>`00-${e}-${t}-${r?"01":"00"}`,_=e=>{if(e==null)return;const t=e.trim().toLowerCase().split("-"),[r,o,n,s]=t;if(!(t.length<4||r===void 0||r.length!==2||!a.test(r)||r==="ff"||r==="00"&&t.length!==4||o===void 0||n===void 0||s===void 0||s.length!==2||!a.test(s)||o.length!==32||n.length!==16||!a.test(o)||!a.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(s,16)&1)===1,traceId:o}},p=(e,t)=>typeof t=="boolean"?{key:e,value:{boolValue:t}}:typeof t=="number"?Number.isFinite(t)?Number.isSafeInteger(t)?{key:e,value:{intValue:String(t)}}:{key:e,value:{doubleValue:t}}:{key:e,value:{stringValue:String(t)}}:{key:e,value:{stringValue:t}},R=e=>e===void 0?[]:Object.entries(e).map(([t,r])=>p(t,r)),E=(e,t,r)=>{const o={},n=new Map,s=(c,i)=>{const d=c.toLowerCase(),f=n.get(d);f===void 0?(n.set(d,c),o[c]=i):o[f]=i};for(const[c,i]of Object.entries(e))s(c,i);for(const[c,i]of Object.entries(t??{}))s(c,i);return r!==void 0&&r.length>0&&s("authorization",`Bearer ${r}`),o},u=e=>Array.isArray(e)?e:[e],A={client:3,consumer:5,internal:1,producer:4,server:2},N=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),l=(e,t)=>{const r={"service.name":e};for(const[o,n]of Object.entries(t??{}))r[o]=n;return Object.entries(r).map(([o,n])=>p(o,n))},S=(e,t,r,o)=>({resourceSpans:[{resource:{attributes:l(r,o)},scopeSpans:[{scope:{name:t},spans:u(e)}]}]}),C=(e,t,r,o)=>({resourceLogs:[{resource:{attributes:l(r,o)},scopeLogs:[{logRecords:u(e),scope:{name:t}}]}]}),L=(e,t,r,o)=>({resourceMetrics:[{resource:{attributes:l(r,o)},scopeMetrics:[{metrics:u(e),scope:{name:t}}]}]}),T=e=>t=>{const r=e?.[t];return typeof r=="string"&&r.length>0?r:void 0},g=(e,t)=>{if(typeof e!="object"||e===null)return;const r=e[t];return typeof r=="string"&&r.length>0?r:void 0},I=e=>{const t={},r=e("SERVICE_VERSION")??e("CF_VERSION_METADATA")??e("VERCEL_GIT_COMMIT_SHA")??e("GITHUB_SHA")??e("COMMIT_SHA");r!==void 0&&(t["service.version"]=r);const o=e("DEPLOYMENT_ENVIRONMENT")??e("ENVIRONMENT")??e("NODE_ENV");return o!==void 0&&(t["deployment.environment"]=o),t},y=(e,t)=>{if(!(t!==void 0||e("CLOUDFLARE")!==void 0||e("CF_ACCOUNT_ID")!==void 0))return{};const o={"cloud.provider":"cloudflare"},n=g(t,"colo")??e("CF_COLO")??e("CLOUDFLARE_COLO");return n!==void 0&&(o["cloud.region"]=n),o},h=(...e)=>{const t={};for(const r of e)if(r!==void 0)for(const[o,n]of Object.entries(r))t[o]=n;return t};export{N as L,A as O,I as a,b,m as c,y as d,p as e,v as f,R as g,E as h,L as i,C as j,h as m,O as o,_ as p,T as r,S as w};
|