-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathangularHandler.ts
273 lines (218 loc) · 8.34 KB
/
angularHandler.ts
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import * as fs from 'fs-extra'
import { tmpdir } from 'os'
import * as path from 'path'
import type { Configuration } from 'webpack'
import type { PresetHandlerResult, WebpackDevServerConfig } from '../devServer'
import { dynamicAbsoluteImport, dynamicImport } from '../dynamic-import'
import { sourceDefaultWebpackDependencies } from './sourceRelativeWebpackModules'
export type BuildOptions = Record<string, any>
export type AngularWebpackDevServerConfig = Extract<WebpackDevServerConfig, {framework: 'angular'}>
type Configurations = {
configurations?: {
[configuration: string]: BuildOptions
}
}
export type AngularJsonProjectConfig = {
projectType: string
root: string
sourceRoot: string
architect: {
build: { options: BuildOptions } & Configurations
}
}
type AngularJson = {
defaultProject?: string
projects: {
[project: string]: AngularJsonProjectConfig
}
}
export async function getProjectConfig (projectRoot: string): Promise<Cypress.AngularDevServerProjectConfig> {
const angularJson = await getAngularJson(projectRoot)
let { defaultProject } = angularJson
if (!defaultProject) {
defaultProject = Object.keys(angularJson.projects).find((name) => angularJson.projects[name].projectType === 'application')
if (!defaultProject) {
throw new Error('Could not find a project with projectType "application" in "angular.json". Visit https://docs.cypress.io/guides/references/configuration#Options-API to see how to pass in a custom project configuration')
}
}
const defaultProjectConfig = angularJson.projects[defaultProject]
const { architect, root, sourceRoot } = defaultProjectConfig
const { build } = architect
return {
root,
sourceRoot,
buildOptions: {
...build.options,
...build.configurations?.development || {},
},
}
}
export function getAngularBuildOptions (buildOptions: BuildOptions, tsConfig: string) {
// Default options are derived from the @angular-devkit/build-angular browser builder, with some options from
// the serve builder thrown in for development.
// see: https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/schema.json
return {
outputPath: 'dist/angular-app',
assets: [],
styles: [],
scripts: [],
fileReplacements: [],
inlineStyleLanguage: 'css',
stylePreprocessorOptions: { includePaths: [] },
resourcesOutputPath: undefined,
commonChunk: true,
baseHref: undefined,
deployUrl: undefined,
verbose: false,
progress: false,
i18nMissingTranslation: 'warning',
i18nDuplicateTranslation: 'warning',
localize: undefined,
watch: true,
poll: undefined,
deleteOutputPath: true,
preserveSymlinks: undefined,
showCircularDependencies: false,
subresourceIntegrity: false,
serviceWorker: false,
ngswConfigPath: undefined,
statsJson: false,
webWorkerTsConfig: undefined,
crossOrigin: 'none',
allowedCommonJsDependencies: [], // Add Cypress 'browser.js' entry point to ignore "CommonJS or AMD dependencies can cause optimization bailouts." warning
buildOptimizer: false,
optimization: false,
vendorChunk: true,
extractLicenses: false,
sourceMap: true,
namedChunks: true,
...buildOptions,
tsConfig,
aot: false,
outputHashing: 'none',
budgets: undefined,
}
}
export async function generateTsConfig (devServerConfig: AngularWebpackDevServerConfig, buildOptions: BuildOptions): Promise<string> {
const { cypressConfig } = devServerConfig
const { projectRoot } = cypressConfig
const specPattern = Array.isArray(cypressConfig.specPattern) ? cypressConfig.specPattern : [cypressConfig.specPattern]
const getProjectFilePath = (...fileParts: string[]): string => toPosix(path.join(projectRoot, ...fileParts))
const includePaths = [...specPattern.map((pattern) => getProjectFilePath(pattern))]
if (cypressConfig.supportFile) {
includePaths.push(toPosix(cypressConfig.supportFile))
}
if (buildOptions.polyfills) {
const polyfills = Array.isArray(buildOptions.polyfills)
? buildOptions.polyfills.filter((p: string) => devServerConfig.options?.projectConfig.sourceRoot && p.startsWith(devServerConfig.options?.projectConfig.sourceRoot))
: [buildOptions.polyfills]
includePaths.push(...polyfills.map((p: string) => getProjectFilePath(p)))
}
const cypressTypes = getProjectFilePath('node_modules', 'cypress', 'types', 'index.d.ts')
includePaths.push(cypressTypes)
const tsConfigContent = JSON.stringify({
extends: getProjectFilePath(buildOptions.tsConfig ?? 'tsconfig.json'),
compilerOptions: {
outDir: getProjectFilePath('out-tsc/cy'),
allowSyntheticDefaultImports: true,
skipLibCheck: true,
},
include: includePaths,
})
const tsConfigPath = path.join(await getTempDir(), 'tsconfig.json')
await fs.writeFile(tsConfigPath, tsConfigContent)
return tsConfigPath
}
export async function getTempDir (): Promise<string> {
const cypressTempDir = path.join(tmpdir(), 'cypress-angular-ct')
await fs.ensureDir(cypressTempDir)
return cypressTempDir
}
export async function getAngularCliModules (projectRoot: string) {
const angularCLiModules = [
'@angular-devkit/build-angular/src/utils/webpack-browser-config.js',
'@angular-devkit/build-angular/src/webpack/configs/common.js',
'@angular-devkit/build-angular/src/webpack/configs/styles.js',
] as const
const [
{ generateBrowserWebpackConfigFromContext },
{ getCommonConfig },
{ getStylesConfig },
] = await Promise.all(angularCLiModules.map((dep) => {
try {
const depPath = require.resolve(dep, { paths: [projectRoot] })
return dynamicAbsoluteImport(depPath)
} catch (e) {
throw new Error(`Could not resolve "${dep}". Do you have "@angular-devkit/build-angular" installed?`)
}
}))
return {
generateBrowserWebpackConfigFromContext,
getCommonConfig,
getStylesConfig,
}
}
export async function getAngularJson (projectRoot: string): Promise<AngularJson> {
const { findUp } = await dynamicImport<typeof import('find-up')>('find-up')
const angularJsonPath = await findUp('angular.json', { cwd: projectRoot })
if (!angularJsonPath) {
throw new Error(`Could not find angular.json. Looked in ${projectRoot} and up.`)
}
const angularJson = await fs.readFile(angularJsonPath, 'utf8')
return JSON.parse(angularJson)
}
function createFakeContext (projectRoot: string, defaultProjectConfig: Cypress.AngularDevServerProjectConfig) {
const logger = {
createChild: () => {
return {
warn: () => {},
}
},
}
const context = {
target: {
project: 'angular',
},
workspaceRoot: projectRoot,
getProjectMetadata: () => {
return {
root: defaultProjectConfig.root,
sourceRoot: defaultProjectConfig.sourceRoot,
projectType: 'application',
}
},
logger,
}
return context
}
export const toPosix = (filePath: string) => filePath.split(path.sep).join(path.posix.sep)
async function getAngularCliWebpackConfig (devServerConfig: AngularWebpackDevServerConfig) {
const { projectRoot } = devServerConfig.cypressConfig
const {
generateBrowserWebpackConfigFromContext,
getCommonConfig,
getStylesConfig,
} = await getAngularCliModules(projectRoot)
// normalize
const projectConfig = devServerConfig.options?.projectConfig || await getProjectConfig(projectRoot)
const tsConfig = await generateTsConfig(devServerConfig, projectConfig.buildOptions)
const buildOptions = getAngularBuildOptions(projectConfig.buildOptions, tsConfig)
const context = createFakeContext(projectRoot, projectConfig)
const { config } = await generateBrowserWebpackConfigFromContext(
buildOptions,
context,
(wco: any) => [getCommonConfig(wco), getStylesConfig(wco)],
)
delete config.entry.main
return config
}
function removeSourceMapPlugin (config: Configuration) {
config.plugins = config.plugins?.filter((plugin) => {
return plugin?.constructor?.name !== 'SourceMapDevToolPlugin'
})
}
export async function angularHandler (devServerConfig: AngularWebpackDevServerConfig): Promise<PresetHandlerResult> {
const webpackConfig = await getAngularCliWebpackConfig(devServerConfig)
removeSourceMapPlugin(webpackConfig)
return { frameworkConfig: webpackConfig, sourceWebpackModulesResult: sourceDefaultWebpackDependencies(devServerConfig) }
}