@blogmcp/sdk 0.7.1 → 0.8.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.
@@ -0,0 +1,158 @@
1
+ /**
2
+ * What a site's review route needs besides the session: response headers, the status page for a
3
+ * link that does not open, the attributes that tell the review layer where the article is, and the
4
+ * one-line bootstrap for sites without a framework wrapper.
5
+ */
6
+
7
+ import { REVIEW_FIELD_ATTR, REVIEW_IGNORE_ATTR, REVIEW_ROOT_ATTR } from './stamp'
8
+ import type { ReviewFailureReason } from './client'
9
+ import type { ReviewSession } from './types'
10
+
11
+ /**
12
+ * Headers for the review page (and its status pages). The page shows an unpublished draft behind a
13
+ * secret URL: never cached, never indexed, never framed, and the URL never leaves in a Referer.
14
+ */
15
+ export function reviewResponseHeaders(): Record<string, string> {
16
+ return {
17
+ 'Cache-Control': 'private, no-store',
18
+ 'X-Robots-Tag': 'noindex, nofollow',
19
+ 'Referrer-Policy': 'no-referrer',
20
+ 'X-Frame-Options': 'DENY',
21
+ }
22
+ }
23
+
24
+ /** Attributes for the element that holds the rendered article. */
25
+ export function reviewRootAttrs(): Record<string, string> {
26
+ return { [REVIEW_ROOT_ATTR]: '' }
27
+ }
28
+
29
+ /** Attributes for the title, description or featured image, so a comment on it names the field. */
30
+ export function reviewFieldAttrs(field: 'title' | 'description' | 'featuredImage'): Record<string, string> {
31
+ return { [REVIEW_FIELD_ATTR]: field }
32
+ }
33
+
34
+ /** Attributes for site chrome inside the article root that is not part of the article. */
35
+ export function reviewIgnoreAttrs(): Record<string, string> {
36
+ return { [REVIEW_IGNORE_ATTR]: '' }
37
+ }
38
+
39
+ export type ReviewLang = 'cs' | 'en'
40
+
41
+ type StatusText = { title: string; body: string }
42
+
43
+ const STATUS_TEXT: Readonly<Record<ReviewLang, Partial<Record<ReviewFailureReason, StatusText>> & { default: StatusText }>> = {
44
+ en: {
45
+ not_found: { title: 'Review link not found', body: 'Check that you opened the whole link, or ask for a new one.' },
46
+ expired: { title: 'This review link has expired', body: 'Ask for a new link to review the current draft.' },
47
+ revoked: { title: 'This review link was closed', body: 'Ask for a new link if you still want to review the draft.' },
48
+ superseded: { title: 'A newer review link replaced this one', body: 'Open the newest link you were sent.' },
49
+ unavailable: { title: 'Reviews are not available right now', body: 'Try again later.' },
50
+ rate_limited: { title: 'Too many requests', body: 'Wait a minute and reload the page.' },
51
+ network: { title: 'The review could not be loaded', body: 'Reload the page in a moment.' },
52
+ default: { title: 'The review could not be loaded', body: 'Reload the page in a moment.' },
53
+ },
54
+ cs: {
55
+ not_found: { title: 'Odkaz na recenzi neexistuje', body: 'Zkontrolujte, že jste otevřeli celý odkaz, nebo si řekněte o nový.' },
56
+ expired: { title: 'Platnost odkazu na recenzi vypršela', body: 'Řekněte si o nový odkaz na aktuální koncept.' },
57
+ revoked: { title: 'Odkaz na recenzi byl zrušen', body: 'Pokud chcete koncept ještě projít, řekněte si o nový odkaz.' },
58
+ superseded: { title: 'Tento odkaz nahradil novější', body: 'Otevřete nejnovější odkaz, který jste dostali.' },
59
+ unavailable: { title: 'Recenze teď nejsou dostupné', body: 'Zkuste to prosím později.' },
60
+ rate_limited: { title: 'Příliš mnoho požadavků', body: 'Chvíli počkejte a stránku načtěte znovu.' },
61
+ network: { title: 'Recenzi se nepodařilo načíst', body: 'Za chvíli stránku načtěte znovu.' },
62
+ default: { title: 'Recenzi se nepodařilo načíst', body: 'Za chvíli stránku načtěte znovu.' },
63
+ },
64
+ }
65
+
66
+ /** Title and sentence for a link that does not open, in the reviewer's language. */
67
+ export function reviewStatusText(reason: ReviewFailureReason, lang: string = 'en'): StatusText {
68
+ const table = STATUS_TEXT[lang.toLowerCase().startsWith('cs') ? 'cs' : 'en']
69
+ return table[reason] ?? table.default
70
+ }
71
+
72
+ function escapeHtml(text: string): string {
73
+ return text.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c] as string)
74
+ }
75
+
76
+ /**
77
+ * A self-contained fragment for a link that does not open (put it in the site's layout, or answer
78
+ * with it as is). Answer with `REVIEW_REASON_STATUS[reason]` and `reviewResponseHeaders()`.
79
+ */
80
+ export function renderReviewStatusHtml(reason: ReviewFailureReason, opts: { lang?: string } = {}): string {
81
+ const t = reviewStatusText(reason, opts.lang)
82
+ return (
83
+ `<section class="blogmcp-review-status" role="status" data-reason="${escapeHtml(reason)}">` +
84
+ `<h1>${escapeHtml(t.title)}</h1><p>${escapeHtml(t.body)}</p></section>`
85
+ )
86
+ }
87
+
88
+ /**
89
+ * The published build of the review layer for `<script>` use (`@blogmcp/review`, dist/global), pinned
90
+ * to an exact version: the page holds the review token, so what runs on it must not change under it.
91
+ * Self-host the file (`@blogmcp/review/global`) under a strict CSP or to add Subresource Integrity.
92
+ */
93
+ export const REVIEW_LAYER_SCRIPT_URL = 'https://cdn.jsdelivr.net/npm/@blogmcp/review@0.1.1/dist/blogmcp-review.global.js'
94
+ /** Id of the JSON island `reviewBootstrapHtml` writes the session into. */
95
+ export const REVIEW_SESSION_ELEMENT_ID = 'blogmcp-review-session'
96
+
97
+ export interface ReviewBootstrapOptions {
98
+ token: string
99
+ kbUrl: string
100
+ /** UI language of the layer; default: the article's. */
101
+ lang?: string
102
+ /** Where the layer's script comes from; default jsDelivr (`REVIEW_LAYER_SCRIPT_URL`). Self-host it under a strict CSP. */
103
+ scriptSrc?: string
104
+ /** CSP nonce for the two script tags. */
105
+ nonce?: string
106
+ }
107
+
108
+ /** JSON safe inside `<script>`: no `</script>`, no `<!--`, no line separators that end a JS string. */
109
+ function scriptJson(value: unknown): string {
110
+ return JSON.stringify(value)
111
+ .replace(/</g, '\\u003c')
112
+ .replace(/>/g, '\\u003e')
113
+ .replace(/&/g, '\\u0026')
114
+ .replace(/\u2028/g, '\\u2028')
115
+ .replace(/\u2029/g, '\\u2029')
116
+ }
117
+
118
+ /**
119
+ * The review layer for a site without a framework wrapper: the session as a JSON island (so the
120
+ * layer does not fetch it again and count a second view), the `<blogmcp-review>` element and its
121
+ * script. Put it at the end of `<body>`, after the article marked with `reviewRootAttrs()`.
122
+ */
123
+ export function reviewBootstrapHtml(session: ReviewSession, opts: ReviewBootstrapOptions): string {
124
+ const nonce = opts.nonce ? ` nonce="${escapeHtml(opts.nonce)}"` : ''
125
+ const lang = opts.lang ?? session.article.languageCode
126
+ return (
127
+ `<script type="application/json" id="${REVIEW_SESSION_ELEMENT_ID}"${nonce}>${scriptJson(session)}</script>` +
128
+ `<blogmcp-review session-id="${REVIEW_SESSION_ELEMENT_ID}" token="${escapeHtml(opts.token)}"` +
129
+ ` kb-url="${escapeHtml(opts.kbUrl)}" lang="${escapeHtml(lang)}"` +
130
+ (opts.nonce ? ` csp-nonce="${escapeHtml(opts.nonce)}"` : '') +
131
+ `></blogmcp-review>` +
132
+ `<script src="${escapeHtml(opts.scriptSrc ?? REVIEW_LAYER_SCRIPT_URL)}" defer${nonce}></script>`
133
+ )
134
+ }
135
+
136
+ /** A KB media reference in article source: optional origin, the route, the slug, an optional query. */
137
+ const MEDIA_REF_RE = /(?:https?:\/\/[^\s"'()<>]+?)?\/api\/(?:kb-)?media\/(file|thumb)\/([A-Za-z0-9][A-Za-z0-9._-]*)(\?[^\s"'()<>]*)?/g
138
+
139
+ /**
140
+ * The working copy as the review page should render it: every reference to a NON-public media item
141
+ * (`/api/media/file/<slug>`, `/api/media/thumb/<slug>`, with or without an origin) points at the
142
+ * signed URL the session carries for it, because the reviewer is anonymous to kb-api and the plain
143
+ * URL would answer 403 (page-review.md §5: the page renders referenced media at any tier). Public
144
+ * items, unknown slugs and everything else stay as they are, so a public draft renders exactly like
145
+ * the live page. Render this; pair the layer against the session's original `content` (the review
146
+ * layer does, offsets are unaffected either way).
147
+ *
148
+ * Components that take a bare `slug` and look the item up themselves are not covered; they show
149
+ * non-public items as missing.
150
+ */
151
+ export function reviewContentWithMedia(content: string, media: ReviewSession['media']): string {
152
+ return content.replace(MEDIA_REF_RE, (whole, route: string, rawSlug: string) => {
153
+ const dot = rawSlug.lastIndexOf('.')
154
+ const item = media[rawSlug] ?? (dot > 0 ? media[rawSlug.slice(0, dot)] : undefined)
155
+ if (!item || item.accessLevel === 'public') return whole
156
+ return route === 'thumb' ? item.thumbnailUrl : item.url
157
+ })
158
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The review plan: the working copy's addressable blocks — `mdx-N` id, body-relative
3
+ * `sourceRange`, and what each block should look like once a site has rendered it.
4
+ *
5
+ * The ids come from mdx-schema's `planArticleUnits`, the same split `@blogmcp/render-embed`'s
6
+ * `parseArticle` (the article-review app, md-editor) uses, so a comment's block id means the same
7
+ * block whichever surface produced it. `stampReviewDom` matches the plan against the site's own
8
+ * DOM; the plan itself renders nothing.
9
+ */
10
+
11
+ import { Marked } from 'marked'
12
+ import { planArticleUnits, type PlanLexToken } from '@blogmcp/mdx-schema/composables/parsing'
13
+
14
+ export interface ReviewPlanUnit {
15
+ /** `mdx-N`. */
16
+ nodeId: string
17
+ /** Offsets into the working copy's body (after the frontmatter). */
18
+ sourceRange: { start: number; end: number }
19
+ kind: 'markdown' | 'component'
20
+ /** The component name, or the markdown block's type (`heading`, `paragraph`, `list`, `code`, …; `span` when unsplit). */
21
+ type: string
22
+ /** Element tags (upper case) a site may render this block as; empty = any. Unused for components. */
23
+ tags: readonly string[]
24
+ /** The block's leading text, normalised (`normalizeReviewText`); '' when it has none. For a component: its children's. */
25
+ text: string
26
+ }
27
+
28
+ export interface ReviewPlan {
29
+ bodyOffset: number
30
+ units: ReviewPlanUnit[]
31
+ }
32
+
33
+ /** How far into a block's text the plan and the DOM are compared. */
34
+ const TEXT_PREFIX = 48
35
+
36
+ /**
37
+ * Text reduced to what survives any renderer: lower-case letters and digits only (diacritics kept),
38
+ * so markdown punctuation, smart quotes, dashes and whitespace never decide a match.
39
+ */
40
+ export function normalizeReviewText(text: string): string {
41
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
42
+ }
43
+
44
+ const ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }
45
+
46
+ /** Markdown inline source → roughly the text a renderer shows (links keep their label, images vanish). */
47
+ function inlineText(md: string): string {
48
+ return md
49
+ .replace(/<!--[\s\S]*?-->/g, '')
50
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
51
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
52
+ .replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1')
53
+ .replace(/<[^>]+>/g, ' ')
54
+ .replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi, (m, e: string) => {
55
+ if (e[0] === '#') {
56
+ const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)
57
+ return Number.isFinite(code) ? String.fromCodePoint(code) : m
58
+ }
59
+ return ENTITIES[e.toLowerCase()] ?? m
60
+ })
61
+ }
62
+
63
+ function hint(md: string): string {
64
+ return normalizeReviewText(inlineText(md)).slice(0, TEXT_PREFIX)
65
+ }
66
+
67
+ const HEADINGS = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'] as const
68
+ /** A paragraph holding only an image is often re-rendered as a figure or a bare image. */
69
+ const PARAGRAPH = ['P', 'FIGURE', 'IMG', 'PICTURE'] as const
70
+
71
+ function describe(token: PlanLexToken | null): { type: string; tags: readonly string[]; text: string } {
72
+ if (!token) return { type: 'span', tags: [], text: '' }
73
+ const t = token as PlanLexToken & {
74
+ text?: string
75
+ items?: Array<{ text?: string }>
76
+ header?: Array<{ text?: string }>
77
+ }
78
+ switch (t.type) {
79
+ case 'heading':
80
+ return { type: 'heading', tags: HEADINGS, text: hint(t.text ?? '') }
81
+ case 'paragraph':
82
+ return { type: 'paragraph', tags: PARAGRAPH, text: hint(t.text ?? '') }
83
+ case 'list':
84
+ return { type: 'list', tags: ['UL', 'OL'], text: hint(t.items?.[0]?.text ?? '') }
85
+ case 'code':
86
+ return { type: 'code', tags: ['PRE'], text: normalizeReviewText(t.text ?? '').slice(0, TEXT_PREFIX) }
87
+ case 'blockquote':
88
+ return { type: 'blockquote', tags: ['BLOCKQUOTE'], text: hint(t.text ?? '') }
89
+ case 'table':
90
+ return { type: 'table', tags: ['TABLE'], text: hint((t.header ?? []).map((h) => h.text ?? '').join(' ')) }
91
+ case 'hr':
92
+ return { type: 'hr', tags: ['HR'], text: '' }
93
+ default:
94
+ // `html` (a raw HTML block) and anything newer: no tag expectation, text only.
95
+ return { type: t.type, tags: [], text: hint(t.raw) }
96
+ }
97
+ }
98
+
99
+ let lexer: Marked | null = null
100
+
101
+ /**
102
+ * The plan of an article's working copy (`ReviewArticle.content`, frontmatter included).
103
+ * `bodyOffset` equals the session's `article.bodyOffset`.
104
+ */
105
+ export function createReviewPlan(content: string): ReviewPlan {
106
+ lexer ??= new Marked()
107
+ const m = lexer
108
+ const plan = planArticleUnits(content, (src) => m.lexer(src) as unknown as PlanLexToken[])
109
+ return {
110
+ bodyOffset: plan.bodyOffset,
111
+ units: plan.units.map((u) =>
112
+ u.kind === 'component'
113
+ ? // A component's text is its children's (a Callout's paragraph): it pairs the component
114
+ // with what a site renders when that site does not mark the root `data-mdx-component`.
115
+ { nodeId: u.nodeId, sourceRange: u.sourceRange, kind: 'component', type: u.name, tags: [], text: hint(u.children ?? '') }
116
+ : { nodeId: u.nodeId, sourceRange: u.sourceRange, kind: 'markdown', ...describe(u.token) },
117
+ ),
118
+ }
119
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Matching the review plan against a site's own rendered article, in the browser.
3
+ *
4
+ * A site renders the working copy with its own article view; the review layer must not change that
5
+ * view's markup. So instead of asking every renderer for a review mode, the layer walks the rendered
6
+ * article once, pairs each plan block with the element that shows it (by tag and leading text, and
7
+ * components by their `data-mdx-component`, which our renderers already emit), and puts ONE
8
+ * attribute on that element: `data-mdx-node-id`. No element is added, moved or wrapped. `restore()`
9
+ * takes the attributes off again.
10
+ *
11
+ * A component the site renders without `data-mdx-component` is paired through its children's
12
+ * text (its first block gets the id). Blocks that cannot be paired (a raw HTML block, a component
13
+ * with no text of its own and no marker, a heading the site moved into its own header) just stay
14
+ * unstamped: comments there fall back to
15
+ * quote + context (level 0), which works with any renderer. A renderer that already stamps
16
+ * `data-mdx-node-id` (`@blogmcp/render-embed-*`) is left as it is.
17
+ */
18
+
19
+ import { normalizeReviewText, type ReviewPlan, type ReviewPlanUnit } from './plan'
20
+ import type { ReviewNodeRef } from './types'
21
+
22
+ /** Put this on the element that holds the article (`reviewRootAttrs()`). */
23
+ export const REVIEW_ROOT_ATTR = 'data-blogmcp-review-root'
24
+ /** Put this on the title, description or featured image (`reviewFieldAttrs(…)`). */
25
+ export const REVIEW_FIELD_ATTR = 'data-blogmcp-review-field'
26
+ /** Elements (and their subtree) the layer must ignore: site chrome inside the article root. */
27
+ export const REVIEW_IGNORE_ATTR = 'data-blogmcp-review-ignore'
28
+
29
+ const NODE_ID_ATTR = 'data-mdx-node-id'
30
+ const COMPONENT_ATTR = 'data-mdx-component'
31
+
32
+ /** What kb-api accepts as a node's component (review.schema.ts `componentName`). */
33
+ const COMPONENT_RE = /^[A-Za-z0-9_.:-]{1,64}$/
34
+
35
+ function componentOf(el: Element): string | null {
36
+ const v = el.getAttribute(COMPONENT_ATTR)
37
+ return v ? v : null
38
+ }
39
+
40
+ /** Elements that are one block each; the walk does not look inside them. */
41
+ const BLOCK_TAGS = new Set([
42
+ 'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'PRE', 'BLOCKQUOTE', 'TABLE', 'HR',
43
+ 'FIGURE', 'IMG', 'PICTURE', 'DL', 'DETAILS',
44
+ ])
45
+ /** Never content. */
46
+ const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'BLOGMCP-REVIEW'])
47
+
48
+ /** How far ahead the matcher looks (plan blocks + elements skipped together) before giving up on a block. */
49
+ const LOOKAHEAD = 6
50
+ /** Shortest leading-text overlap that counts as the same block. */
51
+ const MIN_TEXT = 12
52
+
53
+ /** The element candidates in document order: component roots and block elements, never nested. */
54
+ function candidates(root: Element): Element[] {
55
+ const out: Element[] = []
56
+ const walk = (el: Element): void => {
57
+ for (const child of Array.from(el.children)) {
58
+ if (child.hasAttribute(REVIEW_IGNORE_ATTR) || child.hasAttribute(REVIEW_FIELD_ATTR)) continue
59
+ if (SKIP_TAGS.has(child.tagName.toUpperCase())) continue
60
+ if (componentOf(child) || BLOCK_TAGS.has(child.tagName.toUpperCase())) {
61
+ out.push(child)
62
+ continue
63
+ }
64
+ walk(child)
65
+ }
66
+ }
67
+ walk(root)
68
+ return out
69
+ }
70
+
71
+ function textMatches(want: string, el: Element): boolean {
72
+ const got = normalizeReviewText(el.textContent ?? '').slice(0, want.length)
73
+ if (!want || !got) return false
74
+ const n = Math.min(want.length, got.length, MIN_TEXT * 2)
75
+ if (n < Math.min(MIN_TEXT, want.length)) return false
76
+ return want.slice(0, n) === got.slice(0, n)
77
+ }
78
+
79
+ function pairs(unit: ReviewPlanUnit, el: Element): boolean {
80
+ const component = componentOf(el)
81
+ if (unit.kind === 'component') {
82
+ if (component) return component === unit.type
83
+ // A site component without `data-mdx-component`: its first block, by the children's text.
84
+ // Components with no text of their own (a gallery) stay unpaired.
85
+ return !!unit.text && textMatches(unit.text, el)
86
+ }
87
+ if (component) return false
88
+ if (unit.tags.length > 0 && !unit.tags.includes(el.tagName.toUpperCase())) return false
89
+ if (unit.text) return textMatches(unit.text, el)
90
+ // No text to compare: only a block whose tag says enough on its own (a rule, an image).
91
+ return unit.tags.length > 0 && (unit.type === 'hr' || !(el.textContent ?? '').trim())
92
+ }
93
+
94
+ export interface ReviewStamp {
95
+ /** 1 when at least one block carries an id (comments get block ids and source ranges), else 0. */
96
+ level: 0 | 1
97
+ matched: number
98
+ total: number
99
+ /** The block element of each id that is on the page. */
100
+ elements: ReadonlyMap<string, Element>
101
+ /** The block a node of the article belongs to, as a comment refers to it. */
102
+ nodeRef(node: Node | null): ReviewNodeRef | null
103
+ /** Take off every attribute this stamp put on. */
104
+ restore(): void
105
+ }
106
+
107
+ /** `mdx-3/child-1` (render-embed's nested ids) → `mdx-3`, the id the plan and kb-api know. */
108
+ function baseId(id: string): string {
109
+ return id.split('/')[0] ?? ''
110
+ }
111
+
112
+ /**
113
+ * Pair the plan with the article under `root` and stamp `data-mdx-node-id` on each paired element.
114
+ * Idempotent: an element that already carries an id keeps it.
115
+ */
116
+ export function stampReviewDom(root: Element, plan: ReviewPlan): ReviewStamp {
117
+ const byId = new Map(plan.units.map((u) => [u.nodeId, u]))
118
+ const elements = new Map<string, Element>()
119
+ const added: Element[] = []
120
+
121
+ const existing = Array.from(root.querySelectorAll(`[${NODE_ID_ATTR}]`))
122
+ if (existing.length > 0) {
123
+ for (const el of existing) {
124
+ const id = baseId(el.getAttribute(NODE_ID_ATTR) ?? '')
125
+ if (byId.has(id) && !elements.has(id)) elements.set(id, el)
126
+ }
127
+ } else {
128
+ const units = plan.units
129
+ const els = candidates(root)
130
+ let i = 0
131
+ let j = 0
132
+ while (i < units.length && j < els.length) {
133
+ const unit = units[i]!
134
+ const el = els[j]!
135
+ if (pairs(unit, el)) {
136
+ el.setAttribute(NODE_ID_ATTR, unit.nodeId)
137
+ added.push(el)
138
+ elements.set(unit.nodeId, el)
139
+ i++
140
+ j++
141
+ continue
142
+ }
143
+ let skip: [number, number] | null = null
144
+ for (let d = 1; d <= LOOKAHEAD && !skip; d++) {
145
+ for (let di = 0; di <= d; di++) {
146
+ const dj = d - di
147
+ if (i + di < units.length && j + dj < els.length && pairs(units[i + di]!, els[j + dj]!)) {
148
+ skip = [di, dj]
149
+ break
150
+ }
151
+ }
152
+ }
153
+ if (skip) {
154
+ i += skip[0]
155
+ j += skip[1]
156
+ } else {
157
+ i++ // this block is not on the page (or not recognisable): leave it unstamped
158
+ }
159
+ }
160
+ }
161
+
162
+ const nodeRef = (node: Node | null): ReviewNodeRef | null => {
163
+ let el: Element | null = node instanceof Element ? node : (node?.parentElement ?? null)
164
+ el = el?.closest(`[${NODE_ID_ATTR}]`) ?? null
165
+ if (!el || !root.contains(el)) return null
166
+ const id = baseId(el.getAttribute(NODE_ID_ATTR) ?? '')
167
+ const unit = byId.get(id)
168
+ if (!unit) return null
169
+ const named = componentOf(el)
170
+ // A site's own attribute value must not make the round invalid: fall back to the plan's
171
+ // component name (a component paired by its text), else the tag.
172
+ const component =
173
+ named && COMPONENT_RE.test(named)
174
+ ? named
175
+ : unit.kind === 'component' && COMPONENT_RE.test(unit.type)
176
+ ? unit.type
177
+ : el.tagName.toLowerCase()
178
+ return { id, component, sourceRange: { ...unit.sourceRange } }
179
+ }
180
+
181
+ return {
182
+ level: elements.size > 0 ? 1 : 0,
183
+ matched: elements.size,
184
+ total: plan.units.length,
185
+ elements,
186
+ nodeRef,
187
+ restore() {
188
+ for (const el of added) el.removeAttribute(NODE_ID_ATTR)
189
+ added.length = 0
190
+ },
191
+ }
192
+ }