@utk09/ui-observability 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -23
- package/README.md +83 -86
- package/dist/bus/links.d.ts +5 -4
- package/dist/constants-BpFlszME.cjs +2 -0
- package/dist/constants-BpFlszME.cjs.map +1 -0
- package/dist/constants-CrU3IUyy.js +74 -0
- package/dist/constants-CrU3IUyy.js.map +1 -0
- package/dist/constants.d.ts +13 -1
- package/dist/core/logger.d.ts +7 -5
- package/dist/core/record.d.ts +11 -2
- package/dist/core/runtime.d.ts +10 -0
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +599 -501
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-bibcl7ZS.js → indexeddb-storage-CSaDuHGk.js} +19 -15
- package/dist/indexeddb-storage-CSaDuHGk.js.map +1 -0
- package/dist/indexeddb-storage-DIJIbFnp.cjs +2 -0
- package/dist/indexeddb-storage-DIJIbFnp.cjs.map +1 -0
- package/dist/storage/local-storage.d.ts +14 -0
- package/dist/utils/console.d.ts +4 -1
- package/dist/utils/identity.d.ts +17 -6
- package/dist/utils/sanitize.d.ts +2 -0
- package/package.json +5 -5
- package/dist/constants-BmO0GRWM.cjs +0 -2
- package/dist/constants-BmO0GRWM.cjs.map +0 -1
- package/dist/constants-CQr0wwbQ.js +0 -69
- package/dist/constants-CQr0wwbQ.js.map +0 -1
- package/dist/indexeddb-storage-DeEh8Ag-.cjs +0 -2
- package/dist/indexeddb-storage-DeEh8Ag-.cjs.map +0 -1
- package/dist/indexeddb-storage-bibcl7ZS.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-CrU3IUyy.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// src/constants.ts\n//\n// All limits, thresholds, timing windows, storage keys, patterns, and\n// defaults used by the library.\n\nimport type { ResolvedConfig } from \"./models/config\";\nimport type { LogLevel, LogType } from \"./models/log-record\";\nimport type { StorageLimits } from \"./models/storage\";\n\n// ----------------------------------\n// Library-wide\n// ----------------------------------\n\n/** Prefix on console messages this library writes. */\nexport const LIBRARY_LOG_PREFIX = \"[ui-observability]\";\n\n// ----------------------------------\n// Diagnostics\n// ----------------------------------\n\n/** Throttle window per diagnostic code, in milliseconds. Limits how often an error loop can spam the handler. */\nexport const DIAGNOSTIC_THROTTLE_MS = 1000;\n\n// ----------------------------------\n// Identity\n// ----------------------------------\n\n/** `localStorage` key for the session id and its last-seen time. */\nexport const SESSION_ID_KEY = \"ui-observability.session\";\n\n/** `sessionStorage` key for the tab id. */\nexport const TAB_ID_KEY = \"ui-observability.tab\";\n\n/** Session idle timeout, in milliseconds. */\nexport const SESSION_IDLE_MS = 30 * 60 * 1000;\n\n/** Min gap between session last-seen writes, in milliseconds. */\nexport const SESSION_TOUCH_MS = 60_000;\n\n/** Random id length, in bytes, used when `crypto.randomUUID` is unavailable. */\nexport const ID_BYTE_LENGTH = 16;\n\n/** Distinct values in one byte (256). */\nexport const BYTE_VALUE_COUNT = 256;\n\n// ----------------------------------\n// Platform detection\n// ----------------------------------\n\n/** Matches OpenFin's user agent. */\nexport const OPENFIN_UA_PATTERN = /OpenFin/i;\n\n/** Matches Android's webview token (`wv`). */\nexport const ANDROID_WEBVIEW_UA_PATTERN = /\\bwv\\b/;\n\n/** Matches iOS hardware: iPhone, iPad, iPod. */\nexport const IOS_DEVICE_UA_PATTERN = /\\b(iPhone|iPad|iPod)\\b/;\n\n/** Matches desktop macOS in a user agent. */\nexport const MACINTOSH_UA_PATTERN = /\\bMacintosh\\b/;\n\n/** Matches the mobile token. */\nexport const MOBILE_UA_PATTERN = /\\bMobile\\b/;\n\n/** WebKit engine token, present in every WebKit browser including webviews. */\nexport const WEBKIT_UA_TOKEN = \"AppleWebKit\";\n\n/** Safari token sent by real iOS browsers, not in-app webviews. */\nexport const SAFARI_UA_TOKEN = \"Safari/\";\n\n// ----------------------------------\n// Sanitizing and size estimation\n// ----------------------------------\n\n/** First UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MIN = 0xd800;\n\n/** Last UTF-16 high surrogate code unit. */\nexport const HIGH_SURROGATE_MAX = 0xdbff;\n\n/** Code units below this encode as one UTF-8 byte. */\nexport const UTF8_ONE_BYTE_CEILING = 0x80;\n\n/** Code units below this, and at or above the one-byte ceiling, encode as two UTF-8 bytes. */\nexport const UTF8_TWO_BYTE_CEILING = 0x800;\n\n/** Class names kept in a `describeNode` selector. */\nexport const MAX_NODE_CLASS_NAMES = 3;\n\n/** Byte cost of a null or undefined value. */\nexport const BYTES_PER_NULL = 4;\n\n/** Byte cost of a number (flat estimate). */\nexport const BYTES_PER_NUMBER = 8;\n\n/** Byte cost of a boolean. */\nexport const BYTES_PER_BOOLEAN = 5;\n\n/** Byte cost of an object or array's wrapping braces or brackets. */\nexport const BYTES_PER_CONTAINER = 2;\n\n/** Byte cost of a string's wrapping quotes. */\nexport const BYTES_PER_QUOTED_STRING = 2;\n\n/** Byte cost of one key's punctuation: quotes, colon, comma. */\nexport const BYTES_PER_KEY_OVERHEAD = 4;\n\n// ----------------------------------\n// Record model\n// ----------------------------------\n\n/**\n * Log level to OpenTelemetry severity number.\n * @see {@link LEVEL_ORDER}\n */\nexport const SEVERITY_NUMBER: Record<LogLevel, number> = {\n TRACE: 1,\n DEBUG: 5,\n INFO: 9,\n WARN: 13,\n ERROR: 17,\n FATAL: 21,\n};\n\n/**\n * Alias for `SEVERITY_NUMBER`, used by the level filter.\n * @see {@link SEVERITY_NUMBER}\n */\nexport const LEVEL_ORDER: Record<LogLevel, number> = SEVERITY_NUMBER;\n\n// ----------------------------------\n// Attribute and resource keys\n// ----------------------------------\n//\n// Attribute and resource key names records carry on the wire, following\n// OpenTelemetry conventions. `uiobs.` marks this library's own fields.\n\n/** Record kind attribute key. */\nexport const ATTR_LOG_TYPE = \"log.type\";\n\n/** Record sequence number within its context, from zero. */\nexport const ATTR_LOG_SEQ = \"log.seq\";\n\n/** Logger namespace attribute key. */\nexport const ATTR_APP_NAMESPACE = \"app.namespace\";\n\n/** Document URL when the record was built. */\nexport const ATTR_PAGE_URL = \"page.url\";\n\n/**\n * HTTP request URL attribute key, set by network capture. Don't reuse `ATTR_PAGE_URL`; it would overwrite the request's target.\n * @see {@link ATTR_PAGE_URL}\n */\nexport const ATTR_URL_FULL = \"url.full\";\n\n/** Journey id attribute key. */\nexport const ATTR_JOURNEY_ID = \"journey.id\";\n\n/** Journey name attribute key. */\nexport const ATTR_JOURNEY_NAME = \"journey.name\";\n\n/** Parent journey id, present only on a child journey. */\nexport const ATTR_JOURNEY_PARENT_ID = \"journey.parent_id\";\n\n/** Marks a record whose attributes failed to sanitize. */\nexport const ATTR_SANITIZE_FAILED = \"uiobs.sanitize_failed\";\n\n/**\n * Marks a record whose attributes were dropped for exceeding the byte budget.\n * @see {@link ATTR_ATTRIBUTES_BYTES}\n */\nexport const ATTR_ATTRIBUTES_DROPPED = \"uiobs.attributes_dropped\";\n\n/**\n * Byte size of the dropped attributes.\n * @see {@link ATTR_ATTRIBUTES_DROPPED}\n */\nexport const ATTR_ATTRIBUTES_BYTES = \"uiobs.attributes_bytes\";\n\n/** Application name resource key. */\nexport const RESOURCE_SERVICE_NAME = \"service.name\";\n\n/** Application build version resource key. */\nexport const RESOURCE_SERVICE_VERSION = \"service.version\";\n\n/** Deployment environment resource key. */\nexport const RESOURCE_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\n/**\n * Producer library name resource key.\n * @see {@link TELEMETRY_SDK_NAME}\n */\nexport const RESOURCE_TELEMETRY_SDK_NAME = \"telemetry.sdk.name\";\n\n/**\n * Producer library version resource key.\n * @see {@link TELEMETRY_SDK_VERSION}\n */\nexport const RESOURCE_TELEMETRY_SDK_VERSION = \"telemetry.sdk.version\";\n\n/**\n * Producer SDK language resource key.\n * @see {@link TELEMETRY_SDK_LANGUAGE}\n */\nexport const RESOURCE_TELEMETRY_SDK_LANGUAGE = \"telemetry.sdk.language\";\n\n/** Host platform resource key: browser, webview, or OpenFin. */\nexport const RESOURCE_HOST_PLATFORM = \"host.platform\";\n\n/** Session id resource key. */\nexport const RESOURCE_SESSION_ID = \"session.id\";\n\n/** Tab id resource key. */\nexport const RESOURCE_TAB_ID = \"tab.id\";\n\n/** Context (realm) id resource key. */\nexport const RESOURCE_CONTEXT_ID = \"context.id\";\n\n/** Raw user agent resource key. */\nexport const RESOURCE_BROWSER_USER_AGENT = \"browser.user_agent\";\n\n/** OpenFin application uuid resource key. */\nexport const RESOURCE_OPENFIN_UUID = \"openfin.uuid\";\n\n/** OpenFin window or view name resource key. */\nexport const RESOURCE_OPENFIN_NAME = \"openfin.name\";\n\n/**\n * Value of `telemetry.sdk.name`.\n * @see {@link RESOURCE_TELEMETRY_SDK_NAME}\n */\nexport const TELEMETRY_SDK_NAME = \"@utk09/ui-observability\";\n\n/**\n * Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.\n * @see {@link RESOURCE_TELEMETRY_SDK_VERSION}\n */\nexport const TELEMETRY_SDK_VERSION = \"0.4.0\";\n\n/**\n * Value of `telemetry.sdk.language`.\n * @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}\n */\nexport const TELEMETRY_SDK_LANGUAGE = \"webjs\";\n\n// ----------------------------------\n// Serializers\n// ----------------------------------\n\n/** OTLP/JSON serializer name. */\nexport const SERIALIZER_NAME_OTLP = \"otlp\";\n\n/** ECS serializer name. */\nexport const SERIALIZER_NAME_ECS = \"ecs\";\n\n/**\n * ECS `log.level` names that differ from the lowercased severity text. ECS spells\n * the warning level in full; every other level matches once lowercased.\n * @see {@link SERIALIZER_NAME_ECS}\n */\nexport const ECS_LEVEL_NAMES: Partial<Record<LogLevel, string>> = { WARN: \"warning\" };\n\n/** Content type for an OTLP/JSON body. */\nexport const CONTENT_TYPE_JSON = \"application/json\";\n\n/** Content type for newline-delimited JSON. */\nexport const CONTENT_TYPE_NDJSON = \"application/x-ndjson\";\n\n/** Nanoseconds per millisecond. */\nexport const NANOS_PER_MILLI = 1000000n;\n\n/**\n * Matches a nanosecond epoch written as decimal digits, e.g. \"1755543600123000000\".\n * @see {@link NANOS_PER_MILLI}\n */\nexport const NANOS_PATTERN = /^\\d+$/;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Content-Type header name. */\nexport const HEADER_CONTENT_TYPE = \"Content-Type\";\n\n/** Content-Encoding header name. */\nexport const HEADER_CONTENT_ENCODING = \"Content-Encoding\";\n\n/** Retry-After header name. */\nexport const HEADER_RETRY_AFTER = \"Retry-After\";\n\n/**\n * Batch deduplication key header name.\n * @see {@link QUERY_PARAM_BATCH_ID}\n */\nexport const HEADER_BATCH_ID = \"X-UiObs-Batch-Id\";\n\n/** Delivery attempt number header name. */\nexport const HEADER_ATTEMPT = \"X-UiObs-Attempt\";\n\n/** Gzip encoding name. */\nexport const ENCODING_GZIP = \"gzip\";\n\n/** 401, credentials missing or rejected. */\nexport const HTTP_UNAUTHORIZED = 401;\n\n/** 403, valid credentials but access denied. */\nexport const HTTP_FORBIDDEN = 403;\n\n/** 408, the server closed the connection after a timeout. Retryable. */\nexport const HTTP_REQUEST_TIMEOUT = 408;\n\n/** 413, payload too large; batch must be split. */\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\n/** 429, backpressure. */\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\n/** 500, floor for server-side errors. */\nexport const HTTP_SERVER_ERROR_MIN = 500;\n\n/** 503, temporary unavailability. */\nexport const HTTP_SERVICE_UNAVAILABLE = 503;\n\n/** Milliseconds per second. */\nexport const MILLIS_PER_SECOND = 1000;\n\n// ----------------------------------\n// Exit flush\n// ----------------------------------\n\n/** Max exit payload size, in bytes (`sendBeacon`/`fetch(keepalive)` shared budget). */\nexport const BEACON_LIMIT_BYTES = 60_000;\n\n/** Content type for an exit payload. CORS-safelisted, avoids a preflight. */\nexport const CONTENT_TYPE_TEXT_PLAIN = \"text/plain;charset=UTF-8\";\n\n/**\n * Batch id query param name, for the exit path.\n * @see {@link HEADER_BATCH_ID}\n */\nexport const QUERY_PARAM_BATCH_ID = \"uiobs_batch_id\";\n\n/** Exit reason query param name, for logs only. */\nexport const QUERY_PARAM_EXIT_REASON = \"uiobs_exit\";\n\n// ----------------------------------\n// Storage\n// ----------------------------------\n\n/** localStorage key prefix for a parked batch. */\nexport const BATCH_STORAGE_KEY_PREFIX = \"ui-observability.batch.\";\n\n/** Zero-padded digit width for the creation time in a batch key. */\nexport const BATCH_KEY_TIME_WIDTH = 14;\n\n/** localStorage key prefix for a batch parked by exit flush. */\nexport const EMERGENCY_STORAGE_KEY_PREFIX = \"ui-observability.emergency.\";\n\n/** Max exit batches held at once. */\nexport const EMERGENCY_MAX_ENTRIES = 20;\n\n/** Key used to test whether localStorage accepts writes. */\nexport const STORAGE_PROBE_KEY = \"ui-observability.probe\";\n\n/** Fraction of the store evicted on a quota error (1 in N). */\nexport const QUOTA_EVICTION_DIVISOR = 4;\n\n/** DOMException name for a full store. */\nexport const QUOTA_EXCEEDED_ERROR = \"QuotaExceededError\";\n\n/**\n * Native IndexedDB version. It starts at 11 because Dexie, which this replaced,\n * opened the same database at ten times its own declared version. Anything below\n * 11 makes open() fail with VersionError for an existing installation and every\n * batch already stored there is stranded.\n */\nexport const INDEXEDDB_SCHEMA_VERSION = 11;\n\n/** IndexedDB object store holding batches. Named by Dexie before it was removed. */\nexport const INDEXEDDB_STORE_NAME = \"batches\";\n\n/** Index on the batch store that orders reads by creation time. */\nexport const INDEXEDDB_CREATED_AT_INDEX = \"createdAt\";\n\n/** IndexedDB adapter/strategy name. */\nexport const STORAGE_NAME_INDEXEDDB = \"indexeddb\";\n\n/** localStorage adapter/strategy name. */\nexport const STORAGE_NAME_LOCAL = \"localstorage\";\n\n/** In-memory adapter/strategy name. */\nexport const STORAGE_NAME_MEMORY = \"memory\";\n\n/** No-op adapter/strategy name. */\nexport const STORAGE_NAME_NONE = \"none\";\n\n// ----------------------------------\n// Retry\n// ----------------------------------\n\n/**\n * Origin-wide lock name a drain runs under.\n * @see {@link EMERGENCY_LOCK_NAME}\n */\nexport const DRAIN_LOCK_NAME = \"ui-observability.drain\";\n\n/**\n * Lock name startup recovery runs under.\n * @see {@link DRAIN_LOCK_NAME}\n */\nexport const EMERGENCY_LOCK_NAME = \"ui-observability.emergency\";\n\n/** Batches sent per drain tick. */\nexport const BATCHES_PER_DRAIN = 20;\n\n// ----------------------------------\n// Journey\n// ----------------------------------\n\n/** `sessionStorage` key for the current journey. */\nexport const JOURNEY_STORAGE_KEY = \"ui-observability.journey\";\n\n/**\n * Max journey name length in a token, in characters.\n * @see {@link JOURNEY_TOKEN_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_NAME_MAX_CHARS = 64;\n\n/**\n * Max whole-token length, in characters. A tripwire, not validation.\n * @see {@link JOURNEY_TOKEN_NAME_MAX_CHARS}\n */\nexport const JOURNEY_TOKEN_MAX_CHARS = 256;\n\n/**\n * How long to wait for `fin.me.getOptions()` before giving up on a seeded journey,\n * in milliseconds.\n * @see {@link OPENFIN_JOURNEY_CUSTOM_DATA_KEY}\n */\nexport const OPENFIN_OPTIONS_TIMEOUT_MS = 2000;\n\n/** Key under an OpenFin window's `customData` carrying a seeded journey token. */\nexport const OPENFIN_JOURNEY_CUSTOM_DATA_KEY = \"uiObsJourney\";\n\n/** Matches `+` in standard base64 (`-` in URL-safe). */\nexport const BASE64_PLUS_PATTERN = /\\+/g;\n\n/** Matches `/` in standard base64 (`_` in URL-safe). */\nexport const BASE64_SLASH_PATTERN = /\\//g;\n\n/** Matches trailing `=` padding. */\nexport const BASE64_PADDING_PATTERN = /=+$/;\n\n/** Matches `-` in URL-safe base64 (`+` in standard). */\nexport const BASE64URL_DASH_PATTERN = /-/g;\n\n/** Matches `_` in URL-safe base64 (`/` in standard). */\nexport const BASE64URL_UNDERSCORE_PATTERN = /_/g;\n\n/** Base64 characters per 3-byte group. */\nexport const BASE64_GROUP_CHARS = 4;\n\n// ----------------------------------\n// Tracing\n// ----------------------------------\n\n/** W3C trace id width, in bytes. */\nexport const TRACE_ID_BYTES = 16;\n\n/** W3C span id width, in bytes. */\nexport const SPAN_ID_BYTES = 8;\n\n/** Max ambient trace lifetime with no activity, in milliseconds. */\nexport const TRACE_MAX_AGE_MS = 5 * 60 * 1000;\n\n/** trace-flags value with the sampled bit set. */\nexport const TRACE_FLAGS_SAMPLED = 1;\n\n/** Mask for the one-byte trace-flags field. */\nexport const TRACE_FLAGS_MASK = 0xff;\n\n/**\n * W3C trace context header name\n * @see {@link TRACEPARENT_VERSION}\n */\nexport const TRACEPARENT_HEADER = \"traceparent\";\n\n/** traceparent header version prefix. */\nexport const TRACEPARENT_VERSION = \"00\";\n\n// ----------------------------------\n// Breadcrumbs\n// ----------------------------------\n\n/** Smallest valid breadcrumb buffer capacity. */\nexport const BREADCRUMB_MIN_CAPACITY = 1;\n\n// ----------------------------------\n// Sampling\n// ----------------------------------\n//\n// FNV-1a hash constants, used to turn a sampling key into a stable 0-1\n// fraction.\n\n/** FNV-1a 32-bit offset basis. */\nexport const FNV_OFFSET_BASIS = 0x811c9dc5;\n\n/** FNV-1a 32-bit prime. */\nexport const FNV_PRIME = 0x01000193;\n\n/** Largest 32-bit unsigned value. */\nexport const UINT32_MAX = 0xffffffff;\n\n// ----------------------------------\n// Pipeline\n// ----------------------------------\n\n/** Record kind routed to the metric stream. */\nexport const LOG_TYPE_METRIC: LogType = \"metric\";\n\n// ----------------------------------\n// Bus\n// ----------------------------------\n\n/** Protocol identifier for bus envelopes. Mismatched versions are dropped. */\nexport const BUS_PROTOCOL = \"ui-observability/1\";\n\n/** Global window property key used to locate a same-origin runtime instance. */\nexport const RUNTIME_GLOBAL_KEY = \"ui-observability.runtime\";\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Maximum error records captured per throttling window before suppression. */\nexport const ERROR_STORM_MAX_PER_WINDOW = 20;\n\n/** Error rate-limiting window duration in milliseconds. */\nexport const ERROR_STORM_WINDOW_MS = 10_000;\n\n/**\n * Max ERROR and FATAL records admitted to the pipeline per storm window.\n * A backstop against a render loop, not a shaper: ERROR and FATAL bypass sampling,\n * and a direct logger.error call has no other limit.\n */\nexport const ERROR_CEILING_MAX_PER_WINDOW = 500;\n\n/** Maximum distinct error signatures tracked for deduplication before LRU eviction. */\nexport const MAX_TRACKED_ERROR_SIGNATURES = 200;\n\n/** Maximum character length retained from clicked element text in breadcrumbs. */\nexport const CLICK_TEXT_MAX_CHARS = 50;\n\n/** Maximum character length retained from an aria-label attribute in generated selectors. */\nexport const ARIA_LABEL_MAX_CHARS = 40;\n\n/** Maximum class names included per element in generated CSS selectors. */\nexport const SELECTOR_MAX_CLASSES = 2;\n\n/** CSS styling applied to console prefix labels. */\nexport const CONSOLE_PREFIX_STYLE = \"color:#888\";\n\n/** Scaling factor for rounding duration measurements to three decimal places. */\nexport const DURATION_PRECISION = 1000;\n\n// ----------------------------------\n// Runtime\n// ----------------------------------\n\n/** Minimum duration in milliseconds between storage gap warning reports. */\nexport const GAP_REPORT_THROTTLE_MS = 60_000;\n\n/** Default namespace for telemetry records emitted by auto-capture modules. */\nexport const CAPTURE_NAMESPACE = \"uiobs.capture\";\n\n/** Default namespace for telemetry records emitted by storage subsystems. */\nexport const STORAGE_NAMESPACE = \"uiobs.storage\";\n\n/** Fallback measurement unit applied when none is specified. */\nexport const DEFAULT_METRIC_UNIT = \"count\";\n\n// ----------------------------------\n// Configuration\n// ----------------------------------\n\n/** Default `service.name` when a consumer sets none. */\nexport const UNKNOWN_SERVICE_NAME = \"unknown-service\";\n\n/** Lowest sampling rate (drop everything). */\nexport const SAMPLING_RATE_MIN = 0;\n\n/** Highest sampling rate (keep everything). */\nexport const SAMPLING_RATE_MAX = 1;\n\n/**\n * Fallback for an invalid sampling rate (keep everything).\n * @see {@link SAMPLING_RATE_MAX}\n */\nexport const SAMPLING_RATE_FALLBACK = 1;\n\n/**\n * Config keys with no default, excluded from `DEFAULT_CONFIG`.\n * @see {@link DEFAULT_CONFIG}\n */\nexport const UNDEFAULTED_CONFIG_KEYS = [\n \"redact\",\n \"onDiagnostic\",\n \"headers\",\n \"serializer\",\n \"otelLoader\",\n] as const;\n\n/**\n * Nested config section keys.\n * @see {@link ResolvedConfig}\n */\nexport const CONFIG_SECTIONS = [\"sampling\", \"bus\", \"capture\"] as const;\n\n/**\n * Section keys with no default, excluded from their section of `DEFAULT_CONFIG`.\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const UNDEFAULTED_SECTION_KEYS: Record<(typeof CONFIG_SECTIONS)[number], string[]> = {\n sampling: [],\n bus: [],\n capture: [\"webVitalsLoader\"],\n};\n\n/**\n * Default runtime config, before a consumer's `configure()` call.\n * Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.\n * @see {@link ResolvedConfig}\n * @see {@link UNDEFAULTED_CONFIG_KEYS}\n */\nexport const DEFAULT_CONFIG: Omit<ResolvedConfig, \"serializer\"> = {\n endpoint: \"\",\n serviceName: \"\",\n serviceVersion: \"\",\n environment: \"\",\n enabled: true,\n minLevel: \"INFO\",\n compression: \"gzip\",\n credentials: \"omit\",\n storage: \"auto\",\n sampling: { defaultRate: 1, rates: {}, alwaysSampleTypes: [\"action\"] },\n bus: { mode: \"auto\", trustedOrigins: [], openFinRole: \"auto\" },\n capture: {\n errors: true,\n rejections: true,\n resourceErrors: false,\n fetch: false,\n xhr: false,\n interactions: false,\n navigation: false,\n webVitals: false,\n fullUrls: false,\n ignoreUrls: [],\n propagateTraceHeaderTo: [],\n },\n console: null,\n};\n\n/** Console mirroring level used when a consumer passes `console: true`. */\nexport const CONSOLE_DEFAULT_LEVEL: LogLevel = \"DEBUG\";\n\n// ----------------------------------\n// Batching\n// ----------------------------------\n\n/** Max time a partial log batch waits before it is sent, in milliseconds. */\nexport const LOG_FLUSH_INTERVAL_MS = 2000;\n\n/** Max records per log batch before it is sent early. */\nexport const LOG_BATCH_SIZE = 100;\n\n/** Max time a partial metric batch waits before it is sent, in milliseconds. Metrics batch harder than logs: higher volume, nothing waits on them. */\nexport const METRIC_FLUSH_INTERVAL_MS = 10_000;\n\n/** Max records per metric batch before it is sent early. */\nexport const METRIC_BATCH_SIZE = 500;\n\n/** Max concurrent ingest requests, across both streams. */\nexport const MAX_CONCURRENT_REQUESTS = 2;\n\n// ----------------------------------\n// HTTP transport\n// ----------------------------------\n\n/** Max time one ingest request may take before it is aborted and retried, in milliseconds. */\nexport const REQUEST_TIMEOUT_MS = 15_000;\n\n/** Min payload size to compress, in bytes. */\nexport const COMPRESSION_THRESHOLD_BYTES = 1024;\n\n// ----------------------------------\n// Storage retention\n// ----------------------------------\n\n/** IndexedDB database name. */\nexport const STORAGE_DB_NAME = \"UiObservability\";\n\n/** Capacity and retention thresholds every storage adapter enforces. */\nexport const STORAGE_LIMITS: StorageLimits = {\n maxBatches: 500,\n maxAgeMs: 24 * 60 * 60 * 1000,\n maxAttempts: 5,\n};\n\n// ----------------------------------\n// Retry backoff\n// ----------------------------------\n\n/** First backoff step, in milliseconds. Each attempt doubles it. */\nexport const RETRY_BASE_DELAY_MS = 2000;\n\n/** Backoff ceiling, in milliseconds. */\nexport const RETRY_MAX_DELAY_MS = 60_000;\n\n/** How often to check for stored work when nothing has failed recently, in milliseconds. */\nexport const RETRY_IDLE_DELAY_MS = 30_000;\n\n// ----------------------------------\n// Journey lifetime\n// ----------------------------------\n\n/** Max time a journey stays open before it is treated as abandoned, in milliseconds. */\nexport const JOURNEY_MAX_AGE_MS = 30 * 60 * 1000;\n\n/** Whether closing the owning context ends the journey for everyone. */\nexport const JOURNEY_END_ON_OWNER_CLOSE = false;\n\n/** Query parameter checked at boot for a seeded journey token. */\nexport const JOURNEY_URL_PARAM = \"__uiobs_journey\";\n\n// ----------------------------------\n// Bus handshake\n// ----------------------------------\n\n/** BroadcastChannel name for the control plane. */\nexport const BUS_CHANNEL_NAME = \"ui_observability_control\";\n\n/** Max time a forwarder waits for an owner to answer before it promotes itself, in milliseconds. */\nexport const BUS_HANDSHAKE_TIMEOUT_MS = 1500;\n\n/** Handshake attempts allowed before a cross-origin forwarder promotes itself to sender. */\nexport const BUS_MAX_HANDSHAKE_ATTEMPTS = 3;\n\n/** Max records a context buffers before its bus role is determined. */\nexport const BUS_MAX_BOOT_BUFFER_RECORDS = 500;\n\n// ----------------------------------\n// Capture\n// ----------------------------------\n\n/** Breadcrumbs kept as context for the next error. */\nexport const MAX_BREADCRUMBS = 50;\n\n/** Window within which identical errors are counted but not re-sent, in milliseconds. */\nexport const ERROR_DEDUPE_MS = 5000;\n\n// ----------------------------------\n// Per-record size caps\n// ----------------------------------\n\n/** Size caps applied to every record, enforced after sanitize and after redact. */\nexport const RECORD_LIMITS = {\n maxBodyChars: 4096,\n maxAttributeChars: 8192,\n maxAttributeCount: 128,\n maxStackChars: 8192,\n maxDepth: 6,\n maxArrayLength: 100,\n maxNodes: 10_000,\n maxRecordBytes: 32_768,\n};\n"],"mappings":";AAcA,IAAa,KAAqB,sBAOrB,KAAyB,KAOzB,IAAiB,4BAGjB,IAAa,wBAGb,IAAkB,MAGlB,IAAmB,KAanB,IAAqB,YAGrB,IAA6B,UAG7B,IAAwB,0BAGxB,IAAuB,iBAGvB,IAAoB,cAGpB,IAAkB,eAGlB,IAAkB,WAOlB,IAAqB,OAGrB,IAAqB,OAMrB,IAAwB,MA+BxB,IAA4C;CACvD,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT,GAMa,IAAwC,GAUxC,IAAgB,YAGhB,IAAe,WAGf,IAAqB,iBAGrB,IAAgB,YAMhB,IAAgB,YAGhB,IAAkB,cAGlB,IAAoB,gBAGpB,IAAyB,qBAGzB,IAAuB,yBAMvB,IAA0B,4BAM1B,IAAwB,0BAGxB,IAAwB,gBAGxB,IAA2B,mBAG3B,IAAkC,0BAMlC,IAA8B,sBAM9B,IAAiC,yBAMjC,IAAkC,0BAGlC,IAAyB,iBAGzB,IAAsB,cAGtB,IAAkB,UAGlB,IAAsB,cAGtB,IAA8B,sBAG9B,IAAwB,gBAGxB,IAAwB,gBAMxB,IAAqB,2BAMrB,IAAwB,SAMxB,IAAyB,SAOzB,IAAuB,QAUvB,IAAqD,EAAE,MAAM,UAAU,GAGvE,IAAoB,oBAGpB,IAAsB,wBAGtB,IAAkB,UAMlB,IAAgB,SAOhB,IAAsB,gBAGtB,IAA0B,oBAG1B,IAAqB,eAMrB,IAAkB,oBAGlB,KAAiB,mBAGjB,KAAgB,QAwBhB,KAAoB,KAOpB,KAAqB,KAGrB,KAA0B,4BAM1B,IAAuB,kBAGvB,KAA0B,cAO1B,KAA2B,2BAM3B,KAA+B,+BAM/B,KAAoB,0BAMpB,KAAuB,sBAWvB,KAAuB,WAGvB,KAA6B,aAG7B,KAAyB,aAGzB,KAAqB,gBAGrB,KAAsB,UAGtB,KAAoB,QAUpB,KAAkB,0BAMlB,KAAsB,8BAUtB,KAAsB,4BAmBtB,KAA6B,KAG7B,KAAkC,gBAGlC,KAAsB,OAGtB,KAAuB,OAGvB,KAAyB,OAGzB,KAAyB,MAGzB,KAA+B,MAgB/B,KAAmB,KAYnB,KAAqB,eAoBrB,KAAmB,YAGnB,KAAY,UAGZ,KAAa,YAOb,KAA2B,UAO3B,KAAe,sBAGf,KAAqB,4BAUrB,KAAwB,KAsBxB,KAAuB,cAGvB,KAAqB,KAOrB,KAAyB,KAGzB,KAAoB,iBAGpB,KAAoB,iBAGpB,KAAsB,SAOtB,KAAuB,mBAkBvB,KAA0B;CACrC;CACA;CACA;CACA;CACA;AACF,GAMa,KAAkB;CAAC;CAAY;CAAO;AAAS,GAM/C,KAA+E;CAC1F,UAAU,CAAC;CACX,KAAK,CAAC;CACN,SAAS,CAAC,iBAAiB;AAC7B,GAQa,KAAqD;CAChE,UAAU;CACV,aAAa;CACb,gBAAgB;CAChB,aAAa;CACb,SAAS;CACT,UAAU;CACV,aAAa;CACb,aAAa;CACb,SAAS;CACT,UAAU;EAAE,aAAa;EAAG,OAAO,CAAC;EAAG,mBAAmB,CAAC,QAAQ;CAAE;CACrE,KAAK;EAAE,MAAM;EAAQ,gBAAgB,CAAC;EAAG,aAAa;CAAO;CAC7D,SAAS;EACP,QAAQ;EACR,YAAY;EACZ,gBAAgB;EAChB,OAAO;EACP,KAAK;EACL,cAAc;EACd,YAAY;EACZ,WAAW;EACX,UAAU;EACV,YAAY,CAAC;EACb,wBAAwB,CAAC;CAC3B;CACA,SAAS;AACX,GAGa,KAAkC,SAOlC,KAAwB,KAMxB,KAA2B,KAa3B,KAAqB,MAGrB,KAA8B,MAO9B,KAAkB,mBAGlB,KAAgC;CAC3C,YAAY;CACZ,UAAU;CACV,aAAa;AACf,GAOa,KAAsB,KAGtB,KAAqB,KAGrB,KAAsB,KAOtB,KAAqB,MAMrB,KAAoB,mBAOpB,KAAmB,4BAGnB,KAA2B,MAgB3B,KAAkB,KAOlB,KAAgB;CAC3B,cAAc;CACd,mBAAmB;CACnB,mBAAmB;CACnB,eAAe;CACf,UAAU;CACV,gBAAgB;CAChB,UAAU;CACV,gBAAgB;AAClB"}
|
package/dist/constants.d.ts
CHANGED
|
@@ -138,7 +138,7 @@ export declare const TELEMETRY_SDK_NAME = "@utk09/ui-observability";
|
|
|
138
138
|
* Value of `telemetry.sdk.version`. A literal, not read from package.json. Bump by hand alongside package.json.
|
|
139
139
|
* @see {@link RESOURCE_TELEMETRY_SDK_VERSION}
|
|
140
140
|
*/
|
|
141
|
-
export declare const TELEMETRY_SDK_VERSION = "0.
|
|
141
|
+
export declare const TELEMETRY_SDK_VERSION = "0.4.0";
|
|
142
142
|
/**
|
|
143
143
|
* Value of `telemetry.sdk.language`.
|
|
144
144
|
* @see {@link RESOURCE_TELEMETRY_SDK_LANGUAGE}
|
|
@@ -148,6 +148,12 @@ export declare const TELEMETRY_SDK_LANGUAGE = "webjs";
|
|
|
148
148
|
export declare const SERIALIZER_NAME_OTLP = "otlp";
|
|
149
149
|
/** ECS serializer name. */
|
|
150
150
|
export declare const SERIALIZER_NAME_ECS = "ecs";
|
|
151
|
+
/**
|
|
152
|
+
* ECS `log.level` names that differ from the lowercased severity text. ECS spells
|
|
153
|
+
* the warning level in full; every other level matches once lowercased.
|
|
154
|
+
* @see {@link SERIALIZER_NAME_ECS}
|
|
155
|
+
*/
|
|
156
|
+
export declare const ECS_LEVEL_NAMES: Partial<Record<LogLevel, string>>;
|
|
151
157
|
/** Content type for an OTLP/JSON body. */
|
|
152
158
|
export declare const CONTENT_TYPE_JSON = "application/json";
|
|
153
159
|
/** Content type for newline-delimited JSON. */
|
|
@@ -360,6 +366,11 @@ export declare const UNDEFAULTED_CONFIG_KEYS: readonly ["redact", "onDiagnostic"
|
|
|
360
366
|
* @see {@link ResolvedConfig}
|
|
361
367
|
*/
|
|
362
368
|
export declare const CONFIG_SECTIONS: readonly ["sampling", "bus", "capture"];
|
|
369
|
+
/**
|
|
370
|
+
* Section keys with no default, excluded from their section of `DEFAULT_CONFIG`.
|
|
371
|
+
* @see {@link UNDEFAULTED_CONFIG_KEYS}
|
|
372
|
+
*/
|
|
373
|
+
export declare const UNDEFAULTED_SECTION_KEYS: Record<(typeof CONFIG_SECTIONS)[number], string[]>;
|
|
363
374
|
/**
|
|
364
375
|
* Default runtime config, before a consumer's `configure()` call.
|
|
365
376
|
* Excludes `serializer`; `resolveConfig` supplies its default to avoid a circular import.
|
|
@@ -419,5 +430,6 @@ export declare const RECORD_LIMITS: {
|
|
|
419
430
|
maxStackChars: number;
|
|
420
431
|
maxDepth: number;
|
|
421
432
|
maxArrayLength: number;
|
|
433
|
+
maxNodes: number;
|
|
422
434
|
maxRecordBytes: number;
|
|
423
435
|
};
|
package/dist/core/logger.d.ts
CHANGED
|
@@ -48,16 +48,18 @@ export declare class OneLogger {
|
|
|
48
48
|
*/
|
|
49
49
|
warn: (message: string, payload?: Record<string, unknown>) => void;
|
|
50
50
|
/**
|
|
51
|
-
* Logs an error record with attached breadcrumb history.
|
|
51
|
+
* Logs an error record with attached breadcrumb history. A plain object in the
|
|
52
|
+
* error slot with no payload given is read as the payload.
|
|
52
53
|
* @param message Error description.
|
|
53
|
-
* @param error Caught error instance or
|
|
54
|
+
* @param error Caught error instance, reason, or payload.
|
|
54
55
|
* @param payload Optional contextual attributes.
|
|
55
56
|
*/
|
|
56
57
|
error: (message: string, error?: unknown, payload?: Record<string, unknown>) => void;
|
|
57
58
|
/**
|
|
58
|
-
* Logs a fatal unrecoverable error record.
|
|
59
|
+
* Logs a fatal unrecoverable error record. A plain object in the error slot
|
|
60
|
+
* with no payload given is read as the payload.
|
|
59
61
|
* @param message Error description.
|
|
60
|
-
* @param error Caught error instance or
|
|
62
|
+
* @param error Caught error instance, reason, or payload.
|
|
61
63
|
* @param payload Optional contextual attributes.
|
|
62
64
|
*/
|
|
63
65
|
fatal: (message: string, error?: unknown, payload?: Record<string, unknown>) => void;
|
|
@@ -110,7 +112,7 @@ export declare class OneLogger {
|
|
|
110
112
|
* Builds, logs to console, and emits an error record with attached breadcrumbs.
|
|
111
113
|
* @param level Severity level ("ERROR" or "FATAL").
|
|
112
114
|
* @param message Error description.
|
|
113
|
-
* @param error Caught error instance or
|
|
115
|
+
* @param error Caught error instance, reason, or payload.
|
|
114
116
|
* @param payload Optional contextual attributes.
|
|
115
117
|
*/
|
|
116
118
|
private writeError;
|
package/dist/core/record.d.ts
CHANGED
|
@@ -36,6 +36,15 @@ export interface RecordLimits extends SanitizeLimits {
|
|
|
36
36
|
/** Max total attribute bytes per record. */
|
|
37
37
|
maxRecordBytes: number;
|
|
38
38
|
}
|
|
39
|
+
/** Reason a record was not built. */
|
|
40
|
+
export type DropReason = "level" | "sampling" | "redact";
|
|
41
|
+
/** Outcome of one build call. */
|
|
42
|
+
export interface BuildResult {
|
|
43
|
+
/** Completed record, or null when it was dropped. */
|
|
44
|
+
record: LogRecord | null;
|
|
45
|
+
/** Why it was dropped. Absent when a record was built. */
|
|
46
|
+
dropped?: DropReason;
|
|
47
|
+
}
|
|
39
48
|
/** Input parameters for constructing a single log record. */
|
|
40
49
|
export interface BuildInput {
|
|
41
50
|
/** Severity level of the log entry. */
|
|
@@ -71,9 +80,9 @@ export declare class RecordBuilder {
|
|
|
71
80
|
/**
|
|
72
81
|
* Builds a structured LogRecord from input attributes, applying sanitization and size budgeting.
|
|
73
82
|
* @param input Logger call input parameters.
|
|
74
|
-
* @returns
|
|
83
|
+
* @returns The record, or null with the reason it was dropped.
|
|
75
84
|
*/
|
|
76
|
-
build(input: BuildInput):
|
|
85
|
+
build(input: BuildInput): BuildResult;
|
|
77
86
|
/**
|
|
78
87
|
* Computes or returns cached resource metadata for this runtime context.
|
|
79
88
|
* @returns Resource attributes record.
|
package/dist/core/runtime.d.ts
CHANGED
|
@@ -23,6 +23,8 @@ export declare class ObservabilityRuntime {
|
|
|
23
23
|
readonly platform: PlatformMetadata;
|
|
24
24
|
/** Identity context containing session, tab, and context identifiers. */
|
|
25
25
|
readonly identity: Identity;
|
|
26
|
+
/** Throttled writer of the session's last-seen timestamp. */
|
|
27
|
+
private readonly sessionTouch;
|
|
26
28
|
/** Store for ambient application context attributes. */
|
|
27
29
|
readonly context: ContextStore;
|
|
28
30
|
/** Ring buffer holding contextual user breadcrumbs. */
|
|
@@ -41,6 +43,8 @@ export declare class ObservabilityRuntime {
|
|
|
41
43
|
readonly bus: Bus;
|
|
42
44
|
/** Persistent storage adapter for offline batches (sender role only). */
|
|
43
45
|
private storage?;
|
|
46
|
+
/** Storage strategy the adapter was built from, set once the build starts. */
|
|
47
|
+
private storageBuiltAs?;
|
|
44
48
|
/** HTTP transport instance for live log delivery (sender role only). */
|
|
45
49
|
private transport?;
|
|
46
50
|
/** Background retry engine for redelivering failed batches (sender role only). */
|
|
@@ -89,6 +93,12 @@ export declare class ObservabilityRuntime {
|
|
|
89
93
|
* @param input Partial configuration to merge.
|
|
90
94
|
*/
|
|
91
95
|
private reconfigure;
|
|
96
|
+
/**
|
|
97
|
+
* Restores the storage strategy the adapter was built from. Every other key is read
|
|
98
|
+
* live, but the adapter is built once: swapping it strands the batches already
|
|
99
|
+
* persisted under the old one, which is worse than refusing the change.
|
|
100
|
+
*/
|
|
101
|
+
private keepBuiltStorage;
|
|
92
102
|
/** Initializes asynchronous subsystems and flushes the boot buffer. */
|
|
93
103
|
private init;
|
|
94
104
|
/** Initializes storage, transport, pipeline, and unload listeners for sender role. */
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-BmO0GRWM.cjs");function t(t){return Math.round((performance.now()-t)*e.F)/e.F}function n(e,n,r,i,a){e.logMetric(`${n}.duration`,t(r),`ms`,`histogram`,{status:i,...a})}function r(e,n,r,i,a){e.error(`${n} failed`,i,{"action.duration_ms":t(r),status:`FAILURE`,...a})}function i(e,t,i,a){let o=performance.now();try{let r=i();return n(e,t,o,`SUCCESS`,a),r}catch(n){throw r(e,t,o,n,a),n}}async function a(e,t,i,a){let o=performance.now();try{let r=await i();return n(e,t,o,`SUCCESS`,a),r}catch(n){throw r(e,t,o,n,a),n}}function o(e){return e instanceof Error?e:Error(String(e))}var s=class t{runtime;namespace;options;constructor(e,t,n={}){this.runtime=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.runtime,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>i(this,e,t,n);timeAsync=(e,t,n)=>a(this,e,t,n);write(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=this.runtime.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});i&&t!==`metric`&&this.runtime.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.runtime.console.write(e,n,i?.attributes),this.runtime.emit(i)}writeError(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=n===void 0?void 0:o(n),a=this.runtime.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...r,...i?{"error.type":i.name,"error.message":i.message,"error.stack_trace":i.stack}:{},breadcrumbs:this.runtime.breadcrumbs.snapshot()}});this.runtime.console.write(e,t,i??a?.attributes),this.runtime.emit(a)}};function c(e){typeof e!=`number`&&e.unref?.()}function l(t){return{p:e.S,m:t}}function u(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var d=Symbol.for(e.Lt);function f(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[d]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`direct call into the parent runtime`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function p(e,t){if(typeof window>`u`||window.parent===window)return null;let n=t=>{let n=u(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,n),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`postMessage to parent`,()=>{window.parent.postMessage(l(e),`*`)})},close(){removeEventListener(`message`,n)}}}function m(e,t,n){if(typeof window>`u`)return null;let r=new Set([window.location.origin,...t]),i=new Map,a=t=>{let a=u(t.data);if(a){if(!r.has(t.origin)){n.report(`bus.untrusted_origin`,`ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`,{origin:t.origin,type:a.t});return}t.source&&i.set(t.source,t.origin),e(a,{link:`children`,origin:t.origin})}};return addEventListener(`message`,a),{kind:`children`,post(e){for(let[t,r]of i){let a=t;if(a.closed){i.delete(t);continue}n.guard(`bus.send_failed`,`postMessage to child`,()=>{a.postMessage(l(e),r)})}},close(){removeEventListener(`message`,a),i.clear()}}}function h(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let i=n.guard(`bus.send_failed`,`opening BroadcastChannel`,()=>new r(e));return i?(i.onmessage=e=>{let n=u(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`BroadcastChannel.postMessage`,()=>{i.postMessage(l(e))})},close(){n.guard(`bus.send_failed`,`closing BroadcastChannel`,()=>{i.close()})}}):null}function g(e,t,n){let r=globalThis.fin?.InterApplicationBus;return r?(n.guardAsync(`bus.send_failed`,`InterApplicationBus.subscribe`,()=>r.subscribe({uuid:`*`},e,e=>{let n=u(e);n&&t(n,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(t){n.guardAsync(`bus.send_failed`,`InterApplicationBus.publish`,()=>r.publish(e,l(t)))},close(){}}):null}function _(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=u(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`worker postMessage`,()=>{r(l(e))})},close(){}})}function ee(e,t,n){let r=e=>{let n=u(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`postMessage to a worker`,()=>{e.postMessage(l(t))})},close(){e.removeEventListener(`message`,r)}}}var te={timeoutMs:e.x,maxAttempts:3},ne=[`children`,`direct`,`worker`],re=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=te){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a,this.handshakeOptions=o}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;if(this.isOpenFinProvider=this.resolveOpenFinProvider(),e.mode===`sender`||e.mode===`forwarder`)return this.role=e.mode,this.openControlLinks(),this.role===`forwarder`&&(this.upstream=this.candidateUpstream(),this.upstream||this.diagnostics.report(`bus.no_owner`,`bus.mode is "forwarder" but there is no owner to forward to. Records will be dropped.`)),this.resolved=!0,this.announce(),this.role;this.openControlLinks();let t=f(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`attached directly to the same-origin parent runtime`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`no owner to forward to, sending directly`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.handshakeOptions.maxAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`no owner answered after ${String(r)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)}ms, promoting to sender`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`role is ${this.role}`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`){this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);return}if(e.t===`journey?`){let e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n);return}this.receive(e,n)}attachWorker(e){this.links.push(ee(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&this.awaitingWelcome.settle(!0);break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&t.link!==this.upstream.kind&&this.upstream.post(e);break;case`journey`:this.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});break}case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:ne.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){return this.isCrossOriginFrame()?`retry`:`promote`}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return window.parent.location,!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?_(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:p(this.receive,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(m(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(h(e.b,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=g(e.b,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,this.awaitingWelcome=null,clearTimeout(i),t(e))};this.awaitingWelcome={link:e.kind,settle:r};let i=setTimeout(()=>{r(!1)},this.handshakeOptions.timeoutMs);c(i),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId})}},v=null;function y(e,t){let n=e[t];return n!==void 0&&e instanceof n}function ie(t){if(v)return v;let n=globalThis,r=n.navigator?.userAgent??``,i=`browser`,a,o,s=!1,c=n.fin?.me;return y(n,`ServiceWorkerGlobalScope`)?(i=`service_worker`,s=!0):y(n,`SharedWorkerGlobalScope`)?(i=`shared_worker`,s=!0):y(n,`WorkerGlobalScope`)?(i=`web_worker`,s=!0):c===void 0?n.Capacitor!==void 0||n.Ionic!==void 0?i=`ionic`:n.cordova!==void 0||ae(r)?i=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(i=`node`):(i=e.ht.test(r)?`openfin`:`openfin_web`,t.guard(`openfin.unavailable`,`reading fin.me.identity`,()=>{let e=c.identity;a=e?.uuid,o=e?.name})),v={platform:i,openfinUuid:a,openfinName:o,userAgent:r,isWorker:s,isTopLevelDocument:oe()},v}function ae(t){return e.t.test(t)?!0:(e.$.test(t)||e.st.test(t)&&e.ut.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function oe(){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return!1}}function se(){try{return typeof location<`u`?location.href:``}catch{return``}}function b(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}var ce=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let t=e.target,n=t?.src??t?.href??``;if(t!==null&&t!==globalThis&&n!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?n:b(n);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":t.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let r=e,i=r.message===``?`unknown error`:r.message,a=r.error??Error(i);this.report(`window.onerror`,a,{"error.source":r.filename,"error.line":r.lineno,"error.column":r.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`more than 20 errors in ${String(e.B)}ms, suppressing the rest of this window`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
|
|
2
|
-
`)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};function le(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function x(){return history}var ue=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(x().pushState=this.originalPushState),this.originalReplaceState&&(x().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let t=e.target,n=le(t instanceof Element?t:null),r=t instanceof HTMLElement?t.innerText.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:n,data:r===``?void 0:{text:r}})};onNavigate=()=>{let e=this.lastUrl,t=location.href;if(e===t)return;this.lastUrl=t;let n=this.ctx.config.capture.fullUrls,r=n?e:b(e),i=n?t:b(t);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${r} -> ${i}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":r})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=x(),t=e.pushState,n=e.replaceState;this.originalPushState=t,this.originalReplaceState=n;let r=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(r)},e.replaceState=function(...e){n.apply(this,e),queueMicrotask(r)}}};function S(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function C(){return XMLHttpRequest.prototype}var de=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(C().open=this.originalOpen,null),this.originalSend&&=(C().send=this.originalSend,null)}ignored(e){return S(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let t=this.ctx,n=e=>this.ignored(e),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.href:i.url,s=(a?.method??(i instanceof Request?i.method:`GET`)).toUpperCase();if(n(o))return e(i,a);let c=i,l=a;if(S(o,t.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(t.tracing.headers());if(i instanceof Request){let t=new Headers(i.headers);for(let[n,r]of e)t.set(n,r);c=new Request(i,{headers:t})}else{let t=new Headers(a?.headers);for(let[n,r]of e)t.set(n,r);l={...a,headers:t}}}catch(e){c=i,l=a,t.diagnostics.report(`capture.header_failed`,`could not attach traceparent, sending the request unchanged`,{url:o},e)}let u=performance.now();try{let t=await e(c,l);return r(s,o,t.status,performance.now()-u,void 0),t}catch(e){throw r(s,o,0,performance.now()-u,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},n=C(),r=n.open,i=n.send;this.originalOpen=r,this.originalSend=i,n.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},r.apply(this,[e,t,...n])},n.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),i.apply(this,n)}}record(e,t,n,r,i){let a=this.ctx.config.capture.fullUrls?t:b(t);this.ctx.diagnostics.guard(`capture.record_failed`,`recording ${e} ${a}`,()=>{let t=Math.round(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${a} ${n===0?`failed`:String(n)}`,data:{durationMs:t}});let o={"http.request.method":e,"url.full":a,"http.response.status_code":n,"http.duration_ms":t};if(n===0){this.ctx.logger.error(`${e} ${a} failed`,i,o);return}if(n>=400){this.ctx.logger.warn(`${e} ${a} returned ${String(n)}`,o);return}this.ctx.logger.debug(`${e} ${a}`,o)})}};function fe(){return import(`web-vitals`)}var pe=class{ctx;name=`web-vitals`;installed=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.reportNavigationTiming(),this.loadWebVitals())}uninstall(){this.installed=!1}async loadWebVitals(){let e=this.ctx.config.capture.webVitalsLoader??fe,t=await this.ctx.diagnostics.guardAsync(`capture.install_failed`,`loading web-vitals`,e);if(!t){this.ctx.diagnostics.report(`capture.install_failed`,`web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.`);return}let n=(e,t)=>n=>{this.ctx.logger.logMetric(`web_vitals.${e}`,Math.round(n.value*1e3)/1e3,t,`gauge`,{"metric.rating":n.rating,"metric.id":n.id})};t.onLCP(n(`lcp`,`ms`)),t.onCLS(n(`cls`,`1`)),t.onINP(n(`inp`,`ms`)),t.onFCP(n(`fcp`,`ms`)),t.onTTFB(n(`ttfb`,`ms`))}reportNavigationTiming(){this.ctx.diagnostics.guard(`capture.install_failed`,`reading navigation timing`,()=>{let e=performance.getEntriesByType(`navigation`)[0];if(!e)return;let t={"navigation.dns_ms":e.domainLookupEnd-e.domainLookupStart,"navigation.tcp_ms":e.connectEnd-e.connectStart,"navigation.ttfb_ms":e.responseStart-e.requestStart,"navigation.response_ms":e.responseEnd-e.responseStart,"navigation.dom_interactive_ms":e.domInteractive,"navigation.dom_complete_ms":e.domComplete,"navigation.load_ms":e.loadEventEnd};for(let[n,r]of Object.entries(t))Number.isFinite(r)&&r>=0&&this.ctx.logger.logMetric(n,Math.round(r),`ms`,`gauge`,{"navigation.type":e.type})})}};function w(){return`${String(Date.now())}000000`}function me(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function T(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function E(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return T(16)}function he(e,t,n){return n.guard(`storage.unavailable`,`reading ${e}Storage`,()=>(e===`local`?localStorage:sessionStorage).getItem(t))??null}function D(e,t,n,r){r.guard(`storage.unavailable`,`writing ${e}Storage`,()=>{(e===`local`?localStorage:sessionStorage).setItem(t,n)})}function ge(t){let n=E(),r=Date.now(),i=E(),a=he(`local`,e.Vt,t);if(a)try{let e=JSON.parse(a);e.id&&r-(e.lastSeenAt??0)<18e5&&(i=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let o=JSON.stringify({id:i,lastSeenAt:r});D(`local`,e.Vt,o,t);let s=he(`session`,`ui-observability.tab`,t)??``;return s||(s=E(),D(`session`,e.Qt,s,t)),{sessionId:i,tabId:s,contextId:n}}var _e=0;function ve(t,n){let r=Date.now();if(r-_e<6e4)return;_e=r;let i=JSON.stringify({id:t,lastSeenAt:r});D(`local`,e.Vt,i,n)}function O(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function ye(e){if(e.records.length<2)return null;let t=Math.floor(e.records.length/2),n=t=>({id:E(),records:t,createdAt:e.createdAt,attempts:e.attempts});return[n(e.records.slice(0,t)),n(e.records.slice(t))]}function k(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`acquiring lock ${e}`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function A(e,t){let n=[];return t.guard(`storage.unavailable`,`enumerating localStorage`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function be(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.L}${n}.${t.id}`}function xe(e,t){let n=t.guard(`storage.degraded`,`an emergency entry was not JSON and was dropped`,()=>JSON.parse(e));return n===void 0?null:O(n)?n:(t.report(`storage.degraded`,`an emergency entry was not a batch and was dropped`),null)}async function Se(t,n){let r=0;for(let i of A(e.L,n)){let e=n.guard(`storage.unavailable`,`reading the emergency queue`,()=>{let e=localStorage.getItem(i);return localStorage.removeItem(i),e});if(!e)continue;let a=xe(e,n);if(a!==null)try{await t.save(a),r++}catch(e){n.report(`storage.degraded`,`an emergency batch could not be recovered`,{key:i},e)}}return r}function Ce(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=A(e.L,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(be(t),JSON.stringify(t))})}async function we(e,t){return await k(`ui-observability.emergency`,t,()=>Se(e,t),{skipIfBusy:!1})??0}function Te(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}var Ee=class{limits;diagnostics;onGap;name=e.Jt;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.diagnostics.guard(`storage.quota_exceeded`,`localStorage refused a batch, evicting the oldest`,()=>(localStorage.setItem(Te(e),JSON.stringify(e)),!0))!==!0){let e=this.keys();this.evict(e.slice(0,Math.ceil(e.length/4)));return}await this.prune()}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);if(e===null){this.removeKey(n);continue}t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null?Promise.resolve():(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`updating attempts`,()=>{localStorage.setItem(n,JSON.stringify(r))}),Promise.resolve())}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=(e,n)=>{this.removeKey(e),t.batches++,t.records+=n},r=[];for(let t of this.keys()){let i=this.read(t);if(i===null){n(t,0);continue}if(i.createdAt<e){n(t,i.records.length);continue}r.push({key:t,records:i.records.length})}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e.key,e.records)}return t.batches>0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(t.batches)} stored batches (${String(t.records)} records)`,{...t}),this.onGap?.(t)),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`reading a stored batch`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`a stored batch was corrupt and was removed`,()=>JSON.parse(t));return n===void 0?null:O(n)?n:(this.diagnostics.report(`storage.degraded`,`a stored entry was not a batch and was dropped`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`removing a stored batch`,()=>{localStorage.removeItem(e)})}keys(){return A(e.v,this.diagnostics)}};function j(e){return e.reduce((e,t)=>e+t.records.length,0)}var M=class{limits;onGap;name=e.Yt;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),t.batches+=n.length,t.records+=j(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=j(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},De={name:e.Xt,save:()=>Promise.resolve(),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()};function Oe(e){return e.guard(`storage.unavailable`,`reading indexedDB`,()=>globalThis.indexedDB!=null)===!0}function ke(t){return t.guard(`storage.unavailable`,`probing localStorage`,()=>(localStorage.setItem(e.Zt,`1`),localStorage.removeItem(e.Zt),!0))===!0}async function Ae(e,t,n,r,i){if(e===`none`)return De;if(e===`memory`)return new M(n,i);if(e===`indexeddb`||e===`auto`){if(Oe(r)){let e=await r.guardAsync(`storage.unavailable`,`opening IndexedDB`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-DeEh8Ag-.cjs"));return new e(t,n,r,i)});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB was asked for by name and is unavailable, using memory`),new M(n,i)}return ke(r)?new Ee(n,r,i):(r.report(`storage.degraded`,`no persistent storage available, offline logs are memory only`),new M(n,i))}function N(e,t){if(e.length<=t)return e;let n=je(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function je(e){return e>=55296&&e<=56319}function Me(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function P(e,t){let n={bytes:0};return{value:I(e,t,new WeakSet,0,n),bytes:n.bytes}}function F(e,t){return t.bytes+=L(e)+2,e}function I(e,t,n,r,i){if(e==null)return i.bytes+=4,e;if(typeof e==`string`)return F(N(e,t.maxAttributeChars),i);if(typeof e==`number`)return i.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return i.bytes+=5,e;if(typeof e==`bigint`)return F(`${e.toString()}n`,i);if(typeof e==`symbol`)return F(e.toString(),i);if(typeof e==`function`)return F(`[Function ${e.name===``?`anonymous`:e.name}]`,i);if(r>=t.maxDepth)return F(`[MaxDepth]`,i);if(n.has(e))return F(`[Circular]`,i);n.add(e),i.bytes+=2;try{if(e instanceof Error)return{name:F(e.name,i),message:F(N(e.message,t.maxAttributeChars),i),stack:e.stack?F(N(e.stack,t.maxStackChars),i):void 0,cause:e.cause?I(e.cause,t,n,r+1,i):void 0};if(e instanceof Date)return F(e.toISOString(),i);if(e instanceof RegExp)return F(e.toString(),i);if(e instanceof Map){let a=e,o={},s=0;for(let[e,c]of a){if(s>=t.maxArrayLength){o[`…`]=F(`[${String(a.size-t.maxArrayLength)} more entries]`,i);break}s++;let l=String(e);i.bytes+=L(l)+4,o[l]=I(c,t,n,r+1,i)}return o}if(e instanceof Set)return I([...e].slice(0,t.maxArrayLength),t,n,r,i);if(ArrayBuffer.isView(e)){let t=e.length??0;return F(`[${e.constructor.name}(${String(t)})]`,i)}if(e instanceof Promise)return F(`[Promise]`,i);if(typeof Node<`u`&&e instanceof Node)return F(Me(e),i);if(Array.isArray(e)){let a=e,o=a.slice(0,t.maxArrayLength).map(e=>I(e,t,n,r+1,i));return a.length>t.maxArrayLength&&o.push(F(`[${String(a.length-t.maxArrayLength)} more items]`,i)),o}let a=e.toJSON;if(typeof a==`function`)return I(a.call(e),t,n,r+1,i);let o=e,s=Object.keys(o),c={},l=0;for(let e of s){if(l>=t.maxAttributeCount){c[`…`]=F(`[${String(s.length-l)} more keys]`,i);break}l++,i.bytes+=L(e)+4,c[e]=I(o[e],t,n,r+1,i)}return c}catch(e){return F(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,i)}finally{n.delete(e)}}function L(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}var Ne=class{deps;installed=!1;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`subscribing to close-requested`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`releasing close-requested`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(t){let{diagnostics:n}=this.deps,r=this.endpointUrl();if(r===null)return;let i=this.deps.drainForExit();if(!i||i.records.length===0)return;let a=n.guard(`transport.serialize_failed`,`the ${t} exit flush could not serialize its batch`,()=>this.deps.config.serializer.serialize(i.records));if(!a)return;if(L(a.body)>6e4){Ce(i,n);return}r.searchParams.set(e.gt,i.id),r.searchParams.set(e._t,t);let o=r.toString();this.beacon(o,a.body)||this.keepaliveFetch(o,a.body,t)}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`the exit flush cannot use endpoint ${e}`,()=>new URL(e))??null:null}beacon(t,n){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let r=globalThis.navigator;return r?.sendBeacon?r.sendBeacon(t,new Blob([n],{type:e.A})):!1})===!0}keepaliveFetch(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`the keepalive fetch fallback`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.q]:e.A},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`the exit flush failed`,{reason:r},e)})})}};async function Pe(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.R)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var R=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i){super(t),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function Fe(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.lt);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var Ie=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){!this.config.endpoint||e.records.length===0||await this.post(e)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t){let{config:n}=this,r;try{r=n.serializer.serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`serializer threw, dropping the batch`,{batchId:t.id},e);return}let i=new Headers(await this.resolveHeaders());i.set(e.q,r.contentType),i.set(e.G,t.id),i.set(e.W,String(t.attempts));let a=await this.encodeBody(r.body);typeof a!=`string`&&i.set(e.K,e.R);let o=await this.dispatch(i,a);if(o.ok){this.throttledUntil=0;return}throw await this.classify(o,t.id)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||L(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`gzipping the payload`,()=>Pe(e))??e}async dispatch(t,n){let{config:r}=this,i=new AbortController,a=setTimeout(()=>{i.abort()},e.bt);c(a);try{return await fetch(r.endpoint,{method:`POST`,headers:t,body:n,credentials:r.credentials,signal:i.signal,cache:`no-store`})}catch{if(i.signal.aborted)throw new R(`timeout`,`request exceeded ${String(e.bt)}ms`);let t=globalThis.navigator?.onLine;throw new R(t===!1?`offline`:`transient`,`network error`)}finally{clearTimeout(a)}}async classify(t,n){let r=t.status,i=Fe(t.headers.get(e.J));if(r===401||r===403)return this.diagnostics.report(`transport.rejected_credentials`,`server returned ${String(r)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`,{status:r,endpoint:this.config.endpoint}),new R(`permanent`,`rejected with ${String(r)}`,r);if(r===413)return new R(`too_large`,`payload too large`,r,void 0,await this.readMaxBytes(t));if(r===429||r===503){let e=r===429;return this.throttledUntil=Date.now()+(i??2e3),e&&this.diagnostics.report(`transport.throttled`,`server throttled us`,{retryAfterMs:i}),new R(`throttled`,e?`throttled`:`service unavailable`,r,i)}return r===408||r>=500?new R(`transient`,`server error ${String(r)}`,r):(this.diagnostics.report(`transport.dropped_permanent`,`server rejected the batch with ${String(r)}, dropping it`,{batchId:n,status:r}),new R(`permanent`,`rejected with ${String(r)}`,r))}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`reading the 413 body`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`headers() threw`,()=>Promise.resolve(e()))??{}:e:{}}},Le=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.Ft)}nudge(){this.draining||this.schedule(e.Pt)}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,c(t)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Pt*2**this.attempt,e.It);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await k(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.Ft)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(e.Ft),!0;let t=await this.storage.take(this.batchesPerDrain);if(t.length===0)return this.schedule(e.Ft),!0;for(let e of t)if(this.stopped||!await this.deliver(e))return!0;return this.schedule(t.length===this.batchesPerDrain?0:e.Ft),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`the drain loop threw`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=e.Gt.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`giving up on a batch after ${t.attempts.toString()} attempts`,{batchId:t.id,records:t.records.length}),await this.storage.remove(t.id),!0;try{return await this.transport.send(t),await this.storage.remove(t.id),this.attempt=0,!0}catch(n){let r=n instanceof R?n:void 0;return r?.kind===`permanent`?(await this.storage.remove(t.id),!0):r?.kind===`too_large`?(await this.splitStored(t,r.maxBytes),!0):r?.kind===`offline`?(this.schedule(e.Ft),!1):(await this.storage.bumpAttempts(t.id,t.attempts+1),this.attempt++,this.schedule(r?.retryAfterMs??this.backoffMs()),!1)}}async splitStored(e,t){let n=ye(e);if(await this.storage.remove(e.id),!n){this.diagnostics.report(`transport.dropped_permanent`,`a single record exceeds the server limit and was dropped`,{batchId:e.id,bodies:e.records.map(e=>e.body)});return}this.diagnostics.report(`transport.batch_split`,`the server refused the batch as too large`,{from:e.records.length,to:n[0].records.length,serverMaxBytes:t});for(let e of n)await this.storage.save(e)}},Re={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},ze=class{minLevel;constructor(e){this.minLevel=e}update(e){this.minLevel=e}write(t,n,r){if(this.minLevel===null||e.rt[t]<e.rt[this.minLevel]||typeof console>`u`)return;let i=`%c${e.it}%c ${t}`;if(r===void 0){console[Re[t]](i,e.D,``,n);return}console[Re[t]](i,e.D,``,n,r)}},Be=class{value=0;next(){return++this.value}reset(){this.value=0}},Ve=/^[0-9a-f]{32}$/,He=/^[0-9a-f]{16}$/,Ue=/[1-9a-f]/;function We(){return import(`@opentelemetry/api`)}function Ge(e){return Ve.test(e.traceId)&&Ue.test(e.traceId)&&He.test(e.spanId)&&Ue.test(e.spanId)}function Ke(){return T(16)}function qe(){return T(8)}function Je(){return{traceId:Ke(),spanId:qe(),traceFlags:1,startedAt:Date.now()}}function Ye(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var Xe=class{diagnostics;maxAgeMs;load;ambient=Je();otel;constructor(t,n=e.rn,r=We){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`@opentelemetry/api is not available, so records carry this library's own trace ids`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),Ye(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`reading the active OpenTelemetry span`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(Ge(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=Je(),Ye(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`injecting OpenTelemetry headers`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.nn]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},Ze=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function Qe(t){return e.dt.test(t)?Number(BigInt(t)/e.ft):Date.now()}var $e={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=Qe(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Dt],version:t.resource[e.Ot],environment:t.resource[e.Ct]},user_agent:{original:t.resource[e.xt]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...t.resource,...t.attributes}})}).join(`
|
|
3
|
-
`)}\n`,contentType:e.k}}};function z(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(z).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:B(e)}}:null}function B(e){let t=[];for(let[n,r]of Object.entries(e)){let e=z(r);e&&t.push({key:n,value:e})}return t}var V=new WeakMap;function et(e){let t=V.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return V.set(e,n),n}var H={name:e.zt,serialize(t){let n=new Map;for(let e of t){let t=et(e.resource),r=n.get(t);if(r){r.records.push(e);continue}n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:B(t.resource)},scopeLogs:[{scope:{name:e.en,version:e.tn},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:B(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.O}}};function tt(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function nt(t,n,r){return t===void 0?n??H:t===`otlp`?H:t===`ecs`?$e:tt(t)?t:(r.report(`config.invalid`,`serializer must be "${e.zt}", "ecs" or an implementation`),H)}function rt(t,n){return t===void 0?n:t===!1?null:t===!0?e.E:t}function U(t,n,r){let i=r??e.j,a={...i,...t,serializer:nt(t.serializer,r?.serializer,n),console:rt(t.console,i.console),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(!a.endpoint)n.report(`config.invalid`,`endpoint is missing. Records will be built and dropped, never sent.`);else try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record will report service.name as '${e.on}'.`),e.on);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1, got ${String(o)}`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1, got ${String(t)}`),a.sampling.rates[e]=1);a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]);let c=new Set([...Object.keys(e.j),...e.an]);for(let e of Object.keys(t))c.has(e)||n.report(`config.invalid`,`unknown config key "${e}", ignored. Typo?`);return a}function it(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var at=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},ot=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.it} onDiagnostic handler threw`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},st={maxAgeMs:e.et,endOnOwnerClose:!1,urlParam:e.nt};function W(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function G(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function ct(e){if(typeof e!=`object`||!e)return null;let t=W(e,`id`),n=W(e,`name`),r=G(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:W(e,`parentId`),ownerContextId:W(e,`ownerContextId`)??``}}function lt(e){if(typeof e!=`object`||!e)return null;let t=W(e,`i`),n=W(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:G(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function ut(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.g,`-`).replace(e._,`_`).replace(e.h,``)}function dt(e,t){let n=new Promise((e,n)=>{c(setTimeout(()=>{n(Error(`timed out after ${String(t)}ms`))},t))});return Promise.race([e,n])}var ft=class{options;diagnostics;contextId;onLocalChange;journey=null;expiryTimer=null;constructor(e,t,n,r){this.options=e,this.diagnostics=t,this.contextId=n,this.onLocalChange=r}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`reading the persisted journey`,()=>sessionStorage.getItem(e.tt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,t={}){let n={id:t.id??E(),name:e,startedAt:Date.now(),parentId:t.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(n),this.onLocalChange(n),n}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=ut(e);if(t.length>256){this.diagnostics.report(`journey.token_too_large`,`journey token exceeded the size cap and was not issued`,{length:t.length});return}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`,`discarded a seeded journey older than maxAgeMs`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`adopted 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=ct(this.diagnostics.guard(`storage.degraded`,`parsing the persisted journey`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a persisted journey older than maxAgeMs`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`resumed journey "${t.name}"`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`decoding a seeded journey token`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return lt(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`persisting the journey`,()=>{t===null?sessionStorage.removeItem(e.tt):sessionStorage.setItem(e.tt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`journey "${t.name}" hit maxAgeMs and was ended automatically`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=r,c(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`clearing the persisted journey`,()=>{sessionStorage.removeItem(e.tt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`reading the journey token from the URL`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let t=globalThis.fin?.me,n=t?.getOptions;if(n===void 0)return null;let r=(await this.diagnostics.guardAsync(`openfin.unavailable`,`reading fin.me.getOptions()`,()=>dt(n.call(t),e.mt)))?.customData?.[e.pt];return typeof r==`string`?r:null}};function pt(t){let n=e.V;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.H);return n>>>0}function K(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function mt(e,t){let{rates:n,defaultRate:r}=t.sampling,i,a=-1;for(let[t,r]of Object.entries(n))(e===t||e.startsWith(`${t}.`))&&t.length>a&&(i=r,a=t.length);return i??r}function q(t,n){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let r=mt(t.namespace,n);return r>=1?!0:r<=0?!1:pt(t.journeyId||t.traceId)/e.in<r}function ht(t,n){return q({level:t.severityText,type:K(t,e.l),namespace:K(t,e.n),journeyId:K(t,e.a),traceId:t.traceId},n)}var gt=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};function _t(t){return t.attributes[e.l]===e.ot}var vt={logs:{flushIntervalMs:e.at,batchSize:100},metrics:{flushIntervalMs:e.ct,batchSize:500}},yt=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){if(this.pending.push(e),this.pending.length>=this.options.batchSize){this.onFlush(this);return}this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,c(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},bt=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];ceiling=new gt;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i=vt){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new yt(i.logs,a),metrics:new yt(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=w(),this.route(e))}drainPending(){return this.toBatch([...this.streams.metrics.take(),...this.streams.logs.take()])}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.toBatch([...e,...this.streams.metrics.take(),...this.streams.logs.take()])}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.stop(),this.queue.length=0}toBatch(e){return e.length===0?null:{id:E(),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=_t(e)?this.streams.metrics:this.streams.logs;if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`a record was dropped on its way into a stream`,void 0,e)}}claim(e){let t=e.take(),n={id:E(),records:t,createdAt:Date.now(),attempts:0};this.unconfirmed.set(n.id,n),this.enqueue(n)}enqueue(e){this.queue.push(e),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){try{await this.dispatch(e)}catch(t){this.diagnostics.report(`pipeline.crashed`,`dispatch rejected, which it is written never to do`,{batchId:e.id},t)}finally{this.inFlight--,this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs();if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`stored the batch rather than sending it`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e)}catch(t){await this.store({...e,attempts:e.attempts+1}),this.diagnostics.report(`transport.http_error`,`batch was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async store(e){await this.diagnostics.guardAsync(`storage.degraded`,`persisting an undelivered batch`,async()=>{await this.storage.save(e),this.retry.nudge()})}};function J(e){return e}var xt=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.rt[t]>=e.rt[n.minLevel]:!1}build(t){let{config:n,diagnostics:r,tracing:i,journey:a,sequence:o,limits:s}=this.deps;if(!this.isEnabled(t.level))return r.count(`record.dropped_by_level`),null;let c=i.resolve(),l=a.current();if(!q({level:t.level,type:t.type,namespace:t.namespace,journeyId:l?.id??``,traceId:c.traceId},n))return r.count(`record.dropped_by_sampling`),null;let u=o.next(),d=se(),f=n.capture.fullUrls?d:b(d),p,m=0;try{let e=P(this.deps.context.getAll(),s),n=P(t.scoped??{},s),r=P(t.payload??{},s);m=e.bytes+n.bytes+r.bytes,p={...J(e.value),...J(n.value),...J(r.value)}}catch(t){r.report(`record.sanitize_failed`,`attributes could not be sanitized`,void 0,t),p={[e.d]:!0}}p[e.l]=t.type,p[e.c]=u,p[e.n]=t.namespace,p[e.u]=f,l&&(p[e.a]=l.id,p[e.o]=l.name,l.parentId!==void 0&&(p[e.s]=l.parentId));let h=N(t.body,s.maxBodyChars);h!==t.body&&r.count(`record.truncated`);let g={timeUnixNano:w(),traceId:c.traceId,spanId:c.spanId,traceFlags:c.traceFlags,severityNumber:e.Ut[t.level],severityText:t.level,body:h,attributes:p,resource:this.resource()},_=n.redact;if(_){let e=r.guard(`record.sanitize_failed`,`redact hook threw`,()=>_(g));if(e===null)return r.count(`record.dropped_by_redact`),null;if(e!==void 0&&e!==g){if(me(e)){let t=P(e.attributes,s);g={...e,attributes:J(t.value)},m=t.bytes}else r.report(`record.sanitize_failed`,`redact hook returned something that is not a record, keeping the original`)}}if(m>s.maxRecordBytes){r.report(`record.truncated`,`attributes exceeded the size budget and were dropped`,{bytes:m,body:g.body});let n={[e.l]:t.type,[e.c]:u,[e.n]:t.namespace,[e.u]:f,[e.i]:!0,[e.r]:m};l&&(n[e.a]=l.id,n[e.o]=l.name),g.attributes=n}return g}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Dt]:t.serviceName,[e.Ot]:t.serviceVersion,[e.Ct]:t.environment,[e.Mt]:e.en,[e.Nt]:e.tn,[e.jt]:e.$t,[e.wt]:r.platform,[e.kt]:n.sessionId,[e.At]:n.tabId,[e.St]:n.contextId,[e.xt]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Et]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Tt]:r.openfinName}},this.resourceCache}},Y=Symbol.for(e.Lt),X=class t{diagnostics;config;platform;identity;context=new at;breadcrumbs;tracing;sequence=new Be;journey;builder;console;bus;storage;transport;retry;pipeline;exitFlush;captures=[];bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(t){this.diagnostics=new ot(t.onDiagnostic),this.platform=ie(this.diagnostics),this.config=U(t,this.diagnostics),this.identity=ge(this.diagnostics),this.breadcrumbs=new Ze(50),this.tracing=new Xe(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new ze(this.config.console),this.journey=new ft(st,this.diagnostics,this.identity.contextId,e=>{this.bus.broadcastJourney(e)}),this.builder=new xt({config:this.config,limits:e.yt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform}),this.bus=new re(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}})}busAccept=(e,t)=>{this.destroyed||this.diagnostics.guard(`bus.send_failed`,`accepting a direct message from a child`,()=>{this.bus.acceptDirect(e,t)})};static current(){return globalThis[Y]??null}static configure(e){let n=t.current();if(n&&!n.destroyed)return n.reconfigure(e),n;let r=new t(e);return globalThis[Y]=r,r.init(),r}reconfigure(e){it(this.config,U(e,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.ready&&this.reinstallCaptures(),this.diagnostics.report(`config.reconfigured`,`configure() was called again, the existing runtime was updated`)}async init(){try{let e=this.journey.bootstrap();await this.bus.start()===`sender`&&await this.becomeSender(),await e,this.installCaptures()}catch(e){this.diagnostics.report(`pipeline.crashed`,`startup failed, continuing in a degraded state`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}async becomeSender(){this.storage=await Ae(this.config.storage,e.Wt,e.Gt,this.diagnostics,this.reportGap),this.transport=new Ie(this.config,this.diagnostics),this.retry=new Le(this.storage,this.transport,this.diagnostics,this.config),this.pipeline=new bt(this.transport,this.storage,this.retry,this.diagnostics),this.exitFlush=new Ne({config:this.config,diagnostics:this.diagnostics,drainForExit:()=>this.pipeline?.drainForExit()??null}),await we(this.storage,this.diagnostics),this.retry.start(),this.exitFlush.install()}installCaptures(){let t={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new s(this,e.C)},n=this.config.capture;(n.errors||n.rejections||n.resourceErrors)&&this.captures.push(new ce(t)),(n.fetch||n.xhr)&&this.captures.push(new de(t)),(n.interactions||n.navigation)&&this.captures.push(new ue(t)),n.webVitals&&this.captures.push(new pe(t));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`installing ${e.name}`,()=>{e.install()})}reinstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`uninstalling ${e.name}`,()=>{e.uninstall()});this.captures.length=0,this.installCaptures()}registerWorker(e){this.destroyed||this.diagnostics.guard(`bus.send_failed`,`registering a worker`,()=>{this.bus.attachWorker(e)})}async destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.captures)e.uninstall();this.captures.length=0,this.exitFlush?.flush(`shutdown`),this.exitFlush?.uninstall(),this.retry?.stop(),this.pipeline?.destroy(),this.journey.destroy(),this.bus.destroy(),this.forwardBuffer=[],await this.storage?.close(),t.current()===this&&Reflect.deleteProperty(globalThis,Y)}}emit(e){if(!(!e||this.destroyed)){if(ve(this.identity.sessionId,this.diagnostics),!this.ready){this.bootBuffer.length>=500&&(this.bootBuffer.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),this.bootBuffer.push(e);return}this.route(e)}}route(e){if(this.bus.getRole()===`forwarder`){this.forward(e);return}this.pipeline?.push(e)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}for(let t of e){if(!me(t)){this.diagnostics.count(`record.dropped_malformed`);continue}if(!ht(t,this.config)){this.diagnostics.count(`record.dropped_by_sampling`);continue}this.pipeline?.push(t)}}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new s(this,e.Kt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let t=E();this.diagnostics.report(`bus.role_resolved`,`another context claimed this tab id, most likely a duplicated tab. Regenerating.`,{was:this.identity.tabId,now:t}),this.identity.tabId=t,this.diagnostics.guard(`storage.unavailable`,`persisting the new tab id`,()=>{sessionStorage.setItem(e.Qt,t)}),this.builder.invalidateResource()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting the batches waiting in storage`,()=>this.storage?.count()??Promise.resolve(0))??0}async flush(){if(this.bus.getRole()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e);return}let e=this.pipeline?.drainPending();if(!(!e||!this.transport))try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`persisting the batch drained by flush()`,async()=>{await this.storage?.save({...e,attempts:1}),this.retry?.nudge()}),this.diagnostics.report(`transport.http_error`,`the batch drained by flush() was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}},Z=new Map;function Q(){return X.current()||X.configure({})}function St(e){X.configure(e),Z.clear()}function Ct(e,t){if(t)return new s(Q(),e,t);let n=Z.get(e);return n||(n=new s(Q(),e),Z.set(e,n)),n}function $(){return Ct(`app`)}function wt(e,t){$().trace(e,t)}function Tt(e,t){$().debug(e,t)}function Et(e,t){$().info(e,t)}function Dt(e,t){$().warn(e,t)}function Ot(e,t,n){$().error(e,t,n)}function kt(e,t){$().logAction(e,t)}function At(e,t){$().logEvent(e,t)}function jt(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function Mt(e,t,n){return $().timeSync(e,t,n)}function Nt(e,t,n){return $().timeAsync(e,t,n)}function Pt(e,t){Q().context.set(e,t)}function Ft(e){Q().context.setMany(e)}function It(e){Q().context.remove(e)}function Lt(e,t){return Q().journey.start(e,t)}function Rt(){Q().journey.end()}function zt(){return Q().journey.current()}function Bt(){return Q().journey.getToken()}function Vt(e){return Q().journey.adopt(e,`manual`,!0)}function Ht(e){Q().registerWorker(e)}function Ut(){Q().tracing.rotate(`explicit`)}function Wt(){return Q().tracing.headers()}function Gt(){return Q().flush()}function Kt(){return Q().queueDepth()}function qt(){return Q().diagnostics.snapshot()}async function Jt(){let e=X.current();Z.clear(),await e?.destroy()}exports.OneLogger=s,exports.adoptJourney=Vt,exports.configure=St,exports.currentJourney=zt,exports.debug=Tt,exports.endJourney=Rt,exports.error=Ot,exports.flush=Gt,exports.getDiagnosticCounters=qt,exports.getJourneyToken=Bt,exports.getLogger=Ct,exports.getQueueDepth=Kt,exports.getTraceHeaders=Wt,exports.info=Et,exports.logAction=kt,exports.logEvent=At,exports.logMetric=jt,exports.registerWorker=Ht,exports.removeContext=It,exports.setContext=Pt,exports.setContextMap=Ft,exports.shutdown=Jt,exports.startJourney=Lt,exports.startTrace=Ut,exports.timeAsync=Nt,exports.timeSync=Mt,exports.trace=wt,exports.warn=Dt;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants-BpFlszME.cjs");function t(t){return Math.round((performance.now()-t)*e.F)/e.F}function n(e,n,r,i,a){e.logMetric(`${n}.duration`,t(r),`ms`,`histogram`,{status:i,...a})}function r(e,n,r,i,a){e.error(`${n} failed`,i,{"action.duration_ms":t(r),status:`FAILURE`,...a})}function i(e,t,i,a){let o=performance.now();try{let r=i();return n(e,t,o,`SUCCESS`,a),r}catch(n){throw r(e,t,o,n,a),n}}async function a(e,t,i,a){let o=performance.now();try{let r=await i();return n(e,t,o,`SUCCESS`,a),r}catch(n){throw r(e,t,o,n,a),n}}function o(e,t){if(e instanceof Error)return e;let n=t.guard(`record.sanitize_failed`,`describing an error reason`,()=>String(e));return Error(n??typeof e)}function s(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Error)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}var c=class t{runtime;namespace;options;constructor(e,t,n={}){this.runtime=e,this.namespace=t,this.options=n}child(e,n={}){return new t(this.runtime,`${this.namespace}.${e}`,{scopedContext:{...this.options.scopedContext,...n.scopedContext}})}trace=(e,t)=>{this.write(`TRACE`,`system`,e,t)};debug=(e,t)=>{this.write(`DEBUG`,`system`,e,t)};info=(e,t)=>{this.write(`INFO`,`system`,e,t)};warn=(e,t)=>{this.write(`WARN`,`system`,e,t)};error=(e,t,n)=>{this.writeError(`ERROR`,e,t,n)};fatal=(e,t,n)=>{this.writeError(`FATAL`,e,t,n)};logAction=(e,t)=>{this.write(`INFO`,`action`,e,t)};logEvent=(e,t)=>{this.write(`INFO`,`event`,e,t)};logMetric=(t,n,r=e.M,i=`gauge`,a)=>{this.write(`INFO`,`metric`,t,{"metric.name":t,"metric.value":n,"metric.unit":r,"metric.type":i,...a})};timeSync=(e,t,n)=>i(this,e,t,n);timeAsync=(e,t,n)=>a(this,e,t,n);write(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let{record:i,dropped:a}=this.runtime.builder.build({level:e,type:t,body:n,namespace:this.namespace,scoped:this.options.scopedContext,payload:r});t!==`metric`&&a!==`redact`&&this.runtime.breadcrumbs.push({t:Date.now(),category:t===`action`?`action`:t===`event`?`event`:`log`,message:n}),this.runtime.console.write(e,n,i?.attributes),this.runtime.emit(i)}writeError(e,t,n,r){if(!this.runtime.builder.isEnabled(e))return;let i=r===void 0&&s(n),a=i?n:r,c=i||n===void 0?void 0:o(n,this.runtime.diagnostics),{record:l}=this.runtime.builder.build({level:e,type:`system`,body:t,namespace:this.namespace,scoped:this.options.scopedContext,payload:{...a,...c?{"error.type":c.name,"error.message":c.message,"error.stack_trace":c.stack}:{},breadcrumbs:this.runtime.breadcrumbs.snapshot()}});this.runtime.console.write(e,t,c??l?.attributes),this.runtime.emit(l)}};function l(e){typeof e!=`number`&&e.unref?.()}function u(t){return{p:e.S,m:t}}function d(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.p!==`ui-observability/1`||typeof t.m!=`object`||t.m===null)return null;let n=t.m;return typeof n.t==`string`?n:null}var f=Symbol.for(e.Rt);function p(e,t){if(typeof window>`u`||window.parent===window)return null;let n;try{n=window.parent[f]}catch{return null}if(typeof n?.busAccept!=`function`)return null;let r=n,i=!0;return{kind:`direct`,post(n){i&&t.guard(`bus.send_failed`,`direct call into the parent runtime`,()=>{r.busAccept(n,e)})},close(){i=!1}}}function m(e,t){if(typeof window>`u`||window.parent===window)return null;let n=t=>{let n=d(t.data);n&&t.source===window.parent&&e(n,{link:`parent`,origin:t.origin})};return addEventListener(`message`,n),{kind:`parent`,post(e){t.guard(`bus.send_failed`,`postMessage to parent`,()=>{window.parent.postMessage(u(e),`*`)})},close(){removeEventListener(`message`,n)}}}function h(e,t,n){if(typeof window>`u`)return null;let r=new Set([window.location.origin,...t]),i=new Map,a=t=>{let a=d(t.data);if(a){if(!r.has(t.origin)){n.report(`bus.untrusted_origin`,`ignored a bus message from ${t.origin}. Add it to bus.trustedOrigins if it is yours.`,{origin:t.origin,type:a.t});return}t.source&&i.set(t.source,t.origin),e(a,{link:`children`,origin:t.origin})}};return addEventListener(`message`,a),{kind:`children`,post(e){for(let[t,r]of i){let a=t;if(a.closed){i.delete(t);continue}n.guard(`bus.send_failed`,`postMessage to child`,()=>{a.postMessage(u(e),r)})}},close(){removeEventListener(`message`,a),i.clear()}}}function g(e,t,n){let r=globalThis.BroadcastChannel;if(r===void 0)return null;let i=n.guard(`bus.send_failed`,`opening BroadcastChannel`,()=>new r(e));return i?(i.onmessage=e=>{let n=d(e.data);n&&t(n,{link:`broadcast`,origin:`same-origin`})},{kind:`broadcast`,post(e){n.guard(`bus.send_failed`,`BroadcastChannel.postMessage`,()=>{i.postMessage(u(e))})},close(){n.guard(`bus.send_failed`,`closing BroadcastChannel`,()=>{i.close()})}}):null}function _(e,t,n,r){let i=globalThis.fin?.InterApplicationBus;if(!i)return null;if(!t)return r.report(`openfin.unavailable`,`no OpenFin application uuid, so the InterApplicationBus link stays closed`),null;let a=`${e}.${t}`;return r.guardAsync(`bus.send_failed`,`InterApplicationBus.subscribe`,()=>i.subscribe({uuid:t},a,e=>{let t=d(e);t&&n(t,{link:`openfin`,origin:`openfin`})})),{kind:`openfin`,post(e){r.guardAsync(`bus.send_failed`,`InterApplicationBus.publish`,()=>i.publish(a,u(e)))},close(){}}}function ee(e,t){let n=globalThis,r=n.postMessage;return n.WorkerGlobalScope===void 0||!r?null:(n.addEventListener?.(`message`,t=>{let n=d(t.data);n&&e(n,{link:`owner`,origin:`same-origin`})}),{kind:`owner`,post(e){t.guard(`bus.send_failed`,`worker postMessage`,()=>{r(u(e))})},close(){}})}function te(e,t,n){let r=e=>{let n=d(e.data);n&&t(n,{link:`worker`,origin:`same-origin`})};return e.addEventListener(`message`,r),e.start?.(),{kind:`worker`,post(t){n.guard(`bus.send_failed`,`postMessage to a worker`,()=>{e.postMessage(u(t))})},close(){e.removeEventListener(`message`,r)}}}var ne={timeoutMs:e.x,maxAttempts:3},re=[`children`,`direct`,`worker`],ie=class{config;diagnostics;platform;contextId;tabId;handlers;handshakeOptions;role=`sender`;upstream=null;links=[];openFinLink=null;isOpenFinProvider=!1;resolved=!1;awaitingWelcome=null;constructor(e,t,n,r,i,a,o=ne){this.config=e,this.diagnostics=t,this.platform=n,this.contextId=r,this.tabId=i,this.handlers=a,this.handshakeOptions=o}getRole(){return this.role}isResolved(){return this.resolved}async start(){let{bus:e}=this.config;if(e.mode===`off`)return this.role=`sender`,this.resolved=!0,this.role;if(this.isOpenFinProvider=this.resolveOpenFinProvider(),e.mode===`sender`||e.mode===`forwarder`)return this.role=e.mode,this.openControlLinks(),this.role===`forwarder`&&(this.upstream=this.candidateUpstream(),this.upstream||this.diagnostics.report(`bus.no_owner`,`bus.mode is "forwarder" but there is no owner to forward to. Records will be dropped.`)),this.resolved=!0,this.announce(),this.role;this.openControlLinks();let t=p(this.receive,this.diagnostics);if(t)return this.role=`forwarder`,this.upstream=t,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`attached directly to the same-origin parent runtime`,{role:`forwarder`,via:`direct`}),this.announce(),this.role;let n=this.candidateUpstream();if(!n)return this.role=`sender`,this.resolved=!0,this.diagnostics.report(`bus.role_resolved`,`no owner to forward to, sending directly`,{role:`sender`}),this.announce(),this.role;let r=this.orphanPolicy()===`retry`?this.handshakeOptions.maxAttempts:1,i=!1;for(let e=0;e<r&&!i;e++)i=await this.handshake(n);return this.role=i?`forwarder`:`sender`,this.upstream=i?n:null,i||(n!==this.openFinLink&&n.close(),this.diagnostics.report(`bus.handshake_timeout`,`no owner answered after ${String(r)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)}ms, promoting to sender`,{via:n.kind,crossOrigin:this.isCrossOriginFrame()})),this.diagnostics.report(`bus.role_resolved`,`role is ${this.role}`,{role:this.role,via:i?n.kind:`none`}),this.resolved=!0,this.announce(),this.role}sendRecords(e){this.upstream?.post({t:`records`,from:this.contextId,records:e})}acceptDirect(e,t){if(e.from===this.contextId)return;let n={link:`direct`,origin:`same-origin`};if(e.t===`hello`){this.canOwn(`direct`)&&t({t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId},n);return}if(e.t===`journey?`){let e=this.handlers.onJourneyRequest();e&&t({t:`journey`,from:this.contextId,journey:e},n);return}this.receive(e,n)}attachWorker(e){this.links.push(te(e,this.receive,this.diagnostics))}broadcastJourney(e){this.post({t:`journey`,from:this.contextId,journey:e})}destroy(){for(let e of this.allLinks())e.close();this.links.length=0,this.upstream=null,this.openFinLink=null}allLinks(){return!this.upstream||this.links.includes(this.upstream)?this.links:[...this.links,this.upstream]}post(e){for(let t of this.allLinks())t.post(e)}postOver(e,t){for(let n of this.allLinks())n.kind===e&&n.post(t)}receive=(e,t)=>{if(e.from!==this.contextId)switch(e.t){case`hello`:this.canOwn(t.link)&&this.postOver(t.link,{t:`welcome`,from:this.contextId,to:e.from,tabId:this.tabId});break;case`welcome`:if(e.to!==this.contextId)break;this.awaitingWelcome?.link===t.link&&this.awaitingWelcome.settle(!0);break;case`records`:this.role===`sender`?this.handlers.onRecords(e.records):this.upstream&&t.link!==this.upstream.kind&&this.upstream.post(e);break;case`journey`:this.handlers.onJourney(e.journey);break;case`journey?`:{let e=this.handlers.onJourneyRequest();e&&this.postOver(t.link,{t:`journey`,from:this.contextId,journey:e});break}case`tab`:t.link===`broadcast`&&e.tabId===this.tabId&&this.contextId>e.from&&this.handlers.onTabConflict()}};canOwn(e){return this.role===`sender`?e===`openfin`?this.isOpenFinProvider:re.includes(e):!1}resolveOpenFinProvider(){let e=this.config.bus.openFinRole;if(e!==`auto`)return e===`provider`;if(this.platform.platform!==`openfin`&&this.platform.platform!==`openfin_web`)return!1;let t=globalThis.fin?.me;return!t?.identity||t.isView?!1:!!(t.identity.name&&t.identity.name===t.identity.uuid)}orphanPolicy(){return this.isCrossOriginFrame()?`retry`:`promote`}isCrossOriginFrame(){if(typeof window>`u`||window.parent===window)return!1;try{return Reflect.get(window.parent,`location`),!1}catch{return!0}}candidateUpstream(){return this.platform.isWorker?ee(this.receive,this.diagnostics):this.platform.isTopLevelDocument?this.platform.platform===`openfin`&&!this.isOpenFinProvider?this.ensureOpenFinLink():null:m(this.receive,this.diagnostics)}openControlLinks(){let t=e=>{e&&this.links.push(e)};this.platform.isTopLevelDocument&&(t(h(this.receive,this.config.bus.trustedOrigins,this.diagnostics)),t(g(e.b,this.receive,this.diagnostics))),(this.platform.platform===`openfin`||this.platform.platform===`openfin_web`)&&t(this.ensureOpenFinLink())}ensureOpenFinLink(){return this.openFinLink??=_(e.b,this.platform.openfinUuid,this.receive,this.diagnostics),this.openFinLink}handshake(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,this.awaitingWelcome=null,clearTimeout(i),t(e))};this.awaitingWelcome={link:e.kind,settle:r};let i=setTimeout(()=>{r(!1)},this.handshakeOptions.timeoutMs);l(i),e.post({t:`hello`,from:this.contextId,tabId:this.tabId})})}announce(){this.postOver(`broadcast`,{t:`tab`,from:this.contextId,tabId:this.tabId}),this.post({t:`journey?`,from:this.contextId})}},v=null;function y(e,t){let n=e[t];return n!==void 0&&e instanceof n}function ae(t){if(v)return v;let n=globalThis,r=n.navigator?.userAgent??``,i=`browser`,a,o,s=!1,c=n.fin?.me;return y(n,`ServiceWorkerGlobalScope`)?(i=`service_worker`,s=!0):y(n,`SharedWorkerGlobalScope`)?(i=`shared_worker`,s=!0):y(n,`WorkerGlobalScope`)?(i=`web_worker`,s=!0):c===void 0?n.Capacitor!==void 0||n.Ionic!==void 0?i=`ionic`:n.cordova!==void 0||oe(r)?i=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(i=`node`):(i=e.gt.test(r)?`openfin`:`openfin_web`,t.guard(`openfin.unavailable`,`reading fin.me.identity`,()=>{let e=c.identity;a=e?.uuid,o=e?.name})),v={platform:i,openfinUuid:a,openfinName:o,userAgent:r,isWorker:s,isTopLevelDocument:se()},v}function oe(t){return e.t.test(t)?!0:(e.et.test(t)||e.ct.test(t)&&e.dt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function se(){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return!1}}function ce(){try{return typeof location<`u`?location.href:``}catch{return``}}function b(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}var le=class{ctx;name=`errors`;installed=!1;seen=new Map;windowStart=0;windowCount=0;constructor(e){this.ctx=e}install(){this.installed||typeof addEventListener>`u`||(this.installed=!0,addEventListener(`error`,this.onError,!0),addEventListener(`unhandledrejection`,this.onRejection))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`error`,this.onError,!0),removeEventListener(`unhandledrejection`,this.onRejection),this.seen.clear())}onError=e=>{let t=e.target,n=t?.src??t?.href??``;if(t!==null&&t!==globalThis&&n!==``){if(!this.ctx.config.capture.resourceErrors)return;let e=this.ctx.config.capture.fullUrls?n:b(n);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`resource failed: ${e}`}),this.ctx.logger.warn(`resource failed to load`,{"error.type":`resource`,"resource.url":e,"resource.tag":t.tagName.toLowerCase()});return}if(!this.ctx.config.capture.errors)return;let r=e,i=r.message===``?`unknown error`:r.message,a=r.error??Error(i);this.report(`window.onerror`,a,{"error.source":r.filename,"error.line":r.lineno,"error.column":r.colno})};onRejection=e=>{this.ctx.config.capture.rejections&&this.report(`unhandledrejection`,e.reason,{"error.type":`unhandledrejection`})};report(t,n,r){let i=Date.now();if(i-this.windowStart>1e4&&(this.windowStart=i,this.windowCount=0),this.windowCount++,this.windowCount>20){this.ctx.diagnostics.report(`capture.rate_limited`,`more than 20 errors in ${String(e.V)}ms, suppressing the rest of this window`);return}let a=n instanceof Error?n:Error(String(n)),o=(a.stack??``).split(`
|
|
2
|
+
`)[1]??``,s=`${a.name}|${a.message}|${o}`,c=this.seen.get(s);if(c&&i-c.at<5e3){c.count++,c.at=i;return}let l=c?c.count-1:0;if(this.seen.delete(s),this.seen.set(s,{at:i,count:1}),this.seen.size>200){let[e]=this.seen.keys();this.seen.delete(e)}this.ctx.logger.error(a.message===``?t:a.message,a,{...r,"error.captured_by":t,"error.suppressed_count":l})}};function ue(e){if(e===null)return`unknown`;let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function x(){return history}var de=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(x().pushState=this.originalPushState),this.originalReplaceState&&(x().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let t=e.target,n=ue(t instanceof Element?t:null),r=t instanceof HTMLElement?t.innerText.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:n,data:r===``?void 0:{text:r}})};onNavigate=()=>{let e=this.lastUrl,t=location.href;if(e===t)return;this.lastUrl=t;let n=this.ctx.config.capture.fullUrls,r=n?e:b(e),i=n?t:b(t);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${r} -> ${i}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":r})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=x(),t=e.pushState,n=e.replaceState;this.originalPushState=t,this.originalReplaceState=n;let r=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(r)},e.replaceState=function(...e){n.apply(this,e),queueMicrotask(r)}}};function S(e,t){return t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function C(){return XMLHttpRequest.prototype}var fe=class{ctx;name=`network`;originalFetch=null;originalOpen=null;originalSend=null;constructor(e){this.ctx=e}install(){this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr()}uninstall(){this.originalFetch&&=(globalThis.fetch=this.originalFetch,null),this.originalOpen&&=(C().open=this.originalOpen,null),this.originalSend&&=(C().send=this.originalSend,null)}ignored(e){return S(e,this.ctx.config.capture.ignoreUrls)}installFetch(){if(typeof globalThis.fetch!=`function`||this.originalFetch)return;let e=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;let t=this.ctx,n=e=>this.ignored(e),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)};globalThis.fetch=async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.href:i.url,s=(a?.method??(i instanceof Request?i.method:`GET`)).toUpperCase();if(n(o))return e(i,a);let c=i,l=a;if(S(o,t.config.capture.propagateTraceHeaderTo))try{let e=Object.entries(t.tracing.headers());if(i instanceof Request){let t=new Headers(i.headers);for(let[n,r]of e)t.set(n,r);c=new Request(i,{headers:t})}else{let t=new Headers(a?.headers);for(let[n,r]of e)t.set(n,r);l={...a,headers:t}}}catch(e){c=i,l=a,t.diagnostics.report(`capture.header_failed`,`could not attach traceparent, sending the request unchanged`,{url:o},e)}let u=performance.now();try{let t=await e(c,l);return r(s,o,t.status,performance.now()-u,void 0),t}catch(e){throw r(s,o,0,performance.now()-u,e),e}}}installXhr(){if(typeof XMLHttpRequest>`u`||this.originalOpen)return;let e=e=>this.ignored(e),t=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},n=C(),r=n.open,i=n.send;this.originalOpen=r,this.originalSend=i,n.open=function(e,t,...n){this.__uiobs={method:e.toUpperCase(),url:String(t),startedAt:0},r.apply(this,[e,t,...n])},n.send=function(...n){let r=this.__uiobs;r&&!e(r.url)&&(r.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{t(r.method,r.url,this.status,performance.now()-r.startedAt)})),i.apply(this,n)}}record(e,t,n,r,i){let a=this.ctx.config.capture.fullUrls?t:b(t);this.ctx.diagnostics.guard(`capture.record_failed`,`recording ${e} ${a}`,()=>{let t=Math.round(r);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${a} ${n===0?`failed`:String(n)}`,data:{durationMs:t}});let o={"http.request.method":e,"url.full":a,"http.response.status_code":n,"http.duration_ms":t};if(n===0){this.ctx.logger.error(`${e} ${a} failed`,i,o);return}if(n>=400){this.ctx.logger.warn(`${e} ${a} returned ${String(n)}`,o);return}this.ctx.logger.debug(`${e} ${a}`,o)})}};function pe(){return import(`web-vitals`)}var me=class{ctx;name=`web-vitals`;installed=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.reportNavigationTiming(),this.loadWebVitals())}uninstall(){this.installed=!1}async loadWebVitals(){let e=this.ctx.config.capture.webVitalsLoader??pe,t=await this.ctx.diagnostics.guardAsync(`capture.install_failed`,`loading web-vitals`,e);if(!t){this.ctx.diagnostics.report(`capture.install_failed`,`web-vitals is not available, so LCP, CLS and INP are unavailable. Navigation timing still works.`);return}let n=(e,t)=>n=>{this.ctx.logger.logMetric(`web_vitals.${e}`,Math.round(n.value*1e3)/1e3,t,`gauge`,{"metric.rating":n.rating,"metric.id":n.id})};t.onLCP(n(`lcp`,`ms`)),t.onCLS(n(`cls`,`1`)),t.onINP(n(`inp`,`ms`)),t.onFCP(n(`fcp`,`ms`)),t.onTTFB(n(`ttfb`,`ms`))}reportNavigationTiming(){this.ctx.diagnostics.guard(`capture.install_failed`,`reading navigation timing`,()=>{let e=performance.getEntriesByType(`navigation`)[0];if(!e)return;let t={"navigation.dns_ms":e.domainLookupEnd-e.domainLookupStart,"navigation.tcp_ms":e.connectEnd-e.connectStart,"navigation.ttfb_ms":e.responseStart-e.requestStart,"navigation.response_ms":e.responseEnd-e.responseStart,"navigation.dom_interactive_ms":e.domInteractive,"navigation.dom_complete_ms":e.domComplete,"navigation.load_ms":e.loadEventEnd};for(let[n,r]of Object.entries(t))Number.isFinite(r)&&r>=0&&this.ctx.logger.logMetric(n,Math.round(r),`ms`,`gauge`,{"navigation.type":e.type})})}};function he(){return`${String(Date.now())}000000`}function ge(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.body==`string`&&typeof t.severityText==`string`&&typeof t.timeUnixNano==`string`&&typeof t.attributes==`object`&&t.attributes!==null&&typeof t.resource==`object`&&t.resource!==null}function w(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function T(){try{if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID()}catch{}return w(16)}function _e(e,t,n){return n.guard(`storage.unavailable`,`reading ${e}Storage`,()=>(e===`local`?localStorage:sessionStorage).getItem(t))??null}function E(e,t,n,r){r.guard(`storage.unavailable`,`writing ${e}Storage`,()=>{(e===`local`?localStorage:sessionStorage).setItem(t,n)})}function ve(t){let n=T(),r=Date.now(),i=T(),a=_e(`local`,e.Ht,t);if(a)try{let e=JSON.parse(a);e.id&&r-(e.lastSeenAt??0)<18e5&&(i=e.id)}catch{t.report(`storage.degraded`,`session record was not JSON, starting a new session`)}let o=JSON.stringify({id:i,lastSeenAt:r});E(`local`,e.Ht,o,t);let s=_e(`session`,`ui-observability.tab`,t)??``;return s||(s=T(),E(`session`,e.$t,s,t)),{sessionId:i,tabId:s,contextId:n}}var ye=class{diagnostics;lastTouchAt=0;constructor(e){this.diagnostics=e}touch(t){let n=Date.now();if(n-this.lastTouchAt<6e4)return;this.lastTouchAt=n;let r=JSON.stringify({id:t,lastSeenAt:n});E(`local`,e.Ht,r,this.diagnostics)}};function D(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`id`),n=Reflect.get(e,`createdAt`),r=Reflect.get(e,`attempts`),i=Reflect.get(e,`records`);return typeof t==`string`&&typeof n==`number`&&typeof r==`number`&&Array.isArray(i)}function be(e){if(e.records.length<2)return null;let t=Math.floor(e.records.length/2),n=t=>({id:T(),records:t,createdAt:e.createdAt,attempts:e.attempts});return[n(e.records.slice(0,t)),n(e.records.slice(t))]}function O(e,t,n,{skipIfBusy:r=!0}={}){let i=globalThis.navigator?.locks;return i?.request?t.guardAsync(`storage.degraded`,`acquiring lock ${e}`,()=>i.request(e,{ifAvailable:r},e=>e?n():Promise.resolve(void 0))):n()}function k(e,t){let n=[];return t.guard(`storage.unavailable`,`enumerating localStorage`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}function xe(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.R}${n}.${t.id}`}function Se(e,t){let n=t.guard(`storage.degraded`,`an emergency entry was not JSON and was dropped`,()=>JSON.parse(e));return n===void 0?null:D(n)?n:(t.report(`storage.degraded`,`an emergency entry was not a batch and was dropped`),null)}async function Ce(t,n){let r=0;for(let i of k(e.R,n)){let e=n.guard(`storage.unavailable`,`reading the emergency queue`,()=>{let e=localStorage.getItem(i);return localStorage.removeItem(i),e});if(!e)continue;let a=Se(e,n);if(a!==null)try{await t.save(a),r++}catch(e){n.report(`storage.degraded`,`an emergency batch could not be recovered`,{key:i},e)}}return r}function we(t,n){let r=`writing the emergency queue, ${String(t.records.length)} records`;n.guard(`storage.quota_exceeded`,r,()=>{let r=k(e.R,n);for(let e of r.slice(0,Math.max(0,r.length-20+1)))localStorage.removeItem(e);localStorage.setItem(xe(t),JSON.stringify(t))})}async function Te(e,t){return await O(`ui-observability.emergency`,t,()=>Ce(e,t),{skipIfBusy:!1})??0}function Ee(t){let n=String(t.createdAt).padStart(14,`0`);return`${e.v}${n}.${t.id}`}var De=class{limits;diagnostics;onGap;name=e.Yt;constructor(e,t,n){this.limits=e,this.diagnostics=t,this.onGap=n}async save(e){if(this.write(e,`localStorage refused a batch, evicting the oldest`)){await this.prune();return}this.evictForQuota(),this.write(e,`localStorage refused a batch even after evicting`)||this.reportGap({batches:1,records:e.records.length,reason:`quota`})}take(e){let t=[];for(let n of this.keys().slice(0,e)){let e=this.read(n);if(e===null){this.removeKey(n);continue}t.push(e)}return Promise.resolve(t)}remove(e){let t=this.keyOf(e);return t!==null&&this.removeKey(t),Promise.resolve()}bumpAttempts(e,t){let n=this.keyOf(e);if(n===null)return Promise.resolve();let r=this.read(n);return r===null?Promise.resolve():(r.attempts=t,this.diagnostics.guard(`storage.degraded`,`updating attempts`,()=>{localStorage.setItem(n,JSON.stringify(r))}),Promise.resolve())}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=(e,n)=>{this.removeKey(e),t.batches++,t.records+=n},r=[];for(let t of this.keys()){let i=this.read(t);if(i===null){n(t,0);continue}if(i.createdAt<e){n(t,i.records.length);continue}r.push({key:t,records:i.records.length})}let i=r.length-this.limits.maxBatches;if(i>0){t.reason=`over_capacity`;for(let e of r.slice(0,i))n(e.key,e.records)}return this.reportGap(t),Promise.resolve(t)}count(){return Promise.resolve(this.keys().length)}clear(){return this.evict(this.keys()),Promise.resolve()}close(){return Promise.resolve()}write(e,t){return this.diagnostics.guard(`storage.quota_exceeded`,t,()=>(localStorage.setItem(Ee(e),JSON.stringify(e)),!0))===!0}evictForQuota(){let e=this.keys(),t={batches:0,records:0,reason:`quota`};for(let n of e.slice(0,Math.ceil(e.length/4))){let e=this.read(n);this.removeKey(n),t.batches++,t.records+=e?.records.length??0}this.reportGap(t)}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`dropped ${String(e.batches)} stored batches (${String(e.records)} records)`,{...e}),this.onGap?.(e))}read(e){let t=this.diagnostics.guard(`storage.unavailable`,`reading a stored batch`,()=>localStorage.getItem(e));if(!t)return null;let n=this.diagnostics.guard(`storage.degraded`,`a stored batch was corrupt and was removed`,()=>JSON.parse(t));return n===void 0?null:D(n)?n:(this.diagnostics.report(`storage.degraded`,`a stored entry was not a batch and was dropped`),null)}keyOf(e){return this.keys().find(t=>t.endsWith(`.${e}`))??null}evict(e){for(let t of e)this.removeKey(t)}removeKey(e){this.diagnostics.guard(`storage.degraded`,`removing a stored batch`,()=>{localStorage.removeItem(e)})}keys(){return k(e.v,this.diagnostics)}};function A(e){return e.reduce((e,t)=>e+t.records.length,0)}var j=class{limits;onGap;name=e.Xt;batches=[];constructor(e,t){this.limits=e,this.onGap=t}async save(e){this.batches.push(e),await this.prune()}take(e){return Promise.resolve(this.batches.slice(0,e))}remove(e){return this.batches=this.batches.filter(t=>t.id!==e),Promise.resolve()}bumpAttempts(e,t){let n=this.batches.find(t=>t.id===e);return n&&(n.attempts=t),Promise.resolve()}prune(){let e=Date.now()-this.limits.maxAgeMs,t={batches:0,records:0,reason:`expired`},n=this.batches.filter(t=>t.createdAt<e);this.batches=this.batches.filter(t=>t.createdAt>=e),t.batches+=n.length,t.records+=A(n);let r=this.batches.length-this.limits.maxBatches;if(r>0){t.reason=`over_capacity`;let e=this.batches.slice(0,r);this.batches=this.batches.slice(r),t.batches+=e.length,t.records+=A(e)}return t.batches>0&&this.onGap?.(t),Promise.resolve(t)}count(){return Promise.resolve(this.batches.length)}clear(){return this.batches=[],Promise.resolve()}close(){return this.batches=[],Promise.resolve()}},Oe={name:e.Zt,save:()=>Promise.resolve(),take:()=>Promise.resolve([]),remove:()=>Promise.resolve(),bumpAttempts:()=>Promise.resolve(),prune:()=>Promise.resolve({batches:0,records:0,reason:`expired`}),count:()=>Promise.resolve(0),clear:()=>Promise.resolve(),close:()=>Promise.resolve()};function ke(e){return e.guard(`storage.unavailable`,`reading indexedDB`,()=>globalThis.indexedDB!=null)===!0}function Ae(t){return t.guard(`storage.unavailable`,`probing localStorage`,()=>(localStorage.setItem(e.Qt,`1`),localStorage.removeItem(e.Qt),!0))===!0}async function je(e,t,n,r,i){if(e===`none`)return Oe;if(e===`memory`)return new j(n,i);if(e===`indexeddb`||e===`auto`){if(ke(r)){let e=await r.guardAsync(`storage.unavailable`,`opening IndexedDB`,async()=>{let{IndexedDbStorage:e}=await Promise.resolve().then(()=>require("./indexeddb-storage-DIJIbFnp.cjs"));return new e(t,n,r,i)});if(e)return e}if(e===`indexeddb`)return r.report(`storage.degraded`,`IndexedDB was asked for by name and is unavailable, using memory`),new j(n,i)}return Ae(r)?new De(n,r,i):(r.report(`storage.degraded`,`no persistent storage available, offline logs are memory only`),new j(n,i))}function M(e,t){if(e.length<=t)return e;let n=Me(e.charCodeAt(t-1))?t-1:t;return`${e.slice(0,n)}… [truncated ${String(e.length-n)} chars]`}function Me(e){return e>=55296&&e<=56319}function Ne(e){return`[Element ${(e.nodeName??`NODE`).toLowerCase()}${e.id?`#${e.id}`:``}${typeof e.className==`string`&&e.className?`.${e.className.trim().split(/\s+/).slice(0,3).join(`.`)}`:``}]`}function N(e,t){let n={bytes:0,nodes:0};return{value:F(e,t,new WeakSet,0,n),bytes:n.bytes}}function P(e,t){return t.bytes+=I(e)+2,e}function F(e,t,n,r,i){if(i.nodes++,i.nodes>t.maxNodes)return P(`[MaxNodes]`,i);if(e==null)return i.bytes+=4,e;if(typeof e==`string`)return P(M(e,t.maxAttributeChars),i);if(typeof e==`number`)return i.bytes+=8,Number.isFinite(e)?e:String(e);if(typeof e==`boolean`)return i.bytes+=5,e;if(typeof e==`bigint`)return P(`${e.toString()}n`,i);if(typeof e==`symbol`)return P(e.toString(),i);if(typeof e==`function`)return P(`[Function ${e.name===``?`anonymous`:e.name}]`,i);if(r>=t.maxDepth)return P(`[MaxDepth]`,i);if(n.has(e))return P(`[Circular]`,i);n.add(e),i.bytes+=2;try{if(e instanceof Error)return{name:P(e.name,i),message:P(M(e.message,t.maxAttributeChars),i),stack:e.stack?P(M(e.stack,t.maxStackChars),i):void 0,cause:e.cause?F(e.cause,t,n,r+1,i):void 0};if(e instanceof Date)return P(e.toISOString(),i);if(e instanceof RegExp)return P(e.toString(),i);if(e instanceof Map){let a=e,o={},s=0;for(let[e,c]of a){if(s>=t.maxArrayLength){o[`…`]=P(`[${String(a.size-t.maxArrayLength)} more entries]`,i);break}s++;let l=String(e);i.bytes+=I(l)+4,o[l]=F(c,t,n,r+1,i)}return o}if(e instanceof Set)return F([...e].slice(0,t.maxArrayLength),t,n,r,i);if(ArrayBuffer.isView(e)){let t=e.length??0;return P(`[${e.constructor.name}(${String(t)})]`,i)}if(e instanceof Promise)return P(`[Promise]`,i);if(typeof Node<`u`&&e instanceof Node)return P(Ne(e),i);if(Array.isArray(e)){let a=e,o=a.slice(0,t.maxArrayLength).map(e=>F(e,t,n,r+1,i));return a.length>t.maxArrayLength&&o.push(P(`[${String(a.length-t.maxArrayLength)} more items]`,i)),o}let a=e.toJSON;if(typeof a==`function`)return F(a.call(e),t,n,r+1,i);let o=e,s=Object.keys(o),c={},l=0;for(let e of s){if(l>=t.maxAttributeCount){c[`…`]=P(`[${String(s.length-l)} more keys]`,i);break}l++,i.bytes+=I(e)+4,c[e]=F(o[e],t,n,r+1,i)}return c}catch(e){return P(`[Unserializable: ${e instanceof Error?e.name:`error`}]`,i)}finally{n.delete(e)}}function I(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t}var Pe=class{deps;installed=!1;onVisibility=()=>{document.visibilityState===`hidden`&&this.flush(`hidden`)};onPageHide=()=>{this.flush(`pagehide`)};onFreeze=()=>{this.flush(`freeze`)};onOpenFinClose=()=>{this.flush(`openfin-close`)};constructor(e){this.deps=e}install(){if(this.installed||typeof addEventListener>`u`)return;this.installed=!0,typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze)),addEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`subscribing to close-requested`,()=>{e?.on?.(`close-requested`,this.onOpenFinClose)})}uninstall(){if(!this.installed)return;this.installed=!1,typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze)),removeEventListener(`pagehide`,this.onPageHide);let e=globalThis.fin?.me;this.deps.diagnostics.guard(`openfin.unavailable`,`releasing close-requested`,()=>{e?.removeListener?.(`close-requested`,this.onOpenFinClose)})}flush(t){let{diagnostics:n}=this.deps,r=this.endpointUrl();if(r===null)return;let i=this.deps.drainForExit();if(!i||i.records.length===0)return;let a=n.guard(`transport.serialize_failed`,`the ${t} exit flush could not serialize its batch`,()=>this.deps.config.serializer.serialize(i.records));if(!a)return;if(I(a.body)>6e4){we(i,n);return}r.searchParams.set(e._t,i.id),r.searchParams.set(e.vt,t);let o=r.toString();this.beacon(o,a.body)||this.keepaliveFetch(o,a.body,t)}endpointUrl(){let{endpoint:e}=this.deps.config;return e?this.deps.diagnostics.guard(`config.invalid`,`the exit flush cannot use endpoint ${e}`,()=>new URL(e))??null:null}beacon(t,n){return this.deps.diagnostics.guard(`transport.http_error`,`sendBeacon`,()=>{let r=globalThis.navigator;return r?.sendBeacon?r.sendBeacon(t,new Blob([n],{type:e.A})):!1})===!0}keepaliveFetch(t,n,r){let{config:i,diagnostics:a}=this.deps;a.guard(`transport.http_error`,`the keepalive fetch fallback`,()=>{fetch(t,{method:`POST`,body:n,headers:{[e.J]:e.A},credentials:i.credentials,keepalive:!0}).catch(e=>{a.report(`transport.http_error`,`the exit flush failed`,{reason:r},e)})})}};async function Fe(t){let n=globalThis.CompressionStream;if(n===void 0)return null;let r=new Blob([t]).stream().pipeThrough(new n(e.z)),i=await new Response(r).arrayBuffer();return new Uint8Array(i)}var L=class extends Error{kind;status;retryAfterMs;maxBytes;constructor(e,t,n,r,i){super(t),this.kind=e,this.status=n,this.retryAfterMs=r,this.maxBytes=i,this.name=`TransportError`}};function Ie(t){if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*e.ut);let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var Le=class{config;diagnostics;throttledUntil=0;constructor(e,t){this.config=e,this.diagnostics=t}async send(e){!this.config.endpoint||e.records.length===0||await this.post(e)}throttledForMs(){return Math.max(0,this.throttledUntil-Date.now())}async post(t){let{config:n}=this,r;try{r=n.serializer.serialize(t.records)}catch(e){this.diagnostics.report(`transport.serialize_failed`,`serializer threw, dropping the batch`,{batchId:t.id},e);return}let i=new Headers(await this.resolveHeaders());i.set(e.J,r.contentType),i.set(e.K,t.id),i.set(e.G,String(t.attempts));let a=await this.encodeBody(r.body);typeof a!=`string`&&i.set(e.q,e.z);let o=await this.dispatch(i,a);if(o.ok){this.throttledUntil=0;return}throw await this.classify(o,t.id)}async encodeBody(e){let{config:t}=this;return t.compression!==`gzip`||I(e)<1024?e:await this.diagnostics.guardAsync(`transport.http_error`,`gzipping the payload`,()=>Fe(e))??e}async dispatch(t,n){let{config:r}=this,i=new AbortController,a=setTimeout(()=>{i.abort()},e.xt);l(a);try{return await fetch(r.endpoint,{method:`POST`,headers:t,body:n,credentials:r.credentials,signal:i.signal,cache:`no-store`})}catch{if(i.signal.aborted)throw new L(`timeout`,`request exceeded ${String(e.xt)}ms`);let t=globalThis.navigator?.onLine;throw new L(t===!1?`offline`:`transient`,`network error`)}finally{clearTimeout(a)}}async classify(t,n){let r=t.status,i=Ie(t.headers.get(e.Y));if(r===401||r===403)return this.diagnostics.report(`transport.rejected_credentials`,`server returned ${String(r)}. In a cross-origin iframe the session cookie is a third-party cookie and is very likely blocked. Forward to the platform document instead of promoting to sender, or issue the cookie with the Partitioned attribute.`,{status:r,endpoint:this.config.endpoint}),new L(`permanent`,`rejected with ${String(r)}`,r);if(r===413)return new L(`too_large`,`payload too large`,r,void 0,await this.readMaxBytes(t));if(r===429||r===503){let e=r===429;return this.throttledUntil=Date.now()+(i??2e3),e&&this.diagnostics.report(`transport.throttled`,`server throttled us`,{retryAfterMs:i}),new L(`throttled`,e?`throttled`:`service unavailable`,r,i)}return r===408||r>=500?new L(`transient`,`server error ${String(r)}`,r):(this.diagnostics.report(`transport.dropped_permanent`,`server rejected the batch with ${String(r)}, dropping it`,{batchId:n,status:r}),new L(`permanent`,`rejected with ${String(r)}`,r))}async readMaxBytes(e){return this.diagnostics.guardAsync(`transport.http_error`,`reading the 413 body`,async()=>{let t=JSON.parse(await e.text());return typeof t.maxBytes==`number`?t.maxBytes:void 0})}async resolveHeaders(){let{headers:e}=this.config;return e?typeof e==`function`?await this.diagnostics.guardAsync(`transport.http_error`,`headers() threw`,()=>Promise.resolve(e()))??{}:e:{}}},Re=class{storage;transport;diagnostics;config;batchesPerDrain;timer=null;attempt=0;draining=!1;stopped=!1;onOnline=()=>{this.attempt=0,this.schedule(0)};constructor(e,t,n,r,i=20){this.storage=e,this.transport=t,this.diagnostics=n,this.config=r,this.batchesPerDrain=i}start(){this.stopped=!1,typeof addEventListener<`u`&&addEventListener(`online`,this.onOnline),this.schedule(e.It)}nudge(){this.draining||this.schedule(e.Ft)}stop(){this.stopped=!0,typeof removeEventListener<`u`&&removeEventListener(`online`,this.onOnline),this.clearTimer()}schedule(e){if(this.stopped)return;this.clearTimer();let t=setTimeout(()=>{this.drain()},e);this.timer=t,l(t)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}backoffMs(){let t=Math.min(e.Ft*2**this.attempt,e.Lt);return Math.random()*t}async drain(){if(!this.draining){this.draining=!0;try{await O(`ui-observability.drain`,this.diagnostics,()=>this.drainLocked())!==!0&&this.schedule(e.It)}finally{this.draining=!1}}}async drainLocked(){try{if(globalThis.navigator?.onLine===!1)return this.schedule(e.It),!0;let t=await this.storage.take(this.batchesPerDrain);if(t.length===0)return this.schedule(e.It),!0;for(let e of t)if(this.stopped||!await this.deliver(e))return!0;return this.schedule(t.length===this.batchesPerDrain?0:e.It),!0}catch(e){return this.diagnostics.report(`storage.degraded`,`the drain loop threw`,void 0,e),this.attempt++,this.schedule(this.backoffMs()),!0}}async deliver(t){if(t.attempts>=e.Kt.maxAttempts)return this.diagnostics.report(`storage.dead_lettered`,`giving up on a batch after ${t.attempts.toString()} attempts`,{batchId:t.id,records:t.records.length}),await this.storage.remove(t.id),!0;try{return await this.transport.send(t),await this.storage.remove(t.id),this.attempt=0,!0}catch(n){let r=n instanceof L?n:void 0;return r?.kind===`permanent`?(await this.storage.remove(t.id),!0):r?.kind===`too_large`?(await this.splitStored(t,r.maxBytes),!0):r?.kind===`offline`?(this.schedule(e.It),!1):(await this.storage.bumpAttempts(t.id,t.attempts+1),this.attempt++,this.schedule(r?.retryAfterMs??this.backoffMs()),!1)}}async splitStored(e,t){let n=be(e);if(await this.storage.remove(e.id),!n){this.diagnostics.report(`transport.dropped_permanent`,`a single record exceeds the server limit and was dropped`,{batchId:e.id,bodies:e.records.map(e=>e.body)});return}this.diagnostics.report(`transport.batch_split`,`the server refused the batch as too large`,{from:e.records.length,to:n[0].records.length,serverMaxBytes:t});for(let e of n)await this.storage.save(e)}},ze={TRACE:`debug`,DEBUG:`debug`,INFO:`info`,WARN:`warn`,ERROR:`error`,FATAL:`error`},Be=class{minLevel;diagnostics;constructor(e,t){this.minLevel=e,this.diagnostics=t}update(e){this.minLevel=e}write(t,n,r){if(this.minLevel===null||e.it[t]<e.it[this.minLevel]||typeof console>`u`)return;let i=`%c${e.at}%c ${t}`,a=ze[t];this.diagnostics.guard(`handler.threw`,`mirroring to console.${a}`,()=>{if(r===void 0){console[a](i,e.D,``,n);return}console[a](i,e.D,``,n,r)})}},Ve=class{value=0;next(){return++this.value}reset(){this.value=0}},He=/^[0-9a-f]{32}$/,Ue=/^[0-9a-f]{16}$/,R=/[1-9a-f]/;function We(){return import(`@opentelemetry/api`)}function Ge(e){return He.test(e.traceId)&&R.test(e.traceId)&&Ue.test(e.spanId)&&R.test(e.spanId)}function Ke(){return w(16)}function qe(){return w(8)}function z(){return{traceId:Ke(),spanId:qe(),traceFlags:1,startedAt:Date.now()}}function B(e){return{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}}var Je=class{diagnostics;maxAgeMs;load;ambient=z();otel;constructor(t,n=e.in,r=We){this.diagnostics=t,this.maxAgeMs=n,this.load=r}async loadOtel(){try{this.otel=await this.load()}catch(e){this.diagnostics.report(`trace.otel_failed`,`@opentelemetry/api is not available, so records carry this library's own trace ids`,void 0,e)}}resolve(){let e=this.activeSpanContext();return e===void 0?(Date.now()-this.ambient.startedAt>this.maxAgeMs&&this.rotate(`maxAge`),B(this.ambient)):e}activeSpanContext(){let e=this.otel;if(e)return this.diagnostics.guard(`trace.otel_failed`,`reading the active OpenTelemetry span`,()=>{let t=e.trace.getActiveSpan();if(t===void 0)return;let n=t.spanContext();if(Ge(n))return{traceId:n.traceId,spanId:n.spanId,traceFlags:n.traceFlags}})}rotate(e){return this.ambient=z(),B(this.ambient)}headers(){let t={},n=this.otel;if(n&&this.diagnostics.guard(`trace.otel_failed`,`injecting OpenTelemetry headers`,()=>{n.propagation.inject(n.context.active(),t)}),!t.traceparent){let n=this.resolve(),r=(n.traceFlags&255).toString(16).padStart(2,`0`);t[e.rn]=`00-${n.traceId}-${n.spanId}-${r}`}return t}},Ye=class{buffer;pointer=0;filled=!1;capacity;constructor(e){this.capacity=Math.max(e,1),this.buffer=Array(this.capacity)}push(e){this.buffer[this.pointer]=e,this.pointer=(this.pointer+1)%this.capacity,this.pointer===0&&(this.filled=!0)}snapshot(){return(this.filled?[...this.buffer.slice(this.pointer),...this.buffer.slice(0,this.pointer)]:this.buffer.slice(0,this.pointer)).filter(e=>e!==void 0)}clear(){this.buffer=Array(this.capacity),this.pointer=0,this.filled=!1}};function Xe(t){return e.ft.test(t)?Number(BigInt(t)/e.pt):Date.now()}function Ze(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:typeof e==`bigint`?e.toString():null}function Qe(e,t,n){let r=e[t];if(r===void 0){e[t]=n;return}if(Array.isArray(r)){r.push(n);return}e[t]=[r,n]}function V(e,t,n,r){let i=Ze(n);if(i!==null){Qe(e,t,i);return}if(!(typeof n!=`object`||!n||r.has(n))){if(r.add(n),Array.isArray(n))for(let i of n)V(e,t,i,r);else for(let[i,a]of Object.entries(n))V(e,`${t}.${i}`,a,r);r.delete(n)}}function H(e){let t=Object.create(null),n=new WeakSet;for(let[r,i]of Object.entries(e))V(t,r,i,n);return t}var $e={name:`ecs`,serialize(t){return{body:`${t.map(t=>{let n=Xe(t.timeUnixNano);return JSON.stringify({"@timestamp":new Date(n).toISOString(),message:t.body,log:{level:e.I[t.severityText]??t.severityText.toLowerCase()},trace:{id:t.traceId},span:{id:t.spanId},service:{name:t.resource[e.Ot],version:t.resource[e.kt],environment:t.resource[e.wt]},user_agent:{original:t.resource[e.St]},url:{full:t.attributes[`url.full`]??t.attributes[`page.url`]},labels:{...H(t.resource),...H(t.attributes)}})}).join(`
|
|
3
|
+
`)}\n`,contentType:e.k}}};function U(e){return e==null?null:typeof e==`string`?{stringValue:e}:typeof e==`boolean`?{boolValue:e}:typeof e==`number`?Number.isInteger(e)?{intValue:String(e)}:{doubleValue:e}:typeof e==`bigint`?{intValue:e.toString()}:Array.isArray(e)?{arrayValue:{values:e.map(U).filter(e=>e!==null)}}:typeof e==`object`?{kvlistValue:{values:W(e)}}:null}function W(e){let t=[];for(let[n,r]of Object.entries(e)){let e=U(r);e&&t.push({key:n,value:e})}return t}var et=new WeakMap;function tt(e){let t=et.get(e);if(t!==void 0)return t;let n=JSON.stringify(e);return et.set(e,n),n}var G={name:e.Bt,serialize(t){let n=new Map;for(let e of t){let t=tt(e.resource),r=n.get(t);if(r){r.records.push(e);continue}n.set(t,{resource:e.resource,records:[e]})}let r=[...n.values()].map(t=>({resource:{attributes:W(t.resource)},scopeLogs:[{scope:{name:e.tn,version:e.nn},logRecords:t.records.map(e=>({timeUnixNano:e.timeUnixNano,observedTimeUnixNano:e.observedTimeUnixNano??e.timeUnixNano,severityNumber:e.severityNumber,severityText:e.severityText,body:{stringValue:e.body},traceId:e.traceId,spanId:e.spanId,flags:e.traceFlags,attributes:W(e.attributes)}))}]}));return{body:JSON.stringify({resourceLogs:r}),contentType:e.O}}};function nt(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function rt(t,n,r){return t===void 0?n??G:t===`otlp`?G:t===`ecs`?$e:nt(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Bt}", "ecs" or an implementation`),G)}function it(t,n){return t===void 0?n:t===!1?null:t===!0?e.E:t}function at(t,n,r){let i=r??e.j,a={...i,...t,serializer:rt(t.serializer,r?.serializer,n),console:it(t.console,i.console),sampling:{...i.sampling,...t.sampling,rates:{...i.sampling.rates,...t.sampling?.rates}},bus:{...i.bus,...t.bus},capture:{...i.capture,...t.capture}};if(!a.endpoint)n.report(`config.invalid`,`endpoint is missing. Records will be built and dropped, never sent.`);else try{new URL(a.endpoint)}catch(e){n.report(`config.invalid`,`endpoint is not a valid absolute URL: ${a.endpoint}`,void 0,e)}a.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record will report service.name as '${e.cn}'.`),e.cn);let o=a.sampling.defaultRate;(typeof o!=`number`||o<0||o>1)&&(n.report(`config.invalid`,`sampling.defaultRate must be 0..1, got ${String(o)}`),a.sampling.defaultRate=1);let s=Object.entries(a.sampling.rates);for(let[e,t]of s)(typeof t!=`number`||t<0||t>1)&&(n.report(`config.invalid`,`sampling.rates["${e}"] must be 0..1, got ${String(t)}`),a.sampling.rates[e]=1);return a.capture.ignoreUrls=a.capture.ignoreUrls.filter(e=>e!==r?.endpoint),a.endpoint&&!a.capture.ignoreUrls.includes(a.endpoint)&&(a.capture.ignoreUrls=[...a.capture.ignoreUrls,a.endpoint]),ot(t,n),a}function ot(t,n){let r=new Set([...Object.keys(e.j),...e.on]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`unknown config key "${e}", ignored. Typo?`);for(let r of e.T){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.j[r]),...e.sn[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`unknown config key "${r}.${e}", ignored. Typo?`)}}function st(t,n){for(let r of Object.keys(n))e.T.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.T)Object.assign(t[r],n[r])}var ct=class{map=new Map;set(e,t){this.map.set(e,t)}setMany(e){for(let[t,n]of Object.entries(e))this.map.set(t,n)}get(e){return this.map.get(e)}remove(e){this.map.delete(e)}clear(){this.map.clear()}getAll(){return Object.fromEntries(this.map)}},lt=class{handler;throttleMs;counters=new Map;lastEmitted=new Map;constructor(t,n=e.N){this.handler=t,this.throttleMs=n}setHandler(e){this.handler=e}count(e,t=1){let n=(this.counters.get(e)??0)+t;return this.counters.set(e,n),n}report(t,n,r,i){let a=this.count(t),o=Date.now();if(o-(this.lastEmitted.get(t)??0)<this.throttleMs)return;this.lastEmitted.set(t,o);let s={code:t,message:n,detail:r,cause:i,at:o,count:a};if(this.handler)try{this.handler(s)}catch(t){this.count(`handler.threw`),typeof console<`u`&&console.warn(`${e.at} onDiagnostic handler threw`,t)}}guard(e,t,n){try{return n()}catch(n){this.report(e,t,void 0,n);return}}async guardAsync(e,t,n){try{return await n()}catch(n){this.report(e,t,void 0,n);return}}snapshot(){return Object.fromEntries(this.counters)}reset(){this.counters.clear(),this.lastEmitted.clear()}},ut={maxAgeMs:e.tt,endOnOwnerClose:!1,urlParam:e.rt};function K(e,t){let n=Reflect.get(e,t);return typeof n==`string`&&n!==``?n:void 0}function dt(e,t){let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function ft(e){if(typeof e!=`object`||!e)return null;let t=K(e,`id`),n=K(e,`name`),r=dt(e,`startedAt`);return t===void 0||n===void 0||r===void 0?null:{id:t,name:n,startedAt:r,parentId:K(e,`parentId`),ownerContextId:K(e,`ownerContextId`)??``}}function pt(e){if(typeof e!=`object`||!e)return null;let t=K(e,`i`),n=K(e,`n`);return t===void 0||n===void 0?null:{id:t,name:n,startedAt:dt(e,`s`)??Date.now(),parentId:void 0,ownerContextId:``}}function mt(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.g,`-`).replace(e._,`_`).replace(e.h,``)}function ht(e,t){let n=new Promise((e,n)=>{l(setTimeout(()=>{n(Error(`timed out after ${String(t)}ms`))},t))});return Promise.race([e,n])}var gt=class{options;diagnostics;contextId;onLocalChange;journey=null;expiryTimer=null;constructor(e,t,n,r){this.options=e,this.diagnostics=t,this.contextId=n,this.onLocalChange=r}current(){return this.journey}async bootstrap(){let t=this.readUrlToken();if(t&&this.adopt(t,`url`))return;let n=this.diagnostics.guard(`storage.unavailable`,`reading the persisted journey`,()=>sessionStorage.getItem(e.nt));if(n&&this.restore(n))return;let r=await this.readOpenFinToken();r!==null&&this.adopt(r,`openfin.customData`)}start(e,t={}){let n={id:t.id??T(),name:e,startedAt:Date.now(),parentId:t.parent?this.journey?.id:void 0,ownerContextId:this.contextId};return this.setJourney(n),this.onLocalChange(n),n}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=mt(e);if(t.length>256){this.diagnostics.report(`journey.token_too_large`,`journey token exceeded the size cap and was not issued`,{length:t.length});return}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`,`discarded a seeded journey older than maxAgeMs`,{source:t,name:r.name}),!1):(this.setJourney(r),this.diagnostics.report(`journey.adopted`,`adopted 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=ft(this.diagnostics.guard(`storage.degraded`,`parsing the persisted journey`,()=>JSON.parse(e)));return t===null?!1:Date.now()-t.startedAt>this.options.maxAgeMs?(this.diagnostics.report(`journey.expired`,`discarded a persisted journey older than maxAgeMs`,{name:t.name}),this.clearStored(),!1):(this.setJourney(t),this.diagnostics.report(`journey.adopted`,`resumed journey "${t.name}"`,{source:`sessionStorage`,journeyId:t.id}),!0)}decodeToken(t){return this.diagnostics.guard(`config.invalid`,`decoding a seeded journey token`,()=>{let n=t.replace(e.p,`+`).replace(e.m,`/`),r=(4-n.length%4)%4,i=`=`.repeat(r),a=Uint8Array.from(atob(n+i),e=>e.charCodeAt(0));return pt(JSON.parse(new TextDecoder().decode(a)))})??null}setJourney(t){if(this.journey=t,this.clearTimer(),this.diagnostics.guard(`storage.unavailable`,`persisting the journey`,()=>{t===null?sessionStorage.removeItem(e.nt):sessionStorage.setItem(e.nt,JSON.stringify(t))}),t===null)return;let n=Math.max(this.options.maxAgeMs-(Date.now()-t.startedAt),0),r=setTimeout(()=>{this.diagnostics.report(`journey.expired`,`journey "${t.name}" hit maxAgeMs and was ended automatically`,{journeyId:t.id}),this.journey=null,this.expiryTimer=null,this.clearStored()},n);this.expiryTimer=r,l(r)}clearStored(){this.diagnostics.guard(`storage.unavailable`,`clearing the persisted journey`,()=>{sessionStorage.removeItem(e.nt)})}clearTimer(){this.expiryTimer!==null&&(clearTimeout(this.expiryTimer),this.expiryTimer=null)}readUrlToken(){return this.diagnostics.guard(`config.invalid`,`reading the journey token from the URL`,()=>typeof location>`u`?null:new URL(location.href).searchParams.get(this.options.urlParam))??null}async readOpenFinToken(){let t=globalThis.fin?.me,n=t?.getOptions;if(n===void 0)return null;let r=(await this.diagnostics.guardAsync(`openfin.unavailable`,`reading fin.me.getOptions()`,()=>ht(n.call(t),e.ht)))?.customData?.[e.mt];return typeof r==`string`?r:null}};function _t(t){let n=e.H;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,e.U);return n>>>0}function q(e,t){let n=e.attributes[t];return typeof n==`string`?n:``}function vt(e,t){let{rates:n,defaultRate:r}=t.sampling,i,a=-1;for(let[t,r]of Object.entries(n))(e===t||e.startsWith(`${t}.`))&&t.length>a&&(i=r,a=t.length);return i??r}function yt(t,n){if(t.level===`ERROR`||t.level===`FATAL`||n.sampling.alwaysSampleTypes.includes(t.type))return!0;let r=vt(t.namespace,n);return r>=1?!0:r<=0?!1:_t(t.journeyId||t.traceId)/e.an<r}function bt(t,n){return yt({level:t.severityText,type:q(t,e.l),namespace:q(t,e.n),journeyId:q(t,e.a),traceId:t.traceId},n)}var xt=class{windowStart=0;count=0;allow(e){if(e.severityText!==`ERROR`&&e.severityText!==`FATAL`)return!0;let t=Date.now();return t-this.windowStart>1e4&&(this.windowStart=t,this.count=0),this.count++,this.count<=500}};function St(t){return t.attributes[e.l]===e.st}var Ct={logs:{flushIntervalMs:e.ot,batchSize:100},metrics:{flushIntervalMs:e.lt,batchSize:500}},wt=class{options;onFlush;pending=[];timer=null;constructor(e,t){this.options=e,this.onFlush=t}add(e){if(this.pending.push(e),this.pending.length>=this.options.batchSize){this.onFlush(this);return}this.arm()}take(){this.clearTimer();let e=this.pending;return this.pending=[],e}stop(){this.clearTimer()}arm(){if(this.timer!==null)return;let e=setTimeout(()=>{this.timer=null,this.onFlush(this)},this.options.flushIntervalMs);this.timer=e,l(e)}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},Tt=class{transport;storage;retry;diagnostics;streams;unconfirmed=new Map;queue=[];ceiling=new xt;inFlight=0;pumpScheduled=!1;stopped=!1;constructor(e,t,n,r,i=Ct){this.transport=e,this.storage=t,this.retry=n,this.diagnostics=r;let a=e=>{this.claim(e)};this.streams={logs:new wt(i.logs,a),metrics:new wt(i.metrics,a)}}push(e){this.stopped||(e.observedTimeUnixNano=he(),this.route(e))}drainPending(){return this.toBatch([...this.streams.metrics.take(),...this.streams.logs.take()])}drainForExit(){let e=[...this.unconfirmed.values()].flatMap(e=>e.records);return this.unconfirmed.clear(),this.toBatch([...e,...this.streams.metrics.take(),...this.streams.logs.take()])}destroy(){this.stopped=!0,this.streams.logs.stop(),this.streams.metrics.stop(),this.queue.length=0}toBatch(e){return e.length===0?null:{id:T(),records:e,createdAt:Date.now(),attempts:0}}route(e){try{let t=St(e)?this.streams.metrics:this.streams.logs;if(!this.ceiling.allow(e)){this.diagnostics.count(`record.dropped_by_ceiling`);return}t.add(e)}catch(e){this.diagnostics.report(`pipeline.crashed`,`a record was dropped on its way into a stream`,void 0,e)}}claim(e){let t=e.take(),n={id:T(),records:t,createdAt:Date.now(),attempts:0};this.unconfirmed.set(n.id,n),this.enqueue(n)}enqueue(e){this.queue.push(e),!this.pumpScheduled&&(this.pumpScheduled=!0,queueMicrotask(()=>{this.pumpScheduled=!1,this.pump()}))}pump(){for(;this.inFlight<2;){let e=this.queue.shift();if(!e)return;this.inFlight++,this.run(e)}}async run(e){try{await this.dispatch(e)}catch(t){this.diagnostics.report(`pipeline.crashed`,`dispatch rejected, which it is written never to do`,{batchId:e.id},t)}finally{this.inFlight--,this.pump()}}async dispatch(e){try{let t=this.transport.throttledForMs();if(t>0){await this.store(e),this.diagnostics.report(`transport.throttled`,`stored the batch rather than sending it`,{batchId:e.id,records:e.records.length,throttledMs:t});return}try{await this.transport.send(e)}catch(t){await this.store({...e,attempts:e.attempts+1}),this.diagnostics.report(`transport.http_error`,`batch was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}finally{this.unconfirmed.delete(e.id)}}async store(e){await this.diagnostics.guardAsync(`storage.degraded`,`persisting an undelivered batch`,async()=>{await this.storage.save(e),this.retry.nudge()})}};function J(e){return e}var Et=class{deps;resourceCache=null;constructor(e){this.deps=e}invalidateResource(){this.resourceCache=null}isEnabled(t){let{config:n}=this.deps;return n.enabled?e.it[t]>=e.it[n.minLevel]:!1}build(t){let{config:n,diagnostics:r,tracing:i,journey:a,sequence:o,limits:s}=this.deps;if(!this.isEnabled(t.level))return r.count(`record.dropped_by_level`),{record:null,dropped:`level`};let c=i.resolve(),l=a.current();if(!yt({level:t.level,type:t.type,namespace:t.namespace,journeyId:l?.id??``,traceId:c.traceId},n))return r.count(`record.dropped_by_sampling`),{record:null,dropped:`sampling`};let u=o.next(),d=ce(),f=n.capture.fullUrls?d:b(d),p,m=0;try{let e=N(this.deps.context.getAll(),s),n=N(t.scoped??{},s),r=N(t.payload??{},s);m=e.bytes+n.bytes+r.bytes,p={...J(e.value),...J(n.value),...J(r.value)}}catch(t){r.report(`record.sanitize_failed`,`attributes could not be sanitized`,void 0,t),p={[e.d]:!0}}p[e.l]=t.type,p[e.c]=u,p[e.n]=t.namespace,p[e.u]=f,l&&(p[e.a]=l.id,p[e.o]=l.name,l.parentId!==void 0&&(p[e.s]=l.parentId));let h=M(t.body,s.maxBodyChars);h!==t.body&&r.count(`record.truncated`);let g={timeUnixNano:he(),traceId:c.traceId,spanId:c.spanId,traceFlags:c.traceFlags,severityNumber:e.Wt[t.level],severityText:t.level,body:h,attributes:p,resource:this.resource()},_=n.redact;if(_){let e=r.guard(`record.sanitize_failed`,`redact hook threw`,()=>_(g));if(e===null)return r.count(`record.dropped_by_redact`),{record:null,dropped:`redact`};if(e!==void 0&&e!==g){if(ge(e)){let t=N(e.attributes,s);g={...e,attributes:J(t.value)},m=t.bytes}else r.report(`record.sanitize_failed`,`redact hook returned something that is not a record, keeping the original`)}}if(m>s.maxRecordBytes){r.report(`record.truncated`,`attributes exceeded the size budget and were dropped`,{bytes:m,body:g.body});let n={[e.l]:t.type,[e.c]:u,[e.n]:t.namespace,[e.u]:f,[e.i]:!0,[e.r]:m};l&&(n[e.a]=l.id,n[e.o]=l.name),g.attributes=n}return{record:g}}resource(){if(this.resourceCache)return this.resourceCache;let{config:t,identity:n,platform:r}=this.deps;return this.resourceCache={[e.Ot]:t.serviceName,[e.kt]:t.serviceVersion,[e.wt]:t.environment,[e.Nt]:e.tn,[e.Pt]:e.nn,[e.Mt]:e.en,[e.Tt]:r.platform,[e.At]:n.sessionId,[e.jt]:n.tabId,[e.Ct]:n.contextId,[e.St]:r.userAgent,...r.openfinUuid===void 0?{}:{[e.Dt]:r.openfinUuid},...r.openfinName===void 0?{}:{[e.Et]:r.openfinName}},this.resourceCache}},Y=Symbol.for(e.Rt),X=class t{diagnostics;config;platform;identity;sessionTouch;context=new ct;breadcrumbs;tracing;sequence=new Ve;journey;builder;console;bus;storage;storageBuiltAs;transport;retry;pipeline;exitFlush;captures=[];bootBuffer=[];forwardBuffer=[];forwardScheduled=!1;ready=!1;destroyed=!1;lastGapAt=0;constructor(t){this.diagnostics=new lt(t.onDiagnostic),this.platform=ae(this.diagnostics),this.config=at(t,this.diagnostics),this.identity=ve(this.diagnostics),this.sessionTouch=new ye(this.diagnostics),this.breadcrumbs=new Ye(50),this.tracing=new Je(this.diagnostics,void 0,this.config.otelLoader),this.tracing.loadOtel(),this.console=new Be(this.config.console,this.diagnostics),this.journey=new gt(ut,this.diagnostics,this.identity.contextId,e=>{this.bus.broadcastJourney(e)}),this.builder=new Et({config:this.config,limits:e.bt,diagnostics:this.diagnostics,context:this.context,journey:this.journey,tracing:this.tracing,sequence:this.sequence,identity:this.identity,platform:this.platform}),this.bus=new ie(this.config,this.diagnostics,this.platform,this.identity.contextId,this.identity.tabId,{onRecords:e=>{this.ingestForwarded(e)},onJourney:e=>{this.journey.applyRemote(e)},onJourneyRequest:()=>this.journey.current(),onTabConflict:()=>{this.regenerateTabId()}})}busAccept=(e,t)=>{this.destroyed||this.diagnostics.guard(`bus.send_failed`,`accepting a direct message from a child`,()=>{this.bus.acceptDirect(e,t)})};static current(){return globalThis[Y]??null}static configure(e){let n=t.current();if(n&&!n.destroyed)return n.reconfigure(e),n;let r=new t(e);return globalThis[Y]=r,r.init(),r}reconfigure(e){st(this.config,at(e,this.diagnostics,this.config)),this.diagnostics.setHandler(this.config.onDiagnostic),this.builder.invalidateResource(),this.console.update(this.config.console),this.keepBuiltStorage(),this.ready&&this.reinstallCaptures(),this.diagnostics.report(`config.reconfigured`,`configure() was called again, the existing runtime was updated`)}keepBuiltStorage(){let e=this.storageBuiltAs;e!==void 0&&this.config.storage!==e&&(this.diagnostics.report(`config.invalid`,`storage cannot change after startup, still ${e}`,{requested:this.config.storage}),this.config.storage=e)}async init(){try{let e=this.journey.bootstrap();await this.bus.start()===`sender`&&await this.becomeSender(),await e,this.installCaptures()}catch(e){this.diagnostics.report(`pipeline.crashed`,`startup failed, continuing in a degraded state`,void 0,e)}finally{this.ready=!0,this.releaseBootBuffer()}}async becomeSender(){this.storageBuiltAs=this.config.storage,this.storage=await je(this.config.storage,e.Gt,e.Kt,this.diagnostics,this.reportGap),this.transport=new Le(this.config,this.diagnostics),this.retry=new Re(this.storage,this.transport,this.diagnostics,this.config),this.pipeline=new Tt(this.transport,this.storage,this.retry,this.diagnostics),this.exitFlush=new Pe({config:this.config,diagnostics:this.diagnostics,drainForExit:()=>this.pipeline?.drainForExit()??null}),await Te(this.storage,this.diagnostics),this.retry.start(),this.exitFlush.install()}installCaptures(){let t={config:this.config,diagnostics:this.diagnostics,breadcrumbs:this.breadcrumbs,tracing:this.tracing,logger:new c(this,e.C)},n=this.config.capture;(n.errors||n.rejections||n.resourceErrors)&&this.captures.push(new le(t)),(n.fetch||n.xhr)&&this.captures.push(new fe(t)),(n.interactions||n.navigation)&&this.captures.push(new de(t)),n.webVitals&&this.captures.push(new me(t));for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`installing ${e.name}`,()=>{e.install()})}reinstallCaptures(){for(let e of this.captures)this.diagnostics.guard(`capture.install_failed`,`uninstalling ${e.name}`,()=>{e.uninstall()});this.captures.length=0,this.installCaptures()}registerWorker(e){this.destroyed||this.diagnostics.guard(`bus.send_failed`,`registering a worker`,()=>{this.bus.attachWorker(e)})}async destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.captures)e.uninstall();this.captures.length=0,this.exitFlush?.flush(`shutdown`),this.exitFlush?.uninstall(),this.retry?.stop(),this.pipeline?.destroy(),this.journey.destroy(),this.bus.destroy(),this.forwardBuffer=[],await this.storage?.close(),t.current()===this&&Reflect.deleteProperty(globalThis,Y)}}emit(e){if(!(!e||this.destroyed)){if(this.sessionTouch.touch(this.identity.sessionId),!this.ready){this.bootBuffer.length>=500&&(this.bootBuffer.shift(),this.diagnostics.count(`record.dropped_boot_buffer_full`)),this.bootBuffer.push(e);return}this.route(e)}}route(e){if(this.bus.getRole()===`forwarder`){this.forward(e);return}this.pipeline?.push(e)}forward(e){this.forwardBuffer.push(e),!this.forwardScheduled&&(this.forwardScheduled=!0,queueMicrotask(()=>{this.forwardScheduled=!1;let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e)}))}ingestForwarded(e){if(!Array.isArray(e)){this.diagnostics.count(`record.dropped_malformed`);return}for(let t of e){if(!ge(t)){this.diagnostics.count(`record.dropped_malformed`);continue}if(!bt(t,this.config)){this.diagnostics.count(`record.dropped_by_sampling`);continue}this.pipeline?.push(t)}}releaseBootBuffer(){let e=this.bootBuffer;this.bootBuffer=[];let t=this.journey.current();for(let n of e)t&&!n.attributes[`journey.id`]&&(n.attributes[`journey.id`]=t.id,n.attributes[`journey.name`]=t.name),this.route(n)}reportGap=t=>{let n=Date.now();n-this.lastGapAt<6e4||(this.lastGapAt=n,new c(this,e.qt).warn(`stored records were dropped before delivery`,{"gap.batches":t.batches,"gap.records":t.records,"gap.reason":t.reason}))};regenerateTabId(){let t=T();this.diagnostics.report(`bus.role_resolved`,`another context claimed this tab id, most likely a duplicated tab. Regenerating.`,{was:this.identity.tabId,now:t}),this.identity.tabId=t,this.diagnostics.guard(`storage.unavailable`,`persisting the new tab id`,()=>{sessionStorage.setItem(e.$t,t)}),this.builder.invalidateResource()}async queueDepth(){return await this.diagnostics.guardAsync(`storage.degraded`,`counting the batches waiting in storage`,()=>this.storage?.count()??Promise.resolve(0))??0}async flush(){if(this.bus.getRole()===`forwarder`){let e=this.forwardBuffer;this.forwardBuffer=[],e.length>0&&this.bus.sendRecords(e);return}let e=this.pipeline?.drainPending();if(!(!e||!this.transport))try{await this.transport.send(e)}catch(t){await this.diagnostics.guardAsync(`storage.degraded`,`persisting the batch drained by flush()`,async()=>{await this.storage?.save({...e,attempts:1}),this.retry?.nudge()}),this.diagnostics.report(`transport.http_error`,`the batch drained by flush() was stored for retry instead of being delivered`,{batchId:e.id,records:e.records.length},t)}}},Z=new Map;function Q(){return X.current()||X.configure({})}function Dt(e){X.configure(e),Z.clear()}function Ot(e,t){if(t)return new c(Q(),e,t);let n=Z.get(e);return n||(n=new c(Q(),e),Z.set(e,n)),n}function $(){return Ot(`app`)}function kt(e,t){$().trace(e,t)}function At(e,t){$().debug(e,t)}function jt(e,t){$().info(e,t)}function Mt(e,t){$().warn(e,t)}function Nt(e,t,n){$().error(e,t,n)}function Pt(e,t){$().logAction(e,t)}function Ft(e,t){$().logEvent(e,t)}function It(e,t,n,r,i){$().logMetric(e,t,n,r,i)}function Lt(e,t,n){return $().timeSync(e,t,n)}function Rt(e,t,n){return $().timeAsync(e,t,n)}function zt(e,t){Q().context.set(e,t)}function Bt(e){Q().context.setMany(e)}function Vt(e){Q().context.remove(e)}function Ht(e,t){return Q().journey.start(e,t)}function Ut(){Q().journey.end()}function Wt(){return Q().journey.current()}function Gt(){return Q().journey.getToken()}function Kt(e){return Q().journey.adopt(e,`manual`,!0)}function qt(e){Q().registerWorker(e)}function Jt(){Q().tracing.rotate(`explicit`)}function Yt(){return Q().tracing.headers()}function Xt(){return Q().flush()}function Zt(){return Q().queueDepth()}function Qt(){return Q().diagnostics.snapshot()}async function $t(){let e=X.current();Z.clear(),await e?.destroy()}exports.OneLogger=c,exports.adoptJourney=Kt,exports.configure=Dt,exports.currentJourney=Wt,exports.debug=At,exports.endJourney=Ut,exports.error=Nt,exports.flush=Xt,exports.getDiagnosticCounters=Qt,exports.getJourneyToken=Gt,exports.getLogger=Ot,exports.getQueueDepth=Zt,exports.getTraceHeaders=Yt,exports.info=jt,exports.logAction=Pt,exports.logEvent=Ft,exports.logMetric=It,exports.registerWorker=qt,exports.removeContext=Vt,exports.setContext=zt,exports.setContextMap=Bt,exports.shutdown=$t,exports.startJourney=Ht,exports.startTrace=Jt,exports.timeAsync=Rt,exports.timeSync=Lt,exports.trace=kt,exports.warn=Mt;
|
|
4
4
|
//# sourceMappingURL=index.cjs.map
|