@blogmcp/mdx-schema 0.2.2 → 0.3.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.
@@ -21,6 +21,38 @@ export const HAS_MDX_RE = /<[A-Z][a-zA-Z]*[\s/>]/
21
21
  * - Self-closing: match[4]=name, match[5]=props
22
22
  *
23
23
  * NOTE: Create a new RegExp instance per call (g-flag + exec requires fresh lastIndex).
24
+ *
25
+ * @deprecated MATCHING ONLY — never build a document WALK on this. It cannot express either
26
+ * half of correct extraction, and both gaps caused measured production damage:
27
+ *
28
+ * - NO PROP BOUNDARY. The self-closing branch's props group `(?:[^/]|\/(?!>))*` matches '>'
29
+ * and newlines, so ANY `<Name>` — including a prose mention — starts a match that runs to
30
+ * the next '/>' anywhere in the document. Measured on `docs/public/tools/upload-media.md`:
31
+ * ONE match spanning lines 25→166 (142 lines, 8916 chars, 1362 whitespace-separated "prop"
32
+ * tokens), which SWALLOWS everything it spans — 81.7% of that page's body never reached the
33
+ * renderer.
34
+ * - NO CODE AWARENESS. A component inside a fence (all 4 flavours: bare ```, ```lang,
35
+ * 1-3-space-indented, and ~~~) or inside an inline `code` span is documentation ABOUT the
36
+ * component, and was extracted as a LIVE one. Both the inline SELF-CLOSING form
37
+ * (`` `<Gallery images={[1]} />` ``) and the inline PAIRED form (`` `<Callout>x</Callout>` ``)
38
+ * extracted. A bare `` `<Gallery>` `` mention was ignored only because it has no closer — so
39
+ * "inline spans are already respected" was never true.
40
+ * - The paired branch is not a safe reference to mirror either: `([^>]*)` stops at the first '>'
41
+ * even inside a quoted value (`<Callout title="a > b">Hi</Callout>` → children `b">\nHi`) and
42
+ * eats the trailing '/' of a self-closing tag, absorbing it as paired whenever a later
43
+ * `</Name>` exists (`docs/public/concepts/mdx-storage-format.md:138` swallowed 4 real
44
+ * components that way, across 57 lines).
45
+ *
46
+ * Neither gap is expressible as a regex (nested braces need recursion; code masking needs a
47
+ * block-structure pre-pass), and a post-filter over these matches cannot recover a component a
48
+ * runaway match already consumed — `exec` has advanced past it. The tempting "just mirror the
49
+ * paired branch" tighten to `([^>]*)` is WORSE THAN THE BUG: it passes the entire existing test
50
+ * suite while silently deleting real committed content — `upload-media.md:166-167`
51
+ * (`<Gallery images={[{ src: "<url>", … }]} />`, `<AudioPlayer slug="<slug>" />`) match ZERO
52
+ * times under it.
53
+ *
54
+ * Use {@link scanMdxNodes} (offsets) or {@link extractMdxComponents} (no offsets). Still exported
55
+ * only so already-published consumers keep compiling.
24
56
  */
25
57
  export const MDX_COMPONENT_PATTERN =
26
58
  /<([A-Z][a-zA-Z]*)\s*([^>]*)>([\s\S]*?)<\/\1>|<([A-Z][a-zA-Z]*)\s*((?:[^/]|\/(?!>))*)\/>/g
@@ -94,10 +126,19 @@ export function parseJsxProps(propsString: string): Record<string, unknown> {
94
126
  } else if (s[i] === '{') {
95
127
  const expr = extractBraceExpression(s, i)
96
128
  if (expr) {
129
+ // Try the expression AS WRITTEN first. The `'` → `"` rewrite below exists only to accept
130
+ // single-quoted arrays (`images={['/a.jpg']}`), but applying it first corrupts any valid JSON
131
+ // containing an apostrophe — `{"it's \"x\""}` became `{"it"s \"x\""}` and fell through to the
132
+ // raw-string fallback. That matters now that `serializeProps` emits quote-bearing strings
133
+ // through this brace form.
97
134
  try {
98
- result[name] = JSON.parse(expr.content.replace(/'/g, '"'))
135
+ result[name] = JSON.parse(expr.content)
99
136
  } catch {
100
- result[name] = expr.content
137
+ try {
138
+ result[name] = JSON.parse(expr.content.replace(/'/g, '"'))
139
+ } catch {
140
+ result[name] = expr.content
141
+ }
101
142
  }
102
143
  i = expr.endIndex
103
144
  } else {
@@ -130,7 +171,18 @@ export function serializeProps(props: Record<string, unknown>): string {
130
171
  if (value === true) {
131
172
  parts.push(key)
132
173
  } else if (typeof value === 'string') {
133
- parts.push(`${key}="${value}"`)
174
+ // ⚠ A double quote cannot appear inside a double-quoted JSX attribute, so a value containing
175
+ // one goes out through the BRACE form instead. Emitting it raw produced content that neither
176
+ // this scanner nor @mdx-js/mdx can parse, and the failure was silent in three different ways:
177
+ // {title: 'Vyska 5" a delka'} → the component was DROPPED entirely on re-read
178
+ // {title: 'say "hi"'} → re-read as {title: 'say ', hi: true} — value truncated and a
179
+ // boolean prop invented out of the remaining text
180
+ // {alt: 'a " b', src: '/x'} → dropped, taking the unrelated `src` with it
181
+ // This writer is reachable from ordinary authoring: MdxBlockView's visual prop editor calls it
182
+ // on every edit, so typing a quote into a title corrupted the component on save.
183
+ // `{JSON.stringify(...)}` round-trips through `parseJsxProps`, which parses a brace expression
184
+ // as JSON.
185
+ parts.push(value.includes('"') ? `${key}={${JSON.stringify(value)}}` : `${key}="${value}"`)
134
186
  } else if (typeof value === 'number') {
135
187
  parts.push(`${key}={${value}}`)
136
188
  } else if (typeof value === 'boolean') {
@@ -194,52 +246,599 @@ export function extractFrontmatter(source: string): string | null {
194
246
  }
195
247
 
196
248
  /**
197
- * Extract MDX components from content, splitting into html chunks and component definitions.
198
- * Does NOT process markdown → HTML (caller handles that).
249
+ * Exact start offset of the `stripFrontmatter` result within `content`.
199
250
  *
200
- * @param content - MDX content (frontmatter should already be stripped)
201
- * @returns Array of parsed content items
251
+ * Mirrors `stripFrontmatter` exactly (substring after the closing `---`, then `.trim()`), so an
252
+ * offset produced by scanning the STRIPPED body can be mapped back onto full-article coordinates.
253
+ *
254
+ * ⚠ Do NOT derive this as `content.length - stripped.length` — `stripFrontmatter` trims BOTH
255
+ * ends, so that delta is not the prefix length. That confusion is half of the line-number defect
256
+ * this exists to fix: the validator searched the ORIGINAL content while extraction ran on the
257
+ * STRIPPED copy, so the two offset bases silently differed and a component name merely MENTIONED
258
+ * in frontmatter hijacked every reported line.
259
+ *
260
+ * KNOWN, PRE-EXISTING: a document opening with a `---` THEMATIC BREAK is still misread as
261
+ * frontmatter. This function faithfully mirrors that bug so offsets stay CONSISTENT with
262
+ * `stripFrontmatter`; fixing it is a separate change to `stripFrontmatter` itself.
202
263
  */
203
- export function extractMdxComponents(content: string): ParsedContent[] {
264
+ export function computeBodyOffset(content: string): number {
265
+ if (!content) return 0
266
+ if (!content.startsWith('---')) return 0 // no frontmatter → returned as-is, no trim
267
+ const endIndex = content.indexOf('---', 3)
268
+ if (endIndex === -1) return 0 // unterminated frontmatter → returned as-is
269
+ const preBodyEnd = endIndex + 3
270
+ const afterDelim = content.slice(preBodyEnd)
271
+ return preBodyEnd + (afterDelim.length - afterDelim.trimStart().length)
272
+ }
273
+
274
+ /** 1-based line number containing `offset` within `content`. */
275
+ export function lineAtOffset(content: string, offset: number): number {
276
+ if (offset <= 0) return 1
277
+ const limit = Math.min(offset, content.length)
278
+ let line = 1
279
+ for (let i = 0; i < limit; i++) {
280
+ if (content[i] === '\n') line++
281
+ }
282
+ return line
283
+ }
284
+
285
+ /** `computeCodeMask` flag: this offset is ordinary markup/prose. */
286
+ export const CODE_NONE = 0
287
+ /**
288
+ * `computeCodeMask` flag: this offset is inside a FENCED code block — block-level structure,
289
+ * therefore HIGH confidence. A tag whose own boundary lands in one is malformed and is rejected.
290
+ */
291
+ export const CODE_FENCE = 1
292
+ /**
293
+ * `computeCodeMask` flag: this offset is inside an INLINE code span — AMBIGUOUS, therefore lower
294
+ * confidence. A lone backtick inside a prop value (`title="the \` char"`) can pair with a genuine
295
+ * span later on the same line and mask the tag's own '>' or its closing tag. Inline masking may
296
+ * therefore hide a tag START, but must never invalidate a tag BOUNDARY (see `scanOpenTag`'s caller)
297
+ * and must never be the sole reason a paired tag loses its closer (see `findClosingTag`, which
298
+ * falls back to a masked closer rather than dropping the component).
299
+ */
300
+ export const CODE_INLINE = 2
301
+
302
+ /** Opening fence: up to 3 spaces of indent, then >=3 backticks or tildes, then the info string. */
303
+ const FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/
304
+ /** Closing fence: same run, and nothing but trailing horizontal whitespace after it. */
305
+ const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/
306
+
307
+ /**
308
+ * Flag every offset in `source` that sits inside a code region. `mask[i] !== CODE_NONE` means
309
+ * "offset i is code, not markup". Always exactly `source.length` long.
310
+ *
311
+ * ⚠ A PARALLEL FLAG ARRAY, NOT A MASKED COPY OF THE STRING. This is the one decision in this file
312
+ * that must never be "simplified" later. The obvious implementation — build a masked string and
313
+ * scan that — destroys content, because every slice the scanner emits (props, children, html
314
+ * chunks) would then come from the masked copy: a `<CodeBlock language="md">` wrapping a fenced
315
+ * sample would emit `children` of pure filler, and `title="Use \`code\` inline"` would become
316
+ * `title="Use ______ inline"`. With a flag array there is no second string to slice from by
317
+ * accident, index alignment is free, and the validator's offsets are exact by construction.
318
+ *
319
+ * WHY it exists at all (measured): the scanner had no notion of code, so 100% of the component
320
+ * instances in the entire shipped docs corpus — 49 fenced + 21 inline, ZERO in prose — were
321
+ * extracted as live components. All 4 fence flavours are affected (bare ```, ```lang,
322
+ * 1-3-space-indented, ~~~), and BOTH inline forms extract. It also made a component's own
323
+ * documentation unpublishable: `docs/public/features/editor-mcp.md` was rejected with HTTP 400
324
+ * `Gallery (line 194): Missing required prop "images"` purely from a fenced teaching example, and
325
+ * `features/article-feedback.md` — which contains ZERO fences — was blocked by an inline one.
326
+ *
327
+ * Three deliberate divergences from CommonMark, each chosen because the alternative loses
328
+ * legitimate content. Every one fails OPEN (toward extraction): a false negative re-renders a code
329
+ * sample as a live component — visible and reportable; a false positive DELETES a working
330
+ * component from a published page.
331
+ *
332
+ * 1. An UNTERMINATED fence masks NOTHING, and the scan RESUMES on the next line so a LATER
333
+ * well-formed fence in the same document is still masked. CommonMark extends an unclosed fence
334
+ * to end-of-document; honouring that drops every component after a stray fence, and this is not
335
+ * hypothetical — `docs/public/features/media-picker.md:204` opens a ```json fence it never
336
+ * closes. It would also break the extract → serialize → re-extract roundtrip for
337
+ * `<CodeBlock language="md">\n```\n</CodeBlock>`.
338
+ * 2. Inline spans are SINGLE-LINE and run-length matched (a run of N closes only on exactly N).
339
+ * CommonMark would pair a stray backtick with one on a later line and swallow a real component
340
+ * in between.
341
+ * 3. Four-space INDENTED code blocks are NOT masked. They are the only construct where masking is
342
+ * actively harmful: the continuation lines of a legitimate multi-line component are themselves
343
+ * indented >=4, so masking them would leave the tag matching with its props EMPTIED, turning
344
+ * valid content into a save-blocking `Missing required prop "images"`. A false negative beats a
345
+ * false error. (Blockquoted fences and fences indented >=4 inside list items are likewise not
346
+ * detected — same direction, same reason.)
347
+ */
348
+ export function computeCodeMask(source: string): Uint8Array {
349
+ const mask = new Uint8Array(source.length)
350
+ // Fast path: no fence or span delimiter can exist without one of these.
351
+ if (!source || (!source.includes('`') && !source.includes('~'))) return mask
352
+
353
+ // Line index over the ORIGINAL source; offsets stay valid in both views.
354
+ const lineStart: number[] = []
355
+ const lineEnd: number[] = []
356
+ for (let i = 0; i <= source.length; ) {
357
+ const nl = source.indexOf('\n', i)
358
+ lineStart.push(i)
359
+ lineEnd.push(nl === -1 ? source.length : nl)
360
+ if (nl === -1) break
361
+ i = nl + 1
362
+ }
363
+ /**
364
+ * The line's text WITHOUT its trailing CR.
365
+ *
366
+ * ⚠ Load-bearing for CRLF documents. `FENCE_CLOSE_RE` ends `[ \t]*$`, which a trailing '\r' does
367
+ * not satisfy — so on CRLF content the CLOSING fence never matched, every fenced block read as
368
+ * unterminated, and (because an unterminated fence deliberately masks nothing) the whole code-
369
+ * awareness fix silently did not apply: a fenced `<Gallery images={[1]} />` extracted as a live
370
+ * component again. Nothing in the write path normalises line endings, and the API already
371
+ * receives CRLF articles (there is a CRLF fixture in kb-api's embeddings spec), so this is
372
+ * reachable from ordinary Windows-authored content.
373
+ *
374
+ * Stripping it HERE rather than in the regexes keeps the fix in one place, and cannot disturb
375
+ * offsets: `lineText` feeds only the two fence tests, while the mask is filled from
376
+ * `lineStart`/`lineEnd`, which still index the original source.
377
+ */
378
+ const lineText = (n: number): string => {
379
+ const raw = source.slice(lineStart[n]!, lineEnd[n]!)
380
+ return raw.endsWith('\r') ? raw.slice(0, -1) : raw
381
+ }
382
+ const fencedLine = new Array<boolean>(lineStart.length).fill(false)
383
+
384
+ // ── Pass 1: fenced blocks. Runs FIRST so pass 2 never reads a fence delimiter as a span. ──
385
+ for (let ln = 0; ln < lineStart.length; ) {
386
+ const open = FENCE_OPEN_RE.exec(lineText(ln))
387
+ if (!open) { ln++; continue }
388
+ const marker = open[1]!
389
+ const fenceChar = marker[0]!
390
+ // CommonMark: a backtick-fence info string may not itself contain a backtick.
391
+ if (fenceChar === '`' && open[2]!.includes('`')) { ln++; continue }
392
+
393
+ let close = -1
394
+ for (let k = ln + 1; k < lineStart.length; k++) {
395
+ const m = FENCE_CLOSE_RE.exec(lineText(k))
396
+ if (m && m[1]![0] === fenceChar && m[1]!.length >= marker.length) { close = k; break }
397
+ }
398
+ // Unterminated → mask nothing, and resume on the NEXT line (not `break`) so a later
399
+ // well-formed fence is still masked.
400
+ if (close === -1) { ln++; continue }
401
+
402
+ mask.fill(CODE_FENCE, lineStart[ln]!, lineEnd[close]!)
403
+ for (let k = ln; k <= close; k++) fencedLine[k] = true
404
+ ln = close + 1
405
+ }
406
+
407
+ // ── Pass 2: inline spans, per line, run-length matched. ──
408
+ for (let ln = 0; ln < lineStart.length; ln++) {
409
+ if (fencedLine[ln]) continue
410
+ const from = lineStart[ln]!
411
+ const to = lineEnd[ln]!
412
+ let i = from
413
+ while (i < to) {
414
+ if (source[i] !== '`') { i++; continue }
415
+
416
+ let run = 0
417
+ while (i + run < to && source[i + run] === '`') run++
418
+
419
+ // A run of >=3 at line start is a fence delimiter pass 1 already ruled on (an unterminated
420
+ // opener is deliberately unmasked); reading it as a span delimiter would pair it with a
421
+ // backtick far down the document.
422
+ if (run >= 3 && source.slice(from, i).trim() === '') { i += run; continue }
423
+
424
+ let j = i + run
425
+ let close = -1
426
+ while (j < to) {
427
+ if (source[j] !== '`') { j++; continue }
428
+ let r = 0
429
+ while (j + r < to && source[j + r] === '`') r++
430
+ if (r === run) { close = j; break }
431
+ j += r
432
+ }
433
+ if (close === -1) { i += run; continue } // unterminated span → mask nothing
434
+ mask.fill(CODE_INLINE, i, close + run)
435
+ i = close + run
436
+ }
437
+ }
438
+
439
+ return mask
440
+ }
441
+
442
+ /** One scanned opening tag. Offsets are into the string passed to `scanOpenTag`. */
443
+ interface ScannedTag {
444
+ name: string
445
+ /** Verbatim props source, from the first non-space after the name to the terminator. */
446
+ propsSource: string
447
+ /** Offset just past this tag's '>' or '/>'. */
448
+ tagEnd: number
449
+ selfClosing: boolean
450
+ }
451
+
452
+ /**
453
+ * Scan one opening tag starting at `start` (which must be '<'), returning null when this is not a
454
+ * well-formed MDX component tag. The state machine at depth 0 outside quotes:
455
+ *
456
+ * '<' + [A-Z] → NAME (grammar is letters-only: `Product3D` is deliberately NOT a
457
+ * component — pinned by customComponents.spec.ts)
458
+ * NAME + ws|'>'|'/'→ PROPS (any other char → not a tag; this is what keeps a TS generic
459
+ * like `ref<Set<number>>` out)
460
+ * PROPS + '"'|"'" → IN_STRING (consumes '>' and '/>' — the paired-branch fix)
461
+ * PROPS + '{' → extractBraceExpression() (nesting- and quote-aware; unbalanced → null)
462
+ * PROPS + '/>' → DONE self-closing
463
+ * PROPS + '>' → DONE paired opener
464
+ * PROPS + '<' → NOT A TAG ← load-bearing prop-boundary bound
465
+ * PROPS + blank ln → NOT A TAG ← independent paragraph bound
466
+ *
467
+ * WHY a scanner and not a tightened regex: the old self-closing props group had no bound at all,
468
+ * so a prose `<Gallery>` mention ran to the next '/>' anywhere — 142 lines / 8916 chars / 1362
469
+ * "prop" tokens on `docs/public/tools/upload-media.md`. It cannot be fixed with a regex:
470
+ * - `([^>]*)` (mirroring the paired branch) passes all existing tests while silently DROPPING
471
+ * real committed content — `<Gallery images={[{ src: "<url>", alt: "<title>" }]} />` and
472
+ * `<AudioPlayer slug="<slug>" />` (`upload-media.md:166-167`) match ZERO times under it;
473
+ * - balanced braces nest to arbitrary depth (`images={[{...}]}`), which a JS regex cannot
474
+ * express, and a bounded-depth alternation only moves the silent-drop threshold.
475
+ * Reusing `extractBraceExpression` is what makes this provable rather than merely better: the
476
+ * scanner's notion of "a brace expression" is now the SAME function `parseJsxProps` uses, so a tag
477
+ * this scanner accepts is exactly a tag whose props `parseJsxProps` can read.
478
+ *
479
+ * The '<' bail is what stops the runaway recurring in the new implementation: without it an
480
+ * unterminated `<Gallery images=` walks forward through arbitrary prose to some '/>' hundreds of
481
+ * lines later — the identical old failure with a nicer implementation. A well-formed tag body can
482
+ * never contain a bare '<' at depth 0 outside quotes, and `title="a < b"` / `fn={x < y}` are
483
+ * consumed by the string/brace branches, so the bail costs nothing real.
484
+ *
485
+ * The blank-line bail is a second, independent bound, but it fires ONLY while a prop value is
486
+ * pending (a trailing '='). That condition is not decoration: an unconditional bail dropped
487
+ * `<Gallery\n images={[…]}\n\n columns={2}\n/>`, which @mdx-js/mdx accepts — so the reference
488
+ * parser and this scanner disagreed in the direction that deletes content. It cannot affect a
489
+ * multi-line `images={[ … ]}` either way (that newline lives inside the brace expression, consumed
490
+ * by extractBraceExpression); the measured corpus maximum for a real multi-line component is 4
491
+ * lines.
492
+ *
493
+ * Quoted values have NO escape handling, deliberately — see the `inString` branch. That matches
494
+ * `parseJsxProps`, which also ends a value at the first plain quote, so a tag this scanner accepts
495
+ * is exactly a tag whose props it can read.
496
+ */
497
+ function scanOpenTag(source: string, start: number): ScannedTag | null {
498
+ if (source[start] !== '<') return null
499
+
500
+ const first = source[start + 1]
501
+ if (first === undefined || first < 'A' || first > 'Z') return null
502
+
503
+ let i = start + 2
504
+ while (i < source.length && /[a-zA-Z]/.test(source[i]!)) i++
505
+ const name = source.slice(start + 1, i)
506
+
507
+ const sep = source[i]
508
+ if (sep === undefined) return null
509
+ if (sep !== '>' && sep !== '/' && !/\s/.test(sep)) return null
510
+
511
+ while (i < source.length && /\s/.test(source[i]!)) i++
512
+ const propsStart = i
513
+
514
+ /** True when the newline at `j` is followed by a blank line (i.e. a paragraph break). */
515
+ const blankLineAt = (j: number): boolean => {
516
+ let k = j + 1
517
+ while (k < source.length && (source[k] === ' ' || source[k] === '\t' || source[k] === '\r')) k++
518
+ return k >= source.length || source[k] === '\n'
519
+ }
520
+
521
+ let inString: string | null = null
522
+ while (i < source.length) {
523
+ const ch = source[i]!
524
+
525
+ if (inString) {
526
+ // ⚠ NO backslash-escape branch. JSX attribute values have no escape sequences, and treating
527
+ // '\' as one made an odd trailing run swallow the CLOSING quote: `title="C:\"` left the
528
+ // scanner permanently inside a string, so `<Callout title="C:\">Zaloha</Callout>` extracted
529
+ // ZERO components while the old regex read it fine — a silent drop, with validation still
530
+ // reporting `{valid: true}`. Worse, neither the '<' bail nor the blank-line bail can stop the
531
+ // walk, because both are only evaluated OUTSIDE a string, so a second stray quote later in the
532
+ // document produced a runaway paired match that deleted the prose between them.
533
+ //
534
+ // This is not hypothetical: `serializeProps` emits `key="value"` with no escaping, so the
535
+ // system's own writer produces such a value whenever a prop is edited to contain a quote.
536
+ // `parseJsxProps` likewise ends a value at the first plain '"', so dropping the branch makes
537
+ // the boundary agree with the parser that reads these props.
538
+ //
539
+ // An unterminated quote is still bounded by the paragraph break below, so it can never run
540
+ // away past the tag's own block.
541
+ if (ch === '\n' && blankLineAt(i)) return null
542
+ if (ch === inString) inString = null
543
+ i++
544
+ continue
545
+ }
546
+
547
+ if (ch === '"' || ch === "'") { inString = ch; i++; continue }
548
+
549
+ if (ch === '{') {
550
+ const expr = extractBraceExpression(source, i)
551
+ if (!expr) return null // unbalanced brace → not a tag we can trust
552
+ i = expr.endIndex
553
+ continue
554
+ }
555
+
556
+ if (ch === '/' && source[i + 1] === '>') {
557
+ return { name, propsSource: source.slice(propsStart, i), tagEnd: i + 2, selfClosing: true }
558
+ }
559
+ if (ch === '>') {
560
+ return { name, propsSource: source.slice(propsStart, i), tagEnd: i + 1, selfClosing: false }
561
+ }
562
+ if (ch === '<') return null
563
+
564
+ if (ch === '\n') {
565
+ if (blankLineAt(i)) {
566
+ // Only fatal while a prop VALUE is PENDING — a trailing '=' with nothing after it is the
567
+ // runaway precondition (`<Gallery images=` followed by paragraphs of prose and some stray
568
+ // '/>' far below). A blank line between COMPLETE props is valid MDX: @mdx-js/mdx accepts
569
+ // <Gallery\n images={["/a.jpg"]}\n\n columns={2}\n/>
570
+ // and an unconditional bail dropped it silently — 0 components, `{valid: true}`, and the
571
+ // sanitizer then removed the unknown tag, so the gallery disappeared from the page with no
572
+ // error and no line number to chase. The old regex parsed it and both props.
573
+ let k = i - 1
574
+ while (k >= start && /\s/.test(source[k]!)) k--
575
+ if (source[k] === '=') return null
576
+ }
577
+ i++
578
+ continue
579
+ }
580
+
581
+ i++
582
+ }
583
+
584
+ return null // ran off the end with no terminator
585
+ }
586
+
587
+ /**
588
+ * Find the matching `</Name>` for a paired opener.
589
+ *
590
+ * FIRST match wins (not innermost/balanced) — byte-identical to the lazy `([\s\S]*?)<\/\1>` it
591
+ * replaces, so two sibling `<Callout>`s stay two components (pinned by the existing suite).
592
+ * Same-name NESTING therefore remains unsupported; there is none in the corpus, and changing it
593
+ * would be a behaviour change beyond the measured defects.
594
+ *
595
+ * PREFER an UNMASKED closer; fall back to the first masked one. Two independent reasons:
596
+ * - preferring unmasked is what lets `<CodeBlock language="md">` wrap a fenced sample that itself
597
+ * contains a literal `</CodeBlock>` — the lazy regex stopped at that fake closer and leaked the
598
+ * fence tail into a mangled html chunk;
599
+ * - falling back rather than dropping is what saves the paired form of the inline-span hazard:
600
+ * `<Callout type="info" title="the \` char">x</Callout> and \`code\` after` has its real closer
601
+ * swallowed by an inline span that pairs the prop's stray backtick with the span after the tag.
602
+ * Returning null there would DROP a component that renders correctly today.
603
+ *
604
+ * The preference is bounded by `hasSiblingOpenerBefore`: an unmasked closer lying past another
605
+ * opener of the same name belongs to that sibling, so it is rejected in favour of this tag's own
606
+ * (masked) closer. Without that bound the two components collapse into one and the prose between
607
+ * them is swallowed — the very failure this rewrite exists to remove, one level up.
608
+ *
609
+ * Trailing whitespace before '>' is tolerated (`</Callout >`) — a strict superset of the old
610
+ * behaviour (such a tag matched nothing before and fell into the runaway self-closing branch). The
611
+ * next-non-space-must-be-'>' check is also what stops `</Gallery` matching inside `</GalleryFoo>`.
612
+ */
613
+ function findClosingTag(
614
+ source: string,
615
+ name: string,
616
+ from: number,
617
+ mask: Uint8Array,
618
+ /**
619
+ * Names already proven to have NO unmasked closer left. Purely a performance memo — see below.
620
+ * Caller-owned so it lives for one `scanMdxNodes` call.
621
+ */
622
+ noUnmaskedClosers?: Set<string>,
623
+ ): { start: number; end: number } | null {
624
+ const needle = `</${name}`
625
+ let firstAny: { start: number; end: number } | null = null
626
+
627
+ // ⚠ QUADRATIC GUARD. Without it, every opener of a name whose closers are ALL masked rescans the
628
+ // whole remaining document looking for an unmasked one. Measured: 11KB/22KB/45KB of that shape
629
+ // cost 9.1/21.6/78.5ms (exponent ~1.9) where the old regex was FLAT at 0.1-0.2ms — the one new
630
+ // quadratic this rewrite introduced, and the only shape where it lost to the code it replaced.
631
+ //
632
+ // Soundness: closers at/after a LATER offset are a subset of those at/after an EARLIER one, and
633
+ // openers are visited in ascending order. So "no unmasked closer of this name after X" implies the
634
+ // same for every Y > X, and the memo can never hide a closer a full scan would have found. Once a
635
+ // name is in the set we still need `firstAny`, but that is the FIRST valid closer, so it costs one
636
+ // scan that stops early instead of one that always runs to EOF.
637
+ const skipUnmaskedSearch = noUnmaskedClosers?.has(name) ?? false
638
+
639
+ /**
640
+ * Is there another OPENER of this same name strictly before `limit`?
641
+ *
642
+ * ⚠ This is the sibling bound on the unmasked preference, and it is load-bearing. Without it, a
643
+ * component whose OWN closer is masked by a false-positive inline span walks past its own closer to
644
+ * the next same-name sibling's closer, absorbing that sibling and all the prose between — two
645
+ * components collapse into one and the text in the middle disappears. That is the same failure the
646
+ * whole rewrite exists to remove, reintroduced one level up. Verified with
647
+ * `<A title="` + backtick + `">first</A> ` + span + `\n<A title="t">second</A>`, which produced a
648
+ * single component whose children ran to the second closer.
649
+ *
650
+ * `</Name` never matches `<Name`, so only real openers are found; the letter check after the name
651
+ * stops `<GalleryFoo` counting as a `<Gallery` opener.
652
+ */
653
+ const hasSiblingOpenerBefore = (limit: number): boolean => {
654
+ const openNeedle = `<${name}`
655
+ let k = source.indexOf(openNeedle, from)
656
+ while (k !== -1 && k < limit) {
657
+ const after = source[k + openNeedle.length]
658
+ if (after === undefined || !/[a-zA-Z]/.test(after)) return true
659
+ k = source.indexOf(openNeedle, k + 1)
660
+ }
661
+ return false
662
+ }
663
+
664
+ let i = from
665
+
666
+ while (i < source.length) {
667
+ const at = source.indexOf(needle, i)
668
+ if (at === -1) break
669
+
670
+ let j = at + needle.length
671
+ while (j < source.length && /\s/.test(source[j]!)) j++
672
+ if (source[j] === '>') {
673
+ const hit = { start: at, end: j + 1 }
674
+ // Prefer an unmasked closer, but never one that belongs to a later sibling.
675
+ if (mask[at] === CODE_NONE && !hasSiblingOpenerBefore(at)) return hit
676
+ if (!firstAny) {
677
+ firstAny = hit
678
+ if (skipUnmaskedSearch) return firstAny
679
+ }
680
+ }
681
+
682
+ i = at + needle.length
683
+ }
684
+
685
+ // Ran the whole tail without an unmasked closer: record it so sibling openers skip that scan.
686
+ if (firstAny) noUnmaskedClosers?.add(name)
687
+ return firstAny
688
+ }
689
+
690
+ /** An html span between components, with exact offsets into the scanned string. */
691
+ export interface MdxScanHtmlNode {
692
+ type: 'html'
693
+ /** Verbatim slice of the scanned string (never trimmed). */
694
+ content: string
695
+ start: number
696
+ end: number
697
+ }
698
+
699
+ /** One component instance, with exact offsets into the scanned string. */
700
+ export interface MdxScanComponentNode {
701
+ type: 'component'
702
+ name: string
703
+ /** Raw props source, verbatim — already parsed into `props`, kept for splices and debugging. */
704
+ propsSource: string
705
+ props: Record<string, unknown>
706
+ /** Trimmed inner source; `undefined` for a self-closing tag, `''` for `<X></X>`. */
707
+ children?: string
708
+ /** Offset of '<'. */
709
+ start: number
710
+ /** Offset just past '/>' or '</Name>'. */
711
+ end: number
712
+ }
713
+
714
+ export type MdxScanNode = MdxScanHtmlNode | MdxScanComponentNode
715
+
716
+ /**
717
+ * THE canonical MDX split — single-pass, code-aware, brace/quote-aware, offset-bearing.
718
+ * `extractMdxComponents` is a thin adapter over it; every other surface should be expressed in
719
+ * terms of it rather than re-walking `MDX_COMPONENT_PATTERN` (several sites did, and therefore
720
+ * carried both bugs independently).
721
+ *
722
+ * Structure is LOCATED on the code mask; every string is SLICED from the ORIGINAL. That split is
723
+ * the whole safety property: masking decides what IS a component, never what a component CONTAINS.
724
+ *
725
+ * Offsets are relative to the string PASSED IN. A caller that scanned a frontmatter-stripped body
726
+ * and needs file coordinates must add `computeBodyOffset(originalContent)`.
727
+ *
728
+ * Nested components are handled by consumers re-scanning `children` (see `checkPin`), so the mask
729
+ * is re-derived per level rather than inherited — a fence inside a component's children must still
730
+ * be a fence when that child text is scanned on its own.
731
+ */
732
+ export function scanMdxNodes(content: string): MdxScanNode[] {
733
+ if (!content) return []
204
734
  if (!HAS_MDX_RE.test(content)) {
205
- return [{ type: 'html', content }]
735
+ return [{ type: 'html', content, start: 0, end: content.length }]
206
736
  }
207
737
 
208
- const componentRe = new RegExp(MDX_COMPONENT_PATTERN.source, 'g')
209
- const items: ParsedContent[] = []
738
+ const mask = computeCodeMask(content)
739
+ const nodes: MdxScanNode[] = []
740
+ /** Performance memo for `findClosingTag`; scoped to this one walk. */
741
+ const noUnmaskedClosers = new Set<string>()
210
742
  let lastIndex = 0
211
- let match
743
+ let i = 0
744
+ let foundComponent = false
745
+
746
+ while (i < content.length) {
747
+ const lt = content.indexOf('<', i)
748
+ if (lt === -1) break
749
+
750
+ // A component mentioned inside code is documentation, not markup.
751
+ if (mask[lt] !== CODE_NONE) { i = lt + 1; continue }
212
752
 
213
- while ((match = componentRe.exec(content)) !== null) {
214
- if (match.index > lastIndex) {
215
- const raw = content.slice(lastIndex, match.index)
216
- if (raw.trim()) {
217
- items.push({ type: 'html', content: raw })
753
+ // Parsed from the ORIGINAL — the mask only decided that a tag MAY start here.
754
+ const tag = scanOpenTag(content, lt)
755
+ if (!tag) { i = lt + 1; continue }
756
+
757
+ // The tag's own terminator landed inside a FENCED block → it straddles block structure and is
758
+ // malformed. Fence-only on purpose: an inline span must never veto a boundary, or a stray
759
+ // backtick in a prop value would drop a component that renders correctly today.
760
+ if (mask[tag.tagEnd - 1] === CODE_FENCE) { i = lt + 1; continue }
761
+
762
+ let end: number
763
+ let children: string | undefined
764
+
765
+ if (tag.selfClosing) {
766
+ end = tag.tagEnd
767
+ } else {
768
+ const closer = findClosingTag(content, tag.name, tag.tagEnd, mask, noUnmaskedClosers)
769
+ if (!closer) {
770
+ // An opener with no closer anywhere is literal text — overwhelmingly a prose or
771
+ // inline-code mention like `<Gallery>`, which is exactly what must NOT anchor a match.
772
+ // Resume past the opener, not at lt+1: its body is known to contain no bare '<' at depth
773
+ // 0, and skipping it prevents a `<Gallery />` written inside a QUOTED prop value from
774
+ // being extracted as a component.
775
+ i = tag.tagEnd
776
+ continue
218
777
  }
778
+ children = content.slice(tag.tagEnd, closer.start).trim()
779
+ end = closer.end
219
780
  }
220
781
 
221
- const name = match[1] || match[4] || ''
222
- const propsStr = match[1] ? (match[2] || '') : (match[5] || '')
223
- const children = match[3]
782
+ if (lt > lastIndex) {
783
+ const raw = content.slice(lastIndex, lt)
784
+ if (raw.trim()) nodes.push({ type: 'html', content: raw, start: lastIndex, end: lt })
785
+ }
224
786
 
225
- items.push({
787
+ nodes.push({
226
788
  type: 'component',
227
- name,
228
- props: parseJsxProps(propsStr),
229
- children: children?.trim(),
789
+ name: tag.name,
790
+ propsSource: tag.propsSource,
791
+ props: parseJsxProps(tag.propsSource),
792
+ children,
793
+ start: lt,
794
+ end,
230
795
  })
231
796
 
232
- lastIndex = match.index + match[0].length
797
+ foundComponent = true
798
+ lastIndex = end
799
+ i = end
233
800
  }
234
801
 
235
802
  if (lastIndex < content.length) {
236
- const remaining = content.slice(lastIndex)
237
- if (remaining.trim()) {
238
- items.push({ type: 'html', content: remaining })
239
- }
803
+ const raw = content.slice(lastIndex)
804
+ if (raw.trim()) nodes.push({ type: 'html', content: raw, start: lastIndex, end: content.length })
805
+ }
806
+
807
+ // HAS_MDX_RE matched but nothing well-formed survived (e.g. every occurrence is in code).
808
+ // Collapsing to one html node is what lets every renderer take its existing pure-markdown
809
+ // fallback instead of rendering an empty slot.
810
+ if (!foundComponent) {
811
+ return content.trim() ? [{ type: 'html', content, start: 0, end: content.length }] : []
240
812
  }
241
813
 
242
- // Fallback: regex found no components despite HAS_MDX_RE match
814
+ return nodes
815
+ }
816
+
817
+ /**
818
+ * Extract MDX components from content, splitting into html chunks and component definitions.
819
+ * Does NOT process markdown → HTML (caller handles that).
820
+ *
821
+ * Thin adapter over `scanMdxNodes`; the offsets are dropped here ON PURPOSE. `ParsedContent` is a
822
+ * PUBLISHED type (headless tenants render off it) and existing specs pin its exact shape with a
823
+ * strict `toEqual`, encoding the html / `children: undefined` / `children: ''` tri-state. Adding
824
+ * offsets would break those specs and force every renderer to handle a field it does not use.
825
+ * Callers that need offsets (validation, render-embed, the review app) call `scanMdxNodes`.
826
+ *
827
+ * @param content - MDX content (frontmatter should already be stripped)
828
+ * @returns Array of parsed content items
829
+ */
830
+ export function extractMdxComponents(content: string): ParsedContent[] {
831
+ if (!HAS_MDX_RE.test(content)) {
832
+ return [{ type: 'html', content }]
833
+ }
834
+
835
+ const items: ParsedContent[] = scanMdxNodes(content).map(node =>
836
+ node.type === 'html'
837
+ ? { type: 'html', content: node.content }
838
+ : { type: 'component', name: node.name, props: node.props, children: node.children },
839
+ )
840
+
841
+ // Fallback: nothing well-formed survived the scan.
243
842
  if (items.length === 0 && content.trim()) {
244
843
  return [{ type: 'html', content }]
245
844
  }