|
| 1 | +import fs from 'node:fs' |
| 2 | + |
| 3 | +const CWD = new URL('../', import.meta.url) |
| 4 | + |
| 5 | +// list of all inputs/outputs, with replacements |
| 6 | +const SOURCE_FILES = [ |
| 7 | + { |
| 8 | + source: './index.js', |
| 9 | + types: './types/index.d.ts', |
| 10 | + replacements: [ |
| 11 | + [/const\s+([^=]+)=\s*require\(([^)]+)\)/g, (_, spec, moduleName) => { |
| 12 | + return `import ${spec.trim().replace(/:\s*/g, ' as ')} from ${moduleName.trim()}` |
| 13 | + }], |
| 14 | + [/module\.exports\s*=\s*({[^}]+})/, 'export $1'], |
| 15 | + ] |
| 16 | + } |
| 17 | +] |
| 18 | + |
| 19 | +// Build script |
| 20 | +for (const { source, types, replacements } of SOURCE_FILES) { |
| 21 | + // replace |
| 22 | + let output = fs.readFileSync(new URL(source, CWD), 'utf8') |
| 23 | + for (const [search, replaceValue] of replacements) { |
| 24 | + output = output.replace(search, replaceValue) |
| 25 | + } |
| 26 | + |
| 27 | + // verify |
| 28 | + if (output.includes('require(')) { |
| 29 | + throw new Error('Could not convert all require() statements') |
| 30 | + } |
| 31 | + if (output.includes('module.exports')) { |
| 32 | + throw new Error('Could not convert module.exports statement') |
| 33 | + } |
| 34 | + |
| 35 | + // write source |
| 36 | + fs.writeFileSync(new URL(source.replace(/\.js$/, '.mjs'), CWD), output) |
| 37 | + |
| 38 | + // write types |
| 39 | + fs.copyFileSync(new URL(types, CWD), new URL(types.replace(/\.d\.ts$/, '.d.mts'), CWD)) |
| 40 | +} |
0 commit comments