@reliantlabs/forge-web-runtime 0.4.0 → 0.5.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/dist/telemetry.js CHANGED
@@ -38,13 +38,27 @@
38
38
  // front of such a collector must strip the header or replace it with the real
39
39
  // key. The local ClickStack collector does not enforce, and ignores it.
40
40
  //
41
- // ── Replay: shipped, off, masked ─────────────────────────────────────────
41
+ // ── Replay: shipped, off, masked, media blocked ─────────────────────────
42
42
  //
43
43
  // The SDK bundles an rrweb recorder. It is DISABLED unless `replay: true`.
44
- // When enabled, masking is forced on — every input and all text — because a
45
- // replay records the DOM, which for most apps is the most sensitive data they
46
- // have. There is deliberately no option to turn masking off while replay is
47
- // on; an app that needs unmasked replay passes its own SDK options.
44
+ // Privacy is forced, not offered: every input and all text is masked, canvas is
45
+ // never recorded, and images, video, audio, iframes and embeds are BLOCKED
46
+ // (replaced by a same-size placeholder; their pixels never leave the browser).
47
+ // Images are not inlined and web fonts are not collected. There is deliberately
48
+ // no option to turn any of that off while replay is on; an app that needs
49
+ // unmasked replay passes its own SDK options.
50
+ //
51
+ // `replaySampleRate` (0..1, default 1) records only that share of SESSIONS. The
52
+ // SDK has no session sampler, so the decision is made here, once, and held in
53
+ // sessionStorage for the tab's session.
54
+ //
55
+ // ── Network URLs carry no query string ───────────────────────────────────
56
+ //
57
+ // fetch/XHR spans record the request URL, and a query string is where tokens,
58
+ // OAuth codes and search terms live. The runtime rewrites `http.url` and
59
+ // `url.full` on every fetch/XHR span to the URL without query or fragment.
60
+ // The SDK's own `location.href` attribute (the page URL, stamped on every span)
61
+ // has no client-side hook; the ingest side scrubs it.
48
62
  //
49
63
  // ── Loading ──────────────────────────────────────────────────────────────
50
64
  //
@@ -57,6 +71,8 @@
57
71
  // endpoint, and it never throws.
58
72
  import { trace } from "@opentelemetry/api";
59
73
  import { setExceptionReporter } from "./error-reporter.js";
74
+ import { registerTelemetryStartup } from "./telemetry-gate.js";
75
+ import { isTelemetryDisabled, setTelemetrySink, } from "./track.js";
60
76
  /** Where the browser ships telemetry: this origin's `/_otel`. */
61
77
  export const DEFAULT_INGEST_PATH = "/_otel";
62
78
  /**
@@ -77,20 +93,28 @@ export function initBrowserTelemetry(config) {
77
93
  if (started) {
78
94
  return started;
79
95
  }
96
+ if (isTelemetryDisabled()) {
97
+ return Promise.resolve(false);
98
+ }
80
99
  const ingest = resolveIngestUrl(config.endpoint, window.location.origin);
81
100
  if (!ingest) {
101
+ // Nothing will ever drain track() calls held for the SDK; let them go.
102
+ setTelemetrySink(null);
82
103
  return Promise.resolve(false);
83
104
  }
84
105
  started = start(config, ingest);
106
+ registerTelemetryStartup(started);
85
107
  return started;
86
108
  }
87
109
  async function start(config, ingest) {
88
110
  try {
89
111
  const hdx = resolveClient(await import("@hyperdx/browser"));
90
- if (!hdx) {
112
+ if (!hdx || isTelemetryDisabled()) {
113
+ setTelemetrySink(null);
91
114
  return false;
92
115
  }
93
- hdx.init(buildSdkOptions(config, ingest, window.location.origin));
116
+ const replay = decideReplay(config, sessionStorageOrNull(), Math.random);
117
+ hdx.init(buildSdkOptions({ ...config, replay }, ingest, window.location.origin));
94
118
  tapSdkInputs();
95
119
  setExceptionReporter((error, attributes) => {
96
120
  if (alreadyRecorded(error)) {
@@ -98,11 +122,22 @@ async function start(config, ingest) {
98
122
  }
99
123
  hdx.recordException(error, attributes);
100
124
  });
125
+ setTelemetrySink({
126
+ track: (name, attributes) => hdx.addAction?.(name, attributes),
127
+ setUser: (id) => hdx.setGlobalAttributes?.({ userId: id }),
128
+ disable: () => {
129
+ // Back to "no SDK": reportException returns false, so a caller falls
130
+ // back to console.error and the error does not vanish.
131
+ setExceptionReporter(null);
132
+ hdx.stopSessionRecorder?.();
133
+ },
134
+ });
101
135
  return true;
102
136
  }
103
137
  catch (err) {
104
138
  // Blocked chunk, ad-blocker, SDK throw: telemetry must never break the app.
105
139
  console.debug("[telemetry] disabled:", err);
140
+ setTelemetrySink(null);
106
141
  return false;
107
142
  }
108
143
  }
@@ -159,6 +194,8 @@ function alreadyRecorded(error) {
159
194
  * want to see exactly what is configured — it is pure.
160
195
  */
161
196
  export function buildSdkOptions(config, ingestUrl, pageOrigin) {
197
+ // `config.replay` is the FINAL decision here. initBrowserTelemetry resolves
198
+ // replaySampleRate into it (decideReplay) before calling this.
162
199
  const replay = config.replay === true;
163
200
  const resourceAttributes = {};
164
201
  if (config.serviceVersion) {
@@ -167,35 +204,136 @@ export function buildSdkOptions(config, ingestUrl, pageOrigin) {
167
204
  if (config.serviceNamespace) {
168
205
  resourceAttributes["service.namespace"] = config.serviceNamespace;
169
206
  }
207
+ if (config.frontend) {
208
+ resourceAttributes["forge.frontend"] = config.frontend;
209
+ }
170
210
  if (config.environment) {
171
211
  resourceAttributes["deployment.environment.name"] = config.environment;
172
212
  resourceAttributes["deployment.environment"] = config.environment;
173
213
  }
214
+ const targets = propagationTargets(pageOrigin, config.apiOrigins);
215
+ const advancedNetworkCapture = config.advancedNetworkCapture ?? false;
174
216
  const options = {
175
217
  apiKey: PLACEHOLDER_API_KEY,
176
218
  service: config.serviceName,
177
219
  url: ingestUrl,
178
- tracePropagationTargets: propagationTargets(pageOrigin, config.apiOrigins),
220
+ tracePropagationTargets: targets,
179
221
  // The SDK would otherwise trace its own exports, and it must never
180
222
  // observe the route it ships through.
181
223
  ignoreUrls: [new RegExp(`^${escapeRegExp(ingestUrl)}`)],
182
224
  consoleCapture: config.consoleCapture ?? true,
183
- advancedNetworkCapture: config.advancedNetworkCapture ?? false,
225
+ advancedNetworkCapture,
226
+ // The SDK spreads this over ITS fetch/xhr config as whole keys, so
227
+ // everything it would have set (propagation targets, the capture switch)
228
+ // must be restated here or it is lost.
229
+ instrumentations: {
230
+ fetch: {
231
+ propagateTraceHeaderCorsUrls: targets,
232
+ advancedNetworkCapture: () => advancedNetworkCapture,
233
+ applyCustomAttributesOnSpan: stripNetworkQuery,
234
+ },
235
+ xhr: {
236
+ propagateTraceHeaderCorsUrls: targets,
237
+ advancedNetworkCapture: () => advancedNetworkCapture,
238
+ applyCustomAttributesOnSpan: stripNetworkQuery,
239
+ },
240
+ },
184
241
  // Polls for window.Intercom on a timer; nothing here uses Intercom.
185
242
  disableIntercom: true,
186
243
  disableReplay: !replay,
187
244
  otelResourceAttributes: resourceAttributes,
188
245
  debug: config.debug ?? false,
246
+ // Privacy is forced and unconditional: no path through this function
247
+ // yields an unmasked or media-recording replay. The SDK's own default
248
+ // masks inputs but NOT text, and text is where chat content and records
249
+ // live.
250
+ maskAllInputs: true,
251
+ maskAllText: true,
252
+ recordCanvas: false,
253
+ blockSelector: REPLAY_BLOCK_SELECTOR,
254
+ replay: { inlineImages: false, collectFonts: false },
189
255
  };
190
- if (replay) {
191
- // The SDK's own default masks inputs but NOT text; text is where chat
192
- // content and records live. Force both.
193
- options.maskAllInputs = true;
194
- options.maskAllText = true;
195
- options.recordCanvas = false;
196
- }
197
256
  return options;
198
257
  }
258
+ /** Elements a replay never records: their pixels stay in the browser. */
259
+ export const REPLAY_BLOCK_SELECTOR = "img, picture, video, audio, iframe, object, embed";
260
+ /** Where a replay sampling decision is held for the tab's session. */
261
+ export const REPLAY_SAMPLE_KEY = "forge.replay.sampled";
262
+ /**
263
+ * Whether this session records a replay: config.replay, then the sample rate,
264
+ * drawn once and remembered in `store` so a reload (or a route change that
265
+ * re-runs init) never re-rolls into a session that only half-recorded. With no
266
+ * usable store the draw is made each load. Pure given its inputs; exported for
267
+ * tests.
268
+ */
269
+ export function decideReplay(config, store, random) {
270
+ if (config.replay !== true) {
271
+ return false;
272
+ }
273
+ const rate = clampRate(config.replaySampleRate);
274
+ if (rate >= 1) {
275
+ return true;
276
+ }
277
+ if (rate <= 0) {
278
+ return false;
279
+ }
280
+ try {
281
+ const held = store?.getItem(REPLAY_SAMPLE_KEY);
282
+ if (held === "1" || held === "0") {
283
+ return held === "1";
284
+ }
285
+ }
286
+ catch {
287
+ // Storage blocked: fall through to a fresh draw.
288
+ }
289
+ const sampled = random() < rate;
290
+ try {
291
+ store?.setItem(REPLAY_SAMPLE_KEY, sampled ? "1" : "0");
292
+ }
293
+ catch {
294
+ // Not persisted: the next load draws again.
295
+ }
296
+ return sampled;
297
+ }
298
+ // Unset is "every session"; anything that is not a number is a bug, and a bug
299
+ // must not start recording people.
300
+ function clampRate(rate) {
301
+ if (rate === undefined) {
302
+ return 1;
303
+ }
304
+ if (typeof rate !== "number" || Number.isNaN(rate)) {
305
+ return 0;
306
+ }
307
+ return Math.min(1, Math.max(0, rate));
308
+ }
309
+ function sessionStorageOrNull() {
310
+ try {
311
+ return window.sessionStorage;
312
+ }
313
+ catch {
314
+ return null;
315
+ }
316
+ }
317
+ /** The span attributes that hold a request URL. */
318
+ const URL_ATTRIBUTES = ["http.url", "url.full"];
319
+ /** `url` without its query string and fragment. */
320
+ export function stripUrlQuery(url) {
321
+ const cut = url.search(/[?#]/);
322
+ return cut === -1 ? url : url.slice(0, cut);
323
+ }
324
+ // applyCustomAttributesOnSpan for both instrumentations: it runs before the
325
+ // span ends, so the rewritten value is the one exported.
326
+ function stripNetworkQuery(span) {
327
+ for (const key of URL_ATTRIBUTES) {
328
+ const value = span.attributes?.[key];
329
+ if (typeof value === "string") {
330
+ const stripped = stripUrlQuery(value);
331
+ if (stripped !== value) {
332
+ span.setAttribute(key, stripped);
333
+ }
334
+ }
335
+ }
336
+ }
199
337
  /**
200
338
  * resolveIngestUrl turns the configured endpoint into the absolute URL the SDK
201
339
  * is given, or null when telemetry is off. A path resolves against the page
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,yEAAyE;AACzE,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,iEAAiE;AACjE,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,iEAAiE;AACjE,sEAAsE;AACtE,2EAA2E;AAC3E,8EAA8E;AAC9E,wEAAwE;AACxE,4EAA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: the HyperDX browser SDK, initialised the forge way.\n//\n// Captures errors (uncaught, unhandled rejections, boundary-caught), console\n// output, fetch/XHR spans, document load, long tasks and web vitals, and\n// ships them to ClickStack through a SAME-ORIGIN `/_otel` route.\n//\n// ── Why HyperDX REPLACES the old OTel web wiring, not joins it ───────────\n//\n// @hyperdx/browser wraps @hyperdx/otel-web, which builds its own\n// WebTracerProvider and calls provider.register() — the global tracer\n// provider, context manager and propagator. A second registration (the old\n// `./otel` subpath did exactly that) is rejected by @opentelemetry/api with a\n// \"duplicate registration\" diagnostic and silently loses: whichever ran\n// second would simply never see a span. Two tracer providers cannot coexist\n// in one page, so there is one, and it is HyperDX's. `./otel` and its eight\n// @opentelemetry/* SDK peer dependencies are gone.\n//\n// traceparent on RPCs is unaffected. traceInterceptor (trace.ts) injects the\n// active span's context into every Connect call, or synthesises a valid\n// traceparent when none is active — with no SDK at all. With the SDK running,\n// the fetch span HyperDX opens for the call carries the same trace id, and\n// `apiOrigins` below makes that hold for a cross-origin API too (which is\n// every dev loop: the API binds its own port).\n//\n// ── The browser holds no secret ──────────────────────────────────────────\n//\n// `url` is `${location.origin}/_otel`. The browser talks only to its own\n// origin; a dev-server proxy (next.config.ts rewrites / Vite server.proxy) or\n// the deployment's ingress forwards `/_otel/v1/{traces,logs}` to the OTLP/HTTP\n// port of a collector, and that hop — never the bundle — owns credentials.\n//\n// The SDK nevertheless wants an `apiKey` and sends it as an `authorization`\n// header. We pass PLACEHOLDER_API_KEY, a constant that grants nothing and is\n// public by construction. A collector that enforces ingestion auth (ClickStack\n// `collectorAuthenticationEnforced`) rejects it with 401, so the proxy in\n// front of such a collector must strip the header or replace it with the real\n// key. The local ClickStack collector does not enforce, and ignores it.\n//\n// ── Replay: shipped, off, masked ─────────────────────────────────────────\n//\n// The SDK bundles an rrweb recorder. It is DISABLED unless `replay: true`.\n// When enabled, masking is forced on — every input and all text — because a\n// replay records the DOM, which for most apps is the most sensitive data they\n// have. There is deliberately no option to turn masking off while replay is\n// on; an app that needs unmasked replay passes its own SDK options.\n//\n// ── Loading ──────────────────────────────────────────────────────────────\n//\n// The SDK is ~600 KB minified (rrweb and the OTel web stack are bundled in\n// it), so it is imported lazily: bundlers split it into its own chunk that\n// loads after the app is interactive and costs the first paint nothing.\n// initBrowserTelemetry is therefore async and idempotent — every caller gets\n// the same promise, which is what survives React StrictMode's double mount and\n// Fast Refresh. It is a no-op without a DOM (SSR, prerender) and without an\n// endpoint, and it never throws.\nimport { trace } from \"@opentelemetry/api\";\n\nimport { setExceptionReporter } from \"./error-reporter.js\";\n\n/** Where the browser ships telemetry: this origin's `/_otel`. */\nexport const DEFAULT_INGEST_PATH = \"/_otel\";\n\n/**\n * The apiKey handed to the SDK. Public by construction: it identifies\n * nothing and authorises nothing. See the header — the proxy or collector\n * owns the real credential.\n */\nexport const PLACEHOLDER_API_KEY = \"forge-browser-public\";\n\nexport interface BrowserTelemetryConfig {\n /** `service.name` on everything this page emits. */\n serviceName: string;\n /** `service.version`. Omit for none. */\n serviceVersion?: string;\n /**\n * The forge environment name. Emitted as BOTH `deployment.environment.name`\n * (current semconv) and `deployment.environment` (the legacy key HyperDX's\n * default sources still key on).\n */\n environment?: string;\n /** `service.namespace`, conventionally the project name. */\n serviceNamespace?: string;\n /**\n * Ingest base: a path on this origin (`/_otel`) or, as an escape hatch, an\n * absolute URL. Unset, empty, or `off` disables telemetry — the app runs\n * untraced rather than throwing, which is what makes it safe to call\n * unconditionally from the app shell.\n */\n endpoint?: string;\n /**\n * Origins (or URLs — only the origin is used) of the app's own backend.\n * Requests to them always get a `traceparent` from the SDK's fetch/XHR\n * spans. This page's own origin is always included.\n */\n apiOrigins?: Array<string | undefined>;\n /** Mirror console.* into telemetry. Default true. */\n consoleCapture?: boolean;\n /**\n * Capture full request/response headers AND BODIES on fetch/XHR spans.\n * Default false, and it should stay false: bodies are user data.\n */\n advancedNetworkCapture?: boolean;\n /** Session replay (rrweb). Default false. When true, all text and inputs are masked. */\n replay?: boolean;\n /** Verbose SDK diagnostics to the console. Default false. */\n debug?: boolean;\n}\n\n/** The slice of the SDK this module calls. Typed here, not imported, so the module loads without it. */\ninterface HyperDXClient {\n init(config: Record<string, unknown>): void;\n recordException(error: unknown, attributes?: Record<string, unknown>): void;\n}\n\nlet started: Promise<boolean> | null = null;\n\n/**\n * initBrowserTelemetry starts the HyperDX browser SDK once per page load and\n * resolves to whether it is running. See the module header for the contract.\n */\nexport function initBrowserTelemetry(\n config: BrowserTelemetryConfig,\n): Promise<boolean> {\n if (typeof window === \"undefined\") {\n return Promise.resolve(false);\n }\n if (started) {\n return started;\n }\n const ingest = resolveIngestUrl(config.endpoint, window.location.origin);\n if (!ingest) {\n return Promise.resolve(false);\n }\n started = start(config, ingest);\n return started;\n}\n\nasync function start(\n config: BrowserTelemetryConfig,\n ingest: string,\n): Promise<boolean> {\n try {\n const hdx = resolveClient(await import(\"@hyperdx/browser\"));\n if (!hdx) {\n return false;\n }\n hdx.init(buildSdkOptions(config, ingest, window.location.origin));\n tapSdkInputs();\n setExceptionReporter((error, attributes) => {\n if (alreadyRecorded(error)) {\n return;\n }\n hdx.recordException(error, attributes);\n });\n return true;\n } catch (err) {\n // Blocked chunk, ad-blocker, SDK throw: telemetry must never break the app.\n console.debug(\"[telemetry] disabled:\", err);\n return false;\n }\n}\n\n// ── One failure, one record ──────────────────────────────────────────────\n//\n// The SDK records an Error that reaches window \"error\", window\n// \"unhandledrejection\", or console.error. React (18 and 19) console.errors an\n// error a boundary catches BEFORE it calls componentDidCatch, and Next\n// dispatches an uncaught render error to window \"error\" — so by the time\n// reportException runs, the SDK has usually recorded that very error already.\n// Recording it again would count one failure twice, and the issue layer\n// (which groups by fingerprint) would report two.\n//\n// So the taps below remember which Error OBJECTS the SDK was shown, and the\n// installed recorder skips those. Whatever the SDK did not see — a custom\n// onCaughtError that silences React's logging, an error rethrown as a new\n// object — is still recorded. The console tap is installed after the SDK's own\n// wrapper, so it sits outermost and only observes; every call is forwarded\n// untouched.\n//\n// The cost is the React component stack: the SDK's record of a boundary-caught\n// error comes from console.error(error), which carries the error and its\n// stack but not React's componentStack, and attributes passed to a skipped\n// reportException are dropped with it.\nconst seenBySdk = new WeakSet<object>();\nlet tapped = false;\n\nfunction noteSeen(value: unknown): void {\n if (typeof value === \"object\" && value !== null) {\n seenBySdk.add(value);\n }\n}\n\nfunction tapSdkInputs(): void {\n if (tapped) {\n return;\n }\n tapped = true;\n const wrapped = console.error;\n console.error = function (this: unknown, ...args: unknown[]) {\n for (const arg of args) {\n if (arg instanceof Error) {\n noteSeen(arg);\n }\n }\n return wrapped.apply(this, args);\n };\n window.addEventListener(\"error\", (e) => noteSeen(e.error), true);\n window.addEventListener(\n \"unhandledrejection\",\n (e) => noteSeen(e.reason),\n true,\n );\n}\n\nfunction alreadyRecorded(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && seenBySdk.has(error);\n}\n\n/**\n * The options passed to HyperDX.init. Exported for tests and for apps that\n * want to see exactly what is configured — it is pure.\n */\nexport function buildSdkOptions(\n config: BrowserTelemetryConfig,\n ingestUrl: string,\n pageOrigin: string,\n): Record<string, unknown> {\n const replay = config.replay === true;\n const resourceAttributes: Record<string, string> = {};\n if (config.serviceVersion) {\n resourceAttributes[\"service.version\"] = config.serviceVersion;\n }\n if (config.serviceNamespace) {\n resourceAttributes[\"service.namespace\"] = config.serviceNamespace;\n }\n if (config.environment) {\n resourceAttributes[\"deployment.environment.name\"] = config.environment;\n resourceAttributes[\"deployment.environment\"] = config.environment;\n }\n\n const options: Record<string, unknown> = {\n apiKey: PLACEHOLDER_API_KEY,\n service: config.serviceName,\n url: ingestUrl,\n tracePropagationTargets: propagationTargets(pageOrigin, config.apiOrigins),\n // The SDK would otherwise trace its own exports, and it must never\n // observe the route it ships through.\n ignoreUrls: [new RegExp(`^${escapeRegExp(ingestUrl)}`)],\n consoleCapture: config.consoleCapture ?? true,\n advancedNetworkCapture: config.advancedNetworkCapture ?? false,\n // Polls for window.Intercom on a timer; nothing here uses Intercom.\n disableIntercom: true,\n disableReplay: !replay,\n otelResourceAttributes: resourceAttributes,\n debug: config.debug ?? false,\n };\n if (replay) {\n // The SDK's own default masks inputs but NOT text; text is where chat\n // content and records live. Force both.\n options.maskAllInputs = true;\n options.maskAllText = true;\n options.recordCanvas = false;\n }\n return options;\n}\n\n/**\n * resolveIngestUrl turns the configured endpoint into the absolute URL the SDK\n * is given, or null when telemetry is off. A path resolves against the page\n * origin, so the default is same-origin by construction.\n */\nexport function resolveIngestUrl(\n endpoint: string | undefined,\n pageOrigin: string,\n): string | null {\n const value = (endpoint ?? \"\").trim();\n if (value === \"\" || value.toLowerCase() === \"off\") {\n return null;\n }\n try {\n return new URL(value, pageOrigin).toString().replace(/\\/+$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction propagationTargets(\n pageOrigin: string,\n apiOrigins: Array<string | undefined> = [],\n): RegExp[] {\n const origins = new Set<string>([pageOrigin]);\n for (const raw of apiOrigins) {\n if (!raw) {\n continue;\n }\n try {\n origins.add(new URL(raw, pageOrigin).origin);\n } catch {\n // An unparsable origin is not a target.\n }\n }\n return [...origins].map((o) => new RegExp(`^${escapeRegExp(o)}(?:[/?#]|$)`));\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// @hyperdx/browser is a UMD/CJS bundle whose module.exports IS the client, and\n// its methods use `this`. A bundler hands back a module NAMESPACE that exposes\n// both the client's members at the top level (as read-only getters) and the\n// client itself as `default`. Calling init on the namespace binds `this` to that\n// frozen object and the SDK throws on its first property write, which disabled\n// telemetry silently. So descend to the deepest `default` that is still a\n// client, the real instance, and never settle for the namespace in front of it.\nfunction resolveClient(mod: unknown): HyperDXClient | null {\n let cur: unknown = mod;\n for (let depth = 0; depth < 4; depth++) {\n const next = peek(cur, \"default\");\n if (!isClient(next)) {\n break;\n }\n cur = next;\n }\n return isClient(cur) ? cur : null;\n}\n\nfunction isClient(v: unknown): v is HyperDXClient {\n return (\n typeof peek(v, \"init\") === \"function\" &&\n typeof peek(v, \"recordException\") === \"function\"\n );\n}\n\n// A module namespace object may throw on an absent key (strict ESM\n// interop shims and test doubles do), and \"absent\" is an answer here.\nfunction peek(obj: unknown, key: string): unknown {\n try {\n return (obj as Record<string, unknown>)[key];\n } catch {\n return undefined;\n }\n}\n\n/** The tracer to open manual spans on. Resolves HyperDX's provider once it is running. */\nexport function getTracer(name = \"default\") {\n return trace.getTracer(name);\n}\n\nexport { context, propagation, trace } from \"@opentelemetry/api\";\n"]}
1
+ {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,yEAAyE;AACzE,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,iEAAiE;AACjE,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,iEAAiE;AACjE,sEAAsE;AACtE,2EAA2E;AAC3E,8EAA8E;AAC9E,wEAAwE;AACxE,4EAA4E;AAC5E,4EAA4E;AAC5E,mDAAmD;AACnD,EAAE;AACF,6EAA6E;AAC7E,wEAAwE;AACxE,8EAA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,+CAA+C;AAC/C,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,yEAAyE;AACzE,8EAA8E;AAC9E,+EAA+E;AAC/E,2EAA2E;AAC3E,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,+EAA+E;AAC/E,0EAA0E;AAC1E,8EAA8E;AAC9E,wEAAwE;AACxE,EAAE;AACF,2EAA2E;AAC3E,EAAE;AACF,2EAA2E;AAC3E,gFAAgF;AAChF,2EAA2E;AAC3E,+EAA+E;AAC/E,gFAAgF;AAChF,0EAA0E;AAC1E,8CAA8C;AAC9C,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,wCAAwC;AACxC,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,yEAAyE;AACzE,2EAA2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CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAClC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YACpB,MAAM;QACR,CAAC;QACD,GAAG,GAAG,IAAI,CAAC;IACb,CAAC;IACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AACpC,CAAC;AAED,SAAS,QAAQ,CAAC,CAAU;IAC1B,OAAO,CACL,OAAO,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,UAAU;QACrC,OAAO,IAAI,CAAC,CAAC,EAAE,iBAAiB,CAAC,KAAK,UAAU,CACjD,CAAC;AACJ,CAAC;AAED,mEAAmE;AACnE,sEAAsE;AACtE,SAAS,IAAI,CAAC,GAAY,EAAE,GAAW;IACrC,IAAI,CAAC;QACH,OAAQ,GAA+B,CAAC,GAAG,CAAC,CAAC;IAC/C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,SAAS,CAAC,IAAI,GAAG,SAAS;IACxC,OAAO,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAED,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Browser telemetry: the HyperDX browser SDK, initialised the forge way.\n//\n// Captures errors (uncaught, unhandled rejections, boundary-caught), console\n// output, fetch/XHR spans, document load, long tasks and web vitals, and\n// ships them to ClickStack through a SAME-ORIGIN `/_otel` route.\n//\n// ── Why HyperDX REPLACES the old OTel web wiring, not joins it ───────────\n//\n// @hyperdx/browser wraps @hyperdx/otel-web, which builds its own\n// WebTracerProvider and calls provider.register() — the global tracer\n// provider, context manager and propagator. A second registration (the old\n// `./otel` subpath did exactly that) is rejected by @opentelemetry/api with a\n// \"duplicate registration\" diagnostic and silently loses: whichever ran\n// second would simply never see a span. Two tracer providers cannot coexist\n// in one page, so there is one, and it is HyperDX's. `./otel` and its eight\n// @opentelemetry/* SDK peer dependencies are gone.\n//\n// traceparent on RPCs is unaffected. traceInterceptor (trace.ts) injects the\n// active span's context into every Connect call, or synthesises a valid\n// traceparent when none is active — with no SDK at all. With the SDK running,\n// the fetch span HyperDX opens for the call carries the same trace id, and\n// `apiOrigins` below makes that hold for a cross-origin API too (which is\n// every dev loop: the API binds its own port).\n//\n// ── The browser holds no secret ──────────────────────────────────────────\n//\n// `url` is `${location.origin}/_otel`. The browser talks only to its own\n// origin; a dev-server proxy (next.config.ts rewrites / Vite server.proxy) or\n// the deployment's ingress forwards `/_otel/v1/{traces,logs}` to the OTLP/HTTP\n// port of a collector, and that hop — never the bundle — owns credentials.\n//\n// The SDK nevertheless wants an `apiKey` and sends it as an `authorization`\n// header. We pass PLACEHOLDER_API_KEY, a constant that grants nothing and is\n// public by construction. A collector that enforces ingestion auth (ClickStack\n// `collectorAuthenticationEnforced`) rejects it with 401, so the proxy in\n// front of such a collector must strip the header or replace it with the real\n// key. The local ClickStack collector does not enforce, and ignores it.\n//\n// ── Replay: shipped, off, masked, media blocked ─────────────────────────\n//\n// The SDK bundles an rrweb recorder. It is DISABLED unless `replay: true`.\n// Privacy is forced, not offered: every input and all text is masked, canvas is\n// never recorded, and images, video, audio, iframes and embeds are BLOCKED\n// (replaced by a same-size placeholder; their pixels never leave the browser).\n// Images are not inlined and web fonts are not collected. There is deliberately\n// no option to turn any of that off while replay is on; an app that needs\n// unmasked replay passes its own SDK options.\n//\n// `replaySampleRate` (0..1, default 1) records only that share of SESSIONS. The\n// SDK has no session sampler, so the decision is made here, once, and held in\n// sessionStorage for the tab's session.\n//\n// ── Network URLs carry no query string ───────────────────────────────────\n//\n// fetch/XHR spans record the request URL, and a query string is where tokens,\n// OAuth codes and search terms live. The runtime rewrites `http.url` and\n// `url.full` on every fetch/XHR span to the URL without query or fragment.\n// The SDK's own `location.href` attribute (the page URL, stamped on every span)\n// has no client-side hook; the ingest side scrubs it.\n//\n// ── Loading ──────────────────────────────────────────────────────────────\n//\n// The SDK is ~600 KB minified (rrweb and the OTel web stack are bundled in\n// it), so it is imported lazily: bundlers split it into its own chunk that\n// loads after the app is interactive and costs the first paint nothing.\n// initBrowserTelemetry is therefore async and idempotent — every caller gets\n// the same promise, which is what survives React StrictMode's double mount and\n// Fast Refresh. It is a no-op without a DOM (SSR, prerender) and without an\n// endpoint, and it never throws.\nimport { trace } from \"@opentelemetry/api\";\n\nimport { setExceptionReporter } from \"./error-reporter.js\";\nimport { registerTelemetryStartup } from \"./telemetry-gate.js\";\nimport {\n isTelemetryDisabled,\n setTelemetrySink,\n type TrackValue,\n} from \"./track.js\";\n\n/** Where the browser ships telemetry: this origin's `/_otel`. */\nexport const DEFAULT_INGEST_PATH = \"/_otel\";\n\n/**\n * The apiKey handed to the SDK. Public by construction: it identifies\n * nothing and authorises nothing. See the header — the proxy or collector\n * owns the real credential.\n */\nexport const PLACEHOLDER_API_KEY = \"forge-browser-public\";\n\nexport interface BrowserTelemetryConfig {\n /** `service.name` on everything this page emits. */\n serviceName: string;\n /** `service.version`. Omit for none. */\n serviceVersion?: string;\n /**\n * The forge environment name. Emitted as BOTH `deployment.environment.name`\n * (current semconv) and `deployment.environment` (the legacy key HyperDX's\n * default sources still key on).\n */\n environment?: string;\n /** `service.namespace`, conventionally the project name. */\n serviceNamespace?: string;\n /**\n * The forge frontend's name, emitted as the `forge.frontend` resource\n * attribute. Unlike `serviceName` (which an app may override to anything) it\n * is the stable key that joins this page's telemetry to the frontend and its\n * source maps. Omit for none.\n */\n frontend?: string;\n /**\n * Ingest base: a path on this origin (`/_otel`) or, as an escape hatch, an\n * absolute URL. Unset, empty, or `off` disables telemetry — the app runs\n * untraced rather than throwing, which is what makes it safe to call\n * unconditionally from the app shell.\n */\n endpoint?: string;\n /**\n * Origins (or URLs — only the origin is used) of the app's own backend.\n * Requests to them always get a `traceparent` from the SDK's fetch/XHR\n * spans. This page's own origin is always included.\n */\n apiOrigins?: Array<string | undefined>;\n /**\n * Mirror console.log/info/warn/debug into telemetry spans. Default true;\n * pass false when console output can hold user content. It does NOT stop\n * `console.error(err)` from being recorded as an error: the SDK's error\n * instrumentation is separate and always on.\n */\n consoleCapture?: boolean;\n /**\n * Capture full request/response headers AND BODIES on fetch/XHR spans.\n * Default false, and it should stay false: bodies are user data.\n */\n advancedNetworkCapture?: boolean;\n /**\n * Session replay (rrweb). Default false. When true, all text and inputs are\n * masked, media is blocked and canvas is not recorded (see the header).\n */\n replay?: boolean;\n /**\n * The share of sessions to record when `replay` is true, 0..1. Default 1\n * (every session). Decided once per session and held in sessionStorage. A\n * value that is not a number records nothing. An app with its own policy\n * (every session of a new user, a fraction of the rest) computes the rate\n * it wants for this session and passes it here.\n */\n replaySampleRate?: number;\n /** Verbose SDK diagnostics to the console. Default false. */\n debug?: boolean;\n}\n\n/** The slice of the SDK this module calls. Typed here, not imported, so the module loads without it. */\ninterface HyperDXClient {\n init(config: Record<string, unknown>): void;\n recordException(error: unknown, attributes?: Record<string, unknown>): void;\n addAction?(name: string, attributes?: Record<string, TrackValue>): void;\n setGlobalAttributes?(attributes: Record<string, string>): void;\n stopSessionRecorder?(): void;\n}\n\nlet started: Promise<boolean> | null = null;\n\n/**\n * initBrowserTelemetry starts the HyperDX browser SDK once per page load and\n * resolves to whether it is running. See the module header for the contract.\n */\nexport function initBrowserTelemetry(\n config: BrowserTelemetryConfig,\n): Promise<boolean> {\n if (typeof window === \"undefined\") {\n return Promise.resolve(false);\n }\n if (started) {\n return started;\n }\n if (isTelemetryDisabled()) {\n return Promise.resolve(false);\n }\n const ingest = resolveIngestUrl(config.endpoint, window.location.origin);\n if (!ingest) {\n // Nothing will ever drain track() calls held for the SDK; let them go.\n setTelemetrySink(null);\n return Promise.resolve(false);\n }\n started = start(config, ingest);\n registerTelemetryStartup(started);\n return started;\n}\n\nasync function start(\n config: BrowserTelemetryConfig,\n ingest: string,\n): Promise<boolean> {\n try {\n const hdx = resolveClient(await import(\"@hyperdx/browser\"));\n if (!hdx || isTelemetryDisabled()) {\n setTelemetrySink(null);\n return false;\n }\n const replay = decideReplay(config, sessionStorageOrNull(), Math.random);\n hdx.init(\n buildSdkOptions({ ...config, replay }, ingest, window.location.origin),\n );\n tapSdkInputs();\n setExceptionReporter((error, attributes) => {\n if (alreadyRecorded(error)) {\n return;\n }\n hdx.recordException(error, attributes);\n });\n setTelemetrySink({\n track: (name, attributes) => hdx.addAction?.(name, attributes),\n setUser: (id) => hdx.setGlobalAttributes?.({ userId: id }),\n disable: () => {\n // Back to \"no SDK\": reportException returns false, so a caller falls\n // back to console.error and the error does not vanish.\n setExceptionReporter(null);\n hdx.stopSessionRecorder?.();\n },\n });\n return true;\n } catch (err) {\n // Blocked chunk, ad-blocker, SDK throw: telemetry must never break the app.\n console.debug(\"[telemetry] disabled:\", err);\n setTelemetrySink(null);\n return false;\n }\n}\n\n// ── One failure, one record ──────────────────────────────────────────────\n//\n// The SDK records an Error that reaches window \"error\", window\n// \"unhandledrejection\", or console.error. React (18 and 19) console.errors an\n// error a boundary catches BEFORE it calls componentDidCatch, and Next\n// dispatches an uncaught render error to window \"error\" — so by the time\n// reportException runs, the SDK has usually recorded that very error already.\n// Recording it again would count one failure twice, and the issue layer\n// (which groups by fingerprint) would report two.\n//\n// So the taps below remember which Error OBJECTS the SDK was shown, and the\n// installed recorder skips those. Whatever the SDK did not see — a custom\n// onCaughtError that silences React's logging, an error rethrown as a new\n// object — is still recorded. The console tap is installed after the SDK's own\n// wrapper, so it sits outermost and only observes; every call is forwarded\n// untouched.\n//\n// The cost is the React component stack: the SDK's record of a boundary-caught\n// error comes from console.error(error), which carries the error and its\n// stack but not React's componentStack, and attributes passed to a skipped\n// reportException are dropped with it.\nconst seenBySdk = new WeakSet<object>();\nlet tapped = false;\n\nfunction noteSeen(value: unknown): void {\n if (typeof value === \"object\" && value !== null) {\n seenBySdk.add(value);\n }\n}\n\nfunction tapSdkInputs(): void {\n if (tapped) {\n return;\n }\n tapped = true;\n const wrapped = console.error;\n console.error = function (this: unknown, ...args: unknown[]) {\n for (const arg of args) {\n if (arg instanceof Error) {\n noteSeen(arg);\n }\n }\n return wrapped.apply(this, args);\n };\n window.addEventListener(\"error\", (e) => noteSeen(e.error), true);\n window.addEventListener(\n \"unhandledrejection\",\n (e) => noteSeen(e.reason),\n true,\n );\n}\n\nfunction alreadyRecorded(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && seenBySdk.has(error);\n}\n\n/**\n * The options passed to HyperDX.init. Exported for tests and for apps that\n * want to see exactly what is configured — it is pure.\n */\nexport function buildSdkOptions(\n config: BrowserTelemetryConfig,\n ingestUrl: string,\n pageOrigin: string,\n): Record<string, unknown> {\n // `config.replay` is the FINAL decision here. initBrowserTelemetry resolves\n // replaySampleRate into it (decideReplay) before calling this.\n const replay = config.replay === true;\n const resourceAttributes: Record<string, string> = {};\n if (config.serviceVersion) {\n resourceAttributes[\"service.version\"] = config.serviceVersion;\n }\n if (config.serviceNamespace) {\n resourceAttributes[\"service.namespace\"] = config.serviceNamespace;\n }\n if (config.frontend) {\n resourceAttributes[\"forge.frontend\"] = config.frontend;\n }\n if (config.environment) {\n resourceAttributes[\"deployment.environment.name\"] = config.environment;\n resourceAttributes[\"deployment.environment\"] = config.environment;\n }\n\n const targets = propagationTargets(pageOrigin, config.apiOrigins);\n const advancedNetworkCapture = config.advancedNetworkCapture ?? false;\n const options: Record<string, unknown> = {\n apiKey: PLACEHOLDER_API_KEY,\n service: config.serviceName,\n url: ingestUrl,\n tracePropagationTargets: targets,\n // The SDK would otherwise trace its own exports, and it must never\n // observe the route it ships through.\n ignoreUrls: [new RegExp(`^${escapeRegExp(ingestUrl)}`)],\n consoleCapture: config.consoleCapture ?? true,\n advancedNetworkCapture,\n // The SDK spreads this over ITS fetch/xhr config as whole keys, so\n // everything it would have set (propagation targets, the capture switch)\n // must be restated here or it is lost.\n instrumentations: {\n fetch: {\n propagateTraceHeaderCorsUrls: targets,\n advancedNetworkCapture: () => advancedNetworkCapture,\n applyCustomAttributesOnSpan: stripNetworkQuery,\n },\n xhr: {\n propagateTraceHeaderCorsUrls: targets,\n advancedNetworkCapture: () => advancedNetworkCapture,\n applyCustomAttributesOnSpan: stripNetworkQuery,\n },\n },\n // Polls for window.Intercom on a timer; nothing here uses Intercom.\n disableIntercom: true,\n disableReplay: !replay,\n otelResourceAttributes: resourceAttributes,\n debug: config.debug ?? false,\n // Privacy is forced and unconditional: no path through this function\n // yields an unmasked or media-recording replay. The SDK's own default\n // masks inputs but NOT text, and text is where chat content and records\n // live.\n maskAllInputs: true,\n maskAllText: true,\n recordCanvas: false,\n blockSelector: REPLAY_BLOCK_SELECTOR,\n replay: { inlineImages: false, collectFonts: false },\n };\n return options;\n}\n\n/** Elements a replay never records: their pixels stay in the browser. */\nexport const REPLAY_BLOCK_SELECTOR =\n \"img, picture, video, audio, iframe, object, embed\";\n\n/** Where a replay sampling decision is held for the tab's session. */\nexport const REPLAY_SAMPLE_KEY = \"forge.replay.sampled\";\n\n/** The slice of Storage the sampling decision needs. */\ninterface DecisionStore {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\n/**\n * Whether this session records a replay: config.replay, then the sample rate,\n * drawn once and remembered in `store` so a reload (or a route change that\n * re-runs init) never re-rolls into a session that only half-recorded. With no\n * usable store the draw is made each load. Pure given its inputs; exported for\n * tests.\n */\nexport function decideReplay(\n config: Pick<BrowserTelemetryConfig, \"replay\" | \"replaySampleRate\">,\n store: DecisionStore | null,\n random: () => number,\n): boolean {\n if (config.replay !== true) {\n return false;\n }\n const rate = clampRate(config.replaySampleRate);\n if (rate >= 1) {\n return true;\n }\n if (rate <= 0) {\n return false;\n }\n try {\n const held = store?.getItem(REPLAY_SAMPLE_KEY);\n if (held === \"1\" || held === \"0\") {\n return held === \"1\";\n }\n } catch {\n // Storage blocked: fall through to a fresh draw.\n }\n const sampled = random() < rate;\n try {\n store?.setItem(REPLAY_SAMPLE_KEY, sampled ? \"1\" : \"0\");\n } catch {\n // Not persisted: the next load draws again.\n }\n return sampled;\n}\n\n// Unset is \"every session\"; anything that is not a number is a bug, and a bug\n// must not start recording people.\nfunction clampRate(rate: number | undefined): number {\n if (rate === undefined) {\n return 1;\n }\n if (typeof rate !== \"number\" || Number.isNaN(rate)) {\n return 0;\n }\n return Math.min(1, Math.max(0, rate));\n}\n\nfunction sessionStorageOrNull(): DecisionStore | null {\n try {\n return window.sessionStorage;\n } catch {\n return null;\n }\n}\n\n/** The span attributes that hold a request URL. */\nconst URL_ATTRIBUTES = [\"http.url\", \"url.full\"] as const;\n\n/** `url` without its query string and fragment. */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n return cut === -1 ? url : url.slice(0, cut);\n}\n\ninterface UrlSpan {\n attributes?: Record<string, unknown>;\n setAttribute(key: string, value: string): unknown;\n}\n\n// applyCustomAttributesOnSpan for both instrumentations: it runs before the\n// span ends, so the rewritten value is the one exported.\nfunction stripNetworkQuery(span: UrlSpan): void {\n for (const key of URL_ATTRIBUTES) {\n const value = span.attributes?.[key];\n if (typeof value === \"string\") {\n const stripped = stripUrlQuery(value);\n if (stripped !== value) {\n span.setAttribute(key, stripped);\n }\n }\n }\n}\n\n/**\n * resolveIngestUrl turns the configured endpoint into the absolute URL the SDK\n * is given, or null when telemetry is off. A path resolves against the page\n * origin, so the default is same-origin by construction.\n */\nexport function resolveIngestUrl(\n endpoint: string | undefined,\n pageOrigin: string,\n): string | null {\n const value = (endpoint ?? \"\").trim();\n if (value === \"\" || value.toLowerCase() === \"off\") {\n return null;\n }\n try {\n return new URL(value, pageOrigin).toString().replace(/\\/+$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction propagationTargets(\n pageOrigin: string,\n apiOrigins: Array<string | undefined> = [],\n): RegExp[] {\n const origins = new Set<string>([pageOrigin]);\n for (const raw of apiOrigins) {\n if (!raw) {\n continue;\n }\n try {\n origins.add(new URL(raw, pageOrigin).origin);\n } catch {\n // An unparsable origin is not a target.\n }\n }\n return [...origins].map((o) => new RegExp(`^${escapeRegExp(o)}(?:[/?#]|$)`));\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// @hyperdx/browser is a UMD/CJS bundle whose module.exports IS the client, and\n// its methods use `this`. A bundler hands back a module NAMESPACE that exposes\n// both the client's members at the top level (as read-only getters) and the\n// client itself as `default`. Calling init on the namespace binds `this` to that\n// frozen object and the SDK throws on its first property write, which disabled\n// telemetry silently. So descend to the deepest `default` that is still a\n// client, the real instance, and never settle for the namespace in front of it.\nfunction resolveClient(mod: unknown): HyperDXClient | null {\n let cur: unknown = mod;\n for (let depth = 0; depth < 4; depth++) {\n const next = peek(cur, \"default\");\n if (!isClient(next)) {\n break;\n }\n cur = next;\n }\n return isClient(cur) ? cur : null;\n}\n\nfunction isClient(v: unknown): v is HyperDXClient {\n return (\n typeof peek(v, \"init\") === \"function\" &&\n typeof peek(v, \"recordException\") === \"function\"\n );\n}\n\n// A module namespace object may throw on an absent key (strict ESM\n// interop shims and test doubles do), and \"absent\" is an answer here.\nfunction peek(obj: unknown, key: string): unknown {\n try {\n return (obj as Record<string, unknown>)[key];\n } catch {\n return undefined;\n }\n}\n\n/** The tracer to open manual spans on. Resolves HyperDX's provider once it is running. */\nexport function getTracer(name = \"default\") {\n return trace.getTracer(name);\n}\n\nexport { context, propagation, trace } from \"@opentelemetry/api\";\n"]}
@@ -0,0 +1,72 @@
1
+ /** Most events held while the SDK is still loading. Later calls are dropped. */
2
+ export declare const MAX_QUEUED_EVENTS = 100;
3
+ /** Most props kept on one event; the rest are dropped in insertion order. */
4
+ export declare const MAX_PROP_KEYS = 20;
5
+ /** Longest string prop value, after redaction. */
6
+ export declare const MAX_PROP_VALUE_CHARS = 256;
7
+ /** Longest event name. */
8
+ export declare const MAX_EVENT_NAME_CHARS = 128;
9
+ /** Longest user id. */
10
+ export declare const MAX_USER_ID_CHARS = 128;
11
+ /** A prop key is a dotted lowercase identifier. */
12
+ export declare const PROP_KEY_RE: RegExp;
13
+ /** What a redacted credential becomes. */
14
+ export declare const REDACTED = "[redacted]";
15
+ /** A prop value an event may carry. Anything else is dropped. */
16
+ export type TrackValue = string | number | boolean;
17
+ /** Props accepted by track(); non-conforming entries are dropped, not thrown on. */
18
+ export type TrackProps = Record<string, unknown>;
19
+ /** What the `/telemetry` subpath installs once the SDK is running. */
20
+ export interface TelemetrySink {
21
+ track(name: string, attributes: Record<string, TrackValue>): void;
22
+ setUser(id: string): void;
23
+ disable(): void;
24
+ }
25
+ /** Redact credential shapes from a string. Exported for tests. */
26
+ export declare function redactSecrets(value: string): string;
27
+ /**
28
+ * Reduce caller props to what an event may carry: bounded, typed, redacted.
29
+ * Pure; exported for tests.
30
+ */
31
+ export declare function sanitizeProps(props: TrackProps | undefined): Record<string, TrackValue>;
32
+ /**
33
+ * Record a product event — a funnel step, a feature used — as a span on the
34
+ * current session. Never throws, and is a no-op on the server, after
35
+ * disableTelemetry(), and (once the SDK has started) whenever telemetry is
36
+ * off. Calls made while the SDK is still loading are held, up to
37
+ * MAX_QUEUED_EVENTS, and replayed in order.
38
+ *
39
+ * `name` is a stable, low-cardinality event name ("onboarding_completed"),
40
+ * not a sentence. `props` is bounded and redacted as described in the module
41
+ * header; do not put user content in it.
42
+ */
43
+ export declare function track(name: string, props?: TrackProps): void;
44
+ /**
45
+ * Attach the signed-in user's id to every span and replay from here on, so an
46
+ * error, a funnel step and a replay can be joined to a user. Pass an opaque
47
+ * id — never an email, a name or anything else a person would recognise. Pass
48
+ * null (sign-out) to clear it.
49
+ *
50
+ * The id is carried as the `userId` global attribute. The SDK has no way to
51
+ * delete an attribute, so clearing writes an empty `userId`. Held until the
52
+ * SDK has started; the last call wins.
53
+ */
54
+ export declare function setTelemetryUser(id: string | null | undefined): void;
55
+ /**
56
+ * Turn browser telemetry off for the rest of this page load: stop the replay
57
+ * recorder, drop anything held, and make track(), setTelemetryUser() and
58
+ * reportException() no-ops. For when the user withdraws consent mid-session.
59
+ * See the module header for what it cannot undo.
60
+ */
61
+ export declare function disableTelemetry(): void;
62
+ /** Whether disableTelemetry() has been called. Read by the installed recorder. */
63
+ export declare function isTelemetryDisabled(): boolean;
64
+ /**
65
+ * Install (or clear, with null) the sink track() forwards to, replaying
66
+ * whatever was held. Called by initBrowserTelemetry; an app has no reason to
67
+ * call it directly. Clearing also drops what was held, so a start that failed
68
+ * does not keep a queue nobody will drain.
69
+ */
70
+ export declare function setTelemetrySink(next: TelemetrySink | null): void;
71
+ /** Test seam. */
72
+ export declare function resetTrackState(): void;