1 |
|
2 | const fs = require('fs')
|
3 | const path = require('path')
|
4 | const chalk = require('chalk')
|
5 | const { parse } = require('@babel/parser')
|
6 | const MagicString = require('magic-string').default
|
7 | const tempDir = path.resolve(__dirname, '../temp/node')
|
8 | const typesDir = path.resolve(__dirname, '../types')
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | walkDir(tempDir)
|
14 | console.log(chalk.green.bold(`patched types/* imports`))
|
15 |
|
16 | function slash(p) {
|
17 | return p.replace(/\\/g, '/')
|
18 | }
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | function walkDir(dir) {
|
24 | const files = fs.readdirSync(dir)
|
25 | for (const file of files) {
|
26 | const resolved = path.resolve(dir, file)
|
27 | const isDir = fs.statSync(resolved).isDirectory()
|
28 | if (isDir) {
|
29 | walkDir(resolved)
|
30 | } else {
|
31 | rewriteFile(resolved)
|
32 | }
|
33 | }
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | function rewriteFile(file) {
|
40 | const content = fs.readFileSync(file, 'utf-8')
|
41 | const str = new MagicString(content)
|
42 | let ast
|
43 | try {
|
44 | ast = parse(content, {
|
45 | sourceType: 'module',
|
46 | plugins: ['typescript', 'classProperties']
|
47 | })
|
48 | } catch (e) {
|
49 | console.log(chalk.red(`failed to parse ${file}`))
|
50 | throw e
|
51 | }
|
52 | for (const statement of ast.program.body) {
|
53 | if (
|
54 | (statement.type === 'ImportDeclaration' ||
|
55 | statement.type === 'ExportNamedDeclaration' ||
|
56 | statement.type === 'ExportAllDeclaration') &&
|
57 | statement.source &&
|
58 | statement.source.value.startsWith('types/')
|
59 | ) {
|
60 | const source = statement.source
|
61 | const absoluteTypePath = path.resolve(typesDir, source.value.slice(6))
|
62 | const relativeTypePath = slash(
|
63 | path.relative(path.dirname(file), absoluteTypePath)
|
64 | )
|
65 |
|
66 | str.overwrite(source.start, source.end, JSON.stringify(relativeTypePath))
|
67 | }
|
68 | }
|
69 | fs.writeFileSync(file, str.toString())
|
70 | }
|