Created
August 16, 2024 10:00
-
-
Save hyrious/18cf349a57b0216fa6b03734be9df2bc to your computer and use it in GitHub Desktop.
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
// https://github.com/evanw/esbuild/blob/main/internal/helpers/dataurl.go | |
const CharCode = { | |
Tab: 9, | |
LineFeed: 10, | |
CarriageReturn: 13, | |
Space: 32, | |
Hash: 35, | |
PercentSign: 37, | |
} | |
function isHex(c: number) { | |
return c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0) || c >= 'A'.charCodeAt(0) && c <= 'F'.charCodeAt(0) || c >= 'a'.charCodeAt(0) && c <= 'f'.charCodeAt(0) | |
} | |
function escape(text: string) { | |
const hex = '0123456789ABCDEF' | |
const n = text.length | |
let result = '' | |
// Spaces can be safely emitted for usage like `url()`, however it should always be escaped at the end | |
let trailingStart = n | |
for (; trailingStart > 0; trailingStart--) { | |
const c = text.charCodeAt(trailingStart - 1) | |
if (c > CharCode.Space || c === CharCode.Tab || c === CharCode.LineFeed || c === CharCode.CarriageReturn) | |
break | |
} | |
let runStart = 0 | |
for (let i = 0; i < n; i++) { | |
const c = text.charCodeAt(i) | |
if (c === CharCode.Tab || c === CharCode.LineFeed || c === CharCode.CarriageReturn || c === CharCode.Hash | |
|| i >= trailingStart | |
|| (c === CharCode.PercentSign && i + 2 < n && isHex(text.charCodeAt(i + 1)) && isHex(text.charCodeAt(i + 2))) | |
) { | |
if (runStart < i) | |
result += text.slice(runStart, i) | |
result += `%${hex[c >> 4]}${hex[c & 15]}` | |
runStart = i + 1 | |
} | |
} | |
if (runStart < n) | |
result += text.slice(runStart) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment