Socket
Socket
Sign inDemoInstall

@nuxt/utils

Package Overview
Dependencies
Maintainers
5
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuxt/utils - npm Package Compare versions

Comparing version 2.15.8 to 2.16.0

799

dist/utils.js
/*!
* @nuxt/utils v2.15.8 (c) 2016-2021
* @nuxt/utils v2.16.0 (c) 2016-2023
* Released under the MIT License

@@ -9,4 +9,2 @@ * Repository: https://github.com/nuxt/nuxt.js

Object.defineProperty(exports, '__esModule', { value: true });
const ufo = require('ufo');

@@ -26,34 +24,18 @@ const path = require('path');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
const hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
const properlock__default = /*#__PURE__*/_interopDefaultLegacy(properlock);
const onExit__default = /*#__PURE__*/_interopDefaultLegacy(onExit);
const serialize__default = /*#__PURE__*/_interopDefaultLegacy(serialize);
const _createRequire__default = /*#__PURE__*/_interopDefaultLegacy(_createRequire);
const jiti__default = /*#__PURE__*/_interopDefaultLegacy(jiti);
const UAParser__default = /*#__PURE__*/_interopDefaultLegacy(UAParser);
const semver__default = /*#__PURE__*/_interopDefaultLegacy(semver);
const TARGETS = {
server: 'server',
static: 'static'
server: "server",
static: "static"
};
const MODES = {
universal: 'universal',
spa: 'spa'
universal: "universal",
spa: "spa"
};
const getContext = function getContext (req, res) {
return { req, res }
const getContext = function getContext2(req, res) {
return { req, res };
};
const determineGlobals = function determineGlobals (globalName, globals) {
const determineGlobals = function determineGlobals2(globalName, globals) {
const _globals = {};
for (const global in globals) {
if (typeof globals[global] === 'function') {
if (typeof globals[global] === "function") {
_globals[global] = globals[global](globalName);

@@ -64,93 +46,71 @@ } else {

}
return _globals
return _globals;
};
const isFullStatic = function (options) {
return !options.dev && !options._legacyGenerate && options.target === TARGETS.static && options.render.ssr
const isFullStatic = function(options) {
return !options.dev && !options._legacyGenerate && options.target === TARGETS.static && options.render.ssr;
};
const encodeHtml = function encodeHtml (str) {
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
const encodeHtml = function encodeHtml2(str) {
return str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
};
const isString = obj => typeof obj === 'string' || obj instanceof String;
const isNonEmptyString = obj => Boolean(obj && isString(obj));
const isPureObject = obj => !Array.isArray(obj) && typeof obj === 'object';
const isUrl = function isUrl (url) {
return ufo.hasProtocol(url, true)
const isString = (obj) => typeof obj === "string" || obj instanceof String;
const isNonEmptyString = (obj) => Boolean(obj && isString(obj));
const isPureObject = (obj) => !Array.isArray(obj) && typeof obj === "object";
const isUrl = function isUrl2(url) {
return ufo.hasProtocol(url, true);
};
const urlJoin = ufo.joinURL;
/**
* Wraps value in array if it is not already an array
*
* @param {any} value
* @return {array}
*/
const wrapArray = value => Array.isArray(value) ? value : [value];
const wrapArray = (value) => Array.isArray(value) ? value : [value];
const WHITESPACE_REPLACEMENTS = [
[/[ \t\f\r]+\n/g, '\n'], // strip empty indents
[/{\n{2,}/g, '{\n'], // strip start padding from blocks
[/\n{2,}([ \t\f\r]*})/g, '\n$1'], // strip end padding from blocks
[/\n{3,}/g, '\n\n'], // strip multiple blank lines (1 allowed)
[/\n{2,}$/g, '\n'] // strip blank lines EOF (0 allowed)
[/[ \t\f\r]+\n/g, "\n"],
// strip empty indents
[/{\n{2,}/g, "{\n"],
// strip start padding from blocks
[/\n{2,}([ \t\f\r]*})/g, "\n$1"],
// strip end padding from blocks
[/\n{3,}/g, "\n\n"],
// strip multiple blank lines (1 allowed)
[/^\n+/, ""],
// strip blank lines at the beginning of a string
[/\n{2,}$/, "\n"]
// strip blank lines at the end of a string
];
const stripWhitespace = function stripWhitespace (string) {
const stripWhitespace = function stripWhitespace2(string) {
WHITESPACE_REPLACEMENTS.forEach(([regex, newSubstr]) => {
string = string.replace(regex, newSubstr);
});
return string
return string;
};
const lockPaths = new Set();
const lockPaths = /* @__PURE__ */ new Set();
const defaultLockOptions = {
stale: 30000,
onCompromised: err => consola__default['default'].warn(err)
stale: 3e4,
onCompromised: (err) => consola.warn(err)
};
function getLockOptions (options) {
return Object.assign({}, defaultLockOptions, options)
function getLockOptions(options) {
return Object.assign({}, defaultLockOptions, options);
}
function createLockPath ({ id = 'nuxt', dir, root }) {
const sum = hash__default['default'](`${root}-${dir}`);
return path__default['default'].resolve(root, 'node_modules/.cache/nuxt', `${id}-lock-${sum}`)
function createLockPath({ id = "nuxt", dir, root }) {
const sum = hash(`${root}-${dir}`);
return path.resolve(root, "node_modules/.cache/nuxt", `${id}-lock-${sum}`);
}
async function getLockPath (config) {
async function getLockPath(config) {
const lockPath = createLockPath(config);
// the lock is created for the lockPath as ${lockPath}.lock
// so the (temporary) lockPath needs to exist
await fs__default['default'].ensureDir(lockPath);
return lockPath
await fs.ensureDir(lockPath);
return lockPath;
}
async function lock ({ id, dir, root, options }) {
async function lock({ id, dir, root, options }) {
const lockPath = await getLockPath({ id, dir, root });
try {
const locked = await properlock__default['default'].check(lockPath);
const locked = await properlock.check(lockPath);
if (locked) {
consola__default['default'].fatal(`A lock with id '${id}' already exists on ${dir}`);
consola.fatal(`A lock with id '${id}' already exists on ${dir}`);
}
} catch (e) {
consola__default['default'].debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e);
consola.debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e);
}
let lockWasCompromised = false;
let release;
try {
options = getLockOptions(options);
const onCompromised = options.onCompromised;

@@ -161,112 +121,76 @@ options.onCompromised = (err) => {

};
release = await properlock__default['default'].lock(lockPath, options);
} catch (e) {}
release = await properlock.lock(lockPath, options);
} catch (e) {
}
if (!release) {
consola__default['default'].warn(`Unable to get a lock with id '${id}' on ${dir} (but will continue)`);
return false
consola.warn(`Unable to get a lock with id '${id}' on ${dir} (but will continue)`);
return false;
}
if (!lockPaths.size) {
// make sure to always cleanup our temporary lockPaths
onExit__default['default'](() => {
for (const lockPath of lockPaths) {
fs__default['default'].removeSync(lockPath);
onExit(() => {
for (const lockPath2 of lockPaths) {
fs.removeSync(lockPath2);
}
});
}
lockPaths.add(lockPath);
return async function lockRelease () {
return async function lockRelease() {
try {
await fs__default['default'].remove(lockPath);
await fs.remove(lockPath);
lockPaths.delete(lockPath);
// release as last so the lockPath is still removed
// when it fails on a compromised lock
await release();
} catch (e) {
if (!lockWasCompromised || !e.message.includes('already released')) {
consola__default['default'].debug(e);
return
if (!lockWasCompromised || !e.message.includes("already released")) {
consola.debug(e);
return;
}
// proper-lockfile doesnt remove lockDir when lock is compromised
// removing it here could cause the 'other' process to throw an error
// as well, but in our case its much more likely the lock was
// compromised due to mtime update timeouts
const lockDir = `${lockPath}.lock`;
if (await fs__default['default'].exists(lockDir)) {
await fs__default['default'].remove(lockDir);
if (await fs.exists(lockDir)) {
await fs.remove(lockDir);
}
}
}
};
}
const startsWithAlias = aliasArray => str => aliasArray.some(c => str.startsWith(c));
const startsWithSrcAlias = startsWithAlias(['@', '~']);
const startsWithRootAlias = startsWithAlias(['@@', '~~']);
const isWindows = process.platform.startsWith('win');
const wp = function wp (p = '') {
const startsWithAlias = (aliasArray) => (str) => aliasArray.some((c) => str.startsWith(c));
const startsWithSrcAlias = startsWithAlias(["@", "~"]);
const startsWithRootAlias = startsWithAlias(["@@", "~~"]);
const isWindows = process.platform.startsWith("win");
const wp = function wp2(p = "") {
if (isWindows) {
return p.replace(/\\/g, '\\\\')
return p.replace(/\\/g, "\\\\");
}
return p
return p;
};
// Kept for backward compat (modules may use it from template context)
const wChunk = function wChunk (p = '') {
return p
const wChunk = function wChunk2(p = "") {
return p;
};
const reqSep = /\//g;
const sysSep = lodash.escapeRegExp(path__default['default'].sep);
const normalize = string => string.replace(reqSep, sysSep);
const r = function r (...args) {
const sysSep = lodash.escapeRegExp(path.sep);
const normalize = (string) => string.replace(reqSep, sysSep);
const r = function r2(...args) {
const lastArg = args[args.length - 1];
if (startsWithSrcAlias(lastArg)) {
return wp(lastArg)
return wp(lastArg);
}
return wp(path__default['default'].resolve(...args.map(normalize)))
return wp(path.resolve(...args.map(normalize)));
};
const relativeTo = function relativeTo (...args) {
const relativeTo = function relativeTo2(...args) {
const dir = args.shift();
// Keep webpack inline loader intact
if (args[0].includes('!')) {
const loaders = args.shift().split('!');
return loaders.concat(relativeTo(dir, loaders.pop(), ...args)).join('!')
if (args[0].includes("!")) {
const loaders = args.shift().split("!");
return loaders.concat(relativeTo2(dir, loaders.pop(), ...args)).join("!");
}
// Resolve path
const resolvedPath = r(...args);
// Check if path is an alias
if (startsWithSrcAlias(resolvedPath)) {
return resolvedPath
return resolvedPath;
}
// Make correct relative path
let rp = path__default['default'].relative(dir, resolvedPath);
if (rp[0] !== '.') {
rp = '.' + path__default['default'].sep + rp;
let rp = path.relative(dir, resolvedPath);
if (rp[0] !== ".") {
rp = "." + path.sep + rp;
}
return wp(rp)
return wp(rp);
};
function defineAlias (src, target, prop, opts = {}) {
function defineAlias(src, target, prop, opts = {}) {
const { bind = true, warn = false } = opts;
if (Array.isArray(prop)) {

@@ -276,12 +200,9 @@ for (const p of prop) {

}
return
return;
}
let targetVal = target[prop];
if (bind && typeof targetVal === 'function') {
if (bind && typeof targetVal === "function") {
targetVal = targetVal.bind(target);
}
let warned = false;
Object.defineProperty(src, prop, {

@@ -291,31 +212,27 @@ get: () => {

warned = true;
consola__default['default'].warn({
consola.warn({
message: `'${prop}' is deprecated'`,
// eslint-disable-next-line unicorn/error-message
additional: new Error().stack.split('\n').splice(2).join('\n')
additional: new Error().stack.split("\n").splice(2).join("\n")
});
}
return targetVal
return targetVal;
}
});
}
const isIndex = s => /(.*)\/index\.[^/]+$/.test(s);
function isIndexFileAndFolder (pluginFiles) {
// Return early in case the matching file count exceeds 2 (index.js + folder)
const isIndex = (s) => /(.*)\/index\.[^/]+$/.test(s);
function isIndexFileAndFolder(pluginFiles) {
if (pluginFiles.length !== 2) {
return false
return false;
}
return pluginFiles.some(isIndex)
return pluginFiles.some(isIndex);
}
const getMainModule = () => {
return (require && require.main) || (module && module.main) || module
return require && require.main || module && module.main || module;
};
const routeChildren = function (route) {
const hasChildWithEmptyPath = route.children.some(child => child.path === '');
const routeChildren = function(route) {
const hasChildWithEmptyPath = route.children.some((child) => child.path === "");
if (hasChildWithEmptyPath) {
return route.children
return route.children;
}

@@ -326,22 +243,19 @@ return [

...route,
children: undefined
children: void 0
},
...route.children
]
];
};
const flatRoutes = function flatRoutes (router, fileName = '', routes = []) {
router.forEach((r) => {
if ([':', '*'].some(c => r.path.includes(c))) {
return
const flatRoutes = function flatRoutes2(router, fileName = "", routes = []) {
router.forEach((r2) => {
if ([":", "*"].some((c) => r2.path.includes(c))) {
return;
}
const route = `${fileName}${r.path}/`.replace(/\/+/g, '/');
if (r.children) {
return flatRoutes(routeChildren(r), route, routes)
const route = `${fileName}${r2.path}/`.replace(/\/+/g, "/");
if (r2.children) {
return flatRoutes2(routeChildren(r2), route, routes);
}
// if child path is already absolute, do not make any concatenations
if (r.path && r.path.startsWith('/')) {
routes.push(r.path);
} else if (route !== '/' && route[route.length - 1] === '/') {
if (r2.path && r2.path.startsWith("/")) {
routes.push(r2.path);
} else if (route !== "/" && route[route.length - 1] === "/") {
routes.push(route.slice(0, -1));

@@ -352,7 +266,5 @@ } else {

});
return routes
return routes;
};
// eslint-disable-next-line default-param-last
function cleanChildrenRoutes (routes, isChild = false, routeNameSplitter = '-', trailingSlash, parentRouteName) {
function cleanChildrenRoutes(routes, isChild = false, routeNameSplitter = "-", trailingSlash, parentRouteName) {
const regExpIndex = new RegExp(`${routeNameSplitter}index$`);

@@ -362,4 +274,4 @@ const regExpParentRouteName = new RegExp(`^${parentRouteName}${routeNameSplitter}`);

routes.forEach((route) => {
if (regExpIndex.test(route.name) || route.name === 'index') {
const res = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter);
if (regExpIndex.test(route.name) || route.name === "index") {
const res = route.name.replace(regExpParentRouteName, "").split(routeNameSplitter);
routesIndex.push(res);

@@ -369,21 +281,21 @@ }

routes.forEach((route) => {
route.path = isChild ? route.path.replace('/', '') : route.path;
if (route.path.includes('?')) {
route.path = isChild ? route.path.replace("/", "") : route.path;
if (route.path.includes("?")) {
if (route.name.endsWith(`${routeNameSplitter}index`)) {
route.path = route.path.replace(/\?$/, '');
route.path = route.path.replace(/\?\/?$/, trailingSlash ? "/" : "");
}
const names = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter);
const paths = route.path.split('/');
const names = route.name.replace(regExpParentRouteName, "").split(routeNameSplitter);
const paths = route.path.split("/");
if (!isChild) {
paths.shift();
} // clean first / for parents
routesIndex.forEach((r) => {
const i = r.indexOf('index');
}
routesIndex.forEach((r2) => {
const i = r2.indexOf("index");
if (i < paths.length) {
for (let a = 0; a <= i; a++) {
if (a === i) {
paths[a] = paths[a].replace('?', '');
paths[a] = paths[a].replace("?", "");
}
if (a < i && names[a] !== r[a]) {
break
if (a < i && names[a] !== r2[a]) {
break;
}

@@ -393,7 +305,7 @@ }

});
route.path = (isChild ? '' : '/') + paths.join('/');
route.path = (isChild ? "" : "/") + paths.join("/");
}
route.name = route.name.replace(regExpIndex, '');
route.name = route.name.replace(regExpIndex, "");
if (route.children) {
const defaultChildRoute = route.children.find(child => child.path === '/' || child.path === '');
const defaultChildRoute = route.children.find((child) => child.path === "/" || child.path === "");
const routeName = route.name;

@@ -403,5 +315,5 @@ if (defaultChildRoute) {

if (child.path !== defaultChildRoute.path) {
const parts = child.path.split('/');
parts[1] = parts[1].endsWith('?') ? parts[1].substr(0, parts[1].length - 1) : parts[1];
child.path = parts.join('/');
const parts = child.path.split("/");
parts[1] = parts[1].endsWith("?") ? parts[1].substr(0, parts[1].length - 1) : parts[1];
child.path = parts.join("/");
}

@@ -414,24 +326,19 @@ });

});
return routes
return routes;
}
const DYNAMIC_ROUTE_REGEX = /^\/([:*])/;
const sortRoutes = function sortRoutes (routes) {
const sortRoutes = function sortRoutes2(routes) {
routes.sort((a, b) => {
if (!a.path.length) {
return -1
return -1;
}
if (!b.path.length) {
return 1
return 1;
}
// Order: /static, /index, /:dynamic
// Match exact route before index: /login before /index/_slug
if (a.path === '/') {
return DYNAMIC_ROUTE_REGEX.test(b.path) ? -1 : 1
if (a.path === "/") {
return DYNAMIC_ROUTE_REGEX.test(b.path) ? -1 : 1;
}
if (b.path === '/') {
return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1
if (b.path === "/") {
return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1;
}
let i;

@@ -441,48 +348,33 @@ let res = 0;

let z = 0;
const _a = a.path.split('/');
const _b = b.path.split('/');
const _a = a.path.split("/");
const _b = b.path.split("/");
for (i = 0; i < _a.length; i++) {
if (res !== 0) {
break
break;
}
y = _a[i] === '*' ? 2 : _a[i].includes(':') ? 1 : 0;
z = _b[i] === '*' ? 2 : _b[i].includes(':') ? 1 : 0;
y = _a[i] === "*" ? 2 : _a[i].includes(":") ? 1 : 0;
z = _b[i] === "*" ? 2 : _b[i].includes(":") ? 1 : 0;
res = y - z;
// If a.length >= b.length
if (i === _b.length - 1 && res === 0) {
// unless * found sort by level, then alphabetically
res = _a[i] === '*'
? -1
: (
_a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
);
res = _a[i] === "*" ? -1 : _a.length === _b.length ? a.path.localeCompare(b.path) : _a.length - _b.length;
}
}
if (res === 0) {
// unless * found sort by level, then alphabetically
res = _a[i - 1] === '*' && _b[i]
? 1
: (
_a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
);
res = _a[i - 1] === "*" && _b[i] ? 1 : _a.length === _b.length ? a.path.localeCompare(b.path) : _a.length - _b.length;
}
return res
return res;
});
routes.forEach((route) => {
if (route.children) {
sortRoutes(route.children);
sortRoutes2(route.children);
}
});
return routes
return routes;
};
const createRoutes = function createRoutes ({
const createRoutes = function createRoutes2({
files,
srcDir,
pagesDir = '',
routeNameSplitter = '-',
supportedExtensions = ['vue', 'js'],
pagesDir = "",
routeNameSplitter = "-",
supportedExtensions = ["vue", "js"],
trailingSlash

@@ -492,37 +384,27 @@ }) {

files.forEach((file) => {
const keys = file
.replace(new RegExp(`^${pagesDir}`), '')
.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '')
.replace(/\/{2,}/g, '/')
.split('/')
.slice(1);
const route = { name: '', path: '', component: r(srcDir, file) };
const keys = file.replace(new RegExp(`^${pagesDir}`), "").replace(new RegExp(`\\.(${supportedExtensions.join("|")})$`), "").replace(/\/{2,}/g, "/").split("/").slice(1);
const route = { name: "", path: "", component: r(srcDir, file) };
let parent = routes;
keys.forEach((key, i) => {
// remove underscore only, if its the prefix
const sanitizedKey = key.startsWith('_') ? key.substr(1) : key;
route.name = route.name
? route.name + routeNameSplitter + sanitizedKey
: sanitizedKey;
route.name += key === '_' ? 'all' : '';
route.chunkName = file.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '');
const child = parent.find(parentRoute => parentRoute.name === route.name);
const sanitizedKey = key.startsWith("_") ? key.substr(1) : key;
route.name = route.name ? route.name + routeNameSplitter + sanitizedKey : sanitizedKey;
route.name += key === "_" ? "all" : "";
route.chunkName = file.replace(new RegExp(`\\.(${supportedExtensions.join("|")})$`), "");
const child = parent.find((parentRoute) => parentRoute.name === route.name);
if (child) {
child.children = child.children || [];
parent = child.children;
route.path = '';
} else if (key === 'index' && i + 1 === keys.length) {
route.path += i > 0 ? '' : '/';
route.path = "";
} else if (key === "index" && i + 1 === keys.length) {
route.path += i > 0 ? "" : "/";
} else {
route.path += '/' + ufo.normalizeURL(getRoutePathExtension(key));
if (key.startsWith('_') && key.length > 1) {
route.path += '?';
route.path += "/" + ufo.normalizeURL(getRoutePathExtension(key));
if (key.startsWith("_") && key.length > 1) {
route.path += "?";
}
}
});
if (trailingSlash !== undefined) {
if (trailingSlash !== void 0) {
route.pathToRegexpOptions = { ...route.pathToRegexpOptions, strict: true };
if (trailingSlash && !route.path.endsWith('*')) {
if (trailingSlash && !route.path.endsWith("*")) {
route.path = ufo.withTrailingSlash(route.path);

@@ -533,50 +415,29 @@ } else {

}
parent.push(route);
});
sortRoutes(routes);
return cleanChildrenRoutes(routes, false, routeNameSplitter, trailingSlash)
return cleanChildrenRoutes(routes, false, routeNameSplitter, trailingSlash);
};
// Guard dir1 from dir2 which can be indiscriminately removed
const guardDir = function guardDir (options, key1, key2) {
const guardDir = function guardDir2(options, key1, key2) {
const dir1 = lodash.get(options, key1, false);
const dir2 = lodash.get(options, key2, false);
if (
dir1 &&
dir2 &&
(
dir1 === dir2 ||
(
dir1.startsWith(dir2) &&
!path__default['default'].basename(dir1).startsWith(path__default['default'].basename(dir2))
)
)
) {
if (dir1 && dir2 && (dir1 === dir2 || dir1.startsWith(dir2) && !path.basename(dir1).startsWith(path.basename(dir2)))) {
const errorMessage = `options.${key2} cannot be a parent of or same as ${key1}`;
consola__default['default'].fatal(errorMessage);
throw new Error(errorMessage)
consola.fatal(errorMessage);
throw new Error(errorMessage);
}
};
const getRoutePathExtension = (key) => {
if (key === '_') {
return '*'
if (key === "_") {
return "*";
}
if (key.startsWith('_')) {
return `:${key.substr(1)}`
if (key.startsWith("_")) {
return `:${key.substr(1)}`;
}
return key
return key;
};
const promisifyRoute = function promisifyRoute (fn, ...args) {
// If routes is an array
const promisifyRoute = function promisifyRoute2(fn, ...args) {
if (Array.isArray(fn)) {
return Promise.resolve(fn)
return Promise.resolve(fn);
}
// If routes is a function expecting a callback
if (fn.length === arguments.length) {

@@ -590,27 +451,24 @@ return new Promise((resolve, reject) => {

}, ...args);
})
});
}
let promise = fn(...args);
if (
!promise ||
(!(promise instanceof Promise) && typeof promise.then !== 'function')
) {
if (!promise || !(promise instanceof Promise) && typeof promise.then !== "function") {
promise = Promise.resolve(promise);
}
return promise
return promise;
};
function normalizeFunctions (obj) {
if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) {
return obj
function normalizeFunctions(obj) {
if (typeof obj !== "object" || Array.isArray(obj) || obj === null) {
return obj;
}
for (const key in obj) {
if (key === '__proto__' || key === 'constructor') {
continue
if (key === "__proto__" || key === "constructor") {
continue;
}
const val = obj[key];
if (val !== null && typeof val === 'object' && !Array.isArray(obj)) {
if (val !== null && typeof val === "object" && !Array.isArray(obj)) {
obj[key] = normalizeFunctions(val);
}
if (typeof obj[key] === 'function') {
if (typeof obj[key] === "function") {
const asString = obj[key].toString();

@@ -624,77 +482,61 @@ const match = asString.match(/^([^{(]+)=>\s*([\0-\uFFFF]*)/);

}
// eslint-disable-next-line no-new-func
obj[key] = new Function(...match[1].split(',').map(arg => arg.trim()), functionBody);
obj[key] = new Function(...match[1].split(",").map((arg) => arg.trim()), functionBody);
}
}
}
return obj
return obj;
}
function serializeFunction (func) {
function serializeFunction(func) {
let open = false;
func = normalizeFunctions(func);
return serialize__default['default'](func)
.replace(serializeFunction.assignmentRE, (_, spaces) => {
return `${spaces}: function (`
})
.replace(serializeFunction.internalFunctionRE, (_, spaces, name, args) => {
if (open) {
return `${spaces}${name}: function (${args}) {`
} else {
open = true;
return _
}
})
.replace(new RegExp(`${(func.name || 'function').replace('$', '\\$')}\\s*\\(`), 'function(')
.replace('function function', 'function')
return serialize(func).replace(serializeFunction.assignmentRE, (_, spaces) => {
return `${spaces}: function (`;
}).replace(serializeFunction.internalFunctionRE, (_, spaces, name, args) => {
if (open) {
return `${spaces}${name}: function (${args}) {`;
} else {
open = true;
return _;
}
}).replace(new RegExp(`${(func.name || "function").replace("$", "\\$")}\\s*\\(`), "function(").replace("function function", "function");
}
serializeFunction.internalFunctionRE = /^(\s*)(?!(?:if)|(?:for)|(?:while)|(?:switch)|(?:catch))(\w+)\s*\((.*?)\)\s*\{/gm;
serializeFunction.assignmentRE = /^(\s*):(\w+)\(/gm;
const sequence = function sequence (tasks, fn) {
const sequence = function sequence2(tasks, fn) {
return tasks.reduce(
(promise, task) => promise.then(() => fn(task)),
Promise.resolve()
)
);
};
const parallel = function parallel (tasks, fn) {
return Promise.all(tasks.map(fn))
const parallel = function parallel2(tasks, fn) {
return Promise.all(tasks.map(fn));
};
const chainFn = function chainFn (base, fn) {
if (typeof fn !== 'function') {
return base
const chainFn = function chainFn2(base, fn) {
if (typeof fn !== "function") {
return base;
}
if (typeof base !== 'function') {
return fn
if (typeof base !== "function") {
return fn;
}
return function (arg0, ...args) {
return function(arg0, ...args) {
const next = (previous = arg0) => {
const fnResult = fn.call(this, previous, ...args);
if (fnResult && typeof fnResult.then === 'function') {
return fnResult.then(res => res || previous)
if (fnResult && typeof fnResult.then === "function") {
return fnResult.then((res) => res || previous);
}
return fnResult || previous
return fnResult || previous;
};
const baseResult = base.call(this, arg0, ...args);
if (baseResult && typeof baseResult.then === 'function') {
return baseResult.then(res => next(res))
if (baseResult && typeof baseResult.then === "function") {
return baseResult.then((res) => next(res));
}
return next(baseResult)
}
return next(baseResult);
};
};
async function promiseFinally (fn, finalFn) {
async function promiseFinally(fn, finalFn) {
let result;
try {
if (typeof fn === 'function') {
if (typeof fn === "function") {
result = await fn();

@@ -707,6 +549,5 @@ } else {

}
return result
return result;
}
const timeout = function timeout (fn, ms, msg) {
const timeout = function timeout2(fn, ms, msg) {
let timerId;

@@ -717,14 +558,12 @@ const warpPromise = promiseFinally(fn, () => clearTimeout(timerId));

});
return Promise.race([warpPromise, timerPromise])
return Promise.race([warpPromise, timerPromise]);
};
const waitFor = function waitFor (ms) {
return new Promise(resolve => setTimeout(resolve, ms || 0))
const waitFor = function waitFor2(ms) {
return new Promise((resolve) => setTimeout(resolve, ms || 0));
};
class Timer {
constructor () {
this._times = new Map();
constructor() {
this._times = /* @__PURE__ */ new Map();
}
start (name, description) {
start(name, description) {
const time = {

@@ -736,6 +575,5 @@ name,

this._times.set(name, time);
return time
return time;
}
end (name) {
end(name) {
if (this._times.has(name)) {

@@ -745,18 +583,14 @@ const time = this._times.get(name);

this._times.delete(name);
return time
return time;
}
}
hrtime (start) {
const useBigInt = typeof process.hrtime.bigint === 'function';
hrtime(start) {
const useBigInt = typeof process.hrtime.bigint === "function";
if (start) {
const end = useBigInt ? process.hrtime.bigint() : process.hrtime(start);
return useBigInt
? (end - start) / BigInt(1000000)
: (end[0] * 1e3) + (end[1] * 1e-6)
return useBigInt ? (end - start) / BigInt(1e6) : end[0] * 1e3 + end[1] * 1e-6;
}
return useBigInt ? process.hrtime.bigint() : process.hrtime()
return useBigInt ? process.hrtime.bigint() : process.hrtime();
}
clear () {
clear() {
this._times.clear();

@@ -767,38 +601,27 @@ }

const createRequire = (filename, useJiti = global.__NUXT_DEV__) => {
if (useJiti && typeof jest === 'undefined') {
return jiti__default['default'](filename)
if (useJiti && typeof jest === "undefined") {
return jiti(filename);
}
return _createRequire__default['default'](filename)
return _createRequire(filename);
};
const _require = createRequire();
function isHMRCompatible (id) {
return !/[/\\]mongoose[/\\/]/.test(id)
function isHMRCompatible(id) {
return !/[/\\]mongoose[/\\/]/.test(id);
}
function isExternalDependency (id) {
return /[/\\]node_modules[/\\]/.test(id)
function isExternalDependency(id) {
return /[/\\]node_modules[/\\]/.test(id);
}
function clearRequireCache (id) {
function clearRequireCache(id) {
if (isExternalDependency(id) && isHMRCompatible(id)) {
return
return;
}
const entry = getRequireCacheItem(id);
if (!entry) {
delete _require.cache[id];
return
return;
}
if (entry.parent) {
entry.parent.children = entry.parent.children.filter(e => e.id !== id);
entry.parent.children = entry.parent.children.filter((e) => e.id !== id);
}
// Needs to be cleared before children, to protect against circular deps (#7966)
delete _require.cache[id];
for (const child of entry.children) {

@@ -808,113 +631,97 @@ clearRequireCache(child.id);

}
function scanRequireTree (id, files = new Set()) {
function scanRequireTree(id, files = /* @__PURE__ */ new Set()) {
if (isExternalDependency(id) || files.has(id)) {
return files
return files;
}
const entry = getRequireCacheItem(id);
if (!entry) {
files.add(id);
return files
return files;
}
files.add(entry.id);
for (const child of entry.children) {
scanRequireTree(child.id, files);
}
return files
return files;
}
function getRequireCacheItem (id) {
function getRequireCacheItem(id) {
try {
return _require.cache[id]
return _require.cache[id];
} catch (e) {
}
}
function resolveModule (id, paths) {
if (typeof paths === 'string') {
function resolveModule(id, paths) {
if (typeof paths === "string") {
paths = [paths];
}
return _require.resolve(id, {
paths: [].concat(...(global.__NUXT_PREPATHS__ || []), paths || [], global.__NUXT_PATHS__ || [], process.cwd())
})
paths: [].concat(...global.__NUXT_PREPATHS__ || [], paths || [], global.__NUXT_PATHS__ || [], process.cwd())
});
}
function requireModule (id, paths) {
return _require(resolveModule(id, paths))
function requireModule(id, paths) {
return _require(resolveModule(id, paths));
}
function tryRequire (id, paths) {
try { return requireModule(id, paths) } catch (e) { }
function tryRequire(id, paths) {
try {
return requireModule(id, paths);
} catch (e) {
}
}
function tryResolve (id, paths) {
try { return resolveModule(id, paths) } catch (e) { }
function tryResolve(id, paths) {
try {
return resolveModule(id, paths);
} catch (e) {
}
}
function getPKG (id, paths) {
return tryRequire(path.join(id, 'package.json'), paths)
function getPKG(id, paths) {
return tryRequire(path.join(id, "package.json"), paths);
}
const ModernBrowsers = {
Edge: '16',
Firefox: '60',
Chrome: '61',
'Chrome Headless': '61',
Chromium: '61',
Iron: '61',
Safari: '10.1',
Opera: '48',
Yandex: '18',
Vivaldi: '1.14',
'Mobile Safari': '10.3'
Edge: "16",
Firefox: "60",
Chrome: "61",
"Chrome Headless": "61",
Chromium: "61",
Iron: "61",
Safari: "10.1",
Opera: "48",
Yandex: "18",
Vivaldi: "1.14",
"Mobile Safari": "10.3"
};
let __modernBrowsers;
const getModernBrowsers = () => {
if (__modernBrowsers) {
return __modernBrowsers
return __modernBrowsers;
}
__modernBrowsers = Object.keys(ModernBrowsers)
.reduce((allBrowsers, browser) => {
allBrowsers[browser] = semver__default['default'].coerce(ModernBrowsers[browser]);
return allBrowsers
}, {});
return __modernBrowsers
__modernBrowsers = Object.keys(ModernBrowsers).reduce((allBrowsers, browser) => {
allBrowsers[browser] = semver.coerce(ModernBrowsers[browser]);
return allBrowsers;
}, {});
return __modernBrowsers;
};
const isModernBrowser = (ua) => {
if (!ua) {
return false
return false;
}
const { browser } = UAParser__default['default'](ua);
const browserVersion = semver__default['default'].coerce(browser.version);
const { browser } = UAParser(ua);
const browserVersion = semver.coerce(browser.version);
if (!browserVersion) {
return false
return false;
}
const modernBrowsers = getModernBrowsers();
return Boolean(modernBrowsers[browser.name] && semver__default['default'].gte(browserVersion, modernBrowsers[browser.name]))
return Boolean(modernBrowsers[browser.name] && semver.gte(browserVersion, modernBrowsers[browser.name]));
};
const isModernRequest = (req, modernMode = false) => {
if (modernMode === false) {
return false
return false;
}
const { socket = {}, headers } = req;
if (socket._modern === undefined) {
const ua = headers && headers['user-agent'];
if (socket._modern === void 0) {
const ua = headers && headers["user-agent"];
socket._modern = isModernBrowser(ua);
}
return socket._modern
return socket._modern;
};
// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
const safariNoModuleFix = '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();';

@@ -921,0 +728,0 @@

{
"name": "@nuxt/utils",
"version": "2.15.8",
"version": "2.16.0",
"repository": "nuxt/nuxt.js",

@@ -13,12 +13,12 @@ "license": "MIT",

"create-require": "^1.1.1",
"fs-extra": "^9.1.0",
"fs-extra": "^10.1.0",
"hash-sum": "^2.0.0",
"jiti": "^1.9.2",
"jiti": "^1.16.2",
"lodash": "^4.17.21",
"proper-lockfile": "^4.1.2",
"semver": "^7.3.5",
"serialize-javascript": "^5.0.1",
"signal-exit": "^3.0.3",
"ua-parser-js": "^0.7.28",
"ufo": "^0.7.4"
"semver": "^7.3.8",
"serialize-javascript": "^6.0.1",
"signal-exit": "^3.0.7",
"ua-parser-js": "^1.0.33",
"ufo": "^1.0.1"
},

@@ -25,0 +25,0 @@ "publishConfig": {

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