@lunora/observability 1.0.0-alpha.202 → 1.0.0-alpha.203
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/{NO_SENSITIVE_SCOPE-BeDNs95f.mjs → NO_SENSITIVE_SCOPE-DKzHJewk.mjs} +1 -1
- package/dist/packem_shared/{createDatabaseTally-DxF4KZNq.mjs → createDatabaseTally-fSQyp-qV.mjs} +1 -1
- package/dist/packem_shared/{createMetrics-8Kcf2_ep.mjs → createMetrics-DQynv3tU.mjs} +1 -1
- package/dist/packem_shared/request-log-BVf-TLws.mjs +26 -0
- package/package.json +1 -1
- package/dist/packem_shared/request-log-CgAdxe9y.mjs +0 -26
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as s,AUTH_METRICS_BUCKET_RETENTION as a,AUTH_METRICS_TABLE as o,ensureAuthMetricsTables as T,readAuthMetrics as E,recordAuthEvent as S}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs";import{createMetrics as i,createSpanCollector as c,createTracedFetch as n,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-
|
|
1
|
+
import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as s,AUTH_METRICS_BUCKET_RETENTION as a,AUTH_METRICS_TABLE as o,ensureAuthMetricsTables as T,readAuthMetrics as E,recordAuthEvent as S}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs";import{createMetrics as i,createSpanCollector as c,createTracedFetch as n,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-DQynv3tU.mjs";import{createDatabaseTally as A,formatTally as N,instrumentDatabase as p,instrumentSqlClient as C}from"./packem_shared/createDatabaseTally-fSQyp-qV.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as R,FUNCTION_METRICS_BUCKET_RETENTION as U,FUNCTION_METRICS_INDEX_TABLE as m,FUNCTION_METRICS_MAX_PATHS as l,FUNCTION_METRICS_READ_LIMIT as L,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as g,readFunctionMetricBuckets as O,readFunctionMetricIndexHits as H,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as h,recordFunctionMetric as v}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-Dha-40Hv.mjs";import{applyHostRootSpan as K,setHostSpanAttributes as q}from"./packem_shared/applyHostRootSpan-DToRfMn8.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Q,explainIssue as V,parseExplainIssueArgs as k}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as X,ISSUE_STATE_TABLE as j,ISSUE_STATUSES as w,upsertIssueState as z}from"./packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs";import{LogBuffer as W}from"./packem_shared/LogBuffer-DT7Nz0bA.mjs";import{MetricBuffer as Z}from"./packem_shared/MetricBuffer-BUw1hK3f.mjs";import{readMetricHistory as ee,recordMetricHistory as re}from"./packem_shared/readMetricHistory-BjPDSBkS.mjs";import{latencyBucketIndex as se,readQueryInsights as ae,readQueryMetrics as oe,recordQueryMetric as Te}from"./packem_shared/latencyBucketIndex--kZoW0vc.mjs";import{N as Se,R as _e,S as ie,a as ce,c as ne,e as Ie,b as ue,d as Me,m as Ae,p as Ne,r as pe,f as Ce,g as de,h as fe,s as Re,i as Ue}from"./packem_shared/request-log-BVf-TLws.mjs";import{MIN_ADMIN_TOKEN_LENGTH as le,MIN_AUTH_SECRET_LENGTH as Le,buildSecurityAudit as xe}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Fe,foldTraces as ge}from"./packem_shared/SpanBuffer-DhWVTyym.mjs";import{findDanglingReferences as He}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as be}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,s as AUTH_METRICS_BUCKET_MS,a as AUTH_METRICS_BUCKET_RETENTION,o as AUTH_METRICS_TABLE,Q as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,R as FUNCTION_METRICS_BUCKET_MS,U as FUNCTION_METRICS_BUCKET_RETENTION,m as FUNCTION_METRICS_INDEX_TABLE,l as FUNCTION_METRICS_MAX_PATHS,L as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,X as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,le as MIN_ADMIN_TOKEN_LENGTH,Le as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,Se as NO_SENSITIVE_SCOPE,_e as REQUEST_LOG_TABLE,ie as SENSITIVE_ARG_MASK,Fe as SpanBuffer,ce as appendRequestLogEntry,K as applyHostRootSpan,xe as buildSecurityAudit,A as createDatabaseTally,i as createMetrics,ne as createSensitiveScope,c as createSpanCollector,n as createTracedFetch,I as createTracer,u as dispatchRootSpan,Ie as emitLogEvent,ue as emitRequestLogEvent,T as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Me as ensureRequestLogTable,V as explainIssue,He as findDanglingReferences,ge as foldTraces,N as formatTally,p as instrumentDatabase,C as instrumentSqlClient,se as latencyBucketIndex,Ae as maskSensitiveArgs,g as mergeScanAttribution,k as parseExplainIssueArgs,Ne as parseLogArgs,E as readAuthMetrics,pe as readErrorIssues,O as readFunctionMetricBuckets,H as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,h as readFunctionMetricsTotals,ee as readMetricHistory,ae as readQueryInsights,oe as readQueryMetrics,Ce as readRequestLog,S as recordAuthEvent,v as recordFunctionMetric,re as recordMetricHistory,Te as recordQueryMetric,de as redactArgs,fe as redactCredentials,be as resolveTraceAnchor,Re as sensitiveNames,Ue as sensitiveValues,q as setHostSpanAttributes,z as upsertIssueState};
|
package/dist/packem_shared/{NO_SENSITIVE_SCOPE-BeDNs95f.mjs → NO_SENSITIVE_SCOPE-DKzHJewk.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as E,j as i,R as o,S as g,a as S,c as n,e as L,b as m,d as p,m as R,p as d,r as T,f as _,g as u,h as N,k as v,s as A,i as I}from"./request-log-
|
|
1
|
+
import{N as E,j as i,R as o,S as g,a as S,c as n,e as L,b as m,d as p,m as R,p as d,r as T,f as _,g as u,h as N,k as v,s as A,i as I}from"./request-log-BVf-TLws.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./prune-marker-CksedkkK.mjs";import"./run-sql-0aPgJkIw.mjs";export{E as NO_SENSITIVE_SCOPE,i as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as SENSITIVE_ARG_MASK,S as appendRequestLogEntry,n as createSensitiveScope,L as emitLogEvent,m as emitRequestLogEvent,p as ensureRequestLogTable,R as maskSensitiveArgs,d as parseLogArgs,T as readErrorIssues,_ as readRequestLog,u as redactArgs,N as redactCredentials,v as renderLogMessage,A as sensitiveNames,I as sensitiveValues};
|
package/dist/packem_shared/{createDatabaseTally-DxF4KZNq.mjs → createDatabaseTally-fSQyp-qV.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as T}from"./otlp-DR7601NL.mjs";import{N as l,g}from"./request-log-
|
|
1
|
+
import{o as T}from"./otlp-DR7601NL.mjs";import{N as l,g}from"./request-log-BVf-TLws.mjs";import{toErrorType as E}from"./resolveTraceAnchor-DDAPZRBB.mjs";const h=new Set(["ALTER","ANALYZE","BEGIN","CALL","COMMIT","COPY","CREATE","DEALLOCATE","DELETE","DESCRIBE","DO","DROP","EXECUTE","EXPLAIN","GRANT","INSERT","LISTEN","LOCK","MERGE","NOTIFY","PREPARE","REFRESH","RELEASE","REPLACE","REVOKE","ROLLBACK","SAVEPOINT","SELECT","SET","SHOW","START","TABLE","TRUNCATE","UNLISTEN","UPDATE","VACUUM","VALUES","WITH"]),f="OTHER",O=/^[a-z]+/iu,R=e=>{if(typeof e!="string")return f;let t=0;for(;t<e.length;){const o=e.charAt(t);if(o==="("||o.trim()==="")t+=1;else if(e.startsWith("--",t)){const a=e.indexOf(`
|
|
2
2
|
`,t);if(a===-1)return f;t=a+1}else if(e.startsWith("/*",t)){const a=e.indexOf("*/",t+2);if(a===-1)return f;t=a+2}else break}const r=O.exec(e.slice(t,t+16))?.[0].toUpperCase();return r!==void 0&&h.has(r)?r:f},S=e=>e??"other_sql",m=100,A=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),I=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),P=(e,t)=>{if(!I.has(e))return;const r=t[0];return typeof r=="string"&&r.length>0?r:void 0},M=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),L=(e,t,r)=>{const o=(t.scope??l).text(M(e));return r==="redact"?g(o,t.captureRaw):t.captureRaw===!0?o:E(e)},u=(e,t,r)=>{const{durationMs:o,failure:a,startTs:n}=t;return{durationMs:o,...a===void 0?{}:{error:{message:L(a,e,r),type:E(a)}},functionPath:e.functionPath,kind:"client",ok:a===void 0,parentSpanId:e.anchor.rootSpanId,...e.anchor.rayId===void 0?{}:{rayId:e.anchor.rayId},shardKey:e.shardKey,spanId:T(8),startTs:n,traceId:e.anchor.traceId,userId:e.userId()}},y=async(e,t,r,o)=>{const a=Date.now();let n,s;const c=(e.scope??l).hold();try{return s=await r(),s}catch(d){throw n=d,d}finally{const d=Date.now()-a,{tally:i}=e;i.calls+=1,i.durationMs+=d,i.perOperation[t]=(i.perOperation[t]??0)+1,n!==void 0&&(i.errors+=1);try{e.mode==="spans"&&(i.spansEmitted>=m?i.spansTruncated=!0:(i.spansEmitted+=1,e.record(o({durationMs:d,failure:n,result:s,startTs:a}))))}catch{}c()}},p=(e,t,r)=>{const o=new Map;return new Proxy({},{get(a,n){const s=Reflect.get(e,n,e);if(typeof n!="string"||typeof s!="function"||!t(n))return s;const c=s,d=o.get(n);if(d?.original===c)return d.instrumented;const i=r(n,c.bind(e));return o.set(n,{instrumented:i,original:c}),i},getOwnPropertyDescriptor(a,n){const s=Reflect.getOwnPropertyDescriptor(e,n);return s===void 0?void 0:{...s,configurable:!0}},defineProperty(a,n,s){return s.configurable===!1?!1:Reflect.defineProperty(e,n,s)},deleteProperty(a,n){return Reflect.deleteProperty(e,n)},getPrototypeOf(){return Reflect.getPrototypeOf(e)},has(a,n){return Reflect.has(e,n)},ownKeys(){return Reflect.ownKeys(e)},set(a,n,s){return Reflect.set(e,n,s,e)}})},_=(e,t)=>t.mode==="off"?e:p(e,r=>A.has(r),(r,o)=>async(...a)=>{const n=P(r,a);return y(t,r,()=>o(...a),s=>({...u(t,s,"redact"),attributes:{"db.operation.name":r,...n===void 0?{}:{"db.collection.name":n},"db.system.name":"sqlite"},name:n===void 0?`db.${r}`:`db.${r} ${n}`}))}),C=(e,t)=>{if(t.mode==="off")return e;const r=S(e.dbSystem);return p(e,o=>o==="query",(o,a)=>async(...n)=>{const s=R(n[0]);return y(t,s,()=>a(...n),c=>({...u(t,c,"type-only"),attributes:{"db.operation.name":s,...Array.isArray(c.result)?{"db.response.returned_rows":c.result.length}:{},"db.system.name":r},name:`sql.${s}`}))})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),k=(e,t="db")=>{const r={[`${t}.calls`]:e.calls,[`${t}.duration_ms`]:e.durationMs};e.errors>0&&(r[`${t}.errors`]=e.errors),e.spansTruncated&&(r[`${t}.spans_truncated`]=!0);for(const[o,a]of Object.entries(e.perOperation))r[`${t}.op.${o}`]=a;return r};export{D as createDatabaseTally,k as formatTally,_ as instrumentDatabase,C as instrumentSqlClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as k,g as O,h as w,n as y}from"./request-log-
|
|
1
|
+
import{N as k,g as O,h as w,n as y}from"./request-log-BVf-TLws.mjs";import{o as L,b as X,O as B}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as V}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as P}from"./resolveTraceAnchor-DDAPZRBB.mjs";const G=/[\w.-]/u,J=t=>{let e="";for(const n of t)e+=G.test(n)?n:"_";return e},Q=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=J(t.name),n={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(n[`gen_ai.evaluation.${e}.label`]=t.label),n},W=t=>{const e=Object.keys(t);if(e.length===0||!e.every(s=>s==="attributes"||s==="kind"||s==="links"))return!1;const{kind:n}=t;return n===void 0||Object.hasOwn(B,n)},Y=128,Z=128,K=128,b=(t,e)=>{if(e===void 0)return;let n=Object.keys(t).length;for(const[s,d]of Object.entries(e)){const o=!Object.hasOwn(t,s);o&&n>=K||(o&&(n+=1),t[s]=d)}},F=(t,e)=>{const n=y(t,void 0,e);if(n===void 0||Object.keys(n).length<=K)return n;const s={};return b(s,n),s},U=t=>t?"full":"headline",tt=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},et=t=>{try{return new URL(t).host}catch{return t}},nt=(t,e)=>{try{return t(new URL(e))}catch{return!1}},rt=t=>t===void 0?{}:W(t)?t:{attributes:t},j=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},st=(t,e=!1,n=k)=>{const s={attributes:{},events:[],links:[]},d=U(e),o={spanContext:()=>t,addEvent:(r,a)=>{if(s.events.length>=Y)return;const c=w(n.fields(F(a,d)),e);s.events.push({...c===void 0?{}:{attributes:c},name:n.name(r),ts:Date.now()})},addLink:r=>{if(s.links.length>=Z)return;const a=w(n.fields(F(r.attributes,d)),e);s.links.push({...a===void 0?{}:{attributes:a},spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{b(s.attributes,n.fields(y(Q(r))))},recordException:r=>{const a=r instanceof Error?r.message:String(r);o.addEvent("exception",{"exception.message":O(a,e),...e&&r instanceof Error&&typeof r.stack=="string"?{"exception.stacktrace":r.stack}:{},"exception.type":P(r)})},setAttribute:(r,a)=>{b(s.attributes,n.fields(y({[r]:a},void 0,d)))},setAttributes:r=>{b(s.attributes,n.fields(y(r,void 0,d)))}};return{collected:s,handle:o}},dt=t=>{const{anchor:e,captureRaw:n=!1,fuseHostSpans:s,functionPath:d,record:o,resolveHostTracing:r,scope:a=k,shardKey:c,userId:m}=t,l=g=>async(E,T,u,x)=>{const p=x?.spanId??L(8),I=x?.parentSpanId??g,_=Date.now(),i=rt(u),M=a.fields(y(i.attributes,void 0,U(n))),z=a.name(E),{collected:A,handle:C}=st({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:p,traceId:e.traceId},n,a),q=a.hold(),R=async S=>{let f=!0,v;try{return await T(l(p),C)}catch(h){f=!1;const N=a.text(h instanceof Error?h.message:String(h));throw v={message:O(N,n),type:P(h)},h}finally{const h=Date.now()-_,N=m(),H={};b(H,M),b(H,A.attributes);const $=w(H,n),D=a.value([...i.links??[],...A.links]);try{o({...Object.keys($).length===0?{}:{attributes:$},durationMs:h,...A.events.length===0?{}:{events:A.events},...v===void 0?{}:{error:v},functionPath:d,...i.kind===void 0||i.kind==="internal"?{}:{kind:i.kind},...D.length===0?{}:{links:D},name:z,ok:f,parentSpanId:I,...j(e),shardKey:c,spanId:p,startTs:_,userId:N})}catch{}if(S!==void 0)try{V(S,{attributes:$,durationMs:h,error:v,functionPath:d,ok:f,shardKey:c,userId:N})}catch{}q()}};if(s===!0&&r!==void 0){let S=!1;try{const f=await r();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(z,v=>(S=!0,R(v)))}catch(f){if(S)throw f}}return await R()};return l(e.rootSpanId)},lt=(t,e)=>{const{anchor:n,captureRaw:s=!1,functionPath:d,propagate:o=!0,record:r,scope:a=k,shardKey:c,userId:m}=t;return async(l,g)=>{const E=L(8),T=Date.now(),u=new Request(l,g);(typeof o=="function"?nt(o,u.url):o)&&u.headers.set("traceparent",X(n.traceId,E,n.sampled??!0));let p,I;const _=a.hold();try{const i=await e(u);return I=i.status,i.ok||(p={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const M=a.text(i instanceof Error?i.message:String(i));throw p={message:O(M,s),type:P(i)},i}finally{try{r({attributes:{"http.request.method":u.method,...I===void 0?{}:{"http.response.status_code":I},"url.full":a.text(tt(u.url))},durationMs:Date.now()-T,...p===void 0?{}:{error:p},functionPath:d,kind:"client",name:a.text(`${u.method} ${et(u.url)}`),ok:p===void 0,parentSpanId:n.rootSpanId,...j(n),shardKey:c,spanId:E,startTs:T,userId:m()})}catch{}_()}}},ut=t=>{const{functionPath:e,record:n,scope:s=k,shardKey:d}=t,o=(r,a,c,m)=>{if(!Number.isFinite(c))return;const l=w(s.fields(y(m)));try{n({...l===void 0?{}:{attributes:l},functionPath:e,kind:r,name:s.name(a),shardKey:d,ts:Date.now(),value:c})}catch{}};return{count:(r,a=1,c)=>{o("counter",r,a,c)},gauge:(r,a,c)=>{o("gauge",r,a,c)},record:(r,a,c)=>{o("histogram",r,a,c)}}},pt=t=>{const{anchor:e,captureRaw:n=!1,collected:s,durationMs:d,failure:o,functionPath:r,scope:a=k,shardKey:c,startTs:m,userId:l}=t,g=w(s?.attributes??{},n);return{...Object.keys(g).length===0?{}:{attributes:g},dispatch:!0,durationMs:d,...s===void 0||s.events.length===0?{}:{events:s.events},...o===void 0?{}:{error:{message:O(a.text(o.thrown instanceof Error?o.thrown.message:String(o.thrown)),n),type:P(o.thrown)}},functionPath:r,...s===void 0||s.links.length===0?{}:{links:s.links},name:r,ok:o===void 0,parentSpanId:"",...j(e),shardKey:c,spanId:e.rootSpanId,startTs:m,userId:l}};export{ut as createMetrics,st as createSpanCollector,lt as createTracedFetch,dt as createTracer,pt as dispatchRootSpan,j as spanAnchorFields};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{fingerprintError as q}from"@lunora/fingerprint";import{createRedactor as he,standardRules as Ee}from"@visulima/redact";import{readIssueStates as me}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{p as Ae}from"./prune-marker-CksedkkK.mjs";import{r as m}from"./run-sql-0aPgJkIw.mjs";const Y=e=>{const t=String(e.name),s=String(e.message);return s===""?t:`${t}: ${s}`},N=e=>{if(typeof e=="string")return e;if(e instanceof Error)return Y(e);try{return JSON.stringify(e)??String(e)}catch{return String(e)}},ye=4,_e=10,be=3584,Te=4,P=512,v=8,Oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>{if(!Oe(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=(e,t=0,s=new WeakSet)=>e instanceof Error?!0:typeof e!="object"||e===null||t>=v||s.has(e)?!1:(s.add(e),Array.isArray(e)?e.some(n=>w(n,t+1,s)):Q(e)&&Object.values(e).some(n=>w(n,t+1,s))),Ne=e=>{if(typeof e=="bigint")return String(e);if(typeof e!="object"||e===null)return e;try{return JSON.stringify(e),e}catch{return}},Re=(e,t,s)=>{if(e!==void 0)return t==="none"||t==="minimal"||t==="root"&&s>0?"":t==="short"?e.split(`
|
|
2
|
+
`).slice(0,Te+1).join(`
|
|
3
|
+
`):e},Ie=(e,t,s,n)=>({errors:e,mask:s,memo:new WeakMap,mode:t,path:new Set}),ee=(e,t,s)=>{if(!t.path.has(e)){if(t.memo.has(e))return t.memo.get(e);t.path.add(e);try{const n=s();return t.memo.set(e,n),n}finally{t.path.delete(e)}}},L=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},te=(e,t,s)=>t.path.has(e)||s>ye?{message:e.message,name:e.name}:ee(e,t,()=>{const n=f=>f instanceof Error?te(f,t,s+1):(t.child??(u=>T(u,t,0,s+1)))(f),r=t.mode==="minimal",i=f=>f.length>P?`${f.slice(0,P)}…`:f,c=f=>r&&!(f instanceof Error)?i(N(f)):n(f),a={message:r?i(e.message):e.message,name:e.name};if(!r)for(const[f,u]of Object.entries(e))f!=="message"&&f!=="name"&&L(a,f,n(u));const d=Re(e.stack,t.mode,s);return d!==void 0&&(a.stack=d),e.cause!==void 0&&(a.cause=c(e.cause)),e instanceof AggregateError&&Array.isArray(e.errors)&&(a.errors=e.errors.slice(0,_e).map(f=>c(f))),t.mask(a)}),T=(e,t,s,n)=>e instanceof Error?t.errors==="full"?te(e,t,n):Y(e):typeof e!="object"||e===null||s>=v||!(Array.isArray(e)||Q(e))?Ne(e):ee(e,t,()=>Array.isArray(e)?e.map(r=>T(r,t,s+1,n)):Object.fromEntries(Object.entries(e).map(([r,i])=>[r,T(i,t,s+1,n)]))),se=e=>e,we=(e,t,s)=>{const n=o=>JSON.stringify(T(e,Ie(t,o,s),0,0)),r=o=>o===void 0||o.length<=be,i=n("all");if(t==="headline"||r(i))return i;const c=n("minimal");if(!r(c))return c;for(const o of["root","short","none"]){const a=n(o);if(r(a))return a}return c},C=(e,t="headline",s=se)=>{if(typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;try{return!w(e)||t==="headline"&&e instanceof Error?N(e):we(e,t,s)??String(e)}catch{return String(e)}},U=(e,t,s="headline",n=se)=>{if(e===void 0&&t===void 0)return;const r={};if(t!==void 0)for(const[i,c]of Object.entries(t))L(r,i,C(c,s,n));if(e!==void 0)for(const[i,c]of Object.entries(e))L(r,i,C(c,s,n));return Object.keys(r).length===0?void 0:r},Le=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),ke=new Set(["card","pass","pin","session"]),Me=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),xe=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),je=new Set(["card no","connection string","database url","one time"]),$e=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],De=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Pe=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),Ce=new Set(["max","min","num","total"]),R=4096,Ue=128,Ge=16384,g="<REDACTED>",Ve="[redaction budget exceeded]",Fe=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),G=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,He=(e,t)=>{const s=G(e[t]),n=t>0?G(e[t-1]):void 0;if(Le.has(s))return s;if(n!==void 0){if(s==="key"&&Me.has(n))return"key";if(s==="code"&&xe.has(n))return"code";if(je.has(`${n} ${s}`))return`${n} ${s}`}return $e.some(r=>s.endsWith(r))?s:void 0},re=e=>{const t=Fe(e);if(t.length===0)return"none";const s=Pe.has(t.at(-1))||Ce.has(t[0]);for(let n=t.length-1;n>=0;n-=1){const r=He(t,n);if(r!==void 0)return s?"count-secret":t.slice(n+1).every(i=>De.has(i))?ke.has(r)&&n===t.length-1?"scalar-secret":"secret":"none"}return"none"},Je=e=>typeof e=="boolean"||e===null||e===void 0?e:g,We=e=>{const t=e.indexOf("://")+3,s=e.slice(t),n=s.split(/[?#]/,1)[0],r=n.lastIndexOf("@"),i=n.indexOf(":"),c=n.indexOf("/"),o=i!==-1&&/^\d+$/.test(n.slice(i+1,c===-1?void 0:c)),a=i!==-1&&!o&&(c===-1||i<c);if(r===-1&&a&&s.includes("@",n.length))return e.slice(0,t);const d=r!==-1&&(c===-1||r<c||i!==-1&&i<r&&!o);return`${e.slice(0,t)}${d?n.slice(r+1):n}`},Xe=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,ze=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Be=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,ne=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,oe=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],Ke=String.raw`(?<=^|[^\w-]|${ne})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Ze=new RegExp([...oe.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${ne})${t}${e}`),Ke].join("|"),"g"),qe=new RegExp([...oe.map(({prefix:e})=>e),"eyJ"].join("|")),Ye=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,A=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,V=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,F=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ve=e=>{let t="",s=0;A.lastIndex=0;for(let n=A.exec(e);n!==null;n=A.exec(e)){const r=re(n[2]),i=n.index+n[0].length;V.lastIndex=i;const c=r==="none"?null:V.exec(e);if(c===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){A.lastIndex=Math.max(i,n.index+1);continue}const o=c[0],a=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=i+o.length;a===""&&n[3]===":"&&(F.lastIndex=d,d+=F.exec(e)?.[0].length??0),t+=`${e.slice(s,i)}${a}${g}${o.length>a.length&&o.endsWith(a)?a:""}`,s=d,A.lastIndex=s}return t+e.slice(s)},Qe=/[:=@]|basic|bearer|digest|-u\b|--/i,et=e=>{const t=qe.test(e);if(!t&&!Qe.test(e))return e;const s=e.replaceAll(ze,`-----BEGIN $1-----${g}`).replaceAll(Xe,We).replaceAll(Be,`$1 ${g}`);return ve((t?s.replaceAll(Ze,g):s).replaceAll(Ye,`$1$2$3${g}`))},tt=(e,t)=>{if(t.remaining<=0)return Ve;const s=e.slice(0,R+Ue);t.remaining-=s.length;const n=et(s);return n.length>R||e.length>s.length?`${n.slice(0,R)}…[truncated]`:n},st=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),y=Symbol("no-json"),rt=e=>{const{toJSON:t}=e;if(typeof t!="function")return y;try{const s=t.call(e);return s===e?y:s}catch{return y}},nt=32,b=(e,t,s,n,r)=>{if(typeof e=="string")return n?g:tt(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&st(e))return e;if(t.has(e)||s>=nt)return g;const i=Array.isArray(e)?y:rt(e);if(i!==y){t.add(e);const o=b(i,t,s+1,n,r);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>b(o,t,s+1,n,r)):Object.fromEntries(Object.entries(e).map(([o,a])=>{const d=re(o);return d==="secret"||d==="scalar-secret"&&(typeof a!="object"||a===null)?[o,Je(a)]:[o,b(a,t,s+1,d==="count-secret"&&(typeof a=="string"||Array.isArray(a)),r)]}));return t.delete(e),c},O=e=>b(e,new WeakSet,0,!1,{remaining:Ge}),ot=(e,t)=>{if(e.size<t)return;const s=e.keys().next().value;s!==void 0&&e.delete(s)},it=32,ct=(e,t)=>{let s=t,n;const r=(c,o,a)=>{const d=Object.getOwnPropertyDescriptor(c,o);return d!==void 0&&"value"in d&&n(d.value,a+1)},i=(c,o)=>{if(Array.isArray(c)){for(let d=0;d<c.length;d+=1)if(!r(c,d,o))return!1;return!0}const a=Object.getPrototypeOf(c);if(a!==null&&a!==Object.prototype)return!1;for(const d of Object.keys(c))if(s-=d.length,s<0||!r(c,d,o))return!1;return!0};return n=(c,o)=>(s-=1,s<0?!1:c===null||typeof c=="boolean"?!0:typeof c=="string"?(s-=c.length,s>=0):typeof c=="number"?Number.isFinite(c):typeof c!="object"||o>=it||"toJSON"in c?!1:i(c,o)),n(e,0)},S="__lunora_reqlog__",at=6e4,M=1e3,ie="lunora",ft=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],dt=he(Ee,{exclude:["pass"]}),Jt=(e,t=!1)=>t||e===null||e===void 0?e:O(e),h=(e,t=!1)=>t||e===null||e===void 0?e:dt(O(e)),l="«sensitive»",Wt=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,n])=>[s,t.has(s)?l:n])),lt=8,ce=4,ae=3,x=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),ut=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${x(e)}(?![\p{L}\p{N}])`,"gu"),pt=e=>new RegExp(String.raw`(?<=["'])${x(e)}(?=["'])`,"gu"),H=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${x(e)}(?![\p{L}\p{N}])`,"gu"),gt=new Set(["false","true"]),St=new RegExp("^\\p{N}+$","u"),j=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<ce?[e]:[e,t]},fe=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},de=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),le=e=>{const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join(""),s=btoa(Array.from(e,r=>String.fromCodePoint(r)).join("")),n=s.replaceAll("+","-").replaceAll("/","_").split("=")[0]??"";return[...new Set([s,n,t,t.toUpperCase()])]},ht=e=>{const t=de(e);if(t.length===0)return[];const s=fe(t);return[...s===void 0||s.length===0?[]:j(s),...le(t)]},Et=e=>e instanceof Error&&e.message.length>0?j(e.message):[],mt=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],At=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="string")r.length>0&&t.push(...j(r));else if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")t.push(String(r));else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))t.push(...ht(r));else if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r),t.push(...Et(r));for(const i of Object.values(r))n.push(i);n.push(...mt(r))}}},Xt=(e,t)=>{const s=[];for(const n of t)if(Object.hasOwn(e,n)){const r=e[n];typeof r=="object"&&r!==null&&!(r instanceof ArrayBuffer)&&!ArrayBuffer.isView(r)&&s.push(N(r)),At(r,s)}return s},yt=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),_t=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r);for(const i of yt(r))t.push(i);for(const i of Object.values(r))n.push(i)}}},zt=(e,t)=>{const s=[];for(const n of t)Object.hasOwn(e,n)&&_t(e[n],s);return s},bt=(e,t)=>{if(gt.has(t))return e.replaceAll(pt(t),l).replaceAll(H(t,"="),l);if(t.length>=ce)return e.replaceAll(t,l);if(t.length>=ae)return e.includes(t)?e.replaceAll(ut(t),l):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(l));return St.test(t)?s:s.replaceAll(H(t,"=:"),l)},_=(e,t)=>{if(t.includes(e))return l;let s=e;for(const n of t.toSorted((r,i)=>i.length-r.length))s=bt(s,n);return s},Tt={names:new Set,texts:[]},J=e=>e.texts.length>0||e.names.size>0,Ot=(e,t)=>t.names.has(e)?l:_(e,t.texts),Nt=(e,t)=>{if(!Object.hasOwn(e,t))return t;let s=2;for(;Object.hasOwn(e,`${t}#${String(s)}`);)s+=1;return`${t}#${String(s)}`},Rt=(e,t,s)=>{if(Array.isArray(e)){const i=e.map(c=>s(c));return i.some((c,o)=>c!==e[o])?i:e}let n=!1;const r={};for(const[i,c]of Object.entries(e)){const o=s(c),a=Nt(r,Ot(i,t));n||=o!==c||a!==i,r[a]=o}return n?r:e},It=(e,t)=>{const s=de(e);if(s.length===0)return!1;const n=fe(s);return n!==void 0&&t.texts.some(r=>n.includes(r))||le(s).some(r=>_(r,t.texts)!==r)},k=(e,t,s,n=new Set)=>{if(typeof e=="string")return _(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return It(e,t)?l:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const i=String(e);return i.length>=ae&&t.texts.includes(i)?l:e}if(e instanceof Error){const i=String(e),c=_(i,t.texts);return c===i?e:c}if(typeof e!="object"||e===null)return e;if(s>=lt||n.has(e))return l;n.add(e);const r=Rt(e,t,i=>k(i,t,s+1,n));return n.delete(e),r},wt=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},n=!1,r=0;const i=()=>{n&&r===0&&(s=Tt)},c=o=>s.texts.length===0?o:_(o,s.texts);return{add(o,a=[]){!n&&(o.length>0||a.length>0)&&(s={names:new Set([...s.names,...a]),texts:[...new Set([...s.texts,...o])]})},clear(){n=!0,i()},hold(){r+=1;let o=!1;return()=>{o||(o=!0,r-=1,i())}},fields:o=>o===void 0||!J(s)?o:k(o,s,0),name:o=>s.names.has(o)?l:c(o),text:c,value:o=>J(s)?k(o,s,0):o}},Bt={...wt([]),add:()=>{}},W=new WeakSet,$=e=>{if(!W.has(e)){m(e,`CREATE TABLE IF NOT EXISTS "${S}" (
|
|
4
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
+
ts REAL NOT NULL,
|
|
6
|
+
function_path TEXT NOT NULL,
|
|
7
|
+
shard_key TEXT,
|
|
8
|
+
user_id TEXT,
|
|
9
|
+
identity TEXT,
|
|
10
|
+
args TEXT,
|
|
11
|
+
outcome TEXT NOT NULL,
|
|
12
|
+
error_message TEXT,
|
|
13
|
+
error_fingerprint TEXT,
|
|
14
|
+
trace_id TEXT,
|
|
15
|
+
deployment_id TEXT,
|
|
16
|
+
version_tag TEXT,
|
|
17
|
+
duration_ms REAL NOT NULL,
|
|
18
|
+
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
19
|
+
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
20
|
+
cache_hit INTEGER,
|
|
21
|
+
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
22
|
+
)`);for(const t of ft)try{m(e,`ALTER TABLE "${S}" ADD COLUMN ${t}`)}catch{}W.add(e)}},X=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Lt=e=>e===void 0?null:e?1:0,kt=256,z=1024,I=new Map,ue=e=>{if(!ct(e,z))return;const t=JSON.stringify(e);if(t.length>z)return;const s=I.get(t);if(s!==void 0)return s;const n=JSON.stringify(h(e)),r={json:n,value:JSON.parse(n)};return ot(I,kt),I.set(t,r),r},B=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?JSON.stringify(h(e,t)):s.json},K=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?h(e,t):s.value},Kt=(e,t,s={})=>{$(e);const n=s.captureRaw??!1,r=s.retention??M,i=t.outcome==="error"&&t.errorMessage!==void 0?q({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;m(e,`INSERT INTO "${S}"
|
|
23
|
+
(ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
|
|
24
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:B(t.identity,n),t.redactedArgs===void 0?null:B(t.redactedArgs,n),t.outcome,t.errorMessage===void 0?null:h(t.errorMessage,n),i??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,X(t.tablesRead),X(t.tablesWritten),Lt(t.cacheHit),t.subscriptionsReRun??0),Ae(e,Math.floor(t.ts/at),"request-log",()=>{m(e,`DELETE FROM "${S}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${S}")`,r)})},Zt=(e,t={})=>{const s=t.captureRaw??!1,n={args:e.redactedArgs===void 0?void 0:K(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:h(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:K(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:ie,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},r=JSON.stringify(n);e.outcome==="error"?console.error(r):console.log(r)},Mt="log",xt=e=>e.map(t=>N(t)).join(" "),jt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},qt=(e,t)=>e.length===2&&typeof e[0]=="string"&&jt(e[1])?{fields:U(e[1],t,"full",O),message:e[0]}:{fields:U(void 0,t,"full",O),message:xt(e)},Yt=(e,t={})=>{const s=t.captureRaw??!1,n={fields:e.fields===void 0?void 0:h(e.fields,s),function:e.functionPath,level:e.level,message:h(e.message,s),rayId:e.rayId,shard:e.shardKey,source:ie,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Mt,userId:e.userId};let r;try{r=JSON.stringify(n)}catch{r=JSON.stringify({...n,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(r):e.level==="warn"?console.warn(r):console.log(r)},$t=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,pe=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push($t("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},Z=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},Dt=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pt=e=>{try{return JSON.parse(e)}catch{return}},vt=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["seq > ?"],r=[t.sinceSeq??0];if(pe(n,r,t),t.outcome!==void 0&&(n.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);n.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),r.push(o,o)}r.push(s);const i=t.sinceSeq===void 0?"DESC":"ASC";return m(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
|
|
25
|
+
FROM "${S}" WHERE ${n.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,...r).toArray().map(o=>{const a={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:Z(o.tables_read),tablesWritten:Z(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(a.shardKey=o.shard_key),o.user_id!==null&&(a.userId=o.user_id),o.identity!==null){const d=Dt(o.identity);d!==void 0&&(a.identity=d)}if(o.args!==null){const d=Pt(o.args);d!==void 0&&(a.redactedArgs=d)}return o.error_message!==null&&(a.errorMessage=o.error_message),o.cache_hit!==null&&(a.cacheHit=o.cache_hit===1),o.trace_id!==null&&(a.traceId=o.trace_id),o.deployment_id!==null&&(a.deploymentId=o.deployment_id),o.version_tag!==null&&(a.versionTag=o.version_tag),a})},Ct=(e,t)=>{const s=me(e,[...t.keys()]);for(const n of t.values()){const r=s.get(n.hash);r!==void 0&&(n.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(n.assignee=r.assignee),r.severity!==void 0&&(n.severity=r.severity),n.status=r.status==="resolved"&&n.lastSeen>r.updatedAt?"open":r.status)}},Qt=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["outcome = 'error'"],r=[];pe(n,r,t),r.push(s);const i=m(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
26
|
+
FROM "${S}" WHERE ${n.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),c=new Map,o=new Map;for(const f of i){const u=f.error_message??"",{culprit:ge,hash:Se,title:D}=q({functionPath:f.function_path,message:u}),E=f.error_fingerprint??Se,p=c.get(E);if(p===void 0){c.set(E,{count:1,culprit:ge,firstSeen:f.ts,hash:E,lastSeen:f.ts,sampleMessage:u,status:"open",title:D}),o.set(E,f.ts);continue}p.count+=1,p.firstSeen=Math.min(p.firstSeen,f.ts),p.lastSeen=Math.max(p.lastSeen,f.ts),f.ts>(o.get(E)??Number.NEGATIVE_INFINITY)&&(o.set(E,f.ts),p.sampleMessage=u,p.title=D)}Ct(e,c);const a=[...c.values()];return(t.status===void 0?a:a.filter(f=>f.status===t.status)).toSorted((f,u)=>u.lastSeen-f.lastSeen)};export{Bt as N,S as R,l as S,Kt as a,Zt as b,wt as c,$ as d,Yt as e,vt as f,h as g,Jt as h,Xt as i,M as j,xt as k,Wt as m,U as n,qt as p,Qt as r,zt as s};
|
package/package.json
CHANGED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{fingerprintError as Y}from"@lunora/fingerprint";import{createRedactor as he,standardRules as Ee}from"@visulima/redact";import{readIssueStates as me}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{p as Ae}from"./prune-marker-CksedkkK.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const k=e=>{if(typeof e=="string")return e;if(e instanceof Error)return String(e);try{return JSON.stringify(e)??String(e)}catch{return String(e)}},ye=4,_e=10,be=3584,Te=4,P=512,Oe=["all","root","short","none","minimal"],v=8,Ne=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>{if(!Ne(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},I=(e,t=0,s=new WeakSet)=>e instanceof Error?!0:typeof e!="object"||e===null||t>=v||s.has(e)?!1:(s.add(e),Array.isArray(e)?e.some(r=>I(r,t+1,s)):Q(e)&&Object.values(e).some(r=>I(r,t+1,s))),Re=e=>{if(typeof e=="bigint")return String(e);if(typeof e!="object"||e===null)return e;try{return JSON.stringify(e),e}catch{return}},Ie=(e,t,s)=>{if(e!==void 0)return t==="none"||t==="minimal"||t==="root"&&s>0?"":t==="short"?e.split(`
|
|
2
|
-
`).slice(0,Te+1).join(`
|
|
3
|
-
`):e},C=(e,t,s,r)=>({errors:e,mask:s,memo:new WeakMap,mode:t,path:new Set}),ee=(e,t,s)=>{if(!t.path.has(e)){if(t.memo.has(e))return t.memo.get(e);t.path.add(e);try{const r=s();return t.memo.set(e,r),r}finally{t.path.delete(e)}}},w=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},te=(e,t,s)=>t.path.has(e)||s>ye?{message:e.message,name:e.name}:ee(e,t,()=>{const r=c=>c instanceof Error?te(c,t,s+1):(t.child??(d=>_(d,t,0,s+1)))(c),n=t.mode==="minimal",i={message:n&&e.message.length>P?`${e.message.slice(0,P)}…`:e.message,name:e.name};if(!n)for(const[c,d]of Object.entries(e))c!=="message"&&c!=="name"&&w(i,c,r(d));const o=Ie(e.stack,t.mode,s);return o!==void 0&&(i.stack=o),e.cause!==void 0&&(i.cause=r(e.cause)),e instanceof AggregateError&&Array.isArray(e.errors)&&(i.errors=e.errors.slice(0,_e).map(c=>r(c))),t.mask(i)}),_=(e,t,s,r)=>e instanceof Error?t.errors==="full"?te(e,t,r):String(e):typeof e!="object"||e===null||s>=v||!(Array.isArray(e)||Q(e))?Re(e):ee(e,t,()=>Array.isArray(e)?e.map(n=>_(n,t,s+1,r)):Object.fromEntries(Object.entries(e).map(([n,a])=>[n,_(a,t,s+1,r)]))),se=e=>e,we=(e,t,s)=>{if(t==="headline")return JSON.stringify(_(e,C("headline","none",s),0,0));let r;for(const n of Oe)if(r=JSON.stringify(_(e,C("full",n,s),0,0)),r===void 0||r.length<=be)break;return r},U=(e,t="headline",s=se)=>{if(typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;try{return!I(e)||t==="headline"&&e instanceof Error?k(e):we(e,t,s)??String(e)}catch{return String(e)}},G=(e,t,s="headline",r=se)=>{if(e===void 0&&t===void 0)return;const n={};if(t!==void 0)for(const[a,i]of Object.entries(t))w(n,a,U(i,s,r));if(e!==void 0)for(const[a,i]of Object.entries(e))w(n,a,U(i,s,r));return Object.keys(n).length===0?void 0:n},Le=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),ke=new Set(["card","pass","pin","session"]),Me=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),xe=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),je=new Set(["card no","connection string","database url","one time"]),De=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],$e=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Pe=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),Ce=new Set(["max","min","num","total"]),N=4096,Ue=128,Ge=16384,p="<REDACTED>",Je="[redaction budget exceeded]",Ve=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),J=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,Fe=(e,t)=>{const s=J(e[t]),r=t>0?J(e[t-1]):void 0;if(Le.has(s))return s;if(r!==void 0){if(s==="key"&&Me.has(r))return"key";if(s==="code"&&xe.has(r))return"code";if(je.has(`${r} ${s}`))return`${r} ${s}`}return De.some(n=>s.endsWith(n))?s:void 0},re=e=>{const t=Ve(e);if(t.length===0)return"none";const s=Pe.has(t.at(-1))||Ce.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=Fe(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>$e.has(a))?ke.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},We=e=>typeof e=="boolean"||e===null||e===void 0?e:p,Xe=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),i=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,i===-1?void 0:i)),c=a!==-1&&!o&&(i===-1||a<i);if(n===-1&&c&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(i===-1||n<i||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},He=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,ze=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Be=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,ne=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,oe=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],Ke=String.raw`(?<=^|[^\w-]|${ne})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Ze=new RegExp([...oe.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${ne})${t}${e}`),Ke].join("|"),"g"),qe=new RegExp([...oe.map(({prefix:e})=>e),"eyJ"].join("|")),Ye=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,A=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,V=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,F=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ve=e=>{let t="",s=0;A.lastIndex=0;for(let r=A.exec(e);r!==null;r=A.exec(e)){const n=re(r[2]),a=r.index+r[0].length;V.lastIndex=a;const i=n==="none"?null:V.exec(e);if(i===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(i[0])){A.lastIndex=Math.max(a,r.index+1);continue}const o=i[0],c=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;c===""&&r[3]===":"&&(F.lastIndex=d,d+=F.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${c}${p}${o.length>c.length&&o.endsWith(c)?c:""}`,s=d,A.lastIndex=s}return t+e.slice(s)},Qe=/[:=@]|basic|bearer|digest|-u\b|--/i,et=e=>{const t=qe.test(e);if(!t&&!Qe.test(e))return e;const s=e.replaceAll(ze,`-----BEGIN $1-----${p}`).replaceAll(He,Xe).replaceAll(Be,`$1 ${p}`);return ve((t?s.replaceAll(Ze,p):s).replaceAll(Ye,`$1$2$3${p}`))},tt=(e,t)=>{if(t.remaining<=0)return Je;const s=e.slice(0,N+Ue);t.remaining-=s.length;const r=et(s);return r.length>N||e.length>s.length?`${r.slice(0,N)}…[truncated]`:r},st=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),y=Symbol("no-json"),rt=e=>{const{toJSON:t}=e;if(typeof t!="function")return y;try{const s=t.call(e);return s===e?y:s}catch{return y}},nt=32,T=(e,t,s,r,n)=>{if(typeof e=="string")return r?p:tt(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&st(e))return e;if(t.has(e)||s>=nt)return p;const a=Array.isArray(e)?y:rt(e);if(a!==y){t.add(e);const o=T(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const i=Array.isArray(e)?e.map(o=>T(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,c])=>{const d=re(o);return d==="secret"||d==="scalar-secret"&&(typeof c!="object"||c===null)?[o,We(c)]:[o,T(c,t,s+1,d==="count-secret"&&(typeof c=="string"||Array.isArray(c)),n)]}));return t.delete(e),i},O=e=>T(e,new WeakSet,0,!1,{remaining:Ge}),ot=(e,t)=>{if(e.size<t)return;const s=e.keys().next().value;s!==void 0&&e.delete(s)},it=32,at=(e,t)=>{let s=t,r;const n=(i,o,c)=>{const d=Object.getOwnPropertyDescriptor(i,o);return d!==void 0&&"value"in d&&r(d.value,c+1)},a=(i,o)=>{if(Array.isArray(i)){for(let d=0;d<i.length;d+=1)if(!n(i,d,o))return!1;return!0}const c=Object.getPrototypeOf(i);if(c!==null&&c!==Object.prototype)return!1;for(const d of Object.keys(i))if(s-=d.length,s<0||!n(i,d,o))return!1;return!0};return r=(i,o)=>(s-=1,s<0?!1:i===null||typeof i=="boolean"?!0:typeof i=="string"?(s-=i.length,s>=0):typeof i=="number"?Number.isFinite(i):typeof i!="object"||o>=it||"toJSON"in i?!1:a(i,o)),r(e,0)},g="__lunora_reqlog__",ct=6e4,M=1e3,ie="lunora",dt=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],ft=he(Ee,{exclude:["pass"]}),Wt=(e,t=!1)=>t||e===null||e===void 0?e:O(e),S=(e,t=!1)=>t||e===null||e===void 0?e:ft(O(e)),l="«sensitive»",Xt=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,r])=>[s,t.has(s)?l:r])),lt=8,ae=4,ce=3,x=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),ut=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${x(e)}(?![\p{L}\p{N}])`,"gu"),pt=e=>new RegExp(String.raw`(?<=["'])${x(e)}(?=["'])`,"gu"),W=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${x(e)}(?![\p{L}\p{N}])`,"gu"),gt=new Set(["false","true"]),St=new RegExp("^\\p{N}+$","u"),j=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<ae?[e]:[e,t]},de=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},fe=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),le=e=>{const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join(""),s=btoa(Array.from(e,n=>String.fromCodePoint(n)).join("")),r=s.replaceAll("+","-").replaceAll("/","_").split("=")[0]??"";return[...new Set([s,r,t,t.toUpperCase()])]},ht=e=>{const t=fe(e);if(t.length===0)return[];const s=de(t);return[...s===void 0||s.length===0?[]:j(s),...le(t)]},Et=e=>e instanceof Error&&e.message.length>0?j(e.message):[],mt=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],At=(e,t)=>{const s=new Set,r=[e];for(;r.length>0;){const n=r.pop();if(typeof n=="string")n.length>0&&t.push(...j(n));else if(typeof n=="number"||typeof n=="bigint"||typeof n=="boolean")t.push(String(n));else if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))t.push(...ht(n));else if(typeof n=="object"&&n!==null&&!s.has(n)){s.add(n),t.push(...Et(n));for(const a of Object.values(n))r.push(a);r.push(...mt(n))}}},Ht=(e,t)=>{const s=[];for(const r of t)if(Object.hasOwn(e,r)){const n=e[r];typeof n=="object"&&n!==null&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)&&s.push(k(n)),At(n,s)}return s},yt=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),_t=(e,t)=>{const s=new Set,r=[e];for(;r.length>0;){const n=r.pop();if(typeof n=="object"&&n!==null&&!s.has(n)){s.add(n);for(const a of yt(n))t.push(a);for(const a of Object.values(n))r.push(a)}}},zt=(e,t)=>{const s=[];for(const r of t)Object.hasOwn(e,r)&&_t(e[r],s);return s},bt=(e,t)=>{if(gt.has(t))return e.replaceAll(pt(t),l).replaceAll(W(t,"="),l);if(t.length>=ae)return e.replaceAll(t,l);if(t.length>=ce)return e.includes(t)?e.replaceAll(ut(t),l):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(l));return St.test(t)?s:s.replaceAll(W(t,"=:"),l)},b=(e,t)=>{if(t.includes(e))return l;let s=e;for(const r of t.toSorted((n,a)=>a.length-n.length))s=bt(s,r);return s},Tt={names:new Set,texts:[]},X=e=>e.texts.length>0||e.names.size>0,Ot=(e,t)=>t.names.has(e)?l:b(e,t.texts),Nt=(e,t)=>{if(!Object.hasOwn(e,t))return t;let s=2;for(;Object.hasOwn(e,`${t}#${String(s)}`);)s+=1;return`${t}#${String(s)}`},Rt=(e,t,s)=>{if(Array.isArray(e)){const a=e.map(i=>s(i));return a.some((i,o)=>i!==e[o])?a:e}let r=!1;const n={};for(const[a,i]of Object.entries(e)){const o=s(i),c=Nt(n,Ot(a,t));r||=o!==i||c!==a,n[c]=o}return r?n:e},It=(e,t)=>{const s=fe(e);if(s.length===0)return!1;const r=de(s);return r!==void 0&&t.texts.some(n=>r.includes(n))||le(s).some(n=>b(n,t.texts)!==n)},L=(e,t,s,r=new Set)=>{if(typeof e=="string")return b(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return It(e,t)?l:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const a=String(e);return a.length>=ce&&t.texts.includes(a)?l:e}if(e instanceof Error){const a=String(e),i=b(a,t.texts);return i===a?e:i}if(typeof e!="object"||e===null)return e;if(s>=lt||r.has(e))return l;r.add(e);const n=Rt(e,t,a=>L(a,t,s+1,r));return r.delete(e),n},wt=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},r=!1,n=0;const a=()=>{r&&n===0&&(s=Tt)},i=o=>s.texts.length===0?o:b(o,s.texts);return{add(o,c=[]){!r&&(o.length>0||c.length>0)&&(s={names:new Set([...s.names,...c]),texts:[...new Set([...s.texts,...o])]})},clear(){r=!0,a()},hold(){n+=1;let o=!1;return()=>{o||(o=!0,n-=1,a())}},fields:o=>o===void 0||!X(s)?o:L(o,s,0),name:o=>s.names.has(o)?l:i(o),text:i,value:o=>X(s)?L(o,s,0):o}},Bt={...wt([]),add:()=>{}},H=new WeakSet,D=e=>{if(!H.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${g}" (
|
|
4
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
-
ts REAL NOT NULL,
|
|
6
|
-
function_path TEXT NOT NULL,
|
|
7
|
-
shard_key TEXT,
|
|
8
|
-
user_id TEXT,
|
|
9
|
-
identity TEXT,
|
|
10
|
-
args TEXT,
|
|
11
|
-
outcome TEXT NOT NULL,
|
|
12
|
-
error_message TEXT,
|
|
13
|
-
error_fingerprint TEXT,
|
|
14
|
-
trace_id TEXT,
|
|
15
|
-
deployment_id TEXT,
|
|
16
|
-
version_tag TEXT,
|
|
17
|
-
duration_ms REAL NOT NULL,
|
|
18
|
-
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
19
|
-
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
20
|
-
cache_hit INTEGER,
|
|
21
|
-
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
22
|
-
)`);for(const t of dt)try{E(e,`ALTER TABLE "${g}" ADD COLUMN ${t}`)}catch{}H.add(e)}},z=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Lt=e=>e===void 0?null:e?1:0,kt=256,B=1024,R=new Map,ue=e=>{if(!at(e,B))return;const t=JSON.stringify(e);if(t.length>B)return;const s=R.get(t);if(s!==void 0)return s;const r=JSON.stringify(S(e)),n={json:r,value:JSON.parse(r)};return ot(R,kt),R.set(t,n),n},K=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?JSON.stringify(S(e,t)):s.json},Z=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?S(e,t):s.value},Kt=(e,t,s={})=>{D(e);const r=s.captureRaw??!1,n=s.retention??M,a=t.outcome==="error"&&t.errorMessage!==void 0?Y({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${g}"
|
|
23
|
-
(ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
|
|
24
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:K(t.identity,r),t.redactedArgs===void 0?null:K(t.redactedArgs,r),t.outcome,t.errorMessage===void 0?null:S(t.errorMessage,r),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,z(t.tablesRead),z(t.tablesWritten),Lt(t.cacheHit),t.subscriptionsReRun??0),Ae(e,Math.floor(t.ts/ct),"request-log",()=>{E(e,`DELETE FROM "${g}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${g}")`,n)})},Zt=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:Z(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:S(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:Z(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:ie,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},n=JSON.stringify(r);e.outcome==="error"?console.error(n):console.log(n)},Mt="log",xt=e=>e.map(t=>k(t)).join(" "),jt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},qt=(e,t)=>e.length===2&&typeof e[0]=="string"&&jt(e[1])?{fields:G(e[1],t,"full",O),message:e[0]}:{fields:G(void 0,t,"full",O),message:xt(e)},Yt=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:S(e.fields,s),function:e.functionPath,level:e.level,message:S(e.message,s),rayId:e.rayId,shard:e.shardKey,source:ie,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Mt,userId:e.userId};let n;try{n=JSON.stringify(r)}catch{n=JSON.stringify({...r,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(n):e.level==="warn"?console.warn(n):console.log(n)},Dt=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,pe=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Dt("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},q=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},$t=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pt=e=>{try{return JSON.parse(e)}catch{return}},vt=(e,t={})=>{D(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(pe(r,n,t),t.outcome!==void 0&&(r.push("outcome = ?"),n.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);r.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),n.push(o,o)}n.push(s);const a=t.sinceSeq===void 0?"DESC":"ASC";return E(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
|
|
25
|
-
FROM "${g}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const c={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:q(o.tables_read),tablesWritten:q(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(c.shardKey=o.shard_key),o.user_id!==null&&(c.userId=o.user_id),o.identity!==null){const d=$t(o.identity);d!==void 0&&(c.identity=d)}if(o.args!==null){const d=Pt(o.args);d!==void 0&&(c.redactedArgs=d)}return o.error_message!==null&&(c.errorMessage=o.error_message),o.cache_hit!==null&&(c.cacheHit=o.cache_hit===1),o.trace_id!==null&&(c.traceId=o.trace_id),o.deployment_id!==null&&(c.deploymentId=o.deployment_id),o.version_tag!==null&&(c.versionTag=o.version_tag),c})},Ct=(e,t)=>{const s=me(e,[...t.keys()]);for(const r of t.values()){const n=s.get(r.hash);n!==void 0&&(r.stateUpdatedAt=n.updatedAt,n.assignee!==void 0&&(r.assignee=n.assignee),n.severity!==void 0&&(r.severity=n.severity),r.status=n.status==="resolved"&&r.lastSeen>n.updatedAt?"open":n.status)}},Qt=(e,t={})=>{D(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),r=["outcome = 'error'"],n=[];pe(r,n,t),n.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
26
|
-
FROM "${g}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),i=new Map,o=new Map;for(const f of a){const m=f.error_message??"",{culprit:ge,hash:Se,title:$}=Y({functionPath:f.function_path,message:m}),h=f.error_fingerprint??Se,u=i.get(h);if(u===void 0){i.set(h,{count:1,culprit:ge,firstSeen:f.ts,hash:h,lastSeen:f.ts,sampleMessage:m,status:"open",title:$}),o.set(h,f.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,f.ts),u.lastSeen=Math.max(u.lastSeen,f.ts),f.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,f.ts),u.sampleMessage=m,u.title=$)}Ct(e,i);const c=[...i.values()];return(t.status===void 0?c:c.filter(f=>f.status===t.status)).toSorted((f,m)=>m.lastSeen-f.lastSeen)};export{Bt as N,g as R,l as S,Kt as a,Zt as b,wt as c,D as d,Yt as e,vt as f,S as g,Wt as h,Ht as i,M as j,xt as k,Xt as m,G as n,qt as p,Qt as r,zt as s};
|