@tracewayapp/core 1.2.2 → 2.0.0-beta.1

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.js CHANGED
@@ -20,14 +20,40 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ControlState: () => ControlState,
24
+ DEFAULT_EXCEPTION_TRIGGER_ID: () => DEFAULT_EXCEPTION_TRIGGER_ID,
23
25
  EventBuffer: () => EventBuffer,
24
26
  METRIC_CPU_USED_PCNT: () => METRIC_CPU_USED_PCNT,
25
27
  METRIC_MEM_TOTAL: () => METRIC_MEM_TOTAL,
26
28
  METRIC_MEM_USED: () => METRIC_MEM_USED,
29
+ MODES: () => MODES,
30
+ RingBuffer: () => RingBuffer,
31
+ SEVERITIES: () => SEVERITIES,
32
+ SIGNALS: () => SIGNALS,
33
+ SettingsError: () => SettingsError,
34
+ TriggerEngine: () => TriggerEngine,
35
+ applyLimits: () => applyLimits,
36
+ applyOverlay: () => applyOverlay,
37
+ bytesToUuid: () => bytesToUuid,
38
+ ceilingsFrom: () => ceilingsFrom,
39
+ clampToCeilings: () => clampToCeilings,
40
+ compareVersions: () => compareVersions,
41
+ defaultExceptionTrigger: () => defaultExceptionTrigger,
42
+ defaultSettings: () => defaultSettings,
27
43
  generateUUID: () => generateUUID,
44
+ lowerMode: () => lowerMode,
45
+ matches: () => matches,
46
+ modeRank: () => modeRank,
28
47
  msToNanoseconds: () => msToNanoseconds,
29
48
  nowISO: () => nowISO,
30
- parseConnectionString: () => parseConnectionString
49
+ parseConnectionString: () => parseConnectionString,
50
+ parseMatcher: () => parseMatcher,
51
+ parseSettingsDocument: () => parseSettingsDocument,
52
+ resolveEndpoints: () => resolveEndpoints,
53
+ satisfiesVersion: () => satisfiesVersion,
54
+ unitHash: () => unitHash,
55
+ uuidToBytes: () => uuidToBytes,
56
+ uuidv7: () => uuidv7
31
57
  });
32
58
  module.exports = __toCommonJS(index_exports);
33
59
 
@@ -104,15 +130,940 @@ var EventBuffer = class {
104
130
  }
105
131
  }
106
132
  };
133
+
134
+ // src/connection.ts
135
+ function resolveEndpoints(apiUrl) {
136
+ const base = apiUrl.trim().replace(/\/+$/, "").replace(/\/api\/report$/, "").replace(/\/api$/, "");
137
+ return {
138
+ base,
139
+ logs: `${base}/api/otel/v1/logs`,
140
+ traces: `${base}/api/otel/v1/traces`,
141
+ opamp: `${base}/api/otel/v1/opamp`,
142
+ recordings: `${base}/api/recordings`
143
+ };
144
+ }
145
+
146
+ // src/ids.ts
147
+ function randomBytes(length) {
148
+ const bytes = new Uint8Array(length);
149
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
150
+ crypto.getRandomValues(bytes);
151
+ } else {
152
+ for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);
153
+ }
154
+ return bytes;
155
+ }
156
+ function bytesToUuid(bytes) {
157
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
158
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
159
+ }
160
+ function uuidToBytes(uuid) {
161
+ const hex = uuid.replace(/-/g, "");
162
+ if (!/^[0-9a-fA-F]{32}$/.test(hex)) return null;
163
+ const bytes = new Uint8Array(16);
164
+ for (let i = 0; i < 16; i++) bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
165
+ return bytes;
166
+ }
167
+ function uuidv7(nowMs = Date.now()) {
168
+ const bytes = randomBytes(16);
169
+ let ts = Math.max(0, Math.floor(nowMs));
170
+ for (let i = 5; i >= 0; i--) {
171
+ bytes[i] = ts % 256;
172
+ ts = Math.floor(ts / 256);
173
+ }
174
+ bytes[6] = bytes[6] & 15 | 112;
175
+ bytes[8] = bytes[8] & 63 | 128;
176
+ return bytesToUuid(bytes);
177
+ }
178
+ function unitHash(value) {
179
+ let hash = 2166136261;
180
+ for (let i = 0; i < value.length; i++) {
181
+ hash ^= value.charCodeAt(i);
182
+ hash = Math.imul(hash, 16777619);
183
+ }
184
+ return (hash >>> 0) / 4294967296;
185
+ }
186
+
187
+ // src/settings/types.ts
188
+ var MODES = ["off", "buffer", "stream"];
189
+ var SIGNALS = [
190
+ "errors",
191
+ "messages",
192
+ "network",
193
+ "console",
194
+ "navigation",
195
+ "userActions",
196
+ "webVitals",
197
+ "resourceTiming",
198
+ "custom"
199
+ ];
200
+ var SEVERITIES = [
201
+ "trace",
202
+ "debug",
203
+ "info",
204
+ "warn",
205
+ "error",
206
+ "fatal"
207
+ ];
208
+
209
+ // src/settings/defaults.ts
210
+ var DEFAULT_EXCEPTION_TRIGGER_ID = "default-exception";
211
+ function defaultExceptionTrigger() {
212
+ return {
213
+ id: DEFAULT_EXCEPTION_TRIGGER_ID,
214
+ name: "Error clip",
215
+ enabled: true,
216
+ sampleRate: 1,
217
+ cooldownSeconds: 5,
218
+ maxPerSession: 20,
219
+ steps: [{ match: { key: "event.name", op: "eq", value: "exception" } }],
220
+ actions: [
221
+ { type: "flush", lookbackSeconds: 600, signals: ["*"], replay: false },
222
+ { type: "flush", lookbackSeconds: 30, signals: [], replay: true }
223
+ ]
224
+ };
225
+ }
226
+ function defaultSettings(options = {}) {
227
+ const breadcrumbs = options.recordAllSessions ? "stream" : "buffer";
228
+ return {
229
+ schemaVersion: 1,
230
+ enabled: true,
231
+ signals: {
232
+ errors: { mode: "stream", sampleRate: 1 },
233
+ messages: { mode: "stream", sampleRate: 1 },
234
+ network: { mode: breadcrumbs, sampleRate: 1 },
235
+ console: { mode: breadcrumbs, sampleRate: 1, minSeverity: "info" },
236
+ navigation: { mode: breadcrumbs, sampleRate: 1 },
237
+ userActions: { mode: breadcrumbs, sampleRate: 1 },
238
+ webVitals: { mode: "stream", sampleRate: 1 },
239
+ resourceTiming: { mode: "off", sampleRate: 1 },
240
+ custom: { mode: breadcrumbs, sampleRate: 1 }
241
+ },
242
+ sessions: {
243
+ enabled: true,
244
+ baselineSampleRate: Number.isFinite(options.baselineSampleRate) ? Math.min(1, Math.max(0, options.baselineSampleRate)) : 0
245
+ },
246
+ replay: {
247
+ mode: options.recordAllSessions ? "stream" : "buffer",
248
+ sessionSampleRate: 1,
249
+ maskAllInputs: true
250
+ },
251
+ buffer: {
252
+ maxBytes: 2 * 1024 * 1024,
253
+ maxAgeSeconds: 600,
254
+ replayMaxBytes: 8 * 1024 * 1024,
255
+ persist: true
256
+ },
257
+ triggers: [defaultExceptionTrigger()],
258
+ captures: []
259
+ };
260
+ }
261
+ function ceilingsFrom(options = {}) {
262
+ const allow = (flag) => flag === false ? "off" : "stream";
263
+ const signals = {};
264
+ for (const signal of SIGNALS) signals[signal] = "stream";
265
+ signals.console = allow(options.captureLogs);
266
+ signals.network = allow(options.captureNetwork);
267
+ signals.navigation = allow(options.captureNavigation);
268
+ signals.userActions = allow(options.captureUserActions);
269
+ signals.webVitals = allow(options.captureWebVitals);
270
+ signals.resourceTiming = allow(options.captureResourceTiming);
271
+ return {
272
+ enabled: options.enabled !== false,
273
+ signals,
274
+ replay: allow(options.sessionRecording),
275
+ sessions: options.sessions !== false
276
+ };
277
+ }
278
+
279
+ // src/settings/merge.ts
280
+ var SettingsError = class extends Error {
281
+ };
282
+ var CONDITION_OPS = [
283
+ "eq",
284
+ "neq",
285
+ "in",
286
+ "not_in",
287
+ "contains",
288
+ "icontains",
289
+ "starts_with",
290
+ "glob",
291
+ "exists",
292
+ "not_exists",
293
+ "gt",
294
+ "gte",
295
+ "lt",
296
+ "lte",
297
+ "version"
298
+ ];
299
+ var MAX_MATCHER_DEPTH = 8;
300
+ var MAX_STEP_COUNT = 1e3;
301
+ var MAX_BUFFER_BYTES = 64 * 1024 * 1024;
302
+ var MAX_BUFFER_AGE_SECONDS = 24 * 60 * 60;
303
+ function isObject(value) {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }
306
+ function isMode(value) {
307
+ return typeof value === "string" && MODES.includes(value);
308
+ }
309
+ function rate(value) {
310
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : void 0;
311
+ }
312
+ function positive(value, max) {
313
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(value, max) : void 0;
314
+ }
315
+ function parseSettingsDocument(body) {
316
+ const text2 = typeof body === "string" ? body : new TextDecoder().decode(body);
317
+ let parsed;
318
+ try {
319
+ parsed = JSON.parse(text2);
320
+ } catch {
321
+ throw new SettingsError("settings document is not valid JSON");
322
+ }
323
+ if (!isObject(parsed)) {
324
+ throw new SettingsError("settings document must be a JSON object");
325
+ }
326
+ if (parsed.schemaVersion !== void 0 && parsed.schemaVersion !== 1) {
327
+ throw new SettingsError(
328
+ `unsupported settings schemaVersion ${String(parsed.schemaVersion)}`
329
+ );
330
+ }
331
+ return parsed;
332
+ }
333
+ function scalar(value) {
334
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
335
+ }
336
+ function parseMatcher(value, depth = 0) {
337
+ if (!isObject(value) || depth > MAX_MATCHER_DEPTH) return null;
338
+ if (Array.isArray(value.all) || Array.isArray(value.any)) {
339
+ const key = Array.isArray(value.all) ? "all" : "any";
340
+ const items = [];
341
+ for (const item of value[key]) {
342
+ const parsed = parseMatcher(item, depth + 1);
343
+ if (!parsed) return null;
344
+ items.push(parsed);
345
+ }
346
+ return key === "all" ? { all: items } : { any: items };
347
+ }
348
+ if (value.not !== void 0) {
349
+ const inner = parseMatcher(value.not, depth + 1);
350
+ return inner ? { not: inner } : null;
351
+ }
352
+ if (typeof value.key !== "string" || !value.key) return null;
353
+ if (typeof value.op !== "string" || !CONDITION_OPS.includes(value.op))
354
+ return null;
355
+ const condition = { key: value.key, op: value.op };
356
+ if (value.value !== void 0) {
357
+ if (!scalar(value.value)) return null;
358
+ condition.value = value.value;
359
+ }
360
+ if (value.values !== void 0) {
361
+ if (!Array.isArray(value.values) || !value.values.every(scalar))
362
+ return null;
363
+ condition.values = value.values;
364
+ }
365
+ return condition;
366
+ }
367
+ function parseSignalSelector(value) {
368
+ if (!Array.isArray(value)) return void 0;
369
+ const known = value.filter(
370
+ (s) => s === "*" || SIGNALS.includes(s)
371
+ );
372
+ return known;
373
+ }
374
+ function parseAction(value) {
375
+ if (!isObject(value)) return null;
376
+ switch (value.type) {
377
+ case "flush": {
378
+ const lookbackSeconds = positive(
379
+ value.lookbackSeconds,
380
+ MAX_BUFFER_AGE_SECONDS
381
+ );
382
+ if (lookbackSeconds === void 0) return null;
383
+ return {
384
+ type: "flush",
385
+ lookbackSeconds,
386
+ signals: parseSignalSelector(value.signals),
387
+ replay: value.replay === true
388
+ };
389
+ }
390
+ case "stream": {
391
+ const durationSeconds = positive(
392
+ value.durationSeconds,
393
+ MAX_BUFFER_AGE_SECONDS
394
+ );
395
+ if (durationSeconds === void 0) return null;
396
+ return {
397
+ type: "stream",
398
+ durationSeconds,
399
+ signals: parseSignalSelector(value.signals),
400
+ replay: value.replay === true
401
+ };
402
+ }
403
+ case "startReplay": {
404
+ const durationSeconds = positive(
405
+ value.durationSeconds,
406
+ MAX_BUFFER_AGE_SECONDS
407
+ );
408
+ return durationSeconds === void 0 ? null : { type: "startReplay", durationSeconds };
409
+ }
410
+ case "capture": {
411
+ const durationSeconds = positive(
412
+ value.durationSeconds,
413
+ MAX_BUFFER_AGE_SECONDS
414
+ );
415
+ if (durationSeconds === void 0) return null;
416
+ const action = {
417
+ type: "capture",
418
+ durationSeconds,
419
+ signals: parseSignalSelector(value.signals),
420
+ replay: value.replay === true
421
+ };
422
+ const lookbackSeconds = positive(
423
+ value.lookbackSeconds,
424
+ MAX_BUFFER_AGE_SECONDS
425
+ );
426
+ if (lookbackSeconds !== void 0)
427
+ action.lookbackSeconds = lookbackSeconds;
428
+ return action;
429
+ }
430
+ case "emit": {
431
+ if (typeof value.eventName !== "string" || !value.eventName) return null;
432
+ const attributes = {};
433
+ if (isObject(value.attributes)) {
434
+ for (const [k, v] of Object.entries(value.attributes)) {
435
+ if (typeof v === "string") attributes[k] = v;
436
+ }
437
+ }
438
+ return { type: "emit", eventName: value.eventName, attributes };
439
+ }
440
+ }
441
+ return null;
442
+ }
443
+ function parseSteps(value) {
444
+ if (!Array.isArray(value) || value.length === 0) return null;
445
+ const steps = [];
446
+ for (const raw of value) {
447
+ if (!isObject(raw)) return null;
448
+ const match = parseMatcher(raw.match);
449
+ if (!match) return null;
450
+ const within = raw.withinSeconds;
451
+ const step = {
452
+ match,
453
+ withinSeconds: typeof within === "number" && within > 0 ? within : null
454
+ };
455
+ if (typeof raw.count === "number" && Number.isInteger(raw.count) && raw.count > 1) {
456
+ step.count = Math.min(raw.count, MAX_STEP_COUNT);
457
+ const period = raw.periodSeconds;
458
+ step.periodSeconds = typeof period === "number" && period > 0 ? Math.min(period, MAX_BUFFER_AGE_SECONDS) : null;
459
+ }
460
+ steps.push(step);
461
+ }
462
+ return steps;
463
+ }
464
+ function parseActions(value) {
465
+ if (!Array.isArray(value) || value.length === 0) return null;
466
+ const actions = value.map(parseAction);
467
+ return actions.every((a) => a !== null) ? actions : null;
468
+ }
469
+ function mergeTrigger(base, raw) {
470
+ const steps = raw.steps === void 0 ? base?.steps : parseSteps(raw.steps);
471
+ const actions = raw.actions === void 0 ? base?.actions : parseActions(raw.actions);
472
+ if (!steps || !actions) return null;
473
+ const merged = {
474
+ ...base ?? { id: String(raw.id) },
475
+ steps,
476
+ actions
477
+ };
478
+ if (typeof raw.name === "string") merged.name = raw.name;
479
+ if (typeof raw.enabled === "boolean") merged.enabled = raw.enabled;
480
+ const sampleRate = rate(raw.sampleRate);
481
+ if (sampleRate !== void 0) merged.sampleRate = sampleRate;
482
+ if (typeof raw.cooldownSeconds === "number" && raw.cooldownSeconds >= 0)
483
+ merged.cooldownSeconds = raw.cooldownSeconds;
484
+ if (typeof raw.maxPerSession === "number" && raw.maxPerSession >= 0)
485
+ merged.maxPerSession = raw.maxPerSession;
486
+ return merged;
487
+ }
488
+ function parseCapture(value) {
489
+ if (!isObject(value) || typeof value.id !== "string" || typeof value.until !== "string")
490
+ return null;
491
+ if (!Number.isFinite(Date.parse(value.until))) return null;
492
+ const capture = {
493
+ id: value.id,
494
+ until: value.until,
495
+ replay: value.replay === true
496
+ };
497
+ const lookback = value.lookbackSeconds === 0 ? 0 : positive(value.lookbackSeconds, MAX_BUFFER_AGE_SECONDS);
498
+ if (lookback !== void 0) capture.lookbackSeconds = lookback;
499
+ const signals = parseSignalSelector(value.signals);
500
+ if (signals) capture.signals = signals;
501
+ return capture;
502
+ }
503
+ function cloneSettings(settings) {
504
+ return JSON.parse(JSON.stringify(settings));
505
+ }
506
+ function applyOverlay(base, overlay) {
507
+ const out = cloneSettings(base);
508
+ if (typeof overlay.enabled === "boolean") out.enabled = overlay.enabled;
509
+ if (isObject(overlay.signals)) {
510
+ for (const signal of SIGNALS) {
511
+ const raw = overlay.signals[signal];
512
+ if (!isObject(raw)) continue;
513
+ const target = out.signals[signal];
514
+ if (isMode(raw.mode)) target.mode = raw.mode;
515
+ const sampleRate = rate(raw.sampleRate);
516
+ if (sampleRate !== void 0) target.sampleRate = sampleRate;
517
+ if (typeof raw.minSeverity === "string" && SEVERITIES.includes(raw.minSeverity)) {
518
+ target.minSeverity = raw.minSeverity;
519
+ }
520
+ }
521
+ }
522
+ if (isObject(overlay.sessions)) {
523
+ if (typeof overlay.sessions.enabled === "boolean")
524
+ out.sessions.enabled = overlay.sessions.enabled;
525
+ const baselineRate = rate(overlay.sessions.baselineSampleRate);
526
+ if (baselineRate !== void 0)
527
+ out.sessions.baselineSampleRate = baselineRate;
528
+ }
529
+ if (isObject(overlay.replay)) {
530
+ if (isMode(overlay.replay.mode)) out.replay.mode = overlay.replay.mode;
531
+ const sampleRate = rate(overlay.replay.sessionSampleRate);
532
+ if (sampleRate !== void 0) out.replay.sessionSampleRate = sampleRate;
533
+ if (typeof overlay.replay.maskAllInputs === "boolean")
534
+ out.replay.maskAllInputs = overlay.replay.maskAllInputs;
535
+ }
536
+ if (isObject(overlay.buffer)) {
537
+ const maxBytes = positive(overlay.buffer.maxBytes, MAX_BUFFER_BYTES);
538
+ if (maxBytes !== void 0) out.buffer.maxBytes = maxBytes;
539
+ const maxAge = positive(
540
+ overlay.buffer.maxAgeSeconds,
541
+ MAX_BUFFER_AGE_SECONDS
542
+ );
543
+ if (maxAge !== void 0) out.buffer.maxAgeSeconds = maxAge;
544
+ const replayMax = positive(overlay.buffer.replayMaxBytes, MAX_BUFFER_BYTES);
545
+ if (replayMax !== void 0) out.buffer.replayMaxBytes = replayMax;
546
+ if (typeof overlay.buffer.persist === "boolean")
547
+ out.buffer.persist = overlay.buffer.persist;
548
+ }
549
+ if (Array.isArray(overlay.triggers)) {
550
+ for (const raw of overlay.triggers) {
551
+ if (!isObject(raw) || typeof raw.id !== "string" || !raw.id) continue;
552
+ const index = out.triggers.findIndex((t) => t.id === raw.id);
553
+ const merged = mergeTrigger(
554
+ index >= 0 ? out.triggers[index] : void 0,
555
+ raw
556
+ );
557
+ if (!merged) continue;
558
+ if (index >= 0) out.triggers[index] = merged;
559
+ else out.triggers.push(merged);
560
+ }
561
+ }
562
+ if (Array.isArray(overlay.captures)) {
563
+ out.captures = overlay.captures.map(parseCapture).filter((c) => c !== null);
564
+ }
565
+ return out;
566
+ }
567
+ var MODE_RANK = { off: 0, buffer: 1, stream: 2 };
568
+ function lowerMode(a, b) {
569
+ return MODE_RANK[a] <= MODE_RANK[b] ? a : b;
570
+ }
571
+ function modeRank(mode) {
572
+ return MODE_RANK[mode];
573
+ }
574
+ function applyLimits(ceilings, overlay) {
575
+ if (!overlay || !isObject(overlay.limits)) return ceilings;
576
+ const limits = overlay.limits;
577
+ const out = { ...ceilings, signals: { ...ceilings.signals } };
578
+ if (isObject(limits.signals)) {
579
+ for (const signal of SIGNALS) {
580
+ const mode = limits.signals[signal];
581
+ if (isMode(mode))
582
+ out.signals[signal] = lowerMode(out.signals[signal], mode);
583
+ }
584
+ }
585
+ if (isMode(limits.replay)) out.replay = lowerMode(out.replay, limits.replay);
586
+ return out;
587
+ }
588
+ function clampToCeilings(settings, ceilings) {
589
+ const out = cloneSettings(settings);
590
+ out.enabled = out.enabled && ceilings.enabled;
591
+ for (const signal of SIGNALS) {
592
+ out.signals[signal].mode = lowerMode(
593
+ out.signals[signal].mode,
594
+ ceilings.signals[signal]
595
+ );
596
+ }
597
+ out.replay.mode = lowerMode(out.replay.mode, ceilings.replay);
598
+ out.sessions.enabled = out.sessions.enabled && ceilings.sessions;
599
+ return out;
600
+ }
601
+
602
+ // src/control/control-state.ts
603
+ var ControlState = class {
604
+ constructor(defaults, pageCeilings, now = Date.now) {
605
+ this.defaults = defaults;
606
+ this.pageCeilings = pageCeilings;
607
+ this.now = now;
608
+ this.ceilings = pageCeilings;
609
+ this.effective = clampToCeilings(defaults, pageCeilings);
610
+ }
611
+ defaults;
612
+ pageCeilings;
613
+ now;
614
+ remote = null;
615
+ effective;
616
+ overrides = /* @__PURE__ */ new Map();
617
+ overrideSequence = 0;
618
+ listeners = /* @__PURE__ */ new Set();
619
+ /** The page's ceilings lowered to the plan limits of the current remote document. */
620
+ ceilings;
621
+ settings() {
622
+ return this.effective;
623
+ }
624
+ remoteOverlay() {
625
+ return this.remote;
626
+ }
627
+ /** Applies a parsed remote document, or `null` to fall back to the defaults. */
628
+ applyRemote(overlay) {
629
+ this.remote = overlay;
630
+ this.ceilings = applyLimits(this.pageCeilings, overlay);
631
+ const merged = overlay ? applyOverlay(this.defaults, overlay) : this.defaults;
632
+ this.effective = clampToCeilings(merged, this.ceilings);
633
+ for (const listener of this.listeners) {
634
+ try {
635
+ listener(this.effective);
636
+ } catch {
637
+ }
638
+ }
639
+ }
640
+ onChange(listener) {
641
+ this.listeners.add(listener);
642
+ return () => this.listeners.delete(listener);
643
+ }
644
+ addOverride(override) {
645
+ this.setOverrides(`stream:${this.overrideSequence++}`, [override]);
646
+ }
647
+ setOverrides(owner, overrides) {
648
+ if (overrides.length) this.overrides.set(owner, overrides);
649
+ else this.overrides.delete(owner);
650
+ this.activeOverrides();
651
+ }
652
+ nextOverrideExpiry() {
653
+ const active = this.activeOverrides();
654
+ return active.length ? Math.min(...active.map((o) => o.untilMs)) : void 0;
655
+ }
656
+ activeOverrides() {
657
+ const now = this.now();
658
+ for (const [owner, overrides] of this.overrides) {
659
+ const active = overrides.filter((o) => o.untilMs > now);
660
+ if (active.length) this.overrides.set(owner, active);
661
+ else this.overrides.delete(owner);
662
+ }
663
+ return [...this.overrides.values()].flat();
664
+ }
665
+ canExport(signal) {
666
+ return this.enabled() && this.ceilings.signals[signal] === "stream" && this.modeFor(signal) !== "off";
667
+ }
668
+ enabled() {
669
+ return this.effective.enabled;
670
+ }
671
+ modeFor(signal) {
672
+ if (!this.effective.enabled) return "off";
673
+ const base = this.effective.signals[signal].mode;
674
+ if (base === "stream") return base;
675
+ for (const override of this.activeOverrides()) {
676
+ if (this.covers(override, signal, base))
677
+ return lowerMode("stream", this.ceilings.signals[signal]);
678
+ }
679
+ return base;
680
+ }
681
+ covers(override, signal, base) {
682
+ if (override.signals.includes(signal)) return true;
683
+ if (!override.signals.includes("*")) return false;
684
+ return base !== "off" || override.includeOff === true && this.defaults.signals[signal].mode !== "off";
685
+ }
686
+ replayMode() {
687
+ if (!this.effective.enabled) return "off";
688
+ const base = this.effective.replay.mode;
689
+ const boosted = this.activeOverrides().some((o) => o.replay);
690
+ if (boosted && modeRank(base) < modeRank("stream")) {
691
+ return lowerMode("stream", this.ceilings.replay);
692
+ }
693
+ return base;
694
+ }
695
+ sampleRate(signal) {
696
+ return this.effective.signals[signal].sampleRate;
697
+ }
698
+ };
699
+
700
+ // src/triggers/matcher.ts
701
+ function isCondition(m) {
702
+ return typeof m.key === "string";
703
+ }
704
+ function asNumber(value) {
705
+ if (typeof value === "number" && Number.isFinite(value)) return value;
706
+ if (typeof value === "string" && value.trim() !== "") {
707
+ const n = Number(value);
708
+ if (Number.isFinite(n)) return n;
709
+ }
710
+ return void 0;
711
+ }
712
+ function same(actual, expected) {
713
+ if (actual === expected) return true;
714
+ if (actual === void 0 || actual === null) return false;
715
+ const a = asNumber(actual);
716
+ const e = asNumber(expected);
717
+ if (a !== void 0 && e !== void 0) return a === e;
718
+ return String(actual) === String(expected);
719
+ }
720
+ function versionParts(version) {
721
+ const match = version.trim().match(/^v?(\d+(?:\.\d+)*)/);
722
+ if (!match) return null;
723
+ return match[1].split(".").map((p) => parseInt(p, 10));
724
+ }
725
+ function compareVersions(a, b) {
726
+ const pa = versionParts(a);
727
+ const pb = versionParts(b);
728
+ if (!pa || !pb) return null;
729
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
730
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
731
+ if (diff !== 0) return diff < 0 ? -1 : 1;
732
+ }
733
+ return 0;
734
+ }
735
+ function satisfiesVersion(version, constraint) {
736
+ const comparators = constraint.split(/[\s,]+/).filter(Boolean);
737
+ if (comparators.length === 0) return false;
738
+ for (const comparator of comparators) {
739
+ const match = comparator.match(/^(>=|<=|>|<|=|==|!=)?(.+)$/);
740
+ if (!match) return false;
741
+ const cmp = compareVersions(version, match[2]);
742
+ if (cmp === null) return false;
743
+ const ok = match[1] === ">=" ? cmp >= 0 : match[1] === "<=" ? cmp <= 0 : match[1] === ">" ? cmp > 0 : match[1] === "<" ? cmp < 0 : match[1] === "!=" ? cmp !== 0 : cmp === 0;
744
+ if (!ok) return false;
745
+ }
746
+ return true;
747
+ }
748
+ var MAX_MATCH_TEXT = 4096;
749
+ function text(value) {
750
+ const s = typeof value === "string" ? value : String(value);
751
+ return s.length > MAX_MATCH_TEXT ? s.slice(0, MAX_MATCH_TEXT) : s;
752
+ }
753
+ function globMatch(value, pattern) {
754
+ const t = value.toLowerCase();
755
+ const p = pattern.toLowerCase();
756
+ let ti = 0;
757
+ let pi = 0;
758
+ let star = -1;
759
+ let mark = 0;
760
+ while (ti < t.length) {
761
+ if (pi < p.length && (p[pi] === "?" || p[pi] === t[ti])) {
762
+ ti++;
763
+ pi++;
764
+ } else if (pi < p.length && p[pi] === "*") {
765
+ star = pi++;
766
+ mark = ti;
767
+ } else if (star >= 0) {
768
+ pi = star + 1;
769
+ ti = ++mark;
770
+ } else {
771
+ return false;
772
+ }
773
+ }
774
+ while (pi < p.length && p[pi] === "*") pi++;
775
+ return pi === p.length;
776
+ }
777
+ function evaluateCondition(condition, lookup) {
778
+ const actual = lookup(condition.key);
779
+ const present = actual !== void 0 && actual !== null && actual !== "";
780
+ switch (condition.op) {
781
+ case "exists":
782
+ return present;
783
+ case "not_exists":
784
+ return !present;
785
+ case "eq":
786
+ return same(actual, condition.value);
787
+ case "neq":
788
+ return !same(actual, condition.value);
789
+ case "in":
790
+ return (condition.values ?? []).some((v) => same(actual, v));
791
+ case "not_in":
792
+ return !(condition.values ?? []).some((v) => same(actual, v));
793
+ case "contains":
794
+ return present && condition.value !== void 0 && text(actual).includes(String(condition.value));
795
+ case "icontains":
796
+ return present && condition.value !== void 0 && text(actual).toLowerCase().includes(String(condition.value).toLowerCase());
797
+ case "starts_with":
798
+ return present && condition.value !== void 0 && text(actual).startsWith(String(condition.value));
799
+ case "glob":
800
+ return present && condition.value !== void 0 && globMatch(text(actual), String(condition.value));
801
+ case "gt":
802
+ case "gte":
803
+ case "lt":
804
+ case "lte": {
805
+ const a = asNumber(actual);
806
+ const e = asNumber(condition.value);
807
+ if (a === void 0 || e === void 0) return false;
808
+ return condition.op === "gt" ? a > e : condition.op === "gte" ? a >= e : condition.op === "lt" ? a < e : a <= e;
809
+ }
810
+ case "version":
811
+ return present && condition.value !== void 0 && satisfiesVersion(String(actual), String(condition.value));
812
+ }
813
+ return false;
814
+ }
815
+ function matches(matcher, lookup) {
816
+ if (isCondition(matcher)) return evaluateCondition(matcher, lookup);
817
+ if ("all" in matcher) return matcher.all.every((m) => matches(m, lookup));
818
+ if ("any" in matcher) return matcher.any.some((m) => matches(m, lookup));
819
+ if ("not" in matcher) return !matches(matcher.not, lookup);
820
+ return false;
821
+ }
822
+
823
+ // src/triggers/engine.ts
824
+ var TriggerEngine = class {
825
+ constructor(random = Math.random) {
826
+ this.random = random;
827
+ }
828
+ random;
829
+ triggers = [];
830
+ skipped = /* @__PURE__ */ new Map();
831
+ sessionLimits = /* @__PURE__ */ Object.create(null);
832
+ states = /* @__PURE__ */ new Map();
833
+ setTriggers(triggers) {
834
+ this.triggers = triggers.filter(
835
+ (t) => t.enabled !== false && t.steps.length > 0 && t.actions.length > 0
836
+ );
837
+ const next = /* @__PURE__ */ new Map();
838
+ for (const trigger of this.triggers) {
839
+ const signature = JSON.stringify(trigger.steps);
840
+ const prev = this.states.get(trigger.id);
841
+ next.set(
842
+ trigger.id,
843
+ prev && prev.signature === signature ? prev : {
844
+ signature,
845
+ step: 0,
846
+ lastStepMs: 0,
847
+ hits: [],
848
+ fires: prev?.fires ?? this.sessionLimits[trigger.id]?.fires ?? 0,
849
+ lastFireMs: prev?.lastFireMs ?? this.sessionLimits[trigger.id]?.lastFireMs ?? 0
850
+ }
851
+ );
852
+ }
853
+ this.states = next;
854
+ }
855
+ resetSession() {
856
+ this.sessionLimits = /* @__PURE__ */ Object.create(null);
857
+ for (const state of this.states.values()) {
858
+ state.step = 0;
859
+ state.lastStepMs = 0;
860
+ state.hits = [];
861
+ state.fires = 0;
862
+ state.lastFireMs = 0;
863
+ }
864
+ }
865
+ restoreSessionLimits(saved) {
866
+ if (!saved || typeof saved !== "object" || Array.isArray(saved)) return;
867
+ for (const [id, value] of Object.entries(saved)) {
868
+ if (!value || !Number.isFinite(value.fires) || value.fires < 0 || !Number.isFinite(value.lastFireMs))
869
+ continue;
870
+ this.sessionLimits[id] = {
871
+ fires: value.fires,
872
+ lastFireMs: value.lastFireMs
873
+ };
874
+ const state = this.states.get(id);
875
+ if (state) {
876
+ state.fires = value.fires;
877
+ state.lastFireMs = value.lastFireMs;
878
+ }
879
+ }
880
+ }
881
+ observe(event) {
882
+ this.skipped.clear();
883
+ const fired = [];
884
+ for (const trigger of this.triggers) {
885
+ const state = this.states.get(trigger.id);
886
+ if (!state) continue;
887
+ if (state.step > 0) {
888
+ const within = trigger.steps[state.step].withinSeconds;
889
+ if (within && event.timeMs - state.lastStepMs > within * 1e3)
890
+ restart(state);
891
+ }
892
+ if (!this.advance(trigger, state, event)) continue;
893
+ if (!this.mayFire(trigger, state, event.timeMs)) continue;
894
+ state.fires++;
895
+ state.lastFireMs = event.timeMs;
896
+ this.sessionLimits[trigger.id] = {
897
+ fires: state.fires,
898
+ lastFireMs: state.lastFireMs
899
+ };
900
+ fired.push({ trigger, actions: trigger.actions, cause: event });
901
+ }
902
+ return fired;
903
+ }
904
+ /** Feeds one record to a trigger; true when it completed the last step. */
905
+ advance(trigger, state, event) {
906
+ if (!matches(trigger.steps[state.step].match, event.lookup)) {
907
+ if (state.step === 0 || !matches(trigger.steps[0].match, event.lookup))
908
+ return false;
909
+ restart(state);
910
+ }
911
+ const step = trigger.steps[state.step];
912
+ const needed = step.count ?? 1;
913
+ if (needed > 1) {
914
+ state.hits.push(event.timeMs);
915
+ if (step.periodSeconds) {
916
+ const cutoff = event.timeMs - step.periodSeconds * 1e3;
917
+ state.hits = state.hits.filter((t) => t >= cutoff);
918
+ }
919
+ if (state.hits.length < needed) return false;
920
+ }
921
+ state.hits = [];
922
+ state.step++;
923
+ state.lastStepMs = event.timeMs;
924
+ if (state.step < trigger.steps.length) return false;
925
+ state.step = 0;
926
+ return true;
927
+ }
928
+ mayFire(trigger, state, nowMs) {
929
+ if (trigger.maxPerSession !== void 0 && state.fires >= trigger.maxPerSession) {
930
+ this.skipped.set(trigger.id, "session_clip_limit");
931
+ return false;
932
+ }
933
+ if (trigger.cooldownSeconds && state.fires > 0 && nowMs - state.lastFireMs < trigger.cooldownSeconds * 1e3) {
934
+ this.skipped.set(trigger.id, "cooldown");
935
+ return false;
936
+ }
937
+ const sampleRate = trigger.sampleRate ?? 1;
938
+ const accepted = sampleRate >= 1 || this.random() < sampleRate;
939
+ if (!accepted) this.skipped.set(trigger.id, "sampled_out");
940
+ return accepted;
941
+ }
942
+ };
943
+ function restart(state) {
944
+ state.step = 0;
945
+ state.hits = [];
946
+ }
947
+
948
+ // src/buffer/ring-buffer.ts
949
+ var RingBuffer = class {
950
+ entries = [];
951
+ totalBytes = 0;
952
+ maxBytes;
953
+ maxAgeMs;
954
+ now;
955
+ evicted = 0;
956
+ constructor(options) {
957
+ this.maxBytes = options.maxBytes;
958
+ this.maxAgeMs = options.maxAgeMs;
959
+ this.now = options.now ?? Date.now;
960
+ }
961
+ configure(options) {
962
+ this.maxBytes = options.maxBytes;
963
+ this.maxAgeMs = options.maxAgeMs;
964
+ this.trim();
965
+ }
966
+ push(entry) {
967
+ this.entries.push(entry);
968
+ this.totalBytes += entry.bytes;
969
+ this.trim();
970
+ }
971
+ /** Removes and returns the entries recorded at or after `sinceMs` for the selected signals, oldest first. */
972
+ take(sinceMs, signals, untilMs = Infinity) {
973
+ this.trim();
974
+ const taken = [];
975
+ const kept = [];
976
+ for (const entry of this.entries) {
977
+ if (entry.timeMs >= sinceMs && entry.timeMs <= untilMs && (signals === "*" || signals.has(entry.signal))) {
978
+ taken.push(entry);
979
+ this.totalBytes -= entry.bytes;
980
+ } else {
981
+ kept.push(entry);
982
+ }
983
+ }
984
+ this.entries = kept;
985
+ return taken;
986
+ }
987
+ /** The entries currently held, oldest first, without removing them. */
988
+ snapshot() {
989
+ this.trim();
990
+ return this.entries.slice();
991
+ }
992
+ restore(entries) {
993
+ this.entries.push(...entries);
994
+ this.totalBytes += entries.reduce((sum, entry) => sum + entry.bytes, 0);
995
+ this.entries.sort((a, b) => a.timeMs - b.timeMs);
996
+ this.trim();
997
+ }
998
+ retain(keep) {
999
+ this.entries = this.entries.filter(keep);
1000
+ this.totalBytes = this.entries.reduce((sum, entry) => sum + entry.bytes, 0);
1001
+ this.trim();
1002
+ }
1003
+ clear() {
1004
+ this.entries = [];
1005
+ this.totalBytes = 0;
1006
+ }
1007
+ get size() {
1008
+ return this.entries.length;
1009
+ }
1010
+ get bytes() {
1011
+ return this.totalBytes;
1012
+ }
1013
+ /** Entries dropped to stay within budget since the buffer was created. */
1014
+ get evictedCount() {
1015
+ return this.evicted;
1016
+ }
1017
+ trim() {
1018
+ const cutoff = this.now() - this.maxAgeMs;
1019
+ let drop = 0;
1020
+ let bytes = this.totalBytes;
1021
+ while (drop < this.entries.length && (bytes > this.maxBytes || this.entries[drop].timeMs < cutoff)) {
1022
+ bytes -= this.entries[drop].bytes;
1023
+ drop++;
1024
+ }
1025
+ if (drop > 0) {
1026
+ this.entries = this.entries.slice(drop);
1027
+ this.totalBytes = bytes;
1028
+ this.evicted += drop;
1029
+ }
1030
+ }
1031
+ };
107
1032
  // Annotate the CommonJS export names for ESM import in node:
108
1033
  0 && (module.exports = {
1034
+ ControlState,
1035
+ DEFAULT_EXCEPTION_TRIGGER_ID,
109
1036
  EventBuffer,
110
1037
  METRIC_CPU_USED_PCNT,
111
1038
  METRIC_MEM_TOTAL,
112
1039
  METRIC_MEM_USED,
1040
+ MODES,
1041
+ RingBuffer,
1042
+ SEVERITIES,
1043
+ SIGNALS,
1044
+ SettingsError,
1045
+ TriggerEngine,
1046
+ applyLimits,
1047
+ applyOverlay,
1048
+ bytesToUuid,
1049
+ ceilingsFrom,
1050
+ clampToCeilings,
1051
+ compareVersions,
1052
+ defaultExceptionTrigger,
1053
+ defaultSettings,
113
1054
  generateUUID,
1055
+ lowerMode,
1056
+ matches,
1057
+ modeRank,
114
1058
  msToNanoseconds,
115
1059
  nowISO,
116
- parseConnectionString
1060
+ parseConnectionString,
1061
+ parseMatcher,
1062
+ parseSettingsDocument,
1063
+ resolveEndpoints,
1064
+ satisfiesVersion,
1065
+ unitHash,
1066
+ uuidToBytes,
1067
+ uuidv7
117
1068
  });
118
1069
  //# sourceMappingURL=index.js.map