@utk09/ui-observability 0.9.3 → 0.9.4

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.
Files changed (156) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +108 -33
  3. package/dist/{batch-D5qvsMQ_.cjs → batch-C4oF6XZT.cjs} +2 -2
  4. package/dist/{batch-D5qvsMQ_.cjs.map → batch-C4oF6XZT.cjs.map} +1 -1
  5. package/dist/{batch-DDgxg16_.js → batch-D-4xl7op.js} +4 -4
  6. package/dist/{batch-DDgxg16_.js.map → batch-D-4xl7op.js.map} +1 -1
  7. package/dist/{bus-C6RwKzPW.js → bus-Cyvq-Ngx.js} +5 -5
  8. package/dist/{bus-C6RwKzPW.js.map → bus-Cyvq-Ngx.js.map} +1 -1
  9. package/dist/{bus-WPVDFw2y.cjs → bus-rOhVuRee.cjs} +2 -2
  10. package/dist/{bus-WPVDFw2y.cjs.map → bus-rOhVuRee.cjs.map} +1 -1
  11. package/dist/capture/network.d.ts +1 -0
  12. package/dist/capture/types.d.ts +3 -0
  13. package/dist/capture/web-socket.d.ts +40 -0
  14. package/dist/{console-Dv5GfaNn.js → console-BT7mcgU6.js} +3 -3
  15. package/dist/{console-Dv5GfaNn.js.map → console-BT7mcgU6.js.map} +1 -1
  16. package/dist/{console-BSusX_M-.cjs → console-Boqa7new.cjs} +2 -2
  17. package/dist/{console-BSusX_M-.cjs.map → console-Boqa7new.cjs.map} +1 -1
  18. package/dist/constants-BgRS6MB0.cjs +2 -0
  19. package/dist/constants-BgRS6MB0.cjs.map +1 -0
  20. package/dist/constants-L_d5YvvQ.js +160 -0
  21. package/dist/constants-L_d5YvvQ.js.map +1 -0
  22. package/dist/constants.d.ts +34 -2
  23. package/dist/core/breadcrumbs.d.ts +3 -1
  24. package/dist/core/diagnostics.d.ts +1 -1
  25. package/dist/core/journey.d.ts +7 -0
  26. package/dist/core/meter.d.ts +19 -1
  27. package/dist/core/pipeline.d.ts +12 -4
  28. package/dist/core/record.d.ts +40 -8
  29. package/dist/core/remote-sampling.d.ts +7 -3
  30. package/dist/core/runtime.d.ts +62 -3
  31. package/dist/core/sampling.d.ts +32 -1
  32. package/dist/core/sender.d.ts +8 -0
  33. package/dist/core/spans.d.ts +34 -0
  34. package/dist/{errors-DCZWcHkd.js → errors-BDI96zKc.js} +6 -6
  35. package/dist/errors-BDI96zKc.js.map +1 -0
  36. package/dist/errors-_xEsCVXn.cjs +3 -0
  37. package/dist/errors-_xEsCVXn.cjs.map +1 -0
  38. package/dist/identity-Bwku7zzN.cjs +2 -0
  39. package/dist/identity-Bwku7zzN.cjs.map +1 -0
  40. package/dist/{identity-Di-QXGCC.js → identity-Dtv917nz.js} +33 -23
  41. package/dist/identity-Dtv917nz.js.map +1 -0
  42. package/dist/index.cjs +1 -1
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.ts +23 -1
  45. package/dist/index.js +803 -524
  46. package/dist/index.js.map +1 -1
  47. package/dist/{indexeddb-storage-DX18p39D.cjs → indexeddb-storage-Cvavrf-y.cjs} +2 -2
  48. package/dist/{indexeddb-storage-DX18p39D.cjs.map → indexeddb-storage-Cvavrf-y.cjs.map} +1 -1
  49. package/dist/{indexeddb-storage-T9YIYVYC.js → indexeddb-storage-HgkQUTyS.js} +26 -26
  50. package/dist/{indexeddb-storage-T9YIYVYC.js.map → indexeddb-storage-HgkQUTyS.js.map} +1 -1
  51. package/dist/{interactions-_hfOerfC.cjs → interactions-Bhe1ft8P.cjs} +2 -2
  52. package/dist/interactions-Bhe1ft8P.cjs.map +1 -0
  53. package/dist/{interactions-BLH_tX87.js → interactions-Ck01cEij.js} +3 -3
  54. package/dist/interactions-Ck01cEij.js.map +1 -0
  55. package/dist/journey-Co9OlzrW.cjs +2 -0
  56. package/dist/journey-Co9OlzrW.cjs.map +1 -0
  57. package/dist/{journey-yALMEWF7.js → journey-DRK0A8u_.js} +37 -34
  58. package/dist/journey-DRK0A8u_.js.map +1 -0
  59. package/dist/{library-request-CQD4HUiP.js → library-request-ChCar5F8.js} +3 -3
  60. package/dist/{library-request-CQD4HUiP.js.map → library-request-ChCar5F8.js.map} +1 -1
  61. package/dist/{library-request-BcAxuwsf.cjs → library-request-gMFOCNcn.cjs} +2 -2
  62. package/dist/{library-request-BcAxuwsf.cjs.map → library-request-gMFOCNcn.cjs.map} +1 -1
  63. package/dist/log-record-cwFiLyPY.js +17 -0
  64. package/dist/log-record-cwFiLyPY.js.map +1 -0
  65. package/dist/log-record-jX9eWUP8.cjs +2 -0
  66. package/dist/log-record-jX9eWUP8.cjs.map +1 -0
  67. package/dist/{long-frames-D4Bm3Zkz.cjs → long-frames-Bky6nZDF.cjs} +2 -2
  68. package/dist/long-frames-Bky6nZDF.cjs.map +1 -0
  69. package/dist/{long-frames-DD_Um9_4.js → long-frames-DDumopji.js} +4 -4
  70. package/dist/long-frames-DDumopji.js.map +1 -0
  71. package/dist/models/config.d.ts +56 -5
  72. package/dist/models/log-record.d.ts +1 -1
  73. package/dist/models/plugin.d.ts +47 -0
  74. package/dist/models/stats.d.ts +11 -0
  75. package/dist/{network--GoE7_Or.js → network-BsBZ6_-Q.js} +43 -29
  76. package/dist/network-BsBZ6_-Q.js.map +1 -0
  77. package/dist/network-_4csBGBM.cjs +2 -0
  78. package/dist/network-_4csBGBM.cjs.map +1 -0
  79. package/dist/{platform-GaM6h7XM.js → platform-4yYjMD-B.js} +11 -6
  80. package/dist/platform-4yYjMD-B.js.map +1 -0
  81. package/dist/{platform-kIL5AZB7.cjs → platform-o7r1ocOu.cjs} +2 -2
  82. package/dist/platform-o7r1ocOu.cjs.map +1 -0
  83. package/dist/remote-rules-1KqfVBIu.js +91 -0
  84. package/dist/remote-rules-1KqfVBIu.js.map +1 -0
  85. package/dist/remote-rules-BHgEGlYi.cjs +2 -0
  86. package/dist/remote-rules-BHgEGlYi.cjs.map +1 -0
  87. package/dist/sampling-C4my-ma0.cjs +2 -0
  88. package/dist/sampling-C4my-ma0.cjs.map +1 -0
  89. package/dist/sampling-nYIWP_vP.js +86 -0
  90. package/dist/sampling-nYIWP_vP.js.map +1 -0
  91. package/dist/{sanitize-DP0xDPrt.js → sanitize-BiUKCUG6.js} +2 -2
  92. package/dist/{sanitize-DP0xDPrt.js.map → sanitize-BiUKCUG6.js.map} +1 -1
  93. package/dist/{sanitize--_e4oOPX.cjs → sanitize-BxuPSXOk.cjs} +2 -2
  94. package/dist/{sanitize--_e4oOPX.cjs.map → sanitize-BxuPSXOk.cjs.map} +1 -1
  95. package/dist/sender-6vrT9fFL.cjs +3 -0
  96. package/dist/sender-6vrT9fFL.cjs.map +1 -0
  97. package/dist/{sender-BUBWLn5i.js → sender-DFQMF39P.js} +382 -275
  98. package/dist/sender-DFQMF39P.js.map +1 -0
  99. package/dist/{storm-DhHGHhOc.cjs → storm-6YYbXzT_.cjs} +2 -2
  100. package/dist/{storm-DhHGHhOc.cjs.map → storm-6YYbXzT_.cjs.map} +1 -1
  101. package/dist/{storm-OD5J6Ylm.js → storm-CfO0Sam2.js} +2 -2
  102. package/dist/{storm-OD5J6Ylm.js.map → storm-CfO0Sam2.js.map} +1 -1
  103. package/dist/transport/exit-flush.d.ts +6 -0
  104. package/dist/transport/http-transport.d.ts +2 -1
  105. package/dist/transport/serializers/otlp-traces.d.ts +3 -0
  106. package/dist/transport/serializers/select.d.ts +8 -5
  107. package/dist/transport/status-transport.d.ts +7 -0
  108. package/dist/types-BR9t_w28.js +8 -0
  109. package/dist/types-BR9t_w28.js.map +1 -0
  110. package/dist/types-C7WNpnG1.cjs +2 -0
  111. package/dist/types-C7WNpnG1.cjs.map +1 -0
  112. package/dist/utils/identity.d.ts +11 -0
  113. package/dist/utils/platform.d.ts +8 -0
  114. package/dist/utils/tracing.d.ts +82 -4
  115. package/dist/web-socket-Ar4cZxmd.js +102 -0
  116. package/dist/web-socket-Ar4cZxmd.js.map +1 -0
  117. package/dist/web-socket-BwJdwSHl.cjs +2 -0
  118. package/dist/web-socket-BwJdwSHl.cjs.map +1 -0
  119. package/package.json +1 -1
  120. package/dist/constants-Cb92egPS.cjs +0 -2
  121. package/dist/constants-Cb92egPS.cjs.map +0 -1
  122. package/dist/constants-DhH6VI5a.js +0 -144
  123. package/dist/constants-DhH6VI5a.js.map +0 -1
  124. package/dist/deadline-CUrH0Hd8.cjs +0 -2
  125. package/dist/deadline-CUrH0Hd8.cjs.map +0 -1
  126. package/dist/deadline-DeqXEliN.js +0 -31
  127. package/dist/deadline-DeqXEliN.js.map +0 -1
  128. package/dist/errors-DCZWcHkd.js.map +0 -1
  129. package/dist/errors-ERu-su8m.cjs +0 -3
  130. package/dist/errors-ERu-su8m.cjs.map +0 -1
  131. package/dist/identity-C1WLItSl.cjs +0 -2
  132. package/dist/identity-C1WLItSl.cjs.map +0 -1
  133. package/dist/identity-Di-QXGCC.js.map +0 -1
  134. package/dist/interactions-BLH_tX87.js.map +0 -1
  135. package/dist/interactions-_hfOerfC.cjs.map +0 -1
  136. package/dist/journey-BRUj0hqD.cjs +0 -2
  137. package/dist/journey-BRUj0hqD.cjs.map +0 -1
  138. package/dist/journey-yALMEWF7.js.map +0 -1
  139. package/dist/long-frames-D4Bm3Zkz.cjs.map +0 -1
  140. package/dist/long-frames-DD_Um9_4.js.map +0 -1
  141. package/dist/network--GoE7_Or.js.map +0 -1
  142. package/dist/network-DcuS2H1P.cjs +0 -2
  143. package/dist/network-DcuS2H1P.cjs.map +0 -1
  144. package/dist/platform-GaM6h7XM.js.map +0 -1
  145. package/dist/platform-kIL5AZB7.cjs.map +0 -1
  146. package/dist/remote-rules-6ePq8CrI.js +0 -84
  147. package/dist/remote-rules-6ePq8CrI.js.map +0 -1
  148. package/dist/remote-rules-CI3gbRCL.cjs +0 -2
  149. package/dist/remote-rules-CI3gbRCL.cjs.map +0 -1
  150. package/dist/sampling-C-M8p3FK.cjs +0 -2
  151. package/dist/sampling-C-M8p3FK.cjs.map +0 -1
  152. package/dist/sampling-Ud_WiuU9.js +0 -65
  153. package/dist/sampling-Ud_WiuU9.js.map +0 -1
  154. package/dist/sender-BESHz6my.cjs +0 -3
  155. package/dist/sender-BESHz6my.cjs.map +0 -1
  156. package/dist/sender-BUBWLn5i.js.map +0 -1
@@ -1,53 +1,53 @@
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";
1
+ import { Ot as e, _ as t, b as n, ct as r, dt as i, g as a, kt as o, lt as s, ut as c, v as l, y as u } from "./constants-L_d5YvvQ.js";
2
+ import { c as d, l as f } from "./sampling-nYIWP_vP.js";
3
+ import { i as p, t as m } from "./identity-Dtv917nz.js";
4
+ import { t as h } from "./openfin-BwEN0uj4.js";
5
5
  //#region src/core/journey.ts
6
- var h = {
7
- maxAgeMs: a,
6
+ var g = {
7
+ maxAgeMs: s,
8
8
  endOnOwnerClose: !1,
9
- urlParam: r
9
+ urlParam: i
10
10
  };
11
- function g(e, t) {
11
+ function _(e, t) {
12
12
  let n = Reflect.get(e, t);
13
13
  return typeof n == "string" && n !== "" ? n : void 0;
14
14
  }
15
- function _(e, t) {
15
+ function v(e, t) {
16
16
  let n = Reflect.get(e, t);
17
17
  return typeof n == "number" && Number.isFinite(n) ? n : void 0;
18
18
  }
19
- function v(e) {
19
+ function y(e) {
20
20
  if (typeof e != "object" || !e) return null;
21
- let t = g(e, "id"), n = g(e, "name"), r = _(e, "startedAt");
21
+ let t = _(e, "id"), n = _(e, "name"), r = v(e, "startedAt");
22
22
  return t === void 0 || n === void 0 || r === void 0 ? null : {
23
23
  id: t,
24
24
  name: n,
25
25
  startedAt: r,
26
- parentId: g(e, "parentId"),
27
- ownerContextId: g(e, "ownerContextId") ?? ""
26
+ parentId: _(e, "parentId"),
27
+ ownerContextId: _(e, "ownerContextId") ?? ""
28
28
  };
29
29
  }
30
- function y(e) {
30
+ function b(e) {
31
31
  if (typeof e != "object" || !e) return null;
32
- let t = g(e, "i"), n = g(e, "n");
33
- return t === void 0 || n === void 0 ? null : {
32
+ let t = _(e, "i"), n = _(e, "n"), r = v(e, "s"), i = r !== void 0 && r > Date.now() + 3e5;
33
+ return t === void 0 || n === void 0 || r === void 0 || i ? null : {
34
34
  id: t,
35
35
  name: n,
36
- startedAt: _(e, "s") ?? Date.now(),
36
+ startedAt: r,
37
37
  parentId: void 0,
38
38
  ownerContextId: ""
39
39
  };
40
40
  }
41
- function b(e) {
41
+ function x(e) {
42
42
  let t = JSON.stringify({
43
43
  i: e.id,
44
44
  n: e.name.slice(0, 64),
45
45
  s: e.startedAt
46
46
  }), r = new TextEncoder().encode(t), i = "";
47
47
  for (let e of r) i += String.fromCharCode(e);
48
- return btoa(i).replace(l, "-").replace(n, "_").replace(s, "");
48
+ return btoa(i).replace(u, "-").replace(n, "_").replace(l, "");
49
49
  }
50
- var x = class {
50
+ var S = class {
51
51
  options;
52
52
  diagnostics;
53
53
  contextId;
@@ -55,7 +55,7 @@ var x = class {
55
55
  stores;
56
56
  journey = null;
57
57
  expiryTimer = null;
58
- constructor(e, t, n, r, i = p) {
58
+ constructor(e, t, n, r, i = m) {
59
59
  this.options = e, this.diagnostics = t, this.contextId = n, this.onLocalChange = r, this.stores = i;
60
60
  }
61
61
  current() {
@@ -67,14 +67,14 @@ var x = class {
67
67
  this.removeUrlToken();
68
68
  return;
69
69
  }
70
- let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(o));
70
+ let t = this.diagnostics.guard("storage.unavailable", "The library could not read the persisted journey.", () => this.stores.session().getItem(c));
71
71
  if (t && this.restore(t)) return;
72
72
  let n = await this.readOpenFinToken();
73
73
  n !== null && this.adopt(n, "openfin.customData");
74
74
  }
75
75
  start(e, t = {}) {
76
76
  let n = {
77
- id: t.id ?? f(this.diagnostics),
77
+ id: this.journeyId(t.id),
78
78
  name: e,
79
79
  startedAt: Date.now(),
80
80
  parentId: t.parent ? this.journey?.id : void 0,
@@ -82,6 +82,9 @@ var x = class {
82
82
  };
83
83
  return this.setJourney(n), this.onLocalChange(n), n;
84
84
  }
85
+ journeyId(e) {
86
+ return e === void 0 ? p(this.diagnostics) : typeof e == "string" && r.test(e) ? e : (this.diagnostics.report("config.invalid", "startJourney() needs an id of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id."), p(this.diagnostics));
87
+ }
85
88
  end() {
86
89
  this.journey !== null && (this.setJourney(null), this.onLocalChange(null));
87
90
  }
@@ -92,7 +95,7 @@ var x = class {
92
95
  getToken() {
93
96
  let e = this.journey;
94
97
  if (e === null) return;
95
- let t = b(e);
98
+ let t = x(e);
96
99
  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 });
97
100
  else return t;
98
101
  }
@@ -113,7 +116,7 @@ var x = class {
113
116
  this.clearTimer();
114
117
  }
115
118
  restore(e) {
116
- let t = v(this.diagnostics.guard("storage.degraded", "The library could not parse the persisted journey.", () => JSON.parse(e)));
119
+ let t = y(this.diagnostics.guard("storage.degraded", "The library could not parse the persisted journey.", () => JSON.parse(e)));
117
120
  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}".`, {
118
121
  source: "sessionStorage",
119
122
  journeyId: t.id
@@ -121,22 +124,22 @@ var x = class {
121
124
  }
122
125
  decodeToken(e) {
123
126
  return this.diagnostics.guard("config.invalid", "The library could not decode a seeded journey token.", () => {
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)));
127
+ let n = e.replace(a, "+").replace(t, "/"), r = (4 - n.length % 4) % 4, i = "=".repeat(r), o = Uint8Array.from(atob(n + i), (e) => e.charCodeAt(0));
128
+ return b(JSON.parse(new TextDecoder().decode(o)));
126
129
  }) ?? null;
127
130
  }
128
131
  setJourney(e) {
129
132
  if (this.journey = e, this.clearTimer(), this.diagnostics.guard("storage.unavailable", "The library could not save the journey.", () => {
130
- e === null ? this.stores.session().removeItem(o) : this.stores.session().setItem(o, JSON.stringify(e));
133
+ e === null ? this.stores.session().removeItem(c) : this.stores.session().setItem(c, JSON.stringify(e));
131
134
  }), e === null) return;
132
135
  let t = Math.max(this.options.maxAgeMs - (Date.now() - e.startedAt), 0), n = setTimeout(() => {
133
136
  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();
134
137
  }, t);
135
- this.expiryTimer = n, d(n);
138
+ this.expiryTimer = n, f(n);
136
139
  }
137
140
  clearStored() {
138
141
  this.diagnostics.guard("storage.unavailable", "The library could not clear the persisted journey.", () => {
139
- this.stores.session().removeItem(o);
142
+ this.stores.session().removeItem(c);
140
143
  });
141
144
  }
142
145
  clearTimer() {
@@ -152,13 +155,13 @@ var x = class {
152
155
  });
153
156
  }
154
157
  async readOpenFinToken() {
155
- let t = m()?.me, n = t?.getOptions;
158
+ let t = h()?.me, n = t?.getOptions;
156
159
  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];
160
+ let r = (await this.diagnostics.guardAsync("openfin.unavailable", "The library could not read fin.me.getOptions().", () => d(n.call(t), o)))?.customData?.[e];
158
161
  return typeof r == "string" ? r : null;
159
162
  }
160
163
  };
161
164
  //#endregion
162
- export { x as n, v as r, h as t };
165
+ export { S as n, y as r, g as t };
163
166
 
164
- //# sourceMappingURL=journey-yALMEWF7.js.map
167
+ //# sourceMappingURL=journey-DRK0A8u_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journey-DRK0A8u_.js","names":["OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64URL_UNDERSCORE_PATTERN","BASE64_SLASH_PATTERN","JOURNEY_ID_PATTERN","JOURNEY_URL_PARAM","BASE64URL_DASH_PATTERN","OPENFIN_OPTIONS_TIMEOUT_MS","JOURNEY_MAX_AGE_MS","JOURNEY_STORAGE_KEY","BASE64_PADDING_PATTERN","BASE64_PLUS_PATTERN","withDeadline","unrefTimer","newId","BROWSER_STORES","getFin","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","future","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","requested","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_CLOCK_SKEW_MS,\n JOURNEY_ID_MAX_CHARS,\n JOURNEY_ID_PATTERN,\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 const startedAt = readNumber(value, \"s\");\n // The library always writes a start time. A token without one, or from the future, never expires.\n const future = startedAt !== undefined && startedAt > Date.now() + JOURNEY_CLOCK_SKEW_MS;\n if (id === undefined || name === undefined || startedAt === undefined || future) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\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: this.journeyId(opts.id),\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 /**\n * Gives the id of a new journey. A longer id, or an id with multibyte characters, makes the\n * journey token too long for adoptJourney().\n * @param requested Id from the app, or undefined.\n * @returns The requested id when it matches JOURNEY_ID_PATTERN, else a new id.\n */\n private journeyId(requested: unknown): string {\n if (requested === undefined) {\n return newId(this.diagnostics);\n }\n\n if (typeof requested === \"string\" && JOURNEY_ID_PATTERN.test(requested)) {\n return requested;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `startJourney() needs an id of 1 to ${String(JOURNEY_ID_MAX_CHARS)} letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id.`,\n );\n return newId(this.diagnostics);\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?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;;;AA0CA,IAAagB,IAAkC;CAC7C,UAAUT;CACV,iBAAA;CACA,UAAUH;AACZ;AAsBA,SAASa,EAAW,GAAgB,GAAiC;CACnE,IAAMC,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAYA,MAAU,KAAKA,IAAQ,KAAA;AAC7D;AAQA,SAASG,EAAW,GAAgB,GAAiC;CACnE,IAAMH,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAY,OAAO,SAASA,CAAK,IAAIA,IAAQ,KAAA;AACvE;AAQA,SAAgBI,EAAa,GAAgC;CAC3D,IAAI,OAAOJ,KAAU,aAAYA,GAC/B,OAAO;CAET,IAAMK,IAAKN,EAAWC,GAAO,IAAI,GAC3BM,IAAOP,EAAWC,GAAO,MAAM,GAC/BO,IAAYJ,EAAWH,GAAO,WAAW;CAI/C,OAHIK,MAAO,KAAA,KAAaC,MAAS,KAAA,KAAaC,MAAc,KAAA,IACnD,OAEF;EACL;EACA;EACA;EACA,UAAUR,EAAWC,GAAO,UAA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,QAAQ,aAAa,QAAQ,OAAO,IAAIA,EAAI,IAAI;EAClD,CACF;CACF;CAQA,MAAc,mBAA2C;EACvD,IAAMC,IAAK3C,EAAO,CAAC,EAAE,IACf4C,IAAaD,GAAI;EACvB,IAAIC,MAAe,KAAA,GACjB,OAAO;EAUT,IAAMb,KAAQ,MALQ,KAAK,YAAY,WACrC,uBACA,yDACMnC,EAAagD,EAAW,KAAKD,CAAE,GAAGpD,CAA0B,CACpE,EAAA,EACuB,aAAaN;EACpC,OAAO,OAAO8C,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
@@ -1,7 +1,7 @@
1
- import { pt as e, yn as t } from "./constants-DhH6VI5a.js";
1
+ import { Tn as e, gt as t } from "./constants-L_d5YvvQ.js";
2
2
  import { t as n } from "./global-scope-dp2jADRl.js";
3
3
  //#region src/utils/library-request.ts
4
- var r = n(e), i = Symbol.for(t), a = globalThis, o = () => a[i] ?? 0;
4
+ var r = n(t), i = Symbol.for(e), a = globalThis, o = () => a[i] ?? 0;
5
5
  function s(e) {
6
6
  return r.run(e);
7
7
  }
@@ -22,4 +22,4 @@ function u() {
22
22
  //#endregion
23
23
  export { l as i, u as n, s as r, c as t };
24
24
 
25
- //# sourceMappingURL=library-request-CQD4HUiP.js.map
25
+ //# sourceMappingURL=library-request-ChCar5F8.js.map
@@ -1 +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
+ {"version":3,"file":"library-request-ChCar5F8.js","names":["TRANSPORT_CALL_KEY","LIBRARY_REQUEST_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,EAAYD,CAAmB,GAGvCG,IAAQ,OAAO,IAAIJ,CAAkB,GACrCK,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("./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
1
+ const e=require("./constants-BgRS6MB0.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.gt),n=Symbol.for(e.Tn),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-gMFOCNcn.cjs.map
@@ -1 +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"}
1
+ {"version":3,"file":"library-request-gMFOCNcn.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,17 @@
1
+ import { pt as e } from "./constants-L_d5YvvQ.js";
2
+ //#region src/models/log-record.ts
3
+ function t() {
4
+ return `${String(Date.now())}000000`;
5
+ }
6
+ function n(t) {
7
+ return typeof t == "string" && Object.hasOwn(e, t);
8
+ }
9
+ function r(e) {
10
+ if (typeof e != "object" || !e) return !1;
11
+ let t = e;
12
+ 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;
13
+ }
14
+ //#endregion
15
+ export { r as n, t as r, n as t };
16
+
17
+ //# sourceMappingURL=log-record-cwFiLyPY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-record-cwFiLyPY.js","names":["LEVEL_ORDER","nowUnixNano","isLogLevel","value","isLogRecord","record"],"sources":["../src/models/log-record.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\" | \"span\";\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"],"mappings":";;AA0DA,SAAgBC,IAAsB;CACpC,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE;AAC/B;AAOA,SAAgBC,EAAW,GAAmC;CAC5D,OAAO,OAAOC,KAAU,YAAY,OAAO,OAAOH,GAAaG,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"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-BgRS6MB0.cjs");function t(){return`${String(Date.now())}000000`}function n(t){return typeof t==`string`&&Object.hasOwn(e.pt,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}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
2
+ //# sourceMappingURL=log-record-jX9eWUP8.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-record-jX9eWUP8.cjs","names":["LEVEL_ORDER","require_constants","nowUnixNano","isLogLevel","value","isLogRecord","record"],"sources":["../src/models/log-record.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\" | \"span\";\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"],"mappings":"4CA0DA,SAAgBE,GAAsB,CACpC,MAAO,GAAG,OAAO,KAAK,IAAI,CAAC,EAAE,OAC/B,CAOA,SAAgBC,EAAW,EAAmC,CAC5D,OAAO,OAAOC,GAAU,UAAY,OAAO,OAAOJ,EAAAA,GAAaI,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,EAAO,aAAe,MACtB,OAAOA,EAAO,UAAa,UAC3BA,EAAO,WAAa,IAExB"}
@@ -1,2 +1,2 @@
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
+ const e=require("./platform-o7r1ocOu.cjs"),t=require("./storm-6YYbXzT_.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=>e.i(t,this.ctx.config.capture.fullUrls);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-Bky6nZDF.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-Bky6nZDF.cjs","names":["allowInWindow","recordedUrl","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 { recordedUrl } 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 => recordedUrl(value, this.ctx.config.capture.fullUrls);\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,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5D,UAAA,IAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd,GAAI,KAAK,SACP,OAKF,GAAM,CAAE,QAAS,KAAK,IAChBC,EAAQ,CAACC,EAAK,WACpB,EAAK,WAAa,GAGlB,IAAMC,EACJ,OAAO,oBAAwB,IAC3B,IAAA,GACA,oBAAoB,oBACpBC,EAAOV,EAAY,KAAM,GAASS,GAAW,SAASE,CAAI,CAAC,EAEjE,GAAID,IAAS,IAAA,GAAW,CACtB,GAAI,CAACH,EACH,OAGF,KAAK,IAAI,YAAY,OACnB,yBACA,yEAC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AAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
@@ -1,5 +1,5 @@
1
- import { i as e } from "./platform-GaM6h7XM.js";
2
- import { t } from "./storm-OD5J6Ylm.js";
1
+ import { i as e } from "./platform-4yYjMD-B.js";
2
+ import { t } from "./storm-CfO0Sam2.js";
3
3
  //#region src/capture/long-frames.ts
4
4
  var n = ["long-animation-frame", "longtask"];
5
5
  function r(e) {
@@ -47,7 +47,7 @@ var i = class {
47
47
  if (!t(this.window, 20, i, "long frames")) return;
48
48
  let a = Math.round(n.duration), o = { "frame.type": n.entryType };
49
49
  n.blockingDuration !== void 0 && (o["frame.blocking_ms"] = Math.round(n.blockingDuration));
50
- let s = r(n.scripts), c = (t) => this.ctx.config.capture.fullUrls ? t : e(t);
50
+ let s = r(n.scripts), c = (t) => e(t, this.ctx.config.capture.fullUrls);
51
51
  if (s?.invoker) {
52
52
  let { invoker: e } = s;
53
53
  o["frame.script.invoker"] = e.includes("://") ? c(e) : e;
@@ -62,4 +62,4 @@ var i = class {
62
62
  //#endregion
63
63
  export { i as LongFrameCapture };
64
64
 
65
- //# sourceMappingURL=long-frames-DD_Um9_4.js.map
65
+ //# sourceMappingURL=long-frames-DDumopji.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-DDumopji.js","names":["recordedUrl","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 { recordedUrl } 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 => recordedUrl(value, this.ctx.config.capture.fullUrls);\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;EAErB,CAAC,GAGD,KAAK,SAAS,QAAQ;GAAE;GAAM,UAAUL;EAAM,CAAC;CACjD;CAGA,YAAkB;EAEhB,AADA,KAAK,UAAU,WAAW,GAC1B,KAAK,WAAW,KAAA;CAClB;CAMA,gBAAgC;EAC9B,IAAMO,IAAiB,KAAK,IAAI,OAAO,QAAQ;EAU/C,OARI,OAAOA,KAAU,YAAY,OAAO,SAASA,CAAK,KAAKA,KAAS,IAC3DA,KAGT,KAAK,IAAI,YAAY,OACnB,kBACA,mFACF,GACA;CACF;CAMA,OAAe,GAAyB;EACtC,IAAIF,EAAM,WAAW,KAAK,WACxB;EAGF,IAAM,EAAE,mBAAgB,KAAK;EAE7B,IAAI,CAACG,EAAc,KAAK,QAAA,IAAmCC,GAAa,aAAa,GACnF;EAGF,IAAMC,IAAW,KAAK,MAAML,EAAM,QAAQ,GACpCM,IAAiC,EAAE,cAAcN,EAAM,UAAU;EAEvE,AAAIA,EAAM,qBAAqB,KAAA,MAC7B,EAAM,uBAAuB,KAAK,MAAMA,EAAM,gBAAgB;EAGhE,IAAMT,IAASF,EAAcW,EAAM,OAAO,GAGpCO,KAAO,MAA0BpB,EAAYe,GAAO,KAAK,IAAI,OAAO,QAAQ,QAAQ;EAE1F,IAAIX,GAAQ,SAAS;GAGnB,IAAM,EAAE,eAAYA;GACpB,EAAM,0BAA0BiB,EAAQ,SAAS,KAAK,IAAID,EAAIC,CAAO,IAAIA;EAC3E;EAWA,AATIjB,GAAQ,cACV,EAAM,yBAAyBgB,EAAIhB,EAAO,SAAS,IAGrD,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,cAAc,OAAOc,CAAQ,EAAE;EAC1C,CAAC,GACD,KAAK,IAAI,OAAO,UAAU,0BAA0BA,GAAU,MAAM,aAAaC,CAAK;CACxF;AACF"}
@@ -1,6 +1,7 @@
1
1
  import type { DiagnosticHandler } from "../core/diagnostics";
2
2
  import type { DropSummary } from "./drop";
3
3
  import type { LogLevel, LogRecord } from "./log-record";
4
+ import type { CapturePlugin } from "./plugin";
4
5
  import type { LogSerializer } from "./serializer";
5
6
  /** Backing store for undelivered records. "auto" picks the best one the host supports. */
6
7
  export type StorageStrategy = "auto" | "indexeddb" | "localstorage" | "memory" | "none";
@@ -372,6 +373,17 @@ export interface CaptureOptions {
372
373
  * @default []
373
374
  */
374
375
  propagateTraceHeaderTo: (string | RegExp)[];
376
+ /**
377
+ * Record the open, close and error events of each WebSocket, and count its messages in the
378
+ * counter `ui.websocket.messages`. The library never records the content of a message.
379
+ * @default false
380
+ */
381
+ webSocket: boolean;
382
+ /**
383
+ * Capture modules from the app. A new list replaces the list in force.
384
+ * @default []
385
+ */
386
+ plugins: CapturePlugin[];
375
387
  /**
376
388
  * Supplies the `web-vitals` module without a hard dependency on the package.
377
389
  * @returns A promise that resolves to the `web-vitals` module.
@@ -411,12 +423,13 @@ export interface ResolvedConsole {
411
423
  }
412
424
  /**
413
425
  * Kind of a batch. A batch of metric records is "metrics" when `metricsEndpoint` is set. Its body
414
- * is then an OTLP `ExportMetricsServiceRequest`.
426
+ * is then an OTLP `ExportMetricsServiceRequest`. A batch of span records is "traces". Its body is
427
+ * an OTLP `ExportTraceServiceRequest`.
415
428
  */
416
- export type BatchKind = "logs" | "metrics";
429
+ export type BatchKind = "logs" | "metrics" | "traces";
417
430
  /** One batch that the library gives to a custom transport. */
418
431
  export interface TransportRequest {
419
- /** Kind of the batch. Send a "metrics" body to your metrics endpoint. */
432
+ /** Kind of the batch. Send a "metrics" body to your metrics endpoint, and a "traces" body to your traces endpoint. */
420
433
  kind: BatchKind;
421
434
  /** Serialized batch from the configured serializer. The library does not compress it. */
422
435
  body: string;
@@ -476,6 +489,15 @@ export interface ObservabilityConfig {
476
489
  * @default ""
477
490
  */
478
491
  metricsEndpoint?: string;
492
+ /**
493
+ * OTLP traces endpoint URL, for example `"https://ingest.example/v1/traces"`. With this key, the
494
+ * library records one root span for each trace of the library, and one CLIENT span for each
495
+ * request that gets `traceparent`. It sends them there as an OTLP `ExportTraceServiceRequest`.
496
+ * Without it, the library sends no span. The key needs `serializer: "otlp"`. Set `""` to turn
497
+ * it off.
498
+ * @default ""
499
+ */
500
+ tracesEndpoint?: string;
479
501
  /**
480
502
  * The library reports this value as `service.name`.
481
503
  * @default ""
@@ -501,6 +523,13 @@ export interface ObservabilityConfig {
501
523
  * @default "INFO"
502
524
  */
503
525
  minLevel?: LogLevel;
526
+ /**
527
+ * Minimum level for each namespace prefix. The longest matching prefix wins. For example,
528
+ * `{ "trading.ticks": "DEBUG" }` logs the DEBUG records of `trading.ticks` and of its child
529
+ * namespaces. A namespace with no match uses `minLevel`. A new map replaces the map in force.
530
+ * @default {}
531
+ */
532
+ minLevels?: Record<string, LogLevel>;
504
533
  /**
505
534
  * Set "gzip" to compress a payload that is larger than the compression threshold.
506
535
  * Set "none" for an ingest endpoint that rejects gzip.
@@ -591,6 +620,20 @@ export interface ObservabilityConfig {
591
620
  * @see {@link OtelLoader}
592
621
  */
593
622
  otelLoader?: OtelLoader;
623
+ /**
624
+ * Gives attributes for each record that the library builds. Its values override `setContext()`
625
+ * values. The logger scope and the call payload override its values. The library calls it for
626
+ * each record that sampling keeps. Keep it fast and synchronous. A provider that throws, or
627
+ * that returns a value that is not an object, adds nothing to the record.
628
+ * @returns The attributes, or undefined for none.
629
+ */
630
+ contextProvider?: () => Record<string, unknown> | undefined;
631
+ /**
632
+ * Changes or drops a record. The processors run in list order, before `redact`. A processor has
633
+ * the contract of `redact`. If it throws or returns a value that is not a record, the library
634
+ * drops the record.
635
+ */
636
+ processors?: ((record: LogRecord) => LogRecord | null)[];
594
637
  /**
595
638
  * Rewrites or drops a record before the library sends it. If the hook throws or returns a
596
639
  * value that is not a record, the library drops the record.
@@ -604,8 +647,8 @@ export interface ObservabilityConfig {
604
647
  */
605
648
  onDiagnostic?: DiagnosticHandler;
606
649
  /**
607
- * Receives a summary when the library loses records that it built. Sampling, `minLevel` and
608
- * `redact` do not cause a loss. The library joins the losses of one reason in one task.
650
+ * Receives a summary when the library loses records that it built. Sampling, `minLevel`,
651
+ * `processors` and `redact` do not cause a loss. The library joins the losses of one reason in one task.
609
652
  * Do not log through the library in the hook. A record from the hook can evict a stored batch.
610
653
  * A batch that storage evicts during its send can still reach the server.
611
654
  * @param summary Reason, record count, batch ids, journey ids and action names of the loss.
@@ -619,6 +662,8 @@ export interface ResolvedConfig {
619
662
  endpoint: string | null;
620
663
  /** OTLP metrics endpoint URL. An empty string sends metric records as log records. */
621
664
  metricsEndpoint: string;
665
+ /** OTLP traces endpoint URL, or "" when the library sends no span. */
666
+ tracesEndpoint: string;
622
667
  /** The library reports this value as `service.name`. */
623
668
  serviceName: string;
624
669
  /** The library reports this value as `service.version`. */
@@ -629,6 +674,10 @@ export interface ResolvedConfig {
629
674
  enabled: boolean;
630
675
  /** Minimum level that the library logs. */
631
676
  minLevel: LogLevel;
677
+ /** Minimum level for each namespace prefix. */
678
+ minLevels: Record<string, LogLevel>;
679
+ /** Hooks that change or drop a record before `redact`. */
680
+ processors: NonNullable<ObservabilityConfig["processors"]>;
632
681
  /** "gzip" compresses a payload that is larger than the compression threshold. */
633
682
  compression: "gzip" | "none";
634
683
  /** The library passes this value to `fetch`. */
@@ -684,6 +733,8 @@ export interface ResolvedConfig {
684
733
  transportOnExit?: ExitTransport;
685
734
  /** Supplies the `@opentelemetry/api` module in place of importing it. */
686
735
  otelLoader?: OtelLoader;
736
+ /** Gives attributes for each record that the library builds. */
737
+ contextProvider?: ObservabilityConfig["contextProvider"];
687
738
  /**
688
739
  * Rewrites or drops a record before the library sends it.
689
740
  * @param record The record that the library is about to send.
@@ -5,7 +5,7 @@ export type LogLevel = "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL";
5
5
  * `event` is something that the application did. `metric` is a measurement.
6
6
  * `log` is a log call of the application. `system` is the output of this library.
7
7
  */
8
- export type LogType = "action" | "event" | "metric" | "log" | "system";
8
+ export type LogType = "action" | "event" | "metric" | "log" | "system" | "span";
9
9
  /** Metric value type: level, running total, or distribution. */
10
10
  export type MetricType = "gauge" | "counter" | "histogram";
11
11
  /** Internal record shape. A serializer converts it to the payload format. */
@@ -0,0 +1,47 @@
1
+ import type { OneLogger } from "../core/logger";
2
+ import type { Counter, Histogram, HistogramOptions, InstrumentOptions } from "./metric";
3
+ /** Tools that the library gives to a capture plugin. */
4
+ export interface PluginContext {
5
+ /** Logger for the namespace `uiobs.capture.<plugin name>`. */
6
+ logger: OneLogger;
7
+ /**
8
+ * Gives a counter. It is the same as `counter()`.
9
+ * @param name Metric name.
10
+ * @param options Unit of the values.
11
+ * @returns The counter.
12
+ */
13
+ counter(name: string, options?: InstrumentOptions): Counter;
14
+ /**
15
+ * Gives a histogram. It is the same as `histogram()`.
16
+ * @param name Metric name.
17
+ * @param options Unit of the values and the bucket boundaries.
18
+ * @returns The histogram.
19
+ */
20
+ histogram(name: string, options?: HistogramOptions): Histogram;
21
+ /**
22
+ * Adds a breadcrumb with the category `custom`. It is the same as `addBreadcrumb()`.
23
+ * @param message Description of the event.
24
+ * @param data Optional metadata.
25
+ */
26
+ addBreadcrumb(message: string, data?: Record<string, unknown>): void;
27
+ /**
28
+ * Runs a function. The network capture does not record a request that the function starts
29
+ * synchronously, and does not add `traceparent` to it. Use it for the requests of the plugin.
30
+ * @param fn Function that starts the request.
31
+ * @returns The return value of the function.
32
+ */
33
+ ownRequest<T>(fn: () => T): T;
34
+ }
35
+ /** Capture module from the app. The library installs it with the built-in capture modules. */
36
+ export interface CapturePlugin {
37
+ /** Name of the plugin. Its logger namespace and its diagnostic messages use it. */
38
+ readonly name: string;
39
+ /**
40
+ * Starts the capture. A later `configure()` that changes the capture section calls
41
+ * `uninstall()`, then calls `install()` again.
42
+ * @param ctx Tools of the plugin.
43
+ */
44
+ install(ctx: PluginContext): void;
45
+ /** Stops the capture. Restore each function that the plugin replaced. */
46
+ uninstall(): void;
47
+ }