@utk09/ui-observability 0.9.0 → 0.9.1

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 (118) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +56 -36
  3. package/dist/batch-DEK4bv9N.js +31 -0
  4. package/dist/batch-DEK4bv9N.js.map +1 -0
  5. package/dist/batch-DEVFs28i.cjs +2 -0
  6. package/dist/batch-DEVFs28i.cjs.map +1 -0
  7. package/dist/{bus-CtJWf9QN.cjs → bus-DNFvTkif.cjs} +2 -2
  8. package/dist/{bus-CtJWf9QN.cjs.map → bus-DNFvTkif.cjs.map} +1 -1
  9. package/dist/{bus-D8kH58tb.js → bus-HVQ8E72V.js} +8 -8
  10. package/dist/{bus-D8kH58tb.js.map → bus-HVQ8E72V.js.map} +1 -1
  11. package/dist/{console-DjLbryED.js → console-C9Y639mn.js} +3 -3
  12. package/dist/{console-DjLbryED.js.map → console-C9Y639mn.js.map} +1 -1
  13. package/dist/{console-BpHfWstv.cjs → console-DssDxq1B.cjs} +2 -2
  14. package/dist/{console-BpHfWstv.cjs.map → console-DssDxq1B.cjs.map} +1 -1
  15. package/dist/constants-N99w84xy.js +117 -0
  16. package/dist/constants-N99w84xy.js.map +1 -0
  17. package/dist/constants-X86IDwkC.cjs +2 -0
  18. package/dist/constants-X86IDwkC.cjs.map +1 -0
  19. package/dist/constants.d.ts +18 -11
  20. package/dist/core/drops.d.ts +29 -0
  21. package/dist/core/hold-buffer.d.ts +27 -0
  22. package/dist/core/pipeline.d.ts +2 -7
  23. package/dist/core/runtime.d.ts +44 -8
  24. package/dist/core/sender.d.ts +4 -1
  25. package/dist/deadline-5_PecIl5.js +26 -0
  26. package/dist/deadline-5_PecIl5.js.map +1 -0
  27. package/dist/deadline-XSnm95pg.cjs +2 -0
  28. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  29. package/dist/{errors-CpGRhhIf.cjs → errors-BTWuVnHZ.cjs} +2 -2
  30. package/dist/{errors-CpGRhhIf.cjs.map → errors-BTWuVnHZ.cjs.map} +1 -1
  31. package/dist/{errors-DH4QJS0u.js → errors-CQusIGWJ.js} +4 -4
  32. package/dist/{errors-DH4QJS0u.js.map → errors-CQusIGWJ.js.map} +1 -1
  33. package/dist/{deadline-Cbg2cbUw.cjs → identity-B1GDS1Tb.cjs} +2 -2
  34. package/dist/identity-B1GDS1Tb.cjs.map +1 -0
  35. package/dist/{deadline-B5DINjD5.js → identity-D4DPjTM9.js} +3 -26
  36. package/dist/identity-D4DPjTM9.js.map +1 -0
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.js +467 -318
  41. package/dist/index.js.map +1 -1
  42. package/dist/{indexeddb-storage-n1qkFBGA.js → indexeddb-storage-B8SGUzSV.js} +79 -50
  43. package/dist/indexeddb-storage-B8SGUzSV.js.map +1 -0
  44. package/dist/indexeddb-storage-ukzC82dm.cjs +2 -0
  45. package/dist/indexeddb-storage-ukzC82dm.cjs.map +1 -0
  46. package/dist/{interactions-31eHGwEQ.cjs → interactions-CcxrVzpg.cjs} +2 -2
  47. package/dist/{interactions-31eHGwEQ.cjs.map → interactions-CcxrVzpg.cjs.map} +1 -1
  48. package/dist/{interactions-OU94MPXs.js → interactions-CnjfQgw3.js} +2 -2
  49. package/dist/{interactions-OU94MPXs.js.map → interactions-CnjfQgw3.js.map} +1 -1
  50. package/dist/{journey-CeJ1QoT2.js → journey-DjvDzHyp.js} +17 -16
  51. package/dist/{journey-CeJ1QoT2.js.map → journey-DjvDzHyp.js.map} +1 -1
  52. package/dist/journey-DxlfdFJV.cjs +2 -0
  53. package/dist/journey-DxlfdFJV.cjs.map +1 -0
  54. package/dist/{library-request-C9uJFlbq.cjs → library-request-BZ1ekVtl.cjs} +2 -2
  55. package/dist/{library-request-C9uJFlbq.cjs.map → library-request-BZ1ekVtl.cjs.map} +1 -1
  56. package/dist/{library-request-DvhuplAB.js → library-request-C8kc5YWv.js} +2 -2
  57. package/dist/{library-request-DvhuplAB.js.map → library-request-C8kc5YWv.js.map} +1 -1
  58. package/dist/{long-frames-B8VdA_ny.cjs → long-frames-BGik_Yhy.cjs} +2 -2
  59. package/dist/{long-frames-B8VdA_ny.cjs.map → long-frames-BGik_Yhy.cjs.map} +1 -1
  60. package/dist/{long-frames-C_7OutLs.js → long-frames-CZk3XOkH.js} +3 -3
  61. package/dist/{long-frames-C_7OutLs.js.map → long-frames-CZk3XOkH.js.map} +1 -1
  62. package/dist/models/batch.d.ts +14 -0
  63. package/dist/models/config.d.ts +146 -0
  64. package/dist/models/drop.d.ts +39 -0
  65. package/dist/models/storage.d.ts +15 -3
  66. package/dist/{network-D_lloS5t.js → network-51iicpLl.js} +19 -19
  67. package/dist/{network-D_lloS5t.js.map → network-51iicpLl.js.map} +1 -1
  68. package/dist/{network-BAV7ipyn.cjs → network-jBbjyAJP.cjs} +2 -2
  69. package/dist/{network-BAV7ipyn.cjs.map → network-jBbjyAJP.cjs.map} +1 -1
  70. package/dist/{platform-IHBZGqUe.js → platform-Cjts-8k8.js} +2 -2
  71. package/dist/{platform-IHBZGqUe.js.map → platform-Cjts-8k8.js.map} +1 -1
  72. package/dist/{platform-D4wu1eIF.cjs → platform-DW3GFIUE.cjs} +2 -2
  73. package/dist/{platform-D4wu1eIF.cjs.map → platform-DW3GFIUE.cjs.map} +1 -1
  74. package/dist/{remote-rules-kuDf5gbe.cjs → remote-rules-ByS34k4e.cjs} +2 -2
  75. package/dist/{remote-rules-kuDf5gbe.cjs.map → remote-rules-ByS34k4e.cjs.map} +1 -1
  76. package/dist/{remote-rules-Bt1XsdEQ.js → remote-rules-M-XZ1xbe.js} +2 -2
  77. package/dist/{remote-rules-Bt1XsdEQ.js.map → remote-rules-M-XZ1xbe.js.map} +1 -1
  78. package/dist/{sampling-o0VY1mqQ.js → sampling-BN3Oi6SV.js} +9 -9
  79. package/dist/{sampling-o0VY1mqQ.js.map → sampling-BN3Oi6SV.js.map} +1 -1
  80. package/dist/{sampling-BI15ds9D.cjs → sampling-b2ck5X98.cjs} +2 -2
  81. package/dist/{sampling-BI15ds9D.cjs.map → sampling-b2ck5X98.cjs.map} +1 -1
  82. package/dist/{sanitize-DSIP7amZ.cjs → sanitize-DKp5MRsa.cjs} +2 -2
  83. package/dist/{sanitize-DSIP7amZ.cjs.map → sanitize-DKp5MRsa.cjs.map} +1 -1
  84. package/dist/{sanitize-B9UheVKc.js → sanitize-Dwj9JCkI.js} +2 -2
  85. package/dist/{sanitize-B9UheVKc.js.map → sanitize-Dwj9JCkI.js.map} +1 -1
  86. package/dist/{sender-BnNj9bOX.js → sender-BBY0IcUo.js} +328 -269
  87. package/dist/sender-BBY0IcUo.js.map +1 -0
  88. package/dist/sender-BXoAZKum.cjs +3 -0
  89. package/dist/sender-BXoAZKum.cjs.map +1 -0
  90. package/dist/storage/emergency-queue.d.ts +4 -1
  91. package/dist/storage/eviction.d.ts +40 -0
  92. package/dist/storage/idb-driver.d.ts +6 -0
  93. package/dist/storage/indexeddb-storage.d.ts +13 -5
  94. package/dist/storage/local-storage.d.ts +24 -1
  95. package/dist/storage/memory-storage.d.ts +7 -0
  96. package/dist/{storm-Y-yuBhvv.cjs → storm-CKuaBp7i.cjs} +2 -2
  97. package/dist/{storm-Y-yuBhvv.cjs.map → storm-CKuaBp7i.cjs.map} +1 -1
  98. package/dist/{storm-BTw0J6eE.js → storm-DhtL2eVr.js} +2 -2
  99. package/dist/{storm-BTw0J6eE.js.map → storm-DhtL2eVr.js.map} +1 -1
  100. package/dist/transport/exit-flush.d.ts +6 -0
  101. package/dist/transport/retry-engine.d.ts +7 -3
  102. package/dist/transport/status-transport.d.ts +4 -1
  103. package/dist/utils/console.d.ts +4 -1
  104. package/package.json +1 -1
  105. package/dist/constants-Br3b89Wg.cjs +0 -2
  106. package/dist/constants-Br3b89Wg.cjs.map +0 -1
  107. package/dist/constants-DM94FjVX.js +0 -96
  108. package/dist/constants-DM94FjVX.js.map +0 -1
  109. package/dist/deadline-B5DINjD5.js.map +0 -1
  110. package/dist/deadline-Cbg2cbUw.cjs.map +0 -1
  111. package/dist/indexeddb-storage-DNdf1fmL.cjs +0 -2
  112. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +0 -1
  113. package/dist/indexeddb-storage-n1qkFBGA.js.map +0 -1
  114. package/dist/journey-CE2EcwHW.cjs +0 -2
  115. package/dist/journey-CE2EcwHW.cjs.map +0 -1
  116. package/dist/sender-BnNj9bOX.js.map +0 -1
  117. package/dist/sender-D0OsyB1c.cjs +0 -3
  118. package/dist/sender-D0OsyB1c.cjs.map +0 -1
@@ -1 +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();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AQ,IAAI,EACnD,MACF,CAEA,IAAM4E,EAASjF,EAAAA,EAAiB4C,EAAK,KAAK,WAAW,EAEjDqC,GACF5E,EAAA,EAAY,KAAK,SAAS,OAAQ,KAAK,OAAQ4E,CAAM,CAEzD,CAMA,WAA0B,CACxB,GAAM,CAAE,YAAa,KAErB,GAAI,KAAK,WAAa,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
+ {"version":3,"file":"bus-DNFvTkif.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,GAAI,OAAOC,GAAS,WAAYA,EAC9B,OAAO,KAIT,IAAMC,EAAUD,EAChB,GAAIC,EAAQ,IAAA,sBAAsB,OAAOA,EAAQ,GAAM,UAAYA,EAAQ,IAAM,KAC/E,OAAO,KAGT,IAAMH,EAAUG,EAAQ,EAKxB,OAJI,OAAOH,EAAQ,GAAM,SAIlBA,EAHE,IAIX,CCtCA,IAAMI,EAAc,OAAO,IAAIf,EAAAA,EAAkB,EAG3CgB,EAAgB,OActB,SAASC,EAAc,EAAgB,EAAsB,CAK3D,OAJIC,IAAWF,EACN,mBAAmBG,EAAK,+KAG1B,mBAAmBA,EAAK,QAAQD,EAAO,wDAChD,CAMA,SAASE,GAA8B,CACrC,IAAMC,EAAa,SAAmC,gBACtD,GAAIA,GAAaA,EAAU,OAAS,EAClC,OAAOA,EAAU,KAAK,CAAC,EAKzB,IAAMC,EAAW,SAAS,SAC1B,GAAIA,IAAa,GACf,OAAO,KAGT,GAAI,CACF,OAAO,IAAI,IAAIA,CAAQ,CAAC,CAAC,MAC3B,MAAQ,CACN,OAAO,IACT,CACF,CAQA,SAAgBC,EAAiB,EAAkB,EAAuC,CACxF,GAAI,OAAO,OAAW,KAAe,OAAO,SAAW,OACrD,OAAO,KAGT,IAAIC,EACJ,GAAI,CAEF,EADqB,OAAO,OACRT,EACtB,MAAQ,CAEN,OAAO,IACT,CACA,GAAI,OAAOS,GAAM,WAAc,WAC7B,OAAO,KAGT,IAAMC,EAASD,EACXE,EAAO,GAEX,MAAO,CACL,KAAM,SACN,KAAK,EAAS,CACP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IAAQ,KAAM,CAChBvC,EAAA,EAAY,KAAK,SAAS,OAAQ,KAAK,OAAQ,IAAI,EACnD,MACF,CAEA,IAAM4E,EAASjF,EAAAA,EAAiB4C,EAAK,KAAK,WAAW,EAEjDqC,GACF5E,EAAA,EAAY,KAAK,SAAS,OAAQ,KAAK,OAAQ4E,CAAM,CAEzD,CAMA,WAA0B,CACxB,GAAM,CAAE,YAAa,KAErB,GAAI,KAAK,WAAa,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,11 +1,11 @@
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";
1
+ import { C as e, S as t, T as n, kt as r, qt as i } from "./constants-N99w84xy.js";
2
+ import { r as a } from "./deadline-5_PecIl5.js";
3
+ import { r as o } from "./journey-DjvDzHyp.js";
4
+ import { n as s, t as c } from "./remote-rules-M-XZ1xbe.js";
5
5
  //#region src/models/bus.ts
6
6
  function l(e) {
7
7
  return {
8
- p: i,
8
+ p: n,
9
9
  m: e
10
10
  };
11
11
  }
@@ -18,7 +18,7 @@ function u(e) {
18
18
  }
19
19
  //#endregion
20
20
  //#region src/bus/links.ts
21
- var d = Symbol.for(r), f = "null";
21
+ var d = Symbol.for(i), f = "null";
22
22
  function p(e, t) {
23
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
24
  }
@@ -472,10 +472,10 @@ var S = {
472
472
  from: this.contextId
473
473
  });
474
474
  };
475
- t(), this.rulesPoll = setInterval(t, n), a(this.rulesPoll);
475
+ t(), this.rulesPoll = setInterval(t, r), a(this.rulesPoll);
476
476
  }
477
477
  };
478
478
  //#endregion
479
479
  export { w as Bus };
480
480
 
481
- //# sourceMappingURL=bus-D8kH58tb.js.map
481
+ //# sourceMappingURL=bus-HVQ8E72V.js.map