JavaScriptSourceNormalization.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptSourceNormalization.kt
1package eu.friedcutlet.yokan.services.extensions.js23private val AsyncKeyword = Regex(4 """\basync\b(?=\s*(?:function\b|[A-Za-z_$][A-Za-z0-9_$]*\s*\(|\([^)]*\)\s*=>|[A-Za-z_$][A-Za-z0-9_$]*\s*=>))""",5)6private val AwaitKeyword = Regex("""\bawait\b(?!\s*[:=])""")7private val AwaitMethod = Regex("""\([^)]*\)\s*\{""")89/** Host APIs complete synchronously. Remove modifiers only from code, never scraped text or patterns. */10internal fun synchronousJavaScriptSource(sourceCode: String): String {11 if (!sourceCode.contains("async") && !sourceCode.contains("await")) return sourceCode12 val code = JavaScriptCodeMask(sourceCode).build()13 val removed = BooleanArray(sourceCode.length)14 for (pattern in listOf(AsyncKeyword, AwaitKeyword)) {15 for (match in pattern.findAll(code)) {16 var before = match.range.first - 117 while (before >= 0 && code[before].isWhitespace()) before--18 val previous = code.getOrNull(before)19 if (previous == '.') continue // Object members named async / await are ordinary identifiers.20 if (code.getOrNull(match.range.first - 1) == '$' || code.getOrNull(match.range.last + 1) == '$') continue21 if (pattern === AwaitKeyword) {22 var after = match.range.last + 123 while (after < code.length && code[after].isWhitespace()) after++24 if (code.getOrNull(after) in listOf(null, '}', ',', ';', ')', ']')) continue25 // An object/class method named await is not an await expression.26 if (code.getOrNull(after) == '(' && AwaitMethod.matchAt(code, after) != null) continue27 }28 var end = match.range.last + 129 while (end < sourceCode.length && sourceCode[end] in " \t") end++30 if (pattern === AwaitKeyword) {31 var triviaEnd = end32 while (triviaEnd < code.length && code[triviaEnd].isWhitespace()) triviaEnd++33 // Removing await must not introduce a newline after return/throw (automatic semicolon insertion).34 if ((end until triviaEnd).any { sourceCode[it] == '\n' || sourceCode[it] == '\r' }) end = triviaEnd35 }36 for (index in match.range.first until end) removed[index] = true37 }38 }39 return buildString(sourceCode.length) {40 sourceCode.forEachIndexed { index, char -> if (!removed[index]) append(char) }41 }42}4344/** A lexical mask retains code offsets, including expressions nested inside template literals. */45private class JavaScriptCodeMask(private val source: String) {46 private val mask = source.toCharArray()47 private val expressionKeywords = setOf("return", "throw", "case", "delete", "void", "typeof", "new", "in", "of", "yield", "await", "else", "do", "instanceof")48 private val controlKeywords = setOf("if", "while", "for", "with", "switch", "catch")4950 fun build(): String {51 code(0, interpolation = false)52 return mask.concatToString()53 }5455 private fun hide(start: Int, end: Int, comment: Boolean = false) {56 for (index in start until end) {57 if (source[index] != '\n' && source[index] != '\r') mask[index] = if (comment) ' ' else '#'58 }59 }6061 private fun quoted(start: Int, quote: Char): Int {62 var index = start + 163 while (index < source.length) {64 when (source[index++]) {65 '\\' -> if (index < source.length) index++66 quote -> break67 }68 }69 hide(start, index)70 return index71 }7273 private fun template(start: Int): Int {74 var index = start + 175 var chunk = start76 while (index < source.length) {77 when {78 source[index] == '\\' -> index = (index + 2).coerceAtMost(source.length)79 source[index] == '`' -> {80 hide(chunk, index + 1)81 return index + 182 }83 source[index] == '$' && source.getOrNull(index + 1) == '{' -> {84 hide(chunk, index + 2)85 index = code(index + 2, interpolation = true)86 chunk = index87 }88 else -> index++89 }90 }91 hide(chunk, index)92 return index93 }9495 private fun regexEnd(start: Int): Int? {96 var index = start + 197 var characterClass = false98 while (index < source.length) {99 when (source[index++]) {100 '\n', '\r' -> return null101 '\\' -> if (index < source.length) index++102 '[' -> characterClass = true103 ']' -> characterClass = false104 '/' -> if (!characterClass) {105 while (index < source.length && source[index].isLetter()) index++106 return index107 }108 }109 }110 return null111 }112113 private fun code(start: Int, interpolation: Boolean): Int {114 var index = start115 var braces = 0116 var regexAllowed = true117 var previousWord = ""118 var previousToken = ""119 val controlParentheses = mutableListOf<Boolean>()120 val objectBraces = mutableListOf<Boolean>()121 while (index < source.length) {122 val char = source[index]123 when {124 char.isWhitespace() -> { index++; continue }125 char == '\'' || char == '"' -> { index = quoted(index, char); regexAllowed = false }126 char == '`' -> { index = template(index); regexAllowed = false }127 char == '/' && source.getOrNull(index + 1) == '/' -> {128 val end = source.indexOf('\n', index).let { if (it < 0) source.length else it }129 hide(index, end, comment = true); index = end; continue130 }131 char == '/' && source.getOrNull(index + 1) == '*' -> {132 val end = source.indexOf("*/", index + 2).let { if (it < 0) source.length else it + 2 }133 hide(index, end, comment = true); index = end; continue134 }135 char == '/' && regexAllowed && regexEnd(index) != null -> {136 val end = requireNotNull(regexEnd(index))137 hide(index, end); index = end; regexAllowed = false138 }139 char.isLetter() || char == '_' || char == '$' -> {140 val begin = index++141 while (index < source.length && (source[index].isLetterOrDigit() || source[index] == '_' || source[index] == '$')) index++142 previousWord = source.substring(begin, index)143 previousToken = previousWord144 regexAllowed = previousWord in expressionKeywords145 continue146 }147 char.isDigit() -> {148 index++149 while (index < source.length && (source[index].isLetterOrDigit() || source[index] in "._")) index++150 regexAllowed = false151 }152 else -> {153 index++154 when (char) {155 '(' -> { controlParentheses += previousWord in controlKeywords; regexAllowed = true }156 ')' -> { regexAllowed = controlParentheses.removeLastOrNull() == true }157 '{' -> {158 objectBraces += previousToken in setOf("=", "(", "[", ",", ":", "return") || (interpolation && index - 1 == start)159 braces++; regexAllowed = true160 }161 '}' -> {162 if (braces == 0 && interpolation) { hide(index - 1, index); return index }163 braces--; regexAllowed = objectBraces.removeLastOrNull() != true164 }165 ']', '.' -> regexAllowed = false166 '+', '-' -> {167 if (source.getOrNull(index) == char) { index++; regexAllowed = false }168 else regexAllowed = true169 }170 else -> regexAllowed = true171 }172 }173 }174 previousToken = source.substring((index - 1).coerceAtLeast(start), index)175 previousWord = ""176 }177 return index178 }179}180