@steadphast/connector-nextjs 0.5.4 → 0.7.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/server.js ADDED
@@ -0,0 +1,1149 @@
1
+ // src/collector-render.ts
2
+ import { headers } from "next/headers";
3
+ import { createElement } from "react";
4
+
5
+ // src/behavioral-collector.ts
6
+ function behavioralCollector(nonce, endpoint, timing, issuedAt, route, notice = false, pathCapture = false) {
7
+ let closed = false;
8
+ let started = false;
9
+ let start = 0;
10
+ let startTick = 0;
11
+ let timer;
12
+ const records = [];
13
+ let sampled = 0;
14
+ let actions = 0;
15
+ const dropped = [0, 0, 0, 0, 0, 0];
16
+ let lastSample = Number.NEGATIVE_INFINITY;
17
+ let lastMotion;
18
+ let baseline = false;
19
+ let moved = false;
20
+ let inputObserved = false;
21
+ const motionTimes = [];
22
+ let pointerDown = false;
23
+ let downGeometry;
24
+ let keyDownAt;
25
+ let keyOverlap = false;
26
+ let outstandingKeys = 0;
27
+ let lastKeyUp;
28
+ let keyFlight;
29
+ let lastKeyEvent = Number.NEGATIVE_INFINITY;
30
+ let keyIntervals = 0;
31
+ let scrollIntervals = 0;
32
+ let lastScroll;
33
+ let scrollX = 0;
34
+ let scrollY = 0;
35
+ let lastRawScroll;
36
+ let rawScrollX = 0;
37
+ let rawScrollY = 0;
38
+ let burstFromX = 0;
39
+ let burstFromY = 0;
40
+ let burstEvents = 0;
41
+ const counts = {
42
+ pointer_origin_clicks: 0,
43
+ pointer_origin_clicks_without_motion: 0,
44
+ paste_inputs: 0,
45
+ scroll_bursts: 0,
46
+ single_event_scroll_burst_bins: [0, 0, 0, 0, 0, 0, 0, 0]
47
+ };
48
+ const inputCounts = [0, 0, 0, 0];
49
+ const focused = /* @__PURE__ */ new WeakSet();
50
+ const changed = /* @__PURE__ */ new WeakSet();
51
+ const together = /* @__PURE__ */ new WeakSet();
52
+ let instant = [];
53
+ let lastInput = Number.NEGATIVE_INFINITY;
54
+ const pointerPosition = [0, 0, 0, 0];
55
+ const otherPosition = [0, 0, 0];
56
+ const inputPosition = [0, 0];
57
+ let forwarded;
58
+ let roundTrip;
59
+ let roundTripWatcher;
60
+ let quantum = null;
61
+ let lastClock;
62
+ const listeners = [];
63
+ const encoder = new TextEncoder();
64
+ let recordBytes = 0;
65
+ const budget = 4096 - encoder.encode(
66
+ JSON.stringify({
67
+ version: "1",
68
+ nonce,
69
+ started_at_ms: Date.now(),
70
+ duration_ms: 3e4,
71
+ end: "action-limit",
72
+ timing_enabled: timing,
73
+ timer_quantum_ms: 65535,
74
+ actions: 100,
75
+ sampled: 1024,
76
+ dropped: [65535, 65535, 65535, 65535, 65535, 65535],
77
+ records: [],
78
+ counts: {
79
+ pointer_origin_clicks: 100,
80
+ pointer_origin_clicks_without_motion: 100,
81
+ paste_inputs: 100,
82
+ scroll_bursts: 100,
83
+ single_event_scroll_burst_bins: [
84
+ 100,
85
+ 100,
86
+ 100,
87
+ 100,
88
+ 100,
89
+ 100,
90
+ 100,
91
+ 100
92
+ ],
93
+ pointer_motion_observed: false,
94
+ input_observed: false,
95
+ control_inputs: 1e3,
96
+ control_inputs_without_focus: 1e3,
97
+ changed_controls: 100,
98
+ controls_changed_in_one_instant: 100,
99
+ pointer_click_position: [100, 100, 100, 100],
100
+ other_activation_position: [100, 100, 100],
101
+ input_position: [1e3, 1e3]
102
+ },
103
+ page_round_trip_ms: 3e4
104
+ })
105
+ ).length - 64;
106
+ let observer;
107
+ function listen(target2, name, callback) {
108
+ const fn = callback;
109
+ target2.addEventListener(name, fn, { passive: true, capture: true });
110
+ listeners.push([target2, name, fn]);
111
+ }
112
+ function discard() {
113
+ if (closed) return;
114
+ closed = true;
115
+ clearTimeout(timer);
116
+ clearTimeout(expiry);
117
+ for (const [target2, name, fn] of listeners)
118
+ target2.removeEventListener(name, fn, true);
119
+ listeners.length = 0;
120
+ observer?.disconnect();
121
+ observer = void 0;
122
+ roundTripWatcher?.disconnect();
123
+ roundTripWatcher = void 0;
124
+ instant = [];
125
+ forwarded = void 0;
126
+ records.length = 0;
127
+ dropped.length = 0;
128
+ keyDownAt = void 0;
129
+ lastKeyUp = void 0;
130
+ keyFlight = void 0;
131
+ lastMotion = void 0;
132
+ lastClock = void 0;
133
+ lastScroll = void 0;
134
+ lastRawScroll = void 0;
135
+ motionTimes.length = 0;
136
+ downGeometry = void 0;
137
+ }
138
+ function closeBurst() {
139
+ if (burstEvents === 1) {
140
+ const distance = Math.hypot(
141
+ rawScrollX - burstFromX,
142
+ rawScrollY - burstFromY
143
+ );
144
+ let bin = 0;
145
+ for (const edge of [25, 50, 100, 200, 400, 800, 1600])
146
+ if (distance >= edge) bin++;
147
+ const bins = counts.single_event_scroll_burst_bins;
148
+ bins[bin] = (bins[bin] ?? 0) + 1;
149
+ }
150
+ burstEvents = 0;
151
+ }
152
+ function finish(end) {
153
+ if (closed) return;
154
+ if (!started) {
155
+ discard();
156
+ return;
157
+ }
158
+ closeBurst();
159
+ const keys = records.filter(
160
+ (record) => record.kind === "key"
161
+ );
162
+ const canonical = (values) => values.map((value) => value == null ? null : value - value % 10).sort(
163
+ (a, b) => a === null ? b === null ? 0 : -1 : b === null ? 1 : a - b
164
+ );
165
+ const dwell = canonical(keys.map((key) => key.dwell_ms));
166
+ const flight = canonical(keys.map((key) => key.flight_ms));
167
+ keys.forEach((key, index) => {
168
+ key.dwell_ms = dwell[index] ?? null;
169
+ key.flight_ms = flight[index] ?? null;
170
+ });
171
+ const payload = {
172
+ version: "1",
173
+ nonce,
174
+ started_at_ms: start,
175
+ duration_ms: Math.min(
176
+ 3e4,
177
+ Math.max(0, Math.round(performance.now() - startTick))
178
+ ),
179
+ end,
180
+ timing_enabled: timing,
181
+ timer_quantum_ms: timing ? quantum : null,
182
+ actions,
183
+ sampled,
184
+ dropped,
185
+ records,
186
+ counts: {
187
+ ...counts,
188
+ pointer_motion_observed: moved,
189
+ input_observed: inputObserved,
190
+ control_inputs: inputCounts[0],
191
+ control_inputs_without_focus: inputCounts[1],
192
+ changed_controls: inputCounts[2],
193
+ controls_changed_in_one_instant: inputCounts[3],
194
+ pointer_click_position: pointerPosition,
195
+ other_activation_position: otherPosition,
196
+ input_position: inputPosition
197
+ },
198
+ ...roundTrip === void 0 ? {} : { page_round_trip_ms: roundTrip }
199
+ };
200
+ const body = JSON.stringify(payload);
201
+ discard();
202
+ if (encoder.encode(body).length > 4096) return;
203
+ void fetch(endpoint, {
204
+ method: "POST",
205
+ body,
206
+ headers: { "content-type": "text/plain" },
207
+ credentials: "omit",
208
+ keepalive: true,
209
+ mode: "cors",
210
+ cache: "no-store"
211
+ }).catch(() => {
212
+ });
213
+ }
214
+ function active() {
215
+ if (!started || closed) return false;
216
+ if (location.pathname !== route) {
217
+ finish("route-change");
218
+ return false;
219
+ }
220
+ if (performance.now() - startTick >= 3e4) {
221
+ finish("deadline");
222
+ return false;
223
+ }
224
+ return true;
225
+ }
226
+ function clock() {
227
+ const now = performance.now();
228
+ if (timing && lastClock !== void 0 && now > lastClock) {
229
+ const delta = Math.ceil(now - lastClock);
230
+ quantum = quantum === null ? delta : Math.min(quantum, delta);
231
+ }
232
+ if (timing) lastClock = now;
233
+ return now;
234
+ }
235
+ function at() {
236
+ return timing ? Math.min(3e4, Math.max(0, Math.round(clock() - startTick))) : null;
237
+ }
238
+ function drop(group) {
239
+ dropped[group] = Math.min(65535, (dropped[group] ?? 0) + 1);
240
+ }
241
+ function add(record, group) {
242
+ if (!active()) return;
243
+ if (sampled >= 1024) {
244
+ drop(group);
245
+ return;
246
+ }
247
+ sampled++;
248
+ const size = encoder.encode(JSON.stringify(record)).length + 1;
249
+ if (recordBytes + size > budget) {
250
+ drop(group);
251
+ return;
252
+ }
253
+ recordBytes += size;
254
+ records.push(record);
255
+ }
256
+ function placement(rect) {
257
+ const sized = rect.width > 0 && rect.height > 0;
258
+ return [
259
+ sized && (rect.right <= 0 || rect.bottom <= 0 || rect.left >= window.innerWidth || rect.top >= window.innerHeight),
260
+ !sized
261
+ ];
262
+ }
263
+ function forwardedClick(event, element) {
264
+ const labelForwarded = !!element && forwarded === element;
265
+ forwarded = void 0;
266
+ const path = event.composedPath();
267
+ const label = path.find(
268
+ (node) => node instanceof HTMLLabelElement
269
+ );
270
+ if (label?.control && label.control !== path[0]) {
271
+ forwarded = label.control;
272
+ setTimeout(() => {
273
+ forwarded = void 0;
274
+ }, 0);
275
+ }
276
+ return labelForwarded;
277
+ }
278
+ function clickPosition(element, rect, e, pressed) {
279
+ const [outside, sizeless] = placement(rect);
280
+ if (!pressed) {
281
+ otherPosition[0]++;
282
+ if (outside) otherPosition[1]++;
283
+ if (sizeless) otherPosition[2]++;
284
+ return;
285
+ }
286
+ const root = element.getRootNode();
287
+ const hit = (root instanceof ShadowRoot ? root : document).elementFromPoint(
288
+ e.clientX,
289
+ e.clientY
290
+ );
291
+ pointerPosition[0]++;
292
+ if (!hit || !element.contains(hit)) pointerPosition[1]++;
293
+ if (outside) pointerPosition[2]++;
294
+ if (sizeless) pointerPosition[3]++;
295
+ }
296
+ function countInput(control) {
297
+ if (inputCounts[0] >= 1e3) return;
298
+ const now = performance.now();
299
+ inputCounts[0]++;
300
+ if (!focused.has(control)) inputCounts[1]++;
301
+ if (!changed.has(control) && inputCounts[2] < 100) {
302
+ changed.add(control);
303
+ inputCounts[2]++;
304
+ }
305
+ if (now - lastInput >= 10) instant = [];
306
+ lastInput = now;
307
+ if (!instant.includes(control) && instant.length < 100)
308
+ instant.push(control);
309
+ if (instant.length > 1) {
310
+ for (const member of instant)
311
+ if (changed.has(member) && !together.has(member)) {
312
+ together.add(member);
313
+ inputCounts[3]++;
314
+ }
315
+ }
316
+ const [outside, sizeless] = placement(control.getBoundingClientRect());
317
+ if (outside) inputPosition[0]++;
318
+ if (sizeless) inputPosition[1]++;
319
+ }
320
+ function bound(value) {
321
+ return Math.max(-1e7, Math.min(1e7, Math.round(value)));
322
+ }
323
+ function probe() {
324
+ if (typeof PerformanceObserver === "undefined") return;
325
+ const watcher = new PerformanceObserver((list) => {
326
+ for (const entry of list.getEntriesByName(endpoint)) {
327
+ const request = entry;
328
+ if (request.initiatorType !== "fetch") continue;
329
+ watcher.disconnect();
330
+ if (!closed && request.requestStart > 0 && request.responseStart >= request.requestStart)
331
+ roundTrip = Math.min(
332
+ 3e4,
333
+ Math.round(request.responseStart - request.requestStart)
334
+ );
335
+ return;
336
+ }
337
+ });
338
+ roundTripWatcher = watcher;
339
+ watcher.observe({ type: "resource" });
340
+ void fetch(endpoint, {
341
+ method: "GET",
342
+ credentials: "omit",
343
+ mode: "cors",
344
+ cache: "no-store"
345
+ }).catch(() => {
346
+ });
347
+ }
348
+ function action() {
349
+ if (!closed && ++actions >= 100) finish("action-limit");
350
+ }
351
+ function resetKeys() {
352
+ keyDownAt = void 0;
353
+ keyFlight = void 0;
354
+ lastKeyUp = void 0;
355
+ outstandingKeys = 0;
356
+ keyOverlap = false;
357
+ }
358
+ function settleKeys() {
359
+ if (outstandingKeys > 0 && performance.now() - lastKeyEvent > 2e3)
360
+ resetKeys();
361
+ }
362
+ function refused(node, control) {
363
+ if (node.matches("[data-discover-sensitive], [contenteditable]"))
364
+ return true;
365
+ if (!(node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement || node instanceof HTMLSelectElement))
366
+ return false;
367
+ const autocomplete = node.getAttribute("autocomplete") ?? "";
368
+ const textField = node instanceof HTMLTextAreaElement || node instanceof HTMLInputElement && /^(text|search|email|tel|url)$/.test(node.type);
369
+ return node instanceof HTMLInputElement && !textField && !/^(button|checkbox|radio|range|number|submit|reset)$/.test(
370
+ node.type
371
+ ) || textField && control !== "key" || /password|cc-|payment|transaction|one-time|bday|birth|sex|health/i.test(
372
+ autocomplete
373
+ ) || // A reveal toggle turns a password field into a text field; its name or id still tells.
374
+ // Secret names fail closed: `code` also matches `postal_code`, `pin` also `shipping`.
375
+ /pass|pwd|otp|pin|cvc|cvv|code|card|ccnum|mfa|2fa|ssn|secret|token/i.test(
376
+ `${node.name} ${node.id}`
377
+ ) || // A field that asks for the visitor's details gives key timing only.
378
+ control !== "key" && (/^(email|tel)$/.test(node.type) || /email|tel|name|address|postal-code|country/i.test(autocomplete));
379
+ }
380
+ function target(event, control) {
381
+ const path = event.composedPath();
382
+ const element = path[0];
383
+ if (!(element instanceof HTMLElement) || element.ownerDocument !== document || element instanceof HTMLUnknownElement || element.localName.includes("-") || /^(article|aside|blockquote|body|div|footer|h[1-6]|header|main|nav|p|section|span)$/.test(
384
+ element.localName
385
+ ))
386
+ return void 0;
387
+ let reachesDocument = false;
388
+ for (const node of path) {
389
+ if (node === document) {
390
+ reachesDocument = true;
391
+ break;
392
+ }
393
+ if (node instanceof ShadowRoot) {
394
+ if (node.mode !== "open" || node.ownerDocument !== document)
395
+ return void 0;
396
+ continue;
397
+ }
398
+ if (!(node instanceof HTMLElement) || node.ownerDocument !== document || refused(node, control))
399
+ return void 0;
400
+ }
401
+ if (!reachesDocument) return void 0;
402
+ if (control && (!element.matches('[data-discover-nonsensitive="true"]') || !(element instanceof HTMLSelectElement || element instanceof HTMLButtonElement || element instanceof HTMLInputElement && /^(range|number|checkbox|radio)$/.test(element.type) || control === "key" && (element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement && /^(text|search|email|tel|url)$/.test(element.type)))))
403
+ return void 0;
404
+ return element;
405
+ }
406
+ function motion(event) {
407
+ if (!active()) return;
408
+ const e = event;
409
+ if (e.pointerType !== "mouse" && e.pointerType !== "pen") return;
410
+ const now = performance.now();
411
+ if (!event.composedPath().some((node) => node instanceof HTMLElement && refused(node)))
412
+ moved = true;
413
+ if (timing) {
414
+ lastMotion = now;
415
+ motionTimes.push(now);
416
+ if (motionTimes.length > 3) motionTimes.shift();
417
+ }
418
+ if (!target(event)) return;
419
+ if (now - lastSample < 1e3 / 30) {
420
+ drop(0);
421
+ return;
422
+ }
423
+ lastSample = now;
424
+ baseline = true;
425
+ add(
426
+ {
427
+ kind: "pointer",
428
+ x: Math.round(e.pageX),
429
+ y: Math.round(e.pageY),
430
+ at_ms: at(),
431
+ trusted: e.isTrusted
432
+ },
433
+ 0
434
+ );
435
+ }
436
+ function begin() {
437
+ if (closed || started || document.visibilityState !== "visible" || location.pathname !== route || Date.now() > issuedAt + 6e5)
438
+ return;
439
+ started = true;
440
+ start = Date.now();
441
+ startTick = performance.now();
442
+ scrollX = window.scrollX;
443
+ scrollY = window.scrollY;
444
+ rawScrollX = scrollX;
445
+ rawScrollY = scrollY;
446
+ timer = setTimeout(() => finish("deadline"), 3e4);
447
+ let focusedNow = document.activeElement;
448
+ while (focusedNow) {
449
+ focused.add(focusedNow);
450
+ focusedNow = focusedNow.shadowRoot?.activeElement ?? null;
451
+ }
452
+ if (timing) probe();
453
+ for (const name of [
454
+ "keydown",
455
+ "pointerdown",
456
+ "touchstart",
457
+ "wheel",
458
+ "beforeinput",
459
+ "input"
460
+ ])
461
+ listen(document, name, (event) => {
462
+ if (event.isTrusted && active()) inputObserved = true;
463
+ });
464
+ listen(document, "pointermove", (event) => {
465
+ const type = event.pointerType;
466
+ if (event.isTrusted && (type === "mouse" || type === "pen") && active())
467
+ inputObserved = true;
468
+ });
469
+ listen(document, "pointermove", motion);
470
+ listen(document, "pointerdown", (event) => {
471
+ const e = event;
472
+ const element = target(event);
473
+ pointerDown = active() && !!element && (e.pointerType === "mouse" || e.pointerType === "pen") && e.isPrimary;
474
+ const rect = pointerDown ? element?.getBoundingClientRect() : void 0;
475
+ downGeometry = rect ? [rect.left, rect.top, rect.width, rect.height] : void 0;
476
+ });
477
+ listen(document, "pointercancel", () => {
478
+ pointerDown = false;
479
+ downGeometry = void 0;
480
+ });
481
+ listen(document, "click", (event) => {
482
+ if (!active()) return;
483
+ const element = target(event);
484
+ const e = event;
485
+ const rect = element?.getBoundingClientRect();
486
+ const geometry = !!rect && !!downGeometry && rect.width > 0 && rect.height > 0 && rect.left === downGeometry[0] && rect.top === downGeometry[1] && rect.width === downGeometry[2] && rect.height === downGeometry[3];
487
+ const origin = pointerDown && e.detail > 0 && geometry;
488
+ const eligible = origin && baseline;
489
+ const pressed = pointerDown && e.detail > 0;
490
+ pointerDown = false;
491
+ downGeometry = void 0;
492
+ const labelForwarded = forwardedClick(event, element);
493
+ if (!element || !rect) return;
494
+ if (origin) {
495
+ counts.pointer_origin_clicks++;
496
+ if (!moved) counts.pointer_origin_clicks_without_motion++;
497
+ }
498
+ if (!labelForwarded) clickPosition(element, rect, e, pressed);
499
+ add(
500
+ {
501
+ kind: "click",
502
+ x: Math.round(e.pageX),
503
+ y: Math.round(e.pageY),
504
+ at_ms: at(),
505
+ trusted: e.isTrusted,
506
+ pointer_eligible: eligible,
507
+ approach_ms: timing && eligible && lastMotion !== void 0 ? Math.min(
508
+ 3e4,
509
+ Math.max(0, Math.round(performance.now() - lastMotion))
510
+ ) : null,
511
+ offset_x: eligible ? Math.round(
512
+ Math.max(
513
+ -1,
514
+ Math.min(1, (e.clientX - rect.left) / rect.width - 0.5)
515
+ ) * 1e3
516
+ ) : null,
517
+ offset_y: eligible ? Math.round(
518
+ Math.max(
519
+ -1,
520
+ Math.min(1, (e.clientY - rect.top) / rect.height - 0.5)
521
+ ) * 1e3
522
+ ) : null,
523
+ // Motion events in the 500 ms before the click, throttled and off-target ones
524
+ // included; 3 means 3 or more.
525
+ approach_samples: timing && eligible ? motionTimes.filter((at2) => performance.now() - at2 <= 500).length : null,
526
+ // Geometry only, page CSS px; no label, selector, text or element identity.
527
+ ...pathCapture ? {
528
+ target_box: {
529
+ x: bound(rect.left + window.scrollX),
530
+ y: bound(rect.top + window.scrollY),
531
+ w: bound(rect.width),
532
+ h: bound(rect.height)
533
+ }
534
+ } : {}
535
+ },
536
+ 0
537
+ );
538
+ action();
539
+ });
540
+ listen(document, "keydown", (event) => {
541
+ if (!active()) return;
542
+ settleKeys();
543
+ lastKeyEvent = performance.now();
544
+ const e = event;
545
+ if (!e.repeat) outstandingKeys = Math.min(101, outstandingKeys + 1);
546
+ if (!target(event, "key") || e.repeat || e.isComposing || e.keyCode === 229 || outstandingKeys > 1) {
547
+ keyDownAt = void 0;
548
+ keyOverlap = true;
549
+ lastKeyUp = void 0;
550
+ return;
551
+ }
552
+ if (keyOverlap) return;
553
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
554
+ lastKeyUp = void 0;
555
+ return;
556
+ }
557
+ const now = timing ? clock() : 0;
558
+ keyFlight = timing && lastKeyUp !== void 0 ? Math.min(3e4, Math.max(0, Math.round(now - lastKeyUp))) : void 0;
559
+ keyDownAt = now;
560
+ });
561
+ listen(document, "keyup", (event) => {
562
+ if (!active()) return;
563
+ settleKeys();
564
+ lastKeyEvent = performance.now();
565
+ outstandingKeys = Math.max(0, outstandingKeys - 1);
566
+ if (keyOverlap || outstandingKeys !== 0) {
567
+ if (outstandingKeys === 0) keyOverlap = false;
568
+ keyDownAt = void 0;
569
+ lastKeyUp = void 0;
570
+ return;
571
+ }
572
+ const pressedAt = keyDownAt;
573
+ keyDownAt = void 0;
574
+ const e = event;
575
+ if (pressedAt === void 0 || !target(event, "key") || e.isComposing || e.keyCode === 229) {
576
+ lastKeyUp = void 0;
577
+ return;
578
+ }
579
+ const now = timing ? clock() : 0;
580
+ const duration = timing ? Math.min(3e4, Math.max(0, Math.round(now - pressedAt))) : null;
581
+ const needed = Number(duration !== null) + Number(keyFlight !== void 0);
582
+ if (keyIntervals + needed > 128) {
583
+ drop(1);
584
+ lastKeyUp = void 0;
585
+ keyFlight = void 0;
586
+ action();
587
+ return;
588
+ }
589
+ keyIntervals += needed;
590
+ add(
591
+ {
592
+ kind: "key",
593
+ trusted: event.isTrusted,
594
+ dwell_ms: duration,
595
+ flight_ms: keyFlight ?? null
596
+ },
597
+ 1
598
+ );
599
+ lastKeyUp = timing ? now : void 0;
600
+ keyFlight = void 0;
601
+ action();
602
+ });
603
+ listen(document, "paste", (event) => {
604
+ if (active() && target(event, "input")) {
605
+ add({ kind: "paste", trusted: event.isTrusted }, 2);
606
+ action();
607
+ }
608
+ });
609
+ listen(document, "input", (event) => {
610
+ if (!active()) return;
611
+ const control = target(event, "key");
612
+ if (control) countInput(control);
613
+ if (!target(event, "input")) return;
614
+ const e = event;
615
+ if (e.inputType === "insertFromPaste") {
616
+ counts.paste_inputs = Math.min(100, counts.paste_inputs + 1);
617
+ return;
618
+ }
619
+ settleKeys();
620
+ if (outstandingKeys > 0 || e.isComposing || /Composition/.test(e.inputType))
621
+ return;
622
+ add({ kind: "input", trusted: event.isTrusted }, 2);
623
+ action();
624
+ });
625
+ listen(document, "scroll", (event) => {
626
+ if (!active() || event.target !== document && event.target !== document.documentElement)
627
+ return;
628
+ const now = timing ? clock() : performance.now();
629
+ if (lastRawScroll === void 0 || now - lastRawScroll >= 150) {
630
+ closeBurst();
631
+ counts.scroll_bursts++;
632
+ burstFromX = rawScrollX;
633
+ burstFromY = rawScrollY;
634
+ }
635
+ burstEvents++;
636
+ lastRawScroll = now;
637
+ rawScrollX = window.scrollX;
638
+ rawScrollY = window.scrollY;
639
+ if (lastScroll !== void 0 && now - lastScroll < 150) {
640
+ drop(3);
641
+ return;
642
+ }
643
+ const interval = timing && lastScroll !== void 0 ? Math.min(3e4, Math.max(0, Math.round(now - lastScroll))) : null;
644
+ const dx = Math.round(window.scrollX - scrollX);
645
+ const dy = Math.round(window.scrollY - scrollY);
646
+ scrollX = window.scrollX;
647
+ scrollY = window.scrollY;
648
+ lastScroll = now;
649
+ if (interval !== null && scrollIntervals >= 128) {
650
+ drop(3);
651
+ action();
652
+ return;
653
+ }
654
+ if (interval !== null) scrollIntervals++;
655
+ add(
656
+ {
657
+ kind: "scroll",
658
+ dx,
659
+ dy,
660
+ interval_ms: interval,
661
+ trusted: event.isTrusted
662
+ },
663
+ 3
664
+ );
665
+ action();
666
+ });
667
+ listen(document, "focusin", (event) => {
668
+ if (!active()) return;
669
+ resetKeys();
670
+ const origin = event.composedPath()[0];
671
+ if (origin) focused.add(origin);
672
+ if (target(event)) add({ kind: "focus", trusted: event.isTrusted }, 4);
673
+ });
674
+ listen(window, "blur", resetKeys);
675
+ listen(document, "touchmove", (event) => {
676
+ if (!active() || !target(event)) return;
677
+ const e = event;
678
+ if (e.touches.length !== 1) {
679
+ drop(5);
680
+ return;
681
+ }
682
+ const now = performance.now();
683
+ if (now - lastSample < 1e3 / 30) {
684
+ drop(5);
685
+ return;
686
+ }
687
+ lastSample = now;
688
+ const touch = e.touches[0];
689
+ if (!touch) return;
690
+ add(
691
+ {
692
+ kind: "touch",
693
+ x: Math.round(touch.pageX),
694
+ y: Math.round(touch.pageY),
695
+ at_ms: at(),
696
+ trusted: e.isTrusted,
697
+ pressure: touch.force > 0 && touch.force < 1 && touch.force !== 0.5 ? Math.round(touch.force * 1e3) : null,
698
+ radius_x: touch.radiusX > 1 ? Math.min(1e4, Math.round(touch.radiusX)) : null,
699
+ radius_y: touch.radiusY > 1 ? Math.min(1e4, Math.round(touch.radiusY)) : null
700
+ },
701
+ 5
702
+ );
703
+ });
704
+ listen(document, "touchend", (event) => {
705
+ if (active() && target(event) && event.touches.length === 0)
706
+ action();
707
+ });
708
+ observer = new MutationObserver(() => {
709
+ if (location.pathname !== route) finish("route-change");
710
+ });
711
+ observer.observe(document.documentElement, {
712
+ childList: true,
713
+ subtree: true
714
+ });
715
+ }
716
+ listen(window, "steadphast:behavioral-consent", (event) => {
717
+ const detail = event.detail;
718
+ if (detail?.enabled === false || detail?.revoked === true) {
719
+ discard();
720
+ return;
721
+ }
722
+ if (detail?.granted !== true) {
723
+ if (started) discard();
724
+ return;
725
+ }
726
+ begin();
727
+ });
728
+ listen(window, "steadphast:behavioral-disable", discard);
729
+ listen(window, "steadphast:behavioral-route", () => finish("route-change"));
730
+ listen(window, "popstate", () => finish("route-change"));
731
+ listen(document, "visibilitychange", () => {
732
+ if (document.visibilityState === "hidden") finish("hidden");
733
+ });
734
+ listen(window, "pagehide", () => finish("pagehide"));
735
+ listen(window, "pageshow", (event) => {
736
+ if (event.persisted) discard();
737
+ });
738
+ const expiry = setTimeout(
739
+ discard,
740
+ Math.max(0, issuedAt + 6e5 - Date.now())
741
+ );
742
+ if (notice) {
743
+ listen(document, "visibilitychange", () => {
744
+ if (document.visibilityState === "visible") begin();
745
+ });
746
+ begin();
747
+ }
748
+ window.dispatchEvent(new Event("steadphast:behavioral-ready"));
749
+ }
750
+
751
+ // src/collector/bundle.ts
752
+ var COLLECTOR_SOURCE = `(function(J,ue){var le=2e3,fe=1500,de=250,pe=500,me=Date.now(),ve=typeof performance<"u"?performance.now():0;function z(e,t){var a=typeof globalThis<"u"?globalThis:self,o=a.navigator,i={},f=[],r=null,S=!1,h=/^function (?:get |set )?[\\w$]*\\(\\) \\{\\s*\\[native code\\]\\s*\\}$/;function s(c,u){try{return c()}catch{return u}}function y(){S||(S=!0,clearTimeout(r),t(i))}function p(c,u){if(typeof u=="function"){var l=Function.prototype.toString,m=!1,E,x,W=!1,N=!1;try{h.test(l.call(u))||(m=!0),E=Reflect.ownKeys(u),(E.length!==2||E.indexOf("length")===-1||E.indexOf("name")===-1)&&(m=!0),x=Object.getOwnPropertyDescriptor(u,"name"),(!x||x.writable!==!1)&&(m=!0);try{new u}catch(b){W=b instanceof TypeError}W||(m=!0);try{Object.setPrototypeOf(u,u)}catch{N=!0}N||(m=!0,Object.setPrototypeOf(u,Function.prototype))}catch{m=!0}m&&f.push(c)}}function Ce(c,u){var l=c?Object.getOwnPropertyDescriptor(c.prototype,u):void 0;return l?l.get:void 0}function U(c,u){return c?c.prototype[u]:void 0}i.ua=s(()=>String(o.userAgent)),i.platform=s(()=>String(o.platform)),i.languages=s(()=>Array.prototype.slice.call(o.languages,0,8).map(String)),i.tz=s(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),i.cores=s(()=>o.hardwareConcurrency),i.memory=s(()=>o.deviceMemory),i.brands=s(()=>o.userAgentData.brands.map(c=>c.brand+" "+c.version)),i.webdriver=s(()=>o.webdriver),i.webdriver_own=s(()=>Object.prototype.hasOwnProperty.call(o,"webdriver")),i.headless_ua=s(()=>/HeadlessChrome|PhantomJS|SlimerJS/.test(o.userAgent)),i.clock={date_native:s(()=>h.test(Function.prototype.toString.call(Date.now))),perf_native:s(()=>h.test(Function.prototype.toString.call(a.performance.now)))},i.webgl=s(()=>{var c=e==="worker"?new OffscreenCanvas(8,8):a.document.createElement("canvas"),u=c.getContext("webgl")||c.getContext("webgl2");if(!u)return{ctx:!1};var l=u.getExtension("WEBGL_debug_renderer_info");return{vendor:l?u.getParameter(l.UNMASKED_VENDOR_WEBGL):void 0,renderer:l?u.getParameter(l.UNMASKED_RENDERER_WEBGL):void 0,ctx:!0}},{ctx:!1});var De=e==="worker"?a.WorkerNavigator:a.Navigator;p("Function.prototype.toString",Function.prototype.toString),p("Date.now",Date.now),p("performance.now",a.performance&&a.performance.now),["webdriver","plugins","languages","hardwareConcurrency","deviceMemory","platform","userAgent"].forEach(c=>{p((e==="worker"?"WorkerNavigator.":"Navigator.")+c+"#get",Ce(De,c))}),e!=="worker"&&(p("WebGLRenderingContext.getParameter",U(a.WebGLRenderingContext,"getParameter")),p("Permissions.query",U(a.Permissions,"query")),p("HTMLCanvasElement.toDataURL",U(a.HTMLCanvasElement,"toDataURL")),p("CanvasRenderingContext2D.getImageData",U(a.CanvasRenderingContext2D,"getImageData"))),e!=="worker"&&(i.plugins=s(()=>o.plugins.length),i.screen=s(()=>({w:a.screen.width,h:a.screen.height,dpr:a.devicePixelRatio,outer_zero:a.outerWidth===0||a.outerHeight===0}))),e==="main"&&(i.chrome=s(()=>typeof a.chrome=="object"&&a.chrome!==null),i.rtt=s(()=>o.connection.rtt),i.pdf_viewer=s(()=>o.pdfViewerEnabled),i.share=s(()=>typeof o.share=="function"),i.feature_major=Pe(a),i.os_fonts=s(()=>Re(a.document))),i.proto=f;var G=s(()=>o.userAgentData.getHighEntropyValues(["architecture","bitness","platformVersion","fullVersionList"]));return G&&typeof G.then=="function"?(r=setTimeout(y,300),G.then(c=>{i.uach={arch:c.architecture,bitness:c.bitness,platform_version:c.platformVersion,full_version_list:(c.fullVersionList||[]).map(u=>u.brand+" "+u.version)},y()},()=>{y()})):y(),()=>{S=!0,clearTimeout(r)};function Pe(c){for(var u=[[141,()=>typeof Math.sumPrecise=="function"],[140,()=>typeof Uint8Array.fromBase64=="function"],[136,()=>typeof RegExp.escape=="function"],[135,()=>typeof c.Float16Array=="function"],[134,()=>typeof Error.isError=="function"],[128,()=>typeof Promise.try=="function"],[126,()=>typeof URL.parse=="function"],[122,()=>typeof Set.prototype.union=="function"],[122,()=>typeof c.Iterator=="function"&&typeof c.Iterator.prototype.map=="function"],[121,()=>typeof Array.fromAsync=="function"],[120,()=>typeof URL.canParse=="function"],[119,()=>typeof Promise.withResolvers=="function"],[117,()=>typeof Object.groupBy=="function"],[110,()=>typeof Array.prototype.toSorted=="function"],[98,()=>typeof c.structuredClone=="function"]],l=0;l<u.length;l+=1)if(s(u[l][1],!1))return u[l][0];return 0}function Re(c){var u={mac:["Helvetica Neue","Menlo","Monaco","Apple Color Emoji","SF Pro","Geneva","Avenir"],win:["Segoe UI","Calibri","Consolas","Tahoma","Cambria","Candara"],linux:["DejaVu Sans","Liberation Sans","Ubuntu","Noto Sans","Cantarell","Liberation Mono"]},l=c.createElement("canvas"),m=l.getContext("2d"),E="mmmmmmmmmmlli WAVE 0123 @#%",x=["monospace","sans-serif","serif"],W=x.map(b=>(m.font="24px "+b,m.measureText(E).width)),N={};return Object.keys(u).forEach(b=>{var ce=0;u[b].forEach(Le=>{var Ne=x.some((Me,Te)=>(m.font="24px '"+Le+"', "+Me,m.measureText(E).width!==W[Te]));Ne&&(ce+=1)}),N[b]=ce}),N}}var n={v:1,nonce:J,t:{}},_=null,C=null,D=null,H=!1,P=!1,w=!1,K=!1,q=0,Z=0,$=0,Y=!1,R=null,A=null,M=null,d=null,F=null,Q=[],X=[],V=null,ee,re=v(()=>document.currentScript.nonce,""),te=/^[A-Za-z0-9+/_-]+={0,2}$/.test(re)?re:J,ge=document.scripts.length,he=document.styleSheets.length,ne=v(()=>Object.getOwnPropertyNames(window),[]);function v(e,t){try{return e()}catch{return t}}function T(e,t){Q.push(setTimeout(()=>{w||e()},t))}function O(e,t,a,o){e.addEventListener(t,a,o),X.push([e,t,a,o])}function we(){Q.forEach(clearTimeout),X.forEach(e=>{e[0].removeEventListener(e[1],e[2],e[3])}),V!==null&&v(()=>cancelAnimationFrame(V)),R&&R.disconnect(),F&&F(),A&&A.terminate(),M&&URL.revokeObjectURL(M),d&&d.parentNode&&d.parentNode.removeChild(d)}var ye=/pptr:|__puppeteer_evaluation_script__|__pyppeteer_evaluation_script__|puppeteer-extra|playwright|__playwright_utility_world__|utility|selenium|webdriver/i,be=/cdc_|selenium|webdriver|__nightmare|callPhantom|domAutomationController|__pw|__playwright|_phantom|__fxdriver|__driver|__lastWatirAlert|__webdriver_script|puppeteer|_Selenium_IDE_Recorder/i,I=[];function j(e){var t=v(()=>String(new Error().stack||""),"");ye.test(t)&&I.indexOf(e)===-1&&I.push(e)}j("sync"),v(()=>{var e={};Object.defineProperty(e,"marker",{get:()=>(j("getter"),0)}),e.marker}),T(()=>{j("timeout")},0),v(()=>{V=requestAnimationFrame(()=>{j("raf")})}),v(()=>{var e=new Proxy({},{ownKeys:()=>(q+=1,[])});console.debug(e)}),v(()=>{R=new MutationObserver(e=>{Z+=e.length}),R.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),T(()=>{R.disconnect()},pe)}),O(window,"click",e=>{e.isTrusted===!1&&($+=1)},!0),["keydown","pointerdown","mousedown","touchstart","input"].forEach(e=>{O(window,e,t=>{t.isTrusted&&(Y=!0)},!0)}),F=z("main",e=>{w||(_=e,k())});var ae="("+z.toString()+")";if(typeof Worker!="function"||typeof Blob!="function"||typeof URL.createObjectURL!="function")H=!0;else try{var _e="var s=Date.now()-"+Date.now()+";"+ae+'("worker",function(r){r.started=s;r.clock_delta=Date.now();postMessage(r)})';M=URL.createObjectURL(new Blob([_e],{type:"text/javascript"})),A=new Worker(M),A.onmessage=e=>{if(!w){var t=e.data;t.clock_delta-=Date.now(),t.started=Math.max(0,t.started),C=t,A.terminate(),k()}},A.onerror=()=>{w||(P=!0,A.terminate(),k())}}catch{P=!0}try{d=document.createElement("iframe"),d.setAttribute("sandbox","allow-scripts"),d.style.display="none",d.setAttribute("aria-hidden","true");var Ae='var b=document.createElement("script");b.text="window.__sp_t0_csp=1";document.head.appendChild(b);var bypass=window.__sp_t0_csp===1;delete window.__sp_t0_csp;b.parentNode.removeChild(b);'+ae+'("iframe",function(r){r.clock_delta=Date.now();parent.postMessage({__sp_t0:r,csp_bypass:bypass},"*")})';d.srcdoc=\`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-\`+te+\`'"><script nonce="\`+te+'">'+Ae+"<\\/script>",O(window,"message",e=>{if(!(w||e.source!==d.contentWindow||!e.data||!e.data.__sp_t0)){var t=e.data.__sp_t0;t.clock_delta-=Date.now(),D=t,typeof e.data.csp_bypass=="boolean"&&(ee=e.data.csp_bypass),k()}}),d.onerror=()=>{w||(P=!0,k())},(document.body||document.documentElement).appendChild(d)}catch{P=!0}function oe(){K=!0,T(L,de),k()}document.readyState==="loading"?O(window,"DOMContentLoaded",oe):oe(),T(L,fe),O(window,"pagehide",()=>L("early-exit"));function ie(){document.visibilityState==="hidden"&&L("background-tab")}O(document,"visibilitychange",ie),ie();function k(){K&&_&&C&&D&&L()}function Se(e,t,a){var o=[];if(!e)return o;function i(r,S,h){r&&Object.keys(h).forEach(s=>{var y=h[s](e),p=h[s](r);y!=null&&p!==void 0&&p!==null&&JSON.stringify(y)!==JSON.stringify(p)&&o.push(S+s)})}var f={platform:r=>r.platform,languages:r=>r.languages,hardwareConcurrency:r=>r.cores,deviceMemory:r=>r.memory,brands:r=>r.brands};return i(t,"A7.",f),i(t,"",{"A10.vendor":r=>r.webgl&&r.webgl.vendor,"A10.renderer":r=>r.webgl&&r.webgl.renderer,"A3w.userAgent":r=>r.ua,"A29w.timeZone":r=>r.tz,"A4w.architecture":r=>r.uach&&r.uach.arch,"A4w.bitness":r=>r.uach&&r.uach.bitness,"A4w.platformVersion":r=>r.uach&&r.uach.platform_version,"A4w.fullVersionList":r=>r.uach&&r.uach.full_version_list}),i(a,"A8.",f),i(a,"",{"A8.userAgent":r=>r.ua,"A8.webdriver":r=>r.webdriver,"A8.timeZone":r=>r.tz,"A8.plugins":r=>r.plugins,"A8.dpr":r=>r.screen&&r.screen.dpr,"A8.screenW":r=>r.screen&&r.screen.w,"A8.renderer":r=>r.webgl&&r.webgl.renderer}),o}function se(e){return!e||!_||["ua","uach","webgl"].forEach(t=>{JSON.stringify(e[t])===JSON.stringify(_[t])&&delete e[t]}),e}function B(e){if(e){var t=e.proto;return delete e.proto,t}}function Ee(){var e=v(()=>{var f=Object.getOwnPropertyNames(window);return f.filter(r=>ne.indexOf(r)===-1)},[]),t=v(()=>ne.concat(e,Object.getOwnPropertyNames(document)).filter(f=>be.test(f)),[]),a=B(_),o=B(C),i=B(D);n.t.exec=Math.max(0,Math.round(ve)),n.t.sent=Math.max(0,Date.now()-me),n.main=_||void 0,n.worker=se(C)||void 0,n.iframe=se(D)||void 0,Oe(),n.proto={main:a||[],worker:o,iframe:i},n.globals={late:e.slice(0,32),automation:t.slice(0,16)},n.markers={stack:I,console_trap:q,csp_bypass:ee},n.dom={mutations_500:Z,sheets_added:Math.max(0,document.styleSheets.length-he),scripts_added:Math.max(0,document.scripts.length-ge)},n.events={untrusted_clicks:$,any_input:Y}}function Oe(){n.main&&n.main.uach&&!(n.worker&&n.worker.uach)&&delete n.main.uach.full_version_list}function ke(e){for(var t=0,a=0;a<e.length;a+=1){var o=e.charCodeAt(a);o<128?t+=1:o<2048?t+=2:o>=55296&&o<=56319?(t+=4,a+=1):t+=3}return t}function g(e,t){n[e]&&delete n[e][t]}function xe(){var e="compared",t="input";function a(){return n.xrealm=Se(n.main,n.worker,n.iframe),JSON.stringify(n)}for(var o=a(),i=[[e,()=>{["main","worker","iframe"].forEach(s=>{n[s]&&n[s].uach&&delete n[s].uach.full_version_list})}],[t,()=>{n.globals.late=n.globals.late.slice(0,8)}],[e,()=>g("iframe","uach")],[e,()=>g("worker","uach")],[e,()=>g("main","uach")],[e,()=>g("iframe","webgl")],[e,()=>g("worker","webgl")],[e,()=>g("iframe","ua")],[e,()=>g("worker","ua")],[t,()=>{n.proto.main=n.proto.main.slice(0,4)}],[t,()=>delete n.iframe],[t,()=>delete n.worker],[t,()=>g("main","webgl")],[t,()=>g("main","ua")],[t,()=>delete n.globals],[t,()=>delete n.main],[t,()=>delete n.proto]],f=0;f<i.length&&ke(o)>le;f+=1){var r=o,S=JSON.stringify(n.xrealm);i[f][1](),o=a();var h=o!==r&&(i[f][0]===t||JSON.stringify(n.xrealm)!==S);h&&n.availability==="available"&&(n.availability="insufficient-observation",o=a())}return o}function L(e){if(!w){w=!0,n.availability=e||(document.visibilityState==="hidden"?"background-tab":H?"unsupported-api":P?"script-failure":_&&C&&D?"available":"insufficient-observation"),we(),Ee();var t=xe();v(()=>{fetch(ue,{method:"POST",body:t,keepalive:!0,credentials:"omit",headers:{"content-type":"text/plain"}}).catch(()=>{})})}}})`;
753
+
754
+ // ../connector-core/src/api-environment.ts
755
+ var STEADPHAST_API_KEY_ENV_VAR = "STEADPHAST_API_KEY";
756
+ var LEGACY_DISCOVER_API_KEY_ENV_VAR = "DISCOVER_API_KEY";
757
+ function resolveApiEnvironmentValue(canonicalValue, legacyValue) {
758
+ return canonicalValue ?? legacyValue;
759
+ }
760
+
761
+ // src/config.ts
762
+ var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
763
+ var BEACON_PATHNAME = "/v1/client/t0";
764
+ var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
765
+ var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
766
+ var BEHAVIORAL_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}behavioral`;
767
+ var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
768
+ var DiscoverConfigError = class extends TypeError {
769
+ name = "DiscoverConfigError";
770
+ };
771
+ function validateApiKeyEnvVar(apiKeyEnvVar) {
772
+ if (apiKeyEnvVar?.startsWith("NEXT_PUBLIC_")) {
773
+ throw new DiscoverConfigError(
774
+ "Steadphast connector apiKeyEnvVar must reference a server-only environment variable."
775
+ );
776
+ }
777
+ }
778
+ function resolveProductionIngestUrl(apiUrl) {
779
+ const url = parseStrictUrl(apiUrl, "apiUrl");
780
+ if (url.protocol !== "https:") {
781
+ throw new DiscoverConfigError(
782
+ "Steadphast connector apiUrl must use the https scheme."
783
+ );
784
+ }
785
+ if (url.pathname === LEGACY_CANONICAL_INGEST_PATHNAME) {
786
+ throw new DiscoverConfigError(
787
+ `Steadphast connector apiUrl must not target the canonical-event ingest route; use the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
788
+ );
789
+ }
790
+ if (url.pathname !== "/" && url.pathname !== ENVELOPE_INGEST_PATHNAME) {
791
+ throw new DiscoverConfigError(
792
+ `Steadphast connector apiUrl must be the Discover API origin or the exact ${ENVELOPE_INGEST_PATHNAME} envelope ingest URL.`
793
+ );
794
+ }
795
+ return `${url.origin}${ENVELOPE_INGEST_PATHNAME}`;
796
+ }
797
+ function parseStrictUrl(value, setting) {
798
+ if (typeof value !== "string" || value.length === 0) {
799
+ throw new DiscoverConfigError(
800
+ `Steadphast connector ${setting} must be a non-empty absolute URL string.`
801
+ );
802
+ }
803
+ if (value.includes("?") || value.includes("#")) {
804
+ throw new DiscoverConfigError(
805
+ `Steadphast connector ${setting} must not contain a query or fragment.`
806
+ );
807
+ }
808
+ if (value.includes("@")) {
809
+ throw new DiscoverConfigError(
810
+ `Steadphast connector ${setting} must not contain userinfo.`
811
+ );
812
+ }
813
+ let url;
814
+ try {
815
+ url = new URL(value);
816
+ } catch {
817
+ throw new DiscoverConfigError(
818
+ `Steadphast connector ${setting} must be an absolute URL.`
819
+ );
820
+ }
821
+ if (url.hostname.length === 0) {
822
+ throw new DiscoverConfigError(
823
+ `Steadphast connector ${setting} must contain a host.`
824
+ );
825
+ }
826
+ if (url.username.length > 0 || url.password.length > 0) {
827
+ throw new DiscoverConfigError(
828
+ `Steadphast connector ${setting} must not contain userinfo.`
829
+ );
830
+ }
831
+ return url;
832
+ }
833
+ function resolveApiKey(customEnvVar) {
834
+ const runtime = globalThis;
835
+ const env = runtime.process?.env;
836
+ return customEnvVar !== void 0 ? env?.[customEnvVar] : resolveApiEnvironmentValue(
837
+ env?.[STEADPHAST_API_KEY_ENV_VAR],
838
+ env?.[LEGACY_DISCOVER_API_KEY_ENV_VAR]
839
+ );
840
+ }
841
+
842
+ // src/nonce.ts
843
+ var LAYOUT_VERSION = 1;
844
+ var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
845
+ var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
846
+ var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
847
+ var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
848
+ var T1_KEY_SALT = "steadphast-discover/client-t1/v1/salt";
849
+ var T1_KEY_INFO = "steadphast-discover/client-t1/v1";
850
+ var T1_RENDER_DOMAIN = "steadphast-discover/behavioral-render/v1";
851
+ var MAX_RID_BYTES = 512;
852
+ var MAX_KEY_ID_BYTES = 64;
853
+ var TAG_BYTES = 32;
854
+ var UTF8 = new TextEncoder();
855
+ function parseApiKey(apiKey) {
856
+ const separator = apiKey.indexOf(".");
857
+ if (separator <= 0 || separator === apiKey.length - 1) {
858
+ return void 0;
859
+ }
860
+ const keyId = apiKey.slice(0, separator);
861
+ const secret = apiKey.slice(separator + 1);
862
+ if (UTF8.encode(keyId).byteLength > MAX_KEY_ID_BYTES) {
863
+ return void 0;
864
+ }
865
+ return { keyId, secret };
866
+ }
867
+ function createNonceMinter(apiKey) {
868
+ const parsed = parseApiKey(apiKey);
869
+ if (parsed === void 0) {
870
+ return void 0;
871
+ }
872
+ const keyIdBytes = utf8(parsed.keyId);
873
+ let nonceKey;
874
+ let t1Key;
875
+ return {
876
+ async mintBehavioralContext(context) {
877
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
878
+ const header = utf8(JSON.stringify(context));
879
+ const tag = new Uint8Array(
880
+ await crypto.subtle.sign(
881
+ "HMAC",
882
+ await t1Key,
883
+ concat(utf8(T1_RENDER_DOMAIN), header)
884
+ )
885
+ );
886
+ const wire = bytes(header.byteLength + TAG_BYTES);
887
+ wire.set(header);
888
+ wire.set(tag, header.byteLength);
889
+ return base64UrlNoPad(wire);
890
+ },
891
+ async behavioralFromContext(context, policy) {
892
+ if (context.length > 2048 || policy.mode !== "own") return void 0;
893
+ try {
894
+ const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
895
+ const wire = bytes(binary.length);
896
+ for (let i = 0; i < binary.length; i++) wire[i] = binary.charCodeAt(i);
897
+ if (wire.length <= TAG_BYTES) return void 0;
898
+ const header = wire.subarray(0, -TAG_BYTES);
899
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
900
+ if (!await crypto.subtle.verify(
901
+ "HMAC",
902
+ await t1Key,
903
+ wire.subarray(-TAG_BYTES),
904
+ concat(utf8(T1_RENDER_DOMAIN), header)
905
+ ))
906
+ return void 0;
907
+ const input = JSON.parse(
908
+ new TextDecoder().decode(header)
909
+ );
910
+ if (Date.now() - input.issued_at_ms > 6e5 || input.issued_at_ms > Date.now() + 3e4)
911
+ return void 0;
912
+ const binding = utf8(
913
+ JSON.stringify({
914
+ version: 1,
915
+ key_id: parsed.keyId,
916
+ source: input.source,
917
+ rid: input.rid,
918
+ site: input.site,
919
+ issued_at_ms: input.issued_at_ms,
920
+ expires_at_ms: input.issued_at_ms + 6e5,
921
+ revision: policy.revision,
922
+ timing_enabled: policy.timing_enabled
923
+ })
924
+ );
925
+ const tag = new Uint8Array(
926
+ await crypto.subtle.sign("HMAC", await t1Key, binding)
927
+ );
928
+ const token = bytes(binding.byteLength + TAG_BYTES);
929
+ token.set(binding);
930
+ token.set(tag, binding.byteLength);
931
+ return {
932
+ nonce: base64UrlNoPad(token),
933
+ path: input.path,
934
+ issuedAt: input.issued_at_ms
935
+ };
936
+ } catch {
937
+ return void 0;
938
+ }
939
+ },
940
+ async mintRenderContext(rid, servedAtMs) {
941
+ const header = encodeHeader(rid, servedAtMs, keyIdBytes);
942
+ if (header === void 0) return void 0;
943
+ nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
944
+ const tag = new Uint8Array(
945
+ await crypto.subtle.sign(
946
+ "HMAC",
947
+ await nonceKey,
948
+ concat(utf8(RENDER_CONTEXT_DOMAIN), header)
949
+ )
950
+ );
951
+ const context = bytes(header.byteLength + TAG_BYTES);
952
+ context.set(header);
953
+ context.set(tag, header.byteLength);
954
+ return base64UrlNoPad(context);
955
+ },
956
+ async nonceFromRenderContext(context) {
957
+ if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
958
+ return void 0;
959
+ }
960
+ let decoded;
961
+ try {
962
+ const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
963
+ decoded = bytes(binary.length);
964
+ for (let i = 0; i < binary.length; i++)
965
+ decoded[i] = binary.charCodeAt(i);
966
+ } catch {
967
+ return void 0;
968
+ }
969
+ if (decoded.byteLength <= TAG_BYTES) return void 0;
970
+ const header = decoded.subarray(0, -TAG_BYTES);
971
+ nonceKey ??= deriveNonceKey(parsed, keyIdBytes);
972
+ if (!await crypto.subtle.verify(
973
+ "HMAC",
974
+ await nonceKey,
975
+ decoded.subarray(-TAG_BYTES),
976
+ concat(utf8(RENDER_CONTEXT_DOMAIN), header)
977
+ ))
978
+ return void 0;
979
+ const tag = new Uint8Array(
980
+ await crypto.subtle.sign("HMAC", await nonceKey, header)
981
+ );
982
+ decoded.set(tag, header.byteLength);
983
+ return base64UrlNoPad(decoded);
984
+ }
985
+ };
986
+ }
987
+ function encodeHeader(rid, servedAtMs, keyIdBytes) {
988
+ const ridBytes = utf8(rid);
989
+ if (ridBytes.byteLength === 0 || ridBytes.byteLength > MAX_RID_BYTES || !Number.isSafeInteger(servedAtMs) || servedAtMs < 0) {
990
+ return void 0;
991
+ }
992
+ const header = bytes(
993
+ 1 + 2 + ridBytes.byteLength + 8 + 1 + keyIdBytes.byteLength
994
+ );
995
+ const view = new DataView(header.buffer);
996
+ let offset = 0;
997
+ header[offset] = LAYOUT_VERSION;
998
+ offset += 1;
999
+ view.setUint16(offset, ridBytes.byteLength);
1000
+ offset += 2;
1001
+ header.set(ridBytes, offset);
1002
+ offset += ridBytes.byteLength;
1003
+ view.setBigUint64(offset, BigInt(servedAtMs));
1004
+ offset += 8;
1005
+ header[offset] = keyIdBytes.byteLength;
1006
+ offset += 1;
1007
+ header.set(keyIdBytes, offset);
1008
+ return header;
1009
+ }
1010
+ async function deriveNonceKey(parsed, keyIdBytes, salt = NONCE_KEY_SALT, info = NONCE_KEY_INFO) {
1011
+ const secretKey = await crypto.subtle.importKey(
1012
+ "raw",
1013
+ utf8(parsed.secret),
1014
+ { name: "HMAC", hash: "SHA-256" },
1015
+ false,
1016
+ ["sign"]
1017
+ );
1018
+ const ikm = await crypto.subtle.sign(
1019
+ "HMAC",
1020
+ secretKey,
1021
+ concat(utf8(API_KEY_VERIFIER_DOMAIN), keyIdBytes)
1022
+ );
1023
+ const hkdfKey = await crypto.subtle.importKey("raw", ikm, "HKDF", false, [
1024
+ "deriveBits"
1025
+ ]);
1026
+ const nonceKeyBits = await crypto.subtle.deriveBits(
1027
+ {
1028
+ name: "HKDF",
1029
+ hash: "SHA-256",
1030
+ salt: utf8(salt),
1031
+ info: concat(utf8(info), keyIdBytes)
1032
+ },
1033
+ hkdfKey,
1034
+ TAG_BYTES * 8
1035
+ );
1036
+ return crypto.subtle.importKey(
1037
+ "raw",
1038
+ nonceKeyBits,
1039
+ { name: "HMAC", hash: "SHA-256" },
1040
+ false,
1041
+ ["sign", "verify"]
1042
+ );
1043
+ }
1044
+ function bytes(length) {
1045
+ return new Uint8Array(new ArrayBuffer(length));
1046
+ }
1047
+ function utf8(text) {
1048
+ return UTF8.encode(text);
1049
+ }
1050
+ function concat(prefix, suffix) {
1051
+ const out = bytes(prefix.byteLength + 1 + suffix.byteLength);
1052
+ out.set(prefix, 0);
1053
+ out[prefix.byteLength] = 0;
1054
+ out.set(suffix, prefix.byteLength + 1);
1055
+ return out;
1056
+ }
1057
+ function base64UrlNoPad(bytes2) {
1058
+ let binary = "";
1059
+ for (const byte of bytes2) {
1060
+ binary += String.fromCharCode(byte);
1061
+ }
1062
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1063
+ }
1064
+ var NonceMinterCache = class {
1065
+ #apiKey;
1066
+ #minter;
1067
+ for(apiKey) {
1068
+ if (this.#apiKey !== apiKey) {
1069
+ this.#apiKey = apiKey;
1070
+ this.#minter = createNonceMinter(apiKey);
1071
+ }
1072
+ return this.#minter;
1073
+ }
1074
+ };
1075
+
1076
+ // src/collector-render.ts
1077
+ var minters = new NonceMinterCache();
1078
+ function collectorScript(nonce, endpoint) {
1079
+ const embed = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
1080
+ return `${COLLECTOR_SOURCE}(${embed(nonce)},${embed(endpoint)});`;
1081
+ }
1082
+ async function renderCollector(config, endpoint, cspNonce) {
1083
+ if (config.collector === false || config.collector !== true && (config.behavioral?.mode ?? "own") !== "own")
1084
+ return null;
1085
+ validateApiKeyEnvVar(config.apiKeyEnvVar);
1086
+ const requestHeaders = await headers();
1087
+ const context = requestHeaders.get(COLLECTOR_CONTEXT_HEADER);
1088
+ const behavioralContext = requestHeaders.get(BEHAVIORAL_CONTEXT_HEADER);
1089
+ if (context === null && behavioralContext === null) return null;
1090
+ const apiKey = resolveApiKey(config.apiKeyEnvVar);
1091
+ if (apiKey === void 0) return null;
1092
+ const minter = minters.for(apiKey);
1093
+ if (minter === void 0) return null;
1094
+ const nonce = context === null ? void 0 : await minter.nonceFromRenderContext(context);
1095
+ let script = config.collector === true && nonce !== void 0 ? collectorScript(nonce, endpoint) : "";
1096
+ if ((config.behavioral?.mode ?? "own") === "own" && behavioralContext !== null) {
1097
+ try {
1098
+ const response = await fetch(
1099
+ new URL("/v1/connectors/nextjs/behavioral-policy", endpoint),
1100
+ {
1101
+ headers: { authorization: `Bearer ${apiKey}` },
1102
+ cache: "no-store",
1103
+ signal: AbortSignal.timeout(250)
1104
+ }
1105
+ );
1106
+ const policy = await response.json();
1107
+ if (response.ok && policy.mode === "own" && typeof policy.timing_enabled === "boolean" && Number.isInteger(policy.revision) && policy.revision >= 0 && policy.revision <= 4294967295) {
1108
+ const timing = config.behavioral?.timing === true && policy.timing_enabled;
1109
+ const binding = await minter.behavioralFromContext(behavioralContext, {
1110
+ ...policy,
1111
+ timing_enabled: timing
1112
+ });
1113
+ if (binding && config.behavioral?.routes?.includes(binding.path)) {
1114
+ const args = JSON.stringify([
1115
+ binding.nonce,
1116
+ new URL("/v1/client/t1", endpoint).href,
1117
+ timing,
1118
+ binding.issuedAt,
1119
+ binding.path,
1120
+ // No prompt only when both the deployed site and the workspace say "notice".
1121
+ config.behavioral.consentBasis === "notice" && policy.consent_basis === "notice",
1122
+ // Target boxes only when both the site and the workspace turn path capture on; a
1123
+ // policy without the field (a server before path capture) reads as off.
1124
+ config.behavioral.pathCapture === true && "path_capture_enabled" in policy && policy.path_capture_enabled === true
1125
+ ]).replace(/</g, "\\u003c");
1126
+ script += `;(${behavioralCollector.toString()})(...${args});`;
1127
+ }
1128
+ }
1129
+ } catch {
1130
+ }
1131
+ }
1132
+ if (script === "") return null;
1133
+ return createElement("script", {
1134
+ nonce: cspNonce ?? nonce,
1135
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: package-owned collector with JSON-encoded, script-escaped arguments; no visitor nonce or destination is used.
1136
+ dangerouslySetInnerHTML: { __html: script }
1137
+ });
1138
+ }
1139
+
1140
+ // src/server.ts
1141
+ async function DiscoverCollector(props = {}) {
1142
+ if (!props.config || props.config.collector === false || props.config.collector !== true && ((props.config.behavioral?.mode ?? "own") !== "own" || !props.config.behavioral?.routes?.length))
1143
+ return null;
1144
+ const endpoint = `${new URL(resolveProductionIngestUrl(props.config.apiUrl)).origin}${BEACON_PATHNAME}`;
1145
+ return renderCollector(props.config, endpoint, props.nonce);
1146
+ }
1147
+ export {
1148
+ DiscoverCollector
1149
+ };