dsh-marker 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,610 @@
1
+ // GENERATED FILE — do not edit. Source: packages/protocol/src/index.js
2
+ // Regenerate with: pnpm run sync-protocol
3
+ /**
4
+ * `@dsh-marker/protocol` — the single source of truth for the wire format
5
+ * shared by the DSH host plugin and the Firefox/Zen extension.
6
+ *
7
+ * Deliberately one dependency-free file: `scripts/sync-protocol.mjs` copies it
8
+ * verbatim into the plugin and the extension, so nothing has to bundle, build,
9
+ * or resolve a workspace package at runtime.
10
+ */
11
+
12
+ // ── constants ───────────────────────────────────────────────────────────────
13
+
14
+ /** Bumped whenever a frame or record shape changes incompatibly. */
15
+ export const PROTOCOL_VERSION = 1
16
+
17
+ /** Exact websocket path registered on the DSH host webserver. */
18
+ export const WS_PATH = '/ext/anno'
19
+
20
+ /** Health/discovery endpoint served next to the socket. */
21
+ export const HEALTH_PATH = '/ext/anno/health'
22
+
23
+ /**
24
+ * Flat, newest-first Session catalog backing the overlay's target picker.
25
+ *
26
+ * The picker answers "which conversation does this annotation belong to?", so
27
+ * the list is ordered by activity and never grouped by workspace.
28
+ */
29
+ export const SESSIONS_PATH = '/ext/anno/sessions'
30
+
31
+ /**
32
+ * Durable hand-off from the extension to the Web Client: mentions waiting to be
33
+ * appended to one Session's composer. Same-origin only — the GUI is the page
34
+ * this Host serves, and it never sees the extension's bridge token.
35
+ */
36
+ export const QUEUE_PATH = '/ext/anno/queue'
37
+
38
+ /** Acknowledged queue entries are removed here; POST `{ids}`. */
39
+ export const QUEUE_ACK_PATH = '/ext/anno/queue/ack'
40
+
41
+ /**
42
+ * The Session the Web Client is showing, reported by that Client so the Host
43
+ * can answer "where does an annotation go by default?". Same-origin only, for
44
+ * the same reason the queue is: the GUI is this Host's own page.
45
+ */
46
+ export const FOCUS_PATH = '/ext/anno/focus'
47
+
48
+ /**
49
+ * One annotation read back for display, by id — the Web Client's chip hover
50
+ * card. Same-origin only; a cross-site page has no business reading what the
51
+ * user marked.
52
+ */
53
+ export const ITEM_PATH = '/ext/anno/item'
54
+
55
+ /** The screenshot that belongs to one annotation; `?id=` names it. Same-origin only. */
56
+ export const IMAGE_PATH = '/ext/anno/image'
57
+
58
+ /** Bridge token file name, relative to `$DSH_HOME`. */
59
+ export const TOKEN_FILE = 'ext-bridge-token'
60
+
61
+ // ── discovery ───────────────────────────────────────────────────────────────
62
+ //
63
+ // A host whose port the launcher chose (`--port 0`, DSH Desktop) has to say
64
+ // where it is. Two addresses-only artifacts do that, and neither may ever
65
+ // carry the token: the token answers "whether", these answer "where".
66
+
67
+ /**
68
+ * The name a host publishes so a client can tell a DSH bridge from whatever
69
+ * else happens to answer on the same port.
70
+ */
71
+ export const DISCOVERY_APP = 'dsh-marker'
72
+
73
+ /**
74
+ * Where a host publishes its current origin on a fixed loopback port. `GET`
75
+ * only and anonymous by design: it returns an address, never the token.
76
+ */
77
+ export const LOCATE_PATH = '/ext/anno/locate'
78
+
79
+ /**
80
+ * Locator ports, tried in order. They sit above the default webserver port and
81
+ * below every OS ephemeral range, so the OS is unlikely to hand one out; three
82
+ * of them survive one being taken by an unrelated process or a second host.
83
+ */
84
+ export const LOCATE_PORTS = [30810, 30811, 30812]
85
+
86
+ /** The locator binds IPv4 loopback only, never the host's configured address. */
87
+ export const LOCATE_HOST = '127.0.0.1'
88
+
89
+ /**
90
+ * Endpoint record: the address a host last bound to, written on every start so
91
+ * a human, a script, or a popup file import can read it. Address only — the
92
+ * token has exactly one home, {@link TOKEN_FILE}.
93
+ */
94
+ export const ENDPOINT_FILE = 'ext-bridge-endpoint.json'
95
+
96
+ /** A per-process host id, 16 lowercase hex characters. */
97
+ const INSTANCE_ID = /^[0-9a-f]{16}$/
98
+
99
+ /**
100
+ * Whether a value could be a host's `instanceId`.
101
+ *
102
+ * It ties a locator answer to the health answer for the same host, so a stale
103
+ * answer — or a different process reusing an origin — is dropped rather than
104
+ * connected to.
105
+ * @param {unknown} value
106
+ */
107
+ export function isInstanceId(value) {
108
+ return typeof value === 'string' && INSTANCE_ID.test(value)
109
+ }
110
+
111
+ /** The extension must say hello within this window or the socket is closed. */
112
+ export const HELLO_TIMEOUT_MS = 5_000
113
+
114
+ /** Server-side ping cadence; the client answers with `pong`. */
115
+ export const PING_INTERVAL_MS = 25_000
116
+
117
+ /** Default budget for an agent-initiated pick. */
118
+ export const PICK_TIMEOUT_MS = 120_000
119
+
120
+ /** Movement below this many CSS pixels still counts as a click, not a drag. */
121
+ export const MAX_CLICK_MOVEMENT_PX = 6
122
+
123
+ /** Anchor modalities, in the order the UI cycles through them. */
124
+ export const ANCHOR_KINDS = ['selection', 'element', 'region']
125
+
126
+ /** Annotation lifecycle states. */
127
+ export const STATES = ['open', 'resolved', 'wont_fix']
128
+
129
+ /** Who produced the annotation. */
130
+ export const SOURCES = ['user', 'agent']
131
+
132
+ /** Optional intent tags offered by the composer. */
133
+ export const INTENTS = ['bug', 'change', 'question', 'reference']
134
+
135
+ /** Upper bounds enforced on both sides. */
136
+ export const LIMITS = {
137
+ commentChars: 20_000,
138
+ noteChars: 8_000,
139
+ urlChars: 8_192,
140
+ titleChars: 1_024,
141
+ selectorChars: 4_096,
142
+ excerptChars: 2_000,
143
+ outerHtmlChars: 4_096,
144
+ quoteChars: 4_000,
145
+ imageBase64Chars: 32 * 1024 * 1024,
146
+ listLimit: 200,
147
+ sessionsLimit: 100,
148
+ /** Chip label carried by a routed mention; presentation only, never identity. */
149
+ labelChars: 200,
150
+ }
151
+
152
+ /** Every frame a client may send to the host. */
153
+ export const CLIENT_FRAMES = ['hello', 'ping', 'anno.create', 'anno.query', 'anno.mutate', 'pick.result']
154
+
155
+ /** Every frame the host may send to a client. */
156
+ export const SERVER_FRAMES = [
157
+ 'hello.ok',
158
+ 'pong',
159
+ 'anno.ack',
160
+ 'anno.query.ok',
161
+ 'anno.event',
162
+ 'pick.request',
163
+ 'pick.cancel',
164
+ 'error',
165
+ ]
166
+
167
+ // ── model ───────────────────────────────────────────────────────────────────
168
+
169
+ const ID_PATTERN = /^an-\d{8}-[0-9a-f]{6}$/
170
+ const HEX = '0123456789abcdef'
171
+
172
+ /** @param {number} n */
173
+ function pad(n) {
174
+ return String(n).padStart(2, '0')
175
+ }
176
+
177
+ /**
178
+ * Allocate an annotation id: `an-<yyyymmdd>-<6 hex>`.
179
+ * @param {Date} [now]
180
+ * @param {(max: number) => number} [random] injected for deterministic tests
181
+ */
182
+ export function newAnnotationId(now = new Date(), random = Math.random) {
183
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`
184
+ let tail = ''
185
+ for (let index = 0; index < 6; index += 1) tail += HEX[Math.floor(random() * 16) % 16]
186
+ return `an-${stamp}-${tail}`
187
+ }
188
+
189
+ /** Allocate a pick id (`pk-<6 hex>`). */
190
+ export function newPickId(random = Math.random) {
191
+ let tail = ''
192
+ for (let index = 0; index < 6; index += 1) tail += HEX[Math.floor(random() * 16) % 16]
193
+ return `pk-${tail}`
194
+ }
195
+
196
+ /** @param {unknown} value */
197
+ export function isPlainObject(value) {
198
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
199
+ }
200
+
201
+ /** @param {unknown} value */
202
+ export function isRect(value) {
203
+ if (!isPlainObject(value)) return false
204
+ return ['x', 'y', 'w', 'h'].every((key) => typeof value[key] === 'number' && Number.isFinite(value[key]))
205
+ }
206
+
207
+ /** @param {unknown} value */
208
+ function isString(value) {
209
+ return typeof value === 'string'
210
+ }
211
+
212
+ /**
213
+ * Validate one anchor and return human-readable violations.
214
+ * @param {unknown} anchor
215
+ * @param {string} [path]
216
+ * @returns {string[]}
217
+ */
218
+ export function validateAnchor(anchor, path = 'anchor') {
219
+ /** @type {string[]} */
220
+ const errors = []
221
+ if (!isPlainObject(anchor)) return [`${path} must be an object`]
222
+ if (!ANCHOR_KINDS.includes(anchor.kind)) {
223
+ return [`${path}.kind must be one of ${ANCHOR_KINDS.join('|')}`]
224
+ }
225
+ if (anchor.kind !== 'region' && !isRect(anchor.rect)) {
226
+ errors.push(`${path}.rect must be {x,y,w,h} numbers`)
227
+ }
228
+ if (anchor.kind === 'selection') {
229
+ const quote = anchor.quote
230
+ if (!isPlainObject(quote)) errors.push(`${path}.quote must be an object`)
231
+ else {
232
+ if (!isString(quote.exact) || quote.exact.length === 0)
233
+ errors.push(`${path}.quote.exact must be a non-empty string`)
234
+ if (!isString(quote.prefix)) errors.push(`${path}.quote.prefix must be a string`)
235
+ if (!isString(quote.suffix)) errors.push(`${path}.quote.suffix must be a string`)
236
+ }
237
+ } else if (anchor.kind === 'element') {
238
+ const selectors = anchor.selectors
239
+ if (!isPlainObject(selectors)) errors.push(`${path}.selectors must be an object`)
240
+ else if (!isString(selectors.cssPath) && !isString(selectors.xpath) && !isString(selectors.stable)) {
241
+ errors.push(`${path}.selectors needs at least one of stable|cssPath|xpath`)
242
+ }
243
+ if (!isPlainObject(anchor.fingerprint)) errors.push(`${path}.fingerprint must be an object`)
244
+ } else {
245
+ if (!isRect(anchor.pageRect)) errors.push(`${path}.pageRect must be {x,y,w,h} numbers`)
246
+ if (!isRect(anchor.viewportRect)) errors.push(`${path}.viewportRect must be {x,y,w,h} numbers`)
247
+ if (anchor.intersectingElements !== undefined && !Array.isArray(anchor.intersectingElements)) {
248
+ errors.push(`${path}.intersectingElements must be an array when present`)
249
+ }
250
+ }
251
+ return errors
252
+ }
253
+
254
+ /**
255
+ * Validate the click-time snapshot: what the page looked like at the instant
256
+ * the user marked it, which is the only thing a later reader may rely on.
257
+ * @param {unknown} snapshot
258
+ * @param {string} [path]
259
+ * @returns {string[]}
260
+ */
261
+ export function validateSnapshot(snapshot, path = 'snapshot') {
262
+ if (!isPlainObject(snapshot)) return [`${path} must be an object`]
263
+ const errors = []
264
+ if (!isString(snapshot.at) || Number.isNaN(Date.parse(snapshot.at))) {
265
+ errors.push(`${path}.at must be an ISO timestamp`)
266
+ }
267
+ if (!isRect(snapshot.rect)) errors.push(`${path}.rect must be {x,y,w,h} numbers`)
268
+ const viewport = snapshot.viewport
269
+ if (!isPlainObject(viewport)) errors.push(`${path}.viewport must be an object`)
270
+ else {
271
+ for (const key of ['width', 'height']) {
272
+ if (typeof viewport[key] !== 'number' || !Number.isFinite(viewport[key])) {
273
+ errors.push(`${path}.viewport.${key} must be a number`)
274
+ }
275
+ }
276
+ }
277
+ return errors
278
+ }
279
+
280
+ /**
281
+ * Validate a whole record as it crosses the wire.
282
+ * @param {unknown} record
283
+ * @returns {string[]}
284
+ */
285
+ export function validateRecord(record) {
286
+ /** @type {string[]} */
287
+ const errors = []
288
+ if (!isPlainObject(record)) return ['record must be an object']
289
+ if (!isString(record.id) || !ID_PATTERN.test(record.id)) errors.push('record.id must match an-<yyyymmdd>-<6 hex>')
290
+ if (!isString(record.url) || record.url.length === 0) errors.push('record.url must be a non-empty string')
291
+ else if (record.url.length > LIMITS.urlChars) errors.push(`record.url exceeds ${LIMITS.urlChars} characters`)
292
+ if (!isString(record.comment)) errors.push('record.comment must be a string')
293
+ else if (record.comment.length > LIMITS.commentChars) {
294
+ errors.push(`record.comment exceeds ${LIMITS.commentChars} characters`)
295
+ }
296
+ if (record.intent !== undefined && !INTENTS.includes(record.intent)) {
297
+ errors.push(`record.intent must be one of ${INTENTS.join('|')}`)
298
+ }
299
+ if (!STATES.includes(record.state)) errors.push(`record.state must be one of ${STATES.join('|')}`)
300
+ errors.push(...validateAnchor(record.anchor))
301
+ if (record.snapshot !== undefined) errors.push(...validateSnapshot(record.snapshot))
302
+ const routing = record.routing
303
+ if (!isPlainObject(routing)) errors.push('record.routing must be an object')
304
+ else if (!SOURCES.includes(routing.source)) errors.push(`record.routing.source must be one of ${SOURCES.join('|')}`)
305
+ if (isPlainObject(routing) && routing.label !== undefined) {
306
+ if (!isString(routing.label) || routing.label.length > LIMITS.labelChars) {
307
+ errors.push(`record.routing.label must be a string of at most ${LIMITS.labelChars} characters`)
308
+ }
309
+ }
310
+ if (!isString(record.createdAt) || Number.isNaN(Date.parse(record.createdAt))) {
311
+ errors.push('record.createdAt must be an ISO timestamp')
312
+ }
313
+ return errors
314
+ }
315
+
316
+ /**
317
+ * Fill the fields a client may omit. Never mutates the input.
318
+ * @param {Record<string, any>} input
319
+ * @param {{ now?: () => Date }} [clock]
320
+ */
321
+ export function normalizeRecord(input, clock = { now: () => new Date() }) {
322
+ const now = (clock.now ?? (() => new Date()))().toISOString()
323
+ const url = String(input.url ?? '')
324
+ let origin = ''
325
+ let pathname = ''
326
+ try {
327
+ const parsed = new URL(url)
328
+ // Only http(s) documents carry a routable origin; opaque schemes
329
+ // (`about:`, `file:`, `data:`) keep their raw URL and nothing else.
330
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
331
+ origin = parsed.origin
332
+ pathname = parsed.pathname
333
+ }
334
+ } catch {
335
+ // A restricted page has no parseable URL; the raw value still routes it.
336
+ }
337
+ const crops = isPlainObject(input.crops) ? input.crops : {}
338
+ const routing = isPlainObject(input.routing) ? input.routing : {}
339
+ const snapshot = normalizeSnapshot(input.snapshot)
340
+ return {
341
+ id: input.id,
342
+ url,
343
+ origin,
344
+ pathname,
345
+ title: String(input.title ?? '').slice(0, LIMITS.titleChars),
346
+ anchor: input.anchor,
347
+ comment: String(input.comment ?? '').slice(0, LIMITS.commentChars),
348
+ ...(input.intent === undefined ? {} : { intent: input.intent }),
349
+ ...(snapshot === undefined ? {} : { snapshot }),
350
+ crops: {
351
+ ...(isString(crops.target) ? { target: crops.target } : {}),
352
+ ...(isString(crops.viewport) ? { viewport: crops.viewport } : {}),
353
+ },
354
+ ...(isPlainObject(input.pageContext) ? { pageContext: input.pageContext } : {}),
355
+ routing: {
356
+ source: SOURCES.includes(routing.source) ? routing.source : 'user',
357
+ ...(isString(routing.sessionId) ? { sessionId: routing.sessionId } : {}),
358
+ ...(isString(routing.workspaceHint) ? { workspaceHint: routing.workspaceHint } : {}),
359
+ ...(isString(routing.label) ? { label: routing.label.slice(0, LIMITS.labelChars) } : {}),
360
+ },
361
+ state: STATES.includes(input.state) ? input.state : 'open',
362
+ createdAt: isString(input.createdAt) ? input.createdAt : now,
363
+ updatedAt: now,
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Keep the click-time snapshot that arrived on the wire, minus anything the
369
+ * reader could not render: it is a frozen fact, never recomputed, so a field it
370
+ * does not carry cannot be filled in later.
371
+ * @param {unknown} value
372
+ */
373
+ function normalizeSnapshot(value) {
374
+ if (!isPlainObject(value) || !isRect(value.rect)) return undefined
375
+ if (!isString(value.at) || Number.isNaN(Date.parse(value.at))) return undefined
376
+ const viewport = isPlainObject(value.viewport) ? value.viewport : {}
377
+ const number = (key) => (typeof viewport[key] === 'number' && Number.isFinite(viewport[key]) ? viewport[key] : 0)
378
+ const scrollX = number('scrollX')
379
+ const scrollY = number('scrollY')
380
+ return {
381
+ at: value.at,
382
+ rect: value.rect,
383
+ viewport: {
384
+ width: number('width'),
385
+ height: number('height'),
386
+ dpr: number('dpr'),
387
+ scrollX,
388
+ scrollY,
389
+ },
390
+ }
391
+ }
392
+
393
+ /** @param {string} text @param {number} max */
394
+ export function truncate(text, max) {
395
+ const value = String(text ?? '')
396
+ return value.length <= max ? value : `${value.slice(0, max - 1)}…`
397
+ }
398
+
399
+ /**
400
+ * Compact one-line preview used by `annotate_list` and the popup.
401
+ * @param {Record<string, any>} record
402
+ */
403
+ export function describeAnchor(record) {
404
+ const anchor = record.anchor
405
+ if (!anchor || typeof anchor !== 'object') return 'unknown anchor'
406
+ if (anchor.kind === 'selection') return `selection "${truncate(anchor.quote?.exact ?? '', 60)}"`
407
+ if (anchor.kind === 'element') {
408
+ const tag = anchor.fingerprint?.tag ?? 'element'
409
+ const text = truncate(anchor.fingerprint?.textExcerpt ?? '', 40)
410
+ return `element <${tag}>${text ? ` ${JSON.stringify(text)}` : ''}`
411
+ }
412
+ const page = anchor.pageRect ?? { x: 0, y: 0, w: 0, h: 0 }
413
+ return `region ${Math.round(page.w)}x${Math.round(page.h)} at ${Math.round(page.x)},${Math.round(page.y)}`
414
+ }
415
+
416
+ // ── mentions ────────────────────────────────────────────────────────────────
417
+
418
+ /**
419
+ * URI scheme of an annotation mention. The Web Client renders the Markdown
420
+ * mention as one atomic chip, and the Host resolves it at `agent/pre-step`;
421
+ * neither side ever trusts the label to carry identity.
422
+ */
423
+ export const ANNO_SCHEME = 'dsh-anno:'
424
+
425
+ /** Annotation ids are already URL-safe; anything else cannot be a mention. */
426
+ const ANNO_ID = /^[A-Za-z0-9_-]+$/
427
+
428
+ /** @param {string} label */
429
+ function escapeMentionLabel(label) {
430
+ return String(label).replace(/[\\[\]]/gu, (match) => `\\${match}`)
431
+ }
432
+
433
+ /** @param {string} label */
434
+ function unescapeMentionLabel(label) {
435
+ return label.replace(/\\(.)/gu, '$1')
436
+ }
437
+
438
+ /**
439
+ * Render the canonical mention for one annotation.
440
+ *
441
+ * The label is presentation only: it is what the chip shows and what the model
442
+ * reads in place of the token, so it may be localized and may repeat.
443
+ * @param {{ id: string, label: string }} reference
444
+ * @returns escaped `@[label](dsh-anno:id)` mention, or `''` for an unusable id.
445
+ */
446
+ export function formatAnnoMention(reference) {
447
+ const id = String(reference && reference.id)
448
+ if (!ANNO_ID.test(id)) return ''
449
+ const label = escapeMentionLabel(reference.label == null ? id : reference.label)
450
+ return `@[${label}](${ANNO_SCHEME}${id})`
451
+ }
452
+
453
+ /**
454
+ * Extract annotation mentions from one text value.
455
+ *
456
+ * Malformed mentions are left exactly as written: a user discussing the syntax
457
+ * must not lose their text, and a broken token is not a reference. Bare URIs
458
+ * are recognized too, because pasted text drops the Markdown brackets.
459
+ * @param {string} text
460
+ * @returns {{ text: string, references: { id: string, label: string }[] }} readable
461
+ * text with `@label` in place of each token, plus the references in appearance order.
462
+ */
463
+ export function parseAnnoText(text) {
464
+ const references = []
465
+ const source = String(text ?? '')
466
+ const pattern = /@\[((?:\\.|[^\\\]\n])*)\]\((dsh-anno:([A-Za-z0-9_-]+))\)|(?<![(\w])(dsh-anno:([A-Za-z0-9_-]+))/gu
467
+ const rendered = source.replace(pattern, (match, rawLabel, _markdownUri, markdownId, _bareUri, bareId) => {
468
+ const id = markdownId ?? bareId
469
+ /* istanbul ignore next -- the two-alternative regex always captures exactly one id. */
470
+ if (id === undefined) return match
471
+ const label = rawLabel === undefined ? id : unescapeMentionLabel(rawLabel)
472
+ references.push({ id, label })
473
+ return `@${label}`
474
+ })
475
+ return { text: rendered, references }
476
+ }
477
+
478
+ // ── frames ──────────────────────────────────────────────────────────────────
479
+
480
+ /** @param {unknown} value @param {number} [max] */
481
+ function optionalString(value, max = 200) {
482
+ if (value === undefined) return true
483
+ return typeof value === 'string' && value.length <= max
484
+ }
485
+
486
+ /** @param {unknown} value */
487
+ function optionalBase64(value) {
488
+ if (value === undefined) return true
489
+ return typeof value === 'string' && value.length > 0 && value.length <= LIMITS.imageBase64Chars
490
+ }
491
+
492
+ /**
493
+ * Parse text (or an already-decoded value) into a client frame.
494
+ * @param {string | Uint8Array | unknown} raw
495
+ * @returns {{ ok: true, frame: Record<string, any> } | { ok: false, reason: string }}
496
+ */
497
+ export function parseClientFrame(raw) {
498
+ let value = raw
499
+ if (typeof raw === 'string' || raw instanceof Uint8Array) {
500
+ const text = typeof raw === 'string' ? raw : new TextDecoder().decode(raw)
501
+ if (text.length > LIMITS.imageBase64Chars * 2) return { ok: false, reason: 'frame exceeds the size budget' }
502
+ try {
503
+ value = JSON.parse(text)
504
+ } catch {
505
+ return { ok: false, reason: 'frame is not valid JSON' }
506
+ }
507
+ }
508
+ if (!isPlainObject(value)) return { ok: false, reason: 'frame must be a JSON object' }
509
+ const type = value.t
510
+ if (typeof type !== 'string' || !CLIENT_FRAMES.includes(type)) {
511
+ return { ok: false, reason: `unknown client frame type ${JSON.stringify(type)}` }
512
+ }
513
+ if (!optionalString(value.reqId, 120)) return { ok: false, reason: 'reqId must be a short string' }
514
+
515
+ switch (type) {
516
+ case 'hello':
517
+ if (typeof value.token !== 'string' || value.token.length === 0) {
518
+ return { ok: false, reason: 'hello.token is required' }
519
+ }
520
+ if (typeof value.version !== 'number') return { ok: false, reason: 'hello.version must be a number' }
521
+ return { ok: true, frame: value }
522
+ case 'ping':
523
+ return { ok: true, frame: value }
524
+ case 'anno.create': {
525
+ const errors = validateRecord(value.record)
526
+ if (errors.length > 0) return { ok: false, reason: errors.join('; ') }
527
+ if (!optionalBase64(value.targetImageB64))
528
+ return { ok: false, reason: 'targetImageB64 is not a bounded base64 string' }
529
+ if (!optionalBase64(value.viewportImageB64)) {
530
+ return { ok: false, reason: 'viewportImageB64 is not a bounded base64 string' }
531
+ }
532
+ return { ok: true, frame: value }
533
+ }
534
+ case 'anno.query':
535
+ if (!optionalString(value.url, LIMITS.urlChars)) return { ok: false, reason: 'url filter must be a string' }
536
+ if (value.state !== undefined && value.state !== 'all' && !STATES.includes(value.state)) {
537
+ return { ok: false, reason: `state must be one of ${STATES.join('|')}|all` }
538
+ }
539
+ return { ok: true, frame: value }
540
+ case 'anno.mutate': {
541
+ if (typeof value.id !== 'string') return { ok: false, reason: 'anno.mutate.id is required' }
542
+ const actions = ['resolve', 'wont_fix', 'reopen', 'delete', 'edit']
543
+ if (!actions.includes(value.action))
544
+ return { ok: false, reason: `anno.mutate.action must be one of ${actions.join('|')}` }
545
+ if (!optionalString(value.note, LIMITS.noteChars)) return { ok: false, reason: 'note must be a bounded string' }
546
+ if (value.action === 'edit' && typeof value.comment !== 'string') {
547
+ return { ok: false, reason: 'edit requires comment' }
548
+ }
549
+ return { ok: true, frame: value }
550
+ }
551
+ case 'pick.result': {
552
+ if (typeof value.pickId !== 'string') return { ok: false, reason: 'pick.result.pickId is required' }
553
+ if (typeof value.ok !== 'boolean') return { ok: false, reason: 'pick.result.ok must be a boolean' }
554
+ if (value.ok) {
555
+ const errors = validateRecord(value.record)
556
+ if (errors.length > 0) return { ok: false, reason: errors.join('; ') }
557
+ } else if (!optionalString(value.reason, 400)) {
558
+ return { ok: false, reason: 'pick.result.reason must be a short string' }
559
+ }
560
+ return { ok: true, frame: value }
561
+ }
562
+ default:
563
+ return { ok: false, reason: `unhandled client frame ${type}` }
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Parse a host frame. The extension uses this to reject a compromised or
569
+ * stale host instead of trusting whatever arrives on the socket.
570
+ * @param {string | Uint8Array | unknown} raw
571
+ * @returns {{ ok: true, frame: Record<string, any> } | { ok: false, reason: string }}
572
+ */
573
+ export function parseServerFrame(raw) {
574
+ let value = raw
575
+ if (typeof raw === 'string' || raw instanceof Uint8Array) {
576
+ const text = typeof raw === 'string' ? raw : new TextDecoder().decode(raw)
577
+ try {
578
+ value = JSON.parse(text)
579
+ } catch {
580
+ return { ok: false, reason: 'frame is not valid JSON' }
581
+ }
582
+ }
583
+ if (!isPlainObject(value)) return { ok: false, reason: 'frame must be a JSON object' }
584
+ if (typeof value.t !== 'string' || !SERVER_FRAMES.includes(value.t)) {
585
+ return { ok: false, reason: `unknown server frame type ${JSON.stringify(value.t)}` }
586
+ }
587
+ return { ok: true, frame: value }
588
+ }
589
+
590
+ /** Encode a frame for the wire. */
591
+ export function encodeFrame(frame) {
592
+ return JSON.stringify(frame)
593
+ }
594
+
595
+ /**
596
+ * Two URLs point at the same document when only query and hash differ.
597
+ * @param {{ url?: string }} record
598
+ * @param {string} url
599
+ */
600
+ export function sameDocument(record, url) {
601
+ if (!record || typeof record.url !== 'string' || typeof url !== 'string') return false
602
+ if (record.url === url) return true
603
+ try {
604
+ const left = new URL(record.url)
605
+ const right = new URL(url)
606
+ return left.origin === right.origin && left.pathname === right.pathname
607
+ } catch {
608
+ return false
609
+ }
610
+ }