module-registry.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. /*
  3. Copyright 2019 Google LLC
  4. Use of this source code is governed by an MIT-style
  5. license that can be found in the LICENSE file or at
  6. https://opensource.org/licenses/MIT.
  7. */
  8. const ol = require('common-tags').oneLine;
  9. const upath = require('upath');
  10. /**
  11. * Class for keeping track of which Workbox modules are used by the generated
  12. * service worker script.
  13. *
  14. * @private
  15. */
  16. class ModuleRegistry {
  17. /**
  18. * @private
  19. */
  20. constructor() {
  21. this.modulesUsed = new Map();
  22. }
  23. /**
  24. * @return {Array<string>} A list of all of the import statements that are
  25. * needed for the modules being used.
  26. * @private
  27. */
  28. getImportStatements() {
  29. const workboxModuleImports = [];
  30. for (const [localName, {
  31. moduleName,
  32. pkg
  33. }] of this.modulesUsed) {
  34. // By default require.resolve returns the resolved path of the 'main'
  35. // field, which might be deeper than the package root. To work around
  36. // this, we can find the package's root by resolving its package.json and
  37. // strip the '/package.json' from the resolved path.
  38. const pkgJsonPath = require.resolve(`${pkg}/package.json`);
  39. const pkgRoot = upath.dirname(pkgJsonPath);
  40. const importStatement = ol`import {${moduleName} as ${localName}} from
  41. '${pkgRoot}/${moduleName}.mjs';`;
  42. workboxModuleImports.push(importStatement);
  43. }
  44. return workboxModuleImports;
  45. }
  46. /**
  47. * @param {string} pkg The workbox package that the module belongs to.
  48. * @param {string} moduleName The name of the module to import.
  49. * @return {string} The local variable name that corresponds to that module.
  50. * @private
  51. */
  52. getLocalName(pkg, moduleName) {
  53. return `${pkg.replace(/-/g, '_')}_${moduleName}`;
  54. }
  55. /**
  56. * @param {string} pkg The workbox package that the module belongs to.
  57. * @param {string} moduleName The name of the module to import.
  58. * @return {string} The local variable name that corresponds to that module.
  59. * @private
  60. */
  61. use(pkg, moduleName) {
  62. const localName = this.getLocalName(pkg, moduleName);
  63. this.modulesUsed.set(localName, {
  64. moduleName,
  65. pkg
  66. });
  67. return localName;
  68. }
  69. }
  70. module.exports = ModuleRegistry;