forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
163 lines (144 loc) · 5.43 KB
/
index.ts
File metadata and controls
163 lines (144 loc) · 5.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Rule,
SchematicContext,
SchematicsException,
Tree,
apply,
applyTemplates,
chain,
mergeWith,
move,
url,
} from '@angular-devkit/schematics';
import { join } from 'node:path/posix';
import ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { addDependency, addRootProvider, writeWorkspace } from '../utility';
import { addSymbolToNgModuleMetadata, insertImport } from '../utility/ast-utils';
import { applyToUpdateRecorder } from '../utility/change';
import { getDependency } from '../utility/dependency';
import { getAppModulePath, isStandaloneApp } from '../utility/ng-ast-utils';
import { relativePathToWorkspaceRoot } from '../utility/paths';
import { createProjectSchematic } from '../utility/project';
import { targetBuildNotFoundError } from '../utility/project-targets';
import { findAppConfig } from '../utility/standalone/app_config';
import { findBootstrapApplicationCall, getMainFilePath } from '../utility/standalone/util';
import { Builders } from '../utility/workspace-models';
import { Schema as ServiceWorkerOptions } from './schema';
function addDependencies(): Rule {
return (host: Tree) => {
const coreDep = getDependency(host, '@angular/core');
if (!coreDep) {
throw new SchematicsException('Could not find "@angular/core" version.');
}
return addDependency('@angular/service-worker', coreDep.version);
};
}
function updateAppModule(mainPath: string): Rule {
return (host: Tree, context: SchematicContext) => {
context.logger.debug('Updating appmodule');
const modulePath = getAppModulePath(host, mainPath);
context.logger.debug(`module path: ${modulePath}`);
addImport(host, modulePath, 'ServiceWorkerModule', '@angular/service-worker');
addImport(host, modulePath, 'isDevMode', '@angular/core');
// register SW in application module
const importText = `
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: !isDevMode(),
// Register the ServiceWorker as soon as the application is stable
// or after 30 seconds (whichever comes first).
registrationStrategy: 'registerWhenStable:30000'
})
`;
const moduleSource = getTsSourceFile(host, modulePath);
const metadataChanges = addSymbolToNgModuleMetadata(
moduleSource,
modulePath,
'imports',
importText,
);
if (metadataChanges) {
const recorder = host.beginUpdate(modulePath);
applyToUpdateRecorder(recorder, metadataChanges);
host.commitUpdate(recorder);
}
return host;
};
}
function addProvideServiceWorker(projectName: string, mainPath: string): Rule {
return (host: Tree) => {
const bootstrapCall = findBootstrapApplicationCall(host, mainPath);
const appConfig = findAppConfig(bootstrapCall, host, mainPath)?.filePath || mainPath;
addImport(host, appConfig, 'isDevMode', '@angular/core');
return addRootProvider(
projectName,
({ code, external }) =>
code`${external('provideServiceWorker', '@angular/service-worker')}('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000'
})`,
);
};
}
function getTsSourceFile(host: Tree, path: string): ts.SourceFile {
const content = host.readText(path);
const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
return source;
}
export default createProjectSchematic<ServiceWorkerOptions>(
async (options, { project, workspace, tree }) => {
if (project.extensions.projectType !== 'application') {
throw new SchematicsException(`Service worker requires a project type of "application".`);
}
const buildTarget = project.targets.get('build');
if (!buildTarget) {
throw targetBuildNotFoundError();
}
const buildOptions = buildTarget.options as Record<string, string | boolean>;
const browserEntryPoint = await getMainFilePath(tree, options.project);
const ngswConfigPath = join(project.root, 'ngsw-config.json');
if (
buildTarget.builder === Builders.Application ||
buildTarget.builder === Builders.BuildApplication
) {
const productionConf = buildTarget.configurations?.production;
if (productionConf) {
productionConf.serviceWorker = ngswConfigPath;
}
} else {
buildOptions.serviceWorker = true;
buildOptions.ngswConfigPath = ngswConfigPath;
}
await writeWorkspace(tree, workspace);
return chain([
addDependencies(),
mergeWith(
apply(url('./files'), [
applyTemplates({
...options,
relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(project.root),
}),
move(project.root),
]),
),
isStandaloneApp(tree, browserEntryPoint)
? addProvideServiceWorker(options.project, browserEntryPoint)
: updateAppModule(browserEntryPoint),
]);
},
);
function addImport(host: Tree, filePath: string, symbolName: string, moduleName: string): void {
const moduleSource = getTsSourceFile(host, filePath);
const change = insertImport(moduleSource, filePath, symbolName, moduleName);
if (change) {
const recorder = host.beginUpdate(filePath);
applyToUpdateRecorder(recorder, [change]);
host.commitUpdate(recorder);
}
}