@utk09/ui-observability 0.9.0 → 0.9.2
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/CHANGELOG.md +63 -0
- package/README.md +83 -52
- package/dist/batch-4xKzzSCj.js +31 -0
- package/dist/batch-4xKzzSCj.js.map +1 -0
- package/dist/batch-cys7e53Q.cjs +2 -0
- package/dist/batch-cys7e53Q.cjs.map +1 -0
- package/dist/{bus-CtJWf9QN.cjs → bus-B6vzPmQM.cjs} +2 -2
- package/dist/{bus-CtJWf9QN.cjs.map → bus-B6vzPmQM.cjs.map} +1 -1
- package/dist/{bus-D8kH58tb.js → bus-DrixwdiX.js} +10 -10
- package/dist/{bus-D8kH58tb.js.map → bus-DrixwdiX.js.map} +1 -1
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-DjLbryED.js → console-B3vGRW5p.js} +3 -3
- package/dist/{console-DjLbryED.js.map → console-B3vGRW5p.js.map} +1 -1
- package/dist/{console-BpHfWstv.cjs → console-ChfuJlf9.cjs} +2 -2
- package/dist/{console-BpHfWstv.cjs.map → console-ChfuJlf9.cjs.map} +1 -1
- package/dist/constants-Be83LICb.cjs +2 -0
- package/dist/constants-Be83LICb.cjs.map +1 -0
- package/dist/constants-CQ_D7jIW.js +144 -0
- package/dist/constants-CQ_D7jIW.js.map +1 -0
- package/dist/constants.d.ts +44 -11
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/drops.d.ts +29 -0
- package/dist/core/hold-buffer.d.ts +27 -0
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +7 -19
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +61 -8
- package/dist/core/sampling.d.ts +2 -0
- package/dist/core/sender.d.ts +6 -1
- package/dist/deadline-5_PecIl5.js +26 -0
- package/dist/deadline-5_PecIl5.js.map +1 -0
- package/dist/deadline-XSnm95pg.cjs +2 -0
- package/dist/deadline-XSnm95pg.cjs.map +1 -0
- package/dist/{errors-DH4QJS0u.js → errors-BGs5NOrw.js} +4 -4
- package/dist/{errors-DH4QJS0u.js.map → errors-BGs5NOrw.js.map} +1 -1
- package/dist/{errors-CpGRhhIf.cjs → errors-BMJm7KZZ.cjs} +2 -2
- package/dist/{errors-CpGRhhIf.cjs.map → errors-BMJm7KZZ.cjs.map} +1 -1
- package/dist/identity-DXyV86o-.cjs +2 -0
- package/dist/identity-DXyV86o-.cjs.map +1 -0
- package/dist/{deadline-B5DINjD5.js → identity-rpEyjvVg.js} +3 -26
- package/dist/identity-rpEyjvVg.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.js +683 -369
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-BXaPVPyG.cjs +2 -0
- package/dist/indexeddb-storage-BXaPVPyG.cjs.map +1 -0
- package/dist/{indexeddb-storage-n1qkFBGA.js → indexeddb-storage-Q9fDYlyn.js} +76 -47
- package/dist/indexeddb-storage-Q9fDYlyn.js.map +1 -0
- package/dist/{interactions-OU94MPXs.js → interactions-B8zjCjga.js} +2 -2
- package/dist/{interactions-OU94MPXs.js.map → interactions-B8zjCjga.js.map} +1 -1
- package/dist/{interactions-31eHGwEQ.cjs → interactions-BAGRmtrv.cjs} +2 -2
- package/dist/{interactions-31eHGwEQ.cjs.map → interactions-BAGRmtrv.cjs.map} +1 -1
- package/dist/journey-BGSyy8Es.cjs +2 -0
- package/dist/journey-BGSyy8Es.cjs.map +1 -0
- package/dist/{journey-CeJ1QoT2.js → journey-_dQQ1eMP.js} +27 -26
- package/dist/{journey-CeJ1QoT2.js.map → journey-_dQQ1eMP.js.map} +1 -1
- package/dist/library-request-BIG3Xpx3.cjs +2 -0
- package/dist/library-request-BIG3Xpx3.cjs.map +1 -0
- package/dist/library-request-DX6ev9oG.js +25 -0
- package/dist/library-request-DX6ev9oG.js.map +1 -0
- package/dist/{long-frames-C_7OutLs.js → long-frames-B0tKuChx.js} +3 -3
- package/dist/{long-frames-C_7OutLs.js.map → long-frames-B0tKuChx.js.map} +1 -1
- package/dist/{long-frames-B8VdA_ny.cjs → long-frames-Cq2LgNnp.cjs} +2 -2
- package/dist/{long-frames-B8VdA_ny.cjs.map → long-frames-Cq2LgNnp.cjs.map} +1 -1
- package/dist/models/batch.d.ts +14 -0
- package/dist/models/config.d.ts +169 -0
- package/dist/models/drop.d.ts +39 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/models/storage.d.ts +15 -3
- package/dist/network-C6kJbW6K.cjs +2 -0
- package/dist/network-C6kJbW6K.cjs.map +1 -0
- package/dist/network-CMnEvGJB.js +211 -0
- package/dist/network-CMnEvGJB.js.map +1 -0
- package/dist/{platform-D4wu1eIF.cjs → platform-DNOJjpOm.cjs} +2 -2
- package/dist/{platform-D4wu1eIF.cjs.map → platform-DNOJjpOm.cjs.map} +1 -1
- package/dist/{platform-IHBZGqUe.js → platform-j0uMPwHi.js} +3 -3
- package/dist/{platform-IHBZGqUe.js.map → platform-j0uMPwHi.js.map} +1 -1
- package/dist/{remote-rules-kuDf5gbe.cjs → remote-rules-DgoBJxZL.cjs} +2 -2
- package/dist/{remote-rules-kuDf5gbe.cjs.map → remote-rules-DgoBJxZL.cjs.map} +1 -1
- package/dist/{remote-rules-Bt1XsdEQ.js → remote-rules-UggoZqfP.js} +11 -11
- package/dist/{remote-rules-Bt1XsdEQ.js.map → remote-rules-UggoZqfP.js.map} +1 -1
- package/dist/{sampling-o0VY1mqQ.js → sampling-BLMD8EGM.js} +28 -27
- package/dist/sampling-BLMD8EGM.js.map +1 -0
- package/dist/sampling-MthcVXXU.cjs +2 -0
- package/dist/sampling-MthcVXXU.cjs.map +1 -0
- package/dist/{sanitize-B9UheVKc.js → sanitize-BNwgPj_B.js} +2 -2
- package/dist/{sanitize-B9UheVKc.js.map → sanitize-BNwgPj_B.js.map} +1 -1
- package/dist/{sanitize-DSIP7amZ.cjs → sanitize-BqzPc4Jg.cjs} +2 -2
- package/dist/{sanitize-DSIP7amZ.cjs.map → sanitize-BqzPc4Jg.cjs.map} +1 -1
- package/dist/sender--0_VzPbN.js +1249 -0
- package/dist/sender--0_VzPbN.js.map +1 -0
- package/dist/sender-SPGMqZjD.cjs +3 -0
- package/dist/sender-SPGMqZjD.cjs.map +1 -0
- package/dist/storage/emergency-queue.d.ts +4 -1
- package/dist/storage/eviction.d.ts +40 -0
- package/dist/storage/idb-driver.d.ts +6 -0
- package/dist/storage/indexeddb-storage.d.ts +13 -5
- package/dist/storage/local-storage.d.ts +24 -1
- package/dist/storage/memory-storage.d.ts +7 -0
- package/dist/{storm-Y-yuBhvv.cjs → storm-CTy1dfvs.cjs} +2 -2
- package/dist/{storm-Y-yuBhvv.cjs.map → storm-CTy1dfvs.cjs.map} +1 -1
- package/dist/{storm-BTw0J6eE.js → storm-knaj4GUH.js} +2 -2
- package/dist/{storm-BTw0J6eE.js.map → storm-knaj4GUH.js.map} +1 -1
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +19 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +9 -3
- package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +30 -0
- package/dist/transport/serializers/select.d.ts +20 -4
- package/dist/transport/status-transport.d.ts +23 -12
- package/dist/utils/console.d.ts +4 -1
- package/dist/utils/library-request.d.ts +12 -0
- package/package.json +1 -1
- package/dist/constants-Br3b89Wg.cjs +0 -2
- package/dist/constants-Br3b89Wg.cjs.map +0 -1
- package/dist/constants-DM94FjVX.js +0 -96
- package/dist/constants-DM94FjVX.js.map +0 -1
- package/dist/deadline-B5DINjD5.js.map +0 -1
- package/dist/deadline-Cbg2cbUw.cjs +0 -2
- package/dist/deadline-Cbg2cbUw.cjs.map +0 -1
- package/dist/indexeddb-storage-DNdf1fmL.cjs +0 -2
- package/dist/indexeddb-storage-DNdf1fmL.cjs.map +0 -1
- package/dist/indexeddb-storage-n1qkFBGA.js.map +0 -1
- package/dist/journey-CE2EcwHW.cjs +0 -2
- package/dist/journey-CE2EcwHW.cjs.map +0 -1
- package/dist/library-request-C9uJFlbq.cjs +0 -2
- package/dist/library-request-C9uJFlbq.cjs.map +0 -1
- package/dist/library-request-DvhuplAB.js +0 -14
- package/dist/library-request-DvhuplAB.js.map +0 -1
- package/dist/network-BAV7ipyn.cjs +0 -2
- package/dist/network-BAV7ipyn.cjs.map +0 -1
- package/dist/network-D_lloS5t.js +0 -174
- package/dist/network-D_lloS5t.js.map +0 -1
- package/dist/sampling-BI15ds9D.cjs +0 -2
- package/dist/sampling-BI15ds9D.cjs.map +0 -1
- package/dist/sampling-o0VY1mqQ.js.map +0 -1
- package/dist/sender-BnNj9bOX.js +0 -1050
- package/dist/sender-BnNj9bOX.js.map +0 -1
- package/dist/sender-D0OsyB1c.cjs +0 -3
- package/dist/sender-D0OsyB1c.cjs.map +0 -1
package/dist/network-D_lloS5t.js
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import { r as e } from "./platform-IHBZGqUe.js";
|
|
2
|
-
import { t } from "./patch-CCWfuEY7.js";
|
|
3
|
-
import { t as n } from "./library-request-DvhuplAB.js";
|
|
4
|
-
//#region src/capture/types.ts
|
|
5
|
-
function r(e, t) {
|
|
6
|
-
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
7
|
-
}
|
|
8
|
-
//#endregion
|
|
9
|
-
//#region src/capture/network.ts
|
|
10
|
-
function i() {
|
|
11
|
-
return XMLHttpRequest.prototype;
|
|
12
|
-
}
|
|
13
|
-
function a(e) {
|
|
14
|
-
if (typeof e == "string") return e;
|
|
15
|
-
if (e instanceof URL) return e.href;
|
|
16
|
-
if (typeof e == "object" && e) {
|
|
17
|
-
let { url: t } = e;
|
|
18
|
-
if (typeof t == "string") return t;
|
|
19
|
-
}
|
|
20
|
-
return String(e);
|
|
21
|
-
}
|
|
22
|
-
function o(e, t) {
|
|
23
|
-
let n = t?.method;
|
|
24
|
-
return n === void 0 && typeof e == "object" && e && (n = e.method), c(n ?? "GET");
|
|
25
|
-
}
|
|
26
|
-
function s(e) {
|
|
27
|
-
return typeof e == "object" && !(e instanceof URL) && !(e instanceof Request);
|
|
28
|
-
}
|
|
29
|
-
function c(e) {
|
|
30
|
-
return typeof e == "string" ? e.toUpperCase() : String(e);
|
|
31
|
-
}
|
|
32
|
-
var l = class {
|
|
33
|
-
ctx;
|
|
34
|
-
name = "network";
|
|
35
|
-
installed = !1;
|
|
36
|
-
restores = [];
|
|
37
|
-
constructor(e) {
|
|
38
|
-
this.ctx = e;
|
|
39
|
-
}
|
|
40
|
-
install() {
|
|
41
|
-
this.installed || (this.installed = !0, this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr());
|
|
42
|
-
}
|
|
43
|
-
uninstall() {
|
|
44
|
-
if (this.installed) {
|
|
45
|
-
this.installed = !1;
|
|
46
|
-
for (let e of this.restores.splice(0)) e();
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
ignored(e) {
|
|
50
|
-
return n() || r(e, this.ctx.config.capture.ignoreUrls);
|
|
51
|
-
}
|
|
52
|
-
propagates(e) {
|
|
53
|
-
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
54
|
-
if (t.length === 0) return !1;
|
|
55
|
-
let n = this.ctx.diagnostics.guard("capture.header_failed", "The library could not read the origin of a request URL. Only a RegExp target can match it.", () => new URL(e, location.href).origin);
|
|
56
|
-
return t.some((t) => typeof t == "string" ? t === n : t.test(e));
|
|
57
|
-
}
|
|
58
|
-
installFetch() {
|
|
59
|
-
if (typeof globalThis.fetch != "function") return;
|
|
60
|
-
let e = !0, n = (e, t) => this.prepareFetch(e, t), r = (e, t, n, r, i) => {
|
|
61
|
-
this.record(e, t, n, r, i);
|
|
62
|
-
}, i = t(globalThis, "fetch", (t) => {
|
|
63
|
-
let i = t.bind(globalThis);
|
|
64
|
-
return async function(t, a) {
|
|
65
|
-
let o = e ? n(t, a) : void 0;
|
|
66
|
-
if (!o) return i(t, a);
|
|
67
|
-
let s = performance.now();
|
|
68
|
-
try {
|
|
69
|
-
let e = await i(o.input, o.init);
|
|
70
|
-
return r(o.method, o.url, e.status, performance.now() - s, void 0), e;
|
|
71
|
-
} catch (e) {
|
|
72
|
-
throw r(o.method, o.url, 0, performance.now() - s, e), e;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
});
|
|
76
|
-
this.restores.push(() => {
|
|
77
|
-
e = !1, i();
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
prepareFetch(e, t) {
|
|
81
|
-
let n = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read a fetch request. It sends the request unchanged.", () => {
|
|
82
|
-
let n = a(e);
|
|
83
|
-
if (!this.ignored(n)) return {
|
|
84
|
-
method: o(e, t),
|
|
85
|
-
url: n,
|
|
86
|
-
propagate: this.propagates(n)
|
|
87
|
-
};
|
|
88
|
-
});
|
|
89
|
-
if (!n) return;
|
|
90
|
-
let { method: r, url: i } = n, c = {
|
|
91
|
-
method: r,
|
|
92
|
-
url: i,
|
|
93
|
-
input: e,
|
|
94
|
-
init: t
|
|
95
|
-
};
|
|
96
|
-
if (!n.propagate || s(e)) return c;
|
|
97
|
-
try {
|
|
98
|
-
let n = Object.entries(this.ctx.tracing.headers());
|
|
99
|
-
if (e instanceof Request) {
|
|
100
|
-
let t = new Headers(e.headers);
|
|
101
|
-
for (let [e, r] of n) t.set(e, r);
|
|
102
|
-
c.input = new Request(e, { headers: t });
|
|
103
|
-
} else {
|
|
104
|
-
let e = new Headers(t?.headers);
|
|
105
|
-
for (let [t, r] of n) e.set(t, r);
|
|
106
|
-
c.init = {
|
|
107
|
-
...t,
|
|
108
|
-
headers: e
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
} catch (n) {
|
|
112
|
-
c.input = e, c.init = t, this.ctx.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: i }, n);
|
|
113
|
-
}
|
|
114
|
-
return c;
|
|
115
|
-
}
|
|
116
|
-
installXhr() {
|
|
117
|
-
if (typeof XMLHttpRequest > "u") return;
|
|
118
|
-
let e = !0, n = this.ctx, r = (e) => this.ignored(e), o = (e) => this.propagates(e), s = (e, t, n, r) => {
|
|
119
|
-
this.record(e, t, n, r, void 0);
|
|
120
|
-
}, l = i(), d = t(l, "open", (t) => function(r, i, ...o) {
|
|
121
|
-
e && n.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
122
|
-
this.__uiobs = {
|
|
123
|
-
method: c(r),
|
|
124
|
-
url: a(i),
|
|
125
|
-
startedAt: 0
|
|
126
|
-
};
|
|
127
|
-
}), t.apply(this, [
|
|
128
|
-
r,
|
|
129
|
-
i,
|
|
130
|
-
...o
|
|
131
|
-
]);
|
|
132
|
-
}), f = t(l, "send", (t) => function(...i) {
|
|
133
|
-
let a = e ? this.__uiobs : void 0;
|
|
134
|
-
a && n.diagnostics.guard("capture.record_failed", `The library could not record ${a.method} ${a.url}.`, () => {
|
|
135
|
-
r(a.url) || (a.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
136
|
-
s(a.method, a.url, this.status, performance.now() - a.startedAt);
|
|
137
|
-
}), o(a.url) && u(this, a.url, n));
|
|
138
|
-
}), t.apply(this, i);
|
|
139
|
-
});
|
|
140
|
-
this.restores.push(() => {
|
|
141
|
-
e = !1, d(), f();
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
record(t, n, r, i, a) {
|
|
145
|
-
let o = this.ctx.config.capture.fullUrls ? n : e(n);
|
|
146
|
-
this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${t} ${o}.`, () => {
|
|
147
|
-
let e = Math.round(i);
|
|
148
|
-
this.ctx.breadcrumbs.push({
|
|
149
|
-
t: Date.now(),
|
|
150
|
-
category: "http",
|
|
151
|
-
message: `${t} ${o} ${r === 0 ? "failed" : String(r)}`,
|
|
152
|
-
data: { durationMs: e }
|
|
153
|
-
});
|
|
154
|
-
let n = {
|
|
155
|
-
"http.request.method": t,
|
|
156
|
-
"url.full": o,
|
|
157
|
-
"http.response.status_code": r,
|
|
158
|
-
"http.duration_ms": e
|
|
159
|
-
};
|
|
160
|
-
r === 0 ? this.ctx.logger.error(`${t} ${o} failed`, a, n) : r >= 400 ? this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`, n) : this.ctx.logger.debug(`${t} ${o}`, n);
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
function u(e, t, n) {
|
|
165
|
-
try {
|
|
166
|
-
for (let [t, r] of Object.entries(n.tracing.headers())) e.setRequestHeader(t, r);
|
|
167
|
-
} catch (e) {
|
|
168
|
-
n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
//#endregion
|
|
172
|
-
export { l as NetworkCapture };
|
|
173
|
-
|
|
174
|
-
//# sourceMappingURL=network-D_lloS5t.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"network-D_lloS5t.js","names":["stripUrlQuery","isLibraryRequest","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","patch","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;AAgH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8C,IAAU,KAAK,MAAMxB,CAAU;GAErC,KAAK,IAAI,YAAY,KAAK;IACxB,GAAG,KAAK,IAAI;IACZ,UAAU;IACV,SAAS,GAAGX,EAAO,GAAGX,EAAI,GAAGqB,MAAW,IAAI,WAAW,OAAOA,CAAM;IACpE,MAAM,EAAE,YAAYyB,EAAQ;GAC9B,CAAC;GAED,IAAMC,IAAa;IACjB,uBAAuBpC;IACvB,YAAYX;IACZ,6BAA6BqB;IAC7B,oBAAoByB;GACtB;GAEA,AAAIzB,MAAW,IACb,KAAK,IAAI,OAAO,MAAM,GAAGV,EAAO,GAAGX,EAAI,UAAUuB,GAAOwB,CAAU,IAGhE1B,KAAU,MACZ,KAAK,IAAI,OAAO,KAAK,GAAGV,EAAO,GAAGX,EAAI,YAAY,OAAOqB,CAAM,KAAK0B,CAAU,IAMhF,KAAK,IAAI,OAAO,MAAM,GAAGpC,EAAO,GAAGX,KAAO+C,CAAU;EACtD,CACF;CACF;AACF;AAQA,SAASH,EAAgB,GAAqB,GAAa,GAA2B;CACpF,IAAI;EACF,KAAK,IAAM,CAACX,GAAKC,MAAU,OAAO,QAAQrB,EAAI,QAAQ,QAAQ,CAAC,GAC7D,EAAI,iBAAiBoB,GAAKC,CAAK;CAEnC,SAASX,GAAO;EACd,EAAI,YAAY,OACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants-Br3b89Wg.cjs");function t(){return`${String(Date.now())}000000`}function n(t){return typeof t==`string`&&Object.hasOwn(e.ct,t)}function r(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function i(t){let n=e.W;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.G);return n>>>0}function a(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function o(e,t){let n;for(let[r,i]of Object.entries(t))(e===r||e.startsWith(`${r}.`))&&r.length>(n?.length??-1)&&(n={rate:i,length:r.length});return n}function s(e,t,n){let{rates:r,defaultRate:i,remoteMaxRate:a}=t.sampling,s=o(e,r),c=n?o(e,n.rates):void 0;return c&&c.length>=(s?.length??-1)?Math.min(c.rate,a):s?s.rate:n?.defaultRate===void 0?i:Math.min(n.defaultRate,a)}function c(t,n,r){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let a=s(t.namespace,n,r),o=e.ct[t.level]<e.ct[n.minLevel];return r&&o&&!e.st.includes(t.type)&&(a=Math.min(a,n.sampling.remoteMaxRate)),a>=1?!0:a<=0?!1:i(t.journeyId||t.traceId)/e.gn<a}function l(t,n,r=null){return c({level:t.severityText,type:a(t,e.d),namespace:a(t,e.n),journeyId:a(t,e.s),traceId:t.traceId},n,r)}var u=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
|
|
2
|
-
//# sourceMappingURL=sampling-BI15ds9D.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-BI15ds9D.cjs","names":["LEVEL_ORDER","FNV_OFFSET_BASIS","FNV_PRIME","LEVEL_ORDER","LEVEL_BYPASS_TYPES","UINT32_MAX","ATTR_LOG_TYPE","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","require_constants","nowUnixNano","isLogLevel","value","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","belowMinLevel","shouldSample","ErrorCeiling","now"],"sources":["../src/models/log-record.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n // minLevel does not apply to an action or a metric. Do not cap them.\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":"4CA0DA,SAAgBU,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOZ,EAAAA,GAAaY,CAAK,CACtE,CAUA,SAAgBC,EAAY,EAAoC,CAC9D,GAAI,OAAOD,GAAU,WAAYA,EAC/B,MAAO,GAIT,IAAME,EAASF,EACf,OACE,OAAOE,EAAO,MAAS,UACvB,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,cAAiB,UAC/B,OAAOA,EAAO,YAAe,UAC7BA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Y+B,EAAM,OAAqB/B,EAAAA,GAAYwB,EAAO,UAgBhF,OAfIG,GAAUK,GAAiB,CAAC/B,EAAAA,GAAmB,SAAS8B,EAAM,IAAe,IAC/E,EAAO,KAAK,IAAIX,EAAMI,EAAO,SAAS,aAAa,GAGjDJ,GAAA,EACK,GAELA,GAAA,EACK,GAOFR,EAFKmB,EAAM,WAAaA,EAAM,OAEtB,EAAI7B,EAAAA,GAAakB,CAClC,CAUA,SAAgBa,EACd,EACA,EACA,EAA6B,KACpB,CACT,OAAOH,EACL,CACE,MAAOnB,EAAO,aACd,KAAMI,EAASJ,EAAQR,EAAAA,CAAa,EACpC,UAAWY,EAASJ,EAAQP,EAAAA,CAAkB,EAC9C,UAAWW,EAASJ,EAAQN,EAAAA,CAAe,EAC3C,QAASM,EAAO,OAClB,EACAa,EACAG,CACF,CACF,CAQA,IAAaO,EAAb,KAA0B,CAExB,YAAsB,EAGtB,MAAgB,EAOhB,MAAM,EAA4B,CAChC,GAAIvB,EAAO,eAAiB,SAAWA,EAAO,eAAiB,QAC7D,MAAO,GAGT,IAAMwB,EAAM,KAAK,IAAI,EASrB,OAPIA,EAAM,KAAK,YAAA,MACb,KAAK,YAAcA,EACnB,KAAK,MAAQ,GAGf,KAAK,QAEE,KAAK,OAAA,GACd,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sampling-o0VY1mqQ.js","names":["FNV_PRIME","FNV_OFFSET_BASIS","LEVEL_ORDER","ATTR_LOG_TYPE","UINT32_MAX","ATTR_APP_NAMESPACE","ATTR_JOURNEY_ID","LEVEL_BYPASS_TYPES","nowUnixNano","isLogLevel","value","isLogRecord","record","hash","h","i","readAttr","key","longestPrefix","best","prefix","rate","rates","namespace","rateFor","config","local","fromRemote","remote","remoteMaxRate","defaultRate","shouldSampleInput","input","belowMinLevel","shouldSample","ErrorCeiling","now"],"sources":["../src/models/log-record.ts","../src/core/sampling.ts"],"sourcesContent":["// src/models/log-record.ts\n//\n// Shape of one log record, plus helpers for building and validating it.\n//\n// `src/constants.ts` contains the severity tables.\n\nimport { LEVEL_ORDER } from \"../constants\";\n\n/** OpenTelemetry severity levels, in ascending order. */\nexport type LogLevel = \"TRACE\" | \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"FATAL\";\n\n/**\n * Kind of thing that a record tells about. `action` is something that a person did.\n * `event` is something that the application did. `metric` is a measurement.\n * `log` is a log call of the application. `system` is the output of this library.\n */\nexport type LogType = \"action\" | \"event\" | \"metric\" | \"log\" | \"system\";\n\n/** Metric value type: level, running total, or distribution. */\nexport type MetricType = \"gauge\" | \"counter\" | \"histogram\";\n\n/** Internal record shape. A serializer converts it to the payload format. */\nexport interface LogRecord {\n /**\n * Event time, nanoseconds since epoch, as a decimal string.\n * @see {@link nowUnixNano}\n */\n timeUnixNano: string;\n /**\n * Time when this library received the event, if it differs from `timeUnixNano`.\n * For example, a forwarded record can have a different time.\n */\n observedTimeUnixNano?: string;\n /** Distributed trace id. */\n traceId: string;\n /** Span id within the trace. */\n spanId: string;\n /** OpenTelemetry trace flags. The library uses only the sampled bit. */\n traceFlags: number;\n /** OpenTelemetry severity number for `severityText`. */\n severityNumber: number;\n /** Log level. */\n severityText: LogLevel;\n /** Log message. */\n body: string;\n /** Structured attributes, sanitized and size-capped. */\n attributes: Record<string, unknown>;\n /** Resource attributes, shared by every record from one context. */\n resource: Record<string, unknown>;\n}\n\n/**\n * Returns the current time as a Unix nanosecond timestamp.\n * The function appends zeros and does not multiply. `Date.now() * 1e6` is larger\n * than `Number.MAX_SAFE_INTEGER` and corrupts digits without an error. The trailing\n * zeros show unknown precision. They are not measured digits.\n * @returns Epoch timestamp in nanoseconds, as a decimal string.\n */\nexport function nowUnixNano(): string {\n return `${String(Date.now())}000000`;\n}\n\n/**\n * Checks if a value is a known log level. An own-key check rejects \"toString\".\n * @param value The value to check.\n * @returns True if `value` is a key of the severity table.\n */\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === \"string\" && Object.hasOwn(LEVEL_ORDER, value);\n}\n\n/**\n * Checks if a value has the shape `LogRecord` requires.\n * Use it to validate records from another realm. A malformed record throws\n * during serialization. The check accepts any string as `severityText`, not only\n * a known level. Thus an unknown level from a newer version passes.\n * @param value The value to check.\n * @returns True if `value` has the shape `LogRecord` requires.\n */\nexport function isLogRecord(value: unknown): value is LogRecord {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n // Cast to `Record<string, unknown>`, not to `Partial<LogRecord>`. With `Partial<LogRecord>`,\n // the compiler treats these fields as never null. The checks below then look unnecessary.\n const record = value as Record<string, unknown>;\n return (\n typeof record.body === \"string\" &&\n typeof record.severityText === \"string\" &&\n typeof record.timeUnixNano === \"string\" &&\n typeof record.attributes === \"object\" &&\n record.attributes !== null &&\n typeof record.resource === \"object\" &&\n record.resource !== null\n );\n}\n","// src/core/sampling.ts\n//\n// This module samples records by namespace rule, journey ID and trace ID.\n// The journey ID is the sampling key. The module keeps or drops a full journey.\n// The result is the same across windows and reloads.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_LOG_TYPE,\n ERROR_CEILING_MAX_PER_WINDOW,\n ERROR_STORM_WINDOW_MS,\n FNV_OFFSET_BASIS,\n FNV_PRIME,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n UINT32_MAX,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel, LogRecord, LogType } from \"../models/log-record\";\nimport type { RemoteRules } from \"./remote-sampling\";\n\n/**\n * Computes the 32-bit FNV-1a hash of a string. Do not use it as a security hash.\n * @param value Key string to hash.\n * @returns Unsigned 32-bit integer hash.\n */\nfunction hash(value: string): number {\n let h = FNV_OFFSET_BASIS;\n\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, FNV_PRIME);\n }\n\n return h >>> 0;\n}\n\n/**\n * Reads a string attribute from a log record. It returns an empty string for an absent\n * or non-string value. A forwarded record has passed only a shape check.\n * @param record Log record to test.\n * @param key Attribute key.\n * @returns String attribute value, or empty string if missing or non-string.\n */\nfunction readAttr(record: LogRecord, key: string): string {\n const value: unknown = record.attributes[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** Rate of the longest prefix that matches a namespace. */\ninterface PrefixMatch {\n /** Sampling rate of the prefix. */\n rate: number;\n /** Length of the prefix. */\n length: number;\n}\n\n/**\n * Finds the longest prefix in a rate map that matches a namespace.\n * For example, trading.ticks overrides trading.\n * @param namespace Target application namespace.\n * @param rates Rate for each namespace prefix.\n * @returns The match, or undefined if no prefix matches.\n */\nfunction longestPrefix(namespace: string, rates: Record<string, number>): PrefixMatch | undefined {\n let best: PrefixMatch | undefined;\n\n for (const [prefix, rate] of Object.entries(rates)) {\n const matches = namespace === prefix || namespace.startsWith(`${prefix}.`);\n\n if (matches && prefix.length > (best?.length ?? -1)) {\n best = { rate, length: prefix.length };\n }\n }\n\n return best;\n}\n\n/**\n * Finds the sampling rate for a namespace. The longest matching prefix wins.\n * A remote prefix wins over a config prefix of the same length.\n * @param namespace Target application namespace.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns Matched namespace sampling rate or default rate.\n */\nfunction rateFor(namespace: string, config: ResolvedConfig, remote: RemoteRules | null): number {\n const { rates, defaultRate, remoteMaxRate } = config.sampling;\n const local = longestPrefix(namespace, rates);\n const fromRemote = remote ? longestPrefix(namespace, remote.rates) : undefined;\n\n // Cap a remote rate when sampling reads it. A configure() that lowers the cap then applies\n // immediately.\n if (fromRemote && fromRemote.length >= (local?.length ?? -1)) {\n return Math.min(fromRemote.rate, remoteMaxRate);\n }\n\n if (local) {\n return local.rate;\n }\n\n return remote?.defaultRate === undefined\n ? defaultRate\n : Math.min(remote.defaultRate, remoteMaxRate);\n}\n\n/** Fields that sampling reads. The caller knows all of them before it builds a record. */\nexport interface SampleInput {\n /** Severity level of the entry. */\n level: string;\n /** Telemetry type classification. */\n type: string;\n /** Originating application namespace. */\n namespace: string;\n /** Active journey ID. It is empty when no journey runs. */\n journeyId: string;\n /** Trace ID. It is the sampling key when no journey runs. */\n traceId: string;\n}\n\n/**\n * Decides if sampling keeps an entry. It reads fields, not a record.\n * This lets the caller drop an entry before the attribute walk runs.\n * @param input Fields the sampling decision reads.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the entry.\n */\nexport function shouldSampleInput(\n input: SampleInput,\n config: ResolvedConfig,\n remote: RemoteRules | null,\n): boolean {\n // Errors and fatal records bypass sampling filters.\n if (input.level === \"ERROR\" || input.level === \"FATAL\") {\n return true;\n }\n\n if (config.sampling.alwaysSampleTypes.includes(input.type)) {\n return true;\n }\n\n let rate = rateFor(input.namespace, config, remote);\n\n // A remote minLevel adds the records below minLevel. Cap them too, or they ship at the config rate.\n // minLevel does not apply to an action or a metric. Do not cap them.\n const belowMinLevel = LEVEL_ORDER[input.level as LogLevel] < LEVEL_ORDER[config.minLevel];\n if (remote && belowMinLevel && !LEVEL_BYPASS_TYPES.includes(input.type as LogType)) {\n rate = Math.min(rate, config.sampling.remoteMaxRate);\n }\n\n if (rate >= SAMPLING_RATE_MAX) {\n return true;\n }\n if (rate <= SAMPLING_RATE_MIN) {\n return false;\n }\n\n // Use the trace ID when the journey ID is absent. The trace ID still groups one\n // operation.\n const key = input.journeyId || input.traceId;\n\n return hash(key) / UINT32_MAX < rate;\n}\n\n/**\n * Decides if sampling keeps a built log record. The runtime uses it for records\n * that a child context sends over the bus.\n * @param record Record to evaluate.\n * @param config Active configuration instance.\n * @param remote Remote rules in force, or null.\n * @returns True if the runtime keeps and sends the record.\n */\nexport function shouldSample(\n record: LogRecord,\n config: ResolvedConfig,\n remote: RemoteRules | null = null,\n): boolean {\n return shouldSampleInput(\n {\n level: record.severityText,\n type: readAttr(record, ATTR_LOG_TYPE),\n namespace: readAttr(record, ATTR_APP_NAMESPACE),\n journeyId: readAttr(record, ATTR_JOURNEY_ID),\n traceId: record.traceId,\n },\n config,\n remote,\n );\n}\n\n/**\n * Sets a fixed-window limit on the ERROR and FATAL records that bypass sampling.\n *\n * ErrorCapture already limits auto-captured errors. This class limits the remaining case.\n * An example is application code that calls logger.error in a render loop.\n */\nexport class ErrorCeiling {\n /** Start of the current window, in epoch milliseconds. */\n private windowStart = 0;\n\n /** ERROR and FATAL records admitted in the current window. */\n private count = 0;\n\n /**\n * Checks a record against the limit. It counts only ERROR and FATAL records.\n * @param record Record about to enter a stream.\n * @returns False when the window has no allowance left. The caller must drop the record.\n */\n allow(record: LogRecord): boolean {\n if (record.severityText !== \"ERROR\" && record.severityText !== \"FATAL\") {\n return true;\n }\n\n const now = Date.now();\n // Use a fixed window, not a sliding window. A quiet period adds no allowance.\n if (now - this.windowStart > ERROR_STORM_WINDOW_MS) {\n this.windowStart = now;\n this.count = 0;\n }\n\n this.count++;\n\n return this.count <= ERROR_CEILING_MAX_PER_WINDOW;\n }\n}\n"],"mappings":";;AA0DA,SAAgBQ,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAOA,SAAgBC,EAAW,GAAmC;CAC5D,OAAO,OAAOC,KAAU,YAAY,OAAO,OAAOR,GAAaQ,CAAK;AACtE;AAUA,SAAgBC,EAAY,GAAoC;CAC9D,IAAI,OAAOD,KAAU,aAAYA,GAC/B,OAAO;CAIT,IAAME,IAASF;CACf,OACE,OAAOE,EAAO,QAAS,YACvB,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,gBAAiB,YAC/B,OAAOA,EAAO,cAAe,YAC7BA,EAAO,eAAe,QACtB,OAAOA,EAAO,YAAa,YAC3BA,EAAO,aAAa;AAExB;;;AClEA,SAASC,EAAK,GAAuB;CACnC,IAAIC,IAAIb;CAER,KAAK,IAAIc,IAAI,GAAGA,IAAIL,EAAM,QAAQ,KAEhC,AADA,KAAKA,EAAM,WAAWK,CAAC,GACvB,IAAI,KAAK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