Files
bunext/dist/utils/serialize-for-script.js
T
2026-10-13 15:52:34 +01:00

17 lines
581 B
JavaScript

/**
* # Serialize a value as JSON that is safe to embed in an inline `<script>`
*
* Escapes `<`, `>`, `&`, U+2028 and U+2029 so the payload can never close
* the script tag (`</script>`), open an HTML comment (`<!--`) or otherwise
* change the HTML parser state.
*/
export default function serializeForScript(value) {
const json = JSON.stringify(value ?? null) ?? "null";
return json
.replace(/</g, "\\u003c")
.replace(/>/g, "\\u003e")
.replace(/&/g, "\\u0026")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}