blob: e0374dbffb0fe7bfe506b1d47a59633fddcd657d [file] [log] [blame]
Jack Franklin0155f7d2021-03-02 09:11:22 +00001// Copyright 2021 The Chromium Authors. All rights reserved.
Jack Franklin1557a1c2020-06-08 15:22:13 +01002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5const fs = require('fs');
6const http = require('http');
7const path = require('path');
8const parseURL = require('url').parse;
9const {argv} = require('yargs');
10
11const serverPort = parseInt(process.env.PORT, 10) || 8090;
12
Jack Franklin8742dc82021-02-26 09:17:59 +000013const target = argv.target || process.env.TARGET || 'Default';
14
15/**
16 * This configures the base of the URLs that are injected into each component
17 * doc example to load. By default it's /, so that we load /front_end/..., but
18 * this can be configured if you have a different file structure.
19 */
20const sharedResourcesBase = argv.sharedResourcesBase || '/';
Jack Franklin086ccd52020-11-27 11:00:14 +000021
22/**
Jack Franklin0155f7d2021-03-02 09:11:22 +000023 * The server assumes that examples live in
24 * devtoolsRoot/out/Target/front_end/component_docs, but if you need to add a
25 * prefix you can pass this argument. Passing `foo` will redirect the server to
26 * look in devtoolsRoot/out/Target/foo/front_end/component_docs.
27 */
28const componentDocsBaseArg = argv.componentDocsBase || process.env.COMPONENT_DOCS_BASE || '';
29
30/**
Jack Franklin086ccd52020-11-27 11:00:14 +000031 * When you run npm run components-server we run the script as is from scripts/,
32 * but when this server is run as part of a test suite it's run from
33 * out/Default/gen/scripts, so we have to do a bit of path mangling to figure
34 * out where we are.
35 */
Jack Franklin8742dc82021-02-26 09:17:59 +000036const isRunningInGen = __dirname.includes(path.join('out', path.sep, target));
Jack Franklinb36ad7e2020-12-07 10:20:52 +000037
Jack Franklin8742dc82021-02-26 09:17:59 +000038let pathToOutTargetDir = __dirname;
39/**
40 * If we are in the gen directory, we need to find the out/Default folder to use
41 * as our base to find files from. We could do this with path.join(x, '..',
42 * '..') until we get the right folder, but that's brittle. It's better to
43 * search up for out/Default to be robust to any folder structures.
44 */
45while (isRunningInGen && !pathToOutTargetDir.endsWith(`out${path.sep}${target}`)) {
46 pathToOutTargetDir = path.resolve(pathToOutTargetDir, '..');
47}
Jack Franklin0943df42021-02-26 11:12:13 +000048
49/* If we are not running in out/Default, we'll assume the script is running from the repo root, and navigate to {CWD}/out/Target */
Jack Franklin8742dc82021-02-26 09:17:59 +000050const pathToBuiltOutTargetDirectory =
Jack Franklin0943df42021-02-26 11:12:13 +000051 isRunningInGen ? pathToOutTargetDir : path.resolve(path.join(process.cwd(), 'out', target));
Jack Franklin8742dc82021-02-26 09:17:59 +000052
Jack Franklin90b66132021-01-05 11:33:43 +000053const devtoolsRootFolder = path.resolve(path.join(pathToBuiltOutTargetDirectory, 'gen'));
Jack Franklin0155f7d2021-03-02 09:11:22 +000054const componentDocsBaseFolder = path.join(devtoolsRootFolder, componentDocsBaseArg);
Jack Franklin1557a1c2020-06-08 15:22:13 +010055
Jack Franklin90b66132021-01-05 11:33:43 +000056if (!fs.existsSync(devtoolsRootFolder)) {
57 console.error(`ERROR: Generated front_end folder (${devtoolsRootFolder}) does not exist.`);
Jack Franklin1557a1c2020-06-08 15:22:13 +010058 console.log(
59 'The components server works from the built Ninja output; you may need to run Ninja to update your built DevTools.');
60 console.log('If you build to a target other than default, you need to pass --target=X as an argument');
61 process.exit(1);
62}
63
Jack Franklin086ccd52020-11-27 11:00:14 +000064const server = http.createServer(requestHandler);
65server.listen(serverPort);
66server.once('listening', () => {
67 if (process.send) {
68 process.send(serverPort);
69 }
70 console.log(`Started components server at http://localhost:${serverPort}\n`);
Jack Franklin0155f7d2021-03-02 09:11:22 +000071 console.log(`component_docs location: ${
72 path.relative(process.cwd(), path.join(componentDocsBaseFolder, 'front_end', 'component_docs'))}`);
Jack Franklin086ccd52020-11-27 11:00:14 +000073});
74
75server.once('error', error => {
76 if (process.send) {
77 process.send('ERROR');
78 }
79 throw error;
80});
Jack Franklin1557a1c2020-06-08 15:22:13 +010081
82function createComponentIndexFile(componentPath, componentExamples) {
Jack Franklin7a75e462021-01-08 16:17:13 +000083 const componentName = componentPath.replace('/front_end/component_docs/', '').replace(/_/g, ' ').replace('/', '');
Jack Franklin1557a1c2020-06-08 15:22:13 +010084 // clang-format off
85 return `<!DOCTYPE html>
86 <html>
87 <head>
88 <meta charset="UTF-8" />
89 <meta name="viewport" content="width=device-width" />
90 <title>DevTools component: ${componentName}</title>
91 <style>
92 h1 { text-transform: capitalize; }
93
94 .example {
95 padding: 5px;
96 margin: 10px;
97 }
Jack Franklin7a75e462021-01-08 16:17:13 +000098
99 a:link,
100 a:visited {
101 color: blue;
102 text-decoration: underline;
103 }
104
105 a:hover {
106 text-decoration: none;
107 }
108 .example summary {
109 font-size: 20px;
110 }
111
112 .back-link {
113 padding-left: 5px;
114 font-size: 16px;
115 font-style: italic;
116 }
117
118 iframe { display: block; width: 100%; height: 400px; }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100119 </style>
120 </head>
121 <body>
Jack Franklin7a75e462021-01-08 16:17:13 +0000122 <h1>
123 ${componentName}
124 <a class="back-link" href="/">Back to index</a>
125 </h1>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100126 ${componentExamples.map(example => {
Jack Franklin90b66132021-01-05 11:33:43 +0000127 const fullPath = path.join(componentPath, example);
Jack Franklin7a75e462021-01-08 16:17:13 +0000128 return `<details class="example">
129 <summary><a href="${fullPath}">${example.replace('.html', '').replace(/-|_/g, ' ')}</a></summary>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100130 <iframe src="${fullPath}"></iframe>
Jack Franklin7a75e462021-01-08 16:17:13 +0000131 </details>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100132 }).join('\n')}
133 </body>
134 </html>`;
135 // clang-format on
136}
137
138function createServerIndexFile(componentNames) {
139 // clang-format off
140 return `<!DOCTYPE html>
141 <html>
142 <head>
143 <meta charset="UTF-8" />
144 <meta name="viewport" content="width=device-width" />
145 <title>DevTools components</title>
146 <style>
Jack Franklinb5997162020-11-25 17:28:51 +0000147 a:link, a:visited {
148 color: blue;
149 text-transform: capitalize;
150 text-decoration: none;
151 }
152 a:hover {
153 text-decoration: underline;
154 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100155 </style>
156 </head>
157 <body>
158 <h1>DevTools components</h1>
159 <ul>
160 ${componentNames.map(name => {
Jack Franklinb5997162020-11-25 17:28:51 +0000161 const niceName = name.replace(/_/g, ' ');
Jack Franklin90b66132021-01-05 11:33:43 +0000162 return `<li><a href='/front_end/component_docs/${name}'>${niceName}</a></li>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100163 }).join('\n')}
164 </ul>
165 </body>
166 </html>`;
167 // clang-format on
168}
169
170async function getExamplesForPath(filePath) {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000171 const componentDirectory = path.join(componentDocsBaseFolder, filePath);
Jack Franklinc1501222020-10-02 09:42:08 +0100172 const allFiles = await fs.promises.readdir(componentDirectory);
173 const htmlExampleFiles = allFiles.filter(file => {
174 return path.extname(file) === '.html';
175 });
Jack Franklin1557a1c2020-06-08 15:22:13 +0100176
Jack Franklinc1501222020-10-02 09:42:08 +0100177 return createComponentIndexFile(filePath, htmlExampleFiles);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100178}
179
180function respondWithHtml(response, html) {
181 response.setHeader('Content-Type', 'text/html; charset=utf-8');
182 response.writeHead(200);
183 response.write(html, 'utf8');
184 response.end();
185}
186
187function send404(response, message) {
188 response.writeHead(404);
189 response.write(message, 'utf8');
190 response.end();
191}
192
Jack Franklin279564e2020-07-06 15:25:18 +0100193async function checkFileExists(filePath) {
194 try {
195 const errorsAccessingFile = await fs.promises.access(filePath, fs.constants.R_OK);
196 return !errorsAccessingFile;
197 } catch (e) {
198 return false;
199 }
200}
201
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100202/**
203 * In Devtools-Frontend we load images without a leading slash, e.g.
204 * url(Images/checker.png). This works within devtools, but breaks this component
Jack Franklin4738bc72020-09-17 09:51:24 +0100205 * server as the path ends up as /component_docs/my_component/Images/checker.png.
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100206 * So we check if the path ends in Images/*.* and if so, remove anything before
207 * it. Then it will be resolved correctly.
208 */
209function normalizeImagePathIfRequired(filePath) {
210 const imagePathRegex = /\/Images\/(\S+)\.(\w{3})/;
211 const match = imagePathRegex.exec(filePath);
212 if (!match) {
213 return filePath;
214 }
215
216 const [, imageName, imageExt] = match;
Jack Franklin90b66132021-01-05 11:33:43 +0000217 const normalizedPath = path.join('front_end', 'Images', `${imageName}.${imageExt}`);
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100218 return normalizedPath;
219}
220
Jack Franklin1557a1c2020-06-08 15:22:13 +0100221async function requestHandler(request, response) {
222 const filePath = parseURL(request.url).pathname;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100223 if (filePath === '/favicon.ico') {
224 send404(response, '404, no favicon');
225 return;
226 }
227
228 if (filePath === '/' || filePath === '/index.html') {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000229 const components = await fs.promises.readdir(path.join(componentDocsBaseFolder, 'front_end', 'component_docs'));
Jack Franklinb5997162020-11-25 17:28:51 +0000230 const html = createServerIndexFile(components.filter(filePath => {
Jack Franklin0155f7d2021-03-02 09:11:22 +0000231 const stats = fs.lstatSync(path.join(componentDocsBaseFolder, 'front_end', 'component_docs', filePath));
Jack Franklinb5997162020-11-25 17:28:51 +0000232 // Filter out some build config files (tsconfig, d.ts, etc), and just list the directories.
233 return stats.isDirectory();
234 }));
Jack Franklin1557a1c2020-06-08 15:22:13 +0100235 respondWithHtml(response, html);
Jack Franklin90b66132021-01-05 11:33:43 +0000236 } else if (filePath.startsWith('/front_end/component_docs') && path.extname(filePath) === '') {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100237 // This means it's a component path like /breadcrumbs.
238 const componentHtml = await getExamplesForPath(filePath);
239 respondWithHtml(response, componentHtml);
Jack Franklin36429002020-11-25 15:07:26 +0000240 return;
241 } else if (/component_docs\/(.+)\/(.+)\.html/.test(filePath)) {
242 /** This conditional checks if we are viewing an individual example's HTML
Jack Franklin90b66132021-01-05 11:33:43 +0000243 * file. e.g. localhost:8090/front_end/component_docs/data_grid/basic.html For each
Jack Franklin36429002020-11-25 15:07:26 +0000244 * example we inject themeColors.css into the page so all CSS variables
245 * that components use are available.
246 */
Jack Franklin8742dc82021-02-26 09:17:59 +0000247
Jack Franklin0155f7d2021-03-02 09:11:22 +0000248 /**
249 * We also let the user provide a different base path for any shared
250 * resources that we load. But if this is provided along with the
251 * componentDocsBaseArg, and the two are the same, we don't want to use the
252 * shared resources base, as it's part of the componentDocsBaseArg and
253 * therefore the URL is already correct.
254 *
255 * If we didn't get a componentDocsBaseArg or we did and it's different to
256 * the sharedResourcesBase, we use sharedResourcesBase.
257 */
258 const baseUrlForSharedResource =
259 componentDocsBaseArg && componentDocsBaseArg.endsWith(sharedResourcesBase) ? '/' : `/${sharedResourcesBase}`;
260 const fileContents = await fs.promises.readFile(path.join(componentDocsBaseFolder, filePath), {encoding: 'utf8'});
Jack Franklin8742dc82021-02-26 09:17:59 +0000261 const themeColoursLink = `<link rel="stylesheet" href="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000262 path.join(baseUrlForSharedResource, 'front_end', 'ui', 'themeColors.css')}" type="text/css" />`;
Jack Franklin343c1412021-02-26 15:08:10 +0000263 const inspectorCommonLink = `<link rel="stylesheet" href="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000264 path.join(baseUrlForSharedResource, 'front_end', 'ui', 'inspectorCommon.css')}" type="text/css" />`;
Jack Franklin8742dc82021-02-26 09:17:59 +0000265 const toggleDarkModeScript = `<script type="module" src="${
Jack Franklin0155f7d2021-03-02 09:11:22 +0000266 path.join(baseUrlForSharedResource, 'front_end', 'component_docs', 'component_docs.js')}"></script>`;
Jack Franklin343c1412021-02-26 15:08:10 +0000267 const newFileContents = fileContents.replace('<style>', `${themeColoursLink}\n${inspectorCommonLink}\n<style>`)
Jack Franklin36429002020-11-25 15:07:26 +0000268 .replace('<script', toggleDarkModeScript + '\n<script');
269 respondWithHtml(response, newFileContents);
270
Jack Franklin1557a1c2020-06-08 15:22:13 +0100271 } else {
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100272 // This means it's an asset like a JS file or an image.
273 const normalizedPath = normalizeImagePathIfRequired(filePath);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100274
Jack Franklin0155f7d2021-03-02 09:11:22 +0000275 let fullPath = path.join(componentDocsBaseFolder, normalizedPath);
Jack Franklind0345122020-12-21 09:12:04 +0000276 if (fullPath.endsWith(path.join('locales', 'en-US.json'))) {
277 // Rewrite this path so we can load up the locale in the component-docs
Jack Franklin0155f7d2021-03-02 09:11:22 +0000278 fullPath = path.join(componentDocsBaseFolder, 'front_end', 'i18n', 'locales', 'en-US.json');
Jack Franklind0345122020-12-21 09:12:04 +0000279 }
280
Jack Franklin90b66132021-01-05 11:33:43 +0000281 if (!fullPath.startsWith(devtoolsRootFolder) && !fileIsInTestFolder) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100282 console.error(`Path ${fullPath} is outside the DevTools Frontend root dir.`);
283 process.exit(1);
284 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100285
Jack Franklin279564e2020-07-06 15:25:18 +0100286 const fileExists = await checkFileExists(fullPath);
287
288 if (!fileExists) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100289 send404(response, '404, File not found');
290 return;
291 }
292
293 let encoding = 'utf8';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100294 if (fullPath.endsWith('.wasm') || fullPath.endsWith('.png') || fullPath.endsWith('.jpg') ||
295 fullPath.endsWith('.avif')) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100296 encoding = 'binary';
297 }
298
299 const fileContents = await fs.promises.readFile(fullPath, encoding);
300
301 encoding = 'utf8';
302 if (fullPath.endsWith('.js')) {
303 response.setHeader('Content-Type', 'text/javascript; charset=utf-8');
304 } else if (fullPath.endsWith('.css')) {
305 response.setHeader('Content-Type', 'text/css; charset=utf-8');
306 } else if (fullPath.endsWith('.wasm')) {
307 response.setHeader('Content-Type', 'application/wasm');
308 encoding = 'binary';
309 } else if (fullPath.endsWith('.svg')) {
310 response.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
311 } else if (fullPath.endsWith('.png')) {
312 response.setHeader('Content-Type', 'image/png');
313 encoding = 'binary';
314 } else if (fullPath.endsWith('.jpg')) {
315 response.setHeader('Content-Type', 'image/jpg');
316 encoding = 'binary';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100317 } else if (fullPath.endsWith('.avif')) {
318 response.setHeader('Content-Type', 'image/avif');
319 encoding = 'binary';
Jack Franklin1557a1c2020-06-08 15:22:13 +0100320 }
321
322 response.writeHead(200);
323 response.write(fileContents, encoding);
324 response.end();
325 }
326}