@utk09/ui-observability 0.5.0 → 0.6.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.
- package/CHANGELOG.md +16 -0
- package/README.md +77 -60
- package/dist/bus/bus.d.ts +10 -10
- package/dist/bus/links.d.ts +1 -1
- package/dist/{bus-D3OO0OcL.js → bus-BTMuVkDk.js} +19 -19
- package/dist/bus-BTMuVkDk.js.map +1 -0
- package/dist/bus-ChIXDAWD.cjs +2 -0
- package/dist/bus-ChIXDAWD.cjs.map +1 -0
- package/dist/capture/network.d.ts +2 -2
- package/dist/capture/types.d.ts +10 -10
- package/dist/capture/web-vitals.d.ts +3 -3
- package/dist/{constants-B6kdsCzF.js → constants-0-YchbAL.js} +2 -2
- package/dist/constants-0-YchbAL.js.map +1 -0
- package/dist/{constants-DZH04585.cjs → constants-TUFcy95w.cjs} +2 -2
- package/dist/constants-TUFcy95w.cjs.map +1 -0
- package/dist/constants.d.ts +53 -40
- package/dist/core/breadcrumbs.d.ts +14 -14
- package/dist/core/config.d.ts +5 -4
- package/dist/core/context.d.ts +2 -2
- package/dist/core/diagnostics.d.ts +10 -9
- package/dist/core/journey.d.ts +23 -20
- package/dist/core/logger.d.ts +7 -7
- package/dist/core/pipeline.d.ts +34 -29
- package/dist/core/record.d.ts +6 -6
- package/dist/core/runtime.d.ts +20 -18
- package/dist/core/sampling.d.ts +15 -16
- package/dist/core/sender.d.ts +1 -1
- package/dist/{errors-DPju_xSI.cjs → errors-DRXBRqvm.cjs} +2 -2
- package/dist/errors-DRXBRqvm.cjs.map +1 -0
- package/dist/{errors-Dme9tz-6.js → errors-Dwm2SzBa.js} +4 -4
- package/dist/errors-Dwm2SzBa.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +61 -61
- package/dist/index.js.map +1 -1
- package/dist/indexeddb-storage-B5dwq4hW.cjs +2 -0
- package/dist/indexeddb-storage-B5dwq4hW.cjs.map +1 -0
- package/dist/{indexeddb-storage-nxs_rxGx.js → indexeddb-storage-DjY4Ml6t.js} +16 -16
- package/dist/indexeddb-storage-DjY4Ml6t.js.map +1 -0
- package/dist/{interactions-DP0-rIPJ.cjs → interactions-DVom6eYn.cjs} +2 -2
- package/dist/interactions-DVom6eYn.cjs.map +1 -0
- package/dist/{interactions-C1romMpE.js → interactions-DZmLu7l2.js} +2 -2
- package/dist/interactions-DZmLu7l2.js.map +1 -0
- package/dist/models/batch.d.ts +12 -9
- package/dist/models/bus.d.ts +12 -13
- package/dist/models/config.d.ts +58 -41
- package/dist/models/log-record.d.ts +12 -10
- package/dist/models/serializer.d.ts +3 -2
- package/dist/models/storage.d.ts +2 -2
- package/dist/{network-au-Tqt1n.js → network-C4d2uw2Z.js} +4 -4
- package/dist/network-C4d2uw2Z.js.map +1 -0
- package/dist/network-CuqWadNn.cjs +2 -0
- package/dist/network-CuqWadNn.cjs.map +1 -0
- package/dist/platform-CXio0W2n.cjs +2 -0
- package/dist/platform-CXio0W2n.cjs.map +1 -0
- package/dist/{platform-DMYo3AX3.js → platform-CY8S3hUs.js} +8 -8
- package/dist/platform-CY8S3hUs.js.map +1 -0
- package/dist/sampling-CEthcmEX.cjs +2 -0
- package/dist/sampling-CEthcmEX.cjs.map +1 -0
- package/dist/{sampling-ByI5H44E.js → sampling-CJsI_24L.js} +21 -18
- package/dist/sampling-CJsI_24L.js.map +1 -0
- package/dist/sender-ByFAkXVd.cjs +3 -0
- package/dist/sender-ByFAkXVd.cjs.map +1 -0
- package/dist/{sender-R7lOpyNc.js → sender-dpvR_bHM.js} +60 -60
- package/dist/sender-dpvR_bHM.js.map +1 -0
- package/dist/storage/emergency-queue.d.ts +2 -2
- package/dist/storage/factory.d.ts +2 -1
- package/dist/storage/idb-driver.d.ts +19 -19
- package/dist/storage/indexeddb-storage.d.ts +18 -17
- package/dist/storage/keys.d.ts +1 -1
- package/dist/storage/local-storage.d.ts +19 -18
- package/dist/storage/memory-storage.d.ts +12 -11
- package/dist/transport/compression.d.ts +2 -2
- package/dist/transport/errors.d.ts +8 -7
- package/dist/transport/exit-flush.d.ts +27 -24
- package/dist/transport/http-transport.d.ts +18 -11
- package/dist/transport/retry-engine.d.ts +33 -28
- package/dist/transport/serializers/ecs.d.ts +1 -1
- package/dist/transport/serializers/otlp.d.ts +1 -1
- package/dist/unref-16maCyKA.js.map +1 -1
- package/dist/unref-CU9Nyz_9.cjs.map +1 -1
- package/dist/utils/identity.d.ts +6 -5
- package/dist/utils/lock.d.ts +4 -4
- package/dist/utils/platform.d.ts +5 -3
- package/dist/utils/sanitize.d.ts +5 -2
- package/dist/utils/sequence.d.ts +2 -2
- package/dist/utils/tracing.d.ts +8 -7
- package/dist/web-vitals-B2FYsEAU.cjs +2 -0
- package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
- package/dist/{web-vitals-DwWdLBq6.js → web-vitals-DHZ0yA_H.js} +4 -4
- package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
- package/package.json +1 -1
- package/dist/bus-D3OO0OcL.js.map +0 -1
- package/dist/bus-OdRJVUzr.cjs +0 -2
- package/dist/bus-OdRJVUzr.cjs.map +0 -1
- package/dist/constants-B6kdsCzF.js.map +0 -1
- package/dist/constants-DZH04585.cjs.map +0 -1
- package/dist/errors-DPju_xSI.cjs.map +0 -1
- package/dist/errors-Dme9tz-6.js.map +0 -1
- package/dist/indexeddb-storage-lGdoHGHy.cjs +0 -2
- package/dist/indexeddb-storage-lGdoHGHy.cjs.map +0 -1
- package/dist/indexeddb-storage-nxs_rxGx.js.map +0 -1
- package/dist/interactions-C1romMpE.js.map +0 -1
- package/dist/interactions-DP0-rIPJ.cjs.map +0 -1
- package/dist/network-DDVIJSHd.cjs +0 -2
- package/dist/network-DDVIJSHd.cjs.map +0 -1
- package/dist/network-au-Tqt1n.js.map +0 -1
- package/dist/platform-DMYo3AX3.js.map +0 -1
- package/dist/platform-g99Kn755.cjs +0 -2
- package/dist/platform-g99Kn755.cjs.map +0 -1
- package/dist/sampling-ByI5H44E.js.map +0 -1
- package/dist/sampling-Dui-Fp3u.cjs +0 -2
- package/dist/sampling-Dui-Fp3u.cjs.map +0 -1
- package/dist/sender-R7lOpyNc.js.map +0 -1
- package/dist/sender-vLcbQhiB.cjs +0 -3
- package/dist/sender-vLcbQhiB.cjs.map +0 -1
- package/dist/web-vitals-DM2nvcMJ.cjs +0 -2
- package/dist/web-vitals-DM2nvcMJ.cjs.map +0 -1
- package/dist/web-vitals-DwWdLBq6.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
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.6.0] - 2026-10-11
|
|
6
|
+
|
|
7
|
+
### Breaking changes - v0.6.0
|
|
8
|
+
|
|
9
|
+
- Each diagnostic message, `TransportError` message and IndexedDB error message is a complete sentence. For example, "server throttled us" is now "The server throttles the requests." Filter on `event.code`, not on `event.message`.
|
|
10
|
+
|
|
11
|
+
### Added - v0.6.0
|
|
12
|
+
|
|
13
|
+
- The diagnostic code `platform.api_blocked` counts a browser API that a sandbox or a cross-origin boundary blocks. This includes `crypto.randomUUID`, `window.top` and `location.href`.
|
|
14
|
+
- `getDiagnosticCounters()["record.sanitize_failed"]` counts each value that throws during sanitization, for example a hostile getter.
|
|
15
|
+
|
|
16
|
+
### Changed - v0.6.0
|
|
17
|
+
|
|
18
|
+
- The comments, the JSDoc in the `.d.ts` files and the README follow ASD-STE100.
|
|
19
|
+
- The `BusMode` JSDoc said that `off` "does neither". With `off`, the context delivers its own records.
|
|
20
|
+
|
|
5
21
|
## [0.5.0] - 2026-10-11
|
|
6
22
|
|
|
7
23
|
### Breaking changes - v0.5.0
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Structured logging and UI observability for browsers, embedded webviews and OpenFin containers. The library imports no framework.
|
|
4
4
|
|
|
5
|
-
The library batches records and sends them over HTTP as OTLP/JSON.
|
|
5
|
+
The library batches records and sends them over HTTP as OTLP/JSON. It stores a batch that fails to send, and sends it again later. When the page closes, the library sends the records that are left. Iframes, workers and OpenFin windows share one sender through the bus. A log call never throws.
|
|
6
6
|
|
|
7
7
|
> **Status: early development.** A minor release can change a public API. Pin the exact version.
|
|
8
8
|
|
|
@@ -30,7 +30,9 @@ configure({
|
|
|
30
30
|
});
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
Install `@opentelemetry/api` (`^1`) to put records on the traces your spans
|
|
33
|
+
Install `@opentelemetry/api` (`^1`) to put records on the traces of your spans. Set `otelLoader` to load it. Without `otelLoader`, OTel is off. The library then makes its own `trace_id`.
|
|
34
|
+
|
|
35
|
+
The library never imports a peer by name. A missing peer cannot break your bundler or your dev server.
|
|
34
36
|
|
|
35
37
|
```ts
|
|
36
38
|
configure({
|
|
@@ -62,14 +64,15 @@ log.logAction("ORDER_SUBMIT", { orderId: "ORD-1001", qty: 100 });
|
|
|
62
64
|
log.error("pricing call failed", caughtError);
|
|
63
65
|
```
|
|
64
66
|
|
|
65
|
-
- `configure()` is idempotent. A later call updates the runtime singleton in place. `storage`
|
|
66
|
-
-
|
|
67
|
+
- `configure()` is idempotent. A later call updates the runtime singleton in place. You cannot change `storage` or `identity` after startup. The library reports that change and ignores it.
|
|
68
|
+
- Call `configure()` from one context in each document. A second call changes `service.name` on the records of every other context. In a composed page, the shell calls `configure()`. Each microfrontend uses its own namespace.
|
|
67
69
|
- You can call `getLogger()` at module top level, before `configure()`. The logger finds the runtime on its first write.
|
|
68
|
-
- A write before `configure()` starts a runtime with default settings. It does not throw.
|
|
70
|
+
- A write before the first `configure()` starts a runtime with default settings. It does not throw.
|
|
71
|
+
- After `shutdown()`, every call does nothing until the next `configure()`.
|
|
69
72
|
|
|
70
73
|
### Console Only (No Network)
|
|
71
74
|
|
|
72
|
-
Set `endpoint: null`. The library sends nothing. It
|
|
75
|
+
Set `endpoint: null`. The library sends nothing. It prints records to the console only.
|
|
73
76
|
|
|
74
77
|
```ts
|
|
75
78
|
configure({
|
|
@@ -86,7 +89,7 @@ configure({
|
|
|
86
89
|
- `identity: "memory"` writes no key to `localStorage` or `sessionStorage`.
|
|
87
90
|
- `console` and `minLevel` are independent. `console` sets what the library prints. `minLevel` sets what the library sends.
|
|
88
91
|
- The console output does not depend on the bus or the endpoint.
|
|
89
|
-
- With a `redact` hook, the console shows only what `redact` returns. A record
|
|
92
|
+
- With a `redact` hook, the console shows only what `redact` returns. A record below `minLevel` shows its message and error only, because the library does not build it.
|
|
90
93
|
|
|
91
94
|
---
|
|
92
95
|
|
|
@@ -94,26 +97,26 @@ configure({
|
|
|
94
97
|
|
|
95
98
|
### Lifecycle & Setup
|
|
96
99
|
|
|
97
|
-
| Function | Description
|
|
98
|
-
| ------------------- |
|
|
99
|
-
| `configure(config)` | Starts the runtime singleton, or updates it.
|
|
100
|
-
| `shutdown()` |
|
|
100
|
+
| Function | Description |
|
|
101
|
+
| ------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
102
|
+
| `configure(config)` | Starts the runtime singleton, or updates it. |
|
|
103
|
+
| `shutdown()` | Sends pending records and stops every subsystem. Later calls do nothing until the next `configure()`. |
|
|
101
104
|
|
|
102
105
|
### Logging Methods
|
|
103
106
|
|
|
104
|
-
| Function | Description
|
|
105
|
-
| ---------------------------------------------- |
|
|
106
|
-
| `getLogger(namespace, options?)` | Returns the cached logger for a namespace. With `options`, returns a new
|
|
107
|
-
| `trace(msg, payload?)` | Logs a TRACE record.
|
|
108
|
-
| `debug(msg, payload?)` | Logs a DEBUG record.
|
|
109
|
-
| `info(msg, payload?)` | Logs an INFO record.
|
|
110
|
-
| `warn(msg, payload?)` | Logs a WARN record.
|
|
111
|
-
| `error(msg, err?, payload?)` | Logs an ERROR record with the error and the breadcrumb trail.
|
|
112
|
-
| `logAction(name, payload?)` | Logs one user action.
|
|
113
|
-
| `logEvent(name, payload?)` | Logs one domain or lifecycle event.
|
|
114
|
-
| `logMetric(name, value, unit?, type?, attrs?)` | Logs a measurement (`gauge`, `counter`, `histogram`).
|
|
115
|
-
| `timeSync(label, fn, attrs?)` | Times a function and emits a duration histogram.
|
|
116
|
-
| `timeAsync(label, fn, attrs?)` | Times a promise and emits a duration histogram.
|
|
107
|
+
| Function | Description |
|
|
108
|
+
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
109
|
+
| `getLogger(namespace, options?)` | Returns the cached logger for a namespace. With `options`, it returns a new logger that is not cached. |
|
|
110
|
+
| `trace(msg, payload?)` | Logs a TRACE record. |
|
|
111
|
+
| `debug(msg, payload?)` | Logs a DEBUG record. |
|
|
112
|
+
| `info(msg, payload?)` | Logs an INFO record. |
|
|
113
|
+
| `warn(msg, payload?)` | Logs a WARN record. |
|
|
114
|
+
| `error(msg, err?, payload?)` | Logs an ERROR record with the error and the breadcrumb trail. |
|
|
115
|
+
| `logAction(name, payload?)` | Logs one user action. |
|
|
116
|
+
| `logEvent(name, payload?)` | Logs one domain or lifecycle event. |
|
|
117
|
+
| `logMetric(name, value, unit?, type?, attrs?)` | Logs a measurement (`gauge`, `counter`, `histogram`). |
|
|
118
|
+
| `timeSync(label, fn, attrs?)` | Times a function and emits a duration histogram. |
|
|
119
|
+
| `timeAsync(label, fn, attrs?)` | Times a promise and emits a duration histogram. |
|
|
117
120
|
|
|
118
121
|
### Context & Correlation
|
|
119
122
|
|
|
@@ -145,31 +148,31 @@ configure({
|
|
|
145
148
|
|
|
146
149
|
No key is required. Set `endpoint` to send records.
|
|
147
150
|
|
|
148
|
-
| Key | Default | Description
|
|
149
|
-
| ---------------------------- | ------------ |
|
|
150
|
-
| `endpoint` | `""` | HTTP endpoint that receives the batches. `null` selects console-only mode. `""` reports `config.invalid`.
|
|
151
|
-
| `serviceName` | `""` | `service.name` on every record.
|
|
152
|
-
| `serviceVersion` | `""` | `service.version` on every record.
|
|
153
|
-
| `environment` | `""` | `deployment.environment` on every record.
|
|
154
|
-
| `enabled` | `true` |
|
|
155
|
-
| `minLevel` | `"INFO"` | Lowest level that the library sends (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`).
|
|
156
|
-
| `compression` | `"gzip"` | `gzip` or `none`.
|
|
157
|
-
| `serializer` | `"otlp"` | `otlp`, `ecs`, or a custom `LogSerializer`.
|
|
158
|
-
| `credentials` | `"omit"` | Fetch credentials mode. Set `"include"` for cookie auth.
|
|
159
|
-
| `headers` | `{}` | Static headers, or a function that returns them.
|
|
160
|
-
| `storage` | `"auto"` | Store for undelivered batches: `auto`, `indexeddb`, `localstorage`, `memory` or `none`. Fixed at startup.
|
|
161
|
-
| `identity` | `"storage"` | Store for session, tab and journey ids. `memory` writes no key. Fixed at startup.
|
|
162
|
-
| `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule.
|
|
163
|
-
| `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins.
|
|
164
|
-
| `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate.
|
|
165
|
-
| `bus.mode` | `"auto"` | `auto`, `sender`, `forwarder` or `off`. `off
|
|
166
|
-
| `bus.trustedOrigins` | `[]` | Origins that may post records from a cross-origin frame.
|
|
167
|
-
| `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`.
|
|
168
|
-
| `capture` | See below | Auto-capture settings.
|
|
169
|
-
| `console` | `false` | Prints records to devtools. `true`
|
|
170
|
-
| `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off.
|
|
171
|
-
| `redact(record)` | `undefined` |
|
|
172
|
-
| `onDiagnostic(event)` | `undefined` | Receives
|
|
151
|
+
| Key | Default | Description |
|
|
152
|
+
| ---------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
153
|
+
| `endpoint` | `""` | HTTP endpoint that receives the batches. `null` selects console-only mode. `""` reports `config.invalid`. |
|
|
154
|
+
| `serviceName` | `""` | `service.name` on every record. |
|
|
155
|
+
| `serviceVersion` | `""` | `service.version` on every record. |
|
|
156
|
+
| `environment` | `""` | `deployment.environment` on every record. |
|
|
157
|
+
| `enabled` | `true` | Set `false` to stop all logging. Every log call then does nothing. |
|
|
158
|
+
| `minLevel` | `"INFO"` | Lowest level that the library sends (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`). |
|
|
159
|
+
| `compression` | `"gzip"` | `gzip` or `none`. The library compresses a payload above 1 KB only. |
|
|
160
|
+
| `serializer` | `"otlp"` | `otlp`, `ecs`, or a custom `LogSerializer`. |
|
|
161
|
+
| `credentials` | `"omit"` | Fetch credentials mode. Set `"include"` for cookie auth. |
|
|
162
|
+
| `headers` | `{}` | Static headers, or a function that returns them. |
|
|
163
|
+
| `storage` | `"auto"` | Store for undelivered batches: `auto`, `indexeddb`, `localstorage`, `memory` or `none`. Fixed at startup. |
|
|
164
|
+
| `identity` | `"storage"` | Store for session, tab and journey ids. `memory` writes no key. Fixed at startup. |
|
|
165
|
+
| `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule. |
|
|
166
|
+
| `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins. |
|
|
167
|
+
| `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate. |
|
|
168
|
+
| `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. |
|
|
169
|
+
| `bus.trustedOrigins` | `[]` | Origins that may post records from a cross-origin frame. |
|
|
170
|
+
| `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`. |
|
|
171
|
+
| `capture` | See below | Auto-capture settings. |
|
|
172
|
+
| `console` | `false` | Prints records to devtools. `true` prints from `DEBUG` up. A level name prints from that level up. It does not depend on `minLevel`. |
|
|
173
|
+
| `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off. |
|
|
174
|
+
| `redact(record)` | `undefined` | Changes a record before the library sends or prints it. Return `null` to drop the record. |
|
|
175
|
+
| `onDiagnostic(event)` | `undefined` | Receives the faults of the library itself. |
|
|
173
176
|
|
|
174
177
|
### Auto-Capture Options
|
|
175
178
|
|
|
@@ -189,7 +192,7 @@ capture: {
|
|
|
189
192
|
}
|
|
190
193
|
```
|
|
191
194
|
|
|
192
|
-
`fullUrls` is off. The library cuts
|
|
195
|
+
`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.
|
|
193
196
|
|
|
194
197
|
### Browser Storage Keys
|
|
195
198
|
|
|
@@ -208,26 +211,40 @@ IndexedDB holds undelivered batches with `storage: "auto"` or `"indexeddb"`.
|
|
|
208
211
|
|
|
209
212
|
## Core Architecture
|
|
210
213
|
|
|
211
|
-
- **Code splitting:** The main chunk holds the logger, the record builder and the console sink. The delivery stack loads only when an endpoint
|
|
212
|
-
- **Document singleton:** The runtime
|
|
214
|
+
- **Code splitting:** The main chunk holds the logger, the record builder and the console sink. The delivery stack loads only when you set an endpoint. The bus loads only when the context needs it. Each capture module loads only when you enable it.
|
|
215
|
+
- **Document singleton:** The library keeps the runtime at `globalThis[Symbol.for("ui-observability.runtime")]`. Federated microfrontends and separate bundles share one buffer, one sequence and one transport.
|
|
213
216
|
- **One sender:** Iframes, workers and OpenFin views find the nearest long-lived context. They forward their records to it over the bus. That context batches, stores and sends for all of them.
|
|
214
217
|
- **Five correlation ids:** Each record carries `session.id`, `tab.id`, `context.id`, `journey.id` and `trace_id`.
|
|
215
|
-
- **Durability and exit flush:**
|
|
216
|
-
- **Emergency queue:** The emergency queue is best effort. It writes to `localStorage` synchronously
|
|
217
|
-
- **Configuration after startup:** A second `configure()` call merges the new options into the live runtime. The
|
|
218
|
-
-
|
|
218
|
+
- **Durability and exit flush:** The library stores a batch that fails to send, in IndexedDB or localStorage. It sends the batch again with exponential backoff and jitter. On `pagehide` or `freeze`, it sends pending records with `navigator.sendBeacon` if they are below 60 KB. A larger payload goes to the emergency queue.
|
|
219
|
+
- **Emergency queue:** The emergency queue is best effort. It writes to `localStorage` synchronously, because no other storage works while the page unloads. If the browser refuses the write, the library reports `storage.quota_exceeded`. The library then loses the batch.
|
|
220
|
+
- **Configuration after startup:** A second `configure()` call merges the new options into the live runtime. The runtime refuses 3 changes and reports `config.invalid` for each:
|
|
221
|
+
- A change to `storage`. The stored batches stay in the adapter that the runtime built at startup.
|
|
222
|
+
- A change to `identity`. The ids exist from startup.
|
|
223
|
+
- An `endpoint` change to `null` or `""` after the delivery stack loads. Without an endpoint, the stored batches would be lost. A change to another endpoint URL is accepted.
|
|
224
|
+
- **Deterministic sampling:** FNV-1a hashing applies one keep rate to a whole journey. An error and an explicit action are always kept.
|
|
219
225
|
|
|
220
226
|
---
|
|
221
227
|
|
|
222
228
|
## Ingest Server Requirements
|
|
223
229
|
|
|
224
|
-
The server must
|
|
230
|
+
The ingest server must meet these requirements:
|
|
225
231
|
|
|
226
232
|
1. **Protocol:** Accept `POST` with `Content-Type: application/json` or `text/plain;charset=UTF-8`. `sendBeacon` sends the second one to avoid a CORS preflight.
|
|
227
|
-
2. **Preflight:** Answer `OPTIONS` on the ingest path
|
|
228
|
-
|
|
233
|
+
2. **Preflight:** Answer `OPTIONS` on the ingest path, and allow the request headers:
|
|
234
|
+
|
|
235
|
+
```http
|
|
236
|
+
Access-Control-Allow-Headers: content-type, content-encoding, x-uiobs-batch-id, x-uiobs-attempt
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
- The transport sends `X-UiObs-Batch-Id` and `X-UiObs-Attempt` with each batch.
|
|
240
|
+
- Above 1 KiB, it also sends `Content-Encoding: gzip`.
|
|
241
|
+
- Each of these headers causes a CORS preflight. If the server does not allow them, each preflight fails.
|
|
242
|
+
- After a failed preflight, the library tries the batch 5 more times. It then drops the batch.
|
|
243
|
+
- Only the exit flush records arrive, because the exit flush sends no custom header.
|
|
244
|
+
|
|
245
|
+
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.
|
|
229
246
|
4. **Throttling:** Return `429` or `503` with `Retry-After`. Expose the header with `Access-Control-Expose-Headers: retry-after`.
|
|
230
|
-
5. **Status codes:** `200`, `202` and `204` accept the batch. `413` makes the
|
|
247
|
+
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`.
|
|
231
248
|
|
|
232
249
|
---
|
|
233
250
|
|
package/dist/bus/bus.d.ts
CHANGED
|
@@ -7,12 +7,12 @@ import type { PlatformMetadata } from "../utils/platform";
|
|
|
7
7
|
import { type Receive, type WorkerLike } from "./links";
|
|
8
8
|
/** Handshake timing for a forwarder waiting on an owner. */
|
|
9
9
|
export interface HandshakeOptions {
|
|
10
|
-
/**
|
|
10
|
+
/** Maximum time that a forwarder waits for an owner to answer, in milliseconds. */
|
|
11
11
|
timeoutMs: number;
|
|
12
12
|
/** Attempts allowed before a cross-origin forwarder promotes itself to sender. */
|
|
13
13
|
maxAttempts: number;
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
15
|
+
/** Default handshake timing. Tests build a bus with shorter values. */
|
|
16
16
|
export declare const HANDSHAKE_OPTIONS: HandshakeOptions;
|
|
17
17
|
/** Callbacks for handling records and journey events from connected realms. */
|
|
18
18
|
export interface BusHandlers {
|
|
@@ -20,9 +20,9 @@ export interface BusHandlers {
|
|
|
20
20
|
onRecords: (records: LogRecord[]) => void;
|
|
21
21
|
/** Applies journey updates received from the control bus. */
|
|
22
22
|
onJourney: (journey: Journey | null) => void;
|
|
23
|
-
/** Returns the active journey
|
|
23
|
+
/** Returns the active journey to a child context that requests it. */
|
|
24
24
|
onJourneyRequest: () => Journey | null;
|
|
25
|
-
/**
|
|
25
|
+
/** Runs when two windows use the same tab identifier. */
|
|
26
26
|
onTabConflict: () => void;
|
|
27
27
|
}
|
|
28
28
|
/** Coordinates cross-realm communication, role resolution, and message dispatch. */
|
|
@@ -34,7 +34,7 @@ export declare class Bus {
|
|
|
34
34
|
private readonly tabId;
|
|
35
35
|
private readonly handlers;
|
|
36
36
|
private readonly handshakeOptions;
|
|
37
|
-
/** Current bus role.
|
|
37
|
+
/** Current bus role. The default is "sender". */
|
|
38
38
|
private role;
|
|
39
39
|
/** Upstream forwarding link, or null when acting as sender. */
|
|
40
40
|
private upstream;
|
|
@@ -93,15 +93,15 @@ export declare class Bus {
|
|
|
93
93
|
private allLinks;
|
|
94
94
|
/** Broadcasts a message across all open links. */
|
|
95
95
|
private post;
|
|
96
|
-
/** Sends a message
|
|
96
|
+
/** Sends a message only over links of the given kind. */
|
|
97
97
|
private postOver;
|
|
98
98
|
/** Routes incoming messages to registered handlers or upstream targets. */
|
|
99
99
|
private readonly receive;
|
|
100
100
|
/**
|
|
101
|
-
* Tells whether records from a link can go upstream.
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* different links.
|
|
101
|
+
* Tells whether records from a link can go upstream. Records that go back on
|
|
102
|
+
* their arrival link return to their sender. A direct link is an exception.
|
|
103
|
+
* Each direct link is one call into one parent. Thus two direct links in a
|
|
104
|
+
* chain are different links.
|
|
105
105
|
* @param link Kind of the link the records arrived on.
|
|
106
106
|
* @returns True if the relay is safe.
|
|
107
107
|
*/
|
package/dist/bus/links.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export interface Link {
|
|
|
18
18
|
* @param source Origin and link metadata.
|
|
19
19
|
*/
|
|
20
20
|
export type Receive = (message: BusMessage, source: MessageSource) => void;
|
|
21
|
-
/** Interface
|
|
21
|
+
/** Interface that a same-origin parent runtime exposes on a global symbol. */
|
|
22
22
|
export interface DirectHost {
|
|
23
23
|
/**
|
|
24
24
|
* Accepts a message directly from a child frame and replies synchronously.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Rt as e, S as t, b as n, x as r } from "./constants-
|
|
1
|
+
import { Rt as e, S as t, b as n, x as r } from "./constants-0-YchbAL.js";
|
|
2
2
|
import { t as i } from "./unref-16maCyKA.js";
|
|
3
3
|
//#region src/models/bus.ts
|
|
4
4
|
function a(e) {
|
|
@@ -30,7 +30,7 @@ function c(e, t) {
|
|
|
30
30
|
return {
|
|
31
31
|
kind: "direct",
|
|
32
32
|
post(n) {
|
|
33
|
-
i && t.guard("bus.send_failed", "direct call into the parent runtime", () => {
|
|
33
|
+
i && t.guard("bus.send_failed", "The direct call into the parent runtime failed.", () => {
|
|
34
34
|
r.busAccept(n, e);
|
|
35
35
|
});
|
|
36
36
|
},
|
|
@@ -51,7 +51,7 @@ function l(e, t) {
|
|
|
51
51
|
return addEventListener("message", n), {
|
|
52
52
|
kind: "parent",
|
|
53
53
|
post(e) {
|
|
54
|
-
t.guard("bus.send_failed", "postMessage to parent", () => {
|
|
54
|
+
t.guard("bus.send_failed", "The postMessage call to the parent failed.", () => {
|
|
55
55
|
window.parent.postMessage(a(e), "*");
|
|
56
56
|
});
|
|
57
57
|
},
|
|
@@ -67,7 +67,7 @@ function u(e, t, n) {
|
|
|
67
67
|
a && (r.has(t.origin) ? (t.source && i.set(t.source, t.origin), e(a, {
|
|
68
68
|
link: "children",
|
|
69
69
|
origin: t.origin
|
|
70
|
-
})) : n.report("bus.untrusted_origin", `ignored a
|
|
70
|
+
})) : n.report("bus.untrusted_origin", `The bus ignored a message from ${t.origin}. If you own this origin, add it to bus.trustedOrigins.`, {
|
|
71
71
|
origin: t.origin,
|
|
72
72
|
type: a.t
|
|
73
73
|
}));
|
|
@@ -77,7 +77,7 @@ function u(e, t, n) {
|
|
|
77
77
|
post(e) {
|
|
78
78
|
for (let [t, r] of i) {
|
|
79
79
|
let o = t;
|
|
80
|
-
o.closed ? i.delete(t) : n.guard("bus.send_failed", "postMessage to child", () => {
|
|
80
|
+
o.closed ? i.delete(t) : n.guard("bus.send_failed", "The postMessage call to a child frame failed.", () => {
|
|
81
81
|
o.postMessage(a(e), r);
|
|
82
82
|
});
|
|
83
83
|
}
|
|
@@ -90,7 +90,7 @@ function u(e, t, n) {
|
|
|
90
90
|
function d(e, t, n) {
|
|
91
91
|
let r = globalThis.BroadcastChannel;
|
|
92
92
|
if (r === void 0) return null;
|
|
93
|
-
let i = n.guard("bus.send_failed", "
|
|
93
|
+
let i = n.guard("bus.send_failed", "The library could not open the BroadcastChannel.", () => new r(e));
|
|
94
94
|
return i ? (i.onmessage = (e) => {
|
|
95
95
|
let n = o(e.data);
|
|
96
96
|
n && t(n, {
|
|
@@ -100,12 +100,12 @@ function d(e, t, n) {
|
|
|
100
100
|
}, {
|
|
101
101
|
kind: "broadcast",
|
|
102
102
|
post(e) {
|
|
103
|
-
n.guard("bus.send_failed", "BroadcastChannel.postMessage", () => {
|
|
103
|
+
n.guard("bus.send_failed", "The BroadcastChannel.postMessage call failed.", () => {
|
|
104
104
|
i.postMessage(a(e));
|
|
105
105
|
});
|
|
106
106
|
},
|
|
107
107
|
close() {
|
|
108
|
-
n.guard("bus.send_failed", "
|
|
108
|
+
n.guard("bus.send_failed", "The library could not close the BroadcastChannel.", () => {
|
|
109
109
|
i.close();
|
|
110
110
|
});
|
|
111
111
|
}
|
|
@@ -114,9 +114,9 @@ function d(e, t, n) {
|
|
|
114
114
|
function f(e, t, n, r) {
|
|
115
115
|
let i = globalThis.fin?.InterApplicationBus;
|
|
116
116
|
if (!i) return null;
|
|
117
|
-
if (!t) return r.report("openfin.unavailable", "no
|
|
117
|
+
if (!t) return r.report("openfin.unavailable", "OpenFin gives no application uuid. The InterApplicationBus link stays closed."), null;
|
|
118
118
|
let s = `${e}.${t}`;
|
|
119
|
-
return r.guardAsync("bus.send_failed", "InterApplicationBus.subscribe", () => i.subscribe({ uuid: t }, s, (e) => {
|
|
119
|
+
return r.guardAsync("bus.send_failed", "The InterApplicationBus.subscribe call failed.", () => i.subscribe({ uuid: t }, s, (e) => {
|
|
120
120
|
let t = o(e);
|
|
121
121
|
t && n(t, {
|
|
122
122
|
link: "openfin",
|
|
@@ -125,7 +125,7 @@ function f(e, t, n, r) {
|
|
|
125
125
|
})), {
|
|
126
126
|
kind: "openfin",
|
|
127
127
|
post(e) {
|
|
128
|
-
r.guardAsync("bus.send_failed", "InterApplicationBus.publish", () => i.publish(s, a(e)));
|
|
128
|
+
r.guardAsync("bus.send_failed", "The InterApplicationBus.publish call failed.", () => i.publish(s, a(e)));
|
|
129
129
|
},
|
|
130
130
|
close() {}
|
|
131
131
|
};
|
|
@@ -141,7 +141,7 @@ function p(e, t) {
|
|
|
141
141
|
}), {
|
|
142
142
|
kind: "owner",
|
|
143
143
|
post(e) {
|
|
144
|
-
t.guard("bus.send_failed", "worker
|
|
144
|
+
t.guard("bus.send_failed", "The postMessage call of the worker failed.", () => {
|
|
145
145
|
r(a(e));
|
|
146
146
|
});
|
|
147
147
|
},
|
|
@@ -159,7 +159,7 @@ function m(e, t, n) {
|
|
|
159
159
|
return e.addEventListener("message", r), e.start?.(), {
|
|
160
160
|
kind: "worker",
|
|
161
161
|
post(t) {
|
|
162
|
-
n.guard("bus.send_failed", "postMessage to a worker", () => {
|
|
162
|
+
n.guard("bus.send_failed", "The postMessage call to a worker failed.", () => {
|
|
163
163
|
e.postMessage(a(t));
|
|
164
164
|
});
|
|
165
165
|
},
|
|
@@ -204,21 +204,21 @@ var h = {
|
|
|
204
204
|
async start() {
|
|
205
205
|
let { bus: e } = this.config;
|
|
206
206
|
if (e.mode === "off") return this.role = "sender", this.resolved = !0, this.role;
|
|
207
|
-
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\"
|
|
207
|
+
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
208
|
this.openControlLinks();
|
|
209
209
|
let t = c(this.receive, this.diagnostics);
|
|
210
|
-
if (t) return this.role = "forwarder", this.upstream = t, this.resolved = !0, this.diagnostics.report("bus.role_resolved", "attached directly to the same-origin parent
|
|
210
|
+
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
211
|
role: "forwarder",
|
|
212
212
|
via: "direct"
|
|
213
213
|
}), this.announce(), this.role;
|
|
214
214
|
let n = this.candidateUpstream();
|
|
215
|
-
if (!n) return this.role = "sender", this.resolved = !0, this.diagnostics.report("bus.role_resolved", "
|
|
215
|
+
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;
|
|
216
216
|
let r = this.orphanPolicy() === "retry" ? this.handshakeOptions.maxAttempts : 1, i = !1;
|
|
217
217
|
for (let e = 0; e < r && !i; e++) i = await this.handshake(n);
|
|
218
|
-
return this.role = i ? "forwarder" : "sender", this.upstream = i ? n : null, i || (n !== this.openFinLink && n.close(), this.diagnostics.report("bus.handshake_timeout", `
|
|
218
|
+
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.`, {
|
|
219
219
|
via: n.kind,
|
|
220
220
|
crossOrigin: this.isCrossOriginFrame()
|
|
221
|
-
})), this.diagnostics.report("bus.role_resolved", `role is ${this.role}
|
|
221
|
+
})), this.diagnostics.report("bus.role_resolved", `The bus role is ${this.role}.`, {
|
|
222
222
|
role: this.role,
|
|
223
223
|
via: i ? n.kind : "none"
|
|
224
224
|
}), this.resolved = !0, this.announce(), this.role;
|
|
@@ -375,4 +375,4 @@ var h = {
|
|
|
375
375
|
//#endregion
|
|
376
376
|
export { _ as Bus };
|
|
377
377
|
|
|
378
|
-
//# sourceMappingURL=bus-
|
|
378
|
+
//# sourceMappingURL=bus-BTMuVkDk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bus-BTMuVkDk.js","names":["RUNTIME_GLOBAL_KEY","BUS_PROTOCOL","BUS_CHANNEL_NAME","BUS_HANDSHAKE_TIMEOUT_MS","unrefTimer","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"],"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\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} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { Journey } from \"../core/journey\";\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}\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 /** 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 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 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 \"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 }\n}\n"],"mappings":";;;AAwEA,SAAgBK,EAAS,GAAkC;CACzD,OAAO;EAAE,GAAGJ;EAAc,GAAGK;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;;;AC5BA,IAAMI,IAAc,OAAO,IAAIV,CAAkB;AAQjD,SAAgBW,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,GA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B,KAAK,SAAS,KAAK,WAAW,CAAC,KAExE,KAAK,SAAS,aAAa,aAAa,KAAK,SAAS,aAAa,kBACrE2D,EAAK,KAAK,kBAAkB,CAAC;CAEjC;CAGA,oBAAyC;EAOvC,OANA,KAAK,gBAAgB/B,EACnB5B,GACA,KAAK,SAAS,aACd,KAAK,SACL,KAAK,WACP,GACO,KAAK;CACd;CAOA,UAAkB,GAAmC;EACnD,OAAO,IAAI,SAAS,MAAY;GAC9B,IAAI4D,IAAU,IAERC,KAAU,MAA0B;IACxC,AAAID,MAGJ,IAAU,IACV,KAAK,kBAAkB,MACvB,aAAaE,CAAK,GAClBC,EAAQC,CAAM;GAChB;GAEA,KAAK,kBAAkB;IAAE,MAAMd,EAAU;IAAM,QAAQW;GAAO;GAG9D,IAAMC,IAAQ,iBAAiB;IAC7B,EAAO,EAAK;GACd,GAAG,KAAK,iBAAiB,SAAS;GAElC,AADA5D,EAAW4D,CAAK,GAChBZ,EAAU,KAAK;IAAE,GAAG;IAAS,MAAM,KAAK;IAAW,OAAO,KAAK;GAAM,CAAC;EACxE,CAAC;CACH;CAGA,WAAyB;EAMvB,AALA,KAAK,SAAS,aAAa;GACzB,GAAG;GACH,MAAM,KAAK;GACX,OAAO,KAAK;EACd,CAAC,GACD,KAAK,KAAK;GAAE,GAAG;GAAY,MAAM,KAAK;EAAU,CAAC;CACnD;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants-TUFcy95w.cjs"),t=require("./unref-CU9Nyz_9.cjs");function n(t){return{p:e.S,m:t}}function r(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 i=Symbol.for(e.Rt);function a(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[i]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,a=!0;return{kind:`direct`,post(n){a&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e)})},close(){a=!1}}}function o(e,t){if(typeof window>`u`||window.parent===window)return null;let i=t=>{let n=r(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,i),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(n(e),`*`)})},close(){removeEventListener(`message`,i)}}}function s(e,t,i){if(typeof window>`u`)return null;let a=new Set([window.location.origin,...t]),o=new Map,s=t=>{let n=r(t.data);n&&(a.has(t.origin)?(t.source&&o.set(t.source,t.origin),e(n,{link:`children`,origin:t.origin})):i.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:n.t}))};return addEventListener(`message`,s),{kind:`children`,post(e){for(let[t,r]of o){let a=t;a.closed?o.delete(t):i.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{a.postMessage(n(e),r)})}},close(){removeEventListener(`message`,s),o.clear()}}}function c(e,t,i){let a=globalThis.BroadcastChannel;if(a===void 0)return null;let o=i.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new a(e));return o?(o.onmessage=e=>{let n=r(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){i.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{o.postMessage(n(e))})},close(){i.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{o.close()})}}):null}function l(e,t,i,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=r(e);t&&i(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){a.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>o.publish(s,n(e)))},close(){}}}function u(e,t){let i=globalThis,a=i.postMessage;return i.WorkerGlobalScope===void 0||!a?null:(i.addEventListener?.(`message`,t=>{let n=r(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(n(e))})},close(){}})}function d(e,t,i){let a=e=>{let n=r(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,a),e.start?.(),{kind:`worker`,post(t){i.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(n(t))})},close(){e.removeEventListener(`message`,a)}}}var f={timeoutMs:e.x,maxAttempts:3},p=[`children`,`direct`,`worker`],m=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=f){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=a(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 this.receive(e,n)}attachWorker(e){this.links.push(d(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){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`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:p.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?u(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:o(this.receive,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(s(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(c(e.b,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=l(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})}};exports.Bus=m;
|
|
2
|
+
//# sourceMappingURL=bus-ChIXDAWD.cjs.map
|