blob: 9062fa3d22e75db4b4c405d2dbd46babee0cabb2 [file] [log] [blame]
Benedikt Meurer1022e322025-03-28 13:39:581// Copyright 2025 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Benedikt Meurer8d2ec0b2025-04-03 09:43:245import childProcess from 'node:child_process';
6import fs from 'node:fs/promises';
7import path from 'node:path';
Benedikt Meurerb308e622025-04-17 11:24:298import {performance} from 'node:perf_hooks';
Benedikt Meurer8d2ec0b2025-04-03 09:43:249import util from 'node:util';
10
Nikolay Vitkova5686a82025-04-08 09:06:0011import {
12 autoninjaExecutablePath,
13 gnExecutablePath,
14 rootPath,
15} from './devtools_paths.js';
Benedikt Meurer8d2ec0b2025-04-03 09:43:2416
17const execFile = util.promisify(childProcess.execFile);
18
Benedikt Meurer1022e322025-03-28 13:39:5819/**
20 * Representation of the feature set that is configured for Chrome. This
21 * keeps track of enabled and disabled features and generates the correct
22 * combination of `--enable-features` / `--disable-features` command line
23 * flags.
24 *
25 * There are unit tests for this in `./devtools_build.test.mjs`.
26 */
27export class FeatureSet {
28 #disabled = new Set();
29 #enabled = new Map();
30
31 /**
32 * Disables the given `feature`.
33 *
34 * @param {string} feature the name of the feature to disable.
35 */
36 disable(feature) {
37 this.#disabled.add(feature);
38 this.#enabled.delete(feature);
39 }
40
41 /**
42 * Enables the given `feature`, and optionally adds the `parameters` to it.
43 * For example:
44 * ```js
45 * featureSet.enable('DevToolsFreestyler', {patching: true});
46 * ```
47 * The parameters are additive.
48 *
49 * @param {string} feature the name of the feature to enable.
50 * @param {object} parameters the additional parameters to pass to it, in
51 * the form of key/value pairs.
52 */
53 enable(feature, parameters = {}) {
54 this.#disabled.delete(feature);
55 if (!this.#enabled.has(feature)) {
56 this.#enabled.set(feature, Object.create(null));
57 }
58 for (const [key, value] of Object.entries(parameters)) {
59 this.#enabled.get(feature)[key] = value;
60 }
61 }
62
63 /**
64 * Merge the other `featureSet` into this.
65 *
66 * @param featureSet the other `FeatureSet` to apply.
67 */
68 merge(featureSet) {
69 for (const feature of featureSet.#disabled) {
70 this.disable(feature);
71 }
72 for (const [feature, parameters] of featureSet.#enabled) {
73 this.enable(feature, parameters);
74 }
75 }
76
77 /**
78 * Yields the command line parameters to pass to the invocation of
79 * a Chrome binary for achieving the state of the feature set.
80 */
Benedikt Meurerb308e622025-04-17 11:24:2981 * [Symbol.iterator]() {
Benedikt Meurer1022e322025-03-28 13:39:5882 const disabledFeatures = [...this.#disabled];
83 if (disabledFeatures.length) {
84 yield `--disable-features=${disabledFeatures.sort().join(',')}`;
85 }
86 const enabledFeatures = [...this.#enabled].map(([feature, parameters]) => {
87 parameters = Object.entries(parameters);
88 if (parameters.length) {
89 parameters = parameters.map(([key, value]) => `${key}/${value}`);
90 feature = `${feature}:${parameters.sort().join('/')}`;
91 }
92 return feature;
93 });
94 if (enabledFeatures.length) {
95 yield `--enable-features=${enabledFeatures.sort().join(',')}`;
96 }
97 }
98
99 static parse(text) {
Nikolay Vitkov28c7c022025-04-17 15:04:27100 if (!text) {
101 return [];
102 }
Benedikt Meurer1022e322025-03-28 13:39:58103 const features = [];
104 for (const str of text.split(',')) {
105 const parts = str.split(':');
106 if (parts.length < 1 || parts.length > 2) {
107 throw new Error(`Invalid feature declaration '${str}'`);
108 }
109 const feature = parts[0];
110 const parameters = Object.create(null);
111 if (parts.length > 1) {
112 const args = parts[1].split('/');
113 if (args.length % 2 !== 0) {
Nikolay Vitkova5686a82025-04-08 09:06:00114 throw new Error(
Benedikt Meurerb308e622025-04-17 11:24:29115 `Invalid parameters '${parts[1]}' for feature ${feature}`,
Nikolay Vitkova5686a82025-04-08 09:06:00116 );
Benedikt Meurer1022e322025-03-28 13:39:58117 }
118 for (let i = 0; i < args.length; i += 2) {
119 const key = args[i + 0];
120 const value = args[i + 1];
121 parameters[key] = value;
122 }
123 }
Benedikt Meurerb308e622025-04-17 11:24:29124 features.push({feature, parameters});
Benedikt Meurer1022e322025-03-28 13:39:58125 }
126 return features;
127 }
128}
Benedikt Meurer8d2ec0b2025-04-03 09:43:24129
Benedikt Meurer867b0b42025-04-17 16:31:19130/**
131 * Constructs a human readable error message for the given build `error`.
132 *
133 * @param {Error} error the `Error` from the failed `autoninja` invocation.
134 * @param {string} outDir the absolute path to the `target` out directory.
135 * @param {string} target the targe relative to `//out`.
136 * @return {string} the human readable error message.
137 */
138function buildErrorMessageForNinja(error, outDir, target) {
139 const {message, stderr, stdout} = error;
140 if (stderr) {
141 // Anything that went to stderr has precedence.
142 return `Failed to build \`${target}' in \`${outDir}'
143
144${stderr}
145`;
146 }
147 if (stdout) {
148 // Check for `tsc` or `esbuild` errors in the stdout.
149 const tscErrors = [...stdout.matchAll(/^[^\s].*\(\d+,\d+\): error TS\d+:\s+.*$/gm)].map(([tscError]) => tscError);
150 if (!tscErrors.length) {
151 // We didn't find any `tsc` errors, but maybe there are `esbuild` errors.
152 // Transform these into the `tsc` format (with a made up error code), so
153 // we can report all TypeScript errors consistently in `tsc` format (which
154 // is well-known and understood by tools).
155 const esbuildErrors = stdout.matchAll(/^✘ \[ERROR\] ([^\n]+)\n\n\s+\.\.\/\.\.\/(.+):(\d+):(\d+):/gm);
156 for (const [, message, filename, line, column] of esbuildErrors) {
157 tscErrors.push(`${filename}(${line},${column}): error TS0000: ${message}`);
158 }
159 }
160 if (tscErrors.length) {
161 return `TypeScript compilation failed for \`${target}'
162
163${tscErrors.join('\n')}
164`;
165 }
166
167 // At the very least we strip `ninja: Something, something` lines from the
168 // standard output, since that's not particularly helpful.
169 const output = stdout.replaceAll(/^ninja: [^\n]+\n+/mg, '').trim();
170 return `Failed to build \`${target}' in \`${outDir}'
171
172${output}
173`;
174 }
175 return `Failed to build \`${target}' in \`${outDir}' (${message.substring(0, message.indexOf('\n'))})`;
176}
177
Benedikt Meurer8d2ec0b2025-04-03 09:43:24178export const BuildStep = {
Benedikt Meurer867b0b42025-04-17 16:31:19179 GN: 'gn',
Benedikt Meurer8d2ec0b2025-04-03 09:43:24180 AUTONINJA: 'autoninja',
181};
182
183export class BuildError extends Error {
184 /**
185 * Constructs a new `BuildError` with the given parameters.
186 *
187 * @param {BuildStep} step the build step that failed.
188 * @param {Object} options additional options for the `BuildError`.
189 * @param {Error} options.cause the actual cause for the build error.
190 * @param {string} options.outDir the absolute path to the `target` out directory.
191 * @param {string} options.target the target relative to `//out`.
192 */
193 constructor(step, options) {
Benedikt Meurerb308e622025-04-17 11:24:29194 const {cause, outDir, target} = options;
Benedikt Meurer867b0b42025-04-17 16:31:19195 const message = step === BuildStep.GN ? `\`gn' failed to initialize out directory ${outDir}` :
196 buildErrorMessageForNinja(cause, outDir, target);
197 super(message, {cause});
Benedikt Meurer8d2ec0b2025-04-03 09:43:24198 this.step = step;
Benedikt Meurer867b0b42025-04-17 16:31:19199 this.name = 'BuildError';
Benedikt Meurer8d2ec0b2025-04-03 09:43:24200 this.target = target;
201 this.outDir = outDir;
202 }
Benedikt Meurer8d2ec0b2025-04-03 09:43:24203}
204
205/**
206 * @typedef BuildResult
207 * @type {object}
208 * @property {number} time - wall clock time (in seconds) for the build.
209 */
210
211/**
212 * @param {string} target
Nikolay Vitkova5686a82025-04-08 09:06:00213 * @return {Promise<void>}
Benedikt Meurer8d2ec0b2025-04-03 09:43:24214 */
Nikolay Vitkova5686a82025-04-08 09:06:00215export async function prepareBuild(target) {
Benedikt Meurer8d2ec0b2025-04-03 09:43:24216 const outDir = path.join(rootPath(), 'out', target);
217
218 // Prepare the build directory first.
219 const outDirStat = await fs.stat(outDir).catch(() => null);
220 if (!outDirStat?.isDirectory()) {
221 // Use GN to (optionally create and) initialize the |outDir|.
222 try {
223 const gnExe = gnExecutablePath();
224 const gnArgs = ['-q', 'gen', outDir];
Nikolay Vitkova5686a82025-04-08 09:06:00225 await execFile(gnExe, gnArgs);
Benedikt Meurer8d2ec0b2025-04-03 09:43:24226 } catch (cause) {
Benedikt Meurerb308e622025-04-17 11:24:29227 throw new BuildError(BuildStep.GN, {cause, outDir, target});
Benedikt Meurer8d2ec0b2025-04-03 09:43:24228 }
229 }
Nikolay Vitkova5686a82025-04-08 09:06:00230}
231
232/**
233 * @param {string} target
234 * @param {AbortSignal=} signal
235 * @return {Promise<BuildResult>} a `BuildResult` with statistics for the build.
236 */
237export async function build(target, signal) {
238 const startTime = performance.now();
239 const outDir = path.join(rootPath(), 'out', target);
Benedikt Meurer8d2ec0b2025-04-03 09:43:24240
241 // Build just the devtools-frontend resources in |outDir|. This is important
242 // since we might be running in a full Chromium checkout and certainly don't
243 // want to build all of Chromium first.
244 try {
245 const autoninjaExe = autoninjaExecutablePath();
Benedikt Meurer8ae0adc2025-04-17 08:32:24246 const autoninjaArgs = ['-C', outDir, 'devtools_all_files'];
Benedikt Meurerb308e622025-04-17 11:24:29247 await execFile(autoninjaExe, autoninjaArgs, {signal});
Benedikt Meurer8d2ec0b2025-04-03 09:43:24248 } catch (cause) {
249 if (cause.name === 'AbortError') {
250 throw cause;
251 }
Benedikt Meurerb308e622025-04-17 11:24:29252 throw new BuildError(BuildStep.AUTONINJA, {cause, outDir, target});
Benedikt Meurer8d2ec0b2025-04-03 09:43:24253 }
254
255 // Report the build result.
256 const time = (performance.now() - startTime) / 1000;
Benedikt Meurerb308e622025-04-17 11:24:29257 return {time};
Benedikt Meurer8ae0adc2025-04-17 08:32:24258}