@lunora/observability 1.0.0-alpha.166 → 1.0.0-alpha.168
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-XNqF4rB5.mjs +22 -0
- package/dist/packem_shared/{FUNCTION_METRICS_BUCKETS_TABLE-CHV71isV.mjs → FUNCTION_METRICS_BUCKETS_TABLE-DCdzGBZt.mjs} +5 -5
- package/dist/packem_shared/NO_SENSITIVE_SCOPE-BAbpBlN5.mjs +1 -0
- package/dist/packem_shared/{createDatabaseTally-BgyXiKtq.mjs → createDatabaseTally-ZFZnNvOy.mjs} +1 -1
- package/dist/packem_shared/{createMetrics-CJCccwhm.mjs → createMetrics-EODsLse6.mjs} +1 -1
- package/dist/packem_shared/prune-marker-CksedkkK.mjs +1 -0
- package/dist/packem_shared/request-log-DdeDQptI.mjs +24 -0
- package/package.json +2 -2
- package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.mjs +0 -22
- package/dist/packem_shared/NO_SENSITIVE_SCOPE-BXUByUZ9.mjs +0 -1
- package/dist/packem_shared/prune-marker-B4An9Nuj.mjs +0 -1
- package/dist/packem_shared/request-log-CQL8SsZX.mjs +0 -24
package/dist/index.d.mts
CHANGED
|
@@ -940,7 +940,8 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
|
|
|
940
940
|
*/
|
|
941
941
|
declare const ensureRequestLogTable: (sql: SqlExec) => void;
|
|
942
942
|
/**
|
|
943
|
-
* Append one dispatch to the request log, then
|
|
943
|
+
* Append one dispatch to the request log, then — once per
|
|
944
|
+
* {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
|
|
944
945
|
* recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
|
|
945
946
|
* table first so callers needn't. Args/identity/error message are redacted here
|
|
946
947
|
* so a raw value never reaches the durable table — callers pass the unredacted
|
package/dist/index.d.ts
CHANGED
|
@@ -940,7 +940,8 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
|
|
|
940
940
|
*/
|
|
941
941
|
declare const ensureRequestLogTable: (sql: SqlExec) => void;
|
|
942
942
|
/**
|
|
943
|
-
* Append one dispatch to the request log, then
|
|
943
|
+
* Append one dispatch to the request log, then — once per
|
|
944
|
+
* {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
|
|
944
945
|
* recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
|
|
945
946
|
* table first so callers needn't. Args/identity/error message are redacted here
|
|
946
947
|
* so a raw value never reaches the durable table — callers pass the unredacted
|
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-
|
|
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-XNqF4rB5.mjs";import{createMetrics as i,createSpanCollector as c,createTracedFetch as n,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-EODsLse6.mjs";import{createDatabaseTally as A,formatTally as N,instrumentDatabase as p,instrumentSqlClient as C}from"./packem_shared/createDatabaseTally-ZFZnNvOy.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-DCdzGBZt.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-BmD4CfV0.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-DdeDQptI.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-DnYOc8uk.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};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import{p as n}from"./prune-marker-CksedkkK.mjs";import{r as s}from"./run-sql-0aPgJkIw.mjs";const u="__lunora_auth_metrics",r="__lunora_auth_metrics_buckets",_="app",c=6e4,N=1440,A=t=>Math.floor(t/c)*c,m=t=>{s(t,`CREATE TABLE IF NOT EXISTS "${u}" (
|
|
2
|
+
key TEXT PRIMARY KEY,
|
|
3
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
4
|
+
failures INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
since_ms INTEGER NOT NULL DEFAULT 0
|
|
6
|
+
)`),s(t,`CREATE TABLE IF NOT EXISTS "${r}" (
|
|
7
|
+
bucket_ms INTEGER PRIMARY KEY,
|
|
8
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
failures INTEGER NOT NULL DEFAULT 0
|
|
10
|
+
)`)},I=(t,e)=>{m(t);const E=e.outcome==="fail"?1:0;s(t,`INSERT INTO "${u}" (key, attempts, failures, since_ms)
|
|
11
|
+
VALUES (?, 1, ?, ?)
|
|
12
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
13
|
+
attempts = attempts + 1,
|
|
14
|
+
failures = failures + excluded.failures,
|
|
15
|
+
since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,_,E,e.ts);const T=A(e.ts);s(t,`INSERT INTO "${r}" (bucket_ms, attempts, failures)
|
|
16
|
+
VALUES (?, 1, ?)
|
|
17
|
+
ON CONFLICT(bucket_ms) DO UPDATE SET
|
|
18
|
+
attempts = attempts + 1,
|
|
19
|
+
failures = failures + excluded.failures`,T,E),n(t,T,"",()=>{s(t,`DELETE FROM "${r}"
|
|
20
|
+
WHERE bucket_ms <= (
|
|
21
|
+
SELECT MAX(bucket_ms) - ? FROM "${r}"
|
|
22
|
+
)`,N*c)})},S=t=>{m(t);const e=s(t,`SELECT attempts, failures, since_ms FROM "${u}" WHERE key = ?`,_).toArray()[0],E=e?.attempts??0,T=e?.failures??0,o=e?.since_ms??0,i=s(t,`SELECT bucket_ms, attempts, failures FROM "${r}" ORDER BY bucket_ms ASC`).toArray().map(a=>({attempts:a.attempts,bucketMs:a.bucket_ms,failures:a.failures}));return{attempts:E,failureRate:E===0?0:T/E,failures:T,history:i,sinceMs:o}};export{r as AUTH_METRICS_BUCKETS_TABLE,c as AUTH_METRICS_BUCKET_MS,N as AUTH_METRICS_BUCKET_RETENTION,u as AUTH_METRICS_TABLE,m as ensureAuthMetricsTables,S as readAuthMetrics,I as recordAuthEvent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{p as b}from"./prune-marker-CksedkkK.mjs";import{r}from"./run-sql-0aPgJkIw.mjs";const E="__lunora_metrics",T="__lunora_metrics_buckets",N="__lunora_metrics_scans",L="__lunora_metrics_index",u=6e4,x=1440,I=5e3,l=1e3,D=e=>Math.floor(e/u)*u,f=e=>{const t=new Map;for(const a of e)t.set(`${a.table}\0${a.index}`,{index:a.index,table:a.table});return[...t.values()]},S=new WeakSet,_=e=>{if(!S.has(e)){r(e,`CREATE TABLE IF NOT EXISTS "${E}" (
|
|
2
2
|
path TEXT PRIMARY KEY,
|
|
3
3
|
calls INTEGER NOT NULL DEFAULT 0,
|
|
4
4
|
errors INTEGER NOT NULL DEFAULT 0,
|
|
@@ -26,7 +26,7 @@ import{s as b}from"./prune-marker-B4An9Nuj.mjs";import{r}from"./run-sql-0aPgJkIw
|
|
|
26
26
|
index_name TEXT NOT NULL,
|
|
27
27
|
reads INTEGER NOT NULL DEFAULT 0,
|
|
28
28
|
PRIMARY KEY (table_name, index_name)
|
|
29
|
-
)`),S.add(e)}},R=new WeakMap,$=e=>{let t=R.get(e);return t===void 0&&(t=new Set,R.set(e,t)),t},
|
|
29
|
+
)`),S.add(e)}},R=new WeakMap,$=e=>{let t=R.get(e);return t===void 0&&(t=new Set,R.set(e,t)),t},p=(e,t)=>{const a=$(e);return a.has(t)?!0:r(e,`SELECT 1 AS c FROM "${E}" WHERE path = ? LIMIT 1`,t).toArray().length>0?(a.add(t),!0):r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=I?!1:(a.add(t),!0)},H=(e,t)=>{if(_(e),!p(e,t.path))return;const a=t.scanCounts??[...new Set(t.scannedTables)].map(n=>({count:1,table:n})),s=a.reduce((n,d)=>n+d.count,0),c=t.indexHitCounts??f(t.indexHits??[]).map(n=>({...n,count:1})),o=t.calls??1,m=t.errors??(t.errored?1:0),C=t.conflicts??(t.conflicted?1:0),O=t.durationTotalMs??t.durationMs,M=t.durationMinMs??t.durationMs,U=t.durationMaxMs??t.durationMs,h=t.errored?t.ts:null,i=t.lastErrorAt===void 0?h:t.lastErrorAt,F=i===null?null:t.errorMessage??null;r(e,`INSERT INTO "${E}"
|
|
30
30
|
(path, calls, errors, conflicts, scans, total_duration_ms, min_duration_ms, max_duration_ms, last_called_at, last_error_at, last_error_message)
|
|
31
31
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
32
32
|
ON CONFLICT(path) DO UPDATE SET
|
|
@@ -43,14 +43,14 @@ import{s as b}from"./prune-marker-B4An9Nuj.mjs";import{r}from"./run-sql-0aPgJkIw
|
|
|
43
43
|
VALUES (?, ?, ?, ?)
|
|
44
44
|
ON CONFLICT(path, bucket_ms) DO UPDATE SET
|
|
45
45
|
calls = calls + excluded.calls,
|
|
46
|
-
errors = errors + excluded.errors`,t.path,A,o,m),b(e,A,t.path)
|
|
46
|
+
errors = errors + excluded.errors`,t.path,A,o,m),b(e,A,t.path,()=>{r(e,`DELETE FROM "${T}"
|
|
47
47
|
WHERE path = ?
|
|
48
48
|
AND bucket_ms <= (
|
|
49
49
|
SELECT MAX(bucket_ms) - ? FROM "${T}" WHERE path = ?
|
|
50
|
-
)`,t.path,x*u,t.path);for(const{count:n,table:d}of a)r(e,`INSERT INTO "${N}" (path, table_name, scans)
|
|
50
|
+
)`,t.path,x*u,t.path)});for(const{count:n,table:d}of a)r(e,`INSERT INTO "${N}" (path, table_name, scans)
|
|
51
51
|
VALUES (?, ?, ?)
|
|
52
52
|
ON CONFLICT(path, table_name) DO UPDATE SET
|
|
53
53
|
scans = scans + excluded.scans`,t.path,d,n);for(const n of c)r(e,`INSERT INTO "${L}" (table_name, index_name, reads)
|
|
54
54
|
VALUES (?, ?, ?)
|
|
55
55
|
ON CONFLICT(table_name, index_name) DO UPDATE SET
|
|
56
|
-
reads = reads + excluded.reads`,n.table,n.index,n.count)},
|
|
56
|
+
reads = reads + excluded.reads`,n.table,n.index,n.count)},k=e=>{_(e);const t=r(e,`SELECT path, table_name, scans FROM "${N}" ORDER BY scans DESC, path ASC, table_name ASC LIMIT ${String(l)}`).toArray(),a=new Map;for(const s of t){const c=a.get(s.path),o={scans:s.scans,table:s.table_name};c===void 0?a.set(s.path,[o]):c.push(o)}return a},P=e=>(_(e),r(e,`SELECT table_name, index_name, reads FROM "${L}" ORDER BY table_name ASC, index_name ASC LIMIT ${String(l)}`).toArray().map(a=>({index:a.index_name,reads:a.reads,table:a.table_name}))),X=(e,t)=>{for(const a of t){const s=e.find(c=>c.table===a);s===void 0?e.push({scans:1,table:a}):s.scans+=1}return e.sort((a,s)=>s.scans-a.scans||a.table.localeCompare(s.table)),e},y=e=>{_(e);const t=k(e);return r(e,`SELECT * FROM "${E}" ORDER BY last_called_at DESC LIMIT ${String(l)}`).toArray().map(s=>({calls:s.calls,conflicts:s.conflicts,errors:s.errors,lastCalledAt:s.last_called_at,lastErrorAt:s.last_error_at,lastErrorMessage:s.last_error_message,maxDurationMs:s.max_duration_ms,path:s.path,scannedTables:t.get(s.path)??[],scans:s.scans,totalDurationMs:s.total_duration_ms}))},Y=(e,t)=>{_(e);const a=t===void 0?r(e,`SELECT path, bucket_ms, calls, errors FROM "${T}" ORDER BY bucket_ms DESC, path ASC LIMIT ${String(l+1)}`).toArray():r(e,`SELECT path, bucket_ms, calls, errors FROM "${T}" WHERE path = ? ORDER BY bucket_ms DESC LIMIT ${String(l+1)}`,t).toArray(),s=a.length>l;return{buckets:(s?a.slice(0,l):a).toReversed().map(o=>({bucketMs:o.bucket_ms,calls:o.calls,errors:o.errors,path:o.path})),truncated:s}},G=e=>{_(e);const t=r(e,`SELECT SUM(calls) AS requests, SUM(errors) AS errors FROM "${E}"`).one();return{capped:r(e,`SELECT COUNT(*) AS n FROM "${E}"`).one().n>=I,errors:t.errors??0,requests:t.requests??0}};export{T as FUNCTION_METRICS_BUCKETS_TABLE,u as FUNCTION_METRICS_BUCKET_MS,x as FUNCTION_METRICS_BUCKET_RETENTION,L as FUNCTION_METRICS_INDEX_TABLE,I as FUNCTION_METRICS_MAX_PATHS,l as FUNCTION_METRICS_READ_LIMIT,N as FUNCTION_METRICS_SCANS_TABLE,E as FUNCTION_METRICS_TABLE,_ as ensureFunctionMetricsTables,X as mergeScanAttribution,Y as readFunctionMetricBuckets,P as readFunctionMetricIndexHits,k as readFunctionMetricScans,y as readFunctionMetrics,G as readFunctionMetricsTotals,H as recordFunctionMetric};
|
|
@@ -0,0 +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-DdeDQptI.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-BgyXiKtq.mjs → createDatabaseTally-ZFZnNvOy.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as g}from"./otlp-DR7601NL.mjs";import{N as l,g as p}from"./request-log-
|
|
1
|
+
import{o as g}from"./otlp-DR7601NL.mjs";import{N as l,g as p}from"./request-log-DdeDQptI.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","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchIf","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),P=(e,t)=>{if(!I.has(e))return;const r=t[0];return typeof r=="string"&&r.length>0?r:void 0},L=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),b=(e,t,r)=>{const o=(t.scope??l).text(L(e));return r==="redact"?p(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:b(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:g(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()}},T=(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:T(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 T(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-DdeDQptI.mjs";import{o as L,b as q,O as X}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as B}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as P}from"./resolveTraceAnchor-DDAPZRBB.mjs";const V=/[\w.-]/u,G=t=>{let e="";for(const r of t)e+=V.test(r)?r:"_";return e},J=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=G(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},Q=t=>{const e=Object.keys(t);if(e.length===0||!e.every(s=>s==="attributes"||s==="kind"||s==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(X,r)},W=128,Y=128,K=128,b=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[s,d]of Object.entries(e)){const n=!Object.hasOwn(t,s);n&&r>=K||(n&&(r+=1),t[s]=d)}},F=t=>{const e=y(t);if(e===void 0||Object.keys(e).length<=K)return e;const r={};return b(r,e),r},Z=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},tt=t=>{try{return new URL(t).host}catch{return t}},et=(t,e)=>{try{return t(new URL(e))}catch{return!1}},nt=t=>t===void 0?{}:Q(t)?t:{attributes:t},$=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},rt=(t,e=!1,r=k)=>{const s={attributes:{},events:[],links:[]},d={spanContext:()=>t,addEvent:(n,a)=>{if(s.events.length>=W)return;const o=w(r.fields(F(a)),e);s.events.push({...o===void 0?{}:{attributes:o},name:r.name(n),ts:Date.now()})},addLink:n=>{if(s.links.length>=Y)return;const a=w(r.fields(F(n.attributes)),e);s.links.push({...a===void 0?{}:{attributes:a},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{b(s.attributes,r.fields(y(J(n))))},recordException:n=>{const a=n instanceof Error?n.message:String(n);d.addEvent("exception",{"exception.message":O(a,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":P(n)})},setAttribute:(n,a)=>{b(s.attributes,r.fields(y({[n]:a})))},setAttributes:n=>{b(s.attributes,r.fields(y(n)))}};return{collected:s,handle:d}},it=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:s,functionPath:d,record:n,resolveHostTracing:a,scope:o=k,shardKey:i,userId:m}=t,u=g=>async(E,T,l,x)=>{const p=x?.spanId??L(8),I=x?.parentSpanId??g,_=Date.now(),c=nt(l),M=o.fields(y(c.attributes)),j=o.name(E),{collected:A,handle:U}=rt({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:p,traceId:e.traceId},r,o),C=o.hold(),z=async S=>{let f=!0,v;try{return await T(u(p),U)}catch(h){f=!1;const N=o.text(h instanceof Error?h.message:String(h));throw v={message:O(N,r),type:P(h)},h}finally{const h=Date.now()-_,N=m(),H={};b(H,M),b(H,A.attributes);const R=w(H,r),D=o.value([...c.links??[],...A.links]);try{n({...Object.keys(R).length===0?{}:{attributes:R},durationMs:h,...A.events.length===0?{}:{events:A.events},...v===void 0?{}:{error:v},functionPath:d,...c.kind===void 0||c.kind==="internal"?{}:{kind:c.kind},...D.length===0?{}:{links:D},name:j,ok:f,parentSpanId:I,...$(e),shardKey:i,spanId:p,startTs:_,userId:N})}catch{}if(S!==void 0)try{B(S,{attributes:R,durationMs:h,error:v,functionPath:d,ok:f,shardKey:i,userId:N})}catch{}C()}};if(s===!0&&a!==void 0){let S=!1;try{const f=await a();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(j,v=>(S=!0,z(v)))}catch(f){if(S)throw f}}return await z()};return u(e.rootSpanId)},dt=(t,e)=>{const{anchor:r,captureRaw:s=!1,functionPath:d,propagate:n=!0,record:a,scope:o=k,shardKey:i,userId:m}=t;return async(u,g)=>{const E=L(8),T=Date.now(),l=new Request(u,g);(typeof n=="function"?et(n,l.url):n)&&l.headers.set("traceparent",q(r.traceId,E,r.sampled??!0));let p,I;const _=o.hold();try{const c=await e(l);return I=c.status,c.ok||(p={message:`HTTP ${String(c.status)}`,type:`HTTP_${String(c.status)}`}),c}catch(c){const M=o.text(c instanceof Error?c.message:String(c));throw p={message:O(M,s),type:P(c)},c}finally{try{a({attributes:{"http.request.method":l.method,...I===void 0?{}:{"http.response.status_code":I},"url.full":o.text(Z(l.url))},durationMs:Date.now()-T,...p===void 0?{}:{error:p},functionPath:d,kind:"client",name:o.text(`${l.method} ${tt(l.url)}`),ok:p===void 0,parentSpanId:r.rootSpanId,...$(r),shardKey:i,spanId:E,startTs:T,userId:m()})}catch{}_()}}},ut=t=>{const{functionPath:e,record:r,scope:s=k,shardKey:d}=t,n=(a,o,i,m)=>{if(!Number.isFinite(i))return;const u=w(s.fields(y(m)));try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:a,name:s.name(o),shardKey:d,ts:Date.now(),value:i})}catch{}};return{count:(a,o=1,i)=>{n("counter",a,o,i)},gauge:(a,o,i)=>{n("gauge",a,o,i)},record:(a,o,i)=>{n("histogram",a,o,i)}}},lt=t=>{const{anchor:e,captureRaw:r=!1,collected:s,durationMs:d,failure:n,functionPath:a,scope:o=k,shardKey:i,startTs:m,userId:u}=t,g=w(s?.attributes??{},r);return{...Object.keys(g).length===0?{}:{attributes:g},dispatch:!0,durationMs:d,...s===void 0||s.events.length===0?{}:{events:s.events},...n===void 0?{}:{error:{message:O(o.text(n.thrown instanceof Error?n.thrown.message:String(n.thrown)),r),type:P(n.thrown)}},functionPath:a,...s===void 0||s.links.length===0?{}:{links:s.links},name:a,ok:n===void 0,parentSpanId:"",...$(e),shardKey:i,spanId:e.rootSpanId,startTs:m,userId:u}};export{ut as createMetrics,rt as createSpanCollector,dt as createTracedFetch,it as createTracer,lt as dispatchRootSpan,$ as spanAnchorFields};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=new WeakMap,a=(t,n,r="")=>{let e=o.get(t);return e===void 0&&(e=new Map,o.set(t,e)),e.get(r)===n?!1:(e.set(r,n),!0)},s=(t,n,r,e)=>{if(a(t,n,r))try{e()}catch(u){throw o.get(t)?.delete(r),u}};export{s as p};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{fingerprintError as W}from"@lunora/fingerprint";import{createRedactor as se,standardRules as ne}from"@visulima/redact";import{readIssueStates as re}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{p as oe}from"./prune-marker-CksedkkK.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const N=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)}},x=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:N(e),M=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},$=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))M(s,r,x(n));if(e!==void 0)for(const[r,n]of Object.entries(e))M(s,r,x(n));return Object.keys(s).length===0?void 0:s},ie=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"]),ae=new Set(["card","pass","pin","session"]),ce=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),de=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),le=new Set(["card no","connection string","database url","one time"]),fe=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],ue=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"]),ge=new Set(["max","min","num","total"]),b=4096,he=128,Se=16384,p="<REDACTED>",Ee="[redaction budget exceeded]",_e=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),D=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,Ae=(e,t)=>{const s=D(e[t]),r=t>0?D(e[t-1]):void 0;if(ie.has(s))return s;if(r!==void 0){if(s==="key"&&ce.has(r))return"key";if(s==="code"&&de.has(r))return"code";if(le.has(`${r} ${s}`))return`${r} ${s}`}return fe.some(n=>s.endsWith(n))?s:void 0},F=e=>{const t=_e(e);if(t.length===0)return"none";const s=pe.has(t.at(-1))||ge.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=Ae(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(i=>ue.has(i))?ae.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},me=e=>typeof e=="boolean"||e===null||e===void 0?e:p,ye=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),i=r.indexOf(":"),c=r.indexOf("/"),o=i!==-1&&/^\d+$/.test(r.slice(i+1,c===-1?void 0:c)),a=i!==-1&&!o&&(c===-1||i<c);if(n===-1&&a&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||i!==-1&&i<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},Te=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,be=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Oe=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,X=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,z=[{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\.`}],Ne=String.raw`(?<=^|[^\w-]|${X})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Ie=new RegExp([...z.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${X})${t}${e}`),Ne].join("|"),"g"),we=new RegExp([...z.map(({prefix:e})=>e),"eyJ"].join("|")),Re=/(\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,U=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,P=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,Le=e=>{let t="",s=0;A.lastIndex=0;for(let r=A.exec(e);r!==null;r=A.exec(e)){const n=F(r[2]),i=r.index+r[0].length;U.lastIndex=i;const c=n==="none"?null:U.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){A.lastIndex=Math.max(i,r.index+1);continue}const o=c[0],a=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=i+o.length;a===""&&r[3]===":"&&(P.lastIndex=d,d+=P.exec(e)?.[0].length??0),t+=`${e.slice(s,i)}${a}${p}${o.length>a.length&&o.endsWith(a)?a:""}`,s=d,A.lastIndex=s}return t+e.slice(s)},ke=/[:=@]|basic|bearer|digest|-u\b|--/i,xe=e=>{const t=we.test(e);if(!t&&!ke.test(e))return e;const s=e.replaceAll(be,`-----BEGIN $1-----${p}`).replaceAll(Te,ye).replaceAll(Oe,`$1 ${p}`);return Le((t?s.replaceAll(Ie,p):s).replaceAll(Re,`$1$2$3${p}`))},Me=(e,t)=>{if(t.remaining<=0)return Ee;const s=e.slice(0,b+he);t.remaining-=s.length;const r=xe(s);return r.length>b||e.length>s.length?`${r.slice(0,b)}…[truncated]`:r},$e=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),m=Symbol("no-json"),De=e=>{const{toJSON:t}=e;if(typeof t!="function")return m;try{const s=t.call(e);return s===e?m:s}catch{return m}},Ue=32,T=(e,t,s,r,n)=>{if(typeof e=="string")return r?p:Me(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&$e(e))return e;if(t.has(e)||s>=Ue)return p;const i=Array.isArray(e)?m:De(e);if(i!==m){t.add(e);const o=T(i,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>T(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,a])=>{const d=F(o);return d==="secret"||d==="scalar-secret"&&(typeof a!="object"||a===null)?[o,me(a)]:[o,T(a,t,s+1,d==="count-secret"&&(typeof a=="string"||Array.isArray(a)),n)]}));return t.delete(e),c},H=e=>T(e,new WeakSet,0,!1,{remaining:Se}),h="__lunora_reqlog__",Pe=6e4,I=1e3,B="lunora",Ce=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],je=se(ne,{exclude:["pass"]}),St=(e,t=!1)=>t||e===null||e===void 0?e:H(e),g=(e,t=!1)=>t||e===null||e===void 0?e:je(H(e)),f="«sensitive»",Et=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,r])=>[s,t.has(s)?f:r])),ve=8,J=4,K=3,w=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),Ge=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${w(e)}(?![\p{L}\p{N}])`,"gu"),Ve=e=>new RegExp(String.raw`(?<=["'])${w(e)}(?=["'])`,"gu"),C=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${w(e)}(?![\p{L}\p{N}])`,"gu"),We=new Set(["false","true"]),Fe=new RegExp("^\\p{N}+$","u"),R=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<J?[e]:[e,t]},Z=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},q=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Y=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()])]},Xe=e=>{const t=q(e);if(t.length===0)return[];const s=Z(t);return[...s===void 0||s.length===0?[]:R(s),...Y(t)]},ze=e=>e instanceof Error&&e.message.length>0?R(e.message):[],He=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],Be=(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(...R(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(...Xe(n));else if(typeof n=="object"&&n!==null&&!s.has(n)){s.add(n),t.push(...ze(n));for(const i of Object.values(n))r.push(i);r.push(...He(n))}}},_t=(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(N(n)),Be(n,s)}return s},Je=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),Ke=(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 i of Je(n))t.push(i);for(const i of Object.values(n))r.push(i)}}},At=(e,t)=>{const s=[];for(const r of t)Object.hasOwn(e,r)&&Ke(e[r],s);return s},Ze=(e,t)=>{if(We.has(t))return e.replaceAll(Ve(t),f).replaceAll(C(t,"="),f);if(t.length>=J)return e.replaceAll(t,f);if(t.length>=K)return e.includes(t)?e.replaceAll(Ge(t),f):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(f));return Fe.test(t)?s:s.replaceAll(C(t,"=:"),f)},y=(e,t)=>{if(t.includes(e))return f;let s=e;for(const r of t.toSorted((n,i)=>i.length-n.length))s=Ze(s,r);return s},qe={names:new Set,texts:[]},j=e=>e.texts.length>0||e.names.size>0,Ye=(e,t)=>t.names.has(e)?f:y(e,t.texts),Qe=(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)}`},et=(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 r=!1;const n={};for(const[i,c]of Object.entries(e)){const o=s(c),a=Qe(n,Ye(i,t));r||=o!==c||a!==i,n[a]=o}return r?n:e},tt=(e,t)=>{const s=q(e);if(s.length===0)return!1;const r=Z(s);return r!==void 0&&t.texts.some(n=>r.includes(n))||Y(s).some(n=>y(n,t.texts)!==n)},O=(e,t,s,r=new Set)=>{if(typeof e=="string")return y(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return tt(e,t)?f:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const i=String(e);return i.length>=K&&t.texts.includes(i)?f:e}if(e instanceof Error){const i=String(e),c=y(i,t.texts);return c===i?e:c}if(typeof e!="object"||e===null)return e;if(s>=ve||r.has(e))return f;r.add(e);const n=et(e,t,i=>O(i,t,s+1,r));return r.delete(e),n},st=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},r=!1,n=0;const i=()=>{r&&n===0&&(s=qe)},c=o=>s.texts.length===0?o:y(o,s.texts);return{add(o,a=[]){!r&&(o.length>0||a.length>0)&&(s={names:new Set([...s.names,...a]),texts:[...new Set([...s.texts,...o])]})},clear(){r=!0,i()},hold(){n+=1;let o=!1;return()=>{o||(o=!0,n-=1,i())}},fields:o=>o===void 0||!j(s)?o:O(o,s,0),name:o=>s.names.has(o)?f:c(o),text:c,value:o=>j(s)?O(o,s,0):o}},mt={...st([]),add:()=>{}},v=new WeakSet,L=e=>{if(!v.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${h}" (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
function_path TEXT NOT NULL,
|
|
5
|
+
shard_key TEXT,
|
|
6
|
+
user_id TEXT,
|
|
7
|
+
identity TEXT,
|
|
8
|
+
args TEXT,
|
|
9
|
+
outcome TEXT NOT NULL,
|
|
10
|
+
error_message TEXT,
|
|
11
|
+
error_fingerprint TEXT,
|
|
12
|
+
trace_id TEXT,
|
|
13
|
+
deployment_id TEXT,
|
|
14
|
+
version_tag TEXT,
|
|
15
|
+
duration_ms REAL NOT NULL,
|
|
16
|
+
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
17
|
+
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
18
|
+
cache_hit INTEGER,
|
|
19
|
+
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
20
|
+
)`);for(const t of Ce)try{E(e,`ALTER TABLE "${h}" ADD COLUMN ${t}`)}catch{}v.add(e)}},G=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),nt=e=>e===void 0?null:e?1:0,yt=(e,t,s={})=>{L(e);const r=s.captureRaw??!1,n=s.retention??I,i=t.outcome==="error"&&t.errorMessage!==void 0?W({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${h}"
|
|
21
|
+
(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)
|
|
22
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(g(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(g(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:g(t.errorMessage,r),i??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,G(t.tablesRead),G(t.tablesWritten),nt(t.cacheHit),t.subscriptionsReRun??0),oe(e,Math.floor(t.ts/Pe),"request-log",()=>{E(e,`DELETE FROM "${h}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${h}")`,n)})},Tt=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:g(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:g(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:g(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:B,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)},rt="log",ot=e=>e.map(t=>N(t)).join(" "),it=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},bt=(e,t)=>e.length===2&&typeof e[0]=="string"&&it(e[1])?{fields:$(e[1],t),message:e[0]}:{fields:$(void 0,t),message:ot(e)},Ot=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:g(e.fields,s),function:e.functionPath,level:e.level,message:g(e.message,s),rayId:e.rayId,shard:e.shardKey,source:B,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:rt,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)},at=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,Q=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(at("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))},V=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},ct=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dt=e=>{try{return JSON.parse(e)}catch{return}},Nt=(e,t={})=>{L(e);const s=Math.max(1,Math.min(t.limit??I,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(Q(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 i=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
|
|
23
|
+
FROM "${h}" WHERE ${r.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,...n).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:V(o.tables_read),tablesWritten:V(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=ct(o.identity);d!==void 0&&(a.identity=d)}if(o.args!==null){const d=dt(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})},lt=(e,t)=>{const s=re(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)}},It=(e,t={})=>{L(e);const s=Math.max(1,Math.min(t.limit??I,1e4)),r=["outcome = 'error'"],n=[];Q(r,n,t),n.push(s);const i=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
+
FROM "${h}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of i){const _=l.error_message??"",{culprit:ee,hash:te,title:k}=W({functionPath:l.function_path,message:_}),S=l.error_fingerprint??te,u=c.get(S);if(u===void 0){c.set(S,{count:1,culprit:ee,firstSeen:l.ts,hash:S,lastSeen:l.ts,sampleMessage:_,status:"open",title:k}),o.set(S,l.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,l.ts),u.lastSeen=Math.max(u.lastSeen,l.ts),l.ts>(o.get(S)??Number.NEGATIVE_INFINITY)&&(o.set(S,l.ts),u.sampleMessage=_,u.title=k)}lt(e,c);const a=[...c.values()];return(t.status===void 0?a:a.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{mt as N,h as R,f as S,yt as a,Tt as b,st as c,L as d,Ot as e,Nt as f,g,St as h,_t as i,I as j,ot as k,Et as m,$ as n,bt as p,It as r,At as s};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/observability",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.168",
|
|
4
4
|
"description": "Host-neutral telemetry storage and read models for Lunora, backing the Studio's Logs, Traces, Metrics and Issues views",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"lunora",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
47
47
|
"@lunora/fingerprint": "1.0.0-alpha.9",
|
|
48
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
48
|
+
"@lunora/shard-engine": "1.0.0-alpha.157",
|
|
49
49
|
"@lunora/wire": "1.0.0-alpha.2",
|
|
50
50
|
"@visulima/redact": "5.0.0"
|
|
51
51
|
},
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{s as n}from"./prune-marker-B4An9Nuj.mjs";import{r as e}from"./run-sql-0aPgJkIw.mjs";const u="__lunora_auth_metrics",r="__lunora_auth_metrics_buckets",_="app",c=6e4,N=1440,A=t=>Math.floor(t/c)*c,m=t=>{e(t,`CREATE TABLE IF NOT EXISTS "${u}" (
|
|
2
|
-
key TEXT PRIMARY KEY,
|
|
3
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
4
|
-
failures INTEGER NOT NULL DEFAULT 0,
|
|
5
|
-
since_ms INTEGER NOT NULL DEFAULT 0
|
|
6
|
-
)`),e(t,`CREATE TABLE IF NOT EXISTS "${r}" (
|
|
7
|
-
bucket_ms INTEGER PRIMARY KEY,
|
|
8
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
9
|
-
failures INTEGER NOT NULL DEFAULT 0
|
|
10
|
-
)`)},I=(t,s)=>{m(t);const E=s.outcome==="fail"?1:0;e(t,`INSERT INTO "${u}" (key, attempts, failures, since_ms)
|
|
11
|
-
VALUES (?, 1, ?, ?)
|
|
12
|
-
ON CONFLICT(key) DO UPDATE SET
|
|
13
|
-
attempts = attempts + 1,
|
|
14
|
-
failures = failures + excluded.failures,
|
|
15
|
-
since_ms = CASE WHEN since_ms = 0 THEN excluded.since_ms ELSE since_ms END`,_,E,s.ts);const T=A(s.ts);e(t,`INSERT INTO "${r}" (bucket_ms, attempts, failures)
|
|
16
|
-
VALUES (?, 1, ?)
|
|
17
|
-
ON CONFLICT(bucket_ms) DO UPDATE SET
|
|
18
|
-
attempts = attempts + 1,
|
|
19
|
-
failures = failures + excluded.failures`,T,E),n(t,T)&&e(t,`DELETE FROM "${r}"
|
|
20
|
-
WHERE bucket_ms <= (
|
|
21
|
-
SELECT MAX(bucket_ms) - ? FROM "${r}"
|
|
22
|
-
)`,N*c)},S=t=>{m(t);const s=e(t,`SELECT attempts, failures, since_ms FROM "${u}" WHERE key = ?`,_).toArray()[0],E=s?.attempts??0,T=s?.failures??0,o=s?.since_ms??0,i=e(t,`SELECT bucket_ms, attempts, failures FROM "${r}" ORDER BY bucket_ms ASC`).toArray().map(a=>({attempts:a.attempts,bucketMs:a.bucket_ms,failures:a.failures}));return{attempts:E,failureRate:E===0?0:T/E,failures:T,history:i,sinceMs:o}};export{r as AUTH_METRICS_BUCKETS_TABLE,c as AUTH_METRICS_BUCKET_MS,N as AUTH_METRICS_BUCKET_RETENTION,u as AUTH_METRICS_TABLE,m as ensureAuthMetricsTables,S as readAuthMetrics,I as recordAuthEvent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as t,j as E,R as i,S as o,a as g,c as S,e as n,b as L,d as R,m as d,p as m,r as p,f as T,g as _,h as u,k as N,s as v,i as A}from"./request-log-CQL8SsZX.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as NO_SENSITIVE_SCOPE,E as REQUEST_LOG_RETENTION,i as REQUEST_LOG_TABLE,o as SENSITIVE_ARG_MASK,g as appendRequestLogEntry,S as createSensitiveScope,n as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,d as maskSensitiveArgs,m as parseLogArgs,p as readErrorIssues,T as readRequestLog,_ as redactArgs,u as redactCredentials,N as renderLogMessage,v as sensitiveNames,A as sensitiveValues};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=new WeakMap,a=(t,n,r="")=>{let e=s.get(t);return e===void 0&&(e=new Map,s.set(t,e)),e.get(r)===n?!1:(e.set(r,n),!0)};export{a as s};
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{fingerprintError as F}from"@lunora/fingerprint";import{createRedactor as se,standardRules as ne}from"@visulima/redact";import{readIssueStates as re}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const N=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)}},x=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:N(e),$=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},M=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))$(s,r,x(n));if(e!==void 0)for(const[r,n]of Object.entries(e))$(s,r,x(n));return Object.keys(s).length===0?void 0:s},oe=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"]),ie=new Set(["card","pass","pin","session"]),ae=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),ce=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),de=new Set(["card no","connection string","database url","one time"]),le=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],fe=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"]),ue=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),pe=new Set(["max","min","num","total"]),b=4096,ge=128,he=16384,p="<REDACTED>",Se="[redaction budget exceeded]",Ee=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),D=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,Ae=(e,t)=>{const s=D(e[t]),r=t>0?D(e[t-1]):void 0;if(oe.has(s))return s;if(r!==void 0){if(s==="key"&&ae.has(r))return"key";if(s==="code"&&ce.has(r))return"code";if(de.has(`${r} ${s}`))return`${r} ${s}`}return le.some(n=>s.endsWith(n))?s:void 0},W=e=>{const t=Ee(e);if(t.length===0)return"none";const s=ue.has(t.at(-1))||pe.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=Ae(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(i=>fe.has(i))?ie.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},me=e=>typeof e=="boolean"||e===null||e===void 0?e:p,_e=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),i=r.indexOf(":"),c=r.indexOf("/"),o=i!==-1&&/^\d+$/.test(r.slice(i+1,c===-1?void 0:c)),a=i!==-1&&!o&&(c===-1||i<c);if(n===-1&&a&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||i!==-1&&i<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},ye=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Te=/-----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,X=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,z=[{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\.`}],Oe=String.raw`(?<=^|[^\w-]|${X})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Ne=new RegExp([...z.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${X})${t}${e}`),Oe].join("|"),"g"),Ie=new RegExp([...z.map(({prefix:e})=>e),"eyJ"].join("|")),we=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,m=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,C=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,U=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,Re=e=>{let t="",s=0;m.lastIndex=0;for(let r=m.exec(e);r!==null;r=m.exec(e)){const n=W(r[2]),i=r.index+r[0].length;C.lastIndex=i;const c=n==="none"?null:C.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){m.lastIndex=Math.max(i,r.index+1);continue}const o=c[0],a=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=i+o.length;a===""&&r[3]===":"&&(U.lastIndex=d,d+=U.exec(e)?.[0].length??0),t+=`${e.slice(s,i)}${a}${p}${o.length>a.length&&o.endsWith(a)?a:""}`,s=d,m.lastIndex=s}return t+e.slice(s)},Le=/[:=@]|basic|bearer|digest|-u\b|--/i,ke=e=>{const t=Ie.test(e);if(!t&&!Le.test(e))return e;const s=e.replaceAll(Te,`-----BEGIN $1-----${p}`).replaceAll(ye,_e).replaceAll(be,`$1 ${p}`);return Re((t?s.replaceAll(Ne,p):s).replaceAll(we,`$1$2$3${p}`))},xe=(e,t)=>{if(t.remaining<=0)return Se;const s=e.slice(0,b+ge);t.remaining-=s.length;const r=ke(s);return r.length>b||e.length>s.length?`${r.slice(0,b)}…[truncated]`:r},$e=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),_=Symbol("no-json"),Me=e=>{const{toJSON:t}=e;if(typeof t!="function")return _;try{const s=t.call(e);return s===e?_:s}catch{return _}},De=32,T=(e,t,s,r,n)=>{if(typeof e=="string")return r?p:xe(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&$e(e))return e;if(t.has(e)||s>=De)return p;const i=Array.isArray(e)?_:Me(e);if(i!==_){t.add(e);const o=T(i,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>T(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,a])=>{const d=W(o);return d==="secret"||d==="scalar-secret"&&(typeof a!="object"||a===null)?[o,me(a)]:[o,T(a,t,s+1,d==="count-secret"&&(typeof a=="string"||Array.isArray(a)),n)]}));return t.delete(e),c},H=e=>T(e,new WeakSet,0,!1,{remaining:he}),h="__lunora_reqlog__",I=1e3,B="lunora",Ce=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],Ue=se(ne,{exclude:["pass"]}),pt=(e,t=!1)=>t||e===null||e===void 0?e:H(e),g=(e,t=!1)=>t||e===null||e===void 0?e:Ue(H(e)),f="«sensitive»",gt=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,r])=>[s,t.has(s)?f:r])),je=8,J=4,K=3,w=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),Pe=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${w(e)}(?![\p{L}\p{N}])`,"gu"),ve=e=>new RegExp(String.raw`(?<=["'])${w(e)}(?=["'])`,"gu"),j=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${w(e)}(?![\p{L}\p{N}])`,"gu"),Ve=new Set(["false","true"]),Ge=new RegExp("^\\p{N}+$","u"),R=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<J?[e]:[e,t]},Z=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},q=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),Y=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()])]},Fe=e=>{const t=q(e);if(t.length===0)return[];const s=Z(t);return[...s===void 0||s.length===0?[]:R(s),...Y(t)]},We=e=>e instanceof Error&&e.message.length>0?R(e.message):[],Xe=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],ze=(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(...R(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(...Fe(n));else if(typeof n=="object"&&n!==null&&!s.has(n)){s.add(n),t.push(...We(n));for(const i of Object.values(n))r.push(i);r.push(...Xe(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(N(n)),ze(n,s)}return s},He=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),Be=(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 i of He(n))t.push(i);for(const i of Object.values(n))r.push(i)}}},St=(e,t)=>{const s=[];for(const r of t)Object.hasOwn(e,r)&&Be(e[r],s);return s},Je=(e,t)=>{if(Ve.has(t))return e.replaceAll(ve(t),f).replaceAll(j(t,"="),f);if(t.length>=J)return e.replaceAll(t,f);if(t.length>=K)return e.includes(t)?e.replaceAll(Pe(t),f):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(f));return Ge.test(t)?s:s.replaceAll(j(t,"=:"),f)},y=(e,t)=>{if(t.includes(e))return f;let s=e;for(const r of t.toSorted((n,i)=>i.length-n.length))s=Je(s,r);return s},Ke={names:new Set,texts:[]},P=e=>e.texts.length>0||e.names.size>0,Ze=(e,t)=>t.names.has(e)?f:y(e,t.texts),qe=(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)}`},Ye=(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 r=!1;const n={};for(const[i,c]of Object.entries(e)){const o=s(c),a=qe(n,Ze(i,t));r||=o!==c||a!==i,n[a]=o}return r?n:e},Qe=(e,t)=>{const s=q(e);if(s.length===0)return!1;const r=Z(s);return r!==void 0&&t.texts.some(n=>r.includes(n))||Y(s).some(n=>y(n,t.texts)!==n)},O=(e,t,s,r=new Set)=>{if(typeof e=="string")return y(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Qe(e,t)?f:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const i=String(e);return i.length>=K&&t.texts.includes(i)?f:e}if(e instanceof Error){const i=String(e),c=y(i,t.texts);return c===i?e:c}if(typeof e!="object"||e===null)return e;if(s>=je||r.has(e))return f;r.add(e);const n=Ye(e,t,i=>O(i,t,s+1,r));return r.delete(e),n},et=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},r=!1,n=0;const i=()=>{r&&n===0&&(s=Ke)},c=o=>s.texts.length===0?o:y(o,s.texts);return{add(o,a=[]){!r&&(o.length>0||a.length>0)&&(s={names:new Set([...s.names,...a]),texts:[...new Set([...s.texts,...o])]})},clear(){r=!0,i()},hold(){n+=1;let o=!1;return()=>{o||(o=!0,n-=1,i())}},fields:o=>o===void 0||!P(s)?o:O(o,s,0),name:o=>s.names.has(o)?f:c(o),text:c,value:o=>P(s)?O(o,s,0):o}},Et={...et([]),add:()=>{}},v=new WeakSet,L=e=>{if(!v.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${h}" (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
function_path TEXT NOT NULL,
|
|
5
|
-
shard_key TEXT,
|
|
6
|
-
user_id TEXT,
|
|
7
|
-
identity TEXT,
|
|
8
|
-
args TEXT,
|
|
9
|
-
outcome TEXT NOT NULL,
|
|
10
|
-
error_message TEXT,
|
|
11
|
-
error_fingerprint TEXT,
|
|
12
|
-
trace_id TEXT,
|
|
13
|
-
deployment_id TEXT,
|
|
14
|
-
version_tag TEXT,
|
|
15
|
-
duration_ms REAL NOT NULL,
|
|
16
|
-
tables_read TEXT NOT NULL DEFAULT '[]',
|
|
17
|
-
tables_written TEXT NOT NULL DEFAULT '[]',
|
|
18
|
-
cache_hit INTEGER,
|
|
19
|
-
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
20
|
-
)`);for(const t of Ce)try{E(e,`ALTER TABLE "${h}" ADD COLUMN ${t}`)}catch{}v.add(e)}},V=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),tt=e=>e===void 0?null:e?1:0,At=(e,t,s={})=>{L(e);const r=s.captureRaw??!1,n=s.retention??I,i=t.outcome==="error"&&t.errorMessage!==void 0?F({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${h}"
|
|
21
|
-
(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)
|
|
22
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(g(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(g(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:g(t.errorMessage,r),i??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,V(t.tablesRead),V(t.tablesWritten),tt(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${h}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${h}")`,n)},mt=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:g(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:g(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:g(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:B,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)},st="log",nt=e=>e.map(t=>N(t)).join(" "),rt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},_t=(e,t)=>e.length===2&&typeof e[0]=="string"&&rt(e[1])?{fields:M(e[1],t),message:e[0]}:{fields:M(void 0,t),message:nt(e)},yt=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:g(e.fields,s),function:e.functionPath,level:e.level,message:g(e.message,s),rayId:e.rayId,shard:e.shardKey,source:B,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:st,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)},ot=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,Q=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(ot("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))},G=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},it=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},at=e=>{try{return JSON.parse(e)}catch{return}},Tt=(e,t={})=>{L(e);const s=Math.max(1,Math.min(t.limit??I,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(Q(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 i=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
|
|
23
|
-
FROM "${h}" WHERE ${r.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,...n).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:G(o.tables_read),tablesWritten:G(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=it(o.identity);d!==void 0&&(a.identity=d)}if(o.args!==null){const d=at(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=re(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)}},bt=(e,t={})=>{L(e);const s=Math.max(1,Math.min(t.limit??I,1e4)),r=["outcome = 'error'"],n=[];Q(r,n,t),n.push(s);const i=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
-
FROM "${h}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of i){const A=l.error_message??"",{culprit:ee,hash:te,title:k}=F({functionPath:l.function_path,message:A}),S=l.error_fingerprint??te,u=c.get(S);if(u===void 0){c.set(S,{count:1,culprit:ee,firstSeen:l.ts,hash:S,lastSeen:l.ts,sampleMessage:A,status:"open",title:k}),o.set(S,l.ts);continue}u.count+=1,u.firstSeen=Math.min(u.firstSeen,l.ts),u.lastSeen=Math.max(u.lastSeen,l.ts),l.ts>(o.get(S)??Number.NEGATIVE_INFINITY)&&(o.set(S,l.ts),u.sampleMessage=A,u.title=k)}ct(e,c);const a=[...c.values()];return(t.status===void 0?a:a.filter(l=>l.status===t.status)).toSorted((l,A)=>A.lastSeen-l.lastSeen)};export{Et as N,h as R,f as S,At as a,mt as b,et as c,L as d,yt as e,Tt as f,g,pt as h,ht as i,I as j,nt as k,gt as m,M as n,_t as p,bt as r,St as s};
|