@blogmcp/render-embed 0.1.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/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @blogmcp/render-embed
3
+ *
4
+ * Framework-agnostic core for the headless-renderer review overlay: the postMessage protocol
5
+ * (host ⇄ renderer), the canonical article parse (shared id space), host-side anchoring + untrusted-
6
+ * input clamps, and the two bridges. Framework wrappers (`@blogmcp/render-embed-vue` / `-react`)
7
+ * build on this; the host (article-review MCP-App / md-editor) uses `HostBridge`.
8
+ */
9
+
10
+ export * from './types.js'
11
+ export * from './protocol.js'
12
+ export * from './schema.js'
13
+ export * from './parse.js'
14
+ export * from './anchor.js'
15
+ export * from './media.js'
16
+ export { HostBridge } from './host.js'
17
+ export type {
18
+ HostBridgeOptions,
19
+ HostInitOpts,
20
+ NodeClickedEvent,
21
+ SelectionEvent,
22
+ FallbackReason,
23
+ } from './host.js'
24
+ export { RendererBridge } from './renderer.js'
25
+ export type { RendererBridgeOptions, RenderPayload } from './renderer.js'
package/src/media.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Media URL resolution. Per the design, media is absolutized exactly ONCE, host-side, before the
3
+ * blocks are pushed to the renderer (so the renderer never has to know the right base, and the
4
+ * browser makes no credentialed cross-origin fetch). Phase A ships the plain absolutize; the
5
+ * per-asset short-TTL signed-URL minting (the cross-domain capability) is wired in Phase C.
6
+ */
7
+
8
+ /** Absolutize a relative `/api/media/*` (or any root-relative) URL against the KB origin. */
9
+ export function resolveMediaUrl(src: string, kbOrigin: string): string {
10
+ if (!kbOrigin || typeof src !== 'string' || !src.startsWith('/')) return src
11
+ return kbOrigin.replace(/\/$/, '') + src
12
+ }
13
+
14
+ /** Whether a URL points at the KB media delivery route (the only path that needs absolutizing/signing). */
15
+ export function isKbMediaUrl(src: string): boolean {
16
+ return typeof src === 'string' && /\/api\/media\/(file|thumb|poster)\//.test(src)
17
+ }
package/src/parse.ts ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The canonical article parse — the single source of the markdown-block + MDX-component split that
3
+ * the article-review app's `mdx.ts` pioneered (lifted here so host + renderer + the screenshot
4
+ * fallback all share ONE id space). Pure (no Vue/React); the host injects its own `marked` (so the
5
+ * review app keeps its thumbnail image renderer; the blog passes its own).
6
+ *
7
+ * Each emitted `RenderUnit` carries `nodeId` ('mdx-<n>') + `sourceRange` (byte offsets into the
8
+ * post-frontmatter body) — host-assigned, the shared anchor key across live + fallback rendering.
9
+ */
10
+
11
+ import { Marked } from 'marked'
12
+ import { sanitizeHtml, sanitizeUrl } from '@blogmcp/sanitize'
13
+ import {
14
+ parseJsxProps,
15
+ stripFrontmatter,
16
+ HAS_MDX_RE,
17
+ MDX_COMPONENT_PATTERN,
18
+ } from '@blogmcp/mdx-schema/composables/parsing'
19
+ import type { ParsedArticle, RenderUnit, SourceRange } from './types.js'
20
+
21
+ /**
22
+ * Detects raw HTML in a markdown SOURCE — the fast-path-skip guard in `renderMarkdownSafe`.
23
+ * Matches `<`+letter (tag), `<!` (comment/doctype), `</` (closing); does NOT match bare `<` in
24
+ * text (`x < 3`) or entities. False-positive bias: when in doubt, sanitize (a false positive
25
+ * costs ~10ms; a false negative is XSS). Mirrors blog-sdk/core/markdown.ts's HAS_RAW_HTML_RE.
26
+ */
27
+ const HAS_RAW_HTML_RE = /<[a-zA-Z!/]/
28
+
29
+ /**
30
+ * A GFM `marked` instance whose `walkTokens` hook runs every link/image URL through `sanitizeUrl`
31
+ * (→ 'about:blank' for javascript:/data:/etc) ON THE TOKEN, leaving marked's DEFAULT renderer to
32
+ * emit the safe href with correct inner rendering + HTML escaping. This URL gate is the SECURITY
33
+ * PAIR for `renderMarkdownSafe`'s pre-scan skip: a pure-markdown source like `[x](javascript:alert(1))`
34
+ * carries no raw-HTML marker, so the skip bypasses DOMPurify — the sanitized token therefore can't
35
+ * emit a hostile href. Hosts passing their OWN marked to `parseArticle` MUST likewise emit safe
36
+ * URLs, or the pre-scan is unsafe for them.
37
+ *
38
+ * NB: this uses `walkTokens`, NOT custom link/image renderers — in marked v15 a renderer's token
39
+ * `text` is RAW markdown (not rendered HTML), so overriding the renderer emits literal `**bold**`
40
+ * and unescaped `&`/`<`. Mutating `token.href` preserves marked's correct rendering + escaping.
41
+ *
42
+ * Dependency-light (NO `@blogmcp/sdk`) to avoid a render-embed → blog-sdk cycle + the SSR
43
+ * src-resolution failure it caused; URL safety reuses `sanitizeUrl` from @blogmcp/sanitize.
44
+ */
45
+ export function createDefaultMarked(): Marked {
46
+ return new Marked({
47
+ walkTokens(token) {
48
+ if (token.type === 'link' || token.type === 'image') {
49
+ token.href = sanitizeUrl(token.href)
50
+ }
51
+ },
52
+ })
53
+ }
54
+
55
+ /**
56
+ * Render a markdown span to (conditionally sanitized) HTML — the `parseMarkdownSafe` equivalent,
57
+ * inlined. FAST PATH: when the SOURCE has no raw HTML, marked's output is safe by construction
58
+ * (known-tag whitelist) AND `createDefaultMarked` already URL-sanitized links/images, so the
59
+ * DOMPurify (jsdom, ~5-20ms) pass is SKIPPED — this is the dominant server-side jsdom cost on a
60
+ * typical pure-markdown article. Only raw-HTML sources pay the sanitize. SECURITY: the skip is
61
+ * safe ONLY because the `marked` instance emits safe URLs (see `createDefaultMarked`).
62
+ */
63
+ function renderMarkdownSafe(src: string, marked: Marked): string {
64
+ const html = marked.parse(src, { async: false }) as string
65
+ if (!HAS_RAW_HTML_RE.test(src)) return html
66
+ return sanitizeHtml(html)
67
+ }
68
+
69
+ /**
70
+ * Exact start offset of the trimmed body within `content` (mirrors `stripFrontmatter`: substring
71
+ * after the closing `---`, then `.trim()`). Lets a splice map a body-relative range to a
72
+ * full-content slice without an ambiguous `indexOf`.
73
+ */
74
+ export function computeBodyOffset(content: string): number {
75
+ if (!content) return 0
76
+ let preBodyEnd = 0
77
+ if (content.startsWith('---')) {
78
+ const endIndex = content.indexOf('---', 3)
79
+ if (endIndex === -1) return 0 // unterminated frontmatter → stripFrontmatter returns source as-is
80
+ preBodyEnd = endIndex + 3
81
+ } else {
82
+ return 0 // no frontmatter → stripFrontmatter returns source as-is (no trim)
83
+ }
84
+ const afterDelim = content.slice(preBodyEnd)
85
+ const leadingWs = afterDelim.length - afterDelim.trimStart().length
86
+ return preBodyEnd + leadingWs
87
+ }
88
+
89
+ /**
90
+ * Split a markdown span into top-level BLOCK units, each with its source range within `src`. Uses
91
+ * marked's block lexer (whose token `raw` values concatenate back to the input); GUARDS on that
92
+ * exact reconstruction (e.g. CRLF normalization breaks it) → returns `[]` so the caller falls back
93
+ * to one whole-span block and a splice can never write the wrong byte range. Each range is trimmed
94
+ * of trailing whitespace (editable slice = block text; the full token length still advances offset).
95
+ */
96
+ export function splitMarkdownBlocks(
97
+ src: string,
98
+ marked: Marked,
99
+ ): Array<{ html: string; sourceRange: SourceRange }> {
100
+ let tokens: Array<{ type: string; raw: string }>
101
+ try {
102
+ tokens = marked.lexer(src) as unknown as Array<{ type: string; raw: string }>
103
+ } catch {
104
+ return []
105
+ }
106
+ if (tokens.map((t) => t.raw).join('') !== src) return []
107
+ const blocks: Array<{ html: string; sourceRange: SourceRange }> = []
108
+ let offset = 0
109
+ for (const token of tokens) {
110
+ const start = offset
111
+ offset += token.raw.length
112
+ if (token.type === 'space' || !token.raw.trim()) continue
113
+ const trimmedLen = token.raw.replace(/\s+$/, '').length
114
+ blocks.push({
115
+ html: renderMarkdownSafe(token.raw, marked),
116
+ sourceRange: { start, end: start + trimmedLen },
117
+ })
118
+ }
119
+ return blocks
120
+ }
121
+
122
+ /**
123
+ * Parse article source into a `RenderUnit[]` (block-level html units + MDX component nodes), plus
124
+ * the post-frontmatter `body` and its `bodyOffset` within `content`.
125
+ */
126
+ export function parseArticle(content: string, marked: Marked = createDefaultMarked()): ParsedArticle {
127
+ if (!content) return { mode: 'html', html: '', items: [], body: '', bodyOffset: 0 }
128
+
129
+ const body = stripFrontmatter(content)
130
+ const bodyOffset = computeBodyOffset(content)
131
+
132
+ const items: RenderUnit[] = []
133
+ let nodeIndex = 0
134
+ const nextId = (): string => `mdx-${nodeIndex++}`
135
+
136
+ const pushMarkdownBlocks = (md: string, base: number): void => {
137
+ if (!md.trim()) return
138
+ const blocks = splitMarkdownBlocks(md, marked)
139
+ if (blocks.length > 0) {
140
+ for (const b of blocks) {
141
+ items.push({
142
+ type: 'html',
143
+ html: b.html,
144
+ nodeId: nextId(),
145
+ sourceRange: { start: base + b.sourceRange.start, end: base + b.sourceRange.end },
146
+ })
147
+ }
148
+ } else {
149
+ items.push({
150
+ type: 'html',
151
+ html: renderMarkdownSafe(md, marked),
152
+ nodeId: nextId(),
153
+ sourceRange: { start: base, end: base + md.length },
154
+ })
155
+ }
156
+ }
157
+
158
+ // Fast path: pure markdown.
159
+ if (!HAS_MDX_RE.test(body)) {
160
+ pushMarkdownBlocks(body, 0)
161
+ if (items.length > 0) return { mode: 'html', html: '', items, body, bodyOffset }
162
+ return { mode: 'html', html: renderMarkdownSafe(body, marked), items: [], body, bodyOffset }
163
+ }
164
+
165
+ // MDX path: markdown chunks (themselves block-split) interleaved with component nodes.
166
+ const componentRe = new RegExp(MDX_COMPONENT_PATTERN.source, 'g')
167
+ let lastIndex = 0
168
+ let match: RegExpExecArray | null
169
+
170
+ while ((match = componentRe.exec(body)) !== null) {
171
+ if (match.index > lastIndex) {
172
+ pushMarkdownBlocks(body.slice(lastIndex, match.index), lastIndex)
173
+ }
174
+ const name = match[1] || match[4] || ''
175
+ const propsStr = match[1] ? match[2] || '' : match[5] || ''
176
+ const children = match[3]
177
+ items.push({
178
+ type: 'component',
179
+ name,
180
+ props: parseJsxProps(propsStr),
181
+ children: children?.trim(),
182
+ nodeId: nextId(),
183
+ sourceRange: { start: match.index, end: match.index + match[0].length },
184
+ })
185
+ lastIndex = match.index + match[0].length
186
+ }
187
+
188
+ if (lastIndex < body.length) {
189
+ pushMarkdownBlocks(body.slice(lastIndex), lastIndex)
190
+ }
191
+
192
+ if (items.length === 0 && body.trim()) {
193
+ return { mode: 'html', html: renderMarkdownSafe(body, marked), items: [], body, bodyOffset }
194
+ }
195
+
196
+ const hasComponent = items.some((it) => it.type === 'component')
197
+ return { mode: hasComponent ? 'mdx' : 'html', html: '', items, body, bodyOffset }
198
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The render-embed postMessage protocol — single source of truth for message shapes + the
3
+ * (framework-agnostic, DOM-free) inbound-acceptance gate.
4
+ *
5
+ * Security model (the renderer iframe runs at an OPAQUE origin — `sandbox="allow-scripts"` without
6
+ * `allow-same-origin` — so `event.origin` is `"null"` and useless for auth):
7
+ * - Identity = `event.source === peerWindow` (checked in the DOM glue, host.ts/renderer.ts) +
8
+ * a per-load handshake `nonce` echoed on every frame + the `channel` discriminator.
9
+ * - Inbound payloads are validated against Zod schemas (schema.ts) BEFORE use.
10
+ * - `seq` is monotonic per sender → replay/dup guard.
11
+ * - Host→renderer messages carry ZERO authority (only scroll/highlight/re-render already-authorized
12
+ * content); renderer→host fields are all untrusted (validated/clamped host-side).
13
+ */
14
+
15
+ import type { RenderUnit, Rect } from './types.js'
16
+
17
+ /** Protocol channel id. Bump the trailing version for a breaking change (old peers stay silent). */
18
+ export const RENDER_EMBED_PROTOCOL = 'blogmcp.render-embed/1' as const
19
+
20
+ /** Highest protocol minor this build speaks. `version` negotiation picks `min(host, renderer)`. */
21
+ export const PROTOCOL_MAX_VERSION = 1
22
+
23
+ /** The known set of negotiable versions (never `min()` against an unbounded integer). */
24
+ export const KNOWN_VERSIONS: readonly number[] = [1]
25
+
26
+ export interface Envelope<T extends string, P> {
27
+ /** Discriminates our protocol from stray postMessage noise. */
28
+ channel: typeof RENDER_EMBED_PROTOCOL
29
+ /** Monotonic per-sender; replay/dedup guard. */
30
+ seq: number
31
+ /** Negotiated minor; 0 during handshake. */
32
+ v: number
33
+ /** Per-load handshake nonce; echoed every frame. */
34
+ nonce: string
35
+ type: T
36
+ payload: P
37
+ }
38
+
39
+ export interface ThemeSpec {
40
+ mode: 'light' | 'dark'
41
+ tokens?: Record<string, string>
42
+ }
43
+
44
+ // ---- Host → renderer ----------------------------------------------------------------------------
45
+
46
+ export type HostMessage =
47
+ | Envelope<'embed.init', {
48
+ maxVersion: number
49
+ theme: ThemeSpec
50
+ /** Advisory only; the renderer authenticates via the URL nonce, not this. */
51
+ hostOrigin: string
52
+ capabilities: { wantNodeEvents: boolean; wantSelection: boolean; wantHeight: boolean }
53
+ safeAreaInsets?: { top: number; right: number; bottom: number; left: number }
54
+ // NO token field — secrets never ride this channel.
55
+ }>
56
+ | Envelope<'embed.render', {
57
+ /** PRIMARY: app-parsed, id-stamped units. Media already absolutized server-side in `html`. */
58
+ blocks?: RenderUnit[]
59
+ /** ALT: only honored if the renderer advertised `canParse`. */
60
+ content?: string
61
+ language: string
62
+ }>
63
+ | Envelope<'embed.scrollToNode', { nodeId: string; behavior?: 'smooth' | 'auto' }>
64
+ | Envelope<'embed.highlight', { nodeIds: string[]; kind: 'comment' | 'selection' | 'clear' }>
65
+ | Envelope<'embed.setTheme', ThemeSpec>
66
+
67
+ // ---- Renderer → host ----------------------------------------------------------------------------
68
+
69
+ export interface RendererCapabilities {
70
+ canParse: boolean
71
+ /** true → stamps OUR ids (default); false → opaque handles the host can't validate. */
72
+ honorsNodeIds: boolean
73
+ nodeEvents: boolean
74
+ selection: boolean
75
+ height: boolean
76
+ /** Exposes SSR /preview/[token]?mode=production for the screenshot fallback. */
77
+ screenshotFallback: boolean
78
+ }
79
+
80
+ export type RendererMessage =
81
+ | Envelope<'embed.ready', { version: number; capabilities: RendererCapabilities }>
82
+ | Envelope<'embed.height', { px: number }>
83
+ | Envelope<'embed.nodeClicked', {
84
+ nodeId: string
85
+ rect: Rect
86
+ scroll: { top: number; left: number }
87
+ modifiers?: { meta: boolean; shift: boolean }
88
+ }>
89
+ | Envelope<'embed.selection', {
90
+ nodeId: string
91
+ startOffset: number
92
+ endOffset: number
93
+ /** Host DISCARDS this for storage and re-derives from `sourceRange`. Hint only. */
94
+ text: string
95
+ rect: Rect
96
+ scroll: { top: number; left: number }
97
+ }>
98
+ /** The id set actually painted — lets the host ack render completion (overlay-active gate). */
99
+ | Envelope<'embed.rendered', { units: { nodeId: string }[] }>
100
+ | Envelope<'embed.error', {
101
+ code: 'parse' | 'fetch' | 'token' | 'unsupported' | 'internal'
102
+ message: string
103
+ nodeId?: string
104
+ }>
105
+
106
+ export type AnyMessage = HostMessage | RendererMessage
107
+
108
+ /** Build a well-formed envelope. `seq` is supplied by the bridge's monotonic counter. */
109
+ export function makeEnvelope<T extends string, P>(
110
+ type: T,
111
+ payload: P,
112
+ ctx: { nonce: string; seq: number; v: number },
113
+ ): Envelope<T, P> {
114
+ return { channel: RENDER_EMBED_PROTOCOL, seq: ctx.seq, v: ctx.v, nonce: ctx.nonce, type, payload }
115
+ }
116
+
117
+ export interface AcceptContext {
118
+ /** The handshake nonce this side expects echoed. */
119
+ expectedNonce: string
120
+ /** Highest `seq` already accepted from the peer (monotonic guard). */
121
+ lastSeq: number
122
+ }
123
+
124
+ export type AcceptResult =
125
+ | { ok: true; seq: number }
126
+ | { ok: false; reason: 'not-our-channel' | 'bad-nonce' | 'replayed' | 'malformed' }
127
+
128
+ /**
129
+ * The DOM-free half of the inbound gate (the `event.source === peerWindow` check lives in the DOM
130
+ * glue, where the event is available). Runs BEFORE any payload is touched:
131
+ * 1. channel discriminator,
132
+ * 2. handshake nonce,
133
+ * 3. monotonic seq,
134
+ * 4. structural envelope shape (full payload validation is schema.ts's Zod, layered on top).
135
+ * Returns the parsed `seq` so the caller can advance `lastSeq` only on accept.
136
+ */
137
+ export function acceptEnvelope(raw: unknown, ctx: AcceptContext): AcceptResult {
138
+ if (!raw || typeof raw !== 'object') return { ok: false, reason: 'not-our-channel' }
139
+ const m = raw as Record<string, unknown>
140
+ if (m.channel !== RENDER_EMBED_PROTOCOL) return { ok: false, reason: 'not-our-channel' }
141
+ if (typeof m.nonce !== 'string' || m.nonce !== ctx.expectedNonce) return { ok: false, reason: 'bad-nonce' }
142
+ if (typeof m.seq !== 'number' || !Number.isFinite(m.seq)) return { ok: false, reason: 'malformed' }
143
+ if (m.seq <= ctx.lastSeq) return { ok: false, reason: 'replayed' }
144
+ if (typeof m.type !== 'string' || typeof m.v !== 'number' || !('payload' in m)) {
145
+ return { ok: false, reason: 'malformed' }
146
+ }
147
+ return { ok: true, seq: m.seq }
148
+ }
149
+
150
+ /** Pick the negotiated version: the highest known minor both sides speak, else null (incompatible). */
151
+ export function negotiateVersion(hostMax: number, rendererVersion: number): number | null {
152
+ const candidate = Math.min(hostMax, rendererVersion)
153
+ return KNOWN_VERSIONS.includes(candidate) ? candidate : null
154
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * RendererBridge — the renderer (customer / our blog / sim) side of the protocol. Framework-agnostic
3
+ * DOM glue the `-vue`/`-react` wrappers drive. In `mode:'production'` it installs NO listener and
4
+ * does NO reporting (inert passthrough); in `mode:'edit'` the full protocol is active.
5
+ *
6
+ * Identity: the renderer reads its per-load nonce from its own URL (`?n=`), validates inbound
7
+ * `event.source === window.parent` + the echoed nonce (NOT `event.origin`/`document.referrer` — the
8
+ * embedder may be opaque), and replies to the host with `targetOrigin:"*"` carrying only the echoed
9
+ * nonce (no secret).
10
+ */
11
+
12
+ import {
13
+ acceptEnvelope,
14
+ makeEnvelope,
15
+ PROTOCOL_MAX_VERSION,
16
+ KNOWN_VERSIONS,
17
+ type RendererCapabilities,
18
+ type ThemeSpec,
19
+ } from './protocol.js'
20
+ import { parseHostMessage } from './schema.js'
21
+ import type { RenderMode, RenderUnit } from './types.js'
22
+
23
+ export interface RenderPayload {
24
+ blocks?: RenderUnit[]
25
+ content?: string
26
+ language: string
27
+ }
28
+
29
+ export interface RendererBridgeOptions {
30
+ mode: RenderMode
31
+ /** What this renderer supports. Defaults: honors host ids, all events on, can't parse. */
32
+ capabilities?: Partial<RendererCapabilities>
33
+ onRender: (payload: RenderPayload) => void
34
+ onInit?: (init: { theme: ThemeSpec; safeAreaInsets?: { top: number; right: number; bottom: number; left: number } }) => void
35
+ onSetTheme?: (theme: ThemeSpec) => void
36
+ onScrollToNode?: (nodeId: string, behavior: 'smooth' | 'auto') => void
37
+ onHighlight?: (nodeIds: string[], kind: 'comment' | 'selection' | 'clear') => void
38
+ /** Window to bind to (default `window`); injectable for tests. */
39
+ win?: Window
40
+ }
41
+
42
+ export class RendererBridge {
43
+ private readonly win: Window
44
+ private readonly mode: RenderMode
45
+ private readonly caps: RendererCapabilities
46
+ private readonly nonce: string | null
47
+ private host: Window | null = null
48
+ private started = false
49
+ private seqOut = 0
50
+ private lastSeqIn = -1
51
+ private version = 0
52
+
53
+ constructor(private readonly opts: RendererBridgeOptions) {
54
+ this.win = opts.win ?? (globalThis as unknown as { window: Window }).window
55
+ this.mode = opts.mode
56
+ const search = (() => {
57
+ try {
58
+ return this.win.location?.search ?? ''
59
+ } catch {
60
+ return ''
61
+ }
62
+ })()
63
+ this.nonce = new URLSearchParams(search).get('n')
64
+ this.caps = {
65
+ canParse: false,
66
+ honorsNodeIds: true,
67
+ nodeEvents: true,
68
+ selection: true,
69
+ height: true,
70
+ screenshotFallback: true,
71
+ ...opts.capabilities,
72
+ }
73
+ }
74
+
75
+ /** Begin listening. NO-OP in production mode (inert passthrough). */
76
+ start(): void {
77
+ if (this.mode === 'production') return
78
+ this.win.addEventListener('message', this.onMessage)
79
+ }
80
+
81
+ destroy(): void {
82
+ this.win.removeEventListener('message', this.onMessage)
83
+ }
84
+
85
+ reportHeight(px: number): void {
86
+ this.toHost('embed.height', { px: Math.max(0, Math.round(px)) })
87
+ }
88
+
89
+ reportNodeClick(nodeId: string, el: Element, modifiers?: { meta: boolean; shift: boolean }): void {
90
+ const r = el.getBoundingClientRect()
91
+ this.toHost('embed.nodeClicked', {
92
+ nodeId,
93
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
94
+ scroll: { top: this.win.scrollY || 0, left: this.win.scrollX || 0 },
95
+ ...(modifiers ? { modifiers } : {}),
96
+ })
97
+ }
98
+
99
+ /** Report a DOM Selection — walks to the nearest `[data-mdx-node-id]` and computes block-relative offsets. */
100
+ reportSelection(sel: Selection): void {
101
+ if (sel.rangeCount === 0 || sel.isCollapsed) return
102
+ const range = sel.getRangeAt(0)
103
+ const startEl = (range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentElement) as Element | null
104
+ const block = startEl?.closest('[data-mdx-node-id]') as HTMLElement | null
105
+ const nodeId = block?.getAttribute('data-mdx-node-id')
106
+ if (!block || !nodeId) return
107
+ const pre = this.win.document.createRange()
108
+ pre.selectNodeContents(block)
109
+ try {
110
+ pre.setEnd(range.startContainer, range.startOffset)
111
+ } catch {
112
+ return
113
+ }
114
+ const startOffset = pre.toString().length
115
+ const text = sel.toString()
116
+ const r = range.getBoundingClientRect()
117
+ this.toHost('embed.selection', {
118
+ nodeId,
119
+ startOffset,
120
+ endOffset: startOffset + text.length,
121
+ text,
122
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
123
+ scroll: { top: this.win.scrollY || 0, left: this.win.scrollX || 0 },
124
+ })
125
+ }
126
+
127
+ /** Acknowledge the id set actually painted (host's overlay-active gate). */
128
+ reportRendered(nodeIds: string[]): void {
129
+ this.toHost('embed.rendered', { units: nodeIds.map((nodeId) => ({ nodeId })) })
130
+ }
131
+
132
+ reportError(code: 'parse' | 'fetch' | 'token' | 'unsupported' | 'internal', message: string, nodeId?: string): void {
133
+ this.toHost('embed.error', { code, message, ...(nodeId ? { nodeId } : {}) })
134
+ }
135
+
136
+ // ---- internals ----
137
+
138
+ private toHost(type: string, payload: unknown): void {
139
+ if (!this.host || !this.started || !this.nonce) return
140
+ const env = makeEnvelope(type, payload, { nonce: this.nonce, seq: this.seqOut++, v: this.version })
141
+ // Host origin is opaque → "*" is unavoidable, but the message carries no secret (only the
142
+ // echoed nonce, which authenticates the renderer to the host).
143
+ this.host.postMessage(env, '*')
144
+ }
145
+
146
+ private onMessage = (event: MessageEvent): void => {
147
+ // Identity: parent-window only + echoed nonce (NOT event.origin — embedder may be opaque).
148
+ if (!this.nonce) return
149
+ if (event.source !== this.win.parent) return
150
+ const accepted = acceptEnvelope(event.data, { expectedNonce: this.nonce, lastSeq: this.lastSeqIn })
151
+ if (!accepted.ok) return
152
+ const parsed = parseHostMessage(event.data)
153
+ if (!parsed.success) return
154
+ this.lastSeqIn = accepted.seq
155
+ const msg = parsed.data as { type: string; payload: Record<string, unknown> }
156
+
157
+ switch (msg.type) {
158
+ case 'embed.init': {
159
+ if (this.started) return // single-init latch
160
+ const p = msg.payload as { maxVersion: number; theme: ThemeSpec; safeAreaInsets?: { top: number; right: number; bottom: number; left: number } }
161
+ const negotiated = Math.min(p.maxVersion, PROTOCOL_MAX_VERSION)
162
+ if (!KNOWN_VERSIONS.includes(negotiated)) {
163
+ // Incompatible: tell the host directly (don't latch `started`, so we stay inert).
164
+ const env = makeEnvelope(
165
+ 'embed.error',
166
+ { code: 'unsupported', message: 'no common protocol version' },
167
+ { nonce: this.nonce, seq: this.seqOut++, v: 0 },
168
+ )
169
+ ;(event.source as Window).postMessage(env, '*')
170
+ return
171
+ }
172
+ this.host = event.source as Window
173
+ this.version = negotiated
174
+ this.started = true
175
+ this.toHost('embed.ready', { version: negotiated, capabilities: this.caps })
176
+ this.opts.onInit?.({ theme: p.theme, safeAreaInsets: p.safeAreaInsets })
177
+ return
178
+ }
179
+ case 'embed.render':
180
+ this.opts.onRender(msg.payload as unknown as RenderPayload)
181
+ return
182
+ case 'embed.setTheme':
183
+ this.opts.onSetTheme?.(msg.payload as unknown as ThemeSpec)
184
+ return
185
+ case 'embed.scrollToNode': {
186
+ const p = msg.payload as { nodeId: string; behavior?: 'smooth' | 'auto' }
187
+ this.opts.onScrollToNode?.(p.nodeId, p.behavior ?? 'smooth')
188
+ return
189
+ }
190
+ case 'embed.highlight': {
191
+ const p = msg.payload as { nodeIds: string[]; kind: 'comment' | 'selection' | 'clear' }
192
+ this.opts.onHighlight?.(p.nodeIds, p.kind)
193
+ return
194
+ }
195
+ }
196
+ }
197
+ }