-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
server.js
405 lines (365 loc) · 12.5 KB
/
server.js
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-cond-assign */
function execute(port, options) {
const extractTranslations = require('../write-translations');
const metadataUtils = require('./metadataUtils');
const blog = require('./blog');
const docs = require('./docs');
const env = require('./env.js');
const express = require('express');
const React = require('react');
const request = require('request');
const fs = require('fs-extra');
const path = require('path');
const {isSeparateCss} = require('./utils');
const mkdirp = require('mkdirp');
const glob = require('glob');
const chalk = require('chalk');
const gaze = require('gaze');
const tinylr = require('tiny-lr');
const constants = require('../core/constants');
const translate = require('./translate');
const {renderToStaticMarkupWithDoctype} = require('./renderUtils');
const feed = require('./feed');
const sitemap = require('./sitemap');
const routing = require('./routing');
const CWD = process.cwd();
const join = path.join;
const sep = path.sep;
function removeModulePathFromCache(moduleName) {
/* eslint-disable no-underscore-dangle */
Object.keys(module.constructor._pathCache).forEach(cacheKey => {
if (cacheKey.indexOf(moduleName) > 0) {
delete module.constructor._pathCache[cacheKey];
}
});
}
// Remove a module and child modules from require cache, so server
// does not have to be restarted.
function removeModuleAndChildrenFromCache(moduleName) {
let mod = require.resolve(moduleName);
if (mod && (mod = require.cache[mod])) {
mod.children.forEach(child => {
delete require.cache[child.id];
removeModulePathFromCache(mod.id);
});
delete require.cache[mod.id];
removeModulePathFromCache(mod.id);
}
}
const readMetadata = require('./readMetadata.js');
let Metadata;
let MetadataBlog;
let siteConfig;
function reloadMetadata() {
removeModuleAndChildrenFromCache('./readMetadata.js');
readMetadata.generateMetadataDocs();
removeModuleAndChildrenFromCache('../core/metadata.js');
Metadata = require('../core/metadata.js');
}
function reloadMetadataBlog() {
if (fs.existsSync(join(__dirname, '..', 'core', 'MetadataBlog.js'))) {
removeModuleAndChildrenFromCache(join('..', 'core', 'MetadataBlog.js'));
fs.removeSync(join(__dirname, '..', 'core', 'MetadataBlog.js'));
}
readMetadata.generateMetadataBlog();
MetadataBlog = require(join('..', 'core', 'MetadataBlog.js'));
}
function reloadSiteConfig() {
removeModuleAndChildrenFromCache(join(CWD, 'siteConfig.js'));
siteConfig = require(join(CWD, 'siteConfig.js'));
if (siteConfig.highlight && siteConfig.highlight.hljs) {
siteConfig.highlight.hljs(require('highlight.js'));
}
}
function requestFile(url, res, notFoundCallback) {
request.get(url, (error, response, body) => {
if (!error) {
if (response) {
if (response.statusCode === 404 && notFoundCallback) {
notFoundCallback();
} else {
res.status(response.statusCode).send(body);
}
} else {
console.error('No response');
}
} else {
console.error('Request failed:', error);
}
});
}
function startLiveReload() {
process.env.NODE_ENV = 'development';
const server = tinylr();
server.listen(constants.LIVE_RELOAD_PORT, () => {
console.log(
'LiveReload server started on port %d',
constants.LIVE_RELOAD_PORT
);
});
gaze(
[`../${readMetadata.getDocsPath()}/**/*`, '**/*', '!node_modules/**/*'],
function() {
this.on('all', () => {
server.notifyClients(['/']);
});
}
);
}
reloadMetadata();
reloadMetadataBlog();
extractTranslations();
reloadSiteConfig();
const app = express();
app.get(routing.docs(siteConfig.baseUrl), (req, res, next) => {
const url = req.path.toString().replace(siteConfig.baseUrl, '');
const metadata =
Metadata[
Object.keys(Metadata).find(id => Metadata[id].permalink === url)
];
const file = docs.getFile(metadata);
if (!file) {
next();
return;
}
const rawContent = metadataUtils.extractMetadata(file).rawContent;
removeModuleAndChildrenFromCache('../core/DocsLayout.js');
const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig.baseUrl);
res.send(docs.getMarkup(rawContent, mdToHtml, metadata));
});
app.get(routing.sitemap(siteConfig.baseUrl), (req, res) => {
sitemap((err, xml) => {
if (err) {
res.status(500).send('Sitemap error');
} else {
res.set('Content-Type', 'application/xml');
res.send(xml);
}
});
});
app.get(routing.feed(siteConfig.baseUrl), (req, res, next) => {
res.set('Content-Type', 'application/rss+xml');
const file = req.path
.toString()
.split('blog/')[1]
.toLowerCase();
if (file === 'atom.xml') {
res.send(feed('atom'));
} else if (file === 'feed.xml') {
res.send(feed('rss'));
}
next();
});
app.get(routing.blog(siteConfig.baseUrl), (req, res, next) => {
// Regenerate the blog metadata in case it has changed. Consider improving
// this to regenerate on file save rather than on page request.
reloadMetadataBlog();
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPageLayout.js'));
const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig);
const urlPath = req.path.toString().split('blog/')[1];
if (urlPath === 'index.html') {
res.send(blogPages['/index.html']);
} else if (urlPath.endsWith('/index.html') && blogPages[urlPath]) {
res.send(blogPages[urlPath]);
} else if (urlPath.match(/page([0-9]+)/)) {
res.send(blogPages[`${urlPath.replace(/\/$/, '')}/index.html`]);
} else {
const file = join(CWD, 'blog', blog.urlToSource(urlPath));
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js'));
const blogPost = blog.getPostMarkup(file, siteConfig);
if (!blogPost) {
next();
return;
}
res.send(blogPost);
}
});
app.get(routing.page(siteConfig.baseUrl), (req, res, next) => {
// Look for user-provided HTML file first.
let htmlFile = req.path.toString().replace(siteConfig.baseUrl, '');
htmlFile = join(CWD, 'pages', htmlFile);
if (
fs.existsSync(htmlFile) ||
fs.existsSync(
(htmlFile = htmlFile.replace(
path.basename(htmlFile),
join('en', path.basename(htmlFile))
))
)
) {
if (siteConfig.wrapPagesHTML) {
removeModuleAndChildrenFromCache(join('..', 'core', 'Site.js'));
const Site = require(join('..', 'core', 'Site.js'));
const str = renderToStaticMarkupWithDoctype(
<Site
language="en"
config={siteConfig}
metadata={{id: path.basename(htmlFile, '.html')}}>
<div
dangerouslySetInnerHTML={{
__html: fs.readFileSync(htmlFile, {encoding: 'utf8'}),
}}
/>
</Site>
);
res.send(str);
} else {
res.send(fs.readFileSync(htmlFile, {encoding: 'utf8'}));
}
next();
return;
}
// look for user provided react file either in specified path or in path for english files
let file = req.path.toString().replace(/\.html$/, '.js');
file = file.replace(siteConfig.baseUrl, '');
let userFile = join(CWD, 'pages', file);
let language = env.translation.enabled ? 'en' : '';
const regexLang = /(.*)\/.*\.html$/;
const match = regexLang.exec(req.path);
const parts = match[1].split('/');
const enabledLangTags = env.translation
.enabledLanguages()
.map(lang => lang.tag);
for (let i = 0; i < parts.length; i++) {
if (enabledLangTags.indexOf(parts[i]) !== -1) {
language = parts[i];
}
}
let englishFile = join(CWD, 'pages', file);
if (language && language !== 'en') {
englishFile = englishFile.replace(sep + language + sep, `${sep}en${sep}`);
}
// check for: a file for the page, an english file for page with unspecified language, or an
// english file for the page
if (
fs.existsSync(userFile) ||
fs.existsSync(
(userFile = userFile.replace(
path.basename(userFile),
`en${sep}${path.basename(userFile)}`
))
) ||
fs.existsSync((userFile = englishFile))
) {
// copy into docusaurus so require paths work
const userFileParts = userFile.split(`pages${sep}`);
let tempFile = join(__dirname, '..', 'pages', userFileParts[1]);
tempFile = tempFile.replace(
path.basename(file),
`temp${path.basename(file)}`
);
mkdirp.sync(path.dirname(tempFile));
fs.copySync(userFile, tempFile);
// render into a string
removeModuleAndChildrenFromCache(tempFile);
const ReactComp = require(tempFile);
removeModuleAndChildrenFromCache(join('..', 'core', 'Site.js'));
const Site = require(join('..', 'core', 'Site.js'));
translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype(
<Site
language={language}
config={siteConfig}
title={ReactComp.title}
description={ReactComp.description}
metadata={{id: path.basename(userFile, '.js')}}>
<ReactComp language={language} />
</Site>
);
fs.removeSync(tempFile);
res.send(str);
} else {
next();
}
});
app.get(/main\.css$/, (req, res) => {
const mainCssPath = join(
__dirname,
'..',
'static',
req.path.toString().replace(siteConfig.baseUrl, '/')
);
let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'});
const files = glob.sync(join(CWD, 'static', '**', '*.css'));
files.forEach(file => {
if (isSeparateCss(file, siteConfig.separateCss)) {
return;
}
cssContent = `${cssContent}\n${fs.readFileSync(file, {
encoding: 'utf8',
})}`;
});
if (
!siteConfig.colors ||
!siteConfig.colors.primaryColor ||
!siteConfig.colors.secondaryColor
) {
console.error(
`${chalk.yellow(
'Missing color configuration.'
)} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`
);
}
Object.keys(siteConfig.colors).forEach(key => {
const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
});
if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => {
const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`)
.join(', ');
cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'),
fontString
);
});
}
res.header('Content-Type', 'text/css');
res.send(cssContent);
});
// serve static assets from these locations
app.use(
`${siteConfig.baseUrl}docs/assets`,
express.static(join(CWD, '..', readMetadata.getDocsPath(), 'assets'))
);
app.use(
`${siteConfig.baseUrl}blog/assets`,
express.static(join(CWD, 'blog', 'assets'))
);
app.use(siteConfig.baseUrl, express.static(join(CWD, 'static')));
app.use(siteConfig.baseUrl, express.static(join(__dirname, '..', 'static')));
// "redirect" requests to pages ending with "/" or no extension so that,
// for example, request to "blog" returns "blog/index.html" or "blog.html"
app.get(routing.noExtension(), (req, res, next) => {
const slash = req.path.toString().endsWith('/') ? '' : '/';
const requestUrl = `http://localhost:${port}${req.path}`;
requestFile(`${requestUrl + slash}index.html`, res, () => {
requestFile(
slash === '/'
? `${requestUrl}.html`
: requestUrl.replace(/\/$/, '.html'),
res,
next
);
});
});
// handle special cleanUrl case like '/blog/1.2.3' & '/blog.robots.hai'
// where we should try to serve '/blog/1.2.3.html' & '/blog.robots.hai.html'
app.get(routing.dotfiles(), (req, res, next) => {
if (!siteConfig.cleanUrl) {
next();
return;
}
requestFile(`http://localhost:${port}${req.path}.html`, res, next);
});
if (options.watch) startLiveReload();
app.listen(port);
}
module.exports = execute;