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/src/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- declare module "await-spawn" {
2
- export default (cmd: string, args: string[]): Promise<unknown> => {};
3
- }
1
+ declare module "await-spawn" {
2
+ export default (cmd: string, args: string[]): Promise<unknown> => {};
3
+ }
package/src/utils.mts CHANGED
@@ -1,279 +1,339 @@
1
- import type { Node } from "@web/parse5-utils";
2
- import type { Config } from "./bundle.mjs";
3
- import type { Router } from "express-serve-static-core";
4
- import { copyFile, mkdir, readFile } from "fs/promises";
5
- import path from "path";
6
- import http, { type Server } from "http";
7
- import https, { type Server as HTTPSServer } from "https";
8
- import express from "express";
9
- import postcssrc from "postcss-load-config";
10
- import cssnano from "cssnano";
11
- import { parse, parseFragment, serialize } from "parse5";
12
- import {
13
- createScript,
14
- getTagName,
15
- findElement,
16
- appendChild,
17
- } from "@web/parse5-utils";
18
-
19
- export const bundleConfig = await getBundleConfig();
20
-
21
- export function fileCopy(file: string) {
22
- return copyFile(file, getBuildPath(file));
23
- }
24
-
25
- export function createDir(file: string) {
26
- const buildPath = getBuildPath(file);
27
- const dir = buildPath.split("/").slice(0, -1).join("/");
28
- return mkdir(dir, { recursive: true });
29
- }
30
-
31
- export function getBuildPath(file: string) {
32
- return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
33
- }
34
-
35
- const CONNECTIONS: Array<any> = []; // In order to send the HMR information
36
- export let serverSentEvents:
37
- | undefined
38
- | (({ file, html }: { file: string; html?: string }) => void);
39
- export async function createDefaultServer(
40
- isSecure: boolean
41
- ): Promise<[Router, Server | HTTPSServer]> {
42
- const router = express.Router();
43
- const app = express();
44
- app.use(router);
45
- app.use(express.static(path.join(process.cwd(), bundleConfig.build)));
46
-
47
- router.get("/hmr", (_req, reply) => {
48
- reply.setHeader("Content-Type", "text/event-stream");
49
- reply.setHeader("Cache-Control", "no-cache");
50
- !isSecure && reply.setHeader("Connection", "keep-alive");
51
- CONNECTIONS.push(reply);
52
- serverSentEvents = (data) => {
53
- if (/\.(jsx?|tsx?)$/.test(data.file)) {
54
- data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
55
- }
56
- CONNECTIONS.forEach((rep) => {
57
- rep.write(`data: ${JSON.stringify(data)}\n\n`);
58
- });
59
- };
60
- });
61
-
62
- app.use(async (_req, res) => {
63
- res.setHeader("Content-Type", "text/html");
64
- const file = await readFile(
65
- path.join(process.cwd(), bundleConfig.build, "index.html"),
66
- {
67
- encoding: "utf-8",
68
- }
69
- );
70
- res.send(file);
71
- });
72
-
73
- return [
74
- router,
75
- isSecure
76
- ? https.createServer(
77
- {
78
- key:
79
- bundleConfig.key ||
80
- (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
81
- cert:
82
- bundleConfig.cert ||
83
- (await readFile(path.join(process.cwd(), "localhost.pem"))),
84
- },
85
- app
86
- )
87
- : http.createServer({}, app),
88
- ];
89
- }
90
-
91
- export async function getPostCSSConfig() {
92
- try {
93
- return await postcssrc({});
94
- } catch {
95
- return { plugins: [cssnano], options: {}, file: "" };
96
- }
97
- }
98
-
99
- async function getBundleConfig(): Promise<Config> {
100
- const base = {
101
- build: "build",
102
- src: "src",
103
- port: 5000,
104
- esbuild: {},
105
- "html-minifier-terser": {},
106
- deletePrev: true,
107
- critical: {},
108
- isCritical: false,
109
- hmr: false,
110
- secure: false,
111
- handler: "",
112
- host: "::",
113
- };
114
-
115
- try {
116
- const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
117
- const config = await import(`file://${cfgPath}`);
118
- return { ...base, ...config.default };
119
- } catch {
120
- return base;
121
- }
122
- }
123
-
124
- const htmlIdMap = new Map();
125
- export function addHMRCode(
126
- html: string,
127
- file: string,
128
- ast?: ReturnType<typeof parse | typeof parseFragment>
129
- ) {
130
- if (!htmlIdMap.has(file)) {
131
- htmlIdMap.set(file, randomText());
132
- }
133
-
134
- const script = createScript(
135
- { type: "module" },
136
- getHMRCode(file, htmlIdMap.get(file), bundleConfig.src)
137
- );
138
-
139
- let DOM;
140
- if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
141
- DOM = ast || parse(html);
142
- const headNode = findElement(DOM as Node, (e) => getTagName(e) === "head");
143
- appendChild(headNode, script);
144
- } else {
145
- DOM = ast || parseFragment(html);
146
- appendChild(DOM, script);
147
- }
148
-
149
- //@ts-ignore
150
- DOM.childNodes.forEach((node) =>
151
- node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) })
152
- );
153
-
154
- return serialize(DOM as any);
155
- }
156
-
157
- function randomText() {
158
- return Math.random().toString(32).slice(2);
159
- }
160
-
161
- function getHMRCode(file: string, id: string, src: string) {
162
- return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
163
- window.isHMR = true;
164
- window.lastCalled = new Map();
165
- if (!window.eventsource${id}) {
166
- window.eventsource${id} = new EventSource("/hmr");
167
- window.eventsource${id}.addEventListener('error', (e) => {
168
- setTimeout(() => {
169
- window.eventsource${id} = new EventSource("/hmr");
170
- }, 1000);
171
- });
172
- window.eventsource${id}.addEventListener("message", ({ data }) => {
173
- if (window.lastScroll == null) {
174
- window.lastScroll = window.scrollY;
175
- }
176
- const dataObj = JSON.parse(data);
177
- const file = "${file}";
178
-
179
- if (file === dataObj.file && "html" in dataObj) {
180
- let newHTML;
181
- try {
182
- newHTML = html\`\${dataObj.html}\`
183
- } catch {
184
- setShouldSetReactivity(false);
185
- newHTML = html\`\${dataObj.html}\`
186
- setShouldSetReactivity(true);
187
- }
188
-
189
- if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
190
- document.head.remove(); // Don't try to diff the head – just re-run the scripts
191
-
192
- // Restore Scroll
193
- window.addEventListener("afterRouting", () => {
194
- window.scrollTo(0, window.lastScroll);
195
- delete window.lastScroll;
196
- }, { once: true })
197
-
198
- render(newHTML, document.documentElement, false);
199
- } else {
200
- const hmrID = "${id}";
201
- const hmrElems = Array.from(newHTML.childNodes);
202
- const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
203
- // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
204
- hmrWheres.forEach((where, index) => {
205
- if (index < hmrElems.length) {
206
- render(hmrElems[index], where, false);
207
- } else {
208
- where.remove();
209
- }
210
- });
211
- for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
212
- if (hmrWheres.length) {
213
- const template = document.createElement('template');
214
- hmrElems[hmrWheres.length - 1].after(template);
215
- render(hmrElems[rest], template, false);
216
- template.remove();
217
- } else {
218
- render(hmrElems[rest], false, false)
219
- }
220
- }
221
- }
222
-
223
- $$('link[rel="stylesheet"][href]').forEach(link => {
224
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
225
- })
226
- if (dataObj.html.includes("<script")) updateElem("script");
227
-
228
-
229
- if (dataObj.file === \`${src}/index.html\`) {
230
- dispatchEvent(new Event("popstate"));
231
- }
232
- } else if (dataObj.file.endsWith(".css")) {
233
- const now = performance.now();
234
- if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
235
- $$('link[rel="stylesheet"][href]').forEach(link => {
236
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
237
- })
238
- window.lastCalled.set(dataObj.file, now)
239
- }
240
- } else if (dataObj.file.endsWith(".js")) {
241
- const now = performance.now();
242
- if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
243
- $$('link[rel="stylesheet"][href]').forEach(link => {
244
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
245
- })
246
- updateElem("script");
247
- window.lastCalled.set(dataObj.file, now)
248
- }
249
- }
250
-
251
-
252
- function updateElem(type) {
253
- const hmrId = "${id}";
254
- const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
255
- const attr = type === "script" ? "src" : "href";
256
- const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
257
-
258
- if (elem) {
259
- updateOne(type, attr, elem)
260
- } else {
261
- for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
262
- updateOne(type, attr, e);
263
- }
264
- }
265
- }
266
-
267
- function updateOne(type, attr, elem) {
268
- const clone = document.createElement(type);
269
- for (const key of elem.getAttributeNames()) {
270
- clone.setAttribute(key, elem.getAttribute(key));
271
- }
272
- const attrVal = elem.getAttribute(attr);
273
- if (attrVal) clone.setAttribute(attr, attrVal + "?v=" + String(Math.random().toFixed(4)).slice(2));
274
- render(clone, elem, false);
275
- }
276
- });
277
- }
278
- `;
279
- }
1
+ import type { Node } from "@web/parse5-utils";
2
+ import type { Config } from "./bundle.mjs";
3
+ import type { Router } from "express-serve-static-core";
4
+ import { copyFile, mkdir, readFile } from "fs/promises";
5
+ import path from "path";
6
+ import http, { type Server } from "http";
7
+ import https, { type Server as HTTPSServer } from "https";
8
+ import express from "express";
9
+ import postcssrc from "postcss-load-config";
10
+ import cssnano from "cssnano";
11
+ import { parse, parseFragment, serialize } from "parse5";
12
+ import {
13
+ createScript,
14
+ getTagName,
15
+ findElement,
16
+ appendChild,
17
+ } from "@web/parse5-utils";
18
+
19
+ export const bundleConfig = await getBundleConfig();
20
+
21
+ export function fileCopy(file: string) {
22
+ return copyFile(file, getBuildPath(file));
23
+ }
24
+
25
+ export function createDir(file: string) {
26
+ const buildPath = getBuildPath(file);
27
+ const dir = buildPath.split("/").slice(0, -1).join("/");
28
+ return mkdir(dir, { recursive: true });
29
+ }
30
+
31
+ export function getBuildPath(file: string) {
32
+ return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
33
+ }
34
+
35
+ const CONNECTIONS = new Set<any>(); // In order to send the HMR information
36
+ export let serverSentEvents:
37
+ | undefined
38
+ | (({ file, html }: { file: string; html?: string }) => void);
39
+ export async function createDefaultServer(
40
+ isSecure: boolean,
41
+ ): Promise<[Router, Server | HTTPSServer]> {
42
+ const router = express.Router();
43
+ const app = express();
44
+ app.use(router);
45
+ app.use(express.static(path.join(process.cwd(), bundleConfig.build)));
46
+
47
+ router.get("/hmr", (req, reply) => {
48
+ reply.setHeader("Content-Type", "text/event-stream");
49
+ reply.setHeader("Cache-Control", "no-cache");
50
+ !isSecure && reply.setHeader("Connection", "keep-alive");
51
+ reply.flushHeaders();
52
+
53
+ CONNECTIONS.add(reply);
54
+ req.on("close", () => {
55
+ CONNECTIONS.delete(reply);
56
+ });
57
+
58
+ serverSentEvents = (data) => {
59
+ if (/\.(jsx?|tsx?)$/.test(data.file)) {
60
+ data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
61
+ }
62
+ CONNECTIONS.forEach((rep) => {
63
+ if (rep.destroyed || rep.writableEnded) {
64
+ CONNECTIONS.delete(rep);
65
+ return;
66
+ }
67
+
68
+ rep.write(`data: ${JSON.stringify(data)}\n\n`);
69
+ });
70
+ };
71
+ });
72
+
73
+ app.use(async (_req, res) => {
74
+ res.setHeader("Content-Type", "text/html");
75
+ const file = await readFile(
76
+ path.join(process.cwd(), bundleConfig.build, "index.html"),
77
+ {
78
+ encoding: "utf-8",
79
+ },
80
+ );
81
+ res.send(file);
82
+ });
83
+
84
+ return [
85
+ router,
86
+ isSecure
87
+ ? https.createServer(
88
+ {
89
+ key:
90
+ bundleConfig.key ||
91
+ (await readFile(path.join(process.cwd(), "localhost-key.pem"))),
92
+ cert:
93
+ bundleConfig.cert ||
94
+ (await readFile(path.join(process.cwd(), "localhost.pem"))),
95
+ },
96
+ app,
97
+ )
98
+ : http.createServer({}, app),
99
+ ];
100
+ }
101
+
102
+ export async function getPostCSSConfig() {
103
+ try {
104
+ return await postcssrc({});
105
+ } catch {
106
+ return { plugins: [cssnano], options: {}, file: "" };
107
+ }
108
+ }
109
+
110
+ async function getBundleConfig(): Promise<Config> {
111
+ const base = {
112
+ build: "build",
113
+ src: "src",
114
+ port: 5000,
115
+ esbuild: {},
116
+ "html-minifier-terser": {},
117
+ deletePrev: true,
118
+ critical: {},
119
+ isCritical: false,
120
+ hmr: false,
121
+ secure: false,
122
+ handler: "",
123
+ host: "::",
124
+ };
125
+
126
+ try {
127
+ const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
128
+ const config = await import(`file://${cfgPath}`);
129
+ return { ...base, ...config.default };
130
+ } catch {
131
+ return base;
132
+ }
133
+ }
134
+
135
+ const htmlIdMap = new Map();
136
+ export function addHMRCode(
137
+ html: string,
138
+ file: string,
139
+ ast?: ReturnType<typeof parse | typeof parseFragment>,
140
+ ) {
141
+ if (!htmlIdMap.has(file)) {
142
+ htmlIdMap.set(file, randomText());
143
+ }
144
+
145
+ const script = createScript(
146
+ { type: "module" },
147
+ getHMRCode(file, htmlIdMap.get(file), bundleConfig.src),
148
+ );
149
+
150
+ let DOM;
151
+ if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
152
+ DOM = ast || parse(html);
153
+ const headNode = findElement(DOM as Node, (e) => getTagName(e) === "head");
154
+ appendChild(headNode, script);
155
+ } else {
156
+ DOM = ast || parseFragment(html);
157
+ appendChild(DOM, script);
158
+ }
159
+
160
+ //@ts-ignore
161
+ DOM.childNodes.forEach((node) =>
162
+ node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }),
163
+ );
164
+
165
+ return serialize(DOM as any);
166
+ }
167
+
168
+ function randomText() {
169
+ return Math.random().toString(32).slice(2);
170
+ }
171
+
172
+ function getHMRCode(file: string, id: string, src: string) {
173
+ return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
174
+ window.isHMR = true;
175
+ window.lastCalled = new Map();
176
+ window.htmlBundleHMRConnections ||= new Map();
177
+ window.htmlBundleHMRActiveId = "${id}";
178
+ let shouldReconnect = true;
179
+ let reconnectTimer;
180
+
181
+ for (const [hmrId, eventSource] of window.htmlBundleHMRConnections) {
182
+ if (hmrId !== "${id}") {
183
+ eventSource.close();
184
+ window.htmlBundleHMRConnections.delete(hmrId);
185
+ delete window["eventsource" + hmrId];
186
+ }
187
+ }
188
+
189
+ function closeEventSource() {
190
+ const eventSource = window.eventsource${id};
191
+ if (eventSource) {
192
+ eventSource.close();
193
+ window.htmlBundleHMRConnections.delete("${id}");
194
+ delete window.eventsource${id};
195
+ }
196
+ }
197
+
198
+ function connectEventSource() {
199
+ closeEventSource();
200
+ shouldReconnect = true;
201
+
202
+ const eventSource = new EventSource("/hmr");
203
+ window.eventsource${id} = eventSource;
204
+ window.htmlBundleHMRConnections.set("${id}", eventSource);
205
+
206
+ eventSource.addEventListener('error', () => {
207
+ eventSource.close();
208
+ if (window.eventsource${id} === eventSource) {
209
+ window.htmlBundleHMRConnections.delete("${id}");
210
+ delete window.eventsource${id};
211
+ }
212
+
213
+ if (shouldReconnect && window.htmlBundleHMRActiveId === "${id}") {
214
+ clearTimeout(reconnectTimer);
215
+ reconnectTimer = setTimeout(connectEventSource, 1000);
216
+ }
217
+ });
218
+
219
+ eventSource.addEventListener("message", ({ data }) => {
220
+ if (window.lastScroll == null) {
221
+ window.lastScroll = window.scrollY;
222
+ }
223
+ const dataObj = JSON.parse(data);
224
+ const file = "${file}";
225
+
226
+ if (file === dataObj.file && "html" in dataObj) {
227
+ let newHTML;
228
+ try {
229
+ newHTML = html\`\${dataObj.html}\`
230
+ } catch {
231
+ setShouldSetReactivity(false);
232
+ newHTML = html\`\${dataObj.html}\`
233
+ setShouldSetReactivity(true);
234
+ }
235
+
236
+ if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
237
+ document.head.remove(); // Don't try to diff the head – just re-run the scripts
238
+
239
+ // Restore Scroll
240
+ window.addEventListener("afterRouting", () => {
241
+ window.scrollTo(0, window.lastScroll);
242
+ delete window.lastScroll;
243
+ }, { once: true })
244
+
245
+ render(newHTML, document.documentElement, false);
246
+ } else {
247
+ const hmrID = "${id}";
248
+ const hmrElems = Array.from(newHTML.childNodes);
249
+ const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
250
+ // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
251
+ hmrWheres.forEach((where, index) => {
252
+ if (index < hmrElems.length) {
253
+ render(hmrElems[index], where, false);
254
+ } else {
255
+ where.remove();
256
+ }
257
+ });
258
+ for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
259
+ if (hmrWheres.length) {
260
+ const template = document.createElement('template');
261
+ hmrElems[hmrWheres.length - 1].after(template);
262
+ render(hmrElems[rest], template, false);
263
+ template.remove();
264
+ } else {
265
+ render(hmrElems[rest], false, false)
266
+ }
267
+ }
268
+ }
269
+
270
+ $$('link[rel="stylesheet"][href]').forEach(link => {
271
+ link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
272
+ })
273
+ if (dataObj.html.includes("<script")) updateElem("script");
274
+
275
+
276
+ if (dataObj.file === \`${src}/index.html\`) {
277
+ dispatchEvent(new Event("popstate"));
278
+ }
279
+ } else if (dataObj.file.endsWith(".css")) {
280
+ const now = performance.now();
281
+ if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
282
+ $$('link[rel="stylesheet"][href]').forEach(link => {
283
+ link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
284
+ })
285
+ window.lastCalled.set(dataObj.file, now)
286
+ }
287
+ } else if (dataObj.file.endsWith(".js")) {
288
+ const now = performance.now();
289
+ if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
290
+ $$('link[rel="stylesheet"][href]').forEach(link => {
291
+ link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
292
+ })
293
+ updateElem("script");
294
+ window.lastCalled.set(dataObj.file, now)
295
+ }
296
+ }
297
+
298
+
299
+ function updateElem(type) {
300
+ const hmrId = "${id}";
301
+ const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
302
+ const attr = type === "script" ? "src" : "href";
303
+ const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
304
+
305
+ if (elem) {
306
+ updateOne(type, attr, elem)
307
+ } else {
308
+ for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
309
+ updateOne(type, attr, e);
310
+ }
311
+ }
312
+ }
313
+
314
+ function updateOne(type, attr, elem) {
315
+ const clone = document.createElement(type);
316
+ for (const key of elem.getAttributeNames()) {
317
+ clone.setAttribute(key, elem.getAttribute(key));
318
+ }
319
+ const attrVal = elem.getAttribute(attr);
320
+ if (attrVal) clone.setAttribute(attr, attrVal + "?v=" + String(Math.random().toFixed(4)).slice(2));
321
+ render(clone, elem, false);
322
+ }
323
+ });
324
+ }
325
+
326
+ window.addEventListener("pagehide", () => {
327
+ shouldReconnect = false;
328
+ clearTimeout(reconnectTimer);
329
+ if (window.htmlBundleHMRActiveId === "${id}") {
330
+ delete window.htmlBundleHMRActiveId;
331
+ }
332
+ closeEventSource();
333
+ }, { once: true });
334
+
335
+ if (!window.eventsource${id}) {
336
+ connectEventSource();
337
+ }
338
+ `;
339
+ }