@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/dist/parse.js ADDED
@@ -0,0 +1,185 @@
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
+ import { Marked } from 'marked';
11
+ import { sanitizeHtml, sanitizeUrl } from '@blogmcp/sanitize';
12
+ import { parseJsxProps, stripFrontmatter, HAS_MDX_RE, MDX_COMPONENT_PATTERN, } from '@blogmcp/mdx-schema/composables/parsing';
13
+ /**
14
+ * Detects raw HTML in a markdown SOURCE — the fast-path-skip guard in `renderMarkdownSafe`.
15
+ * Matches `<`+letter (tag), `<!` (comment/doctype), `</` (closing); does NOT match bare `<` in
16
+ * text (`x < 3`) or entities. False-positive bias: when in doubt, sanitize (a false positive
17
+ * costs ~10ms; a false negative is XSS). Mirrors blog-sdk/core/markdown.ts's HAS_RAW_HTML_RE.
18
+ */
19
+ const HAS_RAW_HTML_RE = /<[a-zA-Z!/]/;
20
+ /**
21
+ * A GFM `marked` instance whose `walkTokens` hook runs every link/image URL through `sanitizeUrl`
22
+ * (→ 'about:blank' for javascript:/data:/etc) ON THE TOKEN, leaving marked's DEFAULT renderer to
23
+ * emit the safe href with correct inner rendering + HTML escaping. This URL gate is the SECURITY
24
+ * PAIR for `renderMarkdownSafe`'s pre-scan skip: a pure-markdown source like `[x](javascript:alert(1))`
25
+ * carries no raw-HTML marker, so the skip bypasses DOMPurify — the sanitized token therefore can't
26
+ * emit a hostile href. Hosts passing their OWN marked to `parseArticle` MUST likewise emit safe
27
+ * URLs, or the pre-scan is unsafe for them.
28
+ *
29
+ * NB: this uses `walkTokens`, NOT custom link/image renderers — in marked v15 a renderer's token
30
+ * `text` is RAW markdown (not rendered HTML), so overriding the renderer emits literal `**bold**`
31
+ * and unescaped `&`/`<`. Mutating `token.href` preserves marked's correct rendering + escaping.
32
+ *
33
+ * Dependency-light (NO `@blogmcp/sdk`) to avoid a render-embed → blog-sdk cycle + the SSR
34
+ * src-resolution failure it caused; URL safety reuses `sanitizeUrl` from @blogmcp/sanitize.
35
+ */
36
+ export function createDefaultMarked() {
37
+ return new Marked({
38
+ walkTokens(token) {
39
+ if (token.type === 'link' || token.type === 'image') {
40
+ token.href = sanitizeUrl(token.href);
41
+ }
42
+ },
43
+ });
44
+ }
45
+ /**
46
+ * Render a markdown span to (conditionally sanitized) HTML — the `parseMarkdownSafe` equivalent,
47
+ * inlined. FAST PATH: when the SOURCE has no raw HTML, marked's output is safe by construction
48
+ * (known-tag whitelist) AND `createDefaultMarked` already URL-sanitized links/images, so the
49
+ * DOMPurify (jsdom, ~5-20ms) pass is SKIPPED — this is the dominant server-side jsdom cost on a
50
+ * typical pure-markdown article. Only raw-HTML sources pay the sanitize. SECURITY: the skip is
51
+ * safe ONLY because the `marked` instance emits safe URLs (see `createDefaultMarked`).
52
+ */
53
+ function renderMarkdownSafe(src, marked) {
54
+ const html = marked.parse(src, { async: false });
55
+ if (!HAS_RAW_HTML_RE.test(src))
56
+ return html;
57
+ return sanitizeHtml(html);
58
+ }
59
+ /**
60
+ * Exact start offset of the trimmed body within `content` (mirrors `stripFrontmatter`: substring
61
+ * after the closing `---`, then `.trim()`). Lets a splice map a body-relative range to a
62
+ * full-content slice without an ambiguous `indexOf`.
63
+ */
64
+ export function computeBodyOffset(content) {
65
+ if (!content)
66
+ return 0;
67
+ let preBodyEnd = 0;
68
+ if (content.startsWith('---')) {
69
+ const endIndex = content.indexOf('---', 3);
70
+ if (endIndex === -1)
71
+ return 0; // unterminated frontmatter → stripFrontmatter returns source as-is
72
+ preBodyEnd = endIndex + 3;
73
+ }
74
+ else {
75
+ return 0; // no frontmatter → stripFrontmatter returns source as-is (no trim)
76
+ }
77
+ const afterDelim = content.slice(preBodyEnd);
78
+ const leadingWs = afterDelim.length - afterDelim.trimStart().length;
79
+ return preBodyEnd + leadingWs;
80
+ }
81
+ /**
82
+ * Split a markdown span into top-level BLOCK units, each with its source range within `src`. Uses
83
+ * marked's block lexer (whose token `raw` values concatenate back to the input); GUARDS on that
84
+ * exact reconstruction (e.g. CRLF normalization breaks it) → returns `[]` so the caller falls back
85
+ * to one whole-span block and a splice can never write the wrong byte range. Each range is trimmed
86
+ * of trailing whitespace (editable slice = block text; the full token length still advances offset).
87
+ */
88
+ export function splitMarkdownBlocks(src, marked) {
89
+ let tokens;
90
+ try {
91
+ tokens = marked.lexer(src);
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ if (tokens.map((t) => t.raw).join('') !== src)
97
+ return [];
98
+ const blocks = [];
99
+ let offset = 0;
100
+ for (const token of tokens) {
101
+ const start = offset;
102
+ offset += token.raw.length;
103
+ if (token.type === 'space' || !token.raw.trim())
104
+ continue;
105
+ const trimmedLen = token.raw.replace(/\s+$/, '').length;
106
+ blocks.push({
107
+ html: renderMarkdownSafe(token.raw, marked),
108
+ sourceRange: { start, end: start + trimmedLen },
109
+ });
110
+ }
111
+ return blocks;
112
+ }
113
+ /**
114
+ * Parse article source into a `RenderUnit[]` (block-level html units + MDX component nodes), plus
115
+ * the post-frontmatter `body` and its `bodyOffset` within `content`.
116
+ */
117
+ export function parseArticle(content, marked = createDefaultMarked()) {
118
+ if (!content)
119
+ return { mode: 'html', html: '', items: [], body: '', bodyOffset: 0 };
120
+ const body = stripFrontmatter(content);
121
+ const bodyOffset = computeBodyOffset(content);
122
+ const items = [];
123
+ let nodeIndex = 0;
124
+ const nextId = () => `mdx-${nodeIndex++}`;
125
+ const pushMarkdownBlocks = (md, base) => {
126
+ if (!md.trim())
127
+ return;
128
+ const blocks = splitMarkdownBlocks(md, marked);
129
+ if (blocks.length > 0) {
130
+ for (const b of blocks) {
131
+ items.push({
132
+ type: 'html',
133
+ html: b.html,
134
+ nodeId: nextId(),
135
+ sourceRange: { start: base + b.sourceRange.start, end: base + b.sourceRange.end },
136
+ });
137
+ }
138
+ }
139
+ else {
140
+ items.push({
141
+ type: 'html',
142
+ html: renderMarkdownSafe(md, marked),
143
+ nodeId: nextId(),
144
+ sourceRange: { start: base, end: base + md.length },
145
+ });
146
+ }
147
+ };
148
+ // Fast path: pure markdown.
149
+ if (!HAS_MDX_RE.test(body)) {
150
+ pushMarkdownBlocks(body, 0);
151
+ if (items.length > 0)
152
+ return { mode: 'html', html: '', items, body, bodyOffset };
153
+ return { mode: 'html', html: renderMarkdownSafe(body, marked), items: [], body, bodyOffset };
154
+ }
155
+ // MDX path: markdown chunks (themselves block-split) interleaved with component nodes.
156
+ const componentRe = new RegExp(MDX_COMPONENT_PATTERN.source, 'g');
157
+ let lastIndex = 0;
158
+ let match;
159
+ while ((match = componentRe.exec(body)) !== null) {
160
+ if (match.index > lastIndex) {
161
+ pushMarkdownBlocks(body.slice(lastIndex, match.index), lastIndex);
162
+ }
163
+ const name = match[1] || match[4] || '';
164
+ const propsStr = match[1] ? match[2] || '' : match[5] || '';
165
+ const children = match[3];
166
+ items.push({
167
+ type: 'component',
168
+ name,
169
+ props: parseJsxProps(propsStr),
170
+ children: children?.trim(),
171
+ nodeId: nextId(),
172
+ sourceRange: { start: match.index, end: match.index + match[0].length },
173
+ });
174
+ lastIndex = match.index + match[0].length;
175
+ }
176
+ if (lastIndex < body.length) {
177
+ pushMarkdownBlocks(body.slice(lastIndex), lastIndex);
178
+ }
179
+ if (items.length === 0 && body.trim()) {
180
+ return { mode: 'html', html: renderMarkdownSafe(body, marked), items: [], body, bodyOffset };
181
+ }
182
+ const hasComponent = items.some((it) => it.type === 'component');
183
+ return { mode: hasComponent ? 'mdx' : 'html', html: '', items, body, bodyOffset };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IAC9F,CAAC;IAED,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,KAAK,WAAW,CAAC,CAAA;IAChE,OAAO,EAAE,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,CAAA;AACnF,CAAC"}
@@ -0,0 +1,145 @@
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
+ import type { RenderUnit, Rect } from './types.js';
15
+ /** Protocol channel id. Bump the trailing version for a breaking change (old peers stay silent). */
16
+ export declare const RENDER_EMBED_PROTOCOL: "blogmcp.render-embed/1";
17
+ /** Highest protocol minor this build speaks. `version` negotiation picks `min(host, renderer)`. */
18
+ export declare const PROTOCOL_MAX_VERSION = 1;
19
+ /** The known set of negotiable versions (never `min()` against an unbounded integer). */
20
+ export declare const KNOWN_VERSIONS: readonly number[];
21
+ export interface Envelope<T extends string, P> {
22
+ /** Discriminates our protocol from stray postMessage noise. */
23
+ channel: typeof RENDER_EMBED_PROTOCOL;
24
+ /** Monotonic per-sender; replay/dedup guard. */
25
+ seq: number;
26
+ /** Negotiated minor; 0 during handshake. */
27
+ v: number;
28
+ /** Per-load handshake nonce; echoed every frame. */
29
+ nonce: string;
30
+ type: T;
31
+ payload: P;
32
+ }
33
+ export interface ThemeSpec {
34
+ mode: 'light' | 'dark';
35
+ tokens?: Record<string, string>;
36
+ }
37
+ export type HostMessage = Envelope<'embed.init', {
38
+ maxVersion: number;
39
+ theme: ThemeSpec;
40
+ /** Advisory only; the renderer authenticates via the URL nonce, not this. */
41
+ hostOrigin: string;
42
+ capabilities: {
43
+ wantNodeEvents: boolean;
44
+ wantSelection: boolean;
45
+ wantHeight: boolean;
46
+ };
47
+ safeAreaInsets?: {
48
+ top: number;
49
+ right: number;
50
+ bottom: number;
51
+ left: number;
52
+ };
53
+ }> | Envelope<'embed.render', {
54
+ /** PRIMARY: app-parsed, id-stamped units. Media already absolutized server-side in `html`. */
55
+ blocks?: RenderUnit[];
56
+ /** ALT: only honored if the renderer advertised `canParse`. */
57
+ content?: string;
58
+ language: string;
59
+ }> | Envelope<'embed.scrollToNode', {
60
+ nodeId: string;
61
+ behavior?: 'smooth' | 'auto';
62
+ }> | Envelope<'embed.highlight', {
63
+ nodeIds: string[];
64
+ kind: 'comment' | 'selection' | 'clear';
65
+ }> | Envelope<'embed.setTheme', ThemeSpec>;
66
+ export interface RendererCapabilities {
67
+ canParse: boolean;
68
+ /** true → stamps OUR ids (default); false → opaque handles the host can't validate. */
69
+ honorsNodeIds: boolean;
70
+ nodeEvents: boolean;
71
+ selection: boolean;
72
+ height: boolean;
73
+ /** Exposes SSR /preview/[token]?mode=production for the screenshot fallback. */
74
+ screenshotFallback: boolean;
75
+ }
76
+ export type RendererMessage = Envelope<'embed.ready', {
77
+ version: number;
78
+ capabilities: RendererCapabilities;
79
+ }> | Envelope<'embed.height', {
80
+ px: number;
81
+ }> | Envelope<'embed.nodeClicked', {
82
+ nodeId: string;
83
+ rect: Rect;
84
+ scroll: {
85
+ top: number;
86
+ left: number;
87
+ };
88
+ modifiers?: {
89
+ meta: boolean;
90
+ shift: boolean;
91
+ };
92
+ }> | Envelope<'embed.selection', {
93
+ nodeId: string;
94
+ startOffset: number;
95
+ endOffset: number;
96
+ /** Host DISCARDS this for storage and re-derives from `sourceRange`. Hint only. */
97
+ text: string;
98
+ rect: Rect;
99
+ scroll: {
100
+ top: number;
101
+ left: number;
102
+ };
103
+ }>
104
+ /** The id set actually painted — lets the host ack render completion (overlay-active gate). */
105
+ | Envelope<'embed.rendered', {
106
+ units: {
107
+ nodeId: string;
108
+ }[];
109
+ }> | Envelope<'embed.error', {
110
+ code: 'parse' | 'fetch' | 'token' | 'unsupported' | 'internal';
111
+ message: string;
112
+ nodeId?: string;
113
+ }>;
114
+ export type AnyMessage = HostMessage | RendererMessage;
115
+ /** Build a well-formed envelope. `seq` is supplied by the bridge's monotonic counter. */
116
+ export declare function makeEnvelope<T extends string, P>(type: T, payload: P, ctx: {
117
+ nonce: string;
118
+ seq: number;
119
+ v: number;
120
+ }): Envelope<T, P>;
121
+ export interface AcceptContext {
122
+ /** The handshake nonce this side expects echoed. */
123
+ expectedNonce: string;
124
+ /** Highest `seq` already accepted from the peer (monotonic guard). */
125
+ lastSeq: number;
126
+ }
127
+ export type AcceptResult = {
128
+ ok: true;
129
+ seq: number;
130
+ } | {
131
+ ok: false;
132
+ reason: 'not-our-channel' | 'bad-nonce' | 'replayed' | 'malformed';
133
+ };
134
+ /**
135
+ * The DOM-free half of the inbound gate (the `event.source === peerWindow` check lives in the DOM
136
+ * glue, where the event is available). Runs BEFORE any payload is touched:
137
+ * 1. channel discriminator,
138
+ * 2. handshake nonce,
139
+ * 3. monotonic seq,
140
+ * 4. structural envelope shape (full payload validation is schema.ts's Zod, layered on top).
141
+ * Returns the parsed `seq` so the caller can advance `lastSeq` only on accept.
142
+ */
143
+ export declare function acceptEnvelope(raw: unknown, ctx: AcceptContext): AcceptResult;
144
+ /** Pick the negotiated version: the highest known minor both sides speak, else null (incompatible). */
145
+ export declare function negotiateVersion(hostMax: number, rendererVersion: number): number | null;
@@ -0,0 +1,55 @@
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
+ /** Protocol channel id. Bump the trailing version for a breaking change (old peers stay silent). */
15
+ export const RENDER_EMBED_PROTOCOL = 'blogmcp.render-embed/1';
16
+ /** Highest protocol minor this build speaks. `version` negotiation picks `min(host, renderer)`. */
17
+ export const PROTOCOL_MAX_VERSION = 1;
18
+ /** The known set of negotiable versions (never `min()` against an unbounded integer). */
19
+ export const KNOWN_VERSIONS = [1];
20
+ /** Build a well-formed envelope. `seq` is supplied by the bridge's monotonic counter. */
21
+ export function makeEnvelope(type, payload, ctx) {
22
+ return { channel: RENDER_EMBED_PROTOCOL, seq: ctx.seq, v: ctx.v, nonce: ctx.nonce, type, payload };
23
+ }
24
+ /**
25
+ * The DOM-free half of the inbound gate (the `event.source === peerWindow` check lives in the DOM
26
+ * glue, where the event is available). Runs BEFORE any payload is touched:
27
+ * 1. channel discriminator,
28
+ * 2. handshake nonce,
29
+ * 3. monotonic seq,
30
+ * 4. structural envelope shape (full payload validation is schema.ts's Zod, layered on top).
31
+ * Returns the parsed `seq` so the caller can advance `lastSeq` only on accept.
32
+ */
33
+ export function acceptEnvelope(raw, ctx) {
34
+ if (!raw || typeof raw !== 'object')
35
+ return { ok: false, reason: 'not-our-channel' };
36
+ const m = raw;
37
+ if (m.channel !== RENDER_EMBED_PROTOCOL)
38
+ return { ok: false, reason: 'not-our-channel' };
39
+ if (typeof m.nonce !== 'string' || m.nonce !== ctx.expectedNonce)
40
+ return { ok: false, reason: 'bad-nonce' };
41
+ if (typeof m.seq !== 'number' || !Number.isFinite(m.seq))
42
+ return { ok: false, reason: 'malformed' };
43
+ if (m.seq <= ctx.lastSeq)
44
+ return { ok: false, reason: 'replayed' };
45
+ if (typeof m.type !== 'string' || typeof m.v !== 'number' || !('payload' in m)) {
46
+ return { ok: false, reason: 'malformed' };
47
+ }
48
+ return { ok: true, seq: m.seq };
49
+ }
50
+ /** Pick the negotiated version: the highest known minor both sides speak, else null (incompatible). */
51
+ export function negotiateVersion(hostMax, rendererVersion) {
52
+ const candidate = Math.min(hostMax, rendererVersion);
53
+ return KNOWN_VERSIONS.includes(candidate) ? candidate : null;
54
+ }
55
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,oGAAoG;AACpG,MAAM,CAAC,MAAM,qBAAqB,GAAG,wBAAiC,CAAA;AAEtE,mGAAmG;AACnG,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAA;AAErC,yFAAyF;AACzF,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,CAAC,CAAC,CAAA;AAoFpD,yFAAyF;AACzF,MAAM,UAAU,YAAY,CAC1B,IAAO,EACP,OAAU,EACV,GAA8C;IAE9C,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,CAAA;AACpG,CAAC;AAaD;;;;;;;;GAQG;AACH,MAAM,UAAU,cAAc,CAAC,GAAY,EAAE,GAAkB;IAC7D,IAAI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,OAAO,cAAc,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAA;AAC9D,CAAC"}
@@ -0,0 +1,65 @@
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
+ import { type RendererCapabilities, type ThemeSpec } from './protocol.js';
12
+ import type { RenderMode, RenderUnit } from './types.js';
13
+ export interface RenderPayload {
14
+ blocks?: RenderUnit[];
15
+ content?: string;
16
+ language: string;
17
+ }
18
+ export interface RendererBridgeOptions {
19
+ mode: RenderMode;
20
+ /** What this renderer supports. Defaults: honors host ids, all events on, can't parse. */
21
+ capabilities?: Partial<RendererCapabilities>;
22
+ onRender: (payload: RenderPayload) => void;
23
+ onInit?: (init: {
24
+ theme: ThemeSpec;
25
+ safeAreaInsets?: {
26
+ top: number;
27
+ right: number;
28
+ bottom: number;
29
+ left: number;
30
+ };
31
+ }) => void;
32
+ onSetTheme?: (theme: ThemeSpec) => void;
33
+ onScrollToNode?: (nodeId: string, behavior: 'smooth' | 'auto') => void;
34
+ onHighlight?: (nodeIds: string[], kind: 'comment' | 'selection' | 'clear') => void;
35
+ /** Window to bind to (default `window`); injectable for tests. */
36
+ win?: Window;
37
+ }
38
+ export declare class RendererBridge {
39
+ private readonly opts;
40
+ private readonly win;
41
+ private readonly mode;
42
+ private readonly caps;
43
+ private readonly nonce;
44
+ private host;
45
+ private started;
46
+ private seqOut;
47
+ private lastSeqIn;
48
+ private version;
49
+ constructor(opts: RendererBridgeOptions);
50
+ /** Begin listening. NO-OP in production mode (inert passthrough). */
51
+ start(): void;
52
+ destroy(): void;
53
+ reportHeight(px: number): void;
54
+ reportNodeClick(nodeId: string, el: Element, modifiers?: {
55
+ meta: boolean;
56
+ shift: boolean;
57
+ }): void;
58
+ /** Report a DOM Selection — walks to the nearest `[data-mdx-node-id]` and computes block-relative offsets. */
59
+ reportSelection(sel: Selection): void;
60
+ /** Acknowledge the id set actually painted (host's overlay-active gate). */
61
+ reportRendered(nodeIds: string[]): void;
62
+ reportError(code: 'parse' | 'fetch' | 'token' | 'unsupported' | 'internal', message: string, nodeId?: string): void;
63
+ private toHost;
64
+ private onMessage;
65
+ }
@@ -0,0 +1,166 @@
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
+ import { acceptEnvelope, makeEnvelope, PROTOCOL_MAX_VERSION, KNOWN_VERSIONS, } from './protocol.js';
12
+ import { parseHostMessage } from './schema.js';
13
+ export class RendererBridge {
14
+ opts;
15
+ win;
16
+ mode;
17
+ caps;
18
+ nonce;
19
+ host = null;
20
+ started = false;
21
+ seqOut = 0;
22
+ lastSeqIn = -1;
23
+ version = 0;
24
+ constructor(opts) {
25
+ this.opts = opts;
26
+ this.win = opts.win ?? globalThis.window;
27
+ this.mode = opts.mode;
28
+ const search = (() => {
29
+ try {
30
+ return this.win.location?.search ?? '';
31
+ }
32
+ catch {
33
+ return '';
34
+ }
35
+ })();
36
+ this.nonce = new URLSearchParams(search).get('n');
37
+ this.caps = {
38
+ canParse: false,
39
+ honorsNodeIds: true,
40
+ nodeEvents: true,
41
+ selection: true,
42
+ height: true,
43
+ screenshotFallback: true,
44
+ ...opts.capabilities,
45
+ };
46
+ }
47
+ /** Begin listening. NO-OP in production mode (inert passthrough). */
48
+ start() {
49
+ if (this.mode === 'production')
50
+ return;
51
+ this.win.addEventListener('message', this.onMessage);
52
+ }
53
+ destroy() {
54
+ this.win.removeEventListener('message', this.onMessage);
55
+ }
56
+ reportHeight(px) {
57
+ this.toHost('embed.height', { px: Math.max(0, Math.round(px)) });
58
+ }
59
+ reportNodeClick(nodeId, el, modifiers) {
60
+ const r = el.getBoundingClientRect();
61
+ this.toHost('embed.nodeClicked', {
62
+ nodeId,
63
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
64
+ scroll: { top: this.win.scrollY || 0, left: this.win.scrollX || 0 },
65
+ ...(modifiers ? { modifiers } : {}),
66
+ });
67
+ }
68
+ /** Report a DOM Selection — walks to the nearest `[data-mdx-node-id]` and computes block-relative offsets. */
69
+ reportSelection(sel) {
70
+ if (sel.rangeCount === 0 || sel.isCollapsed)
71
+ return;
72
+ const range = sel.getRangeAt(0);
73
+ const startEl = (range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentElement);
74
+ const block = startEl?.closest('[data-mdx-node-id]');
75
+ const nodeId = block?.getAttribute('data-mdx-node-id');
76
+ if (!block || !nodeId)
77
+ return;
78
+ const pre = this.win.document.createRange();
79
+ pre.selectNodeContents(block);
80
+ try {
81
+ pre.setEnd(range.startContainer, range.startOffset);
82
+ }
83
+ catch {
84
+ return;
85
+ }
86
+ const startOffset = pre.toString().length;
87
+ const text = sel.toString();
88
+ const r = range.getBoundingClientRect();
89
+ this.toHost('embed.selection', {
90
+ nodeId,
91
+ startOffset,
92
+ endOffset: startOffset + text.length,
93
+ text,
94
+ rect: { x: r.x, y: r.y, width: r.width, height: r.height },
95
+ scroll: { top: this.win.scrollY || 0, left: this.win.scrollX || 0 },
96
+ });
97
+ }
98
+ /** Acknowledge the id set actually painted (host's overlay-active gate). */
99
+ reportRendered(nodeIds) {
100
+ this.toHost('embed.rendered', { units: nodeIds.map((nodeId) => ({ nodeId })) });
101
+ }
102
+ reportError(code, message, nodeId) {
103
+ this.toHost('embed.error', { code, message, ...(nodeId ? { nodeId } : {}) });
104
+ }
105
+ // ---- internals ----
106
+ toHost(type, payload) {
107
+ if (!this.host || !this.started || !this.nonce)
108
+ return;
109
+ const env = makeEnvelope(type, payload, { nonce: this.nonce, seq: this.seqOut++, v: this.version });
110
+ // Host origin is opaque → "*" is unavoidable, but the message carries no secret (only the
111
+ // echoed nonce, which authenticates the renderer to the host).
112
+ this.host.postMessage(env, '*');
113
+ }
114
+ onMessage = (event) => {
115
+ // Identity: parent-window only + echoed nonce (NOT event.origin — embedder may be opaque).
116
+ if (!this.nonce)
117
+ return;
118
+ if (event.source !== this.win.parent)
119
+ return;
120
+ const accepted = acceptEnvelope(event.data, { expectedNonce: this.nonce, lastSeq: this.lastSeqIn });
121
+ if (!accepted.ok)
122
+ return;
123
+ const parsed = parseHostMessage(event.data);
124
+ if (!parsed.success)
125
+ return;
126
+ this.lastSeqIn = accepted.seq;
127
+ const msg = parsed.data;
128
+ switch (msg.type) {
129
+ case 'embed.init': {
130
+ if (this.started)
131
+ return; // single-init latch
132
+ const p = msg.payload;
133
+ const negotiated = Math.min(p.maxVersion, PROTOCOL_MAX_VERSION);
134
+ if (!KNOWN_VERSIONS.includes(negotiated)) {
135
+ // Incompatible: tell the host directly (don't latch `started`, so we stay inert).
136
+ const env = makeEnvelope('embed.error', { code: 'unsupported', message: 'no common protocol version' }, { nonce: this.nonce, seq: this.seqOut++, v: 0 });
137
+ event.source.postMessage(env, '*');
138
+ return;
139
+ }
140
+ this.host = event.source;
141
+ this.version = negotiated;
142
+ this.started = true;
143
+ this.toHost('embed.ready', { version: negotiated, capabilities: this.caps });
144
+ this.opts.onInit?.({ theme: p.theme, safeAreaInsets: p.safeAreaInsets });
145
+ return;
146
+ }
147
+ case 'embed.render':
148
+ this.opts.onRender(msg.payload);
149
+ return;
150
+ case 'embed.setTheme':
151
+ this.opts.onSetTheme?.(msg.payload);
152
+ return;
153
+ case 'embed.scrollToNode': {
154
+ const p = msg.payload;
155
+ this.opts.onScrollToNode?.(p.nodeId, p.behavior ?? 'smooth');
156
+ return;
157
+ }
158
+ case 'embed.highlight': {
159
+ const p = msg.payload;
160
+ this.opts.onHighlight?.(p.nodeIds, p.kind);
161
+ return;
162
+ }
163
+ }
164
+ };
165
+ }
166
+ //# sourceMappingURL=renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,cAAc,GAGf,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAsB9C,MAAM,OAAO,cAAc;IAWI;IAVZ,GAAG,CAAQ;IACX,IAAI,CAAY;IAChB,IAAI,CAAsB;IAC1B,KAAK,CAAe;IAC7B,IAAI,GAAkB,IAAI,CAAA;IAC1B,OAAO,GAAG,KAAK,CAAA;IACf,MAAM,GAAG,CAAC,CAAA;IACV,SAAS,GAAG,CAAC,CAAC,CAAA;IACd,OAAO,GAAG,CAAC,CAAA;IAEnB,YAA6B,IAA2B;QAA3B,SAAI,GAAJ,IAAI,CAAuB;QACtD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,IAAK,UAA4C,CAAC,MAAM,CAAA;QAC3E,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;QACrB,MAAM,MAAM,GAAG,CAAC,GAAG,EAAE;YACnB,IAAI,CAAC;gBACH,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,CAAA;YACxC,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE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