aissue 0.0.0-stage → 2.0.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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +390 -2
  3. package/dist/cjs/browser.d.ts +16 -0
  4. package/dist/cjs/browser.js +80 -0
  5. package/dist/cjs/core/breadcrumbs.d.ts +48 -0
  6. package/dist/cjs/core/breadcrumbs.js +313 -0
  7. package/dist/cjs/core/client.d.ts +54 -0
  8. package/dist/cjs/core/client.js +293 -0
  9. package/dist/cjs/core/env.d.ts +19 -0
  10. package/dist/cjs/core/env.js +71 -0
  11. package/dist/cjs/core/event.d.ts +35 -0
  12. package/dist/cjs/core/event.js +187 -0
  13. package/dist/cjs/core/hub.d.ts +20 -0
  14. package/dist/cjs/core/hub.js +21 -0
  15. package/dist/cjs/core/instrument-browser.d.ts +16 -0
  16. package/dist/cjs/core/instrument-browser.js +208 -0
  17. package/dist/cjs/core/instrument-node.d.ts +5 -0
  18. package/dist/cjs/core/instrument-node.js +250 -0
  19. package/dist/cjs/core/instrument.d.ts +12 -0
  20. package/dist/cjs/core/instrument.js +137 -0
  21. package/dist/cjs/core/privacy.d.ts +25 -0
  22. package/dist/cjs/core/privacy.js +269 -0
  23. package/dist/cjs/core/stack.d.ts +13 -0
  24. package/dist/cjs/core/stack.js +147 -0
  25. package/dist/cjs/core/transport.d.ts +31 -0
  26. package/dist/cjs/core/transport.js +154 -0
  27. package/dist/cjs/core/types.d.ts +149 -0
  28. package/dist/cjs/core/types.js +2 -0
  29. package/dist/cjs/core/version.d.ts +2 -0
  30. package/dist/cjs/core/version.js +6 -0
  31. package/dist/cjs/index.d.ts +27 -0
  32. package/dist/cjs/index.js +83 -0
  33. package/dist/cjs/nextjs/client.d.ts +10 -0
  34. package/dist/cjs/nextjs/client.js +99 -0
  35. package/dist/cjs/nextjs/index.d.ts +31 -0
  36. package/dist/cjs/nextjs/index.js +99 -0
  37. package/dist/cjs/node.d.ts +48 -0
  38. package/dist/cjs/node.js +223 -0
  39. package/dist/cjs/package.json +3 -0
  40. package/dist/cjs/react.d.ts +40 -0
  41. package/dist/cjs/react.js +90 -0
  42. package/dist/esm/browser.d.ts +16 -0
  43. package/dist/esm/browser.js +71 -0
  44. package/dist/esm/cli.d.ts +2 -0
  45. package/dist/esm/cli.js +386 -0
  46. package/dist/esm/core/breadcrumbs.d.ts +48 -0
  47. package/dist/esm/core/breadcrumbs.js +296 -0
  48. package/dist/esm/core/client.d.ts +54 -0
  49. package/dist/esm/core/client.js +285 -0
  50. package/dist/esm/core/env.d.ts +19 -0
  51. package/dist/esm/core/env.js +62 -0
  52. package/dist/esm/core/event.d.ts +35 -0
  53. package/dist/esm/core/event.js +179 -0
  54. package/dist/esm/core/hub.d.ts +20 -0
  55. package/dist/esm/core/hub.js +17 -0
  56. package/dist/esm/core/instrument-browser.d.ts +16 -0
  57. package/dist/esm/core/instrument-browser.js +203 -0
  58. package/dist/esm/core/instrument-node.d.ts +5 -0
  59. package/dist/esm/core/instrument-node.js +214 -0
  60. package/dist/esm/core/instrument.d.ts +12 -0
  61. package/dist/esm/core/instrument.js +132 -0
  62. package/dist/esm/core/privacy.d.ts +25 -0
  63. package/dist/esm/core/privacy.js +257 -0
  64. package/dist/esm/core/stack.d.ts +13 -0
  65. package/dist/esm/core/stack.js +140 -0
  66. package/dist/esm/core/transport.d.ts +31 -0
  67. package/dist/esm/core/transport.js +149 -0
  68. package/dist/esm/core/types.d.ts +149 -0
  69. package/dist/esm/core/types.js +1 -0
  70. package/dist/esm/core/version.d.ts +2 -0
  71. package/dist/esm/core/version.js +3 -0
  72. package/dist/esm/index.d.ts +27 -0
  73. package/dist/esm/index.js +72 -0
  74. package/dist/esm/nextjs/client.d.ts +10 -0
  75. package/dist/esm/nextjs/client.js +90 -0
  76. package/dist/esm/nextjs/index.d.ts +31 -0
  77. package/dist/esm/nextjs/index.js +88 -0
  78. package/dist/esm/node.d.ts +48 -0
  79. package/dist/esm/node.js +210 -0
  80. package/dist/esm/react.d.ts +40 -0
  81. package/dist/esm/react.js +47 -0
  82. package/package.json +141 -4
@@ -0,0 +1,296 @@
1
+ import { getHub } from './hub.js';
2
+ import { FILTERED, isSensitiveKey, scrub, scrubText } from './privacy.js';
3
+ export const DEFAULT_MAX_BREADCRUMBS = 50;
4
+ /** Protocol limit: at most 100 breadcrumbs per event. */
5
+ export const MAX_BREADCRUMBS = 100;
6
+ export const MAX_BREADCRUMB_MESSAGE = 1000;
7
+ const MAX_DATA_KEYS = 20;
8
+ const MAX_DATA_VALUE = 1000;
9
+ const MAX_CATEGORY = 100;
10
+ const TYPES = ['default', 'http', 'navigation', 'ui', 'log', 'query'];
11
+ const LEVELS = {
12
+ debug: 'debug',
13
+ trace: 'debug',
14
+ info: 'info',
15
+ log: 'info',
16
+ warning: 'warning',
17
+ warn: 'warning',
18
+ error: 'error',
19
+ fatal: 'error',
20
+ critical: 'error',
21
+ };
22
+ /** Cut to `max` characters, ellipsis included. */
23
+ export function clip(value, max) {
24
+ return value.length > max ? value.slice(0, Math.max(0, max - 3)) + '...' : value;
25
+ }
26
+ /** Short, safe text for any value (used for console arguments and nested data values). */
27
+ export function describeValue(value, max = 4000) {
28
+ try {
29
+ if (typeof value === 'string')
30
+ return value.length > max ? value.slice(0, max) : value;
31
+ if (value === undefined)
32
+ return 'undefined';
33
+ if (value === null)
34
+ return 'null';
35
+ if (typeof value === 'function')
36
+ return '[Function]';
37
+ if (typeof value === 'symbol' || typeof value === 'bigint')
38
+ return String(value);
39
+ if (typeof value !== 'object')
40
+ return String(value);
41
+ const v = value;
42
+ if (value instanceof Error || (typeof v.message === 'string' && typeof v.name === 'string')) {
43
+ return `${String(v.name || 'Error')}: ${String(v.message)}`;
44
+ }
45
+ const json = JSON.stringify(scrub(value));
46
+ return json === undefined ? String(value) : json.length > max ? json.slice(0, max) : json;
47
+ }
48
+ catch {
49
+ return '[unserializable]';
50
+ }
51
+ }
52
+ function toTimestamp(input) {
53
+ try {
54
+ let ms;
55
+ if (input instanceof Date)
56
+ ms = input.getTime();
57
+ else if (typeof input === 'number')
58
+ ms = input < 1e11 ? input * 1000 : input; // seconds or milliseconds
59
+ else if (typeof input === 'string')
60
+ ms = Date.parse(input);
61
+ else
62
+ ms = Date.now();
63
+ if (!Number.isFinite(ms))
64
+ ms = Date.now();
65
+ return new Date(ms).toISOString();
66
+ }
67
+ catch {
68
+ return new Date().toISOString();
69
+ }
70
+ }
71
+ function dataValue(value) {
72
+ if (value === undefined || value === null)
73
+ return undefined;
74
+ switch (typeof value) {
75
+ case 'boolean':
76
+ return value;
77
+ case 'number':
78
+ return Number.isFinite(value) ? value : String(value);
79
+ case 'string':
80
+ return clip(scrubText(value), MAX_DATA_VALUE);
81
+ case 'function':
82
+ case 'symbol':
83
+ return undefined;
84
+ default:
85
+ return clip(scrubText(describeValue(value)), MAX_DATA_VALUE);
86
+ }
87
+ }
88
+ /**
89
+ * Turn user or instrumentation input into a protocol breadcrumb: valid type / level, ISO timestamp,
90
+ * message <= 1000 chars, flat data (<= 20 keys). Sensitive keys and secrets / emails in strings are filtered.
91
+ */
92
+ export function normalizeBreadcrumb(input) {
93
+ if (!input || typeof input !== 'object')
94
+ return null;
95
+ const rawType = typeof input.type === 'string' ? input.type.toLowerCase() : '';
96
+ const type = TYPES.includes(rawType) ? rawType : 'default';
97
+ const level = (typeof input.level === 'string' && LEVELS[input.level.toLowerCase()]) || 'info';
98
+ const rawCategory = typeof input.category === 'string' ? input.category.trim() : '';
99
+ const category = clip(scrubText(rawCategory), MAX_CATEGORY) || (type === 'default' ? 'manual' : type);
100
+ const message = input.message === undefined || input.message === null
101
+ ? ''
102
+ : clip(scrubText(describeValue(input.message)), MAX_BREADCRUMB_MESSAGE);
103
+ const data = {};
104
+ if (input.data && typeof input.data === 'object' && !Array.isArray(input.data)) {
105
+ let count = 0;
106
+ for (const key of Object.keys(input.data)) {
107
+ if (count >= MAX_DATA_KEYS)
108
+ break;
109
+ const value = isSensitiveKey(key) ? FILTERED : dataValue(input.data[key]);
110
+ if (value === undefined)
111
+ continue;
112
+ data[clip(key, MAX_CATEGORY)] = value;
113
+ count++;
114
+ }
115
+ }
116
+ return { timestamp: toTimestamp(input.timestamp), type, category, level, message, data };
117
+ }
118
+ function storage() {
119
+ return getHub().breadcrumbStorage;
120
+ }
121
+ /** The buffer breadcrumbs go to right now: the current request's (Node) or the global one. */
122
+ export function currentBuffer() {
123
+ const hub = getHub();
124
+ try {
125
+ const store = hub.breadcrumbStorage?.getStore();
126
+ if (Array.isArray(store))
127
+ return store;
128
+ }
129
+ catch {
130
+ // fall back to the global buffer
131
+ }
132
+ if (!Array.isArray(hub.breadcrumbs))
133
+ hub.breadcrumbs = [];
134
+ return hub.breadcrumbs;
135
+ }
136
+ /** True when a client is enabled and keeps breadcrumbs (optionally: and this automatic source is on). */
137
+ export function breadcrumbsActive(kind) {
138
+ try {
139
+ const client = getHub().client;
140
+ if (!client || !client.enabled || client.config.maxBreadcrumbs <= 0)
141
+ return false;
142
+ if (!kind)
143
+ return true;
144
+ const auto = client.config.autoBreadcrumbs;
145
+ return auto !== false && !(typeof auto === 'object' && auto !== null && auto[kind] === false);
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
151
+ let recording = false;
152
+ /**
153
+ * Store a breadcrumb in `buffer` (default: the current one). Runs beforeBreadcrumb.
154
+ * Never throws; ignored when the SDK is disabled or while another breadcrumb is being recorded
155
+ * (so a console.log inside beforeBreadcrumb cannot loop).
156
+ */
157
+ export function recordBreadcrumb(input, buffer) {
158
+ if (recording)
159
+ return;
160
+ recording = true;
161
+ try {
162
+ const client = getHub().client;
163
+ if (!client || !client.enabled)
164
+ return;
165
+ const max = client.config.maxBreadcrumbs;
166
+ if (max <= 0)
167
+ return;
168
+ let crumb = normalizeBreadcrumb(input);
169
+ if (!crumb)
170
+ return;
171
+ const before = client.config.beforeBreadcrumb;
172
+ if (before) {
173
+ let result;
174
+ try {
175
+ result = before(crumb);
176
+ }
177
+ catch {
178
+ return; // a throwing beforeBreadcrumb drops the breadcrumb
179
+ }
180
+ if (!result)
181
+ return;
182
+ crumb = normalizeBreadcrumb(result); // re-validate whatever the hook returned
183
+ if (!crumb)
184
+ return;
185
+ }
186
+ const target = buffer || currentBuffer();
187
+ target.push(crumb);
188
+ if (target.length > max)
189
+ target.splice(0, target.length - max);
190
+ }
191
+ catch {
192
+ // never throw into the host app
193
+ }
194
+ finally {
195
+ recording = false;
196
+ }
197
+ }
198
+ /** Copy of the current breadcrumbs (oldest first) for an event. */
199
+ export function snapshotBreadcrumbs() {
200
+ try {
201
+ const client = getHub().client;
202
+ const max = client ? Math.min(client.config.maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;
203
+ if (max <= 0)
204
+ return [];
205
+ return currentBuffer()
206
+ .slice(-max)
207
+ .map((c) => ({ ...c, data: { ...c.data } }));
208
+ }
209
+ catch {
210
+ return [];
211
+ }
212
+ }
213
+ /** Empty the current buffer (the current request's in Node, otherwise the global one). */
214
+ export function clearCurrentBreadcrumbs() {
215
+ try {
216
+ currentBuffer().length = 0;
217
+ }
218
+ catch {
219
+ // ignore
220
+ }
221
+ }
222
+ /** Run `fn` with its own, empty breadcrumb buffer (Node AsyncLocalStorage); plain call elsewhere. */
223
+ export function runWithBreadcrumbScope(fn) {
224
+ const s = storage();
225
+ return s ? s.run([], fn) : fn();
226
+ }
227
+ // --- wrapping helpers shared by the instrumentation -------------------------------------------------
228
+ const WRAPPED = Symbol.for('aissue.wrapped');
229
+ export function isWrapped(fn) {
230
+ return typeof fn === 'function' && !!fn[WRAPPED];
231
+ }
232
+ /**
233
+ * Mark `wrapper` as ours and copy the original's own properties (e.g. Next.js' `__nextPatched` on fetch)
234
+ * so code that inspects the function keeps working.
235
+ */
236
+ export function markWrapped(wrapper, original) {
237
+ try {
238
+ for (const key of Reflect.ownKeys(original)) {
239
+ if (key === 'length' || key === 'name' || key === 'prototype' || key === 'caller' || key === 'arguments')
240
+ continue;
241
+ if (Object.prototype.hasOwnProperty.call(wrapper, key))
242
+ continue;
243
+ const desc = Object.getOwnPropertyDescriptor(original, key);
244
+ if (desc)
245
+ Object.defineProperty(wrapper, key, desc);
246
+ }
247
+ }
248
+ catch {
249
+ // ignore
250
+ }
251
+ try {
252
+ Object.defineProperty(wrapper, WRAPPED, { value: original, configurable: true });
253
+ Object.defineProperty(wrapper, 'name', { value: original.name, configurable: true });
254
+ }
255
+ catch {
256
+ // ignore
257
+ }
258
+ return wrapper;
259
+ }
260
+ /** Replace obj[name] with makeWrapper(original) unless it is already our wrapper. Never throws. */
261
+ export function wrapMethod(obj, name, makeWrapper) {
262
+ try {
263
+ if (!obj || (typeof obj !== 'object' && typeof obj !== 'function'))
264
+ return false;
265
+ const target = obj;
266
+ const original = target[name];
267
+ if (typeof original !== 'function' || isWrapped(original))
268
+ return false;
269
+ target[name] = markWrapped(makeWrapper(original), original);
270
+ return true;
271
+ }
272
+ catch {
273
+ return false;
274
+ }
275
+ }
276
+ /** True for URLs that point at the AIssue host itself (the SDK's own requests). */
277
+ export function isAIssueUrl(url) {
278
+ try {
279
+ const base = getHub().client?.config.baseUrl;
280
+ if (!base || !url)
281
+ return false;
282
+ return url === base || url.startsWith(base + '/') || url.startsWith(base + '?');
283
+ }
284
+ catch {
285
+ return false;
286
+ }
287
+ }
288
+ export function levelForStatus(status) {
289
+ if (!status)
290
+ return 'error';
291
+ if (status >= 500)
292
+ return 'error';
293
+ if (status >= 400)
294
+ return 'warning';
295
+ return 'info';
296
+ }
@@ -0,0 +1,54 @@
1
+ import { type BuildExtras } from './event.js';
2
+ import { Transport, type TransportMode } from './transport.js';
3
+ import type { AIssueOptions, CaptureContext, Platform } from './types.js';
4
+ export declare const DEDUPE_WINDOW_MS = 5000;
5
+ /** Browser noise that is never worth an alert. */
6
+ export declare const BROWSER_DEFAULT_IGNORE: Array<string | RegExp>;
7
+ export interface SetupSettings {
8
+ /** 'browser': key in ?api_key=, text/plain, keepalive, page defaults. 'server': X-API-Key header. */
9
+ runtime?: TransportMode;
10
+ platform?: Platform;
11
+ }
12
+ export interface ResolvedConfig {
13
+ apiKey?: string;
14
+ baseUrl?: string;
15
+ release?: string;
16
+ environment?: string;
17
+ enabled: boolean;
18
+ debug: boolean;
19
+ runtime: TransportMode;
20
+ platform: Platform;
21
+ ignoreErrors: Array<string | RegExp>;
22
+ maxEventsPerMinute: number;
23
+ beforeSend?: AIssueOptions['beforeSend'];
24
+ maxBreadcrumbs: number;
25
+ beforeBreadcrumb?: AIssueOptions['beforeBreadcrumb'];
26
+ autoBreadcrumbs: AIssueOptions['autoBreadcrumbs'];
27
+ }
28
+ /** "https://<key>@host[:port]/<domain id>" -> { apiKey, baseUrl } */
29
+ export declare function parseDsn(dsn: string | undefined): {
30
+ apiKey: string;
31
+ baseUrl: string;
32
+ } | undefined;
33
+ export declare function resolveConfig(options?: AIssueOptions, settings?: SetupSettings): ResolvedConfig;
34
+ export declare class Client {
35
+ readonly config: ResolvedConfig;
36
+ readonly transport?: Transport;
37
+ private readonly sentAt;
38
+ private readonly recent;
39
+ private readonly captured;
40
+ constructor(config: ResolvedConfig);
41
+ get enabled(): boolean;
42
+ log(message: string): void;
43
+ private defaults;
44
+ private isIgnored;
45
+ private isDuplicate;
46
+ private takeRateLimitSlot;
47
+ /** Build, filter and send one event. Never throws. Returns true when the event was handed to fetch. */
48
+ capture(error: unknown, context?: CaptureContext, extras?: BuildExtras): boolean;
49
+ flush(timeoutMs?: number): Promise<boolean>;
50
+ }
51
+ /** Create the client and make it current. Used by every entry point's init(). */
52
+ export declare function setupClient(options?: AIssueOptions, settings?: SetupSettings): Client | undefined;
53
+ /** captureException with internal extras (used by the React boundary). */
54
+ export declare function captureWithExtras(error: unknown, context?: CaptureContext, extras?: BuildExtras): void;
@@ -0,0 +1,285 @@
1
+ import { DEFAULT_MAX_BREADCRUMBS, MAX_BREADCRUMBS, snapshotBreadcrumbs } from './breadcrumbs.js';
2
+ import { detectRelease, isBrowser, isNode, nodeEnv, readEnv } from './env.js';
3
+ import { buildEvent, serializeEvent } from './event.js';
4
+ import { getHub } from './hub.js';
5
+ import { isExtensionUrl } from './stack.js';
6
+ import { Transport } from './transport.js';
7
+ export const DEDUPE_WINDOW_MS = 5000;
8
+ const RATE_WINDOW_MS = 60000;
9
+ const DEFAULT_MAX_EVENTS_PER_MINUTE = 10;
10
+ /** Browser noise that is never worth an alert. */
11
+ export const BROWSER_DEFAULT_IGNORE = [
12
+ 'ResizeObserver loop limit exceeded',
13
+ 'ResizeObserver loop completed with undelivered notifications',
14
+ /^Script error\.?$/,
15
+ ];
16
+ function log(debug, message) {
17
+ if (!debug)
18
+ return;
19
+ try {
20
+ console.log(`[aissue] ${message}`);
21
+ }
22
+ catch {
23
+ // ignore
24
+ }
25
+ }
26
+ function warn(message) {
27
+ try {
28
+ console.warn(`[aissue] ${message}`);
29
+ }
30
+ catch {
31
+ // ignore
32
+ }
33
+ }
34
+ /** "https://<key>@host[:port]/<domain id>" -> { apiKey, baseUrl } */
35
+ export function parseDsn(dsn) {
36
+ if (!dsn)
37
+ return undefined;
38
+ try {
39
+ const url = new URL(dsn);
40
+ if (!url.username || !url.host || !/^https?:$/.test(url.protocol))
41
+ return undefined;
42
+ return { apiKey: decodeURIComponent(url.username), baseUrl: `${url.protocol}//${url.host}` };
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ }
48
+ function str(value) {
49
+ if (typeof value !== 'string')
50
+ return undefined;
51
+ const trimmed = value.trim();
52
+ return trimmed || undefined;
53
+ }
54
+ export function resolveConfig(options = {}, settings = {}) {
55
+ const runtime = settings.runtime ?? (isBrowser() ? 'browser' : 'server');
56
+ // Environment variables are only read on servers; browser bundles get explicit options.
57
+ const env = runtime === 'server' ? readEnv : () => undefined;
58
+ const fromDsn = parseDsn(str(options.dsn));
59
+ let apiKey = str(options.apiKey) || fromDsn?.apiKey || env('AISSUE_API_KEY');
60
+ let baseUrl = str(options.baseUrl) || fromDsn?.baseUrl || env('AISSUE_BASE_URL');
61
+ if (!apiKey || !baseUrl) {
62
+ const envDsn = parseDsn(env('AISSUE_DSN'));
63
+ apiKey = apiKey || envDsn?.apiKey;
64
+ baseUrl = baseUrl || envDsn?.baseUrl;
65
+ }
66
+ const mode = nodeEnv();
67
+ const enabled = options.enabled ?? !(mode === 'development' || mode === 'test');
68
+ const platform = settings.platform ?? (runtime === 'browser' ? 'browser' : isNode() ? 'node' : 'javascript');
69
+ const max = options.maxEventsPerMinute;
70
+ const maxCrumbs = options.maxBreadcrumbs;
71
+ return {
72
+ apiKey,
73
+ baseUrl: baseUrl ? baseUrl.replace(/\/+$/, '') : undefined,
74
+ release: str(options.release) || (runtime === 'server' ? detectRelease() : undefined),
75
+ environment: str(options.environment) || env('AISSUE_ENVIRONMENT') || (runtime === 'server' ? mode : undefined),
76
+ enabled: !!enabled,
77
+ debug: !!options.debug,
78
+ runtime,
79
+ platform,
80
+ ignoreErrors: [
81
+ ...(runtime === 'browser' ? BROWSER_DEFAULT_IGNORE : []),
82
+ ...(Array.isArray(options.ignoreErrors)
83
+ ? options.ignoreErrors.filter((p) => typeof p === 'string' || p instanceof RegExp)
84
+ : []),
85
+ ],
86
+ maxEventsPerMinute: typeof max === 'number' && max >= 0 ? max : DEFAULT_MAX_EVENTS_PER_MINUTE,
87
+ beforeSend: typeof options.beforeSend === 'function' ? options.beforeSend : undefined,
88
+ maxBreadcrumbs: typeof maxCrumbs === 'number' && Number.isFinite(maxCrumbs)
89
+ ? Math.min(MAX_BREADCRUMBS, Math.max(0, Math.floor(maxCrumbs)))
90
+ : DEFAULT_MAX_BREADCRUMBS,
91
+ beforeBreadcrumb: typeof options.beforeBreadcrumb === 'function' ? options.beforeBreadcrumb : undefined,
92
+ autoBreadcrumbs: options.autoBreadcrumbs === false || (options.autoBreadcrumbs && typeof options.autoBreadcrumbs === 'object')
93
+ ? options.autoBreadcrumbs
94
+ : true,
95
+ };
96
+ }
97
+ function matches(pattern, text) {
98
+ if (typeof pattern === 'string')
99
+ return pattern !== '' && text.includes(pattern);
100
+ try {
101
+ pattern.lastIndex = 0;
102
+ return pattern.test(text);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ export class Client {
109
+ constructor(config) {
110
+ this.config = config;
111
+ this.sentAt = [];
112
+ this.recent = new Map();
113
+ this.captured = new WeakSet();
114
+ if (config.enabled && config.apiKey && config.baseUrl) {
115
+ this.transport = new Transport({
116
+ baseUrl: config.baseUrl,
117
+ apiKey: config.apiKey,
118
+ mode: config.runtime,
119
+ log: (m) => log(config.debug, m),
120
+ warn,
121
+ });
122
+ }
123
+ }
124
+ get enabled() {
125
+ return !!this.transport;
126
+ }
127
+ log(message) {
128
+ log(this.config.debug, message);
129
+ }
130
+ defaults() {
131
+ const { config } = this;
132
+ const defaults = {
133
+ platform: config.platform,
134
+ errorCode: config.runtime === 'browser' ? 0 : 500,
135
+ release: config.release,
136
+ environment: config.environment,
137
+ userId: getHub().userId,
138
+ };
139
+ if (config.runtime === 'browser') {
140
+ try {
141
+ const g = globalThis;
142
+ if (g.location && typeof g.location.pathname === 'string')
143
+ defaults.path = g.location.pathname;
144
+ if (g.navigator && typeof g.navigator.userAgent === 'string') {
145
+ defaults.headers = { 'User-Agent': g.navigator.userAgent };
146
+ }
147
+ }
148
+ catch {
149
+ // ignore
150
+ }
151
+ }
152
+ return defaults;
153
+ }
154
+ isIgnored(event) {
155
+ const { type, message } = event.exception;
156
+ const full = `${type}: ${message}`;
157
+ for (const pattern of this.config.ignoreErrors) {
158
+ if (matches(pattern, message) || matches(pattern, full))
159
+ return true;
160
+ }
161
+ if (this.config.runtime === 'browser' && event.frames.length > 0) {
162
+ if (event.frames.every((f) => isExtensionUrl(f.filename)))
163
+ return true;
164
+ }
165
+ return false;
166
+ }
167
+ isDuplicate(event, now) {
168
+ for (const [key, at] of this.recent) {
169
+ if (now - at >= DEDUPE_WINDOW_MS)
170
+ this.recent.delete(key);
171
+ }
172
+ const top = event.frames[event.frames.length - 1];
173
+ const key = [
174
+ event.exception.type,
175
+ event.exception.message,
176
+ top ? `${top.filename}:${top.lineno ?? ''}:${top.colno ?? ''}` : '',
177
+ ].join('\u0000');
178
+ if (this.recent.has(key))
179
+ return true;
180
+ if (this.recent.size >= 100)
181
+ this.recent.clear();
182
+ this.recent.set(key, now);
183
+ return false;
184
+ }
185
+ takeRateLimitSlot(now) {
186
+ while (this.sentAt.length && now - this.sentAt[0] >= RATE_WINDOW_MS)
187
+ this.sentAt.shift();
188
+ if (this.sentAt.length >= this.config.maxEventsPerMinute)
189
+ return false;
190
+ this.sentAt.push(now);
191
+ return true;
192
+ }
193
+ /** Build, filter and send one event. Never throws. Returns true when the event was handed to fetch. */
194
+ capture(error, context, extras) {
195
+ try {
196
+ const transport = this.transport;
197
+ if (!transport)
198
+ return false;
199
+ if (error !== null && typeof error === 'object') {
200
+ if (this.captured.has(error)) {
201
+ this.log('error object already captured; skipping');
202
+ return false;
203
+ }
204
+ }
205
+ let event = buildEvent(error, context || {}, this.defaults(), extras);
206
+ if (this.isIgnored(event)) {
207
+ this.log(`ignored: ${event.exception.type}: ${event.exception.message}`);
208
+ return false;
209
+ }
210
+ const now = Date.now();
211
+ if (this.isDuplicate(event, now)) {
212
+ this.log('duplicate event within 5s; dropped');
213
+ return false;
214
+ }
215
+ if (error !== null && typeof error === 'object')
216
+ this.captured.add(error);
217
+ const breadcrumbs = snapshotBreadcrumbs();
218
+ if (breadcrumbs.length)
219
+ event.breadcrumbs = breadcrumbs;
220
+ if (this.config.beforeSend) {
221
+ try {
222
+ event = this.config.beforeSend(event);
223
+ }
224
+ catch {
225
+ warn('beforeSend threw; dropping the event');
226
+ return false;
227
+ }
228
+ if (!event) {
229
+ this.log('beforeSend dropped the event');
230
+ return false;
231
+ }
232
+ }
233
+ if (transport.isPaused(now)) {
234
+ this.log('paused after a 429 from the server; dropped');
235
+ return false;
236
+ }
237
+ if (!this.takeRateLimitSlot(now)) {
238
+ this.log(`more than ${this.config.maxEventsPerMinute} events this minute; dropped`);
239
+ return false;
240
+ }
241
+ const body = serializeEvent(event);
242
+ if (body === null) {
243
+ this.log('event over 256 KB even after trimming; dropped');
244
+ return false;
245
+ }
246
+ transport.send(body);
247
+ return true;
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ }
253
+ flush(timeoutMs) {
254
+ return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
255
+ }
256
+ }
257
+ /** Create the client and make it current. Used by every entry point's init(). */
258
+ export function setupClient(options = {}, settings = {}) {
259
+ try {
260
+ const config = resolveConfig(options || {}, settings);
261
+ const client = new Client(config);
262
+ getHub().client = client;
263
+ if (config.enabled && !client.enabled) {
264
+ warn('apiKey and baseUrl (or dsn) are required; the SDK is disabled.');
265
+ }
266
+ else {
267
+ client.log(client.enabled
268
+ ? `initialised (platform ${config.platform}, environment ${config.environment ?? '-'}, release ${config.release ?? '-'})`
269
+ : 'disabled (enabled: false, or NODE_ENV is development/test)');
270
+ }
271
+ return client;
272
+ }
273
+ catch {
274
+ return undefined;
275
+ }
276
+ }
277
+ /** captureException with internal extras (used by the React boundary). */
278
+ export function captureWithExtras(error, context, extras) {
279
+ try {
280
+ getHub().client?.capture(error, context, extras);
281
+ }
282
+ catch {
283
+ // never throw into the host app
284
+ }
285
+ }
@@ -0,0 +1,19 @@
1
+ /** Release env vars, first one set wins (ingestion protocol "Release detection"). */
2
+ export declare const RELEASE_ENV_VARS: readonly ["AISSUE_RELEASE", "VERCEL_GIT_COMMIT_SHA", "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", "RENDER_GIT_COMMIT", "RAILWAY_GIT_COMMIT_SHA", "HEROKU_SLUG_COMMIT", "SOURCE_VERSION", "CF_PAGES_COMMIT_SHA", "GITHUB_SHA", "COMMIT_SHA", "GIT_SHA", "GIT_COMMIT"];
3
+ type ProcessLike = {
4
+ env?: Record<string, string | undefined>;
5
+ versions?: Record<string, string | undefined>;
6
+ };
7
+ /** The global `process`, if any (looked up dynamically so bundlers and edge runtimes don't complain). */
8
+ export declare function getProcess(): ProcessLike | undefined;
9
+ /** Read a server-side environment variable (trimmed; undefined when empty). */
10
+ export declare function readEnv(name: string): string | undefined;
11
+ export declare function detectRelease(): string | undefined;
12
+ /**
13
+ * NODE_ENV. `process.env.NODE_ENV` is referenced literally so bundlers (webpack, Next.js, Vite)
14
+ * can inline it in browser builds; a missing `process` global is caught.
15
+ */
16
+ export declare function nodeEnv(): string | undefined;
17
+ export declare function isBrowser(): boolean;
18
+ export declare function isNode(): boolean;
19
+ export {};