docusaurus/packages/docusaurus-1.x/lib/server/server.js

407 lines
13 KiB
JavaScript
Raw Normal View History

2017-07-07 13:28:29 -04:00
/**
* Copyright (c) Facebook, Inc. and its affiliates.
2017-07-07 13:28:29 -04:00
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
2017-07-07 13:28:29 -04:00
*/
/* eslint-disable no-cond-assign */
function execute(port, host) {
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 translate = require('./translate');
const {renderToStaticMarkupWithDoctype} = require('./renderUtils');
const feed = require('./feed');
const sitemap = require('./sitemap');
const routing = require('./routing');
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
const loadConfig = require('./config');
2017-08-02 18:13:10 -04:00
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) {
2017-07-07 13:28:29 -04:00
let mod = require.resolve(moduleName);
2017-08-11 14:39:04 -04:00
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);
2017-07-07 13:28:29 -04:00
}
}
2017-08-11 14:39:04 -04:00
const readMetadata = require('./readMetadata.js');
2017-07-07 13:28:29 -04:00
let Metadata;
let MetadataBlog;
let siteConfig;
2017-07-07 13:28:29 -04:00
function reloadSiteConfig() {
const siteConfigPath = join(CWD, 'siteConfig.js');
removeModuleAndChildrenFromCache(siteConfigPath);
const oldBaseUrl = siteConfig && siteConfig.baseUrl;
siteConfig = loadConfig(siteConfigPath);
if (oldBaseUrl && oldBaseUrl !== siteConfig.baseUrl) {
console.log('Base url has changed. Please restart server ...');
process.exit();
}
}
2017-07-25 19:30:49 -04:00
function reloadMetadata() {
removeModuleAndChildrenFromCache('./readMetadata.js');
readMetadata.generateMetadataDocs();
removeModuleAndChildrenFromCache('../core/metadata.js');
Metadata = require('../core/metadata.js');
2017-07-07 13:28:29 -04:00
}
function reloadMetadataBlog() {
if (fs.existsSync(join(__dirname, '..', 'core', 'MetadataBlog.js'))) {
removeModuleAndChildrenFromCache(join('..', 'core', 'MetadataBlog.js'));
fs.removeSync(join(__dirname, '..', 'core', 'MetadataBlog.js'));
}
reloadSiteConfig();
readMetadata.generateMetadataBlog(siteConfig);
MetadataBlog = require(join('..', 'core', 'MetadataBlog.js'));
}
function reloadTranslations() {
removeModuleAndChildrenFromCache('./translation.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);
}
});
}
2017-07-25 19:30:49 -04:00
reloadMetadata();
reloadMetadataBlog();
extractTranslations();
reloadSiteConfig();
2017-07-07 13:28:29 -04:00
const app = express();
2017-08-03 13:25:01 -04:00
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
app.get(routing.docs(siteConfig), (req, res, next) => {
const url = decodeURI(req.path.toString().replace(siteConfig.baseUrl, ''));
const metakey = Object.keys(Metadata).find(
(id) => Metadata[id].permalink === url,
);
let metadata = Metadata[metakey];
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
const file = docs.getFile(metadata);
if (!file) {
2017-08-09 18:43:30 -04:00
next();
return;
}
const {rawContent, metadata: rawMetadata} = metadataUtils.extractMetadata(
file,
);
// if any of the followings is changed, reload the metadata
const reloadTriggers = ['sidebar_label', 'hide_title', 'title'];
if (reloadTriggers.some((key) => metadata[key] !== rawMetadata[key])) {
reloadMetadata();
extractTranslations();
reloadTranslations();
metadata = Metadata[metakey];
}
reloadSiteConfig();
removeModuleAndChildrenFromCache('../core/DocsLayout.js');
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig);
res.send(docs.getMarkup(rawContent, mdToHtml, metadata, siteConfig));
2017-07-10 19:38:35 -04:00
});
2017-08-03 13:25:01 -04:00
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
app.get(routing.sitemap(siteConfig), (req, res) => {
sitemap((err, xml) => {
if (err) {
res.status(500).send('Sitemap error');
} else {
res.set('Content-Type', 'application/xml');
res.send(xml);
}
});
});
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
app.get(routing.feed(siteConfig), (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();
});
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
app.get(routing.blog(siteConfig), (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];
2017-07-07 13:28:29 -04:00
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`]);
2017-07-10 19:38:35 -04:00
} 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);
2017-07-07 13:28:29 -04:00
}
});
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
app.get(routing.page(siteConfig), (req, res, next) => {
reloadSiteConfig();
// Look for user-provided HTML file first.
let htmlFile = req.path.toString().replace(siteConfig.baseUrl, '');
htmlFile = join(CWD, 'pages', htmlFile);
2017-07-10 19:38:35 -04:00
if (
fs.existsSync(htmlFile) ||
fs.existsSync(
(htmlFile = htmlFile.replace(
path.basename(htmlFile),
join('en', path.basename(htmlFile)),
)),
2017-07-10 19:38:35 -04:00
)
) {
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();
2017-07-07 13:28:29 -04:00
return;
}
2017-08-15 19:55:38 -04:00
// 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);
2017-07-07 13:28:29 -04:00
let language = env.translation.enabled ? 'en' : '';
2017-07-07 13:28:29 -04:00
const regexLang = /(.*)\/.*\.html$/;
const match = regexLang.exec(req.path);
const parts = match[1].split('/');
const enabledLangTags = env.translation
.enabledLanguages()
.map((lang) => lang.tag);
2017-07-07 13:28:29 -04:00
for (let i = 0; i < parts.length; i++) {
if (enabledLangTags.indexOf(parts[i]) !== -1) {
language = parts[i];
}
}
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
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
2017-08-15 19:55:38 -04:00
// english file for the page
2017-07-10 19:38:35 -04:00
if (
fs.existsSync(userFile) ||
fs.existsSync(
(userFile = userFile.replace(
path.basename(userFile),
`en${sep}${path.basename(userFile)}`,
)),
) ||
fs.existsSync((userFile = englishFile))
2017-07-10 19:38:35 -04:00
) {
2017-08-15 19:55:38 -04:00
// copy into docusaurus so require paths work
const userFileParts = userFile.split(join(CWD, `pages${sep}`));
let tempFile = join(__dirname, '..', 'pages', userFileParts[1]);
2017-07-10 19:38:35 -04:00
tempFile = tempFile.replace(
path.basename(file),
`temp${path.basename(file)}`,
2017-07-10 19:38:35 -04:00
);
mkdirp.sync(path.dirname(tempFile));
2017-07-07 13:28:29 -04:00
fs.copySync(userFile, tempFile);
2017-08-15 19:55:38 -04:00
// render into a string
removeModuleAndChildrenFromCache(tempFile);
2017-07-07 13:28:29 -04:00
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')}}>
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
<ReactComp config={siteConfig} language={language} />
</Site>,
2017-07-10 19:38:35 -04:00
);
2017-07-07 13:28:29 -04:00
fs.removeSync(tempFile);
res.send(str);
2017-07-10 19:38:35 -04:00
} else {
2017-07-19 13:50:32 -04:00
next();
2017-07-07 13:28:29 -04:00
}
});
app.get(`${siteConfig.baseUrl}css/main.css`, (req, res) => {
const mainCssPath = join(
__dirname,
'..',
'static',
req.path.toString().replace(siteConfig.baseUrl, '/'),
);
let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'});
2017-07-07 13:28:29 -04:00
const files = glob.sync(join(CWD, 'static', '**', '*.css'));
2017-07-07 13:28:29 -04:00
files.forEach((file) => {
if (isSeparateCss(file, siteConfig.separateCss)) {
return;
}
cssContent = `${cssContent}\n${fs.readFileSync(file, {
encoding: 'utf8',
})}`;
2017-07-07 13:28:29 -04:00
});
2017-08-10 19:03:43 -04:00
if (
2017-08-10 19:10:30 -04:00
!siteConfig.colors ||
2017-08-10 19:03:43 -04:00
!siteConfig.colors.primaryColor ||
!siteConfig.colors.secondaryColor
2017-08-10 19:03:43 -04:00
) {
console.error(
`${chalk.yellow(
'Missing color configuration.',
)} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`,
2017-07-10 19:38:35 -04:00
);
2017-08-10 19:03:43 -04:00
}
Object.keys(siteConfig.colors).forEach((key) => {
2017-08-10 19:03:43 -04:00
const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
2017-08-10 19:03:43 -04:00
});
2017-07-07 13:28:29 -04:00
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');
2017-07-07 13:28:29 -04:00
res.send(cssContent);
});
2017-08-15 19:55:38 -04:00
// serve static assets from these locations
2017-07-31 19:19:02 -04:00
app.use(
feat: Allow modifying `docs` url prefix (#914) * Allow other routes than /docs in the URL siteConfig.js has a new mandatory field named *docsRoute* which default value is 'docs' and that can be customized by the user. This change will allow users who uses the library to host guides and tutorials to customize their websites by assign 'docsRoute' values like 'tutorials' or 'guides'. Fixes #879 * Make "docsRoute" field optional * Isolate docsRoute login in getDocsRoute function * Rename docsRoute to docsUrl * Run prettier * Remove old folders * fix: Restore docusaurus reference link * fix: Add `docsUrl` param fallback. Refactor multiple function calls * Fix linting errors * Update description for docsUrl field * Reduce redundant calls to getDocsUrl * Replace a missed use case for `docsUrl` instead of the function call * Move `getDocsUrl` out from `server/routing.js` to `server/utils.js` **Why?** Because `routing.js` is exporting all router RegEx's, and the `getDocsUrl` suffices more as a util * WiP: Align leading slashes and fix routing around `docsUrl` Checklist: - [x] Added `removeDuplicateLeadingSlashes` util to make sure there is only one leading slash - [-] Fix edge cases for routing: - [x] `docsUrl: ''` - [ ] `docsUrl: '/'` - [ ] make it work with languages - [ ] make it work with versioning * Make leading slashes canonical cross routing and generated links This ensures correct routing for customized `baseUrl` and `docsUrl`. - Changed all routing functions to take `siteConfig` instead of `siteConfig.baseUrl` - Updated tests accordingly * Alternative fallback for `docsUrl` * rework/ fix implementation * cleanup * refactor and add docs for config props * fix typo * fix broken url
2018-11-28 02:34:16 -05:00
`${siteConfig.baseUrl}${
siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''
}assets`,
express.static(join(CWD, '..', readMetadata.getDocsPath(), 'assets')),
2017-07-31 19:19:02 -04:00
);
app.use(
`${siteConfig.baseUrl}blog/assets`,
express.static(join(CWD, 'blog', 'assets')),
2017-07-31 19:19:02 -04:00
);
app.use(siteConfig.baseUrl, express.static(join(CWD, 'static')));
app.use(siteConfig.baseUrl, express.static(join(__dirname, '..', 'static')));
2017-07-07 13:28:29 -04:00
// "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://${host}:${port}${req.path}`;
requestFile(`${requestUrl + slash}index.html`, res, () => {
requestFile(
slash === '/'
? `${requestUrl}.html`
: requestUrl.replace(/\/$/, '.html'),
res,
next,
);
});
2017-07-07 13:28:29 -04:00
});
// 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://${host}:${port}${req.path}.html`, res, next);
});
app.listen(port);
2017-07-07 13:28:29 -04:00
}
module.exports = execute;