|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const { builtinModules } = require('node:module'); |
| 4 | + |
| 5 | +const NODE_BUILTINS = new Set( |
| 6 | + builtinModules |
| 7 | + .map((name) => (name.startsWith('node:') ? name.slice(5) : name)) |
| 8 | + .filter(Boolean), |
| 9 | +); |
| 10 | + |
| 11 | +const IMPORT_PATTERNS = { |
| 12 | + REQUIRE_DESTRUCTURING: new RegExp( |
| 13 | + '(?:const|let|var)\\s*\\{([^}]+)\\}\\s*=\\s*' + |
| 14 | + 'require\\(\\s*[\'"]([^\'"]+)[\'"]\\s*\\);?', |
| 15 | + 'g', |
| 16 | + ), |
| 17 | + REQUIRE_ASSIGNMENT: new RegExp( |
| 18 | + '(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*' + |
| 19 | + 'require\\(\\s*[\'"]([^\'"]+)[\'"]\\s*\\);?', |
| 20 | + 'g', |
| 21 | + ), |
| 22 | + REQUIRE_SIDE_EFFECT: /^require\(\s*['"]([^'"]+)['"]\s*\);?\s*$/gm, |
| 23 | + IMPORT_DESTRUCTURING: new RegExp( |
| 24 | + 'import\\s*\\{([^}]+)\\}\\s*from\\s*[\'"]([^\'"]+)[\'"];?', |
| 25 | + 'g', |
| 26 | + ), |
| 27 | + IMPORT_ASSIGNMENT: new RegExp( |
| 28 | + 'import\\s+([A-Za-z_$][\\w$]*)\\s*from\\s*[\'"]([^\'"]+)[\'"];?', |
| 29 | + 'g', |
| 30 | + ), |
| 31 | +}; |
| 32 | + |
| 33 | +const parseDestructuringBindings = (bindings) => { |
| 34 | + const parts = bindings |
| 35 | + .split(',') |
| 36 | + .map((p) => p.trim()) |
| 37 | + .map((part) => { |
| 38 | + const localName = part.split('=')[0].trim(); |
| 39 | + if (localName === '') return part; |
| 40 | + |
| 41 | + const colonIndex = localName.indexOf(':'); |
| 42 | + if (colonIndex !== -1) { |
| 43 | + return localName.slice(0, colonIndex).trim(); |
| 44 | + } |
| 45 | + |
| 46 | + if (localName.startsWith('...')) return ''; |
| 47 | + |
| 48 | + return localName; |
| 49 | + }) |
| 50 | + .filter(Boolean); |
| 51 | + |
| 52 | + return parts; |
| 53 | +}; |
| 54 | + |
| 55 | +const ensureImportEntry = (importRegistry, specifier) => { |
| 56 | + let entry = importRegistry.get(specifier); |
| 57 | + if (!entry) { |
| 58 | + entry = { |
| 59 | + defaultNames: new Set(), |
| 60 | + named: new Set(), |
| 61 | + sideEffect: false, |
| 62 | + }; |
| 63 | + importRegistry.set(specifier, entry); |
| 64 | + } |
| 65 | + return entry; |
| 66 | +}; |
| 67 | + |
| 68 | +const addDefaultImport = (importRegistry, specifier, localName) => { |
| 69 | + const entry = ensureImportEntry(importRegistry, specifier); |
| 70 | + entry.defaultNames.add(localName); |
| 71 | +}; |
| 72 | + |
| 73 | +const addNamedImport = (importRegistry, specifier, localName) => { |
| 74 | + const entry = ensureImportEntry(importRegistry, specifier); |
| 75 | + entry.named.add(localName); |
| 76 | +}; |
| 77 | + |
| 78 | +const addSideEffectImport = (importRegistry, specifier) => { |
| 79 | + const entry = ensureImportEntry(importRegistry, specifier); |
| 80 | + entry.sideEffect = true; |
| 81 | +}; |
| 82 | + |
| 83 | +const isRelativePath = (specifier) => |
| 84 | + specifier.startsWith('./') || |
| 85 | + specifier.startsWith('../') || |
| 86 | + specifier.startsWith('../../'); |
| 87 | + |
| 88 | +const validateSpecifier = (specifier, filename, lineNumber, line) => { |
| 89 | + if (specifier.startsWith('node:')) { |
| 90 | + const msg = |
| 91 | + `Node built-in require is not allowed in bundle sources: ` + |
| 92 | + `${filename}:${lineNumber}: ${line.trim()}`; |
| 93 | + console.error(msg); |
| 94 | + return { valid: false, shouldKeep: false, isExternal: false }; |
| 95 | + } |
| 96 | + |
| 97 | + if (isRelativePath(specifier)) { |
| 98 | + return { valid: true, shouldKeep: false, isExternal: false }; |
| 99 | + } |
| 100 | + |
| 101 | + if (NODE_BUILTINS.has(specifier)) { |
| 102 | + const msg = |
| 103 | + `Node built-in module imported from bundle source: ` + |
| 104 | + `${filename}:${lineNumber}: ${specifier}`; |
| 105 | + console.warn(msg); |
| 106 | + return { valid: true, shouldKeep: false, isExternal: false }; |
| 107 | + } |
| 108 | + |
| 109 | + return { valid: true, shouldKeep: false, isExternal: true }; |
| 110 | +}; |
| 111 | + |
| 112 | +const processMatch = (patternName, match, filename, importRegistry) => { |
| 113 | + let specifier, bindings, localName; |
| 114 | + |
| 115 | + switch (patternName) { |
| 116 | + case 'REQUIRE_DESTRUCTURING': |
| 117 | + case 'IMPORT_DESTRUCTURING': |
| 118 | + bindings = match[1]; |
| 119 | + specifier = match[2]; |
| 120 | + break; |
| 121 | + case 'REQUIRE_ASSIGNMENT': |
| 122 | + case 'IMPORT_ASSIGNMENT': |
| 123 | + localName = match[1]; |
| 124 | + specifier = match[2]; |
| 125 | + break; |
| 126 | + case 'REQUIRE_SIDE_EFFECT': |
| 127 | + specifier = match[1]; |
| 128 | + break; |
| 129 | + } |
| 130 | + |
| 131 | + const validation = validateSpecifier(specifier, filename, 0, match[0]); |
| 132 | + if (!validation.valid) return; |
| 133 | + |
| 134 | + if (isRelativePath(specifier) || !validation.isExternal) return; |
| 135 | + |
| 136 | + if (patternName.includes('DESTRUCTURING')) { |
| 137 | + const parsedBindings = parseDestructuringBindings(bindings); |
| 138 | + for (const name of parsedBindings) { |
| 139 | + addNamedImport(importRegistry, specifier, name); |
| 140 | + } |
| 141 | + } else if (patternName.includes('ASSIGNMENT')) { |
| 142 | + addDefaultImport(importRegistry, specifier, localName); |
| 143 | + } else if (patternName === 'REQUIRE_SIDE_EFFECT') { |
| 144 | + addSideEffectImport(importRegistry, specifier); |
| 145 | + } |
| 146 | +}; |
| 147 | + |
| 148 | +const processImports = (content, filename, importRegistry) => { |
| 149 | + let result = content; |
| 150 | + |
| 151 | + for (const [patternName, pattern] of Object.entries(IMPORT_PATTERNS)) { |
| 152 | + const regex = new RegExp(pattern.source, pattern.flags); |
| 153 | + let match; |
| 154 | + while ((match = regex.exec(content)) !== null) { |
| 155 | + processMatch(patternName, match, filename, importRegistry); |
| 156 | + } |
| 157 | + result = result.replace(pattern, '\n'); |
| 158 | + } |
| 159 | + |
| 160 | + return result; |
| 161 | +}; |
| 162 | + |
| 163 | +const generateImportStatements = (importRegistry) => { |
| 164 | + if (importRegistry.size === 0) return ''; |
| 165 | + const lines = []; |
| 166 | + |
| 167 | + for (const [depName, entry] of importRegistry.entries()) { |
| 168 | + const specifier = `./${depName}.js`; |
| 169 | + if (entry.sideEffect) lines.push(`import '${specifier}';`); |
| 170 | + |
| 171 | + const namedParts = Array.from(entry.named); |
| 172 | + |
| 173 | + if (entry.defaultNames.size === 0 && namedParts.length === 0) continue; |
| 174 | + |
| 175 | + if (entry.defaultNames.size <= 1) { |
| 176 | + const defaultName = |
| 177 | + entry.defaultNames.size === 1 ? [...entry.defaultNames][0] : null; |
| 178 | + if (defaultName && namedParts.length > 0) { |
| 179 | + const stmt = |
| 180 | + `import ${defaultName}, { ${namedParts.join(', ')} } ` + |
| 181 | + `from '${specifier}';`; |
| 182 | + lines.push(stmt); |
| 183 | + } else if (defaultName) { |
| 184 | + lines.push(`import ${defaultName} from '${specifier}';`); |
| 185 | + } else { |
| 186 | + lines.push(`import { ${namedParts.join(', ')} } from '${specifier}';`); |
| 187 | + } |
| 188 | + continue; |
| 189 | + } |
| 190 | + |
| 191 | + for (const defaultName of entry.defaultNames) { |
| 192 | + lines.push(`import ${defaultName} from '${specifier}';`); |
| 193 | + } |
| 194 | + if (namedParts.length > 0) { |
| 195 | + lines.push(`import { ${namedParts.join(', ')} } from '${specifier}';`); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + return lines.join('\n') + '\n\n'; |
| 200 | +}; |
| 201 | + |
| 202 | +module.exports = { |
| 203 | + processImports, |
| 204 | + generateImportStatements, |
| 205 | +}; |
0 commit comments