proxy-analytics 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1728 @@
1
+ // src/constants.ts
2
+ var LIBRARY_NAME = "proxy-analytics";
3
+ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for(`${LIBRARY_NAME}/instance`);
4
+ var PAYLOAD_VERSION = 1;
5
+ var DEFAULT_FLUSH_INTERVAL = 1e4;
6
+ var DEFAULT_PARSE_TTL = 1e4;
7
+ var DEFAULT_MAX_DEPTH = 32;
8
+ var DEFAULT_MAX_KEYS_PER_OBJECT = 256;
9
+ var DEFAULT_INVENTORY_MAX_ARRAY_ITEMS = 100;
10
+ var KEEPALIVE_LIMIT = 6e4;
11
+
12
+ // src/engine.ts
13
+ var JSON_TYPE = /[/+]json\b/i;
14
+ function createEngine(config) {
15
+ const { plugins, report, tracker, inventory } = config;
16
+ const nativeParse = JSON.parse;
17
+ const stats = /* @__PURE__ */ new Map();
18
+ const timers = /* @__PURE__ */ new Set();
19
+ const expectations = () => {
20
+ const map = /* @__PURE__ */ new Map();
21
+ return {
22
+ map,
23
+ add(key, event) {
24
+ let list = map.get(key);
25
+ if (list === void 0) {
26
+ list = [];
27
+ map.set(key, list);
28
+ }
29
+ list.push(event);
30
+ const timer = setTimeout(() => {
31
+ timers.delete(timer);
32
+ const current = map.get(key);
33
+ if (current === void 0) return;
34
+ const i = current.indexOf(event);
35
+ if (i !== -1) current.splice(i, 1);
36
+ if (current.length === 0) map.delete(key);
37
+ }, config.parseTtl);
38
+ timer.unref?.();
39
+ timers.add(timer);
40
+ },
41
+ take(key) {
42
+ const list = map.get(key);
43
+ if (list === void 0) return void 0;
44
+ const event = list.shift();
45
+ if (list.length === 0) map.delete(key);
46
+ return event;
47
+ }
48
+ };
49
+ };
50
+ const expected = expectations();
51
+ const responses = expectations();
52
+ const statsFor = (key) => {
53
+ let s = stats.get(key);
54
+ if (s === void 0) {
55
+ s = { key, responses: 0, counts: /* @__PURE__ */ new Map() };
56
+ stats.set(key, s);
57
+ }
58
+ return s;
59
+ };
60
+ const track = (data, event, text) => {
61
+ try {
62
+ const value = plugins.transformData(data, event);
63
+ if (typeof value !== "object" || value === null) return value;
64
+ const s = statsFor(event.endpoint);
65
+ const wrapped = tracker.wrap(value, s);
66
+ if (wrapped === value) return value;
67
+ s.responses++;
68
+ if (config.inventorySampleRate >= 1 || Math.random() < config.inventorySampleRate) {
69
+ inventory.offer(event.endpoint, text, value);
70
+ }
71
+ plugins.onTrack(event);
72
+ return wrapped;
73
+ } catch (error) {
74
+ report(error, "track");
75
+ return data;
76
+ }
77
+ };
78
+ return {
79
+ fence: config.fence,
80
+ plugins,
81
+ report,
82
+ table: tracker.table,
83
+ nativeParse,
84
+ stats,
85
+ event(transport, route, status, header) {
86
+ return {
87
+ transport,
88
+ url: route.url,
89
+ method: route.method,
90
+ endpoint: route.endpoint,
91
+ status,
92
+ header
93
+ };
94
+ },
95
+ accepts(event) {
96
+ if (config.responseSampleRate < 1 && !(Math.random() < config.responseSampleRate)) return false;
97
+ if (!config.trackErrors && (event.status < 200 || event.status >= 300)) return false;
98
+ const type = event.header("content-type");
99
+ if (type === null || !JSON_TYPE.test(type)) return false;
100
+ return plugins.onResponse(event);
101
+ },
102
+ transformBody(text, event) {
103
+ return plugins.transformBody(text, event);
104
+ },
105
+ parseAndTrack(text, event) {
106
+ const data = nativeParse(text);
107
+ return track(data, event, text);
108
+ },
109
+ track,
110
+ expectParse(text, event) {
111
+ if (!config.expectParses || text.length === 0) return;
112
+ expected.add(text, event);
113
+ },
114
+ takeExpected(text) {
115
+ return expected.take(text);
116
+ },
117
+ hasExpected() {
118
+ return expected.map.size > 0;
119
+ },
120
+ expectResponse(url, event) {
121
+ if (url !== "") responses.add(url, event);
122
+ },
123
+ takeResponse(url) {
124
+ return responses.take(url);
125
+ },
126
+ dispose() {
127
+ for (const t of timers) clearTimeout(t);
128
+ timers.clear();
129
+ expected.map.clear();
130
+ responses.map.clear();
131
+ inventory.dispose();
132
+ }
133
+ };
134
+ }
135
+
136
+ // src/redact.ts
137
+ var redactKeys = (text) => text.replace(/\b(pa_(?:pub|sec)_[0-9A-Za-z]{4})[0-9A-Za-z]+/g, "$1\u2026").replace(/([?&](?:key|api_key|apikey|token)=)(?!pa_)([^&#\s"]{4})[^&#\s"]+/gi, "$1$2\u2026");
138
+ var isBareKey = (text) => /^\s*pa_(?:pub|sec)_[0-9A-Za-z]+\s*$/.test(text);
139
+
140
+ // src/fence.ts
141
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
142
+ var pageBase = () => {
143
+ const loc = globalThis.location;
144
+ return typeof loc?.href === "string" ? loc.href : void 0;
145
+ };
146
+ function compile(matcher, base) {
147
+ if (typeof matcher === "function") return matcher;
148
+ if (matcher instanceof RegExp) return (url) => matcher.test(url.href);
149
+ if (matcher === "same-origin") {
150
+ if (base === void 0) {
151
+ throw new Error(
152
+ "[proxy-analytics] apis: 'same-origin' needs a page origin; pass `baseUrl` outside browsers."
153
+ );
154
+ }
155
+ const origin2 = new URL(base).origin;
156
+ return (url) => url.origin === origin2;
157
+ }
158
+ const methodMatch = /^([A-Z]+)\s+(.+)$/.exec(matcher);
159
+ const onlyMethod = methodMatch?.[1];
160
+ const spec = methodMatch?.[2] ?? matcher;
161
+ let root;
162
+ try {
163
+ root = new URL(spec.replaceAll("*", "__pa_star__"), base);
164
+ } catch {
165
+ throw new Error(
166
+ `[proxy-analytics] could not resolve URL pattern ${redactKeys(JSON.stringify(matcher))}; use an absolute URL or pass \`baseUrl\`.`
167
+ );
168
+ }
169
+ const origin = root.origin;
170
+ const rawPath = decodeURIComponent(root.pathname).replaceAll("__pa_star__", "*");
171
+ const prefix = rawPath.endsWith("/") ? rawPath.slice(0, -1) : rawPath;
172
+ const methodOk = (method) => onlyMethod === void 0 || method === onlyMethod;
173
+ if (prefix.includes("*")) {
174
+ const source = prefix.split("/").map((seg) => seg === "*" ? "[^/]+" : seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("/");
175
+ const re = new RegExp(`^${source}(?:/|$)`);
176
+ return (url, method) => methodOk(method) && url.origin === origin && re.test(url.pathname);
177
+ }
178
+ if (prefix === "") return (url, method) => methodOk(method) && url.origin === origin;
179
+ return (url, method) => {
180
+ if (!methodOk(method) || url.origin !== origin) return false;
181
+ const path = url.pathname;
182
+ if (!path.startsWith(prefix)) return false;
183
+ return path.length === prefix.length || path.charCodeAt(prefix.length) === 47;
184
+ };
185
+ }
186
+ var ID_SEGMENT = /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,})$/i;
187
+ function defaultEndpointKey(method, url, pageOrigin) {
188
+ const segments = url.pathname.split("/");
189
+ for (let i = 0; i < segments.length; i++) {
190
+ if (ID_SEGMENT.test(segments[i])) segments[i] = ":id";
191
+ }
192
+ const path = segments.join("/");
193
+ return `${method} ${url.origin === pageOrigin ? "" : url.origin}${path}`;
194
+ }
195
+ function createFence(options) {
196
+ const apis = toArray(options.apis);
197
+ if (apis.length === 0) {
198
+ throw new Error(
199
+ "[proxy-analytics] `apis` is required: pass the API root(s) to track, e.g. apis: '/api' or apis: 'https://api.example.com'."
200
+ );
201
+ }
202
+ const base = options.baseUrl ?? pageBase();
203
+ const pageOrigin = base !== void 0 ? new URL(base).origin : void 0;
204
+ const include = apis.map((m) => compile(m, base));
205
+ const ignore = [
206
+ ...toArray(options.ignore).map((m) => compile(m, base)),
207
+ ...(options.alwaysExclude ?? []).map((m) => compile(m, base))
208
+ ];
209
+ const keyOf = options.endpointKey ?? ((info) => defaultEndpointKey(info.method, info.url, pageOrigin));
210
+ return (rawUrl, method) => {
211
+ let url;
212
+ try {
213
+ url = new URL(rawUrl, base);
214
+ } catch {
215
+ return void 0;
216
+ }
217
+ let hit = false;
218
+ for (let i = 0; i < include.length; i++) {
219
+ if (include[i](url, method)) {
220
+ hit = true;
221
+ break;
222
+ }
223
+ }
224
+ if (!hit) return void 0;
225
+ for (let i = 0; i < ignore.length; i++) {
226
+ if (ignore[i](url, method)) return void 0;
227
+ }
228
+ return { url, method, endpoint: keyOf({ method, url }) };
229
+ };
230
+ }
231
+
232
+ // src/tracker/paths.ts
233
+ var STAR = "[*]";
234
+ var DYNAMIC = "{*}";
235
+ var DEFAULT_DYNAMIC_KEYS = [
236
+ /^\d+$/,
237
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
238
+ /^[0-9a-f]{16,}$/i
239
+ ];
240
+ var SIMPLE_KEY = /^[A-Za-z_$][\w$-]*$/;
241
+ function joinKey(parent, key) {
242
+ if (SIMPLE_KEY.test(key)) return parent === "" ? key : `${parent}.${key}`;
243
+ return `${parent}[${JSON.stringify(key)}]`;
244
+ }
245
+ function joinStar(parent) {
246
+ return parent + STAR;
247
+ }
248
+ function joinDynamic(parent) {
249
+ return parent === "" ? DYNAMIC : `${parent}.${DYNAMIC}`;
250
+ }
251
+ function isDynamicKey(key, patterns) {
252
+ for (let i = 0; i < patterns.length; i++) {
253
+ if (patterns[i].test(key)) return true;
254
+ }
255
+ return false;
256
+ }
257
+ function isIndexKey(key) {
258
+ const len = key.length;
259
+ if (len === 0 || len > 10) return false;
260
+ const first = key.charCodeAt(0);
261
+ if (first === 48) return len === 1;
262
+ if (first < 49 || first > 57) return false;
263
+ for (let i = 1; i < len; i++) {
264
+ const c = key.charCodeAt(i);
265
+ if (c < 48 || c > 57) return false;
266
+ }
267
+ return true;
268
+ }
269
+ function serializePathConfig(config) {
270
+ return {
271
+ dynamicKeys: config.dynamicKeys.map((r) => ({ source: r.source, flags: r.flags })),
272
+ maxKeysPerObject: config.maxKeysPerObject,
273
+ maxDepth: config.maxDepth
274
+ };
275
+ }
276
+ function createPathTable(config) {
277
+ const byId = [];
278
+ const make = (path, depth) => {
279
+ const node = {
280
+ id: byId.length,
281
+ path,
282
+ depth,
283
+ children: void 0,
284
+ named: 0,
285
+ star: void 0,
286
+ dynamic: void 0,
287
+ lastCtx: void 0,
288
+ lastBits: 0
289
+ };
290
+ byId.push(node);
291
+ return node;
292
+ };
293
+ const root = make("", 0);
294
+ const dynamicChild = (parent) => {
295
+ if (parent.dynamic === void 0)
296
+ parent.dynamic = make(joinDynamic(parent.path), parent.depth + 1);
297
+ return parent.dynamic;
298
+ };
299
+ return {
300
+ root,
301
+ byId,
302
+ child(parent, key) {
303
+ const hit = parent.children?.get(key);
304
+ if (hit !== void 0) return hit;
305
+ if (parent.depth >= config.maxDepth) return void 0;
306
+ if (parent.children === void 0) parent.children = /* @__PURE__ */ new Map();
307
+ const children = parent.children;
308
+ if (isDynamicKey(key, config.dynamicKeys) || parent.named >= config.maxKeysPerObject) {
309
+ const node2 = dynamicChild(parent);
310
+ if (children.size < config.maxKeysPerObject * 4) children.set(key, node2);
311
+ return node2;
312
+ }
313
+ const node = make(joinKey(parent.path, key), parent.depth + 1);
314
+ parent.named++;
315
+ children.set(key, node);
316
+ return node;
317
+ },
318
+ star(parent) {
319
+ if (parent.star !== void 0) return parent.star;
320
+ if (parent.depth >= config.maxDepth) return void 0;
321
+ parent.star = make(joinStar(parent.path), parent.depth + 1);
322
+ return parent.star;
323
+ }
324
+ };
325
+ }
326
+ function collectPaths(data, config, maxArrayItems, out = /* @__PURE__ */ new Set(), raw = (value) => value) {
327
+ const named = /* @__PURE__ */ new Map();
328
+ const walk = (input, path, depth) => {
329
+ if (input === null || typeof input !== "object" || depth >= config.maxDepth) return;
330
+ const value = raw(input);
331
+ if (Array.isArray(value)) {
332
+ if (value.length === 0) return;
333
+ const childPath = joinStar(path);
334
+ out.add(childPath);
335
+ const n = Math.min(value.length, maxArrayItems);
336
+ for (let i = 0; i < n; i++) walk(value[i], childPath, depth + 1);
337
+ return;
338
+ }
339
+ const record2 = value;
340
+ for (const key in record2) {
341
+ if (!Object.hasOwn(record2, key)) continue;
342
+ let childPath;
343
+ if (isDynamicKey(key, config.dynamicKeys)) {
344
+ childPath = joinDynamic(path);
345
+ } else {
346
+ let keys = named.get(path);
347
+ if (keys === void 0) {
348
+ keys = /* @__PURE__ */ new Set();
349
+ named.set(path, keys);
350
+ }
351
+ if (keys.has(key) || keys.size < config.maxKeysPerObject) {
352
+ keys.add(key);
353
+ childPath = joinKey(path, key);
354
+ } else {
355
+ childPath = joinDynamic(path);
356
+ }
357
+ }
358
+ out.add(childPath);
359
+ walk(record2[key], childPath, depth + 1);
360
+ }
361
+ };
362
+ walk(data, "", 0);
363
+ return out;
364
+ }
365
+
366
+ // src/tracker/proxy.ts
367
+ var STATE = /* @__PURE__ */ Symbol("proxy-analytics/state");
368
+ var stateOf = (value) => value[STATE];
369
+ var safeStateOf = (value) => {
370
+ try {
371
+ return stateOf(value);
372
+ } catch {
373
+ return void 0;
374
+ }
375
+ };
376
+ var ROOTS = /* @__PURE__ */ new WeakMap();
377
+ var proxiesCreated = 0;
378
+ var DIRECT = 1;
379
+ var BULK = 2;
380
+ var hasOwn = Object.prototype.hasOwnProperty;
381
+ var objectProto = Object.prototype;
382
+ var isTrackable = (value) => {
383
+ if (Array.isArray(value)) return true;
384
+ const proto = Object.getPrototypeOf(value);
385
+ return proto === objectProto || proto === null;
386
+ };
387
+ var record = (ctx, node, bit) => {
388
+ let prev;
389
+ if (node.lastCtx === ctx) {
390
+ prev = node.lastBits;
391
+ if ((prev & bit) !== 0) return;
392
+ } else {
393
+ prev = ctx.bits.get(node.id) ?? 0;
394
+ node.lastCtx = ctx;
395
+ node.lastBits = prev;
396
+ if ((prev & bit) !== 0) return;
397
+ }
398
+ const next = prev | bit;
399
+ node.lastBits = next;
400
+ ctx.bits.set(node.id, next);
401
+ const counts = ctx.stats.counts;
402
+ let counter = counts.get(node.id);
403
+ if (counter === void 0) {
404
+ counter = { any: 0, direct: 0, bulk: 0 };
405
+ counts.set(node.id, counter);
406
+ }
407
+ if (prev === 0) counter.any++;
408
+ if (bit === DIRECT) counter.direct++;
409
+ else counter.bulk++;
410
+ if (ctx.onFirst !== void 0) ctx.onFirst(ctx.stats, node, bit === DIRECT ? "direct" : "bulk");
411
+ };
412
+ var epoch = 1;
413
+ var advanceScheduled = false;
414
+ var walked = [];
415
+ var countDistinct = (keys) => {
416
+ if (keys.length > 32) return new Set(keys).size;
417
+ let distinct = 0;
418
+ outer: for (let i = 0; i < keys.length; i++) {
419
+ for (let j = 0; j < i; j++) if (keys[j] === keys[i]) continue outer;
420
+ distinct++;
421
+ }
422
+ return distinct;
423
+ };
424
+ var skippedWereRead = (h, held, missing) => {
425
+ const children = h.node.children;
426
+ if (children === void 0) return false;
427
+ const heldSet = held.length > 32 ? new Set(held) : void 0;
428
+ const bits = h.ctx.bits;
429
+ const keys = Object.keys(h.target);
430
+ let found = 0;
431
+ for (let i = 0; i < keys.length; i++) {
432
+ const key = keys[i];
433
+ if (heldSet !== void 0 ? heldSet.has(key) : held.includes(key)) continue;
434
+ const node = children.get(key);
435
+ if (node === void 0 || ((bits.get(node.id) ?? 0) & DIRECT) === 0) return false;
436
+ if (++found >= missing) return true;
437
+ }
438
+ return false;
439
+ };
440
+ var classify = (h) => {
441
+ const nodes = h.heldNodes;
442
+ const keys = h.heldKeys;
443
+ h.heldNodes = void 0;
444
+ h.heldKeys = void 0;
445
+ h.queued = false;
446
+ const ctx = h.ctx;
447
+ let expected = h.walkExpected;
448
+ if (expected < 0) {
449
+ const t = h.target;
450
+ expected = Array.isArray(t) ? t.length : Object.keys(t).length;
451
+ }
452
+ const distinct = h.isArray ? Math.min(nodes.length, expected) : countDistinct(keys);
453
+ const repeats = nodes.length - distinct;
454
+ const full = distinct >= expected || !h.isArray && distinct > 0 && skippedWereRead(h, keys, expected - distinct);
455
+ const bit = full ? BULK : DIRECT;
456
+ for (let i = 0; i < nodes.length; i++) record(ctx, nodes[i], bit);
457
+ if (!full || repeats === 0 || repeats * 2 >= distinct) return;
458
+ if (h.isArray) {
459
+ record(ctx, nodes[0], DIRECT);
460
+ return;
461
+ }
462
+ for (let i = 0; i < keys.length; i++) {
463
+ for (let j = 0; j < i; j++) {
464
+ if (keys[j] === keys[i]) {
465
+ record(ctx, nodes[i], DIRECT);
466
+ break;
467
+ }
468
+ }
469
+ }
470
+ };
471
+ var closeWindow = () => {
472
+ epoch++;
473
+ advanceScheduled = false;
474
+ for (let i = 0; i < walked.length; i++) classify(walked[i]);
475
+ walked.length = 0;
476
+ };
477
+ var openWindow = (h, expected) => {
478
+ if (h.bulkMark === epoch) {
479
+ if (expected > h.walkExpected) h.walkExpected = expected;
480
+ else if (expected < 0 && h.walkExpected >= 0) return;
481
+ } else {
482
+ h.bulkMark = epoch;
483
+ h.walkExpected = expected;
484
+ }
485
+ if (!advanceScheduled) {
486
+ advanceScheduled = true;
487
+ queueMicrotask(closeWindow);
488
+ }
489
+ };
490
+ var hold = (h, node, key) => {
491
+ if (h.heldNodes === void 0) {
492
+ h.heldNodes = [node];
493
+ h.heldKeys = [key];
494
+ } else {
495
+ h.heldNodes.push(node);
496
+ h.heldKeys.push(key);
497
+ }
498
+ if (!h.queued) {
499
+ h.queued = true;
500
+ walked.push(h);
501
+ }
502
+ };
503
+ var read = (h, node, key, child) => {
504
+ if (h.bulkMark !== epoch) {
505
+ record(h.ctx, node, DIRECT);
506
+ return;
507
+ }
508
+ hold(h, node, key);
509
+ if (child !== void 0) {
510
+ const meta = stateOf(child);
511
+ if (meta !== void 0 && meta.bulkMark !== epoch) openWindow(meta, -1);
512
+ }
513
+ };
514
+ var wrapValue = (ctx, node, value) => {
515
+ if (typeof value !== "object" || value === null) return void 0;
516
+ if (stateOf(value) !== void 0) return value;
517
+ return isTrackable(value) ? create(value, ctx, node) : void 0;
518
+ };
519
+ var nodeFor = (h, target, key, value) => {
520
+ if (h.isArray) {
521
+ if (value === void 0 || !isIndexKey(key)) return void 0;
522
+ return h.node.star ?? h.ctx.table.star(h.node);
523
+ }
524
+ const known = h.node.children?.get(key);
525
+ if (known !== void 0 && value !== void 0) return known;
526
+ if (!hasOwn.call(target, key)) return void 0;
527
+ return h.ctx.table.child(h.node, key);
528
+ };
529
+ var childFor = (h, key, node, value) => {
530
+ let kids = h.kids;
531
+ if (h.isArray) {
532
+ const i = key * 2;
533
+ if (kids !== void 0) {
534
+ const raw = kids[i];
535
+ if (raw === value || kids[i + 1] === value) return kids[i + 1];
536
+ } else {
537
+ kids = h.kids = [];
538
+ }
539
+ const proxy2 = wrapValue(h.ctx, node, value);
540
+ kids[i] = value;
541
+ kids[i + 1] = proxy2;
542
+ return proxy2;
543
+ }
544
+ if (kids !== void 0) {
545
+ for (let i = 0; i < kids.length; i += 3) {
546
+ if (kids[i] !== key) continue;
547
+ if (kids[i + 1] === value || kids[i + 2] === value) return kids[i + 2];
548
+ const proxy2 = wrapValue(h.ctx, node, value);
549
+ kids[i + 1] = value;
550
+ kids[i + 2] = proxy2;
551
+ return proxy2;
552
+ }
553
+ } else {
554
+ kids = h.kids = [];
555
+ }
556
+ const proxy = wrapValue(h.ctx, node, value);
557
+ kids.push(key, value, proxy);
558
+ return proxy;
559
+ };
560
+ var materialize = (h) => {
561
+ if (h.materialized) return;
562
+ h.materialized = true;
563
+ const target = h.target;
564
+ const keys = Object.keys(target);
565
+ for (let i = 0; i < keys.length; i++) {
566
+ const key = keys[i];
567
+ const value = target[key];
568
+ if (typeof value !== "object" || value === null) continue;
569
+ const node = nodeFor(h, target, key, value);
570
+ if (node === void 0) continue;
571
+ const proxy = childFor(h, key, node, value);
572
+ if (proxy !== void 0 && proxy !== value) target[key] = proxy;
573
+ }
574
+ };
575
+ var walkBulk = (ctx, node, input) => {
576
+ let target = input;
577
+ const meta = stateOf(input);
578
+ if (meta !== void 0) {
579
+ if (meta.serializedMark === epoch) return;
580
+ meta.serializedMark = epoch;
581
+ target = meta.target;
582
+ ctx = meta.ctx;
583
+ node = meta.node;
584
+ }
585
+ const table = ctx.table;
586
+ if (Array.isArray(target)) {
587
+ if (target.length === 0) return;
588
+ const star = table.star(node);
589
+ if (star === void 0) return;
590
+ record(ctx, star, BULK);
591
+ for (let i = 0; i < target.length; i++) {
592
+ const v = target[i];
593
+ if (typeof v === "object" && v !== null) walkBulk(ctx, star, v);
594
+ }
595
+ return;
596
+ }
597
+ if (!isTrackable(target)) return;
598
+ const record_ = target;
599
+ for (const key in record_) {
600
+ if (!hasOwn.call(record_, key)) continue;
601
+ const child = table.child(node, key);
602
+ if (child === void 0) continue;
603
+ record(ctx, child, BULK);
604
+ const v = record_[key];
605
+ if (typeof v === "object" && v !== null) walkBulk(ctx, child, v);
606
+ }
607
+ };
608
+ var scheduleEpoch = () => {
609
+ if (!advanceScheduled) {
610
+ advanceScheduled = true;
611
+ queueMicrotask(closeWindow);
612
+ }
613
+ };
614
+ function toJSON() {
615
+ const h = typeof this === "object" && this !== null ? stateOf(this) : void 0;
616
+ if (h === void 0) return this;
617
+ if (h.serializedMark !== epoch) {
618
+ walkBulk(h.ctx, h.node, this);
619
+ scheduleEpoch();
620
+ }
621
+ return h.target;
622
+ }
623
+ var handlerProto = {
624
+ get(target, key) {
625
+ if (typeof key !== "string") {
626
+ if (key === STATE) return this;
627
+ return target[key];
628
+ }
629
+ const h = this;
630
+ const value = target[key];
631
+ const node = nodeFor(h, target, key, value);
632
+ if (node === void 0) {
633
+ if (key === "toJSON" && value === void 0) return toJSON;
634
+ return value;
635
+ }
636
+ if (typeof value !== "object" || value === null || h.materialized) {
637
+ read(h, node, key, void 0);
638
+ return value;
639
+ }
640
+ const child = childFor(h, key, node, value);
641
+ read(h, node, key, child);
642
+ return child ?? value;
643
+ },
644
+ has(target, key) {
645
+ const present = key in target;
646
+ if (!present || typeof key !== "string") return present;
647
+ const h = this;
648
+ const node = nodeFor(h, target, key, target[key]);
649
+ if (node !== void 0) read(h, node, key, void 0);
650
+ return present;
651
+ },
652
+ ownKeys(target) {
653
+ const h = this;
654
+ const keys = Reflect.ownKeys(target);
655
+ openWindow(h, h.isArray ? keys.length - 1 : keys.length);
656
+ return keys;
657
+ },
658
+ // No getOwnPropertyDescriptor trap on purpose: spread and Object.assign call
659
+ // it once per key, and even a trap that returns immediately roughly doubles
660
+ // their cost (measured with bench/run.ts). Values are still wrapped because
661
+ // copies read them through `get`. Known blind spot: descriptor copies
662
+ // (Object.getOwnPropertyDescriptors + defineProperties) see raw values, so
663
+ // reads on such a copy are not recorded. A trap can't fix that cheaply
664
+ // anyway: Object.keys takes every descriptor too, so a descriptor copy and a
665
+ // bare key listing look identical from here.
666
+ set(target, key, value) {
667
+ return Reflect.set(target, key, value);
668
+ },
669
+ defineProperty(target, key, desc) {
670
+ if (desc.configurable === false || desc.writable === false) materialize(this);
671
+ return Reflect.defineProperty(target, key, desc);
672
+ },
673
+ preventExtensions(target) {
674
+ materialize(this);
675
+ return Reflect.preventExtensions(target);
676
+ }
677
+ };
678
+ function Handler(target, ctx, node) {
679
+ this.target = target;
680
+ this.ctx = ctx;
681
+ this.node = node;
682
+ this.isArray = Array.isArray(target);
683
+ this.kids = void 0;
684
+ this.bulkMark = 0;
685
+ this.walkExpected = 0;
686
+ this.heldNodes = void 0;
687
+ this.heldKeys = void 0;
688
+ this.queued = false;
689
+ this.serializedMark = 0;
690
+ this.materialized = false;
691
+ }
692
+ Handler.prototype = handlerProto;
693
+ var create = (target, ctx, node) => {
694
+ proxiesCreated++;
695
+ return new Proxy(target, new Handler(target, ctx, node));
696
+ };
697
+ function createTracker(table, onFirst) {
698
+ return {
699
+ table,
700
+ wrap(data, stats) {
701
+ if (typeof data !== "object" || data === null) return data;
702
+ if (stateOf(data) !== void 0) return data;
703
+ const existing = ROOTS.get(data);
704
+ if (existing !== void 0) return existing;
705
+ if (!isTrackable(data)) return data;
706
+ const ctx = { stats, table, onFirst, bits: /* @__PURE__ */ new Map() };
707
+ const proxy = create(data, ctx, table.root);
708
+ ROOTS.set(data, proxy);
709
+ return proxy;
710
+ }
711
+ };
712
+ }
713
+ function isTracked(value) {
714
+ return typeof value === "object" && value !== null && safeStateOf(value) !== void 0;
715
+ }
716
+ function rawOf(value) {
717
+ const meta = safeStateOf(value);
718
+ return meta !== void 0 ? meta.target : value;
719
+ }
720
+ function unwrap(value) {
721
+ if (proxiesCreated === 0 || typeof value !== "object" || value === null) return value;
722
+ return unwrapDeep(value, /* @__PURE__ */ new Map(), false);
723
+ }
724
+ function unwrapForCopy(value) {
725
+ if (proxiesCreated === 0 || typeof value !== "object" || value === null) return value;
726
+ return unwrapDeep(value, /* @__PURE__ */ new Map(), true);
727
+ }
728
+ var unwrapDeep = (value, seen, copying) => {
729
+ if (typeof value !== "object" || value === null) return value;
730
+ const meta = safeStateOf(value);
731
+ const base = meta !== void 0 ? meta.target : value;
732
+ if (copying && meta !== void 0 && meta.serializedMark !== epoch) {
733
+ walkBulk(meta.ctx, meta.node, value);
734
+ scheduleEpoch();
735
+ }
736
+ if (meta === void 0) {
737
+ try {
738
+ if (!isTrackable(base)) return value;
739
+ } catch {
740
+ return value;
741
+ }
742
+ }
743
+ const done = seen.get(value);
744
+ if (done !== void 0) return done;
745
+ seen.set(value, base);
746
+ if (Array.isArray(base)) {
747
+ let copy2;
748
+ for (let i = 0; i < base.length; i++) {
749
+ const item = base[i];
750
+ const next = unwrapDeep(item, seen, copying);
751
+ if (next !== item) {
752
+ copy2 ?? (copy2 = base.slice());
753
+ copy2[i] = next;
754
+ }
755
+ }
756
+ const result2 = copy2 ?? base;
757
+ seen.set(value, result2);
758
+ return result2;
759
+ }
760
+ const obj = base;
761
+ let copy;
762
+ for (const key in obj) {
763
+ if (!hasOwn.call(obj, key)) continue;
764
+ const item = obj[key];
765
+ const next = unwrapDeep(item, seen, copying);
766
+ if (next !== item) {
767
+ copy ?? (copy = { ...obj });
768
+ copy[key] = next;
769
+ }
770
+ }
771
+ const result = copy ?? base;
772
+ seen.set(value, result);
773
+ return result;
774
+ };
775
+
776
+ // src/intercept/clone-safety.ts
777
+ var TARGETS = [
778
+ { owner: "globalThis", method: "structuredClone", arg: 0 },
779
+ { owner: "Window", method: "postMessage", arg: 0 },
780
+ // Some engines define postMessage on the window object itself.
781
+ { owner: "globalThis", method: "postMessage", arg: 0, ownOnly: true },
782
+ { owner: "Worker", method: "postMessage", arg: 0 },
783
+ { owner: "MessagePort", method: "postMessage", arg: 0 },
784
+ { owner: "BroadcastChannel", method: "postMessage", arg: 0 },
785
+ { owner: "ServiceWorker", method: "postMessage", arg: 0 },
786
+ { owner: "IDBObjectStore", method: "put", arg: 0 },
787
+ { owner: "IDBObjectStore", method: "add", arg: 0 },
788
+ { owner: "IDBCursor", method: "update", arg: 0 },
789
+ { owner: "History", method: "pushState", arg: 0 },
790
+ { owner: "History", method: "replaceState", arg: 0 }
791
+ ];
792
+ function patchCloneSafety() {
793
+ const g = globalThis;
794
+ const restores = [];
795
+ for (const t of TARGETS) {
796
+ const holder = t.owner === "globalThis" ? g : g[t.owner]?.prototype;
797
+ if (holder === void 0 || holder === null) continue;
798
+ if (t.ownOnly === true && !Object.hasOwn(holder, t.method)) continue;
799
+ const original = holder[t.method];
800
+ if (typeof original !== "function") continue;
801
+ const fn = original;
802
+ const patched = function(...args) {
803
+ if (args.length > t.arg) args[t.arg] = unwrapForCopy(args[t.arg]);
804
+ return Reflect.apply(fn, this, args);
805
+ };
806
+ Object.defineProperty(patched, "name", { value: t.method });
807
+ holder[t.method] = patched;
808
+ restores.push(() => {
809
+ if (holder[t.method] === patched) holder[t.method] = original;
810
+ });
811
+ }
812
+ return () => {
813
+ for (const restore of restores.splice(0)) restore();
814
+ };
815
+ }
816
+
817
+ // src/intercept/fetch.ts
818
+ var noop = () => {
819
+ };
820
+ var requestInfo = (input, init) => {
821
+ let url;
822
+ let method;
823
+ if (typeof input === "string") url = input;
824
+ else if (input instanceof URL) url = input.href;
825
+ else if (typeof Request !== "undefined" && input instanceof Request) {
826
+ url = input.url;
827
+ method = input.method;
828
+ } else return void 0;
829
+ return { url, method: (init?.method ?? method ?? "GET").toUpperCase() };
830
+ };
831
+ function patchFetch(engine) {
832
+ const g = globalThis;
833
+ const original = g.fetch;
834
+ if (typeof original !== "function" || typeof Response === "undefined") {
835
+ return { restore: noop, original };
836
+ }
837
+ const proto = Response.prototype;
838
+ const nativeText = proto.text;
839
+ const nativeJson = proto.json;
840
+ const nativeClone = proto.clone;
841
+ let active = true;
842
+ const declined = /* @__PURE__ */ new WeakSet();
843
+ const instrument = (resp, event) => {
844
+ const read2 = () => nativeText.call(resp).then((text) => engine.transformBody(text, event));
845
+ Object.defineProperties(resp, {
846
+ json: {
847
+ configurable: true,
848
+ writable: true,
849
+ value: function json() {
850
+ return read2().then((text) => engine.parseAndTrack(text, event));
851
+ }
852
+ },
853
+ text: {
854
+ configurable: true,
855
+ writable: true,
856
+ value: function text() {
857
+ return read2().then((body) => {
858
+ engine.expectParse(body, event);
859
+ return body;
860
+ });
861
+ }
862
+ },
863
+ clone: {
864
+ configurable: true,
865
+ writable: true,
866
+ value: function clone() {
867
+ const copy = nativeClone.call(resp);
868
+ instrument(copy, event);
869
+ return copy;
870
+ }
871
+ }
872
+ });
873
+ };
874
+ const handleResponse = (resp, route) => {
875
+ try {
876
+ if (!active || !(resp instanceof Response)) return resp;
877
+ const event = engine.event("fetch", route, resp.status, (name) => resp.headers.get(name));
878
+ if (engine.accepts(event)) {
879
+ instrument(resp, event);
880
+ engine.expectResponse(resp.url, event);
881
+ } else {
882
+ declined.add(resp);
883
+ engine.expectResponse(resp.url, null);
884
+ }
885
+ } catch (error) {
886
+ engine.report(error, "response");
887
+ }
888
+ return resp;
889
+ };
890
+ const wrapped = function fetch(...args) {
891
+ if (!active) return Reflect.apply(original, g, args);
892
+ let route;
893
+ try {
894
+ const info = requestInfo(args[0], args[1]);
895
+ route = info === void 0 ? void 0 : engine.fence(info.url, info.method);
896
+ } catch (error) {
897
+ engine.report(error, "request");
898
+ }
899
+ if (route === void 0) return Reflect.apply(original, g, args);
900
+ let callArgs = args;
901
+ if (engine.plugins.hasRequestHooks) {
902
+ try {
903
+ callArgs = applyRequestHooks(engine, route, args);
904
+ } catch (error) {
905
+ engine.report(error, "request");
906
+ }
907
+ }
908
+ const fenced = route;
909
+ return Reflect.apply(original, g, callArgs).then(
910
+ (resp) => handleResponse(resp, fenced)
911
+ );
912
+ };
913
+ const eventFor = (resp) => {
914
+ if (!active || declined.has(resp)) return void 0;
915
+ try {
916
+ const url = resp.url;
917
+ if (typeof url !== "string" || url === "") return void 0;
918
+ const known = engine.takeResponse(url);
919
+ if (known === null) return void 0;
920
+ if (known !== void 0) return known;
921
+ const route = engine.fence(url, "GET");
922
+ if (route === void 0) return void 0;
923
+ const event = engine.event("fetch", route, resp.status, (name) => resp.headers.get(name));
924
+ return engine.accepts(event) ? event : void 0;
925
+ } catch (error) {
926
+ engine.report(error, "response");
927
+ return void 0;
928
+ }
929
+ };
930
+ const protoJson = function json() {
931
+ const event = eventFor(this);
932
+ if (event === void 0) return nativeJson.call(this);
933
+ return nativeText.call(this).then((text) => engine.parseAndTrack(engine.transformBody(text, event), event));
934
+ };
935
+ const protoText = function text() {
936
+ const event = eventFor(this);
937
+ if (event === void 0) return nativeText.call(this);
938
+ return nativeText.call(this).then((text2) => {
939
+ const body = engine.transformBody(text2, event);
940
+ engine.expectParse(body, event);
941
+ return body;
942
+ });
943
+ };
944
+ g.fetch = wrapped;
945
+ proto.json = protoJson;
946
+ proto.text = protoText;
947
+ return {
948
+ original,
949
+ restore() {
950
+ active = false;
951
+ if (g.fetch === wrapped) g.fetch = original;
952
+ if (proto.json === protoJson) proto.json = nativeJson;
953
+ if (proto.text === protoText) proto.text = nativeText;
954
+ }
955
+ };
956
+ }
957
+ function applyRequestHooks(engine, route, args) {
958
+ let headers;
959
+ const event = {
960
+ transport: "fetch",
961
+ url: route.url,
962
+ method: route.method,
963
+ endpoint: route.endpoint,
964
+ setHeader(name, value) {
965
+ if (headers === void 0) {
966
+ const [input2, init2] = args;
967
+ const base = init2?.headers ?? (typeof Request !== "undefined" && input2 instanceof Request ? input2.headers : void 0);
968
+ headers = new Headers(base);
969
+ }
970
+ headers.set(name, value);
971
+ }
972
+ };
973
+ engine.plugins.onRequest(event);
974
+ if (headers === void 0) return args;
975
+ const [input, init] = args;
976
+ return [input, { ...init, headers }];
977
+ }
978
+
979
+ // src/intercept/json-parse.ts
980
+ function patchJsonParse(engine) {
981
+ const native = engine.nativeParse;
982
+ let active = true;
983
+ const parse = function parse2(text, reviver) {
984
+ const result = reviver === void 0 ? native(text) : native(text, reviver);
985
+ if (!active || typeof text !== "string" || !engine.hasExpected()) return result;
986
+ const event = engine.takeExpected(text);
987
+ if (event === void 0) return result;
988
+ return engine.track(result, event, text);
989
+ };
990
+ JSON.parse = parse;
991
+ return () => {
992
+ active = false;
993
+ if (JSON.parse === parse) JSON.parse = native;
994
+ };
995
+ }
996
+
997
+ // src/intercept/xhr.ts
998
+ var noop2 = () => {
999
+ };
1000
+ function patchXhr(engine) {
1001
+ const XHR = globalThis.XMLHttpRequest;
1002
+ if (typeof XHR !== "function") return noop2;
1003
+ const proto = XHR.prototype;
1004
+ const textDesc = Object.getOwnPropertyDescriptor(proto, "responseText");
1005
+ const responseDesc = Object.getOwnPropertyDescriptor(proto, "response");
1006
+ if (textDesc?.get === void 0 || responseDesc?.get === void 0) return noop2;
1007
+ const getText = textDesc.get;
1008
+ const getResponse = responseDesc.get;
1009
+ const originalOpen = proto.open;
1010
+ const originalSend = proto.send;
1011
+ const states = /* @__PURE__ */ new WeakMap();
1012
+ let active = true;
1013
+ const decide = (xhr, s) => {
1014
+ if (s.accepted !== void 0) return s.accepted;
1015
+ try {
1016
+ const event = engine.event("xhr", s.route, xhr.status, (name) => xhr.getResponseHeader(name));
1017
+ s.event = event;
1018
+ s.accepted = engine.accepts(event);
1019
+ } catch (error) {
1020
+ engine.report(error, "response");
1021
+ s.accepted = false;
1022
+ }
1023
+ return s.accepted;
1024
+ };
1025
+ const fromText = (xhr, s, value) => {
1026
+ if (s.text !== void 0) return s.text;
1027
+ if (xhr.readyState !== 4 || !decide(xhr, s)) return value;
1028
+ const event = s.event;
1029
+ try {
1030
+ s.text = engine.transformBody(value, event);
1031
+ engine.expectParse(s.text, event);
1032
+ return s.text;
1033
+ } catch (error) {
1034
+ engine.report(error, "response");
1035
+ return value;
1036
+ }
1037
+ };
1038
+ const fromJson = (xhr, s, value) => {
1039
+ if (s.data !== void 0) return s.data;
1040
+ if (xhr.readyState !== 4 || value === null || !decide(xhr, s)) return value;
1041
+ s.data = engine.track(value, s.event, void 0);
1042
+ return s.data;
1043
+ };
1044
+ const open = function open2(...args) {
1045
+ try {
1046
+ const route = active ? engine.fence(String(args[1]), String(args[0]).toUpperCase()) : void 0;
1047
+ if (route === void 0) states.delete(this);
1048
+ else
1049
+ states.set(this, {
1050
+ route,
1051
+ event: void 0,
1052
+ accepted: void 0,
1053
+ text: void 0,
1054
+ data: void 0
1055
+ });
1056
+ } catch (error) {
1057
+ engine.report(error, "request");
1058
+ states.delete(this);
1059
+ }
1060
+ Reflect.apply(originalOpen, this, args);
1061
+ };
1062
+ const send = function send2(...args) {
1063
+ const s = active ? states.get(this) : void 0;
1064
+ if (s !== void 0) {
1065
+ try {
1066
+ engine.plugins.onRequest({
1067
+ transport: "xhr",
1068
+ url: s.route.url,
1069
+ method: s.route.method,
1070
+ endpoint: s.route.endpoint,
1071
+ setHeader: (name, value) => this.setRequestHeader(name, value)
1072
+ });
1073
+ } catch (error) {
1074
+ engine.report(error, "request");
1075
+ }
1076
+ }
1077
+ Reflect.apply(originalSend, this, args);
1078
+ };
1079
+ proto.open = open;
1080
+ if (engine.plugins.hasRequestHooks) proto.send = send;
1081
+ Object.defineProperty(proto, "responseText", {
1082
+ configurable: true,
1083
+ enumerable: textDesc.enumerable ?? true,
1084
+ get() {
1085
+ const value = getText.call(this);
1086
+ const s = states.get(this);
1087
+ return s === void 0 ? value : fromText(this, s, value);
1088
+ }
1089
+ });
1090
+ Object.defineProperty(proto, "response", {
1091
+ configurable: true,
1092
+ enumerable: responseDesc.enumerable ?? true,
1093
+ get() {
1094
+ const value = getResponse.call(this);
1095
+ const s = states.get(this);
1096
+ if (s === void 0) return value;
1097
+ const type = this.responseType;
1098
+ if (type === "" || type === "text") return fromText(this, s, value);
1099
+ if (type === "json") return fromJson(this, s, value);
1100
+ return value;
1101
+ }
1102
+ });
1103
+ return () => {
1104
+ active = false;
1105
+ if (proto.open === open) proto.open = originalOpen;
1106
+ if (proto.send === send) proto.send = originalSend;
1107
+ Object.defineProperty(proto, "responseText", textDesc);
1108
+ Object.defineProperty(proto, "response", responseDesc);
1109
+ };
1110
+ }
1111
+
1112
+ // src/plugins.ts
1113
+ var collect = (plugins, key) => {
1114
+ const out = [];
1115
+ for (const plugin of plugins) {
1116
+ const hook = plugin[key];
1117
+ if (typeof hook === "function") out.push({ plugin, hook });
1118
+ }
1119
+ return out;
1120
+ };
1121
+ function createPluginRunner(plugins, report) {
1122
+ const setupHooks = collect(plugins, "setup");
1123
+ const requestHooks = collect(plugins, "onRequest");
1124
+ const responseHooks = collect(plugins, "onResponse");
1125
+ const bodyHooks = collect(plugins, "transformBody");
1126
+ const dataHooks = collect(plugins, "transformData");
1127
+ const trackHooks = collect(plugins, "onTrack");
1128
+ const firstReadHooks = collect(plugins, "onFirstRead");
1129
+ const batchHooks = collect(plugins, "onBatch");
1130
+ const teardowns = [];
1131
+ const fail = (plugin, hook, error) => {
1132
+ report(
1133
+ error instanceof Error ? Object.assign(error, { plugin: plugin.name, hook }) : { plugin: plugin.name, hook, error },
1134
+ "plugin"
1135
+ );
1136
+ };
1137
+ return {
1138
+ hasRequestHooks: requestHooks.length > 0,
1139
+ hasFirstReadHooks: firstReadHooks.length > 0,
1140
+ setup(api) {
1141
+ for (const { plugin, hook } of setupHooks) {
1142
+ try {
1143
+ const teardown = hook.call(plugin, api);
1144
+ if (typeof teardown === "function") teardowns.push(teardown);
1145
+ } catch (error) {
1146
+ fail(plugin, "setup", error);
1147
+ }
1148
+ }
1149
+ },
1150
+ teardown() {
1151
+ for (const teardown of teardowns.splice(0)) {
1152
+ try {
1153
+ teardown();
1154
+ } catch (error) {
1155
+ report(error, "plugin");
1156
+ }
1157
+ }
1158
+ },
1159
+ onRequest(event) {
1160
+ for (const { plugin, hook } of requestHooks) {
1161
+ try {
1162
+ hook.call(plugin, event);
1163
+ } catch (error) {
1164
+ fail(plugin, "onRequest", error);
1165
+ }
1166
+ }
1167
+ },
1168
+ onResponse(event) {
1169
+ for (const { plugin, hook } of responseHooks) {
1170
+ try {
1171
+ if (hook.call(plugin, event) === false) return false;
1172
+ } catch (error) {
1173
+ fail(plugin, "onResponse", error);
1174
+ }
1175
+ }
1176
+ return true;
1177
+ },
1178
+ transformBody(body, event) {
1179
+ let out = body;
1180
+ for (const { plugin, hook } of bodyHooks) {
1181
+ try {
1182
+ const next = hook.call(plugin, out, event);
1183
+ if (typeof next === "string") out = next;
1184
+ } catch (error) {
1185
+ fail(plugin, "transformBody", error);
1186
+ }
1187
+ }
1188
+ return out;
1189
+ },
1190
+ transformData(data, event) {
1191
+ let out = data;
1192
+ for (const { plugin, hook } of dataHooks) {
1193
+ try {
1194
+ out = hook.call(plugin, out, event);
1195
+ } catch (error) {
1196
+ fail(plugin, "transformData", error);
1197
+ }
1198
+ }
1199
+ return out;
1200
+ },
1201
+ onTrack(event) {
1202
+ for (const { plugin, hook } of trackHooks) {
1203
+ try {
1204
+ hook.call(plugin, event);
1205
+ } catch (error) {
1206
+ fail(plugin, "onTrack", error);
1207
+ }
1208
+ }
1209
+ },
1210
+ onFirstRead(event) {
1211
+ for (const { plugin, hook } of firstReadHooks) {
1212
+ try {
1213
+ hook.call(plugin, event);
1214
+ } catch (error) {
1215
+ fail(plugin, "onFirstRead", error);
1216
+ }
1217
+ }
1218
+ },
1219
+ onBatch(batch) {
1220
+ let out = batch;
1221
+ for (const { plugin, hook } of batchHooks) {
1222
+ try {
1223
+ const next = hook.call(plugin, out);
1224
+ if (next === false) return void 0;
1225
+ if (next !== void 0) out = next;
1226
+ } catch (error) {
1227
+ fail(plugin, "onBatch", error);
1228
+ }
1229
+ }
1230
+ return out;
1231
+ }
1232
+ };
1233
+ }
1234
+ function definePlugin(plugin) {
1235
+ return plugin;
1236
+ }
1237
+
1238
+ // src/transport/batch.ts
1239
+ function takeReads(stats, table) {
1240
+ const out = [];
1241
+ for (const s of stats) {
1242
+ if (s.responses === 0 && s.counts.size === 0) continue;
1243
+ const reads = [];
1244
+ for (const [id, c] of s.counts) reads.push([table.byId[id].path, c.any, c.direct, c.bulk]);
1245
+ out.push({ key: s.key, responses: s.responses, reads });
1246
+ s.responses = 0;
1247
+ s.counts.clear();
1248
+ }
1249
+ return out;
1250
+ }
1251
+ function buildBatch(sid, rate, reads, inventory) {
1252
+ const dict = /* @__PURE__ */ new Map();
1253
+ const paths = [];
1254
+ const idx = (path) => {
1255
+ let i = dict.get(path);
1256
+ if (i === void 0) {
1257
+ i = paths.length;
1258
+ paths.push(path);
1259
+ dict.set(path, i);
1260
+ }
1261
+ return i;
1262
+ };
1263
+ const byKey = /* @__PURE__ */ new Map();
1264
+ const entry = (key) => {
1265
+ let e = byKey.get(key);
1266
+ if (e === void 0) {
1267
+ e = { key };
1268
+ byKey.set(key, e);
1269
+ }
1270
+ return e;
1271
+ };
1272
+ for (const r of reads) {
1273
+ const e = entry(r.key);
1274
+ e.responses = r.responses;
1275
+ if (r.reads.length > 0) {
1276
+ e.reads = r.reads.map(([p, any, direct, bulk]) => [idx(p), any, direct, bulk]);
1277
+ }
1278
+ }
1279
+ for (const [key, inv] of inventory) {
1280
+ if (inv.inventoried === 0) continue;
1281
+ const e = entry(key);
1282
+ e.inventoried = inv.inventoried;
1283
+ const present = [];
1284
+ for (const [p, count] of inv.present) present.push([idx(p), count]);
1285
+ e.present = present;
1286
+ }
1287
+ if (byKey.size === 0) return void 0;
1288
+ return { v: PAYLOAD_VERSION, sid, ts: Date.now(), rate, paths, endpoints: [...byKey.values()] };
1289
+ }
1290
+ function createSender(endpoint, originalFetch) {
1291
+ return async (batch, { unload }) => {
1292
+ const body = JSON.stringify(batch);
1293
+ const nav = globalThis.navigator;
1294
+ if (unload && typeof nav?.sendBeacon === "function") {
1295
+ if (nav.sendBeacon(endpoint, body)) return;
1296
+ }
1297
+ if (originalFetch === void 0) return;
1298
+ const res = await originalFetch(endpoint, {
1299
+ method: "POST",
1300
+ body,
1301
+ headers: { "content-type": "text/plain;charset=UTF-8" },
1302
+ credentials: "omit",
1303
+ keepalive: body.length < KEEPALIVE_LIMIT
1304
+ });
1305
+ if (!res.ok) throw new Error(`collector responded ${res.status}`);
1306
+ };
1307
+ }
1308
+
1309
+ // src/transport/inventory.ts
1310
+ function mergeInto(target, source) {
1311
+ for (const [endpoint, entry] of source) {
1312
+ let into = target.get(endpoint);
1313
+ if (into === void 0) {
1314
+ into = { inventoried: 0, present: /* @__PURE__ */ new Map() };
1315
+ target.set(endpoint, into);
1316
+ }
1317
+ into.inventoried += entry.inventoried;
1318
+ for (const [path, count] of entry.present) {
1319
+ into.present.set(path, (into.present.get(path) ?? 0) + count);
1320
+ }
1321
+ }
1322
+ return target;
1323
+ }
1324
+ function addPaths(snapshot, endpoint, paths) {
1325
+ let entry = snapshot.get(endpoint);
1326
+ if (entry === void 0) {
1327
+ entry = { inventoried: 0, present: /* @__PURE__ */ new Map() };
1328
+ snapshot.set(endpoint, entry);
1329
+ }
1330
+ entry.inventoried++;
1331
+ for (const path of paths) entry.present.set(path, (entry.present.get(path) ?? 0) + 1);
1332
+ }
1333
+ var scheduleIdle = (() => {
1334
+ const g = globalThis;
1335
+ if (typeof g.requestIdleCallback === "function") {
1336
+ const ric = g.requestIdleCallback.bind(globalThis);
1337
+ return (fn) => {
1338
+ ric(fn, { timeout: 2e3 });
1339
+ };
1340
+ }
1341
+ return (fn) => {
1342
+ const t = setTimeout(fn, 50);
1343
+ t.unref?.();
1344
+ };
1345
+ })();
1346
+ var MAX_QUEUE = 200;
1347
+ function createMainInventory(config, maxArrayItems, raw) {
1348
+ let snapshot = /* @__PURE__ */ new Map();
1349
+ let queue = [];
1350
+ let scheduled = false;
1351
+ const process = (budgetMs) => {
1352
+ const start = Date.now();
1353
+ while (queue.length > 0) {
1354
+ const item = queue.shift();
1355
+ addPaths(
1356
+ snapshot,
1357
+ item.endpoint,
1358
+ collectPaths(item.data, config, maxArrayItems, /* @__PURE__ */ new Set(), raw)
1359
+ );
1360
+ if (Date.now() - start > budgetMs) break;
1361
+ }
1362
+ };
1363
+ const run = () => {
1364
+ scheduled = false;
1365
+ process(8);
1366
+ if (queue.length > 0) schedule();
1367
+ };
1368
+ const schedule = () => {
1369
+ if (scheduled) return;
1370
+ scheduled = true;
1371
+ scheduleIdle(run);
1372
+ };
1373
+ return {
1374
+ offer(endpoint, _text, data) {
1375
+ if (typeof data !== "object" || data === null) return;
1376
+ if (queue.length >= MAX_QUEUE) return;
1377
+ queue.push({ endpoint, data });
1378
+ schedule();
1379
+ },
1380
+ async drain() {
1381
+ process(Number.POSITIVE_INFINITY);
1382
+ const out = snapshot;
1383
+ snapshot = /* @__PURE__ */ new Map();
1384
+ return out;
1385
+ },
1386
+ drainSync() {
1387
+ process(Number.POSITIVE_INFINITY);
1388
+ const out = snapshot;
1389
+ snapshot = /* @__PURE__ */ new Map();
1390
+ return out;
1391
+ },
1392
+ dispose() {
1393
+ queue = [];
1394
+ snapshot = /* @__PURE__ */ new Map();
1395
+ }
1396
+ };
1397
+ }
1398
+
1399
+ // src/worker/source.generated.ts
1400
+ var WORKER_SOURCE = '"use strict";(()=>{var C=/^[A-Za-z_$][\\w$-]*$/;function K(t,e){return C.test(e)?t===""?e:`${t}.${e}`:`${t}[${JSON.stringify(e)}]`}function N(t){return t+"[*]"}function g(t){return t===""?"{*}":`${t}.{*}`}function j(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0;return!1}function P(t){return{dynamicKeys:t.dynamicKeys.map(e=>new RegExp(e.source,e.flags)),maxKeysPerObject:t.maxKeysPerObject,maxDepth:t.maxDepth}}function x(t,e,r,c=new Set,p=d=>d){let d=new Map,l=(f,o,u)=>{if(f===null||typeof f!="object"||u>=e.maxDepth)return;let s=p(f);if(Array.isArray(s)){if(s.length===0)return;let a=N(o);c.add(a);let i=Math.min(s.length,r);for(let n=0;n<i;n++)l(s[n],a,u+1);return}let h=s;for(let a in h){if(!Object.hasOwn(h,a))continue;let i;if(j(a,e.dynamicKeys))i=g(o);else{let n=d.get(o);n===void 0&&(n=new Set,d.set(o,n)),n.has(a)||n.size<e.maxKeysPerObject?(n.add(a),i=K(o,a)):i=g(o)}c.add(i),l(h[a],i,u+1)}};return l(t,"",0),c}var m=globalThis,y,b=100;m.onmessage=t=>{let e=t.data;if(e.t==="init"){y=P(e.paths),b=e.maxArrayItems,m.postMessage({t:"ready"});return}if(e.t==="body"){let r=null;if(y!==void 0)try{r=[...x(JSON.parse(e.text),y,b)]}catch{r=null}m.postMessage({t:"paths",id:e.id,paths:r})}};})();\n';
1401
+
1402
+ // src/transport/worker-inventory.ts
1403
+ var DRAIN_TIMEOUT = 2e3;
1404
+ var MAX_PENDING = 200;
1405
+ function startWorker(option) {
1406
+ if (typeof option === "function") return option();
1407
+ if (option === true) {
1408
+ const blob = new Blob([WORKER_SOURCE], { type: "text/javascript" });
1409
+ const url = URL.createObjectURL(blob);
1410
+ try {
1411
+ return new Worker(url);
1412
+ } finally {
1413
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
1414
+ }
1415
+ }
1416
+ return new Worker(option);
1417
+ }
1418
+ function createWorkerInventory(option, config, maxArrayItems, fallback, onFailure) {
1419
+ if (typeof option !== "function" && typeof Worker === "undefined") return void 0;
1420
+ let worker;
1421
+ try {
1422
+ worker = startWorker(option);
1423
+ } catch (error) {
1424
+ onFailure(error);
1425
+ return void 0;
1426
+ }
1427
+ let failed = false;
1428
+ let nextId = 1;
1429
+ let done = /* @__PURE__ */ new Map();
1430
+ const pending = /* @__PURE__ */ new Map();
1431
+ let idle = [];
1432
+ const wake = () => {
1433
+ const waiting = idle;
1434
+ idle = [];
1435
+ for (const resolve of waiting) resolve();
1436
+ };
1437
+ const takeOver = () => {
1438
+ for (const { endpoint, data } of pending.values()) fallback.offer(endpoint, void 0, data);
1439
+ pending.clear();
1440
+ wake();
1441
+ };
1442
+ const fail = (error) => {
1443
+ if (failed) return;
1444
+ failed = true;
1445
+ onFailure(error);
1446
+ takeOver();
1447
+ try {
1448
+ worker.terminate();
1449
+ } catch {
1450
+ }
1451
+ };
1452
+ worker.addEventListener("error", (event) => {
1453
+ event.preventDefault?.();
1454
+ fail(event);
1455
+ });
1456
+ worker.addEventListener("message", (event) => {
1457
+ const msg = event.data;
1458
+ if (msg.t !== "paths") return;
1459
+ const item = pending.get(msg.id);
1460
+ if (item === void 0) return;
1461
+ pending.delete(msg.id);
1462
+ if (msg.paths !== null) addPaths(done, item.endpoint, msg.paths);
1463
+ if (pending.size === 0) wake();
1464
+ });
1465
+ try {
1466
+ worker.postMessage({
1467
+ t: "init",
1468
+ paths: serializePathConfig(config),
1469
+ maxArrayItems
1470
+ });
1471
+ } catch (error) {
1472
+ fail(error);
1473
+ return void 0;
1474
+ }
1475
+ const take = (rest) => {
1476
+ const out = mergeInto(done, rest);
1477
+ done = /* @__PURE__ */ new Map();
1478
+ return out;
1479
+ };
1480
+ return {
1481
+ offer(endpoint, text, data) {
1482
+ if (failed || text === void 0 || pending.size >= MAX_PENDING) {
1483
+ fallback.offer(endpoint, text, data);
1484
+ return;
1485
+ }
1486
+ const id = nextId++;
1487
+ pending.set(id, { endpoint, data });
1488
+ try {
1489
+ worker.postMessage({ t: "body", id, text });
1490
+ } catch (error) {
1491
+ fail(error);
1492
+ }
1493
+ },
1494
+ async drain() {
1495
+ if (pending.size > 0) {
1496
+ await new Promise((resolve) => {
1497
+ idle.push(resolve);
1498
+ const timer = setTimeout(resolve, DRAIN_TIMEOUT);
1499
+ timer.unref?.();
1500
+ });
1501
+ takeOver();
1502
+ }
1503
+ return take(await fallback.drain());
1504
+ },
1505
+ drainSync() {
1506
+ takeOver();
1507
+ return take(fallback.drainSync());
1508
+ },
1509
+ dispose() {
1510
+ fallback.dispose();
1511
+ pending.clear();
1512
+ done = /* @__PURE__ */ new Map();
1513
+ wake();
1514
+ try {
1515
+ worker.terminate();
1516
+ } catch {
1517
+ }
1518
+ }
1519
+ };
1520
+ }
1521
+
1522
+ // src/install.ts
1523
+ var randomId = () => {
1524
+ const c = globalThis.crypto;
1525
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
1526
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
1527
+ };
1528
+ var disabledHandle = (sessionId) => ({
1529
+ enabled: false,
1530
+ sessionId,
1531
+ flush: async () => {
1532
+ },
1533
+ uninstall: () => {
1534
+ },
1535
+ track: (data) => data
1536
+ });
1537
+ function flush() {
1538
+ const instance = globalThis[GLOBAL_KEY];
1539
+ return instance !== void 0 ? instance.flush() : Promise.resolve();
1540
+ }
1541
+ function checkEndpoint(endpoint, baseUrl) {
1542
+ const example = '"https://app.example.com/api/collect?key=pa_pub_\u2026"';
1543
+ if (isBareKey(endpoint)) {
1544
+ throw new Error(
1545
+ `[${LIBRARY_NAME}] endpoint must be a URL, e.g. ${example}; got ${redactKeys(endpoint)}, which looks like a key. Pass the full ingest URL with the key as ?key=\u2026.`
1546
+ );
1547
+ }
1548
+ const base = baseUrl ?? globalThis.location?.href;
1549
+ let url;
1550
+ try {
1551
+ url = new URL(endpoint, base);
1552
+ } catch {
1553
+ url = void 0;
1554
+ }
1555
+ if (url === void 0 || url.protocol !== "https:" && url.protocol !== "http:") {
1556
+ throw new Error(
1557
+ `[${LIBRARY_NAME}] endpoint must be a URL, e.g. ${example}; got ${redactKeys(JSON.stringify(endpoint))}${base === void 0 ? " (relative URLs need a page or `baseUrl`)" : ""}.`
1558
+ );
1559
+ }
1560
+ }
1561
+ function install(options) {
1562
+ const registry = globalThis;
1563
+ const existing = registry[GLOBAL_KEY];
1564
+ if (existing !== void 0) {
1565
+ console.warn(`[${LIBRARY_NAME}] already installed; returning the existing instance.`);
1566
+ return existing;
1567
+ }
1568
+ const sessionId = randomId();
1569
+ const sampleRate = options.sampleRate ?? 1;
1570
+ const responseSampleRate = options.responseSampleRate ?? 1;
1571
+ if (!(responseSampleRate >= 0 && responseSampleRate <= 1)) {
1572
+ throw new Error(`[${LIBRARY_NAME}] responseSampleRate must be between 0 and 1.`);
1573
+ }
1574
+ if (options.endpoint !== void 0) checkEndpoint(options.endpoint, options.baseUrl);
1575
+ const fence = createFence({
1576
+ apis: options.apis,
1577
+ ignore: options.ignore,
1578
+ baseUrl: options.baseUrl,
1579
+ endpointKey: options.endpointKey,
1580
+ alwaysExclude: options.endpoint !== void 0 ? [options.endpoint] : []
1581
+ });
1582
+ if (!(Math.random() < sampleRate)) return disabledHandle(sessionId);
1583
+ const debug = options.debug === true;
1584
+ const report = (error, phase) => {
1585
+ if (options.onError !== void 0) {
1586
+ try {
1587
+ options.onError(error, phase);
1588
+ } catch {
1589
+ }
1590
+ } else if (debug) {
1591
+ console.warn(`[${LIBRARY_NAME}] ${phase} error`, error);
1592
+ }
1593
+ };
1594
+ const pathConfig = {
1595
+ dynamicKeys: options.paths?.dynamicKeys ?? DEFAULT_DYNAMIC_KEYS,
1596
+ maxKeysPerObject: options.paths?.maxKeysPerObject ?? DEFAULT_MAX_KEYS_PER_OBJECT,
1597
+ maxDepth: options.paths?.maxDepth ?? DEFAULT_MAX_DEPTH
1598
+ };
1599
+ const maxArrayItems = options.inventory?.maxArrayItems ?? DEFAULT_INVENTORY_MAX_ARRAY_ITEMS;
1600
+ const intercept = {
1601
+ fetch: options.intercept?.fetch ?? true,
1602
+ xhr: options.intercept?.xhr ?? true,
1603
+ jsonParse: options.intercept?.jsonParse ?? true,
1604
+ cloneSafety: options.intercept?.cloneSafety ?? true
1605
+ };
1606
+ const plugins = createPluginRunner(options.plugins ?? [], report);
1607
+ const table = createPathTable(pathConfig);
1608
+ const tracker = createTracker(
1609
+ table,
1610
+ plugins.hasFirstReadHooks ? (stats, node, kind) => plugins.onFirstRead({ endpoint: stats.key, path: node.path, kind }) : void 0
1611
+ );
1612
+ const mainInventory = createMainInventory(pathConfig, maxArrayItems, rawOf);
1613
+ const workerOption = options.worker ?? true;
1614
+ const inventory = workerOption === false ? mainInventory : createWorkerInventory(
1615
+ workerOption,
1616
+ pathConfig,
1617
+ maxArrayItems,
1618
+ mainInventory,
1619
+ (error) => report(error, "worker")
1620
+ ) ?? mainInventory;
1621
+ const engine = createEngine({
1622
+ fence,
1623
+ plugins,
1624
+ report,
1625
+ tracker,
1626
+ inventory,
1627
+ inventorySampleRate: options.inventory?.sampleRate ?? 1,
1628
+ trackErrors: options.trackErrors ?? false,
1629
+ responseSampleRate,
1630
+ parseTtl: DEFAULT_PARSE_TTL,
1631
+ expectParses: intercept.jsonParse
1632
+ });
1633
+ const nativeFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : void 0;
1634
+ const restores = [];
1635
+ if (intercept.fetch) restores.push(patchFetch(engine).restore);
1636
+ if (intercept.xhr) restores.push(patchXhr(engine));
1637
+ if (intercept.jsonParse) restores.push(patchJsonParse(engine));
1638
+ if (intercept.cloneSafety) restores.push(patchCloneSafety());
1639
+ const send = options.endpoint !== void 0 ? createSender(options.endpoint, nativeFetch) : void 0;
1640
+ let flushing;
1641
+ const flushNow = async (unload) => {
1642
+ const reads = takeReads(engine.stats.values(), table);
1643
+ const inv = unload ? inventory.drainSync() : await inventory.drain();
1644
+ let batch = buildBatch(sessionId, sampleRate * responseSampleRate, reads, inv);
1645
+ if (batch === void 0) return;
1646
+ batch = plugins.onBatch(batch);
1647
+ if (batch === void 0 || send === void 0) return;
1648
+ try {
1649
+ await send(batch, { unload });
1650
+ } catch (error) {
1651
+ report(error, "flush");
1652
+ }
1653
+ };
1654
+ const flush2 = () => {
1655
+ const run = (flushing ?? Promise.resolve()).then(() => flushNow(false));
1656
+ flushing = run.finally(() => {
1657
+ if (flushing === run) flushing = void 0;
1658
+ });
1659
+ return run;
1660
+ };
1661
+ const interval = setInterval(() => {
1662
+ void flush2();
1663
+ }, options.flushInterval ?? DEFAULT_FLUSH_INTERVAL);
1664
+ interval.unref?.();
1665
+ const doc = globalThis.document;
1666
+ const win = globalThis.addEventListener ? globalThis : void 0;
1667
+ const onHidden = () => {
1668
+ if (doc?.visibilityState === "hidden") void flushNow(true);
1669
+ };
1670
+ const onPageHide = () => {
1671
+ void flushNow(true);
1672
+ };
1673
+ doc?.addEventListener("visibilitychange", onHidden);
1674
+ win?.addEventListener("pagehide", onPageHide);
1675
+ const manualTrack = (data, opts) => {
1676
+ const event = {
1677
+ transport: "manual",
1678
+ url: void 0,
1679
+ method: "MANUAL",
1680
+ endpoint: opts.endpoint,
1681
+ status: 200,
1682
+ header: () => null
1683
+ };
1684
+ return engine.track(data, event, void 0);
1685
+ };
1686
+ const api = { sessionId, flush: flush2, track: manualTrack, unwrap };
1687
+ let installed = true;
1688
+ const handle = {
1689
+ enabled: true,
1690
+ sessionId,
1691
+ flush: flush2,
1692
+ track: manualTrack,
1693
+ uninstall() {
1694
+ if (!installed) return;
1695
+ installed = false;
1696
+ clearInterval(interval);
1697
+ doc?.removeEventListener("visibilitychange", onHidden);
1698
+ win?.removeEventListener("pagehide", onPageHide);
1699
+ for (const restore of restores.splice(0).reverse()) restore();
1700
+ plugins.teardown();
1701
+ engine.dispose();
1702
+ if (registry[GLOBAL_KEY] === handle) registry[GLOBAL_KEY] = void 0;
1703
+ }
1704
+ };
1705
+ registry[GLOBAL_KEY] = handle;
1706
+ plugins.setup(api);
1707
+ if (debug) console.info(`[${LIBRARY_NAME}] installed`, { sessionId });
1708
+ return handle;
1709
+ }
1710
+
1711
+ // src/presets/postgrest.ts
1712
+ function postgrestEndpointKey({ method, url }) {
1713
+ const match = /\/rest\/v1\/(.+?)\/?$/.exec(url.pathname);
1714
+ if (match === null) return `${method} ${url.pathname}`;
1715
+ let resource;
1716
+ try {
1717
+ resource = decodeURIComponent(match[1]);
1718
+ } catch {
1719
+ resource = match[1];
1720
+ }
1721
+ const select = url.searchParams.get("select");
1722
+ if (select === null) return `${method} ${resource}`;
1723
+ return `${method} ${resource}?select=${select.replace(/\s+/g, "")}`;
1724
+ }
1725
+
1726
+ export { DEFAULT_DYNAMIC_KEYS, defaultEndpointKey, definePlugin, flush, install, isTracked, postgrestEndpointKey, unwrap };
1727
+ //# sourceMappingURL=index.js.map
1728
+ //# sourceMappingURL=index.js.map