#148

Astral chars (emoji) lose their low surrogate in SVG text under JavaScriptCore (WKWebView / Safari)

Opensatoshimanopened 17d ago

Repro (pele 1.13.0):

import { renderAsync } from 'pele/lazy';
const { svg } = await renderAsync('flowchart LR\nA["📝"]-->B', { fontFamily: 'sans-serif' });
engineemitted text node
V8 (Node / Chromium)<text ...>📝</text>
JavaScriptCore (WKWebView, Safari)<text ...>\ud83d</text> - lone high surrogate, renders as tofu

Every astral-plane character in a label - most emoji (📝 💻 🔀 📡 👩 👨), CJK ext-B, musical symbols, etc. - loses its low surrogate. BMP chars (e.g. ⚙️ U+2699) survive, so the damage looks like a missing emoji font but is actually corrupted text. Parse output is clean; the corruption happens at svg emission.

Cause: esc/escText in src/svg/builder.ts (the lone-surrogate strip added for #72) uses u-flagged classes:

const RE_NEEDS_ESC = /[&<>"\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff\ufffe\uffff]/u;
const RE_ESC      = /[&<>"]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff\ufffe\uffff]+/gu;

Per spec the u flag should make [\ud800-\udfff] match only unpaired surrogate code points. JavaScriptCore instead applies the class to the low surrogate inside a valid pair - the WebKit 267011 family (/u matching can land mid-pair; fixed in 276031@main with follow-ups through 287202@main, but the behavior below still reproduces on Safari 17.6 / WebKit 19618.3.11.11.5, macOS 14.7.4):

const RE = /[&<>"]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff\ufffe\uffff]+/gu;
'📝x'.replace(RE, '#');
// V8:  '📝x'
// JSC: '\ud83d#x'   (only the low surrogate is matched and stripped)

So on affected engines the #72 fix produces the very thing it removed: a lone surrogate in the emitted svg, which is also not well-formed XML.

Suggested fix: express the strip without the u flag so it is engine-agnostic. Match a valid pair first and pass it through:

const RE_ESC =
  /[\ud800-\udbff][\udc00-\udfff]|[&<>"]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff\ufffe\uffff]+/g;

// replace: valid pair -> keep, everything else -> escape map / strip
(m) => (m.length === 2 && m.charCodeAt(0) >= 0xd800 && m.charCodeAt(0) <= 0xdbff ? m : MAP[m] ?? '')

The alternation consumes a real pair as one unit on every engine (non-u matching is UTF-16 unit based everywhere), so lone surrogates still get stripped while valid pairs survive on WebKit versions before and after the 267011 fix.

Verified in a real WKWebView through the render path; the same string reaches <text> intact on V8.

Activity

0

No activity yet.