WorkboxSW.mjs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import '../_version.mjs';
  8. const CDN_PATH = `WORKBOX_CDN_ROOT_URL`;
  9. const MODULE_KEY_TO_NAME_MAPPING = {
  10. /**
  11. * @name backgroundSync
  12. * @memberof workbox
  13. * @see module:workbox-background-sync
  14. */
  15. backgroundSync: 'background-sync',
  16. /**
  17. * @name broadcastUpdate
  18. * @memberof workbox
  19. * @see module:workbox-broadcast-update
  20. */
  21. broadcastUpdate: 'broadcast-update',
  22. /**
  23. * @name cacheableResponse
  24. * @memberof workbox
  25. * @see module:workbox-cacheable-response
  26. */
  27. cacheableResponse: 'cacheable-response',
  28. /**
  29. * @name core
  30. * @memberof workbox
  31. * @see module:workbox-core
  32. */
  33. core: 'core',
  34. /**
  35. * @name expiration
  36. * @memberof workbox
  37. * @see module:workbox-expiration
  38. */
  39. expiration: 'expiration',
  40. /**
  41. * @name googleAnalytics
  42. * @memberof workbox
  43. * @see module:workbox-google-analytics
  44. */
  45. googleAnalytics: 'offline-ga',
  46. /**
  47. * @name navigationPreload
  48. * @memberof workbox
  49. * @see module:workbox-navigation-preload
  50. */
  51. navigationPreload: 'navigation-preload',
  52. /**
  53. * @name precaching
  54. * @memberof workbox
  55. * @see module:workbox-precaching
  56. */
  57. precaching: 'precaching',
  58. /**
  59. * @name rangeRequests
  60. * @memberof workbox
  61. * @see module:workbox-range-requests
  62. */
  63. rangeRequests: 'range-requests',
  64. /**
  65. * @name routing
  66. * @memberof workbox
  67. * @see module:workbox-routing
  68. */
  69. routing: 'routing',
  70. /**
  71. * @name strategies
  72. * @memberof workbox
  73. * @see module:workbox-strategies
  74. */
  75. strategies: 'strategies',
  76. /**
  77. * @name streams
  78. * @memberof workbox
  79. * @see module:workbox-streams
  80. */
  81. streams: 'streams',
  82. /**
  83. * @name recipes
  84. * @memberof workbox
  85. * @see module:workbox-recipes
  86. */
  87. recipes: 'recipes',
  88. };
  89. /**
  90. * This class can be used to make it easy to use the various parts of
  91. * Workbox.
  92. *
  93. * @private
  94. */
  95. export class WorkboxSW {
  96. /**
  97. * Creates a proxy that automatically loads workbox namespaces on demand.
  98. *
  99. * @private
  100. */
  101. constructor() {
  102. this.v = {};
  103. this._options = {
  104. debug: self.location.hostname === 'localhost',
  105. modulePathPrefix: null,
  106. modulePathCb: null,
  107. };
  108. this._env = this._options.debug ? 'dev' : 'prod';
  109. this._modulesLoaded = false;
  110. return new Proxy(this, {
  111. get(target, key) {
  112. if (target[key]) {
  113. return target[key];
  114. }
  115. const moduleName = MODULE_KEY_TO_NAME_MAPPING[key];
  116. if (moduleName) {
  117. target.loadModule(`workbox-${moduleName}`);
  118. }
  119. return target[key];
  120. },
  121. });
  122. }
  123. /**
  124. * Updates the configuration options. You can specify whether to treat as a
  125. * debug build and whether to use a CDN or a specific path when importing
  126. * other workbox-modules
  127. *
  128. * @param {Object} [options]
  129. * @param {boolean} [options.debug] If true, `dev` builds are using, otherwise
  130. * `prod` builds are used. By default, `prod` is used unless on localhost.
  131. * @param {Function} [options.modulePathPrefix] To avoid using the CDN with
  132. * `workbox-sw` set the path prefix of where modules should be loaded from.
  133. * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`.
  134. * @param {workbox~ModulePathCallback} [options.modulePathCb] If defined,
  135. * this callback will be responsible for determining the path of each
  136. * workbox module.
  137. *
  138. * @alias workbox.setConfig
  139. */
  140. setConfig(options = {}) {
  141. if (!this._modulesLoaded) {
  142. Object.assign(this._options, options);
  143. this._env = this._options.debug ? 'dev' : 'prod';
  144. } else {
  145. throw new Error('Config must be set before accessing workbox.* modules');
  146. }
  147. }
  148. /**
  149. * Load a Workbox module by passing in the appropriate module name.
  150. *
  151. * This is not generally needed unless you know there are modules that are
  152. * dynamically used and you want to safe guard use of the module while the
  153. * user may be offline.
  154. *
  155. * @param {string} moduleName
  156. *
  157. * @alias workbox.loadModule
  158. */
  159. loadModule(moduleName) {
  160. const modulePath = this._getImportPath(moduleName);
  161. try {
  162. importScripts(modulePath);
  163. this._modulesLoaded = true;
  164. } catch (err) {
  165. // TODO Add context of this error if using the CDN vs the local file.
  166. // We can't rely on workbox-core being loaded so using console
  167. // eslint-disable-next-line
  168. console.error(
  169. `Unable to import module '${moduleName}' from '${modulePath}'.`);
  170. throw err;
  171. }
  172. }
  173. /**
  174. * This method will get the path / CDN URL to be used for importScript calls.
  175. *
  176. * @param {string} moduleName
  177. * @return {string} URL to the desired module.
  178. *
  179. * @private
  180. */
  181. _getImportPath(moduleName) {
  182. if (this._options.modulePathCb) {
  183. return this._options.modulePathCb(moduleName, this._options.debug);
  184. }
  185. // TODO: This needs to be dynamic some how.
  186. let pathParts = [CDN_PATH];
  187. const fileName = `${moduleName}.${this._env}.js`;
  188. const pathPrefix = this._options.modulePathPrefix;
  189. if (pathPrefix) {
  190. // Split to avoid issues with developers ending / not ending with slash
  191. pathParts = pathPrefix.split('/');
  192. // We don't need a slash at the end as we will be adding
  193. // a filename regardless
  194. if (pathParts[pathParts.length - 1] === '') {
  195. pathParts.splice(pathParts.length - 1, 1);
  196. }
  197. }
  198. pathParts.push(fileName);
  199. return pathParts.join('/');
  200. }
  201. }