2
1
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2023-12-13 21:00:40 +01:00

Updated var declarations to const/let and no lists

- All var declarations are now const or let as per ES6
- All comma-separated lists / chained declarations are now one declaration per line
- This is for clarity/readability but also made running the var-to-const/let switch smoother
- ESLint rules updated to match

How this was done:

- npm install -g jscodeshift
- git clone https://github.com/cpojer/js-codemod.git
- git clone git@github.com:TryGhost/Ghost.git shallow-ghost
- cd shallow-ghost
- jscodeshift -t ../js-codemod/transforms/unchain-variables.js . -v=2
- jscodeshift -t ../js-codemod/transforms/no-vars.js . -v=2
- yarn
- yarn test
- yarn lint / fix various lint errors (almost all indent) by opening files and saving in vscode
- grunt test-regression
- sorted!
This commit is contained in:
Hannah Wolfe 2020-04-29 16:44:27 +01:00
parent d255d98bbb
commit 22e13acd65
394 changed files with 6299 additions and 5754 deletions

View file

@ -8,5 +8,9 @@
],
"extends": [
"plugin:ghost/node"
]
],
"rules": {
"no-var": "error",
"one-var": [2, "never"]
}
}

View file

@ -48,7 +48,7 @@ const configureGrunt = function (grunt) {
grunt.loadNpmTasks('grunt-subgrunt');
grunt.loadNpmTasks('grunt-update-submodules');
var cfg = {
const cfg = {
// #### Common paths used by tasks
paths: {
build: buildDirectory,
@ -163,7 +163,7 @@ const configureGrunt = function (grunt) {
bg: grunt.option('client') ? false : true,
stdout: function (chunk) {
// hide certain output to prevent confusion when running alongside server
var filter = grunt.option('client') ? false : [
const filter = grunt.option('client') ? false : [
/> ghost-admin/,
/^Livereload/,
/^Serving on/
@ -208,7 +208,7 @@ const configureGrunt = function (grunt) {
},
master: {
command: function () {
var upstream = grunt.option('upstream') || process.env.GHOST_UPSTREAM || 'upstream';
const upstream = grunt.option('upstream') || process.env.GHOST_UPSTREAM || 'upstream';
grunt.log.writeln('Pulling down the latest master from ' + upstream);
return `
git submodule sync
@ -425,7 +425,7 @@ const configureGrunt = function (grunt) {
// so that the test environments do not need to build out the client files
grunt.registerTask('stubClientFiles', function () {
_.each(cfg.clientFiles, function (file) {
var filePath = path.resolve(cwd + '/core/' + file);
const filePath = path.resolve(cwd + '/core/' + file);
fs.ensureFileSync(filePath);
});
});

View file

@ -1,5 +1,5 @@
var config = require('./core/server/config'),
ghostVersion = require('./core/server/lib/ghost-version');
const config = require('./core/server/config');
const ghostVersion = require('./core/server/lib/ghost-version');
/**
* knex-migrator can be used via CLI or within the application

View file

@ -8,12 +8,13 @@
// By default supported AMP HTML tags (no additional script tag necessary):
// amp-img, amp-ad, amp-embed, amp-video and amp-pixel.
// (less) dirty requires
const proxy = require('../../../../services/proxy'),
SafeString = proxy.SafeString;
const proxy = require('../../../../services/proxy');
const SafeString = proxy.SafeString;
function ampComponents() {
let components = [],
html = this.post && this.post.html || this.html;
let components = [];
let html = this.post && this.post.html || this.html;
if (!html) {
return;
@ -23,8 +24,8 @@ function ampComponents() {
components.push('<script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script>');
}
let iframeCount = (html.match(/(<iframe)(.*?)(<\/iframe>)/gi) || []).length,
youtubeCount = (html.match(/(<iframe)(.*?)(youtu.be\/|youtube(-nocookie)?.com\/(v\/|.*u\/\w\/|embed\/|.*v=))(.*?)(<\/iframe>)/gi) || []).length;
let iframeCount = (html.match(/(<iframe)(.*?)(<\/iframe>)/gi) || []).length;
let youtubeCount = (html.match(/(<iframe)(.*?)(youtu.be\/|youtube(-nocookie)?.com\/(v\/|.*u\/\w\/|embed\/|.*v=))(.*?)(<\/iframe>)/gi) || []).length;
if (youtubeCount) {
components.push('<script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>');

View file

@ -6,21 +6,21 @@
//
// Converts normal HTML into AMP HTML with Amperize module and uses a cache to return it from
// there if available. The cacheId is a combination of `updated_at` and the `slug`.
const Promise = require('bluebird'),
moment = require('moment'),
proxy = require('../../../../services/proxy'),
SafeString = proxy.SafeString,
logging = proxy.logging,
i18n = proxy.i18n,
errors = proxy.errors,
urlUtils = proxy.urlUtils,
amperizeCache = {};
const Promise = require('bluebird');
let allowedAMPTags = [],
allowedAMPAttributes = {},
amperize = null,
ampHTML = '',
cleanHTML = '';
const moment = require('moment');
const proxy = require('../../../../services/proxy');
const SafeString = proxy.SafeString;
const logging = proxy.logging;
const i18n = proxy.i18n;
const errors = proxy.errors;
const urlUtils = proxy.urlUtils;
const amperizeCache = {};
let allowedAMPTags = [];
let allowedAMPAttributes = {};
let amperize = null;
let ampHTML = '';
let cleanHTML = '';
allowedAMPTags = ['html', 'body', 'article', 'section', 'nav', 'aside', 'h1', 'h2',
'h3', 'h4', 'h5', 'h6', 'header', 'footer', 'address', 'p', 'hr',
@ -119,8 +119,8 @@ function getAmperizeHTML(html, post) {
return;
}
let Amperize = require('amperize'),
startedAtMoment = moment();
let Amperize = require('amperize');
let startedAtMoment = moment();
amperize = amperize || new Amperize();
@ -163,11 +163,12 @@ function getAmperizeHTML(html, post) {
}
function ampContent() {
let sanitizeHtml = require('sanitize-html'),
cheerio = require('cheerio'),
amperizeHTML = {
amperize: getAmperizeHTML(this.html, this)
};
let sanitizeHtml = require('sanitize-html');
let cheerio = require('cheerio');
let amperizeHTML = {
amperize: getAmperizeHTML(this.html, this)
};
return Promise.props(amperizeHTML).then((result) => {
let $ = null;

View file

@ -1,12 +1,13 @@
const path = require('path'),
express = require('express'),
ampRouter = express.Router(),
const path = require('path');
const express = require('express');
const ampRouter = express.Router();
// Dirty requires
common = require('../../../../server/lib/common'),
urlService = require('../../../services/url'),
helpers = require('../../../services/routing/helpers'),
templateName = 'amp';
// Dirty requires
const common = require('../../../../server/lib/common');
const urlService = require('../../../services/url');
const helpers = require('../../../services/routing/helpers');
const templateName = 'amp';
function _renderer(req, res, next) {
res.routerOptions = {

View file

@ -1,10 +1,11 @@
const urlUtils = require('../../../server/lib/url-utils'),
common = require('../../../server/lib/common'),
middleware = require('./lib/middleware'),
router = require('./lib/router'),
registerHelpers = require('./lib/helpers'),
// routeKeywords.private: 'private'
PRIVATE_KEYWORD = 'private';
const urlUtils = require('../../../server/lib/url-utils');
const common = require('../../../server/lib/common');
const middleware = require('./lib/middleware');
const router = require('./lib/router');
const registerHelpers = require('./lib/helpers');
// routeKeywords.private: 'private'
const PRIVATE_KEYWORD = 'private';
let checkSubdir = function checkSubdir() {
let paths = '';

View file

@ -4,24 +4,24 @@
// Password input used on private.hbs for password-protected blogs
// (less) dirty requires
const proxy = require('../../../../services/proxy'),
SafeString = proxy.SafeString,
templates = proxy.templates;
const proxy = require('../../../../services/proxy');
const SafeString = proxy.SafeString;
const templates = proxy.templates;
// We use the name input_password to match the helper for consistency:
module.exports = function input_password(options) { // eslint-disable-line camelcase
options = options || {};
options.hash = options.hash || {};
let className = (options.hash.class) ? options.hash.class : 'private-login-password',
extras = 'autofocus="autofocus"',
output;
const className = (options.hash.class) ? options.hash.class : 'private-login-password';
let extras = 'autofocus="autofocus"';
if (options.hash.placeholder) {
extras += ` placeholder="${options.hash.placeholder}"`;
}
output = templates.input({
const output = templates.input({
type: 'password',
name: 'password',
className,

View file

@ -91,10 +91,10 @@ const privateBlogging = {
},
authenticatePrivateSession: function authenticatePrivateSession(req, res, next) {
let hash = req.session.token || '',
salt = req.session.salt || '',
isVerified = verifySessionHash(salt, hash),
url;
const hash = req.session.token || '';
const salt = req.session.salt || '';
const isVerified = verifySessionHash(salt, hash);
let url;
if (isVerified) {
return next();
@ -111,9 +111,9 @@ const privateBlogging = {
return res.redirect(urlUtils.urlFor('home', true));
}
let hash = req.session.token || '',
salt = req.session.salt || '',
isVerified = verifySessionHash(salt, hash);
const hash = req.session.token || '';
const salt = req.session.salt || '';
const isVerified = verifySessionHash(salt, hash);
if (isVerified) {
// redirect to home if user is already authenticated

View file

@ -1,11 +1,11 @@
const path = require('path'),
express = require('express'),
middleware = require('./middleware'),
bodyParser = require('body-parser'),
routing = require('../../../services/routing'),
web = require('../../../../server/web'),
templateName = 'private',
privateRouter = express.Router();
const path = require('path');
const express = require('express');
const middleware = require('./middleware');
const bodyParser = require('body-parser');
const routing = require('../../../services/routing');
const web = require('../../../../server/web');
const templateName = 'private';
const privateRouter = express.Router();
function _renderer(req, res) {
res.routerOptions = {

View file

@ -37,7 +37,7 @@ const pathAliases = {
* @returns {boolean}
*/
function isBrowse(options) {
var browse = true;
let browse = true;
if (options.id || options.slug) {
browse = false;
@ -55,10 +55,10 @@ function isBrowse(options) {
* @returns {String}
*/
function resolvePaths(globals, data, value) {
var regex = /\{\{(.*?)\}\}/g;
const regex = /\{\{(.*?)\}\}/g;
value = value.replace(regex, function (match, path) {
var result;
let result;
// Handle aliases
path = pathAliases[path] ? pathAliases[path] : path;
@ -141,7 +141,7 @@ module.exports = function get(resource, options) {
// @TODO: https://github.com/TryGhost/Ghost/issues/10548
return controller[action](apiOptions).then(function success(result) {
var blockParams;
let blockParams;
// used for logging details of slow requests
returnedRowsCount = result[resource] && result[resource].length;

View file

@ -7,9 +7,10 @@ const _ = require('lodash');
// We use the name ghost_foot to match the helper for consistency:
module.exports = function ghost_foot(options) { // eslint-disable-line camelcase
var foot = [],
globalCodeinjection = settingsCache.get('ghost_foot'),
postCodeinjection = options.data.root && options.data.root.post ? options.data.root.post.codeinjection_foot : null;
const foot = [];
const globalCodeinjection = settingsCache.get('ghost_foot');
const postCodeinjection = options.data.root && options.data.root.post ? options.data.root.post.codeinjection_foot : null;
if (!_.isEmpty(globalCodeinjection)) {
foot.push(globalCodeinjection);

View file

@ -15,7 +15,7 @@ function writeMetaTag(property, content, type) {
}
function finaliseStructuredData(metaData) {
var head = [];
const head = [];
_.each(metaData.structuredData, function (content, property) {
if (property === 'article:tag') {
@ -93,16 +93,16 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
return;
}
var head = [],
dataRoot = options.data.root,
context = dataRoot._locals.context ? dataRoot._locals.context : null,
safeVersion = dataRoot._locals.safeVersion,
postCodeInjection = dataRoot && dataRoot.post ? dataRoot.post.codeinjection_head : null,
globalCodeinjection = settingsCache.get('ghost_head'),
useStructuredData = !config.isPrivacyDisabled('useStructuredData'),
referrerPolicy = config.get('referrerPolicy') ? config.get('referrerPolicy') : 'no-referrer-when-downgrade',
favicon = blogIcon.getIconUrl(),
iconType = blogIcon.getIconType(favicon);
const head = [];
const dataRoot = options.data.root;
const context = dataRoot._locals.context ? dataRoot._locals.context : null;
const safeVersion = dataRoot._locals.safeVersion;
const postCodeInjection = dataRoot && dataRoot.post ? dataRoot.post.codeinjection_head : null;
const globalCodeinjection = settingsCache.get('ghost_head');
const useStructuredData = !config.isPrivacyDisabled('useStructuredData');
const referrerPolicy = config.get('referrerPolicy') ? config.get('referrerPolicy') : 'no-referrer-when-downgrade';
const favicon = blogIcon.getIconUrl();
const iconType = blogIcon.getIconType(favicon);
debug('preparation complete, begin fetch');

View file

@ -54,7 +54,7 @@ function handleTag(data, attrs) {
}
function evaluateAuthorList(expr, authors) {
var authorList = expr.split(',').map(function (v) {
const authorList = expr.split(',').map(function (v) {
return v.trim().toLocaleLowerCase();
});
@ -76,7 +76,7 @@ function handleAuthor(data, attrs) {
}
function evaluateIntegerMatch(expr, integer) {
var nthMatch = expr.match(/^nth:(\d+)/);
const nthMatch = expr.match(/^nth:(\d+)/);
if (nthMatch) {
return integer % parseInt(nthMatch[1], 10) === 0;
}
@ -118,39 +118,41 @@ module.exports = function has(options) {
options.hash = options.hash || {};
options.data = options.data || {};
var self = this,
attrs = _.pick(options.hash, validAttrs),
data = _.pick(options.data, ['site', 'config', 'labs']),
checks = {
tag: function () {
return handleTag(self, attrs);
},
author: function () {
return handleAuthor(self, attrs);
},
number: function () {
return attrs.number && evaluateIntegerMatch(attrs.number, options.data.number) || false;
},
index: function () {
return attrs.index && evaluateIntegerMatch(attrs.index, options.data.index) || false;
},
visibility: function () {
return attrs.visibility && evaluateStringMatch(attrs.visibility, self.visibility, true) || false;
},
slug: function () {
return attrs.slug && evaluateStringMatch(attrs.slug, self.slug, true) || false;
},
id: function () {
return attrs.id && evaluateStringMatch(attrs.id, self.id, true) || false;
},
any: function () {
return attrs.any && evaluateList('some', attrs.any, self, data) || false;
},
all: function () {
return attrs.all && evaluateList('every', attrs.all, self, data) || false;
}
const self = this;
const attrs = _.pick(options.hash, validAttrs);
const data = _.pick(options.data, ['site', 'config', 'labs']);
const checks = {
tag: function () {
return handleTag(self, attrs);
},
result;
author: function () {
return handleAuthor(self, attrs);
},
number: function () {
return attrs.number && evaluateIntegerMatch(attrs.number, options.data.number) || false;
},
index: function () {
return attrs.index && evaluateIntegerMatch(attrs.index, options.data.index) || false;
},
visibility: function () {
return attrs.visibility && evaluateStringMatch(attrs.visibility, self.visibility, true) || false;
},
slug: function () {
return attrs.slug && evaluateStringMatch(attrs.slug, self.slug, true) || false;
},
id: function () {
return attrs.id && evaluateStringMatch(attrs.id, self.id, true) || false;
},
any: function () {
return attrs.any && evaluateList('some', attrs.any, self, data) || false;
},
all: function () {
return attrs.all && evaluateList('every', attrs.all, self, data) || false;
}
};
let result;
if (_.isEmpty(attrs)) {
logging.warn(i18n.t('warnings.helpers.has.invalidAttribute'));

View file

@ -7,7 +7,7 @@ const _ = require('lodash');
module.exports = function is(context, options) {
options = options || {};
var currentContext = options.data.root.context;
const currentContext = options.data.root.context;
if (!_.isString(context)) {
logging.warn(i18n.t('warnings.helpers.is.invalidAttribute'));

View file

@ -16,10 +16,10 @@ module.exports = function navigation(options) {
options.hash.isSecondary = options.hash.type && options.hash.type === 'secondary';
delete options.hash.type;
var navigationData = options.data.site[key],
currentUrl = options.data.root.relativeUrl,
self = this,
output;
const navigationData = options.data.site[key];
const currentUrl = options.data.root.relativeUrl;
const self = this;
let output;
if (!_.isObject(navigationData) || _.isFunction(navigationData)) {
throw new errors.IncorrectUsageError({
@ -51,8 +51,8 @@ module.exports = function navigation(options) {
return false;
}
var strippedHref = href.replace(/\/+$/, ''),
strippedCurrentUrl = currentUrl.replace(/\/+$/, '');
const strippedHref = href.replace(/\/+$/, '');
const strippedCurrentUrl = currentUrl.replace(/\/+$/, '');
return strippedHref === strippedCurrentUrl;
}
@ -62,7 +62,7 @@ module.exports = function navigation(options) {
}
output = navigationData.map(function (e) {
var out = {};
const out = {};
out.current = _isCurrentUrl(e.url, currentUrl);
out.label = e.label;
out.slug = slugify(e.label);

View file

@ -6,11 +6,12 @@ const {SafeString} = require('../services/proxy');
// We use the name post_class to match the helper for consistency:
module.exports = function post_class() { // eslint-disable-line camelcase
var classes = ['post'],
tags = this.post && this.post.tags ? this.post.tags : this.tags || [],
featured = this.post && this.post.featured ? this.post.featured : this.featured || false,
image = this.post && this.post.feature_image ? this.post.feature_image : this.feature_image || false,
page = this.post && this.post.page ? this.post.page : this.page || false;
let classes = ['post'];
const tags = this.post && this.post.tags ? this.post.tags : this.tags || [];
const featured = this.post && this.post.featured ? this.post.featured : this.featured || false;
const image = this.post && this.post.feature_image ? this.post.feature_image : this.feature_image || false;
const page = this.post && this.post.page ? this.post.page : this.page || false;
if (tags) {
classes = classes.concat(tags.map(function (tag) {

View file

@ -11,21 +11,22 @@ const moment = require('moment');
const createFrame = hbs.handlebars.createFrame;
const buildApiOptions = function buildApiOptions(options, post) {
var publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'),
slug = post.slug,
op = options.name === 'prev_post' ? '<=' : '>',
order = options.name === 'prev_post' ? 'desc' : 'asc',
apiOptions = {
/**
* @deprecated: `author`, will be removed in Ghost 3.0
*/
include: 'author,authors,tags',
order: 'published_at ' + order,
limit: 1,
// This line deliberately uses double quotes because GQL cannot handle either double quotes
// or escaped singles, see TryGhost/GQL#34
filter: "slug:-" + slug + "+published_at:" + op + "'" + publishedAt + "'" // eslint-disable-line quotes
};
const publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss');
const slug = post.slug;
const op = options.name === 'prev_post' ? '<=' : '>';
const order = options.name === 'prev_post' ? 'desc' : 'asc';
const apiOptions = {
/**
* @deprecated: `author`, will be removed in Ghost 3.0
*/
include: 'author,authors,tags',
order: 'published_at ' + order,
limit: 1,
// This line deliberately uses double quotes because GQL cannot handle either double quotes
// or escaped singles, see TryGhost/GQL#34
filter: "slug:-" + slug + "+published_at:" + op + "'" + publishedAt + "'" // eslint-disable-line quotes
};
if (get(options, 'hash.in')) {
if (options.hash.in === 'primary_tag' && get(post, 'primary_tag.slug')) {
@ -51,7 +52,7 @@ const fetch = function fetch(options, data) {
return controller
.browse(apiOptions)
.then(function handleSuccess(result) {
var related = result.posts[0];
const related = result.posts[0];
if (related) {
return options.fn(related, {data: data});

View file

@ -13,8 +13,8 @@
const {themeI18n} = require('../services/proxy');
module.exports = function t(text, options) {
var bindings = {},
prop;
const bindings = {};
let prop;
for (prop in options.hash) {
if (Object.prototype.hasOwnProperty.call(options.hash, prop)) {
bindings[prop] = options.hash[prop];

View file

@ -13,15 +13,14 @@ module.exports = function tags(options) {
options = options || {};
options.hash = options.hash || {};
const autolink = !(_.isString(options.hash.autolink) && options.hash.autolink === 'false'),
separator = _.isString(options.hash.separator) ? options.hash.separator : ', ',
prefix = _.isString(options.hash.prefix) ? options.hash.prefix : '',
suffix = _.isString(options.hash.suffix) ? options.hash.suffix : '',
limit = options.hash.limit ? parseInt(options.hash.limit, 10) : undefined;
let output = '',
from = options.hash.from ? parseInt(options.hash.from, 10) : 1,
to = options.hash.to ? parseInt(options.hash.to, 10) : undefined;
const autolink = !(_.isString(options.hash.autolink) && options.hash.autolink === 'false');
const separator = _.isString(options.hash.separator) ? options.hash.separator : ', ';
const prefix = _.isString(options.hash.prefix) ? options.hash.prefix : '';
const suffix = _.isString(options.hash.suffix) ? options.hash.suffix : '';
const limit = options.hash.limit ? parseInt(options.hash.limit, 10) : undefined;
let output = '';
let from = options.hash.from ? parseInt(options.hash.from, 10) : 1;
let to = options.hash.to ? parseInt(options.hash.to, 10) : undefined;
function createTagList(tags) {
function processTag(tag) {

View file

@ -8,8 +8,8 @@ const {SafeString, metaData} = require('../services/proxy');
const {getMetaDataUrl} = metaData;
module.exports = function url(options) {
var absolute = options && options.hash.absolute && options.hash.absolute !== 'false',
outputUrl = getMetaDataUrl(this, absolute);
const absolute = options && options.hash.absolute && options.hash.absolute !== 'false';
let outputUrl = getMetaDataUrl(this, absolute);
outputUrl = encodeURI(decodeURI(outputUrl));

View file

@ -1,9 +1,9 @@
var urlUtils = require('../../server/lib/url-utils'),
getUrl = require('./url'),
_ = require('lodash');
const urlUtils = require('../../server/lib/url-utils');
const getUrl = require('./url');
const _ = require('lodash');
function getAmplUrl(data) {
var context = data.context ? data.context : null;
const context = data.context ? data.context : null;
if (_.includes(context, 'post') && !_.includes(context, 'amp')) {
return urlUtils.urlJoin(urlUtils.urlFor('home', true), getUrl(data, false), 'amp/');

View file

@ -1,7 +1,7 @@
const crypto = require('crypto'),
config = require('../../server/config'),
imageLib = require('../../server/lib/image'),
urlUtils = require('../../server/lib/url-utils');
const crypto = require('crypto');
const config = require('../../server/config');
const imageLib = require('../../server/lib/image');
const urlUtils = require('../../server/lib/url-utils');
/**
* Serve either uploaded favicon or default
@ -20,7 +20,7 @@ function getAssetUrl(path, hasMinFile) {
// CASE: Build the output URL
// Add subdirectory...
var output = urlUtils.urlJoin(urlUtils.getSubdir(), '/');
let output = urlUtils.urlJoin(urlUtils.getSubdir(), '/');
// Optionally add /assets/
if (!path.match(/^public/) && !path.match(/^asset/)) {

View file

@ -1,9 +1,9 @@
var getContextObject = require('./context_object.js'),
_ = require('lodash');
const getContextObject = require('./context_object.js');
const _ = require('lodash');
function getAuthorFacebookUrl(data) {
var context = data.context ? data.context : null,
contextObject = getContextObject(data, context);
const context = data.context ? data.context : null;
const contextObject = getContextObject(data, context);
if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.facebook) {
return contextObject.primary_author.facebook;

View file

@ -1,10 +1,10 @@
var urlUtils = require('../../server/lib/url-utils'),
getContextObject = require('./context_object.js'),
_ = require('lodash');
const urlUtils = require('../../server/lib/url-utils');
const getContextObject = require('./context_object.js');
const _ = require('lodash');
function getAuthorImage(data, absolute) {
var context = data.context ? data.context : null,
contextObject = getContextObject(data, context);
const context = data.context ? data.context : null;
const contextObject = getContextObject(data, context);
if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.profile_image) {
return urlUtils.urlFor('image', {image: contextObject.primary_author.profile_image}, absolute);

View file

@ -1,7 +1,7 @@
var urlService = require('../services/url');
const urlService = require('../services/url');
function getAuthorUrl(data, absolute) {
var context = data.context ? data.context[0] : null;
let context = data.context ? data.context[0] : null;
context = context === 'amp' ? 'post' : context;

View file

@ -1,9 +1,9 @@
var urlUtils = require('../../server/lib/url-utils'),
settingsCache = require('../../server/services/settings/cache'),
imageLib = require('../../server/lib/image');
const urlUtils = require('../../server/lib/url-utils');
const settingsCache = require('../../server/services/settings/cache');
const imageLib = require('../../server/lib/image');
function getBlogLogo() {
var logo = {};
const logo = {};
if (settingsCache.get('logo')) {
logo.url = urlUtils.urlFor('image', {image: settingsCache.get('logo')}, true);

View file

@ -1,5 +1,5 @@
var settingsCache = require('../../server/services/settings/cache'),
_ = require('lodash');
const settingsCache = require('../../server/services/settings/cache');
const _ = require('lodash');
function getContextObject(data, context) {
/**

View file

@ -1,10 +1,10 @@
var urlUtils = require('../../server/lib/url-utils'),
getContextObject = require('./context_object.js'),
_ = require('lodash');
const urlUtils = require('../../server/lib/url-utils');
const getContextObject = require('./context_object.js');
const _ = require('lodash');
function getCoverImage(data) {
var context = data.context ? data.context : null,
contextObject = getContextObject(data, context);
const context = data.context ? data.context : null;
const contextObject = getContextObject(data, context);
if (_.includes(context, 'home') || _.includes(context, 'author')) {
if (contextObject.cover_image) {

View file

@ -1,9 +1,9 @@
var getContextObject = require('./context_object.js'),
_ = require('lodash');
const getContextObject = require('./context_object.js');
const _ = require('lodash');
function getCreatorTwitterUrl(data) {
var context = data.context ? data.context : null,
contextObject = getContextObject(data, context);
const context = data.context ? data.context : null;
const contextObject = getContextObject(data, context);
if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.twitter) {
return contextObject.primary_author.twitter;

View file

@ -1,9 +1,9 @@
var downsize = require('downsize');
const downsize = require('downsize');
function getExcerpt(html, truncateOptions) {
truncateOptions = truncateOptions || {};
// Strip inline and bottom footnotes
var excerpt = html.replace(/<a href="#fn.*?rel="footnote">.*?<\/a>/gi, '');
let excerpt = html.replace(/<a href="#fn.*?rel="footnote">.*?<\/a>/gi, '');
excerpt = excerpt.replace(/<div class="footnotes"><ol>.*?<\/ol><\/div>/, '');
// Make sure to have space between paragraphs and new lines

View file

@ -1,6 +1,6 @@
var Promise = require('bluebird'),
_ = require('lodash'),
imageLib = require('../../server/lib/image');
const Promise = require('bluebird');
const _ = require('lodash');
const imageLib = require('../../server/lib/image');
/**
* Get Image dimensions
@ -10,7 +10,7 @@ var Promise = require('bluebird'),
* called to receive image width and height
*/
function getImageDimensions(metaData) {
var fetch = {
const fetch = {
coverImage: imageLib.imageSizeCache(metaData.coverImage.url),
authorImage: imageLib.imageSizeCache(metaData.authorImage.url),
ogImage: imageLib.imageSizeCache(metaData.ogImage.url),

View file

@ -1,80 +1,81 @@
var Promise = require('bluebird'),
settingsCache = require('../../server/services/settings/cache'),
urlUtils = require('../../server/lib/url-utils'),
common = require('../../server/lib/common'),
getUrl = require('./url'),
getImageDimensions = require('./image-dimensions'),
getCanonicalUrl = require('./canonical_url'),
getAmpUrl = require('./amp_url'),
getPaginatedUrl = require('./paginated_url'),
getAuthorUrl = require('./author_url'),
getBlogLogo = require('./blog_logo'),
getRssUrl = require('./rss_url'),
getTitle = require('./title'),
getDescription = require('./description'),
getCoverImage = require('./cover_image'),
getAuthorImage = require('./author_image'),
getAuthorFacebook = require('./author_fb_url'),
getCreatorTwitter = require('./creator_url'),
getKeywords = require('./keywords'),
getPublishedDate = require('./published_date'),
getModifiedDate = require('./modified_date'),
getOgType = require('./og_type'),
getOgImage = require('./og_image'),
getTwitterImage = require('./twitter_image'),
getStructuredData = require('./structured_data'),
getSchema = require('./schema'),
getExcerpt = require('./excerpt');
const Promise = require('bluebird');
const settingsCache = require('../../server/services/settings/cache');
const urlUtils = require('../../server/lib/url-utils');
const common = require('../../server/lib/common');
const getUrl = require('./url');
const getImageDimensions = require('./image-dimensions');
const getCanonicalUrl = require('./canonical_url');
const getAmpUrl = require('./amp_url');
const getPaginatedUrl = require('./paginated_url');
const getAuthorUrl = require('./author_url');
const getBlogLogo = require('./blog_logo');
const getRssUrl = require('./rss_url');
const getTitle = require('./title');
const getDescription = require('./description');
const getCoverImage = require('./cover_image');
const getAuthorImage = require('./author_image');
const getAuthorFacebook = require('./author_fb_url');
const getCreatorTwitter = require('./creator_url');
const getKeywords = require('./keywords');
const getPublishedDate = require('./published_date');
const getModifiedDate = require('./modified_date');
const getOgType = require('./og_type');
const getOgImage = require('./og_image');
const getTwitterImage = require('./twitter_image');
const getStructuredData = require('./structured_data');
const getSchema = require('./schema');
const getExcerpt = require('./excerpt');
function getMetaData(data, root) {
var metaData = {
url: getUrl(data, true),
canonicalUrl: getCanonicalUrl(data),
ampUrl: getAmpUrl(data),
previousUrl: getPaginatedUrl('prev', data, true),
nextUrl: getPaginatedUrl('next', data, true),
authorUrl: getAuthorUrl(data, true),
rssUrl: getRssUrl(data, true),
metaTitle: getTitle(data, root),
metaDescription: getDescription(data, root) || null,
coverImage: {
url: getCoverImage(data, true)
},
authorImage: {
url: getAuthorImage(data, true)
},
ogImage: {
url: getOgImage(data)
},
ogTitle: getTitle(data, root, {property: 'og'}),
ogDescription: getDescription(data, root, {property: 'og'}),
twitterImage: getTwitterImage(data, true),
twitterTitle: getTitle(data, root, {property: 'twitter'}),
twitterDescription: getDescription(data, root, {property: 'twitter'}),
authorFacebook: getAuthorFacebook(data),
creatorTwitter: getCreatorTwitter(data),
keywords: getKeywords(data),
publishedDate: getPublishedDate(data),
modifiedDate: getModifiedDate(data),
ogType: getOgType(data),
// @TODO: pass into each meta helper - wrap each helper
site: {
title: settingsCache.get('title'),
description: settingsCache.get('description'),
url: urlUtils.urlFor('home', true),
facebook: settingsCache.get('facebook'),
twitter: settingsCache.get('twitter'),
timezone: settingsCache.get('active_timezone'),
navigation: settingsCache.get('navigation'),
icon: settingsCache.get('icon'),
cover_image: settingsCache.get('cover_image'),
logo: getBlogLogo(),
amp: settingsCache.get('amp')
}
const metaData = {
url: getUrl(data, true),
canonicalUrl: getCanonicalUrl(data),
ampUrl: getAmpUrl(data),
previousUrl: getPaginatedUrl('prev', data, true),
nextUrl: getPaginatedUrl('next', data, true),
authorUrl: getAuthorUrl(data, true),
rssUrl: getRssUrl(data, true),
metaTitle: getTitle(data, root),
metaDescription: getDescription(data, root) || null,
coverImage: {
url: getCoverImage(data, true)
},
customExcerpt,
metaDescription,
fallbackExcerpt;
authorImage: {
url: getAuthorImage(data, true)
},
ogImage: {
url: getOgImage(data)
},
ogTitle: getTitle(data, root, {property: 'og'}),
ogDescription: getDescription(data, root, {property: 'og'}),
twitterImage: getTwitterImage(data, true),
twitterTitle: getTitle(data, root, {property: 'twitter'}),
twitterDescription: getDescription(data, root, {property: 'twitter'}),
authorFacebook: getAuthorFacebook(data),
creatorTwitter: getCreatorTwitter(data),
keywords: getKeywords(data),
publishedDate: getPublishedDate(data),
modifiedDate: getModifiedDate(data),
ogType: getOgType(data),
// @TODO: pass into each meta helper - wrap each helper
site: {
title: settingsCache.get('title'),
description: settingsCache.get('description'),
url: urlUtils.urlFor('home', true),
facebook: settingsCache.get('facebook'),
twitter: settingsCache.get('twitter'),
timezone: settingsCache.get('active_timezone'),
navigation: settingsCache.get('navigation'),
icon: settingsCache.get('icon'),
cover_image: settingsCache.get('cover_image'),
logo: getBlogLogo(),
amp: settingsCache.get('amp')
}
};
let customExcerpt;
let metaDescription;
let fallbackExcerpt;
// TODO: cleanup these if statements
// NOTE: should use 'post' OR 'page' once https://github.com/TryGhost/Ghost/issues/10042 is resolved

View file

@ -1,8 +1,8 @@
var _ = require('lodash');
const _ = require('lodash');
function getModifiedDate(data) {
var context = data.context ? data.context : null,
modDate;
let context = data.context ? data.context : null;
let modDate;
context = _.includes(context, 'amp') ? 'post' : context;

View file

@ -1,5 +1,5 @@
function getOgType(data) {
var context = data.context ? data.context[0] : null;
let context = data.context ? data.context[0] : null;
context = context === 'amp' ? 'post' : context;

View file

@ -1,20 +1,25 @@
var _ = require('lodash'),
urlUtils = require('../../server/lib/url-utils');
const _ = require('lodash');
const urlUtils = require('../../server/lib/url-utils');
function getPaginatedUrl(page, data, absolute) {
// If we don't have enough information, return null right away
if (!data || !data.relativeUrl || !data.pagination) {
return null;
}
// routeKeywords.page: 'page'
var pagePath = urlUtils.urlJoin('/page/'),
// Try to match the base url, as whatever precedes the pagePath
// routeKeywords.page: 'page'
baseUrlPattern = new RegExp('(.+)?(/page/\\d+/)'),
baseUrlMatch = data.relativeUrl.match(baseUrlPattern),
// If there is no match for pagePath, use the original url, without the trailing slash
baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1),
newRelativeUrl;
const pagePath = urlUtils.urlJoin('/page/');
// Try to match the base url, as whatever precedes the pagePath
// routeKeywords.page: 'page'
const baseUrlPattern = new RegExp('(.+)?(/page/\\d+/)');
const baseUrlMatch = data.relativeUrl.match(baseUrlPattern);
// If there is no match for pagePath, use the original url, without the trailing slash
const baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1);
let newRelativeUrl;
if (page === 'next' && data.pagination.next) {
newRelativeUrl = urlUtils.urlJoin(pagePath, data.pagination.next, '/');

View file

@ -1,5 +1,5 @@
function getPublishedDate(data) {
var context = data.context ? data.context[0] : null;
let context = data.context ? data.context[0] : null;
context = context === 'amp' ? 'post' : context;

View file

@ -1,10 +1,10 @@
var config = require('../../server/config'),
escapeExpression = require('../services/themes/engine').escapeExpression,
socialUrls = require('@tryghost/social-urls'),
_ = require('lodash');
const config = require('../../server/config');
const escapeExpression = require('../services/themes/engine').escapeExpression;
const socialUrls = require('@tryghost/social-urls');
const _ = require('lodash');
function schemaImageObject(metaDataVal) {
var imageObject;
let imageObject;
if (!metaDataVal) {
return null;
}
@ -23,7 +23,7 @@ function schemaImageObject(metaDataVal) {
}
function schemaPublisherObject(metaDataVal) {
var publisherObject;
let publisherObject;
publisherObject = {
'@type': 'Organization',
@ -37,7 +37,7 @@ function schemaPublisherObject(metaDataVal) {
// Creates the final schema object with values that are not null
function trimSchema(schema) {
var schemaObject = {};
const schemaObject = {};
_.each(schema, function (value, key) {
if (value !== null && typeof value !== 'undefined') {
@ -49,7 +49,7 @@ function trimSchema(schema) {
}
function trimSameAs(data, context) {
var sameAs = [];
const sameAs = [];
if (context === 'post' || context === 'page') {
if (data[context].primary_author.website) {
@ -79,8 +79,9 @@ function trimSameAs(data, context) {
function getPostSchema(metaData, data) {
// CASE: metaData.excerpt for post context is populated by either the custom excerpt, the meta description,
// or the automated excerpt of 50 words. It is empty for any other context.
var description = metaData.excerpt ? escapeExpression(metaData.excerpt) : null,
schema;
const description = metaData.excerpt ? escapeExpression(metaData.excerpt) : null;
let schema;
const context = data.page ? 'page' : 'post';
@ -116,7 +117,7 @@ function getPostSchema(metaData, data) {
}
function getHomeSchema(metaData) {
var schema = {
const schema = {
'@context': 'https://schema.org',
'@type': 'WebSite',
publisher: schemaPublisherObject(metaData),
@ -134,7 +135,7 @@ function getHomeSchema(metaData) {
}
function getTagSchema(metaData, data) {
var schema = {
const schema = {
'@context': 'https://schema.org',
'@type': 'Series',
publisher: schemaPublisherObject(metaData),
@ -154,7 +155,7 @@ function getTagSchema(metaData, data) {
}
function getAuthorSchema(metaData, data) {
var schema = {
const schema = {
'@context': 'https://schema.org',
'@type': 'Person',
sameAs: trimSameAs(data, 'author'),
@ -175,7 +176,7 @@ function getAuthorSchema(metaData, data) {
function getSchema(metaData, data) {
if (!config.isPrivacyDisabled('useStructuredData')) {
var context = data.context ? data.context : null;
const context = data.context ? data.context : null;
if (_.includes(context, 'post') || _.includes(context, 'page') || _.includes(context, 'amp')) {
return getPostSchema(metaData, data);
} else if (_.includes(context, 'home')) {

View file

@ -1,8 +1,8 @@
var socialUrls = require('@tryghost/social-urls');
const socialUrls = require('@tryghost/social-urls');
function getStructuredData(metaData) {
var structuredData,
card = 'summary';
let structuredData;
let card = 'summary';
if (metaData.twitterImage || metaData.coverImage.url) {
card = 'summary_large_image';
@ -46,7 +46,7 @@ function getStructuredData(metaData) {
// return structured data removing null or undefined keys
return Object.keys(structuredData).reduce(function (data, key) {
var content = structuredData[key];
const content = structuredData[key];
if (content !== null && typeof content !== 'undefined') {
data[key] = content;
}

View file

@ -1,6 +1,6 @@
var schema = require('../../server/data/schema').checks,
urlUtils = require('../../server/lib/url-utils'),
urlService = require('../services/url');
const schema = require('../../server/data/schema').checks;
const urlUtils = require('../../server/lib/url-utils');
const urlService = require('../services/url');
// This cleans the url from any `/amp` postfixes, so we'll never
// output a url with `/amp` in the end, except for the needed `amphtml`

View file

@ -1,9 +1,10 @@
// This file defines everything that helpers "require"
// With the exception of modules like lodash, Bluebird
// We can later refactor to enforce this something like we did in apps
var hbs = require('./themes/engine'),
settingsCache = require('../../server/services/settings/cache'),
config = require('../../server/config');
const hbs = require('./themes/engine');
const settingsCache = require('../../server/services/settings/cache');
const config = require('../../server/config');
// Direct requires:
// - lodash

View file

@ -147,8 +147,8 @@ class CollectionRouter extends ParentRouter {
* @private
*/
_onTimezoneEdited(settingModel) {
const newTimezone = settingModel.attributes.value,
previousTimezone = settingModel._previousAttributes.value;
const newTimezone = settingModel.attributes.value;
const previousTimezone = settingModel._previousAttributes.value;
if (newTimezone === previousTimezone) {
return;

View file

@ -7,14 +7,15 @@
* Only allows for .use and .get at the moment - we don't have clear use-cases for anything else yet.
*/
const debug = require('ghost-ignition').debug('services:routing:ParentRouter'),
EventEmitter = require('events').EventEmitter,
express = require('express'),
_ = require('lodash'),
url = require('url'),
security = require('../../../server/lib/security'),
urlUtils = require('../../../server/lib/url-utils'),
registry = require('./registry');
const debug = require('ghost-ignition').debug('services:routing:ParentRouter');
const EventEmitter = require('events').EventEmitter;
const express = require('express');
const _ = require('lodash');
const url = require('url');
const security = require('../../../server/lib/security');
const urlUtils = require('../../../server/lib/url-utils');
const registry = require('./registry');
/**
* @description Inherited express router, which gives control to us.

View file

@ -1,9 +1,9 @@
const _ = require('lodash'),
debug = require('ghost-ignition').debug('services:routing:controllers:channel'),
common = require('../../../../server/lib/common'),
security = require('../../../../server/lib/security'),
themes = require('../../themes'),
helpers = require('../helpers');
const _ = require('lodash');
const debug = require('ghost-ignition').debug('services:routing:controllers:channel');
const common = require('../../../../server/lib/common');
const security = require('../../../../server/lib/security');
const themes = require('../../themes');
const helpers = require('../helpers');
/**
* @description Channel controller.

View file

@ -1,10 +1,10 @@
const _ = require('lodash'),
debug = require('ghost-ignition').debug('services:routing:controllers:collection'),
common = require('../../../../server/lib/common'),
security = require('../../../../server/lib/security'),
urlService = require('../../url'),
themes = require('../../themes'),
helpers = require('../helpers');
const _ = require('lodash');
const debug = require('ghost-ignition').debug('services:routing:controllers:collection');
const common = require('../../../../server/lib/common');
const security = require('../../../../server/lib/security');
const urlService = require('../../url');
const themes = require('../../themes');
const helpers = require('../helpers');
/**
* @description Collection controller.

View file

@ -1,15 +1,15 @@
const _ = require('lodash'),
debug = require('ghost-ignition').debug('services:routing:controllers:rss'),
url = require('url'),
security = require('../../../../server/lib/security'),
settingsCache = require('../../../../server/services/settings/cache'),
rssService = require('../../rss'),
helpers = require('../helpers');
const _ = require('lodash');
const debug = require('ghost-ignition').debug('services:routing:controllers:rss');
const url = require('url');
const security = require('../../../../server/lib/security');
const settingsCache = require('../../../../server/services/settings/cache');
const rssService = require('../../rss');
const helpers = require('../helpers');
// @TODO: is this really correct? Should we be using meta data title?
function getTitle(relatedData) {
relatedData = relatedData || {};
var titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || '';
let titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || '';
titleStart += titleStart ? ' - ' : '';
return titleStart + settingsCache.get('title');

View file

@ -1,7 +1,7 @@
const _ = require('lodash'),
Promise = require('bluebird'),
debug = require('ghost-ignition').debug('services:routing:controllers:static'),
helpers = require('../helpers');
const _ = require('lodash');
const Promise = require('bluebird');
const debug = require('ghost-ignition').debug('services:routing:controllers:static');
const helpers = require('../helpers');
function processQuery(query, locals) {
const api = require('../../../../server/api')[locals.apiVersion];

View file

@ -10,15 +10,17 @@
* 2. req.params.page - always has the page parameter, regardless of if the URL contains a keyword
* 3. data - used for telling the difference between posts and pages
*/
const // @TODO: fix this!! These regexes are app specific and should be dynamic. They should not belong here....
// routeKeywords.private: 'private'
privatePattern = new RegExp('^\\/private\\/'),
// routeKeywords.amp: 'amp'
ampPattern = new RegExp('\\/amp\\/$'),
homePattern = new RegExp('^\\/$');
// @TODO: fix this!! These regexes are app specific and should be dynamic. They should not belong here....
// routeKeywords.private: 'private'
const privatePattern = new RegExp('^\\/private\\/');
// routeKeywords.amp: 'amp'
const ampPattern = new RegExp('\\/amp\\/$');
const homePattern = new RegExp('^\\/$');
function setResponseContext(req, res, data) {
var pageParam = req.params && req.params.page !== undefined ? parseInt(req.params.page, 10) : 1;
const pageParam = req.params && req.params.page !== undefined ? parseInt(req.params.page, 10) : 1;
res.locals = res.locals || {};
res.locals.context = [];

View file

@ -72,8 +72,8 @@ function fetchData(pathOptions, routerOptions, locals) {
pathOptions = pathOptions || {};
routerOptions = routerOptions || {};
let postQuery = _.cloneDeep(defaultPostQuery),
props = {};
let postQuery = _.cloneDeep(defaultPostQuery);
let props = {};
if (routerOptions.filter) {
postQuery.options.filter = routerOptions.filter;

View file

@ -6,7 +6,7 @@ const _ = require('lodash');
* @return {Object} containing page variables
*/
function formatPageResponse(result) {
var response = {};
const response = {};
if (result.posts) {
response.posts = result.posts;

View file

@ -1,6 +1,6 @@
const debug = require('ghost-ignition').debug('services:routing:helpers:render-entries'),
formatResponse = require('./format-response'),
renderer = require('./renderer');
const debug = require('ghost-ignition').debug('services:routing:helpers:render-entries');
const formatResponse = require('./format-response');
const renderer = require('./renderer');
/**
* @description Helper to handle rendering multiple resources.

View file

@ -1,6 +1,6 @@
const debug = require('ghost-ignition').debug('services:routing:helpers:render-post'),
formatResponse = require('./format-response'),
renderer = require('./renderer');
const debug = require('ghost-ignition').debug('services:routing:helpers:render-post');
const formatResponse = require('./format-response');
const renderer = require('./renderer');
/**
* @description Helper to handle rendering multiple resources.
*

View file

@ -1,6 +1,6 @@
const debug = require('ghost-ignition').debug('services:routing:helpers:renderer'),
setContext = require('./context'),
templates = require('./templates');
const debug = require('ghost-ignition').debug('services:routing:helpers:renderer');
const setContext = require('./context');
const templates = require('./templates');
/**
* @description Helper function to finally render the data.

View file

@ -2,12 +2,13 @@
//
// Figure out which template should be used to render a request
// based on the templates which are allowed, and what is available in the theme
const _ = require('lodash'),
path = require('path'),
url = require('url'),
config = require('../../../../server/config'),
themes = require('../../themes'),
_private = {};
const _ = require('lodash');
const path = require('path');
const url = require('url');
const config = require('../../../../server/config');
const themes = require('../../themes');
const _private = {};
/**
* @description Get Error Template Hierarchy
@ -20,8 +21,8 @@ const _ = require('lodash'),
* @returns {String[]}
*/
_private.getErrorTemplateHierarchy = function getErrorTemplateHierarchy(statusCode) {
const errorCode = _.toString(statusCode),
templateList = ['error'];
const errorCode = _.toString(statusCode);
const templateList = ['error'];
// Add error class template: E.g. error-4xx.hbs or error-5xx.hbs
templateList.unshift('error-' + errorCode[0] + 'xx');
@ -141,20 +142,20 @@ _private.pickTemplate = function pickTemplate(templateList, fallback) {
};
_private.getTemplateForEntry = function getTemplateForEntry(postObject) {
const templateList = _private.getEntryTemplateHierarchy(postObject),
fallback = templateList[templateList.length - 1];
const templateList = _private.getEntryTemplateHierarchy(postObject);
const fallback = templateList[templateList.length - 1];
return _private.pickTemplate(templateList, fallback);
};
_private.getTemplateForEntries = function getTemplateForEntries(routerOptions, requestOptions) {
const templateList = _private.getEntriesTemplateHierarchy(routerOptions, requestOptions),
fallback = templateList[templateList.length - 1];
const templateList = _private.getEntriesTemplateHierarchy(routerOptions, requestOptions);
const fallback = templateList[templateList.length - 1];
return _private.pickTemplate(templateList, fallback);
};
_private.getTemplateForError = function getTemplateForError(statusCode) {
const templateList = _private.getErrorTemplateHierarchy(statusCode),
fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs');
const templateList = _private.getErrorTemplateHierarchy(statusCode);
const fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs');
return _private.pickTemplate(templateList, fallback);
};

View file

@ -1,5 +1,5 @@
const common = require('../../../../server/lib/common'),
urlUtils = require('../../../../server/lib/url-utils');
const common = require('../../../../server/lib/common');
const urlUtils = require('../../../../server/lib/url-utils');
/**
* @description Middleware, which validates and interprets the page param e.g. /page/1

View file

@ -1,9 +1,9 @@
var crypto = require('crypto'),
generateFeed = require('./generate-feed'),
feedCache = {};
const crypto = require('crypto');
const generateFeed = require('./generate-feed');
const feedCache = {};
module.exports.getXML = function getFeedXml(baseUrl, data) {
var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
const dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
if (!feedCache[baseUrl] || feedCache[baseUrl].hash !== dataHash) {
// We need to regenerate
feedCache[baseUrl] = {

View file

@ -1,12 +1,12 @@
var downsize = require('downsize'),
Promise = require('bluebird'),
cheerio = require('cheerio'),
RSS = require('rss'),
urlUtils = require('../../../server/lib/url-utils'),
urlService = require('../url'),
generateFeed,
generateItem,
generateTags;
const downsize = require('downsize');
const Promise = require('bluebird');
const cheerio = require('cheerio');
const RSS = require('rss');
const urlUtils = require('../../../server/lib/url-utils');
const urlService = require('../url');
let generateFeed;
let generateItem;
let generateTags;
generateTags = function generateTags(data) {
if (data.tags) {

View file

@ -1,9 +1,9 @@
var _ = require('lodash'),
rssCache = require('./cache');
const _ = require('lodash');
const rssCache = require('./cache');
module.exports.render = function render(res, baseUrl, data) {
// Format data - this is the same as what Express does
var rssData = _.merge({}, res.locals, data);
const rssData = _.merge({}, res.locals, data);
// Fetch RSS from the cache
return rssCache

View file

@ -1,9 +1,9 @@
const fs = require('fs-extra'),
Promise = require('bluebird'),
path = require('path'),
debug = require('ghost-ignition').debug('frontend:services:settings:ensure-settings'),
common = require('../../../server/lib/common'),
config = require('../../../server/config');
const fs = require('fs-extra');
const Promise = require('bluebird');
const path = require('path');
const debug = require('ghost-ignition').debug('frontend:services:settings:ensure-settings');
const common = require('../../../server/lib/common');
const config = require('../../../server/config');
/**
* Makes sure that all supported settings files are in the
@ -16,13 +16,13 @@ const fs = require('fs-extra'),
* copy the default yaml file over.
*/
module.exports = function ensureSettingsFiles(knownSettings) {
const contentPath = config.getContentPath('settings'),
defaultSettingsPath = config.get('paths').defaultSettings;
const contentPath = config.getContentPath('settings');
const defaultSettingsPath = config.get('paths').defaultSettings;
return Promise.each(knownSettings, function (setting) {
const fileName = `${setting}.yaml`,
defaultFileName = `default-${fileName}`,
filePath = path.join(contentPath, fileName);
const fileName = `${setting}.yaml`;
const defaultFileName = `default-${fileName}`;
const filePath = path.join(contentPath, fileName);
return fs.readFile(filePath, 'utf8')
.catch({code: 'ENOENT'}, () => {

View file

@ -68,8 +68,8 @@ module.exports = {
* `/content/settings` directory.
*/
getAll: function getAll() {
const knownSettings = this.knownSettings(),
settingsToReturn = {};
const knownSettings = this.knownSettings();
const settingsToReturn = {};
_.each(knownSettings, function (setting) {
settingsToReturn[setting] = SettingsLoader(setting);

View file

@ -1,10 +1,10 @@
const fs = require('fs-extra'),
path = require('path'),
debug = require('ghost-ignition').debug('frontend:services:settings:settings-loader'),
common = require('../../../server/lib/common'),
config = require('../../../server/config'),
yamlParser = require('./yaml-parser'),
validate = require('./validate');
const fs = require('fs-extra');
const path = require('path');
const debug = require('ghost-ignition').debug('frontend:services:settings:settings-loader');
const common = require('../../../server/lib/common');
const config = require('../../../server/config');
const yamlParser = require('./yaml-parser');
const validate = require('./validate');
/**
* Reads the desired settings YAML file and passes the

View file

@ -1,6 +1,6 @@
const yaml = require('js-yaml'),
debug = require('ghost-ignition').debug('frontend:services:settings:yaml-parser'),
common = require('../../../server/lib/common');
const yaml = require('js-yaml');
const debug = require('ghost-ignition').debug('frontend:services:settings:yaml-parser');
const common = require('../../../server/lib/common');
/**
* Takes a YAML file, parses it and returns a JSON Object

View file

@ -1,9 +1,9 @@
const _ = require('lodash'),
xml = require('xml'),
moment = require('moment'),
path = require('path'),
urlUtils = require('../../../server/lib/url-utils'),
localUtils = require('./utils');
const _ = require('lodash');
const xml = require('xml');
const moment = require('moment');
const path = require('path');
const urlUtils = require('../../../server/lib/url-utils');
const localUtils = require('./utils');
// Sitemap specific xml namespace declarations that should not change
const XMLNS_DECLS = {
@ -22,24 +22,28 @@ class BaseSiteMapGenerator {
}
generateXmlFromNodes() {
var self = this,
// Get a mapping of node to timestamp
timedNodes = _.map(this.nodeLookup, function (node, id) {
return {
id: id,
// Using negative here to sort newest to oldest
ts: -(self.nodeTimeLookup[id] || 0),
node: node
};
}, []),
// Sort nodes by timestamp
sortedNodes = _.sortBy(timedNodes, 'ts'),
// Grab just the nodes
urlElements = _.map(sortedNodes, 'node'),
data = {
// Concat the elements to the _attr declaration
urlset: [XMLNS_DECLS].concat(urlElements)
const self = this;
// Get a mapping of node to timestamp
const timedNodes = _.map(this.nodeLookup, function (node, id) {
return {
id: id,
// Using negative here to sort newest to oldest
ts: -(self.nodeTimeLookup[id] || 0),
node: node
};
}, []);
// Sort nodes by timestamp
const sortedNodes = _.sortBy(timedNodes, 'ts');
// Grab just the nodes
const urlElements = _.map(sortedNodes, 'node');
const data = {
// Concat the elements to the _attr declaration
urlset: [XMLNS_DECLS].concat(urlElements)
};
// Return the xml
return localUtils.getDeclarations() + xml(data);
@ -83,7 +87,8 @@ class BaseSiteMapGenerator {
}
createUrlNodeFromDatum(url, datum) {
let node, imgNode;
let node;
let imgNode;
node = {
url: [
@ -103,9 +108,10 @@ class BaseSiteMapGenerator {
createImageNodeFromDatum(datum) {
// Check for cover first because user has cover but the rest only have image
var image = datum.cover_image || datum.profile_image || datum.feature_image,
imageUrl,
imageEl;
const image = datum.cover_image || datum.profile_image || datum.feature_image;
let imageUrl;
let imageEl;
if (!image) {
return;

View file

@ -1,6 +1,6 @@
const config = require('../../../server/config'),
Manager = require('./manager'),
manager = new Manager();
const config = require('../../../server/config');
const Manager = require('./manager');
const manager = new Manager();
// Responsible for handling requests for sitemap files
module.exports = function handler(siteApp) {
@ -22,8 +22,8 @@ module.exports = function handler(siteApp) {
});
siteApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) {
var type = req.params.resource,
page = 1;
const type = req.params.resource;
const page = 1;
res.set({
'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'),

View file

@ -1,8 +1,8 @@
const _ = require('lodash'),
xml = require('xml'),
moment = require('moment'),
urlUtils = require('../../../server/lib/url-utils'),
localUtils = require('./utils');
const _ = require('lodash');
const xml = require('xml');
const moment = require('moment');
const urlUtils = require('../../../server/lib/url-utils');
const localUtils = require('./utils');
const XMLNS_DECLS = {
_attr: {
@ -17,11 +17,12 @@ class SiteMapIndexGenerator {
}
getXml() {
const urlElements = this.generateSiteMapUrlElements(),
data = {
// Concat the elements to the _attr declaration
sitemapindex: [XMLNS_DECLS].concat(urlElements)
};
const urlElements = this.generateSiteMapUrlElements();
const data = {
// Concat the elements to the _attr declaration
sitemapindex: [XMLNS_DECLS].concat(urlElements)
};
// Return the xml
return localUtils.getDeclarations() + xml(data);
@ -29,8 +30,8 @@ class SiteMapIndexGenerator {
generateSiteMapUrlElements() {
return _.map(this.types, (resourceType) => {
var url = urlUtils.urlFor({relativeUrl: '/sitemap-' + resourceType.name + '.xml'}, true),
lastModified = resourceType.lastModified;
const url = urlUtils.urlFor({relativeUrl: '/sitemap-' + resourceType.name + '.xml'}, true);
const lastModified = resourceType.lastModified;
return {
sitemap: [

View file

@ -1,9 +1,9 @@
const common = require('../../../server/lib/common'),
IndexMapGenerator = require('./index-generator'),
PagesMapGenerator = require('./page-generator'),
PostsMapGenerator = require('./post-generator'),
UsersMapGenerator = require('./user-generator'),
TagsMapGenerator = require('./tag-generator');
const common = require('../../../server/lib/common');
const IndexMapGenerator = require('./index-generator');
const PagesMapGenerator = require('./page-generator');
const PostsMapGenerator = require('./post-generator');
const UsersMapGenerator = require('./user-generator');
const TagsMapGenerator = require('./tag-generator');
class SiteMapManager {
constructor(options) {

View file

@ -1,5 +1,5 @@
const _ = require('lodash'),
BaseMapGenerator = require('./base-generator');
const _ = require('lodash');
const BaseMapGenerator = require('./base-generator');
class PageMapGenerator extends BaseMapGenerator {
constructor(opts) {

View file

@ -1,5 +1,5 @@
const _ = require('lodash'),
BaseMapGenerator = require('./base-generator');
const _ = require('lodash');
const BaseMapGenerator = require('./base-generator');
class PostMapGenerator extends BaseMapGenerator {
constructor(opts) {

View file

@ -1,5 +1,5 @@
const _ = require('lodash'),
BaseMapGenerator = require('./base-generator');
const _ = require('lodash');
const BaseMapGenerator = require('./base-generator');
class TagsMapGenerator extends BaseMapGenerator {
constructor(opts) {

View file

@ -1,6 +1,6 @@
const _ = require('lodash'),
validator = require('validator'),
BaseMapGenerator = require('./base-generator');
const _ = require('lodash');
const validator = require('validator');
const BaseMapGenerator = require('./base-generator');
class UserMapGenerator extends BaseMapGenerator {
constructor(opts) {

View file

@ -1,9 +1,9 @@
var urlUtils = require('../../../server/lib/url-utils'),
sitemapsUtils;
const urlUtils = require('../../../server/lib/url-utils');
let sitemapsUtils;
sitemapsUtils = {
getDeclarations: function () {
var baseUrl = urlUtils.urlFor('sitemap_xsl', true);
let baseUrl = urlUtils.urlFor('sitemap_xsl', true);
baseUrl = baseUrl.replace(/^(http:|https:)/, '');
return '<?xml version="1.0" encoding="UTF-8"?>' +
'<?xml-stylesheet type="text/xsl" href="' + baseUrl + '"?>';

View file

@ -1,10 +1,10 @@
var fs = require('fs-extra'),
os = require('os'),
path = require('path'),
config = require('../../../server/config'),
security = require('../../../server/lib/security'),
{compress} = require('@tryghost/zip'),
LocalFileStorage = require('../../../server/adapters/storage/LocalFileStorage');
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const config = require('../../../server/config');
const security = require('../../../server/lib/security');
const {compress} = require('@tryghost/zip');
const LocalFileStorage = require('../../../server/adapters/storage/LocalFileStorage');
/**
* @TODO: combine with loader.js?
@ -21,16 +21,18 @@ class ThemeStorage extends LocalFileStorage {
}
serve(options) {
var self = this;
const self = this;
return function downloadTheme(req, res, next) {
var themeName = options.name,
themePath = path.join(self.storagePath, themeName),
zipName = themeName + '.zip',
// store this in a unique temporary folder
zipBasePath = path.join(os.tmpdir(), security.identifier.uid(10)),
zipPath = path.join(zipBasePath, zipName),
stream;
const themeName = options.name;
const themePath = path.join(self.storagePath, themeName);
const zipName = themeName + '.zip';
// store this in a unique temporary folder
const zipBasePath = path.join(os.tmpdir(), security.identifier.uid(10));
const zipPath = path.join(zipBasePath, zipName);
let stream;
fs.ensureDir(zipBasePath)
.then(function () {

View file

@ -11,14 +11,16 @@
* No properties marked with an _ should be used directly.
*
*/
var join = require('path').join,
_ = require('lodash'),
themeConfig = require('./config'),
themeEngines = require('./engines'),
config = require('../../../server/config'),
engine = require('./engine'),
// Current instance of ActiveTheme
currentActiveTheme;
const join = require('path').join;
const _ = require('lodash');
const themeConfig = require('./config');
const themeEngines = require('./engines');
const config = require('../../../server/config');
const engine = require('./engine');
// Current instance of ActiveTheme
let currentActiveTheme;
class ActiveTheme {
/**

View file

@ -1,9 +1,9 @@
var _ = require('lodash'),
defaultConfig = require('./defaults'),
allowedKeys = ['posts_per_page', 'image_sizes'];
const _ = require('lodash');
const defaultConfig = require('./defaults');
const allowedKeys = ['posts_per_page', 'image_sizes'];
module.exports.create = function configLoader(packageJson) {
var config = _.cloneDeep(defaultConfig);
let config = _.cloneDeep(defaultConfig);
if (packageJson && Object.prototype.hasOwnProperty.call(packageJson, 'config')) {
config = _.assign(config, _.pick(packageJson.config, allowedKeys));

View file

@ -1,6 +1,6 @@
var hbs = require('express-hbs'),
config = require('../../../server/config'),
instance = hbs.create();
const hbs = require('express-hbs');
const config = require('../../../server/config');
const instance = hbs.create();
// @TODO think about a config option for this e.g. theme.devmode?
if (config.get('env') !== 'production') {
@ -10,7 +10,7 @@ if (config.get('env') !== 'production') {
instance.escapeExpression = instance.handlebars.Utils.escapeExpression;
instance.configure = function configure(partialsPath) {
var hbsOptions = {
const hbsOptions = {
partialsDir: [config.get('paths').helperTemplates],
onCompile: function onCompile(exhbs, source) {
return exhbs.handlebars.compile(source, {preventIndent: true});

View file

@ -16,14 +16,15 @@ function asyncHelperWrapper(hbs, name, fn) {
Promise.resolve(fn.call(this, context, options)).then(function asyncHelperSuccess(result) {
cb(result);
}).catch(function asyncHelperError(err) {
var wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({
err: err,
context: 'registerAsyncThemeHelper: ' + name,
errorDetails: {
originalError: err
}
}),
result = config.get('env') === 'development' ? wrappedErr : '';
const wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({
err: err,
context: 'registerAsyncThemeHelper: ' + name,
errorDetails: {
originalError: err
}
});
const result = config.get('env') === 'development' ? wrappedErr : '';
logging.error(wrappedErr);

View file

@ -8,7 +8,7 @@ const {i18n} = require('../../../../server/lib/common');
// Execute a template helper
// All template helpers are register as partial view.
templates.execute = function execute(name, context, data) {
var partial = hbs.handlebars.partials[name];
const partial = hbs.handlebars.partials[name];
if (partial === undefined) {
throw new errors.IncorrectUsageError({

View file

@ -14,7 +14,7 @@ module.exports = {
// Init themes module
// TODO: move this once we're clear what needs to happen here
init: function initThemes() {
var activeThemeName = settingsCache.get('active_theme');
const activeThemeName = settingsCache.get('active_theme');
i18n.init();

View file

@ -1,8 +1,9 @@
/**
* Store themes after loading them from the file system
*/
var _ = require('lodash'),
themeListCache = {};
const _ = require('lodash');
let themeListCache = {};
module.exports = {
get: function get(key) {
@ -23,7 +24,7 @@ module.exports = {
},
init: function init(themes) {
var self = this;
const self = this;
// First, reset the cache
themeListCache = {};
// For each theme, call set. Allows us to do processing on set later.

View file

@ -1,9 +1,9 @@
var debug = require('ghost-ignition').debug('themes:loader'),
config = require('../../../server/config'),
packageJSON = require('../../../server/lib/fs/package-json'),
themeList = require('./list'),
loadAllThemes,
loadOneTheme;
const debug = require('ghost-ignition').debug('themes:loader');
const config = require('../../../server/config');
const packageJSON = require('../../../server/lib/fs/package-json');
const themeList = require('./list');
let loadAllThemes;
let loadOneTheme;
loadAllThemes = function loadAllThemes() {
return packageJSON.read

View file

@ -1,8 +1,8 @@
var _ = require('lodash'),
themeList = require('./list'),
active = require('./active'),
packageJSON = require('../../../server/lib/fs/package-json'),
settingsCache = require('../../../server/services/settings/cache');
const _ = require('lodash');
const themeList = require('./list');
const active = require('./active');
const packageJSON = require('../../../server/lib/fs/package-json');
const settingsCache = require('../../../server/services/settings/cache');
/**
*
@ -17,7 +17,8 @@ var _ = require('lodash'),
* @return {*}
*/
module.exports = function toJSON(name, checkedTheme) {
var themeResult, toFilter;
let themeResult;
let toFilter;
if (!name) {
toFilter = themeList.getAll();

View file

@ -1,7 +1,7 @@
const debug = require('ghost-ignition').debug('services:url:queue'),
EventEmitter = require('events').EventEmitter,
_ = require('lodash'),
common = require('../../../server/lib/common');
const debug = require('ghost-ignition').debug('services:url:queue');
const EventEmitter = require('events').EventEmitter;
const _ = require('lodash');
const common = require('../../../server/lib/common');
/**
* ### Purpose of this queue
@ -102,9 +102,9 @@ class Queue extends EventEmitter {
* @param {Object} options
*/
run(options) {
const event = options.event,
action = options.action,
eventData = options.eventData;
const event = options.event;
const action = options.action;
const eventData = options.eventData;
clearTimeout(this.toNotify[action].timeout);
this.toNotify[action].timeout = null;

View file

@ -1,5 +1,5 @@
const EventEmitter = require('events').EventEmitter,
common = require('../../../server/lib/common');
const EventEmitter = require('events').EventEmitter;
const common = require('../../../server/lib/common');
/**
* Resource cache.

View file

@ -1,27 +1,28 @@
const _ = require('lodash'),
nql = require('@nexes/nql'),
debug = require('ghost-ignition').debug('services:url:generator'),
localUtils = require('../../../server/lib/url-utils'),
// @TODO: merge with filter plugin
EXPANSIONS = [{
key: 'author',
replacement: 'authors.slug'
}, {
key: 'tags',
replacement: 'tags.slug'
}, {
key: 'tag',
replacement: 'tags.slug'
}, {
key: 'authors',
replacement: 'authors.slug'
}, {
key: 'primary_tag',
replacement: 'primary_tag.slug'
}, {
key: 'primary_author',
replacement: 'primary_author.slug'
}];
const _ = require('lodash');
const nql = require('@nexes/nql');
const debug = require('ghost-ignition').debug('services:url:generator');
const localUtils = require('../../../server/lib/url-utils');
// @TODO: merge with filter plugin
const EXPANSIONS = [{
key: 'author',
replacement: 'authors.slug'
}, {
key: 'tags',
replacement: 'tags.slug'
}, {
key: 'tag',
replacement: 'tags.slug'
}, {
key: 'authors',
replacement: 'authors.slug'
}, {
key: 'primary_tag',
replacement: 'primary_tag.slug'
}, {
key: 'primary_author',
replacement: 'primary_author.slug'
}];
const mapNQLKeyValues = require('../../../shared/nql-map-key-values');

View file

@ -1,12 +1,12 @@
const _debug = require('ghost-ignition').debug._base,
debug = _debug('ghost:services:url:service'),
_ = require('lodash'),
common = require('../../../server/lib/common'),
UrlGenerator = require('./UrlGenerator'),
Queue = require('./Queue'),
Urls = require('./Urls'),
Resources = require('./Resources'),
urlUtils = require('../../../server/lib/url-utils');
const _debug = require('ghost-ignition').debug._base;
const debug = _debug('ghost:services:url:service');
const _ = require('lodash');
const common = require('../../../server/lib/common');
const UrlGenerator = require('./UrlGenerator');
const Queue = require('./Queue');
const Urls = require('./Urls');
const Resources = require('./Resources');
const urlUtils = require('../../../server/lib/url-utils');
/**
* The url service class holds all instances in a centralised place.

View file

@ -1,5 +1,5 @@
const UrlService = require('./UrlService'),
urlService = new UrlService();
const UrlService = require('./UrlService');
const urlService = new UrlService();
// Singleton
module.exports = urlService;

View file

@ -99,8 +99,8 @@ SchedulingDefault.prototype.unschedule = function (object, options = {bootstrap:
*/
SchedulingDefault.prototype.run = function () {
const self = this;
let timeout = null,
recursiveRun;
let timeout = null;
let recursiveRun;
// NOTE: Ensure the scheduler never runs twice.
if (this.isRunning) {
@ -111,8 +111,8 @@ SchedulingDefault.prototype.run = function () {
recursiveRun = function recursiveRun() {
timeout = setTimeout(function () {
const times = Object.keys(self.allJobs),
nextJobs = {};
const times = Object.keys(self.allJobs);
const nextJobs = {};
// CASE: We stop till the offset is too big. We are only interested in jobs which need get executed soon.
times.every(function (time) {
@ -142,11 +142,11 @@ SchedulingDefault.prototype.run = function () {
* @private
*/
SchedulingDefault.prototype._addJob = function (object) {
let timestamp = moment(object.time).valueOf(),
keys = [],
sortedJobs = {},
instantJob = {},
i = 0;
let timestamp = moment(object.time).valueOf();
let keys = [];
let sortedJobs = {};
let instantJob = {};
let i = 0;
// CASE: should have been already pinged or should be pinged soon
if (moment(timestamp).diff(moment(), 'minutes') < this.offsetInMinutes) {
@ -218,12 +218,12 @@ SchedulingDefault.prototype._deleteJob = function (object) {
* We can't use "process.nextTick" otherwise we will block I/O operations.
*/
SchedulingDefault.prototype._execute = function (jobs) {
const keys = Object.keys(jobs),
self = this;
const keys = Object.keys(jobs);
const self = this;
keys.forEach(function (timestamp) {
let timeout = null,
diff = moment(Number(timestamp)).diff(moment());
let timeout = null;
let diff = moment(Number(timestamp)).diff(moment());
// NOTE: awake a little before...
timeout = setTimeout(function () {

View file

@ -1,16 +1,17 @@
// # Local File System Image Storage module
// The (default) module for storing images, using the local file system
const serveStatic = require('express').static,
fs = require('fs-extra'),
path = require('path'),
Promise = require('bluebird'),
moment = require('moment'),
config = require('../../config'),
common = require('../../lib/common'),
constants = require('../../lib/constants'),
urlUtils = require('../../lib/url-utils'),
StorageBase = require('ghost-storage-base');
const serveStatic = require('express').static;
const fs = require('fs-extra');
const path = require('path');
const Promise = require('bluebird');
const moment = require('moment');
const config = require('../../config');
const common = require('../../lib/common');
const constants = require('../../lib/constants');
const urlUtils = require('../../lib/url-utils');
const StorageBase = require('ghost-storage-base');
class LocalFileStore extends StorageBase {
constructor() {

View file

@ -15,16 +15,17 @@ const urlUtils = require('../../lib/url-utils');
exports.getLocalFileStoragePath = function getLocalFileStoragePath(imagePath) {
// The '/' in urlJoin is necessary to add the '/' to `content/images`, if no subdirectory is setup
const urlRegExp = new RegExp(`^${urlUtils.urlJoin(
urlUtils.urlFor('home', true),
urlUtils.getSubdir(),
'/',
urlUtils.STATIC_IMAGE_URL_PREFIX)}`
),
filePathRegExp = new RegExp(`^${urlUtils.urlJoin(
urlUtils.getSubdir(),
'/',
urlUtils.STATIC_IMAGE_URL_PREFIX)}`
);
urlUtils.urlFor('home', true),
urlUtils.getSubdir(),
'/',
urlUtils.STATIC_IMAGE_URL_PREFIX)}`
);
const filePathRegExp = new RegExp(`^${urlUtils.urlJoin(
urlUtils.getSubdir(),
'/',
urlUtils.STATIC_IMAGE_URL_PREFIX)}`
);
if (imagePath.match(urlRegExp)) {
return imagePath.replace(urlRegExp, '');

View file

@ -1,14 +1,14 @@
var _ = require('lodash'),
Analytics = require('analytics-node'),
config = require('./config'),
common = require('./lib/common'),
analytics;
const _ = require('lodash');
const Analytics = require('analytics-node');
const config = require('./config');
const common = require('./lib/common');
let analytics;
module.exports.init = function () {
analytics = new Analytics(config.get('segment:key'));
var toTrack,
trackDefaults = config.get('segment:trackDefaults') || {},
prefix = config.get('segment:prefix') || '';
let toTrack;
const trackDefaults = config.get('segment:trackDefaults') || {};
const prefix = config.get('segment:prefix') || '';
toTrack = [
{

View file

@ -162,11 +162,12 @@ module.exports = {
const allNotifications = _private.fetchAllNotifications();
const notificationToMarkAsSeen = allNotifications.find((notification) => {
return notification.id === frame.options.notification_id;
}),
notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => {
return notification.id === frame.options.notification_id;
});
return notification.id === frame.options.notification_id;
});
const notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => {
return notification.id === frame.options.notification_id;
});
if (notificationToMarkAsSeenIndex > -1 && !notificationToMarkAsSeen.dismissible) {
return Promise.reject(new common.errors.NoPermissionError({

View file

@ -189,7 +189,9 @@ const pipeline = (apiController, apiUtils, apiType) => {
obj[key] = function wrapper() {
const apiConfig = {docName, method};
let options, data, frame;
let options;
let data;
let frame;
if (arguments.length === 2) {
data = arguments[0];

View file

@ -162,11 +162,12 @@ module.exports = {
const allNotifications = _private.fetchAllNotifications();
const notificationToMarkAsSeen = allNotifications.find((notification) => {
return notification.id === frame.options.notification_id;
}),
notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => {
return notification.id === frame.options.notification_id;
});
return notification.id === frame.options.notification_id;
});
const notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => {
return notification.id === frame.options.notification_id;
});
if (notificationToMarkAsSeenIndex > -1 && !notificationToMarkAsSeen.dismissible) {
return Promise.reject(new common.errors.NoPermissionError({

View file

@ -1,32 +1,32 @@
var Nconf = require('nconf'),
path = require('path'),
_debug = require('ghost-ignition').debug._base,
debug = _debug('ghost:config'),
localUtils = require('./utils'),
env = process.env.NODE_ENV || 'development',
_private = {};
const Nconf = require('nconf');
const path = require('path');
const _debug = require('ghost-ignition').debug._base;
const debug = _debug('ghost:config');
const localUtils = require('./utils');
const env = process.env.NODE_ENV || 'development';
const _private = {};
_private.loadNconf = function loadNconf(options) {
debug('config start');
options = options || {};
var baseConfigPath = options.baseConfigPath || __dirname,
customConfigPath = options.customConfigPath || process.cwd(),
nconf = new Nconf.Provider();
const baseConfigPath = options.baseConfigPath || __dirname;
const customConfigPath = options.customConfigPath || process.cwd();
const nconf = new Nconf.Provider();
/**
* no channel can override the overrides
*/
* no channel can override the overrides
*/
nconf.file('overrides', path.join(baseConfigPath, 'overrides.json'));
/**
* command line arguments
*/
* command line arguments
*/
nconf.argv();
/**
* env arguments
*/
* env arguments
*/
nconf.env({
separator: '__',
parseValues: true
@ -38,9 +38,9 @@ _private.loadNconf = function loadNconf(options) {
nconf.file('defaults', path.join(baseConfigPath, 'defaults.json'));
/**
* transform all relative paths to absolute paths
* transform sqlite filename path for Ghost-CLI
*/
* transform all relative paths to absolute paths
* transform sqlite filename path for Ghost-CLI
*/
nconf.makePathsAbsolute = localUtils.makePathsAbsolute.bind(nconf);
nconf.isPrivacyDisabled = localUtils.isPrivacyDisabled.bind(nconf);
nconf.getContentPath = localUtils.getContentPath.bind(nconf);
@ -53,19 +53,19 @@ _private.loadNconf = function loadNconf(options) {
nconf.makePathsAbsolute(nconf.get('database:connection'), 'database:connection');
}
/**
* Check if the URL in config has a protocol
*/
* Check if the URL in config has a protocol
*/
nconf.checkUrlProtocol = localUtils.checkUrlProtocol.bind(nconf);
nconf.checkUrlProtocol();
/**
* Ensure that the content path exists
*/
* Ensure that the content path exists
*/
nconf.doesContentPathExist();
/**
* values we have to set manual
*/
* values we have to set manual
*/
nconf.set('env', env);
// Wrap this in a check, because else nconf.get() is executed unnecessarily

View file

@ -1,6 +1,6 @@
var path = require('path'),
fs = require('fs-extra'),
_ = require('lodash');
const path = require('path');
const fs = require('fs-extra');
const _ = require('lodash');
exports.isPrivacyDisabled = function isPrivacyDisabled(privacyFlag) {
if (!this.get('privacy')) {
@ -29,7 +29,7 @@ exports.isPrivacyDisabled = function isPrivacyDisabled(privacyFlag) {
* Path can be a "." to re-present current folder
*/
exports.makePathsAbsolute = function makePathsAbsolute(obj, parent) {
var self = this;
const self = this;
_.each(obj, function (configValue, pathsKey) {
if (_.isObject(configValue)) {
@ -80,7 +80,7 @@ exports.doesContentPathExist = function doesContentPathExist() {
* Check if the URL in config has a protocol and sanitise it if not including a warning that it should be changed
*/
exports.checkUrlProtocol = function checkUrlProtocol() {
var url = this.get('url');
const url = this.get('url');
if (!url.match(/^https?:\/\//i)) {
throw new Error('URL in config must be provided with protocol, eg. "http://my-ghost-blog.com"');
@ -95,7 +95,7 @@ exports.checkUrlProtocol = function checkUrlProtocol() {
* https://github.com/indexzero/nconf/issues/235#issuecomment-257606507
*/
exports.sanitizeDatabaseProperties = function sanitizeDatabaseProperties() {
var database = this.get('database');
const database = this.get('database');
if (this.get('database:client') === 'mysql') {
delete database.connection.filename;

View file

@ -1,18 +1,18 @@
// # Backup Database
// Provides for backing up the database before making potentially destructive changes
var fs = require('fs-extra'),
path = require('path'),
Promise = require('bluebird'),
config = require('../../config'),
common = require('../../lib/common'),
urlUtils = require('../../lib/url-utils'),
exporter = require('../exporter'),
const fs = require('fs-extra');
writeExportFile,
backup;
const path = require('path');
const Promise = require('bluebird');
const config = require('../../config');
const common = require('../../lib/common');
const urlUtils = require('../../lib/url-utils');
const exporter = require('../exporter');
let writeExportFile;
let backup;
writeExportFile = function writeExportFile(exportResult) {
var filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename));
const filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename));
return fs.writeFile(filename, JSON.stringify(exportResult.data)).return(filename);
};
@ -41,7 +41,7 @@ backup = function backup(options) {
common.logging.info('Creating database backup');
options = options || {};
var props = {
const props = {
data: exporter.doExport(options),
filename: exporter.fileName(options)
};

View file

@ -1,14 +1,14 @@
var knex = require('knex'),
config = require('../../config'),
common = require('../../lib/common'),
knexInstance;
const knex = require('knex');
const config = require('../../config');
const common = require('../../lib/common');
let knexInstance;
// @TODO:
// - if you require this file before config file was loaded,
// - then this file is cached and you have no chance to connect to the db anymore
// - bring dynamic into this file (db.connect())
function configure(dbConfig) {
var client = dbConfig.client;
const client = dbConfig.client;
if (client === 'sqlite3') {
dbConfig.useNullAsDefault = Object.prototype.hasOwnProperty.call(dbConfig, 'useNullAsDefault') ? dbConfig.useNullAsDefault : true;

View file

@ -1,4 +1,4 @@
var connection;
let connection;
Object.defineProperty(exports, 'knex', {
enumerable: true,

View file

@ -1,12 +1,14 @@
const KnexMigrator = require('knex-migrator'),
config = require('../../config'),
common = require('../../lib/common'),
knexMigrator = new KnexMigrator({
knexMigratorFilePath: config.get('paths:appRoot')
});
const KnexMigrator = require('knex-migrator');
const config = require('../../config');
const common = require('../../lib/common');
const knexMigrator = new KnexMigrator({
knexMigratorFilePath: config.get('paths:appRoot')
});
module.exports.getState = () => {
let state, err;
let state;
let err;
return knexMigrator.isDatabaseOK()
.then(() => {

View file

@ -1,32 +1,36 @@
var _ = require('lodash'),
Promise = require('bluebird'),
db = require('../../data/db'),
commands = require('../schema').commands,
ghostVersion = require('../../lib/ghost-version'),
common = require('../../lib/common'),
security = require('../../lib/security'),
models = require('../../models'),
EXCLUDED_TABLES = ['sessions', 'mobiledoc_revisions'],
EXCLUDED_FIELDS_CONDITIONS = {
settings: [{
operator: 'whereNot',
key: 'key',
value: 'permalinks'
}]
},
modelOptions = {context: {internal: true}},
const _ = require('lodash');
const Promise = require('bluebird');
const db = require('../../data/db');
const commands = require('../schema').commands;
const ghostVersion = require('../../lib/ghost-version');
const common = require('../../lib/common');
const security = require('../../lib/security');
const models = require('../../models');
const EXCLUDED_TABLES = ['sessions', 'mobiledoc_revisions'];
// private
getVersionAndTables,
exportTable,
const EXCLUDED_FIELDS_CONDITIONS = {
settings: [{
operator: 'whereNot',
key: 'key',
value: 'permalinks'
}]
};
// public
doExport,
exportFileName;
const modelOptions = {context: {internal: true}};
// private
let getVersionAndTables;
let exportTable;
// public
let doExport;
let exportFileName;
exportFileName = function exportFileName(options) {
var datetime = require('moment')().format('YYYY-MM-DD-HH-mm-ss'),
title = '';
const datetime = require('moment')().format('YYYY-MM-DD-HH-mm-ss');
let title = '';
options = options || {};
@ -48,7 +52,7 @@ exportFileName = function exportFileName(options) {
};
getVersionAndTables = function getVersionAndTables(options) {
var props = {
const props = {
version: ghostVersion.full,
tables: commands.getTables(options.transacting)
};
@ -74,7 +78,8 @@ exportTable = function exportTable(tableName, options) {
doExport = function doExport(options) {
options = options || {include: []};
var tables, version;
let tables;
let version;
return getVersionAndTables(options).then(function exportAllTables(result) {
tables = result.tables;
@ -84,7 +89,7 @@ doExport = function doExport(options) {
return exportTable(tableName, options);
});
}).then(function formatData(tableData) {
var exportData = {
const exportData = {
meta: {
exported_on: new Date().getTime(),
version: version

Some files were not shown because too many files have changed in this diff Show more