@daybook/feedback 1.0.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.
@@ -0,0 +1,61 @@
1
+ import type { HandshakeRequest, HandshakeResponse, IngestRequest, IngestResponse } from './types.js';
2
+ /** A file the reporter attached, or a screenshot we captured. Same path from here on. */
3
+ export interface Upload {
4
+ blob: Blob;
5
+ filename: string;
6
+ contentType: string;
7
+ }
8
+ /**
9
+ * Talks to /ingest/v1, and keeps trying.
10
+ *
11
+ * The queue is the part that matters. A report is written in the moment something went wrong, which
12
+ * is frequently the moment the network is also wrong — and a report lost to a failed request is worse
13
+ * than no widget at all, because the reporter believes they have been heard. Queued reports carry an
14
+ * idempotency key, so a retry that the server already received returns the original rather than
15
+ * filing a duplicate.
16
+ */
17
+ export declare class IngestClient {
18
+ private readonly apiUrl;
19
+ private readonly ingestKey;
20
+ /**
21
+ * The handshake's answer, held in memory only.
22
+ *
23
+ * Not localStorage: it is worth thirty minutes, and a stale one persisted across a visit would be
24
+ * refused anyway. A queued offline report carries its own idempotency key and re-handshakes on the
25
+ * next visit, so nothing is lost by forgetting it.
26
+ */
27
+ private session;
28
+ constructor(apiUrl: string, ingestKey: string);
29
+ setSession(token: string | null): void;
30
+ send(request: IngestRequest, uploads?: Upload[]): Promise<IngestResponse>;
31
+ /**
32
+ * Sends anything left from a previous visit. Called on start, so a report written offline yesterday
33
+ * arrives today without the reporter doing anything.
34
+ */
35
+ flush(): Promise<void>;
36
+ /** Stores a report to try later. Screenshots are dropped: a blob cannot survive localStorage. */
37
+ queue(request: IngestRequest): void;
38
+ /**
39
+ * Signs the reporter in with a Daybook account, in a popup.
40
+ *
41
+ * Only for an integration set to that mode — an internal tool, or dogfooding. Everywhere else the
42
+ * reporter is the host's own user and this would be asking them to make an account with a vendor
43
+ * they have never heard of.
44
+ *
45
+ * PKCE, because the code comes back through a browser: the verifier never leaves this page, so a
46
+ * code intercepted in transit cannot be exchanged by whoever intercepted it.
47
+ */
48
+ signIn(): Promise<string>;
49
+ /** Held in memory only, and only long enough to reach the next handshake. */
50
+ private identityToken;
51
+ private base;
52
+ /**
53
+ * Asks who may report from here, what they may send, and what it should look like.
54
+ *
55
+ * One round trip at boot. Everything it answers has to be known before a launcher can be drawn,
56
+ * and asking four separate questions would be four requests on every page load of the host's site.
57
+ */
58
+ handshake(body: HandshakeRequest): Promise<HandshakeResponse>;
59
+ private post;
60
+ private upload;
61
+ }
package/dist/client.js ADDED
@@ -0,0 +1,268 @@
1
+ const QUEUE_KEY = 'pm.feedback.queue';
2
+ const MAX_QUEUED = 20;
3
+ /**
4
+ * Talks to /ingest/v1, and keeps trying.
5
+ *
6
+ * The queue is the part that matters. A report is written in the moment something went wrong, which
7
+ * is frequently the moment the network is also wrong — and a report lost to a failed request is worse
8
+ * than no widget at all, because the reporter believes they have been heard. Queued reports carry an
9
+ * idempotency key, so a retry that the server already received returns the original rather than
10
+ * filing a duplicate.
11
+ */
12
+ export class IngestClient {
13
+ constructor(apiUrl, ingestKey) {
14
+ this.apiUrl = apiUrl;
15
+ this.ingestKey = ingestKey;
16
+ /**
17
+ * The handshake's answer, held in memory only.
18
+ *
19
+ * Not localStorage: it is worth thirty minutes, and a stale one persisted across a visit would be
20
+ * refused anyway. A queued offline report carries its own idempotency key and re-handshakes on the
21
+ * next visit, so nothing is lost by forgetting it.
22
+ */
23
+ this.session = null;
24
+ /** Held in memory only, and only long enough to reach the next handshake. */
25
+ this.identityToken = null;
26
+ }
27
+ setSession(token) {
28
+ this.session = token;
29
+ }
30
+ async send(request, uploads = []) {
31
+ const payload = {
32
+ // Generated here rather than by the caller, so every report is retry-safe whether or not the
33
+ // host app remembered.
34
+ idempotencyKey: request.idempotencyKey ?? uuid(),
35
+ ...request,
36
+ attachments: [
37
+ ...(request.attachments ?? []),
38
+ ...uploads.map(u => ({
39
+ filename: u.filename,
40
+ contentType: u.contentType,
41
+ size: u.blob.size,
42
+ })),
43
+ ],
44
+ };
45
+ const response = await this.post('/ingest/v1', payload);
46
+ if (!response.ok)
47
+ throw await errorFrom(response);
48
+ const result = await response.json();
49
+ // Bytes go through the API, which is what makes this work from a customer's own domain at all:
50
+ // a presigned storage URL would need that bucket to allow their origin. A failed upload does not
51
+ // fail the report — the words are the valuable part and they are already saved. Tickets come
52
+ // back in the order the declarations were sent, so they pair up by index.
53
+ await Promise.all(uploads.map((upload, index) => {
54
+ const ticket = result.attachments[index];
55
+ return ticket ? this.upload(ticket, upload).catch(() => { }) : Promise.resolve();
56
+ }));
57
+ return result;
58
+ }
59
+ /**
60
+ * Sends anything left from a previous visit. Called on start, so a report written offline yesterday
61
+ * arrives today without the reporter doing anything.
62
+ */
63
+ async flush() {
64
+ const queued = readQueue();
65
+ if (queued.length === 0)
66
+ return;
67
+ writeQueue([]);
68
+ for (const request of queued) {
69
+ try {
70
+ const response = await this.post('/ingest/v1', request);
71
+ // 4xx other than 429 means the server will never accept this body. Retrying forever would
72
+ // turn a bad report into a client-side denial of service against our own API.
73
+ if (!response.ok && (response.status === 429 || response.status >= 500)) {
74
+ enqueue(request);
75
+ }
76
+ }
77
+ catch {
78
+ enqueue(request);
79
+ }
80
+ }
81
+ }
82
+ /** Stores a report to try later. Screenshots are dropped: a blob cannot survive localStorage. */
83
+ queue(request) {
84
+ enqueue({
85
+ ...request,
86
+ idempotencyKey: request.idempotencyKey ?? uuid(),
87
+ attachments: undefined,
88
+ });
89
+ }
90
+ /**
91
+ * Signs the reporter in with a Daybook account, in a popup.
92
+ *
93
+ * Only for an integration set to that mode — an internal tool, or dogfooding. Everywhere else the
94
+ * reporter is the host's own user and this would be asking them to make an account with a vendor
95
+ * they have never heard of.
96
+ *
97
+ * PKCE, because the code comes back through a browser: the verifier never leaves this page, so a
98
+ * code intercepted in transit cannot be exchanged by whoever intercepted it.
99
+ */
100
+ async signIn() {
101
+ const verifier = randomString(64);
102
+ const challenge = await sha256Base64Url(verifier);
103
+ const state = randomString(16);
104
+ const url = `${this.base()}/ingest/v1/authorize`
105
+ + `?key=${encodeURIComponent(this.ingestKey)}`
106
+ + `&origin=${encodeURIComponent(location.origin)}`
107
+ + `&code_challenge=${encodeURIComponent(challenge)}`
108
+ + `&state=${encodeURIComponent(state)}`;
109
+ const popup = window.open(url, 'daybook-feedback', 'width=460,height=640');
110
+ if (!popup)
111
+ throw Object.assign(new Error('Popup blocked'), { code: 'popup_blocked' });
112
+ const code = await new Promise((resolve, reject) => {
113
+ // Closed without finishing is a normal outcome, not an error worth a stack trace — but the
114
+ // promise still has to settle or a caller awaiting it hangs forever.
115
+ const closed = setInterval(() => {
116
+ if (popup.closed) {
117
+ finish();
118
+ reject(Object.assign(new Error('Sign-in cancelled'), { code: 'cancelled' }));
119
+ }
120
+ }, 400);
121
+ const onMessage = (event) => {
122
+ // The origin is checked before the payload is read. This listener is on the host's page,
123
+ // so anything on the internet can post to it.
124
+ if (event.origin !== new URL(this.base()).origin)
125
+ return;
126
+ const data = event.data;
127
+ if (data?.source !== 'daybook-feedback')
128
+ return;
129
+ if (data.state !== state)
130
+ return;
131
+ finish();
132
+ if (data.error || !data.code) {
133
+ reject(Object.assign(new Error('Sign-in was refused'), { code: data.error || 'refused' }));
134
+ return;
135
+ }
136
+ resolve(data.code);
137
+ };
138
+ const finish = () => {
139
+ clearInterval(closed);
140
+ window.removeEventListener('message', onMessage);
141
+ };
142
+ window.addEventListener('message', onMessage);
143
+ });
144
+ const response = await this.post('/ingest/v1/token', { code, codeVerifier: verifier });
145
+ if (!response.ok)
146
+ throw await errorFrom(response);
147
+ const { identityToken } = await response.json();
148
+ this.identityToken = identityToken;
149
+ return identityToken;
150
+ }
151
+ base() {
152
+ return this.apiUrl.replace(/\/$/, '');
153
+ }
154
+ /**
155
+ * Asks who may report from here, what they may send, and what it should look like.
156
+ *
157
+ * One round trip at boot. Everything it answers has to be known before a launcher can be drawn,
158
+ * and asking four separate questions would be four requests on every page load of the host's site.
159
+ */
160
+ async handshake(body) {
161
+ const response = await this.post('/ingest/v1/session', {
162
+ ...body,
163
+ identityToken: this.identityToken ?? undefined,
164
+ });
165
+ if (!response.ok)
166
+ throw await errorFrom(response);
167
+ const result = await response.json();
168
+ this.session = result.sessionToken ?? null;
169
+ return result;
170
+ }
171
+ post(path, body) {
172
+ const headers = {
173
+ 'Content-Type': 'application/json',
174
+ 'X-Ingest-Key': this.ingestKey,
175
+ };
176
+ // Only when there is one. A report without a session is still legal — anonymous reporting is
177
+ // the whole point on a public site — and it simply arrives unattributed.
178
+ if (this.session)
179
+ headers['X-Feedback-Session'] = this.session;
180
+ return fetch(`${this.base()}${path}`, {
181
+ method: 'POST',
182
+ headers,
183
+ body: JSON.stringify(body),
184
+ // No credentials: this endpoint is authorised by the ingest key alone, and sending cookies to
185
+ // it would be a CSRF surface for no benefit.
186
+ credentials: 'omit',
187
+ });
188
+ }
189
+ async upload(ticket, upload) {
190
+ const response = await fetch(ticket.uploadUrl, {
191
+ method: ticket.method,
192
+ headers: {
193
+ 'Content-Type': ticket.contentType,
194
+ // The upload goes to our API now rather than to storage, so it needs the key like every
195
+ // other call. A presigned URL carried its own authorisation in the signature.
196
+ 'X-Ingest-Key': this.ingestKey,
197
+ },
198
+ body: upload.blob,
199
+ credentials: 'omit',
200
+ });
201
+ if (!response.ok)
202
+ throw await errorFrom(response);
203
+ // Only after the bytes actually landed. Confirming a failed upload would flip the row to Ready
204
+ // and leave a triager looking for a screenshot that is not there.
205
+ await this.post(`/ingest/v1/attachments/${ticket.id}/confirm`, {});
206
+ }
207
+ }
208
+ function enqueue(request) {
209
+ const queue = readQueue();
210
+ queue.push(request);
211
+ // Oldest dropped. An unbounded queue on a client that is offline for a week fills its storage
212
+ // quota and then breaks the host app's own storage writes.
213
+ writeQueue(queue.slice(-MAX_QUEUED));
214
+ }
215
+ function readQueue() {
216
+ try {
217
+ const raw = localStorage.getItem(QUEUE_KEY);
218
+ return raw ? JSON.parse(raw) : [];
219
+ }
220
+ catch {
221
+ return [];
222
+ }
223
+ }
224
+ function writeQueue(queue) {
225
+ try {
226
+ if (queue.length === 0)
227
+ localStorage.removeItem(QUEUE_KEY);
228
+ else
229
+ localStorage.setItem(QUEUE_KEY, JSON.stringify(queue));
230
+ }
231
+ catch {
232
+ // Quota or a privacy mode that forbids storage. Losing the queue is acceptable; throwing here
233
+ // would lose the report that is being sent right now.
234
+ }
235
+ }
236
+ async function errorFrom(response) {
237
+ let code = `http_${response.status}`;
238
+ try {
239
+ const body = await response.json();
240
+ if (body.code)
241
+ code = body.code;
242
+ if (body.message)
243
+ return Object.assign(new Error(body.message), { code });
244
+ }
245
+ catch {
246
+ // Not JSON; the status is all there is.
247
+ }
248
+ return Object.assign(new Error(`Ingest failed (${response.status})`), { code });
249
+ }
250
+ function uuid() {
251
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
252
+ return crypto.randomUUID();
253
+ }
254
+ // Older Safari. Not cryptographically meaningful — this only has to be unique per client.
255
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
256
+ }
257
+ /** Enough entropy that a verifier cannot be guessed, in the alphabet PKCE permits. */
258
+ function randomString(length) {
259
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
260
+ const bytes = new Uint8Array(length);
261
+ crypto.getRandomValues(bytes);
262
+ return Array.from(bytes, b => alphabet[b % alphabet.length]).join('');
263
+ }
264
+ async function sha256Base64Url(value) {
265
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
266
+ return btoa(String.fromCharCode(...new Uint8Array(digest)))
267
+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
268
+ }
@@ -0,0 +1,18 @@
1
+ import type { Anchor, Breadcrumb } from './types.js';
2
+ /**
3
+ * The metadata a triager needs and a reporter should never be asked for.
4
+ *
5
+ * This is the single biggest gap in the predecessor: its widgets sent the URL, viewport width and
6
+ * height, and nothing else. Every question that followed — which browser, which build, what was the
7
+ * screen actually like — had to be asked in a reply, days later, by which time the reporter had moved
8
+ * on. All of it is available for free at the moment of capture.
9
+ */
10
+ export declare function captureContext(options: {
11
+ anchor?: Anchor | null;
12
+ breadcrumbs?: Breadcrumb[];
13
+ app?: {
14
+ version?: string;
15
+ build?: string;
16
+ environment?: string;
17
+ };
18
+ }): Record<string, unknown>;
@@ -0,0 +1,74 @@
1
+ import { redactUrl } from './redact.js';
2
+ /**
3
+ * The metadata a triager needs and a reporter should never be asked for.
4
+ *
5
+ * This is the single biggest gap in the predecessor: its widgets sent the URL, viewport width and
6
+ * height, and nothing else. Every question that followed — which browser, which build, what was the
7
+ * screen actually like — had to be asked in a reply, days later, by which time the reporter had moved
8
+ * on. All of it is available for free at the moment of capture.
9
+ */
10
+ export function captureContext(options) {
11
+ const context = {
12
+ platform: 'web',
13
+ // Pathname only. The predecessor stored it this way so a report survives moving between staging
14
+ // and production, and that reasoning still holds.
15
+ route: location.pathname,
16
+ title: document.title.slice(0, 200),
17
+ locale: navigator.language,
18
+ timezone: timezone(),
19
+ viewport: {
20
+ width: window.innerWidth,
21
+ height: window.innerHeight,
22
+ // Half of every "the icon is blurry" report is a 2x display, and nobody thinks to mention it.
23
+ dpr: window.devicePixelRatio ?? 1,
24
+ },
25
+ device: device(),
26
+ };
27
+ if (document.referrer)
28
+ context.referrer = redactUrl(document.referrer);
29
+ if (options.app)
30
+ context.app = options.app;
31
+ if (options.anchor)
32
+ context.anchor = options.anchor;
33
+ if (options.breadcrumbs && options.breadcrumbs.length > 0) {
34
+ context.breadcrumbs = options.breadcrumbs;
35
+ }
36
+ return context;
37
+ }
38
+ /**
39
+ * A readable browser and OS rather than the raw user-agent string.
40
+ *
41
+ * A triager should not have to parse "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)…" to learn it
42
+ * was Safari on a Mac. The raw string is kept as well, because this parsing is a heuristic and the
43
+ * original is the only thing that can settle an argument about it.
44
+ */
45
+ function device() {
46
+ const ua = navigator.userAgent;
47
+ const browser = /Edg\//.test(ua) ? 'Edge'
48
+ : /OPR\//.test(ua) ? 'Opera'
49
+ : /Firefox\//.test(ua) ? 'Firefox'
50
+ : /Chrome\//.test(ua) ? 'Chrome'
51
+ : /Safari\//.test(ua) ? 'Safari'
52
+ : 'Unknown';
53
+ const os = /Windows NT/.test(ua) ? 'Windows'
54
+ : /iPhone|iPad|iPod/.test(ua) ? 'iOS'
55
+ : /Mac OS X/.test(ua) ? 'macOS'
56
+ : /Android/.test(ua) ? 'Android'
57
+ : /Linux/.test(ua) ? 'Linux'
58
+ : 'Unknown';
59
+ const version = ua.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/)?.[1];
60
+ return {
61
+ browser: version ? `${browser} ${version}` : browser,
62
+ os,
63
+ touch: navigator.maxTouchPoints > 0,
64
+ userAgent: ua.slice(0, 300),
65
+ };
66
+ }
67
+ function timezone() {
68
+ try {
69
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
70
+ }
71
+ catch {
72
+ return `UTC${-new Date().getTimezoneOffset() / 60}`;
73
+ }
74
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";var DaybookFeedback=(()=>{var I=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var le=(n,e)=>{for(var t in e)I(n,t,{get:e[t],enumerable:!0})},de=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ae(e))!ce.call(n,o)&&o!==t&&I(n,o,{get:()=>e[o],enumerable:!(r=se(e,o))||r.enumerable});return n};var pe=n=>de(I({},"__esModule",{value:!0}),n);var Re={};le(Re,{DaybookFeedback:()=>_,captureAnchor:()=>L,init:()=>Se,resolveAnchor:()=>te});function g(n){var e;try{let t=new URL(n,location.href);return t.origin===location.origin?t.pathname:`${t.origin}${t.pathname}`}catch{return(e=n.split("?")[0])!=null?e:n}}function M(n){var r,o,i,a,s,c;let e=n.tagName.toLowerCase();if(!n.getAttribute("aria-label")&&!n.getAttribute("data-testid")&&!((r=n.textContent)!=null?r:"").trim()){let d=n.closest("button, a, [role=button], [data-testid], label");if(d&&d!==n)return M(d)}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let d=(i=(o=n.getAttribute("name"))!=null?o:n.id)!=null?i:"",p=n instanceof HTMLInputElement?n.type:e;return`${e}[${p}]${d?` name=${d}`:""}`}let t=(c=(a=n.getAttribute("aria-label"))!=null?a:n.getAttribute("data-testid"))!=null?c:((s=n.textContent)!=null?s:"").replace(/\s+/g," ").trim().slice(0,40);return t?`${e} "${t}"`:e}function X(n){return n.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"[email]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[jwt]").replace(/\bBearer\s+[\w.-]+/gi,"Bearer [redacted]").replace(/\b\d{12,19}\b/g,"[number]").slice(0,500)}var W="data-daybook-private";var x=class{constructor(e=40,t=!0){this.limit=e;this.redact=t;this.entries=[];this.detach=[]}list(){return[...this.entries]}add(e,t){for(this.entries.push({at:new Date().toISOString(),type:e,message:this.redact?X(t):t.slice(0,500)});this.entries.length>this.limit;)this.entries.shift()}start(){let e=s=>{let c=s.target;c instanceof Element&&(c.closest("[data-daybook-feedback]")||this.add("click",M(c)))};document.addEventListener("click",e,{capture:!0,passive:!0}),this.detach.push(()=>document.removeEventListener("click",e,{capture:!0}));let t=history.pushState,r=history.replaceState,o=()=>this.add("nav",g(location.href));history.pushState=(...s)=>{t.apply(history,s),o()},history.replaceState=(...s)=>{r.apply(history,s),o()},window.addEventListener("popstate",o),this.detach.push(()=>{history.pushState=t,history.replaceState=r,window.removeEventListener("popstate",o)});for(let s of["error","warn"]){let c=console[s];console[s]=(...d)=>{this.add("console",`${s}: ${d.map(C).join(" ")}`),c.apply(console,d)},this.detach.push(()=>{console[s]=c})}let i=s=>this.add("console",`uncaught: ${s.message}`),a=s=>this.add("console",`unhandled rejection: ${C(s.reason)}`);window.addEventListener("error",i),window.addEventListener("unhandledrejection",a),this.detach.push(()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",a)}),this.watchFetch()}stop(){for(let e of this.detach.splice(0))e()}watchFetch(){if(typeof window.fetch!="function")return;let e=window.fetch;window.fetch=async(...t)=>{let r=performance.now();try{let o=await e.apply(window,t),i=Math.round(performance.now()-r);return(!o.ok||i>3e3)&&this.add("network",`${o.status} ${g(V(t[0]))} ${i}ms`),o}catch(o){throw this.add("network",`failed ${g(V(t[0]))}: ${C(o)}`),o}},this.detach.push(()=>{window.fetch=e})}};function V(n){return typeof n=="string"?n:n instanceof URL?n.href:n.url}function C(n){var e,t;if(typeof n=="string")return n;if(n instanceof Error)return`${n.name}: ${n.message}`;try{return(t=(e=JSON.stringify(n))==null?void 0:e.slice(0,200))!=null?t:String(n)}catch{return String(n)}}var H="pm.feedback.queue";var E=class{constructor(e,t){this.apiUrl=e;this.ingestKey=t;this.session=null;this.identityToken=null}setSession(e){this.session=e}async send(e,t=[]){var a,s;let r={idempotencyKey:(a=e.idempotencyKey)!=null?a:Y(),...e,attachments:[...(s=e.attachments)!=null?s:[],...t.map(c=>({filename:c.filename,contentType:c.contentType,size:c.blob.size}))]},o=await this.post("/ingest/v1",r);if(!o.ok)throw await k(o);let i=await o.json();return await Promise.all(t.map((c,d)=>{let p=i.attachments[d];return p?this.upload(p,c).catch(()=>{}):Promise.resolve()})),i}async flush(){let e=Q();if(e.length!==0){Z([]);for(let t of e)try{let r=await this.post("/ingest/v1",t);!r.ok&&(r.status===429||r.status>=500)&&F(t)}catch{F(t)}}}queue(e){var t;F({...e,idempotencyKey:(t=e.idempotencyKey)!=null?t:Y(),attachments:void 0})}async signIn(){let e=J(64),t=await he(e),r=J(16),o=`${this.base()}/ingest/v1/authorize?key=${encodeURIComponent(this.ingestKey)}&origin=${encodeURIComponent(location.origin)}&code_challenge=${encodeURIComponent(t)}&state=${encodeURIComponent(r)}`,i=window.open(o,"daybook-feedback","width=460,height=640");if(!i)throw Object.assign(new Error("Popup blocked"),{code:"popup_blocked"});let a=await new Promise((d,p)=>{let b=setInterval(()=>{i.closed&&(w(),p(Object.assign(new Error("Sign-in cancelled"),{code:"cancelled"})))},400),y=m=>{if(m.origin!==new URL(this.base()).origin)return;let h=m.data;if((h==null?void 0:h.source)==="daybook-feedback"&&h.state===r){if(w(),h.error||!h.code){p(Object.assign(new Error("Sign-in was refused"),{code:h.error||"refused"}));return}d(h.code)}},w=()=>{clearInterval(b),window.removeEventListener("message",y)};window.addEventListener("message",y)}),s=await this.post("/ingest/v1/token",{code:a,codeVerifier:e});if(!s.ok)throw await k(s);let{identityToken:c}=await s.json();return this.identityToken=c,c}base(){return this.apiUrl.replace(/\/$/,"")}async handshake(e){var o,i;let t=await this.post("/ingest/v1/session",{...e,identityToken:(o=this.identityToken)!=null?o:void 0});if(!t.ok)throw await k(t);let r=await t.json();return this.session=(i=r.sessionToken)!=null?i:null,r}post(e,t){let r={"Content-Type":"application/json","X-Ingest-Key":this.ingestKey};return this.session&&(r["X-Feedback-Session"]=this.session),fetch(`${this.base()}${e}`,{method:"POST",headers:r,body:JSON.stringify(t),credentials:"omit"})}async upload(e,t){let r=await fetch(e.uploadUrl,{method:e.method,headers:{"Content-Type":e.contentType,"X-Ingest-Key":this.ingestKey},body:t.blob,credentials:"omit"});if(!r.ok)throw await k(r);await this.post(`/ingest/v1/attachments/${e.id}/confirm`,{})}};function F(n){let e=Q();e.push(n),Z(e.slice(-20))}function Q(){try{let n=localStorage.getItem(H);return n?JSON.parse(n):[]}catch{return[]}}function Z(n){try{n.length===0?localStorage.removeItem(H):localStorage.setItem(H,JSON.stringify(n))}catch{}}async function k(n){let e=`http_${n.status}`;try{let t=await n.json();if(t.code&&(e=t.code),t.message)return Object.assign(new Error(t.message),{code:e})}catch{}return Object.assign(new Error(`Ingest failed (${n.status})`),{code:e})}function Y(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function J(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t,r=>e[r%e.length]).join("")}async function he(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(n){var t;let e={platform:"web",route:location.pathname,title:document.title.slice(0,200),locale:navigator.language,timezone:fe(),viewport:{width:window.innerWidth,height:window.innerHeight,dpr:(t=window.devicePixelRatio)!=null?t:1},device:ue()};return document.referrer&&(e.referrer=g(document.referrer)),n.app&&(e.app=n.app),n.anchor&&(e.anchor=n.anchor),n.breadcrumbs&&n.breadcrumbs.length>0&&(e.breadcrumbs=n.breadcrumbs),e}function ue(){var o;let n=navigator.userAgent,e=/Edg\//.test(n)?"Edge":/OPR\//.test(n)?"Opera":/Firefox\//.test(n)?"Firefox":/Chrome\//.test(n)?"Chrome":/Safari\//.test(n)?"Safari":"Unknown",t=/Windows NT/.test(n)?"Windows":/iPhone|iPad|iPod/.test(n)?"iOS":/Mac OS X/.test(n)?"macOS":/Android/.test(n)?"Android":/Linux/.test(n)?"Linux":"Unknown",r=(o=n.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/))==null?void 0:o[1];return{browser:r?`${e} ${r}`:e,os:t,touch:navigator.maxTouchPoints>0,userAgent:n.slice(0,300)}}function fe(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return`UTC${-new Date().getTimezoneOffset()/60}`}}async function G(n){var r;if(typeof((r=navigator.mediaDevices)==null?void 0:r.getDisplayMedia)!="function")return null;let e=n?ge():()=>{},t=null;try{if(t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0}),!t.getVideoTracks()[0])return null;await new Promise(a=>setTimeout(a,250));let i=await me(t);return i?{blob:i,filename:"screenshot.png",contentType:"image/png"}:null}catch{return null}finally{t==null||t.getTracks().forEach(o=>o.stop()),e()}}async function me(n){let e=document.createElement("video");e.srcObject=n,e.muted=!0,await e.play().catch(()=>{});let t=document.createElement("canvas");t.width=e.videoWidth||window.innerWidth,t.height=e.videoHeight||window.innerHeight;let r=t.getContext("2d");return r?(r.drawImage(e,0,0,t.width,t.height),e.pause(),e.srcObject=null,new Promise(o=>t.toBlob(i=>o(i),"image/png"))):null}function ge(){let n=[...document.querySelectorAll(`[${W}]`),...document.querySelectorAll('input[type="password"]')],e=n.map(t=>t.style.filter);return n.forEach(t=>{t.style.filter="blur(12px)"}),()=>{n.forEach((t,r)=>{var o;t.style.filter=(o=e[r])!=null?o:""})}}function L(n,e){let t=document.elementFromPoint(n,e);if(!(t instanceof HTMLElement))return{selector:null,offsetX:S(n/window.innerWidth),offsetY:S(e/window.innerHeight),elementText:null};let r=t.getBoundingClientRect();return{selector:be(t),offsetX:r.width>0?S((n-r.left)/r.width):0,offsetY:r.height>0?S((e-r.top)/r.height):0,elementText:ye(t)}}function te(n){if(!n.selector)return{x:n.offsetX*window.innerWidth,y:n.offsetY*window.innerHeight};let e=null;try{e=document.querySelector(n.selector)}catch{return null}if(!e)return null;let t=e.getBoundingClientRect();return{x:t.left+n.offsetX*t.width,y:t.top+n.offsetY*t.height}}function be(n){if(n===document.body)return"body";for(let o of["data-testid","data-test","data-daybook-id","data-cy"]){let i=n.getAttribute(o);if(i){let a=`[${o}="${O(i)}"]`;if(T(a))return a}}if(n.id&&!ee(n.id)){let o=`#${O(n.id)}`;if(T(o))return o}let e=[],t=n;for(;t&&t!==document.body&&e.length<8;){let o=t.tagName.toLowerCase(),i=Array.from(t.classList).filter(c=>!ee(c)).slice(0,2);i.length>0&&(o+=i.map(c=>`.${O(c)}`).join(""));let a=t.parentElement;if(a){let c=Array.from(a.children).filter(d=>d.tagName===t.tagName);c.length>1&&(o+=`:nth-of-type(${c.indexOf(t)+1})`)}e.unshift(o);let s=e.join(" > ");if(T(s))return s;t=a}let r=e.length>0?`body > ${e.join(" > ")}`:null;return r&&T(r)?r:null}function T(n){try{return document.querySelectorAll(n).length===1}catch{return!1}}function ee(n){return/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(n)||/--[0-9a-f]{5,}$/i.test(n)||/^_[0-9a-z]{5,}/i.test(n)||/^v-[0-9a-f]{6,}$/i.test(n)||/^ng-/.test(n)||/[0-9a-f]{8,}/i.test(n)}function ye(n){var r,o,i;let t=((o=(r=n.innerText)!=null?r:n.textContent)!=null?o:"").replace(/\s+/g," ").trim();if(!t){let a=(i=n.getAttribute("aria-label"))!=null?i:n.getAttribute("title");return(a==null?void 0:a.trim())||null}return t.length>80?`${t.slice(0,77)}\u2026`:t}function S(n){return Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}function O(n){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}var we=/^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;function ne(n,e){let t=[];for(let r of n){if(e+t.length>=5)break;let o=we.test(r.type)?r.size>26214400?`Too large (${(r.size/1048576).toFixed(1)} MB, max 25).`:null:"Only images and short videos.";t.push({blob:r,filename:r.name||`pasted-${t.length+1}.${ve(r.type)}`,contentType:r.type,preview:o?null:URL.createObjectURL(r),error:o})}return t}function re(n){var r;let e=(r=n.clipboardData)==null?void 0:r.items;if(!e)return[];let t=[];for(let o of e){if(o.kind!=="file")continue;let i=o.getAsFile();i&&t.push(i)}return t}function R(n){for(let e of n)e.preview&&URL.revokeObjectURL(e.preview)}function ve(n){var e,t;return(t=(e=n.split("/")[1])==null?void 0:e.replace("quicktime","mov"))!=null?t:"bin"}function oe(n){var r;let t=(r=(typeof n.composedPath=="function"?n.composedPath():[])[0])!=null?r:n.target;return!t||t.nodeType!==1?!1:/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)?!0:typeof t.closest=="function"&&t.closest('[contenteditable=""], [contenteditable="true"]')!==null}var $=class{constructor(e,t){this.options=e;this.onSubmit=t;this.mode="idle";this.anchor=null;this.detach=[];this.state="ready";this.reference=null;this.host=document.createElement("div"),this.host.setAttribute("data-daybook-feedback",""),this.host.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none",this.root=this.host.attachShadow({mode:"open"}),this.root.innerHTML=`<style>${Te}</style><style id="theme"></style><div id="layer"></div>`}setTheme(e){var a,s;let t=this.root.getElementById("theme");if(!t)return;if(!e){t.textContent="";return}let r=[];Ee(e.accent)&&r.push(`--pm-accent: ${e.accent}`);let o={none:"0",sm:"6px",md:"12px",lg:"18px"}[(a=e.cornerRadius)!=null?a:"md"];o&&r.push(`--pm-radius: ${o}`);let i=ke[(s=e.position)!=null?s:"bottom-right"];i&&r.push(i),t.textContent=r.length>0?`:host { ${r.join("; ")} }`:"",this.launcherLabel=typeof e.launcherLabel=="string"&&e.launcherLabel.length>0?e.launcherLabel.slice(0,24):void 0}setState(e){this.state=e,this.host.isConnected&&this.render()}mount(){var e;if(document.body.appendChild(this.host),this.render(),this.options.hotkey!==null){let t=((e=this.options.hotkey)!=null?e:"f").toLowerCase(),r=o=>{if(o.key==="Escape"){this.mode="idle",this.anchor=null,this.render();return}o.metaKey||o.ctrlKey||o.altKey||oe(o)||this.mode!=="composing"&&o.key.toLowerCase()===t&&(this.mode=this.mode==="picking"?"idle":"picking",this.render())};window.addEventListener("keydown",r),this.detach.push(()=>window.removeEventListener("keydown",r))}}unmount(){for(let e of this.detach.splice(0))e();this.host.remove()}open(){this.mode="picking",this.render()}setReporter(e){this.reporter=e}render(){let e=this.root.getElementById("layer");if(e.innerHTML="",this.mode==="idle"){e.appendChild(this.state==="pending"?this.pending():this.launcher());return}if(this.mode==="sent"){e.appendChild(this.sent());return}if(this.mode==="picking"){e.appendChild(this.picker());return}e.appendChild(this.composer())}pending(){let e=document.createElement("div");return e.className="launcher launcher--pending",e.setAttribute("role","status"),e.textContent="Feedback access pending approval",e}sent(){let e=document.createElement("div");e.className="panel panel--sent",e.setAttribute("role","status"),e.innerHTML=`
2
+ <div class="sent__tick" aria-hidden="true">&check;</div>
3
+ <div>
4
+ <div class="panel__title">Thank you \u2014 that is on its way.</div>
5
+ ${this.reference?`<div class="panel__anchor">Quote <strong>${ie(this.reference)}</strong> if you follow it up.</div>`:""}
6
+ </div>`;let t=window.setTimeout(()=>{this.mode==="sent"&&(this.mode="idle",this.render())},6e3);return this.detach.push(()=>window.clearTimeout(t)),e}launcher(){var t,r;let e=document.createElement("button");return e.className="launcher",e.textContent=(t=this.launcherLabel)!=null?t:"Feedback",e.title=this.options.hotkey===null?"Report a problem":`Report a problem (${((r=this.options.hotkey)!=null?r:"f").toUpperCase()})`,e.onclick=()=>{this.mode="picking",this.render()},e}picker(){let e=document.createElement("div");return e.className="mask",e.innerHTML='<div class="hint">Click the thing that is wrong \xB7 <kbd>Esc</kbd> to cancel</div>',e.onclick=t=>{e.style.pointerEvents="none",this.anchor=L(t.clientX,t.clientY),e.style.pointerEvents="",this.mode="composing",this.render()},e}composer(){var j,z,B,K,N;let e=document.createElement("div");e.className="panel";let t=(j=this.anchor)!=null&&j.elementText?`on \u201C${this.anchor.elementText}\u201D`:(z=this.anchor)!=null&&z.selector?`on ${this.anchor.selector}`:"on this page";e.innerHTML=`
7
+ <div class="panel__head">
8
+ <div>
9
+ <div class="panel__anchor">${ie(t)}</div>
10
+ <div class="panel__title">Report a problem</div>
11
+ </div>
12
+ <button id="close" class="panel__close" aria-label="Close">&times;</button>
13
+ </div>
14
+
15
+ <textarea id="message" rows="5" placeholder="What happened?"></textarea>
16
+
17
+ <!--
18
+ Under the message, not above it. Four filled buttons at the top were the loudest thing in the
19
+ panel and the least important decision in it \u2014 the default is right almost every time, and
20
+ what somebody came here to do is type.
21
+ -->
22
+ <div class="panel__kinds">
23
+ ${["bug","idea","praise","question"].map((l,u)=>`<button class="kind${u===0?" kind--on":""}" data-kind="${l}">${l}</button>`).join("")}
24
+ </div>
25
+
26
+ <input id="email" type="email" placeholder="Email (optional, so we can reply)" autocomplete="email" />
27
+
28
+ <!-- One attachment area, not two. A checkbox for the screen and a dropzone for a file were
29
+ two ways to do the same thing, stacked, both dim. -->
30
+ <div id="drop" class="drop">
31
+ <label class="shot"><input id="shot" type="checkbox" ${this.options.screenshots===!1?"":"checked"} /> Capture the screen</label>
32
+ <span class="drop__or">or paste, drop, or
33
+ <input id="file" type="file" multiple accept="image/*,video/mp4,video/quicktime,video/webm" hidden />
34
+ <button id="browse" class="link">choose a file</button>
35
+ </span>
36
+ </div>
37
+
38
+ <div id="files" class="files"></div>
39
+ <div id="status" class="status"></div>
40
+
41
+ <div class="panel__foot">
42
+ <span class="panel__note">Sends the page, your browser, and recent errors.</span>
43
+ <button id="cancel" class="ghost">Cancel</button>
44
+ <button id="send" class="primary">Send</button>
45
+ </div>`;let r=[],o=e.querySelector("#files"),i=e.querySelector("#drop"),a=e.querySelector("#file"),s=()=>{o.innerHTML="",r.forEach((l,u)=>{var D;let f=document.createElement("div");f.className=l.error?"file file--bad":"file",f.innerHTML=l.preview?`<img src="${l.preview}" alt="" />`:'<span class="file__icon">\u25A6</span>';let A=document.createElement("span");A.className="file__name",A.textContent=(D=l.error)!=null?D:l.filename,f.appendChild(A);let v=document.createElement("button");v.className="link",v.textContent="\xD7",v.onclick=()=>{R([l]),r.splice(u,1),s()},f.appendChild(v),o.appendChild(f)}),i.style.display=r.length>=5?"none":""},c=l=>{r.push(...ne(l,r.length)),s()};a.onchange=()=>{a.files&&c(a.files)},e.querySelector("#browse").onclick=()=>a.click(),e.addEventListener("paste",l=>{let u=re(l);u.length>0&&(l.preventDefault(),c(u))}),i.addEventListener("dragover",l=>{l.preventDefault(),i.classList.add("drop--over")}),i.addEventListener("dragleave",()=>i.classList.remove("drop--over")),i.addEventListener("drop",l=>{var u,f;l.preventDefault(),i.classList.remove("drop--over"),c(Array.from((f=(u=l.dataTransfer)==null?void 0:u.files)!=null?f:[]))});let d="bug";e.querySelectorAll(".kind").forEach(l=>{l.onclick=()=>{var u;d=(u=l.dataset.kind)!=null?u:"bug",e.querySelectorAll(".kind").forEach(f=>f.classList.remove("kind--on")),l.classList.add("kind--on")}});let p=e.querySelector("#message"),b=e.querySelector("#email"),y=(N=(B=this.reporter)==null?void 0:B.email)!=null?N:(K=this.options.reporter)==null?void 0:K.email;y&&!b.value&&(b.value=y);let w=e.querySelector("#shot"),m=e.querySelector("#status"),h=e.querySelector("#send"),P=()=>{R(r),this.mode="idle",this.anchor=null,this.render()};e.querySelector("#cancel").onclick=P,e.querySelector("#close").onclick=P;let q=async()=>{if(!p.value.trim()){m.textContent="Say what happened first.";return}h.disabled=!0,m.textContent="Sending\u2026";try{this.reference=await this.onSubmit({message:p.value.trim(),kind:d,email:b.value.trim()||void 0,anchor:this.anchor,withScreenshot:w.checked,files:r.filter(l=>!l.error)})||null,R(r),this.mode="sent",this.anchor=null,this.render()}catch(l){h.disabled=!1,m.textContent=l instanceof Error?`${l.message} \u2014 saved, will retry.`:"Failed, saved and will retry."}};return h.onclick=q,p.onkeydown=l=>{(l.metaKey||l.ctrlKey)&&l.key==="Enter"&&q()},setTimeout(()=>p.focus(),0),e}};function ie(n){return n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var ke={"bottom-right":"--pm-left: auto; --pm-right: 16px; --pm-top: auto; --pm-bottom: 16px","bottom-left":"--pm-left: 16px; --pm-right: auto; --pm-top: auto; --pm-bottom: 16px","top-right":"--pm-left: auto; --pm-right: 16px; --pm-top: 16px; --pm-bottom: auto","top-left":"--pm-left: 16px; --pm-right: auto; --pm-top: 16px; --pm-bottom: auto"};function Ee(n){return typeof n=="string"&&/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|hsla?\([\d\s.,%/deg]+\)|[a-z]{3,20})$/i.test(n.trim())}var Te=`
46
+ :host {
47
+ all: initial;
48
+
49
+ /* Defaults, overridden by the theme block the handshake fills in.
50
+ Offsets rather than a keyword: a custom property can hold a value, not a property name, so
51
+ "put it on the left" has to be four numbers and not one word. */
52
+ --pm-accent: #171717;
53
+ --pm-radius: 12px;
54
+ --pm-left: auto;
55
+ --pm-right: 16px;
56
+ --pm-top: auto;
57
+ --pm-bottom: 16px;
58
+ }
59
+ * { box-sizing: border-box; font-family: system-ui, -apple-system, sans-serif }
60
+ #layer { position: fixed; inset: 0; pointer-events: none }
61
+ .launcher {
62
+ position: fixed; pointer-events: auto;
63
+ left: var(--pm-left); right: var(--pm-right);
64
+ top: var(--pm-top); bottom: var(--pm-bottom);
65
+ padding: 9px 14px; border: 0; border-radius: 999px; cursor: pointer;
66
+ background: var(--pm-accent); color: #fafafa; font-size: 13px; font-weight: 500;
67
+ box-shadow: 0 2px 12px rgba(0,0,0,.3);
68
+ }
69
+ .launcher:hover { filter: brightness(1.15) }
70
+ .launcher--pending { cursor: default; opacity: .85 }
71
+ .launcher--pending:hover { filter: none }
72
+ .mask {
73
+ position: fixed; inset: 0; pointer-events: auto; cursor: crosshair;
74
+ background: rgba(23,23,23,.12);
75
+ }
76
+ .hint {
77
+ position: fixed; left: 50%; top: 16px; transform: translateX(-50%);
78
+ padding: 7px 12px; border-radius: 8px; background: #171717; color: #fafafa;
79
+ font-size: 12px; white-space: nowrap;
80
+ }
81
+ kbd {
82
+ padding: 1px 5px; border-radius: 4px; background: #404040;
83
+ font-family: ui-monospace, monospace; font-size: 11px;
84
+ }
85
+ .panel {
86
+ position: fixed; width: 380px; max-width: calc(100vw - 32px); pointer-events: auto;
87
+ left: var(--pm-left); right: var(--pm-right);
88
+ top: var(--pm-top); bottom: var(--pm-bottom);
89
+ padding: 16px; border-radius: var(--pm-radius); background: #fff; color: #171717;
90
+ box-shadow: 0 8px 32px rgba(0,0,0,.24); font-size: 13px;
91
+ }
92
+ .panel__head { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 10px }
93
+ .panel__title { font-weight: 600; font-size: 14px }
94
+
95
+ /* The anchor leads: it is what the reporter pointed at, and the part they need to recognise. */
96
+ .panel__anchor {
97
+ color: #737373; font-size: 11px;
98
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
99
+ }
100
+ .panel__close {
101
+ margin-left: auto; border: 0; background: none; cursor: pointer;
102
+ color: #a3a3a3; font-size: 20px; line-height: 1; padding: 0 2px;
103
+ }
104
+ .panel__close:hover { color: #171717 }
105
+
106
+ /* A confirmation, not a form. */
107
+ .panel--sent { display: flex; align-items: center; gap: 10px }
108
+ .sent__tick {
109
+ flex: none; width: 24px; height: 24px; border-radius: 999px;
110
+ background: #ecfdf5; color: #047857;
111
+ display: grid; place-items: center; font-size: 14px;
112
+ }
113
+
114
+ .panel__kinds { display: flex; gap: 6px; margin: 8px 0 }
115
+ .kind {
116
+ flex: 1; padding: 5px 0; border: 1px solid #e5e5e5; border-radius: 7px;
117
+ background: #fff; color: #525252; cursor: pointer; font-size: 12px; text-transform: capitalize;
118
+ }
119
+ .kind--on { border-color: #171717; background: #171717; color: #fff }
120
+ textarea, input[type=email] {
121
+ width: 100%; padding: 8px; margin-bottom: 8px; border: 1px solid #e5e5e5;
122
+ border-radius: 8px; font-size: 13px; resize: vertical; color: #171717; background: #fff;
123
+ }
124
+ textarea:focus, input:focus { outline: 2px solid #171717; outline-offset: -1px }
125
+ .shot { display: flex; align-items: center; gap: 6px; color: #525252; font-size: 12px }
126
+
127
+ /*
128
+ One row. Cancel used to sit ABOVE Send in a stacked span, which read as a label for it rather than
129
+ an alternative to it \u2014 and put the escape hatch further from the thumb than the commit.
130
+ */
131
+ .panel__foot {
132
+ display: flex; align-items: center; gap: 8px; margin-top: 12px;
133
+ padding-top: 12px; border-top: 1px solid #f0f0f0;
134
+ }
135
+ .panel__note { flex: 1; color: #a3a3a3; font-size: 10px; line-height: 1.3 }
136
+ .primary, .ghost {
137
+ padding: 6px 12px; border-radius: 7px; cursor: pointer; font-size: 12px; font-weight: 500;
138
+ }
139
+ .primary { border: 0; background: #171717; color: #fff }
140
+ .primary:disabled { opacity: .5; cursor: default }
141
+ .ghost { border: 0; background: transparent; color: #737373 }
142
+ .status { margin-top: 6px; color: #b45309; font-size: 11px; min-height: 0 }
143
+ /*
144
+ One attachment area, holding both ways of adding a picture. They were a checkbox and a dropzone
145
+ stacked \u2014 two affordances for one job, and together the busiest part of a panel whose busiest part
146
+ should be the message.
147
+ */
148
+ .drop {
149
+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
150
+ margin-top: 8px; padding: 8px 10px; border: 1px dashed #d4d4d4; border-radius: 8px;
151
+ color: #a3a3a3; font-size: 11px;
152
+ }
153
+ .drop__or { color: #a3a3a3 }
154
+ .drop--over { border-color: #171717; color: #171717; background: #fafafa }
155
+ .files { display: flex; flex-direction: column; gap: 4px; margin-top: 8px }
156
+ .file { display: flex; align-items: center; gap: 6px; font-size: 11px; color: #525252 }
157
+ .file--bad { color: #b45309 }
158
+ .file img { width: 28px; height: 28px; object-fit: cover; border-radius: 4px }
159
+ .file__icon { width: 28px; text-align: center }
160
+ .file__name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
161
+ .link { border: 0; background: transparent; color: #525252; cursor: pointer; font-size: 11px; text-decoration: underline }
162
+ `;var _=class{constructor(e){this.options=e;this.widget=null;this.started=!1;this.inFlight=null;this.epoch=0;this.ready=null;if(!e.apiUrl)throw new Error("apiUrl is required");if(!e.ingestKey)throw new Error("ingestKey is required");this.client=new E(e.apiUrl,e.ingestKey),this.trail=e.breadcrumbs===!1?null:new x(40,e.redact!==!1)}start(){var e;return(e=this.trail)==null||e.start(),this.mount(),this.started||(this.started=!0,this.client.flush()),this.handshake(),this}mount(){this.widget||(this.widget=new $(this.options,e=>this.submit(e)),this.widget.setReporter(this.options.reporter),this.widget.mount())}handshake(){var r,o,i;let e=JSON.stringify([(r=this.options.reporter)!=null?r:null,(o=this.options.signature)!=null?o:null,this.epoch]);if(((i=this.inFlight)==null?void 0:i.key)===e)return this.inFlight.promise;let t=this.runHandshake().finally(()=>{var a;((a=this.inFlight)==null?void 0:a.promise)===t&&(this.inFlight=null)});return this.inFlight={key:e,promise:t},t}async runHandshake(){var e,t,r,o,i,a;try{let s=await this.client.handshake({identity:this.options.reporter,signature:this.options.signature,locale:typeof navigator!="undefined"?navigator.language:void 0});if(this.ready=s,(t=(e=this.options).onReady)==null||t.call(e,s),s.reporterStatus==="Blocked"){(r=this.widget)==null||r.unmount(),this.widget=null;return}this.mount(),this.widget.setTheme(Le(s.theme)),this.widget.setState(s.reporterStatus==="Pending"?"pending":"ready")}catch(s){(i=(o=this.options).onError)==null||i.call(o,s),console.warn("[feedback] handshake failed; the widget will not appear",s),(a=this.widget)==null||a.unmount(),this.widget=null}}identify(e){var t;this.options={...this.options,reporter:e?{...this.options.reporter,...e}:void 0},(t=this.widget)==null||t.setReporter(this.options.reporter),this.widget&&this.handshake()}async signIn(){await this.client.signIn(),this.epoch++,await this.handshake()}authenticate(e){this.options={...this.options,signature:e!=null?e:void 0},this.widget&&this.handshake()}stop(){var e,t;this.started=!1,(e=this.trail)==null||e.stop(),(t=this.widget)==null||t.unmount(),this.widget=null}open(){var e;(e=this.widget)==null||e.open()}async report(e,t={}){var r,o,i;return this.client.send({message:e,surface:this.options.surface,...t,context:{...U({breadcrumbs:(r=this.trail)==null?void 0:r.list(),app:this.options.app}),...(o=t.context)!=null?o:{}},reporter:(i=t.reporter)!=null?i:this.options.reporter})}async submit(e){var i,a,s,c,d;let t=e.withScreenshot&&this.options.screenshots!==!1?await G(this.options.redact!==!1):null,r=[...e.files,...t?[t]:[]],o={message:e.message,kind:e.kind,app:this.options.app,surface:this.options.surface,reporter:e.email?{...this.options.reporter,email:e.email}:this.options.reporter,context:U({anchor:e.anchor,breadcrumbs:(i=this.trail)==null?void 0:i.list(),app:this.options.app})};try{let p=await this.client.send(o,r);return(s=(a=this.options).onSent)==null||s.call(a,p),p.reference}catch(p){throw this.client.queue(o),(d=(c=this.options).onError)==null||d.call(c,p),p}}};function Se(n){return new _(n).start()}function Le(n){if(!n)return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}return pe(Re);})();
@@ -0,0 +1,16 @@
1
+ import type { Upload } from './client.js';
2
+ /** Matches the server's per-report cap, so a fifth file is refused here rather than silently dropped. */
3
+ export declare const MAX_FILES = 5;
4
+ export interface StagedFile extends Upload {
5
+ /** Object URL for the thumbnail. The caller must revoke it — see revoke(). */
6
+ preview: string | null;
7
+ error: string | null;
8
+ }
9
+ export declare function stage(files: Iterable<File>, existing: number): StagedFile[];
10
+ /** From a paste event. Ignores the text/plain that accompanies most clipboard images. */
11
+ export declare function fromPaste(event: ClipboardEvent): File[];
12
+ /**
13
+ * Releases the object URLs. Not calling this leaks the whole file into memory for the lifetime of the
14
+ * page, which on a long-lived single-page app is a real leak rather than a theoretical one.
15
+ */
16
+ export declare function revoke(files: StagedFile[]): void;