html-bundle 6.2.3 → 6.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/dependabot.yml +7 -7
- package/LICENSE +21 -21
- package/README.md +198 -198
- package/dist/bundle.mjs +386 -386
- package/dist/utils.mjs +176 -119
- package/package.json +60 -56
- package/src/bundle.mts +478 -478
- package/src/index.d.ts +3 -3
- package/src/utils.mts +339 -279
- package/tests/bundle.test.mjs +226 -0
- package/tsconfig.json +15 -15
- package/types/static.d.ts +1 -1
package/dist/bundle.mjs
CHANGED
|
@@ -1,386 +1,386 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { performance } from "perf_hooks";
|
|
3
|
-
import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
|
|
4
|
-
import { execFile } from "child_process";
|
|
5
|
-
import { promisify } from "util";
|
|
6
|
-
import { sep } from "path";
|
|
7
|
-
import { glob } from "glob";
|
|
8
|
-
import postcss from "postcss";
|
|
9
|
-
import esbuild from "esbuild";
|
|
10
|
-
import Beasties from "beasties";
|
|
11
|
-
import { minify } from "html-minifier-terser";
|
|
12
|
-
import { watch } from "chokidar";
|
|
13
|
-
import { serialize, parse, parseFragment } from "parse5";
|
|
14
|
-
import { getTagName, findElements } from "@web/parse5-utils";
|
|
15
|
-
import awaitSpawn from "await-spawn";
|
|
16
|
-
import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
|
|
17
|
-
const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
|
|
18
|
-
const isCritical = process.argv.includes("--isCritical") || bundleConfig.isCritical;
|
|
19
|
-
const beasties = new Beasties({
|
|
20
|
-
path: bundleConfig.build,
|
|
21
|
-
logLevel: "silent",
|
|
22
|
-
...bundleConfig.critical,
|
|
23
|
-
});
|
|
24
|
-
const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
|
|
25
|
-
const handlerFile = process.argv.includes("--handler")
|
|
26
|
-
? process.argv[process.argv.indexOf("--handler") + 1]
|
|
27
|
-
: bundleConfig.handler;
|
|
28
|
-
process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
|
|
29
|
-
let timer = performance.now();
|
|
30
|
-
let { plugins, options, file: postcssFile } = await getPostCSSConfig();
|
|
31
|
-
let CSSprocessor = postcss(plugins);
|
|
32
|
-
let router;
|
|
33
|
-
const inlineFiles = new Set();
|
|
34
|
-
const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
|
|
35
|
-
const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
|
|
36
|
-
const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
|
|
37
|
-
const execFilePromise = promisify(execFile);
|
|
38
|
-
if (bundleConfig.deletePrev) {
|
|
39
|
-
await rm(bundleConfig.build, { force: true, recursive: true });
|
|
40
|
-
}
|
|
41
|
-
async function cleanupStaleInlineBundleFiles() {
|
|
42
|
-
const staleFiles = await glob(`${bundleConfig.src}/**/*-bundle-*.tsx`);
|
|
43
|
-
await Promise.all(staleFiles.map((file) => rm(file.replaceAll(sep, "/"), { force: true })));
|
|
44
|
-
}
|
|
45
|
-
async function build(files, firstRun = true) {
|
|
46
|
-
for (const file of files) {
|
|
47
|
-
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
await createDir(file);
|
|
51
|
-
if (!SUPPORTED_FILES.test(file)) {
|
|
52
|
-
if (handlerFile) {
|
|
53
|
-
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
54
|
-
console.log("📋 Logging Handler: ", String(stdout));
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
else {
|
|
58
|
-
if ((await lstat(file)).isDirectory())
|
|
59
|
-
continue;
|
|
60
|
-
await fileCopy(file);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
else {
|
|
64
|
-
if (file.endsWith(".html")) {
|
|
65
|
-
await writeInlineScripts(file);
|
|
66
|
-
}
|
|
67
|
-
else if (file.endsWith(".css")) {
|
|
68
|
-
await minifyCSS(file, getBuildPath(file));
|
|
69
|
-
}
|
|
70
|
-
else {
|
|
71
|
-
inlineFiles.add(file);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
await minifyCode();
|
|
76
|
-
for (const file of inlineFiles) {
|
|
77
|
-
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
78
|
-
inlineFiles.delete(file);
|
|
79
|
-
await rm(file);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
for (const file of files) {
|
|
83
|
-
if (file.endsWith(".html")) {
|
|
84
|
-
await minifyHTML(file, getBuildPath(file));
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
|
|
88
|
-
if (isHMR && firstRun) {
|
|
89
|
-
const [dynamicRouter, server] = await createDefaultServer(isSecure);
|
|
90
|
-
router = dynamicRouter;
|
|
91
|
-
server.listen({ port: bundleConfig.port, host: bundleConfig.host });
|
|
92
|
-
console.log(`💻 Server listening on http${isSecure ? "s" : ""}://${bundleConfig.host === "::" ? "localhost" : bundleConfig.host}:${bundleConfig.port} and is shared in the local network.`);
|
|
93
|
-
console.log(`⌛ Waiting for file changes ...`);
|
|
94
|
-
const chokidarOptions = { awaitWriteFinish: false };
|
|
95
|
-
if (postcssFile) {
|
|
96
|
-
const postCSSWatcher = watch(postcssFile, chokidarOptions);
|
|
97
|
-
const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind"), chokidarOptions); // Assuming that the file ext is the same
|
|
98
|
-
const tsConfigWatcher = watch(postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json", chokidarOptions);
|
|
99
|
-
const cssFiles = files.filter((file) => file.endsWith(".css"));
|
|
100
|
-
postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
|
|
101
|
-
tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
|
|
102
|
-
tsConfigWatcher.on("change", async () => {
|
|
103
|
-
timer = performance.now();
|
|
104
|
-
await build(files, false);
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
const watcher = watch(bundleConfig.src, chokidarOptions);
|
|
108
|
-
watcher.on("add", async (file) => {
|
|
109
|
-
file = String.raw `${file}`.replace(/\\/g, "/"); // glob and chokidar diff
|
|
110
|
-
if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
try {
|
|
114
|
-
await rebuild(file);
|
|
115
|
-
}
|
|
116
|
-
catch { }
|
|
117
|
-
console.log(`⚡ added ${file} to the build`);
|
|
118
|
-
});
|
|
119
|
-
watcher.on("change", async (file) => {
|
|
120
|
-
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
124
|
-
await rebuild(file);
|
|
125
|
-
console.log(`⚡ modified ${file} on the build`);
|
|
126
|
-
});
|
|
127
|
-
watcher.on("unlink", async (file) => {
|
|
128
|
-
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
132
|
-
inlineFiles.delete(file);
|
|
133
|
-
const buildFile = getBuildPath(file)
|
|
134
|
-
.replace(".ts", ".js")
|
|
135
|
-
.replace(".jsx", ".js");
|
|
136
|
-
try {
|
|
137
|
-
await rm(buildFile);
|
|
138
|
-
const bfDir = buildFile.split("/").slice(0, -1).join("/");
|
|
139
|
-
const stats = await readdir(bfDir);
|
|
140
|
-
if (!stats.length)
|
|
141
|
-
await rm(bfDir);
|
|
142
|
-
}
|
|
143
|
-
catch { }
|
|
144
|
-
console.log(`⚡ deleted ${file} from the build`);
|
|
145
|
-
});
|
|
146
|
-
async function rebuild(file) {
|
|
147
|
-
// Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
|
|
148
|
-
await rebuildCSS(files.filter((file) => file.endsWith(".css")));
|
|
149
|
-
let html;
|
|
150
|
-
if (file.endsWith(".html")) {
|
|
151
|
-
// To refill the inlineFiles needed to build JS
|
|
152
|
-
for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
|
|
153
|
-
await writeInlineScripts(htmlFile);
|
|
154
|
-
}
|
|
155
|
-
await minifyCode();
|
|
156
|
-
for (const file of inlineFiles) {
|
|
157
|
-
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
158
|
-
inlineFiles.delete(file);
|
|
159
|
-
await rm(file);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
html = await minifyHTML(file, getBuildPath(file));
|
|
163
|
-
}
|
|
164
|
-
else if (/\.(jsx?|tsx?)$/.test(file)) {
|
|
165
|
-
inlineFiles.add(file);
|
|
166
|
-
await minifyCode();
|
|
167
|
-
}
|
|
168
|
-
else if (!file.endsWith(".css")) {
|
|
169
|
-
if (handlerFile) {
|
|
170
|
-
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
171
|
-
console.log("📋 Logging Handler: ", String(stdout));
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
await fileCopy(file);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
else if (handlerFile) {
|
|
179
|
-
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
180
|
-
console.log("📋 Logging Handler: ", String(stdout));
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
serverSentEvents?.({ file, html });
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
async function minifyCSS(file, buildFile) {
|
|
188
|
-
try {
|
|
189
|
-
const fileText = await readFile(file, { encoding: "utf-8" });
|
|
190
|
-
const result = await CSSprocessor.process(fileText, {
|
|
191
|
-
...options,
|
|
192
|
-
from: file,
|
|
193
|
-
to: buildFile,
|
|
194
|
-
});
|
|
195
|
-
await writeFile(buildFile, result.css);
|
|
196
|
-
}
|
|
197
|
-
catch (err) {
|
|
198
|
-
// @ts-ignore
|
|
199
|
-
console.error(err?.reason);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
async function minifyCode() {
|
|
203
|
-
try {
|
|
204
|
-
return await esbuild.build({
|
|
205
|
-
entryPoints: Array.from(inlineFiles),
|
|
206
|
-
charset: "utf8",
|
|
207
|
-
format: "esm",
|
|
208
|
-
sourcemap: isHMR,
|
|
209
|
-
splitting: true,
|
|
210
|
-
define: {
|
|
211
|
-
"process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
|
|
212
|
-
},
|
|
213
|
-
loader: { ".js": "jsx", ".ts": "tsx" },
|
|
214
|
-
bundle: true,
|
|
215
|
-
minify: true,
|
|
216
|
-
outdir: bundleConfig.build,
|
|
217
|
-
outbase: bundleConfig.src,
|
|
218
|
-
...bundleConfig.esbuild,
|
|
219
|
-
});
|
|
220
|
-
// Stop app from crashing.
|
|
221
|
-
}
|
|
222
|
-
catch (err) {
|
|
223
|
-
if (!isHMR) {
|
|
224
|
-
console.error(err);
|
|
225
|
-
}
|
|
226
|
-
let missingPkg = false;
|
|
227
|
-
if (err?.errors) {
|
|
228
|
-
for (const error of err.errors) {
|
|
229
|
-
if (error.location && error.text?.startsWith("Could not resolve")) {
|
|
230
|
-
missingPkg = true;
|
|
231
|
-
const packageNameRegex = /(?<=").*(?=")/;
|
|
232
|
-
const [pkgName] = error.text.match(packageNameRegex);
|
|
233
|
-
await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
|
|
234
|
-
"install",
|
|
235
|
-
pkgName,
|
|
236
|
-
]);
|
|
237
|
-
console.log(`📦 Package ${pkgName} was installed for you`);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
if (missingPkg) {
|
|
241
|
-
missingPkg = false;
|
|
242
|
-
return minifyCode();
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
const htmlFilesCache = new Map();
|
|
248
|
-
async function writeInlineScripts(file) {
|
|
249
|
-
let fileText = await readFile(file, { encoding: "utf-8" });
|
|
250
|
-
let DOM;
|
|
251
|
-
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
252
|
-
DOM = parse(fileText);
|
|
253
|
-
}
|
|
254
|
-
else {
|
|
255
|
-
DOM = parseFragment(fileText);
|
|
256
|
-
}
|
|
257
|
-
if (isHMR) {
|
|
258
|
-
fileText = addHMRCode(fileText, file, DOM);
|
|
259
|
-
}
|
|
260
|
-
htmlFilesCache.set(file, [fileText, DOM]);
|
|
261
|
-
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
262
|
-
for (let index = 0; index < scripts.length; index++) {
|
|
263
|
-
const script = scripts[index];
|
|
264
|
-
const scriptTextNode = script.childNodes[0];
|
|
265
|
-
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
266
|
-
const type = script.attrs.find((a) => a.name === "type");
|
|
267
|
-
const scriptContent = scriptTextNode?.value;
|
|
268
|
-
if (!scriptContent ||
|
|
269
|
-
isReferencedScript ||
|
|
270
|
-
type?.value === "importmap" ||
|
|
271
|
-
type?.value === "application/ld+json")
|
|
272
|
-
continue;
|
|
273
|
-
const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
|
|
274
|
-
inlineFiles.add(jsFile);
|
|
275
|
-
await writeFile(jsFile, scriptContent);
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
async function minifyHTML(file, buildFile) {
|
|
279
|
-
let fileText, DOM;
|
|
280
|
-
if (htmlFilesCache.has(file)) {
|
|
281
|
-
const cache = htmlFilesCache.get(file);
|
|
282
|
-
fileText = cache[0];
|
|
283
|
-
DOM = cache[1];
|
|
284
|
-
}
|
|
285
|
-
else {
|
|
286
|
-
fileText = await readFile(file, { encoding: "utf-8" });
|
|
287
|
-
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
288
|
-
DOM = parse(fileText);
|
|
289
|
-
}
|
|
290
|
-
else {
|
|
291
|
-
DOM = parseFragment(fileText);
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
// Minify Code
|
|
295
|
-
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
296
|
-
for (let index = 0; index < scripts.length; index++) {
|
|
297
|
-
const script = scripts[index];
|
|
298
|
-
const scriptTextNode = script.childNodes[0];
|
|
299
|
-
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
300
|
-
const type = script.attrs.find((a) => a.name === "type");
|
|
301
|
-
if (!scriptTextNode?.value ||
|
|
302
|
-
isReferencedScript ||
|
|
303
|
-
type?.value === "importmap" ||
|
|
304
|
-
type?.value === "application/ld+json")
|
|
305
|
-
continue;
|
|
306
|
-
// Use bundled file
|
|
307
|
-
const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
|
|
308
|
-
try {
|
|
309
|
-
const scriptContent = await readFile(buildInlineScript, {
|
|
310
|
-
encoding: "utf-8",
|
|
311
|
-
});
|
|
312
|
-
await rm(buildInlineScript);
|
|
313
|
-
scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
|
|
314
|
-
}
|
|
315
|
-
catch { }
|
|
316
|
-
}
|
|
317
|
-
// Minify Inline Style
|
|
318
|
-
const styles = findElements(DOM, (e) => getTagName(e) === "style");
|
|
319
|
-
for (const style of styles) {
|
|
320
|
-
const node = style.childNodes[0];
|
|
321
|
-
const styleContent = node?.value;
|
|
322
|
-
if (!styleContent)
|
|
323
|
-
continue;
|
|
324
|
-
try {
|
|
325
|
-
const { css } = await CSSprocessor.process(styleContent, {
|
|
326
|
-
...options,
|
|
327
|
-
from: undefined,
|
|
328
|
-
});
|
|
329
|
-
node.value = css;
|
|
330
|
-
}
|
|
331
|
-
catch {
|
|
332
|
-
// @ts-ignore
|
|
333
|
-
console.error(err?.reason);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
fileText = serialize(DOM);
|
|
337
|
-
// Minify HTML
|
|
338
|
-
try {
|
|
339
|
-
fileText = await minify(fileText, {
|
|
340
|
-
collapseWhitespace: true,
|
|
341
|
-
removeComments: true,
|
|
342
|
-
...bundleConfig["html-minifier-terser"],
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
catch (e) {
|
|
346
|
-
console.error(e);
|
|
347
|
-
}
|
|
348
|
-
if (isCritical) {
|
|
349
|
-
try {
|
|
350
|
-
const isPartical = !fileText.startsWith("<!DOCTYPE html>");
|
|
351
|
-
fileText = await beasties.process(fileText);
|
|
352
|
-
// fix beasties jsdom
|
|
353
|
-
if (isPartical) {
|
|
354
|
-
fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
catch (err) {
|
|
358
|
-
console.error(err);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
await writeFile(buildFile, fileText);
|
|
362
|
-
return fileText;
|
|
363
|
-
}
|
|
364
|
-
async function rebuildCSS(files, config) {
|
|
365
|
-
const newConfig = await getPostCSSConfig();
|
|
366
|
-
plugins = newConfig.plugins;
|
|
367
|
-
options = newConfig.options;
|
|
368
|
-
CSSprocessor = postcss(plugins);
|
|
369
|
-
for (const file of files) {
|
|
370
|
-
await minifyCSS(file, getBuildPath(file));
|
|
371
|
-
}
|
|
372
|
-
if (config)
|
|
373
|
-
console.log(`⚡ modified ${config}.config`);
|
|
374
|
-
}
|
|
375
|
-
try {
|
|
376
|
-
await cleanupStaleInlineBundleFiles();
|
|
377
|
-
const files = await glob(`${bundleConfig.src}/**/*`);
|
|
378
|
-
await build(files
|
|
379
|
-
.map((file) => file.replaceAll(sep, "/"))
|
|
380
|
-
.filter((file) => !INLINE_BUNDLE_FILE.test(file)));
|
|
381
|
-
}
|
|
382
|
-
catch (err) {
|
|
383
|
-
console.error(err);
|
|
384
|
-
process.exit(1);
|
|
385
|
-
}
|
|
386
|
-
export default router;
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { performance } from "perf_hooks";
|
|
3
|
+
import { readFile, rm, writeFile, readdir, lstat } from "fs/promises";
|
|
4
|
+
import { execFile } from "child_process";
|
|
5
|
+
import { promisify } from "util";
|
|
6
|
+
import { sep } from "path";
|
|
7
|
+
import { glob } from "glob";
|
|
8
|
+
import postcss from "postcss";
|
|
9
|
+
import esbuild from "esbuild";
|
|
10
|
+
import Beasties from "beasties";
|
|
11
|
+
import { minify } from "html-minifier-terser";
|
|
12
|
+
import { watch } from "chokidar";
|
|
13
|
+
import { serialize, parse, parseFragment } from "parse5";
|
|
14
|
+
import { getTagName, findElements } from "@web/parse5-utils";
|
|
15
|
+
import awaitSpawn from "await-spawn";
|
|
16
|
+
import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
|
|
17
|
+
const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
|
|
18
|
+
const isCritical = process.argv.includes("--isCritical") || bundleConfig.isCritical;
|
|
19
|
+
const beasties = new Beasties({
|
|
20
|
+
path: bundleConfig.build,
|
|
21
|
+
logLevel: "silent",
|
|
22
|
+
...bundleConfig.critical,
|
|
23
|
+
});
|
|
24
|
+
const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
|
|
25
|
+
const handlerFile = process.argv.includes("--handler")
|
|
26
|
+
? process.argv[process.argv.indexOf("--handler") + 1]
|
|
27
|
+
: bundleConfig.handler;
|
|
28
|
+
process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
|
|
29
|
+
let timer = performance.now();
|
|
30
|
+
let { plugins, options, file: postcssFile } = await getPostCSSConfig();
|
|
31
|
+
let CSSprocessor = postcss(plugins);
|
|
32
|
+
let router;
|
|
33
|
+
const inlineFiles = new Set();
|
|
34
|
+
const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
|
|
35
|
+
const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
|
|
36
|
+
const SUPPORTED_FILES = /\.(html|css|jsx?|tsx?)$/;
|
|
37
|
+
const execFilePromise = promisify(execFile);
|
|
38
|
+
if (bundleConfig.deletePrev) {
|
|
39
|
+
await rm(bundleConfig.build, { force: true, recursive: true });
|
|
40
|
+
}
|
|
41
|
+
async function cleanupStaleInlineBundleFiles() {
|
|
42
|
+
const staleFiles = await glob(`${bundleConfig.src}/**/*-bundle-*.tsx`);
|
|
43
|
+
await Promise.all(staleFiles.map((file) => rm(file.replaceAll(sep, "/"), { force: true })));
|
|
44
|
+
}
|
|
45
|
+
async function build(files, firstRun = true) {
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
await createDir(file);
|
|
51
|
+
if (!SUPPORTED_FILES.test(file)) {
|
|
52
|
+
if (handlerFile) {
|
|
53
|
+
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
54
|
+
console.log("📋 Logging Handler: ", String(stdout));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
if ((await lstat(file)).isDirectory())
|
|
59
|
+
continue;
|
|
60
|
+
await fileCopy(file);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
if (file.endsWith(".html")) {
|
|
65
|
+
await writeInlineScripts(file);
|
|
66
|
+
}
|
|
67
|
+
else if (file.endsWith(".css")) {
|
|
68
|
+
await minifyCSS(file, getBuildPath(file));
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
inlineFiles.add(file);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
await minifyCode();
|
|
76
|
+
for (const file of inlineFiles) {
|
|
77
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
78
|
+
inlineFiles.delete(file);
|
|
79
|
+
await rm(file);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
for (const file of files) {
|
|
83
|
+
if (file.endsWith(".html")) {
|
|
84
|
+
await minifyHTML(file, getBuildPath(file));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
|
|
88
|
+
if (isHMR && firstRun) {
|
|
89
|
+
const [dynamicRouter, server] = await createDefaultServer(isSecure);
|
|
90
|
+
router = dynamicRouter;
|
|
91
|
+
server.listen({ port: bundleConfig.port, host: bundleConfig.host });
|
|
92
|
+
console.log(`💻 Server listening on http${isSecure ? "s" : ""}://${bundleConfig.host === "::" ? "localhost" : bundleConfig.host}:${bundleConfig.port} and is shared in the local network.`);
|
|
93
|
+
console.log(`⌛ Waiting for file changes ...`);
|
|
94
|
+
const chokidarOptions = { awaitWriteFinish: false };
|
|
95
|
+
if (postcssFile) {
|
|
96
|
+
const postCSSWatcher = watch(postcssFile, chokidarOptions);
|
|
97
|
+
const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind"), chokidarOptions); // Assuming that the file ext is the same
|
|
98
|
+
const tsConfigWatcher = watch(postcssFile.split("\\").slice(0, -1).join("\\") + "\\tsconfig.json", chokidarOptions);
|
|
99
|
+
const cssFiles = files.filter((file) => file.endsWith(".css"));
|
|
100
|
+
postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
|
|
101
|
+
tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
|
|
102
|
+
tsConfigWatcher.on("change", async () => {
|
|
103
|
+
timer = performance.now();
|
|
104
|
+
await build(files, false);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const watcher = watch(bundleConfig.src, chokidarOptions);
|
|
108
|
+
watcher.on("add", async (file) => {
|
|
109
|
+
file = String.raw `${file}`.replace(/\\/g, "/"); // glob and chokidar diff
|
|
110
|
+
if (files.includes(file) || INLINE_BUNDLE_FILE.test(file)) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
await rebuild(file);
|
|
115
|
+
}
|
|
116
|
+
catch { }
|
|
117
|
+
console.log(`⚡ added ${file} to the build`);
|
|
118
|
+
});
|
|
119
|
+
watcher.on("change", async (file) => {
|
|
120
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
124
|
+
await rebuild(file);
|
|
125
|
+
console.log(`⚡ modified ${file} on the build`);
|
|
126
|
+
});
|
|
127
|
+
watcher.on("unlink", async (file) => {
|
|
128
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
132
|
+
inlineFiles.delete(file);
|
|
133
|
+
const buildFile = getBuildPath(file)
|
|
134
|
+
.replace(".ts", ".js")
|
|
135
|
+
.replace(".jsx", ".js");
|
|
136
|
+
try {
|
|
137
|
+
await rm(buildFile);
|
|
138
|
+
const bfDir = buildFile.split("/").slice(0, -1).join("/");
|
|
139
|
+
const stats = await readdir(bfDir);
|
|
140
|
+
if (!stats.length)
|
|
141
|
+
await rm(bfDir);
|
|
142
|
+
}
|
|
143
|
+
catch { }
|
|
144
|
+
console.log(`⚡ deleted ${file} from the build`);
|
|
145
|
+
});
|
|
146
|
+
async function rebuild(file) {
|
|
147
|
+
// Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
|
|
148
|
+
await rebuildCSS(files.filter((file) => file.endsWith(".css")));
|
|
149
|
+
let html;
|
|
150
|
+
if (file.endsWith(".html")) {
|
|
151
|
+
// To refill the inlineFiles needed to build JS
|
|
152
|
+
for (const htmlFile of files.filter((file) => file.endsWith(".html"))) {
|
|
153
|
+
await writeInlineScripts(htmlFile);
|
|
154
|
+
}
|
|
155
|
+
await minifyCode();
|
|
156
|
+
for (const file of inlineFiles) {
|
|
157
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
158
|
+
inlineFiles.delete(file);
|
|
159
|
+
await rm(file);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
html = await minifyHTML(file, getBuildPath(file));
|
|
163
|
+
}
|
|
164
|
+
else if (/\.(jsx?|tsx?)$/.test(file)) {
|
|
165
|
+
inlineFiles.add(file);
|
|
166
|
+
await minifyCode();
|
|
167
|
+
}
|
|
168
|
+
else if (!file.endsWith(".css")) {
|
|
169
|
+
if (handlerFile) {
|
|
170
|
+
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
171
|
+
console.log("📋 Logging Handler: ", String(stdout));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
await fileCopy(file);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (handlerFile) {
|
|
179
|
+
execFilePromise("node", [handlerFile, file]).then(({ stdout }) => {
|
|
180
|
+
console.log("📋 Logging Handler: ", String(stdout));
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
serverSentEvents?.({ file, html });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function minifyCSS(file, buildFile) {
|
|
188
|
+
try {
|
|
189
|
+
const fileText = await readFile(file, { encoding: "utf-8" });
|
|
190
|
+
const result = await CSSprocessor.process(fileText, {
|
|
191
|
+
...options,
|
|
192
|
+
from: file,
|
|
193
|
+
to: buildFile,
|
|
194
|
+
});
|
|
195
|
+
await writeFile(buildFile, result.css);
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
// @ts-ignore
|
|
199
|
+
console.error(err?.reason);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function minifyCode() {
|
|
203
|
+
try {
|
|
204
|
+
return await esbuild.build({
|
|
205
|
+
entryPoints: Array.from(inlineFiles),
|
|
206
|
+
charset: "utf8",
|
|
207
|
+
format: "esm",
|
|
208
|
+
sourcemap: isHMR,
|
|
209
|
+
splitting: true,
|
|
210
|
+
define: {
|
|
211
|
+
"process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
|
|
212
|
+
},
|
|
213
|
+
loader: { ".js": "jsx", ".ts": "tsx" },
|
|
214
|
+
bundle: true,
|
|
215
|
+
minify: true,
|
|
216
|
+
outdir: bundleConfig.build,
|
|
217
|
+
outbase: bundleConfig.src,
|
|
218
|
+
...bundleConfig.esbuild,
|
|
219
|
+
});
|
|
220
|
+
// Stop app from crashing.
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
if (!isHMR) {
|
|
224
|
+
console.error(err);
|
|
225
|
+
}
|
|
226
|
+
let missingPkg = false;
|
|
227
|
+
if (err?.errors) {
|
|
228
|
+
for (const error of err.errors) {
|
|
229
|
+
if (error.location && error.text?.startsWith("Could not resolve")) {
|
|
230
|
+
missingPkg = true;
|
|
231
|
+
const packageNameRegex = /(?<=").*(?=")/;
|
|
232
|
+
const [pkgName] = error.text.match(packageNameRegex);
|
|
233
|
+
await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
|
|
234
|
+
"install",
|
|
235
|
+
pkgName,
|
|
236
|
+
]);
|
|
237
|
+
console.log(`📦 Package ${pkgName} was installed for you`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (missingPkg) {
|
|
241
|
+
missingPkg = false;
|
|
242
|
+
return minifyCode();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const htmlFilesCache = new Map();
|
|
248
|
+
async function writeInlineScripts(file) {
|
|
249
|
+
let fileText = await readFile(file, { encoding: "utf-8" });
|
|
250
|
+
let DOM;
|
|
251
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
252
|
+
DOM = parse(fileText);
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
DOM = parseFragment(fileText);
|
|
256
|
+
}
|
|
257
|
+
if (isHMR) {
|
|
258
|
+
fileText = addHMRCode(fileText, file, DOM);
|
|
259
|
+
}
|
|
260
|
+
htmlFilesCache.set(file, [fileText, DOM]);
|
|
261
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
262
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
263
|
+
const script = scripts[index];
|
|
264
|
+
const scriptTextNode = script.childNodes[0];
|
|
265
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
266
|
+
const type = script.attrs.find((a) => a.name === "type");
|
|
267
|
+
const scriptContent = scriptTextNode?.value;
|
|
268
|
+
if (!scriptContent ||
|
|
269
|
+
isReferencedScript ||
|
|
270
|
+
type?.value === "importmap" ||
|
|
271
|
+
type?.value === "application/ld+json")
|
|
272
|
+
continue;
|
|
273
|
+
const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
|
|
274
|
+
inlineFiles.add(jsFile);
|
|
275
|
+
await writeFile(jsFile, scriptContent);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async function minifyHTML(file, buildFile) {
|
|
279
|
+
let fileText, DOM;
|
|
280
|
+
if (htmlFilesCache.has(file)) {
|
|
281
|
+
const cache = htmlFilesCache.get(file);
|
|
282
|
+
fileText = cache[0];
|
|
283
|
+
DOM = cache[1];
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
fileText = await readFile(file, { encoding: "utf-8" });
|
|
287
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
288
|
+
DOM = parse(fileText);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
DOM = parseFragment(fileText);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// Minify Code
|
|
295
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
296
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
297
|
+
const script = scripts[index];
|
|
298
|
+
const scriptTextNode = script.childNodes[0];
|
|
299
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
300
|
+
const type = script.attrs.find((a) => a.name === "type");
|
|
301
|
+
if (!scriptTextNode?.value ||
|
|
302
|
+
isReferencedScript ||
|
|
303
|
+
type?.value === "importmap" ||
|
|
304
|
+
type?.value === "application/ld+json")
|
|
305
|
+
continue;
|
|
306
|
+
// Use bundled file
|
|
307
|
+
const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
|
|
308
|
+
try {
|
|
309
|
+
const scriptContent = await readFile(buildInlineScript, {
|
|
310
|
+
encoding: "utf-8",
|
|
311
|
+
});
|
|
312
|
+
await rm(buildInlineScript);
|
|
313
|
+
scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
|
|
314
|
+
}
|
|
315
|
+
catch { }
|
|
316
|
+
}
|
|
317
|
+
// Minify Inline Style
|
|
318
|
+
const styles = findElements(DOM, (e) => getTagName(e) === "style");
|
|
319
|
+
for (const style of styles) {
|
|
320
|
+
const node = style.childNodes[0];
|
|
321
|
+
const styleContent = node?.value;
|
|
322
|
+
if (!styleContent)
|
|
323
|
+
continue;
|
|
324
|
+
try {
|
|
325
|
+
const { css } = await CSSprocessor.process(styleContent, {
|
|
326
|
+
...options,
|
|
327
|
+
from: undefined,
|
|
328
|
+
});
|
|
329
|
+
node.value = css;
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
// @ts-ignore
|
|
333
|
+
console.error(err?.reason);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
fileText = serialize(DOM);
|
|
337
|
+
// Minify HTML
|
|
338
|
+
try {
|
|
339
|
+
fileText = await minify(fileText, {
|
|
340
|
+
collapseWhitespace: true,
|
|
341
|
+
removeComments: true,
|
|
342
|
+
...bundleConfig["html-minifier-terser"],
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
catch (e) {
|
|
346
|
+
console.error(e);
|
|
347
|
+
}
|
|
348
|
+
if (isCritical) {
|
|
349
|
+
try {
|
|
350
|
+
const isPartical = !fileText.startsWith("<!DOCTYPE html>");
|
|
351
|
+
fileText = await beasties.process(fileText);
|
|
352
|
+
// fix beasties jsdom
|
|
353
|
+
if (isPartical) {
|
|
354
|
+
fileText = fileText.replace(/<\/?(html|head|body)>/g, "");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
console.error(err);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
await writeFile(buildFile, fileText);
|
|
362
|
+
return fileText;
|
|
363
|
+
}
|
|
364
|
+
async function rebuildCSS(files, config) {
|
|
365
|
+
const newConfig = await getPostCSSConfig();
|
|
366
|
+
plugins = newConfig.plugins;
|
|
367
|
+
options = newConfig.options;
|
|
368
|
+
CSSprocessor = postcss(plugins);
|
|
369
|
+
for (const file of files) {
|
|
370
|
+
await minifyCSS(file, getBuildPath(file));
|
|
371
|
+
}
|
|
372
|
+
if (config)
|
|
373
|
+
console.log(`⚡ modified ${config}.config`);
|
|
374
|
+
}
|
|
375
|
+
try {
|
|
376
|
+
await cleanupStaleInlineBundleFiles();
|
|
377
|
+
const files = await glob(`${bundleConfig.src}/**/*`);
|
|
378
|
+
await build(files
|
|
379
|
+
.map((file) => file.replaceAll(sep, "/"))
|
|
380
|
+
.filter((file) => !INLINE_BUNDLE_FILE.test(file)));
|
|
381
|
+
}
|
|
382
|
+
catch (err) {
|
|
383
|
+
console.error(err);
|
|
384
|
+
process.exit(1);
|
|
385
|
+
}
|
|
386
|
+
export default router;
|