Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@vuepress/shared-utils

Package Overview
Dependencies
Maintainers
2
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vuepress/shared-utils - npm Package Compare versions

Comparing version 1.0.0-alpha.27 to 1.0.0-alpha.28

lib/index.js

37

lib/codegen.js

@@ -1,19 +0,20 @@

exports.pathsToModuleCode = function (files) {
let index = 0
let code = ''
code += files
.map(filePath => `import m${index++} from ${JSON.stringify(filePath)}`)
.join('\n')
code += '\n\nexport default [\n'
for (let i = 0; i < index; i++) {
code += ` m${i}`
code += i === index - 1 ? '\n' : ',\n'
}
code += ']\n'
return code
"use strict";
/**
* Convert paths string to real-world import code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
function pathsToModuleCode(files) {
let index = 0;
let code = '';
code += files
.map(filePath => `import m${index++} from ${JSON.stringify(filePath)}`)
.join('\n');
code += '\n\nexport default [\n';
for (let i = 0; i < index; i++) {
code += ` m${i}`;
code += i === index - 1 ? '\n' : ',\n';
}
code += ']\n';
return code;
}
exports.pathsToModuleCode = pathsToModuleCode;

@@ -0,10 +1,13 @@

"use strict";
/**
* Build functional pipeline.
*/
module.exports = function compose (...processors) {
if (processors.length === 0) return input => input
if (processors.length === 1) return processors[0]
return processors.reduce((prev, next) => {
return (...args) => next(prev(...args))
})
}
module.exports = function compose(...processors) {
if (processors.length === 0)
return (input) => input;
if (processors.length === 1)
return processors[0];
return processors.reduce((prev, next) => {
return (...args) => next(prev(...args));
});
};

@@ -1,67 +0,58 @@

const chalk = require('chalk')
exports.isObject = obj => obj !== null && typeof obj === 'object'
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk_1 = __importDefault(require("chalk"));
exports.isObject = (obj) => obj !== null && typeof obj === 'object';
/**
* Get the raw type string of a value e.g. [object Object]
*/
const _toString = Object.prototype.toString
const getObjectType = x => _toString.call(x).slice(8, -1)
const isOfType = type => x => typeof x === type // eslint-disable-line valid-typeof
const isObjectOfType = type => x => getObjectType(x) === type
exports.isFunction = isOfType('function')
exports.isString = isOfType('string')
exports.isBoolean = isOfType('boolean')
exports.isPlainObject = isObjectOfType('Object')
exports.isUndefined = isOfType('undefined')
exports.isNull = x => x === null
exports.isNullOrUndefined = x => exports.isUndefined(x) || exports.isNull(x)
exports.toRawType = value => _toString.call(value).slice(8, -1)
const _toString = Object.prototype.toString;
const getObjectType = (x) => _toString.call(x).slice(8, -1);
const isOfType = (type) => (x) => typeof x === type; // eslint-disable-line valid-typeof
const isObjectOfType = (type) => (x) => getObjectType(x) === type;
exports.isFunction = isOfType('function');
exports.isString = isOfType('string');
exports.isBoolean = isOfType('boolean');
exports.isPlainObject = isObjectOfType('Object');
exports.isUndefined = isOfType('undefined');
exports.isNull = (x) => x === null;
exports.isNullOrUndefined = (x) => exports.isUndefined(x) || exports.isNull(x);
exports.toRawType = (value) => _toString.call(value).slice(8, -1);
exports.getType = function (fn) {
const match = fn && fn.toString().match(/^\s*function (\w+)/)
return match ? match[1] : ''
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : '';
};
function toNaturalMultiTypesLanguage(types) {
const len = types.length;
if (len === 1) {
return types.join('');
}
const rest = types.slice(0, len - 1);
const last = types[len - 1];
return rest.join(', ') + ' or ' + last;
}
/**
* Transform multi-types to natural language. e.g.
* ['Function'] => 'Function'
* ['Function', 'Object'] => 'Function or Object'
* ['Function', 'Object', 'Number'] => 'Function, Object or Number'
*/
function toNaturalMultiTypesLanguage (types) {
const len = types.length
if (len === 1) {
return types.join('')
}
const rest = types.slice(0, len - 1)
const last = types[len - 1]
return rest.join(', ') + ' or ' + last
function assertTypes(value, types) {
let valid;
let warnMsg;
let actualType = exports.toRawType(value);
const expectedTypes = [];
if (actualType === 'AsyncFunction') {
actualType = 'Function';
}
for (const type of types) {
const expectedType = exports.getType(type);
expectedTypes.push(expectedType);
valid = actualType === expectedType;
if (valid)
break;
}
if (!valid) {
warnMsg =
`expected a ${chalk_1.default.green(toNaturalMultiTypesLanguage(expectedTypes))} ` +
`but got ${chalk_1.default.yellow(actualType)}.`;
}
return { valid, warnMsg };
}
exports.assertTypes = function (value, types) {
let valid
let warnMsg
let actualType = exports.toRawType(value)
const expectedTypes = []
if (actualType === 'AsyncFunction') {
actualType = 'Function'
}
for (const type of types) {
const expectedType = exports.getType(type)
expectedTypes.push(expectedType)
valid = actualType === expectedType
if (valid) break
}
if (!valid) {
warnMsg =
`expected a ${chalk.green(toNaturalMultiTypesLanguage(expectedTypes))} ` +
`but got ${chalk.yellow(actualType)}.`
}
return { valid, warnMsg }
}
exports.assertTypes = assertTypes;

@@ -1,17 +0,8 @@

// This method remove the raw HTML but reserve the HTML wrapped by `<code>`.
// e.g.
// Input: "<a> b", Output: "b"
// Input: "`<a>` b", Output: "`<a>` b"
function removeNonCodeWrappedHTML (str) {
return String(str).replace(/(^|[^><`])<.*>([^><`]|$)/g, '$1$2')
}
// Also clean the html that isn't wrapped by code.
// Because we want to support using VUE components in headers.
// e.g. https://vuepress.vuejs.org/guide/using-vue.html#badge
module.exports = require('./compose')(
removeNonCodeWrappedHTML,
require('./parseHeaders')
)
module.exports.removeNonCodeWrappedHTML = removeNonCodeWrappedHTML
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const compose_1 = __importDefault(require("./compose"));
const parseHeaders_1 = __importDefault(require("./parseHeaders"));
const removeNonCodeWrappedHTML_1 = __importDefault(require("./removeNonCodeWrappedHTML"));
module.exports = compose_1.default(removeNonCodeWrappedHTML_1.default, parseHeaders_1.default);

@@ -1,5 +0,6 @@

module.exports = function ensureEndingSlash (path) {
return /(\.html|\/)$/.test(path)
? path
: path + '/'
}
"use strict";
module.exports = function ensureEndingSlash(path) {
return /(\.html|\/)$/.test(path)
? path
: path + '/';
};

@@ -1,3 +0,4 @@

module.exports = function ensureLeadingSlash (path) {
return path.replace(/^\/?/, '/')
}
"use strict";
module.exports = function ensureLeadingSlash(path) {
return path.replace(/^\/?/, '/');
};

@@ -0,14 +1,12 @@

"use strict";
class ENV {
constructor () {
this.isDebug = false
this.isTest = false
this.isProduction = false
}
setOptions (options) {
Object.assign(this, options)
}
constructor() {
this.isDebug = false;
this.isTest = process.env.NODE_ENV === 'test' || false;
this.isProduction = false;
}
setOptions(options) {
Object.assign(this, options);
}
}
module.exports = new ENV()
module.exports = new ENV();

@@ -1,3 +0,7 @@

const deeplyParseHeaders = require('./deeplyParseHeaders')
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const lru_cache_1 = __importDefault(require("lru-cache"));
const deeplyParseHeaders_1 = __importDefault(require("./deeplyParseHeaders"));
/**

@@ -11,30 +15,26 @@ * Extract heeaders from markdown source content.

*/
const LRU = require('lru-cache')
const cache = LRU({ max: 1000 })
const cache = lru_cache_1.default({ max: 1000 });
module.exports = function (content, include = [], md) {
const key = content + include.join(',')
const hit = cache.get(key)
if (hit) {
return hit
}
const tokens = md.parse(content, {})
const res = []
tokens.forEach((t, i) => {
if (t.type === 'heading_open' && include.includes(t.tag)) {
const title = tokens[i + 1].content
const slug = t.attrs.find(([name]) => name === 'id')[1]
res.push({
level: parseInt(t.tag.slice(1), 10),
title: deeplyParseHeaders(title),
slug: slug || md.slugify(title)
})
const key = content + include.join(',');
const hit = cache.get(key);
if (hit) {
return hit;
}
})
cache.set(key, res)
return res
}
const tokens = md.parse(content, {});
const res = [];
tokens.forEach((t, i) => {
// @ts-ignore
if (t.type === 'heading_open' && include.includes(t.tag)) {
const title = tokens[i + 1].content;
// @ts-ignore
const slug = (t.attrs).find(([name]) => name === 'id')[1];
res.push({
level: parseInt(t.tag.slice(1), 10),
title: deeplyParseHeaders_1.default(title),
slug: slug || md.slugify(title)
});
}
});
cache.set(key, res);
return res;
};

@@ -1,9 +0,14 @@

const fs = require('fs-extra')
exports.fsExistsFallback = function (files) {
for (const file of files) {
if (fs.existsSync(file)) {
return file
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
function fsExistsFallback(files) {
for (const file of files) {
if (fs_extra_1.default.existsSync(file)) {
return file;
}
}
}
}
exports.fsExistsFallback = fsExistsFallback;

@@ -1,20 +0,19 @@

const { indexRE } = require('./isIndexFile')
const isIndexFile = require('./isIndexFile')
const extRE = /\.(vue|md)$/
module.exports = function fileToPath (file) {
if (isIndexFile(file)) {
// README.md -> /
// README.vue -> /
// foo/README.md -> /foo/
// foo/README.vue -> /foo/
return file.replace(indexRE, '/$1')
} else {
// foo.md -> /foo.html
// foo.vue -> /foo.html
// foo/bar.md -> /foo/bar.html
// foo/bar.vue -> /foo/bar.html
return `/${file.replace(extRE, '').replace(/\\/g, '/')}.html`
}
}
"use strict";
const isIndexFile_1 = require("./isIndexFile");
const extRE = /\.(vue|md)$/;
module.exports = function fileToPath(file) {
if (isIndexFile_1.isIndexFile(file)) {
// README.md -> /
// README.vue -> /
// foo/README.md -> /foo/
// foo/README.vue -> /foo/
return file.replace(isIndexFile_1.indexRE, '/$1');
}
else {
// foo.md -> /foo.html
// foo.vue -> /foo.html
// foo/bar.md -> /foo/bar.html
// foo/bar.vue -> /foo/bar.html
return `/${file.replace(extRE, '').replace(/\\/g, '/')}.html`;
}
};

@@ -1,51 +0,34 @@

const ensureEndingSlash = require('./ensureEndingSlash')
const ensureLeadingSlash = require('./ensureLeadingSlash')
// e.g.
// filename: docs/_posts/evan you.md
// content: # yyx 990803
// date: 2018-08-14 11:22:33
// :year/:month/:day/:slug/ => 2018/08/14/evan-you/
// :year-:month-:day-:slug/ => 2018-08-14-evan-you/
// :year/:month/:day/:title/ => 2018/08/14/yyx 990803/
// :year/:month/:day/:original/ => 2018/08/14/_posts/evan you.html
module.exports = function getPermalink ({
pattern,
slug,
date,
regularPath,
localePath = '/'
}) {
if (!pattern) {
return
}
slug = encodeURI(slug)
const d = new Date(date)
const year = d.getFullYear()
const iMonth = d.getMonth() + 1
const iDay = d.getDate()
const minutes = d.getMinutes()
const seconds = d.getSeconds()
const month = iMonth < 10 ? `0${iMonth}` : iMonth
const day = iDay < 10 ? `0${iDay}` : iDay
// Remove leading slash
pattern = pattern.replace(/^\//, '')
const link =
localePath +
pattern
.replace(/:year/, year)
.replace(/:month/, month)
.replace(/:i_month/, iMonth)
.replace(/:i_day/, iDay)
.replace(/:day/, day)
.replace(/:minutes/, minutes)
.replace(/:seconds/, seconds)
.replace(/:slug/, slug)
.replace(/:regular/, regularPath)
return ensureLeadingSlash(ensureEndingSlash(link))
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const ensureEndingSlash_1 = __importDefault(require("./ensureEndingSlash"));
const ensureLeadingSlash_1 = __importDefault(require("./ensureLeadingSlash"));
module.exports = function getPermalink({ pattern, slug, date, regularPath, localePath = '/' }) {
if (!pattern) {
return;
}
slug = encodeURI(slug);
const d = new Date(date);
const year = d.getFullYear();
const iMonth = d.getMonth() + 1;
const iDay = d.getDate();
const minutes = d.getMinutes();
const seconds = d.getSeconds();
const month = iMonth < 10 ? `0${iMonth}` : iMonth;
const day = iDay < 10 ? `0${iDay}` : iDay;
// Remove leading slash
pattern = pattern.replace(/^\//, '');
const link = localePath +
pattern
.replace(/:year/, String(year))
.replace(/:month/, String(month))
.replace(/:i_month/, String(iMonth))
.replace(/:i_day/, String(iDay))
.replace(/:day/, String(day))
.replace(/:minutes/, String(minutes))
.replace(/:seconds/, String(seconds))
.replace(/:slug/, slug)
.replace(/:regular/, regularPath);
return ensureLeadingSlash_1.default(ensureEndingSlash_1.default(link));
};

@@ -1,22 +0,17 @@

const deeplyParseHeaders = require('./deeplyParseHeaders')
/**
* Infer a page's title via frontmatter and content.
*
* @param {object} frontmatter
* @param {string} strippedContent
* @returns {*}
*/
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const deeplyParseHeaders_1 = __importDefault(require("./deeplyParseHeaders"));
module.exports = function (frontmatter, strippedContent) {
if (frontmatter.home) {
return 'Home'
}
if (frontmatter.title) {
return deeplyParseHeaders(frontmatter.title)
}
const match = strippedContent.trim().match(/^#+\s+(.*)/)
if (match) {
return deeplyParseHeaders(match[1])
}
}
if (frontmatter.home) {
return 'Home';
}
if (frontmatter.title) {
return deeplyParseHeaders_1.default(frontmatter.title);
}
const match = strippedContent.trim().match(/^#+\s+(.*)/);
if (match) {
return deeplyParseHeaders_1.default(match[1]);
}
};

@@ -1,8 +0,7 @@

const indexRE = /(^|.*\/)(index|readme)\.(md|vue)$/i
function isIndexFile (file) {
return indexRE.test(file)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexRE = /(^|.*\/)(index|readme)\.(md|vue)$/i;
function isIndexFile(file) {
return exports.indexRE.test(file);
}
module.exports = isIndexFile
module.exports.indexRE = indexRE
exports.isIndexFile = isIndexFile;

@@ -1,103 +0,84 @@

'use strict'
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
/**
* Module dependencies.
*/
const chalk = require('chalk')
const chalk_1 = __importDefault(require("chalk"));
class Logger {
constructor (options) {
this.options = Object.assign(
{
logLevel: process.argv.includes('--debug')
? 4
: 3
},
options
)
}
setOptions (options) {
Object.assign(this.options, options)
}
// level: 4
debug (...args) {
if (this.options.logLevel < 4) {
return
constructor(options) {
this.options = Object.assign({
logLevel: process.argv.includes('--debug')
? 4
: 3
}, options);
}
this.status('magenta', 'debug', ...args)
}
// level: 2
warn (...args) {
if (this.options.logLevel < 2) {
return
setOptions(options) {
Object.assign(this.options, options);
}
console.warn(chalk.yellow('warning'), ...args)
}
// level: 1
error (...args) {
if (this.options.logLevel < 1) {
return
// level: 4
debug(...args) {
if (this.options.logLevel < 4) {
return;
}
this.status('magenta', 'debug', ...args);
}
process.exitCode = process.exitCode || 1
console.error(chalk.red('error'), ...args)
}
// level: 3
success (...args) {
if (this.options.logLevel < 3) {
return
// level: 2
warn(...args) {
if (this.options.logLevel < 2) {
return;
}
console.warn(chalk_1.default.yellow('warning'), ...args);
}
this.status('green', 'success', ...args)
}
// level: 3
tip (...args) {
if (this.options.logLevel < 3) {
return
// level: 1
error(...args) {
if (this.options.logLevel < 1) {
return;
}
process.exitCode = process.exitCode || 1;
console.error(chalk_1.default.red('error'), ...args);
}
this.status('blue', 'tip', ...args)
}
// level: 3
info (...args) {
if (this.options.logLevel < 3) {
return
// level: 3
success(...args) {
if (this.options.logLevel < 3) {
return;
}
this.status('green', 'success', ...args);
}
this.status('cyan', 'info', ...args)
}
wait (...args) {
if (this.options.logLevel < 3) {
return
// level: 3
tip(...args) {
if (this.options.logLevel < 3) {
return;
}
this.status('blue', 'tip', ...args);
}
this.status('cyan', 'wait', ...args)
}
// level: 3
status (color, label, ...args) {
if (this.options.logLevel < 3) {
return
// level: 3
info(...args) {
if (this.options.logLevel < 3) {
return;
}
this.status('cyan', 'info', ...args);
}
console.log(chalk[color](label), ...args)
}
developer (...args) {
if (process.env.VUEPRESS_ENV !== 'developer' && !process.argv.includes('--developer')) {
return
wait(...args) {
if (this.options.logLevel < 3) {
return;
}
this.status('cyan', 'wait', ...args);
}
this.status('cyan', 'developer', ...args)
}
// level: 3
status(color, label, ...args) {
if (this.options.logLevel < 3) {
return;
}
// @ts-ignore
console.log(chalk_1.default[color](label), ...args);
}
developer(...args) {
if (process.env.VUEPRESS_ENV !== 'developer' && !process.argv.includes('--developer')) {
return;
}
this.status('cyan', 'developer', ...args);
}
}
/**
* Expose a logger instance.
*/
module.exports = new Logger()
module.exports = new Logger();

@@ -1,273 +0,190 @@

'use strict'
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Module dependencies.
*/
const path = require('upath')
const chalk = require('chalk')
const { resolveModule, loadModule } = require('./module')
const tryChain = require('./tryChain')
const { fsExistsFallback } = require('./fallback')
const hash = require('hash-sum')
const {
isString,
isFunction,
isObject,
isNullOrUndefined,
assertTypes
} = require('./datatypes')
const SCOPE_PACKAGE_RE = /^@(.*)\/(.*)/
const upath_1 = __importDefault(require("upath"));
const chalk_1 = __importDefault(require("chalk"));
const moduleLoader_1 = require("./moduleLoader");
const tryChain_1 = __importDefault(require("./tryChain"));
const fallback_1 = require("./fallback");
const hash_sum_1 = __importDefault(require("hash-sum"));
const datatypes_1 = require("./datatypes");
const SCOPE_PACKAGE_RE = /^@(.*)\/(.*)/;
/**
* Common module constructor.
*/
class CommonModule {
constructor (entry, name, shortcut, fromDep) {
this.entry = entry
this.shortcut = shortcut
this.name = name
this.fromDep = fromDep
}
constructor(entry, name, shortcut, fromDep) {
this.entry = entry;
this.shortcut = shortcut;
this.name = name;
this.fromDep = fromDep;
}
}
/**
* Expose ModuleResolver.
*/
exports.CommonModule = CommonModule;
class ModuleResolver {
constructor (type, org, allowedTypes = [String], load = false, cwd) {
this.type = type
this.org = org
this.allowedTypes = allowedTypes
this.load = load
this.cwd = cwd || process.cwd()
this.nonScopePrefix = `${org}-${type}-`
this.scopePrefix = `@${org}/${type}-`
this.typePrefixLength = type.length + 1
/* - */
this.prefixSlicePosition = this.typePrefixLength + org.length + 1
/* @ */
}
/**
* Resolve package.
*
* @param {any} req
* @param {string} cwd
* @api public
*/
resolve (req, cwd) {
if (cwd) {
this.setCwd(cwd)
constructor(type, org, allowedTypes = [String], load = false, cwd) {
this.type = type;
this.org = org;
this.allowedTypes = allowedTypes;
this.load = load;
this.cwd = cwd || process.cwd();
this.nonScopePrefix = `${org}-${type}-`;
this.scopePrefix = `@${org}/${type}-`;
this.typePrefixLength = type.length + 1;
/* - */
this.prefixSlicePosition = this.typePrefixLength + org.length + 1;
/* @ */
}
const { valid, warnMsg } = assertTypes(req, this.allowedTypes)
if (!valid) {
throw new Error(`Invalid value for "${chalk.cyan(this.type)}": ${warnMsg}`)
/**
* Resolve package.
*/
resolve(req, cwd) {
if (cwd) {
this.setCwd(cwd);
}
const { valid, warnMsg } = datatypes_1.assertTypes(req, this.allowedTypes);
if (!valid) {
throw new Error(`Invalid value for "${chalk_1.default.cyan(this.type)}": ${warnMsg}`);
}
const isStringRequest = datatypes_1.isString(req);
const isAbsolutePath = isStringRequest && upath_1.default.isAbsolute(req);
const resolved = tryChain_1.default([
[this.resolveNonStringPackage.bind(this), !isStringRequest],
[this.resolveAbsolutePathPackage.bind(this), isStringRequest && isAbsolutePath],
[this.resolveRelativePathPackage.bind(this), isStringRequest && !isAbsolutePath],
[this.resolveDepPackage.bind(this), isStringRequest]
], req);
if (!resolved) {
return new CommonModule(null, null, null, null /* fromDep */);
}
return resolved;
}
const isStringRequest = isString(req)
const isAbsolutePath = isStringRequest && path.isAbsolute(req)
const resolved = tryChain([
[this.resolveNonStringPackage.bind(this), !isStringRequest],
[this.resolveAbsolutePathPackage.bind(this), isStringRequest && isAbsolutePath],
[this.resolveRelativePathPackage.bind(this), isStringRequest && !isAbsolutePath],
[this.resolveDepPackage.bind(this), isStringRequest]
], req)
if (!resolved) {
return new CommonModule(null, null, null, null /* fromDep */)
/**
* Set current working directory.
*/
setCwd(cwd) {
this.cwd = cwd;
return this;
}
return resolved
}
/**
* Set current working directory.
* @param cwd
* @returns {module.ModuleResolver}
* @api public
*/
setCwd (cwd) {
this.cwd = cwd
return this
}
/**
* Resolve non-string package, return directly.
*
* @param {object|function} req
* @param {string} type
* @returns {CommonModule}
* @api private
*/
resolveNonStringPackage (req) {
const { shortcut, name } = this.normalizeRequest(req)
return new CommonModule(req, name, shortcut, false /* fromDep */)
}
/**
* Resolve module with absolute path.
*
* @param {string} req
* @returns {CommonModule}
* @api private
*/
resolveAbsolutePathPackage (req) {
const normalized = fsExistsFallback([
req,
req + '.js',
path.resolve(req, 'index.js')
])
if (!normalized) {
throw new Error(`${req} Not Found.`)
/**
* Resolve non-string package, return directly.
*/
resolveNonStringPackage(req) {
const { shortcut, name } = this.normalizeRequest(req);
return new CommonModule(req, name, shortcut, false /* fromDep */);
}
const dirname = path.parse(normalized).name
const { shortcut, name } = this.normalizeRequest(dirname)
const module = this.load ? require(normalized) : normalized
return new CommonModule(module, name, shortcut, false /* fromDep */)
}
/**
* Resolve module with absolute path.
*
* @param {string} req
* @returns {CommonModule}
* @api private
*/
resolveRelativePathPackage (req) {
req = path.resolve(process.cwd(), req)
return this.resolveAbsolutePathPackage(req)
}
/**
* Resolve module from dependency.
*
* @param {string} req
* @returns {CommonModule}
* @api private
*/
resolveDepPackage (req) {
const { shortcut, name } = this.normalizeRequest(req)
const entry = this.load
? loadModule(name, this.cwd)
: resolveModule(name, this.cwd)
return new CommonModule(entry, name, shortcut, true /* fromDep */)
}
/**
* Get shortcut.
*
* @param {string} req
* @returns {string}
* @api private
*/
getShortcut (req) {
return req.startsWith(this.nonScopePrefix)
? req.slice(this.prefixSlicePosition)
: req
}
/**
* Normalize string request name.
*
* @param {string} req
* @returns {object}
* @api private
*/
normalizeName (req) {
let name
let shortcut
if (req.startsWith('@')) {
const pkg = resolveScopePackage(req)
if (pkg) {
// speicial handling for default org.
if (pkg.org === this.org) {
shortcut = pkg.name.startsWith(`${this.type}-`)
? pkg.name.slice(this.typePrefixLength)
: pkg.name
name = `${this.scopePrefix}${shortcut}`
} else {
shortcut = this.getShortcut(pkg.name)
name = `@${pkg.org}/${this.nonScopePrefix}${shortcut}`
/**
* Resolve module with absolute path.
*/
resolveAbsolutePathPackage(req) {
const normalized = fallback_1.fsExistsFallback([
req,
req + '.js',
upath_1.default.resolve(req, 'index.js')
]);
if (!normalized) {
throw new Error(`${req} Not Found.`);
}
shortcut = `@${pkg.org}/${shortcut}`
}
} else {
shortcut = this.getShortcut(req)
name = `${this.nonScopePrefix}${shortcut}`
const dirname = upath_1.default.parse(normalized).name;
const { shortcut, name } = this.normalizeRequest(dirname);
const module = this.load ? require(normalized) : normalized;
return new CommonModule(module, name, shortcut, false /* fromDep */);
}
return { name, shortcut }
}
/**
* Normalize any request.
*
* @param {any} req
* @returns {object}
* @api private
*/
normalizeRequest (req) {
if (isString(req)) {
return this.normalizeName(req)
/**
* Resolve module with absolute path.
*/
resolveRelativePathPackage(req) {
req = upath_1.default.resolve(process.cwd(), req);
return this.resolveAbsolutePathPackage(req);
}
if (isNullOrUndefined(req)) {
return {
name: null,
shortcut: null
}
/**
* Resolve module from dependency.
*/
resolveDepPackage(req) {
const { shortcut, name } = this.normalizeRequest(req);
const entry = this.load
? moduleLoader_1.loadModule(name, this.cwd)
: moduleLoader_1.resolveModule(name, this.cwd);
return new CommonModule(entry, name, shortcut, true /* fromDep */);
}
if (isObject(req) || isFunction(req)) {
if (isString(req.name)) {
return this.normalizeName(req.name)
} else {
const shortcut = `anonymous-${hash(req)}`
const name = `${this.nonScopePrefix}${shortcut}`
return { name, shortcut }
}
/**
* Get shortcut.
*/
getShortcut(req) {
return req.startsWith(this.nonScopePrefix)
? req.slice(this.prefixSlicePosition)
: req;
}
}
/**
* Normalize string request name.
*/
normalizeName(req) {
let name;
let shortcut;
if (req.startsWith('@')) {
const pkg = resolveScopePackage(req);
if (pkg) {
// speicial handling for default org.
if (pkg.org === this.org) {
shortcut = pkg.name.startsWith(`${this.type}-`)
? pkg.name.slice(this.typePrefixLength)
: pkg.name;
name = `${this.scopePrefix}${shortcut}`;
}
else {
shortcut = this.getShortcut(pkg.name);
name = `@${pkg.org}/${this.nonScopePrefix}${shortcut}`;
}
shortcut = `@${pkg.org}/${shortcut}`;
}
}
else {
shortcut = this.getShortcut(req);
name = `${this.nonScopePrefix}${shortcut}`;
}
// @ts-ignore
return { name, shortcut };
}
/**
* Normalize any request.
*/
normalizeRequest(req) {
if (datatypes_1.isString(req)) {
return this.normalizeName(req);
}
if (datatypes_1.isObject(req) || datatypes_1.isFunction(req)) {
if (datatypes_1.isString(req.name)) {
return this.normalizeName(req.name);
}
else {
const shortcut = `anonymous-${hash_sum_1.default(req)}`;
const name = `${this.nonScopePrefix}${shortcut}`;
return { name, shortcut };
}
}
return {
name: null,
shortcut: null
};
}
}
/**
* Parse info of scope package.
*/
function resolveScopePackage (name) {
if (SCOPE_PACKAGE_RE.test(name)) {
function resolveScopePackage(name) {
if (SCOPE_PACKAGE_RE.test(name)) {
return {
org: RegExp.$1,
name: RegExp.$2
};
}
return {
org: RegExp.$1,
name: RegExp.$2
}
}
return null
org: '',
name: ''
};
}
module.exports = ModuleResolver
module.exports.resolveScopePackage = resolveScopePackage
module.exports.getPluginResolver = (cwd) => new ModuleResolver(
'plugin', 'vuepress', [String, Function, Object], true /* load module */, cwd
)
module.exports.getThemeResolver = (cwd) => new ModuleResolver(
'theme', 'vuepress', [String], false /* load module */, cwd
)
exports.resolveScopePackage = resolveScopePackage;
exports.getPluginResolver = (cwd) => new ModuleResolver('plugin', 'vuepress', [String, Function, Object], true /* load module */, cwd);
exports.getThemeResolver = (cwd) => new ModuleResolver('theme', 'vuepress', [String], false /* load module */, cwd);

@@ -1,4 +0,6 @@

module.exports = str => {
const emojiData = require('markdown-it-emoji/lib/data/full.json')
return String(str).replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder)
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const emojiData = require('markdown-it-emoji/lib/data/full.json');
exports.default = (str) => {
return String(str).replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder);
};

@@ -1,12 +0,12 @@

module.exports = function parseFrontmatter (content) {
const matter = require('gray-matter')
const toml = require('toml')
return matter(content, {
excerpt_separator: '<!-- more -->',
engines: {
toml: toml.parse.bind(toml),
excerpt: false
}
})
}
"use strict";
module.exports = function parseFrontmatter(content) {
const matter = require('gray-matter');
const toml = require('toml');
return matter(content, {
excerpt_separator: '<!-- more -->',
engines: {
toml: toml.parse.bind(toml),
excerpt: false
}
});
};

@@ -0,1 +1,8 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const compose_1 = __importDefault(require("./compose"));
const unescapeHtml_1 = __importDefault(require("./unescapeHtml"));
const parseEmojis_1 = __importDefault(require("./parseEmojis"));
// Since VuePress needs to extract the header from the markdown source

@@ -12,17 +19,9 @@ // file and display it in the sidebar or title (#238), this file simply

// wrapped by <code>(markdown token: '`') tag.
const removeMarkdownTokens = str => String(str)
.replace(/\[(.*)\]\(.*\)/, '$1') // []()
.replace(/(`|\*{1,3}|_)(.*?[^\\])\1/g, '$2') // `{t}` | *{t}* | **{t}** | ***{t}*** | _{t}_
.replace(/(\\)(\*|_|`|\!)/g, '$2') // remove escape char '\'
const trim = str => str.trim()
const removeMarkdownTokens = (str) => String(str)
.replace(/\[(.*)\]\(.*\)/, '$1') // []()
.replace(/(`|\*{1,3}|_)(.*?[^\\])\1/g, '$2') // `{t}` | *{t}* | **{t}** | ***{t}*** | _{t}_
.replace(/(\\)(\*|_|`|\!)/g, '$2'); // remove escape char '\'
const trim = (str) => str.trim();
// Unescape html, parse emojis and remove some md tokens.
module.exports = require('./compose')(
require('./unescapeHtml'),
require('./parseEmojis'),
removeMarkdownTokens,
trim
)
const parseHeaders = compose_1.default(unescapeHtml_1.default, parseEmojis_1.default, removeMarkdownTokens, trim);
module.exports = parseHeaders;

@@ -1,24 +0,28 @@

const compiler = require('vue-template-compiler')
const { parse } = require('@vue/component-compiler-utils')
const parseFrontmatter = require('./parseFrontmatter')
function parseStrippedFrontmatter (src) {
src = `---\n${src}\n---`
return parseFrontmatter(src)
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore
const vue_template_compiler_1 = __importDefault(require("vue-template-compiler"));
const component_compiler_utils_1 = require("@vue/component-compiler-utils");
const parseFrontmatter_1 = __importDefault(require("./parseFrontmatter"));
function parseStrippedFrontmatter(src) {
src = `---\n${src}\n---`;
return parseFrontmatter_1.default(src);
}
module.exports = src => {
const output = parse({
source: src,
compiler,
needMap: false
})
const find = output.customBlocks.find(block => block.type === 'frontmatter')
const frontmatterRaw = find && find.content
if (frontmatterRaw) {
return parseStrippedFrontmatter(frontmatterRaw)
}
return {}
exports.parseStrippedFrontmatter = parseStrippedFrontmatter;
function parse(src) {
const output = component_compiler_utils_1.parse({
source: src,
compiler: vue_template_compiler_1.default,
needMap: false
});
const find = output.customBlocks.find(block => block.type === 'frontmatter');
const frontmatterRaw = find && find.content;
if (frontmatterRaw) {
return parseStrippedFrontmatter(frontmatterRaw);
}
return {};
}
module.exports.parseStrippedFrontmatter = parseStrippedFrontmatter
exports.parse = parse;

@@ -1,23 +0,23 @@

const os = require('os')
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const os_1 = __importDefault(require("os"));
class Performance {
constructor () {
this._totalMemory = os.totalmem()
}
start () {
this._startTime = Date.now()
this._startFreeMemory = os.freemem()
}
stop () {
this._endTime = Date.now()
this._endFreeMemory = os.freemem()
return {
duration: this._endTime - this._startTime,
memoryDiff: this._endFreeMemory - this._startFreeMemory
constructor() {
this._totalMemory = os_1.default.totalmem();
}
}
start() {
this._startTime = Date.now();
this._startFreeMemory = os_1.default.freemem();
}
stop() {
this._endTime = Date.now();
this._endFreeMemory = os_1.default.freemem();
return {
duration: this._endTime - this._startTime,
memoryDiff: this._endFreeMemory - this._startFreeMemory
};
}
}
module.exports = new Performance()
module.exports = new Performance();

@@ -0,22 +1,23 @@

"use strict";
// string.js slugify drops non ascii chars so we have to
// use a custom implementation here
const removeDiacritics = require('diacritics').remove
// @ts-ignore
const diacritics_1 = require("diacritics");
// eslint-disable-next-line no-control-regex
const rControl = /[\u0000-\u001f]/g
const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'<>,.?/]+/g
module.exports = function slugify (str) {
return removeDiacritics(str)
// Remove control characters
.replace(rControl, '')
// Replace special characters
.replace(rSpecial, '-')
// Remove continous separators
.replace(/\-{2,}/g, '-')
// Remove prefixing and trailing separtors
.replace(/^\-+|\-+$/g, '')
// ensure it doesn't start with a number (#121)
.replace(/^(\d)/, '_$1')
// lowercase
.toLowerCase()
}
const rControl = /[\u0000-\u001f]/g;
const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'<>,.?/]+/g;
module.exports = function slugify(str) {
return diacritics_1.remove(str)
// Remove control characters
.replace(rControl, '')
// Replace special characters
.replace(rSpecial, '-')
// Remove continous separators
.replace(/\-{2,}/g, '-')
// Remove prefixing and trailing separtors
.replace(/^\-+|\-+$/g, '')
// ensure it doesn't start with a number (#121)
.replace(/^(\d)/, '_$1')
// lowercase
.toLowerCase();
};

@@ -1,7 +0,10 @@

module.exports = function sort (arr) {
return arr.sort((a, b) => {
if (a < b) return -1
if (a > b) return 1
return 0
})
}
"use strict";
module.exports = function sort(arr) {
return arr.sort((a, b) => {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
});
};

@@ -1,18 +0,11 @@

'use strict'
/**
* Module dependencies.
*/
const path = require('upath')
/**
* Normalize path request to absolute path.
*/
module.exports = function toAbsolutePath (raw, cwd = process.cwd()) {
if (path.isAbsolute(raw)) {
return raw
}
return path.resolve(cwd, raw)
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const upath_1 = __importDefault(require("upath"));
module.exports = function toAbsolutePath(raw, cwd = process.cwd()) {
if (upath_1.default.isAbsolute(raw)) {
return raw;
}
return upath_1.default.resolve(cwd, raw);
};

@@ -1,19 +0,19 @@

module.exports = function tryChain (resolvers, arg) {
let response
let error
for (let resolver of resolvers) {
if (!Array.isArray(resolver)) {
resolver = [resolver, true]
"use strict";
module.exports = function tryChain(resolvers, arg) {
let response;
for (let resolver of resolvers) {
if (!Array.isArray(resolver)) {
resolver = [resolver, true];
}
const [provider, condition] = resolver;
if (!condition) {
continue;
}
try {
response = provider(arg);
return response;
}
catch (e) {
}
}
const [provider, condition] = resolver
if (!condition) {
continue
}
try {
response = provider(arg, error)
return response
} catch (e) {
error = e
}
}
}
};

@@ -1,7 +0,7 @@

module.exports = html => String(html)
.replace(/&quot;/g, '"')
.replace(/&#39;/g, '\'')
.replace(/&#x3A;/g, ':')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
"use strict";
module.exports = (html) => String(html)
.replace(/&quot;/g, '"')
.replace(/&#39;/g, '\'')
.replace(/&#x3A;/g, ':')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>');
{
"name": "@vuepress/shared-utils",
"version": "1.0.0-alpha.27",
"version": "1.0.0-alpha.28",
"description": "shared-utils for vuepress",
"main": "index.js",
"main": "lib/index.js",
"types": "types/index.d.ts",
"files": [
"lib",
"types"
],
"scripts": {
"tsc": "tsc",
"update-index": "node scripts/update-index.js"
},
"publishConfig": {

@@ -7,0 +16,0 @@ "access": "public"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc