@utk09/ui-observability 0.7.0 → 0.9.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 (180) hide show
  1. package/CHANGELOG.md +79 -1
  2. package/README.md +170 -41
  3. package/dist/bus/bus.d.ts +75 -11
  4. package/dist/bus/links.d.ts +6 -3
  5. package/dist/bus-CtJWf9QN.cjs +2 -0
  6. package/dist/bus-CtJWf9QN.cjs.map +1 -0
  7. package/dist/{bus-DfAbg_pg.js → bus-D8kH58tb.js} +176 -73
  8. package/dist/bus-D8kH58tb.js.map +1 -0
  9. package/dist/capture/console.d.ts +37 -0
  10. package/dist/capture/errors.d.ts +2 -4
  11. package/dist/capture/interactions.d.ts +7 -6
  12. package/dist/capture/long-frames.d.ts +31 -0
  13. package/dist/capture/network.d.ts +23 -9
  14. package/dist/capture/storm.d.ts +17 -0
  15. package/dist/capture/types.d.ts +5 -3
  16. package/dist/console-BpHfWstv.cjs +2 -0
  17. package/dist/console-BpHfWstv.cjs.map +1 -0
  18. package/dist/console-DjLbryED.js +82 -0
  19. package/dist/console-DjLbryED.js.map +1 -0
  20. package/dist/constants-Br3b89Wg.cjs +2 -0
  21. package/dist/constants-Br3b89Wg.cjs.map +1 -0
  22. package/dist/constants-DM94FjVX.js +96 -0
  23. package/dist/constants-DM94FjVX.js.map +1 -0
  24. package/dist/constants.d.ts +51 -10
  25. package/dist/core/breadcrumbs.d.ts +1 -1
  26. package/dist/core/diagnostics.d.ts +2 -2
  27. package/dist/core/journey.d.ts +16 -4
  28. package/dist/core/logger.d.ts +6 -2
  29. package/dist/core/pipeline.d.ts +20 -11
  30. package/dist/core/record.d.ts +14 -6
  31. package/dist/core/remote-rules.d.ts +17 -0
  32. package/dist/core/remote-sampling.d.ts +65 -0
  33. package/dist/core/runtime.d.ts +52 -18
  34. package/dist/core/sampling.d.ts +5 -2
  35. package/dist/core/sender.d.ts +18 -10
  36. package/dist/deadline-B5DINjD5.js +111 -0
  37. package/dist/deadline-B5DINjD5.js.map +1 -0
  38. package/dist/deadline-Cbg2cbUw.cjs +2 -0
  39. package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
  40. package/dist/error-like-Ywo5uRHo.js +19 -0
  41. package/dist/error-like-Ywo5uRHo.js.map +1 -0
  42. package/dist/error-like-gGRx2s36.cjs +2 -0
  43. package/dist/error-like-gGRx2s36.cjs.map +1 -0
  44. package/dist/errors-CpGRhhIf.cjs +3 -0
  45. package/dist/errors-CpGRhhIf.cjs.map +1 -0
  46. package/dist/{errors-4MQyjZVj.js → errors-DH4QJS0u.js} +38 -20
  47. package/dist/errors-DH4QJS0u.js.map +1 -0
  48. package/dist/global-scope-BN-Io_yv.cjs +2 -0
  49. package/dist/global-scope-BN-Io_yv.cjs.map +1 -0
  50. package/dist/global-scope-dp2jADRl.js +19 -0
  51. package/dist/global-scope-dp2jADRl.js.map +1 -0
  52. package/dist/index.cjs +1 -1
  53. package/dist/index.cjs.map +1 -1
  54. package/dist/index.d.ts +13 -5
  55. package/dist/index.js +633 -463
  56. package/dist/index.js.map +1 -1
  57. package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
  58. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
  59. package/dist/{indexeddb-storage-0LtUALBg.js → indexeddb-storage-n1qkFBGA.js} +17 -17
  60. package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
  61. package/dist/interactions-31eHGwEQ.cjs +2 -0
  62. package/dist/interactions-31eHGwEQ.cjs.map +1 -0
  63. package/dist/{interactions-BaCmoGLB.js → interactions-OU94MPXs.js} +22 -19
  64. package/dist/interactions-OU94MPXs.js.map +1 -0
  65. package/dist/journey-CE2EcwHW.cjs +2 -0
  66. package/dist/journey-CE2EcwHW.cjs.map +1 -0
  67. package/dist/journey-CeJ1QoT2.js +162 -0
  68. package/dist/journey-CeJ1QoT2.js.map +1 -0
  69. package/dist/library-request-C9uJFlbq.cjs +2 -0
  70. package/dist/library-request-C9uJFlbq.cjs.map +1 -0
  71. package/dist/library-request-DvhuplAB.js +14 -0
  72. package/dist/library-request-DvhuplAB.js.map +1 -0
  73. package/dist/long-frames-B8VdA_ny.cjs +2 -0
  74. package/dist/long-frames-B8VdA_ny.cjs.map +1 -0
  75. package/dist/long-frames-C_7OutLs.js +65 -0
  76. package/dist/long-frames-C_7OutLs.js.map +1 -0
  77. package/dist/models/batch.d.ts +1 -1
  78. package/dist/models/bus.d.ts +23 -4
  79. package/dist/models/config.d.ts +132 -11
  80. package/dist/models/log-record.d.ts +12 -6
  81. package/dist/network-BAV7ipyn.cjs +2 -0
  82. package/dist/network-BAV7ipyn.cjs.map +1 -0
  83. package/dist/network-D_lloS5t.js +174 -0
  84. package/dist/network-D_lloS5t.js.map +1 -0
  85. package/dist/patch-BX8KrPCT.cjs +2 -0
  86. package/dist/patch-BX8KrPCT.cjs.map +1 -0
  87. package/dist/patch-CCWfuEY7.js +9 -0
  88. package/dist/patch-CCWfuEY7.js.map +1 -0
  89. package/dist/{platform-ByQllE_W.cjs → platform-D4wu1eIF.cjs} +2 -2
  90. package/dist/platform-D4wu1eIF.cjs.map +1 -0
  91. package/dist/{platform-YuByH8A5.js → platform-IHBZGqUe.js} +9 -9
  92. package/dist/platform-IHBZGqUe.js.map +1 -0
  93. package/dist/remote-rules-Bt1XsdEQ.js +86 -0
  94. package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
  95. package/dist/remote-rules-kuDf5gbe.cjs +2 -0
  96. package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
  97. package/dist/sampling-BI15ds9D.cjs +2 -0
  98. package/dist/sampling-BI15ds9D.cjs.map +1 -0
  99. package/dist/sampling-o0VY1mqQ.js +63 -0
  100. package/dist/sampling-o0VY1mqQ.js.map +1 -0
  101. package/dist/sanitize-B9UheVKc.js +123 -0
  102. package/dist/sanitize-B9UheVKc.js.map +1 -0
  103. package/dist/sanitize-DSIP7amZ.cjs +2 -0
  104. package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
  105. package/dist/{sender-BIob8eZz.js → sender-BnNj9bOX.js} +415 -272
  106. package/dist/sender-BnNj9bOX.js.map +1 -0
  107. package/dist/sender-D0OsyB1c.cjs +3 -0
  108. package/dist/sender-D0OsyB1c.cjs.map +1 -0
  109. package/dist/storage/emergency-queue.d.ts +1 -1
  110. package/dist/storage/factory.d.ts +1 -1
  111. package/dist/storage/idb-driver.d.ts +1 -1
  112. package/dist/storage/local-storage.d.ts +3 -3
  113. package/dist/storage/memory-storage.d.ts +3 -3
  114. package/dist/storm-BTw0J6eE.js +10 -0
  115. package/dist/storm-BTw0J6eE.js.map +1 -0
  116. package/dist/storm-Y-yuBhvv.cjs +2 -0
  117. package/dist/storm-Y-yuBhvv.cjs.map +1 -0
  118. package/dist/transport/compression.d.ts +1 -1
  119. package/dist/transport/custom-transport.d.ts +20 -0
  120. package/dist/transport/errors.d.ts +2 -1
  121. package/dist/transport/exit-flush.d.ts +32 -13
  122. package/dist/transport/http-transport.d.ts +57 -25
  123. package/dist/transport/memory-transport.d.ts +30 -0
  124. package/dist/transport/retry-engine.d.ts +7 -7
  125. package/dist/transport/serializers/select.d.ts +12 -1
  126. package/dist/transport/status-transport.d.ts +74 -0
  127. package/dist/utils/console.d.ts +1 -1
  128. package/dist/utils/deadline.d.ts +7 -0
  129. package/dist/utils/error-like.d.ts +25 -0
  130. package/dist/utils/global-scope.d.ts +20 -0
  131. package/dist/utils/identity.d.ts +1 -1
  132. package/dist/utils/library-console.d.ts +11 -0
  133. package/dist/utils/library-request.d.ts +12 -0
  134. package/dist/utils/patch.d.ts +9 -0
  135. package/dist/utils/platform.d.ts +3 -3
  136. package/dist/utils/sequence.d.ts +0 -5
  137. package/dist/utils/timer.d.ts +1 -1
  138. package/dist/utils/tracing.d.ts +3 -3
  139. package/dist/utils/unref.d.ts +2 -2
  140. package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
  141. package/dist/web-vitals-Bflr5jSA.js.map +1 -0
  142. package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
  143. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
  144. package/package.json +2 -2
  145. package/dist/bus-DeZzr2bx.cjs +0 -2
  146. package/dist/bus-DeZzr2bx.cjs.map +0 -1
  147. package/dist/bus-DfAbg_pg.js.map +0 -1
  148. package/dist/constants-C8nZQBmQ.js +0 -86
  149. package/dist/constants-C8nZQBmQ.js.map +0 -1
  150. package/dist/constants-IBL_jd5R.cjs +0 -2
  151. package/dist/constants-IBL_jd5R.cjs.map +0 -1
  152. package/dist/errors-4MQyjZVj.js.map +0 -1
  153. package/dist/errors-CUdShXe7.cjs +0 -3
  154. package/dist/errors-CUdShXe7.cjs.map +0 -1
  155. package/dist/indexeddb-storage-0LtUALBg.js.map +0 -1
  156. package/dist/indexeddb-storage-CcEJlq2l.cjs +0 -2
  157. package/dist/indexeddb-storage-CcEJlq2l.cjs.map +0 -1
  158. package/dist/interactions-BMNPQ3WH.cjs +0 -2
  159. package/dist/interactions-BMNPQ3WH.cjs.map +0 -1
  160. package/dist/interactions-BaCmoGLB.js.map +0 -1
  161. package/dist/network-DBNvxCE3.cjs +0 -2
  162. package/dist/network-DBNvxCE3.cjs.map +0 -1
  163. package/dist/network-jQ2t8rU4.js +0 -111
  164. package/dist/network-jQ2t8rU4.js.map +0 -1
  165. package/dist/platform-ByQllE_W.cjs.map +0 -1
  166. package/dist/platform-YuByH8A5.js.map +0 -1
  167. package/dist/sampling-CbYySsZ1.js +0 -251
  168. package/dist/sampling-CbYySsZ1.js.map +0 -1
  169. package/dist/sampling-Cs50xsZl.cjs +0 -2
  170. package/dist/sampling-Cs50xsZl.cjs.map +0 -1
  171. package/dist/sender-BIob8eZz.js.map +0 -1
  172. package/dist/sender-iOjzcueM.cjs +0 -3
  173. package/dist/sender-iOjzcueM.cjs.map +0 -1
  174. package/dist/unref-16maCyKA.js +0 -8
  175. package/dist/unref-16maCyKA.js.map +0 -1
  176. package/dist/unref-CU9Nyz_9.cjs +0 -2
  177. package/dist/unref-CU9Nyz_9.cjs.map +0 -1
  178. package/dist/web-vitals-B2FYsEAU.cjs +0 -2
  179. package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
  180. package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,7 +2,85 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
4
4
 
5
- ## [0.7.0] - unreleased
5
+ ## [0.9.0] - 2026-10-28
6
+
7
+ ### Breaking changes - v0.9.0
8
+
9
+ - The level methods (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) give records with `log.type: "log"`. It was `"system"`. `"system"` is now for the records of the library itself.
10
+ - A cross-origin child frame forwards its records only to a parent on an origin in its `bus.trustedOrigins`, or on its own origin. It posts to that origin, not to `"*"`. With no trusted parent, the frame sends its own records at once.
11
+ - A sandboxed frame without `allow-same-origin` sends its own records. `bus.untrusted_origin` tells you to set `bus.mode: "sender"` in the frame. Add `allow-same-origin` only for content that you trust.
12
+ - `bus.trustedOrigins` does not accept `"null"`. One `"null"` entry trusts each sandboxed and `data:` document, for example a frame in an ad. Set `bus.mode: "sender"` in your sandboxed frame.
13
+ - `journey.scope` sets which contexts adopt a journey. The default `"auto"` is `"tab"` in a browser. A journey no longer goes to other tabs through the broadcast link. Set `"origin"` for the previous behavior. OpenFin and OpenFin Core Web keep `"origin"`.
14
+ - `minLevel` no longer drops action and metric records. It applies to log, event and system records.
15
+ - A string in `capture.propagateTraceHeaderTo` is an origin. It matches a request to that origin only. Before, it matched a substring of the URL. A string that is not a URL, for example `"/api/"`, reports `config.invalid`. To match a path, use a RegExp that starts with `^`.
16
+ - If the `redact` hook throws or returns a value that is not a record, the library drops the record. It counts the drop as `record.dropped_by_redact`. Before, it sent the record without redaction.
17
+ - This release removes `Sequence.reset()`.
18
+
19
+ ### Added - v0.9.0
20
+
21
+ - `fatal(message, error?, payload?)` is a top-level function.
22
+ - `configure()` checks each key: `enabled`, `minLevel`, `console`, `compression`, `credentials`, `headers`, `storage`, `identity`, each `bus`, `journey`, `capture` and `sampling` key. A value of the wrong type reports `config.invalid`. The value in force stays. Level names can have any case. Each `bus.trustedOrigins` entry becomes its origin.
23
+ - `error.data` holds the own string, number and boolean fields of the reason, for example `code`. An object field, for example the `config` of an `AxiosError`, stays out. It holds credentials and request bodies.
24
+ - `timeSync` and `timeAsync` also emit the duration histogram when the function throws or the promise rejects, with `status: "FAILURE"`. The error record and the histogram give the same duration.
25
+ - If a copy of another version owns the page runtime, this copy runs console-only. It installs no capture. It reports `runtime.version_mismatch`. A later `configure()` keeps it console-only. Its log calls and its `shutdown()` do not touch the runtime of the other version.
26
+ - New diagnostic codes: `runtime.version_mismatch` and `record.dropped_no_destination`. The library now also reports `transport.timeout`. It counts `record.dropped_malformed` and `record.sanitize_failed` in more places.
27
+
28
+ ### Changed - v0.9.0
29
+
30
+ - When the document becomes hidden, the library runs a normal flush with the headers, gzip and retry. On `pagehide`, `freeze` and OpenFin close, it uses a keepalive fetch with the last headers when `headers` is set. It uses `sendBeacon` only with no custom headers.
31
+ - While the document is hidden, a send of 60 KB or less uses `keepalive`. A mobile OS can stop a hidden page with no `pagehide`. The exit flush does not send that batch again.
32
+ - Until a `headers` function gives its first result, the exit flush puts the batch in the emergency queue. The next page load sends it with the headers.
33
+ - The exit flush sends the cached result of a `headers` function only while that function and the endpoint are in force.
34
+ - With a `redact` hook, a record that `redact` drops prints no console line. Before, the console printed its message.
35
+ - `shutdown()` runs a normal flush before the exit flush.
36
+ - After a 401 or 403, the library calls a `headers` function one more time. It then sends the batch one more time. A second 401 or 403 drops the batch.
37
+ - `flush()` waits for the batches in the queue and in flight. A flush while the server throttles stores the batch for the retry engine. It does not send around the throttle and the concurrency limit.
38
+ - A later `configure()` reinstalls the capture modules only when the `capture` section changes.
39
+ - A capture module restores a host function, for example `fetch` or `history.pushState`, only if the function still holds the wrapper of the library. A wrapper that another script added later stays in place.
40
+ - The library waits 60 s at most after a `Retry-After` answer.
41
+ - The library removes the journey token from the URL after it adopts the token.
42
+
43
+ ### Fixed - v0.9.0
44
+
45
+ - The build works on Windows. `npm run verify` runs lint after the build.
46
+ - `headers()` and the gzip encoding run under the 15 s request deadline. A `headers()` that never settles no longer holds a send slot.
47
+ - The emergency queue import runs after the sender starts. It no longer delays startup. It no longer drops records from the boot buffer.
48
+ - OTLP sends an integer above `Number.MAX_SAFE_INTEGER` as `doubleValue`, not as a broken `intValue`.
49
+ - The fetch capture no longer throws on an input with a text form only, on a Request from another realm, or on an input it cannot read. The XHR capture no longer throws on a method that is not a string. The capture never changes the result of the call.
50
+ - The XHR capture sends `traceparent` to the targets in `propagateTraceHeaderTo`.
51
+ - An allowlisted Request from another realm keeps its own headers. The library sends it without `traceparent`.
52
+ - An Error from another realm keeps its name, message and stack in the error capture, the console capture, `log.error()`, `console.args` and `cause`.
53
+ - A failed web-vitals import gets a new attempt when a later `configure()` changes the `capture` section.
54
+ - An oversized error record drops the caller attributes first. It keeps each `error.*` field, then the breadcrumbs if they fit.
55
+ - A breadcrumb holds the body after `redact`.
56
+ - The library drops a record that `redact` breaks in place, or a `redact` result with an unknown `severityText`. It counts the drop as `record.dropped_malformed`. The library sets `severityNumber` from the `severityText` that `redact` returns.
57
+ - A payload or a reason with a throwing getter or Proxy trap no longer throws out of a log call. The record gets `uiobs.sanitize_failed: true`.
58
+ - `logMetric` drops `NaN` and `Infinity`. It counts the drop as `record.dropped_malformed`.
59
+ - The bus checks the shape of each journey message. A journey answer holds the address of the context that asked. Only that context adopts it.
60
+ - A sandboxed page without `allow-same-origin` drops each message from a child frame with the origin `"null"`. Before, it trusted those frames as its own origin.
61
+ - The `bus.untrusted_origin` detail keeps only the first 32 characters of the message type.
62
+ - An oversized record keeps `page.url`, `journey.id` and `journey.name` as `redact` left them. Before, the size limit wrote the values from before `redact` back.
63
+
64
+ ## [0.8.0] - 2026-10-14
65
+
66
+ ### Added - v0.8.0
67
+
68
+ - `transport` sends batches through a channel of the app, for example an API client, a WebSocket or IPC. Batching, retry, storage, splitting and the exit flush stay the same. The returned status code has the meaning of the ingest contract. With `transport`, `endpoint` is optional.
69
+ - `transportOnExit` sends the last batch while the page closes. Without it, that batch goes to the emergency queue. The next page load sends it.
70
+ - The package exports the types `Transport`, `TransportRequest`, `TransportResponse` and `ExitTransport`.
71
+ - After the delivery stack loads, `configure()` cannot add or remove `transport`. The library reports `config.invalid`. A new function in place of the one in force is accepted.
72
+ - Network capture skips each request that the library starts itself. This includes a request that a custom transport starts before its first `await`.
73
+ - `createMemoryTransport()` gives tests a transport that keeps each batch in memory. `records()` returns the accepted records. `respondWith()` sets the answer, for example `413` or `429`. The package exports the type `MemoryTransport`.
74
+ - `capture.longFrames` records each frame that freezes the page as the histogram `ui.long_frame.duration`. `capture.longFrameThresholdMs` sets the minimum duration. The default is 100 ms. A browser without `long-animation-frame` gives `longtask` entries.
75
+ - `capture.console` records the console calls of the app. `true` wraps `error` and `warn`. A list selects from `error`, `warn`, `info` and `log`. `error` and `warn` give records. `info` and `log` give breadcrumbs. The library does not record the lines that it prints itself.
76
+ - `sampling.remote` reads sampling rules from the `X-UiObs-Sampling` header of each accepted batch. The rules stay in force for their `ttlMs`, at most 1 hour. They can change rates and lower `minLevel`. `sampling.remoteMaxRate` caps each remote rate. A custom transport returns the rules in `TransportResponse.sampling`. Child frames, workers and OpenFin views ask their owner for the rules.
77
+
78
+ ### Fixed - v0.8.0
79
+
80
+ - `flush()` during startup missed the records in the boot buffer. It now waits for startup to release them.
81
+ - The `sendBeacon` failure message was a fragment. It is now a complete sentence.
82
+
83
+ ## [0.7.0] - 2026-10-12
6
84
 
7
85
  ### Breaking changes - v0.7.0
8
86
 
package/README.md CHANGED
@@ -89,7 +89,7 @@ configure({
89
89
  - `identity: "memory"` writes no key to `localStorage` or `sessionStorage`.
90
90
  - `console` and `minLevel` are independent. `console` sets what the library prints. `minLevel` sets what the library sends.
91
91
  - The console output does not depend on the bus or the endpoint.
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.
92
+ - With a `redact` hook, the console shows only what `redact` returns. A record that `redact` drops prints no line. A record below `minLevel` shows its message and error only, because the library does not build it.
93
93
 
94
94
  ### Console Output
95
95
 
@@ -133,8 +133,103 @@ configure({
133
133
  - A later `configure({ console: "WARN" })` changes the level. The styles stay.
134
134
  - A later `configure({ console: { styles } })` changes the styles. The level stays.
135
135
 
136
+ ### Custom Transport
137
+
138
+ Set `transport` to send batches through a channel of your app, for example an API client with token refresh, a WebSocket, Electron IPC or an OpenFin channel. With `transport`, `endpoint` is optional.
139
+
140
+ ```ts
141
+ configure({
142
+ serviceName: "equities-blotter",
143
+ transport: async (request) => {
144
+ const response = await apiClient.post("/telemetry", request.body, {
145
+ headers: { "Content-Type": request.contentType, "X-UiObs-Batch-Id": request.batchId },
146
+ });
147
+ const retryAfterSeconds = Number(response.headers["retry-after"]);
148
+ return { status: response.status, retryAfterMs: retryAfterSeconds * 1000 };
149
+ },
150
+ // Optional. It runs while the page closes, so it must not wait for a promise.
151
+ transportOnExit: (request) => navigator.sendBeacon("/telemetry", request.body),
152
+ // Network capture must not log the requests of your transport.
153
+ capture: { ignoreUrls: ["/telemetry"] },
154
+ });
155
+ ```
156
+
157
+ - The library keeps batching, retry, storage, splitting and the exit flush.
158
+ - The status code that you return has the meaning of the ingest contract. `2xx` accepts the batch. `413` splits it. `429` and `503` throttle. `408` and `5xx` retry. Each other code drops the batch.
159
+ - A rejected promise counts as a network error. The library sends the batch again later. A call that does not settle in 15 seconds counts as a timeout.
160
+ - The library does not compress `request.body`. Compress it in your transport if necessary.
161
+ - `request.records` holds the built records after `redact`. Do not change them, because the retry engine can send them again.
162
+ - Without `transportOnExit`, the last batch goes to the emergency queue when the page closes. The next page load sends it.
163
+ - With `storage: "none"`, the next page load cannot keep that batch. Set `transportOnExit`, or the library loses the last batch.
164
+ - The library ignores a `retryAfterMs` or a `maxBytes` that is not a finite number. It uses 0 for a negative value.
165
+ - After the delivery stack loads, you cannot add or remove `transport`. You can replace it with another function.
166
+ - Network capture skips a request that your transport starts before its first `await`. Put your telemetry URL in `capture.ignoreUrls` too. A request after an `await` is outside that scope.
167
+
168
+ ### Testing
169
+
170
+ Use `createMemoryTransport()` to check what your code logs. It needs no network and no `fetch` mock.
171
+
172
+ ```ts
173
+ import {
174
+ configure,
175
+ createMemoryTransport,
176
+ flush,
177
+ getLogger,
178
+ shutdown,
179
+ } from "@utk09/ui-observability";
180
+
181
+ const memory = createMemoryTransport();
182
+
183
+ beforeEach(() => {
184
+ configure({
185
+ serviceName: "orders",
186
+ transport: memory.transport,
187
+ storage: "none",
188
+ bus: { mode: "off" },
189
+ identity: "memory",
190
+ });
191
+ });
192
+
193
+ afterEach(async () => {
194
+ memory.clear();
195
+ await shutdown();
196
+ });
197
+
198
+ it("logs the order submit", async () => {
199
+ getLogger("orders.ticket").logAction("ORDER_SUBMIT", { orderId: "ORD-1" });
200
+ await flush();
201
+
202
+ expect(memory.records()).toContainEqual(expect.objectContaining({ body: "ORDER_SUBMIT" }));
203
+ });
204
+ ```
205
+
206
+ - `records()` returns the records of each accepted batch. `batches()` returns each request, accepted or refused.
207
+ - `respondWith(status, retryAfterMs?)` sets the answer for each later batch. Use it to test a `413`, `429` or `500` answer. The default answer is `200`.
208
+ - `flush()` waits for startup. A record that you log directly after `configure()` is in the flushed batch.
209
+ - After `shutdown()`, each call does nothing until the next `configure()`.
210
+ - Set `storage: "none"` in tests. Without it, `shutdown()` stores the unsent records, and the next test can receive them.
211
+
136
212
  ---
137
213
 
214
+ ### Remote Sampling
215
+
216
+ With `sampling: { remote: true }`, the ingest server can change the sampling during an incident. You do not deploy the app again.
217
+
218
+ ```http
219
+ X-UiObs-Sampling: {"v":1,"ttlMs":600000,"defaultRate":0.1,"rates":{"blotter.grid":1},"minLevel":"DEBUG"}
220
+ ```
221
+
222
+ - The library reads the header only on a `2xx` answer to a batch that it sent. A custom transport returns the rules in `TransportResponse.sampling`, as text or as an object.
223
+ - `v` must be `1`. `ttlMs` is mandatory, from more than 0 to 3,600,000 (1 hour). After the TTL, the rules from `configure()` apply again.
224
+ - `rates` apply over the `configure()` rates. The other `configure()` rates stay. `defaultRate` applies only if the header has it.
225
+ - `minLevel` can only lower the level that the library sends. It does not change the console level.
226
+ - `sampling.remoteMaxRate` caps each remote rate. It also caps the records that a remote `minLevel` adds. Set it below 1 to limit the traffic that a compromised server can cause.
227
+ - The library rejects all the rules if one field is not valid, for example a rate outside 0 to 1, more than 100 `rates` or a header longer than 4096 characters. It reports `config.invalid`.
228
+ - The library keeps the rules in memory only. A reload uses the `configure()` rules until the next accepted batch.
229
+ - A child frame, a worker or an OpenFin view asks its owner for the rules at start and each 30 seconds. Set `sampling.remote: true` in each context.
230
+ - A frame accepts rules from a parent only if the parent origin is the page origin or is in `bus.trustedOrigins`. A page that embeds your app cannot lower `minLevel`.
231
+ - Each OpenFin view of one app can read the bus messages of the others. Load only trusted content into a view that has the `fin` API.
232
+
138
233
  ## API Reference
139
234
 
140
235
  ### Lifecycle & Setup
@@ -154,11 +249,14 @@ configure({
154
249
  | `info(msg, payload?)` | Logs an INFO record. |
155
250
  | `warn(msg, payload?)` | Logs a WARN record. |
156
251
  | `error(msg, err?, payload?)` | Logs an ERROR record with the error and the breadcrumb trail. |
252
+ | `fatal(msg, err?, payload?)` | Logs a FATAL record with the error and the breadcrumb trail. |
157
253
  | `logAction(name, payload?)` | Logs one user action. |
158
254
  | `logEvent(name, payload?)` | Logs one domain or lifecycle event. |
159
255
  | `logMetric(name, value, unit?, type?, attrs?)` | Logs a measurement (`gauge`, `counter`, `histogram`). |
160
- | `timeSync(label, fn, attrs?)` | Times a function and emits a duration histogram. |
161
- | `timeAsync(label, fn, attrs?)` | Times a promise and emits a duration histogram. |
256
+ | `timeSync(label, fn, attrs?)` | Times a function and emits a duration histogram with `status` `SUCCESS` or `FAILURE`. |
257
+ | `timeAsync(label, fn, attrs?)` | Times a promise and emits a duration histogram with `status` `SUCCESS` or `FAILURE`. |
258
+
259
+ The level methods give records with `log.type: "log"`. Records of the library itself have `log.type: "system"`. `logMetric` drops a value that is not finite and counts `record.dropped_malformed`.
162
260
 
163
261
  ### Context & Correlation
164
262
 
@@ -178,43 +276,48 @@ configure({
178
276
 
179
277
  ### Delivery & Diagnostics
180
278
 
181
- | Function | Description |
182
- | ------------------------- | ------------------------------------------------------------- |
183
- | `flush()` | Sends the records held in the pipeline or the forward buffer. |
184
- | `getQueueDepth()` | Returns the number of batches in storage. |
185
- | `getDiagnosticCounters()` | Returns the count of each diagnostic code. |
279
+ | Function | Description |
280
+ | ------------------------- | -------------------------------------------------------------------------------------------------- |
281
+ | `flush()` | Sends the records held in the pipeline or the forward buffer, and waits for the batches in flight. |
282
+ | `getQueueDepth()` | Returns the number of batches in storage. |
283
+ | `getDiagnosticCounters()` | Returns the count of each diagnostic code. |
186
284
 
187
285
  ---
188
286
 
189
287
  ## Configuration Options
190
288
 
191
- No key is required. Set `endpoint` to send records.
192
-
193
- | Key | Default | Description |
194
- | ---------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
195
- | `endpoint` | `""` | HTTP endpoint that receives the batches. `null` selects console-only mode. `""` reports `config.invalid`. |
196
- | `serviceName` | `""` | `service.name` on every record. |
197
- | `serviceVersion` | `""` | `service.version` on every record. |
198
- | `environment` | `""` | `deployment.environment` on every record. |
199
- | `enabled` | `true` | Set `false` to stop all logging. Every log call then does nothing. |
200
- | `minLevel` | `"INFO"` | Lowest level that the library sends (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`). |
201
- | `compression` | `"gzip"` | `gzip` or `none`. The library compresses a payload above 1 KB only. |
202
- | `serializer` | `"otlp"` | `otlp`, `ecs`, or a custom `LogSerializer`. |
203
- | `credentials` | `"omit"` | Fetch credentials mode. Set `"include"` for cookie auth. |
204
- | `headers` | `{}` | Static headers, or a function that returns them. |
205
- | `storage` | `"auto"` | Store for undelivered batches: `auto`, `indexeddb`, `localstorage`, `memory` or `none`. Fixed at startup. |
206
- | `identity` | `"storage"` | Store for session, tab and journey ids. `memory` writes no key. Fixed at startup. |
207
- | `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule. |
208
- | `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins. |
209
- | `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate. |
210
- | `bus.mode` | `"auto"` | `auto`, `sender`, `forwarder` or `off`. With `off`, this context sends its own records and opens no link. A same-origin child frame can still forward to it. |
211
- | `bus.trustedOrigins` | `[]` | Origins that may post records from a cross-origin frame. |
212
- | `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`. |
213
- | `capture` | See below | Auto-capture settings. |
214
- | `console` | `false` | Prints records to devtools. `true` prints from `DEBUG` up. A level name prints from that level up. An object sets `level` and `styles` (see Console Output). It does not depend on `minLevel`. |
215
- | `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off. |
216
- | `redact(record)` | `undefined` | Changes a record before the library sends or prints it. Return `null` to drop the record. |
217
- | `onDiagnostic(event)` | `undefined` | Receives the faults of the library itself. |
289
+ No key is required. Set `endpoint` to send records. A value of the wrong type reports `config.invalid`, and the value in force stays. Level names can have any case.
290
+
291
+ | Key | Default | Description |
292
+ | ---------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
293
+ | `endpoint` | `""` | HTTP endpoint that receives the batches. `null` selects console-only mode. `""` reports `config.invalid`. |
294
+ | `serviceName` | `""` | `service.name` on every record. |
295
+ | `serviceVersion` | `""` | `service.version` on every record. |
296
+ | `environment` | `""` | `deployment.environment` on every record. |
297
+ | `enabled` | `true` | Set `false` to stop all logging. Every log call then does nothing. |
298
+ | `minLevel` | `"INFO"` | Lowest level that the library sends (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`). It does not drop actions and metrics. |
299
+ | `compression` | `"gzip"` | `gzip` or `none`. The library compresses a payload above 1 KB only. |
300
+ | `serializer` | `"otlp"` | `otlp`, `ecs`, or a custom `LogSerializer`. |
301
+ | `credentials` | `"omit"` | Fetch credentials mode. Set `"include"` for cookie auth. |
302
+ | `headers` | `{}` | Static headers, or a function that returns them. After a 401 or 403, a function gets one more call and the batch one more send. The exit flush sends the last headers. Before a function gives its first result, the exit flush puts the batch in the emergency queue. `headers: undefined` removes the headers. |
303
+ | `storage` | `"auto"` | Store for undelivered batches: `auto`, `indexeddb`, `localstorage`, `memory` or `none`. Fixed at startup. |
304
+ | `identity` | `"storage"` | Store for session, tab and journey ids. `memory` writes no key. Fixed at startup. |
305
+ | `sampling.defaultRate` | `1` | Keep rate for a namespace with no rule. |
306
+ | `sampling.rates` | `{}` | Keep rate per namespace. The longest matching prefix wins. |
307
+ | `sampling.alwaysSampleTypes` | `["action"]` | Record types that ignore the rate. |
308
+ | `sampling.remote` | `false` | Reads sampling rules from the `X-UiObs-Sampling` header of each accepted batch (see Remote Sampling). |
309
+ | `sampling.remoteMaxRate` | `1` | Highest rate that a remote rule can set. It applies to the remote `defaultRate` and to each remote namespace rate. |
310
+ | `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. |
311
+ | `bus.trustedOrigins` | `[]` | Origins of other documents that this document trusts. A parent accepts records from a child frame on these origins. A cross-origin child frame forwards its records only to a parent on these origins. The library keeps the origin of each URL. For a sandboxed frame, set `bus.mode: "sender"` in the frame. |
312
+ | `bus.openFinRole` | `"auto"` | `auto`, `provider` or `client`. |
313
+ | `journey.scope` | `"auto"` | Which contexts adopt a journey. `context`: each context keeps its own. `tab`: a frame or a worker adopts the journey of its owner. `origin`: each context of the origin, also in other tabs. `auto` is `origin` in OpenFin and `tab` in a browser. |
314
+ | `capture` | See below | Auto-capture settings. |
315
+ | `console` | `false` | Prints records to devtools. `true` prints from `DEBUG` up. A level name prints from that level up. An object sets `level` and `styles` (see Console Output). It does not depend on `minLevel`. |
316
+ | `transport(request)` | `undefined` | Sends batches through a channel of your app in place of HTTP (see Custom Transport). |
317
+ | `transportOnExit(request)` | `undefined` | Sends the last batch while the page closes. It must return a boolean and must not wait. |
318
+ | `otelLoader()` | `undefined` | Loads `@opentelemetry/api`. Without it, OTel is off. |
319
+ | `redact(record)` | `undefined` | Changes a record before the library sends or prints it. Return `null` to drop the record. If the hook throws or returns a value that is not a record, the library drops the record. It counts `record.dropped_by_redact`. |
320
+ | `onDiagnostic(event)` | `undefined` | Receives the faults of the library itself. |
218
321
 
219
322
  ### Auto-Capture Options
220
323
 
@@ -228,13 +331,37 @@ capture: {
228
331
  interactions: false, // Element click breadcrumbs
229
332
  navigation: false, // Single-page navigation URL changes
230
333
  webVitals: false, // Core Web Vitals (LCP, CLS, INP, FCP, TTFB)
334
+ longFrames: false, // Frames that freeze the page, as ui.long_frame.duration
335
+ longFrameThresholdMs: 100, // Minimum frame duration that longFrames records
336
+ console: false, // App console calls: true, or a list such as ["error", "warn", "info"]
231
337
  fullUrls: false, // Keep query strings and fragments on recorded URLs
232
338
  ignoreUrls: [], // URL patterns excluded from network capture
233
- propagateTraceHeaderTo: [], // Target origins allowed to receive traceparent
339
+ propagateTraceHeaderTo: [], // Origins, or RegExp patterns, that receive traceparent
234
340
  }
235
341
  ```
236
342
 
237
- `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.
343
+ `longFrames` records each frame at or above `longFrameThresholdMs` as the histogram `ui.long_frame.duration`. Each long frame also adds a breadcrumb. The next error record then shows the freeze before it.
344
+
345
+ - The library observes `long-animation-frame`. A browser without it gives `longtask` entries, with no script attributes.
346
+ - The attributes are `frame.type`, `frame.blocking_ms`, `frame.script.invoker` and `frame.script.source`. The source URL follows `fullUrls`.
347
+ - The library records at most 20 long frames in each 10-second window.
348
+
349
+ `capture.console` records the console calls of your app and of third-party code. It is different from the top-level `console` option, which prints records.
350
+
351
+ > **Set `redact` before you turn on `capture.console`.** A call such as `console.error("Request failed", error.response)` sends the request headers, for example `Authorization`. Third-party code on the page writes such lines too.
352
+
353
+ - `true` wraps `console.error` and `console.warn`. A list selects from `error`, `warn`, `info` and `log`.
354
+ - `error` gives an ERROR record, and `warn` gives a WARN record. `info` and `log` give a breadcrumb only.
355
+ - The first string is the message. The first `Error` of an `error` call gives the `error.*` fields. The other arguments go into `console.args`.
356
+ - The wrapper calls the original method first. Devtools shows the same text. The source link of the line points to the library wrapper.
357
+ - The library does not record the lines that it prints itself.
358
+ - The library records at most 20 `error` and `warn` calls in each 10-second window. The error capture has a separate limit. Console noise cannot hide an uncaught error.
359
+ - To record an argument, the library reads each property, also a getter. A getter with a side effect then runs during the console call.
360
+ - On `shutdown()`, the library restores each method. If another script wrapped the method later, the library leaves it and reports `capture.install_failed`.
361
+
362
+ `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 a RegExp in `propagateTraceHeaderTo` match the full URL.
363
+
364
+ A string in `propagateTraceHeaderTo` is an origin, for example `"https://api.example"`. It matches a request to that origin only. A URL with a path gives its origin. A relative request URL resolves against the page. To match a path, use a RegExp. A RegExp tests the request URL in the form that the caller gives. Start each RegExp with `^`. Without it, `/\/api\//` also matches `https://vendor.example/api/`. For example, `/^https:\/\/api\.example\/v2\//` matches one path on one origin. `/^\/api\//` matches a relative request URL only.
238
365
 
239
366
  ### Browser Storage Keys
240
367
 
@@ -257,7 +384,8 @@ IndexedDB holds undelivered batches with `storage: "auto"` or `"indexeddb"`.
257
384
  - **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.
258
385
  - **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.
259
386
  - **Five correlation ids:** Each record carries `session.id`, `tab.id`, `context.id`, `journey.id` and `trace_id`.
260
- - **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.
387
+ - **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. When the document becomes hidden, the library runs a normal flush with the headers, gzip and retry. While the document is hidden, a send of 60 KB or less uses `keepalive`. A mobile OS can stop a hidden page with no `pagehide`. On `pagehide`, `freeze` or OpenFin close, it sends pending records with `navigator.sendBeacon` if they are below 60 KB. With `headers`, it uses a keepalive fetch with the last headers, because a beacon cannot set a header. A larger payload goes to the emergency queue. `shutdown()` runs a normal flush before the exit flush.
388
+ - **One library version on a page:** If a copy of another version owns the page runtime, this copy runs console-only. It installs no capture and reports `runtime.version_mismatch`. Load one version of the library on the page.
261
389
  - **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.
262
390
  - **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:
263
391
  - A change to `storage`. The stored batches stay in the adapter that the runtime built at startup.
@@ -282,11 +410,12 @@ The ingest server must meet these requirements:
282
410
  - Above 1 KiB, it also sends `Content-Encoding: gzip`.
283
411
  - Each of these headers causes a CORS preflight. If the server does not allow them, each preflight fails.
284
412
  - After a failed preflight, the library tries the batch 5 more times. It then drops the batch.
285
- - Only the exit flush records arrive, because the exit flush sends no custom header.
413
+ - Only the beacon records of the exit flush arrive, because a beacon sends no custom header.
286
414
 
287
415
  3. **Deduplication:** Deduplicate on the `X-UiObs-Batch-Id` header and the `uiobs_batch_id` query parameter. Keep the ids for at least 24 hours.
288
- 4. **Throttling:** Return `429` or `503` with `Retry-After`. Expose the header with `Access-Control-Expose-Headers: retry-after`.
289
- 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`.
416
+ 4. **Throttling:** Return `429` or `503` with `Retry-After`. Expose the header with `Access-Control-Expose-Headers: retry-after`. The library waits 60 s at most.
417
+ 5. **Status codes:** `200`, `202` and `204` accept the batch. `413` makes the library split the batch. With a `headers` function, a `401` or `403` gets one more send with new headers. The library drops a batch that gets any other `4xx`.
418
+ 6. **Remote sampling (optional):** To send sampling rules, add `X-UiObs-Sampling` to a `2xx` answer. Expose the header with `Access-Control-Expose-Headers: x-uiobs-sampling`.
290
419
 
291
420
  ---
292
421
 
package/dist/bus/bus.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Diagnostics } from "../core/diagnostics";
2
- import type { Journey } from "../core/journey";
2
+ import { type Journey } from "../core/journey";
3
+ import type { RemoteSlot } from "../core/remote-sampling";
3
4
  import type { BusMessage, BusRole } from "../models/bus";
4
5
  import type { ResolvedConfig } from "../models/config";
5
6
  import type { LogRecord } from "../models/log-record";
@@ -24,6 +25,8 @@ export interface BusHandlers {
24
25
  onJourneyRequest: () => Journey | null;
25
26
  /** Runs when two windows use the same tab identifier. */
26
27
  onTabConflict: () => void;
28
+ /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */
29
+ remote: RemoteSlot;
27
30
  }
28
31
  /** Coordinates cross-realm communication, role resolution, and message dispatch. */
29
32
  export declare class Bus {
@@ -42,10 +45,16 @@ export declare class Bus {
42
45
  private readonly links;
43
46
  /** Shared OpenFin InterApplicationBus link instance. */
44
47
  private openFinLink;
45
- /** Indicates whether this context is the OpenFin platform provider. */
48
+ /** True if this context is the OpenFin platform provider. */
46
49
  private isOpenFinProvider;
47
- /** Indicates whether role resolution has completed. */
50
+ /** True if role resolution is complete. */
48
51
  private resolved;
52
+ /** Timer that asks the upstream owner for the remote sampling rules. */
53
+ private rulesPoll;
54
+ /** True after destroy(). A handshake that ends later must not start a timer. */
55
+ private destroyed;
56
+ /** Context id of the owner that answered the handshake. Null with no handshake. */
57
+ private ownerId;
49
58
  /** Active handshake state awaiting welcome response. */
50
59
  private awaitingWelcome;
51
60
  /**
@@ -59,7 +68,7 @@ export declare class Bus {
59
68
  constructor(config: ResolvedConfig, diagnostics: Diagnostics, platform: PlatformMetadata, contextId: string, tabId: string, handlers: BusHandlers, handshakeOptions?: HandshakeOptions);
60
69
  /** Returns the resolved bus role. */
61
70
  getRole(): BusRole;
62
- /** Returns whether role resolution has completed. */
71
+ /** Returns true if role resolution is complete. */
63
72
  isResolved(): boolean;
64
73
  /**
65
74
  * Resolves bus role and establishes control links.
@@ -83,7 +92,7 @@ export declare class Bus {
83
92
  */
84
93
  attachWorker(worker: WorkerLike): void;
85
94
  /**
86
- * Broadcasts journey state changes to all connected links.
95
+ * Sends journey state changes over each link of the journey scope.
87
96
  * @param journey Active journey or null if ended.
88
97
  */
89
98
  broadcastJourney(journey: Journey | null): void;
@@ -91,14 +100,14 @@ export declare class Bus {
91
100
  destroy(): void;
92
101
  /** Returns all unique active links including upstream. */
93
102
  private allLinks;
94
- /** Broadcasts a message across all open links. */
95
- private post;
96
103
  /** Sends a message only over links of the given kind. */
97
104
  private postOver;
105
+ /** Sends a journey message over each link of the journey scope. */
106
+ private postJourney;
98
107
  /** Routes incoming messages to registered handlers or upstream targets. */
99
108
  private readonly receive;
100
109
  /**
101
- * Tells whether records from a link can go upstream. Records that go back on
110
+ * Tells if records from a link can go upstream. Records that go back on
102
111
  * their arrival link return to their sender. A direct link is an exception.
103
112
  * Each direct link is one call into one parent. Thus two direct links in a
104
113
  * chain are different links.
@@ -106,13 +115,13 @@ export declare class Bus {
106
115
  * @returns True if the relay is safe.
107
116
  */
108
117
  private canRelay;
109
- /** Returns whether this context can accept ownership over the given link type. */
118
+ /** Returns true if this context can be the owner of the given link type. */
110
119
  private canOwn;
111
- /** Resolves whether this context represents the OpenFin platform provider. */
120
+ /** Finds if this context is the OpenFin platform provider. */
112
121
  private resolveOpenFinProvider;
113
122
  /** Resolves the handshake orphan policy for the current platform context. */
114
123
  private orphanPolicy;
115
- /** Tests whether the parent window is inaccessible due to cross-origin boundaries. */
124
+ /** Tests if a cross-origin boundary blocks access to the parent window. */
116
125
  private isCrossOriginFrame;
117
126
  /** Identifies the candidate upstream link based on platform hierarchy. */
118
127
  private candidateUpstream;
@@ -128,4 +137,59 @@ export declare class Bus {
128
137
  private handshake;
129
138
  /** Broadcasts tab claim and queries existing journey state. */
130
139
  private announce;
140
+ /**
141
+ * Resolves the journey scope. "auto" gives "origin" in OpenFin and "tab" in a browser.
142
+ * @returns The scope in force.
143
+ */
144
+ private journeyScope;
145
+ /**
146
+ * Tests if a link carries journey messages in the scope in force.
147
+ * Only "origin" uses the broadcast link. That link reaches each tab of the origin.
148
+ * @param link Link kind.
149
+ * @returns True if the link carries journey messages.
150
+ */
151
+ private journeyLink;
152
+ /**
153
+ * Tests if this context adopts a journey message.
154
+ * @param message Journey message.
155
+ * @param source Link and origin of the message.
156
+ * @returns True for a message on a journey link, to this context, from an accepted sender.
157
+ * In "tab" scope, only the owner of a forwarder is an accepted sender.
158
+ */
159
+ private acceptsJourney;
160
+ /**
161
+ * Tests if a message comes from the upstream owner of this forwarder.
162
+ * @param from Context id of the sender.
163
+ * @param link Link kind of the message.
164
+ * @returns True for the upstream link and, after a handshake, the owner that answered it.
165
+ */
166
+ private fromOwner;
167
+ /**
168
+ * Parses a journey payload from another realm and gives it to the runtime.
169
+ * @param payload Journey, or null when the journey ended.
170
+ */
171
+ private applyJourney;
172
+ /**
173
+ * Builds the answer to a sampling question. Null rules end the copy of the forwarder.
174
+ * @param to Context id of the forwarder that asked.
175
+ * @returns The answer.
176
+ */
177
+ private rulesAnswer;
178
+ /**
179
+ * Tests if this context accepts sampling rules from a source.
180
+ * @param to Context id that the answer names.
181
+ * @param source Link and origin of the answer.
182
+ * @returns True only for an answer from the upstream owner to this context.
183
+ */
184
+ private acceptsRules;
185
+ /**
186
+ * Applies the rules of an answer. It ignores rules that are not valid.
187
+ * @param raw Rules of the answer, or null when the upstream has none.
188
+ */
189
+ private applyRules;
190
+ /**
191
+ * Asks the upstream owner for the remote sampling rules now, then at each poll interval.
192
+ * A direct link cannot push the rules to a child. A poll works on each link kind.
193
+ */
194
+ private pollRules;
131
195
  }
@@ -57,12 +57,15 @@ export interface WorkerLike {
57
57
  */
58
58
  export declare function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null;
59
59
  /**
60
- * Creates a postMessage link to the parent window.
60
+ * Creates a postMessage link to a parent window on a trusted origin. Records hold user data.
61
+ * A page on another origin that frames this app must not get them.
61
62
  * @param receive Callback for incoming parent messages.
63
+ * @param trustedOrigins Origins of a parent that can get the records, in addition to this origin.
62
64
  * @param diagnostics Diagnostics reporter.
63
- * @returns Link to parent window, or null if running in top-level window.
65
+ * @returns Link to the parent window, or null at the top level or with an untrusted parent.
66
+ * With null, this context sends its own records.
64
67
  */
65
- export declare function createParentLink(receive: Receive, diagnostics: Diagnostics): Link | null;
68
+ export declare function createParentLink(receive: Receive, trustedOrigins: string[], diagnostics: Diagnostics): Link | null;
66
69
  /**
67
70
  * Creates a link listening to child frames with origin allowlist filtering.
68
71
  * @param receive Callback for messages from authorized child frames.
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-Br3b89Wg.cjs"),t=require("./deadline-Cbg2cbUw.cjs"),n=require("./journey-CE2EcwHW.cjs"),r=require("./remote-rules-kuDf5gbe.cjs");function i(t){return{p:e.w,m:t}}function a(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 o=Symbol.for(e.qt),s=`null`;function c(e,t){return e===s?`The bus ignored ${t} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`:`The bus ignored ${t} from ${e}. If you own this origin, add it to bus.trustedOrigins.`}function l(){let e=location.ancestorOrigins;if(e&&e.length>0)return e.item(0);let t=document.referrer;if(t===``)return null;try{return new URL(t).origin}catch{return null}}function u(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[o]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`The direct call into the parent runtime failed.`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function d(e,t,n){if(typeof window>`u`||window.parent===window)return null;let r=location.origin;if(r===s)return n.report(`bus.untrusted_origin`,`This frame is sandboxed without allow-same-origin. It has an opaque origin. No parent can trust it. This context sends its own records. Set bus.mode: "sender" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`,{origin:r,type:`parent`}),null;let o=new Set([r,...t]),u=l();if(u===null||!o.has(u))return n.report(`bus.untrusted_origin`,u===null?`The origin of the parent frame is unknown. This context sends its own records.`:`The parent frame is on ${u}. This origin is not in bus.trustedOrigins. This context sends its own records.`,{origin:u??``,type:`parent`}),null;let d=new Set,f=t=>{let r=a(t.data);r&&t.source===window.parent&&(o.has(t.origin)?e(r,{link:`parent`,origin:t.origin}):d.has(t.origin)||(d.add(t.origin),n.report(`bus.untrusted_origin`,c(t.origin,`a message`),{origin:t.origin,type:r.t.slice(0,32)})))};return addEventListener(`message`,f),{kind:`parent`,post(e){n.guard(`bus.send_failed`,`The postMessage call to the parent failed.`,()=>{window.parent.postMessage(i(e),u)})},close(){removeEventListener(`message`,f)}}}function f(e,t,n){if(typeof window>`u`)return null;let r=new Set([location.origin,...t]);r.delete(s);let o=new Map,l=t=>{let i=a(t.data);i&&(r.has(t.origin)?(t.source&&o.set(t.source,t.origin),e(i,{link:`children`,origin:t.origin})):n.report(`bus.untrusted_origin`,c(t.origin,`a message`),{origin:t.origin,type:i.t.slice(0,32)}))};return addEventListener(`message`,l),{kind:`children`,post(e){for(let[t,r]of o){let a=t;a.closed?o.delete(t):n.guard(`bus.send_failed`,`The postMessage call to a child frame failed.`,()=>{a.postMessage(i(e),r)})}},close(){removeEventListener(`message`,l),o.clear()}}}function p(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let o=n.guard(`bus.send_failed`,`The library could not open the BroadcastChannel.`,()=>new r(e));return o?(o.onmessage=e=>{let n=a(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`The BroadcastChannel.postMessage call failed.`,()=>{o.postMessage(i(e))})},close(){n.guard(`bus.send_failed`,`The library could not close the BroadcastChannel.`,()=>{o.close()})}}):null}function m(e,t,n,r){let o=globalThis.fin?.InterApplicationBus;if(!o)return null;if(!t)return r.report(`openfin.unavailable`,`OpenFin gives no application uuid. The InterApplicationBus link stays closed.`),null;let s=`${e}.${t}`;return r.guardAsync(`bus.send_failed`,`The InterApplicationBus.subscribe call failed.`,()=>o.subscribe({uuid:t},s,e=>{let t=a(e);t&&n(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){r.guardAsync(`bus.send_failed`,`The InterApplicationBus.publish call failed.`,()=>o.publish(s,i(e)))},close(){}}}function h(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=a(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.`,()=>{r(i(e))})},close(){}})}function g(e,t,n){let r=e=>{let n=a(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`The postMessage call to a worker failed.`,()=>{e.postMessage(i(t))})},close(){e.removeEventListener(`message`,r)}}}var _={timeoutMs:e.C,maxAttempts:3},v=[`children`,`direct`,`worker`],y=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;rulesPoll;destroyed=!1;ownerId=null;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=_){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=u(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 r=this.handlers.onJourneyRequest();r&&this.journeyLink(`direct`)&&t({t:`journey`,from:this.contextId,to:e.from,journey:r},n)}else e.t===`sampling?`?t(this.rulesAnswer(e.from),n):this.receive(e,n)}attachWorker(e){this.links.push(g(e,this.receive,this.diagnostics))}broadcastJourney(e){this.postJourney({t:`journey`,from:this.contextId,journey:e})}destroy(){this.destroyed=!0,clearInterval(this.rulesPoll),this.rulesPoll=void 0;for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.ownerId=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}postJourney(e){for(let t of this.allLinks())this.journeyLink(t.kind)&&t.post(e)}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.ownerId=e.from,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.acceptsJourney(e,t)&&this.applyJourney(e.journey);break;case`journey?`:{let n=this.handlers.onJourneyRequest();n&&this.journeyLink(t.link)&&this.postOver(t.link,{t:`journey`,from:this.contextId,to:e.from,journey:n});break}case`sampling?`:(this.role===`forwarder`?t.link!==this.upstream?.kind:this.canOwn(t.link))&&this.postOver(t.link,this.rulesAnswer(e.from));break;case`sampling`:this.acceptsRules(e.to,t)&&this.applyRules(e.rules);break;case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canRelay(e){return e===`direct`||e!==this.upstream?.kind}canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:v.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?h(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:d(this.receive,this.config.bus.trustedOrigins,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(f(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(p(e.S,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=m(e.S,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.r(a),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.postJourney({t:`journey?`,from:this.contextId}),this.pollRules()}journeyScope(){let{scope:e}=this.config.journey;if(e!==`auto`)return e;let{platform:t}=this.platform;return t===`openfin`||t===`openfin_web`?`origin`:`tab`}journeyLink(e){let t=this.journeyScope();return t===`context`?!1:t===`origin`||e!==`broadcast`}acceptsJourney(e,t){return!this.journeyLink(t.link)||e.to!==void 0&&e.to!==this.contextId?!1:this.journeyScope()===`origin`||this.fromOwner(e.from,t.link)}fromOwner(e,t){return this.role!==`forwarder`||t!==this.upstream?.kind?!1:this.ownerId===null||e===this.ownerId}applyJourney(e){if(e===null){this.handlers.onJourney(null);return}let t=n.r(e);t===null?this.diagnostics.report(`record.dropped_malformed`,`The bus dropped a journey message. Its payload is not a journey.`,{type:`journey`}):this.handlers.onJourney(t)}rulesAnswer(e){let t=this.handlers.remote.sampling?.wire()??null;return{t:`sampling`,from:this.contextId,to:e,rules:t}}acceptsRules(e,t){if(this.role!==`forwarder`||e!==this.contextId||t.link!==this.upstream?.kind)return!1;let{origin:n}=t;return t.link===`parent`&&n!==location.origin&&!this.config.bus.trustedOrigins.includes(n)?(this.diagnostics.report(`bus.untrusted_origin`,`The bus ignored sampling rules from ${n}. If you own this origin, add it to bus.trustedOrigins.`,{origin:n,type:`sampling`}),!1):!0}applyRules(e){if(e===null){r.t(this.handlers.remote,this.config,null);return}let t=r.n(e,this.diagnostics);t&&r.t(this.handlers.remote,this.config,t)}pollRules(){let{upstream:n}=this;if(this.destroyed||this.role!==`forwarder`||!n)return;let r=()=>{this.config.sampling.remote&&n.post({t:`sampling?`,from:this.contextId})};r(),this.rulesPoll=setInterval(r,e.kt),t.r(this.rulesPoll)}};exports.Bus=y;
2
+ //# sourceMappingURL=bus-CtJWf9QN.cjs.map