index.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright Google LLC All Rights Reserved.
  5. *
  6. * Use of this source code is governed by an MIT-style license that can be
  7. * found in the LICENSE file at https://angular.dev/license
  8. */
  9. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. var desc = Object.getOwnPropertyDescriptor(m, k);
  12. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  13. desc = { enumerable: true, get: function() { return m[k]; } };
  14. }
  15. Object.defineProperty(o, k2, desc);
  16. }) : (function(o, m, k, k2) {
  17. if (k2 === undefined) k2 = k;
  18. o[k2] = m[k];
  19. }));
  20. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  21. Object.defineProperty(o, "default", { enumerable: true, value: v });
  22. }) : function(o, v) {
  23. o["default"] = v;
  24. });
  25. var __importStar = (this && this.__importStar) || (function () {
  26. var ownKeys = function(o) {
  27. ownKeys = Object.getOwnPropertyNames || function (o) {
  28. var ar = [];
  29. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  30. return ar;
  31. };
  32. return ownKeys(o);
  33. };
  34. return function (mod) {
  35. if (mod && mod.__esModule) return mod;
  36. var result = {};
  37. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  38. __setModuleDefault(result, mod);
  39. return result;
  40. };
  41. })();
  42. Object.defineProperty(exports, "__esModule", { value: true });
  43. exports.default = default_1;
  44. const core_1 = require("@angular-devkit/core");
  45. const schematics_1 = require("@angular-devkit/schematics");
  46. const ts = __importStar(require("../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
  47. const utility_1 = require("../utility");
  48. const ast_utils_1 = require("../utility/ast-utils");
  49. const change_1 = require("../utility/change");
  50. const dependencies_1 = require("../utility/dependencies");
  51. const ng_ast_utils_1 = require("../utility/ng-ast-utils");
  52. const paths_1 = require("../utility/paths");
  53. const project_targets_1 = require("../utility/project-targets");
  54. const app_config_1 = require("../utility/standalone/app_config");
  55. const util_1 = require("../utility/standalone/util");
  56. const workspace_models_1 = require("../utility/workspace-models");
  57. function addDependencies() {
  58. return (host) => {
  59. const coreDep = (0, dependencies_1.getPackageJsonDependency)(host, '@angular/core');
  60. if (!coreDep) {
  61. throw new schematics_1.SchematicsException('Could not find "@angular/core" version.');
  62. }
  63. return (0, utility_1.addDependency)('@angular/service-worker', coreDep.version);
  64. };
  65. }
  66. function updateAppModule(mainPath) {
  67. return (host, context) => {
  68. context.logger.debug('Updating appmodule');
  69. const modulePath = (0, ng_ast_utils_1.getAppModulePath)(host, mainPath);
  70. context.logger.debug(`module path: ${modulePath}`);
  71. addImport(host, modulePath, 'ServiceWorkerModule', '@angular/service-worker');
  72. addImport(host, modulePath, 'isDevMode', '@angular/core');
  73. // register SW in application module
  74. const importText = core_1.tags.stripIndent `
  75. ServiceWorkerModule.register('ngsw-worker.js', {
  76. enabled: !isDevMode(),
  77. // Register the ServiceWorker as soon as the application is stable
  78. // or after 30 seconds (whichever comes first).
  79. registrationStrategy: 'registerWhenStable:30000'
  80. })
  81. `;
  82. const moduleSource = getTsSourceFile(host, modulePath);
  83. const metadataChanges = (0, ast_utils_1.addSymbolToNgModuleMetadata)(moduleSource, modulePath, 'imports', importText);
  84. if (metadataChanges) {
  85. const recorder = host.beginUpdate(modulePath);
  86. (0, change_1.applyToUpdateRecorder)(recorder, metadataChanges);
  87. host.commitUpdate(recorder);
  88. }
  89. return host;
  90. };
  91. }
  92. function addProvideServiceWorker(projectName, mainPath) {
  93. return (host) => {
  94. const bootstrapCall = (0, util_1.findBootstrapApplicationCall)(host, mainPath);
  95. const appConfig = (0, app_config_1.findAppConfig)(bootstrapCall, host, mainPath)?.filePath || mainPath;
  96. addImport(host, appConfig, 'isDevMode', '@angular/core');
  97. return (0, utility_1.addRootProvider)(projectName, ({ code, external }) => code `${external('provideServiceWorker', '@angular/service-worker')}('ngsw-worker.js', {
  98. enabled: !isDevMode(),
  99. registrationStrategy: 'registerWhenStable:30000'
  100. })`);
  101. };
  102. }
  103. function getTsSourceFile(host, path) {
  104. const content = host.readText(path);
  105. const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
  106. return source;
  107. }
  108. function default_1(options) {
  109. return async (host) => {
  110. const workspace = await (0, utility_1.readWorkspace)(host);
  111. const project = workspace.projects.get(options.project);
  112. if (!project) {
  113. throw new schematics_1.SchematicsException(`Invalid project name (${options.project})`);
  114. }
  115. if (project.extensions.projectType !== 'application') {
  116. throw new schematics_1.SchematicsException(`Service worker requires a project type of "application".`);
  117. }
  118. const buildTarget = project.targets.get('build');
  119. if (!buildTarget) {
  120. throw (0, project_targets_1.targetBuildNotFoundError)();
  121. }
  122. const buildOptions = buildTarget.options;
  123. let browserEntryPoint;
  124. const ngswConfigPath = (0, core_1.join)((0, core_1.normalize)(project.root), 'ngsw-config.json');
  125. if (buildTarget.builder === workspace_models_1.Builders.Application ||
  126. buildTarget.builder === workspace_models_1.Builders.BuildApplication) {
  127. browserEntryPoint = buildOptions.browser;
  128. const productionConf = buildTarget.configurations?.production;
  129. if (productionConf) {
  130. productionConf.serviceWorker = ngswConfigPath;
  131. }
  132. }
  133. else {
  134. browserEntryPoint = buildOptions.main;
  135. buildOptions.serviceWorker = true;
  136. buildOptions.ngswConfigPath = ngswConfigPath;
  137. }
  138. await (0, utility_1.writeWorkspace)(host, workspace);
  139. return (0, schematics_1.chain)([
  140. addDependencies(),
  141. (0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)('./files'), [
  142. (0, schematics_1.applyTemplates)({
  143. ...options,
  144. relativePathToWorkspaceRoot: (0, paths_1.relativePathToWorkspaceRoot)(project.root),
  145. }),
  146. (0, schematics_1.move)(project.root),
  147. ])),
  148. (0, ng_ast_utils_1.isStandaloneApp)(host, browserEntryPoint)
  149. ? addProvideServiceWorker(options.project, browserEntryPoint)
  150. : updateAppModule(browserEntryPoint),
  151. ]);
  152. };
  153. }
  154. function addImport(host, filePath, symbolName, moduleName) {
  155. const moduleSource = getTsSourceFile(host, filePath);
  156. const change = (0, ast_utils_1.insertImport)(moduleSource, filePath, symbolName, moduleName);
  157. if (change) {
  158. const recorder = host.beginUpdate(filePath);
  159. (0, change_1.applyToUpdateRecorder)(recorder, [change]);
  160. host.commitUpdate(recorder);
  161. }
  162. }