auto-cms-server
Version:
Auto turn any webpage into editable CMS without coding.
68 lines (67 loc) • 2.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolvePathname = resolvePathname;
const fs_1 = require("fs");
const path_1 = require("path");
/**
* 0. ../file -> reject (out of site directory)
* 0. /.env -> reject (forbidden files)
* 1. /contact.html -> /contact.html
* 2. /contact -> /contact (if file exists without extension)
* 3. /contact -> /contact/index.html (if dir exists)
* 4. /contact -> /contact.html (if .html file exists without extension)
* 5. /contact -> /contact/index.html (if not exists without extension)
*/
function resolvePathname(options) {
let { site_dir, pathname } = options;
pathname = decodeURIComponent(options.pathname);
// use `resolve(join())` instead of `resolve()` to avoid resolving `/` pathname as root directory
let file = (0, path_1.resolve)((0, path_1.join)(site_dir, pathname));
// 0. ../file -> reject (out of site directory)
if (!file.startsWith(site_dir)) {
return { error: 'resolved pathname is out of the site directory' };
}
// 0. /.env -> reject (forbidden files)
let filename = (0, path_1.basename)(file);
if (filename == '.env' ||
filename.startsWith('.env.') ||
filename.endsWith('.env')) {
return { error: 'resolved pathname is forbidden' };
}
// 1. /contact.html -> /contact.html
if (file.endsWith('.html')) {
return { file, exists: (0, fs_1.existsSync)(file) };
}
try {
let stat = (0, fs_1.statSync)(file);
// 2. /contact -> /contact (if file exists without extension)
if (stat.isFile()) {
return { file, exists: true };
}
// 3. /contact -> /contact/index.html (if dir exists)
if (stat.isDirectory()) {
file = (0, path_1.join)(file, 'index.html');
return { file, exists: (0, fs_1.existsSync)(file) };
}
// e.g. socket file descriptor
return { error: 'unsupported file type' };
}
catch (error) {
// 4. /contact -> /contact.html (if .html file exists without extension)
{
let html_file = file + '.html';
if ((0, fs_1.existsSync)(html_file)) {
return { file: html_file, exists: true };
}
}
// 5. /contact -> /contact/index.html (if not exists without extension)
{
let dir = file;
if (options.mkdir) {
(0, fs_1.mkdirSync)(dir, { recursive: true });
}
let index_file = (0, path_1.join)(dir, 'index.html');
return { file: index_file, exists: false };
}
}
}