@utk09/ui-observability 0.9.1 → 0.9.3
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 +33 -0
- package/README.md +75 -64
- package/dist/batch-D5qvsMQ_.cjs +2 -0
- package/dist/batch-D5qvsMQ_.cjs.map +1 -0
- package/dist/{batch-DEK4bv9N.js → batch-DDgxg16_.js} +7 -4
- package/dist/batch-DDgxg16_.js.map +1 -0
- package/dist/bus/bus.d.ts +0 -4
- package/dist/{bus-HVQ8E72V.js → bus-C6RwKzPW.js} +63 -66
- package/dist/bus-C6RwKzPW.js.map +1 -0
- package/dist/bus-WPVDFw2y.cjs +2 -0
- package/dist/bus-WPVDFw2y.cjs.map +1 -0
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/storm.d.ts +2 -7
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-DssDxq1B.cjs → console-BSusX_M-.cjs} +2 -2
- package/dist/{console-DssDxq1B.cjs.map → console-BSusX_M-.cjs.map} +1 -1
- package/dist/{console-C9Y639mn.js → console-Dv5GfaNn.js} +3 -3
- package/dist/{console-C9Y639mn.js.map → console-Dv5GfaNn.js.map} +1 -1
- package/dist/constants-Cb92egPS.cjs +2 -0
- package/dist/constants-Cb92egPS.cjs.map +1 -0
- package/dist/{constants-N99w84xy.js → constants-DhH6VI5a.js} +39 -12
- package/dist/constants-DhH6VI5a.js.map +1 -0
- package/dist/constants.d.ts +28 -3
- package/dist/core/breadcrumbs.d.ts +1 -3
- package/dist/core/context.d.ts +0 -8
- package/dist/core/diagnostics.d.ts +1 -3
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +5 -12
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +17 -0
- package/dist/core/sampling.d.ts +3 -3
- package/dist/core/sender.d.ts +2 -0
- package/dist/deadline-CUrH0Hd8.cjs +2 -0
- package/dist/deadline-CUrH0Hd8.cjs.map +1 -0
- package/dist/deadline-DeqXEliN.js +31 -0
- package/dist/deadline-DeqXEliN.js.map +1 -0
- package/dist/{errors-CQusIGWJ.js → errors-DCZWcHkd.js} +4 -4
- package/dist/{errors-CQusIGWJ.js.map → errors-DCZWcHkd.js.map} +1 -1
- package/dist/{errors-BTWuVnHZ.cjs → errors-ERu-su8m.cjs} +3 -3
- package/dist/{errors-BTWuVnHZ.cjs.map → errors-ERu-su8m.cjs.map} +1 -1
- package/dist/fixed-window-BR0bu32Y.cjs +2 -0
- package/dist/fixed-window-BR0bu32Y.cjs.map +1 -0
- package/dist/fixed-window-Re7jIRJH.js +9 -0
- package/dist/fixed-window-Re7jIRJH.js.map +1 -0
- package/dist/{identity-B1GDS1Tb.cjs → identity-C1WLItSl.cjs} +2 -2
- package/dist/{identity-B1GDS1Tb.cjs.map → identity-C1WLItSl.cjs.map} +1 -1
- package/dist/{identity-D4DPjTM9.js → identity-Di-QXGCC.js} +2 -2
- package/dist/{identity-D4DPjTM9.js.map → identity-Di-QXGCC.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/index.js +522 -369
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-DX18p39D.cjs +2 -0
- package/dist/indexeddb-storage-DX18p39D.cjs.map +1 -0
- package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-T9YIYVYC.js} +48 -59
- package/dist/indexeddb-storage-T9YIYVYC.js.map +1 -0
- package/dist/{interactions-CnjfQgw3.js → interactions-BLH_tX87.js} +2 -2
- package/dist/{interactions-CnjfQgw3.js.map → interactions-BLH_tX87.js.map} +1 -1
- package/dist/{interactions-CcxrVzpg.cjs → interactions-_hfOerfC.cjs} +2 -2
- package/dist/{interactions-CcxrVzpg.cjs.map → interactions-_hfOerfC.cjs.map} +1 -1
- package/dist/journey-BRUj0hqD.cjs +2 -0
- package/dist/journey-BRUj0hqD.cjs.map +1 -0
- package/dist/{journey-DjvDzHyp.js → journey-yALMEWF7.js} +39 -38
- package/dist/journey-yALMEWF7.js.map +1 -0
- package/dist/library-request-BcAxuwsf.cjs +2 -0
- package/dist/library-request-BcAxuwsf.cjs.map +1 -0
- package/dist/library-request-CQD4HUiP.js +25 -0
- package/dist/library-request-CQD4HUiP.js.map +1 -0
- package/dist/{long-frames-BGik_Yhy.cjs → long-frames-D4Bm3Zkz.cjs} +2 -2
- package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-D4Bm3Zkz.cjs.map} +1 -1
- package/dist/{long-frames-CZk3XOkH.js → long-frames-DD_Um9_4.js} +3 -3
- package/dist/{long-frames-CZk3XOkH.js.map → long-frames-DD_Um9_4.js.map} +1 -1
- package/dist/models/batch.d.ts +6 -0
- package/dist/models/config.d.ts +23 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/network--GoE7_Or.js +211 -0
- package/dist/network--GoE7_Or.js.map +1 -0
- package/dist/network-DcuS2H1P.cjs +2 -0
- package/dist/network-DcuS2H1P.cjs.map +1 -0
- package/dist/openfin-BwEN0uj4.js +8 -0
- package/dist/openfin-BwEN0uj4.js.map +1 -0
- package/dist/openfin-DtH2f7zX.cjs +2 -0
- package/dist/openfin-DtH2f7zX.cjs.map +1 -0
- package/dist/platform-GaM6h7XM.js +52 -0
- package/dist/platform-GaM6h7XM.js.map +1 -0
- package/dist/platform-kIL5AZB7.cjs +2 -0
- package/dist/platform-kIL5AZB7.cjs.map +1 -0
- package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-6ePq8CrI.js} +23 -25
- package/dist/remote-rules-6ePq8CrI.js.map +1 -0
- package/dist/remote-rules-CI3gbRCL.cjs +2 -0
- package/dist/remote-rules-CI3gbRCL.cjs.map +1 -0
- package/dist/sampling-C-M8p3FK.cjs +2 -0
- package/dist/sampling-C-M8p3FK.cjs.map +1 -0
- package/dist/sampling-Ud_WiuU9.js +65 -0
- package/dist/sampling-Ud_WiuU9.js.map +1 -0
- package/dist/{sanitize-DKp5MRsa.cjs → sanitize--_e4oOPX.cjs} +2 -2
- package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize--_e4oOPX.cjs.map} +1 -1
- package/dist/{sanitize-Dwj9JCkI.js → sanitize-DP0xDPrt.js} +2 -2
- package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-DP0xDPrt.js.map} +1 -1
- package/dist/sender-BESHz6my.cjs +3 -0
- package/dist/sender-BESHz6my.cjs.map +1 -0
- package/dist/{sender-BBY0IcUo.js → sender-BUBWLn5i.js} +425 -290
- package/dist/sender-BUBWLn5i.js.map +1 -0
- package/dist/storage/gap.d.ts +20 -0
- package/dist/storage/indexeddb-storage.d.ts +1 -7
- package/dist/storage/keys.d.ts +9 -0
- package/dist/storage/local-storage.d.ts +0 -6
- package/dist/storage/memory-storage.d.ts +1 -1
- package/dist/storm-DhHGHhOc.cjs +2 -0
- package/dist/storm-DhHGHhOc.cjs.map +1 -0
- package/dist/storm-OD5J6Ylm.js +10 -0
- package/dist/storm-OD5J6Ylm.js.map +1 -0
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +13 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +3 -1
- 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 +19 -11
- package/dist/utils/fixed-window.d.ts +15 -0
- package/dist/utils/guards.d.ts +6 -0
- package/dist/utils/library-request.d.ts +12 -0
- package/dist/utils/openfin.d.ts +48 -0
- package/dist/utils/platform.d.ts +5 -0
- package/package.json +2 -3
- package/dist/batch-DEK4bv9N.js.map +0 -1
- package/dist/batch-DEVFs28i.cjs +0 -2
- package/dist/batch-DEVFs28i.cjs.map +0 -1
- package/dist/bus-DNFvTkif.cjs +0 -2
- package/dist/bus-DNFvTkif.cjs.map +0 -1
- package/dist/bus-HVQ8E72V.js.map +0 -1
- package/dist/constants-N99w84xy.js.map +0 -1
- package/dist/constants-X86IDwkC.cjs +0 -2
- package/dist/constants-X86IDwkC.cjs.map +0 -1
- package/dist/deadline-5_PecIl5.js +0 -26
- package/dist/deadline-5_PecIl5.js.map +0 -1
- package/dist/deadline-XSnm95pg.cjs +0 -2
- package/dist/deadline-XSnm95pg.cjs.map +0 -1
- package/dist/indexeddb-storage-B8SGUzSV.js.map +0 -1
- package/dist/indexeddb-storage-ukzC82dm.cjs +0 -2
- package/dist/indexeddb-storage-ukzC82dm.cjs.map +0 -1
- package/dist/journey-DjvDzHyp.js.map +0 -1
- package/dist/journey-DxlfdFJV.cjs +0 -2
- package/dist/journey-DxlfdFJV.cjs.map +0 -1
- package/dist/library-request-BZ1ekVtl.cjs +0 -2
- package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
- package/dist/library-request-C8kc5YWv.js +0 -14
- package/dist/library-request-C8kc5YWv.js.map +0 -1
- package/dist/network-51iicpLl.js +0 -174
- package/dist/network-51iicpLl.js.map +0 -1
- package/dist/network-jBbjyAJP.cjs +0 -2
- package/dist/network-jBbjyAJP.cjs.map +0 -1
- package/dist/platform-Cjts-8k8.js +0 -48
- package/dist/platform-Cjts-8k8.js.map +0 -1
- package/dist/platform-DW3GFIUE.cjs +0 -2
- package/dist/platform-DW3GFIUE.cjs.map +0 -1
- package/dist/remote-rules-ByS34k4e.cjs +0 -2
- package/dist/remote-rules-ByS34k4e.cjs.map +0 -1
- package/dist/remote-rules-M-XZ1xbe.js.map +0 -1
- package/dist/sampling-BN3Oi6SV.js +0 -63
- package/dist/sampling-BN3Oi6SV.js.map +0 -1
- package/dist/sampling-b2ck5X98.cjs +0 -2
- package/dist/sampling-b2ck5X98.cjs.map +0 -1
- package/dist/sender-BBY0IcUo.js.map +0 -1
- package/dist/sender-BXoAZKum.cjs +0 -3
- package/dist/sender-BXoAZKum.cjs.map +0 -1
- package/dist/storm-CKuaBp7i.cjs +0 -2
- package/dist/storm-CKuaBp7i.cjs.map +0 -1
- package/dist/storm-DhtL2eVr.js +0 -10
- package/dist/storm-DhtL2eVr.js.map +0 -1
|
@@ -1,52 +1,53 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { Tt as e, _ as t, b as n, ct as r, g as i, ot as a, st as o, v as s, wt as c, y as l } from "./constants-DhH6VI5a.js";
|
|
2
|
+
import { n as u, r as d } from "./deadline-DeqXEliN.js";
|
|
3
|
+
import { i as f, t as p } from "./identity-Di-QXGCC.js";
|
|
4
|
+
import { t as m } from "./openfin-BwEN0uj4.js";
|
|
4
5
|
//#region src/core/journey.ts
|
|
5
|
-
var
|
|
6
|
-
maxAgeMs:
|
|
6
|
+
var h = {
|
|
7
|
+
maxAgeMs: a,
|
|
7
8
|
endOnOwnerClose: !1,
|
|
8
|
-
urlParam:
|
|
9
|
+
urlParam: r
|
|
9
10
|
};
|
|
10
|
-
function
|
|
11
|
+
function g(e, t) {
|
|
11
12
|
let n = Reflect.get(e, t);
|
|
12
13
|
return typeof n == "string" && n !== "" ? n : void 0;
|
|
13
14
|
}
|
|
14
|
-
function
|
|
15
|
+
function _(e, t) {
|
|
15
16
|
let n = Reflect.get(e, t);
|
|
16
17
|
return typeof n == "number" && Number.isFinite(n) ? n : void 0;
|
|
17
18
|
}
|
|
18
|
-
function
|
|
19
|
+
function v(e) {
|
|
19
20
|
if (typeof e != "object" || !e) return null;
|
|
20
|
-
let t =
|
|
21
|
+
let t = g(e, "id"), n = g(e, "name"), r = _(e, "startedAt");
|
|
21
22
|
return t === void 0 || n === void 0 || r === void 0 ? null : {
|
|
22
23
|
id: t,
|
|
23
24
|
name: n,
|
|
24
25
|
startedAt: r,
|
|
25
|
-
parentId:
|
|
26
|
-
ownerContextId:
|
|
26
|
+
parentId: g(e, "parentId"),
|
|
27
|
+
ownerContextId: g(e, "ownerContextId") ?? ""
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
+
function y(e) {
|
|
30
31
|
if (typeof e != "object" || !e) return null;
|
|
31
|
-
let t =
|
|
32
|
+
let t = g(e, "i"), n = g(e, "n");
|
|
32
33
|
return t === void 0 || n === void 0 ? null : {
|
|
33
34
|
id: t,
|
|
34
35
|
name: n,
|
|
35
|
-
startedAt:
|
|
36
|
+
startedAt: _(e, "s") ?? Date.now(),
|
|
36
37
|
parentId: void 0,
|
|
37
38
|
ownerContextId: ""
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
|
-
function
|
|
41
|
-
let
|
|
42
|
-
i:
|
|
43
|
-
n:
|
|
44
|
-
s:
|
|
45
|
-
}), r = new TextEncoder().encode(
|
|
41
|
+
function b(e) {
|
|
42
|
+
let t = JSON.stringify({
|
|
43
|
+
i: e.id,
|
|
44
|
+
n: e.name.slice(0, 64),
|
|
45
|
+
s: e.startedAt
|
|
46
|
+
}), r = new TextEncoder().encode(t), i = "";
|
|
46
47
|
for (let e of r) i += String.fromCharCode(e);
|
|
47
|
-
return btoa(i).replace(
|
|
48
|
+
return btoa(i).replace(l, "-").replace(n, "_").replace(s, "");
|
|
48
49
|
}
|
|
49
|
-
var
|
|
50
|
+
var x = class {
|
|
50
51
|
options;
|
|
51
52
|
diagnostics;
|
|
52
53
|
contextId;
|
|
@@ -54,7 +55,7 @@ var b = class {
|
|
|
54
55
|
stores;
|
|
55
56
|
journey = null;
|
|
56
57
|
expiryTimer = null;
|
|
57
|
-
constructor(e, t, n, r, i =
|
|
58
|
+
constructor(e, t, n, r, i = p) {
|
|
58
59
|
this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r, this.stores = i;
|
|
59
60
|
}
|
|
60
61
|
current() {
|
|
@@ -66,14 +67,14 @@ var b = class {
|
|
|
66
67
|
this.removeUrlToken();
|
|
67
68
|
return;
|
|
68
69
|
}
|
|
69
|
-
let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(
|
|
70
|
+
let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(o));
|
|
70
71
|
if (t && this.restore(t)) return;
|
|
71
72
|
let n = await this.readOpenFinToken();
|
|
72
73
|
n !== null && this.adopt(n, "openfin.customData");
|
|
73
74
|
}
|
|
74
75
|
start(e, t = {}) {
|
|
75
76
|
let n = {
|
|
76
|
-
id: t.id ??
|
|
77
|
+
id: t.id ?? f(this.diagnostics),
|
|
77
78
|
name: e,
|
|
78
79
|
startedAt: Date.now(),
|
|
79
80
|
parentId: t.parent ? this.journey?.id : void 0,
|
|
@@ -91,7 +92,7 @@ var b = class {
|
|
|
91
92
|
getToken() {
|
|
92
93
|
let e = this.journey;
|
|
93
94
|
if (e === null) return;
|
|
94
|
-
let t =
|
|
95
|
+
let t = b(e);
|
|
95
96
|
if (t.length > 256) this.diagnostics.report("journey.token_too_large", "The journey token is larger than the size limit. The library does not issue it.", { length: t.length });
|
|
96
97
|
else return t;
|
|
97
98
|
}
|
|
@@ -112,7 +113,7 @@ var b = class {
|
|
|
112
113
|
this.clearTimer();
|
|
113
114
|
}
|
|
114
115
|
restore(e) {
|
|
115
|
-
let t =
|
|
116
|
+
let t = v(this.diagnostics.guard("storage.degraded", "The library could not parse the persisted journey.", () => JSON.parse(e)));
|
|
116
117
|
return t === null ? !1 : Date.now() - t.startedAt > this.options.maxAgeMs ? (this.diagnostics.report("journey.expired", "The library discarded a persisted journey older than maxAgeMs.", { name: t.name }), this.clearStored(), !1) : (this.setJourney(t), this.diagnostics.report("journey.adopted", `The library resumed the journey "${t.name}".`, {
|
|
117
118
|
source: "sessionStorage",
|
|
118
119
|
journeyId: t.id
|
|
@@ -120,22 +121,22 @@ var b = class {
|
|
|
120
121
|
}
|
|
121
122
|
decodeToken(e) {
|
|
122
123
|
return this.diagnostics.guard("config.invalid", "The library could not decode a seeded journey token.", () => {
|
|
123
|
-
let
|
|
124
|
-
return
|
|
124
|
+
let n = e.replace(i, "+").replace(t, "/"), r = (4 - n.length % 4) % 4, a = "=".repeat(r), o = Uint8Array.from(atob(n + a), (e) => e.charCodeAt(0));
|
|
125
|
+
return y(JSON.parse(new TextDecoder().decode(o)));
|
|
125
126
|
}) ?? null;
|
|
126
127
|
}
|
|
127
128
|
setJourney(e) {
|
|
128
129
|
if (this.journey = e, this.clearTimer(), this.diagnostics.guard("storage.unavailable", "The library could not save the journey.", () => {
|
|
129
|
-
e === null ? this.stores.session().removeItem(
|
|
130
|
+
e === null ? this.stores.session().removeItem(o) : this.stores.session().setItem(o, JSON.stringify(e));
|
|
130
131
|
}), e === null) return;
|
|
131
132
|
let t = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), n = setTimeout(() => {
|
|
132
133
|
this.diagnostics.report("journey.expired", `The journey "${e.name}" reached maxAgeMs. The library ended it.`, { journeyId: e.id }), this.journey = null, this.expiryTimer = null, this.clearStored();
|
|
133
134
|
}, t);
|
|
134
|
-
this.expiryTimer = n,
|
|
135
|
+
this.expiryTimer = n, d(n);
|
|
135
136
|
}
|
|
136
137
|
clearStored() {
|
|
137
138
|
this.diagnostics.guard("storage.unavailable", "The library could not clear the persisted journey.", () => {
|
|
138
|
-
this.stores.session().removeItem(
|
|
139
|
+
this.stores.session().removeItem(o);
|
|
139
140
|
});
|
|
140
141
|
}
|
|
141
142
|
clearTimer() {
|
|
@@ -151,13 +152,13 @@ var b = class {
|
|
|
151
152
|
});
|
|
152
153
|
}
|
|
153
154
|
async readOpenFinToken() {
|
|
154
|
-
let
|
|
155
|
-
if (
|
|
156
|
-
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () =>
|
|
155
|
+
let t = m()?.me, n = t?.getOptions;
|
|
156
|
+
if (n === void 0) return null;
|
|
157
|
+
let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => u(n.call(t), e)))?.customData?.[c];
|
|
157
158
|
return typeof r == "string" ? r : null;
|
|
158
159
|
}
|
|
159
160
|
};
|
|
160
161
|
//#endregion
|
|
161
|
-
export {
|
|
162
|
+
export { x as n, v as r, h as t };
|
|
162
163
|
|
|
163
|
-
//# sourceMappingURL=journey-
|
|
164
|
+
//# sourceMappingURL=journey-yALMEWF7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"journey-yALMEWF7.js","names":["OPENFIN_OPTIONS_TIMEOUT_MS","BASE64URL_UNDERSCORE_PATTERN","BASE64_SLASH_PATTERN","JOURNEY_URL_PARAM","BASE64URL_DASH_PATTERN","JOURNEY_MAX_AGE_MS","JOURNEY_STORAGE_KEY","BASE64_PADDING_PATTERN","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64_PLUS_PATTERN","withDeadline","unrefTimer","newId","BROWSER_STORES","getFin","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { getFin } from \"../utils/openfin\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = getFin()?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?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uBACA,4DACM;GACJ,KAAK,OAAO,QAAQ,CAAC,CAAC,WAAW/C,CAAmB;EACtD,CACF;CACF;CAGA,aAA2B;EACzB,AAAI,KAAK,gBAAgB,SACvB,aAAa,KAAK,WAAW,GAC7B,KAAK,cAAc;CAEvB;CAMA,eAAsC;EAWpC,OAVc,KAAK,YAAY,MAC7B,kBACA,oEAEM,OAAO,WAAa,MACf,OAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,KAAS;CAClB;CAMA,iBAA+B;EAC7B,KAAK,YAAY,MACf,wBACA,sEACM;GACJ,IAAMgD,IAAM,IAAI,IAAI,SAAS,IAAI;GAGjC,AAFAA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,GAE7C,QAAQ,aAAa,QAAQ,OAAO,IAAIA,EAAI,IAAI;EAClD,CACF;CACF;CAQA,MAAc,mBAA2C;EACvD,IAAMC,IAAKzC,EAAO,CAAC,EAAE,IACf0C,IAAaD,GAAI;EACvB,IAAIC,MAAe,KAAA,GACjB,OAAO;EAUT,IAAMb,KAAQ,MALQ,KAAK,YAAY,WACrC,uBACA,yDACMjC,EAAa8C,EAAW,KAAKD,CAAE,GAAGvD,CAA0B,CACpE,EAAA,EACuB,aAAaQ;EACpC,OAAO,OAAOmC,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-Cb92egPS.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.pt),n=Symbol.for(e.yn),r=globalThis,i=()=>r[n]??0;function a(e){return t.run(e)}function o(){return t.open()}async function s(e){r[n]=i()+1;try{return await e()}finally{r[n]=i()-1}}function c(){return i()>0}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=library-request-BcAxuwsf.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"library-request-BcAxuwsf.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","require_constants","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":"4CAUA,IAAMI,uCAAQJ,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAGvCI,EAAQ,OAAO,IAAIH,EAAAA,EAAkB,EACrCI,EAAQ,WACRC,MAAwBD,EAAMD,IAAU,EAQ9C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOJ,EAAM,IAAIK,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAON,EAAM,KAAK,CACpB,CAQA,eAAsBO,EAAsB,EAA0C,CACpF,EAAMN,GAASE,EAAQ,EAAI,EAE3B,GAAI,CACF,OAAO,MAAME,EAAG,CAClB,QAAU,CACR,EAAMJ,GAASE,EAAQ,EAAI,CAC7B,CACF,CAMA,SAAgBK,GAA8B,CAC5C,OAAOL,EAAQ,EAAI,CACrB"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { pt as e, yn as t } from "./constants-DhH6VI5a.js";
|
|
2
|
+
import { t as n } from "./global-scope-dp2jADRl.js";
|
|
3
|
+
//#region src/utils/library-request.ts
|
|
4
|
+
var r = n(e), i = Symbol.for(t), a = globalThis, o = () => a[i] ?? 0;
|
|
5
|
+
function s(e) {
|
|
6
|
+
return r.run(e);
|
|
7
|
+
}
|
|
8
|
+
function c() {
|
|
9
|
+
return r.open();
|
|
10
|
+
}
|
|
11
|
+
async function l(e) {
|
|
12
|
+
a[i] = o() + 1;
|
|
13
|
+
try {
|
|
14
|
+
return await e();
|
|
15
|
+
} finally {
|
|
16
|
+
a[i] = o() - 1;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function u() {
|
|
20
|
+
return o() > 0;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { l as i, u as n, s as r, c as t };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=library-request-CQD4HUiP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"library-request-CQD4HUiP.js","names":["LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","globalScope","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":";;;AAUA,IAAMG,IAAQD,EAAYF,CAAmB,GAGvCI,IAAQ,OAAO,IAAIH,CAAkB,GACrCI,IAAQ,YACRC,UAAwBD,EAAMD,MAAU;AAQ9C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOJ,EAAM,IAAIK,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAON,EAAM,KAAK;AACpB;AAQA,eAAsBO,EAAsB,GAA0C;CACpF,EAAMN,KAASE,EAAQ,IAAI;CAE3B,IAAI;EACF,OAAO,MAAME,EAAG;CAClB,UAAU;EACR,EAAMJ,KAASE,EAAQ,IAAI;CAC7B;AACF;AAMA,SAAgBK,IAA8B;CAC5C,OAAOL,EAAQ,IAAI;AACrB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./platform-
|
|
2
|
-
//# sourceMappingURL=long-frames-
|
|
1
|
+
const e=require("./platform-kIL5AZB7.cjs"),t=require("./storm-DhHGHhOc.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.i(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
|
|
2
|
+
//# sourceMappingURL=long-frames-D4Bm3Zkz.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"long-frames-
|
|
1
|
+
{"version":3,"file":"long-frames-D4Bm3Zkz.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAG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AMT,EAASF,EAAcW,EAAM,OAAO,EAGpCM,EAAO,GACX,KAAK,IAAI,OAAO,QAAQ,SAAWJ,EAAQjB,EAAAA,EAAciB,CAAK,EAEhE,GAAIX,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t } from "./storm-
|
|
1
|
+
import { i as e } from "./platform-GaM6h7XM.js";
|
|
2
|
+
import { t } from "./storm-OD5J6Ylm.js";
|
|
3
3
|
//#region src/capture/long-frames.ts
|
|
4
4
|
var n = ["long-animation-frame", "longtask"];
|
|
5
5
|
function r(e) {
|
|
@@ -62,4 +62,4 @@ var i = class {
|
|
|
62
62
|
//#endregion
|
|
63
63
|
export { i as LongFrameCapture };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=long-frames-
|
|
65
|
+
//# sourceMappingURL=long-frames-DD_Um9_4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"long-frames-
|
|
1
|
+
{"version":3,"file":"long-frames-DD_Um9_4.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY,KAAK,cAAc,GACpC,KAAK,WAAW,IAAI,qBAAqB,MAAS;GAChD,KAAK,IAAMK,KAASC,EAAK,WAAW,GAClC,KAAK,OAAOD,CAAK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own;
|
|
|
46
46
|
* @returns True for an action record.
|
|
47
47
|
*/
|
|
48
48
|
export declare function isActionRecord(record: LogRecord): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Returns the total record count of the batches.
|
|
51
|
+
* @param batches Batches to measure.
|
|
52
|
+
* @returns Total record count.
|
|
53
|
+
*/
|
|
54
|
+
export declare function countRecords(batches: readonly LogBatch[]): number;
|
package/dist/models/config.d.ts
CHANGED
|
@@ -315,6 +315,12 @@ export interface CaptureOptions {
|
|
|
315
315
|
* @default false
|
|
316
316
|
*/
|
|
317
317
|
xhr: boolean;
|
|
318
|
+
/**
|
|
319
|
+
* Record the `http.client.request.duration` histogram of each request that `fetch` or `xhr`
|
|
320
|
+
* capture sees. The histogram is in seconds.
|
|
321
|
+
* @default true
|
|
322
|
+
*/
|
|
323
|
+
httpMetrics: boolean;
|
|
318
324
|
/**
|
|
319
325
|
* Log clicks and other interactions as breadcrumbs.
|
|
320
326
|
* @default false
|
|
@@ -403,8 +409,15 @@ export interface ResolvedConsole {
|
|
|
403
409
|
/** CSS for the namespace and for each level. */
|
|
404
410
|
styles: Required<ConsoleStyles>;
|
|
405
411
|
}
|
|
412
|
+
/**
|
|
413
|
+
* Kind of a batch. A batch of metric records is "metrics" when `metricsEndpoint` is set. Its body
|
|
414
|
+
* is then an OTLP `ExportMetricsServiceRequest`.
|
|
415
|
+
*/
|
|
416
|
+
export type BatchKind = "logs" | "metrics";
|
|
406
417
|
/** One batch that the library gives to a custom transport. */
|
|
407
418
|
export interface TransportRequest {
|
|
419
|
+
/** Kind of the batch. Send a "metrics" body to your metrics endpoint. */
|
|
420
|
+
kind: BatchKind;
|
|
408
421
|
/** Serialized batch from the configured serializer. The library does not compress it. */
|
|
409
422
|
body: string;
|
|
410
423
|
/** Content type of `body`, from the serializer. */
|
|
@@ -455,6 +468,14 @@ export interface ObservabilityConfig {
|
|
|
455
468
|
* If the key is missing or `""`, the library reports `config.invalid`.
|
|
456
469
|
*/
|
|
457
470
|
endpoint?: string | null;
|
|
471
|
+
/**
|
|
472
|
+
* OTLP metrics endpoint URL, for example `"https://ingest.example/v1/metrics"`. With this key,
|
|
473
|
+
* the library sends each batch of metric records there as an OTLP `ExportMetricsServiceRequest`.
|
|
474
|
+
* Without it, metric records are log records on `endpoint`. The key needs `serializer: "otlp"`.
|
|
475
|
+
* Set `""` to turn it off.
|
|
476
|
+
* @default ""
|
|
477
|
+
*/
|
|
478
|
+
metricsEndpoint?: string;
|
|
458
479
|
/**
|
|
459
480
|
* The library reports this value as `service.name`.
|
|
460
481
|
* @default ""
|
|
@@ -596,6 +617,8 @@ export interface ObservabilityConfig {
|
|
|
596
617
|
export interface ResolvedConfig {
|
|
597
618
|
/** Ingest endpoint URL, or null in console-only mode. */
|
|
598
619
|
endpoint: string | null;
|
|
620
|
+
/** OTLP metrics endpoint URL. An empty string sends metric records as log records. */
|
|
621
|
+
metricsEndpoint: string;
|
|
599
622
|
/** The library reports this value as `service.name`. */
|
|
600
623
|
serviceName: string;
|
|
601
624
|
/** The library reports this value as `service.version`. */
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Attribute set of a metric point. Keep it small. Each set is one series in the backend. */
|
|
2
|
+
export type MetricAttributes = Record<string, string | number | boolean>;
|
|
3
|
+
/** Options of an instrument. */
|
|
4
|
+
export interface InstrumentOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Unit of the values, for example "ms" or "By".
|
|
7
|
+
* @default "count"
|
|
8
|
+
*/
|
|
9
|
+
unit?: string;
|
|
10
|
+
}
|
|
11
|
+
/** Options of a histogram. */
|
|
12
|
+
export interface HistogramOptions extends InstrumentOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Ascending bucket boundaries, at most 50. A value goes into the first bucket whose boundary
|
|
15
|
+
* is equal to or larger than the value.
|
|
16
|
+
* @default [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]
|
|
17
|
+
*/
|
|
18
|
+
boundaries?: readonly number[];
|
|
19
|
+
}
|
|
20
|
+
/** Counter that sums its values in memory. The library sends one point at each interval. */
|
|
21
|
+
export interface Counter {
|
|
22
|
+
/**
|
|
23
|
+
* Adds a value to the sum of an attribute set.
|
|
24
|
+
* @param value Finite number, 0 or larger.
|
|
25
|
+
* @param attributes Attribute set of the point.
|
|
26
|
+
*/
|
|
27
|
+
add(value: number, attributes?: MetricAttributes): void;
|
|
28
|
+
}
|
|
29
|
+
/** Histogram that counts its values in buckets in memory. It sends one point at each interval. */
|
|
30
|
+
export interface Histogram {
|
|
31
|
+
/**
|
|
32
|
+
* Adds a value to the buckets of an attribute set.
|
|
33
|
+
* @param value Finite number.
|
|
34
|
+
* @param attributes Attribute set of the point.
|
|
35
|
+
*/
|
|
36
|
+
record(value: number, attributes?: MetricAttributes): void;
|
|
37
|
+
}
|
|
38
|
+
/** Kind of an instrument. */
|
|
39
|
+
export type InstrumentKind = "counter" | "histogram";
|
|
40
|
+
/** Definition of an instrument. A handle gives it to the meter at each call. */
|
|
41
|
+
export interface InstrumentDef {
|
|
42
|
+
/** Metric name. */
|
|
43
|
+
name: string;
|
|
44
|
+
/** Kind of the instrument. */
|
|
45
|
+
kind: InstrumentKind;
|
|
46
|
+
/** Unit of the values. */
|
|
47
|
+
unit: string;
|
|
48
|
+
/** Bucket boundaries of a histogram. A counter has none. */
|
|
49
|
+
boundaries: readonly number[];
|
|
50
|
+
}
|