@seaproof/core 0.1.0-beta.1 → 0.1.0-beta.2

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/README.md CHANGED
@@ -55,6 +55,17 @@ attached to reports. With a key in a production-mode environment, neither happen
55
55
  `useSeaproof().open()`. You can override this with `mode: "tester" | "production"` and
56
56
  `<FeedbackWidget launcher={true} />`.
57
57
 
58
+ ### Tester sign-in and Do it now
59
+
60
+ With a test or staging key, the test strip at the top of the widget offers **Sign in as
61
+ tester**. The tester enters their own e-mail address and the six-digit code Seaproof sends to
62
+ it, so the team knows who reported even on a shared test account. The session is kept in the
63
+ browser for 30 days, and the strip shows the tester's name and group with **Sign out**. Testers
64
+ in a group that may use the fast track also get a **Do it now** checkbox, for the types their
65
+ group may use (`canFastTrackType(tester, type)`). Who may sign in, and what each group may do, is set up under **Reporters** in the
66
+ admin; see [fast track](../../docs/fast-track.md). Production keys never show sign-in or send a
67
+ session.
68
+
58
69
  ### Feedback button placement
59
70
 
60
71
  In **Project Settings → Feedback button**, choose the built-in button's position, text and
@@ -84,10 +95,20 @@ createSeaproof({
84
95
  apiKey,
85
96
  diagnostics: { console: true, network: true, errors: true }, // or false
86
97
  includeDiagnostics: true, // send also in production
87
- reportCrashes: true, // report uncaught errors on their own
98
+ reportErrors: true, // errors to the Errors page, also in production
88
99
  });
89
100
  ```
90
101
 
102
+ ### Errors
103
+
104
+ Uncaught errors and unhandled rejections go to the project's **Errors** page, grouped by problem
105
+ and linked to reports sent in the same page load. They are on by default for test keys and off for
106
+ production keys; `reportErrors: true` or `false` decides yourself. Until the key's environment is
107
+ known, errors wait. Send errors your app catches with `client.captureException(error, { fingerprint, context })`.
108
+ `client.sessionId` is the id that links reports and errors. `reportCrashes` is deprecated: it turns
109
+ on `reportErrors`, and errors no longer become inbox reports. See
110
+ [Errors in context](https://seaproof.io/docs/error-tracking.md).
111
+
91
112
  ## Styling
92
113
 
93
114
  You restyle the widget with CSS variables. Set them on `:root` or on any ancestor of the
@@ -117,6 +138,9 @@ A colour and logo set under **Branding** in the Seaproof admin are used without
117
138
  the colour fills in when you have not set `--seaproof-primary`, and the logo sits at the top of
118
139
  the panel (`.seaproof-logo`). Turn both off with `branding: false` in the client options.
119
140
 
141
+ On the Free and Team plans, a small "Powered by seaproof" link sits at the bottom of the panel
142
+ (`.seaproof-powered`). The plan decides it on the server; Business and Enterprise leave it out.
143
+
120
144
  For anything else, you can target the stable classes `seaproof-launcher`, `seaproof-backdrop`,
121
145
  `seaproof-panel`, `seaproof-type`, `seaproof-tabs`, `seaproof-footer`, `seaproof-primary` and
122
146
  `seaproof-error`. The built-in
package/dist/index.cjs CHANGED
@@ -27,20 +27,28 @@ __export(index_exports, {
27
27
  ScreenRecorder: () => ScreenRecorder,
28
28
  SeaproofError: () => SeaproofError,
29
29
  browserContext: () => browserContext,
30
+ canFastTrackType: () => canFastTrackType,
30
31
  canRecordScreen: () => canRecordScreen,
31
32
  captureScreenshot: () => captureScreenshot,
33
+ captureScreenshotWithFrame: () => captureScreenshotWithFrame,
32
34
  createSeaproof: () => createSeaproof,
33
35
  defaultStorage: () => defaultStorage,
36
+ describeElement: () => describeElement,
34
37
  describeError: () => describeError,
38
+ drawPins: () => drawPins,
39
+ elementAt: () => elementAt,
35
40
  excludedFromScreenshot: () => excludedFromScreenshot,
36
41
  installCapture: () => installCapture,
42
+ nearestPoint: () => nearestPoint,
37
43
  newConversationId: () => newConversationId,
44
+ pinLabel: () => pinLabel,
45
+ pinMessage: () => pinMessage,
38
46
  redactUrl: () => redactUrl
39
47
  });
40
48
  module.exports = __toCommonJS(index_exports);
41
49
 
42
50
  // src/version.ts
43
- var SDK_VERSION = "0.1.0-beta.1";
51
+ var SDK_VERSION = "0.1.0-beta.2";
44
52
 
45
53
  // src/context.ts
46
54
  function browserContext() {
@@ -246,6 +254,113 @@ function describeError(error) {
246
254
  return error instanceof Error ? error.message : String(error);
247
255
  }
248
256
 
257
+ // src/errorReporter.ts
258
+ var MAX_BATCH = 20;
259
+ var MAX_PENDING = 50;
260
+ var MAX_PER_PAGE = 100;
261
+ var MAX_PER_PROBLEM = 10;
262
+ var MAX_ATTEMPTS = 4;
263
+ var MAX_BREADCRUMBS = 30;
264
+ var ErrorReporter = class {
265
+ constructor(options) {
266
+ this.options = options;
267
+ }
268
+ options;
269
+ pending = [];
270
+ perProblem = /* @__PURE__ */ new Map();
271
+ total = 0;
272
+ timer;
273
+ sending = false;
274
+ attempts = 0;
275
+ /** Events waiting, for tests and `flush`. */
276
+ get size() {
277
+ return this.pending.length;
278
+ }
279
+ add(event) {
280
+ if (this.options.enabled() === false) return;
281
+ const key = event.fingerprint ?? `${event.type}|${event.message}|${firstFrame(event.stack)}`;
282
+ const seen = this.perProblem.get(key) ?? 0;
283
+ if (this.total >= MAX_PER_PAGE || seen >= MAX_PER_PROBLEM) return;
284
+ this.perProblem.set(key, seen + 1);
285
+ this.total++;
286
+ this.pending.push(event);
287
+ if (this.pending.length > MAX_PENDING) this.pending.splice(0, this.pending.length - MAX_PENDING);
288
+ this.schedule(this.options.delayMs ?? 1e3);
289
+ }
290
+ /** Call when the environment becomes known: sends what waited, or forgets it. */
291
+ decided() {
292
+ if (this.options.enabled() === false) this.pending = [];
293
+ else this.schedule(0);
294
+ }
295
+ /** Sends what is waiting now. With `keepalive` the request outlives the page, for `pagehide`. */
296
+ async flush(keepalive = false) {
297
+ if (this.timer !== void 0) clearTimeout(this.timer);
298
+ this.timer = void 0;
299
+ if (this.sending || this.options.enabled() !== true || this.pending.length === 0) return;
300
+ const batch = this.pending.splice(0, MAX_BATCH);
301
+ this.sending = true;
302
+ try {
303
+ await this.options.send(batch, keepalive);
304
+ this.attempts = 0;
305
+ } catch (error) {
306
+ const retry = !(error instanceof SeaproofError) || error.status === 429 || error.status >= 500;
307
+ if (retry && ++this.attempts < MAX_ATTEMPTS) {
308
+ this.pending.unshift(...batch);
309
+ this.sending = false;
310
+ this.schedule(2e3 * 2 ** this.attempts);
311
+ return;
312
+ }
313
+ this.attempts = 0;
314
+ } finally {
315
+ this.sending = false;
316
+ }
317
+ if (this.pending.length > 0) this.schedule(0);
318
+ }
319
+ dispose() {
320
+ if (this.timer !== void 0) clearTimeout(this.timer);
321
+ this.timer = void 0;
322
+ this.pending = [];
323
+ }
324
+ schedule(delayMs) {
325
+ if (this.options.enabled() !== true || this.timer !== void 0) return;
326
+ this.timer = setTimeout(() => {
327
+ this.timer = void 0;
328
+ void this.flush();
329
+ }, delayMs);
330
+ }
331
+ };
332
+ function firstFrame(stack) {
333
+ return stack?.split("\n").find((line) => /^\s*at |@/.test(line))?.trim() ?? "";
334
+ }
335
+ function describeThrown(error, fallbackMessage) {
336
+ if (error instanceof Error) {
337
+ return { type: error.name || error.constructor?.name || "Error", message: error.message || fallbackMessage || "", stack: error.stack };
338
+ }
339
+ if (typeof error === "string") return { type: "Error", message: error };
340
+ let message = fallbackMessage ?? "";
341
+ try {
342
+ message = fallbackMessage ?? JSON.stringify(error) ?? String(error);
343
+ } catch {
344
+ message = String(error);
345
+ }
346
+ return { type: "Error", message };
347
+ }
348
+ function breadcrumbsFrom(entries, message) {
349
+ const list = [...entries];
350
+ const last = list.at(-1);
351
+ if (last?.kind === "error" && message.includes(last.message)) list.pop();
352
+ return list.slice(-MAX_BREADCRUMBS).map((e) => {
353
+ const level = typeof e.level === "string" ? e.level : e.kind === "network" && (typeof e.error === "string" || typeof e.status === "number" && e.status >= 500) ? "error" : void 0;
354
+ return { at: e.t, kind: e.kind, message: e.message, ...level ? { level } : {} };
355
+ });
356
+ }
357
+
358
+ // src/fastTrack.ts
359
+ function canFastTrackType(tester, type) {
360
+ if (!tester?.canFastTrack || type === "question") return false;
361
+ return tester.fastTrackTypes ? tester.fastTrackTypes.includes(type) : true;
362
+ }
363
+
249
364
  // src/reporter.ts
250
365
  var KEY = "seaproof.reporter-key";
251
366
  var SEEN = "seaproof.seen-replies";
@@ -297,7 +412,7 @@ function defaultStorage() {
297
412
 
298
413
  // src/client.ts
299
414
  var DEFAULT_ENDPOINT = "https://api.seaproof.io";
300
- var MAX_CRASH_REPORTS = 3;
415
+ var TESTER_SESSION = "seaproof.tester-session";
301
416
  function newConversationId() {
302
417
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
303
418
  const bytes = crypto.getRandomValues(new Uint8Array(16));
@@ -314,22 +429,29 @@ function createSeaproof(options) {
314
429
  const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
315
430
  const diagnostics = new Diagnostics();
316
431
  const listeners = /* @__PURE__ */ new Set();
317
- const reportedCrashes = /* @__PURE__ */ new Set();
318
- const identity = new ReporterIdentity(options.storage ?? defaultStorage());
432
+ const sessionId = newConversationId();
433
+ const storage = options.storage ?? defaultStorage();
434
+ const identity = new ReporterIdentity(storage);
319
435
  let environment;
320
436
  let environmentName;
321
437
  let branding;
322
438
  let launcher;
439
+ let showPoweredBy = false;
323
440
  let reporter = options.reporter;
441
+ let tester;
442
+ const testerToken = () => storage.getItem(TESTER_SESSION) || void 0;
324
443
  const userHeaders = (user) => user?.externalId && user.userHash ? { "X-Seaproof-User": encodeURIComponent(user.externalId), "X-Seaproof-User-Hash": user.userHash } : {};
325
- async function api(path, body, method = "POST", user = reporter) {
444
+ async function api(path, body, method = "POST", user = reporter, keepalive = false) {
326
445
  const response = await doFetch(`${endpoint}${path}`, {
327
446
  method,
447
+ ...keepalive ? { keepalive } : {},
328
448
  headers: {
329
449
  "Content-Type": "application/json",
330
450
  "X-Seaproof-Key": options.apiKey,
331
451
  "X-Seaproof-Reporter": identity.key,
332
- ...userHeaders(user)
452
+ ...userHeaders(user),
453
+ // The tester session means nothing to a production key; it is never sent there.
454
+ ...isTesterMode() && testerToken() ? { "X-Seaproof-Tester": testerToken() } : {}
333
455
  },
334
456
  body: body === void 0 ? void 0 : JSON.stringify(body)
335
457
  });
@@ -351,6 +473,43 @@ function createSeaproof(options) {
351
473
  );
352
474
  }
353
475
  const isTesterMode = () => options.mode === "tester" || (options.mode ?? "auto") === "auto" && environment === "test";
476
+ const errorsEnabled = () => {
477
+ const chosen = options.reportErrors ?? options.reportCrashes;
478
+ if (chosen !== void 0) return chosen;
479
+ if (options.mode === "tester") return true;
480
+ if (options.mode === "production") return false;
481
+ return environment === void 0 ? void 0 : environment === "test";
482
+ };
483
+ const errors = new ErrorReporter({
484
+ enabled: errorsEnabled,
485
+ send: async (events, keepalive) => {
486
+ await api("/api/v1/sdk/errors", { events }, "POST", reporter, keepalive);
487
+ }
488
+ });
489
+ function captureError(error, handled, capture = {}, fallbackMessage) {
490
+ if (errorsEnabled() === false) return;
491
+ const thrown = describeThrown(error, fallbackMessage);
492
+ const event = {
493
+ id: newConversationId(),
494
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
495
+ type: thrown.type,
496
+ message: thrown.message,
497
+ stack: thrown.stack,
498
+ handled,
499
+ sessionId,
500
+ fingerprint: capture.fingerprint,
501
+ context: mergeContext(
502
+ browserContext(),
503
+ options.appVersion ? { appVersion: options.appVersion } : void 0,
504
+ options.commit ? { commit: options.commit } : void 0,
505
+ options.context?.(),
506
+ capture.context
507
+ ),
508
+ // An uncaught error was just added to the diagnostics under the browser's message.
509
+ breadcrumbs: breadcrumbsFrom(diagnostics.list(), fallbackMessage ?? thrown.message)
510
+ };
511
+ errors.add(event);
512
+ }
354
513
  const client = {
355
514
  get environment() {
356
515
  return environment;
@@ -367,10 +526,20 @@ function createSeaproof(options) {
367
526
  get launcher() {
368
527
  return launcher;
369
528
  },
529
+ get tester() {
530
+ return tester;
531
+ },
532
+ get showPoweredBy() {
533
+ return showPoweredBy;
534
+ },
370
535
  identify(next) {
371
536
  reporter = next ?? void 0;
372
537
  },
373
538
  diagnostics,
539
+ sessionId,
540
+ captureException(error, capture) {
541
+ captureError(error, capture?.handled ?? true, capture);
542
+ },
374
543
  async whoAmI() {
375
544
  return await (await api("/api/v1/sdk/whoami", void 0, "GET")).json();
376
545
  },
@@ -381,7 +550,10 @@ function createSeaproof(options) {
381
550
  environmentName = project.environmentName;
382
551
  if (options.branding !== false) branding = project.branding;
383
552
  launcher = project.launcher;
553
+ showPoweredBy = project.showPoweredBy === true;
554
+ errors.decided();
384
555
  listeners.forEach((l) => l());
556
+ if (isTesterMode() && testerToken()) await refreshTester();
385
557
  } catch (error) {
386
558
  console.warn(`Seaproof: could not fetch the project for the API key. ${describeError(error)}`);
387
559
  }
@@ -408,7 +580,8 @@ function createSeaproof(options) {
408
580
  options.commit ? { commit: options.commit } : void 0,
409
581
  options.context?.(),
410
582
  feedback.context,
411
- automatic ? { custom: { "seaproof.source": "crash" } } : void 0
583
+ automatic ? { custom: { "seaproof.source": "crash" } } : void 0,
584
+ { sessionId }
412
585
  );
413
586
  const sender = feedback.reporter ?? reporter;
414
587
  const response = await api(
@@ -419,6 +592,7 @@ function createSeaproof(options) {
419
592
  description: feedback.description,
420
593
  severity: feedback.severity,
421
594
  linkedTo: feedback.linkedTo,
595
+ doItNow: feedback.doItNow && canFastTrackType(tester, feedback.type ?? "bug") ? true : void 0,
422
596
  reporter: withoutHash(sender),
423
597
  context,
424
598
  attachments: attachments.map(describeAttachment)
@@ -487,32 +661,52 @@ function createSeaproof(options) {
487
661
  return false;
488
662
  }
489
663
  },
664
+ async requestTesterCode(email) {
665
+ await api("/api/v1/sdk/testers/code", { email });
666
+ },
667
+ async signInTester(email, code) {
668
+ const session = await (await api("/api/v1/sdk/testers/session", { email, code })).json();
669
+ storage.setItem(TESTER_SESSION, session.token);
670
+ tester = session.tester;
671
+ listeners.forEach((l) => l());
672
+ return session.tester;
673
+ },
674
+ async signOutTester() {
675
+ try {
676
+ if (testerToken()) await api("/api/v1/sdk/testers/session", void 0, "DELETE");
677
+ } finally {
678
+ storage.setItem(TESTER_SESSION, "");
679
+ tester = void 0;
680
+ listeners.forEach((l) => l());
681
+ }
682
+ },
490
683
  dispose() {
684
+ void errors.flush(true);
685
+ errors.dispose();
491
686
  uninstall();
687
+ removePageHide();
492
688
  listeners.clear();
493
689
  }
494
690
  };
495
- function reportCrash(error, message) {
496
- if (!options.reportCrashes || reportedCrashes.size >= MAX_CRASH_REPORTS || reportedCrashes.has(message)) return;
497
- reportedCrashes.add(message);
498
- const firstLine = message.split("\n")[0];
499
- const stack = error instanceof Error && error.stack ? `
500
-
501
- ${error.stack}` : "";
502
- client.submit(
503
- {
504
- type: "bug",
505
- title: `Crash: ${firstLine.length <= 180 ? firstLine : `${firstLine.slice(0, 177)}...`}`,
506
- description: `${message}${stack}`
507
- },
508
- { automatic: true }
509
- ).catch((e) => console.warn(`Seaproof: could not report the crash. ${describeError(e)}`));
691
+ async function refreshTester() {
692
+ try {
693
+ tester = await (await api("/api/v1/sdk/testers/me", void 0, "GET")).json();
694
+ } catch (error) {
695
+ if (error instanceof SeaproofError && error.status === 401) storage.setItem(TESTER_SESSION, "");
696
+ tester = void 0;
697
+ }
698
+ listeners.forEach((l) => l());
510
699
  }
700
+ const onPageHide = () => void errors.flush(true);
701
+ if (typeof window !== "undefined") window.addEventListener("pagehide", onPageHide);
702
+ const removePageHide = () => {
703
+ if (typeof window !== "undefined") window.removeEventListener("pagehide", onPageHide);
704
+ };
511
705
  const uninstall = options.diagnostics === false ? () => {
512
706
  } : installCapture(diagnostics, {
513
707
  ...options.diagnostics,
514
708
  ignoreUrl: (url) => url.startsWith(endpoint),
515
- onError: reportCrash
709
+ onError: (error, message) => captureError(error, false, {}, message)
516
710
  });
517
711
  return client;
518
712
  }
@@ -611,6 +805,242 @@ var ScreenRecorder = class {
611
805
  }
612
806
  };
613
807
 
808
+ // src/pointing.ts
809
+ var INTERACTIVE = [
810
+ "a[href]",
811
+ "button",
812
+ "input:not([type=hidden])",
813
+ "select",
814
+ "textarea",
815
+ "summary",
816
+ "label",
817
+ "[role=button]",
818
+ "[role=link]",
819
+ "[role=tab]",
820
+ "[role=menuitem]",
821
+ "[role=checkbox]",
822
+ "[role=radio]",
823
+ "[role=switch]",
824
+ "[role=option]",
825
+ "[contenteditable=true]"
826
+ ].join(",");
827
+ var SIMPLE = "img,svg,h1,h2,h3,h4,h5,h6,li,tr,td,th,p";
828
+ var MAX_SHARE = 0.4;
829
+ var MAX_NAME = 60;
830
+ function elementAt(x, y, doc = document) {
831
+ const view = doc.defaultView;
832
+ const area = (view?.innerWidth ?? 0) * (view?.innerHeight ?? 0);
833
+ const hit = doc.elementsFromPoint(x, y).find((el) => !el.closest("[data-seaproof-ignore]"));
834
+ if (!hit || hit === doc.documentElement || hit === doc.body) return null;
835
+ const target = hit.closest(INTERACTIVE) ?? hit.closest(SIMPLE) ?? hit;
836
+ const rect = target.getBoundingClientRect();
837
+ if (rect.width === 0 || rect.height === 0) return null;
838
+ if (area > 0 && rect.width * rect.height / area > MAX_SHARE) return null;
839
+ return { box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, ...describeElement(target) };
840
+ }
841
+ function describeElement(el) {
842
+ return { role: roleOf(el), name: isMasked(el) ? null : nameOf(el) };
843
+ }
844
+ function pinLabel(element) {
845
+ if (!element) return null;
846
+ const { role, name } = element;
847
+ if (role && name) return `${role} "${name}"`;
848
+ return role ?? (name ? `"${name}"` : null);
849
+ }
850
+ function pinMessage(pins) {
851
+ return pins.map((p) => {
852
+ const note = p.note?.trim();
853
+ return `Pin ${p.number}: ${pinLabel(p.element) ?? "a spot on the screen"}${note ? `: "${note}"` : ""}`;
854
+ }).join("\n");
855
+ }
856
+ function isMasked(el) {
857
+ if (el.closest("[data-seaproof-mask]")) return true;
858
+ return el instanceof HTMLInputElement && el.type === "password";
859
+ }
860
+ function roleOf(el) {
861
+ const explicit = el.getAttribute("role");
862
+ if (explicit) return capitalize(explicit.replace(/item$/, " item"));
863
+ const tag = el.tagName.toLowerCase();
864
+ switch (tag) {
865
+ case "button":
866
+ case "summary":
867
+ return "Button";
868
+ case "a":
869
+ return "Link";
870
+ case "select":
871
+ return "List";
872
+ case "textarea":
873
+ return "Field";
874
+ case "img":
875
+ case "svg":
876
+ return "Image";
877
+ case "li":
878
+ return "List item";
879
+ case "tr":
880
+ return "Row";
881
+ case "td":
882
+ case "th":
883
+ return "Cell";
884
+ case "label":
885
+ return "Label";
886
+ case "p":
887
+ return "Text";
888
+ case "input": {
889
+ const type = el.type;
890
+ if (type === "checkbox") return "Checkbox";
891
+ if (type === "radio") return "Option";
892
+ if (type === "button" || type === "submit" || type === "reset") return "Button";
893
+ return "Field";
894
+ }
895
+ }
896
+ return /^h[1-6]$/.test(tag) ? "Heading" : null;
897
+ }
898
+ function nameOf(el) {
899
+ const aria = el.getAttribute("aria-label");
900
+ if (aria?.trim()) return clip(aria);
901
+ const labelledBy = el.getAttribute("aria-labelledby");
902
+ if (labelledBy) {
903
+ const text2 = labelledBy.split(/\s+/).map((id) => el.ownerDocument.getElementById(id)?.textContent ?? "").join(" ");
904
+ if (text2.trim()) return clip(text2);
905
+ }
906
+ if (el instanceof HTMLImageElement) return el.alt.trim() ? clip(el.alt) : null;
907
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
908
+ if (el instanceof HTMLInputElement && ["button", "submit", "reset"].includes(el.type) && el.value.trim()) return clip(el.value);
909
+ const label = el.labels?.[0]?.textContent;
910
+ if (label?.trim()) return clip(label);
911
+ const placeholder = el.getAttribute("placeholder");
912
+ return placeholder?.trim() ? clip(placeholder) : null;
913
+ }
914
+ const title = el.getAttribute("title");
915
+ if (title?.trim()) return clip(title);
916
+ const text = el.textContent ?? "";
917
+ return text.trim() ? clip(text) : null;
918
+ }
919
+ function clip(text) {
920
+ const flat = text.replace(/\s+/g, " ").trim();
921
+ return flat.length > MAX_NAME ? `${flat.slice(0, MAX_NAME - 1)}\u2026` : flat;
922
+ }
923
+ function capitalize(text) {
924
+ return text.charAt(0).toUpperCase() + text.slice(1);
925
+ }
926
+ var SIGNAL = "#e8590c";
927
+ async function drawPins(screenshot, pins, frame) {
928
+ const image = await loadImage(screenshot);
929
+ const canvas = document.createElement("canvas");
930
+ canvas.width = image.naturalWidth;
931
+ canvas.height = image.naturalHeight;
932
+ const ctx = canvas.getContext("2d");
933
+ if (!ctx) return screenshot;
934
+ ctx.drawImage(image, 0, 0);
935
+ const px = (x) => (x - frame.originX) * frame.scale;
936
+ const py = (y) => (y - frame.originY) * frame.scale;
937
+ const line = Math.max(3, Math.round(3 * frame.scale));
938
+ const radius = 12 * frame.scale;
939
+ for (const pin of pins) {
940
+ ctx.lineWidth = line;
941
+ ctx.strokeStyle = SIGNAL;
942
+ let cx = px(pin.x);
943
+ let cy = py(pin.y);
944
+ const box = pin.element?.box;
945
+ if (box) {
946
+ const pad = 4 * frame.scale;
947
+ ctx.beginPath();
948
+ ctx.roundRect(px(box.x) - pad, py(box.y) - pad, box.width * frame.scale + pad * 2, box.height * frame.scale + pad * 2, 8 * frame.scale);
949
+ ctx.stroke();
950
+ cx = px(box.x + box.width) + pad;
951
+ cy = py(box.y) - pad;
952
+ } else {
953
+ ctx.beginPath();
954
+ ctx.arc(cx, cy, radius * 1.6, 0, Math.PI * 2);
955
+ ctx.stroke();
956
+ }
957
+ ctx.beginPath();
958
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2);
959
+ ctx.fillStyle = SIGNAL;
960
+ ctx.fill();
961
+ ctx.fillStyle = "#fff";
962
+ ctx.font = `700 ${Math.round(13 * frame.scale)}px Inter, system-ui, sans-serif`;
963
+ ctx.textAlign = "center";
964
+ ctx.textBaseline = "middle";
965
+ ctx.fillText(String(pin.number), cx, cy + frame.scale);
966
+ const note = pin.note?.trim();
967
+ if (note) {
968
+ const moved = pin.notePosition ? { x: px(pin.notePosition.x), y: py(pin.notePosition.y) } : null;
969
+ drawNote(ctx, note, cx, cy, radius, frame.scale, canvas.width, moved);
970
+ }
971
+ }
972
+ return new Promise((resolve) => canvas.toBlob((blob) => resolve(blob ?? screenshot), "image/png"));
973
+ }
974
+ var NOTE_INK = "#0a1f2e";
975
+ var NOTE_MAX_WIDTH = 240;
976
+ var NOTE_MAX_LINES = 4;
977
+ function drawNote(ctx, note, cx, cy, radius, scale, canvasWidth, moved) {
978
+ const size = Math.round(13 * scale);
979
+ const pad = 8 * scale;
980
+ const lineHeight = Math.round(size * 1.35);
981
+ ctx.font = `600 ${size}px Inter, system-ui, sans-serif`;
982
+ const lines = wrap(ctx, note, NOTE_MAX_WIDTH * scale);
983
+ const width = Math.max(...lines.map((l) => ctx.measureText(l).width)) + pad * 2;
984
+ const height = lines.length * lineHeight + pad * 2;
985
+ const gap = 6 * scale;
986
+ const right = cx + radius + gap;
987
+ const x = moved?.x ?? (right + width <= canvasWidth ? right : Math.max(0, cx - radius - gap - width));
988
+ const y = moved?.y ?? Math.max(0, cy - height / 2);
989
+ if (moved) {
990
+ const [lx, ly] = nearestPoint(cx, cy, x, y, width, height);
991
+ const length = Math.hypot(lx - cx, ly - cy) || 1;
992
+ ctx.beginPath();
993
+ ctx.moveTo(cx + (lx - cx) / length * radius, cy + (ly - cy) / length * radius);
994
+ ctx.lineTo(lx, ly);
995
+ ctx.lineWidth = Math.max(2, 2 * scale);
996
+ ctx.strokeStyle = NOTE_INK;
997
+ ctx.stroke();
998
+ }
999
+ ctx.beginPath();
1000
+ ctx.roundRect(x, y, width, height, 8 * scale);
1001
+ ctx.fillStyle = NOTE_INK;
1002
+ ctx.fill();
1003
+ ctx.fillStyle = "#fff";
1004
+ ctx.textAlign = "left";
1005
+ ctx.textBaseline = "top";
1006
+ lines.forEach((line, i) => ctx.fillText(line, x + pad, y + pad + i * lineHeight));
1007
+ }
1008
+ function nearestPoint(px, py, x, y, width, height) {
1009
+ return [Math.min(Math.max(px, x), x + width), Math.min(Math.max(py, y), y + height)];
1010
+ }
1011
+ function wrap(ctx, text, maxWidth) {
1012
+ const lines = [];
1013
+ let line = "";
1014
+ for (const word of text.replace(/\s+/g, " ").split(" ")) {
1015
+ const next = line ? `${line} ${word}` : word;
1016
+ if (ctx.measureText(next).width <= maxWidth || !line) line = next;
1017
+ else {
1018
+ lines.push(line);
1019
+ line = word;
1020
+ }
1021
+ }
1022
+ if (line) lines.push(line);
1023
+ if (lines.length <= NOTE_MAX_LINES) return lines;
1024
+ const kept = lines.slice(0, NOTE_MAX_LINES);
1025
+ kept[NOTE_MAX_LINES - 1] = `${kept[NOTE_MAX_LINES - 1]}\u2026`;
1026
+ return kept;
1027
+ }
1028
+ function loadImage(blob) {
1029
+ return new Promise((resolve, reject) => {
1030
+ const url = URL.createObjectURL(blob);
1031
+ const img = new Image();
1032
+ img.onload = () => {
1033
+ URL.revokeObjectURL(url);
1034
+ resolve(img);
1035
+ };
1036
+ img.onerror = () => {
1037
+ URL.revokeObjectURL(url);
1038
+ reject(new Error("Seaproof: the screenshot could not be read."));
1039
+ };
1040
+ img.src = url;
1041
+ });
1042
+ }
1043
+
614
1044
  // src/screenshot.ts
615
1045
  var import_html_to_image = require("html-to-image");
616
1046
  function excludedFromScreenshot(node) {
@@ -619,15 +1049,20 @@ function excludedFromScreenshot(node) {
619
1049
  return node instanceof HTMLInputElement && node.type === "password";
620
1050
  }
621
1051
  async function captureScreenshot(element = document.body) {
1052
+ return (await captureScreenshotWithFrame(element)).file;
1053
+ }
1054
+ async function captureScreenshotWithFrame(element = document.body) {
1055
+ const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
1056
+ const rect = element.getBoundingClientRect();
622
1057
  const blob = await (0, import_html_to_image.toBlob)(element, {
623
1058
  cacheBust: true,
624
- pixelRatio: Math.min(window.devicePixelRatio || 1, 2),
1059
+ pixelRatio,
625
1060
  filter: (node) => !excludedFromScreenshot(node)
626
1061
  });
627
1062
  if (!blob) {
628
1063
  throw new Error("Seaproof: the screenshot could not be captured.");
629
1064
  }
630
- return blob;
1065
+ return { file: blob, frame: { originX: rect.left, originY: rect.top, scale: pixelRatio } };
631
1066
  }
632
1067
  // Annotate the CommonJS export names for ESM import in node:
633
1068
  0 && (module.exports = {
@@ -638,13 +1073,21 @@ async function captureScreenshot(element = document.body) {
638
1073
  ScreenRecorder,
639
1074
  SeaproofError,
640
1075
  browserContext,
1076
+ canFastTrackType,
641
1077
  canRecordScreen,
642
1078
  captureScreenshot,
1079
+ captureScreenshotWithFrame,
643
1080
  createSeaproof,
644
1081
  defaultStorage,
1082
+ describeElement,
645
1083
  describeError,
1084
+ drawPins,
1085
+ elementAt,
646
1086
  excludedFromScreenshot,
647
1087
  installCapture,
1088
+ nearestPoint,
648
1089
  newConversationId,
1090
+ pinLabel,
1091
+ pinMessage,
649
1092
  redactUrl
650
1093
  });