@corbado/observe 1.7.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/analysis/client.mjs +1877 -0
  2. package/dist/analysis/config-manager.mjs +108 -0
  3. package/dist/analysis/config.mjs +216 -0
  4. package/dist/analysis/device-info-manager.mjs +168 -0
  5. package/dist/analysis/device.mjs +640 -0
  6. package/dist/analysis/handoff.mjs +7 -0
  7. package/dist/analysis/index.mjs +118 -0
  8. package/dist/analysis/logger.mjs +50 -0
  9. package/dist/analysis/low-events/capture-sequence.mjs +11 -0
  10. package/dist/analysis/low-events/ceremony-initiator.mjs +26 -0
  11. package/dist/analysis/low-events/form-input-binding.mjs +46 -0
  12. package/dist/analysis/low-events/grouped-input-tracker.mjs +248 -0
  13. package/dist/analysis/low-events/input-change-recorder.mjs +200 -0
  14. package/dist/analysis/low-events/input-tracker.mjs +302 -0
  15. package/dist/analysis/low-events/otp-input-binding.mjs +67 -0
  16. package/dist/analysis/low-events/shared-window-observer.mjs +296 -0
  17. package/dist/analysis/low-events/sink.mjs +0 -0
  18. package/dist/analysis/low-events/viewport-batcher.mjs +42 -0
  19. package/dist/analysis/low-events/window-tracker.mjs +40 -0
  20. package/dist/analysis/queue.mjs +954 -0
  21. package/dist/analysis/readers/device.mjs +73 -0
  22. package/dist/analysis/readers/input-paste.mjs +91 -0
  23. package/dist/analysis/readers/input.mjs +61 -0
  24. package/dist/analysis/readers/loader-global.mjs +15 -0
  25. package/dist/analysis/readers/meta.mjs +18 -0
  26. package/dist/analysis/readers/network.mjs +14 -0
  27. package/dist/analysis/readers/page.mjs +30 -0
  28. package/dist/analysis/readers/password-manager-dom.mjs +112 -0
  29. package/dist/analysis/readers/password-manager-extensions.mjs +247 -0
  30. package/dist/analysis/readers/private-mode.mjs +9 -0
  31. package/dist/analysis/readers/storage.mjs +28 -0
  32. package/dist/analysis/readers/web-lock.mjs +56 -0
  33. package/dist/analysis/readers/window-events.mjs +48 -0
  34. package/dist/analysis/storage/index.mjs +249 -0
  35. package/dist/analysis/storage/migration.mjs +56 -0
  36. package/dist/analysis/store/event-store.mjs +132 -0
  37. package/dist/analysis/transport.mjs +0 -0
  38. package/dist/analysis/transports/fetch.mjs +150 -0
  39. package/dist/analysis/types.mjs +25 -0
  40. package/dist/analysis/utils/appconfirmation-operation-full.mjs +19 -0
  41. package/dist/analysis/utils/blocked-user-agents.mjs +37 -0
  42. package/dist/analysis/utils/captcha-operation-full.mjs +17 -0
  43. package/dist/analysis/utils/email-link-continuity.mjs +50 -0
  44. package/dist/analysis/utils/email-link-operation-full.mjs +162 -0
  45. package/dist/analysis/utils/email-otp-operation-full.mjs +38 -0
  46. package/dist/analysis/utils/form-operation-full.mjs +80 -0
  47. package/dist/analysis/utils/key-operation-full.mjs +38 -0
  48. package/dist/analysis/utils/normalize-error.mjs +29 -0
  49. package/dist/analysis/utils/operation-full-provide-identifier-with-cui.mjs +46 -0
  50. package/dist/analysis/utils/operation-full.mjs +235 -0
  51. package/dist/analysis/utils/passkey-deletion-operation-full.mjs +17 -0
  52. package/dist/analysis/utils/passkey-enrollment-operation-full.mjs +35 -0
  53. package/dist/analysis/utils/passkey-login-operation-full.mjs +39 -0
  54. package/dist/analysis/utils/password-enrollment-operation-full.mjs +27 -0
  55. package/dist/analysis/utils/password-login-operation-full.mjs +65 -0
  56. package/dist/analysis/utils/password-manager-sampler.mjs +170 -0
  57. package/dist/analysis/utils/provide-data-operation-full.mjs +28 -0
  58. package/dist/analysis/utils/serialize-raw-error.mjs +205 -0
  59. package/dist/analysis/utils/sms-otp-operation-full.mjs +38 -0
  60. package/dist/analysis/utils/social-operation-login.mjs +17 -0
  61. package/dist/analysis/utils/source-path.mjs +39 -0
  62. package/dist/analysis/utils/sso-operation-login.mjs +37 -0
  63. package/dist/analysis/utils/totp-operation-full.mjs +34 -0
  64. package/dist/analysis/utils/trusted-device-operation-full.mjs +100 -0
  65. package/dist/analysis/utils/webauthn-payloads.mjs +101 -0
  66. package/dist/analysis/version.mjs +7 -0
  67. package/dist/cdn/script.global.js +4 -4
  68. package/dist/index.d.mts +285 -21
  69. package/dist/index.d.ts +285 -21
  70. package/dist/index.js +4 -4
  71. package/dist/index.mjs +4 -4
  72. package/package.json +10 -3
  73. package/tools/reader-meta-text.d.mts +2 -0
  74. package/tools/reader-meta-text.mjs +26 -0
  75. package/tools/strip-reader-meta.d.mts +33 -0
  76. package/tools/strip-reader-meta.mjs +131 -0
@@ -0,0 +1,1877 @@
1
+ // src/client.ts
2
+ import {
3
+ KeySigningOperationFull,
4
+ KeyRegistrationOperationFull
5
+ } from "./utils/key-operation-full.mjs";
6
+ import { reserveCaptureSeq } from "./low-events/capture-sequence.mjs";
7
+ import { readSourcePath } from "./readers/page.mjs";
8
+ import { readUserAgent } from "./readers/device.mjs";
9
+ import { SharedWindowObserver, getCapturePageId } from "./low-events/shared-window-observer.mjs";
10
+ import {
11
+ AuthEventName
12
+ } from "./types.mjs";
13
+ import { FetchTransport } from "./transports/fetch.mjs";
14
+ import { RequestQueue } from "./queue.mjs";
15
+ import { DeviceCollector } from "./device.mjs";
16
+ import { DeviceInfoManager } from "./device-info-manager.mjs";
17
+ import {
18
+ CookieStorage,
19
+ LocalStorage,
20
+ namespacedKey,
21
+ NamespacedStorage,
22
+ SessionStorage
23
+ } from "./storage/index.mjs";
24
+ import { OUTBOX_LOCK_NAME } from "./store/event-store.mjs";
25
+ import { migrateLegacyStorage } from "./storage/migration.mjs";
26
+ import {
27
+ DEFAULT_RELIABILITY_CONFIG,
28
+ resolveFixedDataConfig,
29
+ resolveReliabilityConfig
30
+ } from "./config.mjs";
31
+ import { ConfigManager } from "./config-manager.mjs";
32
+ import { v7 as uuidv7 } from "uuid";
33
+ import { PasskeyLoginOperationFull } from "./utils/passkey-login-operation-full.mjs";
34
+ import { EmailOtpOperationFull } from "./utils/email-otp-operation-full.mjs";
35
+ import { SmsOtpOperationFull } from "./utils/sms-otp-operation-full.mjs";
36
+ import { isBlockedUserAgent } from "./utils/blocked-user-agents.mjs";
37
+ import { hasWebLocks, withWebLock } from "./readers/web-lock.mjs";
38
+ import { SDK_NAME, SDK_VERSION } from "./version.mjs";
39
+ import {
40
+ EmailLinkContinuationOperation,
41
+ EmailLinkOperationFull
42
+ } from "./utils/email-link-operation-full.mjs";
43
+ import {
44
+ PasskeyEnrollmentOperationFull
45
+ } from "./utils/passkey-enrollment-operation-full.mjs";
46
+ import { createLogger } from "./logger.mjs";
47
+ import { PasskeyDeletionOperationFull } from "./utils/passkey-deletion-operation-full.mjs";
48
+ import { PasswordLoginOperationFull } from "./utils/password-login-operation-full.mjs";
49
+ import { PasswordEnrollmentOperationFull } from "./utils/password-enrollment-operation-full.mjs";
50
+ import {
51
+ OperationFullProvideIdentifierWithCUI
52
+ } from "./utils/operation-full-provide-identifier-with-cui.mjs";
53
+ import { SocialLoginOperationFull } from "./utils/social-operation-login.mjs";
54
+ import { SsoLoginOperationFull } from "./utils/sso-operation-login.mjs";
55
+ import { TotpOperationFull } from "./utils/totp-operation-full.mjs";
56
+ import { AppConfirmationOperationFull } from "./utils/appconfirmation-operation-full.mjs";
57
+ import { CaptchaOperationFull } from "./utils/captcha-operation-full.mjs";
58
+ import { FormOperationFull } from "./utils/form-operation-full.mjs";
59
+ import {
60
+ TrustedDeviceCheckOperationFull,
61
+ TrustedDeviceEnrollmentOperationFull
62
+ } from "./utils/trusted-device-operation-full.mjs";
63
+ import { ProvideDataOperationFull } from "./utils/provide-data-operation-full.mjs";
64
+ import { PasswordManagerSampler } from "./utils/password-manager-sampler.mjs";
65
+ var SDK_INFO = {
66
+ name: SDK_NAME,
67
+ version: SDK_VERSION
68
+ };
69
+ var INTEGRATION_VERSION_PATTERN = /^[0-9A-Za-z.+_-]{1,32}$/;
70
+ function sdkInfo(integrationVersion, logger) {
71
+ if (integrationVersion === void 0) return SDK_INFO;
72
+ if (typeof integrationVersion === "string" && INTEGRATION_VERSION_PATTERN.test(integrationVersion)) {
73
+ return { ...SDK_INFO, integrationVersion };
74
+ }
75
+ logger.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])");
76
+ return SDK_INFO;
77
+ }
78
+ var SESSION_STORAGE_KEY = "cbo_session_id";
79
+ var SESSION_CONTINUITY_KEY = "cbo_session";
80
+ var SEQ_STORAGE_KEY = "cbo_seq";
81
+ var EXPERIMENTS_STORAGE_KEY = "cbo_experiments";
82
+ var DATA_POLICY_STORAGE_KEY = "cbo_data_policy";
83
+ var DATA_POLICY_MAX = 255;
84
+ var EXPERIMENT_KEY_RE = /^[A-Za-z0-9_-]+$/;
85
+ var EXPERIMENT_KEY_MAX = 128;
86
+ var EXPERIMENT_VALUE_MAX = 256;
87
+ var TELEMETRY_MESSAGE_MAX = 1e3;
88
+ var PROBE_KIND_RE = /^[a-z][a-z0-9_-]{0,31}$/;
89
+ var PROBE_ID_RE = /^[A-Za-z0-9_-]{1,16}$/;
90
+ var PROBE_CTX_MAX = 64;
91
+ var PROBE_PAGE_IDS_MAX = 32;
92
+ var MAX_SELF_TELEMETRY = 50;
93
+ var SEQ_LOCK_NAME = "cbo_seq";
94
+ var SESSION_ACTIVITY_WRITE_INTERVAL_MS = 1e3;
95
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
96
+ var CorbadoTracker = class _CorbadoTracker {
97
+ constructor(options) {
98
+ this.options = options;
99
+ this.options.debug = options.debug ?? false;
100
+ this.logger = options.logger ?? createLogger({ debug: this.options.debug });
101
+ const localStorage = new LocalStorage(this.logger);
102
+ const sessionStorage = new SessionStorage(this.logger);
103
+ const isCookie = options.storage === "cookie";
104
+ const cookieStorage = isCookie ? new CookieStorage(this.logger, options.cookieDomain) : void 0;
105
+ migrateLegacyStorage(options.projectId, localStorage, sessionStorage, cookieStorage, this.logger);
106
+ const namespace = options.projectId;
107
+ const scoped = (engine) => new NamespacedStorage(engine, namespace);
108
+ this.seqLockName = namespacedKey(SEQ_LOCK_NAME, namespace);
109
+ this.sessionStorage = scoped(sessionStorage);
110
+ this.persistentStorage = scoped(localStorage);
111
+ this.storage = scoped(cookieStorage ?? localStorage);
112
+ this.configOverrides = {
113
+ ...options.sdkConfig,
114
+ ...options.sdkConfig?.retry && { retry: { ...options.sdkConfig.retry } },
115
+ ...options.sdkConfig?.flushOnFlowTypeFinished && {
116
+ flushOnFlowTypeFinished: [...options.sdkConfig.flushOnFlowTypeFinished]
117
+ },
118
+ ...options.sdkConfig?.sourcePathQueryAllow && {
119
+ sourcePathQueryAllow: [...options.sdkConfig.sourcePathQueryAllow]
120
+ }
121
+ };
122
+ this.fixedData = resolveFixedDataConfig(options.fixedDataConfig);
123
+ if (this.fixedData) {
124
+ this.configOverrides.pmd = this.fixedData.pmd;
125
+ }
126
+ const completeOverride = Object.keys(DEFAULT_RELIABILITY_CONFIG).every(
127
+ (key) => this.configOverrides[key] !== void 0
128
+ ) && Object.keys(DEFAULT_RELIABILITY_CONFIG.retry).every(
129
+ (key) => this.configOverrides.retry?.[key] !== void 0
130
+ );
131
+ if (!completeOverride) {
132
+ this.configManager = new ConfigManager(
133
+ options.apiBaseUrl + (options.apiConfigPath ?? "/v1/observe/config") + "/" + options.projectId,
134
+ this.persistentStorage,
135
+ this.logger
136
+ );
137
+ }
138
+ const cachedConfig = this.configManager?.initialConfig;
139
+ this.config = resolveReliabilityConfig(cachedConfig, this.configOverrides);
140
+ if (!completeOverride && !cachedConfig && options.flushInterval != null && this.configOverrides.flushIntervalMs === void 0) {
141
+ this.config = { ...this.config, flushIntervalMs: options.flushInterval };
142
+ }
143
+ if (!completeOverride && !cachedConfig && options.deviceInfoCollectorTimeout != null && this.configOverrides.deviceInfoCollectorTimeoutMs === void 0) {
144
+ this.config = { ...this.config, deviceInfoCollectorTimeoutMs: options.deviceInfoCollectorTimeout };
145
+ }
146
+ if (options.apiBaseUrl !== "") {
147
+ if (!/^https?:\/\//.test(options.apiBaseUrl)) {
148
+ this.logger.critical(
149
+ `Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${options.apiBaseUrl}")`
150
+ );
151
+ this.reportTelemetry("error", "invalid apiBaseUrl: missing http(s) scheme");
152
+ }
153
+ if (options.apiBaseUrl.endsWith("/")) {
154
+ this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${options.apiBaseUrl}")`);
155
+ this.reportTelemetry("error", "invalid apiBaseUrl: trailing slash");
156
+ }
157
+ }
158
+ const url = options.apiBaseUrl + (options.apiEventPath ?? "/v1/observe/events") + "/" + options.projectId;
159
+ this.logger.debug(`Using API endpoint: ${url}`);
160
+ const transport = new FetchTransport({
161
+ logger: this.logger,
162
+ url
163
+ });
164
+ this.sessionId = this.resolveSessionId();
165
+ this.queue = new RequestQueue(
166
+ this.logger,
167
+ transport,
168
+ this.sessionId,
169
+ sdkInfo(this.options.integrationVersion, this.logger),
170
+ {
171
+ debug: this.options.debug,
172
+ config: this.config,
173
+ requestConfig: false,
174
+ outboxLockName: namespacedKey(OUTBOX_LOCK_NAME, namespace),
175
+ getDataPolicy: () => this.dataPolicy,
176
+ fixedData: this.fixedData !== void 0 || typeof __CBO_DATA_PMD__ === "boolean" || typeof __CBO_DATA_PRIVATE_MODE__ === "boolean",
177
+ beforeEventBatchSend: (events) => this.attachUndeliveredDeviceInfo(events),
178
+ // The queue is created before the device info manager; both are only called once it exists.
179
+ standaloneDeviceInfo: {
180
+ has: () => this.deviceInfoManager?.hasStandalone() ?? false,
181
+ take: () => this.deviceInfoManager?.takeStandalone()
182
+ }
183
+ },
184
+ this.persistentStorage
185
+ );
186
+ this.telemetryReady = true;
187
+ this.logger.setTelemetrySink?.((level, message) => this.reportTelemetry(level, message));
188
+ try {
189
+ this.getWindowObserver();
190
+ } catch (error) {
191
+ this.logger.error("Failed to attach page low-event observer", error);
192
+ }
193
+ if (typeof __CBO_DATA_PMD__ === "boolean" ? __CBO_DATA_PMD__ : this.fixedData?.pmd !== false) {
194
+ try {
195
+ this.passwordManagerSampler = this.isTrackingBlocked() ? void 0 : new PasswordManagerSampler(
196
+ this.logger,
197
+ () => typeof __CBO_DATA_PMD__ === "boolean" ? __CBO_DATA_PMD__ : this.config.pmd,
198
+ this.getWindowObserver()
199
+ );
200
+ } catch (error) {
201
+ this.logger.error("Failed to start password manager detection", error);
202
+ }
203
+ }
204
+ const bufferedTelemetry = this.pendingSelfTelemetry;
205
+ this.pendingSelfTelemetry = [];
206
+ for (const item of bufferedTelemetry) {
207
+ this.telemetry(item.level, item.message);
208
+ }
209
+ const deviceInfoCollector = new DeviceCollector(
210
+ this.logger,
211
+ this.storage,
212
+ isCookie ? "cookie" : "localstorage",
213
+ this.sessionStorage,
214
+ () => ({
215
+ timing: this.config.deviceInfoTiming
216
+ }),
217
+ // Timing entries carry raw millisecond values, so they go through the public telemetry path
218
+ // rather than reportTelemetry: the latter dedupes by exact message and is capped per load,
219
+ // where ever-changing messages would crowd out real error diagnostics.
220
+ (level, message) => this.telemetry(level, message),
221
+ this.fixedData?.privateMode ?? true
222
+ );
223
+ this.deviceCollector = deviceInfoCollector;
224
+ const deviceInfoDebounceTime = options.deviceInfoDebounceTime ?? 3e4;
225
+ this.deviceInfoManager = new DeviceInfoManager(
226
+ this.logger,
227
+ deviceInfoCollector,
228
+ Math.max(1, deviceInfoDebounceTime),
229
+ deviceInfoDebounceTime,
230
+ {
231
+ timing: () => this.config.deviceInfoTiming,
232
+ emit: (level, message) => this.telemetry(level, message)
233
+ },
234
+ () => this.queue.notifyDeviceInfo()
235
+ );
236
+ this.deviceInfoManager.start();
237
+ this.experiments = this.loadPersistedExperiments();
238
+ if (options.experiments) {
239
+ this.setExperiments(options.experiments);
240
+ }
241
+ this.dataPolicy = this.loadPersistedDataPolicy();
242
+ if (options.dataPolicy !== void 0) {
243
+ this.setDataPolicy(options.dataPolicy);
244
+ }
245
+ this.configManager?.start((config) => this.handleConfig(config));
246
+ }
247
+ logger;
248
+ queue;
249
+ sessionId;
250
+ storage;
251
+ sessionStorage;
252
+ /** Dedicated localStorage engine for reliability state (config cache, outbox, continuity session, seq). */
253
+ persistentStorage;
254
+ /** Seq/continuity Web Lock name; project-scoped together with the storage keys it guards. */
255
+ seqLockName;
256
+ /** Current resolved policy. Continuity and persistence stay enabled once activated within a document. */
257
+ config;
258
+ configManager;
259
+ configOverrides;
260
+ /** Resolved `fixedDataConfig`; undefined when not given (server-driven data switches). */
261
+ fixedData;
262
+ deviceInfoManager;
263
+ deviceCollector;
264
+ /**
265
+ * Cached per-tab id stamped onto every event's meta (see {@link EventMeta.tabId}). Resolved
266
+ * lazily from the collector's sessionStorage-backed id; stable for the whole page lifetime.
267
+ */
268
+ eventTabId;
269
+ seq = 0;
270
+ /**
271
+ * When the continuity record's `lastActiveAt` was last persisted. Throttles that write inside the
272
+ * seq critical section (see {@link SESSION_ACTIVITY_WRITE_INTERVAL_MS}). 0 = not written yet on
273
+ * this load, so the first allocation always persists.
274
+ */
275
+ lastActivityWriteAt = 0;
276
+ /** Persistent experiment assignments (experiment key → variant), attached to every produced event. */
277
+ experiments = {};
278
+ /**
279
+ * Persistent data policy code, stamped into every batch's `meta.dataPolicy` once set. Never
280
+ * cleared (only overwritten): it survives reloads, session rotation, resetSession and destroy.
281
+ */
282
+ dataPolicy;
283
+ /** Self-instrumentation state: re-entrancy guard, readiness, per-load dedupe, and pre-queue buffer. */
284
+ telemetryReporting = false;
285
+ telemetryReady = false;
286
+ reportedTelemetryKeys = /* @__PURE__ */ new Set();
287
+ pendingSelfTelemetry = [];
288
+ /** Default probe page id (one per tracker instance) and the probe seq counter per page id. */
289
+ probePageId;
290
+ probeSeqs = /* @__PURE__ */ new Map();
291
+ windowObserver;
292
+ passwordManagerSampler;
293
+ /** @internal Shared passive page observation and per-operation context registration. */
294
+ getWindowObserver() {
295
+ return this.windowObserver ??= new SharedWindowObserver(
296
+ this.logger,
297
+ (low, sessionId) => this.enqueueLowEvent(low, sessionId),
298
+ () => this.lowEventFlushKeepalive()
299
+ );
300
+ }
301
+ /** Apply init overrides on every refresh; continuity and persistence only activate within a document. */
302
+ handleConfig(config) {
303
+ const next = resolveReliabilityConfig(config, this.configOverrides);
304
+ next.sessionContinuity ||= this.config.sessionContinuity;
305
+ next.durableOutbox ||= this.config.durableOutbox;
306
+ this.config = next;
307
+ this.queue.updateConfig(this.config);
308
+ }
309
+ /**
310
+ * Returns the logger used by this tracker.
311
+ * @internal
312
+ */
313
+ getLogger() {
314
+ return this.logger;
315
+ }
316
+ applicationTag() {
317
+ if (this.options.applicationId) {
318
+ return { applicationId: this.options.applicationId.toLowerCase() };
319
+ }
320
+ return {};
321
+ }
322
+ // --- Experiments ---
323
+ /**
324
+ * Register the user's variant for an experiment (e.g. `setExperiment("button_color", "blue")`).
325
+ *
326
+ * @remarks
327
+ * Corbado Observe does not assign variants — your app decides, and this records the assignment so
328
+ * Observe can attribute flows to it. The assignment persists (localStorage) across reloads and
329
+ * `resetSession`, and is attached to every event the tracker produces until you change or clear it.
330
+ * Multiple experiments can be active at once. Set it close to where the variant actually affects the
331
+ * user (or use the per-call `experiments` argument on a tracking method) to avoid over-attributing
332
+ * exposure; call {@link clearExperiment} when it no longer applies (e.g. on logout).
333
+ *
334
+ * Never throws: invalid input is ignored with a debug log.
335
+ */
336
+ setExperiment(key, variant) {
337
+ this.setExperiments({ [key]: variant });
338
+ }
339
+ /**
340
+ * Register several experiment assignments at once (experiment key → variant). Additive: existing
341
+ * assignments for other keys are kept. See {@link setExperiment}.
342
+ */
343
+ setExperiments(assignments) {
344
+ try {
345
+ if (!assignments || typeof assignments !== "object") {
346
+ return;
347
+ }
348
+ let changed = false;
349
+ for (const [key, variant] of Object.entries(assignments)) {
350
+ if (!_CorbadoTracker.isValidExperimentKey(key) || !_CorbadoTracker.isValidExperimentVariant(variant)) {
351
+ this.logger.debug(`Ignoring invalid experiment assignment "${String(key)}"`);
352
+ continue;
353
+ }
354
+ if (this.experiments[key] !== variant) {
355
+ this.experiments[key] = variant;
356
+ changed = true;
357
+ }
358
+ }
359
+ if (changed) {
360
+ this.persistExperiments();
361
+ }
362
+ } catch (error) {
363
+ this.logger.error("Failed to set experiments", error);
364
+ }
365
+ }
366
+ /** Remove a single experiment assignment. */
367
+ clearExperiment(key) {
368
+ try {
369
+ if (Object.prototype.hasOwnProperty.call(this.experiments, key)) {
370
+ delete this.experiments[key];
371
+ this.persistExperiments();
372
+ }
373
+ } catch (error) {
374
+ this.logger.error("Failed to clear experiment", error);
375
+ }
376
+ }
377
+ /** Remove all experiment assignments. */
378
+ clearExperiments() {
379
+ try {
380
+ if (Object.keys(this.experiments).length === 0) {
381
+ return;
382
+ }
383
+ this.experiments = {};
384
+ this.persistExperiments();
385
+ } catch (error) {
386
+ this.logger.error("Failed to clear experiments", error);
387
+ }
388
+ }
389
+ /** Returns a copy of the currently active experiment assignments. */
390
+ getExperiments() {
391
+ return { ...this.experiments };
392
+ }
393
+ /**
394
+ * Returns the currently active public SDK configuration, including live updates.
395
+ *
396
+ * @returns A frozen snapshot, created fresh on every call.
397
+ */
398
+ /** @internal Project-scoped localStorage used by operation helpers (e.g. email-link continuity). */
399
+ getPersistentStorage() {
400
+ return this.persistentStorage;
401
+ }
402
+ getSdkConfig() {
403
+ return Object.freeze({
404
+ version: this.config.version,
405
+ aap: this.config.aap,
406
+ rawErrors: this.config.rawErrors
407
+ });
408
+ }
409
+ // --- Data policy ---
410
+ /**
411
+ * Set the data policy code for this tracker (e.g. `setDataPolicy(1)` once the user agreed to
412
+ * extended processing; `setDataPolicy(0)` to return to the project default). Codes are
413
+ * project-scoped non-negative integers (0..255) selecting a policy configured in Corbado; they
414
+ * carry no ordering.
415
+ *
416
+ * The code is persisted (localStorage, project-scoped) and sent as `meta.dataPolicy` on every
417
+ * subsequent batch, across reloads and session rotation. It is never cleared, only overwritten.
418
+ * The server records the latest code it receives for a session (last write wins). Invalid codes
419
+ * are ignored with a debug log; never throws.
420
+ */
421
+ setDataPolicy(code) {
422
+ try {
423
+ if (!_CorbadoTracker.isValidDataPolicy(code)) {
424
+ this.logger.debug(`Ignoring invalid data policy code "${String(code)}"`);
425
+ return;
426
+ }
427
+ if (this.dataPolicy !== code) {
428
+ this.dataPolicy = code;
429
+ this.persistDataPolicy();
430
+ }
431
+ } catch (error) {
432
+ this.logger.error("Failed to set data policy", error);
433
+ }
434
+ }
435
+ /** Returns the current data policy code, or undefined when none has ever been set. */
436
+ getDataPolicy() {
437
+ return this.dataPolicy;
438
+ }
439
+ static isValidDataPolicy(code) {
440
+ return typeof code === "number" && Number.isInteger(code) && code >= 0 && code <= DATA_POLICY_MAX;
441
+ }
442
+ loadPersistedDataPolicy() {
443
+ try {
444
+ const stored = this.persistentStorage.getItem(DATA_POLICY_STORAGE_KEY);
445
+ return _CorbadoTracker.isValidDataPolicy(stored) ? stored : void 0;
446
+ } catch (error) {
447
+ this.logger.debug("Failed to load persisted data policy", error);
448
+ return void 0;
449
+ }
450
+ }
451
+ persistDataPolicy() {
452
+ try {
453
+ if (this.dataPolicy === void 0) {
454
+ return;
455
+ }
456
+ this.persistentStorage.setItem(DATA_POLICY_STORAGE_KEY, this.dataPolicy);
457
+ } catch (error) {
458
+ this.logger.debug("Failed to persist data policy", error);
459
+ }
460
+ }
461
+ static isValidExperimentKey(key) {
462
+ return typeof key === "string" && key.length > 0 && key.length <= EXPERIMENT_KEY_MAX && EXPERIMENT_KEY_RE.test(key);
463
+ }
464
+ static isValidExperimentVariant(variant) {
465
+ return typeof variant === "string" && variant.length > 0 && variant.length <= EXPERIMENT_VALUE_MAX;
466
+ }
467
+ loadPersistedExperiments() {
468
+ try {
469
+ const stored = this.persistentStorage.getItem(EXPERIMENTS_STORAGE_KEY);
470
+ if (!stored || typeof stored !== "object") {
471
+ return {};
472
+ }
473
+ const cleaned = {};
474
+ for (const [key, variant] of Object.entries(stored)) {
475
+ if (_CorbadoTracker.isValidExperimentKey(key) && _CorbadoTracker.isValidExperimentVariant(variant)) {
476
+ cleaned[key] = variant;
477
+ }
478
+ }
479
+ return cleaned;
480
+ } catch (error) {
481
+ this.logger.debug("Failed to load persisted experiments", error);
482
+ return {};
483
+ }
484
+ }
485
+ persistExperiments() {
486
+ try {
487
+ this.persistentStorage.setItem(EXPERIMENTS_STORAGE_KEY, this.experiments);
488
+ } catch (error) {
489
+ this.logger.debug("Failed to persist experiments", error);
490
+ }
491
+ }
492
+ /**
493
+ * Resolves the experiments to attach to one event: the persistent assignments with any per-call
494
+ * override merged on top. Returns undefined when there are none (so the field is omitted).
495
+ */
496
+ resolveExperiments(perCall) {
497
+ const merged = { ...this.experiments };
498
+ if (perCall && typeof perCall === "object") {
499
+ for (const [key, variant] of Object.entries(perCall)) {
500
+ if (_CorbadoTracker.isValidExperimentKey(key) && _CorbadoTracker.isValidExperimentVariant(variant)) {
501
+ merged[key] = variant;
502
+ }
503
+ }
504
+ }
505
+ return Object.keys(merged).length > 0 ? merged : void 0;
506
+ }
507
+ isTrackingBlocked() {
508
+ if (typeof navigator === "undefined") {
509
+ return false;
510
+ }
511
+ return isBlockedUserAgent(
512
+ readUserAgent({
513
+ key: "browser-api:sdk.blocked-user-agent",
514
+ title: "User agent check for crawlers and bots",
515
+ accessNote: "navigator.userAgent, matched against a list of crawler and bot patterns",
516
+ group: "Observe SDK state",
517
+ origin: "observe-external",
518
+ fields: [
519
+ {
520
+ path: "result",
521
+ label: "Whether the browser looks like a bot",
522
+ exposure: "computed",
523
+ transform: { note: "matched against the blocked user-agent list; only the boolean is used (tracking off)" }
524
+ }
525
+ ]
526
+ })
527
+ );
528
+ }
529
+ resolveSessionId() {
530
+ try {
531
+ if (this.config.sessionContinuity) {
532
+ return this.getContinuitySessionId();
533
+ }
534
+ const now = Date.now();
535
+ const stored = this.readPerTabSession();
536
+ if (stored && now - stored.lastActiveAt < this.perTabInactivityMs(stored)) {
537
+ this.persistPerTabSession(stored.id, now);
538
+ this.seq = 0;
539
+ return stored.id;
540
+ }
541
+ const newSessionId = uuidv7();
542
+ this.persistPerTabSession(newSessionId, now);
543
+ this.seq = 0;
544
+ this.logger.debug("Created session id", newSessionId);
545
+ return newSessionId;
546
+ } catch (error) {
547
+ this.logger.error("Failed to get session id", error);
548
+ this.reportTelemetry("error", "failed to get session id");
549
+ return "";
550
+ }
551
+ }
552
+ /**
553
+ * Resolve the session id from localStorage so it survives reloads and is shared across tabs of the
554
+ * same browser. Rotates after `config.sessionInactivityMs` of inactivity (server-controlled,
555
+ * evaluated at boot), resetting the seq counter.
556
+ *
557
+ * Inactivity rotation happens at boot only, here and on the per-tab path {@link resolveSessionId}
558
+ * takes without continuity. Boot is chosen on an assumption, not a guarantee: that a load
559
+ * re-announces its flow, so the fresh session id gets a classifiable flow. That holds where a
560
+ * flow is opened per load. Where one is opened once and carried across loads it does not, and a
561
+ * boot rotation splits that flow — such a project needs a window long enough to span the journey.
562
+ * Mid-page the assumption is not even available: nothing re-announces between two tracked events,
563
+ * so rotating there would leave the started flow unfinished in the old session and the remaining
564
+ * events without a flow start in the new one — one gap counted as a drop-off, one completion
565
+ * counted as nothing. `nextSeq` therefore never rotates on inactivity, on either path.
566
+ */
567
+ getContinuitySessionId() {
568
+ const now = Date.now();
569
+ const existing = this.persistentStorage.getItem(SESSION_CONTINUITY_KEY);
570
+ if (existing?.id && now - existing.lastActiveAt < this.config.sessionInactivityMs) {
571
+ this.persistContinuitySession(existing.id, now);
572
+ this.seq = this.persistentStorage.getItem(SEQ_STORAGE_KEY) ?? 0;
573
+ return existing.id;
574
+ }
575
+ if (!existing?.id) {
576
+ const perTab = this.readPerTabSession();
577
+ if (perTab && now - perTab.lastActiveAt < this.config.sessionInactivityMs) {
578
+ this.persistContinuitySession(perTab.id, now);
579
+ this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
580
+ this.seq = 0;
581
+ this.logger.debug("Adopted per-tab session id as continuity session", perTab.id);
582
+ return perTab.id;
583
+ }
584
+ }
585
+ const newSessionId = uuidv7();
586
+ this.persistContinuitySession(newSessionId, now);
587
+ this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
588
+ this.seq = 0;
589
+ this.logger.debug("Created continuity session id", newSessionId);
590
+ return newSessionId;
591
+ }
592
+ /**
593
+ * Persist the continuity record and remember when, so the throttled refresh in the seq critical
594
+ * section measures from the last write that actually happened — whoever made it.
595
+ */
596
+ persistContinuitySession(id, now) {
597
+ this.lastActivityWriteAt = now;
598
+ this.persistentStorage.setItem(SESSION_CONTINUITY_KEY, { id, lastActiveAt: now });
599
+ }
600
+ /**
601
+ * Read the per-tab session record. A bare string is the format that predates dating: it carries no
602
+ * `lastActiveAt`, so its window can only start on the load that reads it. That load rewrites it in
603
+ * the dated shape, so a tab converts once and ages normally from then on, and the case drains as
604
+ * the rollout replaces the bundles that write it.
605
+ */
606
+ readPerTabSession() {
607
+ const stored = this.sessionStorage.getItem(SESSION_STORAGE_KEY);
608
+ if (!stored) {
609
+ return void 0;
610
+ }
611
+ if (typeof stored === "string") {
612
+ return UUID_RE.test(stored) ? { id: stored, lastActiveAt: Date.now() } : void 0;
613
+ }
614
+ if (typeof stored.lastActiveAt !== "number") {
615
+ return void 0;
616
+ }
617
+ return UUID_RE.test(stored.id) ? stored : void 0;
618
+ }
619
+ /**
620
+ * Persist the per-tab record and remember when, sharing the throttle bookkeeping with the
621
+ * continuity record — a load resolves its session on one path or the other, never both.
622
+ *
623
+ * An explicit timeout override or server config stamps the window. Otherwise carry forward what
624
+ * the tab already knows, so a defaults boot does not replace a previously configured threshold.
625
+ */
626
+ persistPerTabSession(id, now) {
627
+ this.lastActivityWriteAt = now;
628
+ const inactivityMs = this.configOverrides.sessionInactivityMs !== void 0 || this.config.version ? this.config.sessionInactivityMs : this.readPerTabSession()?.inactivityMs;
629
+ this.sessionStorage.setItem(SESSION_STORAGE_KEY, {
630
+ id,
631
+ lastActiveAt: now,
632
+ ...inactivityMs === void 0 ? {} : { inactivityMs }
633
+ });
634
+ }
635
+ /** Explicit init timeout wins; otherwise retain the window a prior configured load recorded. */
636
+ perTabInactivityMs(stored) {
637
+ return this.configOverrides.sessionInactivityMs !== void 0 ? this.config.sessionInactivityMs : stored.inactivityMs ?? this.config.sessionInactivityMs;
638
+ }
639
+ /**
640
+ * Return the next sequence number. With session continuity the counter is persisted so ordering
641
+ * survives reloads/redirects; the read-increment-write runs under a cross-tab Web Lock
642
+ * ({@link SEQ_LOCK_NAME}) so two tabs sharing the session cannot allocate the same seq (where Web
643
+ * Locks are unavailable or exceed the configured timeout it degrades to the historical best-effort merge).
644
+ * Lock grants are FIFO, so seq order matches `track()` call order within a tab. Tracking also keeps the
645
+ * continuity session's `lastActiveAt` fresh (throttled, see {@link SESSION_ACTIVITY_WRITE_INTERVAL_MS}),
646
+ * so the window the NEXT boot evaluates measures real user
647
+ * inactivity instead of time-since-page-load (a long-lived active tab must not rotate the session
648
+ * on the next reload). It never rotates the session itself: the inactivity window is evaluated at
649
+ * boot only ({@link getContinuitySessionId} documents why). Consequence: while a page is never
650
+ * reloaded — foreground idle, bfcache restore, long-lived SPA tab — a session can outlive
651
+ * `sessionInactivityMs`. That inflates flow durations but keeps flow counts correct, which is the
652
+ * better half of the trade. An empty store while this load already has a session id means
653
+ * persistence is failing (or was cleared); the in-memory id is reused then — never re-minted — so
654
+ * a broken store degrades to one session per page load instead of one session per event.
655
+ */
656
+ nextSeq() {
657
+ if (!this.config.sessionContinuity) {
658
+ const now = Date.now();
659
+ if (this.sessionId && now - this.lastActivityWriteAt >= SESSION_ACTIVITY_WRITE_INTERVAL_MS) {
660
+ this.persistPerTabSession(this.sessionId, now);
661
+ }
662
+ return this.seq++;
663
+ }
664
+ const allocate = () => {
665
+ const now = Date.now();
666
+ const storedSession = this.persistentStorage.getItem(SESSION_CONTINUITY_KEY);
667
+ let sessionChanged = false;
668
+ if (!storedSession?.id && this.sessionId) {
669
+ this.persistContinuitySession(this.sessionId, now);
670
+ } else if (!storedSession?.id) {
671
+ const newSessionId = uuidv7();
672
+ this.persistContinuitySession(newSessionId, now);
673
+ this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
674
+ this.sessionId = newSessionId;
675
+ this.queue.setSessionId(newSessionId);
676
+ this.seq = 0;
677
+ sessionChanged = true;
678
+ } else {
679
+ if (now - this.lastActivityWriteAt >= SESSION_ACTIVITY_WRITE_INTERVAL_MS) {
680
+ this.persistContinuitySession(storedSession.id, now);
681
+ }
682
+ if (storedSession.id !== this.sessionId) {
683
+ this.sessionId = storedSession.id;
684
+ this.queue.setSessionId(storedSession.id);
685
+ sessionChanged = true;
686
+ }
687
+ }
688
+ const stored = this.persistentStorage.getItem(SEQ_STORAGE_KEY);
689
+ if (sessionChanged) {
690
+ this.seq = typeof stored === "number" ? stored : 0;
691
+ }
692
+ const current = typeof stored === "number" && stored > this.seq ? stored : this.seq;
693
+ this.seq = current + 1;
694
+ this.persistentStorage.setItem(SEQ_STORAGE_KEY, this.seq);
695
+ return current;
696
+ };
697
+ const timeoutMs = this.config.seqLockTimeoutMs;
698
+ if (timeoutMs === 0 || !hasWebLocks({
699
+ key: "browser-api:sdk.web-locks",
700
+ title: "Coordination of Observe data across open tabs",
701
+ accessNote: "Web Locks API (navigator.locks) on Observe's own lock names",
702
+ group: "Observe SDK state",
703
+ origin: "observe-internal",
704
+ fields: [
705
+ {
706
+ path: "available",
707
+ label: "Whether the browser supports tab coordination",
708
+ exposure: "enum",
709
+ transform: { values: [true, false] }
710
+ }
711
+ ]
712
+ })) {
713
+ return allocate();
714
+ }
715
+ return withWebLock(
716
+ {
717
+ key: "browser-api:sdk.web-locks",
718
+ title: "Coordination of Observe data across open tabs",
719
+ accessNote: "Web Locks API (navigator.locks) on Observe's own lock names",
720
+ group: "Observe SDK state",
721
+ origin: "observe-internal",
722
+ fields: [
723
+ {
724
+ path: "result",
725
+ label: "Coordination between open tabs",
726
+ exposure: "none",
727
+ transform: { note: "own cbo_* lock names; serializes the SDK's storage updates across tabs" }
728
+ }
729
+ ]
730
+ },
731
+ this.seqLockName,
732
+ allocate,
733
+ {
734
+ timeoutMs,
735
+ onTimeout: () => {
736
+ this.logger.warn(`Sequence Web Lock acquisition timed out after ${timeoutMs}ms; using fallback`);
737
+ this.reportTelemetry("info", `seq web lock timeout; using fallback, ${timeoutMs}ms`);
738
+ }
739
+ }
740
+ );
741
+ }
742
+ resolveTrackingSourcePath() {
743
+ if (typeof window === "undefined") {
744
+ return void 0;
745
+ }
746
+ return readSourcePath(
747
+ {
748
+ key: "page:location.source-path",
749
+ title: "Page path and allowed query parameters",
750
+ accessNote: "location.pathname and location.search; the query is reduced by the sourcePathQuery policy inside the reader (trackingSourcePath)",
751
+ group: "Page",
752
+ origin: "observe-external",
753
+ fields: [
754
+ { path: "url.path", label: "Page path", exposure: "raw" },
755
+ {
756
+ path: "url.query",
757
+ label: "Page address parameters (allowed ones only)",
758
+ exposure: "redacted",
759
+ transform: { note: "sourcePathQuery 'allowlist': values of non-allowlisted keys become '*'; 'all': raw" }
760
+ }
761
+ ]
762
+ },
763
+ this.config.sourcePathQuery,
764
+ this.config.sourcePathQueryAllow
765
+ );
766
+ }
767
+ /**
768
+ * Per-tab id for event meta, cached after the first successful resolution: the id is
769
+ * sessionStorage-backed and stable for the whole page lifetime.
770
+ */
771
+ resolveEventTabId() {
772
+ if (this.eventTabId === void 0) {
773
+ this.eventTabId = this.deviceCollector.getTabId();
774
+ }
775
+ return this.eventTabId;
776
+ }
777
+ /** @internal */
778
+ trackSubflowStarted(subflowType, data, options, eventId) {
779
+ const wrappedData = {
780
+ subflowType,
781
+ ...data
782
+ };
783
+ void this.track(
784
+ AuthEventName.SubflowStarted,
785
+ wrappedData,
786
+ options?.userReference,
787
+ void 0,
788
+ void 0,
789
+ options?.explicitTimestamp,
790
+ options?.experiments,
791
+ {
792
+ id: eventId,
793
+ subflowStartEventId: options?.subflowStartEventId,
794
+ sessionId: options?.captureSessionId,
795
+ initiator: options?.initiator
796
+ }
797
+ );
798
+ }
799
+ /** @internal */
800
+ trackSubflowTrigger(subflowType, data, options) {
801
+ const wrappedData = {
802
+ subflowType,
803
+ ...data
804
+ };
805
+ void this.track(
806
+ AuthEventName.SubflowTrigger,
807
+ wrappedData,
808
+ options?.userReference,
809
+ void 0,
810
+ void 0,
811
+ options?.explicitTimestamp,
812
+ options?.experiments,
813
+ {
814
+ subflowStartEventId: options?.subflowStartEventId,
815
+ sessionId: options?.captureSessionId,
816
+ initiator: options?.initiator
817
+ }
818
+ );
819
+ }
820
+ /** @internal */
821
+ trackSubflowStepStarted(subflowType, stepName, data, options, ignoreAsInteraction) {
822
+ const wrappedData = {
823
+ subflowType,
824
+ stepName,
825
+ stepData: data,
826
+ identifier: options?.identifier,
827
+ ignoreAsInteraction
828
+ };
829
+ void this.track(
830
+ AuthEventName.SubflowStepStarted,
831
+ wrappedData,
832
+ options?.userReference,
833
+ void 0,
834
+ void 0,
835
+ options?.explicitTimestamp,
836
+ options?.experiments,
837
+ {
838
+ subflowStartEventId: options?.subflowStartEventId,
839
+ sessionId: options?.captureSessionId,
840
+ initiator: options?.initiator
841
+ }
842
+ );
843
+ }
844
+ /** @internal */
845
+ trackSubflowStepFinished(subflowType, stepName, data, options) {
846
+ const wrappedData = {
847
+ subflowType,
848
+ stepName,
849
+ stepData: data,
850
+ identifier: options?.identifier
851
+ };
852
+ void this.track(
853
+ AuthEventName.SubflowStepFinished,
854
+ wrappedData,
855
+ options?.userReference,
856
+ void 0,
857
+ void 0,
858
+ options?.explicitTimestamp,
859
+ options?.experiments,
860
+ {
861
+ subflowStartEventId: options?.subflowStartEventId,
862
+ sessionId: options?.captureSessionId,
863
+ initiator: options?.initiator
864
+ }
865
+ );
866
+ }
867
+ /** @internal */
868
+ trackSubflowStepError(subflowType, stepName, data, options) {
869
+ const wrappedData = {
870
+ subflowType,
871
+ stepName,
872
+ stepData: data,
873
+ identifier: options?.identifier
874
+ };
875
+ void this.track(
876
+ AuthEventName.SubflowStepError,
877
+ wrappedData,
878
+ options?.userReference,
879
+ void 0,
880
+ void 0,
881
+ options?.explicitTimestamp,
882
+ options?.experiments,
883
+ {
884
+ subflowStartEventId: options?.subflowStartEventId,
885
+ sessionId: options?.captureSessionId,
886
+ initiator: options?.initiator
887
+ }
888
+ );
889
+ }
890
+ /**
891
+ * @remarks
892
+ * @internal
893
+ * Records an additional error occurrence against the subflow. Carries no outcome semantics —
894
+ * step errors are the intended channel; not part of a normal integration.
895
+ */
896
+ trackSubflowError(subflowType, data, options) {
897
+ const wrappedData = {
898
+ subflowType,
899
+ stepData: data
900
+ };
901
+ void this.track(
902
+ AuthEventName.SubflowError,
903
+ wrappedData,
904
+ options?.userReference,
905
+ void 0,
906
+ void 0,
907
+ options?.explicitTimestamp,
908
+ options?.experiments,
909
+ {
910
+ subflowStartEventId: options?.subflowStartEventId,
911
+ sessionId: options?.captureSessionId,
912
+ initiator: options?.initiator
913
+ }
914
+ );
915
+ }
916
+ /**
917
+ * Error situations:
918
+ * - Blocked user agent (see `isBlockedUserAgent`): skip with a debug log and return
919
+ * - Any error before the event is enqueued (e.g. `JSON.stringify` in debug logging, `queue.enqueue`): log `Failed to process event "<name>" before enqueue`
920
+ *
921
+ * @internal
922
+ */
923
+ async track(name, data, userReference, tags, contexts, explicitTimestamp, experiments, capture) {
924
+ try {
925
+ if (this.isTrackingBlocked()) {
926
+ this.logger.debug(`Skipping event "${name}" for blocked user agent.`);
927
+ return;
928
+ }
929
+ if (name === AuthEventName.FlowFinished || name === AuthEventName.FlowAutoFinished || name === AuthEventName.FlowReset) {
930
+ this.windowObserver?.flushInputs();
931
+ }
932
+ const timestamp = explicitTimestamp ?? Date.now();
933
+ const capturedId = capture?.id ?? uuidv7();
934
+ const capturedSessionId = capture?.sessionId ?? this.sessionId;
935
+ const nextSeq = this.nextSeq();
936
+ const seq = typeof nextSeq === "number" ? nextSeq : await nextSeq;
937
+ const trackingSourcePath = this.resolveTrackingSourcePath();
938
+ const event = {
939
+ type: "predefined",
940
+ name,
941
+ id: capturedId,
942
+ timestamp,
943
+ seq,
944
+ data,
945
+ user: userReference,
946
+ contexts,
947
+ tags,
948
+ experiments: this.resolveExperiments(experiments),
949
+ meta: {
950
+ captureVersion: 1,
951
+ pageId: getCapturePageId(),
952
+ initiator: capture?.initiator,
953
+ trackingSourcePath: trackingSourcePath ?? "",
954
+ subflowStartEventId: capture?.subflowStartEventId,
955
+ tabId: this.resolveEventTabId()
956
+ }
957
+ };
958
+ const deviceInfo = this.deviceInfoManager.getForEvent();
959
+ if (deviceInfo) {
960
+ event.deviceInfo = deviceInfo;
961
+ }
962
+ this.logger.debug(`Track: ${name}`, JSON.stringify(event, null, 2));
963
+ const passwordManagers = this.passwordManagerSampler?.takeReport(capturedSessionId);
964
+ if (passwordManagers) {
965
+ event.passwordManagers = passwordManagers;
966
+ }
967
+ this.queue.enqueue(event, capturedSessionId);
968
+ } catch (error) {
969
+ this.logger.error(`Failed to process event "${name}" before enqueue`, error);
970
+ this.reportTelemetry("error", `failed to process event "${name}" before enqueue`);
971
+ }
972
+ }
973
+ // --- Typed Tracking Methods ---
974
+ /**
975
+ * Track when an authentication flow (or flow selection screen) becomes visible.
976
+ *
977
+ * @remarks
978
+ * Call this once when the user first enters an auth touchpoint (for example account login,
979
+ * checkout login, or account recovery). If users can choose between multiple flows
980
+ * (such as login vs signup), pass `flowNames` and optionally `defaultFlowName`.
981
+ *
982
+ * The returned handle can attach identity after completion with `await flow.enrich({ userId })`.
983
+ * Enrichment requires a backend supporting explicit event targeting.
984
+ *
985
+ * @param data - Flow metadata, including one flow (`flowName`) or multiple candidates (`flowNames`).
986
+ * @param tags - Optional key-value tags for filtering and segmentation.
987
+ * @param experiments - Optional per-call experiment overrides.
988
+ * @param contexts - Optional structured event context (e.g. technical metadata that is not an
989
+ * analytical dimension). Written to the event's `contexts` field verbatim.
990
+ * @param options - Optional `explicitTimestamp` (epoch ms) when the flow became visible earlier than
991
+ * this call, e.g. because an integration confirms a screen only after it stayed up for a while.
992
+ *
993
+ * @example
994
+ * ```typescript
995
+ * tracker.flowStarted({
996
+ * flowNames: ["login", "signup"],
997
+ * defaultFlowName: "login",
998
+ * touchpoint: "account",
999
+ * });
1000
+ * ```
1001
+ */
1002
+ flowStarted(data, tags, experiments, contexts, options) {
1003
+ try {
1004
+ const targetEventId = uuidv7();
1005
+ const sessionId = this.sessionId;
1006
+ const effectiveTags = { ...this.options.defaultTags, ...this.applicationTag(), ...tags };
1007
+ void this.track(
1008
+ AuthEventName.FlowStarted,
1009
+ data,
1010
+ void 0,
1011
+ effectiveTags,
1012
+ contexts,
1013
+ options?.explicitTimestamp,
1014
+ experiments,
1015
+ {
1016
+ id: targetEventId,
1017
+ sessionId
1018
+ }
1019
+ );
1020
+ return this.flowHandle(targetEventId, sessionId);
1021
+ } catch (error) {
1022
+ this.logger.warn("Failed to start flow", error);
1023
+ return { enrich: async () => {
1024
+ } };
1025
+ }
1026
+ }
1027
+ /**
1028
+ * Track when the user commits to a specific flow.
1029
+ *
1030
+ * @remarks
1031
+ * Use this after presenting alternatives and once you know which path the user takes
1032
+ * (for example when identifier checks route to login vs signup).
1033
+ *
1034
+ * @param data - Selected flow name.
1035
+ * @param tags - Optional key-value tags for filtering and segmentation.
1036
+ *
1037
+ * @example
1038
+ * ```typescript
1039
+ * tracker.flowDecided({flowName: "signup"});
1040
+ * ```
1041
+ */
1042
+ flowDecided(data, tags, experiments) {
1043
+ void this.track(AuthEventName.FlowDecided, data, void 0, tags, void 0, void 0, experiments);
1044
+ }
1045
+ /**
1046
+ * Track a business/marketing conversion that is not part of an authentication flow.
1047
+ *
1048
+ * @remarks
1049
+ * Use this for outcomes you care about beyond auth, such as a completed purchase,
1050
+ * a started subscription, or a newsletter signup. Provide a stable `name` for the
1051
+ * conversion and (optionally) the `touchpoint` where it happened so it can be
1052
+ * segmented in the same way as flows. Record identity separately with `setUser()`
1053
+ * while the relevant flow is still active.
1054
+ *
1055
+ * Legacy identity fields in `data` remain supported but are deprecated.
1056
+ *
1057
+ * @param data - Conversion name, optional touchpoint, and deprecated user reference fields.
1058
+ * @param tags - Optional key-value tags for filtering and segmentation.
1059
+ *
1060
+ * @example
1061
+ * ```typescript
1062
+ * tracker.conversion({
1063
+ * name: "purchase",
1064
+ * touchpoint: "checkout",
1065
+ * });
1066
+ * ```
1067
+ */
1068
+ conversion(data, tags, experiments) {
1069
+ const { userId, identifier, crossEnvironmentTransactionID, ...dataOut } = data;
1070
+ const userReference = { userId, identifier, crossEnvironmentTransactionID };
1071
+ const effectiveTags = { ...this.options.defaultTags, ...this.applicationTag(), ...tags };
1072
+ void this.track(AuthEventName.Conversion, dataOut, userReference, effectiveTags, void 0, void 0, experiments);
1073
+ }
1074
+ /**
1075
+ * Track when a flow successfully completes.
1076
+ *
1077
+ * @remarks
1078
+ * Fire this when the user has finished the target flow end-to-end, such as completed login,
1079
+ * signup, or recovery. Record identity with `setUser()` while the flow is active,
1080
+ * or enrich it after completion through the handle returned by `flowStarted()` or by this call.
1081
+ *
1082
+ * The returned handle targets the flow this event finished, so identity learned only after
1083
+ * completion — for example from a profile request that follows account creation — can be
1084
+ * attached with `await finished.enrich({ userId })` even on a page that never saw the flow start.
1085
+ * Enrichment requires a backend supporting explicit flow-event targeting.
1086
+ *
1087
+ * Legacy identity fields in `data` remain supported but are deprecated.
1088
+ *
1089
+ * @param data - Finished flow name, optional explicit outcome, and deprecated user reference fields.
1090
+ * @param tags - Optional key-value tags for filtering and segmentation.
1091
+ *
1092
+ * @example
1093
+ * ```typescript
1094
+ * const finished = tracker.flowFinished({ flowName: "signup" });
1095
+ * const userId = await hashUserId(createdAccountId);
1096
+ * await finished.enrich({ userId });
1097
+ * ```
1098
+ */
1099
+ flowFinished(data, tags, experiments) {
1100
+ try {
1101
+ const { userId, identifier, ...dataOut } = data;
1102
+ const userReference = { userId, identifier };
1103
+ const targetEventId = uuidv7();
1104
+ const sessionId = this.sessionId;
1105
+ void this.track(AuthEventName.FlowFinished, dataOut, userReference, tags, void 0, void 0, experiments, {
1106
+ id: targetEventId,
1107
+ sessionId
1108
+ });
1109
+ return this.flowHandle(targetEventId, sessionId);
1110
+ } catch (error) {
1111
+ this.logger.warn("Failed to finish flow", error);
1112
+ return { enrich: async () => {
1113
+ } };
1114
+ }
1115
+ }
1116
+ /** Emits `flow_enriched` against an explicit target, in the session that emitted the target. */
1117
+ flowHandle(targetEventId, sessionId) {
1118
+ return {
1119
+ enrich: async (user) => {
1120
+ try {
1121
+ await this.track(
1122
+ AuthEventName.FlowEnriched,
1123
+ { targetEventId },
1124
+ { ...user },
1125
+ void 0,
1126
+ void 0,
1127
+ void 0,
1128
+ void 0,
1129
+ { sessionId }
1130
+ );
1131
+ } catch (error) {
1132
+ this.logger.warn("Failed to enrich flow", error);
1133
+ }
1134
+ }
1135
+ };
1136
+ }
1137
+ /**
1138
+ * Track when an in-progress flow is reset and restarted.
1139
+ *
1140
+ * @remarks
1141
+ * Use this when users abandon the current path and return to the beginning of the same flow,
1142
+ * for example after switching account/identifier and reopening the first step.
1143
+ *
1144
+ * @param data - Flow name being reset.
1145
+ * @param tags - Optional key-value tags for filtering and segmentation.
1146
+ *
1147
+ * @example
1148
+ * ```typescript
1149
+ * tracker.flowReset({flowName: "login"});
1150
+ * ```
1151
+ */
1152
+ flowReset(data, tags, experiments) {
1153
+ void this.track(AuthEventName.FlowReset, data, void 0, tags, void 0, void 0, experiments);
1154
+ }
1155
+ /**
1156
+ * Track when a flow is considered finished because another flow finished it implicitly.
1157
+ *
1158
+ * @remarks
1159
+ * Use this for automatic completions where no separate explicit finish action happens in the
1160
+ * current flow. Set `flowName` to the auto-finished flow and `finishedByFlowName` to the flow
1161
+ * that caused it. Record identity with `setUser()` while the intended flow is still
1162
+ * current, before it is auto-finished.
1163
+ *
1164
+ * Legacy identity fields in `data` remain supported but are deprecated.
1165
+ *
1166
+ * @param data - Auto-finished flow, finishing flow, and deprecated user reference fields.
1167
+ * @param tags - Optional key-value tags for filtering and segmentation.
1168
+ *
1169
+ * @example
1170
+ * ```typescript
1171
+ * tracker.flowAutoFinished({
1172
+ * flowName: "signup",
1173
+ * finishedByFlowName: "login",
1174
+ * });
1175
+ * ```
1176
+ */
1177
+ flowAutoFinished(data, tags, experiments) {
1178
+ const { userId, identifier, ...dataOut } = data;
1179
+ const userReference = { userId, identifier };
1180
+ void this.track(AuthEventName.FlowAutoFinished, dataOut, userReference, tags, void 0, void 0, experiments);
1181
+ }
1182
+ /**
1183
+ * Record a newly known user reference for the current active flow.
1184
+ *
1185
+ * @remarks
1186
+ * Emits one `flow_enriched` with `match: { flowType: "*", at: "during" }` and `expFol: true` in its data.
1187
+ * Call only after the flow starts and before it finishes. The enrichment belongs
1188
+ * to the current flow at emission time.
1189
+ * Calling after `flowFinished()` cannot enrich that finished flow. If a parent or another
1190
+ * flow is current then, the enrichment belongs to that flow instead.
1191
+ * An empty reference does not clear identity. Cross-environment transaction IDs must be UUIDs;
1192
+ * both environments must report the shared ID while their respective flows are active.
1193
+ *
1194
+ * @param user - User ID, identifier, and/or cross-environment transaction UUID.
1195
+ *
1196
+ * @example
1197
+ * ```typescript
1198
+ * tracker.flowStarted({ flowName: "login" });
1199
+ * tracker.setUser({ userId: "usr_123", identifier: "max@example.com" });
1200
+ * tracker.flowFinished({ flowName: "login" });
1201
+ * ```
1202
+ */
1203
+ setUser(user) {
1204
+ void this.track(AuthEventName.FlowEnriched, { match: { flowType: "*", at: "during" }, expFol: true }, { ...user });
1205
+ }
1206
+ /**
1207
+ * Attach tags to the flow that is open right now.
1208
+ *
1209
+ * @remarks
1210
+ * Emits one `flow_enriched` carrying `tags` and no user reference, with data
1211
+ * `{ match: { flowType, at: "during" } }` plus `expCh` / `expFol` when the options set them.
1212
+ *
1213
+ * - The tags land on the innermost flow open at call time (of `flowType` when given; default `"*"`, any type).
1214
+ * - `expandToChildren` (default `true`): child flows of that flow inherit the tags.
1215
+ * - `expandToFollowing` (default `true`): later sibling flows inherit the tags until the next
1216
+ * sibling of the same flow type as the tagged flow.
1217
+ * - Per key the last `setFlowTags()` value wins; it also overrides a same-key tag passed to that
1218
+ * flow's own tracking calls (e.g. `flowStarted()`).
1219
+ * - Call while the target flow is open. An enrichment after the flow's last container event
1220
+ * (for example after `flowFinished()`) matches no flow and is dropped with a
1221
+ * `flow_enriched/no_matching_flow` classification warning.
1222
+ * - Tag keys and values are case-sensitive. Entries with an empty key or a non-string value are
1223
+ * dropped with a warning; nothing is sent when no valid entry remains.
1224
+ *
1225
+ * @param tags - Key-value tags for filtering and segmentation.
1226
+ * @param options - Target flow type and tag expansion; omitted flags default to `true`.
1227
+ *
1228
+ * @example
1229
+ * ```typescript
1230
+ * tracker.flowStarted({ flowName: "login" });
1231
+ * tracker.setFlowTags({ entryPoint: "checkout" });
1232
+ * tracker.flowFinished({ flowName: "login" });
1233
+ * ```
1234
+ */
1235
+ setFlowTags(tags, options) {
1236
+ try {
1237
+ if (!tags || typeof tags !== "object") {
1238
+ this.logger.warn("setFlowTags: ignoring non-object tags");
1239
+ return;
1240
+ }
1241
+ const valid = {};
1242
+ for (const [key, value] of Object.entries(tags)) {
1243
+ if (key === "" || typeof value !== "string") {
1244
+ this.logger.warn(`setFlowTags: ignoring invalid tag "${key}"`);
1245
+ continue;
1246
+ }
1247
+ valid[key] = value;
1248
+ }
1249
+ if (Object.keys(valid).length === 0) {
1250
+ return;
1251
+ }
1252
+ const data = { match: { flowType: options?.flowType ?? "*", at: "during" } };
1253
+ if (options?.expandToChildren !== void 0) {
1254
+ data.expCh = options.expandToChildren;
1255
+ }
1256
+ if (options?.expandToFollowing !== void 0) {
1257
+ data.expFol = options.expandToFollowing;
1258
+ }
1259
+ void this.track(AuthEventName.FlowEnriched, data, void 0, valid);
1260
+ } catch (error) {
1261
+ this.logger.warn("Failed to set flow tags", error);
1262
+ }
1263
+ }
1264
+ /**
1265
+ * Track when you present authentication method choices to the user.
1266
+ *
1267
+ * @remarks
1268
+ * Use this whenever a decision point is shown with a concrete method set, such as
1269
+ * identifier entry options (`d1`) or post-identifier options (`d3`). Set
1270
+ * `explicitDecisionValue` when the options are re-offered after a user action and you want
1271
+ * to capture what triggered that transition.
1272
+ *
1273
+ * @param data - Decision identifier, offered options, and optional transition reason.
1274
+ * @param tags - Optional key-value tags for filtering and segmentation.
1275
+ * @param experiments - Optional per-call experiment assignments.
1276
+ * @param options - Optional explicit event timestamp.
1277
+ *
1278
+ * @example
1279
+ * ```typescript
1280
+ * tracker.authMethodsDecisionStarted({
1281
+ * decisionName: "d3",
1282
+ * options: ["passkey", "social-google", "password", "reset-flow"],
1283
+ * });
1284
+ * ```
1285
+ */
1286
+ authMethodsDecisionStarted(data, tags, experiments, options) {
1287
+ void this.track(
1288
+ AuthEventName.AuthMethodDecisionStarted,
1289
+ data,
1290
+ void 0,
1291
+ tags,
1292
+ void 0,
1293
+ options?.explicitTimestamp,
1294
+ experiments
1295
+ );
1296
+ }
1297
+ authMethodsDecisionFinished(data, tags, experiments) {
1298
+ void this.track(AuthEventName.AuthMethodDecisionFinished, data, void 0, tags, void 0, void 0, experiments);
1299
+ }
1300
+ // decisions
1301
+ /**
1302
+ * @deprecated Use {@link CorbadoTracker.authMethodsDecisionStarted} instead (its `options`
1303
+ * already accept free-form strings).
1304
+ */
1305
+ authDecisionStarted(data, tags, experiments) {
1306
+ void this.track(AuthEventName.AuthDecisionStarted, data, void 0, tags, void 0, void 0, experiments);
1307
+ }
1308
+ /**
1309
+ * @deprecated Use {@link CorbadoTracker.authMethodsDecisionFinished} instead (its `options`
1310
+ * already accept free-form strings).
1311
+ */
1312
+ authDecisionFinished(data, tags, experiments) {
1313
+ void this.track(AuthEventName.AuthDecisionFinished, data, void 0, tags, void 0, void 0, experiments);
1314
+ }
1315
+ /**
1316
+ * Enqueue a "low" event (granular DOM/window/visualviewport/PWM signal) for the current session.
1317
+ *
1318
+ * @remarks
1319
+ * Low events are sent in the `lows` array of the events endpoint payload, alongside any
1320
+ * pending typed events. Blocked user agents are skipped silently.
1321
+ *
1322
+ * @internal
1323
+ */
1324
+ enqueueLowEvent(low, capturedSessionId) {
1325
+ try {
1326
+ if (this.isTrackingBlocked()) {
1327
+ this.logger.debug(`Skipping low event "${low.lowType}" for blocked user agent.`);
1328
+ return;
1329
+ }
1330
+ this.queue.enqueueLow(
1331
+ {
1332
+ ...low,
1333
+ captureSeq: low.captureSeq ?? reserveCaptureSeq(),
1334
+ captureVersion: 1,
1335
+ pageId: low.pageId ?? getCapturePageId()
1336
+ },
1337
+ capturedSessionId
1338
+ );
1339
+ } catch (error) {
1340
+ this.logger.error(`Failed to process low event "${low.lowType}" before enqueue`, error);
1341
+ }
1342
+ }
1343
+ /**
1344
+ * Record a diagnostic telemetry entry (a `level` + free-form `message`) for the current session.
1345
+ *
1346
+ * @remarks
1347
+ * Telemetry is delivered in the `telemetry` array of the events endpoint payload, tied to the same
1348
+ * session, and is never classified as an auth-flow event. By default a telemetry entry piggybacks
1349
+ * the next normal flush (it does not trigger one on its own); this is server-controlled. Collection
1350
+ * can be turned off server-side via the `telemetry` config flag. Blocked user agents are skipped.
1351
+ *
1352
+ * The message is truncated to {@link TELEMETRY_MESSAGE_MAX} characters. Never pass credentials or
1353
+ * PII — telemetry is for diagnostics only. Like all SDK entry points, this never throws.
1354
+ */
1355
+ telemetry(level, message) {
1356
+ try {
1357
+ if (this.isTrackingBlocked()) {
1358
+ this.logger.debug("Skipping telemetry for blocked user agent.");
1359
+ return;
1360
+ }
1361
+ const text = typeof message === "string" ? message : String(message);
1362
+ if (text.length === 0) {
1363
+ return;
1364
+ }
1365
+ const entry = {
1366
+ id: uuidv7(),
1367
+ level,
1368
+ message: text.length > TELEMETRY_MESSAGE_MAX ? text.slice(0, TELEMETRY_MESSAGE_MAX) : text,
1369
+ ts: Date.now()
1370
+ };
1371
+ this.queue.enqueueTelemetry(entry);
1372
+ } catch (error) {
1373
+ this.logger.error("Failed to process telemetry before enqueue", error);
1374
+ }
1375
+ }
1376
+ /**
1377
+ * Queue a probe item (diagnostic capture produced by a Corbado autocapture bundle).
1378
+ *
1379
+ * @remarks
1380
+ * The SDK fills `id` (uuidv7), `seq` (per `pageId`), `pageId` (default: one random id per tracker
1381
+ * instance) and `ts` (default: now). Items are held in memory only (never the durable outbox) and
1382
+ * ride the regular batches; they are the lowest priority at page unload. Invalid input is dropped.
1383
+ * The payload must already be redacted. Blocked user agents are skipped. Never throws.
1384
+ *
1385
+ * @experimental Internal: used by Corbado autocapture bundles. Not part of the documented API.
1386
+ * @internal
1387
+ */
1388
+ probe(input) {
1389
+ try {
1390
+ if (this.isTrackingBlocked()) {
1391
+ this.logger.debug("Skipping probe for blocked user agent.");
1392
+ return;
1393
+ }
1394
+ if (!input || typeof input !== "object" || typeof input.kind !== "string" || !PROBE_KIND_RE.test(input.kind)) {
1395
+ this.logger.debug("Dropping probe with an invalid kind.");
1396
+ return;
1397
+ }
1398
+ const payload = input.payload;
1399
+ if (!payload || typeof payload !== "object") {
1400
+ this.logger.debug(`Dropping probe "${input.kind}" without an object payload.`);
1401
+ return;
1402
+ }
1403
+ const pageId = typeof input.pageId === "string" && PROBE_ID_RE.test(input.pageId) ? input.pageId : this.defaultProbePageId();
1404
+ const entry = {
1405
+ id: uuidv7(),
1406
+ kind: input.kind,
1407
+ ts: typeof input.ts === "number" && Number.isFinite(input.ts) ? Math.round(input.ts) : Date.now(),
1408
+ pageId,
1409
+ seq: this.nextProbeSeq(pageId),
1410
+ payload
1411
+ };
1412
+ if (typeof input.cfg === "string" && PROBE_ID_RE.test(input.cfg)) {
1413
+ entry.cfg = input.cfg;
1414
+ }
1415
+ const ctx = sanitizeProbeContext(input.ctx);
1416
+ if (ctx) {
1417
+ entry.ctx = ctx;
1418
+ }
1419
+ this.queue.enqueueProbe(entry);
1420
+ } catch (error) {
1421
+ this.logger.error("Failed to process probe before enqueue", error);
1422
+ }
1423
+ }
1424
+ defaultProbePageId() {
1425
+ return this.probePageId ??= randomProbePageId();
1426
+ }
1427
+ nextProbeSeq(pageId) {
1428
+ const seq = this.probeSeqs.get(pageId) ?? 0;
1429
+ this.probeSeqs.delete(pageId);
1430
+ this.probeSeqs.set(pageId, seq + 1);
1431
+ if (this.probeSeqs.size > PROBE_PAGE_IDS_MAX) {
1432
+ const oldest = this.probeSeqs.keys().next().value;
1433
+ if (oldest !== void 0) this.probeSeqs.delete(oldest);
1434
+ }
1435
+ return seq;
1436
+ }
1437
+ /** Convenience wrapper for {@link CorbadoTracker.telemetry} at `info` level. */
1438
+ logInfo(message) {
1439
+ this.telemetry("info", message);
1440
+ }
1441
+ /** Convenience wrapper for {@link CorbadoTracker.telemetry} at `error` level. */
1442
+ logError(message) {
1443
+ this.telemetry("error", message);
1444
+ }
1445
+ /**
1446
+ * Queue hook run right before an event batch is sent: a device info snapshot that no event carried
1447
+ * yet (typically the fast snapshot after a burst of events at page load, or the privateMode update)
1448
+ * rides the first event of this page in the batch that has none. Events of other pages (outbox
1449
+ * replays) are never touched. A snapshot no event can carry goes as the batch's request-level device
1450
+ * info instead (queue option `standaloneDeviceInfo`).
1451
+ *
1452
+ * Error situations:
1453
+ * - Any error: log "Failed to attach device info to batch" and send the batch unchanged
1454
+ */
1455
+ attachUndeliveredDeviceInfo(events) {
1456
+ try {
1457
+ const manager = this.deviceInfoManager;
1458
+ if (!manager?.hasUndelivered()) {
1459
+ return;
1460
+ }
1461
+ const pageId = getCapturePageId();
1462
+ const target = events.find((event) => event.meta?.pageId === pageId && !event.deviceInfo);
1463
+ if (target) {
1464
+ target.deviceInfo = manager.takeUndelivered();
1465
+ }
1466
+ } catch (error) {
1467
+ this.logger.error("Failed to attach device info to batch", error);
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Escalate an internal SDK diagnostic to the telemetry stream (self-instrumentation). This is the
1472
+ * sink behind {@link Logger.reportTelemetry}; chosen internal failure sites route here so faults
1473
+ * that are otherwise only visible with `debug: true` become observable in the field.
1474
+ *
1475
+ * @remarks
1476
+ * Bounded and deduped per load (a persistent fault — blocked storage, a downed endpoint — cannot
1477
+ * flood the stream), re-entrancy-guarded so it can never recurse, and it never throws into the
1478
+ * host. Diagnostics raised before the queue exists (early boot) are buffered and replayed once the
1479
+ * queue is ready. Messages must be stable and low-cardinality (no raw error objects / PII).
1480
+ */
1481
+ reportTelemetry(level, message) {
1482
+ if (this.telemetryReporting) {
1483
+ return;
1484
+ }
1485
+ this.telemetryReporting = true;
1486
+ try {
1487
+ if (this.reportedTelemetryKeys.has(message) || this.reportedTelemetryKeys.size >= MAX_SELF_TELEMETRY) {
1488
+ return;
1489
+ }
1490
+ this.reportedTelemetryKeys.add(message);
1491
+ if (!this.telemetryReady) {
1492
+ this.pendingSelfTelemetry.push({ level, message });
1493
+ return;
1494
+ }
1495
+ this.telemetry(level, message);
1496
+ } catch {
1497
+ } finally {
1498
+ this.telemetryReporting = false;
1499
+ }
1500
+ }
1501
+ /**
1502
+ * Synchronously flush any pending events and low events via beacon. Use during page-unload
1503
+ * style teardown where async flushing is unreliable.
1504
+ *
1505
+ * @param reason What triggered the flush; recorded as `meta.flushReason` on the batch. Defaults
1506
+ * to a direct call by the host app.
1507
+ *
1508
+ * @internal
1509
+ */
1510
+ flushKeepalive(reason = "manual") {
1511
+ try {
1512
+ this.queue.flushKeepalive(reason);
1513
+ } catch (error) {
1514
+ this.logger.error("Failed to flush queue keepalive", error);
1515
+ }
1516
+ }
1517
+ /**
1518
+ * Whether input trackers run the DOM password-manager scan (`pa-1`..`pa-6` lows): only an explicitly
1519
+ * set `fixedDataConfig.pmd` decides; without `fixedDataConfig` or with `pmd` omitted it always runs
1520
+ * (historical behaviour).
1521
+ *
1522
+ * @internal
1523
+ */
1524
+ isPasswordManagerDomScanEnabled() {
1525
+ return this.fixedData?.pmdExplicit ? this.fixedData.pmd : true;
1526
+ }
1527
+ /**
1528
+ * Keepalive flush requested by a low-event tracker's `pagehide` teardown. Gated by the
1529
+ * server-controlled trigger switch `tlf` (boot-snapshot, default true = historical behavior):
1530
+ * disabling it server-side makes low-event delivery rely solely on the queue's own triggers.
1531
+ *
1532
+ * @internal
1533
+ */
1534
+ lowEventFlushKeepalive() {
1535
+ if (!this.config.tlf) {
1536
+ return;
1537
+ }
1538
+ this.flushKeepalive("low-event-teardown");
1539
+ }
1540
+ passkeyLoginFullOperation(config) {
1541
+ return new PasskeyLoginOperationFull(this, config);
1542
+ }
1543
+ passkeyEnrollmentFullOperation(config) {
1544
+ return new PasskeyEnrollmentOperationFull(this, config);
1545
+ }
1546
+ /**
1547
+ * Track a user deleting one of their passkeys through userConfirmation and deletion.
1548
+ *
1549
+ * @param config - Optional configuration; the passkey-deletion subflow has no spec types.
1550
+ * @remarks
1551
+ * Create the operation when the user asks to delete a passkey (e.g. clicks "Remove"); construction
1552
+ * alone is not counted as an interaction. Start userConfirmation when the confirmation dialog opens
1553
+ * and finish it when the user confirms; report a dismissed dialog with
1554
+ * `userConfirmation.errorTyped({ code: "cancelled" })`. Skip userConfirmation when there is no dialog.
1555
+ * Start deletion when the delete request is sent and finish it only when the passkey was deleted;
1556
+ * report a rejection with `deletion.errorTyped({ code })` or a thrown error with `deletion.error(error)`.
1557
+ * Never include credential IDs or other passkey material.
1558
+ * @example
1559
+ * ```ts
1560
+ * const deletion = tracker.passkeyDeletionOperationFull();
1561
+ * deletion.userConfirmation.start({});
1562
+ * if (!(await confirmDialog())) {
1563
+ * deletion.userConfirmation.errorTyped({ code: "cancelled" });
1564
+ * return;
1565
+ * }
1566
+ * deletion.userConfirmation.finished({});
1567
+ * deletion.deletion.start({});
1568
+ * try {
1569
+ * await deletePasskey(id);
1570
+ * deletion.deletion.finished({});
1571
+ * } catch (error) {
1572
+ * deletion.deletion.error(error);
1573
+ * }
1574
+ * ```
1575
+ */
1576
+ passkeyDeletionOperationFull(config) {
1577
+ return new PasskeyDeletionOperationFull(this, config);
1578
+ }
1579
+ passwordLoginFullOperation(autoTrackConfig) {
1580
+ return new PasswordLoginOperationFull(this, autoTrackConfig);
1581
+ }
1582
+ passwordEnrollmentFullOperation(autoTrackConfig) {
1583
+ return new PasswordEnrollmentOperationFull(this, autoTrackConfig);
1584
+ }
1585
+ emailLinkOperationFull(config) {
1586
+ return new EmailLinkOperationFull(this, config);
1587
+ }
1588
+ /**
1589
+ * Continue an email link started on another page (the link's target page). In the same browser
1590
+ * and session it continues page 1's subflow directly; otherwise it emits a continuation start that
1591
+ * the backend joins to page 1 through the transaction ID. See {@link EmailLinkContinuationOperation}.
1592
+ */
1593
+ continueEmailLinkOperation(config) {
1594
+ return new EmailLinkContinuationOperation(this, config);
1595
+ }
1596
+ emailOtpOperationFull(config) {
1597
+ return new EmailOtpOperationFull(this, config);
1598
+ }
1599
+ smsOtpOperationFull(config) {
1600
+ return new SmsOtpOperationFull(this, config);
1601
+ }
1602
+ totpOperationFull(config) {
1603
+ return new TotpOperationFull(this, config);
1604
+ }
1605
+ provideIdentifierOperationFull(config) {
1606
+ return new OperationFullProvideIdentifierWithCUI(
1607
+ this,
1608
+ config
1609
+ );
1610
+ }
1611
+ provideDataOperationFull(config) {
1612
+ return new ProvideDataOperationFull(this, config);
1613
+ }
1614
+ formOperationFull(config) {
1615
+ return new FormOperationFull(this, config);
1616
+ }
1617
+ /**
1618
+ * Track a social login with an external provider (e.g. Google, Apple).
1619
+ *
1620
+ * @param config - Optional spec type and entry.
1621
+ * @remarks
1622
+ * Set `entry` to how the attempt began: omit it for a provider button with a full-page redirect,
1623
+ * `"popup"` when the provider ran in a popup window, `"one-tap"` when the provider showed its own
1624
+ * prompt (e.g. Google One Tap). A One Tap has no redirect: report only `exchangeCode`, never
1625
+ * `getRedirectUrl`.
1626
+ * @example
1627
+ * ```ts
1628
+ * // Provider button:
1629
+ * const social = tracker.socialLoginOperationFull({ explicitSpecType: "pre-identifier" });
1630
+ * social.getRedirectUrl.start({ provider: "google" });
1631
+ * social.getRedirectUrl.finished({});
1632
+ * // Back from the provider, on the new page load:
1633
+ * const back = tracker.socialLoginOperationFull({ explicitSpecType: "pre-identifier" });
1634
+ * back.exchangeCode.start({ provider: "google" });
1635
+ * back.exchangeCode.finished({});
1636
+ *
1637
+ * // Google One Tap, when the credential arrives in page:
1638
+ * const oneTap = tracker.socialLoginOperationFull({ explicitSpecType: "pre-identifier", entry: "one-tap" });
1639
+ * oneTap.exchangeCode.start({ provider: "google" });
1640
+ * oneTap.exchangeCode.finished({});
1641
+ * ```
1642
+ */
1643
+ socialLoginOperationFull(config) {
1644
+ return new SocialLoginOperationFull(this, config);
1645
+ }
1646
+ /**
1647
+ * Track enterprise SSO (SAML/OIDC) through the organization's identity provider.
1648
+ *
1649
+ * @param config - Optional spec type, organization email domain and actor.
1650
+ * @remarks
1651
+ * Use for policy-routed SSO, kept apart from user-chosen social login. Set `actor: "system"` when
1652
+ * the application routed to SSO without a user choice, e.g. by the email domain. Report only the
1653
+ * organization's domain, never a full address.
1654
+ * @example
1655
+ * ```ts
1656
+ * const sso = tracker.ssoLoginOperationFull({
1657
+ * explicitSpecType: "post-identifier",
1658
+ * organizationDomain: "example.com",
1659
+ * actor: "system",
1660
+ * });
1661
+ * sso.getRedirectUrl.start({});
1662
+ * sso.getRedirectUrl.finished({});
1663
+ * // After the identity provider redirects back:
1664
+ * sso.exchangeCode.start({});
1665
+ * sso.exchangeCode.finished({});
1666
+ * ```
1667
+ */
1668
+ ssoLoginOperationFull(config) {
1669
+ return new SsoLoginOperationFull(this, config);
1670
+ }
1671
+ appConfirmationOperationFull(config) {
1672
+ return new AppConfirmationOperationFull(this, config);
1673
+ }
1674
+ /**
1675
+ * Track direct key signing outside WebAuthn through prepare and sign.
1676
+ *
1677
+ * @param config - Optional configuration; explicitSpecType may only be undefined for now.
1678
+ * @remarks
1679
+ * Start prepare when resolving the eligible key and input for an actual attempt, not background
1680
+ * prefetch. Although system-driven, that work is meaningful interaction for classification.
1681
+ * Construction alone does not establish interaction. Finish sign only when the usable signed
1682
+ * artifact is ready, including assembly. Submission is outside this operation. Report failures
1683
+ * on the affected step using error(error). Never include key material, signatures or proofs.
1684
+ * WebAuthn assertions continue to use passkeyLoginFullOperation.
1685
+ * @example
1686
+ * ```ts
1687
+ * const signing = tracker.keySigningOperationFull();
1688
+ * signing.prepare.start({});
1689
+ * // Resolve an eligible key and prepare the signing input.
1690
+ * signing.prepare.finished({});
1691
+ * signing.sign.start({});
1692
+ * // Sign and assemble the artifact returned to the caller.
1693
+ * signing.sign.finished({});
1694
+ * ```
1695
+ */
1696
+ keySigningOperationFull(config) {
1697
+ return new KeySigningOperationFull(this, config);
1698
+ }
1699
+ /**
1700
+ * Track establishing a key's authority through prepare and postResponse.
1701
+ *
1702
+ * @param config - Optional configuration; explicitSpecType may only be undefined for now.
1703
+ * @remarks
1704
+ * Start prepare when building an actual registration request, not background prefetch.
1705
+ * This system-driven work is meaningful interaction; construction alone is not.
1706
+ * postResponse covers submission and acceptance. Finish only when the key is authorized and
1707
+ * usable, not merely when submission returns. Report rejection, transport, execution or timeout
1708
+ * errors on the affected step using error(error). Never include key material or proofs.
1709
+ * Credential creation and any authorizing WebAuthn assertion are separate operations.
1710
+ * @example
1711
+ * ```ts
1712
+ * const registration = tracker.keyRegistrationOperationFull();
1713
+ * registration.prepare.start({});
1714
+ * // Build the registration request.
1715
+ * registration.prepare.finished({});
1716
+ * registration.postResponse.start({});
1717
+ * // Submit and await evidence that the authority is usable.
1718
+ * registration.postResponse.finished({});
1719
+ * ```
1720
+ */
1721
+ keyRegistrationOperationFull(config) {
1722
+ return new KeyRegistrationOperationFull(this, config);
1723
+ }
1724
+ captchaOperationFull(config) {
1725
+ return new CaptchaOperationFull(this, config);
1726
+ }
1727
+ /**
1728
+ * Track a device-trust check through getOptions, ceremony and postResponse.
1729
+ *
1730
+ * @param config - Mechanism, purpose, storage and optional trust name.
1731
+ * @remarks
1732
+ * Only `trusted` completes the check. Negative results (`not-trusted`, `no-eligible-local-key`,
1733
+ * `server-key-no-local-match`) remain incomplete and may settle an early step. Key-specific
1734
+ * results require a key mechanism; the server-specific result requires explicit evidence.
1735
+ * Use `errorTyped({ code, error })` to retain an original diagnostic with a negative result,
1736
+ * or `error(error)` for an unexpected failure. An accepted result may include a stable
1737
+ * pseudonymous `bindingReference`; never send cookie values, proofs or key material.
1738
+ * @example
1739
+ * ```ts
1740
+ * const check = tracker.trustedDeviceCheckOperationFull({
1741
+ * explicitSpecType: "key", storage: "indexeddb", purpose: "additional-verification",
1742
+ * });
1743
+ * check.ceremony.start({});
1744
+ * // On a recognized local-key failure:
1745
+ * check.ceremony.errorTyped({ code: "no_eligible_local_key", error: originalError });
1746
+ * ```
1747
+ */
1748
+ trustedDeviceCheckOperationFull(config) {
1749
+ return new TrustedDeviceCheckOperationFull(this, config);
1750
+ }
1751
+ /**
1752
+ * Track device-trust enrollment through getOptions, ceremony and postResponse.
1753
+ *
1754
+ * @param config - Mechanism, purpose, storage and optional trust name.
1755
+ * @remarks
1756
+ * Report `created`, `renewed` or `unchanged` after host acceptance. Explicit opt-out is `skipped`;
1757
+ * an unanswered operation remains incomplete. User identity uses the existing `setUser` API.
1758
+ * Missing or unsupported purpose/storage logs a warning and is omitted; the operation remains usable.
1759
+ * @example
1760
+ * ```ts
1761
+ * const enrollment = tracker.trustedDeviceEnrollmentOperationFull({
1762
+ * explicitSpecType: "token", storage: "cookie", purpose: "mfa-exemption",
1763
+ * });
1764
+ * enrollment.postResponse.start({});
1765
+ * // After the host grants browser trust:
1766
+ * enrollment.postResponse.finished({ result: "created", bindingReference });
1767
+ * ```
1768
+ */
1769
+ trustedDeviceEnrollmentOperationFull(config) {
1770
+ return new TrustedDeviceEnrollmentOperationFull(this, config);
1771
+ }
1772
+ /**
1773
+ * Flush any pending events and release all resources (timers, event listeners).
1774
+ *
1775
+ * @remarks
1776
+ * After calling destroy, the tracker must not be used. Operation objects
1777
+ * returned by factory methods (e.g. `passwordLoginFullOperation`) that hold
1778
+ * DOM references must be destroyed separately by the caller.
1779
+ * The final flush is gated by the server-controlled trigger switch `td` (default true);
1780
+ * resources are released either way.
1781
+ */
1782
+ async destroy() {
1783
+ this.configManager?.destroy();
1784
+ this.passwordManagerSampler?.destroy();
1785
+ this.windowObserver?.destroy();
1786
+ this.deviceInfoManager.destroy();
1787
+ if (this.config.td) {
1788
+ try {
1789
+ await this.queue.flush("destroy");
1790
+ } catch (error) {
1791
+ this.logger.error("Failed to flush queue during destroy", error);
1792
+ }
1793
+ }
1794
+ this.queue.destroy();
1795
+ }
1796
+ // Session Management
1797
+ /**
1798
+ * Return the Observe session id this tracker is currently reporting under.
1799
+ *
1800
+ * @remarks
1801
+ * Use this to route a server-side event into the same session the browser reports to: read the id,
1802
+ * pass it to your own backend, and let the backend use it as the `sessionID` of its ingest call.
1803
+ * Reading it here is the supported path — the storage layout behind it is an implementation detail
1804
+ * that has already changed once (per-tab `sessionStorage` to the cross-tab continuity record).
1805
+ *
1806
+ * The value is **not stable for the lifetime of the page**. It changes on
1807
+ * {@link CorbadoTracker.resetSession}, when this tab adopts a continuity session another tab
1808
+ * rotated to, and when a failed bootstrap recovers. Read it at the moment you need it; never cache
1809
+ * it across a request.
1810
+ *
1811
+ * `undefined` means no session id could be established at all — an environment without Web Crypto,
1812
+ * where tracking is not working either. Skip the server-side event instead of sending an empty id:
1813
+ * the ingest API requires a UUID and would reject the batch.
1814
+ *
1815
+ * @returns The current session id, or `undefined` if none could be established.
1816
+ *
1817
+ * @example
1818
+ * ```typescript
1819
+ * const sessionId = tracker.getSessionId();
1820
+ * if (sessionId) {
1821
+ * await fetch("/api/checkout", {
1822
+ * method: "POST",
1823
+ * body: JSON.stringify({ ...payload, observeSessionId: sessionId }),
1824
+ * });
1825
+ * }
1826
+ * ```
1827
+ */
1828
+ getSessionId() {
1829
+ if (!this.sessionId) {
1830
+ const recovered = this.resolveSessionId();
1831
+ if (recovered) {
1832
+ this.sessionId = recovered;
1833
+ this.queue.setSessionId(recovered);
1834
+ }
1835
+ }
1836
+ return this.sessionId || void 0;
1837
+ }
1838
+ /** @internal */
1839
+ resetSession() {
1840
+ const newSessionId = uuidv7();
1841
+ if (this.config.sessionContinuity) {
1842
+ this.persistContinuitySession(newSessionId, Date.now());
1843
+ this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
1844
+ } else {
1845
+ this.persistPerTabSession(newSessionId, Date.now());
1846
+ }
1847
+ this.sessionId = newSessionId;
1848
+ this.seq = 0;
1849
+ this.queue.setSessionId(newSessionId);
1850
+ this.logger.debug(`Session reset: ${newSessionId}`);
1851
+ return newSessionId;
1852
+ }
1853
+ };
1854
+ var PROBE_PAGE_ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
1855
+ function randomProbePageId() {
1856
+ const bytes = new Uint8Array(16);
1857
+ try {
1858
+ crypto.getRandomValues(bytes);
1859
+ } catch {
1860
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
1861
+ }
1862
+ let out = "";
1863
+ for (let i = 0; i < bytes.length; i++) out += PROBE_PAGE_ID_ALPHABET[bytes[i] & 63];
1864
+ return out;
1865
+ }
1866
+ function sanitizeProbeContext(ctx) {
1867
+ if (!ctx || typeof ctx !== "object") return void 0;
1868
+ const out = {};
1869
+ for (const key of ["state", "flowType", "step"]) {
1870
+ const value = ctx[key];
1871
+ if (typeof value === "string" && value.length > 0) out[key] = value.slice(0, PROBE_CTX_MAX);
1872
+ }
1873
+ return Object.keys(out).length > 0 ? out : void 0;
1874
+ }
1875
+ export {
1876
+ CorbadoTracker
1877
+ };