@lunora/observability 1.0.0-alpha.206 → 1.0.0-alpha.207

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
@@ -711,6 +711,8 @@ interface AppendRequestLogEntry {
711
711
  userId?: string;
712
712
  versionTag?: string;
713
713
  }
714
+ /** The bound column values of one `__lunora_reqlog__` row, built by {@link buildRequestLogRow}: primitives only. */
715
+ type RequestLogRowValues = ReadonlyArray<null | number | string>;
714
716
  /** Knobs the dispatch site threads into a request-log write. */
715
717
  interface RequestLogWriteOptions {
716
718
  /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
@@ -762,7 +764,7 @@ interface ErrorIssue {
762
764
  /**
763
765
  * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
764
766
  * computed from the RAW (pre-redaction) message at write time and stored on
765
- * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
767
+ * the row — see {@link buildRequestLogRow} — so redacting `sampleMessage`
766
768
  * below can't change the grouping.
767
769
  */
768
770
  hash: string;
@@ -926,7 +928,7 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
926
928
  * call it defensively.
927
929
  *
928
930
  * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
929
- * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
931
+ * from the RAW `error_message` at write time, before {@link buildRequestLogRow}
930
932
  * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
931
933
  * trace id, the correlation key to the span ring and to whatever collector
932
934
  * `otlpSink` ships to.
@@ -941,24 +943,57 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
941
943
  */
942
944
  declare const ensureRequestLogTable: (sql: SqlExec) => void;
943
945
  /**
944
- * Append one dispatch to the request log, then — once per
945
- * {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
946
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
947
- * table first so callers needn't. Args/identity/error message are redacted here
948
- * so a raw value never reaches the durable table — callers pass the unredacted
949
- * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
950
- * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
951
- * dispatch site.
946
+ * Build the bound column values of one `__lunora_reqlog__` row from `entry`, in
947
+ * the column order {@link appendRequestLogRows} inserts. Everything is final here:
948
+ * args, identity and error message redacted (raw only under `captureRaw`, dev
949
+ * only), table lists encoded, the error fingerprint computed. A caller that holds
950
+ * a row before writing it, as the Durable Object's batch does, therefore keeps
951
+ * only primitives and never reads the entry's objects again, so a later mutation
952
+ * of the dispatch's args or identity cannot reach the stored row.
952
953
  *
953
954
  * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
954
- * it's redacted below, and the resulting hash is persisted in
955
- * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
956
- * recomputing `fingerprintError` from the (redacted) `error_message` column, so
957
- * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
958
- * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
959
- * existing Issue or change its identity.
960
- */
961
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
955
+ * it's redacted, and the resulting hash is persisted in `error_fingerprint`.
956
+ * `readErrorIssues` groups off that stored hash instead of recomputing
957
+ * `fingerprintError` from the (redacted) `error_message` column, so masking a
958
+ * PII-bearing value — e.g. two different `<n>`-bucketed IDs that redact to two
959
+ * different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an existing Issue
960
+ * or change its identity.
961
+ */
962
+ declare const buildRequestLogRow: (entry: AppendRequestLogEntry, captureRaw?: boolean) => RequestLogRowValues;
963
+ /**
964
+ * Insert built rows (see {@link buildRequestLogRow}) in order, so `seq` follows
965
+ * it, then trim the log to the most recent `retention` rows (default
966
+ * {@link REQUEST_LOG_RETENTION}, the operator's `LUNORA_REQUEST_LOG_RETENTION`
967
+ * override). Creates the table first so callers needn't.
968
+ *
969
+ * The trim runs on every call rather than once per minute: the Durable Object
970
+ * batches successful dispatches, so calls are rare, and a windowed trim let a
971
+ * burst inside one minute grow the table far past `retention`.
972
+ *
973
+ * One statement per row rather than one multi-row `INSERT`: 17 bound
974
+ * parameters per row would cross workerd's 100-parameter ceiling at six rows.
975
+ *
976
+ * Not atomic: no synchronous transaction works on every host (`ShardHost.transaction`
977
+ * is async, and a Durable Object rejects raw `BEGIN`/`COMMIT`). So a failing insert
978
+ * does not stop the rest: every row is attempted, an error row behind a failed
979
+ * success still lands, the trim always runs, and the first failure is rethrown
980
+ * afterwards. A failed row is simply missing; the rest keep dispatch order in `seq`.
981
+ * A failing trim is rethrown too, and leaves the table above `retention` until the
982
+ * next call's trim.
983
+ *
984
+ * A `SHARD_UNAVAILABLE` refusal is different: the Node host refuses SQL issued
985
+ * outside an open transaction's task before the statement runs, so nothing of the
986
+ * refused row landed and a later retry can write it. The append stops at the first
987
+ * refused row, skips the trim (it would be refused too) and returns without
988
+ * throwing; rows from that index on were not written, and nothing before it is
989
+ * written twice when the caller retries only those. A non-transient failure earlier
990
+ * in the same call is then not rethrown; its row is simply counted as consumed.
991
+ * @returns how many of `rows`, from the start, were consumed (written, or dropped by
992
+ * a non-transient failure); `rows.length` unless a refusal stopped the append
993
+ */
994
+ declare const appendRequestLogRows: (sql: SqlExec, rows: ReadonlyArray<RequestLogRowValues>, options?: {
995
+ retention?: number;
996
+ }) => number;
962
997
  /**
963
998
  * Emit one structured request event to `console` so Cloudflare's Workers Logs /
964
999
  * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
@@ -2467,4 +2502,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2467
2502
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2468
2503
  * core. What is exported here is what a consumer actually needs.
2469
2504
  */
2470
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };
2505
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogRowValues, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, appendRequestLogRows, applyHostRootSpan, buildRequestLogRow, buildSecurityAudit, createDatabaseTally, createMetrics, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };
package/dist/index.d.ts CHANGED
@@ -711,6 +711,8 @@ interface AppendRequestLogEntry {
711
711
  userId?: string;
712
712
  versionTag?: string;
713
713
  }
714
+ /** The bound column values of one `__lunora_reqlog__` row, built by {@link buildRequestLogRow}: primitives only. */
715
+ type RequestLogRowValues = ReadonlyArray<null | number | string>;
714
716
  /** Knobs the dispatch site threads into a request-log write. */
715
717
  interface RequestLogWriteOptions {
716
718
  /** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
@@ -762,7 +764,7 @@ interface ErrorIssue {
762
764
  /**
763
765
  * Stable 16-char grouping hash over `functionPath :: bucket(message)`,
764
766
  * computed from the RAW (pre-redaction) message at write time and stored on
765
- * the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
767
+ * the row — see {@link buildRequestLogRow} — so redacting `sampleMessage`
766
768
  * below can't change the grouping.
767
769
  */
768
770
  hash: string;
@@ -926,7 +928,7 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
926
928
  * call it defensively.
927
929
  *
928
930
  * `error_fingerprint` is the {@link fingerprintError} grouping hash captured
929
- * from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
931
+ * from the RAW `error_message` at write time, before {@link buildRequestLogRow}
930
932
  * redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
931
933
  * trace id, the correlation key to the span ring and to whatever collector
932
934
  * `otlpSink` ships to.
@@ -941,24 +943,57 @@ declare const NO_SENSITIVE_SCOPE: SensitiveScope;
941
943
  */
942
944
  declare const ensureRequestLogTable: (sql: SqlExec) => void;
943
945
  /**
944
- * Append one dispatch to the request log, then — once per
945
- * {@link REQUEST_LOG_PRUNE_WINDOW_MS} window — trim the log back to the most
946
- * recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
947
- * table first so callers needn't. Args/identity/error message are redacted here
948
- * so a raw value never reaches the durable table — callers pass the unredacted
949
- * entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
950
- * the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
951
- * dispatch site.
946
+ * Build the bound column values of one `__lunora_reqlog__` row from `entry`, in
947
+ * the column order {@link appendRequestLogRows} inserts. Everything is final here:
948
+ * args, identity and error message redacted (raw only under `captureRaw`, dev
949
+ * only), table lists encoded, the error fingerprint computed. A caller that holds
950
+ * a row before writing it, as the Durable Object's batch does, therefore keeps
951
+ * only primitives and never reads the entry's objects again, so a later mutation
952
+ * of the dispatch's args or identity cannot reach the stored row.
952
953
  *
953
954
  * The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
954
- * it's redacted below, and the resulting hash is persisted in
955
- * `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
956
- * recomputing `fingerprintError` from the (redacted) `error_message` column, so
957
- * masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
958
- * redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
959
- * existing Issue or change its identity.
960
- */
961
- declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
955
+ * it's redacted, and the resulting hash is persisted in `error_fingerprint`.
956
+ * `readErrorIssues` groups off that stored hash instead of recomputing
957
+ * `fingerprintError` from the (redacted) `error_message` column, so masking a
958
+ * PII-bearing value — e.g. two different `<n>`-bucketed IDs that redact to two
959
+ * different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an existing Issue
960
+ * or change its identity.
961
+ */
962
+ declare const buildRequestLogRow: (entry: AppendRequestLogEntry, captureRaw?: boolean) => RequestLogRowValues;
963
+ /**
964
+ * Insert built rows (see {@link buildRequestLogRow}) in order, so `seq` follows
965
+ * it, then trim the log to the most recent `retention` rows (default
966
+ * {@link REQUEST_LOG_RETENTION}, the operator's `LUNORA_REQUEST_LOG_RETENTION`
967
+ * override). Creates the table first so callers needn't.
968
+ *
969
+ * The trim runs on every call rather than once per minute: the Durable Object
970
+ * batches successful dispatches, so calls are rare, and a windowed trim let a
971
+ * burst inside one minute grow the table far past `retention`.
972
+ *
973
+ * One statement per row rather than one multi-row `INSERT`: 17 bound
974
+ * parameters per row would cross workerd's 100-parameter ceiling at six rows.
975
+ *
976
+ * Not atomic: no synchronous transaction works on every host (`ShardHost.transaction`
977
+ * is async, and a Durable Object rejects raw `BEGIN`/`COMMIT`). So a failing insert
978
+ * does not stop the rest: every row is attempted, an error row behind a failed
979
+ * success still lands, the trim always runs, and the first failure is rethrown
980
+ * afterwards. A failed row is simply missing; the rest keep dispatch order in `seq`.
981
+ * A failing trim is rethrown too, and leaves the table above `retention` until the
982
+ * next call's trim.
983
+ *
984
+ * A `SHARD_UNAVAILABLE` refusal is different: the Node host refuses SQL issued
985
+ * outside an open transaction's task before the statement runs, so nothing of the
986
+ * refused row landed and a later retry can write it. The append stops at the first
987
+ * refused row, skips the trim (it would be refused too) and returns without
988
+ * throwing; rows from that index on were not written, and nothing before it is
989
+ * written twice when the caller retries only those. A non-transient failure earlier
990
+ * in the same call is then not rethrown; its row is simply counted as consumed.
991
+ * @returns how many of `rows`, from the start, were consumed (written, or dropped by
992
+ * a non-transient failure); `rows.length` unless a refusal stopped the append
993
+ */
994
+ declare const appendRequestLogRows: (sql: SqlExec, rows: ReadonlyArray<RequestLogRowValues>, options?: {
995
+ retention?: number;
996
+ }) => number;
962
997
  /**
963
998
  * Emit one structured request event to `console` so Cloudflare's Workers Logs /
964
999
  * Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
@@ -2467,4 +2502,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2467
2502
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2468
2503
  * core. What is exported here is what a consumer actually needs.
2469
2504
  */
2470
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };
2505
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogRowValues, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, appendRequestLogRows, applyHostRootSpan, buildRequestLogRow, buildSecurityAudit, createDatabaseTally, createMetrics, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as s,AUTH_METRICS_BUCKET_RETENTION as a,AUTH_METRICS_TABLE as o,ensureAuthMetricsTables as T,readAuthMetrics as E,recordAuthEvent as S}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs";import{createMetrics as i,createSpanCollector as c,createTracedFetch as n,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-DQynv3tU.mjs";import{createDatabaseTally as A,formatTally as N,instrumentDatabase as p,instrumentSqlClient as C}from"./packem_shared/createDatabaseTally-fSQyp-qV.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as R,FUNCTION_METRICS_BUCKET_RETENTION as U,FUNCTION_METRICS_INDEX_TABLE as m,FUNCTION_METRICS_MAX_PATHS as l,FUNCTION_METRICS_READ_LIMIT as L,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as g,readFunctionMetricBuckets as O,readFunctionMetricIndexHits as H,readFunctionMetricScans as y,readFunctionMetrics as b,readFunctionMetricsTotals as h,recordFunctionMetric as v}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-Dha-40Hv.mjs";import{applyHostRootSpan as K,setHostSpanAttributes as q}from"./packem_shared/applyHostRootSpan-DToRfMn8.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Q,explainIssue as V,parseExplainIssueArgs as k}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as X,ISSUE_STATE_TABLE as j,ISSUE_STATUSES as w,upsertIssueState as z}from"./packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs";import{LogBuffer as W}from"./packem_shared/LogBuffer-CC2ssFlT.mjs";import{MetricBuffer as Z}from"./packem_shared/MetricBuffer-B8e9LgjF.mjs";import{readMetricHistory as ee,recordMetricHistory as re}from"./packem_shared/readMetricHistory-sy8Lp97A.mjs";import{latencyBucketIndex as se,readQueryInsights as ae,readQueryMetrics as oe,recordQueryMetric as Te}from"./packem_shared/latencyBucketIndex-C1aY1MtR.mjs";import{N as Se,R as _e,S as ie,a as ce,c as ne,e as Ie,b as ue,d as Me,m as Ae,p as Ne,r as pe,f as Ce,g as de,h as fe,s as Re,i as Ue}from"./packem_shared/request-log-BVf-TLws.mjs";import{MIN_ADMIN_TOKEN_LENGTH as le,MIN_AUTH_SECRET_LENGTH as Le,buildSecurityAudit as xe}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Fe,foldTraces as ge}from"./packem_shared/SpanBuffer-DPhjMBAd.mjs";import{findDanglingReferences as He}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as be}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,s as AUTH_METRICS_BUCKET_MS,a as AUTH_METRICS_BUCKET_RETENTION,o as AUTH_METRICS_TABLE,Q as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,R as FUNCTION_METRICS_BUCKET_MS,U as FUNCTION_METRICS_BUCKET_RETENTION,m as FUNCTION_METRICS_INDEX_TABLE,l as FUNCTION_METRICS_MAX_PATHS,L as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,X as ISSUE_SEVERITIES,j as ISSUE_STATE_TABLE,w as ISSUE_STATUSES,W as LogBuffer,le as MIN_ADMIN_TOKEN_LENGTH,Le as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,Se as NO_SENSITIVE_SCOPE,_e as REQUEST_LOG_TABLE,ie as SENSITIVE_ARG_MASK,Fe as SpanBuffer,ce as appendRequestLogEntry,K as applyHostRootSpan,xe as buildSecurityAudit,A as createDatabaseTally,i as createMetrics,ne as createSensitiveScope,c as createSpanCollector,n as createTracedFetch,I as createTracer,u as dispatchRootSpan,Ie as emitLogEvent,ue as emitRequestLogEvent,T as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Me as ensureRequestLogTable,V as explainIssue,He as findDanglingReferences,ge as foldTraces,N as formatTally,p as instrumentDatabase,C as instrumentSqlClient,se as latencyBucketIndex,Ae as maskSensitiveArgs,g as mergeScanAttribution,k as parseExplainIssueArgs,Ne as parseLogArgs,E as readAuthMetrics,pe as readErrorIssues,O as readFunctionMetricBuckets,H as readFunctionMetricIndexHits,y as readFunctionMetricScans,b as readFunctionMetrics,h as readFunctionMetricsTotals,ee as readMetricHistory,ae as readQueryInsights,oe as readQueryMetrics,Ce as readRequestLog,S as recordAuthEvent,v as recordFunctionMetric,re as recordMetricHistory,Te as recordQueryMetric,de as redactArgs,fe as redactCredentials,be as resolveTraceAnchor,Re as sensitiveNames,Ue as sensitiveValues,q as setHostSpanAttributes,z as upsertIssueState};
1
+ import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as s,AUTH_METRICS_BUCKET_RETENTION as a,AUTH_METRICS_TABLE as o,ensureAuthMetricsTables as T,readAuthMetrics as E,recordAuthEvent as S}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-BpH1ZAgX.mjs";import{createMetrics as _,createSpanCollector as c,createTracedFetch as n,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-CrGl5keU.mjs";import{createDatabaseTally as A,formatTally as N,instrumentDatabase as p,instrumentSqlClient as C}from"./packem_shared/createDatabaseTally-C538jG3m.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as d,FUNCTION_METRICS_BUCKET_MS as f,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 g,mergeScanAttribution as F,readFunctionMetricBuckets as O,readFunctionMetricIndexHits as H,readFunctionMetricScans as b,readFunctionMetrics as y,readFunctionMetricsTotals as h,recordFunctionMetric as v}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-Dha-40Hv.mjs";import{applyHostRootSpan as K,setHostSpanAttributes as q}from"./packem_shared/applyHostRootSpan-DToRfMn8.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Q,explainIssue as V,parseExplainIssueArgs as k}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as X,ISSUE_STATE_TABLE as w,ISSUE_STATUSES as j,upsertIssueState as z}from"./packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs";import{LogBuffer as W}from"./packem_shared/LogBuffer-CC2ssFlT.mjs";import{MetricBuffer as Z}from"./packem_shared/MetricBuffer-B8e9LgjF.mjs";import{readMetricHistory as ee,recordMetricHistory as re}from"./packem_shared/readMetricHistory-sy8Lp97A.mjs";import{latencyBucketIndex as se,readQueryInsights as ae,readQueryMetrics as oe,recordQueryMetric as Te}from"./packem_shared/latencyBucketIndex-C1aY1MtR.mjs";import{N as Se,R as ie,S as _e,a as ce,b as ne,c as Ie,e as ue,d as Me,f as Ae,m as Ne,p as pe,r as Ce,g as Re,h as de,i as fe,s as Ue,j as me}from"./packem_shared/request-log-CNa4fk1k.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Le,MIN_AUTH_SECRET_LENGTH as xe,buildSecurityAudit as Be}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Fe,foldTraces as Oe}from"./packem_shared/SpanBuffer-DPhjMBAd.mjs";import{findDanglingReferences as be}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as he}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,s as AUTH_METRICS_BUCKET_MS,a as AUTH_METRICS_BUCKET_RETENTION,o as AUTH_METRICS_TABLE,Q as DEFAULT_EXPLAIN_ISSUE_MODEL,d as FUNCTION_METRICS_BUCKETS_TABLE,f as FUNCTION_METRICS_BUCKET_MS,U as FUNCTION_METRICS_BUCKET_RETENTION,m as FUNCTION_METRICS_INDEX_TABLE,l as FUNCTION_METRICS_MAX_PATHS,L as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,X as ISSUE_SEVERITIES,w as ISSUE_STATE_TABLE,j as ISSUE_STATUSES,W as LogBuffer,Le as MIN_ADMIN_TOKEN_LENGTH,xe as MIN_AUTH_SECRET_LENGTH,Z as MetricBuffer,Se as NO_SENSITIVE_SCOPE,ie as REQUEST_LOG_TABLE,_e as SENSITIVE_ARG_MASK,Fe as SpanBuffer,ce as appendRequestLogRows,K as applyHostRootSpan,ne as buildRequestLogRow,Be as buildSecurityAudit,A as createDatabaseTally,_ as createMetrics,Ie as createSensitiveScope,c as createSpanCollector,n as createTracedFetch,I as createTracer,u as dispatchRootSpan,ue as emitLogEvent,Me as emitRequestLogEvent,T as ensureAuthMetricsTables,g as ensureFunctionMetricsTables,Ae as ensureRequestLogTable,V as explainIssue,be as findDanglingReferences,Oe as foldTraces,N as formatTally,p as instrumentDatabase,C as instrumentSqlClient,se as latencyBucketIndex,Ne as maskSensitiveArgs,F as mergeScanAttribution,k as parseExplainIssueArgs,pe as parseLogArgs,E as readAuthMetrics,Ce as readErrorIssues,O as readFunctionMetricBuckets,H as readFunctionMetricIndexHits,b as readFunctionMetricScans,y as readFunctionMetrics,h as readFunctionMetricsTotals,ee as readMetricHistory,ae as readQueryInsights,oe as readQueryMetrics,Re as readRequestLog,S as recordAuthEvent,v as recordFunctionMetric,re as recordMetricHistory,Te as recordQueryMetric,de as redactArgs,fe as redactCredentials,he as resolveTraceAnchor,Ue as sensitiveNames,me as sensitiveValues,q as setHostSpanAttributes,z as upsertIssueState};
@@ -0,0 +1 @@
1
+ import{N as t,k as o,R as i,S as E,a as g,b as R,c as S,e as L,d as n,f as d,m as u,p as m,r as p,g as T,h as _,i as N,l as v,s as A,j as I}from"./request-log-CNa4fk1k.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as NO_SENSITIVE_SCOPE,o as REQUEST_LOG_RETENTION,i as REQUEST_LOG_TABLE,E as SENSITIVE_ARG_MASK,g as appendRequestLogRows,R as buildRequestLogRow,S as createSensitiveScope,L as emitLogEvent,n as emitRequestLogEvent,d as ensureRequestLogTable,u as maskSensitiveArgs,m as parseLogArgs,p as readErrorIssues,T as readRequestLog,_ as redactArgs,N as redactCredentials,v as renderLogMessage,A as sensitiveNames,I as sensitiveValues};
@@ -1,2 +1,2 @@
1
- import{o as T}from"./otlp-DR7601NL.mjs";import{N as l,g}from"./request-log-BVf-TLws.mjs";import{toErrorType as E}from"./resolveTraceAnchor-DDAPZRBB.mjs";const h=new Set(["ALTER","ANALYZE","BEGIN","CALL","COMMIT","COPY","CREATE","DEALLOCATE","DELETE","DESCRIBE","DO","DROP","EXECUTE","EXPLAIN","GRANT","INSERT","LISTEN","LOCK","MERGE","NOTIFY","PREPARE","REFRESH","RELEASE","REPLACE","REVOKE","ROLLBACK","SAVEPOINT","SELECT","SET","SHOW","START","TABLE","TRUNCATE","UNLISTEN","UPDATE","VACUUM","VALUES","WITH"]),f="OTHER",O=/^[a-z]+/iu,R=e=>{if(typeof e!="string")return f;let t=0;for(;t<e.length;){const o=e.charAt(t);if(o==="("||o.trim()==="")t+=1;else if(e.startsWith("--",t)){const a=e.indexOf(`
2
- `,t);if(a===-1)return f;t=a+1}else if(e.startsWith("/*",t)){const a=e.indexOf("*/",t+2);if(a===-1)return f;t=a+2}else break}const r=O.exec(e.slice(t,t+16))?.[0].toUpperCase();return r!==void 0&&h.has(r)?r:f},S=e=>e??"other_sql",m=100,A=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),I=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),P=(e,t)=>{if(!I.has(e))return;const r=t[0];return typeof r=="string"&&r.length>0?r:void 0},M=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),L=(e,t,r)=>{const o=(t.scope??l).text(M(e));return r==="redact"?g(o,t.captureRaw):t.captureRaw===!0?o:E(e)},u=(e,t,r)=>{const{durationMs:o,failure:a,startTs:n}=t;return{durationMs:o,...a===void 0?{}:{error:{message:L(a,e,r),type:E(a)}},functionPath:e.functionPath,kind:"client",ok:a===void 0,parentSpanId:e.anchor.rootSpanId,...e.anchor.rayId===void 0?{}:{rayId:e.anchor.rayId},shardKey:e.shardKey,spanId:T(8),startTs:n,traceId:e.anchor.traceId,userId:e.userId()}},y=async(e,t,r,o)=>{const a=Date.now();let n,s;const c=(e.scope??l).hold();try{return s=await r(),s}catch(d){throw n=d,d}finally{const d=Date.now()-a,{tally:i}=e;i.calls+=1,i.durationMs+=d,i.perOperation[t]=(i.perOperation[t]??0)+1,n!==void 0&&(i.errors+=1);try{e.mode==="spans"&&(i.spansEmitted>=m?i.spansTruncated=!0:(i.spansEmitted+=1,e.record(o({durationMs:d,failure:n,result:s,startTs:a}))))}catch{}c()}},p=(e,t,r)=>{const o=new Map;return new Proxy({},{get(a,n){const s=Reflect.get(e,n,e);if(typeof n!="string"||typeof s!="function"||!t(n))return s;const c=s,d=o.get(n);if(d?.original===c)return d.instrumented;const i=r(n,c.bind(e));return o.set(n,{instrumented:i,original:c}),i},getOwnPropertyDescriptor(a,n){const s=Reflect.getOwnPropertyDescriptor(e,n);return s===void 0?void 0:{...s,configurable:!0}},defineProperty(a,n,s){return s.configurable===!1?!1:Reflect.defineProperty(e,n,s)},deleteProperty(a,n){return Reflect.deleteProperty(e,n)},getPrototypeOf(){return Reflect.getPrototypeOf(e)},has(a,n){return Reflect.has(e,n)},ownKeys(){return Reflect.ownKeys(e)},set(a,n,s){return Reflect.set(e,n,s,e)}})},_=(e,t)=>t.mode==="off"?e:p(e,r=>A.has(r),(r,o)=>async(...a)=>{const n=P(r,a);return y(t,r,()=>o(...a),s=>({...u(t,s,"redact"),attributes:{"db.operation.name":r,...n===void 0?{}:{"db.collection.name":n},"db.system.name":"sqlite"},name:n===void 0?`db.${r}`:`db.${r} ${n}`}))}),C=(e,t)=>{if(t.mode==="off")return e;const r=S(e.dbSystem);return p(e,o=>o==="query",(o,a)=>async(...n)=>{const s=R(n[0]);return y(t,s,()=>a(...n),c=>({...u(t,c,"type-only"),attributes:{"db.operation.name":s,...Array.isArray(c.result)?{"db.response.returned_rows":c.result.length}:{},"db.system.name":r},name:`sql.${s}`}))})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),k=(e,t="db")=>{const r={[`${t}.calls`]:e.calls,[`${t}.duration_ms`]:e.durationMs};e.errors>0&&(r[`${t}.errors`]=e.errors),e.spansTruncated&&(r[`${t}.spans_truncated`]=!0);for(const[o,a]of Object.entries(e.perOperation))r[`${t}.op.${o}`]=a;return r};export{D as createDatabaseTally,k as formatTally,_ as instrumentDatabase,C as instrumentSqlClient};
1
+ import{o as h}from"./otlp-DR7601NL.mjs";import{N as l,h as T}from"./request-log-CNa4fk1k.mjs";import{toErrorType as E}from"./resolveTraceAnchor-DDAPZRBB.mjs";const g=new Set(["ALTER","ANALYZE","BEGIN","CALL","COMMIT","COPY","CREATE","DEALLOCATE","DELETE","DESCRIBE","DO","DROP","EXECUTE","EXPLAIN","GRANT","INSERT","LISTEN","LOCK","MERGE","NOTIFY","PREPARE","REFRESH","RELEASE","REPLACE","REVOKE","ROLLBACK","SAVEPOINT","SELECT","SET","SHOW","START","TABLE","TRUNCATE","UNLISTEN","UPDATE","VACUUM","VALUES","WITH"]),f="OTHER",O=/^[a-z]+/iu,R=e=>{if(typeof e!="string")return f;let t=0;for(;t<e.length;){const o=e.charAt(t);if(o==="("||o.trim()==="")t+=1;else if(e.startsWith("--",t)){const a=e.indexOf(`
2
+ `,t);if(a===-1)return f;t=a+1}else if(e.startsWith("/*",t)){const a=e.indexOf("*/",t+2);if(a===-1)return f;t=a+2}else break}const r=O.exec(e.slice(t,t+16))?.[0].toUpperCase();return r!==void 0&&g.has(r)?r:f},S=e=>e??"other_sql",m=100,A=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","related","replace","restore"]),I=new Set(["aggregate","count","delete","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","patch","patchIf","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),P=(e,t)=>{if(!I.has(e))return;const r=t[0];return typeof r=="string"&&r.length>0?r:void 0},M=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),L=(e,t,r)=>{const o=(t.scope??l).text(M(e));return r==="redact"?T(o,t.captureRaw):t.captureRaw===!0?o:E(e)},u=(e,t,r)=>{const{durationMs:o,failure:a,startTs:n}=t;return{durationMs:o,...a===void 0?{}:{error:{message:L(a,e,r),type:E(a)}},functionPath:e.functionPath,kind:"client",ok:a===void 0,parentSpanId:e.anchor.rootSpanId,...e.anchor.rayId===void 0?{}:{rayId:e.anchor.rayId},shardKey:e.shardKey,spanId:h(8),startTs:n,traceId:e.anchor.traceId,userId:e.userId()}},y=async(e,t,r,o)=>{const a=Date.now();let n,s;const c=(e.scope??l).hold();try{return s=await r(),s}catch(d){throw n=d,d}finally{const d=Date.now()-a,{tally:i}=e;i.calls+=1,i.durationMs+=d,i.perOperation[t]=(i.perOperation[t]??0)+1,n!==void 0&&(i.errors+=1);try{e.mode==="spans"&&(i.spansEmitted>=m?i.spansTruncated=!0:(i.spansEmitted+=1,e.record(o({durationMs:d,failure:n,result:s,startTs:a}))))}catch{}c()}},p=(e,t,r)=>{const o=new Map;return new Proxy({},{get(a,n){const s=Reflect.get(e,n,e);if(typeof n!="string"||typeof s!="function"||!t(n))return s;const c=s,d=o.get(n);if(d?.original===c)return d.instrumented;const i=r(n,c.bind(e));return o.set(n,{instrumented:i,original:c}),i},getOwnPropertyDescriptor(a,n){const s=Reflect.getOwnPropertyDescriptor(e,n);return s===void 0?void 0:{...s,configurable:!0}},defineProperty(a,n,s){return s.configurable===!1?!1:Reflect.defineProperty(e,n,s)},deleteProperty(a,n){return Reflect.deleteProperty(e,n)},getPrototypeOf(){return Reflect.getPrototypeOf(e)},has(a,n){return Reflect.has(e,n)},ownKeys(){return Reflect.ownKeys(e)},set(a,n,s){return Reflect.set(e,n,s,e)}})},_=(e,t)=>t.mode==="off"?e:p(e,r=>A.has(r),(r,o)=>async(...a)=>{const n=P(r,a);return y(t,r,()=>o(...a),s=>({...u(t,s,"redact"),attributes:{"db.operation.name":r,...n===void 0?{}:{"db.collection.name":n},"db.system.name":"sqlite"},name:n===void 0?`db.${r}`:`db.${r} ${n}`}))}),C=(e,t)=>{if(t.mode==="off")return e;const r=S(e.dbSystem);return p(e,o=>o==="query",(o,a)=>async(...n)=>{const s=R(n[0]);return y(t,s,()=>a(...n),c=>({...u(t,c,"type-only"),attributes:{"db.operation.name":s,...Array.isArray(c.result)?{"db.response.returned_rows":c.result.length}:{},"db.system.name":r},name:`sql.${s}`}))})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),k=(e,t="db")=>{const r={[`${t}.calls`]:e.calls,[`${t}.duration_ms`]:e.durationMs};e.errors>0&&(r[`${t}.errors`]=e.errors),e.spansTruncated&&(r[`${t}.spans_truncated`]=!0);for(const[o,a]of Object.entries(e.perOperation))r[`${t}.op.${o}`]=a;return r};export{D as createDatabaseTally,k as formatTally,_ as instrumentDatabase,C as instrumentSqlClient};
@@ -1 +1 @@
1
- import{N as k,g as O,h as w,n as y}from"./request-log-BVf-TLws.mjs";import{o as L,b as X,O as B}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as V}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as P}from"./resolveTraceAnchor-DDAPZRBB.mjs";const G=/[\w.-]/u,J=t=>{let e="";for(const n of t)e+=G.test(n)?n:"_";return e},Q=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=J(t.name),n={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(n[`gen_ai.evaluation.${e}.label`]=t.label),n},W=t=>{const e=Object.keys(t);if(e.length===0||!e.every(s=>s==="attributes"||s==="kind"||s==="links"))return!1;const{kind:n}=t;return n===void 0||Object.hasOwn(B,n)},Y=128,Z=128,K=128,b=(t,e)=>{if(e===void 0)return;let n=Object.keys(t).length;for(const[s,d]of Object.entries(e)){const o=!Object.hasOwn(t,s);o&&n>=K||(o&&(n+=1),t[s]=d)}},F=(t,e)=>{const n=y(t,void 0,e);if(n===void 0||Object.keys(n).length<=K)return n;const s={};return b(s,n),s},U=t=>t?"full":"headline",tt=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},et=t=>{try{return new URL(t).host}catch{return t}},nt=(t,e)=>{try{return t(new URL(e))}catch{return!1}},rt=t=>t===void 0?{}:W(t)?t:{attributes:t},j=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},st=(t,e=!1,n=k)=>{const s={attributes:{},events:[],links:[]},d=U(e),o={spanContext:()=>t,addEvent:(r,a)=>{if(s.events.length>=Y)return;const c=w(n.fields(F(a,d)),e);s.events.push({...c===void 0?{}:{attributes:c},name:n.name(r),ts:Date.now()})},addLink:r=>{if(s.links.length>=Z)return;const a=w(n.fields(F(r.attributes,d)),e);s.links.push({...a===void 0?{}:{attributes:a},spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{b(s.attributes,n.fields(y(Q(r))))},recordException:r=>{const a=r instanceof Error?r.message:String(r);o.addEvent("exception",{"exception.message":O(a,e),...e&&r instanceof Error&&typeof r.stack=="string"?{"exception.stacktrace":r.stack}:{},"exception.type":P(r)})},setAttribute:(r,a)=>{b(s.attributes,n.fields(y({[r]:a},void 0,d)))},setAttributes:r=>{b(s.attributes,n.fields(y(r,void 0,d)))}};return{collected:s,handle:o}},dt=t=>{const{anchor:e,captureRaw:n=!1,fuseHostSpans:s,functionPath:d,record:o,resolveHostTracing:r,scope:a=k,shardKey:c,userId:m}=t,l=g=>async(E,T,u,x)=>{const p=x?.spanId??L(8),I=x?.parentSpanId??g,_=Date.now(),i=rt(u),M=a.fields(y(i.attributes,void 0,U(n))),z=a.name(E),{collected:A,handle:C}=st({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:p,traceId:e.traceId},n,a),q=a.hold(),R=async S=>{let f=!0,v;try{return await T(l(p),C)}catch(h){f=!1;const N=a.text(h instanceof Error?h.message:String(h));throw v={message:O(N,n),type:P(h)},h}finally{const h=Date.now()-_,N=m(),H={};b(H,M),b(H,A.attributes);const $=w(H,n),D=a.value([...i.links??[],...A.links]);try{o({...Object.keys($).length===0?{}:{attributes:$},durationMs:h,...A.events.length===0?{}:{events:A.events},...v===void 0?{}:{error:v},functionPath:d,...i.kind===void 0||i.kind==="internal"?{}:{kind:i.kind},...D.length===0?{}:{links:D},name:z,ok:f,parentSpanId:I,...j(e),shardKey:c,spanId:p,startTs:_,userId:N})}catch{}if(S!==void 0)try{V(S,{attributes:$,durationMs:h,error:v,functionPath:d,ok:f,shardKey:c,userId:N})}catch{}q()}};if(s===!0&&r!==void 0){let S=!1;try{const f=await r();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(z,v=>(S=!0,R(v)))}catch(f){if(S)throw f}}return await R()};return l(e.rootSpanId)},lt=(t,e)=>{const{anchor:n,captureRaw:s=!1,functionPath:d,propagate:o=!0,record:r,scope:a=k,shardKey:c,userId:m}=t;return async(l,g)=>{const E=L(8),T=Date.now(),u=new Request(l,g);(typeof o=="function"?nt(o,u.url):o)&&u.headers.set("traceparent",X(n.traceId,E,n.sampled??!0));let p,I;const _=a.hold();try{const i=await e(u);return I=i.status,i.ok||(p={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const M=a.text(i instanceof Error?i.message:String(i));throw p={message:O(M,s),type:P(i)},i}finally{try{r({attributes:{"http.request.method":u.method,...I===void 0?{}:{"http.response.status_code":I},"url.full":a.text(tt(u.url))},durationMs:Date.now()-T,...p===void 0?{}:{error:p},functionPath:d,kind:"client",name:a.text(`${u.method} ${et(u.url)}`),ok:p===void 0,parentSpanId:n.rootSpanId,...j(n),shardKey:c,spanId:E,startTs:T,userId:m()})}catch{}_()}}},ut=t=>{const{functionPath:e,record:n,scope:s=k,shardKey:d}=t,o=(r,a,c,m)=>{if(!Number.isFinite(c))return;const l=w(s.fields(y(m)));try{n({...l===void 0?{}:{attributes:l},functionPath:e,kind:r,name:s.name(a),shardKey:d,ts:Date.now(),value:c})}catch{}};return{count:(r,a=1,c)=>{o("counter",r,a,c)},gauge:(r,a,c)=>{o("gauge",r,a,c)},record:(r,a,c)=>{o("histogram",r,a,c)}}},pt=t=>{const{anchor:e,captureRaw:n=!1,collected:s,durationMs:d,failure:o,functionPath:r,scope:a=k,shardKey:c,startTs:m,userId:l}=t,g=w(s?.attributes??{},n);return{...Object.keys(g).length===0?{}:{attributes:g},dispatch:!0,durationMs:d,...s===void 0||s.events.length===0?{}:{events:s.events},...o===void 0?{}:{error:{message:O(a.text(o.thrown instanceof Error?o.thrown.message:String(o.thrown)),n),type:P(o.thrown)}},functionPath:r,...s===void 0||s.links.length===0?{}:{links:s.links},name:r,ok:o===void 0,parentSpanId:"",...j(e),shardKey:c,spanId:e.rootSpanId,startTs:m,userId:l}};export{ut as createMetrics,st as createSpanCollector,lt as createTracedFetch,dt as createTracer,pt as dispatchRootSpan,j as spanAnchorFields};
1
+ import{N as k,h as O,i as w,n as y}from"./request-log-CNa4fk1k.mjs";import{o as L,b as X,O as B}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as V}from"./applyHostRootSpan-DToRfMn8.mjs";import{toErrorType as P}from"./resolveTraceAnchor-DDAPZRBB.mjs";const G=/[\w.-]/u,J=t=>{let e="";for(const n of t)e+=G.test(n)?n:"_";return e},Q=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=J(t.name),n={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(n[`gen_ai.evaluation.${e}.label`]=t.label),n},W=t=>{const e=Object.keys(t);if(e.length===0||!e.every(s=>s==="attributes"||s==="kind"||s==="links"))return!1;const{kind:n}=t;return n===void 0||Object.hasOwn(B,n)},Y=128,Z=128,K=128,b=(t,e)=>{if(e===void 0)return;let n=Object.keys(t).length;for(const[s,d]of Object.entries(e)){const o=!Object.hasOwn(t,s);o&&n>=K||(o&&(n+=1),t[s]=d)}},F=(t,e)=>{const n=y(t,void 0,e);if(n===void 0||Object.keys(n).length<=K)return n;const s={};return b(s,n),s},U=t=>t?"full":"headline",tt=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},et=t=>{try{return new URL(t).host}catch{return t}},nt=(t,e)=>{try{return t(new URL(e))}catch{return!1}},rt=t=>t===void 0?{}:W(t)?t:{attributes:t},j=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},st=(t,e=!1,n=k)=>{const s={attributes:{},events:[],links:[]},d=U(e),o={spanContext:()=>t,addEvent:(r,a)=>{if(s.events.length>=Y)return;const c=w(n.fields(F(a,d)),e);s.events.push({...c===void 0?{}:{attributes:c},name:n.name(r),ts:Date.now()})},addLink:r=>{if(s.links.length>=Z)return;const a=w(n.fields(F(r.attributes,d)),e);s.links.push({...a===void 0?{}:{attributes:a},spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{b(s.attributes,n.fields(y(Q(r))))},recordException:r=>{const a=r instanceof Error?r.message:String(r);o.addEvent("exception",{"exception.message":O(a,e),...e&&r instanceof Error&&typeof r.stack=="string"?{"exception.stacktrace":r.stack}:{},"exception.type":P(r)})},setAttribute:(r,a)=>{b(s.attributes,n.fields(y({[r]:a},void 0,d)))},setAttributes:r=>{b(s.attributes,n.fields(y(r,void 0,d)))}};return{collected:s,handle:o}},dt=t=>{const{anchor:e,captureRaw:n=!1,fuseHostSpans:s,functionPath:d,record:o,resolveHostTracing:r,scope:a=k,shardKey:c,userId:m}=t,l=g=>async(E,T,u,x)=>{const p=x?.spanId??L(8),I=x?.parentSpanId??g,_=Date.now(),i=rt(u),M=a.fields(y(i.attributes,void 0,U(n))),z=a.name(E),{collected:A,handle:C}=st({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:p,traceId:e.traceId},n,a),q=a.hold(),R=async S=>{let f=!0,v;try{return await T(l(p),C)}catch(h){f=!1;const N=a.text(h instanceof Error?h.message:String(h));throw v={message:O(N,n),type:P(h)},h}finally{const h=Date.now()-_,N=m(),H={};b(H,M),b(H,A.attributes);const $=w(H,n),D=a.value([...i.links??[],...A.links]);try{o({...Object.keys($).length===0?{}:{attributes:$},durationMs:h,...A.events.length===0?{}:{events:A.events},...v===void 0?{}:{error:v},functionPath:d,...i.kind===void 0||i.kind==="internal"?{}:{kind:i.kind},...D.length===0?{}:{links:D},name:z,ok:f,parentSpanId:I,...j(e),shardKey:c,spanId:p,startTs:_,userId:N})}catch{}if(S!==void 0)try{V(S,{attributes:$,durationMs:h,error:v,functionPath:d,ok:f,shardKey:c,userId:N})}catch{}q()}};if(s===!0&&r!==void 0){let S=!1;try{const f=await r();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(z,v=>(S=!0,R(v)))}catch(f){if(S)throw f}}return await R()};return l(e.rootSpanId)},lt=(t,e)=>{const{anchor:n,captureRaw:s=!1,functionPath:d,propagate:o=!0,record:r,scope:a=k,shardKey:c,userId:m}=t;return async(l,g)=>{const E=L(8),T=Date.now(),u=new Request(l,g);(typeof o=="function"?nt(o,u.url):o)&&u.headers.set("traceparent",X(n.traceId,E,n.sampled??!0));let p,I;const _=a.hold();try{const i=await e(u);return I=i.status,i.ok||(p={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const M=a.text(i instanceof Error?i.message:String(i));throw p={message:O(M,s),type:P(i)},i}finally{try{r({attributes:{"http.request.method":u.method,...I===void 0?{}:{"http.response.status_code":I},"url.full":a.text(tt(u.url))},durationMs:Date.now()-T,...p===void 0?{}:{error:p},functionPath:d,kind:"client",name:a.text(`${u.method} ${et(u.url)}`),ok:p===void 0,parentSpanId:n.rootSpanId,...j(n),shardKey:c,spanId:E,startTs:T,userId:m()})}catch{}_()}}},ut=t=>{const{functionPath:e,record:n,scope:s=k,shardKey:d}=t,o=(r,a,c,m)=>{if(!Number.isFinite(c))return;const l=w(s.fields(y(m)));try{n({...l===void 0?{}:{attributes:l},functionPath:e,kind:r,name:s.name(a),shardKey:d,ts:Date.now(),value:c})}catch{}};return{count:(r,a=1,c)=>{o("counter",r,a,c)},gauge:(r,a,c)=>{o("gauge",r,a,c)},record:(r,a,c)=>{o("histogram",r,a,c)}}},pt=t=>{const{anchor:e,captureRaw:n=!1,collected:s,durationMs:d,failure:o,functionPath:r,scope:a=k,shardKey:c,startTs:m,userId:l}=t,g=w(s?.attributes??{},n);return{...Object.keys(g).length===0?{}:{attributes:g},dispatch:!0,durationMs:d,...s===void 0||s.events.length===0?{}:{events:s.events},...o===void 0?{}:{error:{message:O(a.text(o.thrown instanceof Error?o.thrown.message:String(o.thrown)),n),type:P(o.thrown)}},functionPath:r,...s===void 0||s.links.length===0?{}:{links:s.links},name:r,ok:o===void 0,parentSpanId:"",...j(e),shardKey:c,spanId:e.rootSpanId,startTs:m,userId:l}};export{ut as createMetrics,st as createSpanCollector,lt as createTracedFetch,dt as createTracer,pt as dispatchRootSpan,j as spanAnchorFields};
@@ -0,0 +1,26 @@
1
+ import{isLunoraError as Ee}from"@lunora/errors";import{fingerprintError as Y}from"@lunora/fingerprint";import{createRedactor as me,standardRules as Ae}from"@visulima/redact";import{readIssueStates as ye}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as m}from"./run-sql-0aPgJkIw.mjs";const v=e=>{const t=String(e.name),s=String(e.message);return s===""?t:`${t}: ${s}`},N=e=>{if(typeof e=="string")return e;if(e instanceof Error)return v(e);try{return JSON.stringify(e)??String(e)}catch{return String(e)}},_e=4,be=10,Te=3584,Oe=4,C=512,Q=8,Ne=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ee=e=>{if(!Ne(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=(e,t=0,s=new WeakSet)=>e instanceof Error?!0:typeof e!="object"||e===null||t>=Q||s.has(e)?!1:(s.add(e),Array.isArray(e)?e.some(n=>w(n,t+1,s)):ee(e)&&Object.values(e).some(n=>w(n,t+1,s))),Re=e=>{if(typeof e=="bigint")return String(e);if(typeof e!="object"||e===null)return e;try{return JSON.stringify(e),e}catch{return}},Ie=(e,t,s)=>{if(e!==void 0)return t==="none"||t==="minimal"||t==="root"&&s>0?"":t==="short"?e.split(`
2
+ `).slice(0,Oe+1).join(`
3
+ `):e},we=(e,t,s,n)=>({errors:e,mask:s,memo:new WeakMap,mode:t,path:new Set}),te=(e,t,s)=>{if(!t.path.has(e)){if(t.memo.has(e))return t.memo.get(e);t.path.add(e);try{const n=s();return t.memo.set(e,n),n}finally{t.path.delete(e)}}},L=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},se=(e,t,s)=>t.path.has(e)||s>_e?{message:e.message,name:e.name}:te(e,t,()=>{const n=f=>f instanceof Error?se(f,t,s+1):(t.child??(u=>T(u,t,0,s+1)))(f),r=t.mode==="minimal",c=f=>f.length>C?`${f.slice(0,C)}…`:f,i=f=>r&&!(f instanceof Error)?c(N(f)):n(f),a={message:r?c(e.message):e.message,name:e.name};if(!r)for(const[f,u]of Object.entries(e))f!=="message"&&f!=="name"&&L(a,f,n(u));const d=Ie(e.stack,t.mode,s);return d!==void 0&&(a.stack=d),e.cause!==void 0&&(a.cause=i(e.cause)),e instanceof AggregateError&&Array.isArray(e.errors)&&(a.errors=e.errors.slice(0,be).map(f=>i(f))),t.mask(a)}),T=(e,t,s,n)=>e instanceof Error?t.errors==="full"?se(e,t,n):v(e):typeof e!="object"||e===null||s>=Q||!(Array.isArray(e)||ee(e))?Re(e):te(e,t,()=>Array.isArray(e)?e.map(r=>T(r,t,s+1,n)):Object.fromEntries(Object.entries(e).map(([r,c])=>[r,T(c,t,s+1,n)]))),re=e=>e,Le=(e,t,s)=>{const n=o=>JSON.stringify(T(e,we(t,o,s),0,0)),r=o=>o===void 0||o.length<=Te,c=n("all");if(t==="headline"||r(c))return c;const i=n("minimal");if(!r(i))return i;for(const o of["root","short","none"]){const a=n(o);if(r(a))return a}return i},P=(e,t="headline",s=re)=>{if(typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;try{return!w(e)||t==="headline"&&e instanceof Error?N(e):Le(e,t,s)??String(e)}catch{return String(e)}},U=(e,t,s="headline",n=re)=>{if(e===void 0&&t===void 0)return;const r={};if(t!==void 0)for(const[c,i]of Object.entries(t))L(r,c,P(i,s,n));if(e!==void 0)for(const[c,i]of Object.entries(e))L(r,c,P(i,s,n));return Object.keys(r).length===0?void 0:r},ke=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"]),Me=new Set(["card","pass","pin","session"]),xe=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),je=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),$e=new Set(["card no","connection string","database url","one time"]),De=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],Ce=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Pe=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),Ue=new Set(["max","min","num","total"]),R=4096,Ge=128,Ve=16384,p="<REDACTED>",He="[redaction budget exceeded]",Fe=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),G=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,Je=(e,t)=>{const s=G(e[t]),n=t>0?G(e[t-1]):void 0;if(ke.has(s))return s;if(n!==void 0){if(s==="key"&&xe.has(n))return"key";if(s==="code"&&je.has(n))return"code";if($e.has(`${n} ${s}`))return`${n} ${s}`}return De.some(r=>s.endsWith(r))?s:void 0},ne=e=>{const t=Fe(e);if(t.length===0)return"none";const s=Pe.has(t.at(-1))||Ue.has(t[0]);for(let n=t.length-1;n>=0;n-=1){const r=Je(t,n);if(r!==void 0)return s?"count-secret":t.slice(n+1).every(c=>Ce.has(c))?Me.has(r)&&n===t.length-1?"scalar-secret":"secret":"none"}return"none"},Xe=e=>typeof e=="boolean"||e===null||e===void 0?e:p,We=e=>{const t=e.indexOf("://")+3,s=e.slice(t),n=s.split(/[?#]/,1)[0],r=n.lastIndexOf("@"),c=n.indexOf(":"),i=n.indexOf("/"),o=c!==-1&&/^\d+$/.test(n.slice(c+1,i===-1?void 0:i)),a=c!==-1&&!o&&(i===-1||c<i);if(r===-1&&a&&s.includes("@",n.length))return e.slice(0,t);const d=r!==-1&&(i===-1||r<i||c!==-1&&c<r&&!o);return`${e.slice(0,t)}${d?n.slice(r+1):n}`},ze=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Be=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Ke=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,oe=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,ie=[{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\.`}],Ze=String.raw`(?<=^|[^\w-]|${oe})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,qe=new RegExp([...ie.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${oe})${t}${e}`),Ze].join("|"),"g"),Ye=new RegExp([...ie.map(({prefix:e})=>e),"eyJ"].join("|")),ve=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,A=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,V=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,H=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,Qe=e=>{let t="",s=0;A.lastIndex=0;for(let n=A.exec(e);n!==null;n=A.exec(e)){const r=ne(n[2]),c=n.index+n[0].length;V.lastIndex=c;const i=r==="none"?null:V.exec(e);if(i===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(i[0])){A.lastIndex=Math.max(c,n.index+1);continue}const o=i[0],a=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=c+o.length;a===""&&n[3]===":"&&(H.lastIndex=d,d+=H.exec(e)?.[0].length??0),t+=`${e.slice(s,c)}${a}${p}${o.length>a.length&&o.endsWith(a)?a:""}`,s=d,A.lastIndex=s}return t+e.slice(s)},et=/[:=@]|basic|bearer|digest|-u\b|--/i,tt=e=>{const t=Ye.test(e);if(!t&&!et.test(e))return e;const s=e.replaceAll(Be,`-----BEGIN $1-----${p}`).replaceAll(ze,We).replaceAll(Ke,`$1 ${p}`);return Qe((t?s.replaceAll(qe,p):s).replaceAll(ve,`$1$2$3${p}`))},st=(e,t)=>{if(t.remaining<=0)return He;const s=e.slice(0,R+Ge);t.remaining-=s.length;const n=tt(s);return n.length>R||e.length>s.length?`${n.slice(0,R)}…[truncated]`:n},rt=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),y=Symbol("no-json"),nt=e=>{const{toJSON:t}=e;if(typeof t!="function")return y;try{const s=t.call(e);return s===e?y:s}catch{return y}},ot=32,b=(e,t,s,n,r)=>{if(typeof e=="string")return n?p:st(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&rt(e))return e;if(t.has(e)||s>=ot)return p;const c=Array.isArray(e)?y:nt(e);if(c!==y){t.add(e);const o=b(c,t,s+1,n,r);return t.delete(e),o}t.add(e);const i=Array.isArray(e)?e.map(o=>b(o,t,s+1,n,r)):Object.fromEntries(Object.entries(e).map(([o,a])=>{const d=ne(o);return d==="secret"||d==="scalar-secret"&&(typeof a!="object"||a===null)?[o,Xe(a)]:[o,b(a,t,s+1,d==="count-secret"&&(typeof a=="string"||Array.isArray(a)),r)]}));return t.delete(e),i},O=e=>b(e,new WeakSet,0,!1,{remaining:Ve}),it=(e,t)=>{if(e.size<t)return;const s=e.keys().next().value;s!==void 0&&e.delete(s)},ct=32,at=(e,t)=>{let s=t,n;const r=(i,o,a)=>{const d=Object.getOwnPropertyDescriptor(i,o);return d!==void 0&&"value"in d&&n(d.value,a+1)},c=(i,o)=>{if(Array.isArray(i)){for(let d=0;d<i.length;d+=1)if(!r(i,d,o))return!1;return!0}const a=Object.getPrototypeOf(i);if(a!==null&&a!==Object.prototype)return!1;for(const d of Object.keys(i))if(s-=d.length,s<0||!r(i,d,o))return!1;return!0};return n=(i,o)=>(s-=1,s<0?!1:i===null||typeof i=="boolean"?!0:typeof i=="string"?(s-=i.length,s>=0):typeof i=="number"?Number.isFinite(i):typeof i!="object"||o>=ct||"toJSON"in i?!1:c(i,o)),n(e,0)},h="__lunora_reqlog__",M=1e3,ce="lunora",ft=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],dt=me(Ae,{exclude:["pass"]}),Jt=(e,t=!1)=>t||e===null||e===void 0?e:O(e),S=(e,t=!1)=>t||e===null||e===void 0?e:dt(O(e)),l="«sensitive»",Xt=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,n])=>[s,t.has(s)?l:n])),lt=8,ae=4,fe=3,x=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),ut=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${x(e)}(?![\p{L}\p{N}])`,"gu"),gt=e=>new RegExp(String.raw`(?<=["'])${x(e)}(?=["'])`,"gu"),F=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${x(e)}(?![\p{L}\p{N}])`,"gu"),pt=new Set(["false","true"]),ht=new RegExp("^\\p{N}+$","u"),j=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<ae?[e]:[e,t]},de=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},le=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),ue=e=>{const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join(""),s=btoa(Array.from(e,r=>String.fromCodePoint(r)).join("")),n=s.replaceAll("+","-").replaceAll("/","_").split("=")[0]??"";return[...new Set([s,n,t,t.toUpperCase()])]},St=e=>{const t=le(e);if(t.length===0)return[];const s=de(t);return[...s===void 0||s.length===0?[]:j(s),...ue(t)]},Et=e=>e instanceof Error&&e.message.length>0?j(e.message):[],mt=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],At=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="string")r.length>0&&t.push(...j(r));else if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")t.push(String(r));else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))t.push(...St(r));else if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r),t.push(...Et(r));for(const c of Object.values(r))n.push(c);n.push(...mt(r))}}},Wt=(e,t)=>{const s=[];for(const n of t)if(Object.hasOwn(e,n)){const r=e[n];typeof r=="object"&&r!==null&&!(r instanceof ArrayBuffer)&&!ArrayBuffer.isView(r)&&s.push(N(r)),At(r,s)}return s},yt=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),_t=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r);for(const c of yt(r))t.push(c);for(const c of Object.values(r))n.push(c)}}},zt=(e,t)=>{const s=[];for(const n of t)Object.hasOwn(e,n)&&_t(e[n],s);return s},bt=(e,t)=>{if(pt.has(t))return e.replaceAll(gt(t),l).replaceAll(F(t,"="),l);if(t.length>=ae)return e.replaceAll(t,l);if(t.length>=fe)return e.includes(t)?e.replaceAll(ut(t),l):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(l));return ht.test(t)?s:s.replaceAll(F(t,"=:"),l)},_=(e,t)=>{if(t.includes(e))return l;let s=e;for(const n of t.toSorted((r,c)=>c.length-r.length))s=bt(s,n);return s},Tt={names:new Set,texts:[]},J=e=>e.texts.length>0||e.names.size>0,Ot=(e,t)=>t.names.has(e)?l:_(e,t.texts),Nt=(e,t)=>{if(!Object.hasOwn(e,t))return t;let s=2;for(;Object.hasOwn(e,`${t}#${String(s)}`);)s+=1;return`${t}#${String(s)}`},Rt=(e,t,s)=>{if(Array.isArray(e)){const c=e.map(i=>s(i));return c.some((i,o)=>i!==e[o])?c:e}let n=!1;const r={};for(const[c,i]of Object.entries(e)){const o=s(i),a=Nt(r,Ot(c,t));n||=o!==i||a!==c,r[a]=o}return n?r:e},It=(e,t)=>{const s=le(e);if(s.length===0)return!1;const n=de(s);return n!==void 0&&t.texts.some(r=>n.includes(r))||ue(s).some(r=>_(r,t.texts)!==r)},k=(e,t,s,n=new Set)=>{if(typeof e=="string")return _(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return It(e,t)?l:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const c=String(e);return c.length>=fe&&t.texts.includes(c)?l:e}if(e instanceof Error){const c=String(e),i=_(c,t.texts);return i===c?e:i}if(typeof e!="object"||e===null)return e;if(s>=lt||n.has(e))return l;n.add(e);const r=Rt(e,t,c=>k(c,t,s+1,n));return n.delete(e),r},wt=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},n=!1,r=0;const c=()=>{n&&r===0&&(s=Tt)},i=o=>s.texts.length===0?o:_(o,s.texts);return{add(o,a=[]){!n&&(o.length>0||a.length>0)&&(s={names:new Set([...s.names,...a]),texts:[...new Set([...s.texts,...o])]})},clear(){n=!0,c()},hold(){r+=1;let o=!1;return()=>{o||(o=!0,r-=1,c())}},fields:o=>o===void 0||!J(s)?o:k(o,s,0),name:o=>s.names.has(o)?l:i(o),text:i,value:o=>J(s)?k(o,s,0):o}},Bt={...wt([]),add:()=>{}},X=new WeakSet,$=e=>{if(!X.has(e)){m(e,`CREATE TABLE IF NOT EXISTS "${h}" (
4
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
5
+ ts REAL NOT NULL,
6
+ function_path TEXT NOT NULL,
7
+ shard_key TEXT,
8
+ user_id TEXT,
9
+ identity TEXT,
10
+ args TEXT,
11
+ outcome TEXT NOT NULL,
12
+ error_message TEXT,
13
+ error_fingerprint TEXT,
14
+ trace_id TEXT,
15
+ deployment_id TEXT,
16
+ version_tag TEXT,
17
+ duration_ms REAL NOT NULL,
18
+ tables_read TEXT NOT NULL DEFAULT '[]',
19
+ tables_written TEXT NOT NULL DEFAULT '[]',
20
+ cache_hit INTEGER,
21
+ subscriptions_rerun INTEGER NOT NULL DEFAULT 0
22
+ )`);for(const t of ft)try{m(e,`ALTER TABLE "${h}" ADD COLUMN ${t}`)}catch{}X.add(e)}},W=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Lt=e=>e===void 0?null:e?1:0,kt=256,z=1024,I=new Map,ge=e=>{if(!at(e,z))return;const t=JSON.stringify(e);if(t.length>z)return;const s=I.get(t);if(s!==void 0)return s;const n=JSON.stringify(S(e)),r={json:n,value:JSON.parse(n)};return it(I,kt),I.set(t,r),r},B=(e,t)=>{const s=t?void 0:ge(e);return s===void 0?JSON.stringify(S(e,t)):s.json},K=(e,t)=>{const s=t?void 0:ge(e);return s===void 0?S(e,t):s.value},Kt=(e,t=!1)=>{const s=e.outcome==="error"&&e.errorMessage!==void 0?Y({functionPath:e.functionPath,message:e.errorMessage}).hash:void 0;return[e.ts,e.functionPath,e.shardKey??null,e.userId??null,e.identity===void 0?null:B(e.identity,t),e.redactedArgs===void 0?null:B(e.redactedArgs,t),e.outcome,e.errorMessage===void 0?null:String(S(e.errorMessage,t)),s??null,e.traceId??null,e.deploymentId??null,e.versionTag??null,e.durationMs,W(e.tablesRead),W(e.tablesWritten),Lt(e.cacheHit),e.subscriptionsReRun??0]},Z=e=>Ee(e)&&e.code==="SHARD_UNAVAILABLE",Zt=(e,t,s={})=>{if(t.length===0)return 0;try{$(e)}catch(r){if(Z(r))return 0;throw r}let n;for(const[r,c]of t.entries())try{m(e,`INSERT INTO "${h}"
23
+ (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
24
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,...c)}catch(i){if(Z(i))return r;n??={error:i}}if(m(e,`DELETE FROM "${h}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${h}")`,s.retention??M),n!==void 0)throw n.error;return t.length},qt=(e,t={})=>{const s=t.captureRaw??!1,n={args:e.redactedArgs===void 0?void 0:K(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:S(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:K(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:ce,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},r=JSON.stringify(n);e.outcome==="error"?console.error(r):console.log(r)},Mt="log",xt=e=>e.map(t=>N(t)).join(" "),jt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Yt=(e,t)=>e.length===2&&typeof e[0]=="string"&&jt(e[1])?{fields:U(e[1],t,"full",O),message:e[0]}:{fields:U(void 0,t,"full",O),message:xt(e)},vt=(e,t={})=>{const s=t.captureRaw??!1,n={fields:e.fields===void 0?void 0:S(e.fields,s),function:e.functionPath,level:e.level,message:S(e.message,s),rayId:e.rayId,shard:e.shardKey,source:ce,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Mt,userId:e.userId};let r;try{r=JSON.stringify(n)}catch{r=JSON.stringify({...n,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(r):e.level==="warn"?console.warn(r):console.log(r)},$t=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,pe=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push($t("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},q=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},Dt=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Ct=e=>{try{return JSON.parse(e)}catch{return}},Qt=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["seq > ?"],r=[t.sinceSeq??0];if(pe(n,r,t),t.outcome!==void 0&&(n.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);n.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),r.push(o,o)}r.push(s);const c=t.sinceSeq===void 0?"DESC":"ASC";return m(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
25
+ FROM "${h}" WHERE ${n.join(" AND ")} ORDER BY seq ${c} LIMIT ?`,...r).toArray().map(o=>{const a={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:q(o.tables_read),tablesWritten:q(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(a.shardKey=o.shard_key),o.user_id!==null&&(a.userId=o.user_id),o.identity!==null){const d=Dt(o.identity);d!==void 0&&(a.identity=d)}if(o.args!==null){const d=Ct(o.args);d!==void 0&&(a.redactedArgs=d)}return o.error_message!==null&&(a.errorMessage=o.error_message),o.cache_hit!==null&&(a.cacheHit=o.cache_hit===1),o.trace_id!==null&&(a.traceId=o.trace_id),o.deployment_id!==null&&(a.deploymentId=o.deployment_id),o.version_tag!==null&&(a.versionTag=o.version_tag),a})},Pt=(e,t)=>{const s=ye(e,[...t.keys()]);for(const n of t.values()){const r=s.get(n.hash);r!==void 0&&(n.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(n.assignee=r.assignee),r.severity!==void 0&&(n.severity=r.severity),n.status=r.status==="resolved"&&n.lastSeen>r.updatedAt?"open":r.status)}},es=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["outcome = 'error'"],r=[];pe(n,r,t),r.push(s);const c=m(e,`SELECT function_path, error_message, error_fingerprint, ts
26
+ FROM "${h}" WHERE ${n.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),i=new Map,o=new Map;for(const f of c){const u=f.error_message??"",{culprit:he,hash:Se,title:D}=Y({functionPath:f.function_path,message:u}),E=f.error_fingerprint??Se,g=i.get(E);if(g===void 0){i.set(E,{count:1,culprit:he,firstSeen:f.ts,hash:E,lastSeen:f.ts,sampleMessage:u,status:"open",title:D}),o.set(E,f.ts);continue}g.count+=1,g.firstSeen=Math.min(g.firstSeen,f.ts),g.lastSeen=Math.max(g.lastSeen,f.ts),f.ts>(o.get(E)??Number.NEGATIVE_INFINITY)&&(o.set(E,f.ts),g.sampleMessage=u,g.title=D)}Pt(e,i);const a=[...i.values()];return(t.status===void 0?a:a.filter(f=>f.status===t.status)).toSorted((f,u)=>u.lastSeen-f.lastSeen)};export{Bt as N,h as R,l as S,Zt as a,Kt as b,wt as c,qt as d,vt as e,$ as f,Qt as g,S as h,Jt as i,Wt as j,M as k,xt as l,Xt as m,U as n,Yt as p,es as r,zt as s};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.206",
3
+ "version": "1.0.0-alpha.207",
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",
@@ -1 +0,0 @@
1
- import{N as E,j as i,R as o,S as g,a as S,c as n,e as L,b as m,d as p,m as R,p as d,r as T,f as _,g as u,h as N,k as v,s as A,i as I}from"./request-log-BVf-TLws.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./prune-marker-CksedkkK.mjs";import"./run-sql-0aPgJkIw.mjs";export{E as NO_SENSITIVE_SCOPE,i as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as SENSITIVE_ARG_MASK,S as appendRequestLogEntry,n as createSensitiveScope,L as emitLogEvent,m as emitRequestLogEvent,p as ensureRequestLogTable,R as maskSensitiveArgs,d as parseLogArgs,T as readErrorIssues,_ as readRequestLog,u as redactArgs,N as redactCredentials,v as renderLogMessage,A as sensitiveNames,I as sensitiveValues};
@@ -1,26 +0,0 @@
1
- import{fingerprintError as q}from"@lunora/fingerprint";import{createRedactor as he,standardRules as Ee}from"@visulima/redact";import{readIssueStates as me}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{p as Ae}from"./prune-marker-CksedkkK.mjs";import{r as m}from"./run-sql-0aPgJkIw.mjs";const Y=e=>{const t=String(e.name),s=String(e.message);return s===""?t:`${t}: ${s}`},N=e=>{if(typeof e=="string")return e;if(e instanceof Error)return Y(e);try{return JSON.stringify(e)??String(e)}catch{return String(e)}},ye=4,_e=10,be=3584,Te=4,P=512,v=8,Oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>{if(!Oe(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=(e,t=0,s=new WeakSet)=>e instanceof Error?!0:typeof e!="object"||e===null||t>=v||s.has(e)?!1:(s.add(e),Array.isArray(e)?e.some(n=>w(n,t+1,s)):Q(e)&&Object.values(e).some(n=>w(n,t+1,s))),Ne=e=>{if(typeof e=="bigint")return String(e);if(typeof e!="object"||e===null)return e;try{return JSON.stringify(e),e}catch{return}},Re=(e,t,s)=>{if(e!==void 0)return t==="none"||t==="minimal"||t==="root"&&s>0?"":t==="short"?e.split(`
2
- `).slice(0,Te+1).join(`
3
- `):e},Ie=(e,t,s,n)=>({errors:e,mask:s,memo:new WeakMap,mode:t,path:new Set}),ee=(e,t,s)=>{if(!t.path.has(e)){if(t.memo.has(e))return t.memo.get(e);t.path.add(e);try{const n=s();return t.memo.set(e,n),n}finally{t.path.delete(e)}}},L=(e,t,s)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:s,writable:!0})},te=(e,t,s)=>t.path.has(e)||s>ye?{message:e.message,name:e.name}:ee(e,t,()=>{const n=f=>f instanceof Error?te(f,t,s+1):(t.child??(u=>T(u,t,0,s+1)))(f),r=t.mode==="minimal",i=f=>f.length>P?`${f.slice(0,P)}…`:f,c=f=>r&&!(f instanceof Error)?i(N(f)):n(f),a={message:r?i(e.message):e.message,name:e.name};if(!r)for(const[f,u]of Object.entries(e))f!=="message"&&f!=="name"&&L(a,f,n(u));const d=Re(e.stack,t.mode,s);return d!==void 0&&(a.stack=d),e.cause!==void 0&&(a.cause=c(e.cause)),e instanceof AggregateError&&Array.isArray(e.errors)&&(a.errors=e.errors.slice(0,_e).map(f=>c(f))),t.mask(a)}),T=(e,t,s,n)=>e instanceof Error?t.errors==="full"?te(e,t,n):Y(e):typeof e!="object"||e===null||s>=v||!(Array.isArray(e)||Q(e))?Ne(e):ee(e,t,()=>Array.isArray(e)?e.map(r=>T(r,t,s+1,n)):Object.fromEntries(Object.entries(e).map(([r,i])=>[r,T(i,t,s+1,n)]))),se=e=>e,we=(e,t,s)=>{const n=o=>JSON.stringify(T(e,Ie(t,o,s),0,0)),r=o=>o===void 0||o.length<=be,i=n("all");if(t==="headline"||r(i))return i;const c=n("minimal");if(!r(c))return c;for(const o of["root","short","none"]){const a=n(o);if(r(a))return a}return c},C=(e,t="headline",s=se)=>{if(typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;try{return!w(e)||t==="headline"&&e instanceof Error?N(e):we(e,t,s)??String(e)}catch{return String(e)}},U=(e,t,s="headline",n=se)=>{if(e===void 0&&t===void 0)return;const r={};if(t!==void 0)for(const[i,c]of Object.entries(t))L(r,i,C(c,s,n));if(e!==void 0)for(const[i,c]of Object.entries(e))L(r,i,C(c,s,n));return Object.keys(r).length===0?void 0:r},Le=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),ke=new Set(["card","pass","pin","session"]),Me=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),xe=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),je=new Set(["card no","connection string","database url","one time"]),$e=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],De=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Pe=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),Ce=new Set(["max","min","num","total"]),R=4096,Ue=128,Ge=16384,g="<REDACTED>",Ve="[redaction budget exceeded]",Fe=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),G=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,He=(e,t)=>{const s=G(e[t]),n=t>0?G(e[t-1]):void 0;if(Le.has(s))return s;if(n!==void 0){if(s==="key"&&Me.has(n))return"key";if(s==="code"&&xe.has(n))return"code";if(je.has(`${n} ${s}`))return`${n} ${s}`}return $e.some(r=>s.endsWith(r))?s:void 0},re=e=>{const t=Fe(e);if(t.length===0)return"none";const s=Pe.has(t.at(-1))||Ce.has(t[0]);for(let n=t.length-1;n>=0;n-=1){const r=He(t,n);if(r!==void 0)return s?"count-secret":t.slice(n+1).every(i=>De.has(i))?ke.has(r)&&n===t.length-1?"scalar-secret":"secret":"none"}return"none"},Je=e=>typeof e=="boolean"||e===null||e===void 0?e:g,We=e=>{const t=e.indexOf("://")+3,s=e.slice(t),n=s.split(/[?#]/,1)[0],r=n.lastIndexOf("@"),i=n.indexOf(":"),c=n.indexOf("/"),o=i!==-1&&/^\d+$/.test(n.slice(i+1,c===-1?void 0:c)),a=i!==-1&&!o&&(c===-1||i<c);if(r===-1&&a&&s.includes("@",n.length))return e.slice(0,t);const d=r!==-1&&(c===-1||r<c||i!==-1&&i<r&&!o);return`${e.slice(0,t)}${d?n.slice(r+1):n}`},Xe=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,ze=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Be=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,ne=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,oe=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],Ke=String.raw`(?<=^|[^\w-]|${ne})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Ze=new RegExp([...oe.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${ne})${t}${e}`),Ke].join("|"),"g"),qe=new RegExp([...oe.map(({prefix:e})=>e),"eyJ"].join("|")),Ye=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,A=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,V=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,F=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ve=e=>{let t="",s=0;A.lastIndex=0;for(let n=A.exec(e);n!==null;n=A.exec(e)){const r=re(n[2]),i=n.index+n[0].length;V.lastIndex=i;const c=r==="none"?null:V.exec(e);if(c===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){A.lastIndex=Math.max(i,n.index+1);continue}const o=c[0],a=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=i+o.length;a===""&&n[3]===":"&&(F.lastIndex=d,d+=F.exec(e)?.[0].length??0),t+=`${e.slice(s,i)}${a}${g}${o.length>a.length&&o.endsWith(a)?a:""}`,s=d,A.lastIndex=s}return t+e.slice(s)},Qe=/[:=@]|basic|bearer|digest|-u\b|--/i,et=e=>{const t=qe.test(e);if(!t&&!Qe.test(e))return e;const s=e.replaceAll(ze,`-----BEGIN $1-----${g}`).replaceAll(Xe,We).replaceAll(Be,`$1 ${g}`);return ve((t?s.replaceAll(Ze,g):s).replaceAll(Ye,`$1$2$3${g}`))},tt=(e,t)=>{if(t.remaining<=0)return Ve;const s=e.slice(0,R+Ue);t.remaining-=s.length;const n=et(s);return n.length>R||e.length>s.length?`${n.slice(0,R)}…[truncated]`:n},st=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),y=Symbol("no-json"),rt=e=>{const{toJSON:t}=e;if(typeof t!="function")return y;try{const s=t.call(e);return s===e?y:s}catch{return y}},nt=32,b=(e,t,s,n,r)=>{if(typeof e=="string")return n?g:tt(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&st(e))return e;if(t.has(e)||s>=nt)return g;const i=Array.isArray(e)?y:rt(e);if(i!==y){t.add(e);const o=b(i,t,s+1,n,r);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>b(o,t,s+1,n,r)):Object.fromEntries(Object.entries(e).map(([o,a])=>{const d=re(o);return d==="secret"||d==="scalar-secret"&&(typeof a!="object"||a===null)?[o,Je(a)]:[o,b(a,t,s+1,d==="count-secret"&&(typeof a=="string"||Array.isArray(a)),r)]}));return t.delete(e),c},O=e=>b(e,new WeakSet,0,!1,{remaining:Ge}),ot=(e,t)=>{if(e.size<t)return;const s=e.keys().next().value;s!==void 0&&e.delete(s)},it=32,ct=(e,t)=>{let s=t,n;const r=(c,o,a)=>{const d=Object.getOwnPropertyDescriptor(c,o);return d!==void 0&&"value"in d&&n(d.value,a+1)},i=(c,o)=>{if(Array.isArray(c)){for(let d=0;d<c.length;d+=1)if(!r(c,d,o))return!1;return!0}const a=Object.getPrototypeOf(c);if(a!==null&&a!==Object.prototype)return!1;for(const d of Object.keys(c))if(s-=d.length,s<0||!r(c,d,o))return!1;return!0};return n=(c,o)=>(s-=1,s<0?!1:c===null||typeof c=="boolean"?!0:typeof c=="string"?(s-=c.length,s>=0):typeof c=="number"?Number.isFinite(c):typeof c!="object"||o>=it||"toJSON"in c?!1:i(c,o)),n(e,0)},S="__lunora_reqlog__",at=6e4,M=1e3,ie="lunora",ft=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],dt=he(Ee,{exclude:["pass"]}),Jt=(e,t=!1)=>t||e===null||e===void 0?e:O(e),h=(e,t=!1)=>t||e===null||e===void 0?e:dt(O(e)),l="«sensitive»",Wt=(e,t)=>t.size===0?e:Object.fromEntries(Object.entries(e).map(([s,n])=>[s,t.has(s)?l:n])),lt=8,ce=4,ae=3,x=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),ut=e=>new RegExp(String.raw`(?<![\p{L}\p{N}])${x(e)}(?![\p{L}\p{N}])`,"gu"),pt=e=>new RegExp(String.raw`(?<=["'])${x(e)}(?=["'])`,"gu"),H=(e,t)=>new RegExp(String.raw`(?<=[${t}][ ]*)${x(e)}(?![\p{L}\p{N}])`,"gu"),gt=new Set(["false","true"]),St=new RegExp("^\\p{N}+$","u"),j=e=>{const t=JSON.stringify(e).slice(1,-1);return t===e||e.length<ce?[e]:[e,t]},fe=e=>{try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}},de=e=>e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),le=e=>{const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join(""),s=btoa(Array.from(e,r=>String.fromCodePoint(r)).join("")),n=s.replaceAll("+","-").replaceAll("/","_").split("=")[0]??"";return[...new Set([s,n,t,t.toUpperCase()])]},ht=e=>{const t=de(e);if(t.length===0)return[];const s=fe(t);return[...s===void 0||s.length===0?[]:j(s),...le(t)]},Et=e=>e instanceof Error&&e.message.length>0?j(e.message):[],mt=e=>e instanceof Error?e instanceof AggregateError?[e.cause,...e.errors]:[e.cause]:[],At=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="string")r.length>0&&t.push(...j(r));else if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")t.push(String(r));else if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))t.push(...ht(r));else if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r),t.push(...Et(r));for(const i of Object.values(r))n.push(i);n.push(...mt(r))}}},Xt=(e,t)=>{const s=[];for(const n of t)if(Object.hasOwn(e,n)){const r=e[n];typeof r=="object"&&r!==null&&!(r instanceof ArrayBuffer)&&!ArrayBuffer.isView(r)&&s.push(N(r)),At(r,s)}return s},yt=e=>Array.isArray(e)?[]:Object.keys(e).filter(t=>t.length>0),_t=(e,t)=>{const s=new Set,n=[e];for(;n.length>0;){const r=n.pop();if(typeof r=="object"&&r!==null&&!s.has(r)){s.add(r);for(const i of yt(r))t.push(i);for(const i of Object.values(r))n.push(i)}}},zt=(e,t)=>{const s=[];for(const n of t)Object.hasOwn(e,n)&&_t(e[n],s);return s},bt=(e,t)=>{if(gt.has(t))return e.replaceAll(pt(t),l).replaceAll(H(t,"="),l);if(t.length>=ce)return e.replaceAll(t,l);if(t.length>=ae)return e.includes(t)?e.replaceAll(ut(t),l):e;const s=e.replaceAll(JSON.stringify(t),JSON.stringify(l));return St.test(t)?s:s.replaceAll(H(t,"=:"),l)},_=(e,t)=>{if(t.includes(e))return l;let s=e;for(const n of t.toSorted((r,i)=>i.length-r.length))s=bt(s,n);return s},Tt={names:new Set,texts:[]},J=e=>e.texts.length>0||e.names.size>0,Ot=(e,t)=>t.names.has(e)?l:_(e,t.texts),Nt=(e,t)=>{if(!Object.hasOwn(e,t))return t;let s=2;for(;Object.hasOwn(e,`${t}#${String(s)}`);)s+=1;return`${t}#${String(s)}`},Rt=(e,t,s)=>{if(Array.isArray(e)){const i=e.map(c=>s(c));return i.some((c,o)=>c!==e[o])?i:e}let n=!1;const r={};for(const[i,c]of Object.entries(e)){const o=s(c),a=Nt(r,Ot(i,t));n||=o!==c||a!==i,r[a]=o}return n?r:e},It=(e,t)=>{const s=de(e);if(s.length===0)return!1;const n=fe(s);return n!==void 0&&t.texts.some(r=>n.includes(r))||le(s).some(r=>_(r,t.texts)!==r)},k=(e,t,s,n=new Set)=>{if(typeof e=="string")return _(e,t.texts);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return It(e,t)?l:e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"){const i=String(e);return i.length>=ae&&t.texts.includes(i)?l:e}if(e instanceof Error){const i=String(e),c=_(i,t.texts);return c===i?e:c}if(typeof e!="object"||e===null)return e;if(s>=lt||n.has(e))return l;n.add(e);const r=Rt(e,t,i=>k(i,t,s+1,n));return n.delete(e),r},wt=(e,t=[])=>{let s={names:new Set(t),texts:[...new Set(e)]},n=!1,r=0;const i=()=>{n&&r===0&&(s=Tt)},c=o=>s.texts.length===0?o:_(o,s.texts);return{add(o,a=[]){!n&&(o.length>0||a.length>0)&&(s={names:new Set([...s.names,...a]),texts:[...new Set([...s.texts,...o])]})},clear(){n=!0,i()},hold(){r+=1;let o=!1;return()=>{o||(o=!0,r-=1,i())}},fields:o=>o===void 0||!J(s)?o:k(o,s,0),name:o=>s.names.has(o)?l:c(o),text:c,value:o=>J(s)?k(o,s,0):o}},Bt={...wt([]),add:()=>{}},W=new WeakSet,$=e=>{if(!W.has(e)){m(e,`CREATE TABLE IF NOT EXISTS "${S}" (
4
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
5
- ts REAL NOT NULL,
6
- function_path TEXT NOT NULL,
7
- shard_key TEXT,
8
- user_id TEXT,
9
- identity TEXT,
10
- args TEXT,
11
- outcome TEXT NOT NULL,
12
- error_message TEXT,
13
- error_fingerprint TEXT,
14
- trace_id TEXT,
15
- deployment_id TEXT,
16
- version_tag TEXT,
17
- duration_ms REAL NOT NULL,
18
- tables_read TEXT NOT NULL DEFAULT '[]',
19
- tables_written TEXT NOT NULL DEFAULT '[]',
20
- cache_hit INTEGER,
21
- subscriptions_rerun INTEGER NOT NULL DEFAULT 0
22
- )`);for(const t of ft)try{m(e,`ALTER TABLE "${S}" ADD COLUMN ${t}`)}catch{}W.add(e)}},X=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Lt=e=>e===void 0?null:e?1:0,kt=256,z=1024,I=new Map,ue=e=>{if(!ct(e,z))return;const t=JSON.stringify(e);if(t.length>z)return;const s=I.get(t);if(s!==void 0)return s;const n=JSON.stringify(h(e)),r={json:n,value:JSON.parse(n)};return ot(I,kt),I.set(t,r),r},B=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?JSON.stringify(h(e,t)):s.json},K=(e,t)=>{const s=t?void 0:ue(e);return s===void 0?h(e,t):s.value},Kt=(e,t,s={})=>{$(e);const n=s.captureRaw??!1,r=s.retention??M,i=t.outcome==="error"&&t.errorMessage!==void 0?q({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;m(e,`INSERT INTO "${S}"
23
- (ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
24
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:B(t.identity,n),t.redactedArgs===void 0?null:B(t.redactedArgs,n),t.outcome,t.errorMessage===void 0?null:h(t.errorMessage,n),i??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,X(t.tablesRead),X(t.tablesWritten),Lt(t.cacheHit),t.subscriptionsReRun??0),Ae(e,Math.floor(t.ts/at),"request-log",()=>{m(e,`DELETE FROM "${S}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${S}")`,r)})},Zt=(e,t={})=>{const s=t.captureRaw??!1,n={args:e.redactedArgs===void 0?void 0:K(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:h(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:K(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:ie,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},r=JSON.stringify(n);e.outcome==="error"?console.error(r):console.log(r)},Mt="log",xt=e=>e.map(t=>N(t)).join(" "),jt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},qt=(e,t)=>e.length===2&&typeof e[0]=="string"&&jt(e[1])?{fields:U(e[1],t,"full",O),message:e[0]}:{fields:U(void 0,t,"full",O),message:xt(e)},Yt=(e,t={})=>{const s=t.captureRaw??!1,n={fields:e.fields===void 0?void 0:h(e.fields,s),function:e.functionPath,level:e.level,message:h(e.message,s),rayId:e.rayId,shard:e.shardKey,source:ie,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Mt,userId:e.userId};let r;try{r=JSON.stringify(n)}catch{r=JSON.stringify({...n,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(r):e.level==="warn"?console.warn(r):console.log(r)},$t=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,pe=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push($t("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},Z=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},Dt=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pt=e=>{try{return JSON.parse(e)}catch{return}},vt=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["seq > ?"],r=[t.sinceSeq??0];if(pe(n,r,t),t.outcome!==void 0&&(n.push("outcome = ?"),r.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);n.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),r.push(o,o)}r.push(s);const i=t.sinceSeq===void 0?"DESC":"ASC";return m(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
25
- FROM "${S}" WHERE ${n.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,...r).toArray().map(o=>{const a={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:Z(o.tables_read),tablesWritten:Z(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(a.shardKey=o.shard_key),o.user_id!==null&&(a.userId=o.user_id),o.identity!==null){const d=Dt(o.identity);d!==void 0&&(a.identity=d)}if(o.args!==null){const d=Pt(o.args);d!==void 0&&(a.redactedArgs=d)}return o.error_message!==null&&(a.errorMessage=o.error_message),o.cache_hit!==null&&(a.cacheHit=o.cache_hit===1),o.trace_id!==null&&(a.traceId=o.trace_id),o.deployment_id!==null&&(a.deploymentId=o.deployment_id),o.version_tag!==null&&(a.versionTag=o.version_tag),a})},Ct=(e,t)=>{const s=me(e,[...t.keys()]);for(const n of t.values()){const r=s.get(n.hash);r!==void 0&&(n.stateUpdatedAt=r.updatedAt,r.assignee!==void 0&&(n.assignee=r.assignee),r.severity!==void 0&&(n.severity=r.severity),n.status=r.status==="resolved"&&n.lastSeen>r.updatedAt?"open":r.status)}},Qt=(e,t={})=>{$(e);const s=Math.max(1,Math.min(t.limit??M,1e4)),n=["outcome = 'error'"],r=[];pe(n,r,t),r.push(s);const i=m(e,`SELECT function_path, error_message, error_fingerprint, ts
26
- FROM "${S}" WHERE ${n.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...r).toArray(),c=new Map,o=new Map;for(const f of i){const u=f.error_message??"",{culprit:ge,hash:Se,title:D}=q({functionPath:f.function_path,message:u}),E=f.error_fingerprint??Se,p=c.get(E);if(p===void 0){c.set(E,{count:1,culprit:ge,firstSeen:f.ts,hash:E,lastSeen:f.ts,sampleMessage:u,status:"open",title:D}),o.set(E,f.ts);continue}p.count+=1,p.firstSeen=Math.min(p.firstSeen,f.ts),p.lastSeen=Math.max(p.lastSeen,f.ts),f.ts>(o.get(E)??Number.NEGATIVE_INFINITY)&&(o.set(E,f.ts),p.sampleMessage=u,p.title=D)}Ct(e,c);const a=[...c.values()];return(t.status===void 0?a:a.filter(f=>f.status===t.status)).toSorted((f,u)=>u.lastSeen-f.lastSeen)};export{Bt as N,S as R,l as S,Kt as a,Zt as b,wt as c,$ as d,Yt as e,vt as f,h as g,Jt as h,Xt as i,M as j,xt as k,Wt as m,U as n,qt as p,Qt as r,zt as s};