@utk09/ui-observability 0.7.0 → 0.8.0

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 (122) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +122 -0
  3. package/dist/bus/bus.d.ts +30 -0
  4. package/dist/bus-CUXRY0JR.cjs +2 -0
  5. package/dist/bus-CUXRY0JR.cjs.map +1 -0
  6. package/dist/{bus-DfAbg_pg.js → bus-DPDrlUBY.js} +96 -50
  7. package/dist/bus-DPDrlUBY.js.map +1 -0
  8. package/dist/capture/console.d.ts +37 -0
  9. package/dist/capture/errors.d.ts +2 -4
  10. package/dist/capture/long-frames.d.ts +31 -0
  11. package/dist/capture/storm.d.ts +17 -0
  12. package/dist/capture/types.d.ts +2 -0
  13. package/dist/console-CNljJict.js +81 -0
  14. package/dist/console-CNljJict.js.map +1 -0
  15. package/dist/console-PKzc-FmR.cjs +2 -0
  16. package/dist/console-PKzc-FmR.cjs.map +1 -0
  17. package/dist/constants-B28fDv2F.cjs +2 -0
  18. package/dist/constants-B28fDv2F.cjs.map +1 -0
  19. package/dist/constants-Bu49bm39.js +93 -0
  20. package/dist/constants-Bu49bm39.js.map +1 -0
  21. package/dist/constants.d.ts +32 -2
  22. package/dist/core/breadcrumbs.d.ts +1 -1
  23. package/dist/core/pipeline.d.ts +2 -2
  24. package/dist/core/record.d.ts +3 -0
  25. package/dist/core/remote-rules.d.ts +17 -0
  26. package/dist/core/remote-sampling.d.ts +65 -0
  27. package/dist/core/runtime.d.ts +10 -4
  28. package/dist/core/sampling.d.ts +5 -2
  29. package/dist/core/sender.d.ts +3 -0
  30. package/dist/errors-C78ZTjet.cjs +3 -0
  31. package/dist/errors-C78ZTjet.cjs.map +1 -0
  32. package/dist/{errors-4MQyjZVj.js → errors-Dnc-X4Ec.js} +19 -20
  33. package/dist/errors-Dnc-X4Ec.js.map +1 -0
  34. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  35. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  36. package/dist/global-scope-dp2jADRl.js +19 -0
  37. package/dist/global-scope-dp2jADRl.js.map +1 -0
  38. package/dist/index.cjs +1 -1
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.js +287 -242
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexeddb-storage-D0p3iMD0.cjs +2 -0
  44. package/dist/{indexeddb-storage-CcEJlq2l.cjs.map → indexeddb-storage-D0p3iMD0.cjs.map} +1 -1
  45. package/dist/{indexeddb-storage-0LtUALBg.js → indexeddb-storage-uD4oaRMc.js} +10 -10
  46. package/dist/{indexeddb-storage-0LtUALBg.js.map → indexeddb-storage-uD4oaRMc.js.map} +1 -1
  47. package/dist/{interactions-BMNPQ3WH.cjs → interactions-CsE2y_fQ.cjs} +2 -2
  48. package/dist/{interactions-BMNPQ3WH.cjs.map → interactions-CsE2y_fQ.cjs.map} +1 -1
  49. package/dist/{interactions-BaCmoGLB.js → interactions-igKTAJvj.js} +2 -2
  50. package/dist/{interactions-BaCmoGLB.js.map → interactions-igKTAJvj.js.map} +1 -1
  51. package/dist/library-request-Br_T09Bn.cjs +2 -0
  52. package/dist/library-request-Br_T09Bn.cjs.map +1 -0
  53. package/dist/library-request-Dt0fXhcn.js +14 -0
  54. package/dist/library-request-Dt0fXhcn.js.map +1 -0
  55. package/dist/long-frames-6pnjWSSR.js +65 -0
  56. package/dist/long-frames-6pnjWSSR.js.map +1 -0
  57. package/dist/long-frames-DahhqM6u.cjs +2 -0
  58. package/dist/long-frames-DahhqM6u.cjs.map +1 -0
  59. package/dist/models/bus.d.ts +16 -0
  60. package/dist/models/config.d.ts +90 -0
  61. package/dist/network-CZ0aFUsy.cjs +2 -0
  62. package/dist/network-CZ0aFUsy.cjs.map +1 -0
  63. package/dist/{network-jQ2t8rU4.js → network-aSNbwpue.js} +16 -15
  64. package/dist/network-aSNbwpue.js.map +1 -0
  65. package/dist/{platform-YuByH8A5.js → platform-BwbMRwHm.js} +7 -7
  66. package/dist/{platform-YuByH8A5.js.map → platform-BwbMRwHm.js.map} +1 -1
  67. package/dist/{platform-ByQllE_W.cjs → platform-D_XkVIF6.cjs} +2 -2
  68. package/dist/{platform-ByQllE_W.cjs.map → platform-D_XkVIF6.cjs.map} +1 -1
  69. package/dist/remote-rules-5UA23alm.js +86 -0
  70. package/dist/remote-rules-5UA23alm.js.map +1 -0
  71. package/dist/remote-rules-rJJZKVG8.cjs +2 -0
  72. package/dist/remote-rules-rJJZKVG8.cjs.map +1 -0
  73. package/dist/sampling-E4x92Nn2.cjs +2 -0
  74. package/dist/sampling-E4x92Nn2.cjs.map +1 -0
  75. package/dist/sampling-J1eahbfT.js +160 -0
  76. package/dist/sampling-J1eahbfT.js.map +1 -0
  77. package/dist/sanitize-BMhh8ghJ.cjs +2 -0
  78. package/dist/sanitize-BMhh8ghJ.cjs.map +1 -0
  79. package/dist/sanitize-UJ-4Lb0n.js +114 -0
  80. package/dist/sanitize-UJ-4Lb0n.js.map +1 -0
  81. package/dist/sender-B6ufz26f.cjs +3 -0
  82. package/dist/sender-B6ufz26f.cjs.map +1 -0
  83. package/dist/{sender-BIob8eZz.js → sender-G6v4Uqi4.js} +304 -219
  84. package/dist/sender-G6v4Uqi4.js.map +1 -0
  85. package/dist/storm-BtzgLOCX.cjs +2 -0
  86. package/dist/storm-BtzgLOCX.cjs.map +1 -0
  87. package/dist/storm-DJkEZP_8.js +10 -0
  88. package/dist/storm-DJkEZP_8.js.map +1 -0
  89. package/dist/transport/custom-transport.d.ts +20 -0
  90. package/dist/transport/errors.d.ts +2 -1
  91. package/dist/transport/exit-flush.d.ts +15 -0
  92. package/dist/transport/http-transport.d.ts +2 -24
  93. package/dist/transport/memory-transport.d.ts +30 -0
  94. package/dist/transport/retry-engine.d.ts +2 -2
  95. package/dist/transport/serializers/select.d.ts +12 -1
  96. package/dist/transport/status-transport.d.ts +72 -0
  97. package/dist/utils/deadline.d.ts +7 -0
  98. package/dist/utils/global-scope.d.ts +20 -0
  99. package/dist/utils/library-console.d.ts +11 -0
  100. package/dist/utils/library-request.d.ts +12 -0
  101. package/package.json +1 -1
  102. package/dist/bus-DeZzr2bx.cjs +0 -2
  103. package/dist/bus-DeZzr2bx.cjs.map +0 -1
  104. package/dist/bus-DfAbg_pg.js.map +0 -1
  105. package/dist/constants-C8nZQBmQ.js +0 -86
  106. package/dist/constants-C8nZQBmQ.js.map +0 -1
  107. package/dist/constants-IBL_jd5R.cjs +0 -2
  108. package/dist/constants-IBL_jd5R.cjs.map +0 -1
  109. package/dist/errors-4MQyjZVj.js.map +0 -1
  110. package/dist/errors-CUdShXe7.cjs +0 -3
  111. package/dist/errors-CUdShXe7.cjs.map +0 -1
  112. package/dist/indexeddb-storage-CcEJlq2l.cjs +0 -2
  113. package/dist/network-DBNvxCE3.cjs +0 -2
  114. package/dist/network-DBNvxCE3.cjs.map +0 -1
  115. package/dist/network-jQ2t8rU4.js.map +0 -1
  116. package/dist/sampling-CbYySsZ1.js +0 -251
  117. package/dist/sampling-CbYySsZ1.js.map +0 -1
  118. package/dist/sampling-Cs50xsZl.cjs +0 -2
  119. package/dist/sampling-Cs50xsZl.cjs.map +0 -1
  120. package/dist/sender-BIob8eZz.js.map +0 -1
  121. package/dist/sender-iOjzcueM.cjs +0 -3
  122. package/dist/sender-iOjzcueM.cjs.map +0 -1
@@ -1,13 +1,14 @@
1
- import { Rt as e, S as t, b as n, x as r } from "./constants-C8nZQBmQ.js";
2
- import { t as i } from "./unref-16maCyKA.js";
1
+ import { Et as e, S as t, Wt as n, b as r, x as i } from "./constants-Bu49bm39.js";
2
+ import { t as a } from "./unref-16maCyKA.js";
3
+ import { n as o, t as s } from "./remote-rules-5UA23alm.js";
3
4
  //#region src/models/bus.ts
4
- function a(e) {
5
+ function c(e) {
5
6
  return {
6
7
  p: t,
7
8
  m: e
8
9
  };
9
10
  }
10
- function o(e) {
11
+ function l(e) {
11
12
  if (typeof e != "object" || !e) return null;
12
13
  let t = e;
13
14
  if (t.p !== "ui-observability/1" || typeof t.m != "object" || t.m === null) return null;
@@ -16,12 +17,12 @@ function o(e) {
16
17
  }
17
18
  //#endregion
18
19
  //#region src/bus/links.ts
19
- var s = Symbol.for(e);
20
- function c(e, t) {
20
+ var u = Symbol.for(n);
21
+ function d(e, t) {
21
22
  if (typeof window > "u" || window.parent === window) return null;
22
23
  let n;
23
24
  try {
24
- n = window.parent[s];
25
+ n = window.parent[u];
25
26
  } catch {
26
27
  return null;
27
28
  }
@@ -39,10 +40,10 @@ function c(e, t) {
39
40
  }
40
41
  };
41
42
  }
42
- function l(e, t) {
43
+ function f(e, t) {
43
44
  if (typeof window > "u" || window.parent === window) return null;
44
45
  let n = (t) => {
45
- let n = o(t.data);
46
+ let n = l(t.data);
46
47
  n && t.source === window.parent && e(n, {
47
48
  link: "parent",
48
49
  origin: t.origin
@@ -52,7 +53,7 @@ function l(e, t) {
52
53
  kind: "parent",
53
54
  post(e) {
54
55
  t.guard("bus.send_failed", "The postMessage call to the parent failed.", () => {
55
- window.parent.postMessage(a(e), "*");
56
+ window.parent.postMessage(c(e), "*");
56
57
  });
57
58
  },
58
59
  close() {
@@ -60,10 +61,10 @@ function l(e, t) {
60
61
  }
61
62
  };
62
63
  }
63
- function u(e, t, n) {
64
+ function p(e, t, n) {
64
65
  if (typeof window > "u") return null;
65
- let r = /* @__PURE__ */ new Set([window.location.origin, ...t]), i = /* @__PURE__ */ new Map(), s = (t) => {
66
- let a = o(t.data);
66
+ let r = /* @__PURE__ */ new Set([window.location.origin, ...t]), i = /* @__PURE__ */ new Map(), a = (t) => {
67
+ let a = l(t.data);
67
68
  a && (r.has(t.origin) ? (t.source && i.set(t.source, t.origin), e(a, {
68
69
  link: "children",
69
70
  origin: t.origin
@@ -72,27 +73,27 @@ function u(e, t, n) {
72
73
  type: a.t
73
74
  }));
74
75
  };
75
- return addEventListener("message", s), {
76
+ return addEventListener("message", a), {
76
77
  kind: "children",
77
78
  post(e) {
78
79
  for (let [t, r] of i) {
79
- let o = t;
80
- o.closed ? i.delete(t) : n.guard("bus.send_failed", "The postMessage call to a child frame failed.", () => {
81
- o.postMessage(a(e), r);
80
+ let a = t;
81
+ a.closed ? i.delete(t) : n.guard("bus.send_failed", "The postMessage call to a child frame failed.", () => {
82
+ a.postMessage(c(e), r);
82
83
  });
83
84
  }
84
85
  },
85
86
  close() {
86
- removeEventListener("message", s), i.clear();
87
+ removeEventListener("message", a), i.clear();
87
88
  }
88
89
  };
89
90
  }
90
- function d(e, t, n) {
91
+ function m(e, t, n) {
91
92
  let r = globalThis.BroadcastChannel;
92
93
  if (r === void 0) return null;
93
94
  let i = n.guard("bus.send_failed", "The library could not open the BroadcastChannel.", () => new r(e));
94
95
  return i ? (i.onmessage = (e) => {
95
- let n = o(e.data);
96
+ let n = l(e.data);
96
97
  n && t(n, {
97
98
  link: "broadcast",
98
99
  origin: "same-origin"
@@ -101,7 +102,7 @@ function d(e, t, n) {
101
102
  kind: "broadcast",
102
103
  post(e) {
103
104
  n.guard("bus.send_failed", "The BroadcastChannel.postMessage call failed.", () => {
104
- i.postMessage(a(e));
105
+ i.postMessage(c(e));
105
106
  });
106
107
  },
107
108
  close() {
@@ -111,13 +112,13 @@ function d(e, t, n) {
111
112
  }
112
113
  }) : null;
113
114
  }
114
- function f(e, t, n, r) {
115
+ function h(e, t, n, r) {
115
116
  let i = globalThis.fin?.InterApplicationBus;
116
117
  if (!i) return null;
117
118
  if (!t) return r.report("openfin.unavailable", "OpenFin gives no application uuid. The InterApplicationBus link stays closed."), null;
118
- let s = `${e}.${t}`;
119
- return r.guardAsync("bus.send_failed", "The InterApplicationBus.subscribe call failed.", () => i.subscribe({ uuid: t }, s, (e) => {
120
- let t = o(e);
119
+ let a = `${e}.${t}`;
120
+ return r.guardAsync("bus.send_failed", "The InterApplicationBus.subscribe call failed.", () => i.subscribe({ uuid: t }, a, (e) => {
121
+ let t = l(e);
121
122
  t && n(t, {
122
123
  link: "openfin",
123
124
  origin: "openfin"
@@ -125,15 +126,15 @@ function f(e, t, n, r) {
125
126
  })), {
126
127
  kind: "openfin",
127
128
  post(e) {
128
- r.guardAsync("bus.send_failed", "The InterApplicationBus.publish call failed.", () => i.publish(s, a(e)));
129
+ r.guardAsync("bus.send_failed", "The InterApplicationBus.publish call failed.", () => i.publish(a, c(e)));
129
130
  },
130
131
  close() {}
131
132
  };
132
133
  }
133
- function p(e, t) {
134
+ function g(e, t) {
134
135
  let n = globalThis, r = n.postMessage;
135
136
  return n.WorkerGlobalScope === void 0 || !r ? null : (n.addEventListener?.("message", (t) => {
136
- let n = o(t.data);
137
+ let n = l(t.data);
137
138
  n && e(n, {
138
139
  link: "owner",
139
140
  origin: "same-origin"
@@ -142,15 +143,15 @@ function p(e, t) {
142
143
  kind: "owner",
143
144
  post(e) {
144
145
  t.guard("bus.send_failed", "The postMessage call of the worker failed.", () => {
145
- r(a(e));
146
+ r(c(e));
146
147
  });
147
148
  },
148
149
  close() {}
149
150
  });
150
151
  }
151
- function m(e, t, n) {
152
+ function _(e, t, n) {
152
153
  let r = (e) => {
153
- let n = o(e.data);
154
+ let n = l(e.data);
154
155
  n && t(n, {
155
156
  link: "worker",
156
157
  origin: "same-origin"
@@ -160,7 +161,7 @@ function m(e, t, n) {
160
161
  kind: "worker",
161
162
  post(t) {
162
163
  n.guard("bus.send_failed", "The postMessage call to a worker failed.", () => {
163
- e.postMessage(a(t));
164
+ e.postMessage(c(t));
164
165
  });
165
166
  },
166
167
  close() {
@@ -170,14 +171,14 @@ function m(e, t, n) {
170
171
  }
171
172
  //#endregion
172
173
  //#region src/bus/bus.ts
173
- var h = {
174
- timeoutMs: r,
174
+ var v = {
175
+ timeoutMs: i,
175
176
  maxAttempts: 3
176
- }, g = [
177
+ }, y = [
177
178
  "children",
178
179
  "direct",
179
180
  "worker"
180
- ], _ = class {
181
+ ], b = class {
181
182
  config;
182
183
  diagnostics;
183
184
  platform;
@@ -191,8 +192,10 @@ var h = {
191
192
  openFinLink = null;
192
193
  isOpenFinProvider = !1;
193
194
  resolved = !1;
195
+ rulesPoll;
196
+ destroyed = !1;
194
197
  awaitingWelcome = null;
195
- constructor(e, t, n, r, i, a, o = h) {
198
+ constructor(e, t, n, r, i, a, o = v) {
196
199
  this.config = e, this.diagnostics = t, this.platform = n, this.contextId = r, this.tabId = i, this.handlers = a, this.handshakeOptions = o;
197
200
  }
198
201
  getRole() {
@@ -206,7 +209,7 @@ var h = {
206
209
  if (e.mode === "off") return this.role = "sender", this.resolved = !0, this.role;
207
210
  if (this.isOpenFinProvider = this.resolveOpenFinProvider(), e.mode === "sender" || e.mode === "forwarder") return this.role = e.mode, this.openControlLinks(), this.role === "forwarder" && (this.upstream = this.candidateUpstream(), this.upstream || this.diagnostics.report("bus.no_owner", "bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.")), this.resolved = !0, this.announce(), this.role;
208
211
  this.openControlLinks();
209
- let t = c(this.receive, this.diagnostics);
212
+ let t = d(this.receive, this.diagnostics);
210
213
  if (t) return this.role = "forwarder", this.upstream = t, this.resolved = !0, this.diagnostics.report("bus.role_resolved", "This context attached directly to the runtime of its same-origin parent.", {
211
214
  role: "forwarder",
212
215
  via: "direct"
@@ -249,10 +252,10 @@ var h = {
249
252
  from: this.contextId,
250
253
  journey: e
251
254
  }, n);
252
- } else this.receive(e, n);
255
+ } else e.t === "sampling?" ? t(this.rulesAnswer(e.from), n) : this.receive(e, n);
253
256
  }
254
257
  attachWorker(e) {
255
- this.links.push(m(e, this.receive, this.diagnostics));
258
+ this.links.push(_(e, this.receive, this.diagnostics));
256
259
  }
257
260
  broadcastJourney(e) {
258
261
  this.post({
@@ -262,6 +265,7 @@ var h = {
262
265
  });
263
266
  }
264
267
  destroy() {
268
+ this.destroyed = !0, clearInterval(this.rulesPoll), this.rulesPoll = void 0;
265
269
  for (let e of this.allLinks()) e.close();
266
270
  this.links.length = 0, this.upstream = null, this.openFinLink = null;
267
271
  }
@@ -303,6 +307,12 @@ var h = {
303
307
  });
304
308
  break;
305
309
  }
310
+ case "sampling?":
311
+ (this.role === "forwarder" ? t.link !== this.upstream?.kind : this.canOwn(t.link)) && this.postOver(t.link, this.rulesAnswer(e.from));
312
+ break;
313
+ case "sampling":
314
+ this.acceptsRules(e.to, t) && this.applyRules(e.rules);
315
+ break;
306
316
  case "tab": t.link === "broadcast" && e.tabId === this.tabId && this.contextId > e.from && this.handlers.onTabConflict();
307
317
  }
308
318
  };
@@ -310,7 +320,7 @@ var h = {
310
320
  return e === "direct" || e !== this.upstream?.kind;
311
321
  }
312
322
  canOwn(e) {
313
- return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : g.includes(e) : !1;
323
+ return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : y.includes(e) : !1;
314
324
  }
315
325
  resolveOpenFinProvider() {
316
326
  let e = this.config.bus.openFinRole;
@@ -331,30 +341,30 @@ var h = {
331
341
  }
332
342
  }
333
343
  candidateUpstream() {
334
- return this.platform.isWorker ? p(this.receive, this.diagnostics) : this.platform.isTopLevelDocument ? this.platform.platform === "openfin" && !this.isOpenFinProvider ? this.ensureOpenFinLink() : null : l(this.receive, this.diagnostics);
344
+ return this.platform.isWorker ? g(this.receive, this.diagnostics) : this.platform.isTopLevelDocument ? this.platform.platform === "openfin" && !this.isOpenFinProvider ? this.ensureOpenFinLink() : null : f(this.receive, this.diagnostics);
335
345
  }
336
346
  openControlLinks() {
337
347
  let e = (e) => {
338
348
  e && this.links.push(e);
339
349
  };
340
- this.platform.isTopLevelDocument && (e(u(this.receive, this.config.bus.trustedOrigins, this.diagnostics)), e(d(n, this.receive, this.diagnostics))), (this.platform.platform === "openfin" || this.platform.platform === "openfin_web") && e(this.ensureOpenFinLink());
350
+ this.platform.isTopLevelDocument && (e(p(this.receive, this.config.bus.trustedOrigins, this.diagnostics)), e(m(r, this.receive, this.diagnostics))), (this.platform.platform === "openfin" || this.platform.platform === "openfin_web") && e(this.ensureOpenFinLink());
341
351
  }
342
352
  ensureOpenFinLink() {
343
- return this.openFinLink ??= f(n, this.platform.openfinUuid, this.receive, this.diagnostics), this.openFinLink;
353
+ return this.openFinLink ??= h(r, this.platform.openfinUuid, this.receive, this.diagnostics), this.openFinLink;
344
354
  }
345
355
  handshake(e) {
346
356
  return new Promise((t) => {
347
357
  let n = !1, r = (e) => {
348
- n || (n = !0, this.awaitingWelcome = null, clearTimeout(a), t(e));
358
+ n || (n = !0, this.awaitingWelcome = null, clearTimeout(i), t(e));
349
359
  };
350
360
  this.awaitingWelcome = {
351
361
  link: e.kind,
352
362
  settle: r
353
363
  };
354
- let a = setTimeout(() => {
364
+ let i = setTimeout(() => {
355
365
  r(!1);
356
366
  }, this.handshakeOptions.timeoutMs);
357
- i(a), e.post({
367
+ a(i), e.post({
358
368
  t: "hello",
359
369
  from: this.contextId,
360
370
  tabId: this.tabId
@@ -369,10 +379,46 @@ var h = {
369
379
  }), this.post({
370
380
  t: "journey?",
371
381
  from: this.contextId
372
- });
382
+ }), this.pollRules();
383
+ }
384
+ rulesAnswer(e) {
385
+ let t = this.handlers.remote.sampling?.wire() ?? null;
386
+ return {
387
+ t: "sampling",
388
+ from: this.contextId,
389
+ to: e,
390
+ rules: t
391
+ };
392
+ }
393
+ acceptsRules(e, t) {
394
+ if (this.role !== "forwarder" || e !== this.contextId || t.link !== this.upstream?.kind) return !1;
395
+ let { origin: n } = t;
396
+ return t.link === "parent" && n !== location.origin && !this.config.bus.trustedOrigins.includes(n) ? (this.diagnostics.report("bus.untrusted_origin", `The bus ignored sampling rules from ${n}. If you own this origin, add it to bus.trustedOrigins.`, {
397
+ origin: n,
398
+ type: "sampling"
399
+ }), !1) : !0;
400
+ }
401
+ applyRules(e) {
402
+ if (e === null) {
403
+ s(this.handlers.remote, this.config, null);
404
+ return;
405
+ }
406
+ let t = o(e, this.diagnostics);
407
+ t && s(this.handlers.remote, this.config, t);
408
+ }
409
+ pollRules() {
410
+ let { upstream: t } = this;
411
+ if (this.destroyed || this.role !== "forwarder" || !t) return;
412
+ let n = () => {
413
+ this.config.sampling.remote && t.post({
414
+ t: "sampling?",
415
+ from: this.contextId
416
+ });
417
+ };
418
+ n(), this.rulesPoll = setInterval(n, e), a(this.rulesPoll);
373
419
  }
374
420
  };
375
421
  //#endregion
376
- export { _ as Bus };
422
+ export { b as Bus };
377
423
 
378
- //# sourceMappingURL=bus-DfAbg_pg.js.map
424
+ //# sourceMappingURL=bus-DPDrlUBY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus-DPDrlUBY.js","names":["REMOTE_SAMPLING_POLL_MS","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","unrefTimer","parseRemoteRules","applyRemote","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","createDirectLink","host","target","open","diagnostics","receive","createParentLink","onMessage","event","createChildrenLink","trusted","trustedOrigins","sources","source","origin","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","createOwnerLink","scope","send","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","reply","current","link","configured","me","push","settled","finish","timer","resolve","result","rules","to","update","upstream","ask"],"sources":["../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL } from \"../constants\";\nimport type { Journey } from \"../core/journey\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role indicating whether this context sends records directly or forwards upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel. The bus uses it to route incoming and outgoing messages.\n * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe\n * looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Inbound transport channel kind. */\n link: LinkKind;\n /** `event.origin` for `parent` and `children`. Other links use `\"same-origin\"` or `\"openfin\"`. */\n origin: string;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: \"hello\"; from: string; tabId: string }\n /**\n * Handshake response from an upstream owner. The `to` field holds the address.\n * A welcome on InterApplicationBus goes to every subscriber. Without an address,\n * each waiting view accepts the welcome as its own.\n */\n | { t: \"welcome\"; from: string; to: string; tabId: string }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: \"records\"; from: string; records: LogRecord[] }\n /** Broadcast update announcing a new or ended journey state. */\n | { t: \"journey\"; from: string; journey: Journey | null }\n /** Query requesting active journey state from connected peers. */\n | { t: \"journey?\"; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: \"tab\"; from: string; tabId: string }\n /** Request of a forwarder for the remote sampling rules in force. */\n | { t: \"sampling?\"; from: string }\n /**\n * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field\n * holds the address of the forwarder that asked. The receiver validates `rules` again.\n * Null rules end the copy of the forwarder.\n */\n | { t: \"sampling\"; from: string; to: string; rules: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A\n * document gets `message` events from all embedded content on the page. This\n * includes analytics tags, video players and extensions. Without the tag check,\n * the bus parses a message from a video player as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\n\n/** Bidirectional communication channel for bus message transport. */\nexport interface Link {\n /** Channel transport kind. */\n readonly kind: LinkKind;\n\n /**\n * Sends a message over the channel without throwing.\n * @param message Bus message to transmit.\n */\n post(message: BusMessage): void;\n\n /** Releases listeners, subscriptions, or channels held open by the link. */\n close(): void;\n}\n\n/**\n * Callback invoked when a bus message arrives on a link.\n * @param message Received bus message.\n * @param source Origin and link metadata.\n */\nexport type Receive = (message: BusMessage, source: MessageSource) => void;\n\n/** Interface that a same-origin parent runtime exposes on a global symbol. */\nexport interface DirectHost {\n /**\n * Accepts a message directly from a child frame and replies synchronously.\n * @param message Child bus message.\n * @param reply Callback for synchronous response.\n */\n busAccept(message: BusMessage, reply: Receive): void;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n const target = host;\n let open = true;\n\n return {\n kind: \"direct\",\n post(message) {\n if (!open) {\n return;\n }\n\n // Stops an error in the parent runtime from breaking a logging call in the child.\n diagnostics.guard(\n \"bus.send_failed\",\n \"The direct call into the parent runtime failed.\",\n () => {\n target.busAccept(message, receive);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to the parent window.\n * @param receive Callback for incoming parent messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to parent window, or null if running in top-level window.\n */\nexport function createParentLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n // This context trusts the parent because it selected the parent as its upstream.\n if (message && event.source === window.parent) {\n receive(message, { link: \"parent\", origin: event.origin });\n }\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // An outbound \"*\" target is safe. The payload holds only this context's records.\n // The parent already gets these records by another path.\n // For inbound trust, see createChildrenLink.\n window.parent.postMessage(envelope(message), \"*\");\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n const trusted = new Set([window.location.origin, ...trustedOrigins]);\n // The map keeps the origin of each source.\n // A child that navigates must not get the ids of its previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n if (!trusted.has(event.origin)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored a message from ${event.origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin: event.origin, type: message.t },\n );\n return;\n }\n\n if (event.source) {\n sources.set(event.source, event.origin);\n }\n receive(message, { link: \"children\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n continue;\n }\n diagnostics.guard(\n \"bus.send_failed\",\n \"The postMessage call to a child frame failed.\",\n () => {\n // Targets the last known origin of the child. The browser drops the\n // message if the child navigated to a different origin.\n target.postMessage(envelope(message), origin);\n },\n );\n }\n },\n close() {\n removeEventListener(\"message\", onMessage);\n sources.clear();\n },\n };\n}\n\n/**\n * Creates a same-origin BroadcastChannel link for cross-tab control messages.\n * @param channelName BroadcastChannel identifier.\n * @param receive Callback for incoming cross-tab messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Broadcast link, or null if unsupported.\n */\nexport function createBroadcastLink(\n channelName: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const BC = (globalThis as { BroadcastChannel?: typeof BroadcastChannel }).BroadcastChannel;\n if (typeof BC === \"undefined\") {\n return null;\n }\n\n const channel = diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not open the BroadcastChannel.\",\n () => new BC(channelName),\n );\n if (!channel) {\n return null;\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"broadcast\", origin: \"same-origin\" });\n }\n };\n\n return {\n kind: \"broadcast\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The BroadcastChannel.postMessage call failed.\", () => {\n channel.postMessage(envelope(message));\n });\n },\n close() {\n diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not close the BroadcastChannel.\",\n () => {\n channel.close();\n },\n );\n },\n };\n}\n\n/** Structural interface for OpenFin InterApplicationBus operations. */\ninterface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/**\n * Creates an OpenFin InterApplicationBus link scoped to one application.\n * @param topic InterApplicationBus topic prefix.\n * @param appUuid OpenFin application uuid owning this context.\n * @param receive Callback for received topic messages.\n * @param diagnostics Diagnostics reporter.\n * @returns OpenFin link, or null if InterApplicationBus or the identity is unavailable.\n */\nexport function createOpenFinLink(\n topic: string,\n appUuid: string | undefined,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const fin = (globalThis as { fin?: { InterApplicationBus?: FinIab } }).fin;\n const iab = fin?.InterApplicationBus;\n if (!iab) {\n return null;\n }\n if (!appUuid) {\n // publish() sends to every subscriber on the runtime. Without a uuid scope,\n // this link shares the bus of this app with all other apps.\n diagnostics.report(\n \"openfin.unavailable\",\n \"OpenFin gives no application uuid. The InterApplicationBus link stays closed.\",\n );\n return null;\n }\n\n // The topic and the subscriber identity both contain the uuid. The topic keeps\n // messages of this app from other apps. The identity rejects messages from other apps.\n const scoped = `${topic}.${appUuid}`;\n\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.subscribe call failed.\",\n () =>\n iab.subscribe({ uuid: appUuid }, scoped, (raw) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, { link: \"openfin\", origin: \"openfin\" });\n }\n }),\n );\n\n return {\n kind: \"openfin\",\n post(message) {\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.publish call failed.\",\n () => iab.publish(scoped, envelope(message)),\n );\n },\n close() {\n // OpenFin removes the subscriptions when the context closes.\n },\n };\n}\n\n/**\n * Creates the worker-side link pointing at the document that created this\n * worker. Emits `kind: \"owner\"`.\n * @param receive Callback for incoming messages from the owning document.\n * @param diagnostics Diagnostics reporter.\n * @returns Owner link, or null outside a DedicatedWorkerGlobalScope.\n */\nexport function createOwnerLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n const scope = globalThis as unknown as {\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: string, listener: (event: MessageEvent) => void) => void;\n WorkerGlobalScope?: unknown;\n };\n const send = scope.postMessage;\n if (typeof scope.WorkerGlobalScope === \"undefined\" || !send) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"owner\", origin: \"same-origin\" });\n }\n };\n scope.addEventListener?.(\"message\", onMessage);\n\n return {\n kind: \"owner\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call of the worker failed.\", () => {\n send(envelope(message));\n });\n },\n close() {\n // Worker scope listeners stop when the worker stops.\n },\n };\n}\n\n/**\n * Creates the document-side link pointing at one attached worker or port.\n * Emits `kind: \"worker\"`.\n * @param worker Target worker instance or MessagePort.\n * @param receive Callback for messages from the worker.\n * @param diagnostics Diagnostics reporter.\n * @returns Document-to-worker link.\n */\nexport function createWorkerLink(\n worker: WorkerLike,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link {\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"worker\", origin: \"same-origin\" });\n }\n };\n worker.addEventListener(\"message\", onMessage);\n\n // Starts delivery on a MessagePort. A Worker has no start method.\n worker.start?.();\n\n return {\n kind: \"worker\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a worker failed.\", () => {\n worker.postMessage(envelope(message));\n });\n },\n close() {\n worker.removeEventListener(\"message\", onMessage);\n },\n };\n}\n","// src/bus/bus.ts\n//\n// Resolves the bus role and routes messages between realms.\n\nimport {\n BUS_CHANNEL_NAME,\n BUS_HANDSHAKE_TIMEOUT_MS,\n BUS_MAX_HANDSHAKE_ATTEMPTS,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { Journey } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport {\n createBroadcastLink,\n createChildrenLink,\n createDirectLink,\n createOpenFinLink,\n createOwnerLink,\n createParentLink,\n createWorkerLink,\n type Link,\n type Receive,\n type WorkerLike,\n} from \"./links\";\n\n/** Handshake timing for a forwarder waiting on an owner. */\nexport interface HandshakeOptions {\n /** Maximum time that a forwarder waits for an owner to answer, in milliseconds. */\n timeoutMs: number;\n /** Attempts allowed before a cross-origin forwarder promotes itself to sender. */\n maxAttempts: number;\n}\n\n/** Default handshake timing. Tests build a bus with shorter values. */\nexport const HANDSHAKE_OPTIONS: HandshakeOptions = {\n timeoutMs: BUS_HANDSHAKE_TIMEOUT_MS,\n maxAttempts: BUS_MAX_HANDSHAKE_ATTEMPTS,\n};\n\n/** Callbacks for handling records and journey events from connected realms. */\nexport interface BusHandlers {\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Structural shape of fin.me identity metadata. */\ninterface OpenFinMe {\n isView?: boolean;\n identity?: { uuid?: string; name?: string };\n}\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Current bus role. The default is \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** Indicates whether this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Indicates whether role resolution has completed. */\n private resolved = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(). A handshake that ends later must not start a timer. */\n private destroyed = false;\n /** Active handshake state awaiting welcome response. */\n private awaitingWelcome: {\n link: LinkKind;\n settle: (ok: boolean) => void;\n } | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param platform Platform runtime metadata.\n * @param contextId Unique context identifier for loop prevention.\n * @param tabId Tab identifier announced on broadcast channels.\n * @param handlers Callbacks for routed bus events.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n private readonly platform: PlatformMetadata,\n private readonly contextId: string,\n private readonly tabId: string,\n private readonly handlers: BusHandlers,\n private readonly handshakeOptions: HandshakeOptions = HANDSHAKE_OPTIONS,\n ) {}\n\n /** Returns the resolved bus role. */\n getRole(): BusRole {\n return this.role;\n }\n\n /** Returns whether role resolution has completed. */\n isResolved(): boolean {\n return this.resolved;\n }\n\n /**\n * Resolves bus role and establishes control links.\n * @returns Resolved role.\n */\n async start(): Promise<BusRole> {\n const { bus } = this.config;\n\n if (bus.mode === \"off\") {\n this.role = \"sender\";\n this.resolved = true;\n return this.role;\n }\n\n this.isOpenFinProvider = this.resolveOpenFinProvider();\n\n if (bus.mode === \"sender\" || bus.mode === \"forwarder\") {\n this.role = bus.mode;\n this.openControlLinks();\n if (this.role === \"forwarder\") {\n this.upstream = this.candidateUpstream();\n if (!this.upstream) {\n this.diagnostics.report(\n \"bus.no_owner\",\n 'bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.',\n );\n }\n }\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n this.openControlLinks();\n\n // A same-origin parent runtime accepts a direct synchronous link.\n const direct = createDirectLink(this.receive, this.diagnostics);\n if (direct) {\n this.role = \"forwarder\";\n this.upstream = direct;\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"This context attached directly to the runtime of its same-origin parent.\",\n {\n role: \"forwarder\",\n via: \"direct\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const candidate = this.candidateUpstream();\n\n if (!candidate) {\n this.role = \"sender\";\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"No owner exists. This context sends its own records.\",\n {\n role: \"sender\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const attempts = this.orphanPolicy() === \"retry\" ? this.handshakeOptions.maxAttempts : 1;\n\n let welcomed = false;\n for (let attempt = 0; attempt < attempts && !welcomed; attempt++) {\n welcomed = await this.handshake(candidate);\n }\n\n this.role = welcomed ? \"forwarder\" : \"sender\";\n this.upstream = welcomed ? candidate : null;\n if (!welcomed) {\n // OpenFin link remains open for control messages.\n if (candidate !== this.openFinLink) {\n candidate.close();\n }\n this.diagnostics.report(\n \"bus.handshake_timeout\",\n `No owner answered after ${String(attempts)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,\n { via: candidate.kind, crossOrigin: this.isCrossOriginFrame() },\n );\n }\n this.diagnostics.report(\"bus.role_resolved\", `The bus role is ${this.role}.`, {\n role: this.role,\n via: welcomed ? candidate.kind : \"none\",\n });\n\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n /**\n * Forwards records to the upstream owner if configured.\n * @param records Batch of log records to send.\n */\n sendRecords(records: LogRecord[]): void {\n this.upstream?.post({ t: \"records\", from: this.contextId, records });\n }\n\n /**\n * Synchronously processes direct messages from same-origin child contexts.\n * @param message Received bus message.\n * @param reply Direct response callback.\n */\n acceptDirect(message: BusMessage, reply: Receive): void {\n if (message.from === this.contextId) {\n return;\n }\n const source: MessageSource = { link: \"direct\", origin: \"same-origin\" };\n\n if (message.t === \"hello\") {\n if (this.canOwn(\"direct\")) {\n reply(\n {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n },\n source,\n );\n }\n return;\n }\n if (message.t === \"journey?\") {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n reply({ t: \"journey\", from: this.contextId, journey: current }, source);\n }\n return;\n }\n // A direct link has no channel from the parent to the child. The parent answers here.\n if (message.t === \"sampling?\") {\n reply(this.rulesAnswer(message.from), source);\n return;\n }\n this.receive(message, source);\n }\n\n /**\n * Connects a worker instance to the bus control plane.\n * @param worker Worker instance.\n */\n attachWorker(worker: WorkerLike): void {\n this.links.push(createWorkerLink(worker, this.receive, this.diagnostics));\n }\n\n /**\n * Broadcasts journey state changes to all connected links.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.post({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Broadcasts a message across all open links. */\n private post(message: BusMessage): void {\n for (const link of this.allLinks()) {\n link.post(message);\n }\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case \"hello\":\n if (this.canOwn(source.link)) {\n this.postOver(source.link, {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n });\n }\n break;\n\n case \"welcome\":\n if (message.to !== this.contextId) {\n break;\n }\n if (this.awaitingWelcome?.link === source.link) {\n this.awaitingWelcome.settle(true);\n }\n break;\n\n case \"records\":\n if (this.role === \"sender\") {\n this.handlers.onRecords(message.records);\n } else if (this.upstream && this.canRelay(source.link)) {\n // Relays records upstream in nested frame chains.\n this.upstream.post(message);\n }\n break;\n\n case \"journey\":\n this.handlers.onJourney(message.journey);\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n if (current) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n journey: current,\n });\n }\n break;\n }\n\n case \"sampling?\":\n // A forwarder answers only its own children. A sibling on its upstream link asks too.\n // A sibling answer on OpenFin gives N squared messages, and a stale copy can win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.postOver(source.link, this.rulesAnswer(message.from));\n }\n break;\n\n case \"sampling\":\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case \"tab\":\n // A collision applies only to two different contexts on the broadcast channel.\n // The id comparison selects one context of the pair.\n // Without it, both contexts report the conflict and rename.\n if (\n source.link === \"broadcast\" &&\n message.tabId === this.tabId &&\n this.contextId > message.from\n ) {\n this.handlers.onTabConflict();\n }\n break;\n }\n };\n\n /**\n * Tells whether records from a link can go upstream. Records that go back on\n * their arrival link return to their sender. A direct link is an exception.\n * Each direct link is one call into one parent. Thus two direct links in a\n * chain are different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Returns whether this context can accept ownership over the given link type. */\n private canOwn(link: LinkKind): boolean {\n if (this.role !== \"sender\") {\n return false;\n }\n if (link === \"openfin\") {\n return this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Resolves whether this context represents the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = (globalThis as { fin?: { me?: OpenFinMe } }).fin?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests whether the parent window is inaccessible due to cross-origin boundaries. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. Lint rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (this.platform.isTopLevelDocument) {\n push(createChildrenLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics));\n push(createBroadcastLink(BUS_CHANNEL_NAME, this.receive, this.diagnostics));\n }\n if (this.platform.platform === \"openfin\" || this.platform.platform === \"openfin_web\") {\n push(this.ensureOpenFinLink());\n }\n }\n\n /** Returns the singleton OpenFin InterApplicationBus link. */\n private ensureOpenFinLink(): Link | null {\n this.openFinLink ??= createOpenFinLink(\n BUS_CHANNEL_NAME,\n this.platform.openfinUuid,\n this.receive,\n this.diagnostics,\n );\n return this.openFinLink;\n }\n\n /**\n * Executes a hello/welcome handshake over candidate link.\n * @param candidate Upstream link candidate.\n * @returns True if welcome response arrived before timeout.\n */\n private handshake(candidate: Link): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (result: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n this.awaitingWelcome = null;\n clearTimeout(timer);\n resolve(result);\n };\n\n this.awaitingWelcome = { link: candidate.kind, settle: finish };\n // finish reads timer, which the code declares after finish. This order is safe.\n // finish can run only after the post below. The timer exists at that time.\n const timer = setTimeout(() => {\n finish(false);\n }, this.handshakeOptions.timeoutMs);\n unrefTimer(timer);\n candidate.post({ t: \"hello\", from: this.contextId, tabId: this.tabId });\n });\n }\n\n /** Broadcasts tab claim and queries existing journey state. */\n private announce(): void {\n this.postOver(\"broadcast\", {\n t: \"tab\",\n from: this.contextId,\n tabId: this.tabId,\n });\n this.post({ t: \"journey?\", from: this.contextId });\n this.pollRules();\n }\n\n /**\n * Builds the answer to a sampling question. Null rules end the copy of the forwarder.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: \"sampling\", from: this.contextId, to, rules };\n }\n\n /**\n * Tests whether this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link is not trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. It must not lower minLevel and read the records.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== location.origin &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Applies the rules of an answer. It ignores rules that are not valid.\n * @param raw Rules of the answer, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then at each poll interval.\n * A direct link cannot push the rules to a child. A poll works on each link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config at each poll. A later configure() can turn remote sampling on or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: \"sampling?\", from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":";;;;AAgFA,SAAgBQ,EAAS,GAAkC;CACzD,OAAO;EAAE,GAAGP;EAAc,GAAGQ;CAAQ;AACvC;AAUA,SAAgBC,EAAO,GAAkC;CACvD,IAAI,OAAOC,KAAS,aAAYA,GAC9B,OAAO;CAIT,IAAMC,IAAUD;CAChB,IAAIC,EAAQ,MAAA,wBAAsB,OAAOA,EAAQ,KAAM,YAAYA,EAAQ,MAAM,MAC/E,OAAO;CAGT,IAAMH,IAAUG,EAAQ;CAKxB,OAJI,OAAOH,EAAQ,KAAM,WAIlBA,IAHE;AAIX;;;ACpCA,IAAMI,IAAc,OAAO,IAAIX,CAAkB;AAQjD,SAAgBY,EAAiB,GAAkB,GAAuC;CACxF,IAAI,OAAO,SAAW,OAAe,OAAO,WAAW,QACrD,OAAO;CAGT,IAAIC;CACJ,IAAI;EAEF,IADqB,OAAO,OACRF;CACtB,QAAQ;EAEN,OAAO;CACT;CACA,IAAI,OAAOE,GAAM,aAAc,YAC7B,OAAO;CAGT,IAAMC,IAASD,GACXE,IAAO;CAEX,OAAO;EACL,MAAM;EACN,KAAK,GAAS;GACZ,AAAKA,KAKLC,EAAY,MACV,mBACA,yDACM;IACJ,EAAO,UAAUT,GAASU,CAAO;GACnC,CACF;EACF;EACA,QAAQ;GACN,IAAO;EACT;CACF;AACF;AAQA,SAAgBC,EAAiB,GAAkB,GAAuC;CACxF,IAAI,OAAO,SAAW,OAAe,OAAO,WAAW,QACrD,OAAO;CAGT,IAAMC,KAAa,MAA8B;EAC/C,IAAMZ,IAAUC,EAAOY,EAAM,IAAI;EAEjC,AAAIb,KAAWa,EAAM,WAAW,OAAO,UACrCH,EAAQV,GAAS;GAAE,MAAM;GAAU,QAAQa,EAAM;EAAO,CAAC;CAE7D;C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Y,GAAgC;EAE/D,IAAI,KAAK,SAAS,eAAeC,MAAO,KAAK,aAAa5C,EAAO,SAAS,KAAK,UAAU,MACvF,OAAO;EAIT,IAAM,EAAE,cAAWA;EAenB,OAZEA,EAAO,SAAS,YAChBC,MAAW,SAAS,UACpB,CAAC,KAAK,OAAO,IAAI,eAAe,SAASA,CAAM,KAE/C,KAAK,YAAY,OACf,wBACA,uCAAuCA,EAAO,0DAC9C;GAAE;GAAQ,MAAM;EAAW,CAC7B,GACO,MAGF;CACT;CAMA,WAAmB,GAAoB;EACrC,IAAIU,MAAQ,MAAM;GAChB,EAAY,KAAK,SAAS,QAAQ,KAAK,QAAQ,IAAI;GACnD;EACF;EAEA,IAAMkC,IAASlE,EAAiBgC,GAAK,KAAK,WAAW;EAErD,AAAIkC,KACFjE,EAAY,KAAK,SAAS,QAAQ,KAAK,QAAQiE,CAAM;CAEzD;CAMA,YAA0B;EACxB,IAAM,EAAE,gBAAa;EAErB,IAAI,KAAK,aAAa,KAAK,SAAS,eAAe,CAACC,GAClD;EAIF,IAAMC,UAAkB;GACtB,AAAI,KAAK,OAAO,SAAS,UACvBD,EAAS,KAAK;IAAE,GAAG;IAAa,MAAM,KAAK;GAAU,CAAC;EAE1D;EAIA,AAFAC,EAAI,GACJ,KAAK,YAAY,YAAYA,GAAK1E,CAAuB,GACzDK,EAAW,KAAK,SAAS;CAC3B;AACF"}
@@ -0,0 +1,37 @@
1
+ import type { Capture, CaptureContext } from "./types";
2
+ /** Wraps the selected console methods. It records each call as a record or a breadcrumb. */
3
+ export declare class ConsoleCapture implements Capture {
4
+ private readonly ctx;
5
+ /** Capture module identifier. */
6
+ readonly name = "console";
7
+ /** Active wrappers. A wrapper that is not in this map calls only the original. */
8
+ private readonly wrapped;
9
+ /** Prevents a second wrap on a wrapped method. */
10
+ private installed;
11
+ /** Rate limit of this capture. Console noise must not use the allowance of the error capture. */
12
+ private readonly window;
13
+ /**
14
+ * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.
15
+ */
16
+ constructor(ctx: CaptureContext);
17
+ /** Wraps each selected method. */
18
+ install(): void;
19
+ /** Restores each method that still holds the wrapper of this capture. */
20
+ uninstall(): void;
21
+ /**
22
+ * Reads the methods from the configuration. It reports a value that is not usable.
23
+ * @returns Methods to wrap, with no duplicates.
24
+ */
25
+ private readMethods;
26
+ /**
27
+ * Replaces one console method with a wrapper that calls the original first.
28
+ * @param method Console method to wrap.
29
+ */
30
+ private wrap;
31
+ /**
32
+ * Records one console call.
33
+ * @param method Console method of the call.
34
+ * @param args Arguments of the call.
35
+ */
36
+ private record;
37
+ }
@@ -8,10 +8,8 @@ export declare class ErrorCapture implements Capture {
8
8
  private installed;
9
9
  /** Recently reported error signatures in LRU order. */
10
10
  private readonly seen;
11
- /** Start timestamp of the active throttling window in epoch milliseconds. */
12
- private windowStart;
13
- /** Errors reported during the active throttling window. */
14
- private windowCount;
11
+ /** Rate limit of this capture. Console noise has its own window and cannot use it. */
12
+ private readonly window;
15
13
  /**
16
14
  * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.
17
15
  */
@@ -0,0 +1,31 @@
1
+ import type { Capture, CaptureContext } from "./types";
2
+ /** Records each long animation frame as a histogram metric and a breadcrumb. */
3
+ export declare class LongFrameCapture implements Capture {
4
+ private readonly ctx;
5
+ /** Capture module identifier. */
6
+ readonly name = "long-frames";
7
+ /** Active observer. Undefined when the capture is not installed. */
8
+ private observer;
9
+ /** Rate limit of this capture. A frozen tab must not flood the pipeline. */
10
+ private readonly window;
11
+ /** Minimum frame duration to record, in milliseconds. */
12
+ private threshold;
13
+ /**
14
+ * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.
15
+ */
16
+ constructor(ctx: CaptureContext);
17
+ /** Observes the best entry type that the browser supports. */
18
+ install(): void;
19
+ /** Disconnects the observer. */
20
+ uninstall(): void;
21
+ /**
22
+ * Reads the threshold from the configuration. It reports a value that is not usable.
23
+ * @returns Minimum frame duration to record, in milliseconds.
24
+ */
25
+ private readThreshold;
26
+ /**
27
+ * Records one frame at or above the threshold.
28
+ * @param entry Long animation frame or long task entry.
29
+ */
30
+ private record;
31
+ }
@@ -0,0 +1,17 @@
1
+ import type { Diagnostics } from "../core/diagnostics";
2
+ /** State of one fixed window. Captures that share a limit share one object. */
3
+ export interface StormWindow {
4
+ /** Start of the current window, in epoch milliseconds. */
5
+ start: number;
6
+ /** Events counted in the current window. */
7
+ count: number;
8
+ }
9
+ /**
10
+ * Counts one event in a fixed window. It reports each event over the limit.
11
+ * @param window Window state to change.
12
+ * @param limit Maximum events in each window.
13
+ * @param diagnostics Diagnostics reporter.
14
+ * @param what Plural name of the events, for the diagnostic message.
15
+ * @returns False when the window has no allowance left. The caller must drop the event.
16
+ */
17
+ export declare function allowInWindow(window: StormWindow, limit: number, diagnostics: Diagnostics, what: string): boolean;
@@ -54,6 +54,8 @@ export interface CaptureOnce {
54
54
  webVitals: boolean;
55
55
  /** True after the library reports navigation timing. */
56
56
  navigationTiming: boolean;
57
+ /** True after the first long frame install. Only that install reads buffered frames. */
58
+ longFrames: boolean;
57
59
  }
58
60
  /** Shared runtime dependencies provided to auto-capture instances. */
59
61
  export interface CaptureContext {
@@ -0,0 +1,81 @@
1
+ import { a as e, i as t, o as n } from "./sanitize-UJ-4Lb0n.js";
2
+ import { t as r } from "./storm-DJkEZP_8.js";
3
+ //#region src/capture/console.ts
4
+ var i = [
5
+ "error",
6
+ "warn",
7
+ "info",
8
+ "log"
9
+ ], a = ["error", "warn"];
10
+ function o(t, n) {
11
+ return (...r) => {
12
+ Reflect.apply(t, console, r), !e() && n.record?.(r);
13
+ };
14
+ }
15
+ var s = class {
16
+ ctx;
17
+ name = "console";
18
+ wrapped = /* @__PURE__ */ new Map();
19
+ installed = !1;
20
+ window = {
21
+ start: 0,
22
+ count: 0
23
+ };
24
+ constructor(e) {
25
+ this.ctx = e;
26
+ }
27
+ install() {
28
+ if (!(this.installed || typeof console > "u")) {
29
+ this.installed = !0;
30
+ for (let e of this.readMethods()) this.wrap(e);
31
+ }
32
+ }
33
+ uninstall() {
34
+ if (this.installed) {
35
+ this.installed = !1;
36
+ for (let [e, { original: t, wrapper: n, target: r }] of this.wrapped) r.record = null, console[e] === n ? console[e] = t : this.ctx.diagnostics.report("capture.install_failed", `Another script wrapped console.${e} after the library. The library leaves that wrapper in place.`);
37
+ this.wrapped.clear();
38
+ }
39
+ }
40
+ readMethods() {
41
+ let e = this.ctx.config.capture.console;
42
+ return e === !0 ? a : Array.isArray(e) && e.every((e) => i.includes(e)) ? [...new Set(e)] : (this.ctx.diagnostics.report("config.invalid", "capture.console must be true, false or a list of \"error\", \"warn\", \"info\" and \"log\". The console capture is off."), []);
43
+ }
44
+ wrap(e) {
45
+ let t = console[e], r = { record: (t) => {
46
+ n(() => {
47
+ this.ctx.diagnostics.guard("capture.record_failed", `The library could not record a console.${e} call.`, () => {
48
+ this.record(e, t);
49
+ });
50
+ });
51
+ } }, i = o(t, r);
52
+ this.wrapped.set(e, {
53
+ original: t,
54
+ wrapper: i,
55
+ target: r
56
+ }), console[e] = i;
57
+ }
58
+ record(e, n) {
59
+ let i = n.findIndex((e) => e instanceof Error), a = n.findIndex((e) => typeof e == "string"), o = n[i], s = n[a] ?? o?.message ?? `console.${e}`;
60
+ if (e === "info" || e === "log") {
61
+ this.ctx.breadcrumbs.push({
62
+ t: Date.now(),
63
+ category: "console",
64
+ message: t(s, 200),
65
+ data: { "console.method": e }
66
+ });
67
+ return;
68
+ }
69
+ let { diagnostics: c, logger: l } = this.ctx;
70
+ if (!r(this.window, 20, c, "console records")) return;
71
+ let u = e === "error" ? [a, i] : [a], d = n.filter((e, t) => !u.includes(t)), f = { "console.method": e };
72
+ d.length > 0 && (f["console.args"] = d), e === "warn" ? l.warn(s, f) : l.error(s, o, {
73
+ ...f,
74
+ "error.captured_by": "console.error"
75
+ });
76
+ }
77
+ };
78
+ //#endregion
79
+ export { s as ConsoleCapture };
80
+
81
+ //# sourceMappingURL=console-CNljJict.js.map