@blogmcp/sdk 0.7.0 → 0.8.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/dist/core/auth.js +21 -21
- package/dist/core/index.js +88 -65
- package/dist/core/review/client.d.ts +125 -0
- package/dist/core/review/client.js +116 -0
- package/dist/core/review/index.d.ts +7 -1
- package/dist/core/review/index.js +27 -4
- package/dist/core/review/page.d.ts +70 -0
- package/dist/core/review/page.js +78 -0
- package/dist/core/review/plan.d.ts +39 -0
- package/dist/core/review/plan.js +57 -0
- package/dist/core/review/stamp.d.ts +40 -0
- package/dist/core/review/stamp.js +106 -0
- package/package.json +3 -3
- package/src/core/auth.ts +5 -1
- package/src/core/review/client.ts +275 -0
- package/src/core/review/index.ts +39 -1
- package/src/core/review/page.ts +158 -0
- package/src/core/review/plan.ts +117 -0
- package/src/core/review/stamp.ts +179 -0
package/src/core/review/index.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Review links — review a draft on your own article page (docs: "Add review to your
|
|
3
|
-
* frontend").
|
|
3
|
+
* frontend"). Framework-free: wire types and the agent formatter (server code such as
|
|
4
|
+
* md-editor's MCP tools), the page API client, the helpers a site's review route needs,
|
|
5
|
+
* and the block plan + DOM matching the review layer (`@blogmcp/review`) is built on.
|
|
4
6
|
*/
|
|
5
7
|
export {
|
|
6
8
|
REVIEW_PAGE_PATH,
|
|
@@ -20,3 +22,39 @@ export {
|
|
|
20
22
|
type StoredReviewRound,
|
|
21
23
|
} from './types'
|
|
22
24
|
export { formatReviewRound, formatReviewForAgent } from './format'
|
|
25
|
+
export {
|
|
26
|
+
getReviewSession,
|
|
27
|
+
createReviewClient,
|
|
28
|
+
REVIEW_REASON_STATUS,
|
|
29
|
+
type ReviewFailureReason,
|
|
30
|
+
type ReviewFailure,
|
|
31
|
+
type ReviewResult,
|
|
32
|
+
type ReviewTransportOptions,
|
|
33
|
+
type GetReviewSessionOptions,
|
|
34
|
+
type ReviewMediaQuery,
|
|
35
|
+
type ReviewSubmitAnswer,
|
|
36
|
+
type ReviewClient,
|
|
37
|
+
type ReviewClientOptions,
|
|
38
|
+
} from './client'
|
|
39
|
+
export {
|
|
40
|
+
reviewResponseHeaders,
|
|
41
|
+
reviewRootAttrs,
|
|
42
|
+
reviewFieldAttrs,
|
|
43
|
+
reviewIgnoreAttrs,
|
|
44
|
+
reviewStatusText,
|
|
45
|
+
renderReviewStatusHtml,
|
|
46
|
+
reviewBootstrapHtml,
|
|
47
|
+
reviewContentWithMedia,
|
|
48
|
+
REVIEW_LAYER_SCRIPT_URL,
|
|
49
|
+
REVIEW_SESSION_ELEMENT_ID,
|
|
50
|
+
type ReviewLang,
|
|
51
|
+
type ReviewBootstrapOptions,
|
|
52
|
+
} from './page'
|
|
53
|
+
export { createReviewPlan, normalizeReviewText, type ReviewPlan, type ReviewPlanUnit } from './plan'
|
|
54
|
+
export {
|
|
55
|
+
stampReviewDom,
|
|
56
|
+
REVIEW_ROOT_ATTR,
|
|
57
|
+
REVIEW_FIELD_ATTR,
|
|
58
|
+
REVIEW_IGNORE_ATTR,
|
|
59
|
+
type ReviewStamp,
|
|
60
|
+
} from './stamp'
|
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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.0/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,117 @@
|
|
|
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. */
|
|
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
|
+
? { nodeId: u.nodeId, sourceRange: u.sourceRange, kind: 'component', type: u.name, tags: [], text: '' }
|
|
114
|
+
: { nodeId: u.nodeId, sourceRange: u.sourceRange, kind: 'markdown', ...describe(u.token) },
|
|
115
|
+
),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
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
|
+
* Blocks that cannot be paired (a raw HTML block, a custom component without `data-mdx-component`,
|
|
12
|
+
* a heading the site moved into its own header) just stay unstamped: comments there fall back to
|
|
13
|
+
* quote + context (level 0), which works with any renderer. A renderer that already stamps
|
|
14
|
+
* `data-mdx-node-id` (`@blogmcp/render-embed-*`) is left as it is.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { normalizeReviewText, type ReviewPlan, type ReviewPlanUnit } from './plan'
|
|
18
|
+
import type { ReviewNodeRef } from './types'
|
|
19
|
+
|
|
20
|
+
/** Put this on the element that holds the article (`reviewRootAttrs()`). */
|
|
21
|
+
export const REVIEW_ROOT_ATTR = 'data-blogmcp-review-root'
|
|
22
|
+
/** Put this on the title, description or featured image (`reviewFieldAttrs(…)`). */
|
|
23
|
+
export const REVIEW_FIELD_ATTR = 'data-blogmcp-review-field'
|
|
24
|
+
/** Elements (and their subtree) the layer must ignore: site chrome inside the article root. */
|
|
25
|
+
export const REVIEW_IGNORE_ATTR = 'data-blogmcp-review-ignore'
|
|
26
|
+
|
|
27
|
+
const NODE_ID_ATTR = 'data-mdx-node-id'
|
|
28
|
+
const COMPONENT_ATTR = 'data-mdx-component'
|
|
29
|
+
|
|
30
|
+
/** What kb-api accepts as a node's component (review.schema.ts `componentName`). */
|
|
31
|
+
const COMPONENT_RE = /^[A-Za-z0-9_.:-]{1,64}$/
|
|
32
|
+
|
|
33
|
+
function componentOf(el: Element): string | null {
|
|
34
|
+
const v = el.getAttribute(COMPONENT_ATTR)
|
|
35
|
+
return v ? v : null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Elements that are one block each; the walk does not look inside them. */
|
|
39
|
+
const BLOCK_TAGS = new Set([
|
|
40
|
+
'P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'PRE', 'BLOCKQUOTE', 'TABLE', 'HR',
|
|
41
|
+
'FIGURE', 'IMG', 'PICTURE', 'DL', 'DETAILS',
|
|
42
|
+
])
|
|
43
|
+
/** Never content. */
|
|
44
|
+
const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT', 'BLOGMCP-REVIEW'])
|
|
45
|
+
|
|
46
|
+
/** How far ahead the matcher looks (plan blocks + elements skipped together) before giving up on a block. */
|
|
47
|
+
const LOOKAHEAD = 6
|
|
48
|
+
/** Shortest leading-text overlap that counts as the same block. */
|
|
49
|
+
const MIN_TEXT = 12
|
|
50
|
+
|
|
51
|
+
/** The element candidates in document order: component roots and block elements, never nested. */
|
|
52
|
+
function candidates(root: Element): Element[] {
|
|
53
|
+
const out: Element[] = []
|
|
54
|
+
const walk = (el: Element): void => {
|
|
55
|
+
for (const child of Array.from(el.children)) {
|
|
56
|
+
if (child.hasAttribute(REVIEW_IGNORE_ATTR) || child.hasAttribute(REVIEW_FIELD_ATTR)) continue
|
|
57
|
+
if (SKIP_TAGS.has(child.tagName.toUpperCase())) continue
|
|
58
|
+
if (componentOf(child) || BLOCK_TAGS.has(child.tagName.toUpperCase())) {
|
|
59
|
+
out.push(child)
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
walk(child)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
walk(root)
|
|
66
|
+
return out
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function textMatches(want: string, el: Element): boolean {
|
|
70
|
+
const got = normalizeReviewText(el.textContent ?? '').slice(0, want.length)
|
|
71
|
+
if (!want || !got) return false
|
|
72
|
+
const n = Math.min(want.length, got.length, MIN_TEXT * 2)
|
|
73
|
+
if (n < Math.min(MIN_TEXT, want.length)) return false
|
|
74
|
+
return want.slice(0, n) === got.slice(0, n)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function pairs(unit: ReviewPlanUnit, el: Element): boolean {
|
|
78
|
+
const component = componentOf(el)
|
|
79
|
+
if (unit.kind === 'component') return component === unit.type
|
|
80
|
+
if (component) return false
|
|
81
|
+
if (unit.tags.length > 0 && !unit.tags.includes(el.tagName.toUpperCase())) return false
|
|
82
|
+
if (unit.text) return textMatches(unit.text, el)
|
|
83
|
+
// No text to compare: only a block whose tag says enough on its own (a rule, an image).
|
|
84
|
+
return unit.tags.length > 0 && (unit.type === 'hr' || !(el.textContent ?? '').trim())
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ReviewStamp {
|
|
88
|
+
/** 1 when at least one block carries an id (comments get block ids and source ranges), else 0. */
|
|
89
|
+
level: 0 | 1
|
|
90
|
+
matched: number
|
|
91
|
+
total: number
|
|
92
|
+
/** The block element of each id that is on the page. */
|
|
93
|
+
elements: ReadonlyMap<string, Element>
|
|
94
|
+
/** The block a node of the article belongs to, as a comment refers to it. */
|
|
95
|
+
nodeRef(node: Node | null): ReviewNodeRef | null
|
|
96
|
+
/** Take off every attribute this stamp put on. */
|
|
97
|
+
restore(): void
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `mdx-3/child-1` (render-embed's nested ids) → `mdx-3`, the id the plan and kb-api know. */
|
|
101
|
+
function baseId(id: string): string {
|
|
102
|
+
return id.split('/')[0] ?? ''
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Pair the plan with the article under `root` and stamp `data-mdx-node-id` on each paired element.
|
|
107
|
+
* Idempotent: an element that already carries an id keeps it.
|
|
108
|
+
*/
|
|
109
|
+
export function stampReviewDom(root: Element, plan: ReviewPlan): ReviewStamp {
|
|
110
|
+
const byId = new Map(plan.units.map((u) => [u.nodeId, u]))
|
|
111
|
+
const elements = new Map<string, Element>()
|
|
112
|
+
const added: Element[] = []
|
|
113
|
+
|
|
114
|
+
const existing = Array.from(root.querySelectorAll(`[${NODE_ID_ATTR}]`))
|
|
115
|
+
if (existing.length > 0) {
|
|
116
|
+
for (const el of existing) {
|
|
117
|
+
const id = baseId(el.getAttribute(NODE_ID_ATTR) ?? '')
|
|
118
|
+
if (byId.has(id) && !elements.has(id)) elements.set(id, el)
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
const units = plan.units
|
|
122
|
+
const els = candidates(root)
|
|
123
|
+
let i = 0
|
|
124
|
+
let j = 0
|
|
125
|
+
while (i < units.length && j < els.length) {
|
|
126
|
+
const unit = units[i]!
|
|
127
|
+
const el = els[j]!
|
|
128
|
+
if (pairs(unit, el)) {
|
|
129
|
+
el.setAttribute(NODE_ID_ATTR, unit.nodeId)
|
|
130
|
+
added.push(el)
|
|
131
|
+
elements.set(unit.nodeId, el)
|
|
132
|
+
i++
|
|
133
|
+
j++
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
let skip: [number, number] | null = null
|
|
137
|
+
for (let d = 1; d <= LOOKAHEAD && !skip; d++) {
|
|
138
|
+
for (let di = 0; di <= d; di++) {
|
|
139
|
+
const dj = d - di
|
|
140
|
+
if (i + di < units.length && j + dj < els.length && pairs(units[i + di]!, els[j + dj]!)) {
|
|
141
|
+
skip = [di, dj]
|
|
142
|
+
break
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (skip) {
|
|
147
|
+
i += skip[0]
|
|
148
|
+
j += skip[1]
|
|
149
|
+
} else {
|
|
150
|
+
i++ // this block is not on the page (or not recognisable): leave it unstamped
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const nodeRef = (node: Node | null): ReviewNodeRef | null => {
|
|
156
|
+
let el: Element | null = node instanceof Element ? node : (node?.parentElement ?? null)
|
|
157
|
+
el = el?.closest(`[${NODE_ID_ATTR}]`) ?? null
|
|
158
|
+
if (!el || !root.contains(el)) return null
|
|
159
|
+
const id = baseId(el.getAttribute(NODE_ID_ATTR) ?? '')
|
|
160
|
+
const unit = byId.get(id)
|
|
161
|
+
if (!unit) return null
|
|
162
|
+
const named = componentOf(el)
|
|
163
|
+
// A site's own attribute value must not make the round invalid: fall back to the tag.
|
|
164
|
+
const component = named && COMPONENT_RE.test(named) ? named : el.tagName.toLowerCase()
|
|
165
|
+
return { id, component, sourceRange: { ...unit.sourceRange } }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
level: elements.size > 0 ? 1 : 0,
|
|
170
|
+
matched: elements.size,
|
|
171
|
+
total: plan.units.length,
|
|
172
|
+
elements,
|
|
173
|
+
nodeRef,
|
|
174
|
+
restore() {
|
|
175
|
+
for (const el of added) el.removeAttribute(NODE_ID_ATTR)
|
|
176
|
+
added.length = 0
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
}
|