@docusaurus/plugin-pwa 2.0.0-beta.1ec2c95e3 → 2.0.0-beta.21

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/lib/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { LoadContext, Plugin } from '@docusaurus/types';
8
+ import type { PluginOptions } from '@docusaurus/plugin-pwa';
9
+ export default function pluginPWA(context: LoadContext, options: PluginOptions): Plugin<void>;
10
+ export { validateOptions } from './options';
package/lib/index.js ADDED
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.validateOptions = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const path_1 = tslib_1.__importDefault(require("path"));
12
+ const webpack_1 = tslib_1.__importDefault(require("webpack"));
13
+ const terser_webpack_plugin_1 = tslib_1.__importDefault(require("terser-webpack-plugin"));
14
+ const workbox_build_1 = require("workbox-build");
15
+ const utils_1 = require("@docusaurus/utils");
16
+ const utils_2 = require("@docusaurus/core/lib/webpack/utils");
17
+ const LogPlugin_1 = tslib_1.__importDefault(require("@docusaurus/core/lib/webpack/plugins/LogPlugin"));
18
+ const theme_translations_1 = require("@docusaurus/theme-translations");
19
+ const isProd = process.env.NODE_ENV === 'production';
20
+ function getSWBabelLoader() {
21
+ return {
22
+ loader: 'babel-loader',
23
+ options: {
24
+ babelrc: false,
25
+ configFile: false,
26
+ presets: [
27
+ [
28
+ require.resolve('@babel/preset-env'),
29
+ {
30
+ useBuiltIns: 'entry',
31
+ corejs: '3',
32
+ // See https://twitter.com/jeffposnick/status/1280223070876315649
33
+ targets: 'chrome >= 56',
34
+ },
35
+ ],
36
+ ],
37
+ },
38
+ };
39
+ }
40
+ function pluginPWA(context, options) {
41
+ const { outDir, baseUrl, i18n: { currentLocale }, } = context;
42
+ const { debug, offlineModeActivationStrategies, injectManifestConfig, pwaHead, swCustom, swRegister, } = options;
43
+ return {
44
+ name: 'docusaurus-plugin-pwa',
45
+ getThemePath() {
46
+ return '../lib/theme';
47
+ },
48
+ getTypeScriptThemePath() {
49
+ return '../src/theme';
50
+ },
51
+ getClientModules() {
52
+ return isProd && swRegister ? [swRegister] : [];
53
+ },
54
+ getDefaultCodeTranslationMessages() {
55
+ return (0, theme_translations_1.readDefaultCodeTranslationMessages)({
56
+ locale: currentLocale,
57
+ name: 'plugin-pwa',
58
+ });
59
+ },
60
+ configureWebpack(config) {
61
+ if (!isProd) {
62
+ return {};
63
+ }
64
+ return {
65
+ plugins: [
66
+ new webpack_1.default.EnvironmentPlugin({
67
+ PWA_DEBUG: debug,
68
+ PWA_SERVICE_WORKER_URL: path_1.default.posix.resolve(`${config.output?.publicPath || '/'}`, 'sw.js'),
69
+ PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES: offlineModeActivationStrategies,
70
+ }),
71
+ ],
72
+ };
73
+ },
74
+ injectHtmlTags() {
75
+ const headTags = [];
76
+ if (isProd) {
77
+ pwaHead.forEach(({ tagName, ...attributes }) => {
78
+ ['href', 'content'].forEach((attribute) => {
79
+ const attributeValue = attributes[attribute];
80
+ if (!attributeValue) {
81
+ return;
82
+ }
83
+ const attributePath = !!path_1.default.extname(attributeValue) && attributeValue;
84
+ if (attributePath && !attributePath.startsWith(baseUrl)) {
85
+ attributes[attribute] = (0, utils_1.normalizeUrl)([baseUrl, attributeValue]);
86
+ }
87
+ });
88
+ return headTags.push({
89
+ tagName,
90
+ attributes,
91
+ });
92
+ });
93
+ }
94
+ return { headTags };
95
+ },
96
+ async postBuild(props) {
97
+ if (!isProd) {
98
+ return;
99
+ }
100
+ const swSourceFileTest = /\.m?js$/;
101
+ const swWebpackConfig = {
102
+ entry: require.resolve('./sw.js'),
103
+ output: {
104
+ path: outDir,
105
+ filename: 'sw.js',
106
+ publicPath: baseUrl,
107
+ },
108
+ target: 'webworker',
109
+ mode: debug ? 'development' : 'production',
110
+ devtool: debug ? 'source-map' : false,
111
+ optimization: {
112
+ splitChunks: false,
113
+ minimize: !debug,
114
+ // See https://developers.google.com/web/tools/workbox/guides/using-bundlers#webpack
115
+ minimizer: debug
116
+ ? []
117
+ : [
118
+ new terser_webpack_plugin_1.default({
119
+ test: swSourceFileTest,
120
+ }),
121
+ ],
122
+ },
123
+ plugins: [
124
+ new webpack_1.default.EnvironmentPlugin({
125
+ // Fallback value required with Webpack 5
126
+ PWA_SW_CUSTOM: swCustom ?? '',
127
+ }),
128
+ new LogPlugin_1.default({
129
+ name: 'Service Worker',
130
+ color: 'red',
131
+ }),
132
+ ],
133
+ module: {
134
+ rules: [
135
+ {
136
+ test: swSourceFileTest,
137
+ exclude: /node_modules/,
138
+ use: getSWBabelLoader(),
139
+ },
140
+ ],
141
+ },
142
+ };
143
+ await (0, utils_2.compile)([swWebpackConfig]);
144
+ const swDest = path_1.default.resolve(props.outDir, 'sw.js');
145
+ await (0, workbox_build_1.injectManifest)({
146
+ ...injectManifestConfig,
147
+ globPatterns: [
148
+ '**/*.{js,json,css,html}',
149
+ '**/*.{png,jpg,jpeg,gif,svg,ico}',
150
+ '**/*.{woff,woff2,eot,ttf,otf}',
151
+ // @ts-expect-error: internal API?
152
+ ...(workbox_build_1.injectManifest.globPatterns ?? []),
153
+ ],
154
+ // Those attributes are not overrideable
155
+ swDest,
156
+ swSrc: swDest,
157
+ globDirectory: props.outDir,
158
+ });
159
+ },
160
+ };
161
+ }
162
+ exports.default = pluginPWA;
163
+ var options_1 = require("./options");
164
+ Object.defineProperty(exports, "validateOptions", { enumerable: true, get: function () { return options_1.validateOptions; } });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { OptionValidationContext } from '@docusaurus/types';
8
+ import type { PluginOptions } from '@docusaurus/plugin-pwa';
9
+ export declare function validateOptions({ validate, options, }: OptionValidationContext<PluginOptions, PluginOptions>): PluginOptions;
package/lib/options.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.validateOptions = void 0;
10
+ const utils_validation_1 = require("@docusaurus/utils-validation");
11
+ const DEFAULT_OPTIONS = {
12
+ debug: false,
13
+ offlineModeActivationStrategies: [
14
+ 'appInstalled',
15
+ 'queryString',
16
+ 'standalone',
17
+ ],
18
+ injectManifestConfig: {},
19
+ pwaHead: [],
20
+ swCustom: undefined,
21
+ swRegister: './registerSw.js',
22
+ };
23
+ const optionsSchema = utils_validation_1.Joi.object({
24
+ debug: utils_validation_1.Joi.bool().default(DEFAULT_OPTIONS.debug),
25
+ offlineModeActivationStrategies: utils_validation_1.Joi.array()
26
+ .items(utils_validation_1.Joi.string()
27
+ .valid('appInstalled', 'queryString', 'standalone', 'mobile', 'saveData', 'always')
28
+ .required())
29
+ .default(DEFAULT_OPTIONS.offlineModeActivationStrategies),
30
+ injectManifestConfig: utils_validation_1.Joi.object().default(DEFAULT_OPTIONS.injectManifestConfig),
31
+ pwaHead: utils_validation_1.Joi.array()
32
+ .items(utils_validation_1.Joi.object({ tagName: utils_validation_1.Joi.string().required() }).unknown().required())
33
+ .default(DEFAULT_OPTIONS.pwaHead),
34
+ swCustom: utils_validation_1.Joi.string(),
35
+ swRegister: utils_validation_1.Joi.alternatives()
36
+ .try(utils_validation_1.Joi.string(), utils_validation_1.Joi.bool().valid(false))
37
+ .default(DEFAULT_OPTIONS.swRegister),
38
+ // @ts-expect-error: forbidden
39
+ reloadPopup: utils_validation_1.Joi.any().forbidden().messages({
40
+ 'any.unknown': 'The reloadPopup option is removed in favor of swizzling. See https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-pwa#customizing-reload-popup for how to customize the reload popup using swizzling.',
41
+ }),
42
+ });
43
+ function validateOptions({ validate, options, }) {
44
+ return validate(optionsSchema, options);
45
+ }
46
+ exports.validateOptions = validateOptions;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ declare global {
8
+ interface Navigator {
9
+ getInstalledRelatedApps: () => Promise<{
10
+ platform: string;
11
+ }[]>;
12
+ connection?: {
13
+ effectiveType: string;
14
+ saveData: boolean;
15
+ };
16
+ }
17
+ }
18
+ export {};
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import { createStorageSlot } from '@docusaurus/theme-common';
8
+ // First: read the env variables (provided by Webpack)
9
+ /* eslint-disable prefer-destructuring */
10
+ const PWA_SERVICE_WORKER_URL = process.env.PWA_SERVICE_WORKER_URL;
11
+ const PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES = process.env
12
+ .PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES;
13
+ const PWA_DEBUG = process.env.PWA_DEBUG;
14
+ /* eslint-enable prefer-destructuring */
15
+ const debug = PWA_DEBUG; // Shortcut
16
+ const MAX_MOBILE_WIDTH = 940;
17
+ const AppInstalledEventFiredStorage = createStorageSlot('docusaurus.pwa.event.appInstalled.fired');
18
+ async function clearRegistrations() {
19
+ const registrations = await navigator.serviceWorker.getRegistrations();
20
+ if (debug) {
21
+ console.log(`[Docusaurus-PWA][registerSw]: will unregister all service worker registrations`, registrations);
22
+ }
23
+ await Promise.all(registrations.map(async (registration) => {
24
+ const result = await registration.unregister();
25
+ if (debug) {
26
+ console.log(`[Docusaurus-PWA][registerSw]: unregister() service worker registration`, registrations, result);
27
+ }
28
+ }));
29
+ if (debug) {
30
+ console.log(`[Docusaurus-PWA][registerSw]: unregistered all service worker registrations`, registrations);
31
+ }
32
+ window.location.reload();
33
+ }
34
+ /*
35
+ As of 2021:
36
+ It is complicated and not very reliable to detect an app is actually installed.
37
+ https://stackoverflow.com/questions/51735869/check-if-user-has-already-installed-pwa-to-homescreen-on-chrome
38
+
39
+ - appinstalled event is not in the spec anymore and seems to not fire? https://firt.dev/pwa-2021#less-capabilities-%E2%98%B9%EF%B8%8F
40
+ - getInstalledRelatedApps() is only supported in recent Chrome and does not seem to reliable either https://github.com/WICG/get-installed-related-apps
41
+ - display-mode: standalone is not exactly the same concept, but looks like a decent fallback https://petelepage.com/blog/2019/07/is-my-pwa-installed/
42
+ */
43
+ async function isAppInstalledEventFired() {
44
+ return AppInstalledEventFiredStorage.get() === 'true';
45
+ }
46
+ async function isAppInstalledRelatedApps() {
47
+ if ('getInstalledRelatedApps' in window.navigator) {
48
+ const relatedApps = await navigator.getInstalledRelatedApps();
49
+ return relatedApps.some((app) => app.platform === 'webapp');
50
+ }
51
+ return false;
52
+ }
53
+ function isStandaloneDisplayMode() {
54
+ return window.matchMedia('(display-mode: standalone)').matches;
55
+ }
56
+ const OfflineModeActivationStrategiesImplementations = {
57
+ always: () => true,
58
+ mobile: () => window.innerWidth <= MAX_MOBILE_WIDTH,
59
+ saveData: () => !!navigator.connection?.saveData,
60
+ appInstalled: async () => {
61
+ const installedEventFired = await isAppInstalledEventFired();
62
+ const installedRelatedApps = await isAppInstalledRelatedApps();
63
+ return installedEventFired || installedRelatedApps;
64
+ },
65
+ standalone: () => isStandaloneDisplayMode(),
66
+ queryString: () => new URLSearchParams(window.location.search).get('offlineMode') === 'true',
67
+ };
68
+ async function isStrategyActive(strategyName) {
69
+ return OfflineModeActivationStrategiesImplementations[strategyName]();
70
+ }
71
+ async function getActiveStrategies() {
72
+ const activeStrategies = await Promise.all(PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES.map(async (strategyName) => {
73
+ const isActive = await isStrategyActive(strategyName);
74
+ return isActive ? strategyName : undefined;
75
+ }));
76
+ return activeStrategies.filter(Boolean);
77
+ }
78
+ async function isOfflineModeEnabled() {
79
+ const activeStrategies = await getActiveStrategies();
80
+ const enabled = activeStrategies.length > 0;
81
+ if (debug) {
82
+ const logObject = {
83
+ activeStrategies,
84
+ availableStrategies: PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES,
85
+ };
86
+ if (enabled) {
87
+ console.log('[Docusaurus-PWA][registerSw]: offline mode enabled, because of activation strategies', logObject);
88
+ }
89
+ else {
90
+ console.log('[Docusaurus-PWA][registerSw]: offline mode disabled, because none of the offlineModeActivationStrategies could be used', logObject);
91
+ }
92
+ }
93
+ return enabled;
94
+ }
95
+ function createServiceWorkerUrl(params) {
96
+ const paramsQueryString = JSON.stringify(params);
97
+ const url = `${PWA_SERVICE_WORKER_URL}?params=${encodeURIComponent(paramsQueryString)}`;
98
+ if (debug) {
99
+ console.log(`[Docusaurus-PWA][registerSw]: service worker url`, {
100
+ url,
101
+ params,
102
+ });
103
+ }
104
+ return url;
105
+ }
106
+ async function registerSW() {
107
+ const { Workbox } = await import('workbox-window');
108
+ const offlineMode = await isOfflineModeEnabled();
109
+ const url = createServiceWorkerUrl({ offlineMode, debug });
110
+ const wb = new Workbox(url);
111
+ const registration = await wb.register();
112
+ const sendSkipWaiting = () => wb.messageSW({ type: 'SKIP_WAITING' });
113
+ const handleServiceWorkerWaiting = async () => {
114
+ if (debug) {
115
+ console.log('[Docusaurus-PWA][registerSw]: handleServiceWorkerWaiting');
116
+ }
117
+ // Immediately load new service worker when files aren't cached
118
+ if (!offlineMode) {
119
+ sendSkipWaiting();
120
+ }
121
+ else {
122
+ const renderReloadPopup = (await import('./renderReloadPopup')).default;
123
+ await renderReloadPopup({
124
+ onReload() {
125
+ wb.addEventListener('controlling', () => {
126
+ window.location.reload();
127
+ });
128
+ sendSkipWaiting();
129
+ },
130
+ });
131
+ }
132
+ };
133
+ if (debug && registration) {
134
+ if (registration.active) {
135
+ console.log('[Docusaurus-PWA][registerSw]: registration.active', registration);
136
+ }
137
+ if (registration.installing) {
138
+ console.log('[Docusaurus-PWA][registerSw]: registration.installing', registration);
139
+ }
140
+ if (registration.waiting) {
141
+ console.log('[Docusaurus-PWA][registerSw]: registration.waiting', registration);
142
+ }
143
+ }
144
+ // Update the current service worker when the next one has finished
145
+ // installing and transitions to waiting state.
146
+ wb.addEventListener('waiting', (event) => {
147
+ if (debug) {
148
+ console.log('[Docusaurus-PWA][registerSw]: event waiting', event);
149
+ }
150
+ handleServiceWorkerWaiting();
151
+ });
152
+ // Update current service worker if the next one finishes installing and
153
+ // moves to waiting state in another tab.
154
+ // @ts-expect-error: not present in the API typings anymore
155
+ wb.addEventListener('externalwaiting', (event) => {
156
+ if (debug) {
157
+ console.log('[Docusaurus-PWA][registerSw]: event externalwaiting', event);
158
+ }
159
+ handleServiceWorkerWaiting();
160
+ });
161
+ // Update service worker if the next one is already in the waiting state.
162
+ // This happens when the user doesn't click on `reload` in the popup.
163
+ if (registration?.waiting) {
164
+ await handleServiceWorkerWaiting();
165
+ }
166
+ }
167
+ // TODO these events still works in chrome but have been removed from the spec
168
+ // in 2019! See https://github.com/w3c/manifest/pull/836
169
+ function addLegacyAppInstalledEventsListeners() {
170
+ if (typeof window !== 'undefined') {
171
+ if (debug) {
172
+ console.log('[Docusaurus-PWA][registerSw]: addLegacyAppInstalledEventsListeners');
173
+ }
174
+ window.addEventListener('appinstalled', async (event) => {
175
+ if (debug) {
176
+ console.log('[Docusaurus-PWA][registerSw]: event appinstalled', event);
177
+ }
178
+ AppInstalledEventFiredStorage.set('true');
179
+ if (debug) {
180
+ console.log("[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.set('true')");
181
+ }
182
+ // After the app is installed, we register a service worker with the path
183
+ // `/sw?enabled`. Since the previous service worker was `/sw`, it'll be
184
+ // treated as a new one. The previous registration will need to be
185
+ // cleared, otherwise the reload popup will show.
186
+ await clearRegistrations();
187
+ });
188
+ // TODO this event still works in chrome but has been removed from the spec
189
+ // in 2019!!!
190
+ window.addEventListener('beforeinstallprompt', async (event) => {
191
+ if (debug) {
192
+ console.log('[Docusaurus-PWA][registerSw]: event beforeinstallprompt', event);
193
+ }
194
+ // TODO instead of default browser install UI, show custom docusaurus
195
+ // prompt?
196
+ // event.preventDefault();
197
+ if (debug) {
198
+ console.log('[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.get()', AppInstalledEventFiredStorage.get());
199
+ }
200
+ if (AppInstalledEventFiredStorage.get()) {
201
+ AppInstalledEventFiredStorage.del();
202
+ if (debug) {
203
+ console.log('[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.del()');
204
+ }
205
+ // After uninstalling the app, if the user doesn't clear all data, then
206
+ // the previous service worker will continue serving cached files. We
207
+ // need to clear registrations and reload, otherwise the popup shows.
208
+ await clearRegistrations();
209
+ }
210
+ });
211
+ if (debug) {
212
+ console.log('[Docusaurus-PWA][registerSw]: legacy appinstalled and beforeinstallprompt event listeners installed');
213
+ }
214
+ }
215
+ }
216
+ /*
217
+ Init code to run on the client!
218
+ */
219
+ if (typeof window !== 'undefined') {
220
+ if (debug) {
221
+ console.log('[Docusaurus-PWA][registerSw]: debug mode enabled');
222
+ }
223
+ if ('serviceWorker' in navigator) {
224
+ // First: add the listeners asap/synchronously
225
+ addLegacyAppInstalledEventsListeners();
226
+ // Then try to register the SW using lazy/dynamic imports
227
+ registerSW().catch((e) => console.error('registerSW failed', e));
228
+ }
229
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import type { Props } from '@theme/PwaReloadPopup';
8
+ export default function renderReloadPopup(props: Props): Promise<void>;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import React from 'react';
8
+ import ReactDOM from 'react-dom';
9
+ const POPUP_CONTAINER_ID = 'pwa-popup-container';
10
+ const getContainer = () => document.getElementById(POPUP_CONTAINER_ID);
11
+ const createContainer = () => {
12
+ const container = document.createElement('div');
13
+ container.id = POPUP_CONTAINER_ID;
14
+ document.body.appendChild(container);
15
+ return container;
16
+ };
17
+ export default async function renderReloadPopup(props) {
18
+ const container = getContainer() || createContainer();
19
+ const ReloadPopup = (await import('@theme/PwaReloadPopup')).default;
20
+ ReactDOM.render(<ReloadPopup {...props}/>, container);
21
+ }
package/lib/sw.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ export {};
package/lib/sw.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ /* eslint-disable no-restricted-globals */
8
+ import { PrecacheController } from 'workbox-precaching';
9
+ function parseSwParams() {
10
+ const params = JSON.parse(new URLSearchParams(self.location.search).get('params'));
11
+ if (params.debug) {
12
+ console.log('[Docusaurus-PWA][SW]: Service Worker params:', params);
13
+ }
14
+ return params;
15
+ }
16
+ // Doc advises against dynamic imports in SW
17
+ // https://developers.google.com/web/tools/workbox/guides/using-bundlers#code_splitting_and_dynamic_imports
18
+ // https://twitter.com/sebastienlorber/status/1280155204575518720
19
+ // but looks it's working fine as it's inlined by webpack, need to double check
20
+ async function runSWCustomCode(params) {
21
+ if (process.env.PWA_SW_CUSTOM) {
22
+ const customSW = await import(process.env.PWA_SW_CUSTOM);
23
+ if (typeof customSW.default === 'function') {
24
+ customSW.default(params);
25
+ }
26
+ else if (params.debug) {
27
+ console.warn('[Docusaurus-PWA][SW]: swCustom should have a default export function');
28
+ }
29
+ }
30
+ }
31
+ /**
32
+ * Gets different possible variations for a request URL. Similar to
33
+ * https://git.io/JvixK
34
+ */
35
+ function getPossibleURLs(url) {
36
+ const urlObject = new URL(url, self.location.href);
37
+ if (urlObject.origin !== self.location.origin) {
38
+ return [];
39
+ }
40
+ // Ignore search params and hash
41
+ urlObject.search = '';
42
+ urlObject.hash = '';
43
+ return [
44
+ // /blog.html
45
+ urlObject.href,
46
+ // /blog/ => /blog/index.html
47
+ // /blog => /blog/index.html
48
+ `${urlObject.href}${urlObject.pathname.endsWith('/') ? '' : '/'}index.html`,
49
+ ];
50
+ }
51
+ (async () => {
52
+ const params = parseSwParams();
53
+ // eslint-disable-next-line no-underscore-dangle
54
+ const precacheManifest = self.__WB_MANIFEST;
55
+ const controller = new PrecacheController({
56
+ // Safer to turn this true?
57
+ fallbackToNetwork: true,
58
+ });
59
+ if (params.offlineMode) {
60
+ controller.addToCacheList(precacheManifest);
61
+ if (params.debug) {
62
+ console.log('[Docusaurus-PWA][SW]: addToCacheList', { precacheManifest });
63
+ }
64
+ }
65
+ await runSWCustomCode(params);
66
+ self.addEventListener('install', (event) => {
67
+ if (params.debug) {
68
+ console.log('[Docusaurus-PWA][SW]: install event', { event });
69
+ }
70
+ event.waitUntil(controller.install(event));
71
+ });
72
+ self.addEventListener('activate', (event) => {
73
+ if (params.debug) {
74
+ console.log('[Docusaurus-PWA][SW]: activate event', { event });
75
+ }
76
+ event.waitUntil(controller.activate(event));
77
+ });
78
+ self.addEventListener('fetch', async (event) => {
79
+ if (params.offlineMode) {
80
+ const requestURL = event.request.url;
81
+ const possibleURLs = getPossibleURLs(requestURL);
82
+ for (const possibleURL of possibleURLs) {
83
+ const cacheKey = controller.getCacheKeyForURL(possibleURL);
84
+ if (cacheKey) {
85
+ const cachedResponse = caches.match(cacheKey);
86
+ if (params.debug) {
87
+ console.log('[Docusaurus-PWA][SW]: serving cached asset', {
88
+ requestURL,
89
+ possibleURL,
90
+ possibleURLs,
91
+ cacheKey,
92
+ cachedResponse,
93
+ });
94
+ }
95
+ event.respondWith(cachedResponse);
96
+ break;
97
+ }
98
+ }
99
+ }
100
+ });
101
+ self.addEventListener('message', async (event) => {
102
+ if (params.debug) {
103
+ console.log('[Docusaurus-PWA][SW]: message event', { event });
104
+ }
105
+ const type = event.data?.type;
106
+ if (type === 'SKIP_WAITING') {
107
+ // lib def bug, see https://github.com/microsoft/TypeScript/issues/14877
108
+ self.skipWaiting();
109
+ }
110
+ });
111
+ })();
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ /// <reference types="react" />
8
+ import type { Props } from '@theme/PwaReloadPopup';
9
+ export default function PwaReloadPopup({ onReload }: Props): JSX.Element | false;
@@ -4,16 +4,12 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
-
8
7
  import React, {useState} from 'react';
9
8
  import clsx from 'clsx';
10
9
  import Translate, {translate} from '@docusaurus/Translate';
11
-
12
10
  import styles from './styles.module.css';
13
-
14
11
  export default function PwaReloadPopup({onReload}) {
15
12
  const [isVisible, setIsVisible] = useState(true);
16
-
17
13
  return (
18
14
  isVisible && (
19
15
  <div className={clsx('alert', 'alert--secondary', styles.popup)}>