hexo-offline 3.0.0 → 5.0.0

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 CHANGED
@@ -30,13 +30,45 @@ While hexo-offline aims to provide zero-config offline enhancement to your hexo
30
30
  // offline config passed to workbox-build.
31
31
  module.exports = {
32
32
  globPatterns: ["**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}"],
33
- globDirectory: "/path/to/hexo/public",
34
- swDest: "/path/to/hexo/service-worker.js",
35
- },
33
+ };
36
34
  ```
37
35
 
38
36
  Again, the config is demo only and you don't have to copy and paste if you serves all contents from the origin server.
39
37
 
38
+ `globPatterns` and the other glob options are matched against the files Hexo generates, relative to the public folder. The service worker is always generated as `service-worker.js` in the public folder, so `globDirectory` and `swDest` are not supported.
39
+
40
+ ### How it works
41
+
42
+ hexo-offline runs when Hexo generates the site, after every page has been rendered and before the files are written to the public folder. It adds `service-worker.js` and the Workbox runtime to the generated files and injects the register script into `index.html`, so they are written and deployed like any other generated file, including with `hexo generate --deploy`.
43
+
44
+ The service worker is generated whenever the site is generated for publishing: `hexo generate`, `hexo generate --deploy`, `hexo deploy --generate`, or a plain `hexo deploy` when there is no public folder yet. A plain `hexo deploy` with an existing public folder deploys it as it is. The service worker is not generated by `hexo server` or `hexo generate --watch` (or while Hexo watches for changes through its API), so local previews don't install one. Because `hexo generate --watch` writes the public folder without the service worker (and removes one generated earlier), run `hexo generate` again before deploying.
45
+
46
+ To try the service worker locally, run `hexo generate` and serve the public folder on a different port from the one you use for `hexo server`, for example `hexo server --static --port 4001`. A service worker installed on a port keeps serving its cached pages there until it is unregistered in the browser's developer tools.
47
+
48
+ ### Upgrading from v4
49
+
50
+ - `globDirectory` and `swDest` are no longer supported and are ignored with a warning. Remove them from `hexo-offline.config.cjs`.
51
+ - The service worker is now generated together with the rest of the site, so `hexo generate --deploy` and `hexo deploy --generate` deploy it. You no longer need to run `hexo generate` and `hexo deploy` separately.
52
+ - `hexo server` and `hexo generate --watch` no longer generate a service worker.
53
+ - `skipWaiting` and `clientsClaim` now default to `true`. See [Updating to new content](#updating-to-new-content).
54
+ - Node.js ^20.17.0 or >=22.5.0 is required.
55
+ - Run `hexo clean` once after upgrading, so the files v4 wrote directly to the public folder (such as an old `workbox-*.js`) are removed.
56
+
57
+ ### Updating to new content
58
+
59
+ By default hexo-offline sets `skipWaiting: true` and `clientsClaim: true`, so a newly deployed service worker takes over as soon as it is installed. After you deploy, the first page view may still show the cached content. The new service worker downloads the updated files in the background, and once it has finished installing, the next refresh or visit shows the new content.
60
+
61
+ A page that is already open when the new service worker takes over keeps its old HTML, but any files it requests afterwards come from the new version. If a deploy renames or significantly changes theme scripts or styles, such a page may look or behave oddly until it is reloaded.
62
+
63
+ To keep Workbox's default behaviour, where a new service worker waits until every tab of the site is closed, set both options to `false` in `hexo-offline.config.cjs`. If the file already exists, add them to the object it already exports rather than adding a second `module.exports`:
64
+
65
+ ```js
66
+ module.exports = {
67
+ skipWaiting: false,
68
+ clientsClaim: false,
69
+ };
70
+ ```
71
+
40
72
  ### What if content is served via CDN?
41
73
 
42
74
  Suppose that you have used two CDN scripts:
@@ -61,7 +93,7 @@ module.exports = {
61
93
  handler: "CacheFirst"
62
94
  }
63
95
  ]
64
- },
96
+ };
65
97
  ```
66
98
 
67
99
  For more information, see [Workbox Runtime Caching Entry](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build?hl=en#.RuntimeCachingEntry).
package/lib/index.js CHANGED
@@ -4,4 +4,6 @@ var _lib = _interopRequireDefault(require("./lib"));
4
4
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
5
5
  /* global hexo */
6
6
 
7
- hexo.extend.filter.register("before_exit", _lib.default);
7
+ // Run after other after_generate filters (default priority 10), so files they
8
+ // modify are precached with their final content.
9
+ hexo.extend.filter.register("after_generate", _lib.default, 100);
package/lib/lib/index.js CHANGED
@@ -4,10 +4,85 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = _default;
7
- var _runWorkboxBuild = _interopRequireDefault(require("./run-workbox-build"));
8
- var _injectSwRegister = _interopRequireDefault(require("./inject-sw-register"));
7
+ var _loadConfig = _interopRequireDefault(require("./load-config.js"));
8
+ var _injectSwRegister = _interopRequireDefault(require("./inject-sw-register.js"));
9
+ var _readRoute = _interopRequireDefault(require("./read-route.js"));
10
+ var _runWorkboxBuild = _interopRequireDefault(require("./run-workbox-build.js"));
9
11
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
+ // Only build the service worker when the site is generated for publishing:
13
+ // `hexo generate` and `hexo deploy`, or Hexo used through its API (no command).
14
+ // Skipped for `hexo server`, so local previews are not cached by a service
15
+ // worker, and for commands like `hexo list` that load the site without
16
+ // writing it.
17
+ function isPublishCommand(hexo) {
18
+ const cmd = hexo.env?.cmd;
19
+ if (!cmd) {
20
+ return true;
21
+ }
22
+ const name = cmd.toLowerCase();
23
+ const alias = hexo.extend?.console?.alias ?? {};
24
+ return ["generate", "deploy"].includes(alias[name] ?? name);
25
+ }
26
+
27
+ // `hexo generate --watch`, or Hexo watching through its API (`hexo.watch()`,
28
+ // also used by hexo-server), which sets `_watchBox` (Hexo 5 to 8) until
29
+ // `hexo.unwatch()`.
30
+ function isWatching(hexo) {
31
+ const args = hexo.env?.args ?? {};
32
+ return Boolean(args.w || args.watch || hexo._watchBox != null);
33
+ }
34
+
35
+ // The limit from `hexo generate --concurrency <n>` (or `-c <n>`), if given.
36
+ function getConcurrency(hexo) {
37
+ const args = hexo.env?.args ?? {};
38
+ const value = Number.parseInt(args.c ?? args.concurrency, 10);
39
+ return value > 0 ? value : undefined;
40
+ }
41
+
42
+ // Hexo instances already warned about watch mode (the filter runs on every
43
+ // change while watching).
44
+ const warnedAboutWatch = new WeakSet();
45
+
46
+ // after_generate filter: runs once Hexo has built every route and before the
47
+ // routes are written to the public folder (and before `hexo g -d` deploys).
10
48
  async function _default() {
11
- await _runWorkboxBuild.default.call(this);
12
- return (0, _injectSwRegister.default)(this.public_dir);
49
+ if (!isPublishCommand(this)) {
50
+ return;
51
+ }
52
+ const {
53
+ route,
54
+ log: logger
55
+ } = this;
56
+ // `hexo generate --watch` writes the public folder without the service
57
+ // worker, so warn that it needs a regular build before deploying.
58
+ if (isWatching(this)) {
59
+ if (!warnedAboutWatch.has(this)) {
60
+ warnedAboutWatch.add(this);
61
+ logger.warn("hexo-offline: the service worker is not generated in watch mode, and Hexo removes the previously generated one from the public folder. Run `hexo generate` before deploying.");
62
+ }
63
+ return;
64
+ }
65
+ if (!route.list().includes("index.html")) {
66
+ return;
67
+ }
68
+ let indexHTML;
69
+ try {
70
+ indexHTML = await (0, _readRoute.default)(route, "index.html");
71
+ } catch {
72
+ // Leave the route alone: Hexo reports the error when it writes it.
73
+ logger.warn("hexo-offline: not generating the service worker because index.html failed to generate.");
74
+ return;
75
+ }
76
+ const config = (0, _loadConfig.default)(this);
77
+ // Inject before building, so index.html is precached with the script.
78
+ route.set("index.html", (0, _injectSwRegister.default)(indexHTML.toString()));
79
+ try {
80
+ // Don't return the result: after_generate filters pass their return value
81
+ // on to the next filter.
82
+ await (0, _runWorkboxBuild.default)(route, logger, config, this.public_dir, getConcurrency(this));
83
+ } catch (err) {
84
+ // Don't leave index.html registering a service worker that wasn't built.
85
+ route.set("index.html", indexHTML);
86
+ throw err;
87
+ }
13
88
  }
@@ -3,30 +3,19 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.default = void 0;
6
+ exports.default = injectSWRegister;
7
7
  var _fs = _interopRequireDefault(require("fs"));
8
8
  var _path = _interopRequireDefault(require("path"));
9
9
  var _constants = require("./constants.js");
10
10
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
11
  const template = _fs.default.readFileSync(_path.default.join(__dirname, "./template.js"), "utf-8");
12
- const helperSWRegister = function () {
13
- const registerContent = template.replace("__workerName__", _constants.workerName);
14
- return `<script>${registerContent}</script>`;
15
- };
16
- const injectSWRegisterWithContent = script => publicDir => {
17
- const indexHTMLPath = _path.default.join(publicDir, "index.html");
12
+ const script = `<script>${template.replace("__workerName__", _constants.workerName)}</script>`;
18
13
 
19
- // early return when no index.html presets in public directory
20
- if (!_fs.default.existsSync(indexHTMLPath)) {
21
- return;
14
+ // Insert the service worker register script before the closing </body></html>.
15
+ function injectSWRegister(html) {
16
+ // return as-is if it has been injected before
17
+ if (html.includes(`${script}</body></html>`)) {
18
+ return html;
22
19
  }
23
- const fileContent = _fs.default.readFileSync(indexHTMLPath, "utf-8");
24
-
25
- // early return if it has been injected before
26
- if (fileContent.includes(`${script}</body></html>`)) {
27
- return;
28
- }
29
- const injectedContent = fileContent.replace(/<\/body>\s*<\/html>\s*$/, `${script}</body></html>`);
30
- _fs.default.writeFileSync(indexHTMLPath, injectedContent);
31
- };
32
- var _default = exports.default = injectSWRegisterWithContent(helperSWRegister());
20
+ return html.replace(/<\/body>\s*<\/html>\s*$/, `${script}</body></html>`);
21
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = loadConfig;
7
+ var _fs = _interopRequireDefault(require("fs"));
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _constants = require("./constants.js");
10
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
+ // Options that no longer apply: the service worker is built from Hexo's
12
+ // generated routes and always emitted as a route named `workerName`.
13
+ const removedOptions = ["globDirectory", "swDest"];
14
+ function loadConfig({
15
+ base_dir: baseDir,
16
+ config,
17
+ log: logger
18
+ }) {
19
+ let offline;
20
+ if (config && "offline" in config) {
21
+ logger.warn(`
22
+ Starting from hexo-offline v2 the 'offline' config in _config.yaml is
23
+ deprecated. Please create 'hexo-offline.config.cjs' in hexo root directory.
24
+ See https://github.com/JLHwung/hexo-offline#usage for more info.
25
+ `);
26
+ offline = config.offline;
27
+ }
28
+
29
+ // A missing config file is fine. If it exists but fails to load, report it
30
+ // and still generate a service worker without it, rather than shipping a
31
+ // site without an up-to-date worker.
32
+ const configPath = _path.default.resolve(baseDir, "hexo-offline.config.cjs");
33
+ try {
34
+ if (_fs.default.existsSync(configPath)) {
35
+ // Re-read the config file itself (not modules it requires) on every
36
+ // build in a long-running process.
37
+ delete require.cache[require.resolve(configPath)];
38
+ offline = require(configPath);
39
+ }
40
+ } catch (err) {
41
+ logger.error(`hexo-offline: ignoring ${configPath} because it failed to load:\n${err?.stack ?? String(err)}`);
42
+ }
43
+ if (offline == null) {
44
+ return {};
45
+ }
46
+ if (typeof offline !== "object") {
47
+ logger.warn(`hexo-offline: ignoring the offline config because it is not an object.`);
48
+ return {};
49
+ }
50
+ const ignored = removedOptions.filter(key => key in offline);
51
+ if (ignored.length > 0) {
52
+ logger.warn(`hexo-offline: ignoring ${ignored.map(key => `'${key}'`).join(" and ")}. ` + `Since hexo-offline v5 the service worker is built from the files Hexo ` + `generates and is always written to '${_constants.workerName}' in the public folder.`);
53
+ offline = {
54
+ ...offline
55
+ };
56
+ for (const key of ignored) {
57
+ delete offline[key];
58
+ }
59
+ }
60
+ return offline;
61
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = readRoute;
7
+ // Read the full content of a Hexo route into a Buffer.
8
+ function readRoute(route, routePath) {
9
+ return new Promise((resolve, reject) => {
10
+ const stream = route.get(routePath);
11
+ if (!stream) {
12
+ reject(new Error(`Route not found: ${routePath}`));
13
+ return;
14
+ }
15
+ const chunks = [];
16
+ stream.on("data", chunk => {
17
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
18
+ });
19
+ stream.on("end", () => resolve(Buffer.concat(chunks)));
20
+ stream.on("error", reject);
21
+ });
22
+ }
@@ -5,21 +5,17 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = runWorkboxBuild;
7
7
  var _fs = _interopRequireDefault(require("fs"));
8
+ var _os = _interopRequireDefault(require("os"));
8
9
  var _path = _interopRequireDefault(require("path"));
9
10
  var _workboxBuild = require("workbox-build");
10
- var _constants = require("./constants");
11
+ var _constants = require("./constants.js");
12
+ var _readRoute = _interopRequireDefault(require("./read-route.js"));
11
13
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
- function generateSWPrecacheConfig({
13
- publicDir
14
- }, extraWorkboxBuildConfig) {
15
- const hexoPublicDir = publicDir;
16
- return {
17
- globPatterns: ["**/*.{js,mjs,html,css,png,jpg,gif,webp,svg,eot,ttf,woff,woff2}"],
18
- globDirectory: hexoPublicDir,
19
- swDest: _path.default.join(publicDir, _constants.workerName),
20
- ...extraWorkboxBuildConfig
21
- };
22
- }
14
+ const defaultGlobPatterns = ["**/*.{js,mjs,html,css,png,jpg,gif,webp,svg,eot,ttf,woff,woff2}"];
15
+
16
+ // How many routes are read and copied at the same time, unless Hexo is run
17
+ // with --concurrency.
18
+ const defaultConcurrency = 16;
23
19
  function formatNumber(number) {
24
20
  try {
25
21
  return new Intl.NumberFormat().format(number);
@@ -27,45 +23,179 @@ function formatNumber(number) {
27
23
  return number;
28
24
  }
29
25
  }
26
+
27
+ // Name the public folder rather than the temporary copy that was globbed.
28
+ // Some warnings embed the path JSON-encoded, which escapes "\" on Windows.
29
+ function replaceGlobDirectory(warning, globDirectory, publicDir) {
30
+ if (!publicDir) {
31
+ return warning;
32
+ }
33
+ // Hexo's public_dir ends with a separator; globDirectory doesn't.
34
+ const target = publicDir.replace(/[\\/]+$/, "");
35
+ const json = value => JSON.stringify(value).slice(1, -1);
36
+ // Replace with functions, so "$" in the path is not a replacement pattern.
37
+ return warning.replaceAll(json(globDirectory), () => json(target)).replaceAll(globDirectory, () => target);
38
+ }
30
39
  function printSWResult({
31
40
  count,
32
41
  size,
33
42
  warnings
34
- }, logger) {
43
+ }, logger, globDirectory, publicDir) {
35
44
  for (const warning of warnings) {
36
- logger.warn(warnings);
45
+ logger.warn(replaceGlobDirectory(warning, globDirectory, publicDir));
37
46
  }
38
47
  logger.info(`Generated manifests for ${formatNumber(count)} files. Total size: ${formatNumber(size)} bytes.`);
39
48
  }
40
- async function runWorkboxBuild() {
41
- const {
42
- public_dir: publicDir,
43
- base_dir: baseDir,
44
- config,
45
- log: logger
46
- } = this;
47
49
 
48
- // early return when no index.html presets in public directory
49
- const indexHTMLPath = _path.default.join(publicDir, "index.html");
50
- if (!_fs.default.existsSync(indexHTMLPath)) {
51
- return Promise.resolve();
50
+ // The glob patterns workbox-build will match against globDirectory, in a form
51
+ // that can be matched against route paths: `precache` for globPatterns, and
52
+ // `templates` for templatedURLs dependencies, which workbox-build hashes
53
+ // whatever their size.
54
+ function getGlobPatterns({
55
+ globPatterns,
56
+ templatedURLs
57
+ }) {
58
+ const templates = [];
59
+ for (const dependencies of Object.values(templatedURLs ?? {})) {
60
+ if (Array.isArray(dependencies)) {
61
+ templates.push(...dependencies);
62
+ }
52
63
  }
53
- let offline;
54
- if ("offline" in config) {
55
- logger.warn(`
56
- Starting from hexo-offline v2 the 'offline' config in _config.yaml is
57
- deprecated. Please create 'hexo-offline.config.cjs' in hexo root directory.
58
- See https://github.com/JLHwung/hexo-offline#usage for more info.
59
- `);
60
- offline = config.offline;
64
+ return {
65
+ precache: toRoutePatterns(Array.isArray(globPatterns) ? globPatterns : []),
66
+ templates: toRoutePatterns(templates)
67
+ };
68
+ }
69
+
70
+ // Glob patterns in a form that can be matched against route paths. Invalid
71
+ // entries are dropped here; workbox-build reports them when it validates the
72
+ // config.
73
+ function toRoutePatterns(patterns) {
74
+ return patterns.filter(pattern => typeof pattern === "string")
75
+ // glob resolves "./**/*.css" against globDirectory; route paths have no "./".
76
+ .map(pattern => pattern.replace(/^\.\//, ""));
77
+ }
78
+
79
+ // workbox-build's defaults for the options that limit what is precached.
80
+ const defaultGlobIgnores = ["**/node_modules/**/*"];
81
+ const defaultMaximumFileSize = 2 * 1024 * 1024;
82
+
83
+ // Files this build writes itself: the service worker and the Workbox runtime,
84
+ // with their source maps. They must not be precached.
85
+ function isGeneratedFile(routePath) {
86
+ return routePath === _constants.workerName || routePath === `${_constants.workerName}.map` || /^workbox-[0-9a-f]+\.js(\.map)?$/.test(routePath);
87
+ }
88
+
89
+ // Run `fn` over `items` with at most `limit` calls in flight. Waits for every
90
+ // call to settle before rethrowing the first error.
91
+ async function forEachConcurrently(items, limit, fn) {
92
+ let next = 0;
93
+ const workers = Array.from({
94
+ length: Math.min(limit, items.length)
95
+ }, async () => {
96
+ while (next < items.length) {
97
+ await fn(items[next++]);
98
+ }
99
+ });
100
+ const failed = (await Promise.allSettled(workers)).find(({
101
+ status
102
+ }) => status === "rejected");
103
+ if (failed) {
104
+ throw failed.reason;
61
105
  }
106
+ }
107
+
108
+ /**
109
+ * Generate the service worker from Hexo's routes and add the generated files
110
+ * as routes, so Hexo writes them to the public folder (and deployers pick them
111
+ * up) like any other generated file.
112
+ *
113
+ * workbox-build only globs files on disk, so routes that may be precached are
114
+ * copied to a temporary directory first.
115
+ */
116
+ async function runWorkboxBuild(route, logger, extraConfig, publicDir, concurrency = defaultConcurrency) {
117
+ if (typeof _path.default.posix.matchesGlob !== "function") {
118
+ throw new Error(`hexo-offline requires Node.js ^20.17.0 or >=22.5.0 (current: ${process.version}).`);
119
+ }
120
+ const workboxConfig = {
121
+ skipWaiting: true,
122
+ clientsClaim: true,
123
+ ...extraConfig
124
+ };
125
+ workboxConfig.globPatterns ??= defaultGlobPatterns;
126
+ // generateSW appends to globIgnores; don't change the user's array.
127
+ if (Array.isArray(workboxConfig.globIgnores)) {
128
+ workboxConfig.globIgnores = [...workboxConfig.globIgnores];
129
+ }
130
+ const patterns = getGlobPatterns(workboxConfig);
131
+ const ignores = toRoutePatterns(Array.isArray(workboxConfig.globIgnores) ? workboxConfig.globIgnores : defaultGlobIgnores);
132
+ const maximumFileSize = workboxConfig.maximumFileSizeToCacheInBytes ?? defaultMaximumFileSize;
133
+ const matches = (routePath, globs) => globs.some(glob => _path.default.posix.matchesGlob(routePath, glob));
134
+ const tmpDir = _fs.default.mkdtempSync(_path.default.join(_os.default.tmpdir(), "hexo-offline-"));
62
135
  try {
63
- offline = require(_path.default.resolve(baseDir, "hexo-offline.config.cjs"));
64
- } catch {}
65
- const SWPrecacheConfig = generateSWPrecacheConfig({
66
- publicDir
67
- }, offline);
68
- const result = await (0, _workboxBuild.generateSW)(SWPrecacheConfig);
69
- printSWResult(result, logger);
70
- return result;
136
+ const globDirectory = _path.default.join(tmpDir, "public");
137
+ const outDir = _path.default.join(tmpDir, "out");
138
+ _fs.default.mkdirSync(globDirectory);
139
+
140
+ // workbox-build applies the exact glob rules later; this only picks the
141
+ // routes it may precache, so nothing else is read or copied.
142
+ const candidates = route.list().filter(routePath => !isGeneratedFile(routePath) && matches(routePath, [...patterns.precache, ...patterns.templates]) && !matches(routePath, ignores));
143
+ await forEachConcurrently(candidates, concurrency, async routePath => {
144
+ let content;
145
+ try {
146
+ content = await (0, _readRoute.default)(route, routePath);
147
+ } catch {
148
+ // Hexo reports the error itself when it writes this route.
149
+ logger.warn(`hexo-offline: not precaching ${routePath} because it failed to generate.`);
150
+ return;
151
+ }
152
+ // Keep pages, styles and scripts, which Hexo may have rendered, so they
153
+ // aren't rendered a second time. Other files (images, fonts) are usually
154
+ // copied as-is, cheap to read again and may be large, so they are not kept.
155
+ if (/\.(html|css|m?js)$/.test(routePath)) {
156
+ route.set(routePath, {
157
+ data: content,
158
+ modified: route.isModified(routePath)
159
+ });
160
+ }
161
+ // workbox-build would skip it anyway; don't copy it. templatedURLs
162
+ // dependencies are hashed whatever their size, so they are always copied.
163
+ if (content.length > maximumFileSize && !matches(routePath, patterns.templates)) {
164
+ logger.warn(`hexo-offline: not precaching ${routePath} because it is ${formatNumber(content.length)} bytes, larger than maximumFileSizeToCacheInBytes (${formatNumber(maximumFileSize)}).`);
165
+ return;
166
+ }
167
+ const dest = _path.default.join(globDirectory, routePath);
168
+ try {
169
+ _fs.default.mkdirSync(_path.default.dirname(dest), {
170
+ recursive: true
171
+ });
172
+ _fs.default.writeFileSync(dest, content);
173
+ } catch (err) {
174
+ logger.warn(`hexo-offline: not precaching ${routePath} because it could not be copied to a temporary folder: ${err.message}`);
175
+ }
176
+ });
177
+ const result = await (0, _workboxBuild.generateSW)({
178
+ ...workboxConfig,
179
+ globDirectory,
180
+ swDest: _path.default.join(outDir, _constants.workerName)
181
+ });
182
+ for (const file of result.filePaths) {
183
+ const routePath = _path.default.relative(outDir, file).split(_path.default.sep).join("/");
184
+ route.set(routePath, _fs.default.readFileSync(file));
185
+ }
186
+ printSWResult(result, logger, globDirectory, publicDir);
187
+ return result;
188
+ } finally {
189
+ // Failing to clean up must not fail the build (or hide its error), e.g.
190
+ // when another process briefly holds a file open on Windows.
191
+ try {
192
+ _fs.default.rmSync(tmpDir, {
193
+ recursive: true,
194
+ force: true,
195
+ maxRetries: 3
196
+ });
197
+ } catch (err) {
198
+ logger.warn(`hexo-offline: could not remove the temporary folder ${tmpDir}: ${err.message}`);
199
+ }
200
+ }
71
201
  }
@@ -1 +1 @@
1
- "use strict";if("serviceWorker"in navigator){navigator.serviceWorker.register("__workerName__").then((function(reg){reg.onupdatefound=function(){var installingWorker=reg.installing;installingWorker.onstatechange=function(){switch(installingWorker.state){case"installed":if(navigator.serviceWorker.controller){console.log("New or updated content is available.")}else{console.log("Content is now available offline!")}break;case"redundant":console.error("The installing service worker became redundant.");break}}}}))["catch"]((function(e){console.error("Error during service worker registration:",e)}))}
1
+ "use strict";if("serviceWorker"in navigator){navigator.serviceWorker.register("__workerName__").then(function(reg){reg.onupdatefound=function(){var installingWorker=reg.installing;installingWorker.onstatechange=function(){switch(installingWorker.state){case"installed":if(navigator.serviceWorker.controller){console.log("New or updated content is available.")}else{console.log("Content is now available offline!")}break;case"redundant":console.error("The installing service worker became redundant.");break}}}})["catch"](function(e){console.error("Error during service worker registration:",e)})}
package/package.json CHANGED
@@ -1,39 +1,39 @@
1
1
  {
2
2
  "name": "hexo-offline",
3
- "version": "3.0.0",
3
+ "version": "5.0.0",
4
4
  "description": "Out-of-the-box hexo offline experience",
5
5
  "main": "lib/index.js",
6
6
  "repository": "https://github.com/JLHwung/hexo-offline.git",
7
7
  "author": "Huáng Jùnliàng <hexo-offline@jhuang.me>",
8
8
  "license": "BSD-2-Clause",
9
9
  "scripts": {
10
- "clean": "rimraf lib && rimraf run-workbox-build.spec",
10
+ "clean": "node -e \"fs.rmSync('lib', { recursive: true, force: true })\"",
11
11
  "build:template": "babel src/lib/template.js --out-file lib/lib/template.js && terser lib/lib/template.js -o lib/lib/template.js",
12
12
  "build:lib": "babel src --out-dir lib",
13
13
  "build": "npm run build:lib && npm run build:template",
14
14
  "test": "node --test",
15
- "prepublishOnly": "npm run test && npm run clean && npm run build"
15
+ "prepublishOnly": "npm run clean && npm run build && npm run test"
16
16
  },
17
17
  "dependencies": {
18
- "workbox-build": "^7.1.1"
18
+ "workbox-build": "^7.3.0"
19
19
  },
20
20
  "devDependencies": {
21
- "@babel/cli": "^7.24.0",
22
- "@babel/core": "^7.24.0",
23
- "@babel/preset-env": "^7.24.0",
21
+ "@babel/cli": "^8.1.0",
22
+ "@babel/core": "^8.1.0",
23
+ "@babel/preset-env": "^8.0.7",
24
24
  "husky": "^9.1.5",
25
- "lint-staged": "^15.2.9",
25
+ "lint-staged": "^17.0.0",
26
26
  "prettier": "^3.3.3",
27
27
  "terser": "^5.31.6"
28
28
  },
29
29
  "peerDependencies": {
30
- "hexo": "^5.0.0 || ^6.0.0 || ^7.0.0"
30
+ "hexo": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
31
31
  },
32
32
  "engines": {
33
- "node": ">=18"
33
+ "node": "^20.17.0 || >=22.5.0"
34
34
  },
35
35
  "files": [
36
36
  "lib"
37
37
  ],
38
- "packageManager": "yarn@4.5.0"
38
+ "packageManager": "yarn@4.19.0"
39
39
  }