@cypress/webpack-dev-server 1.8.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +54 -75
  2. package/dist/CypressCTWebpackPlugin.d.ts +15 -0
  3. package/dist/CypressCTWebpackPlugin.js +105 -0
  4. package/dist/aut-runner.js +1 -0
  5. package/dist/constants.d.ts +1 -0
  6. package/dist/constants.js +9 -0
  7. package/dist/createWebpackDevServer.d.ts +26 -0
  8. package/dist/createWebpackDevServer.js +49 -0
  9. package/dist/devServer.d.ts +35 -0
  10. package/dist/devServer.js +106 -0
  11. package/dist/helpers/angularHandler.d.ts +80 -0
  12. package/dist/helpers/angularHandler.js +131 -0
  13. package/dist/helpers/createReactAppHandler.d.ts +8 -0
  14. package/dist/helpers/createReactAppHandler.js +301 -0
  15. package/dist/helpers/nextHandler.d.ts +3 -0
  16. package/dist/helpers/nextHandler.js +237 -0
  17. package/dist/helpers/nuxtHandler.d.ts +2 -0
  18. package/dist/helpers/nuxtHandler.js +28 -0
  19. package/dist/helpers/sourceRelativeWebpackModules.d.ts +46 -0
  20. package/dist/helpers/sourceRelativeWebpackModules.js +212 -0
  21. package/dist/helpers/vueCliHandler.d.ts +2 -0
  22. package/dist/helpers/vueCliHandler.js +24 -0
  23. package/dist/index.d.ts +3 -15
  24. package/dist/index.js +4 -63
  25. package/dist/loader.d.ts +1 -3
  26. package/dist/loader.js +8 -28
  27. package/dist/makeDefaultWebpackConfig.d.ts +1 -0
  28. package/dist/makeDefaultWebpackConfig.js +50 -0
  29. package/dist/makeWebpackConfig.d.ts +6 -16
  30. package/dist/makeWebpackConfig.js +139 -93
  31. package/dist/measureWebpackPerformance.d.ts +1 -2
  32. package/dist/measureWebpackPerformance.js +11 -8
  33. package/package.json +34 -25
  34. package/CHANGELOG.md +0 -181
  35. package/dist/plugin.d.ts +0 -45
  36. package/dist/plugin.js +0 -84
  37. package/dist/startServer.d.ts +0 -13
  38. package/dist/startServer.js +0 -75
  39. package/dist/webpack.config.d.ts +0 -2
  40. package/dist/webpack.config.js +0 -24
  41. package/dist/webpackDevServerFacts.d.ts +0 -6
  42. package/dist/webpackDevServerFacts.js +0 -19
  43. package/index-template.html +0 -12
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.allCssTests = exports.nextHandler = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6
+ const module_1 = (0, tslib_1.__importDefault)(require("module"));
7
+ const fs = (0, tslib_1.__importStar)(require("fs"));
8
+ const path = (0, tslib_1.__importStar)(require("path"));
9
+ const sourceRelativeWebpackModules_1 = require("./sourceRelativeWebpackModules");
10
+ const debug = (0, debug_1.default)('cypress:webpack-dev-server-fresh:nextHandler');
11
+ async function nextHandler(devServerConfig) {
12
+ const webpackConfig = await loadWebpackConfig(devServerConfig);
13
+ debug('resolved next.js webpack config %o', webpackConfig);
14
+ checkSWC(webpackConfig, devServerConfig.cypressConfig);
15
+ watchEntryPoint(webpackConfig);
16
+ allowGlobalStylesImports(webpackConfig);
17
+ changeNextCachePath(webpackConfig);
18
+ return { frameworkConfig: webpackConfig, sourceWebpackModulesResult: sourceNextWebpackDeps(devServerConfig) };
19
+ }
20
+ exports.nextHandler = nextHandler;
21
+ /**
22
+ * Acquire the modules needed to load the Next webpack config. We are using Next's APIs to grab the webpackConfig
23
+ * but since this is in the binary, we have to `require.resolve` them from the projectRoot
24
+ * `loadConfig` acquires the next.config.js
25
+ * `getNextJsBaseWebpackConfig` acquires the webpackConfig dependent on the next.config.js
26
+ */
27
+ function getNextJsPackages(devServerConfig) {
28
+ var _a, _b;
29
+ const resolvePaths = { paths: [devServerConfig.cypressConfig.projectRoot] };
30
+ const packages = {};
31
+ try {
32
+ const loadConfigPath = require.resolve('next/dist/server/config', resolvePaths);
33
+ packages.loadConfig = require(loadConfigPath).default;
34
+ }
35
+ catch (e) {
36
+ throw new Error(`Failed to load "next/dist/server/config" with error: ${(_a = e.message) !== null && _a !== void 0 ? _a : e}`);
37
+ }
38
+ try {
39
+ const getNextJsBaseWebpackConfigPath = require.resolve('next/dist/build/webpack-config', resolvePaths);
40
+ packages.getNextJsBaseWebpackConfig = require(getNextJsBaseWebpackConfigPath).default;
41
+ }
42
+ catch (e) {
43
+ throw new Error(`Failed to load "next/dist/build/webpack-config" with error: ${(_b = e.message) !== null && _b !== void 0 ? _b : e}`);
44
+ }
45
+ return packages;
46
+ }
47
+ async function loadWebpackConfig(devServerConfig) {
48
+ const { loadConfig, getNextJsBaseWebpackConfig } = getNextJsPackages(devServerConfig);
49
+ const nextConfig = await loadConfig('development', devServerConfig.cypressConfig.projectRoot);
50
+ const runWebpackSpan = getRunWebpackSpan(devServerConfig);
51
+ const webpackConfig = await getNextJsBaseWebpackConfig(devServerConfig.cypressConfig.projectRoot, Object.assign(Object.assign({ buildId: `@cypress/react-${Math.random().toString()}`, config: nextConfig, dev: true, pagesDir: await findPagesDir(devServerConfig.cypressConfig.projectRoot), entrypoints: {}, rewrites: { fallback: [], afterFiles: [], beforeFiles: [] } }, runWebpackSpan), {
52
+ // Client webpack config for Next.js <= 12.1.5
53
+ isServer: false,
54
+ // Client webpack config for Next.js > 12.1.5
55
+ compilerType: 'client' }));
56
+ delete webpackConfig.entry;
57
+ return webpackConfig;
58
+ }
59
+ /**
60
+ * Check if Next is using the SWC compiler. Compilation will fail if user has `nodeVersion: "bundled"` set
61
+ * due to SWC certificate issues.
62
+ */
63
+ function checkSWC(webpackConfig, cypressConfig) {
64
+ var _a, _b;
65
+ const hasSWCLoader = (_b = (_a = webpackConfig.module) === null || _a === void 0 ? void 0 : _a.rules) === null || _b === void 0 ? void 0 : _b.some((rule) => {
66
+ var _a;
67
+ return typeof rule !== 'string' && ((_a = rule.oneOf) === null || _a === void 0 ? void 0 : _a.some((oneOf) => { var _a; return ((_a = oneOf.use) === null || _a === void 0 ? void 0 : _a.loader) === 'next-swc-loader'; }));
68
+ });
69
+ // "resolvedNodePath" is only set when using the user's Node.js, which is required to compile Next.js with SWC optimizations
70
+ // If it is not set, they have either explicitly set "nodeVersion" to "bundled" or are are using Cypress < 9.0.0 where it was set to "bundled" by default
71
+ if (hasSWCLoader && cypressConfig.nodeVersion === 'bundled') {
72
+ throw new Error(`Cypress cannot compile your Next.js application when "nodeVersion" is set to "bundled". Please remove this option from your Cypress configuration file.`);
73
+ }
74
+ return false;
75
+ }
76
+ const exists = async (file) => {
77
+ try {
78
+ await fs.promises.access(file, fs.constants.F_OK);
79
+ return true;
80
+ }
81
+ catch (_) {
82
+ return false;
83
+ }
84
+ };
85
+ /**
86
+ * Next allows the `pages` directory to be located at either
87
+ * `${projectRoot}/pages` or `${projectRoot}/src/pages`.
88
+ * If neither is found, return projectRoot
89
+ */
90
+ async function findPagesDir(projectRoot) {
91
+ // prioritize ./pages over ./src/pages
92
+ let pagesDir = path.join(projectRoot, 'pages');
93
+ if (await exists(pagesDir)) {
94
+ return pagesDir;
95
+ }
96
+ pagesDir = path.join(projectRoot, 'src', 'pages');
97
+ if (await exists(pagesDir)) {
98
+ return pagesDir;
99
+ }
100
+ return projectRoot;
101
+ }
102
+ // Starting with v11.1.1, a trace is required.
103
+ // 'next/dist/telemetry/trace/trace' only exists since v10.0.9
104
+ // and our peerDeps support back to v8 so try-catch this import
105
+ // Starting from 12.0 trace is now located in 'next/dist/trace/trace'
106
+ function getRunWebpackSpan(devServerConfig) {
107
+ let trace;
108
+ try {
109
+ try {
110
+ const traceImportPath = require.resolve('next/dist/telemetry/trace/trace', { paths: [devServerConfig.cypressConfig.projectRoot] });
111
+ trace = require(traceImportPath).trace;
112
+ return { runWebpackSpan: trace('cypress') };
113
+ }
114
+ catch (_) {
115
+ // @ts-ignore
116
+ const traceImportPath = require.resolve('next/dist/trace/trace', { paths: [devServerConfig.cypressConfig.projectRoot] });
117
+ trace = require(traceImportPath).trace;
118
+ return { runWebpackSpan: trace('cypress') };
119
+ }
120
+ }
121
+ catch (_) {
122
+ return {};
123
+ }
124
+ }
125
+ const originalModuleLoad = module_1.default._load;
126
+ function sourceNextWebpackDeps(devServerConfig) {
127
+ const framework = (0, sourceRelativeWebpackModules_1.sourceFramework)(devServerConfig);
128
+ const webpack = sourceNextWebpack(devServerConfig, framework);
129
+ const webpackDevServer = (0, sourceRelativeWebpackModules_1.sourceWebpackDevServer)(devServerConfig, framework);
130
+ const htmlWebpackPlugin = (0, sourceRelativeWebpackModules_1.sourceHtmlWebpackPlugin)(devServerConfig, framework, webpack);
131
+ return {
132
+ framework,
133
+ webpack,
134
+ webpackDevServer,
135
+ htmlWebpackPlugin,
136
+ };
137
+ }
138
+ function sourceNextWebpack(devServerConfig, framework) {
139
+ const searchRoot = framework.importPath;
140
+ debug('NextWebpack: Attempting to load NextWebpack from %s', searchRoot);
141
+ let webpackJsonPath;
142
+ const webpack = {};
143
+ try {
144
+ webpackJsonPath = require.resolve('next/dist/compiled/webpack/package.json', {
145
+ paths: [searchRoot],
146
+ });
147
+ }
148
+ catch (e) {
149
+ debug('NextWebpack: Failed to load NextWebpack - %s', e);
150
+ throw e;
151
+ }
152
+ // Next 11 allows the choice of webpack@4 or webpack@5, depending on the "webpack5" property in their next.config.js
153
+ // The webpackModule.init" for Next 11 returns a webpack@4 or webpack@4 compiler instance based on this boolean
154
+ let webpack5 = true;
155
+ const importPath = path.join(path.dirname(webpackJsonPath), 'webpack.js');
156
+ const webpackModule = require(importPath);
157
+ try {
158
+ const nextConfig = require(path.resolve(devServerConfig.cypressConfig.projectRoot, 'next.config.js'));
159
+ debug('NextWebpack: next.config.js found - %o', nextConfig);
160
+ if (nextConfig.webpack5 === false) {
161
+ webpack5 = false;
162
+ }
163
+ }
164
+ catch (e) {
165
+ // No next.config.js, assume webpack 5
166
+ }
167
+ debug('NextWebpack: webpack5 - %s', webpack5);
168
+ webpackModule.init(webpack5);
169
+ const packageJson = require(webpackJsonPath);
170
+ webpack.importPath = importPath;
171
+ // The package.json of "next/dist/compiled/webpack/package.json" has no version so we supply the version for later use
172
+ webpack.packageJson = Object.assign(Object.assign({}, packageJson), { version: webpack5 ? '5' : '4' });
173
+ webpack.module = webpackModule.webpack;
174
+ webpack.majorVersion = (0, sourceRelativeWebpackModules_1.getMajorVersion)(webpack.packageJson, [4, 5]);
175
+ debug('NextWebpack: Successfully loaded NextWebpack - %o', webpack);
176
+ module_1.default._load = function (request, parent, isMain) {
177
+ // Next with webpack@4 doesn't ship certain dependencies that HtmlWebpackPlugin requires, so we patch the resolution through to our bundled version
178
+ if ((request === 'webpack' || request.startsWith('webpack/')) && webpack.majorVersion === 4) {
179
+ const resolvePath = require.resolve(request, {
180
+ paths: [(0, sourceRelativeWebpackModules_1.cypressWebpackPath)(devServerConfig)],
181
+ });
182
+ debug('NextWebpack: Module._load for webpack@4 - %s', resolvePath);
183
+ return originalModuleLoad(resolvePath, parent, isMain);
184
+ }
185
+ if (request === 'webpack' || request.startsWith('webpack/')) {
186
+ const resolvePath = require.resolve(request, {
187
+ paths: [framework.importPath],
188
+ });
189
+ debug('NextWebpack: Module._load - %s', resolvePath);
190
+ return originalModuleLoad(resolvePath, parent, isMain);
191
+ }
192
+ return originalModuleLoad(request, parent, isMain);
193
+ };
194
+ return webpack;
195
+ }
196
+ // Next webpack compiler ignored watching any node_modules changes, but we need to watch
197
+ // for changes to 'dist/browser.js' in order to detect new specs that have been added
198
+ function watchEntryPoint(webpackConfig) {
199
+ if (webpackConfig.watchOptions && Array.isArray(webpackConfig.watchOptions.ignored)) {
200
+ webpackConfig.watchOptions = Object.assign(Object.assign({}, webpackConfig.watchOptions), { ignored: [...webpackConfig.watchOptions.ignored.filter((pattern) => !/node_modules/.test(pattern)), '**/node_modules/!(@cypress/webpack-dev-server/dist/browser.js)**'] });
201
+ debug('found options next.js watchOptions.ignored %O', webpackConfig.watchOptions.ignored);
202
+ }
203
+ }
204
+ // We are matching the Next.js regex rules exactly. If we were writing our own loader, we could
205
+ // condense these regex rules into a single rule but we need the regex.source to be identical to what
206
+ // we get from Next.js webpack config
207
+ // see: https://github.com/vercel/next.js/blob/20486c159d8538a337da6b07b0b4490a3a0d6b91/packages/next/build/webpack/config/blocks/css/index.ts#L18
208
+ const globalCssRe = [/(?<!\.module)\.css$/, /(?<!\.module)\.(scss|sass)$/];
209
+ const globalCssModulesRe = [/\.module\.css$/, /\.module\.(scss|sass)$/];
210
+ exports.allCssTests = [...globalCssRe, ...globalCssModulesRe];
211
+ // Next does not allow global styles to be loaded outside of the main <App /> component.
212
+ // We want users to be able to import the global styles into their component support file so we
213
+ // delete the "issuer" from the rules that process css/scss files.
214
+ // see: https://github.com/cypress-io/cypress/issues/22525
215
+ // Motivated by: https://github.com/bem/next-global-css
216
+ function allowGlobalStylesImports(webpackConfig) {
217
+ var _a;
218
+ const rules = ((_a = webpackConfig.module) === null || _a === void 0 ? void 0 : _a.rules) || [];
219
+ for (const rule of rules) {
220
+ if (typeof rule !== 'string' && rule.oneOf) {
221
+ for (const oneOf of rule.oneOf) {
222
+ if (oneOf.test && exports.allCssTests.some((re) => { var _a; return re.source === ((_a = oneOf.test) === null || _a === void 0 ? void 0 : _a.source); })) {
223
+ delete oneOf.issuer;
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
229
+ // Our modifications of the Next webpack config can corrupt the cache used for local development.
230
+ // We separate the cache used for CT from the normal cache (".next/cache/webpack" -> ".next/cache/cypress-webpack") so they don't interfere with each other
231
+ function changeNextCachePath(webpackConfig) {
232
+ if (typeof webpackConfig.cache === 'object' && ('cacheDirectory' in webpackConfig.cache) && webpackConfig.cache.cacheDirectory) {
233
+ const { cacheDirectory } = webpackConfig.cache;
234
+ webpackConfig.cache.cacheDirectory = cacheDirectory.replace(/webpack$/, 'cypress-webpack');
235
+ debug('Changing Next cache path from %s to %s', cacheDirectory, webpackConfig.cache.cacheDirectory);
236
+ }
237
+ }
@@ -0,0 +1,2 @@
1
+ import type { PresetHandlerResult, WebpackDevServerConfig } from '../devServer';
2
+ export declare function nuxtHandler(devServerConfig: WebpackDevServerConfig): Promise<PresetHandlerResult>;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.nuxtHandler = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6
+ const sourceRelativeWebpackModules_1 = require("./sourceRelativeWebpackModules");
7
+ const debug = (0, debug_1.default)('cypress:webpack-dev-server:nuxtHandler');
8
+ async function nuxtHandler(devServerConfig) {
9
+ const sourceWebpackModulesResult = (0, sourceRelativeWebpackModules_1.sourceDefaultWebpackDependencies)(devServerConfig);
10
+ try {
11
+ const nuxt = require.resolve('nuxt', {
12
+ paths: [devServerConfig.cypressConfig.projectRoot],
13
+ });
14
+ const { getWebpackConfig } = require(nuxt);
15
+ const webpackConfig = await getWebpackConfig();
16
+ // Nuxt has asset size warnings configured by default which will cause webpack overlays to appear
17
+ // in the browser which we don't want.
18
+ delete webpackConfig.performance;
19
+ delete webpackConfig.entry;
20
+ debug('webpack config %o', webpackConfig);
21
+ return { frameworkConfig: webpackConfig, sourceWebpackModulesResult };
22
+ }
23
+ catch (e) {
24
+ console.error(e); // eslint-disable-line no-console
25
+ throw Error(`Error loading nuxt. Looked in ${require.resolve.paths(devServerConfig.cypressConfig.projectRoot)}`);
26
+ }
27
+ }
28
+ exports.nuxtHandler = nuxtHandler;
@@ -0,0 +1,46 @@
1
+ /// <reference types="node" />
2
+ import Module from 'module';
3
+ import type { WebpackDevServerConfig } from '../devServer';
4
+ export declare type ModuleClass = typeof Module & {
5
+ _load(id: string, parent: Module, isMain: boolean): any;
6
+ _resolveFilename(request: string, parent: Module, isMain: boolean, options?: {
7
+ paths: string[];
8
+ }): string;
9
+ _cache: Record<string, Module>;
10
+ };
11
+ export interface PackageJson {
12
+ name: string;
13
+ version: string;
14
+ }
15
+ export interface SourcedDependency {
16
+ importPath: string;
17
+ packageJson: PackageJson;
18
+ }
19
+ export interface SourcedWebpack extends SourcedDependency {
20
+ module: Function;
21
+ majorVersion: 4 | 5;
22
+ }
23
+ export interface SourcedWebpackDevServer extends SourcedDependency {
24
+ module: {
25
+ new (...args: unknown[]): unknown;
26
+ };
27
+ majorVersion: 3 | 4;
28
+ }
29
+ export interface SourcedHtmlWebpackPlugin extends SourcedDependency {
30
+ module: unknown;
31
+ majorVersion: 4 | 5;
32
+ }
33
+ export interface SourceRelativeWebpackResult {
34
+ framework: SourcedDependency | null;
35
+ webpack: SourcedWebpack;
36
+ webpackDevServer: SourcedWebpackDevServer;
37
+ htmlWebpackPlugin: SourcedHtmlWebpackPlugin;
38
+ }
39
+ export declare const cypressWebpackPath: (config: WebpackDevServerConfig) => string;
40
+ export declare function sourceFramework(config: WebpackDevServerConfig): SourcedDependency | null;
41
+ export declare function sourceWebpack(config: WebpackDevServerConfig, framework: SourcedDependency | null): SourcedWebpack;
42
+ export declare function sourceWebpackDevServer(config: WebpackDevServerConfig, framework?: SourcedDependency | null): SourcedWebpackDevServer;
43
+ export declare function sourceHtmlWebpackPlugin(config: WebpackDevServerConfig, framework: SourcedDependency | null, webpack: SourcedWebpack): SourcedHtmlWebpackPlugin;
44
+ export declare function sourceDefaultWebpackDependencies(config: WebpackDevServerConfig): SourceRelativeWebpackResult;
45
+ export declare function getMajorVersion<T extends number>(json: PackageJson, acceptedVersions: T[]): T;
46
+ export declare function restoreLoadHook(): void;
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.restoreLoadHook = exports.getMajorVersion = exports.sourceDefaultWebpackDependencies = exports.sourceHtmlWebpackPlugin = exports.sourceWebpackDevServer = exports.sourceWebpack = exports.sourceFramework = exports.cypressWebpackPath = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const module_1 = (0, tslib_1.__importDefault)(require("module"));
6
+ const path_1 = (0, tslib_1.__importDefault)(require("path"));
7
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
8
+ const debug = (0, debug_1.default)('cypress:webpack-dev-server:sourceRelativeWebpackModules');
9
+ const originalModuleLoad = module_1.default._load;
10
+ const originalModuleResolveFilename = module_1.default._resolveFilename;
11
+ // We ship webpack@4 as part of '@cypress/webpack-batteries-included-preprocessor'. The path to this module
12
+ // serves as our fallback.
13
+ const cypressWebpackPath = (config) => {
14
+ return require.resolve('@cypress/webpack-batteries-included-preprocessor', {
15
+ paths: [config.cypressConfig.cypressBinaryRoot],
16
+ });
17
+ };
18
+ exports.cypressWebpackPath = cypressWebpackPath;
19
+ const frameworkWebpackMapper = {
20
+ 'create-react-app': 'react-scripts',
21
+ 'vue-cli': '@vue/cli-service',
22
+ 'nuxt': '@nuxt/webpack',
23
+ react: undefined,
24
+ vue: undefined,
25
+ next: 'next',
26
+ // TODO: revert once Angular is slated for release
27
+ // 'angular': '@angular-devkit/build-angular',
28
+ };
29
+ // Source the users framework from the provided projectRoot. The framework, if available, will serve
30
+ // as the resolve base for webpack dependency resolution.
31
+ function sourceFramework(config) {
32
+ debug('Framework: Attempting to source framework for %s', config.cypressConfig.projectRoot);
33
+ if (!config.framework) {
34
+ debug('Framework: No framework provided');
35
+ return null;
36
+ }
37
+ const sourceOfWebpack = frameworkWebpackMapper[config.framework];
38
+ if (!sourceOfWebpack) {
39
+ debug('Not a higher-order framework so webpack dependencies should be resolvable from projectRoot');
40
+ return null;
41
+ }
42
+ const framework = {};
43
+ try {
44
+ const frameworkJsonPath = require.resolve(`${sourceOfWebpack}/package.json`, {
45
+ paths: [config.cypressConfig.projectRoot],
46
+ });
47
+ const frameworkPathRoot = path_1.default.dirname(frameworkJsonPath);
48
+ // Want to make sure we're sourcing this from the user's code. Otherwise we can
49
+ // warn and tell them they don't have their dependencies installed
50
+ framework.importPath = frameworkPathRoot;
51
+ framework.packageJson = require(frameworkJsonPath);
52
+ debug('Framework: Successfully sourced framework - %o', framework);
53
+ return framework;
54
+ }
55
+ catch (e) {
56
+ debug('Framework: Failed to source framework - %s', e);
57
+ // TODO
58
+ return null;
59
+ }
60
+ }
61
+ exports.sourceFramework = sourceFramework;
62
+ // Source the webpack module from the provided framework or projectRoot. We override the module resolution
63
+ // so that other packages that import webpack resolve to the version we found.
64
+ // If none is found, we fallback to the bundled version in '@cypress/webpack-batteries-included-preprocessor'.
65
+ function sourceWebpack(config, framework) {
66
+ var _a;
67
+ const searchRoot = (_a = framework === null || framework === void 0 ? void 0 : framework.importPath) !== null && _a !== void 0 ? _a : config.cypressConfig.projectRoot;
68
+ debug('Webpack: Attempting to source webpack from %s', searchRoot);
69
+ const webpack = {};
70
+ let webpackJsonPath;
71
+ try {
72
+ webpackJsonPath = require.resolve('webpack/package.json', {
73
+ paths: [searchRoot],
74
+ });
75
+ }
76
+ catch (e) {
77
+ if (e.code !== 'MODULE_NOT_FOUND') {
78
+ debug('Webpack: Failed to source webpack - %s', e);
79
+ throw e;
80
+ }
81
+ debug('Webpack: Falling back to bundled version');
82
+ webpackJsonPath = require.resolve('webpack/package.json', {
83
+ paths: [(0, exports.cypressWebpackPath)(config)],
84
+ });
85
+ }
86
+ webpack.importPath = path_1.default.dirname(webpackJsonPath);
87
+ webpack.packageJson = require(webpackJsonPath);
88
+ webpack.module = require(webpack.importPath);
89
+ webpack.majorVersion = getMajorVersion(webpack.packageJson, [4, 5]);
90
+ debug('Webpack: Successfully sourced webpack - %o', webpack);
91
+ module_1.default._load = function (request, parent, isMain) {
92
+ if (request === 'webpack' || request.startsWith('webpack/')) {
93
+ const resolvePath = require.resolve(request, {
94
+ paths: [webpack.importPath],
95
+ });
96
+ debug('Webpack: Module._load resolvePath - %s', resolvePath);
97
+ return originalModuleLoad(resolvePath, parent, isMain);
98
+ }
99
+ return originalModuleLoad(request, parent, isMain);
100
+ };
101
+ module_1.default._resolveFilename = function (request, parent, isMain, options) {
102
+ if (request === 'webpack' || request.startsWith('webpack/') && !(options === null || options === void 0 ? void 0 : options.paths)) {
103
+ const resolveFilename = originalModuleResolveFilename(request, parent, isMain, {
104
+ paths: [webpack.importPath],
105
+ });
106
+ debug('Webpack: Module._resolveFilename resolveFilename - %s', resolveFilename);
107
+ return resolveFilename;
108
+ }
109
+ return originalModuleResolveFilename(request, parent, isMain, options);
110
+ };
111
+ return webpack;
112
+ }
113
+ exports.sourceWebpack = sourceWebpack;
114
+ // Source the webpack-dev-server module from the provided framework or projectRoot.
115
+ // If none is found, we fallback to the version bundled with this package.
116
+ function sourceWebpackDevServer(config, framework) {
117
+ var _a;
118
+ const searchRoot = (_a = framework === null || framework === void 0 ? void 0 : framework.importPath) !== null && _a !== void 0 ? _a : config.cypressConfig.projectRoot;
119
+ debug('WebpackDevServer: Attempting to source webpack-dev-server from %s', searchRoot);
120
+ const webpackDevServer = {};
121
+ let webpackDevServerJsonPath;
122
+ try {
123
+ webpackDevServerJsonPath = require.resolve('webpack-dev-server/package.json', {
124
+ paths: [searchRoot],
125
+ });
126
+ }
127
+ catch (e) {
128
+ if (e.code !== 'MODULE_NOT_FOUND') {
129
+ debug('WebpackDevServer: Failed to source webpack-dev-server - %s', e);
130
+ throw e;
131
+ }
132
+ debug('WebpackDevServer: Falling back to bundled version');
133
+ webpackDevServerJsonPath = require.resolve('webpack-dev-server/package.json', {
134
+ paths: [__dirname],
135
+ });
136
+ }
137
+ webpackDevServer.importPath = path_1.default.dirname(webpackDevServerJsonPath);
138
+ webpackDevServer.packageJson = require(webpackDevServerJsonPath);
139
+ webpackDevServer.module = require(webpackDevServer.importPath);
140
+ webpackDevServer.majorVersion = getMajorVersion(webpackDevServer.packageJson, [3, 4]);
141
+ debug('WebpackDevServer: Successfully sourced webpack-dev-server - %o', webpackDevServer);
142
+ return webpackDevServer;
143
+ }
144
+ exports.sourceWebpackDevServer = sourceWebpackDevServer;
145
+ // Source the html-webpack-plugin module from the provided framework or projectRoot.
146
+ // If none is found, we fallback to the version bundled with this package dependent on the major version of webpack.
147
+ // We ship both v4 and v5 of 'html-webpack-plugin' by aliasing the package with the major version (check package.json).
148
+ function sourceHtmlWebpackPlugin(config, framework, webpack) {
149
+ var _a;
150
+ const searchRoot = (_a = framework === null || framework === void 0 ? void 0 : framework.importPath) !== null && _a !== void 0 ? _a : config.cypressConfig.projectRoot;
151
+ debug('HtmlWebpackPlugin: Attempting to source html-webpack-plugin from %s', searchRoot);
152
+ const htmlWebpackPlugin = {};
153
+ let htmlWebpackPluginJsonPath;
154
+ try {
155
+ htmlWebpackPluginJsonPath = require.resolve('html-webpack-plugin/package.json', {
156
+ paths: [searchRoot],
157
+ });
158
+ htmlWebpackPlugin.packageJson = require(htmlWebpackPluginJsonPath);
159
+ // Check that they're not using v3 of html-webpack-plugin. Since we should be the only consumer of it,
160
+ // we shouldn't be concerned with using our own copy if they've shipped w/ an earlier version
161
+ htmlWebpackPlugin.majorVersion = getMajorVersion(htmlWebpackPlugin.packageJson, [4, 5]);
162
+ }
163
+ catch (e) {
164
+ const err = e;
165
+ if (err.code !== 'MODULE_NOT_FOUND' && !err.message.includes('Unexpected major version')) {
166
+ debug('HtmlWebpackPlugin: Failed to source html-webpack-plugin - %s', e);
167
+ throw e;
168
+ }
169
+ const htmlWebpack = `html-webpack-plugin-${webpack.majorVersion}`;
170
+ debug('HtmlWebpackPlugin: Falling back to bundled version %s', htmlWebpack);
171
+ htmlWebpackPluginJsonPath = require.resolve(`${htmlWebpack}/package.json`, {
172
+ paths: [
173
+ __dirname,
174
+ ],
175
+ });
176
+ }
177
+ htmlWebpackPlugin.importPath = path_1.default.dirname(htmlWebpackPluginJsonPath),
178
+ htmlWebpackPlugin.packageJson = require(htmlWebpackPluginJsonPath),
179
+ htmlWebpackPlugin.module = require(htmlWebpackPlugin.importPath),
180
+ htmlWebpackPlugin.majorVersion = getMajorVersion(htmlWebpackPlugin.packageJson, [4, 5]);
181
+ debug('HtmlWebpackPlugin: Successfully sourced html-webpack-plugin - %o', htmlWebpackPlugin);
182
+ return htmlWebpackPlugin;
183
+ }
184
+ exports.sourceHtmlWebpackPlugin = sourceHtmlWebpackPlugin;
185
+ // Most frameworks follow a similar path for sourcing webpack dependencies so this is a utility to handle all the sourcing.
186
+ function sourceDefaultWebpackDependencies(config) {
187
+ const framework = sourceFramework(config);
188
+ const webpack = sourceWebpack(config, framework);
189
+ const webpackDevServer = sourceWebpackDevServer(config, framework);
190
+ const htmlWebpackPlugin = sourceHtmlWebpackPlugin(config, framework, webpack);
191
+ return {
192
+ framework,
193
+ webpack,
194
+ webpackDevServer,
195
+ htmlWebpackPlugin,
196
+ };
197
+ }
198
+ exports.sourceDefaultWebpackDependencies = sourceDefaultWebpackDependencies;
199
+ function getMajorVersion(json, acceptedVersions) {
200
+ const major = Number(json.version.split('.')[0]);
201
+ if (!acceptedVersions.includes(major)) {
202
+ throw new Error(`Unexpected major version of ${json.name}. ` +
203
+ `Cypress webpack-dev-server works with ${json.name} versions ${acceptedVersions.join(', ')} - saw ${json.version}`);
204
+ }
205
+ return Number(major);
206
+ }
207
+ exports.getMajorVersion = getMajorVersion;
208
+ function restoreLoadHook() {
209
+ module_1.default._load = originalModuleLoad;
210
+ module_1.default._resolveFilename = originalModuleResolveFilename;
211
+ }
212
+ exports.restoreLoadHook = restoreLoadHook;
@@ -0,0 +1,2 @@
1
+ import type { PresetHandlerResult, WebpackDevServerConfig } from '../devServer';
2
+ export declare function vueCliHandler(devServerConfig: WebpackDevServerConfig): PresetHandlerResult;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.vueCliHandler = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
6
+ const sourceRelativeWebpackModules_1 = require("./sourceRelativeWebpackModules");
7
+ const debug = (0, debug_1.default)('cypress:webpack-dev-server:vueCliHandler');
8
+ function vueCliHandler(devServerConfig) {
9
+ const sourceWebpackModulesResult = (0, sourceRelativeWebpackModules_1.sourceDefaultWebpackDependencies)(devServerConfig);
10
+ try {
11
+ const config = require.resolve('@vue/cli-service/webpack.config', {
12
+ paths: [devServerConfig.cypressConfig.projectRoot],
13
+ });
14
+ const webpackConfig = require(config);
15
+ debug('webpack config %o', webpackConfig);
16
+ delete webpackConfig.entry;
17
+ return { frameworkConfig: webpackConfig, sourceWebpackModulesResult };
18
+ }
19
+ catch (e) {
20
+ console.error(e); // eslint-disable-line no-console
21
+ throw Error(`Error loading @vue/cli-service/webpack.config.js. Looked in ${require.resolve.paths(devServerConfig.cypressConfig.projectRoot)}`);
22
+ }
23
+ }
24
+ exports.vueCliHandler = vueCliHandler;
package/dist/index.d.ts CHANGED
@@ -1,15 +1,3 @@
1
- /// <reference types="cypress" />
2
- import { StartDevServer, WebpackConfigurationWithDevServer } from './startServer';
3
- declare type DoneCallback = () => unknown;
4
- export interface ResolvedDevServerConfig {
5
- port: number;
6
- close: (done?: DoneCallback) => void;
7
- }
8
- export { StartDevServer };
9
- export declare function startDevServer(startDevServerArgs: StartDevServer, exitProcess?: (code?: number | undefined) => never): Promise<ResolvedDevServerConfig>;
10
- export interface CypressWebpackDevServerConfig {
11
- webpackConfig?: WebpackConfigurationWithDevServer;
12
- template?: string;
13
- }
14
- export declare function devServer(cypressDevServerConfig: Cypress.DevServerConfig, devServerConfig?: CypressWebpackDevServerConfig): Promise<ResolvedDevServerConfig>;
15
- export declare function defineDevServerConfig(devServerConfig: CypressWebpackDevServerConfig): CypressWebpackDevServerConfig;
1
+ import { devServer } from './devServer';
2
+ export { devServer };
3
+ export default devServer;
package/dist/index.js CHANGED
@@ -1,65 +1,6 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.defineDevServerConfig = exports.devServer = exports.startDevServer = void 0;
13
- const debug_1 = require("debug");
14
- const startServer_1 = require("./startServer");
15
- const webpackDevServerFacts_1 = require("./webpackDevServerFacts");
16
- const debug = (0, debug_1.debug)('cypress:webpack-dev-server:webpack');
17
- function startDevServer(startDevServerArgs, exitProcess = process.exit) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- const webpackDevServer = yield (0, startServer_1.start)(startDevServerArgs, exitProcess);
20
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
21
- if (webpackDevServerFacts_1.webpackDevServerFacts.isV3()) {
22
- // @ts-ignore
23
- const server = webpackDevServer.listen(0, '127.0.0.1', () => {
24
- // FIXME: handle address returning a string
25
- const port = server.address().port;
26
- debug('Component testing webpack server started on port', port);
27
- resolve({
28
- port,
29
- close: (done) => {
30
- server.close();
31
- done === null || done === void 0 ? void 0 : done();
32
- },
33
- });
34
- });
35
- return;
36
- }
37
- if (webpackDevServerFacts_1.webpackDevServerFacts.isV4()) {
38
- yield webpackDevServer.start();
39
- resolve({
40
- // @ts-expect-error @types do not yet support v4
41
- port: webpackDevServer.options.port,
42
- close: (done) => {
43
- webpackDevServer.stop();
44
- done === null || done === void 0 ? void 0 : done();
45
- },
46
- });
47
- return;
48
- }
49
- reject(webpackDevServerFacts_1.webpackDevServerFacts.unsupported());
50
- }));
51
- });
52
- }
53
- exports.startDevServer = startDevServer;
54
- function devServer(cypressDevServerConfig, devServerConfig) {
55
- return startDevServer({
56
- options: cypressDevServerConfig,
57
- webpackConfig: devServerConfig === null || devServerConfig === void 0 ? void 0 : devServerConfig.webpackConfig,
58
- template: devServerConfig === null || devServerConfig === void 0 ? void 0 : devServerConfig.template,
59
- });
60
- }
61
- exports.devServer = devServer;
62
- function defineDevServerConfig(devServerConfig) {
63
- return devServerConfig;
64
- }
65
- exports.defineDevServerConfig = defineDevServerConfig;
3
+ exports.devServer = void 0;
4
+ const devServer_1 = require("./devServer");
5
+ Object.defineProperty(exports, "devServer", { enumerable: true, get: function () { return devServer_1.devServer; } });
6
+ exports.default = devServer_1.devServer;
package/dist/loader.d.ts CHANGED
@@ -1,3 +1 @@
1
- import { CypressCTWebpackContext } from './plugin';
2
- import type { LoaderContext } from 'webpack';
3
- export default function loader(this: CypressCTWebpackContext & LoaderContext<void>): string;
1
+ export default function loader(this: unknown): string;