@djangocfg/monitor 2.1.216 → 2.1.217

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/index.cjs CHANGED
@@ -1,7 +1,14 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
5
12
  var __copyProps = (to, from, except, desc) => {
6
13
  if (from && typeof from === "object" || typeof from === "function") {
7
14
  for (let key of __getOwnPropNames(from))
@@ -10,9 +17,882 @@ var __copyProps = (to, from, except, desc) => {
10
17
  }
11
18
  return to;
12
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
13
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
29
 
15
30
  // src/index.ts
16
31
  var index_exports = {};
32
+ __export(index_exports, {
33
+ EventLevel: () => FrontendEventIngestRequestLevel,
34
+ EventType: () => FrontendEventIngestRequestEventType
35
+ });
17
36
  module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/_api/generated/cfg_monitor/monitor/client.ts
39
+ var _Monitor = class _Monitor {
40
+ constructor(client) {
41
+ this.client = client;
42
+ }
43
+ /**
44
+ * Ingest browser events
45
+ *
46
+ * Accepts a batch of up to 50 frontend events. No authentication required.
47
+ */
48
+ async ingestCreate(data) {
49
+ const response = await this.client.request("POST", "/cfg/monitor/ingest/", { body: data });
50
+ return response;
51
+ }
52
+ };
53
+ __name(_Monitor, "Monitor");
54
+ var Monitor = _Monitor;
55
+
56
+ // src/_api/generated/cfg_monitor/http.ts
57
+ var _FetchAdapter = class _FetchAdapter {
58
+ async request(request) {
59
+ const { method, url, headers, body, params, formData, binaryBody } = request;
60
+ let finalUrl = url;
61
+ if (params) {
62
+ const searchParams = new URLSearchParams();
63
+ Object.entries(params).forEach(([key, value]) => {
64
+ if (value !== null && value !== void 0) {
65
+ searchParams.append(key, String(value));
66
+ }
67
+ });
68
+ const queryString = searchParams.toString();
69
+ if (queryString) {
70
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
71
+ }
72
+ }
73
+ const finalHeaders = { ...headers };
74
+ let requestBody;
75
+ if (formData) {
76
+ requestBody = formData;
77
+ } else if (binaryBody) {
78
+ finalHeaders["Content-Type"] = "application/octet-stream";
79
+ requestBody = binaryBody;
80
+ } else if (body) {
81
+ finalHeaders["Content-Type"] = "application/json";
82
+ requestBody = JSON.stringify(body);
83
+ }
84
+ const response = await fetch(finalUrl, {
85
+ method,
86
+ headers: finalHeaders,
87
+ body: requestBody,
88
+ credentials: "include"
89
+ // Include Django session cookies
90
+ });
91
+ let data = null;
92
+ const contentType = response.headers.get("content-type");
93
+ if (response.status !== 204 && contentType?.includes("application/json")) {
94
+ data = await response.json();
95
+ } else if (response.status !== 204) {
96
+ data = await response.text();
97
+ }
98
+ const responseHeaders = {};
99
+ response.headers.forEach((value, key) => {
100
+ responseHeaders[key] = value;
101
+ });
102
+ return {
103
+ data,
104
+ status: response.status,
105
+ statusText: response.statusText,
106
+ headers: responseHeaders
107
+ };
108
+ }
109
+ };
110
+ __name(_FetchAdapter, "FetchAdapter");
111
+ var FetchAdapter = _FetchAdapter;
112
+
113
+ // src/_api/generated/cfg_monitor/errors.ts
114
+ var _APIError = class _APIError extends Error {
115
+ constructor(statusCode, statusText, response, url, message) {
116
+ super(message || `HTTP ${statusCode}: ${statusText}`);
117
+ this.statusCode = statusCode;
118
+ this.statusText = statusText;
119
+ this.response = response;
120
+ this.url = url;
121
+ this.name = "APIError";
122
+ }
123
+ /**
124
+ * Get error details from response.
125
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
126
+ */
127
+ get details() {
128
+ if (typeof this.response === "object" && this.response !== null) {
129
+ return this.response;
130
+ }
131
+ return null;
132
+ }
133
+ /**
134
+ * Get field-specific validation errors from DRF.
135
+ * Returns: { "field_name": ["error1", "error2"], ... }
136
+ */
137
+ get fieldErrors() {
138
+ const details = this.details;
139
+ if (!details) return null;
140
+ const fieldErrors = {};
141
+ for (const [key, value] of Object.entries(details)) {
142
+ if (Array.isArray(value)) {
143
+ fieldErrors[key] = value;
144
+ }
145
+ }
146
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
147
+ }
148
+ /**
149
+ * Get single error message from DRF.
150
+ * Checks for "detail", "message", or first field error.
151
+ */
152
+ get errorMessage() {
153
+ const details = this.details;
154
+ if (!details) return this.message;
155
+ if (details.detail) {
156
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
157
+ }
158
+ if (details.message) {
159
+ return String(details.message);
160
+ }
161
+ const fieldErrors = this.fieldErrors;
162
+ if (fieldErrors) {
163
+ const firstField = Object.keys(fieldErrors)[0];
164
+ if (firstField) {
165
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
166
+ }
167
+ }
168
+ return this.message;
169
+ }
170
+ // Helper methods for common HTTP status codes
171
+ get isValidationError() {
172
+ return this.statusCode === 400;
173
+ }
174
+ get isAuthError() {
175
+ return this.statusCode === 401;
176
+ }
177
+ get isPermissionError() {
178
+ return this.statusCode === 403;
179
+ }
180
+ get isNotFoundError() {
181
+ return this.statusCode === 404;
182
+ }
183
+ get isServerError() {
184
+ return this.statusCode >= 500 && this.statusCode < 600;
185
+ }
186
+ };
187
+ __name(_APIError, "APIError");
188
+ var APIError = _APIError;
189
+ var _NetworkError = class _NetworkError extends Error {
190
+ constructor(message, url, originalError) {
191
+ super(message);
192
+ this.url = url;
193
+ this.originalError = originalError;
194
+ this.name = "NetworkError";
195
+ }
196
+ };
197
+ __name(_NetworkError, "NetworkError");
198
+ var NetworkError = _NetworkError;
199
+
200
+ // src/_api/generated/cfg_monitor/logger.ts
201
+ var import_consola = require("consola");
202
+ var DEFAULT_CONFIG = {
203
+ enabled: process.env.NODE_ENV !== "production",
204
+ logRequests: true,
205
+ logResponses: true,
206
+ logErrors: true,
207
+ logBodies: true,
208
+ logHeaders: false
209
+ };
210
+ var SENSITIVE_HEADERS = [
211
+ "authorization",
212
+ "cookie",
213
+ "set-cookie",
214
+ "x-api-key",
215
+ "x-csrf-token"
216
+ ];
217
+ var _APILogger = class _APILogger {
218
+ constructor(config = {}) {
219
+ this.config = { ...DEFAULT_CONFIG, ...config };
220
+ this.consola = config.consola || (0, import_consola.createConsola)({
221
+ level: this.config.enabled ? 4 : 0
222
+ });
223
+ }
224
+ /**
225
+ * Enable logging
226
+ */
227
+ enable() {
228
+ this.config.enabled = true;
229
+ }
230
+ /**
231
+ * Disable logging
232
+ */
233
+ disable() {
234
+ this.config.enabled = false;
235
+ }
236
+ /**
237
+ * Update configuration
238
+ */
239
+ setConfig(config) {
240
+ this.config = { ...this.config, ...config };
241
+ }
242
+ /**
243
+ * Filter sensitive headers
244
+ */
245
+ filterHeaders(headers) {
246
+ if (!headers) return {};
247
+ const filtered = {};
248
+ Object.keys(headers).forEach((key) => {
249
+ const lowerKey = key.toLowerCase();
250
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
251
+ filtered[key] = "***";
252
+ } else {
253
+ filtered[key] = headers[key] || "";
254
+ }
255
+ });
256
+ return filtered;
257
+ }
258
+ /**
259
+ * Log request
260
+ */
261
+ logRequest(request) {
262
+ if (!this.config.enabled || !this.config.logRequests) return;
263
+ const { method, url, headers, body } = request;
264
+ this.consola.start(`${method} ${url}`);
265
+ if (this.config.logHeaders && headers) {
266
+ this.consola.debug("Headers:", this.filterHeaders(headers));
267
+ }
268
+ if (this.config.logBodies && body) {
269
+ this.consola.debug("Body:", body);
270
+ }
271
+ }
272
+ /**
273
+ * Log response
274
+ */
275
+ logResponse(request, response) {
276
+ if (!this.config.enabled || !this.config.logResponses) return;
277
+ const { method, url } = request;
278
+ const { status, statusText, data, duration } = response;
279
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
280
+ this.consola.success(
281
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
282
+ );
283
+ if (this.config.logBodies && data) {
284
+ this.consola.debug("Response:", data);
285
+ }
286
+ }
287
+ /**
288
+ * Log error
289
+ */
290
+ logError(request, error) {
291
+ if (!this.config.enabled || !this.config.logErrors) return;
292
+ const { method, url } = request;
293
+ const { message, statusCode, fieldErrors, duration } = error;
294
+ this.consola.error(
295
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
296
+ );
297
+ this.consola.error("Message:", message);
298
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
299
+ this.consola.error("Field Errors:");
300
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
301
+ errors.forEach((err) => {
302
+ this.consola.error(` \u2022 ${field}: ${err}`);
303
+ });
304
+ });
305
+ }
306
+ }
307
+ /**
308
+ * Log general info
309
+ */
310
+ info(message, ...args) {
311
+ if (!this.config.enabled) return;
312
+ this.consola.info(message, ...args);
313
+ }
314
+ /**
315
+ * Log warning
316
+ */
317
+ warn(message, ...args) {
318
+ if (!this.config.enabled) return;
319
+ this.consola.warn(message, ...args);
320
+ }
321
+ /**
322
+ * Log error
323
+ */
324
+ error(message, ...args) {
325
+ if (!this.config.enabled) return;
326
+ this.consola.error(message, ...args);
327
+ }
328
+ /**
329
+ * Log debug
330
+ */
331
+ debug(message, ...args) {
332
+ if (!this.config.enabled) return;
333
+ this.consola.debug(message, ...args);
334
+ }
335
+ /**
336
+ * Log success
337
+ */
338
+ success(message, ...args) {
339
+ if (!this.config.enabled) return;
340
+ this.consola.success(message, ...args);
341
+ }
342
+ /**
343
+ * Create a sub-logger with prefix
344
+ */
345
+ withTag(tag) {
346
+ return this.consola.withTag(tag);
347
+ }
348
+ };
349
+ __name(_APILogger, "APILogger");
350
+ var APILogger = _APILogger;
351
+ var defaultLogger = new APILogger();
352
+
353
+ // src/_api/generated/cfg_monitor/retry.ts
354
+ var import_p_retry = __toESM(require("p-retry"), 1);
355
+ var DEFAULT_RETRY_CONFIG = {
356
+ retries: 3,
357
+ factor: 2,
358
+ minTimeout: 1e3,
359
+ maxTimeout: 6e4,
360
+ randomize: true,
361
+ onFailedAttempt: /* @__PURE__ */ __name(() => {
362
+ }, "onFailedAttempt")
363
+ };
364
+ function shouldRetry(error) {
365
+ if (error instanceof NetworkError) {
366
+ return true;
367
+ }
368
+ if (error instanceof APIError) {
369
+ const status = error.statusCode;
370
+ if (status >= 500 && status < 600) {
371
+ return true;
372
+ }
373
+ if (status === 429) {
374
+ return true;
375
+ }
376
+ return false;
377
+ }
378
+ return true;
379
+ }
380
+ __name(shouldRetry, "shouldRetry");
381
+ async function withRetry(fn, config) {
382
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
383
+ return (0, import_p_retry.default)(
384
+ async () => {
385
+ try {
386
+ return await fn();
387
+ } catch (error) {
388
+ if (!shouldRetry(error)) {
389
+ throw new import_p_retry.AbortError(error);
390
+ }
391
+ throw error;
392
+ }
393
+ },
394
+ {
395
+ retries: finalConfig.retries,
396
+ factor: finalConfig.factor,
397
+ minTimeout: finalConfig.minTimeout,
398
+ maxTimeout: finalConfig.maxTimeout,
399
+ randomize: finalConfig.randomize,
400
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
401
+ const pRetryError = error;
402
+ finalConfig.onFailedAttempt({
403
+ error: pRetryError,
404
+ attemptNumber: pRetryError.attemptNumber,
405
+ retriesLeft: pRetryError.retriesLeft
406
+ });
407
+ } : void 0
408
+ }
409
+ );
410
+ }
411
+ __name(withRetry, "withRetry");
412
+
413
+ // src/_api/generated/cfg_monitor/client.ts
414
+ var _APIClient = class _APIClient {
415
+ constructor(baseUrl, options) {
416
+ this.logger = null;
417
+ this.retryConfig = null;
418
+ this.tokenGetter = null;
419
+ this.baseUrl = baseUrl.replace(/\/$/, "");
420
+ this.httpClient = options?.httpClient || new FetchAdapter();
421
+ this.tokenGetter = options?.tokenGetter || null;
422
+ if (options?.loggerConfig !== void 0) {
423
+ this.logger = new APILogger(options.loggerConfig);
424
+ }
425
+ if (options?.retryConfig !== void 0) {
426
+ this.retryConfig = options.retryConfig;
427
+ }
428
+ this.monitor = new Monitor(this);
429
+ }
430
+ /**
431
+ * Get CSRF token from cookies (for SessionAuthentication).
432
+ *
433
+ * Returns null if cookie doesn't exist (JWT-only auth).
434
+ */
435
+ getCsrfToken() {
436
+ const name = "csrftoken";
437
+ const value = `; ${document.cookie}`;
438
+ const parts = value.split(`; ${name}=`);
439
+ if (parts.length === 2) {
440
+ return parts.pop()?.split(";").shift() || null;
441
+ }
442
+ return null;
443
+ }
444
+ /**
445
+ * Get the base URL for building streaming/download URLs.
446
+ */
447
+ getBaseUrl() {
448
+ return this.baseUrl;
449
+ }
450
+ /**
451
+ * Get JWT token for URL authentication (used in streaming endpoints).
452
+ * Returns null if no token getter is configured or no token is available.
453
+ */
454
+ getToken() {
455
+ return this.tokenGetter ? this.tokenGetter() : null;
456
+ }
457
+ /**
458
+ * Make HTTP request with Django CSRF and session handling.
459
+ * Automatically retries on network errors and 5xx server errors.
460
+ */
461
+ async request(method, path, options) {
462
+ if (this.retryConfig) {
463
+ return withRetry(() => this._makeRequest(method, path, options), {
464
+ ...this.retryConfig,
465
+ onFailedAttempt: /* @__PURE__ */ __name((info) => {
466
+ if (this.logger) {
467
+ this.logger.warn(
468
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
469
+ );
470
+ }
471
+ this.retryConfig?.onFailedAttempt?.(info);
472
+ }, "onFailedAttempt")
473
+ });
474
+ }
475
+ return this._makeRequest(method, path, options);
476
+ }
477
+ /**
478
+ * Internal request method (without retry wrapper).
479
+ * Used by request() method with optional retry logic.
480
+ */
481
+ async _makeRequest(method, path, options) {
482
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
483
+ const startTime = Date.now();
484
+ const headers = {
485
+ ...options?.headers || {}
486
+ };
487
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
488
+ headers["Content-Type"] = "application/json";
489
+ }
490
+ if (this.logger) {
491
+ this.logger.logRequest({
492
+ method,
493
+ url,
494
+ headers,
495
+ body: options?.formData || options?.body,
496
+ timestamp: startTime
497
+ });
498
+ }
499
+ try {
500
+ const response = await this.httpClient.request({
501
+ method,
502
+ url,
503
+ headers,
504
+ params: options?.params,
505
+ body: options?.body,
506
+ formData: options?.formData,
507
+ binaryBody: options?.binaryBody
508
+ });
509
+ const duration = Date.now() - startTime;
510
+ if (response.status >= 400) {
511
+ const error = new APIError(
512
+ response.status,
513
+ response.statusText,
514
+ response.data,
515
+ url
516
+ );
517
+ if (this.logger) {
518
+ this.logger.logError(
519
+ {
520
+ method,
521
+ url,
522
+ headers,
523
+ body: options?.formData || options?.body,
524
+ timestamp: startTime
525
+ },
526
+ {
527
+ message: error.message,
528
+ statusCode: response.status,
529
+ duration,
530
+ timestamp: Date.now()
531
+ }
532
+ );
533
+ }
534
+ throw error;
535
+ }
536
+ if (this.logger) {
537
+ this.logger.logResponse(
538
+ {
539
+ method,
540
+ url,
541
+ headers,
542
+ body: options?.formData || options?.body,
543
+ timestamp: startTime
544
+ },
545
+ {
546
+ status: response.status,
547
+ statusText: response.statusText,
548
+ data: response.data,
549
+ duration,
550
+ timestamp: Date.now()
551
+ }
552
+ );
553
+ }
554
+ return response.data;
555
+ } catch (error) {
556
+ const duration = Date.now() - startTime;
557
+ if (error instanceof APIError) {
558
+ throw error;
559
+ }
560
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
561
+ if (this.logger) {
562
+ if (isCORSError) {
563
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
564
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
565
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
566
+ } else {
567
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
568
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
569
+ }
570
+ }
571
+ if (typeof window !== "undefined") {
572
+ try {
573
+ if (isCORSError) {
574
+ window.dispatchEvent(new CustomEvent("cors-error", {
575
+ detail: {
576
+ url,
577
+ method,
578
+ error: error instanceof Error ? error.message : String(error),
579
+ timestamp: /* @__PURE__ */ new Date()
580
+ },
581
+ bubbles: true,
582
+ cancelable: false
583
+ }));
584
+ } else {
585
+ window.dispatchEvent(new CustomEvent("network-error", {
586
+ detail: {
587
+ url,
588
+ method,
589
+ error: error instanceof Error ? error.message : String(error),
590
+ timestamp: /* @__PURE__ */ new Date()
591
+ },
592
+ bubbles: true,
593
+ cancelable: false
594
+ }));
595
+ }
596
+ } catch (eventError) {
597
+ }
598
+ }
599
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
600
+ if (this.logger) {
601
+ this.logger.logError(
602
+ {
603
+ method,
604
+ url,
605
+ headers,
606
+ body: options?.formData || options?.body,
607
+ timestamp: startTime
608
+ },
609
+ {
610
+ message: networkError.message,
611
+ duration,
612
+ timestamp: Date.now()
613
+ }
614
+ );
615
+ }
616
+ throw networkError;
617
+ }
618
+ }
619
+ };
620
+ __name(_APIClient, "APIClient");
621
+ var APIClient = _APIClient;
622
+
623
+ // src/_api/generated/cfg_monitor/storage.ts
624
+ var _LocalStorageAdapter = class _LocalStorageAdapter {
625
+ constructor(logger) {
626
+ this.logger = logger;
627
+ }
628
+ getItem(key) {
629
+ try {
630
+ if (typeof window !== "undefined" && window.localStorage) {
631
+ const value = localStorage.getItem(key);
632
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
633
+ return value;
634
+ }
635
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
636
+ } catch (error) {
637
+ this.logger?.error("LocalStorage.getItem failed:", error);
638
+ }
639
+ return null;
640
+ }
641
+ setItem(key, value) {
642
+ try {
643
+ if (typeof window !== "undefined" && window.localStorage) {
644
+ localStorage.setItem(key, value);
645
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
646
+ } else {
647
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
648
+ }
649
+ } catch (error) {
650
+ this.logger?.error("LocalStorage.setItem failed:", error);
651
+ }
652
+ }
653
+ removeItem(key) {
654
+ try {
655
+ if (typeof window !== "undefined" && window.localStorage) {
656
+ localStorage.removeItem(key);
657
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
658
+ } else {
659
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
660
+ }
661
+ } catch (error) {
662
+ this.logger?.error("LocalStorage.removeItem failed:", error);
663
+ }
664
+ }
665
+ };
666
+ __name(_LocalStorageAdapter, "LocalStorageAdapter");
667
+ var LocalStorageAdapter = _LocalStorageAdapter;
668
+ var _MemoryStorageAdapter = class _MemoryStorageAdapter {
669
+ constructor(logger) {
670
+ this.storage = /* @__PURE__ */ new Map();
671
+ this.logger = logger;
672
+ }
673
+ getItem(key) {
674
+ const value = this.storage.get(key) || null;
675
+ this.logger?.debug(`MemoryStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
676
+ return value;
677
+ }
678
+ setItem(key, value) {
679
+ this.storage.set(key, value);
680
+ this.logger?.debug(`MemoryStorage.setItem("${key}"): success`);
681
+ }
682
+ removeItem(key) {
683
+ this.storage.delete(key);
684
+ this.logger?.debug(`MemoryStorage.removeItem("${key}"): success`);
685
+ }
686
+ };
687
+ __name(_MemoryStorageAdapter, "MemoryStorageAdapter");
688
+ var MemoryStorageAdapter = _MemoryStorageAdapter;
689
+
690
+ // src/_api/generated/cfg_monitor/enums.ts
691
+ var FrontendEventIngestRequestEventType = /* @__PURE__ */ ((FrontendEventIngestRequestEventType2) => {
692
+ FrontendEventIngestRequestEventType2["ERROR"] = "ERROR";
693
+ FrontendEventIngestRequestEventType2["WARNING"] = "WARNING";
694
+ FrontendEventIngestRequestEventType2["INFO"] = "INFO";
695
+ FrontendEventIngestRequestEventType2["PAGE_VIEW"] = "PAGE_VIEW";
696
+ FrontendEventIngestRequestEventType2["PERFORMANCE"] = "PERFORMANCE";
697
+ FrontendEventIngestRequestEventType2["NETWORK_ERROR"] = "NETWORK_ERROR";
698
+ FrontendEventIngestRequestEventType2["JS_ERROR"] = "JS_ERROR";
699
+ FrontendEventIngestRequestEventType2["CONSOLE"] = "CONSOLE";
700
+ return FrontendEventIngestRequestEventType2;
701
+ })(FrontendEventIngestRequestEventType || {});
702
+ var FrontendEventIngestRequestLevel = /* @__PURE__ */ ((FrontendEventIngestRequestLevel2) => {
703
+ FrontendEventIngestRequestLevel2["ERROR"] = "error";
704
+ FrontendEventIngestRequestLevel2["WARN"] = "warn";
705
+ FrontendEventIngestRequestLevel2["INFO"] = "info";
706
+ FrontendEventIngestRequestLevel2["DEBUG"] = "debug";
707
+ return FrontendEventIngestRequestLevel2;
708
+ })(FrontendEventIngestRequestLevel || {});
709
+
710
+ // src/_api/generated/cfg_monitor/_utils/schemas/FrontendEventIngestRequest.schema.ts
711
+ var import_zod = require("zod");
712
+ var FrontendEventIngestRequestSchema = import_zod.z.object({
713
+ event_type: import_zod.z.nativeEnum(FrontendEventIngestRequestEventType),
714
+ message: import_zod.z.string().min(1).max(5e3),
715
+ level: import_zod.z.nativeEnum(FrontendEventIngestRequestLevel).optional(),
716
+ stack_trace: import_zod.z.string().max(2e4).optional(),
717
+ url: import_zod.z.string().max(2e3).optional(),
718
+ fingerprint: import_zod.z.string().max(64).optional(),
719
+ http_status: import_zod.z.number().int().nullable().optional(),
720
+ http_method: import_zod.z.string().max(10).optional(),
721
+ http_url: import_zod.z.string().max(2e3).optional(),
722
+ user_agent: import_zod.z.string().max(500).optional(),
723
+ session_id: import_zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
724
+ browser_fingerprint: import_zod.z.string().max(64).optional(),
725
+ extra: import_zod.z.record(import_zod.z.string(), import_zod.z.any()).optional(),
726
+ project_name: import_zod.z.string().max(100).optional(),
727
+ environment: import_zod.z.string().max(20).optional()
728
+ });
729
+
730
+ // src/_api/generated/cfg_monitor/_utils/schemas/IngestBatchRequest.schema.ts
731
+ var import_zod2 = require("zod");
732
+ var IngestBatchRequestSchema = import_zod2.z.object({
733
+ events: import_zod2.z.array(FrontendEventIngestRequestSchema)
734
+ });
735
+
736
+ // src/_api/generated/cfg_monitor/index.ts
737
+ var TOKEN_KEY = "auth_token";
738
+ var REFRESH_TOKEN_KEY = "refresh_token";
739
+ function detectLocale() {
740
+ try {
741
+ if (typeof document !== "undefined") {
742
+ const match = document.cookie.match(/(?:^|;\s*)NEXT_LOCALE=([^;]*)/);
743
+ if (match) return match[1];
744
+ }
745
+ if (typeof navigator !== "undefined" && navigator.language) {
746
+ return navigator.language;
747
+ }
748
+ } catch {
749
+ }
750
+ return null;
751
+ }
752
+ __name(detectLocale, "detectLocale");
753
+ var _API = class _API {
754
+ constructor(baseUrl, options) {
755
+ this._token = null;
756
+ this._refreshToken = null;
757
+ this._locale = null;
758
+ this.baseUrl = baseUrl;
759
+ this.options = options;
760
+ const logger = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
761
+ this.storage = options?.storage || new LocalStorageAdapter(logger);
762
+ this._locale = options?.locale || null;
763
+ this._loadTokensFromStorage();
764
+ this._client = new APIClient(this.baseUrl, {
765
+ httpClient: this.options?.httpClient,
766
+ retryConfig: this.options?.retryConfig,
767
+ loggerConfig: this.options?.loggerConfig,
768
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
769
+ });
770
+ this._injectAuthHeader();
771
+ this.monitor = this._client.monitor;
772
+ }
773
+ _loadTokensFromStorage() {
774
+ this._token = this.storage.getItem(TOKEN_KEY);
775
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
776
+ }
777
+ _reinitClients() {
778
+ this._client = new APIClient(this.baseUrl, {
779
+ httpClient: this.options?.httpClient,
780
+ retryConfig: this.options?.retryConfig,
781
+ loggerConfig: this.options?.loggerConfig,
782
+ tokenGetter: /* @__PURE__ */ __name(() => this.getToken(), "tokenGetter")
783
+ });
784
+ this._injectAuthHeader();
785
+ this.monitor = this._client.monitor;
786
+ }
787
+ _injectAuthHeader() {
788
+ const originalRequest = this._client.request.bind(this._client);
789
+ this._client.request = async (method, path, options) => {
790
+ const token = this.getToken();
791
+ const locale = this._locale || detectLocale();
792
+ const mergedOptions = {
793
+ ...options,
794
+ headers: {
795
+ ...options?.headers || {},
796
+ ...token ? { "Authorization": `Bearer ${token}` } : {},
797
+ ...locale ? { "Accept-Language": locale } : {}
798
+ }
799
+ };
800
+ return originalRequest(method, path, mergedOptions);
801
+ };
802
+ }
803
+ /**
804
+ * Get current JWT token
805
+ */
806
+ getToken() {
807
+ return this.storage.getItem(TOKEN_KEY);
808
+ }
809
+ /**
810
+ * Get current refresh token
811
+ */
812
+ getRefreshToken() {
813
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
814
+ }
815
+ /**
816
+ * Set JWT token and refresh token
817
+ * @param token - JWT access token
818
+ * @param refreshToken - JWT refresh token (optional)
819
+ */
820
+ setToken(token, refreshToken) {
821
+ this._token = token;
822
+ this.storage.setItem(TOKEN_KEY, token);
823
+ if (refreshToken) {
824
+ this._refreshToken = refreshToken;
825
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
826
+ }
827
+ this._reinitClients();
828
+ }
829
+ /**
830
+ * Clear all tokens
831
+ */
832
+ clearTokens() {
833
+ this._token = null;
834
+ this._refreshToken = null;
835
+ this.storage.removeItem(TOKEN_KEY);
836
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
837
+ this._reinitClients();
838
+ }
839
+ /**
840
+ * Check if user is authenticated
841
+ */
842
+ isAuthenticated() {
843
+ return !!this.getToken();
844
+ }
845
+ /**
846
+ * Update base URL and reinitialize clients
847
+ * @param url - New base URL
848
+ */
849
+ setBaseUrl(url) {
850
+ this.baseUrl = url;
851
+ this._reinitClients();
852
+ }
853
+ /**
854
+ * Get current base URL
855
+ */
856
+ getBaseUrl() {
857
+ return this.baseUrl;
858
+ }
859
+ /**
860
+ * Set locale for Accept-Language header
861
+ * @param locale - Locale string (e.g. 'en', 'ko', 'ru') or null to clear
862
+ */
863
+ setLocale(locale) {
864
+ this._locale = locale;
865
+ }
866
+ /**
867
+ * Get current locale
868
+ */
869
+ getLocale() {
870
+ return this._locale;
871
+ }
872
+ /**
873
+ * Get OpenAPI schema path
874
+ * @returns Path to the OpenAPI schema JSON file
875
+ *
876
+ * Note: The OpenAPI schema is available in the schema.json file.
877
+ * You can load it dynamically using:
878
+ * ```typescript
879
+ * const schema = await fetch('./schema.json').then(r => r.json());
880
+ * // or using fs in Node.js:
881
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
882
+ * ```
883
+ */
884
+ getSchemaPath() {
885
+ return "./schema.json";
886
+ }
887
+ };
888
+ __name(_API, "API");
889
+ var API = _API;
890
+
891
+ // src/_api/BaseClient.ts
892
+ var monitorApi = new API("", { storage: new MemoryStorageAdapter() });
893
+ var _BaseClient = class _BaseClient {
894
+ };
895
+ __name(_BaseClient, "BaseClient");
896
+ _BaseClient.monitorApi = monitorApi;
897
+ var BaseClient = _BaseClient;
18
898
  //# sourceMappingURL=index.cjs.map