@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
package/CHANGELOG.md CHANGED
@@ -2,7 +2,26 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
4
4
 
5
- ## [0.7.0] - unreleased
5
+ ## [0.8.0] - 2026-10-14
6
+
7
+ ### Added - v0.8.0
8
+
9
+ - `transport` sends batches through a channel of the app, for example an API client, a WebSocket or IPC. Batching, retry, storage, splitting and the exit flush stay the same. The returned status code has the meaning of the ingest contract. With `transport`, `endpoint` is optional.
10
+ - `transportOnExit` sends the last batch while the page closes. Without it, that batch goes to the emergency queue. The next page load sends it.
11
+ - The package exports the types `Transport`, `TransportRequest`, `TransportResponse` and `ExitTransport`.
12
+ - After the delivery stack loads, `configure()` cannot add or remove `transport`. The library reports `config.invalid`. A new function in place of the one in force is accepted.
13
+ - Network capture skips each request that the library starts itself. This includes a request that a custom transport starts before its first `await`.
14
+ - `createMemoryTransport()` gives tests a transport that keeps each batch in memory. `records()` returns the accepted records. `respondWith()` sets the answer, for example `413` or `429`. The package exports the type `MemoryTransport`.
15
+ - `capture.longFrames` records each frame that freezes the page as the histogram `ui.long_frame.duration`. `capture.longFrameThresholdMs` sets the minimum duration. The default is 100 ms. A browser without `long-animation-frame` gives `longtask` entries.
16
+ - `capture.console` records the console calls of the app. `true` wraps `error` and `warn`. A list selects from `error`, `warn`, `info` and `log`. `error` and `warn` give records. `info` and `log` give breadcrumbs. The library does not record the lines that it prints itself.
17
+ - `sampling.remote` reads sampling rules from the `X-UiObs-Sampling` header of each accepted batch. The rules stay in force for their `ttlMs`, at most 1 hour. They can change rates and lower `minLevel`. `sampling.remoteMaxRate` caps each remote rate. A custom transport returns the rules in `TransportResponse.sampling`. Child frames, workers and OpenFin views ask their owner for the rules.
18
+
19
+ ### Fixed - v0.8.0
20
+
21
+ - `flush()` during startup missed the records in the boot buffer. It now waits for startup to release them.
22
+ - The `sendBeacon` failure message was a fragment. It is now a complete sentence.
23
+
24
+ ## [0.7.0] - 2026-10-12
6
25
 
7
26
  ### Breaking changes - v0.7.0
8
27
 
package/README.md CHANGED
@@ -133,8 +133,103 @@ configure({
133
133
  - A later `configure({ console: "WARN" })` changes the level. The styles stay.
134
134
  - A later `configure({ console: { styles } })` changes the styles. The level stays.
135
135
 
136
+ ### Custom Transport
137
+
138
+ Set `transport` to send batches through a channel of your app, for example an API client with token refresh, a WebSocket, Electron IPC or an OpenFin channel. With `transport`, `endpoint` is optional.
139
+
140
+ ```ts
141
+ configure({
142
+ serviceName: "equities-blotter",
143
+ transport: async (request) => {
144
+ const response = await apiClient.post("/telemetry", request.body, {
145
+ headers: { "Content-Type": request.contentType, "X-UiObs-Batch-Id": request.batchId },
146
+ });
147
+ const retryAfterSeconds = Number(response.headers["retry-after"]);
148
+ return { status: response.status, retryAfterMs: retryAfterSeconds * 1000 };
149
+ },
150
+ // Optional. It runs while the page closes, so it must not wait for a promise.
151
+ transportOnExit: (request) => navigator.sendBeacon("/telemetry", request.body),
152
+ // Network capture must not log the requests of your transport.
153
+ capture: { ignoreUrls: ["/telemetry"] },
154
+ });
155
+ ```
156
+
157
+ - The library keeps batching, retry, storage, splitting and the exit flush.
158
+ - The status code that you return has the meaning of the ingest contract. `2xx` accepts the batch. `413` splits it. `429` and `503` throttle. `408` and `5xx` retry. Each other code drops the batch.
159
+ - A rejected promise counts as a network error. The library sends the batch again later. A call that does not settle in 15 seconds counts as a timeout.
160
+ - The library does not compress `request.body`. Compress it in your transport if necessary.
161
+ - `request.records` holds the built records after `redact`. Do not change them, because the retry engine can send them again.
162
+ - Without `transportOnExit`, the last batch goes to the emergency queue when the page closes. The next page load sends it.
163
+ - With `storage: "none"`, the next page load cannot keep that batch. Set `transportOnExit`, or the library loses the last batch.
164
+ - The library ignores a `retryAfterMs` or a `maxBytes` that is not a finite number. It uses 0 for a negative value.
165
+ - After the delivery stack loads, you cannot add or remove `transport`. You can replace it with another function.
166
+ - Network capture skips a request that your transport starts before its first `await`. Put your telemetry URL in `capture.ignoreUrls` too. A request after an `await` is outside that scope.
167
+
168
+ ### Testing
169
+
170
+ Use `createMemoryTransport()` to check what your code logs. It needs no network and no `fetch` mock.
171
+
172
+ ```ts
173
+ import {
174
+ configure,
175
+ createMemoryTransport,
176
+ flush,
177
+ getLogger,
178
+ shutdown,
179
+ } from "@utk09/ui-observability";
180
+
181
+ const memory = createMemoryTransport();
182
+
183
+ beforeEach(() => {
184
+ configure({
185
+ serviceName: "orders",
186
+ transport: memory.transport,
187
+ storage: "none",
188
+ bus: { mode: "off" },
189
+ identity: "memory",
190
+ });
191
+ });
192
+
193
+ afterEach(async () => {
194
+ memory.clear();
195
+ await shutdown();
196
+ });
197
+
198
+ it("logs the order submit", async () => {
199
+ getLogger("orders.ticket").logAction("ORDER_SUBMIT", { orderId: "ORD-1" });
200
+ await flush();
201
+
202
+ expect(memory.records()).toContainEqual(expect.objectContaining({ body: "ORDER_SUBMIT" }));
203
+ });
204
+ ```
205
+
206
+ - `records()` returns the records of each accepted batch. `batches()` returns each request, accepted or refused.
207
+ - `respondWith(status, retryAfterMs?)` sets the answer for each later batch. Use it to test a `413`, `429` or `500` answer. The default answer is `200`.
208
+ - `flush()` waits for startup. A record that you log directly after `configure()` is in the flushed batch.
209
+ - After `shutdown()`, each call does nothing until the next `configure()`.
210
+ - Set `storage: "none"` in tests. Without it, `shutdown()` stores the unsent records, and the next test can receive them.
211
+
136
212
  ---
137
213
 
214
+ ### Remote Sampling
215
+
216
+ With `sampling: { remote: true }`, the ingest server can change the sampling during an incident. You do not deploy the app again.
217
+
218
+ ```http
219
+ X-UiObs-Sampling: {"v":1,"ttlMs":600000,"defaultRate":0.1,"rates":{"blotter.grid":1},"minLevel":"DEBUG"}
220
+ ```
221
+
222
+ - The library reads the header only on a `2xx` answer to a batch that it sent. A custom transport returns the rules in `TransportResponse.sampling`, as text or as an object.
223
+ - `v` must be `1`. `ttlMs` is mandatory, from more than 0 to 3,600,000 (1 hour). After the TTL, the rules from `configure()` apply again.
224
+ - `rates` apply over the `configure()` rates. The other `configure()` rates stay. `defaultRate` applies only if the header has it.
225
+ - `minLevel` can only lower the level that the library sends. It does not change the console level.
226
+ - `sampling.remoteMaxRate` caps each remote rate. It also caps the records that a remote `minLevel` adds. Set it below 1 to limit the traffic that a compromised server can cause.
227
+ - The library rejects all the rules if one field is not valid, for example a rate outside 0 to 1, more than 100 `rates` or a header longer than 4096 characters. It reports `config.invalid`.
228
+ - The library keeps the rules in memory only. A reload uses the `configure()` rules until the next accepted batch.
229
+ - A child frame, a worker or an OpenFin view asks its owner for the rules at start and each 30 seconds. Set `sampling.remote: true` in each context.
230
+ - A frame accepts rules from a parent only if the parent origin is the page origin or is in `bus.trustedOrigins`. A page that embeds your app cannot lower `minLevel`.
231
+ - Each OpenFin view of one app can read the bus messages of the others. Load only trusted content into a view that has the `fin` API.
232
+
138
233
  ## API Reference
139
234
 
140
235
  ### Lifecycle & Setup
@@ -207,11 +302,15 @@ No key is required. Set `endpoint` to send records.
207
302
  | `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule. |
208
303
  | `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins. |
209
304
  | `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate. |
305
+ | `sampling.remote` | `false` | Reads sampling rules from the `X-UiObs-Sampling` header of each accepted batch (see Remote Sampling). |
306
+ | `sampling.remoteMaxRate` | `1` | Highest rate that a remote rule can set. It applies to the remote `defaultRate` and to each remote namespace rate. |
210
307
  | `bus.mode` | `"auto"` | `auto`, `sender`, `forwarder` or `off`. With `off`, this context sends its own records and opens no link. A same-origin child frame can still forward to it. |
211
308
  | `bus.trustedOrigins` | `[]` | Origins that may post records from a cross-origin frame. |
212
309
  | `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`. |
213
310
  | `capture` | See below | Auto-capture settings. |
214
311
  | `console` | `false` | Prints records to devtools. `true` prints from `DEBUG` up. A level name prints from that level up. An object sets `level` and `styles` (see Console Output). It does not depend on `minLevel`. |
312
+ | `transport(request)` | `undefined` | Sends batches through a channel of your app in place of HTTP (see Custom Transport). |
313
+ | `transportOnExit(request)` | `undefined` | Sends the last batch while the page closes. It must return a boolean and must not wait. |
215
314
  | `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off. |
216
315
  | `redact(record)` | `undefined` | Changes a record before the library sends or prints it. Return `null` to drop the record. |
217
316
  | `onDiagnostic(event)` | `undefined` | Receives the faults of the library itself. |
@@ -228,12 +327,34 @@ capture: {
228
327
  interactions: false, // Element click breadcrumbs
229
328
  navigation: false, // Single-page navigation URL changes
230
329
  webVitals: false, // Core Web Vitals (LCP, CLS, INP, FCP, TTFB)
330
+ longFrames: false, // Frames that freeze the page, as ui.long_frame.duration
331
+ longFrameThresholdMs: 100, // Minimum frame duration that longFrames records
332
+ console: false, // App console calls: true, or a list such as ["error", "warn", "info"]
231
333
  fullUrls: false, // Keep query strings and fragments on recorded URLs
232
334
  ignoreUrls: [], // URL patterns excluded from network capture
233
335
  propagateTraceHeaderTo: [], // Target origins allowed to receive traceparent
234
336
  }
235
337
  ```
236
338
 
339
+ `longFrames` records each frame at or above `longFrameThresholdMs` as the histogram `ui.long_frame.duration`. Each long frame also adds a breadcrumb. The next error record then shows the freeze before it.
340
+
341
+ - The library observes `long-animation-frame`. A browser without it gives `longtask` entries, with no script attributes.
342
+ - The attributes are `frame.type`, `frame.blocking_ms`, `frame.script.invoker` and `frame.script.source`. The source URL follows `fullUrls`.
343
+ - The library records at most 20 long frames in each 10-second window.
344
+
345
+ `capture.console` records the console calls of your app and of third-party code. It is different from the top-level `console` option, which prints records.
346
+
347
+ > **Set `redact` before you turn on `capture.console`.** A call such as `console.error("Request failed", error.response)` sends the request headers, for example `Authorization`. Third-party code on the page writes such lines too.
348
+
349
+ - `true` wraps `console.error` and `console.warn`. A list selects from `error`, `warn`, `info` and `log`.
350
+ - `error` gives an ERROR record, and `warn` gives a WARN record. `info` and `log` give a breadcrumb only.
351
+ - The first string is the message. The first `Error` of an `error` call gives the `error.*` fields. The other arguments go into `console.args`.
352
+ - The wrapper calls the original method first. Devtools shows the same text. The source link of the line points to the library wrapper.
353
+ - The library does not record the lines that it prints itself.
354
+ - The library records at most 20 `error` and `warn` calls in each 10-second window. The error capture has a separate limit. Console noise cannot hide an uncaught error.
355
+ - To record an argument, the library reads each property, also a getter. A getter with a side effect then runs during the console call.
356
+ - On `shutdown()`, the library restores each method. If another script wrapped the method later, the library leaves it and reports `capture.install_failed`.
357
+
237
358
  `fullUrls` is off by default. The library then cuts each recorded URL at the first `?` or `#`. This applies to the page URL, the request target and the URL of a failed resource. `ignoreUrls` and `propagateTraceHeaderTo` match the full URL.
238
359
 
239
360
  ### Browser Storage Keys
@@ -287,6 +408,7 @@ The ingest server must meet these requirements:
287
408
  3. **Deduplication:** Deduplicate on the `X-UiObs-Batch-Id` header and the `uiobs_batch_id` query parameter. Keep the ids for at least 24 hours.
288
409
  4. **Throttling:** Return `429` or `503` with `Retry-After`. Expose the header with `Access-Control-Expose-Headers: retry-after`.
289
410
  5. **Status codes:** `200`, `202` and `204` accept the batch. `413` makes the library split the batch. The library drops a batch that gets any other `4xx`.
411
+ 6. **Remote sampling (optional):** To send sampling rules, add `X-UiObs-Sampling` to a `2xx` answer. Expose the header with `Access-Control-Expose-Headers: x-uiobs-sampling`.
290
412
 
291
413
  ---
292
414
 
package/dist/bus/bus.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
2
  import type { Journey } from "../core/journey";
3
+ import type { RemoteSlot } from "../core/remote-sampling";
3
4
  import type { BusMessage, BusRole } from "../models/bus";
4
5
  import type { ResolvedConfig } from "../models/config";
5
6
  import type { LogRecord } from "../models/log-record";
@@ -24,6 +25,8 @@ export interface BusHandlers {
24
25
  onJourneyRequest: () => Journey | null;
25
26
  /** Runs when two windows use the same tab identifier. */
26
27
  onTabConflict: () => void;
28
+ /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */
29
+ remote: RemoteSlot;
27
30
  }
28
31
  /** Coordinates cross-realm communication, role resolution, and message dispatch. */
29
32
  export declare class Bus {
@@ -46,6 +49,10 @@ export declare class Bus {
46
49
  private isOpenFinProvider;
47
50
  /** Indicates whether role resolution has completed. */
48
51
  private resolved;
52
+ /** Timer that asks the upstream owner for the remote sampling rules. */
53
+ private rulesPoll;
54
+ /** True after destroy(). A handshake that ends later must not start a timer. */
55
+ private destroyed;
49
56
  /** Active handshake state awaiting welcome response. */
50
57
  private awaitingWelcome;
51
58
  /**
@@ -128,4 +135,27 @@ export declare class Bus {
128
135
  private handshake;
129
136
  /** Broadcasts tab claim and queries existing journey state. */
130
137
  private announce;
138
+ /**
139
+ * Builds the answer to a sampling question. Null rules end the copy of the forwarder.
140
+ * @param to Context id of the forwarder that asked.
141
+ * @returns The answer.
142
+ */
143
+ private rulesAnswer;
144
+ /**
145
+ * Tests whether this context accepts sampling rules from a source.
146
+ * @param to Context id that the answer names.
147
+ * @param source Link and origin of the answer.
148
+ * @returns True only for an answer from the upstream owner to this context.
149
+ */
150
+ private acceptsRules;
151
+ /**
152
+ * Applies the rules of an answer. It ignores rules that are not valid.
153
+ * @param raw Rules of the answer, or null when the upstream has none.
154
+ */
155
+ private applyRules;
156
+ /**
157
+ * Asks the upstream owner for the remote sampling rules now, then at each poll interval.
158
+ * A direct link cannot push the rules to a child. A poll works on each link kind.
159
+ */
160
+ private pollRules;
131
161
  }
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-B28fDv2F.cjs"),t=require("./unref-CU9Nyz_9.cjs"),n=require("./remote-rules-rJJZKVG8.cjs");function r(t){return{p:e.S,m:t}}function i(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var a=Symbol.for(e.Wt);function o(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[a]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function s(e,t){if(typeof window>`u`||window.parent===window)return null;let n=t=>{let n=i(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,n),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(r(e),`*`)})},close(){removeEventListener(`message`,n)}}}function c(e,t,n){if(typeof window>`u`)return null;let a=new Set([window.location.origin,...t]),o=new Map,s=t=>{let r=i(t.data);r&&(a.has(t.origin)?(t.source&&o.set(t.source,t.origin),e(r,{link:`children`,origin:t.origin})):n.report(`bus.untrusted_origin`,`The bus ignored a message from ${t.origin}. If you own this origin, add it to bus.trustedOrigins.`,{origin:t.origin,type:r.t}))};return addEventListener(`message`,s),{kind:`children`,post(e){for(let[t,i]of o){let a=t;a.closed?o.delete(t):n.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{a.postMessage(r(e),i)})}},close(){removeEventListener(`message`,s),o.clear()}}}function l(e,t,n){let a=globalThis.BroadcastChannel;if(a===void 0)return null;let o=n.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new a(e));return o?(o.onmessage=e=>{let n=i(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{o.postMessage(r(e))})},close(){n.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{o.close()})}}):null}function u(e,t,n,a){let o=globalThis.fin?.InterApplicationBus;if(!o)return null;if(!t)return a.report(`openfin.unavailable`,`OpenFin gives no application uuid. The InterApplicationBus link stays closed.`),null;let s=`${e}.${t}`;return a.guardAsync(`bus.send_failed`,`The InterApplicationBus.subscribe call failed.`,()=>o.subscribe({uuid:t},s,e=>{let t=i(e);t&&n(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){a.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>o.publish(s,r(e)))},close(){}}}function d(e,t){let n=globalThis,a=n.postMessage;return n.WorkerGlobalScope===void 0||!a?null:(n.addEventListener?.(`message`,t=>{let n=i(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`The postMessage call of the worker failed.`,()=>{a(r(e))})},close(){}})}function f(e,t,n){let a=e=>{let n=i(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,a),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(r(t))})},close(){e.removeEventListener(`message`,a)}}}var p={timeoutMs:e.x,maxAttempts:3},m=[`children`,`direct`,`worker`],h=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;rulesPoll;destroyed=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=p){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a,this.handshakeOptions=o}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;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;this.openControlLinks();let t=o(this.receive,this.diagnostics);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.`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`No owner exists. This context sends its own records.`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.handshakeOptions.maxAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`No owner answered after ${String(r)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`The bus role is ${this.role}.`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`)this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);else if(e.t===`journey?`){let e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n)}else e.t===`sampling?`?t(this.rulesAnswer(e.from),n):this.receive(e,n)}attachWorker(e){this.links.push(f(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){this.destroyed=!0,clearInterval(this.rulesPoll),this.rulesPoll=void 0;for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&this.awaitingWelcome.settle(!0);break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&this.canRelay(t.link)&&this.upstream.post(e);break;case`journey`:this.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});break}case`sampling?`:(this.role===`forwarder`?t.link!==this.upstream?.kind:this.canOwn(t.link))&&this.postOver(t.link,this.rulesAnswer(e.from));break;case`sampling`:this.acceptsRules(e.to,t)&&this.applyRules(e.rules);break;case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canRelay(e){return e===`direct`||e!==this.upstream?.kind}canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:m.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){return this.isCrossOriginFrame()?`retry`:`promote`}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return Reflect.get(window.parent,`location`),!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?d(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:s(this.receive,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(c(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(l(e.b,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=u(e.b,this.platform.openfinUuid,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,this.awaitingWelcome=null,clearTimeout(a),n(e))};this.awaitingWelcome={link:e.kind,settle:i};let a=setTimeout(()=>{i(!1)},this.handshakeOptions.timeoutMs);t.t(a),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId}),this.pollRules()}rulesAnswer(e){let t=this.handlers.remote.sampling?.wire()??null;return{t:`sampling`,from:this.contextId,to:e,rules:t}}acceptsRules(e,t){if(this.role!==`forwarder`||e!==this.contextId||t.link!==this.upstream?.kind)return!1;let{origin:n}=t;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.`,{origin:n,type:`sampling`}),!1):!0}applyRules(e){if(e===null){n.t(this.handlers.remote,this.config,null);return}let t=n.n(e,this.diagnostics);t&&n.t(this.handlers.remote,this.config,t)}pollRules(){let{upstream:n}=this;if(this.destroyed||this.role!==`forwarder`||!n)return;let r=()=>{this.config.sampling.remote&&n.post({t:`sampling?`,from:this.contextId})};r(),this.rulesPoll=setInterval(r,e.Et),t.t(this.rulesPoll)}};exports.Bus=h;
2
+ //# sourceMappingURL=bus-CUXRY0JR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus-CUXRY0JR.cjs","names":["BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_HANDSHAKE_TIMEOUT_MS","BUS_CHANNEL_NAME","parseRemoteRules","REMOTE_SAMPLING_POLL_MS","require_constants","require_unref","require_remote_rules","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":"uHAgFA,SAAgBS,EAAS,EAAkC,CACzD,MAAO,CAAE,EAAGT,EAAAA,EAAc,EAAGU,CAAQ,CACvC,CAUA,SAAgBC,EAAO,EAAkC,CACvD,GAAI,OAAOC,GAAS,WAAYA,EAC9B,OAAO,KAIT,IAAMC,EAAUD,EAChB,GAAIC,EAAQ,IAAA,sBAAsB,OAAOA,EAAQ,GAAM,UAAYA,EAAQ,IAAM,KAC/E,OAAO,KAGT,IAAMH,EAAUG,EAAQ,EAKxB,OAJI,OAAOH,EAAQ,GAAM,SAIlBA,EAHE,IAIX,CCpCA,IAAMI,EAAc,OAAO,IAAIb,EAAAA,EAAkB,EAQjD,SAAgBc,EAAiB,EAAkB,EAAuC,CACxF,GAAI,OAAO,OAAW,KAAe,OAAO,SAAW,OACrD,OAAO,KAGT,IAAIC,EACJ,GAAI,CAEF,EADqB,OAAO,OACRF,EACtB,MAAQ,CAEN,OAAO,IACT,CACA,GAAI,OAAOE,GAAM,WAAc,WAC7B,OAAO,KAGT,IAAMC,EAASD,EACXE,EAAO,GAEX,MAAO,CACL,KAAM,SACN,KAAK,EAAS,CACPA,GAKLC,EAAY,MACV,kBACA,sDACM,CACJF,EAAO,UAAUP,EAASU,CAAO,CACnC,CACF,CACF,EACA,OAAQ,CACN,EAAO,EACT,CACF,CACF,CAQA,SAAgBC,EAAiB,EAAkB,EAAuC,CACxF,GAAI,OAAO,OAAW,KAAe,OAAO,SAAW,O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