* Splits a string on commas that are at the top level (not inside parentheses, brackets, braces, or string literals). * This handles cases like "func(a, b), other" and 'return "a,b", x' correctly. * Supports single quotes, double quotes, and backticks, with proper escape handling.
(str: string)
| 26 | * Supports single quotes, double quotes, and backticks, with proper escape handling. |
| 27 | */ |
| 28 | function splitOnTopLevelCommas(str: string): string[] { |
| 29 | const results: string[] = [] |
| 30 | let current = '' |
| 31 | let depth = 0 |
| 32 | let inString: '"' | "'" | '`' | null = null |
| 33 | let escaped = false |
| 34 | |
| 35 | for (const char of str) { |
| 36 | // Handle escape sequences |
| 37 | if (escaped) { |
| 38 | current += char |
| 39 | escaped = false |
| 40 | continue |
| 41 | } |
| 42 | |
| 43 | if (char === '\\') { |
| 44 | current += char |
| 45 | escaped = true |
| 46 | continue |
| 47 | } |
| 48 | |
| 49 | // Handle string literals |
| 50 | if (char === '"' || char === "'" || char === '`') { |
| 51 | if (inString === null) { |
| 52 | // Entering a string |
| 53 | inString = char |
| 54 | } else if (inString === char) { |
| 55 | // Exiting a string (matching quote) |
| 56 | inString = null |
| 57 | } |
| 58 | current += char |
| 59 | continue |
| 60 | } |
| 61 | |
| 62 | // If we're inside a string, just add the character |
| 63 | if (inString !== null) { |
| 64 | current += char |
| 65 | continue |
| 66 | } |
| 67 | |
| 68 | // Handle brackets/parens/braces (only when not in a string) |
| 69 | if (char === '(' || char === '[' || char === '{') { |
| 70 | depth++ |
| 71 | current += char |
| 72 | } else if (char === ')' || char === ']' || char === '}') { |
| 73 | depth-- |
| 74 | current += char |
| 75 | } else if (char === ',' && depth === 0) { |
| 76 | // Split on comma only at top level and not in a string |
| 77 | results.push(current) |
| 78 | current = '' |
| 79 | } else { |
| 80 | current += char |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // Don't forget the last segment |
| 85 | if (current) { |