@docusaurus/plugin-pwa 0.0.0-4194 → 0.0.0-4203

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.
@@ -0,0 +1,20 @@
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
+
8
+ const path = require('path');
9
+ const fs = require('fs-extra');
10
+
11
+ /**
12
+ * Copy all untyped and static assets files to lib.
13
+ */
14
+ const srcDir = path.resolve(__dirname, 'src');
15
+ const libDir = path.resolve(__dirname, 'lib');
16
+ fs.copySync(srcDir, libDir, {
17
+ filter(filepath) {
18
+ return !/__tests__/.test(filepath) && !/\.tsx?$/.test(filepath);
19
+ },
20
+ });
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 (context: LoadContext, options: PluginOptions): Plugin<void>;
10
+ export { validateOptions } from './options';
package/lib/index.js ADDED
@@ -0,0 +1,161 @@
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 utils_1 = require("@docusaurus/utils");
12
+ const utils_2 = require("@docusaurus/core/lib/webpack/utils");
13
+ const LogPlugin_1 = (0, tslib_1.__importDefault)(require("@docusaurus/core/lib/webpack/plugins/LogPlugin"));
14
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
15
+ const webpack_1 = (0, tslib_1.__importDefault)(require("webpack"));
16
+ const terser_webpack_plugin_1 = (0, tslib_1.__importDefault)(require("terser-webpack-plugin"));
17
+ const workbox_build_1 = require("workbox-build");
18
+ const isProd = process.env.NODE_ENV === 'production';
19
+ function getSWBabelLoader() {
20
+ return {
21
+ loader: 'babel-loader',
22
+ options: {
23
+ babelrc: false,
24
+ configFile: false,
25
+ presets: [
26
+ [
27
+ require.resolve('@babel/preset-env'),
28
+ {
29
+ useBuiltIns: 'entry',
30
+ corejs: '3',
31
+ // See https://twitter.com/jeffposnick/status/1280223070876315649
32
+ targets: 'chrome >= 56',
33
+ },
34
+ ],
35
+ ],
36
+ plugins: [
37
+ require.resolve('@babel/plugin-proposal-object-rest-spread'),
38
+ require.resolve('@babel/plugin-proposal-optional-chaining'),
39
+ require.resolve('@babel/plugin-proposal-nullish-coalescing-operator'),
40
+ ],
41
+ },
42
+ };
43
+ }
44
+ function default_1(context, options) {
45
+ const { outDir, baseUrl } = context;
46
+ const { debug, offlineModeActivationStrategies, injectManifestConfig, reloadPopup, pwaHead, swCustom, swRegister, } = options;
47
+ return {
48
+ name: 'docusaurus-plugin-pwa',
49
+ getThemePath() {
50
+ return path_1.default.resolve(__dirname, './theme');
51
+ },
52
+ getClientModules() {
53
+ return isProd ? [swRegister] : [];
54
+ },
55
+ configureWebpack(config) {
56
+ var _a;
57
+ if (!isProd) {
58
+ return {};
59
+ }
60
+ return {
61
+ plugins: [
62
+ new webpack_1.default.EnvironmentPlugin({
63
+ PWA_DEBUG: debug,
64
+ PWA_SERVICE_WORKER_URL: path_1.default.posix.resolve(`${((_a = config.output) === null || _a === void 0 ? void 0 : _a.publicPath) || '/'}`, 'sw.js'),
65
+ PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES: offlineModeActivationStrategies,
66
+ PWA_RELOAD_POPUP: reloadPopup,
67
+ }),
68
+ ],
69
+ };
70
+ },
71
+ injectHtmlTags() {
72
+ const headTags = [];
73
+ if (isProd && pwaHead) {
74
+ pwaHead.forEach(({ tagName, ...attributes }) => {
75
+ ['href', 'content'].forEach((attribute) => {
76
+ const attributeValue = attributes[attribute];
77
+ if (!attributeValue) {
78
+ return;
79
+ }
80
+ const attributePath = !!path_1.default.extname(attributeValue) && attributeValue;
81
+ if (attributePath && !attributePath.startsWith(baseUrl)) {
82
+ attributes[attribute] = (0, utils_1.normalizeUrl)([baseUrl, attributeValue]);
83
+ }
84
+ });
85
+ return headTags.push({
86
+ tagName,
87
+ attributes,
88
+ });
89
+ });
90
+ }
91
+ return { headTags };
92
+ },
93
+ async postBuild(props) {
94
+ if (!isProd) {
95
+ return;
96
+ }
97
+ const swSourceFileTest = /\.m?js$/;
98
+ const swWebpackConfig = {
99
+ entry: path_1.default.resolve(__dirname, 'sw.js'),
100
+ output: {
101
+ path: outDir,
102
+ filename: 'sw.js',
103
+ publicPath: baseUrl,
104
+ },
105
+ target: 'webworker',
106
+ mode: debug ? 'development' : 'production',
107
+ devtool: debug ? 'source-map' : false,
108
+ optimization: {
109
+ splitChunks: false,
110
+ minimize: !debug,
111
+ // see https://developers.google.com/web/tools/workbox/guides/using-bundlers#webpack
112
+ minimizer: debug
113
+ ? []
114
+ : [
115
+ new terser_webpack_plugin_1.default({
116
+ test: swSourceFileTest,
117
+ }),
118
+ ],
119
+ },
120
+ plugins: [
121
+ new webpack_1.default.EnvironmentPlugin({
122
+ PWA_SW_CUSTOM: swCustom || '', // fallback value required with Webpack 5
123
+ }),
124
+ new LogPlugin_1.default({
125
+ name: 'Service Worker',
126
+ color: 'red',
127
+ }),
128
+ ],
129
+ module: {
130
+ rules: [
131
+ {
132
+ test: swSourceFileTest,
133
+ exclude: /(node_modules)/,
134
+ use: getSWBabelLoader(),
135
+ },
136
+ ],
137
+ },
138
+ };
139
+ await (0, utils_2.compile)([swWebpackConfig]);
140
+ const swDest = path_1.default.resolve(props.outDir, 'sw.js');
141
+ await (0, workbox_build_1.injectManifest)({
142
+ ...injectManifestConfig,
143
+ globPatterns: [
144
+ '**/*.{js,json,css,html}',
145
+ '**/*.{png,jpg,jpeg,gif,svg,ico}',
146
+ '**/*.{woff,woff2,eot,ttf,otf}',
147
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
148
+ // @ts-ignore
149
+ ...(workbox_build_1.injectManifest.globPatterns || []),
150
+ ],
151
+ // those attributes are not overrideable
152
+ swDest,
153
+ swSrc: swDest,
154
+ globDirectory: props.outDir,
155
+ });
156
+ },
157
+ };
158
+ }
159
+ exports.default = default_1;
160
+ var options_1 = require("./options");
161
+ Object.defineProperty(exports, "validateOptions", { enumerable: true, get: function () { return options_1.validateOptions; } });
@@ -0,0 +1,5 @@
1
+ import { Joi } from '@docusaurus/utils-validation';
2
+ import type { ThemeConfig, ValidationResult, OptionValidationContext } from '@docusaurus/types';
3
+ import type { PluginOptions } from '@docusaurus/plugin-pwa';
4
+ export declare const Schema: Joi.ObjectSchema<any>;
5
+ export declare function validateOptions({ validate, options, }: OptionValidationContext<PluginOptions>): ValidationResult<ThemeConfig>;
package/lib/options.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateOptions = exports.Schema = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /**
6
+ * Copyright (c) Facebook, Inc. and its affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */
11
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
12
+ const utils_validation_1 = require("@docusaurus/utils-validation");
13
+ const DEFAULT_OPTIONS = {
14
+ debug: false,
15
+ offlineModeActivationStrategies: [
16
+ 'appInstalled',
17
+ 'queryString',
18
+ 'standalone',
19
+ ],
20
+ injectManifestConfig: {},
21
+ pwaHead: [],
22
+ swCustom: undefined,
23
+ swRegister: path_1.default.join(__dirname, 'registerSw.js'),
24
+ reloadPopup: '@theme/PwaReloadPopup',
25
+ };
26
+ exports.Schema = utils_validation_1.Joi.object({
27
+ debug: utils_validation_1.Joi.bool().default(DEFAULT_OPTIONS.debug),
28
+ offlineModeActivationStrategies: utils_validation_1.Joi.array()
29
+ .items(utils_validation_1.Joi.string()
30
+ .valid('appInstalled', 'queryString', 'standalone', 'mobile', 'saveData', 'always')
31
+ .required())
32
+ .default(DEFAULT_OPTIONS.offlineModeActivationStrategies),
33
+ injectManifestConfig: utils_validation_1.Joi.object().default(DEFAULT_OPTIONS.injectManifestConfig),
34
+ pwaHead: utils_validation_1.Joi.array()
35
+ .items(utils_validation_1.Joi.object({ tagName: utils_validation_1.Joi.string().required() }).unknown().required())
36
+ .default(DEFAULT_OPTIONS.pwaHead),
37
+ swCustom: utils_validation_1.Joi.string(),
38
+ swRegister: utils_validation_1.Joi.alternatives()
39
+ .try(utils_validation_1.Joi.string(), utils_validation_1.Joi.bool().valid(false))
40
+ .default(DEFAULT_OPTIONS.swRegister),
41
+ reloadPopup: utils_validation_1.Joi.alternatives()
42
+ .try(utils_validation_1.Joi.string(), utils_validation_1.Joi.bool().valid(false))
43
+ .default(DEFAULT_OPTIONS.reloadPopup),
44
+ });
45
+ function validateOptions({ validate, options, }) {
46
+ return validate(exports.Schema, options);
47
+ }
48
+ exports.validateOptions = validateOptions;
@@ -0,0 +1,303 @@
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
+
9
+ // First: read the env variables (provided by Webpack)
10
+ /* eslint-disable prefer-destructuring */
11
+ const PWA_SERVICE_WORKER_URL = process.env.PWA_SERVICE_WORKER_URL;
12
+ const PWA_RELOAD_POPUP = process.env.PWA_RELOAD_POPUP;
13
+ const PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES =
14
+ process.env.PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES;
15
+ const PWA_DEBUG = process.env.PWA_DEBUG;
16
+ /* eslint-enable prefer-destructuring */
17
+
18
+ const debug = PWA_DEBUG; // shortcut
19
+
20
+ const MAX_MOBILE_WIDTH = 940;
21
+
22
+ const AppInstalledEventFiredStorage = createStorageSlot(
23
+ 'docusaurus.pwa.event.appInstalled.fired',
24
+ );
25
+
26
+ async function clearRegistrations() {
27
+ const registrations = await navigator.serviceWorker.getRegistrations();
28
+ if (debug) {
29
+ console.log(
30
+ `[Docusaurus-PWA][registerSw]: will unregister all service worker registrations`,
31
+ registrations,
32
+ );
33
+ }
34
+ await Promise.all(
35
+ registrations.map(async (registration) => {
36
+ const result = await registration?.registration?.unregister();
37
+ if (debug) {
38
+ console.log(
39
+ `[Docusaurus-PWA][registerSw]: unregister() service worker registration`,
40
+ registrations,
41
+ result,
42
+ );
43
+ }
44
+ }),
45
+ );
46
+ if (debug) {
47
+ console.log(
48
+ `[Docusaurus-PWA][registerSw]: unregistered all service worker registrations`,
49
+ registrations,
50
+ );
51
+ }
52
+ window.location.reload();
53
+ }
54
+
55
+ /*
56
+ As of 2021:
57
+ It is complicated and not very reliable to detect an app is actually installed.
58
+ https://stackoverflow.com/questions/51735869/check-if-user-has-already-installed-pwa-to-homescreen-on-chrome
59
+
60
+ - 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
61
+ - getInstalledRelatedApps() is only supported in recent Chrome and does not seem to reliable either https://github.com/WICG/get-installed-related-apps
62
+ - 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/
63
+ */
64
+ async function isAppInstalledEventFired() {
65
+ return AppInstalledEventFiredStorage.get() === 'true';
66
+ }
67
+ async function isAppInstalledRelatedApps() {
68
+ if ('getInstalledRelatedApps' in window.navigator) {
69
+ const relatedApps = await navigator.getInstalledRelatedApps();
70
+ return relatedApps.some((app) => app.platform === 'webapp');
71
+ }
72
+ return false;
73
+ }
74
+ function isStandaloneDisplayMode() {
75
+ return window.matchMedia('(display-mode: standalone)').matches;
76
+ }
77
+
78
+ const OfflineModeActivationStrategiesImplementations = {
79
+ always: () => true,
80
+ mobile: () => window.innerWidth <= MAX_MOBILE_WIDTH,
81
+ saveData: () => !!(navigator.connection && navigator.connection.saveData),
82
+ appInstalled: async () => {
83
+ const installedEventFired = await isAppInstalledEventFired();
84
+ const installedRelatedApps = await isAppInstalledRelatedApps();
85
+ return installedEventFired || installedRelatedApps;
86
+ },
87
+ standalone: () => isStandaloneDisplayMode(),
88
+ queryString: () =>
89
+ new URLSearchParams(window.location.search).get('offlineMode') === 'true',
90
+ };
91
+
92
+ async function isStrategyActive(strategyName) {
93
+ return OfflineModeActivationStrategiesImplementations[strategyName]();
94
+ }
95
+
96
+ async function getActiveStrategies() {
97
+ const activeStrategies = await Promise.all(
98
+ PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES.map(async (strategyName) => {
99
+ const isActive = await isStrategyActive(strategyName);
100
+ return isActive ? strategyName : undefined;
101
+ }),
102
+ );
103
+ return activeStrategies.filter(Boolean); // remove undefined values
104
+ }
105
+
106
+ async function isOfflineModeEnabled() {
107
+ const activeStrategies = await getActiveStrategies();
108
+ const enabled = activeStrategies.length > 0;
109
+ if (debug) {
110
+ const logObject = {
111
+ activeStrategies,
112
+ availableStrategies: PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES,
113
+ };
114
+ if (enabled) {
115
+ console.log(
116
+ '[Docusaurus-PWA][registerSw]: offline mode enabled, because of activation strategies',
117
+ logObject,
118
+ );
119
+ } else {
120
+ console.log(
121
+ '[Docusaurus-PWA][registerSw]: offline mode disabled, because none of the offlineModeActivationStrategies could be used',
122
+ logObject,
123
+ );
124
+ }
125
+ }
126
+ return enabled;
127
+ }
128
+
129
+ function createServiceWorkerUrl(params) {
130
+ const paramsQueryString = JSON.stringify(params);
131
+ const url = `${PWA_SERVICE_WORKER_URL}?params=${encodeURIComponent(
132
+ paramsQueryString,
133
+ )}`;
134
+ if (debug) {
135
+ console.log(`[Docusaurus-PWA][registerSw]: service worker url`, {
136
+ url,
137
+ params,
138
+ });
139
+ }
140
+ return url;
141
+ }
142
+
143
+ async function registerSW() {
144
+ const {Workbox} = await import('workbox-window');
145
+
146
+ const offlineMode = await isOfflineModeEnabled();
147
+
148
+ const url = createServiceWorkerUrl({offlineMode, debug});
149
+ const wb = new Workbox(url);
150
+
151
+ const registration = await wb.register();
152
+
153
+ const sendSkipWaiting = () => wb.messageSW({type: 'SKIP_WAITING'});
154
+
155
+ const handleServiceWorkerWaiting = async () => {
156
+ if (debug) {
157
+ console.log('[Docusaurus-PWA][registerSw]: handleServiceWorkerWaiting');
158
+ }
159
+ // Immediately load new service worker when files aren't cached
160
+ if (!offlineMode) {
161
+ sendSkipWaiting();
162
+ } else if (PWA_RELOAD_POPUP) {
163
+ const renderReloadPopup = (await import('./renderReloadPopup')).default;
164
+ await renderReloadPopup({
165
+ onReload() {
166
+ wb.addEventListener('controlling', () => {
167
+ window.location.reload();
168
+ });
169
+ sendSkipWaiting();
170
+ },
171
+ });
172
+ }
173
+ };
174
+
175
+ if (debug) {
176
+ if (registration.active) {
177
+ console.log(
178
+ '[Docusaurus-PWA][registerSw]: registration.active',
179
+ registration,
180
+ );
181
+ }
182
+ if (registration.installing) {
183
+ console.log(
184
+ '[Docusaurus-PWA][registerSw]: registration.installing',
185
+ registration,
186
+ );
187
+ }
188
+ if (registration.waiting) {
189
+ console.log(
190
+ '[Docusaurus-PWA][registerSw]: registration.waiting',
191
+ registration,
192
+ );
193
+ }
194
+ }
195
+
196
+ // Update the current service worker when the next one has finished
197
+ // installing and transitions to waiting state.
198
+ wb.addEventListener('waiting', (event) => {
199
+ if (debug) {
200
+ console.log('[Docusaurus-PWA][registerSw]: event waiting', event);
201
+ }
202
+ handleServiceWorkerWaiting();
203
+ });
204
+
205
+ // Update current service worker if the next one finishes installing and
206
+ // moves to waiting state in another tab.
207
+ wb.addEventListener('externalwaiting', (event) => {
208
+ if (debug) {
209
+ console.log('[Docusaurus-PWA][registerSw]: event externalwaiting', event);
210
+ }
211
+ handleServiceWorkerWaiting();
212
+ });
213
+
214
+ // Update service worker if the next one is already in the waiting state.
215
+ // This happens when the user doesn't click on `reload` in the popup.
216
+ if (registration.waiting) {
217
+ await handleServiceWorkerWaiting();
218
+ }
219
+ }
220
+
221
+ // TODO these events still works in chrome but have been removed from the spec in 2019!
222
+ // See https://github.com/w3c/manifest/pull/836
223
+ function addLegacyAppInstalledEventsListeners() {
224
+ if (typeof window !== 'undefined') {
225
+ if (debug) {
226
+ console.log(
227
+ '[Docusaurus-PWA][registerSw]: addLegacyAppInstalledEventsListeners',
228
+ );
229
+ }
230
+
231
+ window.addEventListener('appinstalled', async (event) => {
232
+ if (debug) {
233
+ console.log('[Docusaurus-PWA][registerSw]: event appinstalled', event);
234
+ }
235
+
236
+ AppInstalledEventFiredStorage.set('true');
237
+ if (debug) {
238
+ console.log(
239
+ "[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.set('true')",
240
+ );
241
+ }
242
+
243
+ // After the app is installed, we register a service worker with the path
244
+ // `/sw?enabled`. Since the previous service worker was `/sw`, it'll be
245
+ // treated as a new one. The previous registration will need to be
246
+ // cleared, otherwise the reload popup will show.
247
+ await clearRegistrations();
248
+ });
249
+
250
+ // TODO this event still works in chrome but has been removed from the spec in 2019!!!
251
+ window.addEventListener('beforeinstallprompt', async (event) => {
252
+ if (debug) {
253
+ console.log(
254
+ '[Docusaurus-PWA][registerSw]: event beforeinstallprompt',
255
+ event,
256
+ );
257
+ }
258
+ // TODO instead of default browser install UI, show custom docusaurus prompt?
259
+ // event.preventDefault();
260
+ if (debug) {
261
+ console.log(
262
+ '[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.get()',
263
+ AppInstalledEventFiredStorage.get(),
264
+ );
265
+ }
266
+ if (AppInstalledEventFiredStorage.get()) {
267
+ AppInstalledEventFiredStorage.del();
268
+ if (debug) {
269
+ console.log(
270
+ '[Docusaurus-PWA][registerSw]: AppInstalledEventFiredStorage.del()',
271
+ );
272
+ }
273
+ // After uninstalling the app, if the user doesn't clear all data, then
274
+ // the previous service worker will continue serving cached files. We
275
+ // need to clear registrations and reload, otherwise the popup will show.
276
+ await clearRegistrations();
277
+ }
278
+ });
279
+
280
+ if (debug) {
281
+ console.log(
282
+ '[Docusaurus-PWA][registerSw]: legacy appinstalled and beforeinstallprompt event listeners installed',
283
+ );
284
+ }
285
+ }
286
+ }
287
+
288
+ /*
289
+ Init code to run on the client!
290
+ */
291
+ if (typeof window !== 'undefined') {
292
+ if (debug) {
293
+ console.log('[Docusaurus-PWA][registerSw]: debug mode enabled');
294
+ }
295
+
296
+ if ('serviceWorker' in navigator) {
297
+ // First: add the listeners asap/synchronously
298
+ addLegacyAppInstalledEventsListeners();
299
+
300
+ // Then try to register the SW using lazy/dynamic imports
301
+ registerSW().catch((e) => console.error('registerSW failed', e));
302
+ }
303
+ }
@@ -0,0 +1,26 @@
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
+
8
+ import React from 'react';
9
+ import {render} from 'react-dom';
10
+
11
+ const POPUP_CONTAINER_ID = 'pwa-popup-container';
12
+
13
+ const getContainer = () => document.getElementById(POPUP_CONTAINER_ID);
14
+
15
+ const createContainer = () => {
16
+ const container = document.createElement('div');
17
+ container.id = POPUP_CONTAINER_ID;
18
+ document.body.appendChild(container);
19
+ return container;
20
+ };
21
+
22
+ export default async function renderReloadPopup(props) {
23
+ const container = getContainer() || createContainer();
24
+ const {default: ReloadPopup} = await import(process.env.PWA_RELOAD_POPUP);
25
+ render(<ReloadPopup {...props} />, container);
26
+ }
package/lib/sw.js ADDED
@@ -0,0 +1,145 @@
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
+
9
+ import {PrecacheController} from 'workbox-precaching';
10
+
11
+ function parseSwParams() {
12
+ const params = JSON.parse(
13
+ new URLSearchParams(self.location.search).get('params'),
14
+ );
15
+ if (params.debug) {
16
+ console.log('[Docusaurus-PWA][SW]: Service Worker params:', params);
17
+ }
18
+ return params;
19
+ }
20
+
21
+ // doc advise against dynamic imports in SW
22
+ // https://developers.google.com/web/tools/workbox/guides/using-bundlers#code_splitting_and_dynamic_imports
23
+ // https://twitter.com/sebastienlorber/status/1280155204575518720
24
+ // but I think it's working fine as it's inlined by webpack, need to double check?
25
+ async function runSWCustomCode(params) {
26
+ if (process.env.PWA_SW_CUSTOM) {
27
+ const customSW = await import(process.env.PWA_SW_CUSTOM);
28
+ if (typeof customSW.default === 'function') {
29
+ customSW.default(params);
30
+ } else if (params.debug) {
31
+ console.warn(
32
+ '[Docusaurus-PWA][SW]: swCustom should have a default export function',
33
+ );
34
+ }
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Gets different possible variations for a request URL. Similar to
40
+ * https://git.io/JvixK
41
+ *
42
+ * @param {string} url
43
+ */
44
+ function getPossibleURLs(url) {
45
+ const possibleURLs = [];
46
+ const urlObject = new URL(url, self.location.href);
47
+
48
+ if (urlObject.origin !== self.location.origin) {
49
+ return possibleURLs;
50
+ }
51
+
52
+ // Ignore search params and hash
53
+ urlObject.search = '';
54
+ urlObject.hash = '';
55
+
56
+ // /blog.html
57
+ possibleURLs.push(urlObject.href);
58
+
59
+ // /blog/ => /blog/index.html
60
+ if (urlObject.pathname.endsWith('/')) {
61
+ possibleURLs.push(`${urlObject.href}index.html`);
62
+ } else {
63
+ // /blog => /blog/index.html
64
+ possibleURLs.push(`${urlObject.href}/index.html`);
65
+ }
66
+
67
+ return possibleURLs;
68
+ }
69
+
70
+ (async () => {
71
+ const params = parseSwParams();
72
+
73
+ const precacheManifest = self.__WB_MANIFEST;
74
+ const controller = new PrecacheController({
75
+ fallbackToNetwork: true, // safer to turn this true?
76
+ });
77
+
78
+ if (params.offlineMode) {
79
+ controller.addToCacheList(precacheManifest);
80
+ if (params.debug) {
81
+ console.log('[Docusaurus-PWA][SW]: addToCacheList', {
82
+ precacheManifest,
83
+ });
84
+ }
85
+ }
86
+
87
+ await runSWCustomCode(params);
88
+
89
+ self.addEventListener('install', (event) => {
90
+ if (params.debug) {
91
+ console.log('[Docusaurus-PWA][SW]: install event', {
92
+ event,
93
+ });
94
+ }
95
+ event.waitUntil(controller.install(event));
96
+ });
97
+
98
+ self.addEventListener('activate', (event) => {
99
+ if (params.debug) {
100
+ console.log('[Docusaurus-PWA][SW]: activate event', {
101
+ event,
102
+ });
103
+ }
104
+ event.waitUntil(controller.activate(event));
105
+ });
106
+
107
+ self.addEventListener('fetch', async (event) => {
108
+ if (params.offlineMode) {
109
+ const requestURL = event.request.url;
110
+ const possibleURLs = getPossibleURLs(requestURL);
111
+ for (let i = 0; i < possibleURLs.length; i += 1) {
112
+ const possibleURL = possibleURLs[i];
113
+ const cacheKey = controller.getCacheKeyForURL(possibleURL);
114
+ if (cacheKey) {
115
+ const cachedResponse = caches.match(cacheKey);
116
+ if (params.debug) {
117
+ console.log('[Docusaurus-PWA][SW]: serving cached asset', {
118
+ requestURL,
119
+ possibleURL,
120
+ possibleURLs,
121
+ cacheKey,
122
+ cachedResponse,
123
+ });
124
+ }
125
+ event.respondWith(cachedResponse);
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ });
131
+
132
+ self.addEventListener('message', async (event) => {
133
+ if (params.debug) {
134
+ console.log('[Docusaurus-PWA][SW]: message event', {
135
+ event,
136
+ });
137
+ }
138
+
139
+ const type = event.data && event.data.type;
140
+
141
+ if (type === 'SKIP_WAITING') {
142
+ self.skipWaiting();
143
+ }
144
+ });
145
+ })();
@@ -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
+ /// <reference types="react" />
8
+ import type { PwaReloadPopupProps } from '@theme/PwaReloadPopup';
9
+ declare function PwaReloadPopup({ onReload }: PwaReloadPopupProps): JSX.Element | false;
10
+ export default PwaReloadPopup;
@@ -0,0 +1,39 @@
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, { useState } from 'react';
8
+ import clsx from 'clsx';
9
+ import Translate, { translate } from '@docusaurus/Translate';
10
+ import styles from './styles.module.css';
11
+ function PwaReloadPopup({ onReload }) {
12
+ const [isVisible, setIsVisible] = useState(true);
13
+ return (isVisible && (<div className={clsx('alert', 'alert--secondary', styles.popup)}>
14
+ <p>
15
+ <Translate id="theme.PwaReloadPopup.info" description="The text for PWA reload popup">
16
+ New version available
17
+ </Translate>
18
+ </p>
19
+ <div className={styles.buttonContainer}>
20
+ <button className="button button--link" type="button" onClick={() => {
21
+ setIsVisible(false);
22
+ onReload();
23
+ }}>
24
+ <Translate id="theme.PwaReloadPopup.refreshButtonText" description="The text for PWA reload button">
25
+ Refresh
26
+ </Translate>
27
+ </button>
28
+
29
+ <button aria-label={translate({
30
+ id: 'theme.PwaReloadPopup.closeButtonAriaLabel',
31
+ message: 'Close',
32
+ description: 'The ARIA label for close button of PWA reload popup',
33
+ })} className="close" type="button" onClick={() => setIsVisible(false)}>
34
+ <span aria-hidden="true">×</span>
35
+ </button>
36
+ </div>
37
+ </div>));
38
+ }
39
+ export default PwaReloadPopup;
@@ -0,0 +1,39 @@
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
+
8
+ .popup {
9
+ position: fixed;
10
+ bottom: 16px;
11
+ right: 16px;
12
+ width: 344px;
13
+ display: flex;
14
+ align-items: center;
15
+ justify-content: space-between;
16
+ z-index: 999;
17
+ }
18
+
19
+ .popup p {
20
+ margin: 0;
21
+ }
22
+
23
+ @media screen and (max-width: 500px) {
24
+ .popup {
25
+ width: 100%;
26
+ bottom: 0;
27
+ right: 0;
28
+ }
29
+ }
30
+
31
+ .buttonContainer {
32
+ display: flex;
33
+ align-items: center;
34
+ }
35
+
36
+ .buttonContainer :global(.close) {
37
+ margin: 0;
38
+ padding: 0;
39
+ }
package/package.json CHANGED
@@ -1,8 +1,15 @@
1
1
  {
2
2
  "name": "@docusaurus/plugin-pwa",
3
- "version": "0.0.0-4194",
3
+ "version": "0.0.0-4203",
4
4
  "description": "Docusaurus Plugin to add PWA support.",
5
- "main": "src/index.js",
5
+ "main": "lib/index.js",
6
+ "types": "src/plugin-pwa.d.ts",
7
+ "scripts": {
8
+ "build": "yarn build:server && yarn build:browser && yarn build:copy",
9
+ "build:server": "tsc --project tsconfig.server.json",
10
+ "build:browser": "tsc --project tsconfig.browser.json",
11
+ "build:copy": "node copyUntypedFiles.js"
12
+ },
6
13
  "publishConfig": {
7
14
  "access": "public"
8
15
  },
@@ -16,10 +23,10 @@
16
23
  "@babel/plugin-proposal-nullish-coalescing-operator": "^7.12.13",
17
24
  "@babel/plugin-proposal-optional-chaining": "^7.12.16",
18
25
  "@babel/preset-env": "^7.15.6",
19
- "@docusaurus/core": "0.0.0-4194",
20
- "@docusaurus/theme-common": "0.0.0-4194",
21
- "@docusaurus/utils": "0.0.0-4194",
22
- "@docusaurus/utils-validation": "0.0.0-4194",
26
+ "@docusaurus/core": "0.0.0-4203",
27
+ "@docusaurus/theme-common": "0.0.0-4203",
28
+ "@docusaurus/utils": "0.0.0-4203",
29
+ "@docusaurus/utils-validation": "0.0.0-4203",
23
30
  "babel-loader": "^8.2.2",
24
31
  "clsx": "^1.1.1",
25
32
  "core-js": "^2.6.5",
@@ -30,10 +37,14 @@
30
37
  "workbox-precaching": "^6.1.1",
31
38
  "workbox-window": "^6.1.1"
32
39
  },
40
+ "devDependencies": {
41
+ "@docusaurus/module-type-aliases": "0.0.0-4203",
42
+ "fs-extra": "^10.0.0"
43
+ },
33
44
  "peerDependencies": {
34
45
  "@babel/core": "^7.0.0",
35
46
  "react": "^16.8.4 || ^17.0.0",
36
47
  "react-dom": "^16.8.4 || ^17.0.0"
37
48
  },
38
- "gitHead": "a1d0d7eccb76e4fc7f44a694b99de88fe6f97272"
49
+ "gitHead": "c593f92915e118d87c10015d5db2c42eda4b5ef3"
39
50
  }
@@ -5,15 +5,17 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- const LogPlugin =
9
- require('@docusaurus/core/lib/webpack/plugins/LogPlugin').default;
10
- const {compile} = require('@docusaurus/core/lib/webpack/utils');
11
- const {normalizeUrl} = require('@docusaurus/utils');
12
- const path = require('path');
13
- const webpack = require('webpack');
14
- const {injectManifest} = require('workbox-build');
15
- const {PluginOptionSchema} = require('./pluginOptionSchema');
16
- const Terser = require('terser-webpack-plugin');
8
+ import type {HtmlTags, LoadContext, Plugin} from '@docusaurus/types';
9
+ import type {PluginOptions} from '@docusaurus/plugin-pwa';
10
+ import {normalizeUrl} from '@docusaurus/utils';
11
+ import {compile} from '@docusaurus/core/lib/webpack/utils';
12
+ import LogPlugin from '@docusaurus/core/lib/webpack/plugins/LogPlugin';
13
+
14
+ import path from 'path';
15
+ import webpack, {Configuration} from 'webpack';
16
+ import Terser from 'terser-webpack-plugin';
17
+
18
+ import {injectManifest} from 'workbox-build';
17
19
 
18
20
  const isProd = process.env.NODE_ENV === 'production';
19
21
 
@@ -43,7 +45,10 @@ function getSWBabelLoader() {
43
45
  };
44
46
  }
45
47
 
46
- function plugin(context, options) {
48
+ export default function (
49
+ context: LoadContext,
50
+ options: PluginOptions,
51
+ ): Plugin<void> {
47
52
  const {outDir, baseUrl} = context;
48
53
  const {
49
54
  debug,
@@ -76,7 +81,7 @@ function plugin(context, options) {
76
81
  new webpack.EnvironmentPlugin({
77
82
  PWA_DEBUG: debug,
78
83
  PWA_SERVICE_WORKER_URL: path.posix.resolve(
79
- `${config.output.publicPath || '/'}`,
84
+ `${config.output?.publicPath || '/'}`,
80
85
  'sw.js',
81
86
  ),
82
87
  PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES:
@@ -88,10 +93,10 @@ function plugin(context, options) {
88
93
  },
89
94
 
90
95
  injectHtmlTags() {
91
- const headTags = [];
96
+ const headTags: HtmlTags = [];
92
97
  if (isProd && pwaHead) {
93
98
  pwaHead.forEach(({tagName, ...attributes}) => {
94
- ['href', 'content'].forEach((attribute) => {
99
+ (['href', 'content'] as const).forEach((attribute) => {
95
100
  const attributeValue = attributes[attribute];
96
101
 
97
102
  if (!attributeValue) {
@@ -122,7 +127,7 @@ function plugin(context, options) {
122
127
 
123
128
  const swSourceFileTest = /\.m?js$/;
124
129
 
125
- const swWebpackConfig = {
130
+ const swWebpackConfig: Configuration = {
126
131
  entry: path.resolve(__dirname, 'sw.js'),
127
132
  output: {
128
133
  path: outDir,
@@ -136,12 +141,13 @@ function plugin(context, options) {
136
141
  splitChunks: false,
137
142
  minimize: !debug,
138
143
  // see https://developers.google.com/web/tools/workbox/guides/using-bundlers#webpack
139
- minimizer: [
140
- !debug &&
141
- new Terser({
142
- test: swSourceFileTest,
143
- }),
144
- ].filter(Boolean),
144
+ minimizer: debug
145
+ ? []
146
+ : [
147
+ new Terser({
148
+ test: swSourceFileTest,
149
+ }),
150
+ ],
145
151
  },
146
152
  plugins: [
147
153
  new webpack.EnvironmentPlugin({
@@ -173,6 +179,8 @@ function plugin(context, options) {
173
179
  '**/*.{js,json,css,html}',
174
180
  '**/*.{png,jpg,jpeg,gif,svg,ico}',
175
181
  '**/*.{woff,woff2,eot,ttf,otf}',
182
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
183
+ // @ts-ignore
176
184
  ...(injectManifest.globPatterns || []),
177
185
  ],
178
186
  // those attributes are not overrideable
@@ -184,8 +192,4 @@ function plugin(context, options) {
184
192
  };
185
193
  }
186
194
 
187
- module.exports = plugin;
188
-
189
- plugin.validateOptions = function validateOptions({validate, options}) {
190
- return validate(PluginOptionSchema, options);
191
- };
195
+ export {validateOptions} from './options';
@@ -4,9 +4,14 @@
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
- const {Joi} = require('@docusaurus/utils-validation');
9
- const path = require('path');
7
+ import path from 'path';
8
+ import {Joi} from '@docusaurus/utils-validation';
9
+ import type {
10
+ ThemeConfig,
11
+ ValidationResult,
12
+ OptionValidationContext,
13
+ } from '@docusaurus/types';
14
+ import type {PluginOptions} from '@docusaurus/plugin-pwa';
10
15
 
11
16
  const DEFAULT_OPTIONS = {
12
17
  debug: false,
@@ -22,7 +27,7 @@ const DEFAULT_OPTIONS = {
22
27
  reloadPopup: '@theme/PwaReloadPopup',
23
28
  };
24
29
 
25
- exports.PluginOptionSchema = Joi.object({
30
+ export const Schema = Joi.object({
26
31
  debug: Joi.bool().default(DEFAULT_OPTIONS.debug),
27
32
  offlineModeActivationStrategies: Joi.array()
28
33
  .items(
@@ -52,3 +57,10 @@ exports.PluginOptionSchema = Joi.object({
52
57
  .try(Joi.string(), Joi.bool().valid(false))
53
58
  .default(DEFAULT_OPTIONS.reloadPopup),
54
59
  });
60
+
61
+ export function validateOptions({
62
+ validate,
63
+ options,
64
+ }: OptionValidationContext<PluginOptions>): ValidationResult<ThemeConfig> {
65
+ return validate(Schema, options);
66
+ }
@@ -0,0 +1,34 @@
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
+
8
+ declare module '@docusaurus/plugin-pwa' {
9
+ export type pwaHead = {
10
+ tagName: string;
11
+ href?: string;
12
+ content?: string;
13
+ [attributeName: string]: string | boolean;
14
+ };
15
+
16
+ export type PluginOptions = {
17
+ debug?: boolean;
18
+ offlineModeActivationStrategies;
19
+ injectManifestConfig;
20
+ reloadPopup;
21
+ pwaHead: pwaHead[];
22
+ swCustom;
23
+ swRegister;
24
+ };
25
+ }
26
+
27
+ declare module '@theme/PwaReloadPopup' {
28
+ export type PwaReloadPopupProps = {
29
+ readonly onReload: () => void;
30
+ };
31
+
32
+ const PwaReloadPopup: (props: PwaReloadPopupProps) => JSX.Element;
33
+ export default PwaReloadPopup;
34
+ }
@@ -9,9 +9,11 @@ import React, {useState} from 'react';
9
9
  import clsx from 'clsx';
10
10
  import Translate, {translate} from '@docusaurus/Translate';
11
11
 
12
+ import type {PwaReloadPopupProps} from '@theme/PwaReloadPopup';
13
+
12
14
  import styles from './styles.module.css';
13
15
 
14
- export default function PwaReloadPopup({onReload}) {
16
+ function PwaReloadPopup({onReload}: PwaReloadPopupProps): JSX.Element | false {
15
17
  const [isVisible, setIsVisible] = useState(true);
16
18
 
17
19
  return (
@@ -56,3 +58,5 @@ export default function PwaReloadPopup({onReload}) {
56
58
  )
57
59
  );
58
60
  }
61
+
62
+ export default PwaReloadPopup;
package/src/types.d.ts ADDED
@@ -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
+
8
+ /// <reference types="@docusaurus/module-type-aliases" />
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "esnext",
5
+ "jsx": "react-native"
6
+ },
7
+ "include": ["src/theme/", "src/*.d.ts"]
8
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "lib": ["DOM", "ES2019"],
5
+ "rootDir": "src",
6
+ "baseUrl": "src",
7
+ "outDir": "lib"
8
+ }
9
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "include": ["src/*.ts"]
4
+ }