html-bundle 5.5.0 → 6.0.1-beta
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/README.md +30 -21
- package/dist/bundle.mjs +327 -0
- package/dist/utils.js +168 -0
- package/dist/utils.mjs +166 -0
- package/package.json +3 -2
- package/src/bundle.mts +381 -0
- package/src/index.d.ts +3 -0
- package/src/utils.mts +203 -0
- package/dist/bundle.js +0 -625
- package/src/bundle.ts +0 -732
package/README.md
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
# html-bundle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A (primarily) zero-config bundler for HTML files. The idea is to use HTML as Single File Components, because HTML can already include `<style>` and `<script>` elements.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🦾 TypeScript (reference it as .js or write inline TS)
|
|
8
|
+
- 📦 Automatic Package Installation
|
|
9
|
+
- 💨 HMR
|
|
10
|
+
- ⚡ [ESBuild](https://github.com/evanw/esbuild)
|
|
11
|
+
- 🦔 [Critical CSS](https://github.com/evanw/esbuild)
|
|
12
|
+
- 💅 PostCSS and Tailwind CSS Support
|
|
13
|
+
- 🛡️ Almost no need to restart
|
|
4
14
|
|
|
5
15
|

|
|
6
16
|
|
|
@@ -20,19 +30,7 @@ Add an entry to script in package.json (see flags below).
|
|
|
20
30
|
}
|
|
21
31
|
```
|
|
22
32
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
```json
|
|
26
|
-
{
|
|
27
|
-
"scripts": {
|
|
28
|
-
"dev": "html-bundle --hmr --secure",
|
|
29
|
-
"build": "html-bundle --critical",
|
|
30
|
-
"serve": "html-bundle --serveOnly --secure"
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
Add a `postcss.config.cjs` file and run the build command.
|
|
33
|
+
Add a `postcss.config.js` file and run the build command.
|
|
36
34
|
<em>If you do not create this config file, a minimal in-memory config file will be created with `cssnano` as plugin.</em>
|
|
37
35
|
|
|
38
36
|
```properties
|
|
@@ -41,22 +39,33 @@ $ npm run build
|
|
|
41
39
|
|
|
42
40
|
## CLI
|
|
43
41
|
|
|
44
|
-
`--
|
|
42
|
+
`--hmr`: boots up a static server and enables Hot Module Replacement. **This generates a development build.**<br>
|
|
45
43
|
`--secure`: creates a secure HTTP2 over HTTPS instance. This requires the files `localhost.pem` and `localhost-key.pem` in the root folder. You can generate them with [mkcert](https://github.com/FiloSottile/mkcert) for instance.<br>
|
|
46
|
-
`--
|
|
47
|
-
`--
|
|
48
|
-
|
|
44
|
+
`--critical`: uses critical to extract and inline critical-path CSS to HTML.<br>
|
|
45
|
+
`--handler`: path to your custom handler. Here, you can handle all non-supported files. You can get the filename via `process.argv[2]`.
|
|
46
|
+
|
|
47
|
+
## Optional Config
|
|
48
|
+
|
|
49
|
+
_The CLI flags can also be set by the config. Flags set by the CLI will override the config._
|
|
50
|
+
Generate the config in the root and call it "bundle.config.js"
|
|
51
|
+
|
|
52
|
+
**src:** input path. Default to "src"<br>
|
|
53
|
+
**build:** output path. Defaults to "build"<br>
|
|
54
|
+
**port:** For the HMR Server. Defaults to 5000<br>
|
|
55
|
+
**esbuild:** Your additional config<br>
|
|
56
|
+
**html-minifier-terser:** Your additional config<br>
|
|
57
|
+
**critical:** Your additional config<br>
|
|
49
58
|
|
|
50
59
|
## Concept
|
|
51
60
|
|
|
52
|
-
The bundler always globs all HTML, CSS and TS/JS files from the `src
|
|
61
|
+
The bundler always globs all HTML, CSS and TS/JS files from the `src` (config) directory and processes them to the `build` (config) directory. PostCSS is being used for CSS files and inline styles, html-minifier-terser for HTML and esbuild to bundle, minify, etc. for inline and referenced TS/JS. Server-sent events and [hydro-js](https://github.com/Krutsch/hydro-js) are used for HMR. This will install hydro-js to your dependencies. In order to trigger SPA Routers, the popstate event is being triggered after HMR Operations.
|
|
53
62
|
|
|
54
63
|
## Example hydro-js
|
|
55
64
|
|
|
56
|
-
|
|
65
|
+
Get the idea from [hydro-starter](https://github.com/Krutsch/hydro-starter).<br>
|
|
57
66
|
Set `"jsxFactory": "h"` in `tsconfig.json` for JSX.
|
|
58
67
|
|
|
59
|
-
|
|
68
|
+
### Input
|
|
60
69
|
|
|
61
70
|
```html
|
|
62
71
|
<!DOCTYPE html>
|
package/dist/bundle.mjs
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { performance } from "perf_hooks";
|
|
3
|
+
import { readFile, rm, writeFile, readdir } from "fs/promises";
|
|
4
|
+
import { execFile } from "child_process";
|
|
5
|
+
import { promisify } from "util";
|
|
6
|
+
import glob from "glob";
|
|
7
|
+
import postcss from "postcss";
|
|
8
|
+
import esbuild from "esbuild";
|
|
9
|
+
import critical from "critical";
|
|
10
|
+
import { minify } from "html-minifier-terser";
|
|
11
|
+
import { watch } from "chokidar";
|
|
12
|
+
import { serialize, parse, parseFragment } from "parse5";
|
|
13
|
+
import { getTagName, findElements } from "@web/parse5-utils";
|
|
14
|
+
import awaitSpawn from "await-spawn";
|
|
15
|
+
import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
|
|
16
|
+
const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
|
|
17
|
+
const isCritical = process.argv.includes("--critical") || bundleConfig.critical;
|
|
18
|
+
const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
|
|
19
|
+
const handlerFile = process.argv.includes("--handler")
|
|
20
|
+
? process.argv[process.argv.indexOf("--handler") + 1]
|
|
21
|
+
: bundleConfig.handler;
|
|
22
|
+
process.env.NODE_ENV = isHMR ? "development" : "production"; // just in case other tools are using it
|
|
23
|
+
const timer = performance.now();
|
|
24
|
+
let { plugins, options, file: postcssFile } = await getPostCSSConfig();
|
|
25
|
+
let CSSprocessor = postcss(plugins);
|
|
26
|
+
let fastify;
|
|
27
|
+
const inlineFiles = new Set();
|
|
28
|
+
const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
|
|
29
|
+
const INLINE_BUNDLE_FILE = /-bundle-\d+.tsx$/;
|
|
30
|
+
const SUPPORTED_FILES = /\.(html|css|m?jsx?|m?tsx?)$/;
|
|
31
|
+
const execFilePromise = promisify(execFile);
|
|
32
|
+
await rm(bundleConfig.build, { force: true, recursive: true });
|
|
33
|
+
glob(`${bundleConfig.src}/**/*.*`, build);
|
|
34
|
+
async function build(err, files) {
|
|
35
|
+
if (err) {
|
|
36
|
+
console.error(err);
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
if (isHMR) {
|
|
40
|
+
fastify = await createDefaultServer(isSecure);
|
|
41
|
+
fastify.listen(bundleConfig.port);
|
|
42
|
+
console.log(`💻 Sever listening on port ${bundleConfig.port}.`);
|
|
43
|
+
}
|
|
44
|
+
for (const file of files) {
|
|
45
|
+
await createDir(file);
|
|
46
|
+
if (!SUPPORTED_FILES.test(file)) {
|
|
47
|
+
if (handlerFile) {
|
|
48
|
+
const { stdout } = await execFilePromise("node", [handlerFile, file]);
|
|
49
|
+
console.log("📋 Logging Handler: ", String(stdout));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
await fileCopy(file);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
if (file.endsWith(".html")) {
|
|
57
|
+
await writeInlineScripts(file);
|
|
58
|
+
}
|
|
59
|
+
else if (file.endsWith(".css")) {
|
|
60
|
+
await minifyCSS(file, getBuildPath(file));
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
inlineFiles.add(file);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
await minifyCode();
|
|
68
|
+
for (const file of inlineFiles) {
|
|
69
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
70
|
+
inlineFiles.delete(file);
|
|
71
|
+
await rm(file);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
for (const file of files) {
|
|
75
|
+
if (file.endsWith(".html")) {
|
|
76
|
+
await minifyHTML(file, getBuildPath(file));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
console.log(`🚀 Build finished in ${(performance.now() - timer).toFixed(2)}ms ✨`);
|
|
80
|
+
if (isHMR) {
|
|
81
|
+
console.log(`⌛ Waiting for file changes ...`);
|
|
82
|
+
if (postcssFile) {
|
|
83
|
+
const postCSSWatcher = watch(postcssFile);
|
|
84
|
+
const tailwindCSSWatcher = watch(postcssFile.replace("postcss", "tailwind")); // Assuming that the file ext is the same
|
|
85
|
+
const cssFiles = files.filter((file) => file.endsWith(".css"));
|
|
86
|
+
postCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "postcss"));
|
|
87
|
+
tailwindCSSWatcher.on("change", async () => await rebuildCSS(cssFiles, "tailwind"));
|
|
88
|
+
}
|
|
89
|
+
const watcher = watch(bundleConfig.src);
|
|
90
|
+
let addCount = 0; // The add watcher will add all the files initially - do not rebuild them
|
|
91
|
+
watcher.on("add", async (file) => {
|
|
92
|
+
if (addCount++ <= files.length || INLINE_BUNDLE_FILE.test(file)) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
file = String.raw `${file}`.replace(/\\/g, "/"); // glob and chokidar diff
|
|
96
|
+
await rebuild(file);
|
|
97
|
+
console.log(`⚡ added ${file} to the build`);
|
|
98
|
+
});
|
|
99
|
+
watcher.on("change", async (file) => {
|
|
100
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
104
|
+
await rebuild(file);
|
|
105
|
+
console.log(`⚡ modified ${file} on the build`);
|
|
106
|
+
});
|
|
107
|
+
watcher.on("unlink", async (file) => {
|
|
108
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
file = String.raw `${file}`.replace(/\\/g, "/");
|
|
112
|
+
inlineFiles.delete(file);
|
|
113
|
+
const buildFile = getBuildPath(file)
|
|
114
|
+
.replace(".ts", ".js")
|
|
115
|
+
.replace(".jsx", ".js");
|
|
116
|
+
await rm(buildFile);
|
|
117
|
+
const bfDir = buildFile.split("/").slice(0, -1).join("/");
|
|
118
|
+
const stats = await readdir(bfDir);
|
|
119
|
+
if (!stats.length)
|
|
120
|
+
await rm(bfDir);
|
|
121
|
+
console.log(`⚡ deleted ${file} from the build`);
|
|
122
|
+
});
|
|
123
|
+
async function rebuild(file) {
|
|
124
|
+
// Rebuild all CSS because a change in any file might need to trigger PostCSS zu rebuild(e.g. Tailwind CSS)
|
|
125
|
+
await rebuildCSS(files.filter((file) => file.endsWith(".css")));
|
|
126
|
+
let html;
|
|
127
|
+
if (file.endsWith(".html")) {
|
|
128
|
+
// To refill the inlineFiles needed to build JS
|
|
129
|
+
for (const htmlFile of files.filter((file) => file.endsWith("html"))) {
|
|
130
|
+
await writeInlineScripts(htmlFile);
|
|
131
|
+
}
|
|
132
|
+
await minifyCode();
|
|
133
|
+
for (const file of inlineFiles) {
|
|
134
|
+
if (INLINE_BUNDLE_FILE.test(file)) {
|
|
135
|
+
inlineFiles.delete(file);
|
|
136
|
+
await rm(file);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
html = await minifyHTML(file, getBuildPath(file));
|
|
140
|
+
}
|
|
141
|
+
else if (/(m?jsx?|m?tsx?)$/.test(file)) {
|
|
142
|
+
await minifyCode();
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
const { stdout } = await execFilePromise("node", [handlerFile, file]);
|
|
146
|
+
console.log("📋 Logging Handler: ", String(stdout));
|
|
147
|
+
}
|
|
148
|
+
serverSentEvents({ file, html });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async function minifyCSS(file, buildFile) {
|
|
153
|
+
try {
|
|
154
|
+
const fileText = await readFile(file, { encoding: "utf-8" });
|
|
155
|
+
const result = await CSSprocessor.process(fileText, {
|
|
156
|
+
...options,
|
|
157
|
+
from: file,
|
|
158
|
+
to: buildFile,
|
|
159
|
+
});
|
|
160
|
+
await writeFile(buildFile, result.css);
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
console.error(err);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function minifyCode() {
|
|
167
|
+
try {
|
|
168
|
+
return await esbuild.build({
|
|
169
|
+
entryPoints: Array.from(inlineFiles),
|
|
170
|
+
charset: "utf8",
|
|
171
|
+
format: "esm",
|
|
172
|
+
incremental: isHMR,
|
|
173
|
+
sourcemap: isHMR,
|
|
174
|
+
splitting: true,
|
|
175
|
+
define: {
|
|
176
|
+
"process.env.NODE_ENV": process.env.NODE_ENV,
|
|
177
|
+
},
|
|
178
|
+
loader: { ".js": "jsx", ".ts": "tsx" },
|
|
179
|
+
bundle: true,
|
|
180
|
+
minify: true,
|
|
181
|
+
outdir: bundleConfig.build,
|
|
182
|
+
outbase: bundleConfig.src,
|
|
183
|
+
...bundleConfig.esbuild,
|
|
184
|
+
});
|
|
185
|
+
// Stop app from crashing.
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
if (!isHMR) {
|
|
189
|
+
console.error(err);
|
|
190
|
+
}
|
|
191
|
+
let missingPkg = false;
|
|
192
|
+
if (err?.errors) {
|
|
193
|
+
for (const error of err.errors) {
|
|
194
|
+
if (error.text?.startsWith("Could not resolve")) {
|
|
195
|
+
missingPkg = true;
|
|
196
|
+
const packageNameRegex = /(?<=").*(?=")/;
|
|
197
|
+
const [pkgName] = error.text.match(packageNameRegex);
|
|
198
|
+
console.log(`📦 Package ${pkgName} was installed for you`);
|
|
199
|
+
await awaitSpawn(process.platform === "win32" ? "npm.cmd" : "npm", [
|
|
200
|
+
"install",
|
|
201
|
+
pkgName,
|
|
202
|
+
]);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (missingPkg) {
|
|
206
|
+
missingPkg = false;
|
|
207
|
+
return minifyCode();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const htmlFilesCache = new Map();
|
|
213
|
+
async function writeInlineScripts(file) {
|
|
214
|
+
let fileText = await readFile(file, { encoding: "utf-8" });
|
|
215
|
+
let DOM;
|
|
216
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
217
|
+
DOM = parse(fileText);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
DOM = parseFragment(fileText);
|
|
221
|
+
}
|
|
222
|
+
if (isHMR) {
|
|
223
|
+
fileText = addHMRCode(fileText, file, DOM);
|
|
224
|
+
}
|
|
225
|
+
htmlFilesCache.set(file, [fileText, DOM]);
|
|
226
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
227
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
228
|
+
const script = scripts[index];
|
|
229
|
+
const scriptTextNode = script.childNodes[0];
|
|
230
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
231
|
+
const scriptContent = scriptTextNode?.value;
|
|
232
|
+
if (!scriptContent || isReferencedScript)
|
|
233
|
+
continue;
|
|
234
|
+
const jsFile = file.replace(".html", `-bundle-${index}.tsx`);
|
|
235
|
+
inlineFiles.add(jsFile);
|
|
236
|
+
await writeFile(jsFile, scriptContent);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function minifyHTML(file, buildFile) {
|
|
240
|
+
let fileText, DOM;
|
|
241
|
+
if (htmlFilesCache.has(file)) {
|
|
242
|
+
const cache = htmlFilesCache.get(file);
|
|
243
|
+
fileText = cache[0];
|
|
244
|
+
DOM = cache[1];
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
fileText = await readFile(file, { encoding: "utf-8" });
|
|
248
|
+
if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
|
|
249
|
+
DOM = parse(fileText);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
DOM = parseFragment(fileText);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// Minify Code
|
|
256
|
+
const scripts = findElements(DOM, (e) => getTagName(e) === "script");
|
|
257
|
+
for (let index = 0; index < scripts.length; index++) {
|
|
258
|
+
const script = scripts[index];
|
|
259
|
+
const scriptTextNode = script.childNodes[0];
|
|
260
|
+
const isReferencedScript = script.attrs.find((a) => a.name === "src");
|
|
261
|
+
if (!scriptTextNode?.value || isReferencedScript)
|
|
262
|
+
continue;
|
|
263
|
+
// Use bundled file
|
|
264
|
+
const buildInlineScript = buildFile.replace(".html", `-bundle-${index}.js`);
|
|
265
|
+
const scriptContent = await readFile(buildInlineScript, {
|
|
266
|
+
encoding: "utf-8",
|
|
267
|
+
});
|
|
268
|
+
await rm(buildInlineScript);
|
|
269
|
+
scriptTextNode.value = scriptContent.replace(TEMPLATE_LITERAL_MINIFIER, " ");
|
|
270
|
+
}
|
|
271
|
+
// Minify Inline Style
|
|
272
|
+
const styles = findElements(DOM, (e) => getTagName(e) === "style");
|
|
273
|
+
for (const style of styles) {
|
|
274
|
+
const node = style.childNodes[0];
|
|
275
|
+
const styleContent = node?.value;
|
|
276
|
+
if (!styleContent)
|
|
277
|
+
continue;
|
|
278
|
+
const { css } = await CSSprocessor.process(styleContent, {
|
|
279
|
+
...options,
|
|
280
|
+
from: undefined,
|
|
281
|
+
});
|
|
282
|
+
node.value = css;
|
|
283
|
+
}
|
|
284
|
+
fileText = serialize(DOM);
|
|
285
|
+
// Minify HTML
|
|
286
|
+
fileText = await minify(fileText, {
|
|
287
|
+
collapseWhitespace: true,
|
|
288
|
+
removeComments: true,
|
|
289
|
+
...bundleConfig["html-minifier-terser"],
|
|
290
|
+
});
|
|
291
|
+
if (!isCritical) {
|
|
292
|
+
await writeFile(buildFile, fileText);
|
|
293
|
+
return fileText;
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
const buildFileArr = buildFile.split("/");
|
|
297
|
+
const fileWithBase = buildFileArr.pop();
|
|
298
|
+
const buildDir = buildFileArr.join("/");
|
|
299
|
+
// critical is generating the files on the fs
|
|
300
|
+
try {
|
|
301
|
+
const { html } = await critical.generate({
|
|
302
|
+
base: buildDir,
|
|
303
|
+
html: fileText,
|
|
304
|
+
target: fileWithBase,
|
|
305
|
+
inline: !isSecure,
|
|
306
|
+
extract: true,
|
|
307
|
+
rebase: () => { },
|
|
308
|
+
...bundleConfig.critical,
|
|
309
|
+
});
|
|
310
|
+
return html;
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
console.error(err);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async function rebuildCSS(files, config) {
|
|
318
|
+
const newConfig = await getPostCSSConfig();
|
|
319
|
+
plugins = newConfig.plugins;
|
|
320
|
+
options = newConfig.options;
|
|
321
|
+
CSSprocessor = postcss(plugins);
|
|
322
|
+
for (const file of files) {
|
|
323
|
+
await minifyCSS(file, getBuildPath(file));
|
|
324
|
+
}
|
|
325
|
+
if (config)
|
|
326
|
+
console.log(`⚡ modified ${config}.config`);
|
|
327
|
+
}
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { access, copyFile, mkdir, readFile } from "fs/promises";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import fastifyStatic from "fastify-static";
|
|
5
|
+
import postcssrc from "postcss-load-config";
|
|
6
|
+
import cssnano from "cssnano";
|
|
7
|
+
import { parse, parseFragment, serialize } from "parse5";
|
|
8
|
+
import { createScript, getTagName, findElement, appendChild, } from "@web/parse5-utils";
|
|
9
|
+
export const bundleConfig = await getBundleConfig();
|
|
10
|
+
export function fileCopy(file) {
|
|
11
|
+
return copyFile(file, getBuildPath(file));
|
|
12
|
+
}
|
|
13
|
+
export function createDir(file) {
|
|
14
|
+
const buildPath = getBuildPath(file);
|
|
15
|
+
const dir = buildPath.split("/").slice(0, -1).join("/");
|
|
16
|
+
return mkdir(dir, { recursive: true });
|
|
17
|
+
}
|
|
18
|
+
export function getBuildPath(file) {
|
|
19
|
+
return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
|
|
20
|
+
}
|
|
21
|
+
const CONNECTIONS = []; // In order to send the HMR information
|
|
22
|
+
export let serverSentEvents;
|
|
23
|
+
export async function createDefaultServer(isSecure) {
|
|
24
|
+
const fastify = Fastify(isSecure
|
|
25
|
+
? {
|
|
26
|
+
http2: true,
|
|
27
|
+
https: {
|
|
28
|
+
key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
|
|
29
|
+
cert: await readFile(path.join(process.cwd(), "localhost.pem")),
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
: void 0);
|
|
33
|
+
fastify.setNotFoundHandler(async (_req, reply) => {
|
|
34
|
+
const file = await readFile(path.join(process.cwd(), bundleConfig.build, "/index.html"), {
|
|
35
|
+
encoding: "utf-8",
|
|
36
|
+
});
|
|
37
|
+
reply.header("Content-Type", "text/html; charset=UTF-8");
|
|
38
|
+
return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
|
|
39
|
+
});
|
|
40
|
+
fastify.register(fastifyStatic, {
|
|
41
|
+
root: path.join(process.cwd(), bundleConfig.build),
|
|
42
|
+
});
|
|
43
|
+
fastify.get("/events", (_req, reply) => {
|
|
44
|
+
reply.raw.setHeader("Content-Type", "text/event-stream");
|
|
45
|
+
reply.raw.setHeader("Cache-Control", "no-cache");
|
|
46
|
+
!isSecure && reply.raw.setHeader("Connection", "keep-alive");
|
|
47
|
+
CONNECTIONS.push(reply.raw);
|
|
48
|
+
serverSentEvents = (data) => CONNECTIONS.forEach((rep) => {
|
|
49
|
+
rep.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
return fastify;
|
|
53
|
+
}
|
|
54
|
+
export function getPostCSSConfig() {
|
|
55
|
+
try {
|
|
56
|
+
return postcssrc({});
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return { plugins: [cssnano], options: {}, file: "" };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function getBundleConfig() {
|
|
63
|
+
const base = {
|
|
64
|
+
build: "build",
|
|
65
|
+
src: "src",
|
|
66
|
+
port: 5000,
|
|
67
|
+
esbuild: {},
|
|
68
|
+
"html-minifier-terser": {},
|
|
69
|
+
critical: {},
|
|
70
|
+
};
|
|
71
|
+
try {
|
|
72
|
+
const cfgPath = path.resolve(process.cwd(), "bundle.config.cjs");
|
|
73
|
+
await access(cfgPath, 0);
|
|
74
|
+
const config = await import(`file://${cfgPath}`);
|
|
75
|
+
return { ...base, ...config.default };
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
console.log("catch");
|
|
79
|
+
return base;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const htmlIdMap = new Map();
|
|
83
|
+
export function addHMRCode(html, file, ast) {
|
|
84
|
+
if (!htmlIdMap.has(file)) {
|
|
85
|
+
htmlIdMap.set(file, randomText());
|
|
86
|
+
}
|
|
87
|
+
const script = createScript({ type: "module" }, getHMRCode(file, htmlIdMap.get(file), bundleConfig.src, bundleConfig.build));
|
|
88
|
+
let DOM;
|
|
89
|
+
if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
|
|
90
|
+
DOM = ast || parse(html);
|
|
91
|
+
const headNode = findElement(DOM, (e) => getTagName(e) === "head");
|
|
92
|
+
appendChild(headNode, script);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
DOM = ast || parseFragment(html);
|
|
96
|
+
appendChild(DOM, script);
|
|
97
|
+
}
|
|
98
|
+
//@ts-ignore
|
|
99
|
+
DOM.childNodes.forEach((node) => node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }));
|
|
100
|
+
return serialize(DOM);
|
|
101
|
+
}
|
|
102
|
+
function randomText() {
|
|
103
|
+
return Math.random().toString(32).slice(2);
|
|
104
|
+
}
|
|
105
|
+
function getHMRCode(file, id, src, build) {
|
|
106
|
+
return `import { render, html, $, $$, setInsertDiffing } from "hydro-js";
|
|
107
|
+
if (!window.eventsource${id}) {
|
|
108
|
+
setInsertDiffing(true);
|
|
109
|
+
window.eventsource${id} = new EventSource("/events");
|
|
110
|
+
window.eventsource${id}.addEventListener("message", ({ data }) => {
|
|
111
|
+
const dataObj = JSON.parse(data);
|
|
112
|
+
const file = "${file}";
|
|
113
|
+
|
|
114
|
+
if (file === dataObj.file && "html" in dataObj) {
|
|
115
|
+
if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
|
|
116
|
+
document.head.remove(); // Don't try to diff the head – just re-run the scripts
|
|
117
|
+
render(html\`\${dataObj.html}\`, document.documentElement);
|
|
118
|
+
} else {
|
|
119
|
+
const hmrID = "${id}";
|
|
120
|
+
const newHTML = html\`\${dataObj.html}\`;
|
|
121
|
+
const hmrElems = Array.from(newHTML.childNodes);
|
|
122
|
+
const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
|
|
123
|
+
// render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
|
|
124
|
+
hmrWheres.forEach((where, index) => {
|
|
125
|
+
if (index < hmrElems.length) {
|
|
126
|
+
render(hmrElems[index], where, false);
|
|
127
|
+
} else {
|
|
128
|
+
where.remove();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
|
|
132
|
+
if (hmrWheres.length) {
|
|
133
|
+
const template = document.createElement('template');
|
|
134
|
+
hmrElems[hmrWheres.length - 1].after(template);
|
|
135
|
+
render(hmrElems[rest], template, false);
|
|
136
|
+
template.remove();
|
|
137
|
+
} else {
|
|
138
|
+
render(hmrElems[rest], false, false)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
setTimeout(() => dispatchEvent(new Event("popstate")));
|
|
144
|
+
} else if (dataObj.file.endsWith("css")) {
|
|
145
|
+
updateElem("link");
|
|
146
|
+
} else if (dataObj.file.endsWith("js")) {
|
|
147
|
+
updateElem("script")
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function updateElem(type) {
|
|
151
|
+
const hmrId = "${id}";
|
|
152
|
+
const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
|
|
153
|
+
const attr = type === "script" ? "src" : "href";
|
|
154
|
+
const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
|
|
155
|
+
|
|
156
|
+
if (elem) {
|
|
157
|
+
const clone = document.createElement(type);
|
|
158
|
+
for (const key of elem.getAttributeNames()) {
|
|
159
|
+
clone.setAttribute(key, elem.getAttribute(key));
|
|
160
|
+
}
|
|
161
|
+
clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
|
|
162
|
+
render(clone, elem, false);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
`;
|
|
168
|
+
}
|