@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.
- package/LICENSE +21 -0
- package/README.md +279 -0
- package/dist/anchor.d.ts +24 -0
- package/dist/anchor.js +161 -0
- package/dist/breadcrumbs.d.ts +29 -0
- package/dist/breadcrumbs.js +134 -0
- package/dist/client.d.ts +61 -0
- package/dist/client.js +268 -0
- package/dist/context.d.ts +18 -0
- package/dist/context.js +74 -0
- package/dist/feedback.js +162 -0
- package/dist/files.d.ts +16 -0
- package/dist/files.js +61 -0
- package/dist/hotkey.d.ts +15 -0
- package/dist/hotkey.js +27 -0
- package/dist/index.d.ts +108 -0
- package/dist/index.js +274 -0
- package/dist/redact.d.ts +29 -0
- package/dist/redact.js +76 -0
- package/dist/screenshot.d.ts +17 -0
- package/dist/screenshot.js +69 -0
- package/dist/types.d.ts +165 -0
- package/dist/types.js +1 -0
- package/dist/widget.d.ts +81 -0
- package/dist/widget.js +535 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daybook
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# `@daybook/feedback`
|
|
2
|
+
|
|
3
|
+
In-app feedback for the web. The reporter points at what is wrong and says what happened; everything
|
|
4
|
+
a triager needs is captured without asking them.
|
|
5
|
+
|
|
6
|
+
9 KB gzipped, no dependencies.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
### Script tag — no build step
|
|
11
|
+
|
|
12
|
+
```html
|
|
13
|
+
<script src="https://daybook.team/sdk/v1/feedback.js"></script>
|
|
14
|
+
<script>
|
|
15
|
+
var pm = DaybookFeedback.init({
|
|
16
|
+
apiUrl: 'https://pm-api.hreben.us',
|
|
17
|
+
ingestKey: 'pmi_…',
|
|
18
|
+
reporter: { externalId: user.id, email: user.email },
|
|
19
|
+
})
|
|
20
|
+
</script>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
> **The package is not on npm yet.** Everything below is the shape it will have, and works today if
|
|
24
|
+
> you vendor `feedback.js` into your own build. Until it is published, the script tag is the route
|
|
25
|
+
> that works — it serves the same bundle.
|
|
26
|
+
|
|
27
|
+
The `/sdk/v1/` path is versioned on purpose. A script tag points at a URL forever, so what is there
|
|
28
|
+
stays compatible with what `/ingest/v1` accepts; a breaking change would appear at `/sdk/v2/` beside
|
|
29
|
+
it rather than replacing it under everybody's feet.
|
|
30
|
+
|
|
31
|
+
### JavaScript, as a module
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
import { init } from '@daybook/feedback'
|
|
35
|
+
|
|
36
|
+
const pm = init({
|
|
37
|
+
apiUrl: 'https://pm-api.hreben.us',
|
|
38
|
+
ingestKey: 'pmi_…', // per-environment, write-only, safe to ship
|
|
39
|
+
app: { version: '1.4.0' },
|
|
40
|
+
reporter: { externalId: user.id, email: user.email },
|
|
41
|
+
})
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### React
|
|
45
|
+
|
|
46
|
+
Mount it once, near the root — not per route, or each navigation starts a second widget.
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
// FeedbackWidget.tsx
|
|
50
|
+
import { useEffect } from 'react'
|
|
51
|
+
import { init } from '@daybook/feedback'
|
|
52
|
+
|
|
53
|
+
export function FeedbackWidget({ user }: { user: { id: string; email: string } | null }) {
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
const pm = init({
|
|
56
|
+
apiUrl: import.meta.env.VITE_FEEDBACK_API_URL,
|
|
57
|
+
ingestKey: import.meta.env.VITE_FEEDBACK_KEY,
|
|
58
|
+
surface: 'web-app',
|
|
59
|
+
reporter: user ? { externalId: user.id, email: user.email } : undefined,
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
// Strict mode runs effects twice in development. stop() is what makes that harmless —
|
|
63
|
+
// without it you get two launchers, and the first one holds the events.
|
|
64
|
+
return () => pm.stop()
|
|
65
|
+
}, [user?.id])
|
|
66
|
+
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Render `<FeedbackWidget user={user} />` once in your layout. It draws nothing itself: the widget
|
|
72
|
+
attaches to `document.body`, so it is not affected by a parent's `overflow` or stacking context.
|
|
73
|
+
|
|
74
|
+
### Vue
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// useFeedback.ts
|
|
78
|
+
import { onMounted, onUnmounted, watch, type Ref } from 'vue'
|
|
79
|
+
import { init, type DaybookFeedback } from '@daybook/feedback'
|
|
80
|
+
|
|
81
|
+
export function useFeedback(user: Ref<{ id: string; email: string } | null>) {
|
|
82
|
+
let pm: DaybookFeedback | null = null
|
|
83
|
+
|
|
84
|
+
// Mounted rather than created in setup(), so it does nothing during SSR — the widget needs a
|
|
85
|
+
// document. Whoever is signed in *now* is passed to init: a watcher with `immediate: true`
|
|
86
|
+
// would fire during setup, before this runs, and identify() on nothing is silently no-op.
|
|
87
|
+
onMounted(() => {
|
|
88
|
+
pm = init({
|
|
89
|
+
apiUrl: import.meta.env.VITE_FEEDBACK_API_URL,
|
|
90
|
+
ingestKey: import.meta.env.VITE_FEEDBACK_KEY,
|
|
91
|
+
surface: 'web-app',
|
|
92
|
+
reporter: user.value
|
|
93
|
+
? { externalId: user.value.id, email: user.value.email }
|
|
94
|
+
: undefined,
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
// identify() re-handshakes, so signing in and out is reflected without remounting — which
|
|
99
|
+
// matters because an approval granted to that person is only seen at the next handshake.
|
|
100
|
+
watch(user, next => pm?.identify(
|
|
101
|
+
next ? { externalId: next.id, email: next.email } : null))
|
|
102
|
+
|
|
103
|
+
onUnmounted(() => pm?.stop())
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Call `useFeedback(user)` once, from `App.vue`.
|
|
108
|
+
|
|
109
|
+
A launcher appears bottom-right. `F` opens the picker, `Esc` backs out, `Cmd/Ctrl+Enter` sends.
|
|
110
|
+
|
|
111
|
+
## Allow your domain first
|
|
112
|
+
|
|
113
|
+
The widget only runs on domains you have listed. In Daybook, open **Project settings → Feedback
|
|
114
|
+
widget**, and add your origin to an environment. That is the whole step — it works the moment you
|
|
115
|
+
save it. There is nothing to verify, because the list only ever *narrows* what a key already
|
|
116
|
+
permits: it cannot grant anyone access to anything.
|
|
117
|
+
|
|
118
|
+
`localhost` is an origin like any other. Put it on the **development** environment and you are
|
|
119
|
+
working in a minute.
|
|
120
|
+
|
|
121
|
+
On a domain that is not listed, the handshake returns `403 origin_not_allowed` and the widget quietly
|
|
122
|
+
does not appear — which is also what it does on a revoked key and on a dead network. A feedback
|
|
123
|
+
button must never break the page it is on.
|
|
124
|
+
|
|
125
|
+
## One key, many surfaces
|
|
126
|
+
|
|
127
|
+
One key serves a whole product. Each install says which part of it it is:
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
init({ ingestKey: 'pmi_…', surface: 'mobile-web' })
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`surface` is a component key from your project. The key still fixes the project and the environment
|
|
134
|
+
— the parts that must not be forgeable — so this only routes *within* a project you already write
|
|
135
|
+
to. An unknown value falls back to the key's own component rather than failing: losing the
|
|
136
|
+
attribution is not a reason to lose the report.
|
|
137
|
+
|
|
138
|
+
## Who is reporting
|
|
139
|
+
|
|
140
|
+
`init` takes a `reporter`, and `identify()` updates it once the host app knows who signed in:
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
const pm = init({ … })
|
|
144
|
+
|
|
145
|
+
pm.identify({ externalId: user.id, email: user.email, name: user.name })
|
|
146
|
+
pm.identify(null) // signing out
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
That is enough for most installs. But **a browser saying who it is, is a claim** — anybody viewing
|
|
150
|
+
the page can type any address into the console. If your integration is set to require it, your
|
|
151
|
+
*backend* signs the identity:
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
// On your server. The identity secret never reaches a browser.
|
|
155
|
+
const signature = crypto
|
|
156
|
+
.createHmac('sha256', process.env.DAYBOOK_IDENTITY_SECRET)
|
|
157
|
+
.update(user.id)
|
|
158
|
+
.digest('hex')
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
```js
|
|
162
|
+
// In the page, with the signature your server produced.
|
|
163
|
+
init({ …, reporter: { externalId: user.id, email: user.email }, signature })
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`pm.authenticate(signature)` sets it later, for an app that fetches it after boot.
|
|
167
|
+
|
|
168
|
+
Same shape as Intercom's and Crisp's identity verification, deliberately — if you have done one of
|
|
169
|
+
those, you have done this.
|
|
170
|
+
|
|
171
|
+
### Or sign in with Daybook
|
|
172
|
+
|
|
173
|
+
A third mode, for when the reporter already has a Daybook account — an internal tool, or your own
|
|
174
|
+
team dogfooding. Then there is no secret to configure at all:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
const pm = init({ apiUrl: '…', ingestKey: 'pmi_…' })
|
|
178
|
+
|
|
179
|
+
// It opens a popup, so a real click has to trigger it — a call at startup is blocked.
|
|
180
|
+
document.querySelector('#feedback-signin')
|
|
181
|
+
?.addEventListener('click', () => pm.signIn())
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
In React, hold the instance in a `useRef` and call it from your own button's `onClick`; in Vue,
|
|
185
|
+
return `() => pm?.signIn()` from the composable. In this mode the reporter is settled by the
|
|
186
|
+
sign-in, so nothing needs `reporter` or `identify()`.
|
|
187
|
+
|
|
188
|
+
They approve a short consent screen, and we authenticate them rather than taking your word for it.
|
|
189
|
+
|
|
190
|
+
**Not for a product whose reporters are your customers.** They would have to create an account with
|
|
191
|
+
us to report a bug, which is how feedback stops arriving.
|
|
192
|
+
|
|
193
|
+
## Approval
|
|
194
|
+
|
|
195
|
+
Separately from *how* an identity is established, the integration decides *who may file*: **Open**
|
|
196
|
+
(anyone, anonymously), **Identified** (anyone who says who they are), or **Approved** (only people
|
|
197
|
+
somebody let in). Under Approved, a new reporter sees "Feedback
|
|
198
|
+
access pending approval" instead of the launcher until a maintainer approves them, and a blocked one
|
|
199
|
+
sees nothing at all.
|
|
200
|
+
|
|
201
|
+
`onReady` tells the host app which of those happened, if you would rather say it in your own words:
|
|
202
|
+
|
|
203
|
+
```js
|
|
204
|
+
init({ …, onReady: h => console.log(h.reporterStatus) }) // Approved | Pending | Blocked | Anonymous
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## What it captures
|
|
208
|
+
|
|
209
|
+
The reason this exists rather than a form: the questions that follow "it looks wrong" — which browser,
|
|
210
|
+
which build, what errored just before — are all answerable at the moment of capture, and unanswerable
|
|
211
|
+
three days later when the reporter has moved on.
|
|
212
|
+
|
|
213
|
+
- **The element**, as a CSS selector plus the click position as a fraction of that element's bounding
|
|
214
|
+
box. Not page pixels: an anchor recorded on a desktop layout has to still mean something on a phone.
|
|
215
|
+
An 80-character text snapshot comes too, so a human can find the thing after a redesign breaks the
|
|
216
|
+
selector.
|
|
217
|
+
- **Page and device** — route, title, referrer, locale, timezone, viewport with DPR, and a readable
|
|
218
|
+
browser and OS rather than a raw user-agent string.
|
|
219
|
+
- **Breadcrumbs** — the last 40 navigations, clicks, console errors and failed or slow requests.
|
|
220
|
+
- **A screenshot**, if you leave `screenshots` on and the reporter consents to the browser's share
|
|
221
|
+
prompt.
|
|
222
|
+
|
|
223
|
+
## Redaction
|
|
224
|
+
|
|
225
|
+
On by default, and it runs before anything leaves the device — the server cannot undo a leak that has
|
|
226
|
+
already crossed the wire.
|
|
227
|
+
|
|
228
|
+
- Input values are described, never reproduced: `[7 chars]`, or `[redacted]` when the field name
|
|
229
|
+
suggests a secret.
|
|
230
|
+
- Query strings are stripped from every captured URL.
|
|
231
|
+
- Emails, JWTs, bearer tokens and long digit runs are masked in console text.
|
|
232
|
+
- Password fields and anything you mark `data-daybook-private` are blurred before a screenshot is taken.
|
|
233
|
+
|
|
234
|
+
```html
|
|
235
|
+
<div data-daybook-private>Card ending 4242</div>
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Turn it off with `redact: false` only if you are certain about what is on screen.
|
|
239
|
+
|
|
240
|
+
## Offline
|
|
241
|
+
|
|
242
|
+
A report written the moment something breaks is frequently written the moment the network is also
|
|
243
|
+
broken. Failed sends are queued in `localStorage` and retried on the next visit, carrying an
|
|
244
|
+
idempotency key so a retry the server already received returns the original rather than filing a
|
|
245
|
+
duplicate. 4xx responses other than 429 are not retried — a client that retries a rejected body
|
|
246
|
+
forever becomes a denial of service against its own backend.
|
|
247
|
+
|
|
248
|
+
## Without the UI
|
|
249
|
+
|
|
250
|
+
```js
|
|
251
|
+
const pm = init({ … })
|
|
252
|
+
|
|
253
|
+
pm.open() // your own "Report a problem" menu item
|
|
254
|
+
await pm.report('Checkout threw', { // a caught error, no user present
|
|
255
|
+
kind: 'bug',
|
|
256
|
+
context: { orderId: '123' },
|
|
257
|
+
})
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`report()` takes no screenshot: there is nobody there to consent to a screen share.
|
|
261
|
+
|
|
262
|
+
## Theming, but not styling
|
|
263
|
+
|
|
264
|
+
The widget renders in a shadow root. A host page's `* { }` reset, its `button { all: unset }`, or its
|
|
265
|
+
own stacking context cannot reach in — which matters because the page someone is reporting a problem
|
|
266
|
+
on is exactly the page whose CSS you should not trust.
|
|
267
|
+
|
|
268
|
+
So it is themed from Daybook rather than from your stylesheet: accent colour, corner radius, position
|
|
269
|
+
and launcher label are set on the integration and arrive with the handshake, which means changing
|
|
270
|
+
them needs no redeploy of your site. Anything not on that list is not settable, on purpose.
|
|
271
|
+
|
|
272
|
+
## Limits
|
|
273
|
+
|
|
274
|
+
Two, and they are different things. A **burst limit** of 60 reports a minute per install stops a
|
|
275
|
+
leaked key becoming a write loop. A **period quota** belongs to the whole Daybook project and is what
|
|
276
|
+
runs out at the end of a month; the integrations screen shows how much of it is spent.
|
|
277
|
+
|
|
278
|
+
Attachments go through the API rather than straight to storage, capped per environment — 8 MB by
|
|
279
|
+
default, which is generous for a screenshot.
|
package/dist/anchor.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Anchor } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Turns a click into a durable reference to what was clicked.
|
|
4
|
+
*
|
|
5
|
+
* The approach is taken from the predecessor's widget, which ran this in production across 131
|
|
6
|
+
* reports: a CSS selector for the element, plus the click position expressed as a fraction of that
|
|
7
|
+
* element's bounding box. Page coordinates would be worthless — a pin dropped on a desktop layout
|
|
8
|
+
* would land in the wrong place on a narrow one, or off-screen entirely.
|
|
9
|
+
*
|
|
10
|
+
* The selector is generated here rather than with @medv/finder, which the predecessor used. Not
|
|
11
|
+
* because that library is wrong, but because this SDK is loaded by a snippet on someone else's page:
|
|
12
|
+
* every dependency is bytes they did not ask for and a supply-chain surface they cannot audit. The
|
|
13
|
+
* generator below is ~60 lines and handles the cases that matter.
|
|
14
|
+
*/
|
|
15
|
+
export declare function captureAnchor(clientX: number, clientY: number): Anchor;
|
|
16
|
+
/**
|
|
17
|
+
* Replays an anchor against the current page. Null means the element is gone — the caller should
|
|
18
|
+
* show the report somewhere visible rather than silently dropping it, because a comment nobody can
|
|
19
|
+
* find is a comment that was never made.
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolveAnchor(anchor: Anchor): {
|
|
22
|
+
x: number;
|
|
23
|
+
y: number;
|
|
24
|
+
} | null;
|
package/dist/anchor.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns a click into a durable reference to what was clicked.
|
|
3
|
+
*
|
|
4
|
+
* The approach is taken from the predecessor's widget, which ran this in production across 131
|
|
5
|
+
* reports: a CSS selector for the element, plus the click position expressed as a fraction of that
|
|
6
|
+
* element's bounding box. Page coordinates would be worthless — a pin dropped on a desktop layout
|
|
7
|
+
* would land in the wrong place on a narrow one, or off-screen entirely.
|
|
8
|
+
*
|
|
9
|
+
* The selector is generated here rather than with @medv/finder, which the predecessor used. Not
|
|
10
|
+
* because that library is wrong, but because this SDK is loaded by a snippet on someone else's page:
|
|
11
|
+
* every dependency is bytes they did not ask for and a supply-chain surface they cannot audit. The
|
|
12
|
+
* generator below is ~60 lines and handles the cases that matter.
|
|
13
|
+
*/
|
|
14
|
+
export function captureAnchor(clientX, clientY) {
|
|
15
|
+
const element = document.elementFromPoint(clientX, clientY);
|
|
16
|
+
if (!(element instanceof HTMLElement)) {
|
|
17
|
+
// Fall back to viewport-relative, so a click on empty space still records roughly where the
|
|
18
|
+
// reporter was looking rather than being dropped.
|
|
19
|
+
return {
|
|
20
|
+
selector: null,
|
|
21
|
+
offsetX: clamp01(clientX / window.innerWidth),
|
|
22
|
+
offsetY: clamp01(clientY / window.innerHeight),
|
|
23
|
+
elementText: null,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const box = element.getBoundingClientRect();
|
|
27
|
+
return {
|
|
28
|
+
selector: selectorFor(element),
|
|
29
|
+
offsetX: box.width > 0 ? clamp01((clientX - box.left) / box.width) : 0,
|
|
30
|
+
offsetY: box.height > 0 ? clamp01((clientY - box.top) / box.height) : 0,
|
|
31
|
+
elementText: textOf(element),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Replays an anchor against the current page. Null means the element is gone — the caller should
|
|
36
|
+
* show the report somewhere visible rather than silently dropping it, because a comment nobody can
|
|
37
|
+
* find is a comment that was never made.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveAnchor(anchor) {
|
|
40
|
+
if (!anchor.selector) {
|
|
41
|
+
return {
|
|
42
|
+
x: anchor.offsetX * window.innerWidth,
|
|
43
|
+
y: anchor.offsetY * window.innerHeight,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
let element = null;
|
|
47
|
+
try {
|
|
48
|
+
element = document.querySelector(anchor.selector);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// An invalid selector is possible if the page or the SDK changed under it.
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
if (!element)
|
|
55
|
+
return null;
|
|
56
|
+
const box = element.getBoundingClientRect();
|
|
57
|
+
return {
|
|
58
|
+
x: box.left + anchor.offsetX * box.width,
|
|
59
|
+
y: box.top + anchor.offsetY * box.height,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Builds the shortest selector that uniquely identifies an element.
|
|
64
|
+
*
|
|
65
|
+
* Preference order is deliberate: a stable id or test attribute beats a class list, which beats
|
|
66
|
+
* structural position. Framework-generated classes are skipped — a Tailwind or CSS-module class is
|
|
67
|
+
* not an identity, and a selector built from one breaks on the next build.
|
|
68
|
+
*/
|
|
69
|
+
function selectorFor(element) {
|
|
70
|
+
if (element === document.body)
|
|
71
|
+
return 'body';
|
|
72
|
+
// Test and analytics attributes exist precisely to be stable. If the page has one, use it.
|
|
73
|
+
for (const attribute of ['data-testid', 'data-test', 'data-daybook-id', 'data-cy']) {
|
|
74
|
+
const value = element.getAttribute(attribute);
|
|
75
|
+
if (value) {
|
|
76
|
+
const candidate = `[${attribute}="${cssEscape(value)}"]`;
|
|
77
|
+
if (isUnique(candidate))
|
|
78
|
+
return candidate;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (element.id && !looksGenerated(element.id)) {
|
|
82
|
+
const candidate = `#${cssEscape(element.id)}`;
|
|
83
|
+
if (isUnique(candidate))
|
|
84
|
+
return candidate;
|
|
85
|
+
}
|
|
86
|
+
const path = [];
|
|
87
|
+
let current = element;
|
|
88
|
+
while (current && current !== document.body && path.length < 8) {
|
|
89
|
+
let step = current.tagName.toLowerCase();
|
|
90
|
+
const meaningful = Array.from(current.classList)
|
|
91
|
+
.filter(c => !looksGenerated(c))
|
|
92
|
+
.slice(0, 2);
|
|
93
|
+
if (meaningful.length > 0)
|
|
94
|
+
step += meaningful.map(c => `.${cssEscape(c)}`).join('');
|
|
95
|
+
// nth-of-type only when the parent has siblings of the same shape, so selectors stay readable
|
|
96
|
+
// for a human reading them in a report.
|
|
97
|
+
const parent = current.parentElement;
|
|
98
|
+
if (parent) {
|
|
99
|
+
const twins = Array.from(parent.children).filter(c => c.tagName === current.tagName);
|
|
100
|
+
if (twins.length > 1)
|
|
101
|
+
step += `:nth-of-type(${twins.indexOf(current) + 1})`;
|
|
102
|
+
}
|
|
103
|
+
path.unshift(step);
|
|
104
|
+
const candidate = path.join(' > ');
|
|
105
|
+
if (isUnique(candidate))
|
|
106
|
+
return candidate;
|
|
107
|
+
current = parent;
|
|
108
|
+
}
|
|
109
|
+
const full = path.length > 0 ? `body > ${path.join(' > ')}` : null;
|
|
110
|
+
return full && isUnique(full) ? full : null;
|
|
111
|
+
}
|
|
112
|
+
function isUnique(selector) {
|
|
113
|
+
try {
|
|
114
|
+
return document.querySelectorAll(selector).length === 1;
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Heuristic for build-generated names: hashes, CSS-module suffixes, styled-component classes and
|
|
122
|
+
* framework scope ids. A selector built on one of these is valid until the next deploy.
|
|
123
|
+
*/
|
|
124
|
+
function looksGenerated(name) {
|
|
125
|
+
return (/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(name) || // sc-abc123, css-1x2y3z
|
|
126
|
+
/--[0-9a-f]{5,}$/i.test(name) || // module--hash
|
|
127
|
+
/^_[0-9a-z]{5,}/i.test(name) || // _1a2b3c
|
|
128
|
+
/^v-[0-9a-f]{6,}$/i.test(name) || // Vue scope id
|
|
129
|
+
/^ng-/.test(name) ||
|
|
130
|
+
/[0-9a-f]{8,}/i.test(name) // any long hex run
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A readable label for the element.
|
|
135
|
+
*
|
|
136
|
+
* innerText, not textContent: textContent concatenates every descendant with no separator, so a
|
|
137
|
+
* button containing a label and a visually-hidden copy of it came out as
|
|
138
|
+
* "Change passwordChange password". It also ignores CSS, so it happily returns text the reporter
|
|
139
|
+
* cannot see. innerText respects both, and falls back to textContent where it is unavailable.
|
|
140
|
+
*/
|
|
141
|
+
function textOf(element) {
|
|
142
|
+
const raw = element.innerText ?? element.textContent ?? '';
|
|
143
|
+
const text = raw.replace(/\s+/g, ' ').trim();
|
|
144
|
+
if (!text) {
|
|
145
|
+
// An icon-only control has no text at all, and its accessible name is the only label there is.
|
|
146
|
+
const label = element.getAttribute('aria-label') ?? element.getAttribute('title');
|
|
147
|
+
return label?.trim() || null;
|
|
148
|
+
}
|
|
149
|
+
return text.length > 80 ? `${text.slice(0, 77)}…` : text;
|
|
150
|
+
}
|
|
151
|
+
function clamp01(value) {
|
|
152
|
+
if (!Number.isFinite(value))
|
|
153
|
+
return 0;
|
|
154
|
+
return Math.max(0, Math.min(1, value));
|
|
155
|
+
}
|
|
156
|
+
/** CSS.escape where available; a conservative fallback where it is not. */
|
|
157
|
+
function cssEscape(value) {
|
|
158
|
+
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function')
|
|
159
|
+
return CSS.escape(value);
|
|
160
|
+
return value.replace(/([^\w-])/g, '\\$1');
|
|
161
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Breadcrumb } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* A bounded ring of what happened before the report.
|
|
4
|
+
*
|
|
5
|
+
* The value of this is the difference between "it broke" and "it broke after I saved, then the
|
|
6
|
+
* request 500'd" — which is the report a developer can act on without a reply. Capped and
|
|
7
|
+
* oldest-dropped, because an unbounded buffer on a long-lived single-page app becomes a memory leak
|
|
8
|
+
* and a payload nobody reads.
|
|
9
|
+
*/
|
|
10
|
+
export declare class BreadcrumbTrail {
|
|
11
|
+
private readonly limit;
|
|
12
|
+
private readonly redact;
|
|
13
|
+
private readonly entries;
|
|
14
|
+
private readonly detach;
|
|
15
|
+
constructor(limit?: number, redact?: boolean);
|
|
16
|
+
list(): Breadcrumb[];
|
|
17
|
+
add(type: Breadcrumb['type'], message: string): void;
|
|
18
|
+
/**
|
|
19
|
+
* Starts listening. Everything patched here is restored by stop(), so a host app that unmounts the
|
|
20
|
+
* widget is not left with our wrappers in place.
|
|
21
|
+
*/
|
|
22
|
+
start(): void;
|
|
23
|
+
stop(): void;
|
|
24
|
+
/**
|
|
25
|
+
* Failed and slow requests only. A record of every successful call would drown the interesting one
|
|
26
|
+
* and would carry URLs the report has no business containing.
|
|
27
|
+
*/
|
|
28
|
+
private watchFetch;
|
|
29
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { describeElement, redactText, redactUrl } from './redact.js';
|
|
2
|
+
/**
|
|
3
|
+
* A bounded ring of what happened before the report.
|
|
4
|
+
*
|
|
5
|
+
* The value of this is the difference between "it broke" and "it broke after I saved, then the
|
|
6
|
+
* request 500'd" — which is the report a developer can act on without a reply. Capped and
|
|
7
|
+
* oldest-dropped, because an unbounded buffer on a long-lived single-page app becomes a memory leak
|
|
8
|
+
* and a payload nobody reads.
|
|
9
|
+
*/
|
|
10
|
+
export class BreadcrumbTrail {
|
|
11
|
+
constructor(limit = 40, redact = true) {
|
|
12
|
+
this.limit = limit;
|
|
13
|
+
this.redact = redact;
|
|
14
|
+
this.entries = [];
|
|
15
|
+
this.detach = [];
|
|
16
|
+
}
|
|
17
|
+
list() {
|
|
18
|
+
return [...this.entries];
|
|
19
|
+
}
|
|
20
|
+
add(type, message) {
|
|
21
|
+
this.entries.push({
|
|
22
|
+
at: new Date().toISOString(),
|
|
23
|
+
type,
|
|
24
|
+
message: this.redact ? redactText(message) : message.slice(0, 500),
|
|
25
|
+
});
|
|
26
|
+
// Oldest out. shift() on an array this small is cheaper than the bookkeeping a real ring buffer
|
|
27
|
+
// would need.
|
|
28
|
+
while (this.entries.length > this.limit)
|
|
29
|
+
this.entries.shift();
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Starts listening. Everything patched here is restored by stop(), so a host app that unmounts the
|
|
33
|
+
* widget is not left with our wrappers in place.
|
|
34
|
+
*/
|
|
35
|
+
start() {
|
|
36
|
+
const onClick = (event) => {
|
|
37
|
+
const target = event.target;
|
|
38
|
+
if (!(target instanceof Element))
|
|
39
|
+
return;
|
|
40
|
+
// Never our own UI. Without this every report ends with a few "click div" entries from the
|
|
41
|
+
// widget the reporter used to file it — noise in the one place a triager is actually reading.
|
|
42
|
+
if (target.closest('[data-daybook-feedback]'))
|
|
43
|
+
return;
|
|
44
|
+
this.add('click', describeElement(target));
|
|
45
|
+
};
|
|
46
|
+
document.addEventListener('click', onClick, { capture: true, passive: true });
|
|
47
|
+
this.detach.push(() => document.removeEventListener('click', onClick, { capture: true }));
|
|
48
|
+
// Navigation in a single-page app does not fire a page load, so the history methods are wrapped.
|
|
49
|
+
// Both are restored on stop.
|
|
50
|
+
const originalPush = history.pushState;
|
|
51
|
+
const originalReplace = history.replaceState;
|
|
52
|
+
const record = () => this.add('nav', redactUrl(location.href));
|
|
53
|
+
history.pushState = (...args) => {
|
|
54
|
+
originalPush.apply(history, args);
|
|
55
|
+
record();
|
|
56
|
+
};
|
|
57
|
+
history.replaceState = (...args) => {
|
|
58
|
+
originalReplace.apply(history, args);
|
|
59
|
+
record();
|
|
60
|
+
};
|
|
61
|
+
window.addEventListener('popstate', record);
|
|
62
|
+
this.detach.push(() => {
|
|
63
|
+
history.pushState = originalPush;
|
|
64
|
+
history.replaceState = originalReplace;
|
|
65
|
+
window.removeEventListener('popstate', record);
|
|
66
|
+
});
|
|
67
|
+
// Errors and warnings only. A full console log is noise, a privacy problem, and large.
|
|
68
|
+
for (const level of ['error', 'warn']) {
|
|
69
|
+
const original = console[level];
|
|
70
|
+
console[level] = (...args) => {
|
|
71
|
+
this.add('console', `${level}: ${args.map(stringify).join(' ')}`);
|
|
72
|
+
original.apply(console, args);
|
|
73
|
+
};
|
|
74
|
+
this.detach.push(() => { console[level] = original; });
|
|
75
|
+
}
|
|
76
|
+
const onError = (event) => this.add('console', `uncaught: ${event.message}`);
|
|
77
|
+
const onRejection = (event) => this.add('console', `unhandled rejection: ${stringify(event.reason)}`);
|
|
78
|
+
window.addEventListener('error', onError);
|
|
79
|
+
window.addEventListener('unhandledrejection', onRejection);
|
|
80
|
+
this.detach.push(() => {
|
|
81
|
+
window.removeEventListener('error', onError);
|
|
82
|
+
window.removeEventListener('unhandledrejection', onRejection);
|
|
83
|
+
});
|
|
84
|
+
this.watchFetch();
|
|
85
|
+
}
|
|
86
|
+
stop() {
|
|
87
|
+
for (const undo of this.detach.splice(0))
|
|
88
|
+
undo();
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Failed and slow requests only. A record of every successful call would drown the interesting one
|
|
92
|
+
* and would carry URLs the report has no business containing.
|
|
93
|
+
*/
|
|
94
|
+
watchFetch() {
|
|
95
|
+
if (typeof window.fetch !== 'function')
|
|
96
|
+
return;
|
|
97
|
+
const original = window.fetch;
|
|
98
|
+
window.fetch = async (...args) => {
|
|
99
|
+
const started = performance.now();
|
|
100
|
+
try {
|
|
101
|
+
const response = await original.apply(window, args);
|
|
102
|
+
const ms = Math.round(performance.now() - started);
|
|
103
|
+
if (!response.ok || ms > 3000) {
|
|
104
|
+
this.add('network', `${response.status} ${redactUrl(urlOf(args[0]))} ${ms}ms`);
|
|
105
|
+
}
|
|
106
|
+
return response;
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
this.add('network', `failed ${redactUrl(urlOf(args[0]))}: ${stringify(error)}`);
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
this.detach.push(() => { window.fetch = original; });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function urlOf(input) {
|
|
117
|
+
if (typeof input === 'string')
|
|
118
|
+
return input;
|
|
119
|
+
if (input instanceof URL)
|
|
120
|
+
return input.href;
|
|
121
|
+
return input.url;
|
|
122
|
+
}
|
|
123
|
+
function stringify(value) {
|
|
124
|
+
if (typeof value === 'string')
|
|
125
|
+
return value;
|
|
126
|
+
if (value instanceof Error)
|
|
127
|
+
return `${value.name}: ${value.message}`;
|
|
128
|
+
try {
|
|
129
|
+
return JSON.stringify(value)?.slice(0, 200) ?? String(value);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return String(value);
|
|
133
|
+
}
|
|
134
|
+
}
|