@lunora/observability 1.0.0-alpha.122 → 1.0.0-alpha.124

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 CHANGED
@@ -160,6 +160,14 @@ interface EvaluationInput {
160
160
  /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
161
161
  score: number;
162
162
  }
163
+ /** The unredacted facts about a thrown value, for observability sinks only. */
164
+ interface ErrorDetail {
165
+ /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
+ code?: string;
167
+ message: string;
168
+ name: string;
169
+ stack?: string;
170
+ }
163
171
  /**
164
172
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
165
173
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -173,6 +181,14 @@ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" |
173
181
  interface LogEvent {
174
182
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
175
183
  args: unknown[];
184
+ /**
185
+ * The first `Error` the call was handed, as an argument
186
+ * (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
187
+ * unredacted `message`, `stack`, and `code` when it carries one. Absent when
188
+ * the line logged no `Error`. An error tracker reads this rather than parsing
189
+ * the rendered `message`.
190
+ */
191
+ error?: ErrorDetail;
176
192
  /**
177
193
  * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
178
194
  * event** via `ctx.log.event(name, fields)` rather than as a human-readable
package/dist/index.d.ts CHANGED
@@ -160,6 +160,14 @@ interface EvaluationInput {
160
160
  /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
161
161
  score: number;
162
162
  }
163
+ /** The unredacted facts about a thrown value, for observability sinks only. */
164
+ interface ErrorDetail {
165
+ /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
+ code?: string;
167
+ message: string;
168
+ name: string;
169
+ stack?: string;
170
+ }
163
171
  /**
164
172
  * Severity of a `ctx.log.*` call. The five console method names (`log` is the
165
173
  * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
@@ -173,6 +181,14 @@ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" |
173
181
  interface LogEvent {
174
182
  /** Raw arguments passed to the `ctx.log.*` call, in order. */
175
183
  args: unknown[];
184
+ /**
185
+ * The first `Error` the call was handed, as an argument
186
+ * (`ctx.log.error("failed", err)`) or a fields value (`{ err }`): its `name`,
187
+ * unredacted `message`, `stack`, and `code` when it carries one. Absent when
188
+ * the line logged no `Error`. An error tracker reads this rather than parsing
189
+ * the rendered `message`.
190
+ */
191
+ error?: ErrorDetail;
176
192
  /**
177
193
  * OTel `LogRecord.eventName` — set when the line was emitted as a **structured
178
194
  * event** via `ctx.log.event(name, fields)` rather than as a human-readable
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as o,AUTH_METRICS_BUCKET_RETENTION as T,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.mjs";import{createMetrics as S,createSpanCollector as n,createTracedFetch as i,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-Byt8y5Kw.mjs";import{createDatabaseTally as p,formatTally as A,instrumentDatabase as C,instrumentSqlClient as N}from"./packem_shared/createDatabaseTally-BGQNFq78.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as R,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,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 H,readFunctionMetricIndexHits as O,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as D,recordFunctionMetric as h}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{applyHostRootSpan as q,setHostSpanAttributes as v}from"./packem_shared/applyHostRootSpan-DToRfMn8.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as G,explainIssue as X,parseExplainIssueArgs as P}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as V,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{M as Z}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as ee,recordMetricHistory as re}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as oe,readQueryMetrics as Te,recordQueryMetric as ae}from"./packem_shared/readQueryInsights-DkQfxGfP.mjs";import{R as Ee,a as _e,e as ce,b as Se,c as ne,p as ie,r as Ie,d as ue,f as Me}from"./packem_shared/request-log-BmtC_cDV.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Ae,MIN_AUTH_SECRET_LENGTH as Ce,buildSecurityAudit as Ne}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Re,foldTraces as Ue}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as me}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as le}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,o as AUTH_METRICS_BUCKET_MS,T as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,G as DEFAULT_EXPLAIN_ISSUE_MODEL,R as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d 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,V as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,Ae as MIN_ADMIN_TOKEN_LENGTH,Ce as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,Ee as REQUEST_LOG_TABLE,Re as SpanBuffer,_e as appendRequestLogEntry,q as applyHostRootSpan,Ne as buildSecurityAudit,p as createDatabaseTally,S as createMetrics,n as createSpanCollector,i as createTracedFetch,I as createTracer,u as dispatchRootSpan,ce as emitLogEvent,Se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,ne as ensureRequestLogTable,X as explainIssue,me as findDanglingReferences,Ue as foldTraces,A as formatTally,C as instrumentDatabase,N as instrumentSqlClient,g as mergeScanAttribution,P as parseExplainIssueArgs,ie as parseLogArgs,E as readAuthMetrics,Ie as readErrorIssues,H as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,D as readFunctionMetricsTotals,ee as readMetricHistory,oe as readQueryInsights,Te as readQueryMetrics,ue as readRequestLog,_ as recordAuthEvent,h as recordFunctionMetric,re as recordMetricHistory,ae as recordQueryMetric,Me as redactArgs,le as resolveTraceAnchor,v as setHostSpanAttributes,z as upsertIssueState};
1
+ import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as o,AUTH_METRICS_BUCKET_RETENTION as T,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.mjs";import{createMetrics as S,createSpanCollector as n,createTracedFetch as i,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-D8wcdkye.mjs";import{createDatabaseTally as p,formatTally as A,instrumentDatabase as C,instrumentSqlClient as N}from"./packem_shared/createDatabaseTally-giaawEcd.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as R,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,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 H,readFunctionMetricIndexHits as O,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as D,recordFunctionMetric as h}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{applyHostRootSpan as q,setHostSpanAttributes as v}from"./packem_shared/applyHostRootSpan-DToRfMn8.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as G,explainIssue as X,parseExplainIssueArgs as P}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as V,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{M as Z}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as ee,recordMetricHistory as re}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as oe,readQueryMetrics as Te,recordQueryMetric as ae}from"./packem_shared/readQueryInsights-DkQfxGfP.mjs";import{R as Ee,a as _e,e as ce,b as Se,c as ne,p as ie,r as Ie,d as ue,f as Me}from"./packem_shared/request-log-YtJxmSWX.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Ae,MIN_AUTH_SECRET_LENGTH as Ce,buildSecurityAudit as Ne}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Re,foldTraces as Ue}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as me}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as le}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,o as AUTH_METRICS_BUCKET_MS,T as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,G as DEFAULT_EXPLAIN_ISSUE_MODEL,R as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d 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,V as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,Ae as MIN_ADMIN_TOKEN_LENGTH,Ce as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,Ee as REQUEST_LOG_TABLE,Re as SpanBuffer,_e as appendRequestLogEntry,q as applyHostRootSpan,Ne as buildSecurityAudit,p as createDatabaseTally,S as createMetrics,n as createSpanCollector,i as createTracedFetch,I as createTracer,u as dispatchRootSpan,ce as emitLogEvent,Se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,ne as ensureRequestLogTable,X as explainIssue,me as findDanglingReferences,Ue as foldTraces,A as formatTally,C as instrumentDatabase,N as instrumentSqlClient,g as mergeScanAttribution,P as parseExplainIssueArgs,ie as parseLogArgs,E as readAuthMetrics,Ie as readErrorIssues,H as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,D as readFunctionMetricsTotals,ee as readMetricHistory,oe as readQueryInsights,Te as readQueryMetrics,ue as readRequestLog,_ as recordAuthEvent,h as recordFunctionMetric,re as recordMetricHistory,ae as recordQueryMetric,Me as redactArgs,le as resolveTraceAnchor,v as setHostSpanAttributes,z as upsertIssueState};
@@ -1 +1 @@
1
- import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-BmtC_cDV.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,d as parseLogArgs,p as readErrorIssues,n as readRequestLog,u as redactArgs,T as redactSecrets,i as renderLogMessage};
1
+ import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-YtJxmSWX.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,d as parseLogArgs,p as readErrorIssues,n as readRequestLog,u as redactArgs,T as redactSecrets,i as renderLogMessage};
@@ -1,2 +1,2 @@
1
- import{o as y}from"./otlp-DR7601NL.mjs";import{f as O}from"./request-log-BmtC_cDV.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"]),d="OTHER",g=/^[a-z]+/iu,R=t=>{if(typeof t!="string")return d;let e=0;for(;e<t.length;){const a=t.charAt(e);if(a==="("||a.trim()==="")e+=1;else if(t.startsWith("--",e)){const s=t.indexOf(`
1
+ import{o as y}from"./otlp-DR7601NL.mjs";import{f as O}from"./request-log-YtJxmSWX.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"]),d="OTHER",g=/^[a-z]+/iu,R=t=>{if(typeof t!="string")return d;let e=0;for(;e<t.length;){const a=t.charAt(e);if(a==="("||a.trim()==="")e+=1;else if(t.startsWith("--",e)){const s=t.indexOf(`
2
2
  `,e);if(s===-1)return d;e=s+1}else if(t.startsWith("/*",e)){const s=t.indexOf("*/",e+2);if(s===-1)return d;e=s+2}else break}const r=g.exec(t.slice(e,e+16))?.[0].toUpperCase();return r!==void 0&&h.has(r)?r:d},p=t=>t??"other_sql",S=100,m=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),A=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),I=(t,e)=>{if(!A.has(t))return;const r=e[0];return typeof r=="string"&&r.length>0?r:void 0},f=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),L=(t,e,r)=>r==="redact"?O(f(t),e.captureRaw):e.captureRaw===!0?f(t):E(t),u=(t,e,r)=>{const{durationMs:a,failure:s,startTs:n}=e;return{durationMs:a,...s===void 0?{}:{error:{message:L(s,t,r),type:E(s)}},functionPath:t.functionPath,kind:"client",ok:s===void 0,parentSpanId:t.anchor.rootSpanId,...t.anchor.rayId===void 0?{}:{rayId:t.anchor.rayId},shardKey:t.shardKey,spanId:y(8),startTs:n,traceId:t.anchor.traceId,userId:t.userId()}},l=async(t,e,r,a)=>{const s=Date.now();let n,o;try{return o=await r(),o}catch(i){throw n=i,i}finally{const i=Date.now()-s,{tally:c}=t;c.calls+=1,c.durationMs+=i,c.perOperation[e]=(c.perOperation[e]??0)+1,n!==void 0&&(c.errors+=1);try{t.mode==="spans"&&(c.spansEmitted>=S?c.spansTruncated=!0:(c.spansEmitted+=1,t.record(a({durationMs:i,failure:n,result:o,startTs:s}))))}catch{}}},T=(t,e,r)=>{const a=new Map;return new Proxy({},{get(s,n){const o=Reflect.get(t,n,t);if(typeof n!="string"||typeof o!="function"||!e(n))return o;let i=a.get(n);return i===void 0&&(i=r(n,o.bind(t)),a.set(n,i)),i},getOwnPropertyDescriptor(s,n){const o=Reflect.getOwnPropertyDescriptor(t,n);return o===void 0?void 0:{...o,configurable:!0}},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(s,n){return Reflect.has(t,n)},ownKeys(){return Reflect.ownKeys(t)}})},b=(t,e)=>e.mode==="off"?t:T(t,r=>m.has(r),(r,a)=>async(...s)=>{const n=I(r,s);return l(e,r,()=>a(...s),o=>({...u(e,o,"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}`}))}),N=(t,e)=>{if(e.mode==="off")return t;const r=p(t.dbSystem);return T(t,a=>a==="query",(a,s)=>async(...n)=>{const o=R(n[0]);return l(e,o,()=>s(...n),i=>({...u(e,i,"type-only"),attributes:{"db.operation.name":o,...Array.isArray(i.result)?{"db.response.returned_rows":i.result.length}:{},"db.system.name":r},name:`sql.${o}`}))})},C=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),_=(t,e="db")=>{const r={[`${e}.calls`]:t.calls,[`${e}.duration_ms`]:t.durationMs};t.errors>0&&(r[`${e}.errors`]=t.errors),t.spansTruncated&&(r[`${e}.spans_truncated`]=!0);for(const[a,s]of Object.entries(t.perOperation))r[`${e}.op.${a}`]=s;return r};export{C as createDatabaseTally,_ as formatTally,b as instrumentDatabase,N as instrumentSqlClient};
@@ -1 +1 @@
1
- import{f as _,g as k,n as y}from"./request-log-BmtC_cDV.mjs";import{o as x,b as L,O as K}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as U}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as O}from"./resolveTraceAnchor-DDAPZRBB.mjs";const q=/[\w.-]/u,C=t=>{let e="";for(const r of t)e+=q.test(r)?r:"_";return e},X=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=C(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},B=t=>{const e=Object.keys(t);if(e.length===0||!e.every(a=>a==="attributes"||a==="kind"||a==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(K,r)},V=128,G=128,z=128,b=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[a,n]of Object.entries(e)){const s=!Object.hasOwn(t,a);s&&r>=z||(s&&(r+=1),t[a]=n)}},j=t=>{const e=y(t);if(e===void 0||Object.keys(e).length<=z)return e;const r={};return b(r,e),r},J=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},Q=t=>{try{return new URL(t).host}catch{return t}},W=(t,e)=>{try{return t(new URL(e))}catch{return!1}},Y=t=>t===void 0?{}:B(t)?t:{attributes:t},H=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},Z=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},a={spanContext:()=>t,addEvent:(n,s)=>{if(r.events.length>=V)return;const o=k(j(s),e);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=G)return;const s=k(j(n.attributes),e);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{b(r.attributes,y(X(n)))},recordException:n=>{const s=n instanceof Error?n.message:String(n);a.addEvent("exception",{"exception.message":_(s,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":O(n)})},setAttribute:(n,s)=>{b(r.attributes,y({[n]:s}))},setAttributes:n=>{b(r.attributes,y(n))}};return{collected:r,handle:a}},st=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:a,functionPath:n,record:s,resolveHostTracing:o,shardKey:c,userId:f}=t,d=m=>async(I,E,u,P)=>{const l=P?.spanId??x(8),w=P?.parentSpanId??m,i=Date.now(),g=Y(u),D=y(g.attributes),{collected:T,handle:F}=Z({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),R=async S=>{let p=!0,v;try{return await E(d(l),F)}catch(h){p=!1;const A=h instanceof Error?h.message:String(h);throw v={message:_(A,r),type:O(h)},h}finally{const h=Date.now()-i,A=f(),N={};b(N,D),b(N,T.attributes);const M=k(N,r),$=[...g.links??[],...T.links];try{s({...Object.keys(M).length===0?{}:{attributes:M},durationMs:h,...T.events.length===0?{}:{events:T.events},...v===void 0?{}:{error:v},functionPath:n,...g.kind===void 0||g.kind==="internal"?{}:{kind:g.kind},...$.length===0?{}:{links:$},name:I,ok:p,parentSpanId:w,...H(e),shardKey:c,spanId:l,startTs:i,userId:A})}catch{}if(S!==void 0)try{U(S,{attributes:M,durationMs:h,error:v,functionPath:n,ok:p,shardKey:c,userId:A})}catch{}}};if(a===!0&&o!==void 0){let S=!1;try{const p=await o();if(p!==void 0&&typeof p.enterSpan=="function")return await p.enterSpan(I,v=>(S=!0,R(v)))}catch(p){if(S)throw p}}return await R()};return d(e.rootSpanId)},at=(t,e)=>{const{anchor:r,captureRaw:a=!1,functionPath:n,propagate:s=!0,record:o,shardKey:c,userId:f}=t;return async(d,m)=>{const I=x(8),E=Date.now(),u=new Request(d,m);(typeof s=="function"?W(s,u.url):s)&&u.headers.set("traceparent",L(r.traceId,I,r.sampled??!0));let l,w;try{const i=await e(u);return w=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const g=i instanceof Error?i.message:String(i);throw l={message:_(g,a),type:O(i)},i}finally{try{o({attributes:{"http.request.method":u.method,...w===void 0?{}:{"http.response.status_code":w},"url.full":J(u.url)},durationMs:Date.now()-E,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${Q(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,...H(r),shardKey:c,spanId:I,startTs:E,userId:f()})}catch{}}}},ot=t=>{const{functionPath:e,record:r,shardKey:a}=t,n=(s,o,c,f)=>{if(!Number.isFinite(c))return;const d=k(y(f));try{r({...d===void 0?{}:{attributes:d},functionPath:e,kind:s,name:o,shardKey:a,ts:Date.now(),value:c})}catch{}};return{count:(s,o=1,c)=>{n("counter",s,o,c)},gauge:(s,o,c)=>{n("gauge",s,o,c)},record:(s,o,c)=>{n("histogram",s,o,c)}}},ct=t=>{const{anchor:e,captureRaw:r=!1,collected:a,durationMs:n,failure:s,functionPath:o,shardKey:c,startTs:f,userId:d}=t,m=k(a?.attributes??{},r);return{...Object.keys(m).length===0?{}:{attributes:m},dispatch:!0,durationMs:n,...a===void 0||a.events.length===0?{}:{events:a.events},...s===void 0?{}:{error:{message:_(s.thrown instanceof Error?s.thrown.message:String(s.thrown),r),type:O(s.thrown)}},functionPath:o,...a===void 0||a.links.length===0?{}:{links:a.links},name:o,ok:s===void 0,parentSpanId:"",...H(e),shardKey:c,spanId:e.rootSpanId,startTs:f,userId:d}};export{ot as createMetrics,Z as createSpanCollector,at as createTracedFetch,st as createTracer,ct as dispatchRootSpan,H as spanAnchorFields};
1
+ import{f as _,g as k,n as y}from"./request-log-YtJxmSWX.mjs";import{o as x,b as L,O as K}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as U}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as O}from"./resolveTraceAnchor-DDAPZRBB.mjs";const q=/[\w.-]/u,C=t=>{let e="";for(const r of t)e+=q.test(r)?r:"_";return e},X=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=C(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},B=t=>{const e=Object.keys(t);if(e.length===0||!e.every(a=>a==="attributes"||a==="kind"||a==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(K,r)},V=128,G=128,z=128,b=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[a,n]of Object.entries(e)){const s=!Object.hasOwn(t,a);s&&r>=z||(s&&(r+=1),t[a]=n)}},j=t=>{const e=y(t);if(e===void 0||Object.keys(e).length<=z)return e;const r={};return b(r,e),r},J=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},Q=t=>{try{return new URL(t).host}catch{return t}},W=(t,e)=>{try{return t(new URL(e))}catch{return!1}},Y=t=>t===void 0?{}:B(t)?t:{attributes:t},H=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},Z=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},a={spanContext:()=>t,addEvent:(n,s)=>{if(r.events.length>=V)return;const o=k(j(s),e);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=G)return;const s=k(j(n.attributes),e);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{b(r.attributes,y(X(n)))},recordException:n=>{const s=n instanceof Error?n.message:String(n);a.addEvent("exception",{"exception.message":_(s,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":O(n)})},setAttribute:(n,s)=>{b(r.attributes,y({[n]:s}))},setAttributes:n=>{b(r.attributes,y(n))}};return{collected:r,handle:a}},st=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:a,functionPath:n,record:s,resolveHostTracing:o,shardKey:c,userId:f}=t,d=m=>async(I,E,u,P)=>{const l=P?.spanId??x(8),w=P?.parentSpanId??m,i=Date.now(),g=Y(u),D=y(g.attributes),{collected:T,handle:F}=Z({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),R=async S=>{let p=!0,v;try{return await E(d(l),F)}catch(h){p=!1;const A=h instanceof Error?h.message:String(h);throw v={message:_(A,r),type:O(h)},h}finally{const h=Date.now()-i,A=f(),N={};b(N,D),b(N,T.attributes);const M=k(N,r),$=[...g.links??[],...T.links];try{s({...Object.keys(M).length===0?{}:{attributes:M},durationMs:h,...T.events.length===0?{}:{events:T.events},...v===void 0?{}:{error:v},functionPath:n,...g.kind===void 0||g.kind==="internal"?{}:{kind:g.kind},...$.length===0?{}:{links:$},name:I,ok:p,parentSpanId:w,...H(e),shardKey:c,spanId:l,startTs:i,userId:A})}catch{}if(S!==void 0)try{U(S,{attributes:M,durationMs:h,error:v,functionPath:n,ok:p,shardKey:c,userId:A})}catch{}}};if(a===!0&&o!==void 0){let S=!1;try{const p=await o();if(p!==void 0&&typeof p.enterSpan=="function")return await p.enterSpan(I,v=>(S=!0,R(v)))}catch(p){if(S)throw p}}return await R()};return d(e.rootSpanId)},at=(t,e)=>{const{anchor:r,captureRaw:a=!1,functionPath:n,propagate:s=!0,record:o,shardKey:c,userId:f}=t;return async(d,m)=>{const I=x(8),E=Date.now(),u=new Request(d,m);(typeof s=="function"?W(s,u.url):s)&&u.headers.set("traceparent",L(r.traceId,I,r.sampled??!0));let l,w;try{const i=await e(u);return w=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const g=i instanceof Error?i.message:String(i);throw l={message:_(g,a),type:O(i)},i}finally{try{o({attributes:{"http.request.method":u.method,...w===void 0?{}:{"http.response.status_code":w},"url.full":J(u.url)},durationMs:Date.now()-E,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${Q(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,...H(r),shardKey:c,spanId:I,startTs:E,userId:f()})}catch{}}}},ot=t=>{const{functionPath:e,record:r,shardKey:a}=t,n=(s,o,c,f)=>{if(!Number.isFinite(c))return;const d=k(y(f));try{r({...d===void 0?{}:{attributes:d},functionPath:e,kind:s,name:o,shardKey:a,ts:Date.now(),value:c})}catch{}};return{count:(s,o=1,c)=>{n("counter",s,o,c)},gauge:(s,o,c)=>{n("gauge",s,o,c)},record:(s,o,c)=>{n("histogram",s,o,c)}}},ct=t=>{const{anchor:e,captureRaw:r=!1,collected:a,durationMs:n,failure:s,functionPath:o,shardKey:c,startTs:f,userId:d}=t,m=k(a?.attributes??{},r);return{...Object.keys(m).length===0?{}:{attributes:m},dispatch:!0,durationMs:n,...a===void 0||a.events.length===0?{}:{events:a.events},...s===void 0?{}:{error:{message:_(s.thrown instanceof Error?s.thrown.message:String(s.thrown),r),type:O(s.thrown)}},functionPath:o,...a===void 0||a.links.length===0?{}:{links:a.links},name:o,ok:s===void 0,parentSpanId:"",...H(e),shardKey:c,spanId:e.rootSpanId,startTs:f,userId:d}};export{ot as createMetrics,Z as createSpanCollector,at as createTracedFetch,st as createTracer,ct as dispatchRootSpan,H as spanAnchorFields};
@@ -0,0 +1,24 @@
1
+ import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as j,standardRules as z}from"@visulima/redact";import{readIssueStates as H}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const D=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)}},I=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:D(e),O=(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]=I(n);if(e!==void 0)for(const[r,n]of Object.entries(e))s[r]=I(n);return Object.keys(s).length===0?void 0:s},V=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"]),Z=new Set(["card","pass","pin","session"]),J=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),K=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),B=new Set(["card no","connection string","database url","one time"]),Y=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],q=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"]),Q=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),ee=new Set(["max","min","num","total"]),T=4096,te=128,se=16384,u="<REDACTED>",re="[redaction budget exceeded]",ne=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),N=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,oe=(e,t)=>{const s=N(e[t]),r=t>0?N(e[t-1]):void 0;if(V.has(s))return s;if(r!==void 0){if(s==="key"&&J.has(r))return"key";if(s==="code"&&K.has(r))return"code";if(B.has(`${r} ${s}`))return`${r} ${s}`}return Y.some(n=>s.endsWith(n))?s:void 0},$=e=>{const t=ne(e);if(t.length===0)return"none";const s=Q.has(t.at(-1))||ee.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=oe(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>q.has(a))?Z.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},ie=e=>typeof e=="boolean"||e===null||e===void 0?e:u,ae=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),c=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,c===-1?void 0:c)),i=a!==-1&&!o&&(c===-1||a<c);if(n===-1&&i&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},ce=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,de=/-----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,C=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,U=[{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\.`}],fe=String.raw`(?<=^|[^\w-]|${C})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ue=new RegExp([...U.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${C})${t}${e}`),fe].join("|"),"g"),ge=new RegExp([...U.map(({prefix:e})=>e),"eyJ"].join("|")),pe=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,S=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,L=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,k=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,he=e=>{let t="",s=0;S.lastIndex=0;for(let r=S.exec(e);r!==null;r=S.exec(e)){const n=$(r[2]),a=r.index+r[0].length;L.lastIndex=a;const c=n==="none"?null:L.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){S.lastIndex=Math.max(a,r.index+1);continue}const o=c[0],i=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;i===""&&r[3]===":"&&(k.lastIndex=d,d+=k.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${i}${u}${o.length>i.length&&o.endsWith(i)?i:""}`,s=d,S.lastIndex=s}return t+e.slice(s)},Ee=/[:=@]|basic|bearer|digest|-u\b|--/i,_e=e=>{const t=ge.test(e);if(!t&&!Ee.test(e))return e;const s=e.replaceAll(de,`-----BEGIN $1-----${u}`).replaceAll(ce,ae).replaceAll(le,`$1 ${u}`);return he((t?s.replaceAll(ue,u):s).replaceAll(pe,`$1$2$3${u}`))},Se=(e,t)=>{if(t.remaining<=0)return re;const s=e.slice(0,T+te);t.remaining-=s.length;const r=_e(s);return r.length>T||e.length>s.length?`${r.slice(0,T)}…[truncated]`:r},me=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"),Ae=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}},Te=32,A=(e,t,s,r,n)=>{if(typeof e=="string")return r?u:Se(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&me(e))return e;if(t.has(e)||s>=Te)return u;const a=Array.isArray(e)?m:Ae(e);if(a!==m){t.add(e);const o=A(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>A(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,i])=>{const d=$(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,ie(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},P=e=>A(e,new WeakSet,0,!1,{remaining:se}),p="__lunora_reqlog__",y=1e3,W="lunora",ye=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],be=j(z,{exclude:["pass"]}),Ce=(e,t=!1)=>t||e===null||e===void 0?e:P(e),g=(e,t=!1)=>t||e===null||e===void 0?e:be(P(e)),w=new WeakSet,b=e=>{if(!w.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${p}" (
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 ye)try{E(e,`ALTER TABLE "${p}" ADD COLUMN ${t}`)}catch{}w.add(e)}},v=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Re=e=>e===void 0?null:e?1:0,Ue=(e,t,s={})=>{b(e);const r=s.captureRaw??!1,n=s.retention??y,a=t.outcome==="error"&&t.errorMessage!==void 0?M({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${p}"
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),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,v(t.tablesRead),v(t.tablesWritten),Re(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},Pe=(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:W,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)},Ie="log",Oe=e=>e.map(t=>D(t)).join(" "),Ne=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},We=(e,t)=>e.length===2&&typeof e[0]=="string"&&Ne(e[1])?{fields:O(e[1],t),message:e[0]}:{fields:O(void 0,t),message:Oe(e)},Fe=(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:W,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Ie,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)},Le=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,F=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Le("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[]}},ke=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},we=e=>{try{return JSON.parse(e)}catch{return}},Ge=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(F(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
23
+ FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const i={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&&(i.shardKey=o.shard_key),o.user_id!==null&&(i.userId=o.user_id),o.identity!==null){const d=ke(o.identity);d!==void 0&&(i.identity=d)}if(o.args!==null){const d=we(o.args);d!==void 0&&(i.redactedArgs=d)}return o.error_message!==null&&(i.errorMessage=o.error_message),o.cache_hit!==null&&(i.cacheHit=o.cache_hit===1),o.trace_id!==null&&(i.traceId=o.trace_id),o.deployment_id!==null&&(i.deploymentId=o.deployment_id),o.version_tag!==null&&(i.versionTag=o.version_tag),i})},ve=(e,t)=>{const s=H(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)}},Xe=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["outcome = 'error'"],n=[];F(r,n,t),n.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
24
+ FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:G,hash:X,title:R}=M({functionPath:l.function_path,message:_}),h=l.error_fingerprint??X,f=c.get(h);if(f===void 0){c.set(h,{count:1,culprit:G,firstSeen:l.ts,hash:h,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(h,l.ts);continue}f.count+=1,f.firstSeen=Math.min(f.firstSeen,l.ts),f.lastSeen=Math.max(f.lastSeen,l.ts),l.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,l.ts),f.sampleMessage=_,f.title=R)}ve(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{p as R,Ue as a,Pe as b,b as c,Ge as d,Fe as e,g as f,Ce as g,y as h,Oe as i,O as n,We as p,Xe as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.122",
3
+ "version": "1.0.0-alpha.124",
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.50",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.9",
48
- "@lunora/shard-engine": "1.0.0-alpha.113",
48
+ "@lunora/shard-engine": "1.0.0-alpha.114",
49
49
  "@visulima/redact": "5.0.0"
50
50
  },
51
51
  "engines": {
@@ -1,24 +0,0 @@
1
- import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as G,standardRules as X}from"@visulima/redact";import{readIssueStates as z}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const H=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},I=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:H(e),O=(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]=I(n);if(e!==void 0)for(const[r,n]of Object.entries(e))s[r]=I(n);return Object.keys(s).length===0?void 0:s},V=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"]),J=new Set(["card","pass","pin","session"]),Z=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),K=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),B=new Set(["card no","connection string","database url","one time"]),Y=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],q=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"]),Q=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),ee=new Set(["max","min","num","total"]),T=4096,te=128,se=16384,u="<REDACTED>",re="[redaction budget exceeded]",ne=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),N=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,oe=(e,t)=>{const s=N(e[t]),r=t>0?N(e[t-1]):void 0;if(V.has(s))return s;if(r!==void 0){if(s==="key"&&Z.has(r))return"key";if(s==="code"&&K.has(r))return"code";if(B.has(`${r} ${s}`))return`${r} ${s}`}return Y.some(n=>s.endsWith(n))?s:void 0},D=e=>{const t=ne(e);if(t.length===0)return"none";const s=Q.has(t.at(-1))||ee.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=oe(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>q.has(a))?J.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},ie=e=>typeof e=="boolean"||e===null||e===void 0?e:u,ae=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),c=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,c===-1?void 0:c)),i=a!==-1&&!o&&(c===-1||a<c);if(n===-1&&i&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},ce=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,de=/-----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,$=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,C=[{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\.`}],fe=String.raw`(?<=^|[^\w-]|${$})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ue=new RegExp([...C.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${$})${t}${e}`),fe].join("|"),"g"),ge=new RegExp([...C.map(({prefix:e})=>e),"eyJ"].join("|")),pe=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,S=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,L=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,k=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,he=e=>{let t="",s=0;S.lastIndex=0;for(let r=S.exec(e);r!==null;r=S.exec(e)){const n=D(r[2]),a=r.index+r[0].length;L.lastIndex=a;const c=n==="none"?null:L.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){S.lastIndex=Math.max(a,r.index+1);continue}const o=c[0],i=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;i===""&&r[3]===":"&&(k.lastIndex=d,d+=k.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${i}${u}${o.length>i.length&&o.endsWith(i)?i:""}`,s=d,S.lastIndex=s}return t+e.slice(s)},Ee=/[:=@]|basic|bearer|digest|-u\b|--/i,_e=e=>{const t=ge.test(e);if(!t&&!Ee.test(e))return e;const s=e.replaceAll(de,`-----BEGIN $1-----${u}`).replaceAll(ce,ae).replaceAll(le,`$1 ${u}`);return he((t?s.replaceAll(ue,u):s).replaceAll(pe,`$1$2$3${u}`))},Se=(e,t)=>{if(t.remaining<=0)return re;const s=e.slice(0,T+te);t.remaining-=s.length;const r=_e(s);return r.length>T||e.length>s.length?`${r.slice(0,T)}…[truncated]`:r},me=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"),Ae=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}},Te=32,A=(e,t,s,r,n)=>{if(typeof e=="string")return r?u:Se(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&me(e))return e;if(t.has(e)||s>=Te)return u;const a=Array.isArray(e)?m:Ae(e);if(a!==m){t.add(e);const o=A(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>A(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,i])=>{const d=D(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,ie(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},U=e=>A(e,new WeakSet,0,!1,{remaining:se}),p="__lunora_reqlog__",y=1e3,P="lunora",ye=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],be=G(X,{exclude:["pass"]}),Ce=(e,t=!1)=>t||e===null||e===void 0?e:U(e),g=(e,t=!1)=>t||e===null||e===void 0?e:be(U(e)),w=new WeakSet,b=e=>{if(!w.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${p}" (
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 ye)try{E(e,`ALTER TABLE "${p}" ADD COLUMN ${t}`)}catch{}w.add(e)}},v=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Re=e=>e===void 0?null:e?1:0,Ue=(e,t,s={})=>{b(e);const r=s.captureRaw??!1,n=s.retention??y,a=t.outcome==="error"&&t.errorMessage!==void 0?M({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${p}"
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),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,v(t.tablesRead),v(t.tablesWritten),Re(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},Pe=(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:P,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)},Ie="log",Oe=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),Ne=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},We=(e,t)=>e.length===2&&typeof e[0]=="string"&&Ne(e[1])?{fields:O(e[1],t),message:e[0]}:{fields:O(void 0,t),message:Oe(e)},je=(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:P,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Ie,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)},Le=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,W=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Le("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[]}},ke=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},we=e=>{try{return JSON.parse(e)}catch{return}},Fe=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(W(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
23
- FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const i={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&&(i.shardKey=o.shard_key),o.user_id!==null&&(i.userId=o.user_id),o.identity!==null){const d=ke(o.identity);d!==void 0&&(i.identity=d)}if(o.args!==null){const d=we(o.args);d!==void 0&&(i.redactedArgs=d)}return o.error_message!==null&&(i.errorMessage=o.error_message),o.cache_hit!==null&&(i.cacheHit=o.cache_hit===1),o.trace_id!==null&&(i.traceId=o.trace_id),o.deployment_id!==null&&(i.deploymentId=o.deployment_id),o.version_tag!==null&&(i.versionTag=o.version_tag),i})},ve=(e,t)=>{const s=z(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)}},Ge=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["outcome = 'error'"],n=[];W(r,n,t),n.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
24
- FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:j,hash:F,title:R}=M({functionPath:l.function_path,message:_}),h=l.error_fingerprint??F,f=c.get(h);if(f===void 0){c.set(h,{count:1,culprit:j,firstSeen:l.ts,hash:h,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(h,l.ts);continue}f.count+=1,f.firstSeen=Math.min(f.firstSeen,l.ts),f.lastSeen=Math.max(f.lastSeen,l.ts),l.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,l.ts),f.sampleMessage=_,f.title=R)}ve(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{p as R,Ue as a,Pe as b,b as c,Fe as d,je as e,g as f,Ce as g,y as h,Oe as i,O as n,We as p,Ge as r};