(code: string, origin: string, dependencies: Record<string, string>)
| 4 | * Rewrites all imports in the given code to point to unpkg URLs. |
| 5 | */ |
| 6 | export function rewriteImports(code: string, origin: string, dependencies: Record<string, string>): string { |
| 7 | let [imports] = parse(code); |
| 8 | let rewrites: { start: number; end: number; value: string }[] = []; |
| 9 | |
| 10 | for (let imp of imports) { |
| 11 | // Skip imports without a specifier |
| 12 | if (imp.n === undefined) { |
| 13 | continue; |
| 14 | } |
| 15 | |
| 16 | let specifier = code.slice(imp.s, imp.e); |
| 17 | |
| 18 | let rewriteValue: string; |
| 19 | if (imp.t === 2) { |
| 20 | // dynamic import() |
| 21 | let match = /^(["'])([^"']*)\1$/.exec(specifier); |
| 22 | if (match === null) continue; // not a simple string literal |
| 23 | rewriteValue = match[1] + rewriteSpecifier(match[2], origin, dependencies) + match[1]; |
| 24 | } else { |
| 25 | rewriteValue = rewriteSpecifier(specifier, origin, dependencies); |
| 26 | } |
| 27 | |
| 28 | if (rewriteValue !== specifier) { |
| 29 | rewrites.push({ start: imp.s, end: imp.e, value: rewriteValue }); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | // Sort rewrites in reverse order to avoid position shifts |
| 34 | rewrites.sort((a, b) => b.start - a.start); |
| 35 | |
| 36 | let result = code; |
| 37 | for (let { start, end, value } of rewrites) { |
| 38 | result = result.slice(0, start) + value + result.slice(end); |
| 39 | } |
| 40 | |
| 41 | return result; |
| 42 | } |
| 43 | |
| 44 | function rewriteSpecifier(specifier: string, origin: string, dependencies: Record<string, string>): string { |
| 45 | if (specifier === "" || isValidUrl(specifier)) { |
no test coverage detected