-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathangularHandler.ts
339 lines (273 loc) · 11.1 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import * as fs from 'fs-extra'
import { tmpdir } from 'os'
import * as path from 'path'
import { gte } from 'semver'
import type { Configuration, RuleSetRule } from 'webpack'
import type { PresetHandlerResult, WebpackDevServerConfig } from '../devServer'
import { dynamicAbsoluteImport, dynamicImport } from '../dynamic-import'
import { sourceDefaultWebpackDependencies } from './sourceRelativeWebpackModules'
import debugLib from 'debug'
import type { logging as AngularLogging } from '@angular-devkit/core'
const debugPrefix = 'cypress:webpack-dev-server:angularHandler'
const debug = debugLib(debugPrefix)
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://on.cypress.io/configuration 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 { workspaceRoot = projectRoot } = buildOptions
const specPattern = Array.isArray(cypressConfig.specPattern) ? cypressConfig.specPattern : [cypressConfig.specPattern]
const getProjectFilePath = (...fileParts: string[]): string => toPosix(path.join(...fileParts))
const includePaths = [...specPattern.map((pattern) => getProjectFilePath(projectRoot, 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(workspaceRoot, p)))
}
const typeRoots = [
getProjectFilePath(workspaceRoot, 'node_modules'),
]
const types = ['cypress']
const tsConfigContent = JSON.stringify({
extends: getProjectFilePath(projectRoot, buildOptions.tsConfig ?? 'tsconfig.json'),
compilerOptions: {
outDir: getProjectFilePath(projectRoot, 'out-tsc/cy'),
allowSyntheticDefaultImports: true,
skipLibCheck: true,
types,
typeRoots,
},
include: includePaths,
}, null, 2)
const tsConfigPath = path.join(await getTempDir(path.basename(projectRoot)), 'tsconfig.json')
await fs.writeFile(tsConfigPath, tsConfigContent)
return tsConfigPath
}
export async function getTempDir (projectName: string): Promise<string> {
const cypressTempDir = path.join(tmpdir(), 'cypress-angular-ct', projectName)
await fs.ensureDir(cypressTempDir)
return cypressTempDir
}
export async function getAngularCliModules (projectRoot: string) {
let angularVersion: string
try {
angularVersion = await getInstalledPackageVersion('@angular-devkit/core', projectRoot)
} catch {
throw new Error(`Could not resolve "@angular-devkit/core". Do you have it installed?`)
}
const angularCLiModules = [
'@angular-devkit/build-angular/src/utils/webpack-browser-config.js',
// in Angular 16.1 the locations of these files below were changed
...(
gte(angularVersion, '16.1.0')
? ['@angular-devkit/build-angular/src/tools/webpack/configs/common.js', '@angular-devkit/build-angular/src/tools/webpack/configs/styles.js']
: ['@angular-devkit/build-angular/src/webpack/configs/common.js', '@angular-devkit/build-angular/src/webpack/configs/styles.js']
),
'@angular-devkit/core/src/index.js',
] as const
const [
{ generateBrowserWebpackConfigFromContext },
{ getCommonConfig },
{ getStylesConfig },
{ logging },
] = 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" and "@angular-devkit/core" installed?`)
}
}))
return {
generateBrowserWebpackConfigFromContext,
getCommonConfig,
getStylesConfig,
logging,
}
}
async function getInstalledPackageVersion (pkgName: string, projectRoot: string): Promise<string> {
const packageJsonPath = require.resolve(`${pkgName}/package.json`, { paths: [projectRoot] })
const { version } = JSON.parse(
await fs.readFile(packageJsonPath, { encoding: 'utf-8' }),
)
return version
}
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, logging: typeof AngularLogging) {
const logger = new logging.Logger(debugPrefix)
// Proxy all logging calls through to the debug logger
logger.forEach((value: AngularLogging.LogEntry) => {
debug(JSON.stringify(value))
})
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,
logging,
} = 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(projectConfig.buildOptions.workspaceRoot || projectRoot, projectConfig, logging)
const { config } = await generateBrowserWebpackConfigFromContext(
buildOptions,
context,
(wco: any) => {
// Starting in Angular 16, the `getStylesConfig` function returns a `Promise`.
// We wrap it with `Promise.resolve` so we support older version of Angular
// returning a non-Promise result.
const stylesConfig = Promise.resolve(getStylesConfig(wco)).then((config) => {
// We modify resolve-url-loader and set `root` to be `projectRoot` + `sourceRoot` to ensure
// imports in scss, sass, etc are correctly resolved.
// https://github.com/cypress-io/cypress/issues/24272
config.module.rules.forEach((rule: RuleSetRule) => {
rule.rules?.forEach((ruleSet) => {
if (!Array.isArray(ruleSet.use)) {
return
}
ruleSet.use.map((loader) => {
if (typeof loader !== 'object' || typeof loader.options !== 'object' || !loader.loader?.includes('resolve-url-loader')) {
return
}
const root = projectConfig.buildOptions.workspaceRoot || path.join(devServerConfig.cypressConfig.projectRoot, projectConfig.sourceRoot)
debug('Adding root %s to resolve-url-loader options', root)
loader.options.root = root
})
})
})
return config
})
return [getCommonConfig(wco), stylesConfig]
},
)
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) }
}