-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolkadot-dev-build-ts.cjs
executable file
·290 lines (233 loc) · 8.44 KB
/
polkadot-dev-build-ts.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env node
// Copyright 2017-2021 @polkadot/dev authors & contributors
// SPDX-License-Identifier: Apache-2.0
const babel = require('@babel/cli/lib/babel/dir').default;
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');
const { EXT_CJS, EXT_ESM } = require('../config/babel-extensions.cjs');
const copySync = require('./copySync.cjs');
const execSync = require('./execSync.cjs');
const BL_CONFIGS = ['babel.config.js', 'babel.config.cjs'];
const WP_CONFIGS = ['webpack.config.js', 'webpack.config.cjs'];
const CPX = ['js', 'cjs', 'mjs', 'json', 'd.ts', 'css', 'gif', 'hbs', 'jpg', 'png', 'svg']
.map((ext) => `src/**/*.${ext}`)
.concat(['package.json', 'README.md']);
console.log('$ polkadot-dev-build-ts', process.argv.slice(2).join(' '));
const isTypeModule = EXT_ESM === '.js';
const EXT_OTHER = isTypeModule ? EXT_CJS : EXT_ESM;
// webpack build
function buildWebpack () {
const config = WP_CONFIGS.find((c) => fs.existsSync(path.join(process.cwd(), c)));
execSync(`yarn polkadot-exec-webpack --config ${config} --mode production`);
}
// compile via babel, either via supplied config or default
async function buildBabel (dir, type) {
const configs = BL_CONFIGS.map((c) => path.join(process.cwd(), `../../${c}`));
const outDir = path.join(process.cwd(), 'build');
await babel({
babelOptions: {
configFile: type === 'esm'
? path.join(__dirname, '../config/babel-config-esm.cjs')
: configs.find((f) => fs.existsSync(f)) || path.join(__dirname, '../config/babel-config-cjs.cjs')
},
cliOptions: {
extensions: ['.ts', '.tsx'],
filenames: ['src'],
ignore: '**/*.d.ts',
outDir,
outFileExtension: type === 'esm' ? EXT_ESM : EXT_CJS
}
});
// rewrite a skeleton package.json with a type=module
if (type !== 'esm') {
[...CPX]
.concat(`../../build/${dir}/src/**/*.d.ts`, `../../build/packages/${dir}/src/**/*.d.ts`)
.forEach((src) => copySync(src, 'build'));
}
}
function relativePath (value) {
return `${value.startsWith('.') ? value : './'}${value}`.replace(/\/\//g, '/');
}
// creates an entry for the cjs/esm name
function createMapEntry (rootDir, jsPath) {
jsPath = relativePath(jsPath);
const otherPath = jsPath.replace('.js', EXT_OTHER);
const otherReq = isTypeModule ? 'require' : 'import';
const field = otherPath !== jsPath && fs.existsSync(path.join(rootDir, otherPath))
? {
[otherReq]: otherPath,
// eslint-disable-next-line sort-keys
default: jsPath
}
: jsPath;
if (jsPath.endsWith('.js')) {
if (jsPath.endsWith('/index.js')) {
return [jsPath.replace('/index.js', ''), field];
} else {
return [jsPath.replace('.js', ''), field];
}
}
return [jsPath, field];
}
// find the names of all the files in a certain directory
function findFiles (buildDir, extra = '') {
const currDir = extra ? path.join(buildDir, extra) : buildDir;
return fs
.readdirSync(currDir)
.reduce((all, jsName) => {
const jsPath = `${extra}/${jsName}`;
const thisPath = path.join(buildDir, jsPath);
const toDelete = jsName.includes('.spec.') || // no tests
jsName.endsWith('.d.js') || // no .d.ts compiled outputs
jsName.endsWith(`.d${EXT_OTHER}`) || // same as above, esm version
(
jsName.endsWith('.d.ts') && // .d.ts without .js as an output
!fs.existsSync(path.join(buildDir, jsPath.replace('.d.ts', '.js')))
);
if (toDelete) {
fs.unlinkSync(thisPath);
} else if (fs.statSync(thisPath).isDirectory()) {
findFiles(buildDir, jsPath).forEach((entry) => all.push(entry));
} else if (!jsName.endsWith(EXT_OTHER) || !fs.existsSync(path.join(buildDir, jsPath.replace(EXT_OTHER, '.js')))) {
// this is not mapped to a compiled .js file (where we have dual esm/cjs mappings)
all.push(createMapEntry(buildDir, jsPath));
}
return all;
}, []);
}
// iterate through all the files that have been built, creating an exports map
function buildExports () {
const buildDir = path.join(process.cwd(), 'build');
const pkgPath = path.join(buildDir, 'package.json');
const pkg = require(pkgPath);
const list = findFiles(buildDir);
if (!list.some(([key]) => key === '.')) {
// for the env-specifics, add a root key (if not available)
list.push(['.', {
browser: createMapEntry(buildDir, pkg.browser)[1],
node: createMapEntry(buildDir, pkg.main)[1],
'react-native': createMapEntry(buildDir, pkg['react-native'])[1]
}]);
const indexDef = relativePath(pkg.main).replace('.js', '.d.ts');
const indexKey = './index.d.ts';
// additionally, add an index key, if not available
if (!list.some(([key]) => key === indexKey)) {
list.push([indexKey, indexDef]);
}
}
pkg.exports = list
.sort((a, b) => a[0].localeCompare(b[0]))
.reduce((all, [path, config]) => ({
...all,
[path]: typeof config === 'string'
? config
: {
...((pkg.exports && pkg.exports[path]) || {}),
...config
}
}), {});
pkg.type = isTypeModule
? 'module'
: 'commonjs';
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
}
function sortJson (json) {
return Object
.entries(json)
.sort(([a], [b]) => a.localeCompare(b))
.reduce((all, [k, v]) => ({ ...all, [k]: v }), {});
}
function orderPackageJson (repoPath, dir, json) {
json.bugs = `https://github.com/${repoPath}/issues`;
json.homepage = `https://github.com/${repoPath}${dir ? `/tree/master/packages/${dir}` : ''}#readme`;
json.license = json.license || 'Apache-2';
json.repository = {
...(dir
? { directory: `packages/${dir}` }
: {}
),
type: 'git',
url: `https://github.com/${repoPath}.git`
};
json.sideEffects = json.sideEffects || false;
// sort the object
const sorted = sortJson(json);
// remove empty artifacts
['engines'].forEach((d) => {
if (typeof json[d] === 'object' && Object.keys(json[d]).length === 0) {
delete sorted[d];
}
});
// move the different entry points to the (almost) end
['browser', 'electron', 'main', 'react-native'].forEach((d) => {
delete sorted[d];
if (json[d]) {
sorted[d] = json[d];
}
});
// move bin, scripts & dependencies to the end
[
['bin', 'scripts'],
['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'resolutions']
].forEach((a) =>
a.forEach((d) => {
delete sorted[d];
if (json[d] && Object.keys(json[d]).length) {
sorted[d] = sortJson(json[d]);
}
})
);
fs.writeFileSync(path.join(process.cwd(), 'package.json'), `${JSON.stringify(sorted, null, 2)}\n`);
}
async function buildJs (repoPath, dir) {
const json = require(path.join(process.cwd(), './package.json'));
const { name, version } = json;
console.log(`*** ${name} ${version}`);
orderPackageJson(repoPath, dir, json);
if (!fs.existsSync(path.join(process.cwd(), '.skip-build'))) {
mkdirp.sync('build');
fs.writeFileSync(path.join(process.cwd(), 'src/packageInfo.ts'), `// Copyright 2017-2021 ${name} authors & contributors
// SPDX-License-Identifier: Apache-2.0
// Auto-generated by @polkadot/dev, do not edit
export const packageInfo = { name: '${name}', version: '${version}' };
`);
if (fs.existsSync(path.join(process.cwd(), 'public'))) {
buildWebpack();
} else {
await buildBabel(dir, 'cjs');
await buildBabel(dir, 'esm');
buildExports();
}
console.log();
}
}
async function main () {
execSync('yarn polkadot-dev-clean-build');
const pkg = require(path.join(process.cwd(), 'package.json'));
if (pkg.scripts && pkg.scripts['build:extra']) {
execSync('yarn build:extra');
}
const repoPath = pkg.repository.url
.split('https://github.com/')[1]
.split('.git')[0];
orderPackageJson(repoPath, null, pkg);
process.chdir('packages');
execSync('yarn polkadot-exec-tsc --emitDeclarationOnly --outdir ../build');
const dirs = fs
.readdirSync('.')
.filter((dir) => fs.statSync(dir).isDirectory() && fs.existsSync(path.join(process.cwd(), dir, 'src')));
for (const dir of dirs) {
process.chdir(dir);
await buildJs(repoPath, dir);
process.chdir('..');
}
process.chdir('..');
if (['js', 'mjs', 'cjs'].some((e) => fs.existsSync(path.join(process.cwd(), `rollup.config.${e}`)))) {
execSync('yarn polkadot-exec-rollup --config');
}
}
main().catch((error) => {
console.error(error);
process.exit(-1);
});