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/dist/utils.mjs CHANGED
@@ -19,23 +19,31 @@ export function createDir(file) {
19
19
  export function getBuildPath(file) {
20
20
  return file.replace(`${bundleConfig.src}/`, `${bundleConfig.build}/`);
21
21
  }
22
- const CONNECTIONS = []; // In order to send the HMR information
22
+ const CONNECTIONS = new Set(); // In order to send the HMR information
23
23
  export let serverSentEvents;
24
24
  export async function createDefaultServer(isSecure) {
25
25
  const router = express.Router();
26
26
  const app = express();
27
27
  app.use(router);
28
28
  app.use(express.static(path.join(process.cwd(), bundleConfig.build)));
29
- router.get("/hmr", (_req, reply) => {
29
+ router.get("/hmr", (req, reply) => {
30
30
  reply.setHeader("Content-Type", "text/event-stream");
31
31
  reply.setHeader("Cache-Control", "no-cache");
32
32
  !isSecure && reply.setHeader("Connection", "keep-alive");
33
- CONNECTIONS.push(reply);
33
+ reply.flushHeaders();
34
+ CONNECTIONS.add(reply);
35
+ req.on("close", () => {
36
+ CONNECTIONS.delete(reply);
37
+ });
34
38
  serverSentEvents = (data) => {
35
39
  if (/\.(jsx?|tsx?)$/.test(data.file)) {
36
40
  data.file = data.file.replace(".ts", ".js").replace(".jsx", ".js");
37
41
  }
38
42
  CONNECTIONS.forEach((rep) => {
43
+ if (rep.destroyed || rep.writableEnded) {
44
+ CONNECTIONS.delete(rep);
45
+ return;
46
+ }
39
47
  rep.write(`data: ${JSON.stringify(data)}\n\n`);
40
48
  });
41
49
  };
@@ -115,121 +123,170 @@ function randomText() {
115
123
  return Math.random().toString(32).slice(2);
116
124
  }
117
125
  function getHMRCode(file, id, src) {
118
- return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
119
- window.isHMR = true;
120
- window.lastCalled = new Map();
121
- if (!window.eventsource${id}) {
122
- window.eventsource${id} = new EventSource("/hmr");
123
- window.eventsource${id}.addEventListener('error', (e) => {
124
- setTimeout(() => {
125
- window.eventsource${id} = new EventSource("/hmr");
126
- }, 1000);
127
- });
128
- window.eventsource${id}.addEventListener("message", ({ data }) => {
129
- if (window.lastScroll == null) {
130
- window.lastScroll = window.scrollY;
131
- }
132
- const dataObj = JSON.parse(data);
133
- const file = "${file}";
134
-
135
- if (file === dataObj.file && "html" in dataObj) {
136
- let newHTML;
137
- try {
138
- newHTML = html\`\${dataObj.html}\`
139
- } catch {
140
- setShouldSetReactivity(false);
141
- newHTML = html\`\${dataObj.html}\`
142
- setShouldSetReactivity(true);
143
- }
144
-
145
- if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
146
- document.head.remove(); // Don't try to diff the head – just re-run the scripts
147
-
148
- // Restore Scroll
149
- window.addEventListener("afterRouting", () => {
150
- window.scrollTo(0, window.lastScroll);
151
- delete window.lastScroll;
152
- }, { once: true })
153
-
154
- render(newHTML, document.documentElement, false);
155
- } else {
156
- const hmrID = "${id}";
157
- const hmrElems = Array.from(newHTML.childNodes);
158
- const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
159
- // render new elements for old elements. Then, remove rest old elements and add add new elements after the last old one
160
- hmrWheres.forEach((where, index) => {
161
- if (index < hmrElems.length) {
162
- render(hmrElems[index], where, false);
163
- } else {
164
- where.remove();
165
- }
166
- });
167
- for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
168
- if (hmrWheres.length) {
169
- const template = document.createElement('template');
170
- hmrElems[hmrWheres.length - 1].after(template);
171
- render(hmrElems[rest], template, false);
172
- template.remove();
173
- } else {
174
- render(hmrElems[rest], false, false)
175
- }
176
- }
177
- }
178
-
179
- $$('link[rel="stylesheet"][href]').forEach(link => {
180
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
181
- })
182
- if (dataObj.html.includes("<script")) updateElem("script");
183
-
184
-
185
- if (dataObj.file === \`${src}/index.html\`) {
186
- dispatchEvent(new Event("popstate"));
187
- }
188
- } else if (dataObj.file.endsWith(".css")) {
189
- const now = performance.now();
190
- if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
191
- $$('link[rel="stylesheet"][href]').forEach(link => {
192
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
193
- })
194
- window.lastCalled.set(dataObj.file, now)
195
- }
196
- } else if (dataObj.file.endsWith(".js")) {
197
- const now = performance.now();
198
- if (!window.lastCalled.has(dataObj.file) || now - window.lastCalled.get(dataObj.file) > 100) {
199
- $$('link[rel="stylesheet"][href]').forEach(link => {
200
- link.setAttribute("href", link.getAttribute("href") + "?v=" + String(Math.random().toFixed(4)).slice(2));
201
- })
202
- updateElem("script");
203
- window.lastCalled.set(dataObj.file, now)
204
- }
205
- }
206
-
207
-
208
- function updateElem(type) {
209
- const hmrId = "${id}";
210
- const noSrcFile = dataObj.file.replace(\`${src}/\`, '');
211
- const attr = type === "script" ? "src" : "href";
212
- const elem = $(\`[data-hmr="\${hmrId}"] \${type}[\${attr}^="\${noSrcFile}"]\`); // could be $(\`\${type}[data-hmr="\${hmrId}"][\${attr}^="\${noSrcFile}"]\`) ?
213
-
214
- if (elem) {
215
- updateOne(type, attr, elem)
216
- } else {
217
- for(const e of $$(\`[data-hmr="\${hmrId}"] \${type}\`)) {
218
- updateOne(type, attr, e);
219
- }
220
- }
221
- }
222
-
223
- function updateOne(type, attr, elem) {
224
- const clone = document.createElement(type);
225
- for (const key of elem.getAttributeNames()) {
226
- clone.setAttribute(key, elem.getAttribute(key));
227
- }
228
- const attrVal = elem.getAttribute(attr);
229
- if (attrVal) clone.setAttribute(attr, attrVal + "?v=" + String(Math.random().toFixed(4)).slice(2));
230
- render(clone, elem, false);
231
- }
232
- });
233
- }
126
+ return `import { render, html, $, $$, setShouldSetReactivity } from "hydro-js";
127
+ window.isHMR = true;
128
+ window.lastCalled = new Map();
129
+ window.htmlBundleHMRConnections ||= new Map();
130
+ window.htmlBundleHMRActiveId = "${id}";
131
+ let shouldReconnect = true;
132
+ let reconnectTimer;
133
+
134
+ for (const [hmrId, eventSource] of window.htmlBundleHMRConnections) {
135
+ if (hmrId !== "${id}") {
136
+ eventSource.close();
137
+ window.htmlBundleHMRConnections.delete(hmrId);
138
+ delete window["eventsource" + hmrId];
139
+ }
140
+ }
141
+
142
+ function closeEventSource() {
143
+ const eventSource = window.eventsource${id};
144
+ if (eventSource) {
145
+ eventSource.close();
146
+ window.htmlBundleHMRConnections.delete("${id}");
147
+ delete window.eventsource${id};
148
+ }
149
+ }
150
+
151
+ function connectEventSource() {
152
+ closeEventSource();
153
+ shouldReconnect = true;
154
+
155
+ const eventSource = new EventSource("/hmr");
156
+ window.eventsource${id} = eventSource;
157
+ window.htmlBundleHMRConnections.set("${id}", eventSource);
158
+
159
+ eventSource.addEventListener('error', () => {
160
+ eventSource.close();
161
+ if (window.eventsource${id} === eventSource) {
162
+ window.htmlBundleHMRConnections.delete("${id}");
163
+ delete window.eventsource${id};
164
+ }
165
+
166
+ if (shouldReconnect && window.htmlBundleHMRActiveId === "${id}") {
167
+ clearTimeout(reconnectTimer);
168
+ reconnectTimer = setTimeout(connectEventSource, 1000);
169
+ }
170
+ });
171
+
172
+ eventSource.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
+ window.addEventListener("pagehide", () => {
280
+ shouldReconnect = false;
281
+ clearTimeout(reconnectTimer);
282
+ if (window.htmlBundleHMRActiveId === "${id}") {
283
+ delete window.htmlBundleHMRActiveId;
284
+ }
285
+ closeEventSource();
286
+ }, { once: true });
287
+
288
+ if (!window.eventsource${id}) {
289
+ connectEventSource();
290
+ }
234
291
  `;
235
292
  }
package/package.json CHANGED
@@ -1,56 +1,60 @@
1
- {
2
- "name": "html-bundle",
3
- "version": "6.2.3",
4
- "description": "A very simple bundler for HTML SFC",
5
- "bin": "./dist/bundle.mjs",
6
- "main": "./dist/bundle.mjs",
7
- "module": "./dist/bundle.mjs",
8
- "exports": {
9
- "import": "./dist/bundle.mjs",
10
- "default": "./dist/bundle.mjs"
11
- },
12
- "types": "./dist/bundle.d.mts",
13
- "scripts": {
14
- "start": "tsc",
15
- "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
16
- },
17
- "keywords": [
18
- "bundler",
19
- "SFC",
20
- "HTML",
21
- "TypeScript",
22
- "esbuild",
23
- "hydro-js"
24
- ],
25
- "author": "Fabian Klingenberg <klingenberg.fabian@gmx.de> (https://klingenberg.works/)",
26
- "license": "MIT",
27
- "devDependencies": {
28
- "@types/cssnano": "^5.1.3",
29
- "@types/express": "~5.0.2",
30
- "@types/glob": "^9.0.0",
31
- "@types/html-minifier-terser": "^7.0.2",
32
- "@types/parse5": "^7.0.0",
33
- "@types/postcss-load-config": "^3.0.1",
34
- "typescript": "^6.0.3"
35
- },
36
- "repository": {
37
- "type": "git",
38
- "url": "git+https://github.com/Krutsch/html-bundle.git"
39
- },
40
- "bugs": "https://github.com/Krutsch/html-bundle/issues",
41
- "dependencies": {
42
- "@web/parse5-utils": "^2.1.1",
43
- "await-spawn": "^4.0.2",
44
- "beasties": "^0.4.2",
45
- "chokidar": "^5.0.0",
46
- "cssnano": "^7.1.5",
47
- "esbuild": "^0.28.0",
48
- "express": "^5.2.1",
49
- "glob": "^13.0.6",
50
- "html-minifier-terser": "^7.2.0",
51
- "hydro-js": "^1.8.15",
52
- "parse5": "^8.0.1",
53
- "postcss": "^8.5.10",
54
- "postcss-load-config": "^6.0.1"
55
- }
56
- }
1
+ {
2
+ "name": "html-bundle",
3
+ "version": "6.3.1",
4
+ "description": "A very simple bundler for HTML SFC",
5
+ "bin": "./dist/bundle.mjs",
6
+ "main": "./dist/bundle.mjs",
7
+ "module": "./dist/bundle.mjs",
8
+ "exports": {
9
+ "import": "./dist/bundle.mjs",
10
+ "default": "./dist/bundle.mjs"
11
+ },
12
+ "types": "./dist/bundle.d.mts",
13
+ "scripts": {
14
+ "start": "tsc && node -e \"require('fs').chmodSync('dist/bundle.mjs', 0o755)\"",
15
+ "test": "npm run start && node --test tests/*.test.mjs",
16
+ "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
17
+ },
18
+ "keywords": [
19
+ "bundler",
20
+ "SFC",
21
+ "HTML",
22
+ "TypeScript",
23
+ "esbuild",
24
+ "hydro-js"
25
+ ],
26
+ "author": "Fabian Klingenberg <klingenberg.fabian@gmx.de> (https://klingenberg.works/)",
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "@types/cssnano": "^5.1.3",
30
+ "@types/express": "~5.0.6",
31
+ "@types/glob": "^9.0.0",
32
+ "@types/html-minifier-terser": "^7.0.2",
33
+ "@types/parse5": "^7.0.0",
34
+ "@types/postcss-load-config": "^3.0.1",
35
+ "typescript": "^6.0.3"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/Krutsch/html-bundle.git"
40
+ },
41
+ "bugs": "https://github.com/Krutsch/html-bundle/issues",
42
+ "dependencies": {
43
+ "@web/parse5-utils": "^2.1.1",
44
+ "await-spawn": "^4.0.2",
45
+ "beasties": "^0.4.2",
46
+ "chokidar": "^5.0.0",
47
+ "cssnano": "^8.0.2",
48
+ "esbuild": "^0.28.1",
49
+ "express": "^5.2.1",
50
+ "glob": "^13.0.6",
51
+ "html-minifier-terser": "^7.2.0",
52
+ "hydro-js": "^1.9.0",
53
+ "parse5": "^8.0.1",
54
+ "postcss": "^8.5.16",
55
+ "postcss-load-config": "^6.0.1"
56
+ },
57
+ "allowScripts": {
58
+ "esbuild@0.28.1": true
59
+ }
60
+ }