@squasher-ai/browser-logger 0.1.1 → 0.3.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 (47) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1 -1
  3. package/dist/_vendor/result-runtime/attempt.d.ts +17 -0
  4. package/dist/_vendor/result-runtime/attempt.js +62 -0
  5. package/dist/_vendor/sdk-runtime/batching/index.d.ts +42 -0
  6. package/dist/_vendor/sdk-runtime/batching/index.js +48 -0
  7. package/dist/_vendor/sdk-runtime/errors/headers.d.ts +6 -0
  8. package/dist/_vendor/sdk-runtime/errors/headers.js +44 -0
  9. package/dist/_vendor/sdk-runtime/errors/index.d.ts +95 -0
  10. package/dist/_vendor/sdk-runtime/errors/index.js +157 -0
  11. package/dist/_vendor/sdk-runtime/headers.d.ts +48 -0
  12. package/dist/_vendor/sdk-runtime/headers.js +67 -0
  13. package/dist/_vendor/sdk-runtime/platform.d.ts +33 -0
  14. package/dist/_vendor/sdk-runtime/platform.js +173 -0
  15. package/dist/_vendor/sdk-runtime/retry.d.ts +50 -0
  16. package/dist/_vendor/sdk-runtime/retry.js +104 -0
  17. package/dist/_vendor/sdk-runtime/runtime/actionable-error.d.ts +37 -0
  18. package/dist/_vendor/sdk-runtime/runtime/actionable-error.js +123 -0
  19. package/dist/_vendor/sdk-runtime/runtime/environment.d.ts +18 -0
  20. package/dist/_vendor/sdk-runtime/runtime/environment.js +81 -0
  21. package/dist/_vendor/sdk-runtime/runtime/public-sdk-runtime.d.ts +12 -0
  22. package/dist/_vendor/sdk-runtime/runtime/public-sdk-runtime.js +38 -0
  23. package/dist/_vendor/sdk-runtime/runtime/redaction.d.ts +14 -0
  24. package/dist/_vendor/sdk-runtime/runtime/redaction.js +120 -0
  25. package/dist/_vendor/sdk-runtime/runtime/release.d.ts +35 -0
  26. package/dist/_vendor/sdk-runtime/runtime/release.js +120 -0
  27. package/dist/_vendor/sdk-runtime/sampling/index.d.ts +43 -0
  28. package/dist/_vendor/sdk-runtime/sampling/index.js +70 -0
  29. package/dist/browser-logger.d.ts +2 -3
  30. package/dist/browser-logger.js +5 -5
  31. package/dist/browser-logger.umd.js +598 -131
  32. package/dist/index.d.ts +4 -5
  33. package/dist/index.js +2 -2
  34. package/dist/serializer.d.ts +1 -2
  35. package/dist/serializer.js +62 -75
  36. package/dist/transport.d.ts +21 -5
  37. package/dist/transport.js +45 -42
  38. package/dist/types.d.ts +0 -1
  39. package/package.json +6 -6
  40. package/dist/browser-logger.d.ts.map +0 -1
  41. package/dist/global.d.ts +0 -14
  42. package/dist/global.d.ts.map +0 -1
  43. package/dist/global.js +0 -14
  44. package/dist/index.d.ts.map +0 -1
  45. package/dist/serializer.d.ts.map +0 -1
  46. package/dist/transport.d.ts.map +0 -1
  47. package/dist/types.d.ts.map +0 -1
@@ -0,0 +1,14 @@
1
+ export type RedactableValue = boolean | null | number | string | RedactableValue[] | {
2
+ [key: string]: RedactableValue;
3
+ };
4
+ export type RedactorKeyMask = RegExp | string;
5
+ export type RedactorPathSegment = number | string;
6
+ export type RedactorPathMask = readonly RedactorPathSegment[] | string;
7
+ export interface RedactorOptions {
8
+ mask?: string;
9
+ keyMasks?: readonly RedactorKeyMask[];
10
+ pathMasks?: readonly RedactorPathMask[];
11
+ patternMasks?: readonly RegExp[];
12
+ }
13
+ export type Redactor = (value: RedactableValue) => RedactableValue;
14
+ export declare function createRedactor(options?: RedactorOptions): Redactor;
@@ -0,0 +1,120 @@
1
+ const DEFAULT_MASK = "[REDACTED]";
2
+ const EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
3
+ const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+\b/gi;
4
+ const JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g;
5
+ const API_KEY_PATTERN = /\b(?:sk|pk|sq|squasher)_(?:pk|sk|live|test|dev|prod)?_?[A-Za-z0-9_-]{16,}\b/g;
6
+ const SENSITIVE_KEY_PARTS = [
7
+ "apikey",
8
+ "authorization",
9
+ "authtoken",
10
+ "bearertoken",
11
+ "clientsecret",
12
+ "cookie",
13
+ "idtoken",
14
+ "password",
15
+ "passwd",
16
+ "privatekey",
17
+ "refreshtoken",
18
+ "secret",
19
+ "sessiontoken",
20
+ "squasherkey",
21
+ "token",
22
+ ];
23
+ export function createRedactor(options = {}) {
24
+ const config = {
25
+ mask: options.mask ?? DEFAULT_MASK,
26
+ keyMasks: options.keyMasks ?? [],
27
+ pathMasks: options.pathMasks ?? [],
28
+ patternMasks: options.patternMasks ?? [],
29
+ };
30
+ return (value) => redactValue(value, [], config);
31
+ }
32
+ function redactValue(value, path, config) {
33
+ if (Object.prototype.toString.call(value) === "[object String]") {
34
+ return redactString(String(value), config);
35
+ }
36
+ if (Array.isArray(value)) {
37
+ return value.map((item, index) => redactValue(item, [...path, index], config));
38
+ }
39
+ if (!isRedactableRecord(value))
40
+ return value;
41
+ const result = {};
42
+ for (const [key, item] of Object.entries(value)) {
43
+ const itemPath = [...path, key];
44
+ result[key] = shouldMaskField(key, itemPath, config)
45
+ ? config.mask
46
+ : redactValue(item, itemPath, config);
47
+ }
48
+ return result;
49
+ }
50
+ function isRedactableRecord(value) {
51
+ if (value === null)
52
+ return false;
53
+ try {
54
+ const prototype = Object.getPrototypeOf(Object(value));
55
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ function redactString(value, config) {
62
+ let redacted = value
63
+ .replace(EMAIL_PATTERN, config.mask)
64
+ .replace(BEARER_PATTERN, `Bearer ${config.mask}`)
65
+ .replace(JWT_PATTERN, config.mask)
66
+ .replace(API_KEY_PATTERN, config.mask);
67
+ for (const pattern of config.patternMasks) {
68
+ redacted = redacted.replace(globalPattern(pattern), config.mask);
69
+ }
70
+ return redacted;
71
+ }
72
+ function shouldMaskField(key, path, config) {
73
+ if (isSensitiveKey(key))
74
+ return true;
75
+ if (config.keyMasks.some((mask) => matchesKeyMask(mask, key)))
76
+ return true;
77
+ return config.pathMasks.some((mask) => matchesPathMask(mask, path));
78
+ }
79
+ function isSensitiveKey(key) {
80
+ const normalized = normalizeSegment(key);
81
+ return SENSITIVE_KEY_PARTS.some((part) => normalized.includes(part));
82
+ }
83
+ function matchesKeyMask(mask, key) {
84
+ if (isRegularExpression(mask)) {
85
+ mask.lastIndex = 0;
86
+ return RegExp.prototype.test.call(mask, key);
87
+ }
88
+ return normalizeSegment(String(mask)) === normalizeSegment(key);
89
+ }
90
+ function matchesPathMask(mask, path) {
91
+ const maskPath = Array.isArray(mask) ? mask : splitPath(String(mask));
92
+ if (maskPath.length !== path.length)
93
+ return false;
94
+ for (let index = 0; index < maskPath.length; index += 1) {
95
+ const segment = maskPath[index];
96
+ if (segment === "*")
97
+ continue;
98
+ if (normalizePathSegment(segment) !== normalizePathSegment(path[index]))
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ function isRegularExpression(mask) {
104
+ return Object.prototype.toString.call(mask) === "[object RegExp]";
105
+ }
106
+ function splitPath(path) {
107
+ return path.split(".").filter((segment) => segment.length > 0);
108
+ }
109
+ function normalizePathSegment(segment) {
110
+ return Object.prototype.toString.call(segment) === "[object Number]"
111
+ ? String(segment)
112
+ : normalizeSegment(String(segment ?? ""));
113
+ }
114
+ function normalizeSegment(segment) {
115
+ return segment.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
116
+ }
117
+ function globalPattern(pattern) {
118
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
119
+ return new RegExp(pattern.source, flags);
120
+ }
@@ -0,0 +1,35 @@
1
+ import { type RuntimeEnvironment } from "./environment.js";
2
+ /**
3
+ * `canonical` is what every consumer should display / store: v-prefix
4
+ * stripped, `service@version+build` form rebuilt from the parsed components,
5
+ * so `v1.2.3` and `1.2.3` (or two inputs with different whitespace) compare
6
+ * equal by `canonical`.
7
+ */
8
+ export interface ParsedRelease {
9
+ canonical: string;
10
+ service: string | null;
11
+ version: string;
12
+ build: string | null;
13
+ isSemver: boolean;
14
+ }
15
+ export type ReleaseInput = string | null | undefined;
16
+ /**
17
+ * Parse + validate a release string. Returns `null` for empty input, junk
18
+ * sentinels, values over 200 chars, or strings with whitespace / control chars.
19
+ * Accepts: `1.2.3`, `v1.2.3`, `svc@1.2.3`, `svc@1.2.3+sha`, `1.2.3+sha`, and
20
+ * bare git shas (non-semver but valid).
21
+ */
22
+ export declare function parseRelease(input: ReleaseInput): ParsedRelease | null;
23
+ /**
24
+ * True when `parseRelease(input)` would accept the value. Pure boolean — use
25
+ * this at validation boundaries that don't need the parsed pieces (e.g. zod
26
+ * `.refine()`, ingest pre-filters).
27
+ */
28
+ export declare function isValidRelease(input: ReleaseInput): input is string;
29
+ /**
30
+ * Auto-detect a release from common CI/host env vars so customers on
31
+ * Vercel / Railway / Render / Fly / GitHub Actions get a useful release tag
32
+ * without configuring anything. Explicit `SQUASHER_RELEASE` always wins;
33
+ * values that fail `parseRelease` are skipped and detection continues.
34
+ */
35
+ export declare function detectRelease(env?: Readonly<RuntimeEnvironment>): string | null;
@@ -0,0 +1,120 @@
1
+ import { readProcessEnvironment } from "./environment.js";
2
+ const MAX_LEN = 200;
3
+ const JUNK_VALUES = new Set([
4
+ "",
5
+ "undefined",
6
+ "null",
7
+ "nan",
8
+ "latest",
9
+ "unknown",
10
+ "(none)",
11
+ "n/a",
12
+ "none",
13
+ ]);
14
+ const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9a-zA-Z.-]+)?$/;
15
+ const VERSION_CHAR_RE = /^[A-Za-z0-9._-]+$/;
16
+ const BUILD_CHAR_RE = /^[A-Za-z0-9._-]+$/;
17
+ const SERVICE_CHAR_RE = /^[A-Za-z0-9._/@-]+$/;
18
+ /**
19
+ * Parse + validate a release string. Returns `null` for empty input, junk
20
+ * sentinels, values over 200 chars, or strings with whitespace / control chars.
21
+ * Accepts: `1.2.3`, `v1.2.3`, `svc@1.2.3`, `svc@1.2.3+sha`, `1.2.3+sha`, and
22
+ * bare git shas (non-semver but valid).
23
+ */
24
+ export function parseRelease(input) {
25
+ if (Object.prototype.toString.call(input) !== "[object String]")
26
+ return null;
27
+ const raw = String(input).trim();
28
+ if (raw.length === 0 || raw.length > MAX_LEN)
29
+ return null;
30
+ if (JUNK_VALUES.has(raw.toLowerCase()))
31
+ return null;
32
+ // Reject whitespace + ASCII control chars (NUL..US, DEL).
33
+ // oxlint-disable-next-line no-control-regex
34
+ if (/[\s\x00-\x1f\x7f]/.test(raw))
35
+ return null;
36
+ // Only the LAST `@` separates service from version, so npm-style scopes
37
+ // like `@org/pkg@1.2.3` parse with `@org/pkg` as the service.
38
+ const atIndex = raw.lastIndexOf("@");
39
+ let service = null;
40
+ let rest = raw;
41
+ if (atIndex >= 0) {
42
+ const left = raw.slice(0, atIndex);
43
+ const right = raw.slice(atIndex + 1);
44
+ if (right.length === 0)
45
+ return null;
46
+ service = left.length > 0 ? left : null;
47
+ rest = right;
48
+ }
49
+ if (service !== null && !SERVICE_CHAR_RE.test(service))
50
+ return null;
51
+ const plusIndex = rest.indexOf("+");
52
+ let version;
53
+ let build;
54
+ if (plusIndex >= 0) {
55
+ version = rest.slice(0, plusIndex);
56
+ build = rest.slice(plusIndex + 1);
57
+ if (version.length === 0 || build.length === 0)
58
+ return null;
59
+ if (!BUILD_CHAR_RE.test(build))
60
+ return null;
61
+ }
62
+ else {
63
+ version = rest;
64
+ build = null;
65
+ }
66
+ if (!VERSION_CHAR_RE.test(version))
67
+ return null;
68
+ // Strip a `v` prefix only when followed by a digit — don't eat the first
69
+ // character of names like `viper`.
70
+ const normalizedVersion = version.length > 1 &&
71
+ (version[0] === "v" || version[0] === "V") &&
72
+ /[0-9]/.test(version[1] ?? "")
73
+ ? version.slice(1)
74
+ : version;
75
+ const isSemver = SEMVER_RE.test(normalizedVersion);
76
+ const canonical = [
77
+ service !== null ? `${service}@` : "",
78
+ normalizedVersion,
79
+ build !== null ? `+${build}` : "",
80
+ ].join("");
81
+ return { canonical, service, version: normalizedVersion, build, isSemver };
82
+ }
83
+ /**
84
+ * True when `parseRelease(input)` would accept the value. Pure boolean — use
85
+ * this at validation boundaries that don't need the parsed pieces (e.g. zod
86
+ * `.refine()`, ingest pre-filters).
87
+ */
88
+ export function isValidRelease(input) {
89
+ return parseRelease(input) !== null;
90
+ }
91
+ /**
92
+ * Auto-detect a release from common CI/host env vars so customers on
93
+ * Vercel / Railway / Render / Fly / GitHub Actions get a useful release tag
94
+ * without configuring anything. Explicit `SQUASHER_RELEASE` always wins;
95
+ * values that fail `parseRelease` are skipped and detection continues.
96
+ */
97
+ export function detectRelease(env = readProcessEnvironment()) {
98
+ const candidates = [
99
+ env.SQUASHER_RELEASE,
100
+ env.VERCEL_GIT_COMMIT_SHA,
101
+ env.RAILWAY_GIT_COMMIT_SHA,
102
+ env.RENDER_GIT_COMMIT,
103
+ env.FLY_MACHINE_VERSION,
104
+ env.GITHUB_SHA,
105
+ npmPackageCandidate(env),
106
+ ];
107
+ for (const value of candidates) {
108
+ const parsed = parseRelease(value);
109
+ if (parsed !== null)
110
+ return parsed.canonical;
111
+ }
112
+ return null;
113
+ }
114
+ function npmPackageCandidate(env) {
115
+ const version = env.npm_package_version;
116
+ if (!version)
117
+ return null;
118
+ const name = env.npm_package_name;
119
+ return name ? `${name}@${version}` : version;
120
+ }
@@ -0,0 +1,43 @@
1
+ interface TelemetrySamplingConfig {
2
+ successRate?: number;
3
+ errorRate?: number;
4
+ slowRate?: number;
5
+ slowThresholdMs?: number;
6
+ alwaysSampleUserIds?: string[];
7
+ alwaysSampleReleases?: string[];
8
+ }
9
+ type SamplingAttributePrimitive = boolean | null | number | string;
10
+ type SamplingAttributeValue = SamplingAttributePrimitive | SamplingAttributeValue[] | SamplingAttributes;
11
+ interface SamplingAttributes {
12
+ [key: string]: SamplingAttributeValue;
13
+ }
14
+ interface SamplingEvent {
15
+ attributes?: SamplingAttributes;
16
+ distinct_id?: string;
17
+ event_name?: string;
18
+ kind?: string;
19
+ level?: string;
20
+ message: string;
21
+ release?: string;
22
+ session_id?: string;
23
+ timestamp?: number | string;
24
+ trace?: {
25
+ duration_ms?: number;
26
+ status?: string;
27
+ trace_id?: string;
28
+ };
29
+ user?: {
30
+ id?: string;
31
+ };
32
+ }
33
+ export interface ResolvedTelemetrySampling {
34
+ successRate: number;
35
+ errorRate: number;
36
+ slowRate: number;
37
+ slowThresholdMs: number;
38
+ alwaysSampleUserIds: ReadonlySet<string>;
39
+ alwaysSampleReleases: ReadonlySet<string>;
40
+ }
41
+ export declare function resolveTelemetrySampling(config: TelemetrySamplingConfig | undefined): ResolvedTelemetrySampling;
42
+ export declare function shouldSampleTelemetry(event: SamplingEvent, config: ResolvedTelemetrySampling): boolean;
43
+ export {};
@@ -0,0 +1,70 @@
1
+ export function resolveTelemetrySampling(config) {
2
+ return {
3
+ successRate: rate(config?.successRate, 1),
4
+ errorRate: rate(config?.errorRate, 1),
5
+ slowRate: rate(config?.slowRate, 1),
6
+ slowThresholdMs: Math.max(0, config?.slowThresholdMs ?? 1_000),
7
+ alwaysSampleUserIds: new Set(config?.alwaysSampleUserIds ?? []),
8
+ alwaysSampleReleases: new Set(config?.alwaysSampleReleases ?? []),
9
+ };
10
+ }
11
+ export function shouldSampleTelemetry(event, config) {
12
+ if ((event.distinct_id && config.alwaysSampleUserIds.has(event.distinct_id)) ||
13
+ (event.user?.id && config.alwaysSampleUserIds.has(event.user.id)))
14
+ return true;
15
+ if (event.release && config.alwaysSampleReleases.has(event.release))
16
+ return true;
17
+ // AI generation events are metered usage: dropping them would under-report
18
+ // tokens, cost, and cache reads on the AI dashboards, so they are never sampled.
19
+ if (event.kind === "llm_generation")
20
+ return true;
21
+ // Events in one trace share a hash input, but each outcome class applies its
22
+ // configured threshold. This correlates their decisions without pretending
23
+ // that event sampling is whole-trace tail sampling.
24
+ const durationMs = event.trace?.duration_ms;
25
+ const selectedRate = isFailure(event)
26
+ ? config.errorRate
27
+ : durationMs !== undefined && durationMs >= config.slowThresholdMs
28
+ ? config.slowRate
29
+ : config.successRate;
30
+ if (selectedRate >= 1)
31
+ return true;
32
+ if (selectedRate <= 0)
33
+ return false;
34
+ return stableFraction(sampleKey(event)) < selectedRate;
35
+ }
36
+ function isFailure(event) {
37
+ if (event.level === "fatal" || event.level === "error" || event.level === "warning")
38
+ return true;
39
+ if (event.kind === "error" || event.trace?.status === "error")
40
+ return true;
41
+ const outcome = event.attributes?.["squasher.outcome"] ?? event.attributes?.outcome;
42
+ return outcome === "failure" || outcome === "error";
43
+ }
44
+ function sampleKey(event) {
45
+ if (event.trace?.trace_id)
46
+ return `trace:${event.trace.trace_id}`;
47
+ return [
48
+ event.session_id,
49
+ event.distinct_id,
50
+ event.user?.id,
51
+ event.event_name,
52
+ event.message,
53
+ event.timestamp === undefined ? undefined : String(event.timestamp),
54
+ ]
55
+ .filter((value) => Boolean(value))
56
+ .join("|");
57
+ }
58
+ function stableFraction(value) {
59
+ let hash = 2166136261;
60
+ for (let index = 0; index < value.length; index++) {
61
+ hash ^= value.charCodeAt(index);
62
+ hash = Math.imul(hash, 16777619);
63
+ }
64
+ return (hash >>> 0) / 0x1_0000_0000;
65
+ }
66
+ function rate(value, fallback) {
67
+ if (value === undefined || !Number.isFinite(value))
68
+ return fallback;
69
+ return Math.min(1, Math.max(0, value));
70
+ }
@@ -1,4 +1,4 @@
1
- import type { BrowserLoggerConfig } from "./types";
1
+ import type { BrowserLoggerConfig } from "./types.js";
2
2
  export declare class BrowserLogger {
3
3
  private readonly config;
4
4
  private readonly transport;
@@ -7,7 +7,6 @@ export declare class BrowserLogger {
7
7
  constructor(config: BrowserLoggerConfig);
8
8
  flush(): Promise<void>;
9
9
  close(): Promise<void>;
10
- private installConsoleErrorCapture;
10
+ protected installConsoleErrorCapture(): void;
11
11
  private restoreConsoleErrorCapture;
12
12
  }
13
- //# sourceMappingURL=browser-logger.d.ts.map
@@ -1,6 +1,6 @@
1
- import { buildConsoleEvent } from "./serializer";
2
- import { BrowserLoggerTransport } from "./transport";
3
- const DEFAULT_ENDPOINT = "https://ingest.squasher.ai";
1
+ import { DEFAULT_INGEST_ENDPOINT } from "./_vendor/sdk-runtime/runtime/public-sdk-runtime.js";
2
+ import { buildConsoleEvent } from "./serializer.js";
3
+ import { BrowserLoggerTransport } from "./transport.js";
4
4
  export class BrowserLogger {
5
5
  config;
6
6
  transport;
@@ -33,7 +33,7 @@ export class BrowserLogger {
33
33
  }
34
34
  const originalConsoleError = this.originalConsoleError;
35
35
  console.error = (...args) => {
36
- Reflect.apply(originalConsoleError, console, args);
36
+ originalConsoleError.call(console, ...args);
37
37
  this.transport.enqueue(buildConsoleEvent(args, "error"));
38
38
  };
39
39
  this.installed = true;
@@ -50,7 +50,7 @@ function resolveConfig(config) {
50
50
  return {
51
51
  apiKey: config.apiKey,
52
52
  projectId: config.projectId,
53
- endpoint: config.endpoint ?? DEFAULT_ENDPOINT,
53
+ endpoint: config.endpoint ?? DEFAULT_INGEST_ENDPOINT,
54
54
  captureConsoleErrors: config.captureConsoleErrors ?? true,
55
55
  };
56
56
  }