html-bundle 5.4.17 → 5.5.2

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.
@@ -34,32 +34,21 @@ else {
34
34
  // Performance Observer and file watcher
35
35
  const globHTML = new Event.EventEmitter();
36
36
  const taskEmitter = new Event.EventEmitter();
37
- const start = performance.now();
37
+ let start = performance.now();
38
+ let addedHMR = false;
38
39
  let expectedTasks = 0; // This will be increased in globHandlers
39
40
  let finishedTasks = 0; // Current status
40
41
  taskEmitter.on("done", () => {
41
42
  finishedTasks++;
42
43
  if (finishedTasks === expectedTasks) {
43
44
  console.log(`🚀 Build finished in ${(performance.now() - start).toFixed(2)}ms ✨`);
44
- if (isHMR) {
45
+ if (isHMR && !addedHMR) {
46
+ addedHMR = true;
45
47
  if (file) {
46
48
  const postCSSWatcher = watch(file);
47
- postCSSWatcher.on("change", () => {
48
- console.log(" modified postcss.config – CSS will rebuild now.");
49
- const newConfig = createPostCSSConfig();
50
- plugins = newConfig.plugins;
51
- options = newConfig.options;
52
- CSSprocessor = postcss(plugins);
53
- glob(`${SOURCE_FOLDER}/**/*.css`, {}, (err, files) => {
54
- errorHandler(err);
55
- expectedTasks += files.length;
56
- for (const filename of files) {
57
- const [buildFilename, buildPathDir] = getBuildNames(filename);
58
- fs.mkdirSync(buildPathDir, { recursive: true });
59
- minifyCSS(filename, buildFilename);
60
- }
61
- });
62
- });
49
+ const tailwindCSSWatcher = watch(file.replace("postcss", "tailwind"));
50
+ postCSSWatcher.on("change", () => rebuildCSS("postcss"));
51
+ tailwindCSSWatcher.on("change", () => rebuildCSS("tailwind"));
63
52
  }
64
53
  console.log(`⌛ Waiting for file changes ...`);
65
54
  const watcher = watch(SOURCE_FOLDER);
@@ -67,6 +56,8 @@ else {
67
56
  let initialAdd = 0;
68
57
  let hasJSTS = false;
69
58
  watcher.on("add", (filename) => {
59
+ start = performance.now();
60
+ rebuildCSS();
70
61
  // Return if it was added by the build system itself
71
62
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
72
63
  return;
@@ -89,6 +80,8 @@ else {
89
80
  });
90
81
  });
91
82
  watcher.on("change", (filename) => {
83
+ start = performance.now();
84
+ rebuildCSS();
92
85
  // Return if it was changed by the build system itself
93
86
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
94
87
  return;
@@ -99,6 +92,7 @@ else {
99
92
  console.log(`⚡ modified ${buildFilename}`);
100
93
  });
101
94
  watcher.on("unlink", (filename) => {
95
+ start = performance.now();
102
96
  // Return if it was deleted by the build system itself
103
97
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
104
98
  return;
@@ -117,6 +111,24 @@ else {
117
111
  }
118
112
  }
119
113
  });
114
+ function rebuildCSS(config) {
115
+ start = performance.now();
116
+ if (config)
117
+ console.log(`⚡ modified ${config}.config – CSS will rebuild now.`);
118
+ const newConfig = createPostCSSConfig();
119
+ plugins = newConfig.plugins;
120
+ options = newConfig.options;
121
+ CSSprocessor = postcss(plugins);
122
+ glob(`${SOURCE_FOLDER}/**/*.css`, {}, (err, files) => {
123
+ errorHandler(err);
124
+ expectedTasks += files.length;
125
+ for (const filename of files) {
126
+ const [buildFilename, buildPathDir] = getBuildNames(filename);
127
+ fs.mkdirSync(buildPathDir, { recursive: true });
128
+ minifyCSS(filename, buildFilename);
129
+ }
130
+ });
131
+ }
120
132
  // Basic configuration
121
133
  const SOURCE_FOLDER = "src";
122
134
  const BUILD_FOLDER = "build";
@@ -258,7 +270,7 @@ else {
258
270
  if (!isInline) {
259
271
  taskEmitter.emit("done");
260
272
  globHTML.emit("getReady");
261
- if (serverSentEvents) {
273
+ if (serverSentEvents && file) {
262
274
  const changedFile = tsMaybeX2JS(file);
263
275
  const [buildFilename] = getBuildNames(changedFile);
264
276
  const js = fs.readFileSync(buildFilename, { encoding: "utf8" });
@@ -353,7 +365,6 @@ else {
353
365
  base: buildDir,
354
366
  html: fileText,
355
367
  target: fileWithBase,
356
- minify: true,
357
368
  inline: !isCSP,
358
369
  extract: true,
359
370
  rebase: () => { },
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "html-bundle",
3
- "version": "5.4.17",
3
+ "version": "5.5.2",
4
4
  "description": "A very simple bundler for HTML SFC",
5
- "bin": "./cjs/bundle.js",
5
+ "bin": "./dist/bundle.mjs",
6
6
  "scripts": {
7
- "start": "tsc && tsc -p tsconfig.cjs.json",
7
+ "start": "tsc",
8
8
  "update": "npx npm-check-updates -u && npx typesync && npm i && npm outdated"
9
9
  },
10
10
  "keywords": [
@@ -19,11 +19,11 @@
19
19
  "license": "MIT",
20
20
  "devDependencies": {
21
21
  "@types/cssnano": "^4.0.1",
22
- "@types/glob": "^7.1.4",
23
- "@types/html-minifier-terser": "^6.0.0",
24
- "@types/parse5": "^6.0.1",
22
+ "@types/glob": "^7.2.0",
23
+ "@types/html-minifier-terser": "^6.1.0",
24
+ "@types/parse5": "^6.0.3",
25
25
  "@types/postcss-load-config": "^3.0.1",
26
- "typescript": "^4.4.3"
26
+ "typescript": "^4.5.4"
27
27
  },
28
28
  "repository": {
29
29
  "type": "git",
@@ -34,14 +34,14 @@
34
34
  "@web/parse5-utils": "^1.3.0",
35
35
  "chokidar": "^3.5.2",
36
36
  "critical": "^4.0.1",
37
- "cssnano": "^5.0.8",
38
- "esbuild": "^0.13.0",
39
- "fastify": "^3.21.5",
40
- "fastify-static": "^4.2.3",
41
- "glob": "^7.1.7",
42
- "html-minifier-terser": "^6.0.2",
37
+ "cssnano": "^5.0.14",
38
+ "esbuild": "^0.14.8",
39
+ "fastify": "^3.25.2",
40
+ "fastify-static": "^4.5.0",
41
+ "glob": "^7.2.0",
42
+ "html-minifier-terser": "^6.1.0",
43
43
  "parse5": "^6.0.1",
44
- "postcss": "^8.3.7",
44
+ "postcss": "^8.4.5",
45
45
  "postcss-load-config": "^3.1.0"
46
46
  }
47
47
  }
@@ -49,7 +49,8 @@ if (isServeOnly) {
49
49
  // Performance Observer and file watcher
50
50
  const globHTML = new Event.EventEmitter();
51
51
  const taskEmitter = new Event.EventEmitter();
52
- const start = performance.now();
52
+ let start = performance.now();
53
+ let addedHMR = false;
53
54
  let expectedTasks = 0; // This will be increased in globHandlers
54
55
  let finishedTasks = 0; // Current status
55
56
  taskEmitter.on("done", () => {
@@ -60,26 +61,13 @@ if (isServeOnly) {
60
61
  `🚀 Build finished in ${(performance.now() - start).toFixed(2)}ms ✨`
61
62
  );
62
63
 
63
- if (isHMR) {
64
+ if (isHMR && !addedHMR) {
65
+ addedHMR = true;
64
66
  if (file) {
65
67
  const postCSSWatcher = watch(file);
66
- postCSSWatcher.on("change", () => {
67
- console.log(" modified postcss.config – CSS will rebuild now.");
68
- const newConfig = createPostCSSConfig();
69
- plugins = newConfig.plugins;
70
- options = newConfig.options;
71
- CSSprocessor = postcss(plugins as AcceptedPlugin[]);
72
-
73
- glob(`${SOURCE_FOLDER}/**/*.css`, {}, (err, files) => {
74
- errorHandler(err);
75
- expectedTasks += files.length;
76
- for (const filename of files) {
77
- const [buildFilename, buildPathDir] = getBuildNames(filename);
78
- fs.mkdirSync(buildPathDir, { recursive: true });
79
- minifyCSS(filename, buildFilename);
80
- }
81
- });
82
- });
68
+ const tailwindCSSWatcher = watch(file.replace("postcss", "tailwind"));
69
+ postCSSWatcher.on("change", () => rebuildCSS("postcss"));
70
+ tailwindCSSWatcher.on("change", () => rebuildCSS("tailwind"));
83
71
  }
84
72
 
85
73
  console.log(`⌛ Waiting for file changes ...`);
@@ -89,6 +77,8 @@ if (isServeOnly) {
89
77
  let hasJSTS = false;
90
78
 
91
79
  watcher.on("add", (filename) => {
80
+ start = performance.now();
81
+ rebuildCSS();
92
82
  // Return if it was added by the build system itself
93
83
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
94
84
  return;
@@ -112,6 +102,8 @@ if (isServeOnly) {
112
102
  });
113
103
  });
114
104
  watcher.on("change", (filename) => {
105
+ start = performance.now();
106
+ rebuildCSS();
115
107
  // Return if it was changed by the build system itself
116
108
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
117
109
  return;
@@ -123,6 +115,7 @@ if (isServeOnly) {
123
115
  console.log(`⚡ modified ${buildFilename}`);
124
116
  });
125
117
  watcher.on("unlink", (filename) => {
118
+ start = performance.now();
126
119
  // Return if it was deleted by the build system itself
127
120
  if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
128
121
  return;
@@ -143,6 +136,25 @@ if (isServeOnly) {
143
136
  }
144
137
  });
145
138
 
139
+ function rebuildCSS(config?: string) {
140
+ start = performance.now();
141
+ if (config)
142
+ console.log(`⚡ modified ${config}.config – CSS will rebuild now.`);
143
+ const newConfig = createPostCSSConfig();
144
+ plugins = newConfig.plugins;
145
+ options = newConfig.options;
146
+ CSSprocessor = postcss(plugins as AcceptedPlugin[]);
147
+ glob(`${SOURCE_FOLDER}/**/*.css`, {}, (err, files) => {
148
+ errorHandler(err);
149
+ expectedTasks += files.length;
150
+ for (const filename of files) {
151
+ const [buildFilename, buildPathDir] = getBuildNames(filename);
152
+ fs.mkdirSync(buildPathDir, { recursive: true });
153
+ minifyCSS(filename, buildFilename);
154
+ }
155
+ });
156
+ }
157
+
146
158
  // Basic configuration
147
159
  const SOURCE_FOLDER = "src";
148
160
  const BUILD_FOLDER = "build";
@@ -318,8 +330,8 @@ if (isServeOnly) {
318
330
  taskEmitter.emit("done");
319
331
  globHTML.emit("getReady");
320
332
 
321
- if (serverSentEvents) {
322
- const changedFile = tsMaybeX2JS(file!);
333
+ if (serverSentEvents && file) {
334
+ const changedFile = tsMaybeX2JS(file);
323
335
  const [buildFilename] = getBuildNames(changedFile);
324
336
  const js = fs.readFileSync(buildFilename, { encoding: "utf8" });
325
337
  serverSentEvents({
@@ -427,7 +439,6 @@ if (isServeOnly) {
427
439
  base: buildDir,
428
440
  html: fileText,
429
441
  target: fileWithBase,
430
- minify: true,
431
442
  inline: !isCSP,
432
443
  extract: true,
433
444
  rebase: () => {},
package/tsconfig.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "target": "ESNext",
4
4
  "module": "ESNext",
5
5
  "lib": ["ESNext"],
6
- "outDir": "./esm",
6
+ "outDir": "./dist",
7
7
  "rootDir": "./src",
8
8
  "strict": true,
9
9
  "skipLibCheck": true,
package/cjs/bundle.js DELETED
@@ -1,696 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault =
4
- (this && this.__importDefault) ||
5
- function (mod) {
6
- return mod && mod.__esModule ? mod : { default: mod };
7
- };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- const fs_1 = __importDefault(require("fs"));
10
- const perf_hooks_1 = require("perf_hooks");
11
- const events_1 = __importDefault(require("events"));
12
- const glob_1 = __importDefault(require("glob"));
13
- const path_1 = __importDefault(require("path"));
14
- const fastify_1 = __importDefault(require("fastify"));
15
- const fastify_static_1 = __importDefault(require("fastify-static"));
16
- const postcss_1 = __importDefault(require("postcss"));
17
- const postcss_load_config_1 = __importDefault(require("postcss-load-config"));
18
- const cssnano_1 = __importDefault(require("cssnano"));
19
- const esbuild_1 = __importDefault(require("esbuild"));
20
- const critical_1 = __importDefault(require("critical"));
21
- const html_minifier_terser_1 = require("html-minifier-terser");
22
- const chokidar_1 = require("chokidar");
23
- const parse5_1 = require("parse5");
24
- const parse5_utils_1 = require("@web/parse5-utils");
25
- // CLI and options
26
- const isCritical = process.argv.includes("--critical");
27
- const isHMR = process.argv.includes("--hmr");
28
- const isCSP = process.argv.includes("--csp");
29
- const isSecure = process.argv.includes("--secure");
30
- const isServeOnly = process.argv.includes("--serveOnly");
31
- let fastify;
32
- if (isServeOnly) {
33
- createDefaultServer();
34
- fastify.listen(5000);
35
- console.log(`💻 Sever listening on port 5000.`);
36
- } else {
37
- process.env.NODE_ENV = isHMR ? "development" : "production";
38
- let { plugins, options, file } = createPostCSSConfig();
39
- let CSSprocessor = (0, postcss_1.default)(plugins);
40
- // Performance Observer and file watcher
41
- const globHTML = new events_1.default.EventEmitter();
42
- const taskEmitter = new events_1.default.EventEmitter();
43
- const start = perf_hooks_1.performance.now();
44
- let expectedTasks = 0; // This will be increased in globHandlers
45
- let finishedTasks = 0; // Current status
46
- taskEmitter.on("done", () => {
47
- finishedTasks++;
48
- if (finishedTasks === expectedTasks) {
49
- console.log(
50
- `🚀 Build finished in ${(
51
- perf_hooks_1.performance.now() - start
52
- ).toFixed(2)}ms ✨`
53
- );
54
- if (isHMR) {
55
- if (file) {
56
- const postCSSWatcher = (0, chokidar_1.watch)(file);
57
- postCSSWatcher.on("change", () => {
58
- console.log("⚡ modified postcss.config – CSS will rebuild now.");
59
- const newConfig = createPostCSSConfig();
60
- plugins = newConfig.plugins;
61
- options = newConfig.options;
62
- CSSprocessor = (0, postcss_1.default)(plugins);
63
- (0, glob_1.default)(
64
- `${SOURCE_FOLDER}/**/*.css`,
65
- {},
66
- (err, files) => {
67
- errorHandler(err);
68
- expectedTasks += files.length;
69
- for (const filename of files) {
70
- const [buildFilename, buildPathDir] = getBuildNames(filename);
71
- fs_1.default.mkdirSync(buildPathDir, { recursive: true });
72
- minifyCSS(filename, buildFilename);
73
- }
74
- }
75
- );
76
- });
77
- }
78
- console.log(`⌛ Waiting for file changes ...`);
79
- const watcher = (0, chokidar_1.watch)(SOURCE_FOLDER);
80
- // The add watcher will add all the files initially - do not rebuild them
81
- let initialAdd = 0;
82
- let hasJSTS = false;
83
- watcher.on("add", (filename) => {
84
- // Return if it was added by the build system itself
85
- if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
86
- return;
87
- }
88
- filename = String.raw`${filename}`.replace(/\\/g, "/");
89
- if (filename.endsWith(".html") || filename.endsWith(".css")) {
90
- initialAdd++;
91
- } else if (hasJSTS === false && /\.(j|t)sx?$/.test(filename)) {
92
- hasJSTS = true;
93
- initialAdd++;
94
- }
95
- if (initialAdd <= expectedTasks) return;
96
- const [buildFilename, buildPathDir] = getBuildNames(filename);
97
- fs_1.default.mkdir(buildPathDir, { recursive: true }, (err) => {
98
- errorHandler(err);
99
- rebuild(filename);
100
- console.log(`⚡ added ${buildFilename}`);
101
- });
102
- });
103
- watcher.on("change", (filename) => {
104
- // Return if it was changed by the build system itself
105
- if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
106
- return;
107
- }
108
- filename = String.raw`${filename}`.replace(/\\/g, "/");
109
- rebuild(filename);
110
- const [buildFilename] = getBuildNames(filename);
111
- console.log(`⚡ modified ${buildFilename}`);
112
- });
113
- watcher.on("unlink", (filename) => {
114
- // Return if it was deleted by the build system itself
115
- if (/-bundle-\d+\.(j|t)sx?$/.test(filename)) {
116
- return;
117
- }
118
- filename = String.raw`${filename}`.replace(/\\/g, "/");
119
- JSTSFiles.delete(filename);
120
- const [buildFilename, buildPathDir] = getBuildNames(filename);
121
- fs_1.default.rm(tsMaybeX2JS(buildFilename), (err) => {
122
- errorHandler(err);
123
- console.log(`⚡ deleted ${buildFilename}`);
124
- const length = fs_1.default.readdirSync(buildPathDir).length;
125
- if (!length) fs_1.default.rmdir(buildPathDir, errorHandler);
126
- });
127
- });
128
- }
129
- }
130
- });
131
- // Basic configuration
132
- const SOURCE_FOLDER = "src";
133
- const BUILD_FOLDER = "build";
134
- const TEMPLATE_LITERAL_MINIFIER = /\n\s+/g;
135
- const CONNECTIONS = []; // HMR
136
- let htmlTasks = 0;
137
- let serverSentEvents;
138
- if (isHMR) {
139
- fastify = (0, fastify_1.default)(
140
- isSecure
141
- ? {
142
- http2: true,
143
- https: {
144
- key: fs_1.default.readFileSync(
145
- path_1.default.join(process.cwd(), "localhost-key.pem")
146
- ),
147
- cert: fs_1.default.readFileSync(
148
- path_1.default.join(process.cwd(), "localhost.pem")
149
- ),
150
- },
151
- }
152
- : void 0
153
- );
154
- fastify.setNotFoundHandler((_req, reply) => {
155
- const file = fs_1.default.readFileSync(
156
- path_1.default.join(process.cwd(), BUILD_FOLDER, "/index.html"),
157
- {
158
- encoding: "utf-8",
159
- }
160
- );
161
- reply.header("Content-Type", "text/html; charset=UTF-8");
162
- return reply.send(addHMRCode(file, "build/index.html"));
163
- });
164
- fastify.register(fastify_static_1.default, {
165
- root: path_1.default.join(process.cwd(), BUILD_FOLDER),
166
- });
167
- fastify.get("/events", (_req, reply) => {
168
- reply.raw.setHeader("Content-Type", "text/event-stream");
169
- reply.raw.setHeader("Cache-Control", "no-cache");
170
- !isSecure && reply.raw.setHeader("Connection", "keep-alive");
171
- CONNECTIONS.push(reply.raw);
172
- serverSentEvents = (data) =>
173
- CONNECTIONS.forEach((rep) => {
174
- rep.write(`data: ${JSON.stringify(data)}\n\n`);
175
- });
176
- });
177
- }
178
- // THE BUNDLE CODE
179
- // Glob all files and transform the code
180
- (0, glob_1.default)(`${SOURCE_FOLDER}/**/*.html`, {}, (err, files) => {
181
- errorHandler(err);
182
- expectedTasks += files.length;
183
- htmlTasks += files.length;
184
- if (isHMR) {
185
- createHMRHandlers(files);
186
- fastify.listen(5000);
187
- console.log(`💻 Sever listening on port 5000.`);
188
- }
189
- });
190
- (0, glob_1.default)(`${SOURCE_FOLDER}/**/*.css`, {}, (err, files) => {
191
- errorHandler(err);
192
- expectedTasks += files.length;
193
- for (const filename of files) {
194
- const [buildFilename, buildPathDir] = getBuildNames(filename);
195
- fs_1.default.mkdirSync(buildPathDir, { recursive: true });
196
- minifyCSS(filename, buildFilename);
197
- }
198
- });
199
- const JSTSFiles = new Set();
200
- (0, glob_1.default)(
201
- `${SOURCE_FOLDER}/**/!(*.d).{ts,js,tsx,jsx}`,
202
- {},
203
- (err, files) => {
204
- errorHandler(err);
205
- if (files.length) {
206
- expectedTasks += 1;
207
- } else {
208
- globHTML.emit("getReady");
209
- }
210
- files.forEach((file) => JSTSFiles.add(file));
211
- minifyTSJS().catch(errorHandler);
212
- }
213
- );
214
- globHTML.on("getReady", () => {
215
- if (expectedTasks - htmlTasks === finishedTasks) {
216
- // After CSS and JS because critical needs file built css files and inline script might reference js files.
217
- (0, glob_1.default)(
218
- `${SOURCE_FOLDER}/**/*.html`,
219
- {},
220
- async (err, files) => {
221
- errorHandler(err);
222
- await createGlobalJS(files);
223
- files.forEach((filename) => {
224
- const [buildFilename, buildPathDir] = getBuildNames(filename);
225
- fs_1.default.mkdirSync(buildPathDir, { recursive: true });
226
- minifyHTML(filename, buildFilename);
227
- });
228
- }
229
- );
230
- }
231
- });
232
- function createGlobalJS(files) {
233
- const scriptFilenames = [];
234
- files.forEach((filename) => {
235
- const fileText = fs_1.default.readFileSync(filename, {
236
- encoding: "utf-8",
237
- });
238
- let DOM;
239
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
240
- DOM = (0, parse5_1.parse)(fileText);
241
- } else {
242
- DOM = (0, parse5_1.parseFragment)(fileText);
243
- }
244
- const scripts = (0, parse5_utils_1.findElements)(
245
- DOM,
246
- (e) => (0, parse5_utils_1.getTagName)(e) === "script"
247
- );
248
- scripts.forEach((script, index) => {
249
- const scriptTextNode = script.childNodes[0];
250
- const isReferencedScript = script.attrs.find((a) => a.name === "src");
251
- //@ts-ignore
252
- const scriptContent =
253
- scriptTextNode === null || scriptTextNode === void 0
254
- ? void 0
255
- : scriptTextNode.value;
256
- if (!scriptContent || isReferencedScript) return;
257
- const jsFilename = filename.replace(".html", `-bundle-${index}.js`);
258
- scriptFilenames.push(jsFilename);
259
- fs_1.default.writeFileSync(jsFilename, scriptContent);
260
- });
261
- });
262
- scriptFilenames.forEach((file) => JSTSFiles.add(file));
263
- return minifyTSJS(true)
264
- .catch(console.error)
265
- .finally(() =>
266
- scriptFilenames.forEach((file) => {
267
- JSTSFiles.delete(file);
268
- try {
269
- fs_1.default.rmSync(file);
270
- } catch (_a) {}
271
- })
272
- );
273
- }
274
- function minifyTSJS(isInline = false, file) {
275
- return esbuild_1
276
- .build({
277
- entryPoints: Array.from(JSTSFiles),
278
- charset: "utf8",
279
- format: "esm",
280
- incremental: isHMR,
281
- sourcemap: isHMR,
282
- splitting: true,
283
- define: {
284
- "process.env.NODE_ENV": isHMR ? '"development"' : '"production"',
285
- },
286
- loader: { ".js": "jsx", ".ts": "tsx" },
287
- bundle: true,
288
- minify: true,
289
- outdir: BUILD_FOLDER,
290
- outbase: SOURCE_FOLDER,
291
- })
292
- .then(() => {
293
- if (!isInline) {
294
- taskEmitter.emit("done");
295
- globHTML.emit("getReady");
296
- if (serverSentEvents) {
297
- const changedFile = tsMaybeX2JS(file);
298
- const [buildFilename] = getBuildNames(changedFile);
299
- const js = fs_1.default.readFileSync(buildFilename, {
300
- encoding: "utf8",
301
- });
302
- serverSentEvents({
303
- js,
304
- filename: buildFilename.split(`${BUILD_FOLDER}/`).pop(),
305
- });
306
- }
307
- }
308
- });
309
- }
310
- function minifyCSS(filename, buildFilename) {
311
- const fileText = fs_1.default.readFileSync(filename, { encoding: "utf-8" });
312
- return CSSprocessor.process(
313
- fileText,
314
- Object.assign(Object.assign({}, options), {
315
- from: filename,
316
- to: buildFilename,
317
- })
318
- )
319
- .then((result) => {
320
- fs_1.default.writeFileSync(buildFilename, result.css);
321
- taskEmitter.emit("done");
322
- globHTML.emit("getReady");
323
- if (serverSentEvents) {
324
- serverSentEvents({
325
- css: result.css,
326
- filename: buildFilename.split(`${BUILD_FOLDER}/`).pop(),
327
- });
328
- }
329
- })
330
- .catch((err) => {
331
- console.error(err);
332
- });
333
- }
334
- async function minifyHTML(filename, buildFilename) {
335
- let fileText = fs_1.default.readFileSync(filename, { encoding: "utf-8" });
336
- let DOM;
337
- if (fileText.includes("<!DOCTYPE html>") || fileText.includes("<html")) {
338
- DOM = (0, parse5_1.parse)(fileText);
339
- } else {
340
- DOM = (0, parse5_1.parseFragment)(fileText);
341
- }
342
- // Minify Code
343
- const scripts = (0, parse5_utils_1.findElements)(
344
- DOM,
345
- (e) => (0, parse5_utils_1.getTagName)(e) === "script"
346
- );
347
- scripts.forEach((script, index) => {
348
- const scriptTextNode = script.childNodes[0];
349
- const isReferencedScript = script.attrs.find((a) => a.name === "src");
350
- //@ts-ignore
351
- if (
352
- !(scriptTextNode === null || scriptTextNode === void 0
353
- ? void 0
354
- : scriptTextNode.value) ||
355
- isReferencedScript
356
- )
357
- return;
358
- // Use bundled file and remove it from fs
359
- const bundledFilename = buildFilename.replace(
360
- ".html",
361
- `-bundle-${index}.js`
362
- );
363
- try {
364
- const scriptContent = fs_1.default.readFileSync(bundledFilename, {
365
- encoding: "utf-8",
366
- });
367
- fs_1.default.rmSync(bundledFilename);
368
- // Replace src with bundled code
369
- //@ts-ignore
370
- scriptTextNode.value = scriptContent.replace(
371
- TEMPLATE_LITERAL_MINIFIER,
372
- " "
373
- );
374
- } catch (_a) {}
375
- });
376
- // Minify Inline Style
377
- const styles = (0, parse5_utils_1.findElements)(
378
- DOM,
379
- (e) => (0, parse5_utils_1.getTagName)(e) === "style"
380
- );
381
- for (const style of styles) {
382
- const node = style.childNodes[0];
383
- //@ts-ignore
384
- const styleContent =
385
- node === null || node === void 0 ? void 0 : node.value;
386
- if (!styleContent) continue;
387
- const { css } = await CSSprocessor.process(
388
- styleContent,
389
- Object.assign(Object.assign({}, options), { from: undefined })
390
- );
391
- //@ts-ignore
392
- node.value = css;
393
- }
394
- fileText = (0, parse5_1.serialize)(DOM);
395
- // Minify HTML
396
- fileText = await (0, html_minifier_terser_1.minify)(fileText, {
397
- collapseWhitespace: true,
398
- removeComments: true,
399
- });
400
- if (isCritical) {
401
- const buildFilenameArr = buildFilename.split("/");
402
- const fileWithBase = buildFilenameArr.pop();
403
- const buildDir = buildFilenameArr.join("/");
404
- // critical is generating the files on the fs
405
- return critical_1.default
406
- .generate({
407
- base: buildDir,
408
- html: fileText,
409
- target: fileWithBase,
410
- minify: true,
411
- inline: !isCSP,
412
- extract: true,
413
- rebase: () => {},
414
- })
415
- .then(({ html }) => {
416
- taskEmitter.emit("done");
417
- if (serverSentEvents) {
418
- serverSentEvents({
419
- html: addHMRCode(html, buildFilename),
420
- filename: buildFilename,
421
- });
422
- }
423
- })
424
- .catch((err) => {
425
- console.error(err);
426
- });
427
- } else {
428
- fs_1.default.writeFileSync(buildFilename, fileText);
429
- taskEmitter.emit("done");
430
- if (serverSentEvents) {
431
- serverSentEvents({
432
- html: addHMRCode(fileText, buildFilename),
433
- filename: buildFilename,
434
- });
435
- }
436
- }
437
- }
438
- // Helper functions from here
439
- function createPostCSSConfig() {
440
- try {
441
- return postcss_load_config_1.default.sync({});
442
- } catch (_a) {
443
- return { plugins: [cssnano_1.default], options: {}, file: "" };
444
- }
445
- }
446
- function getBuildNames(filename) {
447
- const buildFilename = filename.replace(
448
- `${SOURCE_FOLDER}/`,
449
- `${BUILD_FOLDER}/`
450
- );
451
- const buildFilenameArr = buildFilename.split("/");
452
- buildFilenameArr.pop();
453
- const buildPathDir = buildFilenameArr.join("/");
454
- return [buildFilename, buildPathDir];
455
- }
456
- async function rebuild(filename) {
457
- const [buildFilename] = getBuildNames(filename);
458
- if (/\.(j|t)sx?$/.test(filename)) {
459
- JSTSFiles.add(filename);
460
- } else if (filename.endsWith(".css")) {
461
- await minifyCSS(filename, buildFilename);
462
- }
463
- (0, glob_1.default)(
464
- `${SOURCE_FOLDER}/**/*.html`,
465
- {},
466
- async (err, files) => {
467
- errorHandler(err);
468
- await createGlobalJS(files);
469
- if (filename.endsWith(".html")) {
470
- minifyHTML(filename, buildFilename);
471
- } else if (
472
- /\.(j|t)sx?$/.test(filename) ||
473
- (filename.endsWith(".css") && isCritical)
474
- ) {
475
- for (const htmlFilename of files) {
476
- const [htmlBuildFilename] = getBuildNames(htmlFilename);
477
- await minifyHTML(htmlFilename, htmlBuildFilename);
478
- }
479
- if (/\.(j|t)sx?$/.test(filename) && serverSentEvents) {
480
- const jsFile = tsMaybeX2JS(buildFilename);
481
- try {
482
- // Do not try to send empty files
483
- serverSentEvents({
484
- js: fs_1.default.readFileSync(jsFile, { encoding: "utf-8" }),
485
- filename: jsFile.split(`${BUILD_FOLDER}/`).pop(),
486
- });
487
- } catch (_a) {}
488
- }
489
- }
490
- }
491
- );
492
- }
493
- const getHMRCode = (
494
- filename,
495
- id
496
- ) => `import { render, html, setShouldSetReactivity, $$, setGlobalSchedule, setInsertDiffing } from "https://unpkg.com/hydro-js/dist/library.js";
497
-
498
- if (!window.eventsource${id}) {
499
- setGlobalSchedule(false);
500
- setShouldSetReactivity(false);
501
-
502
- window.eventsource${id} = new EventSource("/events");
503
- window.eventsource${id}.addEventListener("message", ({ data }) => {
504
- const dataObj = JSON.parse(data);
505
-
506
- if ("html" in dataObj && "${filename}" === dataObj.filename) {
507
- setInsertDiffing(true);
508
-
509
- let newHTML;
510
- let isBody;
511
-
512
- if (dataObj.html.startsWith('<!DOCTYPE html>') || dataObj.html.startsWith('<html')) {
513
- newHTML = html\`\${dataObj.html}\`;
514
- } else {
515
- newHTML = html\`<body>\${dataObj.html}</body>\`
516
- isBody = true
517
- }
518
-
519
- if (isBody) {
520
- const hmrID = "${id}";
521
- const hmrElems = Array.from(newHTML.childNodes);
522
- const hmrWheres = Array.from($$(\`[data-hmr="\${hmrID}"]\`))
523
- // Render new Elements in old Elements, also remove rest old Elements and add add new elements after the last old one
524
- hmrWheres.forEach((where, index) => {
525
- if (index < hmrElems.length) {
526
- render(hmrElems[index], where);
527
- } else {
528
- where.remove();
529
- }
530
- });
531
- for (let rest = hmrWheres.length; rest < hmrElems.length; rest++) {
532
- if (hmrWheres.length) {
533
- const template = document.createElement('template');
534
- hmrElems[hmrWheres.length - 1].after(template);
535
- render(hmrElems[rest], template);
536
- template.remove();
537
- } else {
538
- render(hmrElems[rest])
539
- }
540
- }
541
- } else {
542
- const oldElementCount = document.body.querySelectorAll('*').length;
543
- render(newHTML, document.documentElement);
544
- const newElementCount = document.body.querySelectorAll('*').length;
545
-
546
- // Looks like JS did not reload? Last resort - hard refresh
547
- if (newElementCount < 5 && Math.abs(newElementCount - oldElementCount) > 10) {
548
- location.reload()
549
- }
550
- }
551
- setInsertDiffing(false);
552
- if (dataObj.filename === 'build/index.html') {
553
- dispatchEvent(new Event("popstate"));
554
- }
555
- } else if ("css" in dataObj) {
556
- window.onceEveryXTime(100, window.updateCSS, [updateAttr]);
557
- } else if ("js" in dataObj) {
558
- window.onceEveryXTime(100, window.updateJS, [updateAttr]);
559
- }
560
-
561
- function updateAttr (attr, forceUpdate = false) {
562
- return (elem) => {
563
- const attrValue = elem[attr].replace(/\\?v=.*/, "");
564
- if (forceUpdate || attrValue.endsWith(dataObj.filename)) {
565
- elem[attr] = \`\${attrValue}?v=\${Math.random().toFixed(4)}\`;
566
- } else if (elem.localName === 'script' && !elem.src && new RegExp(\`["']\${dataObj.filename}["']\`).test(elem.textContent)) {
567
- elem.setAttribute('data-inline', String(Math.random().toFixed(4)).slice(2));
568
- }
569
- }
570
- };
571
- });
572
-
573
- if (!window.updateCSS) {
574
- window.updateCSS = function updateCSS(updateAttr) {
575
- $$('link').forEach(updateAttr("href"));
576
- window.fnToLastCalled.set(window.updateCSS, performance.now())
577
- }
578
- }
579
- if (!window.updateJS) {
580
- window.updateJS = function updateJS(updateAttr) {
581
- window.fnToLastCalled.set(window.updateJS, performance.now());
582
- const copy = html\`\${document.documentElement.outerHTML}\`;
583
- copy.querySelectorAll('script').forEach(updateAttr("src"));
584
- render(copy, document.documentElement);
585
- }
586
- }
587
- if (!window.fnToLastCalled) {
588
- window.fnToLastCalled = new Map();
589
- }
590
- if (!window.onceEveryXTime) {
591
- window.onceEveryXTime = function (time, fn, params) {
592
- if (!window.fnToLastCalled.has(fn) || performance.now() - window.fnToLastCalled.get(fn) > time) {
593
- fn(...params)
594
- }
595
- }
596
- }
597
- }`;
598
- function randomText() {
599
- return Math.random().toString(32).slice(2);
600
- }
601
- const htmlIdMap = new Map();
602
- function addHMRCode(html, filename) {
603
- if (!htmlIdMap.has(filename)) {
604
- htmlIdMap.set(filename, randomText());
605
- }
606
- const script = (0, parse5_utils_1.createScript)(
607
- { type: "module" },
608
- getHMRCode(filename, htmlIdMap.get(filename))
609
- );
610
- let ast;
611
- if (html.includes("<!DOCTYPE html>") || html.includes("<html")) {
612
- ast = (0, parse5_1.parse)(html);
613
- const headNode = (0, parse5_utils_1.findElement)(
614
- ast,
615
- (e) => (0, parse5_utils_1.getTagName)(e) === "head"
616
- );
617
- (0, parse5_utils_1.appendChild)(headNode, script);
618
- } else {
619
- ast = (0, parse5_1.parseFragment)(html);
620
- (0, parse5_utils_1.appendChild)(ast, script);
621
- ast.childNodes.forEach((node) => {
622
- var _a;
623
- //@ts-ignore
624
- return (_a = node.attrs) === null || _a === void 0
625
- ? void 0
626
- : _a.push({ name: "data-hmr", value: htmlIdMap.get(filename) });
627
- });
628
- }
629
- // Burst CSS cache
630
- (0, parse5_utils_1.findElements)(
631
- ast,
632
- (e) => (0, parse5_utils_1.getTagName)(e) === "link"
633
- ).forEach((link) => {
634
- const href = link.attrs.find((attr) => attr.name === "href");
635
- const rel = link.attrs.find((attr) => attr.name === "rel");
636
- if (rel.value === "stylesheet") {
637
- href.value += `?v=${Math.random().toFixed(4)}`;
638
- }
639
- });
640
- return (0, parse5_1.serialize)(ast);
641
- }
642
- function createHMRHandlers(files) {
643
- files.forEach((filename) => {
644
- const newFilename = "/" + filename.replace(/src\//, "");
645
- const filePath = newFilename.split("/");
646
- const endName = filePath.pop();
647
- if (endName.endsWith("index.html")) {
648
- //@ts-ignore
649
- fastify.get(filePath.join("/") + "/", HMRHandler);
650
- }
651
- //@ts-ignore
652
- fastify.get(newFilename, HMRHandler);
653
- });
654
- }
655
- function HMRHandler(request, reply) {
656
- let filename = request.url;
657
- if (filename.endsWith("/")) {
658
- filename += "index.html";
659
- }
660
- filename = BUILD_FOLDER + filename;
661
- const file = fs_1.default.readFileSync(filename, {
662
- encoding: "utf-8",
663
- });
664
- reply.header("Content-Type", "text/html; charset=UTF-8");
665
- return reply.send(addHMRCode(file, filename));
666
- }
667
- function errorHandler(err) {
668
- if (err) {
669
- console.error(err);
670
- process.exit(1);
671
- }
672
- }
673
- function tsMaybeX2JS(filename) {
674
- return filename.replace(".ts", ".js").replace(".jsx", ".js");
675
- }
676
- }
677
- function createDefaultServer(BUILD_FOLDER = "build") {
678
- fastify = (0, fastify_1.default)(
679
- isSecure
680
- ? {
681
- http2: true,
682
- https: {
683
- key: fs_1.default.readFileSync(
684
- path_1.default.join(process.cwd(), "localhost-key.pem")
685
- ),
686
- cert: fs_1.default.readFileSync(
687
- path_1.default.join(process.cwd(), "localhost.pem")
688
- ),
689
- },
690
- }
691
- : void 0
692
- );
693
- fastify.register(fastify_static_1.default, {
694
- root: path_1.default.join(process.cwd(), BUILD_FOLDER),
695
- });
696
- }
package/tsconfig.cjs.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "module": "CommonJS",
5
- "lib": ["ES2017"],
6
- "outDir": "./cjs",
7
- "rootDir": "./src",
8
- "strict": true,
9
- "skipLibCheck": true,
10
- "moduleResolution": "node",
11
- "esModuleInterop": true,
12
- "forceConsistentCasingInFileNames": true,
13
- "typeRoots": ["node_modules/@types"]
14
- },
15
- "include": ["src", "types"]
16
- }