@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bus-CtJWf9QN.cjs","names":["BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_HANDSHAKE_TIMEOUT_MS","BUS_CHANNEL_NAME","parseJourney","parseRemoteRules","REMOTE_SAMPLING_POLL_MS","require_constants","require_deadline","require_journey","require_remote_rules","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","OPAQUE_ORIGIN","untrustedText","origin","what","parentOrigin","ancestors","referrer","createDirectLink","host","target","open","diagnostics","receive","createParentLink","self","trusted","trustedOrigins","reported","onMessage","event","createChildrenLink","sources","source","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","createOwnerLink","scope","send","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","reply","current","link","configured","me","push","settled","finish","timer","resolve","result","from","payload","journey","rules","to","update","upstream","ask"],"sources":["../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL } from \"../constants\";\nimport type { LogRecord } from \"./log-record\";\n\n/** Delivery role. It tells if this context sends its records or forwards them upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel. The bus uses it to route incoming and outgoing messages.\n * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe\n * looks like a duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Inbound transport channel kind. */\n link: LinkKind;\n /** `event.origin` for `parent` and `children`. Other links use `\"same-origin\"` or `\"openfin\"`. */\n origin: string;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: \"hello\"; from: string; tabId: string }\n /**\n * Handshake response from an upstream owner. The `to` field holds the address.\n * A welcome on InterApplicationBus goes to every subscriber. Without an address,\n * each waiting view accepts the welcome as its own.\n */\n | { t: \"welcome\"; from: string; to: string; tabId: string }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: \"records\"; from: string; records: LogRecord[] }\n /**\n * Journey update, or the answer to a journey question. An answer holds the address of the\n * context that asked in `to`. The payload comes from another realm. The receiver parses it.\n */\n | { t: \"journey\"; from: string; to?: string; journey: unknown }\n /** Query requesting active journey state from connected peers. */\n | { t: \"journey?\"; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: \"tab\"; from: string; tabId: string }\n /** Request of a forwarder for the remote sampling rules in force. */\n | { t: \"sampling?\"; from: string }\n /**\n * Remote sampling rules in the shape of the header, with the remaining TTL. The `to` field\n * holds the address of the forwarder that asked. The receiver validates `rules` again.\n * Null rules end the copy of the forwarder.\n */\n | { t: \"sampling\"; from: string; to: string; rules: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A\n * document gets `message` events from all embedded content on the page. This\n * includes analytics tags, video players and extensions. Without the tag check,\n * the bus parses a message from a video player as a log record.\n * @param data Raw payload received over a transport link.\n * @returns Validated message, or null if payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { BUS_TYPE_DETAIL_MAX_CHARS, RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\n\n/** Bidirectional communication channel for bus message transport. */\nexport interface Link {\n /** Channel transport kind. */\n readonly kind: LinkKind;\n\n /**\n * Sends a message over the channel without throwing.\n * @param message Bus message to transmit.\n */\n post(message: BusMessage): void;\n\n /** Releases listeners, subscriptions, or channels held open by the link. */\n close(): void;\n}\n\n/**\n * Callback invoked when a bus message arrives on a link.\n * @param message Received bus message.\n * @param source Origin and link metadata.\n */\nexport type Receive = (message: BusMessage, source: MessageSource) => void;\n\n/** Interface that a same-origin parent runtime exposes on a global symbol. */\nexport interface DirectHost {\n /**\n * Accepts a message directly from a child frame and replies synchronously.\n * @param message Child bus message.\n * @param reply Callback for synchronous response.\n */\n busAccept(message: BusMessage, reply: Receive): void;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst OPAQUE_ORIGIN = \"null\";\n\n/** Location with the ancestor list that Chromium and WebKit give. */\ninterface LocationWithAncestors {\n origin: string;\n ancestorOrigins?: { length: number; item: (index: number) => string | null };\n}\n\n/**\n * Builds the message for an ignored message from an untrusted origin.\n * @param origin Origin of the sender.\n * @param what What the bus ignored, for example \"a message\".\n * @returns The message. A sandboxed sender gets the fix for its frame.\n */\nfunction untrustedText(origin: string, what: string): string {\n if (origin === OPAQUE_ORIGIN) {\n return `The bus ignored ${what} 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.`;\n }\n\n return `The bus ignored ${what} from ${origin}. If you own this origin, add it to bus.trustedOrigins.`;\n}\n\n/**\n * Reads the origin of the parent frame. A cross-origin parent does not give its location.\n * @returns The origin, or null when the browser does not give it.\n */\nfunction parentOrigin(): string | null {\n const ancestors = (location as LocationWithAncestors).ancestorOrigins;\n if (ancestors && ancestors.length > 0) {\n return ancestors.item(0);\n }\n\n // Firefox has no ancestorOrigins. The referrer of a frame is the page that loaded it.\n // A Referrer-Policy of no-referrer gives \"\". The caller reports an unknown origin.\n const referrer = document.referrer;\n if (referrer === \"\") {\n return null;\n }\n\n try {\n return new URL(referrer).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if parent is inaccessible or lacks a runtime.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n const target = host;\n let open = true;\n\n return {\n kind: \"direct\",\n post(message) {\n if (!open) {\n return;\n }\n\n // Stops an error in the parent runtime from breaking a logging call in the child.\n diagnostics.guard(\n \"bus.send_failed\",\n \"The direct call into the parent runtime failed.\",\n () => {\n target.busAccept(message, receive);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to a parent window on a trusted origin. Records hold user data.\n * A page on another origin that frames this app must not get them.\n * @param receive Callback for incoming parent messages.\n * @param trustedOrigins Origins of a parent that can get the records, in addition to this origin.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to the parent window, or null at the top level or with an untrusted parent.\n * With null, this context sends its own records.\n */\nexport function createParentLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n // A sandboxed frame has an opaque origin. No parent can list it in its own trust list.\n const self = location.origin;\n if (self === OPAQUE_ORIGIN) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n '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.',\n { origin: self, type: \"parent\" },\n );\n return null;\n }\n\n const trusted = new Set([self, ...trustedOrigins]);\n const target = parentOrigin();\n if (target === null || !trusted.has(target)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n target === null\n ? \"The origin of the parent frame is unknown. This context sends its own records.\"\n : `The parent frame is on ${target}. This origin is not in bus.trustedOrigins. This context sends its own records.`,\n { origin: target ?? \"\", type: \"parent\" },\n );\n return null;\n }\n\n // Report each untrusted origin one time. A hostile parent can send many messages.\n const reported = new Set<string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message || event.source !== window.parent) {\n return;\n }\n\n // The parent can navigate to another origin after this frame loads.\n if (!trusted.has(event.origin)) {\n if (!reported.has(event.origin)) {\n reported.add(event.origin);\n // The parent sets message.t. Keep it out of the message text. Cut it in the detail.\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n }\n return;\n }\n\n receive(message, { link: \"parent\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // Target the trusted origin, not \"*\". The browser drops the message if the parent\n // navigated to another origin.\n window.parent.postMessage(envelope(message), target);\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // A sandboxed page has the opaque origin \"null\". Each sandboxed child also has it.\n const trusted = new Set([location.origin, ...trustedOrigins]);\n trusted.delete(OPAQUE_ORIGIN);\n\n // The map keeps the origin of each source.\n // A child that navigates must not get the ids of its previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n if (!trusted.has(event.origin)) {\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n return;\n }\n\n if (event.source) {\n sources.set(event.source, event.origin);\n }\n receive(message, { link: \"children\", origin: event.origin });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n continue;\n }\n diagnostics.guard(\n \"bus.send_failed\",\n \"The postMessage call to a child frame failed.\",\n () => {\n // Targets the last known origin of the child. The browser drops the\n // message if the child navigated to a different origin.\n target.postMessage(envelope(message), origin);\n },\n );\n }\n },\n close() {\n removeEventListener(\"message\", onMessage);\n sources.clear();\n },\n };\n}\n\n/**\n * Creates a same-origin BroadcastChannel link for cross-tab control messages.\n * @param channelName BroadcastChannel identifier.\n * @param receive Callback for incoming cross-tab messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Broadcast link, or null if unsupported.\n */\nexport function createBroadcastLink(\n channelName: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const BC = (globalThis as { BroadcastChannel?: typeof BroadcastChannel }).BroadcastChannel;\n if (typeof BC === \"undefined\") {\n return null;\n }\n\n const channel = diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not open the BroadcastChannel.\",\n () => new BC(channelName),\n );\n if (!channel) {\n return null;\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"broadcast\", origin: \"same-origin\" });\n }\n };\n\n return {\n kind: \"broadcast\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The BroadcastChannel.postMessage call failed.\", () => {\n channel.postMessage(envelope(message));\n });\n },\n close() {\n diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not close the BroadcastChannel.\",\n () => {\n channel.close();\n },\n );\n },\n };\n}\n\n/** Structural interface for OpenFin InterApplicationBus operations. */\ninterface FinIab {\n /**\n * Publishes a message to all topic subscribers.\n * @param topic Topic name.\n * @param message Message payload.\n */\n publish(topic: string, message: unknown): Promise<void>;\n\n /**\n * Subscribes a listener to a topic for matching application identities.\n * @param identity Target application identity.\n * @param topic Topic name.\n * @param listener Message callback.\n */\n subscribe(\n identity: { uuid: string },\n topic: string,\n listener: (message: unknown) => void,\n ): Promise<void>;\n}\n\n/**\n * Creates an OpenFin InterApplicationBus link scoped to one application.\n * @param topic InterApplicationBus topic prefix.\n * @param appUuid OpenFin application uuid owning this context.\n * @param receive Callback for received topic messages.\n * @param diagnostics Diagnostics reporter.\n * @returns OpenFin link, or null if InterApplicationBus or the identity is unavailable.\n */\nexport function createOpenFinLink(\n topic: string,\n appUuid: string | undefined,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const fin = (globalThis as { fin?: { InterApplicationBus?: FinIab } }).fin;\n const iab = fin?.InterApplicationBus;\n if (!iab) {\n return null;\n }\n if (!appUuid) {\n // publish() sends to every subscriber on the runtime. Without a uuid scope,\n // this link shares the bus of this app with all other apps.\n diagnostics.report(\n \"openfin.unavailable\",\n \"OpenFin gives no application uuid. The InterApplicationBus link stays closed.\",\n );\n return null;\n }\n\n // The topic and the subscriber identity both contain the uuid. The topic keeps\n // messages of this app from other apps. The identity rejects messages from other apps.\n const scoped = `${topic}.${appUuid}`;\n\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.subscribe call failed.\",\n () =>\n iab.subscribe({ uuid: appUuid }, scoped, (raw) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, { link: \"openfin\", origin: \"openfin\" });\n }\n }),\n );\n\n return {\n kind: \"openfin\",\n post(message) {\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.publish call failed.\",\n () => iab.publish(scoped, envelope(message)),\n );\n },\n close() {\n // OpenFin removes the subscriptions when the context closes.\n },\n };\n}\n\n/**\n * Creates the worker-side link pointing at the document that created this\n * worker. Emits `kind: \"owner\"`.\n * @param receive Callback for incoming messages from the owning document.\n * @param diagnostics Diagnostics reporter.\n * @returns Owner link, or null outside a DedicatedWorkerGlobalScope.\n */\nexport function createOwnerLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n const scope = globalThis as unknown as {\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: string, listener: (event: MessageEvent) => void) => void;\n WorkerGlobalScope?: unknown;\n };\n const send = scope.postMessage;\n if (typeof scope.WorkerGlobalScope === \"undefined\" || !send) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"owner\", origin: \"same-origin\" });\n }\n };\n scope.addEventListener?.(\"message\", onMessage);\n\n return {\n kind: \"owner\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call of the worker failed.\", () => {\n send(envelope(message));\n });\n },\n close() {\n // Worker scope listeners stop when the worker stops.\n },\n };\n}\n\n/**\n * Creates the document-side link pointing at one attached worker or port.\n * Emits `kind: \"worker\"`.\n * @param worker Target worker instance or MessagePort.\n * @param receive Callback for messages from the worker.\n * @param diagnostics Diagnostics reporter.\n * @returns Document-to-worker link.\n */\nexport function createWorkerLink(\n worker: WorkerLike,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link {\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"worker\", origin: \"same-origin\" });\n }\n };\n worker.addEventListener(\"message\", onMessage);\n\n // Starts delivery on a MessagePort. A Worker has no start method.\n worker.start?.();\n\n return {\n kind: \"worker\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a worker failed.\", () => {\n worker.postMessage(envelope(message));\n });\n },\n close() {\n worker.removeEventListener(\"message\", onMessage);\n },\n };\n}\n","// src/bus/bus.ts\n//\n// Resolves the bus role and routes messages between realms.\n\nimport {\n BUS_CHANNEL_NAME,\n BUS_HANDSHAKE_TIMEOUT_MS,\n BUS_MAX_HANDSHAKE_ATTEMPTS,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type Journey, parseJourney } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { JourneyScope, ResolvedConfig } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { unrefTimer } from \"../utils/unref\";\nimport {\n createBroadcastLink,\n createChildrenLink,\n createDirectLink,\n createOpenFinLink,\n createOwnerLink,\n createParentLink,\n createWorkerLink,\n type Link,\n type Receive,\n type WorkerLike,\n} from \"./links\";\n\n/** Handshake timing for a forwarder waiting on an owner. */\nexport interface HandshakeOptions {\n /** Maximum time that a forwarder waits for an owner to answer, in milliseconds. */\n timeoutMs: number;\n /** Attempts allowed before a cross-origin forwarder promotes itself to sender. */\n maxAttempts: number;\n}\n\n/** Default handshake timing. Tests build a bus with shorter values. */\nexport const HANDSHAKE_OPTIONS: HandshakeOptions = {\n timeoutMs: BUS_HANDSHAKE_TIMEOUT_MS,\n maxAttempts: BUS_MAX_HANDSHAKE_ATTEMPTS,\n};\n\n/** Callbacks for handling records and journey events from connected realms. */\nexport interface BusHandlers {\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /** Slot of the runtime for the remote sampling rules. The bus reads it and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Journey scope after the bus resolves \"auto\". */\ntype ResolvedScope = Exclude<JourneyScope, \"auto\">;\n\n/** Structural shape of fin.me identity metadata. */\ninterface OpenFinMe {\n isView?: boolean;\n identity?: { uuid?: string; name?: string };\n}\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Current bus role. The default is \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** True if this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** True if role resolution is complete. */\n private resolved = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(). A handshake that ends later must not start a timer. */\n private destroyed = false;\n /** Context id of the owner that answered the handshake. Null with no handshake. */\n private ownerId: string | null = null;\n /** Active handshake state awaiting welcome response. */\n private awaitingWelcome: {\n link: LinkKind;\n settle: (ok: boolean) => void;\n } | null = null;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param platform Platform runtime metadata.\n * @param contextId Unique context identifier for loop prevention.\n * @param tabId Tab identifier announced on broadcast channels.\n * @param handlers Callbacks for routed bus events.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n private readonly platform: PlatformMetadata,\n private readonly contextId: string,\n private readonly tabId: string,\n private readonly handlers: BusHandlers,\n private readonly handshakeOptions: HandshakeOptions = HANDSHAKE_OPTIONS,\n ) {}\n\n /** Returns the resolved bus role. */\n getRole(): BusRole {\n return this.role;\n }\n\n /** Returns true if role resolution is complete. */\n isResolved(): boolean {\n return this.resolved;\n }\n\n /**\n * Resolves bus role and establishes control links.\n * @returns Resolved role.\n */\n async start(): Promise<BusRole> {\n const { bus } = this.config;\n\n if (bus.mode === \"off\") {\n this.role = \"sender\";\n this.resolved = true;\n return this.role;\n }\n\n this.isOpenFinProvider = this.resolveOpenFinProvider();\n\n if (bus.mode === \"sender\" || bus.mode === \"forwarder\") {\n this.role = bus.mode;\n this.openControlLinks();\n if (this.role === \"forwarder\") {\n this.upstream = this.candidateUpstream();\n if (!this.upstream) {\n this.diagnostics.report(\n \"bus.no_owner\",\n 'bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.',\n );\n }\n }\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n this.openControlLinks();\n\n // A same-origin parent runtime accepts a direct synchronous link.\n const direct = createDirectLink(this.receive, this.diagnostics);\n if (direct) {\n this.role = \"forwarder\";\n this.upstream = direct;\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"This context attached directly to the runtime of its same-origin parent.\",\n {\n role: \"forwarder\",\n via: \"direct\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const candidate = this.candidateUpstream();\n\n if (!candidate) {\n this.role = \"sender\";\n this.resolved = true;\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"No owner exists. This context sends its own records.\",\n {\n role: \"sender\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const attempts = this.orphanPolicy() === \"retry\" ? this.handshakeOptions.maxAttempts : 1;\n\n let welcomed = false;\n for (let attempt = 0; attempt < attempts && !welcomed; attempt++) {\n welcomed = await this.handshake(candidate);\n }\n\n this.role = welcomed ? \"forwarder\" : \"sender\";\n this.upstream = welcomed ? candidate : null;\n if (!welcomed) {\n // OpenFin link remains open for control messages.\n if (candidate !== this.openFinLink) {\n candidate.close();\n }\n this.diagnostics.report(\n \"bus.handshake_timeout\",\n `No owner answered after ${String(attempts)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,\n { via: candidate.kind, crossOrigin: this.isCrossOriginFrame() },\n );\n }\n this.diagnostics.report(\"bus.role_resolved\", `The bus role is ${this.role}.`, {\n role: this.role,\n via: welcomed ? candidate.kind : \"none\",\n });\n\n this.resolved = true;\n this.announce();\n return this.role;\n }\n\n /**\n * Forwards records to the upstream owner if configured.\n * @param records Batch of log records to send.\n */\n sendRecords(records: LogRecord[]): void {\n this.upstream?.post({ t: \"records\", from: this.contextId, records });\n }\n\n /**\n * Synchronously processes direct messages from same-origin child contexts.\n * @param message Received bus message.\n * @param reply Direct response callback.\n */\n acceptDirect(message: BusMessage, reply: Receive): void {\n if (message.from === this.contextId) {\n return;\n }\n const source: MessageSource = { link: \"direct\", origin: \"same-origin\" };\n\n if (message.t === \"hello\") {\n if (this.canOwn(\"direct\")) {\n reply(\n {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n },\n source,\n );\n }\n return;\n }\n if (message.t === \"journey?\") {\n const current = this.handlers.onJourneyRequest();\n if (current && this.journeyLink(\"direct\")) {\n reply({ t: \"journey\", from: this.contextId, to: message.from, journey: current }, source);\n }\n return;\n }\n // A direct link has no channel from the parent to the child. The parent answers here.\n if (message.t === \"sampling?\") {\n reply(this.rulesAnswer(message.from), source);\n return;\n }\n this.receive(message, source);\n }\n\n /**\n * Connects a worker instance to the bus control plane.\n * @param worker Worker instance.\n */\n attachWorker(worker: WorkerLike): void {\n this.links.push(createWorkerLink(worker, this.receive, this.diagnostics));\n }\n\n /**\n * Sends journey state changes over each link of the journey scope.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.postJourney({ t: \"journey\", from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.ownerId = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Sends a journey message over each link of the journey scope. */\n private postJourney(message: BusMessage): void {\n for (const link of this.allLinks()) {\n if (this.journeyLink(link.kind)) {\n link.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case \"hello\":\n if (this.canOwn(source.link)) {\n this.postOver(source.link, {\n t: \"welcome\",\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n });\n }\n break;\n\n case \"welcome\":\n if (message.to !== this.contextId) {\n break;\n }\n if (this.awaitingWelcome?.link === source.link) {\n // Keep the owner. Only it can set the journey of this context on a shared link.\n this.ownerId = message.from;\n this.awaitingWelcome.settle(true);\n }\n break;\n\n case \"records\":\n if (this.role === \"sender\") {\n this.handlers.onRecords(message.records);\n } else if (this.upstream && this.canRelay(source.link)) {\n // Relays records upstream in nested frame chains.\n this.upstream.post(message);\n }\n break;\n\n case \"journey\":\n if (this.acceptsJourney(message, source)) {\n this.applyJourney(message.journey);\n }\n break;\n\n case \"journey?\": {\n const current = this.handlers.onJourneyRequest();\n // Address the answer. On a shared link, each other context ignores it.\n if (current && this.journeyLink(source.link)) {\n this.postOver(source.link, {\n t: \"journey\",\n from: this.contextId,\n to: message.from,\n journey: current,\n });\n }\n break;\n }\n\n case \"sampling?\":\n // A forwarder answers only its own children. A sibling on its upstream link asks too.\n // A sibling answer on OpenFin gives N squared messages, and a stale copy can win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.postOver(source.link, this.rulesAnswer(message.from));\n }\n break;\n\n case \"sampling\":\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case \"tab\":\n // A collision applies only to two different contexts on the broadcast channel.\n // The id comparison selects one context of the pair.\n // Without it, both contexts report the conflict and rename.\n if (\n source.link === \"broadcast\" &&\n message.tabId === this.tabId &&\n this.contextId > message.from\n ) {\n this.handlers.onTabConflict();\n }\n break;\n }\n };\n\n /**\n * Tells if records from a link can go upstream. Records that go back on\n * their arrival link return to their sender. A direct link is an exception.\n * Each direct link is one call into one parent. Thus two direct links in a\n * chain are different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Returns true if this context can be the owner of the given link type. */\n private canOwn(link: LinkKind): boolean {\n if (this.role !== \"sender\") {\n return false;\n }\n if (link === \"openfin\") {\n return this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Finds if this context is the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = (globalThis as { fin?: { me?: OpenFinMe } }).fin?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Tests if a cross-origin boundary blocks access to the parent window. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. Lint rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (this.platform.isTopLevelDocument) {\n push(createChildrenLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics));\n push(createBroadcastLink(BUS_CHANNEL_NAME, this.receive, this.diagnostics));\n }\n if (this.platform.platform === \"openfin\" || this.platform.platform === \"openfin_web\") {\n push(this.ensureOpenFinLink());\n }\n }\n\n /** Returns the singleton OpenFin InterApplicationBus link. */\n private ensureOpenFinLink(): Link | null {\n this.openFinLink ??= createOpenFinLink(\n BUS_CHANNEL_NAME,\n this.platform.openfinUuid,\n this.receive,\n this.diagnostics,\n );\n return this.openFinLink;\n }\n\n /**\n * Executes a hello/welcome handshake over candidate link.\n * @param candidate Upstream link candidate.\n * @returns True if welcome response arrived before timeout.\n */\n private handshake(candidate: Link): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (result: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n this.awaitingWelcome = null;\n clearTimeout(timer);\n resolve(result);\n };\n\n this.awaitingWelcome = { link: candidate.kind, settle: finish };\n // finish reads timer, which the code declares after finish. This order is safe.\n // finish can run only after the post below. The timer exists at that time.\n const timer = setTimeout(() => {\n finish(false);\n }, this.handshakeOptions.timeoutMs);\n unrefTimer(timer);\n candidate.post({ t: \"hello\", from: this.contextId, tabId: this.tabId });\n });\n }\n\n /** Broadcasts tab claim and queries existing journey state. */\n private announce(): void {\n this.postOver(\"broadcast\", {\n t: \"tab\",\n from: this.contextId,\n tabId: this.tabId,\n });\n this.postJourney({ t: \"journey?\", from: this.contextId });\n this.pollRules();\n }\n\n /**\n * Resolves the journey scope. \"auto\" gives \"origin\" in OpenFin and \"tab\" in a browser.\n * @returns The scope in force.\n */\n private journeyScope(): ResolvedScope {\n const { scope } = this.config.journey;\n if (scope !== \"auto\") {\n return scope;\n }\n\n const { platform } = this.platform;\n return platform === \"openfin\" || platform === \"openfin_web\" ? \"origin\" : \"tab\";\n }\n\n /**\n * Tests if a link carries journey messages in the scope in force.\n * Only \"origin\" uses the broadcast link. That link reaches each tab of the origin.\n * @param link Link kind.\n * @returns True if the link carries journey messages.\n */\n private journeyLink(link: LinkKind): boolean {\n const scope = this.journeyScope();\n if (scope === \"context\") {\n return false;\n }\n\n return scope === \"origin\" || link !== \"broadcast\";\n }\n\n /**\n * Tests if this context adopts a journey message.\n * @param message Journey message.\n * @param source Link and origin of the message.\n * @returns True for a message on a journey link, to this context, from an accepted sender.\n * In \"tab\" scope, only the owner of a forwarder is an accepted sender.\n */\n private acceptsJourney(\n message: Extract<BusMessage, { t: \"journey\" }>,\n source: MessageSource,\n ): boolean {\n if (!this.journeyLink(source.link)) {\n return false;\n }\n\n if (message.to !== undefined && message.to !== this.contextId) {\n return false;\n }\n\n return this.journeyScope() === \"origin\" || this.fromOwner(message.from, source.link);\n }\n\n /**\n * Tests if a message comes from the upstream owner of this forwarder.\n * @param from Context id of the sender.\n * @param link Link kind of the message.\n * @returns True for the upstream link and, after a handshake, the owner that answered it.\n */\n private fromOwner(from: string, link: LinkKind): boolean {\n if (this.role !== \"forwarder\" || link !== this.upstream?.kind) {\n return false;\n }\n\n return this.ownerId === null || from === this.ownerId;\n }\n\n /**\n * Parses a journey payload from another realm and gives it to the runtime.\n * @param payload Journey, or null when the journey ended.\n */\n private applyJourney(payload: unknown): void {\n if (payload === null) {\n this.handlers.onJourney(null);\n return;\n }\n\n const journey = parseJourney(payload);\n if (journey === null) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n \"The bus dropped a journey message. Its payload is not a journey.\",\n { type: \"journey\" },\n );\n return;\n }\n\n this.handlers.onJourney(journey);\n }\n\n /**\n * Builds the answer to a sampling question. Null rules end the copy of the forwarder.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: \"sampling\", from: this.contextId, to, rules };\n }\n\n /**\n * Tests if this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link is not trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. It must not lower minLevel and read the records.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== location.origin &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return true;\n }\n\n /**\n * Applies the rules of an answer. It ignores rules that are not valid.\n * @param raw Rules of the answer, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then at each poll interval.\n * A direct link cannot push the rules to a child. A poll works on each link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config at each poll. A later configure() can turn remote sampling on or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: \"sampling?\", from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":"8JAkFA,SAAgBW,EAAS,EAAkC,CACzD,MAAO,CAAE,EAAGX,EAAAA,EAAc,EAAGY,CAAQ,CACvC,CAUA,SAAgBC,EAAO,EAAkC,CACvD,GAA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a,KAAK,OAAS,aAAe,CAACC,EAClD,OAIF,IAAMC,MAAkB,CAClB,KAAK,OAAO,SAAS,QACvBD,EAAS,KAAK,CAAE,EAAG,YAAa,KAAM,KAAK,SAAU,CAAC,CAE1D,EAEAC,EAAI,EACJ,KAAK,UAAY,YAAYA,EAAKlF,EAAAA,EAAuB,EACzDE,EAAA,EAAW,KAAK,SAAS,CAC3B,CACF"}
@@ -1,13 +1,15 @@
1
- import { Rt as e, S as t, b as n, x as r } from "./constants-C8nZQBmQ.js";
2
- import { t as i } from "./unref-16maCyKA.js";
1
+ import { C as e, S as t, kt as n, qt as r, w as i } from "./constants-DM94FjVX.js";
2
+ import { r as a } from "./deadline-B5DINjD5.js";
3
+ import { r as o } from "./journey-CeJ1QoT2.js";
4
+ import { n as s, t as c } from "./remote-rules-Bt1XsdEQ.js";
3
5
  //#region src/models/bus.ts
4
- function a(e) {
6
+ function l(e) {
5
7
  return {
6
- p: t,
8
+ p: i,
7
9
  m: e
8
10
  };
9
11
  }
10
- function o(e) {
12
+ function u(e) {
11
13
  if (typeof e != "object" || !e) return null;
12
14
  let t = e;
13
15
  if (t.p !== "ui-observability/1" || typeof t.m != "object" || t.m === null) return null;
@@ -16,12 +18,26 @@ function o(e) {
16
18
  }
17
19
  //#endregion
18
20
  //#region src/bus/links.ts
19
- var s = Symbol.for(e);
20
- function c(e, t) {
21
+ var d = Symbol.for(r), f = "null";
22
+ function p(e, t) {
23
+ return e === f ? `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.`;
24
+ }
25
+ function m() {
26
+ let e = location.ancestorOrigins;
27
+ if (e && e.length > 0) return e.item(0);
28
+ let t = document.referrer;
29
+ if (t === "") return null;
30
+ try {
31
+ return new URL(t).origin;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+ function h(e, t) {
21
37
  if (typeof window > "u" || window.parent === window) return null;
22
38
  let n;
23
39
  try {
24
- n = window.parent[s];
40
+ n = window.parent[d];
25
41
  } catch {
26
42
  return null;
27
43
  }
@@ -39,60 +55,75 @@ function c(e, t) {
39
55
  }
40
56
  };
41
57
  }
42
- function l(e, t) {
58
+ function g(e, t, n) {
43
59
  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, {
60
+ let r = location.origin;
61
+ if (r === f) 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.", {
62
+ origin: r,
63
+ type: "parent"
64
+ }), null;
65
+ let i = /* @__PURE__ */ new Set([r, ...t]), a = m();
66
+ if (a === null || !i.has(a)) return n.report("bus.untrusted_origin", a === null ? "The origin of the parent frame is unknown. This context sends its own records." : `The parent frame is on ${a}. This origin is not in bus.trustedOrigins. This context sends its own records.`, {
67
+ origin: a ?? "",
68
+ type: "parent"
69
+ }), null;
70
+ let o = /* @__PURE__ */ new Set(), s = (t) => {
71
+ let r = u(t.data);
72
+ r && t.source === window.parent && (i.has(t.origin) ? e(r, {
47
73
  link: "parent",
48
74
  origin: t.origin
49
- });
75
+ }) : o.has(t.origin) || (o.add(t.origin), n.report("bus.untrusted_origin", p(t.origin, "a message"), {
76
+ origin: t.origin,
77
+ type: r.t.slice(0, 32)
78
+ })));
50
79
  };
51
- return addEventListener("message", n), {
80
+ return addEventListener("message", s), {
52
81
  kind: "parent",
53
82
  post(e) {
54
- t.guard("bus.send_failed", "The postMessage call to the parent failed.", () => {
55
- window.parent.postMessage(a(e), "*");
83
+ n.guard("bus.send_failed", "The postMessage call to the parent failed.", () => {
84
+ window.parent.postMessage(l(e), a);
56
85
  });
57
86
  },
58
87
  close() {
59
- removeEventListener("message", n);
88
+ removeEventListener("message", s);
60
89
  }
61
90
  };
62
91
  }
63
- function u(e, t, n) {
92
+ function _(e, t, n) {
64
93
  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);
94
+ let r = /* @__PURE__ */ new Set([location.origin, ...t]);
95
+ r.delete(f);
96
+ let i = /* @__PURE__ */ new Map(), a = (t) => {
97
+ let a = u(t.data);
67
98
  a && (r.has(t.origin) ? (t.source && i.set(t.source, t.origin), e(a, {
68
99
  link: "children",
69
100
  origin: t.origin
70
- })) : n.report("bus.untrusted_origin", `The bus ignored a message from ${t.origin}. If you own this origin, add it to bus.trustedOrigins.`, {
101
+ })) : n.report("bus.untrusted_origin", p(t.origin, "a message"), {
71
102
  origin: t.origin,
72
- type: a.t
103
+ type: a.t.slice(0, 32)
73
104
  }));
74
105
  };
75
- return addEventListener("message", s), {
106
+ return addEventListener("message", a), {
76
107
  kind: "children",
77
108
  post(e) {
78
109
  for (let [t, r] of i) {
79
- let o = t;
80
- o.closed ? i.delete(t) : n.guard("bus.send_failed", "The postMessage call to a child frame failed.", () => {
81
- o.postMessage(a(e), r);
110
+ let a = t;
111
+ a.closed ? i.delete(t) : n.guard("bus.send_failed", "The postMessage call to a child frame failed.", () => {
112
+ a.postMessage(l(e), r);
82
113
  });
83
114
  }
84
115
  },
85
116
  close() {
86
- removeEventListener("message", s), i.clear();
117
+ removeEventListener("message", a), i.clear();
87
118
  }
88
119
  };
89
120
  }
90
- function d(e, t, n) {
121
+ function v(e, t, n) {
91
122
  let r = globalThis.BroadcastChannel;
92
123
  if (r === void 0) return null;
93
124
  let i = n.guard("bus.send_failed", "The library could not open the BroadcastChannel.", () => new r(e));
94
125
  return i ? (i.onmessage = (e) => {
95
- let n = o(e.data);
126
+ let n = u(e.data);
96
127
  n && t(n, {
97
128
  link: "broadcast",
98
129
  origin: "same-origin"
@@ -101,7 +132,7 @@ function d(e, t, n) {
101
132
  kind: "broadcast",
102
133
  post(e) {
103
134
  n.guard("bus.send_failed", "The BroadcastChannel.postMessage call failed.", () => {
104
- i.postMessage(a(e));
135
+ i.postMessage(l(e));
105
136
  });
106
137
  },
107
138
  close() {
@@ -111,13 +142,13 @@ function d(e, t, n) {
111
142
  }
112
143
  }) : null;
113
144
  }
114
- function f(e, t, n, r) {
145
+ function y(e, t, n, r) {
115
146
  let i = globalThis.fin?.InterApplicationBus;
116
147
  if (!i) return null;
117
148
  if (!t) return r.report("openfin.unavailable", "OpenFin gives no application uuid. The InterApplicationBus link stays closed."), null;
118
- let s = `${e}.${t}`;
119
- return r.guardAsync("bus.send_failed", "The InterApplicationBus.subscribe call failed.", () => i.subscribe({ uuid: t }, s, (e) => {
120
- let t = o(e);
149
+ let a = `${e}.${t}`;
150
+ return r.guardAsync("bus.send_failed", "The InterApplicationBus.subscribe call failed.", () => i.subscribe({ uuid: t }, a, (e) => {
151
+ let t = u(e);
121
152
  t && n(t, {
122
153
  link: "openfin",
123
154
  origin: "openfin"
@@ -125,15 +156,15 @@ function f(e, t, n, r) {
125
156
  })), {
126
157
  kind: "openfin",
127
158
  post(e) {
128
- r.guardAsync("bus.send_failed", "The InterApplicationBus.publish call failed.", () => i.publish(s, a(e)));
159
+ r.guardAsync("bus.send_failed", "The InterApplicationBus.publish call failed.", () => i.publish(a, l(e)));
129
160
  },
130
161
  close() {}
131
162
  };
132
163
  }
133
- function p(e, t) {
164
+ function b(e, t) {
134
165
  let n = globalThis, r = n.postMessage;
135
166
  return n.WorkerGlobalScope === void 0 || !r ? null : (n.addEventListener?.("message", (t) => {
136
- let n = o(t.data);
167
+ let n = u(t.data);
137
168
  n && e(n, {
138
169
  link: "owner",
139
170
  origin: "same-origin"
@@ -142,15 +173,15 @@ function p(e, t) {
142
173
  kind: "owner",
143
174
  post(e) {
144
175
  t.guard("bus.send_failed", "The postMessage call of the worker failed.", () => {
145
- r(a(e));
176
+ r(l(e));
146
177
  });
147
178
  },
148
179
  close() {}
149
180
  });
150
181
  }
151
- function m(e, t, n) {
182
+ function x(e, t, n) {
152
183
  let r = (e) => {
153
- let n = o(e.data);
184
+ let n = u(e.data);
154
185
  n && t(n, {
155
186
  link: "worker",
156
187
  origin: "same-origin"
@@ -160,7 +191,7 @@ function m(e, t, n) {
160
191
  kind: "worker",
161
192
  post(t) {
162
193
  n.guard("bus.send_failed", "The postMessage call to a worker failed.", () => {
163
- e.postMessage(a(t));
194
+ e.postMessage(l(t));
164
195
  });
165
196
  },
166
197
  close() {
@@ -170,14 +201,14 @@ function m(e, t, n) {
170
201
  }
171
202
  //#endregion
172
203
  //#region src/bus/bus.ts
173
- var h = {
174
- timeoutMs: r,
204
+ var S = {
205
+ timeoutMs: e,
175
206
  maxAttempts: 3
176
- }, g = [
207
+ }, C = [
177
208
  "children",
178
209
  "direct",
179
210
  "worker"
180
- ], _ = class {
211
+ ], w = class {
181
212
  config;
182
213
  diagnostics;
183
214
  platform;
@@ -191,8 +222,11 @@ var h = {
191
222
  openFinLink = null;
192
223
  isOpenFinProvider = !1;
193
224
  resolved = !1;
225
+ rulesPoll;
226
+ destroyed = !1;
227
+ ownerId = null;
194
228
  awaitingWelcome = null;
195
- constructor(e, t, n, r, i, a, o = h) {
229
+ constructor(e, t, n, r, i, a, o = S) {
196
230
  this.config = e, this.diagnostics = t, this.platform = n, this.contextId = r, this.tabId = i, this.handlers = a, this.handshakeOptions = o;
197
231
  }
198
232
  getRole() {
@@ -206,7 +240,7 @@ var h = {
206
240
  if (e.mode === "off") return this.role = "sender", this.resolved = !0, this.role;
207
241
  if (this.isOpenFinProvider = this.resolveOpenFinProvider(), e.mode === "sender" || e.mode === "forwarder") return this.role = e.mode, this.openControlLinks(), this.role === "forwarder" && (this.upstream = this.candidateUpstream(), this.upstream || this.diagnostics.report("bus.no_owner", "bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.")), this.resolved = !0, this.announce(), this.role;
208
242
  this.openControlLinks();
209
- let t = c(this.receive, this.diagnostics);
243
+ let t = h(this.receive, this.diagnostics);
210
244
  if (t) return this.role = "forwarder", this.upstream = t, this.resolved = !0, this.diagnostics.report("bus.role_resolved", "This context attached directly to the runtime of its same-origin parent.", {
211
245
  role: "forwarder",
212
246
  via: "direct"
@@ -243,37 +277,39 @@ var h = {
243
277
  tabId: this.tabId
244
278
  }, n);
245
279
  else if (e.t === "journey?") {
246
- let e = this.handlers.onJourneyRequest();
247
- e && t({
280
+ let r = this.handlers.onJourneyRequest();
281
+ r && this.journeyLink("direct") && t({
248
282
  t: "journey",
249
283
  from: this.contextId,
250
- journey: e
284
+ to: e.from,
285
+ journey: r
251
286
  }, n);
252
- } else this.receive(e, n);
287
+ } else e.t === "sampling?" ? t(this.rulesAnswer(e.from), n) : this.receive(e, n);
253
288
  }
254
289
  attachWorker(e) {
255
- this.links.push(m(e, this.receive, this.diagnostics));
290
+ this.links.push(x(e, this.receive, this.diagnostics));
256
291
  }
257
292
  broadcastJourney(e) {
258
- this.post({
293
+ this.postJourney({
259
294
  t: "journey",
260
295
  from: this.contextId,
261
296
  journey: e
262
297
  });
263
298
  }
264
299
  destroy() {
300
+ this.destroyed = !0, clearInterval(this.rulesPoll), this.rulesPoll = void 0;
265
301
  for (let e of this.allLinks()) e.close();
266
- this.links.length = 0, this.upstream = null, this.openFinLink = null;
302
+ this.links.length = 0, this.upstream = null, this.ownerId = null, this.openFinLink = null;
267
303
  }
268
304
  allLinks() {
269
305
  return !this.upstream || this.links.includes(this.upstream) ? this.links : [...this.links, this.upstream];
270
306
  }
271
- post(e) {
272
- for (let t of this.allLinks()) t.post(e);
273
- }
274
307
  postOver(e, t) {
275
308
  for (let n of this.allLinks()) n.kind === e && n.post(t);
276
309
  }
310
+ postJourney(e) {
311
+ for (let t of this.allLinks()) this.journeyLink(t.kind) && t.post(e);
312
+ }
277
313
  receive = (e, t) => {
278
314
  if (e.from !== this.contextId) switch (e.t) {
279
315
  case "hello":
@@ -286,23 +322,30 @@ var h = {
286
322
  break;
287
323
  case "welcome":
288
324
  if (e.to !== this.contextId) break;
289
- this.awaitingWelcome?.link === t.link && this.awaitingWelcome.settle(!0);
325
+ this.awaitingWelcome?.link === t.link && (this.ownerId = e.from, this.awaitingWelcome.settle(!0));
290
326
  break;
291
327
  case "records":
292
328
  this.role === "sender" ? this.handlers.onRecords(e.records) : this.upstream && this.canRelay(t.link) && this.upstream.post(e);
293
329
  break;
294
330
  case "journey":
295
- this.handlers.onJourney(e.journey);
331
+ this.acceptsJourney(e, t) && this.applyJourney(e.journey);
296
332
  break;
297
333
  case "journey?": {
298
- let e = this.handlers.onJourneyRequest();
299
- e && this.postOver(t.link, {
334
+ let n = this.handlers.onJourneyRequest();
335
+ n && this.journeyLink(t.link) && this.postOver(t.link, {
300
336
  t: "journey",
301
337
  from: this.contextId,
302
- journey: e
338
+ to: e.from,
339
+ journey: n
303
340
  });
304
341
  break;
305
342
  }
343
+ case "sampling?":
344
+ (this.role === "forwarder" ? t.link !== this.upstream?.kind : this.canOwn(t.link)) && this.postOver(t.link, this.rulesAnswer(e.from));
345
+ break;
346
+ case "sampling":
347
+ this.acceptsRules(e.to, t) && this.applyRules(e.rules);
348
+ break;
306
349
  case "tab": t.link === "broadcast" && e.tabId === this.tabId && this.contextId > e.from && this.handlers.onTabConflict();
307
350
  }
308
351
  };
@@ -310,7 +353,7 @@ var h = {
310
353
  return e === "direct" || e !== this.upstream?.kind;
311
354
  }
312
355
  canOwn(e) {
313
- return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : g.includes(e) : !1;
356
+ return this.role === "sender" ? e === "openfin" ? this.isOpenFinProvider : C.includes(e) : !1;
314
357
  }
315
358
  resolveOpenFinProvider() {
316
359
  let e = this.config.bus.openFinRole;
@@ -331,30 +374,30 @@ var h = {
331
374
  }
332
375
  }
333
376
  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);
377
+ return this.platform.isWorker ? b(this.receive, this.diagnostics) : this.platform.isTopLevelDocument ? this.platform.platform === "openfin" && !this.isOpenFinProvider ? this.ensureOpenFinLink() : null : g(this.receive, this.config.bus.trustedOrigins, this.diagnostics);
335
378
  }
336
379
  openControlLinks() {
337
380
  let e = (e) => {
338
381
  e && this.links.push(e);
339
382
  };
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());
383
+ this.platform.isTopLevelDocument && (e(_(this.receive, this.config.bus.trustedOrigins, this.diagnostics)), e(v(t, this.receive, this.diagnostics))), (this.platform.platform === "openfin" || this.platform.platform === "openfin_web") && e(this.ensureOpenFinLink());
341
384
  }
342
385
  ensureOpenFinLink() {
343
- return this.openFinLink ??= f(n, this.platform.openfinUuid, this.receive, this.diagnostics), this.openFinLink;
386
+ return this.openFinLink ??= y(t, this.platform.openfinUuid, this.receive, this.diagnostics), this.openFinLink;
344
387
  }
345
388
  handshake(e) {
346
389
  return new Promise((t) => {
347
390
  let n = !1, r = (e) => {
348
- n || (n = !0, this.awaitingWelcome = null, clearTimeout(a), t(e));
391
+ n || (n = !0, this.awaitingWelcome = null, clearTimeout(i), t(e));
349
392
  };
350
393
  this.awaitingWelcome = {
351
394
  link: e.kind,
352
395
  settle: r
353
396
  };
354
- let a = setTimeout(() => {
397
+ let i = setTimeout(() => {
355
398
  r(!1);
356
399
  }, this.handshakeOptions.timeoutMs);
357
- i(a), e.post({
400
+ a(i), e.post({
358
401
  t: "hello",
359
402
  from: this.contextId,
360
403
  tabId: this.tabId
@@ -366,13 +409,73 @@ var h = {
366
409
  t: "tab",
367
410
  from: this.contextId,
368
411
  tabId: this.tabId
369
- }), this.post({
412
+ }), this.postJourney({
370
413
  t: "journey?",
371
414
  from: this.contextId
372
- });
415
+ }), this.pollRules();
416
+ }
417
+ journeyScope() {
418
+ let { scope: e } = this.config.journey;
419
+ if (e !== "auto") return e;
420
+ let { platform: t } = this.platform;
421
+ return t === "openfin" || t === "openfin_web" ? "origin" : "tab";
422
+ }
423
+ journeyLink(e) {
424
+ let t = this.journeyScope();
425
+ return t === "context" ? !1 : t === "origin" || e !== "broadcast";
426
+ }
427
+ acceptsJourney(e, t) {
428
+ return !this.journeyLink(t.link) || e.to !== void 0 && e.to !== this.contextId ? !1 : this.journeyScope() === "origin" || this.fromOwner(e.from, t.link);
429
+ }
430
+ fromOwner(e, t) {
431
+ return this.role !== "forwarder" || t !== this.upstream?.kind ? !1 : this.ownerId === null || e === this.ownerId;
432
+ }
433
+ applyJourney(e) {
434
+ if (e === null) {
435
+ this.handlers.onJourney(null);
436
+ return;
437
+ }
438
+ let t = o(e);
439
+ 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);
440
+ }
441
+ rulesAnswer(e) {
442
+ let t = this.handlers.remote.sampling?.wire() ?? null;
443
+ return {
444
+ t: "sampling",
445
+ from: this.contextId,
446
+ to: e,
447
+ rules: t
448
+ };
449
+ }
450
+ acceptsRules(e, t) {
451
+ if (this.role !== "forwarder" || e !== this.contextId || t.link !== this.upstream?.kind) return !1;
452
+ let { origin: n } = t;
453
+ 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.`, {
454
+ origin: n,
455
+ type: "sampling"
456
+ }), !1) : !0;
457
+ }
458
+ applyRules(e) {
459
+ if (e === null) {
460
+ c(this.handlers.remote, this.config, null);
461
+ return;
462
+ }
463
+ let t = s(e, this.diagnostics);
464
+ t && c(this.handlers.remote, this.config, t);
465
+ }
466
+ pollRules() {
467
+ let { upstream: e } = this;
468
+ if (this.destroyed || this.role !== "forwarder" || !e) return;
469
+ let t = () => {
470
+ this.config.sampling.remote && e.post({
471
+ t: "sampling?",
472
+ from: this.contextId
473
+ });
474
+ };
475
+ t(), this.rulesPoll = setInterval(t, n), a(this.rulesPoll);
373
476
  }
374
477
  };
375
478
  //#endregion
376
- export { _ as Bus };
479
+ export { w as Bus };
377
480
 
378
- //# sourceMappingURL=bus-DfAbg_pg.js.map
481
+ //# sourceMappingURL=bus-D8kH58tb.js.map