ReviewOS

stacks/stx

component scanner runs over <script> content — JS string literals like Leaflet's '<v:shape>' get mis-resolved as components

#1730
Closed glennmichael123 opened this 23 days ago · 1 comment
23 days ago

Summary

stx's component-tag scanner walks the assembled page HTML with three regex passes (kebab-case → PascalCase → lowercase). These passes run against the full output, including <script> content. JS string literals that look like tags get matched and treated as component references.

Concrete repro: Leaflet 1.9's VML feature detection contains the literal:

div.innerHTML = '<v:shape adj="1"/>'

The lowercase regex (/[a-z][a-z0-9]*/) doesn't include : in its charset, so the match captures just v. v isn't in the built-in tag set, so the resolver tries to load v.stx from every configured component dir, fails with ENOENT, and injects the error string verbatim into the emitted JS — including unescaped single quotes around the failed path:

div.innerHTML = '[Error loading component: ENOENT: no such file or directory, open 'v']

The browser parser hits the unbalanced quote and dies with Uncaught SyntaxError: Unexpected identifier 'v'. Stack trace points into Leaflet's internals, masking the real cause.

Originally reported on stacksjs/stacks#1920 (a downstream project hitting this through Leaflet integration). Filing here because the fix belongs in stx.

Reproducer

<!-- resources/components/CourtMap.stx -->
<script client>
  import L from 'leaflet'
  onMount(() => { L.map('host').setView([40.7, -74.0], 13) })
</script>
<div id="host" class="h-64"></div>
bun add leaflet
bun stx dev
# Visit any page that includes CourtMap.stx — Uncaught SyntaxError: Unexpected identifier 'v'

Reproduces with the published leaflet@1.9.4. The triggering substring is '<v:shape adj="1"/>' inside Leaflet's vml feature detection — any library shipping legacy VML / XML-namespaced tag strings as JS string literals will produce the same shape (older jQuery plugins, some charting libs, anything compiled with IE6-era fallback code).

Root cause

packages/stx/src/component-renderer.ts:822-831 — inside processCustomElementTags:

// Process kebab-case components (e.g., <my-component />)
const kebabPattern = /[a-z][a-z0-9]*-[a-z0-9-]*/
output = await processTagsWithParser(output, kebabPattern, false)

// Process PascalCase components (e.g., <MyComponent />)
const pascalPattern = /[A-Z][a-zA-Z0-9]*/
output = await processTagsWithParser(output, pascalPattern, true)

// Process single-word lowercase components (e.g., <card />) - skip HTML tags
const lowercasePattern = /[a-z][a-z0-9]*/
output = await processTagsWithParser(output, lowercasePattern, false, htmlTags)

output at this point is the assembled page HTML including the rendered <script> blocks. findComponentTags(result, tagPattern, skipTags) doesn't know not to descend into script bodies — it operates purely on the string with a regex.

The same three-pass structure exists in packages/stx/src/component-processing.ts:748-757 (processCustomElements), which isn't on the live call graph today but should get the same fix defensively.

Impact

  • Silent at the framework layer — warnings only when options.debug is on.
  • Loud at runtime, in the wrong place — the error points into Leaflet's internals (or whatever library's literal happened to match), not into the user's template.
  • Blocks the "just bun add it" affordance for any non-trivial third-party browser library whose source contains legacy IE/XML markup as JS strings.
  • Original report estimated ~30 minutes to trace from "Unexpected identifier 'v'" → grep bundled output → find the injected ENOENT → match against Leaflet's source.

Suggested fix

Stash <script>...</script> content behind sentinel markers before the three-pass scan, restore after. stx already uses this shape inside per-component template processing — just apply it at the outer assembly pass too.

async function processCustomElementTags(template, context, filePath, options, dependencies) {
  if (!template) return template
  let output = template
  // ... existing setup ...

  // Stash <script> content so JS string literals like '<v:shape>'
  // aren't mistaken for component refs.
  const stashedScripts: string[] = []
  output = output.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, (m) => {
    const idx = stashedScripts.length
    stashedScripts.push(m)
    return `\x00STX_SCRIPT_${idx}\x00`
  })

  // ── existing three-pass scan ──
  output = await processTagsWithParser(output, kebabPattern, false)
  output = await processTagsWithParser(output, pascalPattern, true)
  output = await processTagsWithParser(output, lowercasePattern, false, htmlTags)

  return output.replace(/\x00STX_SCRIPT_(\d+)\x00/g, (_, idx) => stashedScripts[+idx])
}

Tradeoffs vs other approaches

  • Skip colonized tag names in the lowercase pass (/[a-z][a-z0-9]*(?![:_])/) — narrower fix, only addresses XML-namespaced strings. Still trips on bare <vshape> or similar non-builtin lowercase tags inside JS strings.
  • HTML-aware tokenizer instead of regex — correct but much bigger change.
  • Stash <script> content (this proposal) — matches what stx already does in the per-template scan, smallest delta.

<style> content might warrant the same treatment for consistency (a CSS string like content: "<x>" could trip the same trap), though I haven't seen a real-world repro for it.

Environment

  • stx main
  • Bun 1.3.13
  • Caught via leaflet@1.9.4 integration, reproduces on any browser
23 days ago

Fixed by b819ff5 on main.

<script> bodies are now stashed behind NUL-delimited sentinel markers before the three-pass component-tag scan in both component-renderer.ts:processCustomElementTags (the live path) and component-processing.ts:processCustomElements (defensive — currently not on the call graph). Restored after the scan completes.

Five-case regression test in test/components/script-tag-stashing.test.ts covers Leaflet's exact <v:shape adj="1"/> literal, multiple tag-like literals in one script, all script-tag variants (inline / type=module / <script client>), out-of-script tags still scanned, and no sentinel leakage. Verified by stashing the fix and re-running: 4/5 new tests fail without it, 5/5 pass with it. Fix also incidentally recovers 2 pre-existing component test failures.

Commit message references the issue but didn't include a Closes trigger — closing manually.

Sign in to comment on this issue.