@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":"journey-CeJ1QoT2.js","names":["BASE64_PADDING_PATTERN","JOURNEY_STORAGE_KEY","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64URL_UNDERSCORE_PATTERN","BASE64URL_DASH_PATTERN","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","OPENFIN_OPTIONS_TIMEOUT_MS","BASE64_SLASH_PATTERN","BROWSER_STORES","withDeadline","unrefTimer","newId","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;AAsCA,IAAac,IAAkC;CAC7C,UAAUT;CACV,iBAAA;CACA,UAAUC;AACZ;AAkCA,SAASS,EAAW,GAAgB,GAAiC;CACnE,IAAMC,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAYA,MAAU,KAAKA,IAAQ,KAAA;AAC7D;AAQA,SAASG,EAAW,GAAgB,GAAiC;CACnE,IAAMH,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAY,OAAO,SAASA,CAAK,IAAIA,IAAQ,KAAA;AACvE;AAQA,SAAgBI,EAAa,GAAgC;CAC3D,IAAI,OAAOJ,KAAU,aAAYA,GAC/B,OAAO;CAET,IAAMK,IAAKN,EAAWC,GAAO,IAAI,GAC3BM,IAAOP,EAAWC,GAAO,MAAM,GAC/BO,IAAYJ,EAAWH,GAAO,WAAW;CAI/C,OAHIK,MAAO,KAAA,KAAaC,MAAS,KAAA,KAAaC,MAAc,KAAA,IACnD,OAEF;EACL;EACA;EACA;EACA,UAAUR,EAAWC,GAAO,UAAU;EAC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CACpE,EAAA,EACuB,aAAaN;EACpC,OAAO,OAAOwC,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
1
+ {"version":3,"file":"journey-DjvDzHyp.js","names":["BASE64_PADDING_PATTERN","JOURNEY_MAX_AGE_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64URL_UNDERSCORE_PATTERN","BASE64URL_DASH_PATTERN","JOURNEY_STORAGE_KEY","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","OPENFIN_OPTIONS_TIMEOUT_MS","BASE64_SLASH_PATTERN","newId","BROWSER_STORES","withDeadline","unrefTimer","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;;AAsCA,IAAac,IAAkC;CAC7C,UAAUb;CACV,iBAAA;CACA,UAAUK;AACZ;AAkCA,SAASS,EAAW,GAAgB,GAAiC;CACnE,IAAMC,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAYA,MAAU,KAAKA,IAAQ,KAAA;AAC7D;AAQA,SAASG,EAAW,GAAgB,GAAiC;CACnE,IAAMH,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAY,OAAO,SAASA,CAAK,IAAIA,IAAQ,KAAA;AACvE;AAQA,SAAgBI,EAAa,GAAgC;CAC3D,IAAI,OAAOJ,KAAU,aAAYA,GAC/B,OAAO;CAET,IAAMK,IAAKN,EAAWC,GAAO,IAAI,GAC3BM,IAAOP,EAAWC,GAAO,MAAM,GAC/BO,IAAYJ,EAAWH,GAAO,WAAW;CAI/C,OAHIK,MAAO,KAAA,KAAaC,MAAS,KAAA,KAAaC,MAAc,KAAA,IACnD,OAEF;EACL;EACA;EACA;EACA,UAAUR,EAAWC,GAAO,UAAU;EACtC,gBAAgBD,EAAWC,GAAO,gBAAgB,KAAK;CACzD;AACF;AAOA,SAASQ,EAAwB,GAAgC;CAC/D,IAAI,OAAOR,KAAU,aAAYA,GAC/B,OAAO;CAET,IAAMK,IAAKN,EAAWC,GAAO,GAAG,GAC1BM,IAAOP,EAAWC,GAAO,GAAG;CAIlC,OAHIK,MAAO,KAAA,KAAaC,MAAS,KAAA,IACxB,OAEF;EACL;EACA;EACA,WAAWH,EAAWH,GAAO,GAAG,KAAK,KAAK,IAAI;EAC9C,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K,cAAc,MACnB,KAAK,YAAY;EACnB,GAAGwB,CAAS;EAEZ,AADA,KAAK,cAAcC,GACnBvC,EAAWuC,CAAK;CAClB;CAGA,cAA4B;EAC1B,KAAK,YAAY,MACf,uBACA,4DACM;GACJ,KAAK,OAAO,QAAQ,CAAC,CAAC,WAAW/C,CAAmB;EACtD,CACF;CACF;CAGA,aAA2B;EACzB,AAAI,KAAK,gBAAgB,SACvB,aAAa,KAAK,WAAW,GAC7B,KAAK,cAAc;CAEvB;CAMA,eAAsC;EAWpC,OAVc,KAAK,YAAY,MAC7B,kBACA,oEAEM,OAAO,WAAa,MACf,OAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,KAAS;CAClB;CAMA,iBAA+B;EAC7B,KAAK,YAAY,MACf,wBACA,sEACM;GACJ,IAAMgD,IAAM,IAAI,IAAI,SAAS,IAAI;GAGjC,AAFAA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,GAE7C,QAAQ,aAAa,QAAQ,OAAO,IAAIA,EAAI,IAAI;EAClD,CACF;CACF;CAQA,MAAc,mBAA2C;EACvD,IAAMC,IAAM,WAA6B,KAAK,IACxCC,IAAaD,GAAI;EACvB,IAAIC,MAAe,KAAA,GACjB,OAAO;EAUT,IAAMb,KAAQ,MALQ,KAAK,YAAY,WACrC,uBACA,yDACM9B,EAAa2C,EAAW,KAAKD,CAAE,GAAG9C,CAA0B,CACpE,EAAA,EACuB,aAAaN;EACpC,OAAO,OAAOwC,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-X86IDwkC.cjs"),t=require("./identity-B1GDS1Tb.cjs"),n=require("./deadline-XSnm95pg.cjs");var r={maxAgeMs:e.at,endOnOwnerClose:!1,urlParam:e.st};function i(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function a(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function o(e){if(typeof e!=`object`||!e)return null;let t=i(e,`id`),n=i(e,`name`),r=a(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:i(e,`parentId`),ownerContextId:i(e,`ownerContextId`)??``}}function s(e){if(typeof e!=`object`||!e)return null;let t=i(e,`i`),n=i(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:a(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function c(t){let n=JSON.stringify({i:t.id,n:t.name.slice(0,64),s:t.startedAt}),r=new TextEncoder().encode(n),i=``;for(let e of r)i+=String.fromCharCode(e);return btoa(i).replace(e.v,`-`).replace(e.y,`_`).replace(e._,``)}var l=class{options;diagnostics;contextId;onLocalChange;stores;journey=null;expiryTimer=null;constructor(e,n,r,i,a=t.t){this.options=e,this.diagnostics=n,this.contextId=r,this.onLocalChange=i,this.stores=a}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`)){this.removeUrlToken();return}let n=this.diagnostics.guard(`storage.unavailable`,`The library could not read the persisted journey.`,()=>this.stores.session().getItem(e.ot));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,n={}){let r={id:n.id??t.i(this.diagnostics),name:e,startedAt:Date.now(),parentId:n.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(r),this.onLocalChange(r),r}end(){this.journey!==null&&(this.setJourney(null),this.onLocalChange(null))}applyRemote(e){let t=this.journey;(e===null||t===null||e.id!==t.id)&&this.setJourney(e)}getToken(){let e=this.journey;if(e===null)return;let t=c(e);if(t.length>256)this.diagnostics.report(`journey.token_too_large`,`The journey token is larger than the size limit. The library does not issue it.`,{length:t.length});else return t}adopt(e,t,n=!1){let r=this.decodeToken(e);return r===null?!1:Date.now()-r.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a seeded journey older than maxAgeMs.`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`The library adopted the journey "${r.name}".`,{source:t,journeyId:r.id}),n&&this.onLocalChange(r),!0)}ownerClosed(e){this.options.endOnOwnerClose&&this.journey?.ownerContextId===e&&this.end()}destroy(){this.clearTimer()}restore(e){let t=o(this.diagnostics.guard(`storage.degraded`,`The library could not parse the persisted journey.`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`The library discarded a persisted journey older than maxAgeMs.`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`The library resumed the journey "${t.name}".`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`The library could not decode a seeded journey token.`,()=>{let n=t.replace(e.h,`+`).replace(e.g,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return s(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`The library could not save the journey.`,()=>{t===null?this.stores.session().removeItem(e.ot):this.stores.session().setItem(e.ot,JSON.stringify(t))}),t===null)return;let r=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),i=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`The journey "${t.name}" reached maxAgeMs. The library ended it.`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},r);this.expiryTimer=i,n.r(i)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`The library could not clear the persisted journey.`,()=>{this.stores.session().removeItem(e.ot)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`The library could not read the journey token from the URL.`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}removeUrlToken(){this.diagnostics.guard(`platform.api_blocked`,`The library could not remove the journey token from the URL.`,()=>{let e=new URL(location.href);e.searchParams.delete(this.options.urlParam),history.replaceState(history.state,``,e.href)})}async readOpenFinToken(){let t=globalThis.fin?.me,r=t?.getOptions;if(r===void 0)return null;let i=(await this.diagnostics.guardAsync(`openfin.unavailable`,`The library could not read fin.me.getOptions().`,()=>n.n(r.call(t),e.xt)))?.customData?.[e.bt];return typeof i==`string`?i:null}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
+ //# sourceMappingURL=journey-DxlfdFJV.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journey-DxlfdFJV.cjs","names":["JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","require_constants","require_identity","require_deadline","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":"sHAsCA,IAAagB,EAAkC,CAC7C,SAAUhB,EAAAA,GACV,gBAAA,GACA,SAAUC,EAAAA,EACZ,EAkCA,SAASgB,EAAW,EAAgB,EAAiC,CACnE,IAAMC,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAYA,IAAU,GAAKA,EAAQ,IAAA,EAC7D,CAQA,SAASG,EAAW,EAAgB,EAAiC,CACnE,IAAMH,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE,CAQA,SAAgBI,EAAa,EAAgC,CAC3D,GAAI,OAAOJ,GAAU,WAAYA,EAC/B,OAAO,KAET,IAAMK,EAAKN,EAAWC,EAAO,IAAI,EAC3BM,EAAOP,EAAWC,EAAO,MAAM,EAC/BO,EAAYJ,EAAWH,EAAO,WAAW,EAI/C,OAHIK,IAAO,IAAA,IAAaC,IAAS,IAAA,IA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IAAMb,GAAQ,MALQ,KAAK,YAAY,WACrC,sBACA,sDACMlC,EAAAA,EAAa+C,EAAW,KAAKD,CAAE,EAAG7C,EAAAA,EAA0B,CACpE,EAAA,EACuB,aAAaC,EAAAA,IACpC,OAAO,OAAOgC,GAAU,SAAWA,EAAQ,IAC7C,CACF"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-Br3b89Wg.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.dt);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
- //# sourceMappingURL=library-request-C9uJFlbq.cjs.map
1
+ const e=require("./constants-X86IDwkC.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.ft);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
+ //# sourceMappingURL=library-request-BZ1ekVtl.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-C9uJFlbq.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","require_constants","scope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":"4CAUA,IAAMG,uCAAQH,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAQ7C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB"}
1
+ {"version":3,"file":"library-request-BZ1ekVtl.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","require_constants","scope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":"4CAUA,IAAMG,uCAAQH,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAQ7C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB"}
@@ -1,4 +1,4 @@
1
- import { dt as e } from "./constants-DM94FjVX.js";
1
+ import { ft as e } from "./constants-N99w84xy.js";
2
2
  import { t } from "./global-scope-dp2jADRl.js";
3
3
  //#region src/utils/library-request.ts
4
4
  var n = t(e);
@@ -11,4 +11,4 @@ function i() {
11
11
  //#endregion
12
12
  export { r as n, i as t };
13
13
 
14
- //# sourceMappingURL=library-request-DvhuplAB.js.map
14
+ //# sourceMappingURL=library-request-C8kc5YWv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-DvhuplAB.js","names":["LIBRARY_REQUEST_KEY","scope","globalScope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":";;;AAUA,IAAMC,IAAQC,EAAYF,CAAmB;AAQ7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB"}
1
+ {"version":3,"file":"library-request-C8kc5YWv.js","names":["LIBRARY_REQUEST_KEY","scope","globalScope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":";;;AAUA,IAAMC,IAAQC,EAAYF,CAAmB;AAQ7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB"}
@@ -1,2 +1,2 @@
1
- const e=require("./platform-D4wu1eIF.cjs"),t=require("./storm-Y-yuBhvv.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.r(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
2
- //# sourceMappingURL=long-frames-B8VdA_ny.cjs.map
1
+ const e=require("./platform-DW3GFIUE.cjs"),t=require("./storm-CKuaBp7i.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.r(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
2
+ //# sourceMappingURL=long-frames-BGik_Yhy.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"long-frames-B8VdA_ny.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5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AK,IAAI,OAAO,QAAQ,SAAWJ,EAAQjB,EAAAA,EAAciB,CAAK,EAEhE,GAAIX,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
1
+ {"version":3,"file":"long-frames-BGik_Yhy.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAM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MJ,EAAM,QAAQ,EACpCK,EAAiC,CAAE,aAAcL,EAAM,SAAU,EAEnEA,EAAM,mBAAqB,IAAA,KAC7B,EAAM,qBAAuB,KAAK,MAAMA,EAAM,gBAAgB,GAGhE,IAAMT,EAASF,EAAcW,EAAM,OAAO,EAGpCM,EAAO,GACX,KAAK,IAAI,OAAO,QAAQ,SAAWJ,EAAQjB,EAAAA,EAAciB,CAAK,EAEhE,GAAIX,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
@@ -1,5 +1,5 @@
1
- import { r as e } from "./platform-IHBZGqUe.js";
2
- import { t } from "./storm-BTw0J6eE.js";
1
+ import { r as e } from "./platform-Cjts-8k8.js";
2
+ import { t } from "./storm-DhtL2eVr.js";
3
3
  //#region src/capture/long-frames.ts
4
4
  var n = ["long-animation-frame", "longtask"];
5
5
  function r(e) {
@@ -62,4 +62,4 @@ var i = class {
62
62
  //#endregion
63
63
  export { i as LongFrameCapture };
64
64
 
65
- //# sourceMappingURL=long-frames-C_7OutLs.js.map
65
+ //# sourceMappingURL=long-frames-CZk3XOkH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"long-frames-C_7OutLs.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY,KAAK,cAAc,GACpC,KAAK,WAAW,IAAI,qBAAqB,MAAS;GAChD,KAA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3XOkH.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI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K;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,cAAc,OAAOc,CAAQ,EAAE;EAC1C,CAAC,GACD,KAAK,IAAI,OAAO,UAAU,0BAA0BA,GAAU,MAAM,aAAaC,CAAK;CACxF;AACF"}
@@ -32,3 +32,17 @@ export declare function isLogBatch(value: unknown): value is LogBatch;
32
32
  * @returns Two batches, or `null` if a single record is already over the limit.
33
33
  */
34
34
  export declare function splitBatch(batch: LogBatch, diagnostics: Diagnostics): [LogBatch, LogBatch] | null;
35
+ /**
36
+ * Reads one attribute of a record. A record from storage can be corrupt. It can be null or have
37
+ * no attributes.
38
+ * @param record Record to read.
39
+ * @param key Attribute key.
40
+ * @returns The attribute value, or undefined for a corrupt record.
41
+ */
42
+ export declare function attributeOf(record: LogRecord, key: string): unknown;
43
+ /**
44
+ * Tests if a record is an action. A corrupt record from storage is not an action.
45
+ * @param record Record to test.
46
+ * @returns True for an action record.
47
+ */
48
+ export declare function isActionRecord(record: LogRecord): boolean;
@@ -1,4 +1,5 @@
1
1
  import type { DiagnosticHandler } from "../core/diagnostics";
2
+ import type { DropSummary } from "./drop";
2
3
  import type { LogLevel, LogRecord } from "./log-record";
3
4
  import type { LogSerializer } from "./serializer";
4
5
  /** Backing store for undelivered records. "auto" picks the best one the host supports. */
@@ -177,6 +178,110 @@ export interface JourneyOptions {
177
178
  * @default "auto"
178
179
  */
179
180
  scope: JourneyScope;
181
+ /**
182
+ * Maximum open time of a journey, in milliseconds. Then the library ends it. The range is
183
+ * 1 minute to 24 hours. You cannot change this value after startup.
184
+ * @default 1800000
185
+ */
186
+ maxAgeMs: number;
187
+ }
188
+ /** Batch size and flush interval of each record stream. You cannot change them after startup. */
189
+ export interface BatchingOptions {
190
+ /**
191
+ * Maximum wait of a partial log batch, in milliseconds. The range is 100 to 60000.
192
+ * @default 2000
193
+ */
194
+ logFlushIntervalMs: number;
195
+ /**
196
+ * Maximum records in one log batch. The range is 1 to 1000.
197
+ * @default 100
198
+ */
199
+ logBatchSize: number;
200
+ /**
201
+ * Maximum wait of a partial metric batch, in milliseconds. The range is 100 to 60000.
202
+ * @default 10000
203
+ */
204
+ metricFlushIntervalMs: number;
205
+ /**
206
+ * Maximum records in one metric batch. The range is 1 to 1000.
207
+ * @default 500
208
+ */
209
+ metricBatchSize: number;
210
+ }
211
+ /**
212
+ * How long the library keeps an undelivered batch.
213
+ * - "limited": the batch stays until `maxAgeMs` or `maxAttempts`.
214
+ * - "until-delivered": the batch has no age limit and no attempt limit. `maxBatches` still
215
+ * applies. A permanent error still drops the batch.
216
+ */
217
+ export type RetentionMode = "limited" | "until-delivered";
218
+ /** Retention of undelivered batches. You cannot change it after startup. */
219
+ export interface RetentionOptions {
220
+ /**
221
+ * Retention rule.
222
+ * @default "limited"
223
+ */
224
+ mode: RetentionMode;
225
+ /**
226
+ * Maximum stored batches. A new batch evicts the oldest batch without an action first. The
227
+ * range is 1 to 5000.
228
+ * @default 500
229
+ */
230
+ maxBatches: number;
231
+ /**
232
+ * Maximum age of a stored batch, in milliseconds. The range is 1 minute to 7 days.
233
+ * @default 86400000
234
+ */
235
+ maxAgeMs: number;
236
+ /**
237
+ * Maximum send attempts of a stored batch. The range is 1 to 20.
238
+ * @default 5
239
+ */
240
+ maxAttempts: number;
241
+ }
242
+ /** Size limits for each record. You cannot change them after startup. */
243
+ export interface LimitOptions {
244
+ /**
245
+ * Maximum body length, in characters. The range is 256 to 65536.
246
+ * @default 4096
247
+ */
248
+ maxBodyChars: number;
249
+ /**
250
+ * Maximum length of a string attribute, in characters. The range is 256 to 65536.
251
+ * @default 8192
252
+ */
253
+ maxAttributeChars: number;
254
+ /**
255
+ * Maximum keys in one object. The range is 1 to 1024.
256
+ * @default 128
257
+ */
258
+ maxAttributeCount: number;
259
+ /**
260
+ * Maximum length of an error stack, in characters. The range is 256 to 65536.
261
+ * @default 8192
262
+ */
263
+ maxStackChars: number;
264
+ /**
265
+ * Maximum depth of a nested value. The range is 1 to 16.
266
+ * @default 6
267
+ */
268
+ maxDepth: number;
269
+ /**
270
+ * Maximum items in one array, set or map. The range is 1 to 10000.
271
+ * @default 100
272
+ */
273
+ maxArrayLength: number;
274
+ /**
275
+ * Maximum values in one sanitize pass. The range is 100 to 100000.
276
+ * @default 10000
277
+ */
278
+ maxNodes: number;
279
+ /**
280
+ * Maximum attribute bytes of one record. Above it, the library drops the caller attributes.
281
+ * The range is 1024 to 60000.
282
+ * @default 32768
283
+ */
284
+ maxRecordBytes: number;
180
285
  }
181
286
  /** Console method that the console capture can wrap. */
182
287
  export type CapturedConsoleMethod = "error" | "warn" | "info" | "log";
@@ -422,6 +527,21 @@ export interface ObservabilityConfig {
422
527
  * @see {@link JourneyOptions}
423
528
  */
424
529
  journey?: Partial<JourneyOptions>;
530
+ /**
531
+ * Batch size and flush interval of each record stream.
532
+ * @see {@link BatchingOptions}
533
+ */
534
+ batching?: Partial<BatchingOptions>;
535
+ /**
536
+ * Retention of undelivered batches.
537
+ * @see {@link RetentionOptions}
538
+ */
539
+ retention?: Partial<RetentionOptions>;
540
+ /**
541
+ * Size limits for each record.
542
+ * @see {@link LimitOptions}
543
+ */
544
+ limits?: Partial<LimitOptions>;
425
545
  /**
426
546
  * Automatic instrumentation.
427
547
  * @see {@link CaptureOptions}
@@ -462,6 +582,15 @@ export interface ObservabilityConfig {
462
582
  * @see {@link DiagnosticHandler}
463
583
  */
464
584
  onDiagnostic?: DiagnosticHandler;
585
+ /**
586
+ * Receives a summary when the library loses records that it built. Sampling, `minLevel` and
587
+ * `redact` do not cause a loss. The library joins the losses of one reason in one task.
588
+ * Do not log through the library in the hook. A record from the hook can evict a stored batch.
589
+ * A batch that storage evicts during its send can still reach the server.
590
+ * @param summary Reason, record count, batch ids, journey ids and action names of the loss.
591
+ * @see {@link DropSummary}
592
+ */
593
+ onDrop?: (summary: DropSummary) => void;
465
594
  }
466
595
  /** Fully resolved configuration that the runtime holds. */
467
596
  export interface ResolvedConfig {
@@ -500,6 +629,21 @@ export interface ResolvedConfig {
500
629
  * @see {@link JourneyOptions}
501
630
  */
502
631
  journey: JourneyOptions;
632
+ /**
633
+ * Batch size and flush interval of each record stream.
634
+ * @see {@link BatchingOptions}
635
+ */
636
+ batching: BatchingOptions;
637
+ /**
638
+ * Retention of undelivered batches.
639
+ * @see {@link RetentionOptions}
640
+ */
641
+ retention: RetentionOptions;
642
+ /**
643
+ * Size limits for each record.
644
+ * @see {@link LimitOptions}
645
+ */
646
+ limits: LimitOptions;
503
647
  /**
504
648
  * Automatic instrumentation.
505
649
  * @see {@link CaptureOptions}
@@ -528,4 +672,6 @@ export interface ResolvedConfig {
528
672
  * @see {@link DiagnosticHandler}
529
673
  */
530
674
  onDiagnostic?: DiagnosticHandler;
675
+ /** Receives a summary when the library loses records that it built. */
676
+ onDrop?: ObservabilityConfig["onDrop"];
531
677
  }
@@ -0,0 +1,39 @@
1
+ import type { LogRecord } from "./log-record";
2
+ /**
3
+ * Cause of a loss.
4
+ * - "buffer_full": a hold buffer before startup or before the sender loads is full.
5
+ * - "expired", "over_capacity", "quota": storage removed stored batches. The reasons are
6
+ * `retention.maxAgeMs`, `retention.maxBatches` and the storage quota of the browser.
7
+ * - "max_attempts": a stored batch reached `retention.maxAttempts`.
8
+ * - "rejected": the server refused the batch permanently, or one record is too large for it.
9
+ * - "unserializable": the serializer threw on the batch.
10
+ * - "exit_queue_full": the exit queue in localStorage is full. It drops its oldest batch.
11
+ * - "load_failed": the delivery code did not load, or shutdown() came first. The held records are
12
+ * lost.
13
+ * - "not_stored": storage did not keep a batch after a failed send. The cause is a write error or
14
+ * `storage: "none"`.
15
+ */
16
+ export type LossReason = "buffer_full" | "expired" | "over_capacity" | "quota" | "max_attempts" | "rejected" | "unserializable" | "exit_queue_full" | "load_failed" | "not_stored";
17
+ /**
18
+ * One report of lost records. The library joins the losses of one reason in one task.
19
+ * Each list holds at most 20 different values.
20
+ */
21
+ export interface DropSummary {
22
+ /** Cause of the loss. */
23
+ reason: LossReason;
24
+ /** Number of lost records. */
25
+ records: number;
26
+ /** Ids of the lost batches. A hold buffer loses records, not batches. Its list is empty. */
27
+ batchIds: string[];
28
+ /** Journey ids of the lost records. */
29
+ journeyIds: string[];
30
+ /** Names of the lost action records. An action is an audit fact. */
31
+ actions: string[];
32
+ }
33
+ /**
34
+ * Receives lost records. The runtime adds them to the onDrop report.
35
+ * @param reason Cause of the loss.
36
+ * @param records Lost records.
37
+ * @param batchIds Ids of the lost batches.
38
+ */
39
+ export type LossReporter = (reason: LossReason, records: readonly LogRecord[], batchIds?: readonly string[]) => void;