html-bundle 5.5.2 → 6.0.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/README.md +48 -30
- package/dist/bundle.mjs +279 -566
- package/dist/utils.mjs +195 -0
- package/logo.jpg +0 -0
- package/package.json +2 -1
- package/src/bundle.mts +315 -653
- package/src/index.d.ts +3 -0
- package/src/utils.mts +231 -0
package/src/index.d.ts
ADDED
package/src/utils.mts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import type { FastifyServerOptions } from "fastify";
|
|
2
|
+
import { copyFile, mkdir, readFile } from "fs/promises";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import Fastify from "fastify";
|
|
5
|
+
import fastifyStatic from "fastify-static";
|
|
6
|
+
import postcssrc from "postcss-load-config";
|
|
7
|
+
import cssnano from "cssnano";
|
|
8
|
+
import { parse, parseFragment, serialize } from "parse5";
|
|
9
|
+
import {
|
|
10
|
+
createScript,
|
|
11
|
+
getTagName,
|
|
12
|
+
findElement,
|
|
13
|
+
appendChild,
|
|
14
|
+
} from "@web/parse5-utils";
|
|
15
|
+
|
|
16
|
+
export const bundleConfig = await getBundleConfig();
|
|
17
|
+
|
|
18
|
+
export function fileCopy(file: string) {
|
|
19
|
+
return copyFile(file, getBuildPath(file));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createDir(file: string) {
|
|
23
|
+
const buildPath = getBuildPath(file);
|
|
24
|
+
const dir = buildPath.split("/").slice(0, -1).join("/");
|
|
25
|
+
return mkdir(dir, { recursive: true });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function getBuildPath(file: string) {
|
|
29
|
+
return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const CONNECTIONS: Array<any> = []; // In order to send the HMR information
|
|
33
|
+
export let serverSentEvents:
|
|
34
|
+
| undefined
|
|
35
|
+
| (({ file, html }: { file: string; html?: string }) => void);
|
|
36
|
+
export async function createDefaultServer(isSecure: boolean) {
|
|
37
|
+
const fastify = Fastify(
|
|
38
|
+
isSecure
|
|
39
|
+
? ({
|
|
40
|
+
http2: true,
|
|
41
|
+
https: {
|
|
42
|
+
key: await readFile(path.join(process.cwd(), "localhost-key.pem")),
|
|
43
|
+
cert: await readFile(path.join(process.cwd(), "localhost.pem")),
|
|
44
|
+
},
|
|
45
|
+
} as FastifyServerOptions)
|
|
46
|
+
: void 0
|
|
47
|
+
);
|
|
48
|
+
fastify.setNotFoundHandler(async (_req, reply) => {
|
|
49
|
+
const file = await readFile(
|
|
50
|
+
path.join(process.cwd(), bundleConfig.build, "/index.html"),
|
|
51
|
+
{
|
|
52
|
+
encoding: "utf-8",
|
|
53
|
+
}
|
|
54
|
+
);
|
|
55
|
+
reply.header("Content-Type", "text/html; charset=UTF-8");
|
|
56
|
+
return reply.send(addHMRCode(file, `${bundleConfig.src}/index.html`));
|
|
57
|
+
});
|
|
58
|
+
fastify.register(fastifyStatic, {
|
|
59
|
+
root: path.join(process.cwd(), bundleConfig.build),
|
|
60
|
+
});
|
|
61
|
+
fastify.get("/hmr", (_req, reply) => {
|
|
62
|
+
reply.raw.setHeader("Content-Type", "text/event-stream");
|
|
63
|
+
reply.raw.setHeader("Cache-Control", "no-cache");
|
|
64
|
+
!isSecure && reply.raw.setHeader("Connection", "keep-alive");
|
|
65
|
+
|
|
66
|
+
CONNECTIONS.push(reply.raw);
|
|
67
|
+
|
|
68
|
+
serverSentEvents = (data) => {
|
|
69
|
+
if (/\.(jsx?|tsx?)$/.test(data.file)) {
|
|
70
|
+
data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
|
|
71
|
+
}
|
|
72
|
+
CONNECTIONS.forEach((rep) => {
|
|
73
|
+
rep.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
return fastify;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function getPostCSSConfig() {
|
|
81
|
+
try {
|
|
82
|
+
return await postcssrc({});
|
|
83
|
+
} catch {
|
|
84
|
+
return { plugins: [cssnano], options: {}, file: "" };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function getBundleConfig() {
|
|
89
|
+
const base = {
|
|
90
|
+
build: "build",
|
|
91
|
+
src: "src",
|
|
92
|
+
port: 5000,
|
|
93
|
+
esbuild: {},
|
|
94
|
+
"html-minifier-terser": {},
|
|
95
|
+
critical: {},
|
|
96
|
+
deletePrev: true,
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
|
|
101
|
+
const config = await import(`file://${cfgPath}`);
|
|
102
|
+
return { ...base, ...config.default };
|
|
103
|
+
} catch {
|
|
104
|
+
return base;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const htmlIdMap = new Map();
|
|
109
|
+
export function addHMRCode(
|
|
110
|
+
html: string,
|
|
111
|
+
file: string,
|
|
112
|
+
ast?: ReturnType<typeof parse | typeof parseFragment>
|
|
113
|
+
) {
|
|
114
|
+
if (!htmlIdMap.has(file)) {
|
|
115
|
+
htmlIdMap.set(file, randomText());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const script = createScript(
|
|
119
|
+
{ type: "module" },
|
|
120
|
+
getHMRCode(file, htmlIdMap.get(file), bundleConfig.src)
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
let DOM;
|
|
124
|
+
if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
|
|
125
|
+
DOM = ast || parse(html);
|
|
126
|
+
const headNode = findElement(DOM, (e) => getTagName(e) === "head");
|
|
127
|
+
appendChild(headNode, script);
|
|
128
|
+
} else {
|
|
129
|
+
DOM = ast || parseFragment(html);
|
|
130
|
+
appendChild(DOM, script);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
//@ts-ignore
|
|
134
|
+
DOM.childNodes.forEach((node) =>
|
|
135
|
+
node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) })
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
return serialize(DOM);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function randomText() {
|
|
142
|
+
return Math.random().toString(32).slice(2);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function getHMRCode(file: string, id: string, src: string) {
|
|
146
|
+
return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
|
|
147
|
+
window.isHMR = true;
|
|
148
|
+
if (!window.eventsource${id}) {
|
|
149
|
+
window.eventsource${id} = new EventSource("/hmr");
|
|
150
|
+
window.eventsource${id}.addEventListener('error', (e) => {
|
|
151
|
+
setTimeout(() => {
|
|
152
|
+
window.eventsource${id} = new EventSource("/hmr");
|
|
153
|
+
}, 1000);
|
|
154
|
+
});
|
|
155
|
+
window.eventsource${id}.addEventListener("message", ({ data }) => {
|
|
156
|
+
const dataObj = JSON.parse(data);
|
|
157
|
+
const file = "${file}";
|
|
158
|
+
|
|
159
|
+
if (file === dataObj.file && "html" in dataObj) {
|
|
160
|
+
let newHTML;
|
|
161
|
+
try {
|
|
162
|
+
newHTML = html\`\${dataObj.html}\`
|
|
163
|
+
} catch {
|
|
164
|
+
setShouldSetReactivity(false);
|
|
165
|
+
newHTML = html\`\${dataObj.html}\`
|
|
166
|
+
setShouldSetReactivity(true);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
|
|
170
|
+
document.head.remove(); // Don't try to diff the head – just re-run the scripts
|
|
171
|
+
render(newHTML, document.documentElement, false);
|
|
172
|
+
} else {
|
|
173
|
+
const hmrID = "${id}";
|
|
174
|
+
const hmrElems = Array.from(newHTML.childNodes);
|
|
175
|
+
const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
|
|
176
|
+
// render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
|
|
177
|
+
hmrWheres.forEach((where, index) => {
|
|
178
|
+
if (index < hmrElems.length) {
|
|
179
|
+
render(hmrElems[index], where, false);
|
|
180
|
+
} else {
|
|
181
|
+
where.remove();
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
|
|
185
|
+
if (hmrWheres.length) {
|
|
186
|
+
const template = document.createElement('template');
|
|
187
|
+
hmrElems[hmrWheres.length - 1].after(template);
|
|
188
|
+
render(hmrElems[rest], template, false);
|
|
189
|
+
template.remove();
|
|
190
|
+
} else {
|
|
191
|
+
render(hmrElems[rest], false, false)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (dataObj.file === \`${src}/index.html\`) {
|
|
197
|
+
dispatchEvent(new Event("popstate"));
|
|
198
|
+
}
|
|
199
|
+
} else if (dataObj.file.endsWith(".css")) {
|
|
200
|
+
updateElem("link");
|
|
201
|
+
} else if (dataObj.file.endsWith(".js")) {
|
|
202
|
+
updateElem("script")
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function updateElem(type) {
|
|
206
|
+
const hmrId = "${id}";
|
|
207
|
+
const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
|
|
208
|
+
const attr = type === "script" ? "src" : "href";
|
|
209
|
+
const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
|
|
210
|
+
|
|
211
|
+
if (elem) {
|
|
212
|
+
updateOne(type, attr, elem)
|
|
213
|
+
} else {
|
|
214
|
+
for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
|
|
215
|
+
updateOne(type, attr, e);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function updateOne(type, attr, elem) {
|
|
221
|
+
const clone = document.createElement(type);
|
|
222
|
+
for (const key of elem.getAttributeNames()) {
|
|
223
|
+
clone.setAttribute(key, elem.getAttribute(key));
|
|
224
|
+
}
|
|
225
|
+
clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
|
|
226
|
+
render(clone, elem, false);
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
`;
|
|
231
|
+
}
|