(source: string)
| 23 | } |
| 24 | |
| 25 | export function parse(source: string): Imports { |
| 26 | const fail = (): never => { |
| 27 | throw new Error(`Invalid import declaration: ${source}`) |
| 28 | } |
| 29 | const decode = (text: string): string => |
| 30 | text.replace( |
| 31 | /\\(?:u\{([\da-fA-F]+)\}|u([\da-fA-F]{4})|x([\da-fA-F]{2})|(\r\n|[\s\S]))/gu, |
| 32 | (match, point, unit, hex, char, offset) => { |
| 33 | const digits = point ?? unit ?? hex |
| 34 | if (digits !== undefined) { |
| 35 | const value = Number.parseInt(digits, 16) |
| 36 | return value <= 0x10ffff ? String.fromCodePoint(value) : fail() |
| 37 | } |
| 38 | if ( |
| 39 | char === "u" || char === "x" || /[1-9]/.test(char) || |
| 40 | (char === "0" && /\d/.test(text[offset + match.length] ?? "")) |
| 41 | ) return fail() |
| 42 | return escapes[char] ?? char |
| 43 | } |
| 44 | ) |
| 45 | const tokens = tokenize(source).map((token) => { |
| 46 | const value = decode(token.kind === "string" ? token.text.slice(1, -1) : token.text) |
| 47 | if (token.kind === "identifier" && !/^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(value)) return fail() |
| 48 | return { kind: token.kind, value } |
| 49 | }) |
| 50 | |
| 51 | let index = 0 |
| 52 | const at = (value: string): boolean => tokens[index]?.value === value && tokens[index]?.kind !== "string" |
| 53 | const take = (value: string): boolean => at(value) ? (index++, true) : false |
| 54 | const expect = (value: string): void => { |
| 55 | if (!take(value)) fail() |
| 56 | } |
| 57 | const identifier = (): string => { |
| 58 | const token = tokens[index++] |
| 59 | return token?.kind === "identifier" ? token.value : fail() |
| 60 | } |
| 61 | const string = (): string => { |
| 62 | const token = tokens[index++] |
| 63 | return token?.kind === "string" ? token.value : fail() |
| 64 | } |
| 65 | const imports: Array<Imports[number]> = [] |
| 66 | while (index < tokens.length) { |
| 67 | expect("import") |
| 68 | const clause: Array<Omit<Import, "module" | "attributes">> = [] |
| 69 | let typeOnly = false |
| 70 | if (tokens[index]?.kind !== "string") { |
| 71 | typeOnly = at("type") && tokens[index + 1]?.value !== "from" && tokens[index + 1]?.value !== "," |
| 72 | ? (index++, true) |
| 73 | : false |
| 74 | if (tokens[index]?.kind === "identifier") { |
| 75 | clause.push({ kind: "Default", imported: "default", local: identifier(), typeOnly }) |
| 76 | if (!take(",")) expect("from") |
| 77 | } |
| 78 | if (take("*")) { |
| 79 | expect("as") |
| 80 | clause.push({ kind: "Namespace", imported: "*", local: identifier(), typeOnly }) |
| 81 | expect("from") |
| 82 | } else if (take("{")) { |
nothing calls this directly
no test coverage detected