@utk09/ui-observability 0.4.1 → 0.5.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 (69) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +69 -31
  3. package/dist/bus-D3OO0OcL.js +378 -0
  4. package/dist/bus-D3OO0OcL.js.map +1 -0
  5. package/dist/bus-OdRJVUzr.cjs +2 -0
  6. package/dist/bus-OdRJVUzr.cjs.map +1 -0
  7. package/dist/capture/web-vitals.d.ts +4 -1
  8. package/dist/{constants-DVbpJ1tv.js → constants-B6kdsCzF.js} +9 -8
  9. package/dist/constants-B6kdsCzF.js.map +1 -0
  10. package/dist/constants-DZH04585.cjs +2 -0
  11. package/dist/constants-DZH04585.cjs.map +1 -0
  12. package/dist/constants.d.ts +3 -1
  13. package/dist/core/journey.d.ts +5 -2
  14. package/dist/core/logger.d.ts +22 -3
  15. package/dist/core/runtime.d.ts +100 -18
  16. package/dist/core/sender.d.ts +58 -0
  17. package/dist/errors-DPju_xSI.cjs +3 -0
  18. package/dist/errors-DPju_xSI.cjs.map +1 -0
  19. package/dist/errors-Dme9tz-6.js +76 -0
  20. package/dist/errors-Dme9tz-6.js.map +1 -0
  21. package/dist/index.cjs +1 -3
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.js +452 -2223
  24. package/dist/index.js.map +1 -1
  25. package/dist/indexeddb-storage-lGdoHGHy.cjs +2 -0
  26. package/dist/indexeddb-storage-lGdoHGHy.cjs.map +1 -0
  27. package/dist/{indexeddb-storage-B6uqejZb.js → indexeddb-storage-nxs_rxGx.js} +4 -8
  28. package/dist/indexeddb-storage-nxs_rxGx.js.map +1 -0
  29. package/dist/interactions-C1romMpE.js +67 -0
  30. package/dist/interactions-C1romMpE.js.map +1 -0
  31. package/dist/interactions-DP0-rIPJ.cjs +2 -0
  32. package/dist/interactions-DP0-rIPJ.cjs.map +1 -0
  33. package/dist/models/config.d.ts +29 -11
  34. package/dist/network-DDVIJSHd.cjs +2 -0
  35. package/dist/network-DDVIJSHd.cjs.map +1 -0
  36. package/dist/network-au-Tqt1n.js +111 -0
  37. package/dist/network-au-Tqt1n.js.map +1 -0
  38. package/dist/platform-DMYo3AX3.js +48 -0
  39. package/dist/platform-DMYo3AX3.js.map +1 -0
  40. package/dist/platform-g99Kn755.cjs +2 -0
  41. package/dist/platform-g99Kn755.cjs.map +1 -0
  42. package/dist/sampling-ByI5H44E.js +248 -0
  43. package/dist/sampling-ByI5H44E.js.map +1 -0
  44. package/dist/sampling-Dui-Fp3u.cjs +2 -0
  45. package/dist/sampling-Dui-Fp3u.cjs.map +1 -0
  46. package/dist/sender-R7lOpyNc.js +907 -0
  47. package/dist/sender-R7lOpyNc.js.map +1 -0
  48. package/dist/sender-vLcbQhiB.cjs +3 -0
  49. package/dist/sender-vLcbQhiB.cjs.map +1 -0
  50. package/dist/transport/http-transport.d.ts +2 -0
  51. package/dist/transport/serializers/select.d.ts +8 -0
  52. package/dist/unref-16maCyKA.js +8 -0
  53. package/dist/unref-16maCyKA.js.map +1 -0
  54. package/dist/unref-CU9Nyz_9.cjs +2 -0
  55. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  56. package/dist/utils/console.d.ts +11 -3
  57. package/dist/utils/identity.d.ts +47 -3
  58. package/dist/utils/tracing.d.ts +6 -5
  59. package/dist/web-vitals-DM2nvcMJ.cjs +2 -0
  60. package/dist/web-vitals-DM2nvcMJ.cjs.map +1 -0
  61. package/dist/web-vitals-DwWdLBq6.js +51 -0
  62. package/dist/web-vitals-DwWdLBq6.js.map +1 -0
  63. package/package.json +21 -11
  64. package/dist/constants-DVbpJ1tv.js.map +0 -1
  65. package/dist/constants-tQpoTzkY.cjs +0 -2
  66. package/dist/constants-tQpoTzkY.cjs.map +0 -1
  67. package/dist/indexeddb-storage-B6uqejZb.js.map +0 -1
  68. package/dist/indexeddb-storage-CgT1GLYj.cjs +0 -2
  69. package/dist/indexeddb-storage-CgT1GLYj.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,53 @@
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.5.0] - 2026-10-11
6
+
7
+ ### Breaking changes - v0.5.0
8
+
9
+ - The library does not import `@opentelemetry/api` by itself. Set `otelLoader` to put records on your spans. Without `otelLoader`, OTel is off. The library reports no diagnostic.
10
+ - `capture.webVitals` needs `capture.webVitalsLoader`. Without the loader, the library reports `config.invalid`. Navigation timing continues.
11
+ - `console` does not depend on `minLevel`. `minLevel` limits what the library sends. `console` limits what it prints.
12
+ - A console line starts with the logger namespace, for example `[board.hop] WARN`. It started with `[ui-observability]`.
13
+ - A console line shows the caller's payload. It showed all record attributes.
14
+ - With a `redact` hook, the console shows only what `redact` returns. A record that the library does not build shows its message and error only.
15
+ - After `shutdown()`, every call does nothing until the next `configure()`. A log call after `shutdown()` started a new runtime with default settings.
16
+ - After the delivery stack loads, `configure({ endpoint: null })` and `configure({ endpoint: "" })` report `config.invalid`. The endpoint in force stays.
17
+ - `OneLogger` takes a function that returns the runtime. It took the runtime.
18
+
19
+ ```ts
20
+ // OpenTelemetry, imported by the library before 0.5.0
21
+ configure({ endpoint, otelLoader: () => import("@opentelemetry/api") });
22
+
23
+ // web vitals
24
+ configure({ endpoint, capture: { webVitals: true, webVitalsLoader: () => import("web-vitals") } });
25
+ ```
26
+
27
+ ### Added - v0.5.0
28
+
29
+ - `endpoint: null` selects console-only mode. The library sends nothing. It reports no diagnostic about the endpoint. A missing endpoint or `""` still reports `config.invalid`.
30
+ - `identity: "memory"` keeps session, tab and journey ids in memory. The library writes no key to `localStorage` or `sessionStorage` for them. You cannot change `identity` after startup.
31
+ - `npm run check:peers` fails if a built file imports an optional peer by name.
32
+
33
+ ### Fixed - v0.5.0
34
+
35
+ - The Vite dev server failed when a peer was not installed. `dist/index.js` imported `web-vitals` and `@opentelemetry/api` by name. Peers load only through the loaders.
36
+ - `getLogger()` before `configure()` started a runtime with default settings. That runtime refused a later `configure({ storage })`. A logger finds the runtime on its first write.
37
+ - A logger held across `shutdown()` wrote to the destroyed runtime. After the next `configure()`, it writes to the new runtime.
38
+ - `error(message, err, payload)` printed the error without the payload. The console line shows both.
39
+ - A `shutdown()` during startup still installed the capture modules. Their window listeners stayed until the page closed.
40
+ - `endpoint: undefined` in a later `configure()` removed the live endpoint. The endpoint in force now stays.
41
+ - The runtime dropped a forwarded record that arrived before the pipeline existed. The record now waits for the delivery stack.
42
+ - A `configure()` during startup did not apply to `endpoint` or `capture`. It applies now.
43
+ - A worker registered in a nested frame lost its handshake while the bus started. The runtime now attaches the worker when it constructs the bus.
44
+ - `flush()`, `getQueueDepth()` and `shutdown()` did not wait for a delivery stack that was still loading. They wait now.
45
+ - A `%o` or `%c` in a logger namespace changed the console output. The namespace now prints as text.
46
+ - A failed exit flush install left the retry loop running. The library now stops the retry loop.
47
+
48
+ ### Performance - v0.5.0
49
+
50
+ - The main chunk holds only 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. A console-only setup loads half the code of 0.4.1.
51
+
5
52
  ## [0.4.1] - 2026-09-09
6
53
 
7
54
  ### Fixed - v0.4.1
package/README.md CHANGED
@@ -18,7 +18,7 @@ npm install @utk09/ui-observability
18
18
 
19
19
  Both peers are optional. The library has no runtime dependency.
20
20
 
21
- Install `web-vitals` (`^4 || ^5 || ^6`) for `capture.webVitals`:
21
+ Install `web-vitals` (`^4 || ^5 || ^6`) for `capture.webVitals`, and set `capture.webVitalsLoader`. Without the loader, the library reports `config.invalid`:
22
22
 
23
23
  ```ts
24
24
  configure({
@@ -30,7 +30,7 @@ configure({
30
30
  });
31
31
  ```
32
32
 
33
- Install `@opentelemetry/api` (`^1`) to put records on the traces your spans carry. Without it, the library mints its own `trace_id` and reports `trace.otel_failed` one time. The library imports the package when it is installed. Set `otelLoader` when your bundler cannot resolve the import:
33
+ Install `@opentelemetry/api` (`^1`) to put records on the traces your spans carry. Set `otelLoader` to load it. Without `otelLoader`, OTel is off and the library mints its own `trace_id`. The library never imports a peer by name, so a missing peer cannot break your bundler or dev server:
34
34
 
35
35
  ```ts
36
36
  configure({
@@ -62,9 +62,31 @@ log.logAction("ORDER_SUBMIT", { orderId: "ORD-1001", qty: 100 });
62
62
  log.error("pricing call failed", caughtError);
63
63
  ```
64
64
 
65
- - `configure()` is idempotent. A later call updates the runtime singleton in place. `storage` is fixed at startup. A later change to it is reported and ignored.
65
+ - `configure()` is idempotent. A later call updates the runtime singleton in place. `storage` and `identity` are fixed at startup. A later change to them is reported and ignored.
66
66
  - One context per document calls `configure()`. A second call renames `service.name` on the records of every other context. In a composed page, the shell configures, and each microfrontend takes a namespace.
67
- - A log call before `configure()` goes to an implicit runtime. It does not throw.
67
+ - 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.
69
+
70
+ ### Console Only (No Network)
71
+
72
+ Set `endpoint: null`. The library sends nothing. It writes records to the console only.
73
+
74
+ ```ts
75
+ configure({
76
+ endpoint: null,
77
+ serviceName: "skardela",
78
+ identity: "memory",
79
+ storage: "none",
80
+ bus: { mode: "off" },
81
+ console: import.meta.env.DEV ? "DEBUG" : "WARN",
82
+ });
83
+ ```
84
+
85
+ - `endpoint: null` loads no transport, no storage and no exit flush. It reports no diagnostic.
86
+ - `identity: "memory"` writes no key to `localStorage` or `sessionStorage`.
87
+ - `console` and `minLevel` are independent. `console` sets what the library prints. `minLevel` sets what the library sends.
88
+ - 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 that the library does not build shows its message and error only.
68
90
 
69
91
  ---
70
92
 
@@ -121,32 +143,33 @@ log.error("pricing call failed", caughtError);
121
143
 
122
144
  ## Configuration Options
123
145
 
124
- `endpoint` is the only required key.
125
-
126
- | Key | Default | Description |
127
- | ---------------------------- | ------------ | --------------------------------------------------------------------------------- |
128
- | `endpoint` | _required_ | HTTP endpoint that receives the batches. |
129
- | `serviceName` | `""` | `service.name` on every record. |
130
- | `serviceVersion` | `""` | `service.version` on every record. |
131
- | `environment` | `""` | `deployment.environment` on every record. |
132
- | `enabled` | `true` | Kill switch. `false` makes every log call a no-op. |
133
- | `minLevel` | `"INFO"` | Lowest level that ships (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`). |
134
- | `compression` | `"gzip"` | `gzip` or `none`. It applies above 1 KB. |
135
- | `serializer` | `"otlp"` | `otlp`, `ecs`, or a custom `LogSerializer`. |
136
- | `credentials` | `"omit"` | Fetch credentials mode. Set `"include"` for cookie auth. |
137
- | `headers` | `{}` | Static headers, or a function that returns them. |
138
- | `storage` | `"auto"` | `auto`, `indexeddb`, `localstorage`, `memory` or `none`. Fixed at startup. |
139
- | `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule. |
140
- | `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins. |
141
- | `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate. |
142
- | `bus.mode` | `"auto"` | `auto`, `sender`, `forwarder` or `off`. |
143
- | `bus.trustedOrigins` | `[]` | Origins that may post records from a cross-origin frame. |
144
- | `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`. |
145
- | `capture` | See below | Auto-capture settings. |
146
- | `console` | `false` | Mirrors records to devtools. `true` starts at `DEBUG`. A level name starts there. |
147
- | `otelLoader()` | `undefined` | Supplies `@opentelemetry/api`. Omit it and the library imports the package. |
148
- | `redact(record)` | `undefined` | Mutates a record before it ships. Return `null` to drop it. |
149
- | `onDiagnostic(event)` | `undefined` | Receives this library's own faults. |
146
+ No key is required. Set `endpoint` to send records.
147
+
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` | Kill switch. `false` makes every log call a no-op. |
155
+ | `minLevel` | `"INFO"` | Lowest level that the library sends (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`). |
156
+ | `compression` | `"gzip"` | `gzip` or `none`. It applies above 1 KB. |
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` sends this context's own records and opens no link. A same-origin child frame can still forward to it. |
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` starts at `DEBUG`. A level name starts there. It does not depend on `minLevel`. |
170
+ | `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off. |
171
+ | `redact(record)` | `undefined` | Mutates a record before it ships. Return `null` to drop it. |
172
+ | `onDiagnostic(event)` | `undefined` | Receives this library's own faults. |
150
173
 
151
174
  ### Auto-Capture Options
152
175
 
@@ -168,16 +191,30 @@ capture: {
168
191
 
169
192
  `fullUrls` is off. The library cuts a page URL, a request target and a failed resource URL at the first `?` or `#`. `ignoreUrls` and `propagateTraceHeaderTo` match the whole URL.
170
193
 
194
+ ### Browser Storage Keys
195
+
196
+ | Key | Store | Written when | Option that stops it |
197
+ | ------------------------------ | ---------------- | ---------------------------------------------------------------- | --------------------------------------------- |
198
+ | `ui-observability.session` | `localStorage` | At startup, then at most one time each minute while logging | `identity: "memory"` |
199
+ | `ui-observability.tab` | `sessionStorage` | At startup, and when the bus finds a duplicated tab | `identity: "memory"` |
200
+ | `ui-observability.journey` | `sessionStorage` | When a journey starts or ends | `identity: "memory"` |
201
+ | `ui-observability.batch.*` | `localStorage` | When a send fails and the `localstorage` adapter holds the batch | `storage` other than `auto` or `localstorage` |
202
+ | `ui-observability.emergency.*` | `localStorage` | When the exit flush cannot send a batch | `endpoint: null` |
203
+ | `ui-observability.probe` | `localStorage` | One write and one remove, when the library tests `localStorage` | `storage` other than `auto` or `localstorage` |
204
+
205
+ IndexedDB holds undelivered batches with `storage: "auto"` or `"indexeddb"`.
206
+
171
207
  ---
172
208
 
173
209
  ## Core Architecture
174
210
 
211
+ - **Code splitting:** The main chunk holds the logger, the record builder and the console sink. The delivery stack loads only when an endpoint is set. The bus loads only when the context needs it. Each capture module loads only when it is enabled.
175
212
  - **Document singleton:** The runtime pins to `globalThis[Symbol.for("ui-observability.runtime")]`. Federated microfrontends and separate bundles share one buffer, one sequence and one transport.
176
213
  - **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.
177
214
  - **Five correlation ids:** Each record carries `session.id`, `tab.id`, `context.id`, `journey.id` and `trace_id`.
178
215
  - **Durability and exit flush:** A failed send persists to IndexedDB or localStorage, then retries with exponential jittered backoff. On `pagehide` or `freeze`, pending records go out with `navigator.sendBeacon` below 60 KB. A larger payload goes to the emergency queue.
179
216
  - **Emergency queue:** The emergency queue is best effort. It writes to `localStorage` synchronously. No other storage works while the document unloads. A refused write reports `storage.quota_exceeded`. The library then loses the batch.
180
- - **Configuration after startup:** A second `configure()` call merges the new options into the live runtime. The `storage` option is the exception. The runtime builds the storage adapter one time. A change leaves the stored batches in the old adapter. The runtime refuses the change. It reports `config.invalid`.
217
+ - **Configuration after startup:** A second `configure()` call merges the new options into the live runtime. The `storage` option is the exception. The runtime builds the storage adapter one time. A change leaves the stored batches in the old adapter. The runtime refuses the change. It reports `config.invalid`. The same rule applies to `identity`, and to an endpoint change to `null` or `""` after the delivery stack loads. A change to another endpoint URL is accepted.
181
218
  - **Deterministic sampling:** FNV-1a hashing applies one keep rate to a whole journey. An error and an explicit action bypass sampling.
182
219
 
183
220
  ---
@@ -214,6 +251,7 @@ npm run build
214
251
  npm run example:react # http://localhost:5180
215
252
  npm run example:angular # http://localhost:4200
216
253
  npm run example:microfrontend # Shell on http://localhost:5191, remotes on 5192 and 5193
254
+ npm run example:console-only # http://localhost:5195
217
255
  ```
218
256
 
219
257
  ---
@@ -0,0 +1,378 @@
1
+ import { Rt as e, S as t, b as n, x as r } from "./constants-B6kdsCzF.js";
2
+ import { t as i } from "./unref-16maCyKA.js";
3
+ //#region src/models/bus.ts
4
+ function a(e) {
5
+ return {
6
+ p: t,
7
+ m: e
8
+ };
9
+ }
10
+ function o(e) {
11
+ if (typeof e != "object" || !e) return null;
12
+ let t = e;
13
+ if (t.p !== "ui-observability/1" || typeof t.m != "object" || t.m === null) return null;
14
+ let n = t.m;
15
+ return typeof n.t == "string" ? n : null;
16
+ }
17
+ //#endregion
18
+ //#region src/bus/links.ts
19
+ var s = Symbol.for(e);
20
+ function c(e, t) {
21
+ if (typeof window > "u" || window.parent === window) return null;
22
+ let n;
23
+ try {
24
+ n = window.parent[s];
25
+ } catch {
26
+ return null;
27
+ }
28
+ if (typeof n?.busAccept != "function") return null;
29
+ let r = n, i = !0;
30
+ return {
31
+ kind: "direct",
32
+ post(n) {
33
+ i && t.guard("bus.send_failed", "direct call into the parent runtime", () => {
34
+ r.busAccept(n, e);
35
+ });
36
+ },
37
+ close() {
38
+ i = !1;
39
+ }
40
+ };
41
+ }
42
+ function l(e, t) {
43
+ if (typeof window > "u" || window.parent === window) return null;
44
+ let n = (t) => {
45
+ let n = o(t.data);
46
+ n && t.source === window.parent && e(n, {
47
+ link: "parent",
48
+ origin: t.origin
49
+ });
50
+ };
51
+ return addEventListener("message", n), {
52
+ kind: "parent",
53
+ post(e) {
54
+ t.guard("bus.send_failed", "postMessage to parent", () => {
55
+ window.parent.postMessage(a(e), "*");
56
+ });
57
+ },
58
+ close() {
59
+ removeEventListener("message", n);
60
+ }
61
+ };
62
+ }
63
+ function u(e, t, n) {
64
+ if (typeof window > "u") return null;
65
+ let r = /* @__PURE__ */ new Set([window.location.origin, ...t]), i = /* @__PURE__ */ new Map(), s = (t) => {
66
+ let a = o(t.data);
67
+ a && (r.has(t.origin) ? (t.source && i.set(t.source, t.origin), e(a, {
68
+ link: "children",
69
+ origin: t.origin
70
+ })) : n.report("bus.untrusted_origin", `ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`, {
71
+ origin: t.origin,
72
+ type: a.t
73
+ }));
74
+ };
75
+ return addEventListener("message", s), {
76
+ kind: "children",
77
+ post(e) {
78
+ for (let [t, r] of i) {
79
+ let o = t;
80
+ o.closed ? i.delete(t) : n.guard("bus.send_failed", "postMessage to child", () => {
81
+ o.postMessage(a(e), r);
82
+ });
83
+ }
84
+ },
85
+ close() {
86
+ removeEventListener("message", s), i.clear();
87
+ }
88
+ };
89
+ }
90
+ function d(e, t, n) {
91
+ let r = globalThis.BroadcastChannel;
92
+ if (r === void 0) return null;
93
+ let i = n.guard("bus.send_failed", "opening BroadcastChannel", () => new r(e));
94
+ return i ? (i.onmessage = (e) => {
95
+ let n = o(e.data);
96
+ n && t(n, {
97
+ link: "broadcast",
98
+ origin: "same-origin"
99
+ });
100
+ }, {
101
+ kind: "broadcast",
102
+ post(e) {
103
+ n.guard("bus.send_failed", "BroadcastChannel.postMessage", () => {
104
+ i.postMessage(a(e));
105
+ });
106
+ },
107
+ close() {
108
+ n.guard("bus.send_failed", "closing BroadcastChannel", () => {
109
+ i.close();
110
+ });
111
+ }
112
+ }) : null;
113
+ }
114
+ function f(e, t, n, r) {
115
+ let i = globalThis.fin?.InterApplicationBus;
116
+ if (!i) return null;
117
+ if (!t) return r.report("openfin.unavailable", "no OpenFin application uuid, so the InterApplicationBus link stays closed"), null;
118
+ let s = `${e}.${t}`;
119
+ return r.guardAsync("bus.send_failed", "InterApplicationBus.subscribe", () => i.subscribe({ uuid: t }, s, (e) => {
120
+ let t = o(e);
121
+ t && n(t, {
122
+ link: "openfin",
123
+ origin: "openfin"
124
+ });
125
+ })), {
126
+ kind: "openfin",
127
+ post(e) {
128
+ r.guardAsync("bus.send_failed", "InterApplicationBus.publish", () => i.publish(s, a(e)));
129
+ },
130
+ close() {}
131
+ };
132
+ }
133
+ function p(e, t) {
134
+ let n = globalThis, r = n.postMessage;
135
+ return n.WorkerGlobalScope === void 0 || !r ? null : (n.addEventListener?.("message", (t) => {
136
+ let n = o(t.data);
137
+ n && e(n, {
138
+ link: "owner",
139
+ origin: "same-origin"
140
+ });
141
+ }), {
142
+ kind: "owner",
143
+ post(e) {
144
+ t.guard("bus.send_failed", "worker postMessage", () => {
145
+ r(a(e));
146
+ });
147
+ },
148
+ close() {}
149
+ });
150
+ }
151
+ function m(e, t, n) {
152
+ let r = (e) => {
153
+ let n = o(e.data);
154
+ n && t(n, {
155
+ link: "worker",
156
+ origin: "same-origin"
157
+ });
158
+ };
159
+ return e.addEventListener("message", r), e.start?.(), {
160
+ kind: "worker",
161
+ post(t) {
162
+ n.guard("bus.send_failed", "postMessage to a worker", () => {
163
+ e.postMessage(a(t));
164
+ });
165
+ },
166
+ close() {
167
+ e.removeEventListener("message", r);
168
+ }
169
+ };
170
+ }
171
+ //#endregion
172
+ //#region src/bus/bus.ts
173
+ var h = {
174
+ timeoutMs: r,
175
+ maxAttempts: 3
176
+ }, g = [
177
+ "children",
178
+ "direct",
179
+ "worker"
180
+ ], _ = class {
181
+ config;
182
+ diagnostics;
183
+ platform;
184
+ contextId;
185
+ tabId;
186
+ handlers;
187
+ handshakeOptions;
188
+ role = "sender";
189
+ upstream = null;
190
+ links = [];
191
+ openFinLink = null;
192
+ isOpenFinProvider = !1;
193
+ resolved = !1;
194
+ awaitingWelcome = null;
195
+ constructor(e, t, n, r, i, a, o = h) {
196
+ this.config = e, this.diagnostics = t, this.platform = n, this.contextId = r, this.tabId = i, this.handlers = a, this.handshakeOptions = o;
197
+ }
198
+ getRole() {
199
+ return this.role;
200
+ }
201
+ isResolved() {
202
+ return this.resolved;
203
+ }
204
+ async start() {
205
+ let { bus: e } = this.config;
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\" but there is no owner to forward to. Records will be dropped.")), this.resolved = !0, this.announce(), this.role;
208
+ this.openControlLinks();
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 runtime", {
211
+ role: "forwarder",
212
+ via: "direct"
213
+ }), this.announce(), this.role;
214
+ let n = this.candidateUpstream();
215
+ if (!n) return this.role = "sender", this.resolved = !0, this.diagnostics.report("bus.role_resolved", "no owner to forward to, sending directly", { role: "sender" }), this.announce(), this.role;
216
+ let r = this.orphanPolicy() === "retry" ? this.handshakeOptions.maxAttempts : 1, i = !1;
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", `no owner answered after ${String(r)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)}ms, promoting to sender`, {
219
+ via: n.kind,
220
+ crossOrigin: this.isCrossOriginFrame()
221
+ })), this.diagnostics.report("bus.role_resolved", `role is ${this.role}`, {
222
+ role: this.role,
223
+ via: i ? n.kind : "none"
224
+ }), this.resolved = !0, this.announce(), this.role;
225
+ }
226
+ sendRecords(e) {
227
+ this.upstream?.post({
228
+ t: "records",
229
+ from: this.contextId,
230
+ records: e
231
+ });
232
+ }
233
+ acceptDirect(e, t) {
234
+ if (e.from === this.contextId) return;
235
+ let n = {
236
+ link: "direct",
237
+ origin: "same-origin"
238
+ };
239
+ if (e.t === "hello") this.canOwn("direct") && t({
240
+ t: "welcome",
241
+ from: this.contextId,
242
+ to: e.from,
243
+ tabId: this.tabId
244
+ }, n);
245
+ else if (e.t === "journey?") {
246
+ let e = this.handlers.onJourneyRequest();
247
+ e && t({
248
+ t: "journey",
249
+ from: this.contextId,
250
+ journey: e
251
+ }, n);
252
+ } else this.receive(e, n);
253
+ }
254
+ attachWorker(e) {
255
+ this.links.push(m(e, this.receive, this.diagnostics));
256
+ }
257
+ broadcastJourney(e) {
258
+ this.post({
259
+ t: "journey",
260
+ from: this.contextId,
261
+ journey: e
262
+ });
263
+ }
264
+ destroy() {
265
+ for (let e of this.allLinks()) e.close();
266
+ this.links.length = 0, this.upstream = null, this.openFinLink = null;
267
+ }
268
+ allLinks() {
269
+ return !this.upstream || this.links.includes(this.upstream) ? this.links : [...this.links, this.upstream];
270
+ }
271
+ post(e) {
272
+ for (let t of this.allLinks()) t.post(e);
273
+ }
274
+ postOver(e, t) {
275
+ for (let n of this.allLinks()) n.kind === e && n.post(t);
276
+ }
277
+ receive = (e, t) => {
278
+ if (e.from !== this.contextId) switch (e.t) {
279
+ case "hello":
280
+ this.canOwn(t.link) && this.postOver(t.link, {
281
+ t: "welcome",
282
+ from: this.contextId,
283
+ to: e.from,
284
+ tabId: this.tabId
285
+ });
286
+ break;
287
+ case "welcome":
288
+ if (e.to !== this.contextId) break;
289
+ this.awaitingWelcome?.link === t.link && this.awaitingWelcome.settle(!0);
290
+ break;
291
+ case "records":
292
+ this.role === "sender" ? this.handlers.onRecords(e.records) : this.upstream && this.canRelay(t.link) && this.upstream.post(e);
293
+ break;
294
+ case "journey":
295
+ this.handlers.onJourney(e.journey);
296
+ break;
297
+ case "journey?": {
298
+ let e = this.handlers.onJourneyRequest();
299
+ e && this.postOver(t.link, {
300
+ t: "journey",
301
+ from: this.contextId,
302
+ journey: e
303
+ });
304
+ break;
305
+ }
306
+ case "tab": t.link === "broadcast" && e.tabId === this.tabId && this.contextId > e.from && this.handlers.onTabConflict();
307
+ }
308
+ };
309
+ canRelay(e) {
310
+ return e === "direct" || e !== this.upstream?.kind;
311
+ }
312
+ canOwn(e) {
313
+ return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : g.includes(e) : !1;
314
+ }
315
+ resolveOpenFinProvider() {
316
+ let e = this.config.bus.openFinRole;
317
+ if (e !== "auto") return e === "provider";
318
+ if (this.platform.platform !== "openfin" && this.platform.platform !== "openfin_web") return !1;
319
+ let t = globalThis.fin?.me;
320
+ return !t?.identity || t.isView ? !1 : !!(t.identity.name && t.identity.name === t.identity.uuid);
321
+ }
322
+ orphanPolicy() {
323
+ return this.isCrossOriginFrame() ? "retry" : "promote";
324
+ }
325
+ isCrossOriginFrame() {
326
+ if (typeof window > "u" || window.parent === window) return !1;
327
+ try {
328
+ return Reflect.get(window.parent, "location"), !1;
329
+ } catch {
330
+ return !0;
331
+ }
332
+ }
333
+ candidateUpstream() {
334
+ return this.platform.isWorker ? p(this.receive, this.diagnostics) : this.platform.isTopLevelDocument ? this.platform.platform === "openfin" && !this.isOpenFinProvider ? this.ensureOpenFinLink() : null : l(this.receive, this.diagnostics);
335
+ }
336
+ openControlLinks() {
337
+ let e = (e) => {
338
+ e && this.links.push(e);
339
+ };
340
+ this.platform.isTopLevelDocument && (e(u(this.receive, this.config.bus.trustedOrigins, this.diagnostics)), e(d(n, this.receive, this.diagnostics))), (this.platform.platform === "openfin" || this.platform.platform === "openfin_web") && e(this.ensureOpenFinLink());
341
+ }
342
+ ensureOpenFinLink() {
343
+ return this.openFinLink ??= f(n, this.platform.openfinUuid, this.receive, this.diagnostics), this.openFinLink;
344
+ }
345
+ handshake(e) {
346
+ return new Promise((t) => {
347
+ let n = !1, r = (e) => {
348
+ n || (n = !0, this.awaitingWelcome = null, clearTimeout(a), t(e));
349
+ };
350
+ this.awaitingWelcome = {
351
+ link: e.kind,
352
+ settle: r
353
+ };
354
+ let a = setTimeout(() => {
355
+ r(!1);
356
+ }, this.handshakeOptions.timeoutMs);
357
+ i(a), e.post({
358
+ t: "hello",
359
+ from: this.contextId,
360
+ tabId: this.tabId
361
+ });
362
+ });
363
+ }
364
+ announce() {
365
+ this.postOver("broadcast", {
366
+ t: "tab",
367
+ from: this.contextId,
368
+ tabId: this.tabId
369
+ }), this.post({
370
+ t: "journey?",
371
+ from: this.contextId
372
+ });
373
+ }
374
+ };
375
+ //#endregion
376
+ export { _ as Bus };
377
+
378
+ //# sourceMappingURL=bus-D3OO0OcL.js.map