html-bundle 6.0.0-beta → 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/dist/bundle.mjs CHANGED
@@ -12,7 +12,7 @@ import { watch } from "chokidar";
12
12
  import { serialize, parse, parseFragment } from "parse5";
13
13
  import { getTagName, findElements } from "@web/parse5-utils";
14
14
  import awaitSpawn from "await-spawn";
15
- import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.js";
15
+ import { fileCopy, createDefaultServer, getPostCSSConfig, getBuildPath, createDir, bundleConfig, serverSentEvents, addHMRCode, } from "./utils.mjs";
16
16
  const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
17
17
  const isCritical = process.argv.includes("--critical") || bundleConfig.critical;
18
18
  const isSecure = process.argv.includes("--secure") || bundleConfig.secure; // uses CSP for critical too
package/dist/utils.mjs ADDED
@@ -0,0 +1,166 @@
1
+ import { 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.js");
73
+ const config = await import(`file://${cfgPath}`);
74
+ return { ...base, ...config.default };
75
+ }
76
+ catch {
77
+ return base;
78
+ }
79
+ }
80
+ const htmlIdMap = new Map();
81
+ export function addHMRCode(html, file, ast) {
82
+ if (!htmlIdMap.has(file)) {
83
+ htmlIdMap.set(file, randomText());
84
+ }
85
+ const script = createScript({ type: "module" }, getHMRCode(file, htmlIdMap.get(file), bundleConfig.src));
86
+ let DOM;
87
+ if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
88
+ DOM = ast || parse(html);
89
+ const headNode = findElement(DOM, (e) => getTagName(e) === "head");
90
+ appendChild(headNode, script);
91
+ }
92
+ else {
93
+ DOM = ast || parseFragment(html);
94
+ appendChild(DOM, script);
95
+ }
96
+ //@ts-ignore
97
+ DOM.childNodes.forEach((node) => node.attrs?.push({ name: "data-hmr", value: htmlIdMap.get(file) }));
98
+ return serialize(DOM);
99
+ }
100
+ function randomText() {
101
+ return Math.random().toString(32).slice(2);
102
+ }
103
+ function getHMRCode(file, id, src) {
104
+ return `import { render, html, $, $$, setInsertDiffing } from "hydro-js";
105
+ if (!window.eventsource${id}) {
106
+ setInsertDiffing(true);
107
+ window.eventsource${id} = new EventSource("/events");
108
+ window.eventsource${id}.addEventListener("message", ({ data }) => {
109
+ const dataObj = JSON.parse(data);
110
+ const file = "${file}";
111
+
112
+ if (file === dataObj.file && "html" in dataObj) {
113
+ if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
114
+ document.head.remove(); // Don't try to diff the head – just re-run the scripts
115
+ render(html\`\${dataObj.html}\`, document.documentElement);
116
+ } else {
117
+ const hmrID = "${id}";
118
+ const newHTML = html\`\${dataObj.html}\`;
119
+ const hmrElems = Array.from(newHTML.childNodes);
120
+ const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
121
+ // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
122
+ hmrWheres.forEach((where, index) => {
123
+ if (index < hmrElems.length) {
124
+ render(hmrElems[index], where, false);
125
+ } else {
126
+ where.remove();
127
+ }
128
+ });
129
+ for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
130
+ if (hmrWheres.length) {
131
+ const template = document.createElement('template');
132
+ hmrElems[hmrWheres.length - 1].after(template);
133
+ render(hmrElems[rest], template, false);
134
+ template.remove();
135
+ } else {
136
+ render(hmrElems[rest], false, false)
137
+ }
138
+ }
139
+ }
140
+
141
+ setTimeout(() => dispatchEvent(new Event("popstate")));
142
+ } else if (dataObj.file.endsWith("css")) {
143
+ updateElem("link");
144
+ } else if (dataObj.file.endsWith("js")) {
145
+ updateElem("script")
146
+ }
147
+
148
+ function updateElem(type) {
149
+ const hmrId = "${id}";
150
+ const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
151
+ const attr = type === "script" ? "src" : "href";
152
+ const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
153
+
154
+ if (elem) {
155
+ const clone = document.createElement(type);
156
+ for (const key of elem.getAttributeNames()) {
157
+ clone.setAttribute(key, elem.getAttribute(key));
158
+ }
159
+ clone.setAttribute(attr, elem.getAttribute(attr) + "?v=" + String(Math.random().toFixed(4)).slice(2));
160
+ render(clone, elem, false);
161
+ }
162
+ }
163
+ });
164
+ }
165
+ `;
166
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "html-bundle",
3
- "version": "6.0.0-beta",
3
+ "version": "6.0.1-beta",
4
4
  "description": "A very simple bundler for HTML SFC",
5
5
  "bin": "./dist/bundle.mjs",
6
6
  "scripts": {
package/src/bundle.mts CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  bundleConfig,
25
25
  serverSentEvents,
26
26
  addHMRCode,
27
- } from "./utils.js";
27
+ } from "./utils.mjs";
28
28
 
29
29
  const isHMR = process.argv.includes("--hmr") || bundleConfig.hmr;
30
30
  const isCritical = process.argv.includes("--critical") || bundleConfig.critical;
@@ -1,5 +1,5 @@
1
1
  import type { FastifyServerOptions } from "fastify";
2
- import { access, copyFile, mkdir, readFile } from "fs/promises";
2
+ import { copyFile, mkdir, readFile } from "fs/promises";
3
3
  import path from "path";
4
4
  import Fastify from "fastify";
5
5
  import fastifyStatic from "fastify-static";
@@ -92,12 +92,10 @@ async function getBundleConfig() {
92
92
  };
93
93
 
94
94
  try {
95
- const cfgPath = path.resolve(process.cwd(), "bundle.config.cjs");
96
- await access(cfgPath, 0);
95
+ const cfgPath = path.resolve(process.cwd(), "bundle.config.js");
97
96
  const config = await import(`file://${cfgPath}`);
98
97
  return { ...base, ...config.default };
99
98
  } catch {
100
- console.log("catch");
101
99
  return base;
102
100
  }
103
101
  }
@@ -114,7 +112,7 @@ export function addHMRCode(
114
112
 
115
113
  const script = createScript(
116
114
  { type: "module" },
117
- getHMRCode(file, htmlIdMap.get(file), bundleConfig.src, bundleConfig.build)
115
+ getHMRCode(file, htmlIdMap.get(file), bundleConfig.src)
118
116
  );
119
117
 
120
118
  let DOM;
@@ -139,7 +137,7 @@ function randomText() {
139
137
  return Math.random().toString(32).slice(2);
140
138
  }
141
139
 
142
- function getHMRCode(file: string, id: string, src: string, build: string) {
140
+ function getHMRCode(file: string, id: string, src: string) {
143
141
  return `import { render, html, $, $$, setInsertDiffing } from "hydro-js";
144
142
  if (!window.eventsource${id}) {
145
143
  setInsertDiffing(true);