Nuxt/lib/utils.js

100 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2016-11-07 01:34:58 +00:00
'use strict'
2017-05-18 08:44:31 +00:00
import { resolve, sep } from 'path'
import _ from 'lodash'
2016-11-07 01:34:58 +00:00
2017-01-11 19:14:59 +00:00
export function encodeHtml (str) {
2017-01-11 21:51:52 +00:00
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
2017-01-11 19:14:59 +00:00
}
2016-11-07 01:34:58 +00:00
2017-01-11 19:14:59 +00:00
export function getContext (req, res) {
return { req, res }
}
2016-11-07 01:34:58 +00:00
2017-01-11 19:14:59 +00:00
export function setAnsiColors (ansiHTML) {
2016-11-07 01:34:58 +00:00
ansiHTML.setColors({
reset: ['efefef', 'a6004c'],
darkgrey: '5a012b',
yellow: 'ffab07',
green: 'aeefba',
magenta: 'ff84bf',
blue: '3505a0',
cyan: '56eaec',
red: '4e053a'
})
}
2017-05-14 18:21:14 +00:00
export async function waitFor (ms) {
2016-11-07 01:34:58 +00:00
return new Promise(function (resolve) {
setTimeout(resolve, (ms || 0))
})
}
2016-11-10 18:34:59 +00:00
2017-01-11 19:14:59 +00:00
export function urlJoin () {
2017-02-16 17:16:00 +00:00
return [].slice.call(arguments).join('/').replace(/\/+/g, '/').replace(':/', '://')
2016-11-10 18:34:59 +00:00
}
2016-11-24 00:47:11 +00:00
2017-03-16 17:52:38 +00:00
export function isUrl (url) {
return (url.indexOf('http') === 0 || url.indexOf('//') === 0)
}
export function promisifyRoute (fn) {
// If routes is an array
2016-11-24 00:47:11 +00:00
if (Array.isArray(fn)) {
return Promise.resolve(fn)
}
// If routes is a function expecting a callback
2016-11-24 00:47:11 +00:00
if (fn.length === 1) {
2016-12-10 11:39:11 +00:00
return new Promise((resolve, reject) => {
2016-11-24 00:47:11 +00:00
fn(function (err, routeParams) {
if (err) {
reject(err)
}
resolve(routeParams)
})
})
}
2016-12-10 11:39:11 +00:00
let promise = fn()
2017-04-06 09:18:27 +00:00
if (!promise || (!(promise instanceof Promise) && (typeof promise.then !== 'function'))) {
2016-11-24 00:47:11 +00:00
promise = Promise.resolve(promise)
}
return promise
}
export function sequence (tasks, fn) {
return tasks.reduce((promise, task) => promise.then(() => fn(task)), Promise.resolve())
}
2017-05-12 07:57:24 +00:00
export function chainFn (base, fn) {
2017-05-14 23:01:41 +00:00
/* istanbul ignore if */
2017-05-12 07:57:24 +00:00
if (!(fn instanceof Function)) {
return
}
return function () {
if (base instanceof Function) {
base.apply(this, arguments)
}
fn.apply(this, arguments)
}
}
2017-05-18 08:44:31 +00:00
export function wp (p) {
2017-05-18 08:44:31 +00:00
/* istanbul ignore if */
if (/^win/.test(process.platform)) {
p = p.replace(/\\/g, '\\\\')
}
return p
}
const reqSep = /\//g
const sysSep = _.escapeRegExp(sep)
const normalize = string => string.replace(reqSep, sysSep)
export function r () {
let args = Array.from(arguments)
if (_.last(args).includes('~')) {
return wp(_.last(args))
}
args = args.map(normalize)
return wp(resolve.apply(null, args))
}