blob: 07150ddfbe49b9fa024bd51e757387e8566cd3c4 [file] [log] [blame]
Jack Franklin1557a1c2020-06-08 15:22:13 +01001// Copyright (c) 2020 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
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/**
23 * When you run npm run components-server we run the script as is from scripts/,
24 * but when this server is run as part of a test suite it's run from
25 * out/Default/gen/scripts, so we have to do a bit of path mangling to figure
26 * out where we are.
27 */
Jack Franklin8742dc82021-02-26 09:17:59 +000028const isRunningInGen = __dirname.includes(path.join('out', path.sep, target));
Jack Franklinb36ad7e2020-12-07 10:20:52 +000029
Jack Franklin8742dc82021-02-26 09:17:59 +000030let pathToOutTargetDir = __dirname;
31/**
32 * If we are in the gen directory, we need to find the out/Default folder to use
33 * as our base to find files from. We could do this with path.join(x, '..',
34 * '..') until we get the right folder, but that's brittle. It's better to
35 * search up for out/Default to be robust to any folder structures.
36 */
37while (isRunningInGen && !pathToOutTargetDir.endsWith(`out${path.sep}${target}`)) {
38 pathToOutTargetDir = path.resolve(pathToOutTargetDir, '..');
39}
40const pathToBuiltOutTargetDirectory =
41 isRunningInGen ? pathToOutTargetDir : path.resolve(path.join(__dirname, '..', '..', 'out', target));
42
Jack Franklin90b66132021-01-05 11:33:43 +000043const devtoolsRootFolder = path.resolve(path.join(pathToBuiltOutTargetDirectory, 'gen'));
Jack Franklin1557a1c2020-06-08 15:22:13 +010044
Jack Franklin90b66132021-01-05 11:33:43 +000045if (!fs.existsSync(devtoolsRootFolder)) {
46 console.error(`ERROR: Generated front_end folder (${devtoolsRootFolder}) does not exist.`);
Jack Franklin1557a1c2020-06-08 15:22:13 +010047 console.log(
48 'The components server works from the built Ninja output; you may need to run Ninja to update your built DevTools.');
49 console.log('If you build to a target other than default, you need to pass --target=X as an argument');
50 process.exit(1);
51}
52
Jack Franklin086ccd52020-11-27 11:00:14 +000053const server = http.createServer(requestHandler);
54server.listen(serverPort);
55server.once('listening', () => {
56 if (process.send) {
57 process.send(serverPort);
58 }
59 console.log(`Started components server at http://localhost:${serverPort}\n`);
60});
61
62server.once('error', error => {
63 if (process.send) {
64 process.send('ERROR');
65 }
66 throw error;
67});
Jack Franklin1557a1c2020-06-08 15:22:13 +010068
69function createComponentIndexFile(componentPath, componentExamples) {
Jack Franklin7a75e462021-01-08 16:17:13 +000070 const componentName = componentPath.replace('/front_end/component_docs/', '').replace(/_/g, ' ').replace('/', '');
Jack Franklin1557a1c2020-06-08 15:22:13 +010071 // clang-format off
72 return `<!DOCTYPE html>
73 <html>
74 <head>
75 <meta charset="UTF-8" />
76 <meta name="viewport" content="width=device-width" />
77 <title>DevTools component: ${componentName}</title>
78 <style>
79 h1 { text-transform: capitalize; }
80
81 .example {
82 padding: 5px;
83 margin: 10px;
84 }
Jack Franklin7a75e462021-01-08 16:17:13 +000085
86 a:link,
87 a:visited {
88 color: blue;
89 text-decoration: underline;
90 }
91
92 a:hover {
93 text-decoration: none;
94 }
95 .example summary {
96 font-size: 20px;
97 }
98
99 .back-link {
100 padding-left: 5px;
101 font-size: 16px;
102 font-style: italic;
103 }
104
105 iframe { display: block; width: 100%; height: 400px; }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100106 </style>
107 </head>
108 <body>
Jack Franklin7a75e462021-01-08 16:17:13 +0000109 <h1>
110 ${componentName}
111 <a class="back-link" href="/">Back to index</a>
112 </h1>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100113 ${componentExamples.map(example => {
Jack Franklin90b66132021-01-05 11:33:43 +0000114 const fullPath = path.join(componentPath, example);
Jack Franklin7a75e462021-01-08 16:17:13 +0000115 return `<details class="example">
116 <summary><a href="${fullPath}">${example.replace('.html', '').replace(/-|_/g, ' ')}</a></summary>
Jack Franklin1557a1c2020-06-08 15:22:13 +0100117 <iframe src="${fullPath}"></iframe>
Jack Franklin7a75e462021-01-08 16:17:13 +0000118 </details>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100119 }).join('\n')}
120 </body>
121 </html>`;
122 // clang-format on
123}
124
125function createServerIndexFile(componentNames) {
126 // clang-format off
127 return `<!DOCTYPE html>
128 <html>
129 <head>
130 <meta charset="UTF-8" />
131 <meta name="viewport" content="width=device-width" />
132 <title>DevTools components</title>
133 <style>
Jack Franklinb5997162020-11-25 17:28:51 +0000134 a:link, a:visited {
135 color: blue;
136 text-transform: capitalize;
137 text-decoration: none;
138 }
139 a:hover {
140 text-decoration: underline;
141 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100142 </style>
143 </head>
144 <body>
145 <h1>DevTools components</h1>
146 <ul>
147 ${componentNames.map(name => {
Jack Franklinb5997162020-11-25 17:28:51 +0000148 const niceName = name.replace(/_/g, ' ');
Jack Franklin90b66132021-01-05 11:33:43 +0000149 return `<li><a href='/front_end/component_docs/${name}'>${niceName}</a></li>`;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100150 }).join('\n')}
151 </ul>
152 </body>
153 </html>`;
154 // clang-format on
155}
156
157async function getExamplesForPath(filePath) {
Jack Franklin90b66132021-01-05 11:33:43 +0000158 const componentDirectory = path.join(devtoolsRootFolder, filePath);
Jack Franklinc1501222020-10-02 09:42:08 +0100159 const allFiles = await fs.promises.readdir(componentDirectory);
160 const htmlExampleFiles = allFiles.filter(file => {
161 return path.extname(file) === '.html';
162 });
Jack Franklin1557a1c2020-06-08 15:22:13 +0100163
Jack Franklinc1501222020-10-02 09:42:08 +0100164 return createComponentIndexFile(filePath, htmlExampleFiles);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100165}
166
167function respondWithHtml(response, html) {
168 response.setHeader('Content-Type', 'text/html; charset=utf-8');
169 response.writeHead(200);
170 response.write(html, 'utf8');
171 response.end();
172}
173
174function send404(response, message) {
175 response.writeHead(404);
176 response.write(message, 'utf8');
177 response.end();
178}
179
Jack Franklin279564e2020-07-06 15:25:18 +0100180async function checkFileExists(filePath) {
181 try {
182 const errorsAccessingFile = await fs.promises.access(filePath, fs.constants.R_OK);
183 return !errorsAccessingFile;
184 } catch (e) {
185 return false;
186 }
187}
188
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100189/**
190 * In Devtools-Frontend we load images without a leading slash, e.g.
191 * url(Images/checker.png). This works within devtools, but breaks this component
Jack Franklin4738bc72020-09-17 09:51:24 +0100192 * server as the path ends up as /component_docs/my_component/Images/checker.png.
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100193 * So we check if the path ends in Images/*.* and if so, remove anything before
194 * it. Then it will be resolved correctly.
195 */
196function normalizeImagePathIfRequired(filePath) {
197 const imagePathRegex = /\/Images\/(\S+)\.(\w{3})/;
198 const match = imagePathRegex.exec(filePath);
199 if (!match) {
200 return filePath;
201 }
202
203 const [, imageName, imageExt] = match;
Jack Franklin90b66132021-01-05 11:33:43 +0000204 const normalizedPath = path.join('front_end', 'Images', `${imageName}.${imageExt}`);
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100205 return normalizedPath;
206}
207
Jack Franklin1557a1c2020-06-08 15:22:13 +0100208async function requestHandler(request, response) {
209 const filePath = parseURL(request.url).pathname;
Jack Franklin1557a1c2020-06-08 15:22:13 +0100210 if (filePath === '/favicon.ico') {
211 send404(response, '404, no favicon');
212 return;
213 }
214
215 if (filePath === '/' || filePath === '/index.html') {
Jack Franklin90b66132021-01-05 11:33:43 +0000216 const components = await fs.promises.readdir(path.join(devtoolsRootFolder, 'front_end', 'component_docs'));
Jack Franklinb5997162020-11-25 17:28:51 +0000217 const html = createServerIndexFile(components.filter(filePath => {
Jack Franklin90b66132021-01-05 11:33:43 +0000218 const stats = fs.lstatSync(path.join(devtoolsRootFolder, 'front_end', 'component_docs', filePath));
Jack Franklinb5997162020-11-25 17:28:51 +0000219 // Filter out some build config files (tsconfig, d.ts, etc), and just list the directories.
220 return stats.isDirectory();
221 }));
Jack Franklin1557a1c2020-06-08 15:22:13 +0100222 respondWithHtml(response, html);
Jack Franklin90b66132021-01-05 11:33:43 +0000223 } else if (filePath.startsWith('/front_end/component_docs') && path.extname(filePath) === '') {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100224 // This means it's a component path like /breadcrumbs.
225 const componentHtml = await getExamplesForPath(filePath);
226 respondWithHtml(response, componentHtml);
Jack Franklin36429002020-11-25 15:07:26 +0000227 return;
228 } else if (/component_docs\/(.+)\/(.+)\.html/.test(filePath)) {
229 /** This conditional checks if we are viewing an individual example's HTML
Jack Franklin90b66132021-01-05 11:33:43 +0000230 * file. e.g. localhost:8090/front_end/component_docs/data_grid/basic.html For each
Jack Franklin36429002020-11-25 15:07:26 +0000231 * example we inject themeColors.css into the page so all CSS variables
232 * that components use are available.
233 */
Jack Franklin8742dc82021-02-26 09:17:59 +0000234
235 // server --base=.
236
237 // server --base=devtools-frontend
238
Jack Franklin90b66132021-01-05 11:33:43 +0000239 const fileContents = await fs.promises.readFile(path.join(devtoolsRootFolder, filePath), {encoding: 'utf8'});
Jack Franklin8742dc82021-02-26 09:17:59 +0000240 const themeColoursLink = `<link rel="stylesheet" href="${
241 path.join(sharedResourcesBase, 'front_end', 'ui', 'themeColors.css')}" type="text/css" />`;
242 const inspectorStyleLink = `<link rel="stylesheet" href="${
243 path.join(sharedResourcesBase, 'front_end', 'ui', 'inspectorStyle.css')}" type="text/css" />`;
244 const toggleDarkModeScript = `<script type="module" src="${
245 path.join(sharedResourcesBase, 'front_end', 'component_docs', 'component_docs.js')}"></script>`;
Jack Frankline6dcd242021-01-18 16:09:22 +0000246 const newFileContents = fileContents.replace('<style>', `${themeColoursLink}\n${inspectorStyleLink}\n<style>`)
Jack Franklin36429002020-11-25 15:07:26 +0000247 .replace('<script', toggleDarkModeScript + '\n<script');
248 respondWithHtml(response, newFileContents);
249
Jack Franklin1557a1c2020-06-08 15:22:13 +0100250 } else {
Jack Franklin9d4ecf72020-09-16 14:04:30 +0100251 // This means it's an asset like a JS file or an image.
252 const normalizedPath = normalizeImagePathIfRequired(filePath);
Jack Franklin1557a1c2020-06-08 15:22:13 +0100253
Jack Franklin90b66132021-01-05 11:33:43 +0000254 let fullPath = path.join(devtoolsRootFolder, normalizedPath);
Jack Franklind0345122020-12-21 09:12:04 +0000255 if (fullPath.endsWith(path.join('locales', 'en-US.json'))) {
256 // Rewrite this path so we can load up the locale in the component-docs
Jack Franklin90b66132021-01-05 11:33:43 +0000257 fullPath = path.join(devtoolsRootFolder, 'front_end', 'i18n', 'locales', 'en-US.json');
Jack Franklind0345122020-12-21 09:12:04 +0000258 }
259
Jack Franklin90b66132021-01-05 11:33:43 +0000260 if (!fullPath.startsWith(devtoolsRootFolder) && !fileIsInTestFolder) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100261 console.error(`Path ${fullPath} is outside the DevTools Frontend root dir.`);
262 process.exit(1);
263 }
Jack Franklin1557a1c2020-06-08 15:22:13 +0100264
Jack Franklin279564e2020-07-06 15:25:18 +0100265 const fileExists = await checkFileExists(fullPath);
266
267 if (!fileExists) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100268 send404(response, '404, File not found');
269 return;
270 }
271
272 let encoding = 'utf8';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100273 if (fullPath.endsWith('.wasm') || fullPath.endsWith('.png') || fullPath.endsWith('.jpg') ||
274 fullPath.endsWith('.avif')) {
Jack Franklin1557a1c2020-06-08 15:22:13 +0100275 encoding = 'binary';
276 }
277
278 const fileContents = await fs.promises.readFile(fullPath, encoding);
279
280 encoding = 'utf8';
281 if (fullPath.endsWith('.js')) {
282 response.setHeader('Content-Type', 'text/javascript; charset=utf-8');
283 } else if (fullPath.endsWith('.css')) {
284 response.setHeader('Content-Type', 'text/css; charset=utf-8');
285 } else if (fullPath.endsWith('.wasm')) {
286 response.setHeader('Content-Type', 'application/wasm');
287 encoding = 'binary';
288 } else if (fullPath.endsWith('.svg')) {
289 response.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
290 } else if (fullPath.endsWith('.png')) {
291 response.setHeader('Content-Type', 'image/png');
292 encoding = 'binary';
293 } else if (fullPath.endsWith('.jpg')) {
294 response.setHeader('Content-Type', 'image/jpg');
295 encoding = 'binary';
Mathias Bynensc38abd42020-12-24 08:20:05 +0100296 } else if (fullPath.endsWith('.avif')) {
297 response.setHeader('Content-Type', 'image/avif');
298 encoding = 'binary';
Jack Franklin1557a1c2020-06-08 15:22:13 +0100299 }
300
301 response.writeHead(200);
302 response.write(fileContents, encoding);
303 response.end();
304 }
305}