@acryldev/feedback 0.0.0-stage → 0.1.1

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/store.ts ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * The notes people sent, in the app's own data: one JSON line per note in `notes.jsonl`, the ids the builder has seen in `seen.json`, and a note's
3
+ * screenshot as a file in `shots/`. Appending never rewrites a note, so a crash loses at most the note being written; an image is written before its
4
+ * note, so a note never names a missing file.
5
+ */
6
+ import { randomUUID } from 'node:crypto'
7
+ import { existsSync } from 'node:fs'
8
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
9
+ import { join } from 'node:path'
10
+
11
+ /** The element a note was pinned on: a CSS selector to find it again, and a short name to show. */
12
+ export interface PinnedElement {
13
+ readonly selector: string
14
+ readonly label: string
15
+ }
16
+
17
+ export type ScreenshotMediaType = 'image/webp' | 'image/png'
18
+
19
+ /** A note's screenshot, as stored beside the notes. */
20
+ export interface FeedbackScreenshot {
21
+ /** The file under `shots/`. */
22
+ readonly file: string
23
+ readonly mediaType: ScreenshotMediaType
24
+ readonly width: number
25
+ readonly height: number
26
+ readonly bytes: number
27
+ }
28
+
29
+ /**
30
+ * A note already pinned on an element of a page, as that page's own script sees it: where to find the element again and the number its badge
31
+ * shows. It carries no note text, because anyone who opens the page can read this.
32
+ */
33
+ export interface FeedbackPin {
34
+ readonly selector: string
35
+ readonly number: number
36
+ }
37
+
38
+ export interface FeedbackNote {
39
+ readonly id: string
40
+ /** ISO time it was sent. */
41
+ readonly at: string
42
+ readonly text: string
43
+ /** The page's path (and query) it was sent from. */
44
+ readonly page: string
45
+ /** Absent for "Nothing specific". */
46
+ readonly element?: PinnedElement
47
+ /** What the person saw when they sent it; absent when the browser refused the capture. */
48
+ readonly screenshot?: FeedbackScreenshot
49
+ /** The builder has seen it in the frame. */
50
+ readonly seen: boolean
51
+ }
52
+
53
+ /** One screenshot as the page sent it, decoded and checked. */
54
+ export interface NewScreenshot {
55
+ readonly mediaType: ScreenshotMediaType
56
+ readonly width: number
57
+ readonly height: number
58
+ readonly data: Buffer
59
+ }
60
+
61
+ export interface NewNote {
62
+ readonly text: string
63
+ readonly page: string
64
+ readonly element?: PinnedElement
65
+ readonly screenshot?: NewScreenshot
66
+ }
67
+
68
+ /** A stored screenshot's bytes and type. */
69
+ export interface StoredScreenshot {
70
+ readonly bytes: Buffer
71
+ readonly mediaType: ScreenshotMediaType
72
+ }
73
+
74
+ export const LIMITS = {
75
+ text: 2000,
76
+ page: 500,
77
+ selector: 500,
78
+ label: 120,
79
+ /** Decoded image bytes; the page downscales and re-encodes below this. */
80
+ screenshotBytes: 512 * 1024,
81
+ screenshotSide: 2000,
82
+ } as const
83
+
84
+ const DATA_URL = /^data:(image\/(?:webp|png));base64,([A-Za-z0-9+/]+={0,2})$/u
85
+ const NOTE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u
86
+
87
+ /** One screenshot from the page: a WebP or PNG data URL, its size, and the bytes. A string says what is wrong. */
88
+ export function parseScreenshot(value: unknown): NewScreenshot | string {
89
+ if (typeof value !== 'object' || value === null) return 'the screenshot must be an object'
90
+ const { data, width, height } = value as Record<string, unknown>
91
+ if (typeof data !== 'string') return 'the screenshot has no image'
92
+ const match = DATA_URL.exec(data)
93
+ if (match === null || match[1] === undefined || match[2] === undefined)
94
+ return 'the screenshot must be a WebP or PNG data URL'
95
+ const mediaType = match[1] as ScreenshotMediaType
96
+ const bytes = Buffer.from(match[2], 'base64')
97
+ if (bytes.length === 0) return 'the screenshot is empty'
98
+ if (bytes.length > LIMITS.screenshotBytes)
99
+ return `a screenshot is at most ${String(Math.round(LIMITS.screenshotBytes / 1024))} KB`
100
+ const webp =
101
+ bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP'
102
+ const png = bytes[0] === 0x89 && bytes.subarray(1, 4).toString() === 'PNG'
103
+ if ((mediaType === 'image/webp' && !webp) || (mediaType === 'image/png' && !png))
104
+ return 'the screenshot is not the image its type names'
105
+ if (
106
+ !Number.isInteger(width) ||
107
+ !Number.isInteger(height) ||
108
+ (width as number) < 1 ||
109
+ (height as number) < 1 ||
110
+ (width as number) > LIMITS.screenshotSide ||
111
+ (height as number) > LIMITS.screenshotSide
112
+ )
113
+ return `the screenshot needs its size, up to ${String(LIMITS.screenshotSide)} px a side`
114
+ return { mediaType, width: width as number, height: height as number, data: bytes }
115
+ }
116
+
117
+ /** A note as a page sent it, checked; a string says what is wrong. */
118
+ export function parseNewNote(body: unknown): NewNote | string {
119
+ if (body === null || typeof body !== 'object') return 'send a JSON object'
120
+ const { text, page, element, screenshot } = body as Record<string, unknown>
121
+ if (typeof text !== 'string' || text.trim() === '') return 'write a note'
122
+ if (text.length > LIMITS.text) return `a note has at most ${LIMITS.text} characters`
123
+ if (typeof page !== 'string' || !page.startsWith('/') || page.length > LIMITS.page)
124
+ return 'the page must be a path'
125
+ let pinned: PinnedElement | undefined
126
+ if (element !== undefined && element !== null) {
127
+ if (typeof element !== 'object') return 'the element must be an object'
128
+ const { selector, label } = element as Record<string, unknown>
129
+ if (typeof selector !== 'string' || selector === '' || selector.length > LIMITS.selector)
130
+ return 'the element needs a selector'
131
+ if (typeof label !== 'string' || label === '' || label.length > LIMITS.label)
132
+ return 'the element needs a name'
133
+ pinned = { selector, label }
134
+ }
135
+ let shot: NewScreenshot | undefined
136
+ if (screenshot !== undefined && screenshot !== null) {
137
+ const parsed = parseScreenshot(screenshot)
138
+ if (typeof parsed === 'string') return parsed
139
+ shot = parsed
140
+ }
141
+ return {
142
+ text: text.trim(),
143
+ page,
144
+ ...(pinned === undefined ? {} : { element: pinned }),
145
+ ...(shot === undefined ? {} : { screenshot: shot }),
146
+ }
147
+ }
148
+
149
+ function storedScreenshot(raw: unknown): FeedbackScreenshot | undefined {
150
+ if (raw === null || typeof raw !== 'object') return undefined
151
+ const { file, mediaType, width, height, bytes } = raw as Record<string, unknown>
152
+ if (
153
+ typeof file !== 'string' ||
154
+ (mediaType !== 'image/webp' && mediaType !== 'image/png') ||
155
+ !Number.isInteger(width) ||
156
+ !Number.isInteger(height) ||
157
+ !Number.isInteger(bytes)
158
+ )
159
+ return undefined
160
+ return {
161
+ file,
162
+ mediaType,
163
+ width: width as number,
164
+ height: height as number,
165
+ bytes: bytes as number,
166
+ }
167
+ }
168
+
169
+ export class FeedbackStore {
170
+ private readonly notesFile: string
171
+ private readonly seenFile: string
172
+ private readonly shotsDir: string
173
+ /** Writes one after another, so two notes never interleave in the file. */
174
+ private queue: Promise<unknown> = Promise.resolve()
175
+
176
+ constructor(dir: string) {
177
+ this.notesFile = join(dir, 'notes.jsonl')
178
+ this.seenFile = join(dir, 'seen.json')
179
+ this.shotsDir = join(dir, 'shots')
180
+ }
181
+
182
+ add(note: NewNote, now: Date = new Date()): Promise<FeedbackNote> {
183
+ const id = randomUUID()
184
+ const shot = note.screenshot
185
+ const stored = {
186
+ id,
187
+ at: now.toISOString(),
188
+ text: note.text,
189
+ page: note.page,
190
+ ...(note.element === undefined ? {} : { element: note.element }),
191
+ ...(shot === undefined
192
+ ? {}
193
+ : {
194
+ screenshot: {
195
+ file: `${id}.${shot.mediaType === 'image/webp' ? 'webp' : 'png'}`,
196
+ mediaType: shot.mediaType,
197
+ width: shot.width,
198
+ height: shot.height,
199
+ bytes: shot.data.length,
200
+ },
201
+ }),
202
+ }
203
+ return this.serial(async () => {
204
+ await mkdir(join(this.notesFile, '..'), { recursive: true })
205
+ if (shot !== undefined) {
206
+ // The image first: a note in the file always has its screenshot.
207
+ await mkdir(this.shotsDir, { recursive: true })
208
+ await writeFile(
209
+ join(this.shotsDir, `${id}.${shot.mediaType === 'image/webp' ? 'webp' : 'png'}`),
210
+ shot.data,
211
+ )
212
+ }
213
+ await appendFile(this.notesFile, `${JSON.stringify(stored)}\n`)
214
+ return { ...stored, seen: false }
215
+ })
216
+ }
217
+
218
+ /** One note's screenshot, when it has one and the file is still there. */
219
+ async screenshot(id: string): Promise<StoredScreenshot | undefined> {
220
+ if (!NOTE_ID.test(id)) return undefined
221
+ for (const [ext, mediaType] of [
222
+ ['webp', 'image/webp'],
223
+ ['png', 'image/png'],
224
+ ] as const) {
225
+ try {
226
+ return { bytes: await readFile(join(this.shotsDir, `${id}.${ext}`)), mediaType }
227
+ } catch {
228
+ // Not this type; try the other.
229
+ }
230
+ }
231
+ return undefined
232
+ }
233
+
234
+ /**
235
+ * The pins of one page, for the badges its visitors see: the elements a note was pinned on, numbered in the order their first note came,
236
+ * oldest first. One pin per element, so two notes on the same element share its badge, and the number of a pin never moves once it is given.
237
+ */
238
+ async pins(page: string): Promise<FeedbackPin[]> {
239
+ const pins: FeedbackPin[] = []
240
+ const taken = new Set<string>()
241
+ for (const note of (await this.list()).reverse()) {
242
+ const element = note.element
243
+ if (note.page !== page || element === undefined || taken.has(element.selector)) continue
244
+ taken.add(element.selector)
245
+ pins.push({ selector: element.selector, number: pins.length + 1 })
246
+ }
247
+ return pins
248
+ }
249
+
250
+ /** Every note, newest first. A line that is not a note is skipped. */
251
+ async list(): Promise<FeedbackNote[]> {
252
+ if (!existsSync(this.notesFile)) return []
253
+ const seen = await this.seen()
254
+ const notes: FeedbackNote[] = []
255
+ for (const line of (await readFile(this.notesFile, 'utf8')).split('\n')) {
256
+ if (line.trim() === '') continue
257
+ try {
258
+ const raw = JSON.parse(line) as Omit<FeedbackNote, 'seen'> & {
259
+ readonly screenshot?: unknown
260
+ }
261
+ if (
262
+ typeof raw.id === 'string' &&
263
+ typeof raw.at === 'string' &&
264
+ typeof raw.text === 'string' &&
265
+ typeof raw.page === 'string'
266
+ ) {
267
+ const { screenshot, ...rest } = raw
268
+ const shot = storedScreenshot(screenshot)
269
+ notes.push({
270
+ ...rest,
271
+ seen: seen.has(raw.id),
272
+ ...(shot === undefined ? {} : { screenshot: shot }),
273
+ })
274
+ }
275
+ } catch {
276
+ // A torn last line: skipped.
277
+ }
278
+ }
279
+ return notes.reverse()
280
+ }
281
+
282
+ markSeen(ids: readonly string[]): Promise<void> {
283
+ return this.serial(async () => {
284
+ const seen = await this.seen()
285
+ for (const id of ids) seen.add(id)
286
+ await mkdir(join(this.seenFile, '..'), { recursive: true })
287
+ await writeFile(this.seenFile, JSON.stringify([...seen]))
288
+ })
289
+ }
290
+
291
+ private async seen(): Promise<Set<string>> {
292
+ try {
293
+ const ids: unknown = JSON.parse(await readFile(this.seenFile, 'utf8'))
294
+ return new Set(
295
+ Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [],
296
+ )
297
+ } catch {
298
+ return new Set()
299
+ }
300
+ }
301
+
302
+ private serial<T>(work: () => Promise<T>): Promise<T> {
303
+ const next = this.queue.then(work, work)
304
+ this.queue = next.catch(() => {})
305
+ return next
306
+ }
307
+ }
@@ -0,0 +1,287 @@
1
+ import assert from 'node:assert/strict'
2
+ import { appendFileSync, mkdtempSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { afterEach, describe, test } from 'node:test'
6
+ import { canCaptureTab, elementLabel, frameViewOf, shotSize } from '../client.js'
7
+ import { FeedbackStore, LIMITS, parseNewNote, parseScreenshot } from '../store.ts'
8
+
9
+ const dirs: string[] = []
10
+ afterEach(() => {
11
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
12
+ })
13
+ const directory = () => {
14
+ const dir = mkdtempSync(join(tmpdir(), 'feedback-test-'))
15
+ dirs.push(dir)
16
+ return dir
17
+ }
18
+
19
+ describe('a note from a page', () => {
20
+ test('keeps the note, the page and the element it was pinned on', () => {
21
+ assert.deepEqual(
22
+ parseNewNote({
23
+ text: ' Due date is cut off ',
24
+ page: '/app/',
25
+ element: { selector: 'main > li:nth-of-type(2)', label: 'li "Fix the invite link"' },
26
+ }),
27
+ {
28
+ text: 'Due date is cut off',
29
+ page: '/app/',
30
+ element: { selector: 'main > li:nth-of-type(2)', label: 'li "Fix the invite link"' },
31
+ },
32
+ )
33
+ assert.deepEqual(parseNewNote({ text: 'Can I see only my tasks?', page: '/' }), {
34
+ text: 'Can I see only my tasks?',
35
+ page: '/',
36
+ })
37
+ })
38
+
39
+ test('says what is wrong with a note it refuses', () => {
40
+ assert.equal(parseNewNote({ text: ' ', page: '/' }), 'write a note')
41
+ assert.equal(parseNewNote({ text: 'x', page: 'https://elsewhere' }), 'the page must be a path')
42
+ assert.equal(
43
+ parseNewNote({ text: 'x'.repeat(2001), page: '/' }),
44
+ 'a note has at most 2000 characters',
45
+ )
46
+ assert.equal(
47
+ parseNewNote({ text: 'x', page: '/', element: { selector: '' } }),
48
+ 'the element needs a selector',
49
+ )
50
+ assert.equal(parseNewNote('x'), 'send a JSON object')
51
+ })
52
+ })
53
+
54
+ describe('the notes', () => {
55
+ test('lists them newest first, and remembers which the builder has seen', async () => {
56
+ const store = new FeedbackStore(directory())
57
+ const first = await store.add({ text: 'one', page: '/' }, new Date('2026-11-03T10:00:00Z'))
58
+ const second = await store.add({ text: 'two', page: '/' }, new Date('2026-11-03T11:00:00Z'))
59
+ assert.deepEqual(
60
+ (await store.list()).map((note) => [note.text, note.seen]),
61
+ [
62
+ ['two', false],
63
+ ['one', false],
64
+ ],
65
+ )
66
+ await store.markSeen([first.id])
67
+ assert.deepEqual(
68
+ (await store.list()).map((note) => [note.id, note.seen]),
69
+ [
70
+ [second.id, false],
71
+ [first.id, true],
72
+ ],
73
+ )
74
+ })
75
+
76
+ test('skips a torn line and reads an empty store as no notes', async () => {
77
+ const dir = directory()
78
+ const store = new FeedbackStore(dir)
79
+ assert.deepEqual(await store.list(), [])
80
+ await store.add({ text: 'kept', page: '/' })
81
+ appendFileSync(join(dir, 'notes.jsonl'), '{"id":"x","te')
82
+ assert.deepEqual(
83
+ (await store.list()).map((note) => note.text),
84
+ ['kept'],
85
+ )
86
+ })
87
+ })
88
+
89
+ describe('the pins a page shows', () => {
90
+ test('numbers the elements of that page in the order their first note came, and carries no note text', async () => {
91
+ const store = new FeedbackStore(directory())
92
+ await store.add({
93
+ text: 'first',
94
+ page: '/',
95
+ element: { selector: 'main > li:nth-of-type(1)', label: 'task' },
96
+ })
97
+ await store.add({
98
+ text: 'elsewhere',
99
+ page: '/about',
100
+ element: { selector: 'h1', label: 'heading' },
101
+ })
102
+ await store.add({ text: 'general', page: '/' })
103
+ await store.add({
104
+ text: 'second',
105
+ page: '/',
106
+ element: { selector: 'main > li:nth-of-type(2)', label: 'task' },
107
+ })
108
+ assert.deepEqual(await store.pins('/'), [
109
+ { selector: 'main > li:nth-of-type(1)', number: 1 },
110
+ { selector: 'main > li:nth-of-type(2)', number: 2 },
111
+ ])
112
+ assert.deepEqual(await store.pins('/about'), [{ selector: 'h1', number: 1 }])
113
+ assert.deepEqual(await store.pins('/nowhere'), [])
114
+ assert.deepEqual(Object.keys((await store.pins('/'))[0] ?? {}).sort(), ['number', 'selector'])
115
+ })
116
+
117
+ test('gives two notes on one element one pin, and the next element the next number', async () => {
118
+ const store = new FeedbackStore(directory())
119
+ await store.add({ text: 'one', page: '/', element: { selector: '.card', label: 'card' } })
120
+ await store.add({ text: 'two', page: '/', element: { selector: '.card', label: 'card' } })
121
+ await store.add({ text: 'three', page: '/', element: { selector: '.filter', label: 'filter' } })
122
+ assert.deepEqual(await store.pins('/'), [
123
+ { selector: '.card', number: 1 },
124
+ { selector: '.filter', number: 2 },
125
+ ])
126
+ })
127
+ })
128
+
129
+ describe('the frame view', () => {
130
+ test('is the handle a same-origin parent publishes, and nothing when the page is opened directly', () => {
131
+ const handle = { mode: 'build' }
132
+ assert.equal(frameViewOf({ parent: { [Symbol.for('acryl.frame.view')]: handle } }), handle)
133
+ const top: { parent: unknown } = { parent: undefined }
134
+ top.parent = top
135
+ assert.equal(frameViewOf(top), undefined)
136
+ const crossOrigin = {
137
+ get parent(): unknown {
138
+ throw new Error('cross-origin')
139
+ },
140
+ }
141
+ assert.equal(frameViewOf(crossOrigin), undefined)
142
+ })
143
+ })
144
+
145
+ describe('a screenshot with a note', () => {
146
+ const webp = Buffer.concat([
147
+ Buffer.from('RIFF'),
148
+ Buffer.from([0, 0, 0, 0]),
149
+ Buffer.from('WEBP'),
150
+ Buffer.from([0, 0, 0, 0]),
151
+ ])
152
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
153
+ const dataUrl = (type: string, bytes: Buffer) => `data:${type};base64,${bytes.toString('base64')}`
154
+
155
+ test('reads a WebP or PNG with its size, and refuses anything else with a reason', () => {
156
+ const shot = parseScreenshot({ data: dataUrl('image/webp', webp), width: 800, height: 600 })
157
+ assert.equal(typeof shot === 'string' ? shot : shot.mediaType, 'image/webp')
158
+ assert.deepEqual(parseScreenshot({ data: dataUrl('image/png', png), width: 10, height: 12 }), {
159
+ mediaType: 'image/png',
160
+ width: 10,
161
+ height: 12,
162
+ data: png,
163
+ })
164
+ assert.match(
165
+ String(parseScreenshot({ data: dataUrl('image/gif', png), width: 1, height: 1 })),
166
+ /WebP or PNG/,
167
+ )
168
+ assert.match(
169
+ String(parseScreenshot({ data: dataUrl('image/webp', png), width: 1, height: 1 })),
170
+ /not the image/,
171
+ )
172
+ assert.match(
173
+ String(parseScreenshot({ data: dataUrl('image/webp', webp), width: 0, height: 1 })),
174
+ /size/,
175
+ )
176
+ assert.match(
177
+ String(
178
+ parseScreenshot({
179
+ data: `data:image/webp;base64,${Buffer.alloc(LIMITS.screenshotBytes + 1).toString('base64')}`,
180
+ width: 1,
181
+ height: 1,
182
+ }),
183
+ ),
184
+ /at most/,
185
+ )
186
+ })
187
+
188
+ test('a note carries its screenshot to the store, which serves the bytes back', async () => {
189
+ const dir = directory()
190
+ const store = new FeedbackStore(dir)
191
+ const note = parseNewNote({
192
+ text: 'the button is cut',
193
+ page: '/app/',
194
+ screenshot: { data: dataUrl('image/webp', webp), width: 800, height: 600 },
195
+ })
196
+ assert.equal(typeof note, 'object')
197
+ const stored = await store.add(note as Exclude<typeof note, string>)
198
+ assert.equal(stored.screenshot?.mediaType, 'image/webp')
199
+ assert.equal(stored.screenshot?.width, 800)
200
+ assert.equal(stored.screenshot?.bytes, webp.length)
201
+ const listed = await store.list()
202
+ assert.deepEqual(listed[0]?.screenshot, stored.screenshot)
203
+ assert.deepEqual(await store.screenshot(stored.id), { bytes: webp, mediaType: 'image/webp' })
204
+ assert.equal(await store.screenshot('not-an-id'), undefined)
205
+ })
206
+
207
+ test('a note without a screenshot stays exactly as it was', async () => {
208
+ const dir = directory()
209
+ const store = new FeedbackStore(dir)
210
+ const stored = await store.add({ text: 'no picture', page: '/' })
211
+ assert.equal(stored.screenshot, undefined)
212
+ assert.equal(await store.screenshot(stored.id), undefined)
213
+ })
214
+ })
215
+
216
+ describe('the screenshot size', () => {
217
+ test('downscales the long side to 1280 and leaves a smaller view alone', () => {
218
+ assert.deepEqual(shotSize(2560, 1440), { width: 1280, height: 720 })
219
+ assert.deepEqual(shotSize(800, 600), { width: 800, height: 600 })
220
+ assert.deepEqual(shotSize(100, 2000), { width: 64, height: 1280 })
221
+ })
222
+ })
223
+
224
+ describe('the screenshot option', () => {
225
+ const chrome =
226
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
227
+ const edge =
228
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0'
229
+ const firefox =
230
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:132.0) Gecko/20100101 Firefox/132.0'
231
+ const safari =
232
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15'
233
+ const android =
234
+ 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36'
235
+
236
+ test('offers the tab capture only where the browser can target the tab', () => {
237
+ assert.equal(canCaptureTab(chrome, true), true)
238
+ assert.equal(canCaptureTab(edge, true), true)
239
+ assert.equal(canCaptureTab(firefox, true), false)
240
+ assert.equal(canCaptureTab(safari, true), false)
241
+ assert.equal(canCaptureTab(android, true), false)
242
+ assert.equal(canCaptureTab(chrome, false), false)
243
+ })
244
+ })
245
+
246
+ describe('the label of a picked element', () => {
247
+ /** Just enough of a DOM element for the label: attributes, a heading query, children and a tag. */
248
+ type Fake = {
249
+ nodeType: number
250
+ tagName?: string
251
+ textContent?: string
252
+ childNodes?: Fake[]
253
+ heading?: Fake
254
+ attrs?: Record<string, string>
255
+ }
256
+ const text = (value: string): Fake => ({ nodeType: 3, textContent: value })
257
+ const el = (tagName: string, childNodes: Fake[], extra: Partial<Fake> = {}): Fake => ({
258
+ nodeType: 1,
259
+ tagName: tagName.toUpperCase(),
260
+ childNodes,
261
+ ...extra,
262
+ })
263
+ const dom = (fake: Fake): Element =>
264
+ ({
265
+ getAttribute: (name: string) => fake.attrs?.[name] ?? null,
266
+ querySelector: () =>
267
+ fake.heading === undefined ? null : { textContent: fake.heading.textContent },
268
+ childNodes: fake.childNodes ?? [],
269
+ tagName: fake.tagName,
270
+ }) as unknown as Element
271
+
272
+ test('a card is named by its first text, not by a bold name inside it', () => {
273
+ const card = el('div', [
274
+ text('Fix the invite link'),
275
+ el('div', [el('b', [text('Ben')]), text(' · due Thu')]),
276
+ ])
277
+ assert.equal(elementLabel(dom(card)), '"Fix the invite link"')
278
+ })
279
+
280
+ test('an element that says what it is, or shows nothing, keeps that name', () => {
281
+ assert.equal(
282
+ elementLabel(dom(el('div', [], { attrs: { 'aria-label': 'Task card' } }))),
283
+ 'Task card',
284
+ )
285
+ assert.equal(elementLabel(dom(el('div', []))), 'div')
286
+ })
287
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "allowImportingTsExtensions": true,
8
+ "erasableSyntaxOnly": true,
9
+ "rootDir": ".",
10
+ "outDir": "lib",
11
+ "declaration": true,
12
+ "declarationDir": "lib/types",
13
+ "esModuleInterop": true,
14
+ "strict": true,
15
+ "noImplicitOverride": true,
16
+ "verbatimModuleSyntax": true,
17
+ "skipLibCheck": true,
18
+ "types": ["node"]
19
+ },
20
+ "include": ["*.ts"]
21
+ }
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { defineConfig } from 'tsdown'
3
+
4
+ /** The package's importable files, exactly as `plugin.json`'s `entries` names them (the copy path uses the same table). */
5
+ const { entries } = JSON.parse(readFileSync(new URL('./plugin.json', import.meta.url), 'utf8')) as {
6
+ entries: Record<string, string>
7
+ }
8
+ const entry = Object.fromEntries(
9
+ Object.entries(entries).map(([, file]) => [file.replace(/.ts$/, ''), file]),
10
+ )
11
+
12
+ export default defineConfig({
13
+ name: '@acryldev/feedback',
14
+ entry,
15
+ outDir: 'lib',
16
+ format: 'esm',
17
+ platform: 'node',
18
+ target: 'es2024',
19
+ fixedExtension: false,
20
+ dts: false,
21
+ clean: true,
22
+ sourcemap: true,
23
+ })