Created
August 13, 2025 10:50
-
-
Save vphantom/5fb8bcaecf562591a0cf8d488474be23 to your computer and use it in GitHub Desktop.
Re-escape Unicode characters in CSS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| /** | |
| * escape-unicode.js - A script to escape Unicode characters in CSS content properties | |
| * | |
| * This script finds actual Unicode characters in CSS content properties and | |
| * converts them back to escape sequences. It's designed to be run after the | |
| * PostCSS/LightningCSS build process. | |
| * | |
| * Usage: node escape-unicode.js <css-file> | |
| */ | |
| const fs = require('fs'); | |
| const contentRegex = /content\s*:\s*(['"])(.*?)\1/g; | |
| /** | |
| * Escape Unicode characters in a string | |
| * @param {string} str - The string to process | |
| * @returns {string} - The processed string with Unicode characters escaped | |
| */ | |
| function escapeUnicode(str) { | |
| return str.replace( | |
| /[\u0080-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, | |
| (char) => { | |
| const codePoint = char.codePointAt(0).toString(16); | |
| return ( | |
| '\\' + | |
| (codePoint.length <= 4 ? codePoint.padStart(4, '0') : codePoint) | |
| ); | |
| } | |
| ); | |
| } | |
| /** | |
| * Process a CSS file to escape Unicode characters in content properties | |
| * | |
| * @param {string} filePath - Path to the CSS file | |
| */ | |
| function escapeUnicodeInFile(filePath) { | |
| console.log(`Processing file: ${filePath}`); | |
| let css; | |
| try { | |
| css = fs.readFileSync(filePath, 'utf8'); | |
| } catch (error) { | |
| console.error(`Error reading file: ${error.message}`); | |
| process.exit(1); | |
| } | |
| let changesCount = 0; | |
| const fixed = css.replace(contentRegex, (match, quote, content) => { | |
| const escaped = escapeUnicode(content); | |
| if (escaped !== content) { | |
| changesCount++; | |
| } | |
| return `content: ${quote}${escaped}${quote}`; | |
| }); | |
| if (changesCount > 0) { | |
| try { | |
| fs.writeFileSync(filePath, fixed, 'utf8'); | |
| console.log( | |
| `Escaped ${changesCount} Unicode content properties in ${filePath}` | |
| ); | |
| } catch (error) { | |
| console.error(`Error writing file: ${error.message}`); | |
| process.exit(1); | |
| } | |
| } else { | |
| console.log('No changes needed.'); | |
| } | |
| } | |
| const args = process.argv.slice(2); | |
| if (args.length === 0) { | |
| console.error('Please provide a CSS file path.'); | |
| process.exit(1); | |
| } | |
| args.forEach(escapeUnicodeInFile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment