@lunora/observability 1.0.0-alpha.155 → 1.0.0-alpha.157

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
@@ -164,6 +164,12 @@ interface EvaluationInput {
164
164
  interface ErrorDetail {
165
165
  /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
166
  code?: string;
167
+ /**
168
+ * The operator-only `internal` context of a `LunoraError`, when it is JSON-safe.
169
+ * Attached by the shard only on the detail header (see {@link describeInternal}),
170
+ * never by {@link describeError}, so it cannot leak into a log-event `error`.
171
+ */
172
+ internal?: Record<string, unknown>;
167
173
  message: string;
168
174
  name: string;
169
175
  stack?: string;
@@ -1878,6 +1884,17 @@ interface ReadIssuesOptions {
1878
1884
  /** Exact acting-userId match. */
1879
1885
  userId?: string;
1880
1886
  }
1887
+ /**
1888
+ * Mask credentials only, leaving PII alone: `maskCredentials` — credential key
1889
+ * names, `name=value` pairs, auth schemes, JWTs, PEM keys, URL query / fragment
1890
+ * / userinfo. For span, event, link and metric attributes: {@link redactArgs}'
1891
+ * PII rules key on names like `id`, `url` and `date` and mask uuids, so they
1892
+ * would erase the very `order.id` / `url` attributes a trace is read by, and
1893
+ * `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
1894
+ * thread, where every span, event and metric pays it. `captureRaw` as in
1895
+ * {@link redactArgs}.
1896
+ */
1897
+ declare const redactCredentials: (value: unknown, captureRaw?: boolean) => unknown;
1881
1898
  /**
1882
1899
  * Redact the secrets / PII out of a value before it reaches the durable log, a
1883
1900
  * Logpush event, a function-metrics row or a span's error message:
@@ -2341,4 +2358,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2341
2358
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2342
2359
  * core. What is exported here is what a consumer actually needs.
2343
2360
  */
2344
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
2361
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
package/dist/index.d.ts CHANGED
@@ -164,6 +164,12 @@ interface EvaluationInput {
164
164
  interface ErrorDetail {
165
165
  /** The `LunoraError` taxonomy code, when the thrown value carries one. */
166
166
  code?: string;
167
+ /**
168
+ * The operator-only `internal` context of a `LunoraError`, when it is JSON-safe.
169
+ * Attached by the shard only on the detail header (see {@link describeInternal}),
170
+ * never by {@link describeError}, so it cannot leak into a log-event `error`.
171
+ */
172
+ internal?: Record<string, unknown>;
167
173
  message: string;
168
174
  name: string;
169
175
  stack?: string;
@@ -1878,6 +1884,17 @@ interface ReadIssuesOptions {
1878
1884
  /** Exact acting-userId match. */
1879
1885
  userId?: string;
1880
1886
  }
1887
+ /**
1888
+ * Mask credentials only, leaving PII alone: `maskCredentials` — credential key
1889
+ * names, `name=value` pairs, auth schemes, JWTs, PEM keys, URL query / fragment
1890
+ * / userinfo. For span, event, link and metric attributes: {@link redactArgs}'
1891
+ * PII rules key on names like `id`, `url` and `date` and mask uuids, so they
1892
+ * would erase the very `order.id` / `url` attributes a trace is read by, and
1893
+ * `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
1894
+ * thread, where every span, event and metric pays it. `captureRaw` as in
1895
+ * {@link redactArgs}.
1896
+ */
1897
+ declare const redactCredentials: (value: unknown, captureRaw?: boolean) => unknown;
1881
1898
  /**
1882
1899
  * Redact the secrets / PII out of a value before it reaches the durable log, a
1883
1900
  * Logpush event, a function-metrics row or a span's error message:
@@ -2341,4 +2358,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2341
2358
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2342
2359
  * core. What is exported here is what a consumer actually needs.
2343
2360
  */
2344
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
2361
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
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 n,createSpanCollector as S,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-mUypNATC.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as d,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 H,readFunctionMetricIndexHits as O,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as D,recordFunctionMetric as h}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-CHV71isV.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 k}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{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 oe,readQueryInsights as Te,readQueryMetrics as ae,recordQueryMetric as se}from"./packem_shared/latencyBucketIndex--kZoW0vc.mjs";import{R as _e,a as ce,e as ne,b as Se,c as ie,p as Ie,r as ue,d as Me,f as pe}from"./packem_shared/request-log-YtJxmSWX.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Ce,MIN_AUTH_SECRET_LENGTH as Ne,buildSecurityAudit as fe}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 Le}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as xe}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,d 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,V as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,Ce as MIN_ADMIN_TOKEN_LENGTH,Ne as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,_e as REQUEST_LOG_TABLE,Re as SpanBuffer,ce as appendRequestLogEntry,q as applyHostRootSpan,fe as buildSecurityAudit,p as createDatabaseTally,n as createMetrics,S as createSpanCollector,i as createTracedFetch,I as createTracer,u as dispatchRootSpan,ne as emitLogEvent,Se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,ie as ensureRequestLogTable,X as explainIssue,Le as findDanglingReferences,Ue as foldTraces,A as formatTally,C as instrumentDatabase,N as instrumentSqlClient,oe as latencyBucketIndex,g as mergeScanAttribution,k as parseExplainIssueArgs,Ie as parseLogArgs,E as readAuthMetrics,ue as readErrorIssues,H as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,D as readFunctionMetricsTotals,ee as readMetricHistory,Te as readQueryInsights,ae as readQueryMetrics,Me as readRequestLog,_ as recordAuthEvent,h as recordFunctionMetric,re as recordMetricHistory,se as recordQueryMetric,pe as redactArgs,xe 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 c}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.mjs";import{createMetrics as n,createSpanCollector as S,createTracedFetch as i,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-Bm_eapf6.mjs";import{createDatabaseTally as p,formatTally as A,instrumentDatabase as C,instrumentSqlClient as N}from"./packem_shared/createDatabaseTally-BmfGzp1v.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 H,readFunctionMetricIndexHits as O,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as D,recordFunctionMetric as h}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-CHV71isV.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 k}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{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 oe,readQueryInsights as Te,readQueryMetrics as ae,recordQueryMetric as se}from"./packem_shared/latencyBucketIndex--kZoW0vc.mjs";import{R as ce,a as _e,e as ne,b as Se,c as ie,p as Ie,r as ue,d as Me,f as pe,g as Ae}from"./packem_shared/request-log-DosHwXO1.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Ne,MIN_AUTH_SECRET_LENGTH as de,buildSecurityAudit as fe}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Ue,foldTraces as me}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as le}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as Be}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,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,V as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,Ne as MIN_ADMIN_TOKEN_LENGTH,de as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,ce as REQUEST_LOG_TABLE,Ue as SpanBuffer,_e as appendRequestLogEntry,q as applyHostRootSpan,fe as buildSecurityAudit,p as createDatabaseTally,n as createMetrics,S as createSpanCollector,i as createTracedFetch,I as createTracer,u as dispatchRootSpan,ne as emitLogEvent,Se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,ie as ensureRequestLogTable,X as explainIssue,le as findDanglingReferences,me as foldTraces,A as formatTally,C as instrumentDatabase,N as instrumentSqlClient,oe as latencyBucketIndex,g as mergeScanAttribution,k as parseExplainIssueArgs,Ie as parseLogArgs,E as readAuthMetrics,ue as readErrorIssues,H as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,D as readFunctionMetricsTotals,ee as readMetricHistory,Te as readQueryInsights,ae as readQueryMetrics,Me as readRequestLog,c as recordAuthEvent,h as recordFunctionMetric,re as recordMetricHistory,se as recordQueryMetric,pe as redactArgs,Ae as redactCredentials,Be as resolveTraceAnchor,v as setHostSpanAttributes,z as upsertIssueState};
@@ -0,0 +1 @@
1
+ import{h as t,R as o,a as g,e as E,b as L,c as d,p as R,r as n,d as p,f as i,g as u,i as T}from"./request-log-DosHwXO1.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,d as ensureRequestLogTable,R as parseLogArgs,n as readErrorIssues,p as readRequestLog,i as redactArgs,u as redactCredentials,T as renderLogMessage};
@@ -1,2 +1,2 @@
1
- import{o as g}from"./otlp-DR7601NL.mjs";import{f as p}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",R=/^[a-z]+/iu,O=t=>{if(typeof t!="string")return d;let e=0;for(;e<t.length;){const o=t.charAt(e);if(o==="("||o.trim()==="")e+=1;else if(t.startsWith("--",e)){const a=t.indexOf(`
1
+ import{o as g}from"./otlp-DR7601NL.mjs";import{f as p}from"./request-log-DosHwXO1.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",R=/^[a-z]+/iu,O=t=>{if(typeof t!="string")return d;let e=0;for(;e<t.length;){const o=t.charAt(e);if(o==="("||o.trim()==="")e+=1;else if(t.startsWith("--",e)){const a=t.indexOf(`
2
2
  `,e);if(a===-1)return d;e=a+1}else if(t.startsWith("/*",e)){const a=t.indexOf("*/",e+2);if(a===-1)return d;e=a+2}else break}const r=R.exec(t.slice(e,e+16))?.[0].toUpperCase();return r!==void 0&&h.has(r)?r:d},m=t=>t??"other_sql",S=100,A=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),I=new Set(["aggregate","count","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchIf","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),P=(t,e)=>{if(!I.has(t))return;const r=e[0];return typeof r=="string"&&r.length>0?r:void 0},l=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),L=(t,e,r)=>r==="redact"?p(l(t),e.captureRaw):e.captureRaw===!0?l(t):E(t),u=(t,e,r)=>{const{durationMs:o,failure:a,startTs:n}=e;return{durationMs:o,...a===void 0?{}:{error:{message:L(a,t,r),type:E(a)}},functionPath:t.functionPath,kind:"client",ok:a===void 0,parentSpanId:t.anchor.rootSpanId,...t.anchor.rayId===void 0?{}:{rayId:t.anchor.rayId},shardKey:t.shardKey,spanId:g(8),startTs:n,traceId:t.anchor.traceId,userId:t.userId()}},y=async(t,e,r,o)=>{const a=Date.now();let n,s;try{return s=await r(),s}catch(i){throw n=i,i}finally{const i=Date.now()-a,{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(o({durationMs:i,failure:n,result:s,startTs:a}))))}catch{}}},T=(t,e,r)=>{const o=new Map;return new Proxy({},{get(a,n){const s=Reflect.get(t,n,t);if(typeof n!="string"||typeof s!="function"||!e(n))return s;const i=s,c=o.get(n);if(c?.original===i)return c.instrumented;const f=r(n,i.bind(t));return o.set(n,{instrumented:f,original:i}),f},getOwnPropertyDescriptor(a,n){const s=Reflect.getOwnPropertyDescriptor(t,n);return s===void 0?void 0:{...s,configurable:!0}},defineProperty(a,n,s){return s.configurable===!1?!1:Reflect.defineProperty(t,n,s)},deleteProperty(a,n){return Reflect.deleteProperty(t,n)},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(a,n){return Reflect.has(t,n)},ownKeys(){return Reflect.ownKeys(t)},set(a,n,s){return Reflect.set(t,n,s,t)}})},_=(t,e)=>e.mode==="off"?t:T(t,r=>A.has(r),(r,o)=>async(...a)=>{const n=P(r,a);return y(e,r,()=>o(...a),s=>({...u(e,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}`}))}),N=(t,e)=>{if(e.mode==="off")return t;const r=m(t.dbSystem);return T(t,o=>o==="query",(o,a)=>async(...n)=>{const s=O(n[0]);return y(e,s,()=>a(...n),i=>({...u(e,i,"type-only"),attributes:{"db.operation.name":s,...Array.isArray(i.result)?{"db.response.returned_rows":i.result.length}:{},"db.system.name":r},name:`sql.${s}`}))})},C=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),D=(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[o,a]of Object.entries(t.perOperation))r[`${e}.op.${o}`]=a;return r};export{C as createDatabaseTally,D as formatTally,_ as instrumentDatabase,N as instrumentSqlClient};
@@ -1 +1 @@
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};
1
+ import{f as _,g as S,n as y}from"./request-log-DosHwXO1.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=S(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=S(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 k=>{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=S(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(k!==void 0)try{U(k,{attributes:M,durationMs:h,error:v,functionPath:n,ok:p,shardKey:c,userId:A})}catch{}}};if(a===!0&&o!==void 0){let k=!1;try{const p=await o();if(p!==void 0&&typeof p.enterSpan=="function")return await p.enterSpan(I,v=>(k=!0,R(v)))}catch(p){if(k)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=S(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=S(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 D}from"@lunora/fingerprint";import{createRedactor as z,standardRules as H}from"@visulima/redact";import{readIssueStates as V}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const $=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:$(e),O=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},N=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))O(s,r,I(n));if(e!==void 0)for(const[r,n]of Object.entries(e))O(s,r,I(n));return Object.keys(s).length===0?void 0:s},Z=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"]),K=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),B=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),Y=new Set(["card no","connection string","database url","one time"]),q=["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"]),ee=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),te=new Set(["max","min","num","total"]),T=4096,se=128,re=16384,u="<REDACTED>",ne="[redaction budget exceeded]",oe=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),L=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,ie=(e,t)=>{const s=L(e[t]),r=t>0?L(e[t-1]):void 0;if(Z.has(s))return s;if(r!==void 0){if(s==="key"&&K.has(r))return"key";if(s==="code"&&B.has(r))return"code";if(Y.has(`${r} ${s}`))return`${r} ${s}`}return q.some(n=>s.endsWith(n))?s:void 0},C=e=>{const t=oe(e);if(t.length===0)return"none";const s=ee.has(t.at(-1))||te.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=ie(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"},ae=e=>typeof e=="boolean"||e===null||e===void 0?e:u,ce=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}`},de=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,le=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,fe=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,U=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,P=[{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\.`}],ue=String.raw`(?<=^|[^\w-]|${U})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ge=new RegExp([...P.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${U})${t}${e}`),ue].join("|"),"g"),pe=new RegExp([...P.map(({prefix:e})=>e),"eyJ"].join("|")),he=/(\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,w=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,k=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,Ee=e=>{let t="",s=0;m.lastIndex=0;for(let r=m.exec(e);r!==null;r=m.exec(e)){const n=C(r[2]),a=r.index+r[0].length;w.lastIndex=a;const c=n==="none"?null:w.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){m.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,m.lastIndex=s}return t+e.slice(s)},_e=/[:=@]|basic|bearer|digest|-u\b|--/i,me=e=>{const t=pe.test(e);if(!t&&!_e.test(e))return e;const s=e.replaceAll(le,`-----BEGIN $1-----${u}`).replaceAll(de,ce).replaceAll(fe,`$1 ${u}`);return Ee((t?s.replaceAll(ge,u):s).replaceAll(he,`$1$2$3${u}`))},Se=(e,t)=>{if(t.remaining<=0)return ne;const s=e.slice(0,T+se);t.remaining-=s.length;const r=me(s);return r.length>T||e.length>s.length?`${r.slice(0,T)}…[truncated]`:r},Ae=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),S=Symbol("no-json"),Te=e=>{const{toJSON:t}=e;if(typeof t!="function")return S;try{const s=t.call(e);return s===e?S:s}catch{return S}},ye=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)&&Ae(e))return e;if(t.has(e)||s>=ye)return u;const a=Array.isArray(e)?S:Te(e);if(a!==S){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=C(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,ae(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},W=e=>A(e,new WeakSet,0,!1,{remaining:re}),p="__lunora_reqlog__",y=1e3,F="lunora",be=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],Re=z(H,{exclude:["pass"]}),Ue=(e,t=!1)=>t||e===null||e===void 0?e:W(e),g=(e,t=!1)=>t||e===null||e===void 0?e:Re(W(e)),v=new WeakSet,b=e=>{if(!v.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 be)try{E(e,`ALTER TABLE "${p}" ADD COLUMN ${t}`)}catch{}v.add(e)}},x=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Ie=e=>e===void 0?null:e?1:0,Pe=(e,t,s={})=>{b(e);const r=s.captureRaw??!1,n=s.retention??y,a=t.outcome==="error"&&t.errorMessage!==void 0?D({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,x(t.tablesRead),x(t.tablesWritten),Ie(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},We=(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:F,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)},Oe="log",Ne=e=>e.map(t=>$(t)).join(" "),Le=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fe=(e,t)=>e.length===2&&typeof e[0]=="string"&&Le(e[1])?{fields:N(e[1],t),message:e[0]}:{fields:N(void 0,t),message:Ne(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:F,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Oe,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)},we=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,j=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(we("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))},M=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}},ve=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(j(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:M(o.tables_read),tablesWritten:M(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=ve(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})},xe=(e,t)=>{const s=V(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=[];j(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}=D({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)}xe(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,Pe as a,We as b,b as c,Ge as d,je as e,g as f,Ue as g,y as h,Ne as i,N as n,Fe 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.155",
3
+ "version": "1.0.0-alpha.157",
4
4
  "description": "Host-neutral telemetry storage and read models for Lunora, backing the Studio's Logs, Traces, Metrics and Issues views",
5
5
  "keywords": [
6
6
  "lunora",
@@ -45,7 +45,7 @@
45
45
  "dependencies": {
46
46
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.9",
48
- "@lunora/shard-engine": "1.0.0-alpha.144",
48
+ "@lunora/shard-engine": "1.0.0-alpha.146",
49
49
  "@lunora/wire": "1.0.0-alpha.1",
50
50
  "@visulima/redact": "5.0.0"
51
51
  },
@@ -1 +0,0 @@
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,24 +0,0 @@
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};