-
Notifications
You must be signed in to change notification settings - Fork 269
/
esbuild.js
311 lines (290 loc) · 8.6 KB
/
esbuild.js
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
const { build } = require('esbuild');
const yargs = require('yargs');
const chokidar = require('chokidar');
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const crypto = require('crypto');
const argv = yargs(process.argv.slice(2))
.command('build', 'Builds the project files')
.options({
platform: {
type: 'string',
default: 'browser',
describe: 'The platform to build for.',
choices: ['browser'],
},
watch: {
type: 'boolean',
default: false,
describe: 'Should watch the files and rebuild on change?',
},
})
.help()
.alias('help', 'h').argv;
// Attached to all script URLs to force browsers to download the
// resources again.
const CACHE_BUSTER = Math.random().toFixed(16).slice(2);
// Provided by esbuild – see build.js in the repo root.
const serviceWorkerOrigin =
process.env.SERVICE_WORKER_ORIGIN || 'http://127.0.0.1:8777';
const serviceWorkerUrl = `${serviceWorkerOrigin}/service-worker.js`;
const wasmWorkerBackend = process.env.WASM_WORKER_BACKEND || 'iframe';
let workerThreadScript;
if (wasmWorkerBackend === 'iframe') {
const wasmWorkerOrigin =
process.env.WASM_WORKER_ORIGIN || 'http://127.0.0.1:8778';
workerThreadScript = `${wasmWorkerOrigin}/iframe-worker.html?${CACHE_BUSTER}`;
} else {
workerThreadScript = `${serviceWorkerOrigin}/worker-thread.js?${CACHE_BUSTER}`;
}
const globalOutDir = 'build';
async function main() {
const baseConfig = {
logLevel: 'info',
platform: argv.platform,
outdir: globalOutDir,
watch: argv.watch,
target: ['chrome106', 'firefox100', 'safari15'],
bundle: true,
nodePaths: ['packages', 'src/wordpress-plugin-ide/bundler/polyfills'],
loader: {
'.php': 'text',
'.txt.js': 'text',
'.js': 'jsx',
},
treeShaking: true,
minify: true,
};
// This build step exists solely to compute the hash of service-worker.js.
//
// The browsers tend to cling to the service worker script even when the
// code itself changes. Computing the script hash allows us to compare
// the expected and registered service worker versions and force the
// invalidation.
build({
...baseConfig,
minify: false,
entryPoints: {
'service-worker': 'src/wordpress-playground/service-worker.ts',
},
entryNames: 'sw-mock-to-get-hash.[hash]',
plugins: [
// Delete the outdated "hashful" service worker builds.
cleanup({ pattern: 'sw-mock-to-get-hash.*.js' }),
{
name: 'import-json-file',
setup(currentBuild) {
currentBuild.initialOptions.metafile = true;
// Whenever the build is finished, write the hash to
// "service-worker-version.ts" where it can be imported by
// both the frontend script and the service worker.
currentBuild.onEnd((result) => {
const filename = Object.keys(
result.metafile.outputs
)[0];
const hash = filename.split('.')[1];
fs.writeFileSync(
'src/wordpress-playground/service-worker-version.ts',
`/* Automatically refreshed by esbuild.js */ ` +
`export default ${JSON.stringify(hash)}; \n`
);
});
// Instead of importing the actual service worker version, provide
// an empty string to avoid an infinite loop of building the service
// worker, refreshing the hash, building a new service worker with the
// updated hash, refreshing the hash again, etc.
currentBuild.onLoad(
{
filter: /.*/,
namespace: 'service-worker-version',
},
() => ({
contents: `export default ""`,
loader: 'ts',
})
);
// Make sure the "service-worker-version" import will be handled by
// the onLoad call above.
currentBuild.onResolve(
{ filter: /service-worker-version$/ },
(args) => ({
path: args.path,
namespace: 'service-worker-version',
})
);
},
},
],
});
build({
...baseConfig,
entryPoints: {
'service-worker': 'src/wordpress-playground/service-worker.ts',
'setup-fast-refresh-runtime':
'src/wordpress-plugin-ide/bundler/react-fast-refresh/setup-react-refresh-runtime.js',
},
});
build({
...baseConfig,
define: {
CACHE_BUSTER: JSON.stringify(CACHE_BUSTER),
'process.env.BUILD_PLATFORM': JSON.stringify(argv.platform),
'process.env.NODE_ENV': JSON.stringify('development'),
SERVICE_WORKER_URL: JSON.stringify(serviceWorkerUrl),
WASM_WORKER_THREAD_SCRIPT_URL: JSON.stringify(workerThreadScript),
WASM_WORKER_BACKEND: JSON.stringify(wasmWorkerBackend),
WP_JS_HASH: JSON.stringify(hashFiles([`build/wp.js`])),
PHP_JS_HASH: JSON.stringify(hashFiles(glob.sync('build/php-*.js'))),
},
entryPoints: {
'worker-thread': 'src/wordpress-playground/worker-thread.ts',
app: 'src/wordpress-playground/index.tsx',
'wordpress-plugin-ide': 'src/wordpress-plugin-ide/index.ts',
react: 'react',
'react-dom': 'react-dom',
},
splitting: true,
sourcemap: true,
format: 'esm',
metafile: true,
plugins: [cleanup({ pattern: 'chunk-*' })],
});
build({
logLevel: 'info',
platform: 'node',
outdir: './build-scripts/',
bundle: true,
external: ['@microsoft/*', 'node_modules/*'],
entryPoints: [
'./src/typescript-reference-doc-generator/bin/tsdoc-to-api-markdown.js',
],
sourcemap: true,
watch: argv.watch,
});
console.log('');
console.log('Static files copied: ');
mapGlob(`src/*/*.html`, buildHTMLFile);
mapGlob(`src/wordpress-playground/bundling/test/*.html`, buildHTMLFile);
mapGlob(`node_modules/react/umd/react.development.js`, copyToDist);
mapGlob(`node_modules/react-dom/umd/react-dom.development.js`, copyToDist);
mapGlob(`src/*/*.php`, copyToDist);
if (argv.watch) {
const liveServer = require('live-server');
const request = require('request');
liveServer.start({
port: 8777,
root: __dirname + '/build',
open: '/wordpress.html',
middleware: [
(req, res, next) => {
if (req.url.endsWith('iframe-worker.html')) {
res.setHeader('Origin-Agent-Cluster', '?1');
} else if (req.url.startsWith('/plugin-proxy')) {
const url = new URL(req.url, 'http://127.0.0.1:8777');
if (url.searchParams.has('plugin')) {
const pluginName = url.searchParams
.get('plugin')
.replace(/[^a-zA-Z0-9\.\-_]/, '');
request(
`https://downloads.wordpress.org/plugin/${pluginName}`
).pipe(res);
} else if (url.searchParams.has('theme')) {
const themeName = url.searchParams
.get('theme')
.replace(/[^a-zA-Z0-9\.\-_]/, '');
request(
`https://downloads.wordpress.org/theme/${themeName}`
).pipe(res);
} else {
res.end('Invalid request');
}
return;
}
next();
},
],
});
// Serve the iframe worker from a different origin
// to make the Origin-Agent-Cluster header work.
// See https://web.dev/origin-agent-cluster/ for more info.
liveServer.start({
port: 8778,
root: __dirname + '/build',
open: false,
});
}
}
if (require.main === module) {
main();
}
exports.main = main;
function mapGlob(pattern, mapper) {
glob.sync(pattern).map(mapper).forEach(logBuiltFile);
if (argv.watch) {
chokidar.watch(pattern).on('change', mapper);
}
}
function copyToDist(filePath) {
outdir = globalOutDir;
const filename = filePath.split('/').pop();
const outPath = `${outdir}/${filename}`;
fs.copyFileSync(filePath, outPath);
return outPath;
}
function buildHTMLFile(filePath) {
const outdir = globalOutDir;
let content = fs.readFileSync(filePath).toString();
content = content.replace(
/(<script[^>]+src=")([^"]+)("><\/script>)/,
`$1$2?${CACHE_BUSTER}$3`
);
const filename = filePath.split('/').pop();
const outPath = `${outdir}/${filename}`;
fs.writeFileSync(outPath, content);
return outPath;
}
function logBuiltFile(outPath) {
const outPathToLog = outPath.replace(/^\.\//, '');
console.log(` ${outPathToLog}`);
}
function fileSize(filePath) {
if (!fs.existsSync(filePath)) {
return 0;
}
return fs.statSync(filePath).size;
}
function hashFiles(filePaths) {
// if all files exist
if (!filePaths.every(fs.existsSync)) {
return '';
}
return sha256(
Buffer.concat(filePaths.map((filePath) => fs.readFileSync(filePath)))
);
}
function sha256(buffer) {
const hash = crypto.createHash('sha256');
hash.update(buffer);
return hash.digest('hex');
}
function cleanup({ pattern = '*' }) {
return {
name: 'cleanupFiles',
setup(build) {
const options = build.initialOptions;
build.onEnd((result) => {
if (!result.metafile) {
return;
}
const safelist = new Set(Object.keys(result.metafile.outputs));
const files = glob.sync(path.join(options.outdir, pattern));
files.forEach((path) => {
if (!safelist.has(path)) {
fs.unlinkSync(path);
}
});
});
},
};
}