@lunora/runtime 1.0.0-alpha.29 → 1.0.0-alpha.290
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +201 -104
- package/README.md +55 -13
- package/dist/index.d.mts +3749 -618
- package/dist/index.d.ts +3749 -618
- package/dist/index.mjs +1 -16
- package/dist/packem_shared/BACKUP_KEY_PREFIX-BOtSu-_3.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LOG_COLUMNS-gYMhXLzO.mjs +1 -0
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-w_RLPiwj.mjs +2 -0
- package/dist/packem_shared/HEALTH_PATH-B8ndDG3s.mjs +1 -0
- package/dist/packem_shared/LOG_ARCHIVE_NOT_CONFIGURED-CDpi4yFD.mjs +1 -0
- package/dist/packem_shared/LOG_ARCHIVE_PATH-dTuCzfyj.mjs +1 -0
- package/dist/packem_shared/LunoraError-PkZWF-_g.mjs +1 -0
- package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-YmXqH-jH.mjs +1 -0
- package/dist/packem_shared/STORAGE_UPLOAD_MAX_BODY_BYTES-Onz8HkiB.mjs +1 -0
- package/dist/packem_shared/analyticsEngineSink-CPMYRnjL.mjs +1 -0
- package/dist/packem_shared/applyJurisdiction-DKQE8kOA.mjs +1 -0
- package/dist/packem_shared/applyRestCache-DWFguIzs.mjs +1 -0
- package/dist/packem_shared/argsFromQuery-CcvrU4tb.mjs +1 -0
- package/dist/packem_shared/base64-Bl1_r2k1.mjs +1 -0
- package/dist/packem_shared/composeIdentityResolvers-CpdHuDyk.mjs +1 -0
- package/dist/packem_shared/composeWorker-Bhpq03F6.mjs +40 -0
- package/dist/packem_shared/createCrossShardRelationCapabilities-Bm04PAy7.mjs +1 -0
- package/dist/packem_shared/createKvCursorStore-Bkn5pilz.mjs +1 -0
- package/dist/packem_shared/createQueryCoordinator-CaQF9cds.mjs +1 -0
- package/dist/packem_shared/createShardClient-Dar1gB9v.mjs +1 -0
- package/dist/packem_shared/declareAppJurisdiction-DEba2p42.mjs +1 -0
- package/dist/packem_shared/decorateResponse-BJmIUgEV.mjs +1 -0
- package/dist/packem_shared/emitLogEvent-CdybnWG8.mjs +1 -0
- package/dist/packem_shared/enrichSink-8_qnPWNH.mjs +1 -0
- package/dist/packem_shared/error-detail-C46mdOTW.mjs +1 -0
- package/dist/packem_shared/export-tap-C2B_SATf.mjs +3 -0
- package/dist/packem_shared/identity-header-CG1FNe-S.mjs +1 -0
- package/dist/packem_shared/loadStudioDocument-W6CieK4y.mjs +1 -0
- package/dist/packem_shared/memoize-identity-DzVUB2rt.mjs +1 -0
- package/dist/packem_shared/memoizeIdentity-CUl7PPpt.mjs +1 -0
- package/dist/packem_shared/method-guard-8Jo4Q8uS.mjs +1 -0
- package/dist/packem_shared/observability-9slk__Gi.mjs +1 -0
- package/dist/packem_shared/observability-sinks-BA76CH4h.mjs +6 -0
- package/dist/packem_shared/origin-paywall-B6eOO67m.mjs +1 -0
- package/dist/packem_shared/otlp-resource-BBR8xs6m.mjs +1 -0
- package/dist/packem_shared/parseStackFrames-CZddjveh.mjs +2 -0
- package/dist/packem_shared/pipeline-log-reader-C-nuWG_e.mjs +1 -0
- package/dist/packem_shared/portable-json-CSq6T1AU.mjs +1 -0
- package/dist/packem_shared/rest-cache-q5V06Etw.mjs +1 -0
- package/dist/packem_shared/rest-routes-D5NWHmVl.mjs +1 -0
- package/dist/packem_shared/security-headers-0DqdJ04h.mjs +1 -0
- package/dist/packem_shared/toAirbyteMessages-DY0vsuEn.mjs +1 -0
- package/dist/packem_shared/worker-version-B-qCFtEJ.mjs +1 -0
- package/package.json +11 -3
- package/dist/packem_shared/DEFAULT_REGISTRY_CACHE_TTL_MS-B3pA7aXp.mjs +0 -79
- package/dist/packem_shared/LunoraError-Bpb9EFJ3.mjs +0 -22
- package/dist/packem_shared/NOOP_EXECUTION_CONTEXT-CCTu0Bf1.mjs +0 -8
- package/dist/packem_shared/analyticsEngineSink-DKZvbDFG.mjs +0 -284
- package/dist/packem_shared/applyJurisdiction-BkZtTkct.mjs +0 -20
- package/dist/packem_shared/composeIdentityResolvers-XGjO7V1J.mjs +0 -55
- package/dist/packem_shared/composeWorker-Br4_GgSW.mjs +0 -3350
- package/dist/packem_shared/createCrossShardRelationCapabilities-CbcWjkAn.mjs +0 -63
- package/dist/packem_shared/createQueryCoordinator-DNCJzOZE.mjs +0 -847
- package/dist/packem_shared/decorateResponse-DRWQFNhF.mjs +0 -273
- package/dist/packem_shared/emitLogEvent-pEdtqAK8.mjs +0 -20
- package/dist/packem_shared/otlp-0FQT3AI8.mjs +0 -85
- package/dist/packem_shared/toAirbyteMessages-DrHdplb4.mjs +0 -39
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{encodeWire as w,decodeWire as f}from"@lunora/wire";import{e as S,c as I}from"./identity-header-CG1FNe-S.mjs";import{O as p,a as g}from"./origin-paywall-B6eOO67m.mjs";import{applyJurisdiction as N,resolveShard as L}from"./applyJurisdiction-DKQE8kOA.mjs";const A=e=>{if(typeof e=="string")return e;const t=e?.__lunoraRef;if(typeof t!="string"||t.length===0)throw new n("INTERNAL","createShardClient: expected a generated function reference (api.*/internal.*) or a 'namespace:fn' string");return t},E=e=>{const t=new n(e.code,e.message);return e.data!==void 0&&(t.data=f(e.data)),typeof e.why=="string"&&(t.why=e.why),t},x=(e,t={})=>{const l=N(e,t.jurisdiction),y=t.system??!0,c=r=>x(e,{...t,...r});return{as:r=>c({as:r}),asSystem:()=>c({as:void 0}),call:async(r,m,o)=>{const i=A(r),h=o?.shardKey??t.shardKey;if(h===void 0||h.length===0)throw new n("INTERNAL",`createShardClient: no shard key for "${i}" — pass one to createShardClient({ shardKey }), .forShard(key), or the call's options`);const a={"content-type":"application/json"};y&&(a[g]=p,a["x-lunora-system"]="1"),t.as&&(a["x-lunora-userid"]=S(t.as.userId),t.as.claims&&(a["x-lunora-identity"]=I(t.as.claims))),o?.mutationId!==void 0&&o.mutationId.length>0&&(a["x-lunora-mutation-id"]=o.mutationId);const s=await L(l,h).fetch(new Request("https://shard.internal/rpc",{body:JSON.stringify({args:w(m??{}),functionPath:i}),headers:a,method:"POST"})),u=s.statusText?` ${s.statusText}`:"";let d;try{d=await s.json()}catch{throw new n("INTERNAL",`createShardClient: shard response for "${i}" was not JSON (status ${String(s.status)}${u})`)}if("error"in d)throw E(d.error);if(!s.ok)throw new n("INTERNAL",`createShardClient: shard call "${i}" failed (status ${String(s.status)}${u})`);return f(d.result)},forShard:r=>c({shardKey:r})}};export{x as createShardClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=Symbol.for("lunora:app-jurisdiction"),r=globalThis,i=t=>{const e=r[o];if(e!==void 0&&e!==t)throw new TypeError(`lunora: the app jurisdiction is already "${e}"; refusing to redeclare it as "${t}".`);r[o]=t},s=()=>r[o],n=()=>{delete r[o]};export{i as declareAppJurisdiction,s as getAppJurisdiction,n as resetAppJurisdiction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as s,e as a,a as i,h as n,r as t}from"./security-headers-0DqdJ04h.mjs";import"./LunoraError-PkZWF-_g.mjs";export{s as decorateResponse,a as enforceOrigin,i as enforceWebSocketOrigin,n as handleCorsPreflight,t as resolveSecurity};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./error-detail-C46mdOTW.mjs";import{e as i,a as m,f as o}from"./observability-9slk__Gi.mjs";export{i as emitLogEvent,m as emitRpcEvent,o as flushSink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{redactArgs as b,redactCredentials as y}from"@lunora/observability";import{S as O,n as S,t as x,e as E}from"./observability-sinks-BA76CH4h.mjs";const d=t=>{try{t()}catch{}},m=(t,o)=>{const r={};for(const n of O)t[n]!==void 0&&(r[n]=t[n]);return t.flush&&(r.flush=n=>{d(()=>t.flush?.(n))}),t.onLog&&(r.onLog=(n,c)=>{const e=o.log===void 0?n:o.log(n);e!==void 0&&d(()=>t.onLog?.(e,c))}),t.onMetric&&(r.onMetric=(n,c)=>{const e=o.metric===void 0?n:o.metric(n);e!==void 0&&d(()=>t.onMetric?.(e,c))}),t.onRpc&&(r.onRpc=(n,c)=>{const e=o.rpc===void 0?n:o.rpc(n);e!==void 0&&d(()=>t.onRpc?.(e,c))}),t.onSpan&&(r.onSpan=(n,c)=>{const e=o.span===void 0?n:o.span(n);e!==void 0&&d(()=>t.onSpan?.(e,c))}),r},g=5;let l=0;const j=t=>{if(l>=g)return;l+=1;const o=l===g?" 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.${o}`,t instanceof Error?t.name:typeof t)}catch{}},R=(t,o,r)=>{if(t instanceof Error)return r==="full"?x(t,o):E(t);const n=Reflect.get(t,"toJSON");if(typeof n=="function"){const e=n.call(t);return e!==t?o(e):Object.fromEntries(Object.entries(t).map(([i,s])=>[i,o(s)]))}if(Array.isArray(t))return t.map(e=>o(e));const c=Object.getPrototypeOf(t);return c!==Object.prototype&&c!==null?t:Object.fromEntries(Object.entries(t).map(([e,i])=>[e,o(i)]))},u=t=>({ancestors:new WeakSet,copies:new WeakMap,errors:t}),a=(t,o)=>{if(typeof t=="symbol"||typeof t=="function"||typeof t=="bigint")return String(t);if(typeof t!="object"||t===null)return t;if(!o.ancestors.has(t)){if(o.copies.has(t))return o.copies.get(t);o.ancestors.add(t);try{const r=R(t,n=>a(n,o),o.errors);return o.copies.set(t,r),r}finally{o.ancestors.delete(t)}}},p=(t,o,r)=>{try{const n=t(a(o,u("full")),r),c=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([,f])=>f!==void 0)),e=r==="log"?"full":"headline",i=c===void 0?void 0:a(c,u(e)),s=r==="log"?b(i):y(i);return S(s,void 0,e)}catch(n){j(n);return}},M=(t,o)=>m(t,{log:r=>{const n=p(o,r,"log");return n===void 0?r:{...r,fields:{...n,...r.fields}}},metric:r=>{const n=p(o,r,"metric");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}},rpc:r=>{const n=p(o,r,"rpc");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}},span:r=>{const n=p(o,r,"span");return n===void 0?r:{...r,attributes:{...n,...r.attributes}}}}),h=(t,o)=>{const r=t.split("*");if(r.length===1)return o===t;const n=r[0]??"",c=r.at(-1)??"";if(o.length<n.length+c.length||!o.startsWith(n)||!o.endsWith(c))return!1;const e=o.length-c.length;let i=n.length;for(const s of r.slice(1,-1)){const f=o.indexOf(s,i);if(f===-1||f+s.length>e)return!1;i=f+s.length}return i<=e},F=(t,o)=>o.exclude?.some(r=>h(r,t))?!1:o.include===void 0||o.include.length===0||o.include.some(r=>h(r,t)),I=(t,o)=>{const r=n=>F(n.functionPath,o)?n:void 0;return m(t,{log:r,metric:r,rpc:r,span:r})};export{M as enrichSink,I as filterSink,h as globMatch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a="x-lunora-want-error-detail",c="x-lunora-error-detail";const d=t=>{if(!(t instanceof Error))return{message:String(t),name:typeof t};const{code:n}=t;return{...typeof n=="string"?{code:n}:{},message:t.message,name:t.name,...t.stack===void 0?{}:{stack:t.stack.slice(0,8192)}}},s=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);const i=(t,n)=>n instanceof Error?{...n,message:n.message,name:n.name}:n,E=(t,{capped:n=!0}={})=>{if(t instanceof Error)try{const{internal:e}=t;if(!s(e))return;const r=JSON.stringify(e,i);if(n&&r.length>16384)return;const o=JSON.parse(r);return s(o)?o:void 0}catch{return}},f=t=>{try{const n=JSON.parse(JSON.stringify(t,i));return s(n)?n:void 0}catch{return}},p=t=>{if(t!=null)try{const n=JSON.parse(decodeURIComponent(t));if(typeof n?.message!="string"||typeof n.name!="string")return;const{internal:e,...r}=n;return s(e)?{...r,internal:e}:r}catch{return}};export{c as E,a as W,d as a,E as b,p as d,f as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{f as K,t as j}from"./base64-Bl1_r2k1.mjs";import{t as O}from"./portable-json-CSq6T1AU.mjs";const N=new TextEncoder,q=e=>j(N.encode(JSON.stringify(e))),B=e=>{const r={g:0,s:{},v:1};if(typeof e!="string"||e.length===0)return r;try{const t=JSON.parse(new TextDecoder().decode(K(e))),o=t.s&&typeof t.s=="object"?t.s:{},s={};for(const[i,n]of Object.entries(o))typeof n=="number"&&Number.isFinite(n)&&(s[i]=n);return{g:typeof t.g=="number"&&Number.isFinite(t.g)?t.g:0,s,v:1}}catch{return r}},P=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0;return{doc:(e.doc&&typeof e.doc=="object"?e.doc:void 0)??(s===void 0?{}:{_id:s}),op:o,table:r}},M=e=>Math.max(1,Math.min(e??1e3,1e4)),D=(e,r,t)=>{for(const o of r)e.push(P(o));return t!==void 0&&r.length>=t},R=e=>new Promise(r=>{setTimeout(r,e)}),$=e=>{const r=typeof e.table=="string"?e.table:"",t=typeof e.op=="string"?e.op:"",o=t==="delete"||t==="insert"||t==="update"?t:"upsert",s=typeof e.id=="string"?e.id:void 0,i=e.doc&&typeof e.doc=="object"?O(e.doc):void 0,n=typeof e.seq=="number"&&Number.isFinite(e.seq)?e.seq:void 0,c=typeof e.ts=="number"&&Number.isFinite(e.ts)?e.ts:void 0;return{op:o,table:r,...i===void 0?{}:{doc:i},...s===void 0?{}:{id:s},...n===void 0?{}:{seq:n},...c===void 0?{}:{ts:c}}},T=async(e,r,t,o,s,i)=>{let n=0;for(;;)try{await e.deliver(r);return}catch(c){if(n>=t)throw c instanceof Error?c:new Error(String(c));const d=Math.min(o*2**n,s);await i(d),n+=1}},I=async e=>{const{coordinator:r,cursorStore:t,defaultShardKey:o,headers:s,initialBackoffMs:i=100,limit:n,maxBackoffMs:c=5e3,maxRetries:d=3,shardDO:S,sink:p,sleep:k=R,tables:C}=e,h=await t.read(p.name),b=await r.orchestrateCdcSync(S,{cursors:h,defaultShardKey:o,headers:s,limit:n,tables:C}),l={...h},m=[];let v=0,f=!1;for(const a of b.shards){if(a.error){m.push({error:a.error.message,shardKey:a.shardKey}),f=!0;continue}const y=a.changes??[];if(y.length===0){l[a.shardKey]=a.cursor;continue}const g=y.map(u=>$(u)),E={changes:g,cursor:a.cursor,shardKey:a.shardKey,sink:p.name};try{await T(p,E,d,i,c,k),l[a.shardKey]=a.cursor,v+=g.length,y.length>=M(n)&&(f=!0)}catch(u){m.push({error:u instanceof Error?u.message:String(u),shardKey:a.shardKey}),f=!0}}return await t.write(p.name,l),{cursors:l,delivered:v,failures:m,hasMore:f,shards:b.shards.length}},x=e=>{if(typeof e.name!="string"||e.name.length===0)throw new Error("defineExportSink: `name` must be a non-empty string");if(typeof e.deliver!="function")throw new TypeError("defineExportSink: `deliver` must be a function");return{deliver:e.deliver,name:e.name}},w=e=>`${e.map(r=>JSON.stringify(r)).join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,J=e=>{const r=e.fetchImpl??((t,o)=>fetch(t,o));return x({deliver:async t=>{const o=await r(e.url,{body:w(t.changes),headers:{"content-type":"application/x-ndjson","x-lunora-cursor":String(t.cursor),"x-lunora-shard":t.shardKey,"x-lunora-sink":t.sink,...e.headers},method:"POST"});if(!o.ok)throw new Error(`webhook export sink "${e.name}" returned ${String(o.status)}`)},name:e.name})},U=e=>{let r=e.prefix??"cdc";for(;r.endsWith("/");)r=r.slice(0,-1);return x({deliver:async t=>{const o=`${r}/${t.shardKey}/${String(t.cursor)}.ndjson`;await e.bucket.put(o,w(t.changes),{httpMetadata:{contentType:"application/x-ndjson"}})},name:e.name})},z=()=>{const e={};return{read:r=>Promise.resolve({...e[r]}),snapshot:()=>structuredClone(e),write:(r,t)=>(e[r]={...t},Promise.resolve())}},W=(e,r)=>{const t=r?.keyPrefix??"__lunora_source_cursor:export",o=s=>`${t}:${s}`;return{read:async s=>{const i=await e.get(o(s),"json");if(i===null||typeof i!="object")return{};const n={};for(const[c,d]of Object.entries(i))typeof d=="number"&&Number.isFinite(d)&&(n[c]=d);return n},write:async(s,i)=>{await e.put(o(s),JSON.stringify(i))}}};export{z as a,I as b,W as c,x as d,B as e,D as f,q as g,M as h,U as r,$ as s,J as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as o,f as c}from"./base64-Bl1_r2k1.mjs";const s=new TextDecoder,d=new TextEncoder,r="=",i=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},a=e=>o(d.encode(e)),E=e=>a(JSON.stringify(e)),f=e=>{if(e)try{const t=e[0]==="{"?e:s.decode(c(e)),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}},y=e=>!e.startsWith(r)&&i(e)?e:`${r}${o(d.encode(e))}`,l=e=>{if(e){if(!e.startsWith(r))return e;try{return s.decode(c(e.slice(r.length)))}catch{return}}},p=e=>typeof e=="number"&&Date.now()>=e,x="x-lunora-expect-subject",b=e=>{const t=f(e)?.subject;return t===null||typeof t=="string"?{subject:t}:void 0};export{x as E,l as a,b,E as c,f as d,y as e,a as f,p as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n="https://lunora-studio.invalid",s=t=>typeof t=="object"&&t!==null&&typeof t.fetch=="function",c=async(t,e)=>{if(!s(t))return;const o=await t.fetch(new Request(`${n}/_lunora/studio/${e}.json`));if(!o.ok||!(o.headers.get("content-type")??"").includes("application/json")){await o.body?.cancel();return}return o.json()};export{c as loadStudioDocument};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as p}from"./identity-header-CG1FNe-S.mjs";const h=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)},_=n=>{const e=new WeakMap;return(t,r,l)=>{const o=e.get(t);if(o)return o;const i=Promise.resolve(n(t,r,l));return e.set(t,i),i}},I=5e3,g=500,x=32,T=n=>{const e=n.headers.get("cookie")??"",t=n.headers.get("authorization")??"";if(!(e===""&&t===""))return`${t}\0${e}`},R=n=>{if(!n)return;const{exp:e,expiresAtMs:t}=n;return typeof t=="number"&&Number.isFinite(t)?t:typeof e=="number"&&Number.isFinite(e)?e*1e3:void 0},N=(n,e={})=>{const t=e.ttlMs??I,r=Math.max(1,e.maxEntries??g),l=e.cacheKey??T,o=_(n);if(t<=0)return o;const i=new Map;return(E,M,y)=>{const s=l(E);if(s===void 0||y?.access!==void 0)return o(E,M,y);const m=Date.now(),a=i.get(s);if(a&&a.expiresAt>m)return a.value;if(a&&i.delete(s),i.size>=r){let c=0;for(const[d,A]of i){if(c>=x)break;c+=1,A.expiresAt<=m&&i.delete(d)}}const u=Promise.resolve(o(E,M,y)),f={expiresAt:m+t,value:u};return u.then(c=>{if(c===null){i.get(s)===f&&i.delete(s);return}const d=R(c);d!==void 0&&d<f.expiresAt&&(f.expiresAt=d)}).catch(()=>{i.get(s)?.value===u&&i.delete(s)}),i.delete(s),h(i,r),i.set(s,f),u}},v=new Map,k=256,z=2048,b=n=>{const e=JSON.stringify(n);if(e.length>z)return p(e);const t=v.get(e);if(t!==void 0)return t;const r=p(e);return h(v,k),v.set(e,r),r};export{_ as a,b,h as e,N as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as i,a as o,b as a}from"./memoize-identity-DzVUB2rt.mjs";import"./identity-header-CG1FNe-S.mjs";export{i as memoizeIdentity,o as memoizeIdentityPerRequest,a as memoizedIdentityHeader};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as t}from"./LunoraError-PkZWF-_g.mjs";const n=(e,o)=>o.includes(e.method)?void 0:new Response(void 0,{headers:{allow:o.join(", ")},status:405}),a=(e,o,s)=>{if(e.method!==o)throw new t(`${s} endpoint requires ${o}`,{code:"METHOD_NOT_ALLOWED",status:405})};export{a,n as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{redactCredentials as s}from"@lunora/observability";import{t as i}from"./error-detail-C46mdOTW.mjs";const h="x-lunora-sample-errors",o=1,u=r=>{const t=Number.parseInt(r.slice(-8),16);return Number.isFinite(t)?t/4294967296:0},d=(r,t=o)=>{const e=Number.isFinite(t)?t:o;return e>=1?!0:e<=0?!1:u(r)<e},l=(r,t)=>({isTraced:d(t,r?.headRate??o),keepErrors:r?.alwaysSampleErrors??!0}),p=(r,t)=>r.isTraced||r.keepErrors&&t,E=r=>{const t=i(r);return t===void 0?void 0:s(t)},f=r=>{if(r.error===void 0)return r;let t;try{t=r.error.internal}catch{const e=Object.getOwnPropertyDescriptors(r.error);return delete e.internal,{...r,error:Object.create(Object.getPrototypeOf(r.error),e)}}return t===void 0?r:{...r,error:{...r.error,internal:E(t)}}},T=(r,t,e,n,c)=>{if(!r?.onRpc)return;const a=c??(n!==void 0&&t.traceId!==void 0?l(n,t.traceId):void 0);if(!(a!==void 0&&!p(a,!t.ok)))try{r.onRpc(f(t),e)}catch{}},S=(r,t,e)=>{if(r?.onLog)try{r.onLog(t,e)}catch{}},y=(r,t)=>{if(r?.flush)try{r.flush(t)}catch{}};export{h as S,T as a,S as e,y as f,l as r};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{LunoraError as lt}from"@lunora/errors";import{redactCredentials as ft,redactArgs as M}from"@lunora/observability";import{stableStringify as pt}from"@lunora/wire";import{e as l,L as h,c as W,o as G,f as S,O as Y,g as mt,h as q,w as ht,i as yt,j as gt,m as bt}from"./otlp-resource-BBR8xs6m.mjs";import{t as kt}from"./error-detail-C46mdOTW.mjs";const Z=t=>{const r=String(t.name),o=String(t.message);return o===""?r:`${r}: ${o}`},Q=t=>{if(typeof t=="string")return t;if(t instanceof Error)return Z(t);try{return JSON.stringify(t)??String(t)}catch{return String(t)}},St=4,It=10,v=3584,Et=4,J=512,Tt=["all","root","short","none","minimal"],tt=8,Ot=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rt=t=>{if(!Ot(t))return!1;const r=Object.getPrototypeOf(t);return r===Object.prototype||r===null},j=(t,r=0,o=new WeakSet)=>t instanceof Error?!0:typeof t!="object"||t===null||r>=tt||o.has(t)?!1:(o.add(t),Array.isArray(t)?t.some(s=>j(s,r+1,o)):rt(t)&&Object.values(t).some(s=>j(s,r+1,o))),ot=t=>{if(typeof t=="bigint")return String(t);if(typeof t!="object"||t===null)return t;try{return JSON.stringify(t),t}catch{return}},At=(t,r,o)=>{if(t!==void 0)return r==="none"||r==="minimal"||r==="root"&&o>0?"":r==="short"?t.split(`
|
|
2
|
+
`).slice(0,Et+1).join(`
|
|
3
|
+
`):t},st=(t,r,o,s)=>({...s===void 0?{}:{child:s},errors:t,mask:o,memo:new WeakMap,mode:r,path:new Set}),et=(t,r,o)=>{if(!r.path.has(t)){if(r.memo.has(t))return r.memo.get(t);r.path.add(t);try{const s=o();return r.memo.set(t,s),s}finally{r.path.delete(t)}}},nt=(t,r,o)=>{Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:o,writable:!0})},x=(t,r,o)=>r.path.has(t)||o>St?{message:t.message,name:t.name}:et(t,r,()=>{const s=n=>n instanceof Error?x(n,r,o+1):(r.child??(u=>w(u,r,0,o+1)))(n),e=r.mode==="minimal",i=n=>n.length>J?`${n.slice(0,J)}…`:n,a=n=>e&&!(n instanceof Error)?i(Q(n)):s(n),p={message:e?i(t.message):t.message,name:t.name};if(!e)for(const[n,u]of Object.entries(t))n!=="message"&&n!=="name"&&nt(p,n,s(u));const y=At(t.stack,r.mode,o);return y!==void 0&&(p.stack=y),t.cause!==void 0&&(p.cause=a(t.cause)),t instanceof AggregateError&&Array.isArray(t.errors)&&(p.errors=t.errors.slice(0,It).map(n=>a(n))),r.mask(p)}),w=(t,r,o,s)=>t instanceof Error?r.errors==="full"?x(t,r,s):Z(t):typeof t!="object"||t===null||o>=tt||!(Array.isArray(t)||rt(t))?ot(t):et(t,r,()=>Array.isArray(t)?t.map(e=>w(e,r,o+1,s)):Object.fromEntries(Object.entries(t).map(([e,i])=>[e,w(i,r,o+1,s)]))),Pt=t=>{try{return JSON.stringify(t).length}catch{return Number.POSITIVE_INFINITY}},U=t=>t,rr=(t,r=ot)=>{let o;for(const s of Tt)if(o=x(t,st("full",s,U,r),0),Pt(o)<=v)break;return o},Rt=(t,r,o)=>{const s=c=>JSON.stringify(w(t,st(r,c,o),0,0)),e=c=>c===void 0||c.length<=v,i=s("all");if(r==="headline"||e(i))return i;const a=s("minimal");if(!e(a))return a;for(const c of["root","short","none"]){const p=s(c);if(e(p))return p}return a},_=(t,r="headline",o=U)=>{if(typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;try{return!j(t)||r==="headline"&&t instanceof Error?Q(t):Rt(t,r,o)??String(t)}catch{return String(t)}},or=(t,r,o="headline",s=U)=>{if(t===void 0&&r===void 0)return;const e={};if(t!==void 0)for(const[i,a]of Object.entries(t))nt(e,i,_(a,o,s));return Object.keys(e).length===0?void 0:e},wt=512,_t=200,Lt=t=>{const r=t.maxItems??wt,o=t.maxDelayMs??_t;let s=[],e,i,a;const c=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},p=async()=>{c();const n=s;s=[];const u=a;i=void 0,a=void 0;try{n.length>0&&await t.export(n)}catch{}finally{u?.()}},y=n=>{i===void 0&&(i=new Promise(u=>{a=u}),e=setTimeout(()=>{p()},o)),n?.(i)};return{add:(n,u)=>{for(s.push(n);s.length>r;)s.shift();y(u),s.length>=r&&p()},flush:async n=>{if(s.length===0){c();return}const u=p();return n?.(u),u},get size(){return s.length}}},Nt=1,Mt=0,jt=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"]),xt={errorType:h.errorType,functionPath:h.functionPath,rayId:h.rayId,shardKey:h.shardKey,userId:h.userId},Ut=t=>{const r=kt(t);return r===void 0?[]:[l("lunora.error.internal",JSON.stringify(ft(r)))]},at=(t,r,o,s)=>[l("exception.type",t),l("exception.message",r),...o===void 0?[]:[l("exception.stacktrace",o)],...s===void 0?[]:Ut(s)],Dt=(t,r)=>{const o=[l(h.functionPath,t.functionPath),l(h.ok,t.ok)];if(t.method!==void 0&&o.push(l("http.request.method",t.method)),t.path!==void 0&&o.push(l("url.path",t.path)),o.push(l("http.route",t.functionPath)),t.scheme!==void 0&&o.push(l("url.scheme",t.scheme)),t.host!==void 0&&o.push(l("server.address",t.host)),t.port!==void 0&&o.push(l("server.port",t.port)),t.userAgent!==void 0&&o.push(l("user_agent.original",t.userAgent)),t.shardKey!==void 0&&o.push(l(h.shardKey,t.shardKey)),t.rayId!==void 0&&o.push(l(h.rayId,t.rayId)),o.push(l("http.response.status_code",t.error?.status??200)),t.error&&o.push(l(h.errorType,t.error.code),l("lunora.error_status",t.error.status)),t.fanOut&&o.push(l("lunora.fanout.table",t.fanOut.table),l("lunora.fanout.shards",t.fanOut.shards),l("lunora.fanout.failed",t.fanOut.failed)),t.attributes!==void 0){const e=new Set([...jt,...o.map(a=>a.key)]),i=W(Object.fromEntries(Object.entries(t.attributes).map(([a,c])=>[a,_(c)])));o.push(...i.filter(a=>!e.has(a.key)))}const s={attributes:o,endTimeUnixNano:S(r),kind:Y.server,name:t.functionPath,...t.parentSpanId===void 0?{}:{parentSpanId:t.parentSpanId},spanId:t.spanId??G(8),startTimeUnixNano:S(r-t.durationMs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId??G(16)};return t.traceFlags!==void 0&&(s.flags=t.traceFlags),t.error&&(s.events=[{attributes:at(t.error.code,t.error.message,t.error.stack,t.error.internal),name:"exception",timeUnixNano:S(r)}]),s},D=(t,r)=>{const o=new Map,s=new Set(Object.keys(t).map(e=>xt[e]));for(const[e,i]of Object.entries(r??{}))s.has(e)||o.set(e,l(e,_(i)));return o.set(h.functionPath,l(h.functionPath,t.functionPath)),t.shardKey!==void 0&&o.set(h.shardKey,l(h.shardKey,t.shardKey)),t.userId!==void 0&&o.set(h.userId,l(h.userId,t.userId)),t.rayId!==void 0&&o.set(h.rayId,l(h.rayId,t.rayId)),t.errorType!==void 0&&o.set(h.errorType,l(h.errorType,t.errorType)),[...o.values()]},Ft=t=>{const r={attributes:D({errorType:t.error?.type,functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.attributes),endTimeUnixNano:S(t.startTs+t.durationMs),flags:t.sampled===!1?Mt:Nt,kind:Y[t.kind??"internal"],name:t.name,parentSpanId:t.parentSpanId,spanId:t.spanId,startTimeUnixNano:S(t.startTs),status:t.ok?{code:1}:{code:2,message:t.error?.message??""},traceId:t.traceId},o=s=>W(Object.fromEntries(Object.entries(s??{}).map(([e,i])=>[e,_(i)])));return t.events!==void 0&&t.events.length>0&&(r.events=t.events.map(s=>({attributes:o(s.attributes),name:s.name,timeUnixNano:S(s.ts)}))),t.links!==void 0&&t.links.length>0&&(r.links=t.links.map(s=>({attributes:o(s.attributes),spanId:s.spanId,traceId:s.traceId}))),r},Kt=t=>{const r=S(t.ts),o=D({functionPath:t.functionPath,shardKey:t.shardKey},t.attributes),s=t.traceId===void 0?void 0:[{asDouble:t.value,timeUnixNano:r,traceId:t.traceId}],e={asDouble:t.value,attributes:o,...s===void 0?{}:{exemplars:s},timeUnixNano:r};return t.kind==="gauge"?{gauge:{dataPoints:[e]},name:t.name}:t.kind==="histogram"?{histogram:{aggregationTemporality:1,dataPoints:[{attributes:o,bucketCounts:["1"],count:"1",...s===void 0?{}:{exemplars:s},explicitBounds:[],max:t.value,min:t.value,sum:t.value,timeUnixNano:r}]},name:t.name}:{name:t.name,sum:{aggregationTemporality:1,dataPoints:[e],isMonotonic:!0}}},$t=t=>{const r={attributes:D({functionPath:t.functionPath,rayId:t.rayId,shardKey:t.shardKey,userId:t.userId},t.fields),body:{stringValue:t.message},severityNumber:mt[t.level],severityText:t.level.toUpperCase(),timeUnixNano:S(t.ts)};if(t.traceId!==void 0&&(r.traceId=t.traceId),t.spanId!==void 0&&(r.spanId=t.spanId),t.error!==void 0){const o=at(t.error.name,t.error.message,t.error.stack,t.error.internal),s=new Set(o.map(e=>e.key));r.attributes=[...r.attributes.filter(e=>!s.has(e.key)),...o]}return t.eventName!==void 0&&(r.eventName=t.eventName,r.attributes=[...r.attributes.filter(o=>o.key!=="event.name"),l("event.name",t.eventName)]),r},Ht=1024,V=5;let N=0;const Ct=(t,r)=>{if(N>=V)return;N+=1;let o;try{o=new URL(t).host}catch{o="<unparseable endpoint>"}const s=N===V?" Further OTLP rejections are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] collector ${o} rejected the export with HTTP ${String(r)}; the batch is DROPPED (there is no retry).${s}`)},Bt=async t=>{const r=new Blob([t]).stream().pipeThrough(new CompressionStream("gzip"));return new Response(r).arrayBuffer()},it=async(t,r,o,s)=>{try{const e=JSON.stringify(r),{byteLength:i}=new TextEncoder().encode(e),a=(i<Ht?fetch(t,{body:e,headers:o,method:"POST"}):Bt(e).then(c=>fetch(t,{body:c,headers:{...o,"content-encoding":"gzip"},method:"POST"}))).then(c=>{c.ok||Ct(t,c.status)},()=>{});s?.(a),await a}catch{}},Gt=(t,r,o,s)=>{it(t,r,o,s?.waitUntil).catch(()=>{})},P=(t,r)=>r===!0&&t.ok,Jt=t=>t.kind==="metric"?void 0:t.event.traceId,Vt=t=>{const r=Map.groupBy(t,s=>Jt(s)),o=r.get(void 0)??[];return r.delete(void 0),{byTrace:r,untraced:o}},X=5,Xt=(t,r,o)=>{if(r===void 0)return t;const{byTrace:s,untraced:e}=Vt(t),i=[...e];let a=0,c;for(const[p,y]of s){let n;try{n=r({logs:y.filter(u=>u.kind==="log").map(u=>u.event),rpc:y.filter(u=>u.kind==="rpc").map(u=>u.event),spans:y.filter(u=>u.kind==="span").map(u=>u.event),traceId:p})}catch(u){a+=1,a===1&&(c=u),n=!0}n&&i.push(...y)}return a>0&&o(c,a),i},O=(t,r)=>{let o;try{o=r===void 0?t:r(t)}catch{o=void 0}return o??void 0},zt=t=>{const r=M(t.message);if(t.stack===void 0)return{...t,message:r};const o=`: ${t.message}`,s=t.stack.indexOf(o),i=t.message!==""&&s!==-1&&!t.stack.slice(0,s).includes(`
|
|
4
|
+
`)?t.stack.slice(s+o.length):t.stack.split(`
|
|
5
|
+
`).filter(a=>a.trimStart().startsWith("at ")).map(a=>`
|
|
6
|
+
${a}`).join("");return{...t,message:r,stack:`${t.name}: ${r}${i}`}},Wt=t=>({...t,...t.error===void 0?{}:{error:zt(t.error)},...t.fields===void 0?{}:{fields:M(t.fields)},message:M(t.message)}),z=(t,r,o)=>{if(t.kind==="rpc"){const e=O(t.event,r?.rpc);return e===void 0?void 0:{bucket:"spans",encoded:Dt(e,t.endMs)}}if(t.kind==="span"){const e=O(t.event,r?.span);return e===void 0?void 0:{bucket:"spans",encoded:Ft(e)}}if(t.kind==="log"){const e=O(o?Wt(t.event):t.event,r?.log);return e===void 0?void 0:{bucket:"logs",encoded:$t(e)}}const s=O(t.event,r?.metric);return s===void 0?void 0:{bucket:"metrics",encoded:Kt(s)}},Yt=["fuseCloudflareTraces","instrumentDatabase","metricHistory","traceFetch"],sr=(t={})=>{const{onlyErrors:r}=t;return{onLog:o=>{o.level==="error"||o.level==="fatal"?console.error("[lunora:log]",o.functionPath,o.message):console.log("[lunora:log]",o.functionPath,o.message)},onMetric:o=>{console.log("[lunora:metric]",`${o.name}=${String(o.value)}`,o.kind,o.functionPath)},onRpc:o=>{P(o,r)||(o.ok?console.log("[lunora:rpc]",o):console.error("[lunora:rpc]",o))},onSpan:o=>{const s=o.ok?"ok":`error ${o.error?.type??""}`.trim();console.log("[lunora:span]",o.name,`${String(o.durationMs)}ms`,s,o.functionPath)}}},er=t=>{const{headers:r,onlyErrors:o,transform:s,transformLog:e,url:i}=t,a=q({"content-type":"application/json"},r),c=(p,y)=>{try{const n=fetch(i,{body:JSON.stringify(p),headers:a,method:"POST"}).catch(()=>{});y?.waitUntil&&y.waitUntil(n)}catch{}};return{onLog:(p,y)=>{const n=O(p,e);n!==void 0&&c(n,y)},onRpc:(p,y)=>{if(P(p,o))return;const n=O(p,s);n!==void 0&&c(n,y)}}},nr=t=>{const{dataset:r,onlyErrors:o}=t;return{onRpc:s=>{if(!P(s,o))try{r.writeDataPoint({blobs:[s.functionPath,s.ok?"ok":"error",s.shardKey??"",s.error?.code??"",s.fanOut?.table??""],doubles:[s.durationMs,s.ok?0:1,s.fanOut?.shards??0,s.fanOut?.failed??0],indexes:[s.functionPath]})}catch{}}}},ar=t=>{const{pipeline:r,serializeFields:o}=t;return{onLog:(s,e)=>{try{const i={functionPath:s.functionPath,level:s.level,message:s.message,ts:s.ts};s.fields&&(i.fields=o===!0?JSON.stringify(s.fields):s.fields);for(const c of["shardKey","userId","traceId","spanId"])s[c]!==void 0&&(i[c]=s[c]);const a=r.send([i]).catch(()=>{});e?.waitUntil&&e.waitUntil(a)}catch{}}}},ir=t=>{const{batch:r,deploymentEnvironment:o,detectResources:s,endpoint:e,headers:i,onlyErrors:a,postProcessor:c,resourceAttributes:p,serviceNamespace:y,serviceVersion:n,tailSampler:u,token:ct}=t,F=t.serviceName??"lunora",K=t.redactLogs??!0;if(r!==!1&&r?.maxItems!==void 0&&(!Number.isInteger(r.maxItems)||r.maxItems<1))throw new lt("ENV_INVALID",`otlpSink: \`batch.maxItems\` must be a positive integer, received ${String(r.maxItems)}.`);const $={...n===void 0?{}:{"service.version":n},...y===void 0?{}:{"service.namespace":y},...o===void 0?{}:{"deployment.environment":o},...p},H=new WeakMap,k=f=>{if(s!==!0||f?.resourceAttributes===void 0)return $;const d=H.get(f);if(d!==void 0)return d;const m=bt(f.resourceAttributes(),$);return H.set(f,m),m};let I=e;for(;I.endsWith("/");)I=I.slice(0,-1);const C={logs:{url:`${I}/v1/logs`,wrap:gt},metrics:{url:`${I}/v1/metrics`,wrap:yt},spans:{url:`${I}/v1/traces`,wrap:ht}},B=q({"content-type":"application/json"},i,ct);let L=0;const dt=(f,d)=>{if(L>=X)return;L+=1;const m=L===X?" Further tailSampler failures from this sink are silenced until the isolate restarts.":"";console.error(`[lunora:otlp] tailSampler threw for ${String(d)} trace(s) in this flush window; keeping them (fail-open), so the sampling policy did NOT apply.${m}`,f)},ut=async f=>{const d=Xt(f,u,dt),m=new Map;for(const g of d){const b=z(g,c,K);if(b===void 0)continue;const R=pt(g.resource);let T=m.get(R);T===void 0&&(T={logs:[],metrics:[],resource:g.resource,spans:[]},m.set(R,T)),T[b.bucket].push(b.encoded)}const E=[];for(const[,g]of m)for(const b of["spans","logs","metrics"])if(g[b].length>0){const{url:R,wrap:T}=C[b];E.push(it(R,T(g[b],"@lunora/runtime",F,g.resource),B))}await Promise.all(E)};if(r===!1){const f=(d,m)=>{const E=z(d,c,K);if(E!==void 0){const{url:g,wrap:b}=C[E.bucket];Gt(g,b(E.encoded,"@lunora/runtime",F,d.resource),B,m)}};return{onLog:(d,m)=>{f({event:d,kind:"log",resource:k(m)},m)},onMetric:(d,m)=>{f({event:d,kind:"metric",resource:k(m)},m)},onRpc:(d,m)=>{P(d,a)||f({endMs:Date.now(),event:d,kind:"rpc",resource:k(m)},m)},onSpan:(d,m)=>{f({event:d,kind:"span",resource:k(m)},m)}}}const A=Lt({export:ut,...r?.maxDelayMs===void 0?{}:{maxDelayMs:r.maxDelayMs},...r?.maxItems===void 0?{}:{maxItems:r.maxItems}});return{flush:f=>{A.flush(f?.waitUntil).catch(()=>{})},onLog:(f,d)=>{A.add({event:f,kind:"log",resource:k(d)},d?.waitUntil)},onMetric:(f,d)=>{A.add({event:f,kind:"metric",resource:k(d)},d?.waitUntil)},onRpc:(f,d)=>{P(f,a)||A.add({endMs:Date.now(),event:f,kind:"rpc",resource:k(d)},d?.waitUntil)},onSpan:(f,d)=>{A.add({event:f,kind:"span",resource:k(d)},d?.waitUntil)}}},cr=(...t)=>{const r=(s,e)=>{for(const i of t){const a=i[s];if(a)try{a.apply(i,e)}catch{}}},o={};for(const s of t)for(const e of Yt)o[e]===void 0&&s[e]!==void 0&&(o[e]=s[e]);return{...o,flush:s=>{r("flush",[s])},onLog:(s,e)=>{r("onLog",[s,e])},onMetric:(s,e)=>{r("onMetric",[s,e])},onRpc:(s,e)=>{r("onRpc",[s,e])},onSpan:(s,e)=>{r("onSpan",[s,e])}}};export{Yt as S,nr as a,sr as b,cr as c,Z as e,or as n,ir as o,ar as p,rr as t,er as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a="x-lunora-paywall",A="1";export{A as O,a};
|
|
@@ -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,2 @@
|
|
|
1
|
+
const l=e=>{const t=e.trim();if(!t.startsWith("at "))return;let n=t.slice(3),o="<anonymous>";const i=n.lastIndexOf(" (");n.endsWith(")")&&i!==-1&&(o=n.slice(0,i),n=n.slice(i+2,-1));const s=n.lastIndexOf(":"),c=s<=0?-1:n.lastIndexOf(":",s-1),a=Number.parseInt(n.slice(c+1,s),10),r=Number.parseInt(n.slice(s+1),10);if(!(c<=0||Number.isNaN(a)||Number.isNaN(r)))return{colno:r,filename:n.slice(0,c),function:o,lineno:a}},f=e=>{const t=new Error(e.message);return t.name=e.name??e.code??"Error",e.stack!==void 0&&(t.stack=e.stack),e.code!==void 0&&(t.code=e.code),t},m=e=>{if(e===void 0)return[];const t=[];for(const n of e.split(`
|
|
2
|
+
`)){const o=l(n);o!==void 0&&t.push(o)}return t.toReversed()};export{m as parseStackFrames,f as toError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{raw as n,desc as F,sql as r}from"@lunora/bindings/r2sql";const u=["trace","debug","log","info","warn","error","fatal"],T={fields:"fields",functionPath:"functionPath",level:"level",message:"message",shardKey:"shardKey",spanId:"spanId",traceId:"traceId",ts:"ts",userId:"userId"},N=500,w=1e4,_=e=>e===void 0||!Number.isFinite(e)?N:Math.min(Math.max(Math.floor(e),1),w),D=e=>typeof e=="number"?e:Number(e),L=e=>e==null?"":String(e),U=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},S=e=>{const s=JSON.stringify([e.ts,e.level,e.functionPath,e.message,e.traceId,e.spanId,e.shardKey,e.userId,e.fields]);let t=0,l=0;for(const v of s){const I=v.codePointAt(0)??0;t=(t*31+I)%2147483647,l=(l*131+I)%4294967291}return`${t.toString(36)}.${l.toString(36)}`},y=(e,s,t,l)=>{if(s.sinceTs!==void 0&&e.where(r`${n(t.ts)} >= ${s.sinceTs}`),s.untilTs!==void 0&&e.where(r`${n(t.ts)} <= ${s.untilTs}`),s.level!==void 0)e.where(r`${n(t.level)} = ${s.level}`);else if(s.minLevel!==void 0){const v=u.indexOf(s.minLevel),I=v===-1?[...u]:u.slice(v);e.where(r`${n(t.level)} IN ${I}`)}s.functionPath!==void 0&&e.where(r`${n(t.functionPath)} = ${s.functionPath}`),s.functionPathPrefix!==void 0&&e.where(r`${n(t.functionPath)} LIKE ${`${s.functionPathPrefix}%`}`),s.traceId!==void 0&&e.where(r`${n(t.traceId)} = ${s.traceId}`),s.shardKey!==void 0&&e.where(r`${n(t.shardKey)} = ${s.shardKey}`),s.userId!==void 0&&e.where(r`${n(t.userId)} = ${s.userId}`),l!==void 0&&e.where(r`${n(t.ts)} <= ${l}`)},G=T,J=(e,s)=>{const t={...T,...s.columnMap},l=s.namespace===void 0?s.table:`${s.namespace}.${s.table}`,v=a=>{const c={functionPath:L(a[t.functionPath]),level:L(a[t.level]),message:L(a[t.message]),ts:D(a[t.ts])},o=a[t.fields];o!=null&&(c.fields=U(o));for(const d of["shardKey","userId","traceId","spanId"]){const i=a[t[d]];i!=null&&(c[d]=L(i))}return c},I=async(a,c,o)=>{const d=e.from(l).select(n(t.functionPath),n(t.level),n(t.message),n(t.ts),n(t.fields),n(t.shardKey),n(t.userId),n(t.traceId),n(t.spanId));y(d,a,t,c),d.orderBy(F(n(t.ts))).limit(o);const{rows:i}=await d.run();return i},A=async(a,c,o,d)=>{const i=await I(a,c,d),$=[];for(const P of i){const f=v(P);o!==void 0&&c!==void 0&&f.ts===c&&o.has(S(f))||$.push(f)}return{decoded:$,truncated:i.length>=d}};return{query:async(a={})=>{const c=_(a.limit),{cursor:o}=a,d=o?.ts,i=o?.seen!==void 0&&o.seen.length>0?new Set(o.seen):void 0,$=Math.min(c+1,w),P=3;let f=[],m=!1;for(let h=0;h<P;h+=1){const K=Math.min($*2**h,w),O=await A(a,d,i,K);if(f=O.decoded,m=O.truncated,f.length>c||!m||K>=w)break}const R=f.length>c,g=R?f.slice(0,c):f,M=g.at(-1);if(M===void 0||!(R||m))return{rows:g};const p=M.ts,E=g.filter(h=>h.ts===p).map(h=>S(h)),x=[...d===p&&o?.seen!==void 0?o.seen:[],...E];return{nextCursor:x.length>0?{seen:x,ts:p}:{ts:p},rows:g}}}};export{G as D,u as L,J as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{decodeWire as f,isPlainObject as s}from"@lunora/wire";import{a as i}from"./base64-Bl1_r2k1.mjs";const o=r=>{if(typeof r=="bigint")return r.toString();if(r instanceof ArrayBuffer)return i(new Uint8Array(r));if(ArrayBuffer.isView(r))return i(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));if(Array.isArray(r))return r.map(t=>o(t));if(s(r)){const t={};for(const e of Object.keys(r)){const n=o(r[e]);e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}return t}return r},y=r=>o(f(r));export{y as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m="/_lunora/rest",h=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],d=["x-d1-bookmark","x-lunora-shard-key"],v=e=>[...h,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],l=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,p=e=>l.test(e),E=(e,t,a=[])=>t?.access!==void 0||h.some(s=>e.has(s))||a.some(s=>!p(s)||e.has(s)),u=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,c=(...e)=>{const t=[];for(const a of e)for(const s of a?.split(",")??[]){const n=s.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},g=(e,t)=>{const a=[t,`max-age=${String(u(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&a.push(`stale-while-revalidate=${String(u(e.staleWhileRevalidate))}`),a.join(", ")},R=e=>e.scope==="public"?c(e.vary,...v(e),...d):c(e.vary,...d),f=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},x=e=>{const t=f(e);if(t!==void 0)return`${m}/${t.namespace}/${t.name}`},A=e=>e==="query"?"GET":"POST",H=e=>{const t=[];for(const a of e){if(a.exposure?.rest!==!0||a.kind==="stream")continue;const s=f(a.functionPath),n=x(a.functionPath);s===void 0||n===void 0||t.push({functionPath:a.functionPath,kind:a.kind,method:A(a.kind),name:s.name,namespace:s.namespace,path:n})}return t.sort((a,s)=>a.path<s.path?-1:+(a.path>s.path)),t},C=(e,t,a)=>E(e.headers,a,t.credentialHeaders),S=(e,t,a)=>e.scope==="public"&&!C(t,e,a)?"public":"private",b=(e,t,a,s)=>{if(t.method!=="GET"||a<200||a>299)return;const n={"cache-control":g(e,S(e,t,s))};e.tag!==void 0&&e.tag!==""&&(n["cache-tag"]=e.tag);const r=R(e);return r!==void 0&&(n.vary=r),n},k=(e,t,a,s)=>{if(t===void 0)return e;const n=b(t,a,e.status,s);if(n===void 0)return e;const r=new Response(e.body,e);for(const[i,o]of Object.entries(n))r.headers.set(i,i==="vary"?c(r.headers.get("vary")??void 0,o)??o:o);return r};export{k as a,b,u as c,R as d,S as e,H as f,C as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as O,d as P,e as B,a as x,f as D}from"./rest-cache-q5V06Etw.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
|
+
import{LunoraError as g}from"./LunoraError-PkZWF-_g.mjs";const D=new Set(["0","disabled","false","no","off"]),C=new Set(["1","enabled","on","true","yes"]),O=e=>typeof e=="string"&&D.has(e.trim().toLowerCase()),R=e=>typeof e=="string"&&C.has(e.trim().toLowerCase()),S=e=>{if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===null||s===Object.prototype},_="default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",N="accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()",P=31536e3,I={coop:void 0,csp:void 0,enabled:!1,frameOptions:void 0,hsts:void 0,permissionsPolicy:void 0,referrerPolicy:void 0},k=e=>{if(e===!1)return;const s=e===void 0||e===!0?{}:e,o=s.maxAge??P,r=s.includeSubDomains??!0;return`max-age=${String(o)}${r?"; includeSubDomains":""}${s.preload===!0?"; preload":""}`},x=(e,s)=>s!==void 0?["frame-ancestors 'self'",...s].join(" "):e==="DENY"?"frame-ancestors 'none'":e==="SAMEORIGIN"?"frame-ancestors 'self'":void 0,H=/^[a-z][\d+.a-z-]*:\/\/(?:\*\.)?[\d.a-z-]+(?::\d{1,5})?$/iu,w=e=>[...e].every(s=>s===" "||s>=" "&&s!==""&&s<="ÿ"),T=["same-origin","same-origin-allow-popups","unsafe-none"],U=["DENY","SAMEORIGIN"],f=["includeSubDomains","maxAge","preload"],b=["csp","permissionsPolicy","referrerPolicy"],u=[...b,"crossOriginOpenerPolicy","frameAncestors","frameOptions","hsts"],d=e=>e.map(s=>JSON.stringify(s)).join(", "),j=(e,s)=>{if(typeof e=="boolean")return e;if(!S(e)){s.push("security.headers.hsts must be a boolean or an object { maxAge?, includeSubDomains?, preload? }");return}for(const n of Object.keys(e).filter(i=>!f.includes(i)))s.push(`security.headers.hsts.${n} is not an option (expected ${d(f)})`);const{includeSubDomains:o,maxAge:r,preload:t}=e;r!==void 0&&!(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&s.push(`security.headers.hsts.maxAge must be a whole number of seconds (got ${JSON.stringify(r)})`);for(const[n,i]of[["includeSubDomains",o],["preload",t]])i!==void 0&&typeof i!="boolean"&&s.push(`security.headers.hsts.${n} must be a boolean`);return{...o===void 0?{}:{includeSubDomains:o},...r===void 0?{}:{maxAge:r},...t===void 0?{}:{preload:t}}},p=(e,s,o,r)=>{if(s===void 0||s===!1||o.includes(s))return s;r.push(`security.headers.${e} must be one of ${d(o)} or false (got ${JSON.stringify(s)})`)},$=(e,s)=>{if(e!==void 0){if(!Array.isArray(e)){s.push('security.headers.frameAncestors must be an array of origins like ["https://partner.example"]');return}for(const o of e)(typeof o!="string"||!H.test(o)||!w(o))&&s.push(`security.headers.frameAncestors entry ${JSON.stringify(o)} is not an origin like "https://partner.example"`);return[...e]}},M=e=>{if(e===void 0||typeof e=="boolean")return{ok:!0,value:e};if(!S(e))return{ok:!1,problems:[`security.headers must be a boolean or an object (got ${Array.isArray(e)?"an array":JSON.stringify(e)})`]};const s=Object.keys(e).filter(r=>!u.includes(r)).map(r=>`security.headers.${r} is not an option (expected ${d(u)})`),o={};for(const r of b){const t=e[r];t===void 0||t===!1?o[r]=t:typeof t!="string"?s.push(`security.headers.${r} must be a string or false`):w(t)?o[r]=t:s.push(`security.headers.${r} contains a line break or control character`)}return o.crossOriginOpenerPolicy=p("crossOriginOpenerPolicy",e.crossOriginOpenerPolicy,T,s),o.frameOptions=p("frameOptions",e.frameOptions,U,s),o.frameAncestors=$(e.frameAncestors,s),o.hsts=e.hsts===void 0?void 0:j(e.hsts,s),o.frameAncestors!==void 0&&typeof o.csp=="string"&&s.push("security.headers.frameAncestors cannot be combined with a csp string: put the frame-ancestors directive in the csp"),o.frameAncestors!==void 0&&o.frameOptions==="DENY"&&s.push('security.headers.frameAncestors cannot be combined with frameOptions: "DENY"'),o.frameAncestors!==void 0&&o.csp===!1&&s.push("security.headers.frameAncestors needs the Content-Security-Policy that carries it; it cannot be combined with csp: false"),s.length>0?{ok:!1,problems:s}:{ok:!0,value:Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}},X=(e,s)=>e??(O(s)?!1:void 0),F=e=>{if(e===!1)return I;const s=e===void 0||e===!0?{}:e,o=s.frameAncestors!==void 0||s.frameOptions===!1?void 0:s.frameOptions??"SAMEORIGIN",r=["base-uri 'none'","object-src 'none'",x(o,s.frameAncestors)].filter(n=>n!==void 0).join("; ");let t;return typeof s.csp=="string"?t={htmlValue:s.csp,value:s.csp}:s.csp!==!1&&(t={htmlValue:r,value:_}),{coop:s.crossOriginOpenerPolicy===!1?void 0:s.crossOriginOpenerPolicy??"same-origin-allow-popups",csp:t,enabled:!0,frameOptions:o,hsts:k(s.hsts),permissionsPolicy:s.permissionsPolicy===!1?void 0:s.permissionsPolicy??N,referrerPolicy:s.referrerPolicy===!1?void 0:s.referrerPolicy??"strict-origin-when-cross-origin"}},h=["Authorization","Content-Type","Last-Event-ID","X-D1-Bookmark","X-Lunora-Client-Id","X-Lunora-Client-Seq","X-Lunora-Expect-Subject","X-Lunora-Min-Seq","X-Lunora-Mutation-Id","X-Lunora-Shard-Key"],m=["DELETE","GET","HEAD","PATCH","POST","PUT"],Y=new Set(["GET","HEAD","OPTIONS"]),G=e=>{const s={allowCredentials:!1,allowedHeaders:h,allowedMethods:m,enabled:!1,isAllowed:()=>!1,isExplicitlyAllowed:()=>!1,maxAge:600};if(e===void 0||e===!1)return s;const o=e.allowCredentials??!1,r=e.allowedOrigins;let t,n;if(typeof r=="function"){const i=v=>r(v)===!0;t=i,n=i,console.warn(`@lunora/runtime: security.cors uses a custom \`allowedOrigins\` predicate. It is trusted by the CSRF and WebSocket origin checks${o?" AND reflects matching origins with credentials (`allowCredentials: true`)":""} — ensure it matches ONLY trusted origins by exact equality; an over-broad predicate (e.g. \`() => true\`, or \`endsWith\`/\`includes\` checks) defeats the allowlist.`)}else{const i=r;if(i.includes("*")&&o)throw new g('@lunora/runtime: security.cors cannot combine a wildcard origin ("*") with allowCredentials: true — browsers reject it and it defeats the allowlist.');t=a=>i.includes("*")||i.includes(a),n=a=>i.includes(a)}return{allowCredentials:o,allowedHeaders:[...new Set([...h,...e.allowedHeaders??[]])],allowedMethods:e.allowedMethods??m,enabled:!0,isAllowed:t,isExplicitlyAllowed:n,maxAge:e.maxAge??600}},B=e=>{if(e===!1)return{allowLoopback:!1,enabled:!1,trustedOrigins:[]};const s=e===void 0||e===!0?{}:e;return{allowLoopback:s.allowLoopback??!0,enabled:!0,trustedOrigins:s.trustedOrigins??[]}},V=e=>{const s=e?.LUNORA_ALLOWED_ORIGINS;if(typeof s!="string")return;const o=s.split(",").map(n=>n.trim()).filter(n=>n.length>0);return o.length===0?void 0:{allowCredentials:!o.includes("*")&&R(e?.LUNORA_CORS_ALLOW_CREDENTIALS),allowedOrigins:o}},q=(e,s)=>{const o=M(X(e?.headers,s?.LUNORA_SECURITY_HEADERS)),r=e?.csrf??(O(s?.LUNORA_SECURITY_CSRF)?!1:void 0),t=e?.cors??V(s);if(!o.ok)throw new g(`@lunora/runtime: ${o.problems.join("; ")}`);return{cors:G(t),csrf:B(r),headers:F(o.value)}},K=new Set(["127.0.0.1","::1","[::1]","localhost"]),y=e=>{try{return K.has(new URL(e).hostname)}catch{return!1}},l=e=>{if(e)try{return new URL(e).origin}catch{return}},A=(e,s,o)=>e===s||o.csrf.trustedOrigins.includes(e)||o.csrf.allowLoopback&&y(s)&&y(e)?!0:o.cors.enabled&&o.cors.isExplicitlyAllowed(e),E=(e,s,o)=>Response.json({error:{code:"FORBIDDEN_ORIGIN",expectedOrigin:o,message:`${e} rejected: Origin ${s===void 0?"was missing":`"${s}"`} is not trusted (this worker serves "${o}"). Add it to \`security.csrf.trustedOrigins\` (or LUNORA_ALLOWED_ORIGINS) if it is yours. Behind a dev proxy this usually means the proxy rewrote the host: keep both ends on loopback, or list the dev-server origin.`,receivedOrigin:s}},{headers:{"content-type":"application/json"},status:403}),ee=(e,s)=>{if(!s.csrf.enabled||Y.has(e.method)||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"))??l(e.headers.get("referer"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin state-changing request",r,o)},se=(e,s)=>{if(!s.csrf.enabled||!e.headers.get("cookie"))return;const o=new URL(e.url).origin,r=l(e.headers.get("origin"));if(!(r!==void 0&&A(r,o,s)))return E("cross-origin websocket upgrade",r,o)},W=["X-D1-Bookmark","X-Lunora-Edge-Cache","X-Lunora-Live-Connection","X-Lunora-Shard-Key"],L=(e,s)=>{const o=new Headers;return o.set("access-control-allow-origin",e),o.set("access-control-expose-headers",W.join(", ")),o.append("vary","Origin"),s.allowCredentials&&o.set("access-control-allow-credentials","true"),o},oe=(e,s)=>{if(!s.cors.enabled||e.method!=="OPTIONS")return;const o=e.headers.get("origin");if(!o||!e.headers.get("access-control-request-method")||!s.cors.isAllowed(o))return;const r=L(o,s.cors),t=e.headers.get("access-control-request-headers");r.set("access-control-allow-methods",s.cors.allowedMethods.join(", "));let n;if(t===null)n=s.cors.allowedHeaders.join(", ");else{const i=new Set(s.cors.allowedHeaders.map(a=>a.toLowerCase()));n=t.split(",").map(a=>a.trim()).filter(a=>a.length>0&&i.has(a.toLowerCase())).join(", ")}return r.set("access-control-allow-headers",n),r.set("access-control-max-age",String(s.cors.maxAge)),new Response(null,{headers:r,status:204})},J=e=>(e.headers.get("content-type")??"").toLowerCase().includes("text/html"),c=(e,s,o)=>{e.has(s)||e.set(s,o)},z=(e,s,o,r)=>{r.hsts!==void 0&&new URL(s.url).protocol==="https:"&&c(e,"strict-transport-security",r.hsts),c(e,"x-content-type-options","nosniff"),r.frameOptions!==void 0&&c(e,"x-frame-options",r.frameOptions),r.referrerPolicy!==void 0&&c(e,"referrer-policy",r.referrerPolicy),r.permissionsPolicy!==void 0&&c(e,"permissions-policy",r.permissionsPolicy),r.coop!==void 0&&c(e,"cross-origin-opener-policy",r.coop),r.csp!==void 0&&c(e,"content-security-policy",J(o)?r.csp.htmlValue:r.csp.value)},Q=(e,s,o)=>{const r=s.headers.get("origin");if(!(!r||!o.isAllowed(r)))for(const[t,n]of L(r,o).entries())t==="vary"?e.append("vary",n):c(e,t,n)},re=(e,s,o)=>{if(e.status===101||e.webSocket)return e;const r=new Headers(e.headers);return o.headers.enabled&&z(r,s,e,o.headers),o.cors.enabled&&Q(r,s,o.cors),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})};export{se as a,re as d,ee as e,oe as h,S as i,q as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as b}from"./portable-json-CSq6T1AU.mjs";const p="_id",f=(t,n=p)=>{const o=Object.create(null),s=Object.create(null),c=Object.create(null),a=Object.create(null),h=e=>typeof n=="string"?n:n[e]??p,l=(e,r)=>{const u=e[r];if(u)return u;const d=[];return e[r]=d,d};for(const e of t.changes){a[e.table]??={primary_key:[h(e.table)]};const r=b(e.doc);e.op==="delete"?l(c,e.table).push(r):e.op==="update"?l(s,e.table).push(r):l(o,e.table).push(r)}return{delete:c,hasMore:t.hasMore,insert:o,schema:a,state:{cursor:t.nextCursor},update:s}},m=(t,n=Date.now())=>{const o=[];for(const s of t.changes){const c=b(s.doc),a=s.op==="delete"?{...c,_lunora_deleted:!0}:c;o.push({record:{data:a,emitted_at:n,stream:s.table},type:"RECORD"})}return o.push({state:{data:{cursor:t.nextCursor}},type:"STATE"}),o};export{m as toAirbyteMessages,f as toFivetranResponse};
|
|
@@ -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.
|
|
3
|
+
"version": "1.0.0-alpha.290",
|
|
4
4
|
"description": "Lunora Worker runtime: the RPC router, shard resolver, and query coordinator",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -46,7 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/
|
|
49
|
+
"@lunora/bindings": "1.0.0-alpha.151",
|
|
50
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
+
"@lunora/observability": "^1.0.0-alpha.203",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.80",
|
|
53
|
+
"@lunora/wire": "1.0.0-alpha.6"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"@lunora/shard-engine": ">=1.0.0-alpha.135 <2.0.0-0",
|
|
57
|
+
"@lunora/workflow": ">=1.0.0-alpha.24 <2.0.0-0"
|
|
50
58
|
},
|
|
51
59
|
"engines": {
|
|
52
60
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { LunoraError } from './LunoraError-Bpb9EFJ3.mjs';
|
|
2
|
-
import { applyJurisdiction } from './applyJurisdiction-BkZtTkct.mjs';
|
|
3
|
-
|
|
4
|
-
const SHARD_REGISTRY_DO_NAME = "__lunora_shard_registry__";
|
|
5
|
-
const DEFAULT_REGISTRY_CACHE_TTL_MS = 3e4;
|
|
6
|
-
const REGISTRY_BASE_URL = "https://shard-registry.internal";
|
|
7
|
-
const decodeJson = async (response) => (
|
|
8
|
-
// Response.json() throws on non-JSON; the DO always returns JSON so this
|
|
9
|
-
// only surfaces if the DO route is misbehaving — let it bubble.
|
|
10
|
-
await response.json()
|
|
11
|
-
);
|
|
12
|
-
const createDynamicShardRegistry = (options) => {
|
|
13
|
-
const instanceName = options.instanceName ?? SHARD_REGISTRY_DO_NAME;
|
|
14
|
-
const cacheTtlMs = options.cacheTtlMs ?? DEFAULT_REGISTRY_CACHE_TTL_MS;
|
|
15
|
-
const cache = /* @__PURE__ */ new Map();
|
|
16
|
-
const namespace = applyJurisdiction(options.namespace, options.jurisdiction);
|
|
17
|
-
let cachedStub;
|
|
18
|
-
const stub = () => {
|
|
19
|
-
cachedStub ??= namespace.get(namespace.idFromName(instanceName));
|
|
20
|
-
return cachedStub;
|
|
21
|
-
};
|
|
22
|
-
const post = async (path, body) => stub().fetch(
|
|
23
|
-
new Request(`${REGISTRY_BASE_URL}${path}`, {
|
|
24
|
-
body: JSON.stringify(body),
|
|
25
|
-
headers: { "content-type": "application/json" },
|
|
26
|
-
method: "POST"
|
|
27
|
-
})
|
|
28
|
-
);
|
|
29
|
-
const get = async (path) => stub().fetch(new Request(`${REGISTRY_BASE_URL}${path}`, { method: "GET" }));
|
|
30
|
-
return {
|
|
31
|
-
invalidate(table) {
|
|
32
|
-
if (table === void 0) {
|
|
33
|
-
cache.clear();
|
|
34
|
-
} else {
|
|
35
|
-
cache.delete(table);
|
|
36
|
-
}
|
|
37
|
-
},
|
|
38
|
-
async listShardKeys(table) {
|
|
39
|
-
const now = Date.now();
|
|
40
|
-
const cached = cache.get(table);
|
|
41
|
-
if (cached && cached.expiresAt > now) {
|
|
42
|
-
return cached.shardKeys;
|
|
43
|
-
}
|
|
44
|
-
const response = await get(`/list?table=${encodeURIComponent(table)}`);
|
|
45
|
-
if (!response.ok) {
|
|
46
|
-
throw new LunoraError(`shard registry /list returned ${String(response.status)}`);
|
|
47
|
-
}
|
|
48
|
-
const { shardKeys } = await decodeJson(response);
|
|
49
|
-
if (cacheTtlMs > 0) {
|
|
50
|
-
cache.set(table, { expiresAt: now + cacheTtlMs, shardKeys });
|
|
51
|
-
}
|
|
52
|
-
return shardKeys;
|
|
53
|
-
},
|
|
54
|
-
async register(table, shardKey) {
|
|
55
|
-
const response = await post("/register", { shardKey, table });
|
|
56
|
-
if (!response.ok) {
|
|
57
|
-
throw new LunoraError(`shard registry /register returned ${String(response.status)}`);
|
|
58
|
-
}
|
|
59
|
-
cache.delete(table);
|
|
60
|
-
},
|
|
61
|
-
async snapshot() {
|
|
62
|
-
const response = await get("/snapshot");
|
|
63
|
-
if (!response.ok) {
|
|
64
|
-
throw new LunoraError(`shard registry /snapshot returned ${String(response.status)}`);
|
|
65
|
-
}
|
|
66
|
-
const { tables } = await decodeJson(response);
|
|
67
|
-
return tables;
|
|
68
|
-
},
|
|
69
|
-
async unregister(table, shardKey) {
|
|
70
|
-
const response = await post("/unregister", { shardKey, table });
|
|
71
|
-
if (!response.ok) {
|
|
72
|
-
throw new LunoraError(`shard registry /unregister returned ${String(response.status)}`);
|
|
73
|
-
}
|
|
74
|
-
cache.delete(table);
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
export { DEFAULT_REGISTRY_CACHE_TTL_MS, SHARD_REGISTRY_DO_NAME, createDynamicShardRegistry };
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { LunoraError as LunoraError$1, toErrorBody } from '@lunora/errors';
|
|
2
|
-
|
|
3
|
-
const toErrorResponse = (error) => {
|
|
4
|
-
const { body, redacted, status } = toErrorBody(error, { fallbackCode: "INTERNAL", redactedMessage: "Internal error" });
|
|
5
|
-
if (redacted) {
|
|
6
|
-
console.error("[lunora] internal error:", error);
|
|
7
|
-
}
|
|
8
|
-
return Response.json({ error: body }, {
|
|
9
|
-
headers: { "content-type": "application/json" },
|
|
10
|
-
status
|
|
11
|
-
});
|
|
12
|
-
};
|
|
13
|
-
class LunoraError extends LunoraError$1 {
|
|
14
|
-
constructor(message, options) {
|
|
15
|
-
super(options?.code ?? "INTERNAL", message, { cause: options?.cause, status: options?.status });
|
|
16
|
-
}
|
|
17
|
-
toResponse() {
|
|
18
|
-
return toErrorResponse(this);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export { LunoraError, toErrorResponse };
|