From 2d654b6ecbc050ef4e6a9b5348ae82cf292ba175 Mon Sep 17 00:00:00 2001
From: Shane McGuirt <10144278+srmcguirt@users.noreply.github.com>
Date: Mon, 25 May 2026 13:29:52 -0400
Subject: [PATCH] =?UTF-8?q?feat(markdown):=20cohort=207b=20=E2=80=94=20cor?=
=?UTF-8?q?e=200.2.0=20startScopeWithAttrs=20+=20emitters-markdown=20+=20r?=
=?UTF-8?q?ender-markdown?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
KN-1: @kindly-note/core 0.1.0 → 0.2.0 (minor). Add the optional
startScopeWithAttrs(scope, attrs) method to the Emitter contract (spec
§13.3a) plus matcher plumbing (Mode/CompiledMode gain an optional attrs
payload; the matcher routes through startScopeWithAttrs when the emitter
implements it, else falls back to startScope). Backward-compatible —
emitters-html and the recording emitter are unaffected; all 71 existing
core tests pass + 3 new attrs-routing tests.
KN-2: NEW @kindly-note/emitters-markdown — a semantic-HTML emitter that
reinterprets lang-markdown's highlight-style scope stream into
-
,
, , , ,
(sub-language fences highlighted
via emitters-html), ,
← no href; dangerous scheme neutralised
+```
+
+---
+
+## Changesets
+
+- `.changeset/core-start-scope-with-attrs.md` — `@kindly-note/core: minor`.
+- `.changeset/emitters-markdown-initial.md` — `@kindly-note/emitters-markdown: minor` (initial).
+- `.changeset/render-markdown-initial.md` — `@kindly-note/render-markdown: minor` (initial).
+
+### Team-Lead notes for the "Version Packages" PR
+
+1. **Core version is `0.1.0` in source on this branch** (NOT manually bumped). The `minor` changeset bumps it to `0.2.0` at `changeset version` time. The new packages declare `@kindly-note/core@^0.1.0` so `changeset status` validates cleanly against the current snapshot. **Per the spec the runtime floor is `core@^0.2.0`** (the new packages need the `startScopeWithAttrs` contract); after the core bump lands, the ranges may be tightened to `^0.2.0` (a non-breaking tightening) if desired. Functionally `^0.1.0` is safe because `startScopeWithAttrs` is an *added* optional method and the matcher fallback is backward-compatible.
+2. **Pre-1.0 `minor` quirk (publish.md lesson #4):** `bun x changeset status --verbose` currently projects `1.0.0` for the new packages and cascades `major`/`1.0.0` onto core's dependents (browser, emitters-html, legacy-plugin-adapter). This is the documented changesets pre-1.0 anomaly — **verify and manually correct the projected versions** at version-time (core → 0.2.0; new packages → 0.1.0; dependents → 0.1.1 patch from the core peer refresh, not 1.0.0).
+3. **Do NOT publish from this branch** — publishing is the Team Lead's post-review step via `release.yml`.
+
+---
+
+## Out of scope (proven absent)
+
+- **GFM** (tables / task-lists / strikethrough / autolinks) — `@kindly-note/lang-markdown-gfm` (KN-4), deferred (D1). Tests assert no `
`/``/`` output.
+- **Reference-style links, setext headings, raw-HTML blocks, images** — not produced by the v0 lang-markdown tokeniser (cohort 7a OPEN-QUESTION block). The emitter handles whatever the tokeniser emits; richer markdown lands when the tokeniser gains those modes (the `attrs` + `startScopeWithAttrs` contract is ready for image `src`/heading `id` when they do).
diff --git a/packages/core/src/compile.ts b/packages/core/src/compile.ts
index 86e495a..3276ef5 100644
--- a/packages/core/src/compile.ts
+++ b/packages/core/src/compile.ts
@@ -76,6 +76,13 @@ export interface CompiledMode {
readonly endSameAsBegin: boolean;
readonly beginScope?: string | ScopeMap;
readonly endScope?: string | ScopeMap;
+ /**
+ * Static attribute payload forwarded from the source Mode. spec §13.3a.
+ * When present (and `scope` is a string), the matcher opens the scope via
+ * `Emitter.startScopeWithAttrs` when the emitter implements it, else falls
+ * back to `Emitter.startScope`. Added in core 0.2.0 (additive, optional).
+ */
+ readonly attrs?: Readonly>;
/** Source-string form of the begin pattern (for capture in parent union). */
readonly beginPattern?: string;
/** Source-string form of the end pattern (for capture in parent union). */
@@ -318,6 +325,8 @@ function compileMode(
if (mutable.subLanguage !== undefined) compiled.subLanguage = mutable.subLanguage;
if (derivedBeginScope !== undefined) compiled.beginScope = derivedBeginScope;
if (mutable.endScope !== undefined) compiled.endScope = mutable.endScope;
+ // spec §13.3a: forward the static attribute payload (core 0.2.0, additive).
+ if (mutable.attrs !== undefined) compiled.attrs = mutable.attrs;
// Memoise BEFORE recursing into children so cycles see the placeholder.
memo.set(mode, compiled);
diff --git a/packages/core/src/emitter.ts b/packages/core/src/emitter.ts
index edab1b3..4001282 100644
--- a/packages/core/src/emitter.ts
+++ b/packages/core/src/emitter.ts
@@ -29,13 +29,33 @@ export interface EmitterOptions {
/**
* The six-method emitter contract. spec section 5.1.
*
- * Engine call order: zero-or-more (startScope|endScope|addText|addSubLanguage),
- * then exactly one finalize(), then exactly one render(). The engine may also
- * call toTokenStream() *before* render() when this emitter was created for a
- * sub-language and the parent needs its tokens.
+ * Engine call order: zero-or-more (startScope|startScopeWithAttrs|endScope|
+ * addText|addSubLanguage), then exactly one finalize(), then exactly one
+ * render(). The engine may also call toTokenStream() *before* render() when
+ * this emitter was created for a sub-language and the parent needs its tokens.
*/
export interface Emitter {
startScope(scope: string): void;
+ /**
+ * Open a scope that carries attributes. spec section 13.3a (decision (a)).
+ *
+ * OPTIONAL — added in core 0.2.0 as a backward-compatible minor. Emitters
+ * that produce attribute-bearing markup (`@kindly-note/emitters-markdown`'s
+ * ``, `
`);
+ paragraph = [];
+ };
+
+ while (i < lines.length) {
+ const line = lines[i] ?? [];
+ const lead = lineLeadKind(line);
+
+ if (lead === 'blank' || lead === 'empty') {
+ flushParagraph();
+ i++;
+ continue;
+ }
+ if (lead === 'headingHashes') {
+ flushParagraph();
+ out.push(renderHeading(line, ctx));
+ i++;
+ continue;
+ }
+ if (lead === 'hr') {
+ flushParagraph();
+ out.push('');
+ i++;
+ continue;
+ }
+ if (lead === 'codeBlock') {
+ flushParagraph();
+ out.push(renderCodeBlockLine(line));
+ i++;
+ continue;
+ }
+ if (lead === 'bullet') {
+ flushParagraph();
+ const consumed = renderList(lines, i, ctx);
+ out.push(consumed.html);
+ i = consumed.nextIndex;
+ continue;
+ }
+ if (lead === 'quoteLine') {
+ flushParagraph();
+ const consumed = renderBlockquote(lines, i, ctx);
+ out.push(consumed.html);
+ i = consumed.nextIndex;
+ continue;
+ }
+ // Ordinary paragraph line.
+ paragraph.push(line);
+ i++;
+ }
+ flushParagraph();
+
+ return out.join('\n');
+}
+
+/** Drop leading whitespace-only text atoms from a line. */
+function stripLeadingWhitespace(line: Line): Atom[] {
+ const copy = [...line];
+ while (copy.length > 0) {
+ const first = copy[0];
+ if (first !== undefined && first.kind === 'text' && first.text.trim() === '') copy.shift();
+ else break;
+ }
+ return copy;
+}
+
+function renderHeading(line: Line, ctx: RenderContext): string {
+ const cleaned = stripLeadingWhitespace(line);
+ const head = cleaned[0];
+ const level = head !== undefined && head.kind === 'headingHashes' ? head.level : 1;
+ // The heading body is the `section` atom(s) plus any inline atoms after it.
+ const bodyAtoms: Atom[] = [];
+ for (let k = 1; k < cleaned.length; k++) {
+ const a = cleaned[k];
+ if (a === undefined) continue;
+ if (a.kind === 'section') {
+ // The section text may have a leading space the tokeniser kept.
+ bodyAtoms.push({ kind: 'text', text: a.text.replace(/^[ \t]+/, '') });
+ } else {
+ bodyAtoms.push(a);
+ }
+ }
+ const inner = renderInlineAtoms(bodyAtoms, ctx).trimStart();
+ const lvl = Math.min(Math.max(level, 1), 6);
+ return `${inner}`;
+}
+
+function renderCodeBlockLine(line: Line): string {
+ // The line holds a single resolved codeBlock atom (fence delimiters were
+ // collapsed during normalizeAtoms). spec §13.1: the html is either escaped
+ // plain text (generic fence) or pre-rendered safe sub-language markup.
+ for (const a of line) {
+ if (a.kind === 'codeBlock') return `
${a.html}
`;
+ }
+ return '';
+}
+
+function renderList(
+ lines: readonly Line[],
+ start: number,
+ ctx: RenderContext,
+): { html: string; nextIndex: number } {
+ // Determine ordered-ness from the first bullet.
+ const firstLead = stripLeadingWhitespace(lines[start] ?? []);
+ const firstBullet = firstLead.find((a) => a.kind === 'bullet');
+ const ordered = firstBullet !== undefined && firstBullet.kind === 'bullet' && firstBullet.ordered;
+ const items: string[] = [];
+ let i = start;
+ while (i < lines.length) {
+ const line = lines[i] ?? [];
+ const lead = lineLeadKind(line);
+ if (lead === 'blank' || lead === 'empty') {
+ // A single blank line ends a tight list in this v0 renderer.
+ i++;
+ break;
+ }
+ if (lead !== 'bullet') break;
+ const cleaned = stripLeadingWhitespace(line);
+ // Drop the leading bullet atom; the rest is the item's inline content.
+ const itemAtoms: Atom[] = [];
+ let seenBullet = false;
+ for (const a of cleaned) {
+ if (!seenBullet && a.kind === 'bullet') {
+ seenBullet = true;
+ continue;
+ }
+ itemAtoms.push(a);
+ }
+ const inner = renderInlineAtoms(itemAtoms, ctx).replace(/^[ \t]+/, '');
+ items.push(`
${inner}
`);
+ i++;
+ }
+ const tag = ordered ? 'ol' : 'ul';
+ return { html: `<${tag}>${items.join('')}${tag}>`, nextIndex: i };
+}
+
+function renderBlockquote(
+ lines: readonly Line[],
+ start: number,
+ ctx: RenderContext,
+): { html: string; nextIndex: number } {
+ const inners: string[] = [];
+ let i = start;
+ while (i < lines.length) {
+ const line = lines[i] ?? [];
+ const lead = lineLeadKind(line);
+ if (lead !== 'quoteLine') break;
+ const cleaned = stripLeadingWhitespace(line);
+ for (const a of cleaned) {
+ if (a.kind === 'quoteLine') {
+ inners.push(renderInlineAtoms(a.inline, ctx));
+ }
+ }
+ i++;
+ }
+ return { html: `
${inners.join('\n')}
`, nextIndex: i };
+}
diff --git a/packages/emitters-markdown/src/url-policy.ts b/packages/emitters-markdown/src/url-policy.ts
new file mode 100644
index 0000000..1763a68
--- /dev/null
+++ b/packages/emitters-markdown/src/url-policy.ts
@@ -0,0 +1,92 @@
+// URL allowlist / scheme policy for @kindly-note/emitters-markdown.
+//
+// spec §13.1 (URL rows): the default policy permits only a small allowlist of
+// schemes plus anchor (`#…`) and relative URLs; everything else (notably
+// `javascript:`, `vbscript:`, `data:`, `file:`) is neutralised — the link text
+// is preserved but the `href` is dropped. Auto-linked URLs in text are checked
+// against the same allowlist.
+//
+// This is a STRUCTURAL guarantee, not a sanitiser pass: the renderer asks the
+// policy "what href, if any, should this URL produce" and only ever emits the
+// returned value. A `null` return means "no href" — the renderer emits the
+// link/image text but never an attribute carrying a dangerous scheme.
+
+/**
+ * A URL policy: given a raw URL string from markdown source, return the href
+ * to emit, or `null` to emit no href. Pure and synchronous (spec §13.5: v0/v1.0
+ * markdown rendering is sync-only — no async link probing).
+ */
+export type UrlPolicy = (url: string) => string | null;
+
+/** The default scheme allowlist. spec §13.1. */
+export const DEFAULT_URL_ALLOWLIST: readonly string[] = Object.freeze([
+ 'http',
+ 'https',
+ 'mailto',
+ 'tel',
+]);
+
+// Leading / embedded control characters and whitespace are stripped before
+// scheme analysis so `java\tscript:` / `java\nscript:` obfuscation cannot
+// smuggle a blocked scheme past the check (browsers ignore these inside the
+// scheme). Written with \u escapes so the source carries no literal control
+// bytes; the class covers C0 controls (U+0000–U+001F) and the space.
+// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping C0 control chars is the security intent.
+const CONTROL_AND_WS_RE = /[\u0000-\u0020]/g;
+
+/**
+ * Extract the scheme of a URL (the part before the first `:`), lowercased, or
+ * `undefined` when the URL has no scheme (relative path / fragment / etc.).
+ *
+ * A `:` that appears after a path/query/fragment delimiter, or that is not
+ * preceded by a valid scheme token (`[a-z][a-z0-9+.-]*`), is NOT a scheme
+ * separator — e.g. `/path:with:colons` or `foo?a=b:c` are schemeless.
+ */
+function schemeOf(url: string): string | undefined {
+ const colon = url.indexOf(':');
+ if (colon < 0) return undefined;
+ const candidate = url.slice(0, colon);
+ // A scheme cannot contain a path/query/fragment delimiter.
+ if (/[/?#\\]/.test(candidate)) return undefined;
+ // RFC 3986 scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ).
+ if (!/^[a-zA-Z][a-zA-Z0-9+.-]*$/.test(candidate)) return undefined;
+ return candidate.toLowerCase();
+}
+
+/**
+ * Build a {@link UrlPolicy} from a scheme allowlist. The returned policy:
+ * - permits fragment-only URLs (`#section`),
+ * - permits scheme-relative (`//host/...`) and path-relative / absolute-path
+ * URLs (no scheme),
+ * - permits any URL whose scheme is in `allowlist` (case-insensitive),
+ * - returns `null` for everything else (e.g. `javascript:`, `data:`,
+ * `vbscript:`, `file:`).
+ *
+ * Obfuscation via leading / embedded control characters in the scheme is
+ * defeated by stripping those characters before scheme analysis.
+ */
+export function allowlistUrlPolicy(allowlist: readonly string[]): UrlPolicy {
+ const allowed = new Set(allowlist.map((s) => s.toLowerCase()));
+ return (rawUrl: string): string | null => {
+ const url = rawUrl.trim();
+ if (url === '') return null;
+ // Defeat control-character obfuscation in the scheme region: analyse a
+ // de-controlled copy, but emit the trimmed original when permitted.
+ const deControlled = url.replace(CONTROL_AND_WS_RE, '');
+ const scheme = schemeOf(deControlled);
+ if (scheme === undefined) {
+ // No scheme: fragment, relative, or absolute path. All permitted.
+ return url;
+ }
+ if (allowed.has(scheme)) {
+ return url;
+ }
+ return null;
+ };
+}
+
+/**
+ * The default URL policy — the {@link DEFAULT_URL_ALLOWLIST} plus relative /
+ * fragment URLs. spec §13.1.
+ */
+export const defaultUrlPolicy: UrlPolicy = allowlistUrlPolicy(DEFAULT_URL_ALLOWLIST);
diff --git a/packages/emitters-markdown/tests/escape.test.ts b/packages/emitters-markdown/tests/escape.test.ts
new file mode 100644
index 0000000..5f0add5
--- /dev/null
+++ b/packages/emitters-markdown/tests/escape.test.ts
@@ -0,0 +1,42 @@
+// Unit tests for HTML escaping + bidi-control normalisation. spec §13.1.
+
+import { describe, expect, it } from 'vitest';
+import { htmlEscape, normalizeBidi } from '../src/index.js';
+
+describe('htmlEscape', () => {
+ it('escapes the five HTML special characters', () => {
+ expect(htmlEscape('<>&"\'')).toBe('<>&"'');
+ });
+
+ it('escapes a script tag so it cannot execute', () => {
+ expect(htmlEscape('')).toBe('<script>alert(1)</script>');
+ });
+
+ it('passes plain text through unchanged', () => {
+ expect(htmlEscape('hello world 123')).toBe('hello world 123');
+ });
+});
+
+describe('normalizeBidi', () => {
+ it('replaces a right-to-left override (U+202E) with U+FFFD', () => {
+ const trojan = `safe${String.fromCodePoint(0x202e)}evil`;
+ const out = normalizeBidi(trojan);
+ expect(out).not.toContain(String.fromCodePoint(0x202e));
+ expect(out).toContain('�');
+ });
+
+ it('replaces every targeted bidi/invisible control code point', () => {
+ const cps = [
+ 0x061c, 0x200b, 0x200c, 0x200d, 0x200e, 0x200f, 0x202a, 0x202b, 0x202c, 0x202d, 0x202e,
+ 0x2066, 0x2067, 0x2068, 0x2069, 0xfeff,
+ ];
+ for (const cp of cps) {
+ const out = normalizeBidi(`a${String.fromCodePoint(cp)}b`);
+ expect(out).toBe('a�b');
+ }
+ });
+
+ it('leaves ordinary text untouched', () => {
+ expect(normalizeBidi('plain text')).toBe('plain text');
+ });
+});
diff --git a/packages/emitters-markdown/tests/render.test.ts b/packages/emitters-markdown/tests/render.test.ts
new file mode 100644
index 0000000..a2ceb53
--- /dev/null
+++ b/packages/emitters-markdown/tests/render.test.ts
@@ -0,0 +1,173 @@
+// End-to-end tests for @kindly-note/emitters-markdown — drives the real
+// engine + @kindly-note/lang-markdown tokeniser through the markdown emitter
+// and asserts on the produced semantic HTML.
+//
+// Proves spec §13 acceptance:
+// - Block structure: headings h1-h6, paragraphs, lists (ul/ol), blockquotes,
+// horizontal rules, fenced code (with + without sub-language highlighting).
+// - Inline: , , , with the URL security policy.
+// - SECURITY (spec §13.1): raw HTML escaped; javascript:/data: URLs
+// neutralised; on* never emitted; bidi controls normalised.
+
+import { createHighlighter } from '@kindly-note/core';
+import json from '@kindly-note/lang-json';
+import markdown from '@kindly-note/lang-markdown';
+import { describe, expect, it } from 'vitest';
+import { markdownHtmlEmitter, markdownHtmlEmitterWith } from '../src/index.js';
+
+function render(src: string, emitter = markdownHtmlEmitter): string {
+ const hl = createHighlighter({ languages: [markdown, json], emitter });
+ return hl.highlight(src, { language: 'markdown' }).value;
+}
+
+describe('block structure', () => {
+ it('renders ATX headings at the right level', () => {
+ expect(render('# Hello World')).toBe('