@lunora/observability 1.0.0-alpha.200 → 1.0.0-alpha.202
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 +19 -2
- package/dist/index.d.ts +19 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/LogBuffer-DT7Nz0bA.mjs +1 -0
- package/dist/packem_shared/{NO_SENSITIVE_SCOPE-z-NXXakX.mjs → NO_SENSITIVE_SCOPE-BeDNs95f.mjs} +1 -1
- package/dist/packem_shared/{SpanBuffer-C8-8zvYg.mjs → SpanBuffer-DhWVTyym.mjs} +1 -1
- package/dist/packem_shared/{createDatabaseTally-BNj6kmo2.mjs → createDatabaseTally-DxF4KZNq.mjs} +1 -1
- package/dist/packem_shared/createMetrics-8Kcf2_ep.mjs +1 -0
- package/dist/packem_shared/request-log-CgAdxe9y.mjs +26 -0
- package/package.json +2 -2
- package/dist/packem_shared/LogBuffer-BmD4CfV0.mjs +0 -1
- package/dist/packem_shared/createMetrics-C6AXtDTF.mjs +0 -1
- package/dist/packem_shared/request-log-B7gOe-_k.mjs +0 -24
package/dist/index.d.mts
CHANGED
|
@@ -212,8 +212,9 @@ interface LogEvent {
|
|
|
212
212
|
/**
|
|
213
213
|
* Structured fields the caller attached (`ctx.log.info(message, fields)` or a
|
|
214
214
|
* bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
|
|
215
|
-
* JSON-safe primitives (see `shared/log-fields.ts`).
|
|
216
|
-
*
|
|
215
|
+
* JSON-safe primitives (see `shared/log-fields.ts`). An `Error` value arrives
|
|
216
|
+
* as the JSON of its name, message, stack and cause chain; `parseLoggedError`
|
|
217
|
+
* reads it back. Absent for a plain console-style call.
|
|
217
218
|
*/
|
|
218
219
|
fields?: LogFields;
|
|
219
220
|
/** Function path that emitted the line, e.g. `"messages:list"`. */
|
|
@@ -990,6 +991,11 @@ type LogEventInput = LogEvent;
|
|
|
990
991
|
* `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
|
|
991
992
|
* the per-call fields (per-call wins); the result is normalized to a fresh bag
|
|
992
993
|
* of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
|
|
994
|
+
* An `Error` in the fields keeps its stack and `cause` chain: a log line is where
|
|
995
|
+
* a caller logs an error to read it later. Its own fields are copied too (an HTTP
|
|
996
|
+
* client error's `config.headers`), which the caller never chose to log, so each
|
|
997
|
+
* logged Error's record has its credentials masked by key before it is written:
|
|
998
|
+
* the fields reach the Studio buffer, `sink.onLog` and the archive as they are.
|
|
993
999
|
*/
|
|
994
1000
|
declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
|
|
995
1001
|
fields?: LogFields;
|
|
@@ -1846,6 +1852,13 @@ interface LogEntry {
|
|
|
1846
1852
|
/** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
|
|
1847
1853
|
fields?: Record<string, unknown>;
|
|
1848
1854
|
functionPath?: string;
|
|
1855
|
+
/**
|
|
1856
|
+
* The line's identity, set by {@link LogBuffer.push}: the buffer's own random id and the line's number in it, so
|
|
1857
|
+
* it is never reused, not across a clear, a Durable Object restart or another shard's buffer. What a reader keys a
|
|
1858
|
+
* line by: two lines can share every other field (a retry loop), and a live reader's list shifts as lines are
|
|
1859
|
+
* prepended and evicted.
|
|
1860
|
+
*/
|
|
1861
|
+
id?: string;
|
|
1849
1862
|
instance?: string;
|
|
1850
1863
|
level: LogLevel;
|
|
1851
1864
|
message: string;
|
|
@@ -1874,6 +1887,10 @@ declare class LogBuffer {
|
|
|
1874
1887
|
private readonly capacity;
|
|
1875
1888
|
/** How many entries the ring has evicted since it was last cleared. */
|
|
1876
1889
|
private droppedCount;
|
|
1890
|
+
/** This buffer's part of each {@link LogEntry.id}: a restarted Durable Object, or another shard, numbers from 0 again. */
|
|
1891
|
+
private readonly incarnation;
|
|
1892
|
+
/** The next line's number. Not reset by {@link LogBuffer.clear}, so a line pushed after a clear never takes a cleared line's id. */
|
|
1893
|
+
private nextNumber;
|
|
1877
1894
|
constructor(capacity?: number);
|
|
1878
1895
|
/**
|
|
1879
1896
|
* Entries evicted for capacity since the last {@link LogBuffer.clear}.
|
package/dist/index.d.ts
CHANGED
|
@@ -212,8 +212,9 @@ interface LogEvent {
|
|
|
212
212
|
/**
|
|
213
213
|
* Structured fields the caller attached (`ctx.log.info(message, fields)` or a
|
|
214
214
|
* bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
|
|
215
|
-
* JSON-safe primitives (see `shared/log-fields.ts`).
|
|
216
|
-
*
|
|
215
|
+
* JSON-safe primitives (see `shared/log-fields.ts`). An `Error` value arrives
|
|
216
|
+
* as the JSON of its name, message, stack and cause chain; `parseLoggedError`
|
|
217
|
+
* reads it back. Absent for a plain console-style call.
|
|
217
218
|
*/
|
|
218
219
|
fields?: LogFields;
|
|
219
220
|
/** Function path that emitted the line, e.g. `"messages:list"`. */
|
|
@@ -990,6 +991,11 @@ type LogEventInput = LogEvent;
|
|
|
990
991
|
* `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
|
|
991
992
|
* the per-call fields (per-call wins); the result is normalized to a fresh bag
|
|
992
993
|
* of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
|
|
994
|
+
* An `Error` in the fields keeps its stack and `cause` chain: a log line is where
|
|
995
|
+
* a caller logs an error to read it later. Its own fields are copied too (an HTTP
|
|
996
|
+
* client error's `config.headers`), which the caller never chose to log, so each
|
|
997
|
+
* logged Error's record has its credentials masked by key before it is written:
|
|
998
|
+
* the fields reach the Studio buffer, `sink.onLog` and the archive as they are.
|
|
993
999
|
*/
|
|
994
1000
|
declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
|
|
995
1001
|
fields?: LogFields;
|
|
@@ -1846,6 +1852,13 @@ interface LogEntry {
|
|
|
1846
1852
|
/** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
|
|
1847
1853
|
fields?: Record<string, unknown>;
|
|
1848
1854
|
functionPath?: string;
|
|
1855
|
+
/**
|
|
1856
|
+
* The line's identity, set by {@link LogBuffer.push}: the buffer's own random id and the line's number in it, so
|
|
1857
|
+
* it is never reused, not across a clear, a Durable Object restart or another shard's buffer. What a reader keys a
|
|
1858
|
+
* line by: two lines can share every other field (a retry loop), and a live reader's list shifts as lines are
|
|
1859
|
+
* prepended and evicted.
|
|
1860
|
+
*/
|
|
1861
|
+
id?: string;
|
|
1849
1862
|
instance?: string;
|
|
1850
1863
|
level: LogLevel;
|
|
1851
1864
|
message: string;
|
|
@@ -1874,6 +1887,10 @@ declare class LogBuffer {
|
|
|
1874
1887
|
private readonly capacity;
|
|
1875
1888
|
/** How many entries the ring has evicted since it was last cleared. */
|
|
1876
1889
|
private droppedCount;
|
|
1890
|
+
/** This buffer's part of each {@link LogEntry.id}: a restarted Durable Object, or another shard, numbers from 0 again. */
|
|
1891
|
+
private readonly incarnation;
|
|
1892
|
+
/** The next line's number. Not reset by {@link LogBuffer.clear}, so a line pushed after a clear never takes a cleared line's id. */
|
|
1893
|
+
private nextNumber;
|
|
1877
1894
|
constructor(capacity?: number);
|
|
1878
1895
|
/**
|
|
1879
1896
|
* Entries evicted for capacity since the last {@link LogBuffer.clear}.
|
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-8Kcf2_ep.mjs";import{createDatabaseTally as A,formatTally as N,instrumentDatabase as p,instrumentSqlClient as C}from"./packem_shared/createDatabaseTally-DxF4KZNq.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-CgAdxe9y.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i=500,r=t=>Number.isFinite(t)&&t>=1?Math.trunc(t):500;class n{buffer=[];capacity;droppedCount=0;incarnation=crypto.randomUUID();nextNumber=0;constructor(e=500){this.capacity=r(e)}get dropped(){return this.droppedCount}get size(){return this.buffer.length}clear(){this.buffer.length=0,this.droppedCount=0}entries(){return this.buffer.toReversed()}push(e){this.buffer.push({...e,id:`${this.incarnation}:${String(this.nextNumber)}`}),this.nextNumber+=1,this.buffer.length>this.capacity&&(this.buffer.shift(),this.droppedCount+=1)}}export{i as DEFAULT_CAPACITY,n as LogBuffer,r as normalizeCapacity};
|
package/dist/packem_shared/{NO_SENSITIVE_SCOPE-z-NXXakX.mjs → NO_SENSITIVE_SCOPE-BeDNs95f.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-CgAdxe9y.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_CAPACITY as I,normalizeCapacity as l}from"./LogBuffer-
|
|
1
|
+
import{DEFAULT_CAPACITY as I,normalizeCapacity as l}from"./LogBuffer-DT7Nz0bA.mjs";class C{buffer=[];capacity;traceCounts=new Map;droppedCount=0;constructor(c=I){this.capacity=l(c)}get dropped(){return this.droppedCount}get size(){return this.buffer.length}clear(){this.buffer.length=0,this.traceCounts.clear(),this.droppedCount=0}entries(){return[...this.buffer]}hasTrace(c){return this.traceCounts.has(c)}push(c){const r=Object.freeze({...c});if(this.buffer.push(r),this.traceCounts.set(r.traceId,(this.traceCounts.get(r.traceId)??0)+1),this.buffer.length>this.capacity){const o=this.buffer.shift(),n=(this.traceCounts.get(o.traceId)??1)-1;n===0?this.traceCounts.delete(o.traceId):this.traceCounts.set(o.traceId,n),this.droppedCount+=1}}}const b=50,v=d=>{const c=new Map;for(const r of d){const o=c.get(r.traceId);o===void 0?c.set(r.traceId,[r]):o.push(r)}return c},T=(d,c)=>{const r=d.find(n=>n.dispatch===!0);if(r!==void 0)return r;const o=d.toSorted((n,t)=>n.startTs-t.startTs);return o.find(n=>!c.has(n.parentSpanId))??o[0]},g=(d,c)=>{const r=new Map([[d.spanId,0]]);return o=>{const n=[],t=new Set;let e=o,a=0;for(;;){const i=r.get(e.spanId);if(i!==void 0){a=i;break}if(t.has(e.spanId))break;t.add(e.spanId),n.push(e);const h=c.get(e.parentSpanId);if(h===void 0)break;e=h}for(const[i,h]of n.toReversed().entries())r.set(h.spanId,a+i+1);return r.get(o.spanId)??a}},m=(d,c)=>{const r=new Map(d.map(t=>[t.spanId,t.depth])),o=new Map,n=[];for(const t of d){if(t.spanId===c){n.push(t);continue}const e=r.get(t.parentSpanId)===t.depth-1?t.parentSpanId:c,a=o.get(e);a===void 0?o.set(e,[t]):a.push(t)}for(const t of o.values())t.sort((e,a)=>e.offsetMs-a.offsetMs);return{childrenOf:o,roots:n}},M=(d,c)=>{const{childrenOf:r,roots:o}=m(d,c),n=[],t=new Set,e=o.toReversed();for(;e.length>0;){const a=e.pop();if(t.has(a))continue;t.add(a),n.push(a);const i=r.get(a.spanId);if(i!==void 0)for(const h of i.toReversed())e.push(h)}if(n.length!==d.length)for(const a of d)t.has(a)||n.push(a);return n},k=(d,c=b)=>{const r=v(d),o=[...r.entries()].map(([t,e])=>({group:e,startTs:Math.min(...e.map(a=>a.startTs)),traceId:t})).toSorted((t,e)=>e.startTs-t.startTs).slice(0,c),n=[];for(const{group:t,traceId:e}of o){const a=new Map(t.map(s=>[s.spanId,s])),i=T(t,a);if(i===void 0)continue;const h=g(i,a),{startTs:u}=i,f=Math.max(...t.map(s=>s.startTs+s.durationMs)),p=t.map(s=>({...s.attributes===void 0?{}:{attributes:s.attributes},depth:h(s),durationMs:s.durationMs,...s.error===void 0?{}:{error:s.error},...s.events===void 0?{}:{events:s.events},...s.kind===void 0?{}:{kind:s.kind},name:s.name,offsetMs:Math.max(0,s.startTs-u),ok:s.ok,parentSpanId:s.parentSpanId,spanId:s.spanId}));n.push({durationMs:f-u,functionPath:i.functionPath,ok:t.every(s=>s.ok),rootName:i.name,...i.shardKey===void 0?{}:{shardKey:i.shardKey},spans:M(p,i.spanId),startTs:u,traceId:e})}return{total:r.size,traces:n.toSorted((t,e)=>e.startTs-t.startTs)}};export{b as DEFAULT_TRACE_LIMIT,C as SpanBuffer,k as foldTraces};
|
package/dist/packem_shared/{createDatabaseTally-BNj6kmo2.mjs → createDatabaseTally-DxF4KZNq.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-CgAdxe9y.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as k,g as O,h as w,n as y}from"./request-log-CgAdxe9y.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 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};
|
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.202",
|
|
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.10",
|
|
48
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
48
|
+
"@lunora/shard-engine": "^1.0.0-alpha.187",
|
|
49
49
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
50
50
|
"@visulima/redact": "5.0.0"
|
|
51
51
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=500,r=t=>Number.isFinite(t)&&t>=1?Math.trunc(t):500;class i{buffer=[];capacity;droppedCount=0;constructor(e=500){this.capacity=r(e)}get dropped(){return this.droppedCount}get size(){return this.buffer.length}clear(){this.buffer.length=0,this.droppedCount=0}entries(){return this.buffer.toReversed()}push(e){this.buffer.push(e),this.buffer.length>this.capacity&&(this.buffer.shift(),this.droppedCount+=1)}}export{s as DEFAULT_CAPACITY,i as LogBuffer,r as normalizeCapacity};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as k,g as O,h as w,n as y}from"./request-log-B7gOe-_k.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};
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{fingerprintError as z}from"@lunora/fingerprint";import{createRedactor as ae,standardRules as ce}from"@visulima/redact";import{readIssueStates as de}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{p as le}from"./prune-marker-CksedkkK.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const I=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)}},M=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:I(e),D=(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[n,r]of Object.entries(t))D(s,n,M(r));if(e!==void 0)for(const[n,r]of Object.entries(e))D(s,n,M(r));return Object.keys(s).length===0?void 0:s},fe=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"]),ue=new Set(["card","pass","pin","session"]),pe=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),ge=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),he=new Set(["card no","connection string","database url","one time"]),Se=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],Ee=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"]),_e=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),me=new Set(["max","min","num","total"]),T=4096,Ae=128,ye=16384,p="<REDACTED>",be="[redaction budget exceeded]",Te=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,Oe=(e,t)=>{const s=j(e[t]),n=t>0?j(e[t-1]):void 0;if(fe.has(s))return s;if(n!==void 0){if(s==="key"&&pe.has(n))return"key";if(s==="code"&&ge.has(n))return"code";if(he.has(`${n} ${s}`))return`${n} ${s}`}return Se.some(r=>s.endsWith(r))?s:void 0},H=e=>{const t=Te(e);if(t.length===0)return"none";const s=_e.has(t.at(-1))||me.has(t[0]);for(let n=t.length-1;n>=0;n-=1){const r=Oe(t,n);if(r!==void 0)return s?"count-secret":t.slice(n+1).every(a=>Ee.has(a))?ue.has(r)&&n===t.length-1?"scalar-secret":"secret":"none"}return"none"},Ne=e=>typeof e=="boolean"||e===null||e===void 0?e:p,Ie=e=>{const t=e.indexOf("://")+3,s=e.slice(t),n=s.split(/[?#]/,1)[0],r=n.lastIndexOf("@"),a=n.indexOf(":"),i=n.indexOf("/"),o=a!==-1&&/^\d+$/.test(n.slice(a+1,i===-1?void 0:i)),c=a!==-1&&!o&&(i===-1||a<i);if(r===-1&&c&&s.includes("@",n.length))return e.slice(0,t);const d=r!==-1&&(i===-1||r<i||a!==-1&&a<r&&!o);return`${e.slice(0,t)}${d?n.slice(r+1):n}`},we=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Re=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Le=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,B=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,K=[{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-]|${B})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,xe=new RegExp([...K.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${B})${t}${e}`),ke].join("|"),"g"),Me=new RegExp([...K.map(({prefix:e})=>e),"eyJ"].join("|")),De=/(\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,P=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,$e=e=>{let t="",s=0;m.lastIndex=0;for(let n=m.exec(e);n!==null;n=m.exec(e)){const r=H(n[2]),a=n.index+n[0].length;C.lastIndex=a;const i=r==="none"?null:C.exec(e);if(i===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(i[0])){m.lastIndex=Math.max(a,n.index+1);continue}const o=i[0],c=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;c===""&&n[3]===":"&&(P.lastIndex=d,d+=P.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${c}${p}${o.length>c.length&&o.endsWith(c)?c:""}`,s=d,m.lastIndex=s}return t+e.slice(s)},je=/[:=@]|basic|bearer|digest|-u\b|--/i,Ce=e=>{const t=Me.test(e);if(!t&&!je.test(e))return e;const s=e.replaceAll(Re,`-----BEGIN $1-----${p}`).replaceAll(we,Ie).replaceAll(Le,`$1 ${p}`);return $e((t?s.replaceAll(xe,p):s).replaceAll(De,`$1$2$3${p}`))},Pe=(e,t)=>{if(t.remaining<=0)return be;const s=e.slice(0,T+Ae);t.remaining-=s.length;const n=Ce(s);return n.length>T||e.length>s.length?`${n.slice(0,T)}…[truncated]`:n},ve=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),A=Symbol("no-json"),Ue=e=>{const{toJSON:t}=e;if(typeof t!="function")return A;try{const s=t.call(e);return s===e?A:s}catch{return A}},Ve=32,b=(e,t,s,n,r)=>{if(typeof e=="string")return n?p:Pe(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&ve(e))return e;if(t.has(e)||s>=Ve)return p;const a=Array.isArray(e)?A:Ue(e);if(a!==A){t.add(e);const o=b(a,t,s+1,n,r);return t.delete(e),o}t.add(e);const i=Array.isArray(e)?e.map(o=>b(o,t,s+1,n,r)):Object.fromEntries(Object.entries(e).map(([o,c])=>{const d=H(o);return d==="secret"||d==="scalar-secret"&&(typeof c!="object"||c===null)?[o,Ne(c)]:[o,b(c,t,s+1,d==="count-secret"&&(typeof c=="string"||Array.isArray(c)),r)]}));return t.delete(e),i},Z=e=>b(e,new WeakSet,0,!1,{remaining:ye}),Ge=(e,t)=>{if(e.size<t)return;const s=e.keys().next().value;s!==void 0&&e.delete(s)},Fe=32,We=(e,t)=>{let s=t,n;const r=(i,o,c)=>{const d=Object.getOwnPropertyDescriptor(i,o);return d!==void 0&&"value"in d&&n(d.value,c+1)},a=(i,o)=>{if(Array.isArray(i)){for(let d=0;d<i.length;d+=1)if(!r(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||!r(i,d,o))return!1;return!0};return n=(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>=Fe||"toJSON"in i?!1:a(i,o)),n(e,0)},g="__lunora_reqlog__",Je=6e4,w=1e3,q="lunora",Xe=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],ze=ae(ce,{exclude:["pass"]}),Nt=(e,t=!1)=>t||e===null||e===void 0?e:Z(e),h=(e,t=!1)=>t||e===null||e===void 0?e:ze(Z(e)),f="«sensitive»",It=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,n])=>[s,t.has(s)?f:n])),He=8,Y=4,Q=3,R=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),Be=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${R(e)}(?![\p{L}\p{N}])`,"gu"),Ke=e=>new RegExp(String.raw`(?<=["'])${R(e)}(?=["'])`,"gu"),v=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${R(e)}(?![\p{L}\p{N}])`,"gu"),Ze=new Set(["false","true"]),qe=new RegExp("^\\p{N}+$","u"),L=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<Y?[e]:[e,t]},ee=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},te=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),se=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()])]},Ye=e=>{const t=te(e);if(t.length===0)return[];const s=ee(t);return[...s===void 0||s.length===0?[]:L(s),...se(t)]},Qe=e=>e instanceof Error&&e.message.length>0?L(e.message):[],et=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],tt=(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(...L(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(...Ye(r));else if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r),t.push(...Qe(r));for(const a of Object.values(r))n.push(a);n.push(...et(r))}}},wt=(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(I(r)),tt(r,s)}return s},st=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),rt=(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 a of st(r))t.push(a);for(const a of Object.values(r))n.push(a)}}},Rt=(e,t)=>{const s=[];for(const n of t)Object.hasOwn(e,n)&&rt(e[n],s);return s},nt=(e,t)=>{if(Ze.has(t))return e.replaceAll(Ke(t),f).replaceAll(v(t,"="),f);if(t.length>=Y)return e.replaceAll(t,f);if(t.length>=Q)return e.includes(t)?e.replaceAll(Be(t),f):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(f));return qe.test(t)?s:s.replaceAll(v(t,"=:"),f)},y=(e,t)=>{if(t.includes(e))return f;let s=e;for(const n of t.toSorted((r,a)=>a.length-r.length))s=nt(s,n);return s},ot={names:new Set,texts:[]},U=e=>e.texts.length>0||e.names.size>0,it=(e,t)=>t.names.has(e)?f:y(e,t.texts),at=(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)}`},ct=(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 n=!1;const r={};for(const[a,i]of Object.entries(e)){const o=s(i),c=at(r,it(a,t));n||=o!==i||c!==a,r[c]=o}return n?r:e},dt=(e,t)=>{const s=te(e);if(s.length===0)return!1;const n=ee(s);return n!==void 0&&t.texts.some(r=>n.includes(r))||se(s).some(r=>y(r,t.texts)!==r)},N=(e,t,s,n=new Set)=>{if(typeof e=="string")return y(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return dt(e,t)?f:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const a=String(e);return a.length>=Q&&t.texts.includes(a)?f:e}if(e instanceof Error){const a=String(e),i=y(a,t.texts);return i===a?e:i}if(typeof e!="object"||e===null)return e;if(s>=He||n.has(e))return f;n.add(e);const r=ct(e,t,a=>N(a,t,s+1,n));return n.delete(e),r},lt=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},n=!1,r=0;const a=()=>{n&&r===0&&(s=ot)},i=o=>s.texts.length===0?o:y(o,s.texts);return{add(o,c=[]){!n&&(o.length>0||c.length>0)&&(s={names:new Set([...s.names,...c]),texts:[...new Set([...s.texts,...o])]})},clear(){n=!0,a()},hold(){r+=1;let o=!1;return()=>{o||(o=!0,r-=1,a())}},fields:o=>o===void 0||!U(s)?o:N(o,s,0),name:o=>s.names.has(o)?f:i(o),text:i,value:o=>U(s)?N(o,s,0):o}},Lt={...lt([]),add:()=>{}},V=new WeakSet,k=e=>{if(!V.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${g}" (
|
|
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 Xe)try{E(e,`ALTER TABLE "${g}" ADD COLUMN ${t}`)}catch{}V.add(e)}},G=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),ft=e=>e===void 0?null:e?1:0,ut=256,F=1024,O=new Map,re=e=>{if(!We(e,F))return;const t=JSON.stringify(e);if(t.length>F)return;const s=O.get(t);if(s!==void 0)return s;const n=JSON.stringify(h(e)),r={json:n,value:JSON.parse(n)};return Ge(O,ut),O.set(t,r),r},W=(e,t)=>{const s=t?void 0:re(e);return s===void 0?JSON.stringify(h(e,t)):s.json},J=(e,t)=>{const s=t?void 0:re(e);return s===void 0?h(e,t):s.value},kt=(e,t,s={})=>{k(e);const n=s.captureRaw??!1,r=s.retention??w,a=t.outcome==="error"&&t.errorMessage!==void 0?z({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${g}"
|
|
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:W(t.identity,n),t.redactedArgs===void 0?null:W(t.redactedArgs,n),t.outcome,t.errorMessage===void 0?null:h(t.errorMessage,n),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,G(t.tablesRead),G(t.tablesWritten),ft(t.cacheHit),t.subscriptionsReRun??0),le(e,Math.floor(t.ts/Je),"request-log",()=>{E(e,`DELETE FROM "${g}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${g}")`,r)})},xt=(e,t={})=>{const s=t.captureRaw??!1,n={args:e.redactedArgs===void 0?void 0:J(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:J(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:q,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)},pt="log",gt=e=>e.map(t=>I(t)).join(" "),ht=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Mt=(e,t)=>e.length===2&&typeof e[0]=="string"&&ht(e[1])?{fields:$(e[1],t),message:e[0]}:{fields:$(void 0,t),message:gt(e)},Dt=(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:q,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:pt,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)},St=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,ne=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(St("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))},X=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},Et=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},_t=e=>{try{return JSON.parse(e)}catch{return}},$t=(e,t={})=>{k(e);const s=Math.max(1,Math.min(t.limit??w,1e4)),n=["seq > ?"],r=[t.sinceSeq??0];if(ne(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 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
|
|
23
|
-
FROM "${g}" WHERE ${n.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...r).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:X(o.tables_read),tablesWritten:X(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=Et(o.identity);d!==void 0&&(c.identity=d)}if(o.args!==null){const d=_t(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})},mt=(e,t)=>{const s=de(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)}},jt=(e,t={})=>{k(e);const s=Math.max(1,Math.min(t.limit??w,1e4)),n=["outcome = 'error'"],r=[];ne(n,r,t),r.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
-
FROM "${g}" WHERE ${n.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),i=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:oe,hash:ie,title:x}=z({functionPath:l.function_path,message:_}),S=l.error_fingerprint??ie,u=i.get(S);if(u===void 0){i.set(S,{count:1,culprit:oe,firstSeen:l.ts,hash:S,lastSeen:l.ts,sampleMessage:_,status:"open",title:x}),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=x)}mt(e,i);const c=[...i.values()];return(t.status===void 0?c:c.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{Lt as N,g as R,f as S,kt as a,xt as b,lt as c,k as d,Dt as e,$t as f,h as g,Nt as h,wt as i,w as j,gt as k,It as m,$ as n,Mt as p,jt as r,Rt as s};
|