From a8fc68fec03c9eef33fe11b42aa99c82ff1160a4 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 20 Jan 2021 20:54:13 +0100 Subject: [PATCH] chore: remove unused utils --- packages/nuxt3/src/utils/index.ts | 4 - packages/nuxt3/src/utils/locking.ts | 121 -------------- packages/nuxt3/src/utils/modern.ts | 83 --------- packages/nuxt3/src/utils/route.ts | 231 -------------------------- packages/nuxt3/src/utils/serialize.ts | 61 ------- packages/nuxt3/src/utils/timer.ts | 93 ----------- 6 files changed, 593 deletions(-) delete mode 100644 packages/nuxt3/src/utils/locking.ts delete mode 100644 packages/nuxt3/src/utils/modern.ts delete mode 100644 packages/nuxt3/src/utils/serialize.ts delete mode 100644 packages/nuxt3/src/utils/timer.ts diff --git a/packages/nuxt3/src/utils/index.ts b/packages/nuxt3/src/utils/index.ts index 06dc05af2f..0010fadcc5 100644 --- a/packages/nuxt3/src/utils/index.ts +++ b/packages/nuxt3/src/utils/index.ts @@ -1,11 +1,7 @@ export * from './context' export * from './lang' -// export * from './locking' export * from './resolve' export * from './route' -// export * from './serialize' export * from './task' -// export * from './timer' export * from './cjs' -// export * from './modern' export * from './constants' diff --git a/packages/nuxt3/src/utils/locking.ts b/packages/nuxt3/src/utils/locking.ts deleted file mode 100644 index f976586e8a..0000000000 --- a/packages/nuxt3/src/utils/locking.ts +++ /dev/null @@ -1,121 +0,0 @@ -import path from 'path' -import consola from 'consola' -import hash from 'hash-sum' -import fs from 'fs-extra' -import properlock, { LockOptions } from 'proper-lockfile' -import onExit from 'signal-exit' - -export const lockPaths = new Set() - -export const defaultLockOptions: Required< - Pick -> = { - stale: 30000, - onCompromised: err => consola.warn(err) -} - -export function getLockOptions (options: Partial) { - return Object.assign({}, defaultLockOptions, options) -} - -interface NuxtLockOptions { - id?: string - dir: string - root: string - options?: LockOptions -} - -export function createLockPath ({ - id = 'nuxt', - dir, - root -}: Pick) { - const sum = hash(`${root}-${dir}`) - - return path.resolve(root, 'node_modules/.cache/nuxt', `${id}-lock-${sum}`) -} - -export async function getLockPath ( - config: Pick -) { - const lockPath = createLockPath(config) - - // the lock is created for the lockPath as ${lockPath}.lock - // so the (temporary) lockPath needs to exist - await fs.ensureDir(lockPath) - - return lockPath -} - -export async function lock ({ id, dir, root, options }: NuxtLockOptions) { - const lockPath = await getLockPath({ - id, - dir, - root - }) - - try { - const locked = await properlock.check(lockPath) - if (locked) { - consola.fatal(`A lock with id '${id}' already exists on ${dir}`) - } - } catch (e) { - consola.debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e) - } - - let lockWasCompromised = false - let release: (() => Promise) | undefined - - try { - options = getLockOptions(options) - - const onCompromised = options.onCompromised - options.onCompromised = (err) => { - onCompromised(err) - lockWasCompromised = true - } - - release = await properlock.lock(lockPath, options) - } catch (e) {} - - if (!release) { - 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(() => { - for (const lockPath of lockPaths) { - fs.removeSync(lockPath) - } - }) - } - - lockPaths.add(lockPath) - - return async function lockRelease () { - try { - 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.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.pathExists(lockDir)) { - await fs.remove(lockDir) - } - } - } -} diff --git a/packages/nuxt3/src/utils/modern.ts b/packages/nuxt3/src/utils/modern.ts deleted file mode 100644 index 02ce8441a6..0000000000 --- a/packages/nuxt3/src/utils/modern.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type { IncomingMessage } from 'http' -import { UAParser } from 'ua-parser-js' - -import type { SemVer } from 'semver' - -export 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' -} as const - -type ModernBrowsersT = { -readonly [key in keyof typeof ModernBrowsers]: SemVer } - -let semver: typeof import('semver') -let __modernBrowsers: ModernBrowsersT - -const getModernBrowsers = () => { - if (__modernBrowsers) { - return __modernBrowsers - } - - __modernBrowsers = (Object.keys(ModernBrowsers) as Array< - keyof typeof ModernBrowsers - >).reduce( - (allBrowsers, browser) => { - const version = semver.coerce(ModernBrowsers[browser]) - if (version) { allBrowsers[browser] = version } - return allBrowsers - }, - {} as ModernBrowsersT - ) - return __modernBrowsers -} - -interface NuxtRequest extends IncomingMessage { - socket: IncomingMessage['socket'] & { - _modern?: boolean - } -} - -export const isModernBrowser = (ua: string) => { - if (!ua) { - return false - } - if (!semver) { - semver = require('semver') - } - const browser = new UAParser(ua).getBrowser() - const browserVersion = semver.coerce(browser.version) - if (!browserVersion) { - return false - } - const modernBrowsers = getModernBrowsers() - const name = browser.name as keyof typeof modernBrowsers - return Boolean( - name && name in modernBrowsers && semver.gte(browserVersion, modernBrowsers[name]) - ) -} - -export const isModernRequest = (req: NuxtRequest, modernMode: boolean | string = false) => { - if (modernMode === false) { - return false - } - - const { socket = {} as NuxtRequest['socket'], headers } = req - if (socket._modern === undefined) { - const ua = headers && headers['user-agent'] - socket._modern = ua && isModernBrowser(ua) - } - - return socket._modern -} - -// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc -export 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()}}();' diff --git a/packages/nuxt3/src/utils/route.ts b/packages/nuxt3/src/utils/route.ts index 1e8819a4ba..c3d443196f 100644 --- a/packages/nuxt3/src/utils/route.ts +++ b/packages/nuxt3/src/utils/route.ts @@ -7,144 +7,6 @@ import type { _RouteRecordBase } from 'vue-router' import { r } from './resolve' -export const flatRoutes = function flatRoutes (router, fileName = '', routes: string[] = []) { - router.forEach((r) => { - if ([':', '*'].some(c => r.path.includes(c))) { - return - } - if (r.children) { - if (fileName === '' && r.path === '/') { - routes.push('/') - } - - return flatRoutes(r.children, fileName + r.path + '/', routes) - } - fileName = fileName.replace(/\/+/g, '/') - - // if child path is already absolute, do not make any concatenations - if (r.path && r.path.startsWith('/')) { - routes.push(r.path) - } else if (r.path === '' && fileName[fileName.length - 1] === '/') { - routes.push(fileName.slice(0, -1) + r.path) - } else { - routes.push(fileName + r.path) - } - }) - return routes -} - -function cleanChildrenRoutes (routes: NuxtRouteConfig[], isChild = false, routeNameSplitter = '-') { - let start = -1 - const regExpIndex = new RegExp(`${routeNameSplitter}index$`) - const routesIndex: string[][] = [] - routes.forEach((route) => { - if (route.name && typeof route.name === 'string' && (regExpIndex.test(route.name) || route.name === 'index')) { - // Save indexOf 'index' key in name - const res = route.name.split(routeNameSplitter) - const s = res.indexOf('index') - start = start === -1 || s < start ? s : start - routesIndex.push(res) - } - }) - routes.forEach((route) => { - route.path = isChild ? route.path.replace('/', '') : route.path - if (route.path.includes('?')) { - const names = typeof route.name === 'string' ? route.name.split(routeNameSplitter) : [] - const paths = route.path.split('/') - if (!isChild) { - paths.shift() - } // clean first / for parents - routesIndex.forEach((r) => { - const i = r.indexOf('index') - start // children names - if (i < paths.length) { - for (let a = 0; a <= i; a++) { - if (a === i) { - paths[a] = paths[a].replace('?', '') - } - if (a < i && names[a] !== r[a]) { - break - } - } - } - }) - route.path = (isChild ? '' : '/') + paths.join('/') - } - if (route.name) { - route.name = typeof route.name === 'string' && route.name.replace(regExpIndex, '') - } - if (route.children) { - if (route.children.find(child => child.path === '')) { - delete route.name - } - route.children = cleanChildrenRoutes(route.children, true, routeNameSplitter) - } - }) - return routes -} - -const DYNAMIC_ROUTE_REGEX = /^\/([:*])/ - -export const sortRoutes = function sortRoutes (routes: NuxtRouteConfig[]) { - routes.sort((a, b) => { - if (!a.path.length) { - return -1 - } - if (!b.path.length) { - 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 (b.path === '/') { - return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1 - } - - let i - let res = 0 - let y = 0 - let z = 0 - const _a = a.path.split('/') - const _b = b.path.split('/') - for (i = 0; i < _a.length; i++) { - if (res !== 0) { - break - } - 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) - ) - } - } - - 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) - ) - } - return res - }) - - routes.forEach((route) => { - if (route.children) { - sortRoutes(route.children) - } - }) - - return routes -} - interface CreateRouteOptions { files: string[] srcDir: string @@ -161,61 +23,6 @@ interface NuxtRouteConfig extends Omit<_RouteRecordBase, 'children'> { children?: NuxtRouteConfig[] } -export const createRoutes = function createRoutes ({ - files, - srcDir, - pagesDir = '', - routeNameSplitter = '-', - supportedExtensions = ['vue', 'js'], - trailingSlash -}: CreateRouteOptions) { - const routes: NuxtRouteConfig[] = [] - files.forEach((file) => { - const keys = file - .replace(new RegExp(`^${pagesDir}`), '') - .replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '') - .replace(/\/{2,}/g, '/') - .split('/') - .slice(1) - const route: NuxtRouteConfig = { 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 && typeof route.name === 'string' - ? 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 ? '' : '/' - } else { - route.path += '/' + getRoutePathExtension(key) - - if (key.startsWith('_') && key.length > 1) { - route.path += '?' - } - } - }) - if (trailingSlash !== undefined) { - route.pathToRegexpOptions = { ...route.pathToRegexpOptions, strict: true } - route.path = route.path.replace(/\/+$/, '') + (trailingSlash ? '/' : '') || '/' - } - - parent.push(route) - }) - - sortRoutes(routes) - return cleanChildrenRoutes(routes, false, routeNameSplitter) -} - // Guard dir1 from dir2 which can be indiscriminately removed export const guardDir = function guardDir (options: Record, key1: string, key2: string) { const dir1 = get(options, key1, false) as string @@ -237,41 +44,3 @@ export const guardDir = function guardDir (options: Record, key1: s throw new Error(errorMessage) } } - -const getRoutePathExtension = (key: string) => { - if (key === '_') { - return '*' - } - - if (key.startsWith('_')) { - return `:${key.substr(1)}` - } - - return key -} - -export const promisifyRoute = function promisifyRoute (fn, ...args) { - // If routes is an array - if (Array.isArray(fn)) { - return Promise.resolve(fn) - } - // If routes is a function expecting a callback - if (fn.length === arguments.length) { - return new Promise((resolve, reject) => { - fn((err, routeParams) => { - if (err) { - reject(err) - } - resolve(routeParams) - }, ...args) - }) - } - let promise = fn(...args) - if ( - !promise || - (!(promise instanceof Promise) && typeof promise.then !== 'function') - ) { - promise = Promise.resolve(promise) - } - return promise -} diff --git a/packages/nuxt3/src/utils/serialize.ts b/packages/nuxt3/src/utils/serialize.ts deleted file mode 100644 index 343b666518..0000000000 --- a/packages/nuxt3/src/utils/serialize.ts +++ /dev/null @@ -1,61 +0,0 @@ -import serialize from 'serialize-javascript' - -// eslint-disable-next-line no-redeclare -export function normalizeFunctions(obj: Array): Array -// eslint-disable-next-line no-redeclare -export function normalizeFunctions(obj: null): null -// eslint-disable-next-line no-redeclare -export function normalizeFunctions(obj: Function): Function -// eslint-disable-next-line no-redeclare -export function normalizeFunctions(obj: Record): Record -// eslint-disable-next-line no-redeclare -export function normalizeFunctions (obj: Array | null | Function | Record) { - if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) { - return obj - } - for (const key in obj) { - if (key === '__proto__' || key === 'constructor') { - continue - } - const val = obj[key] - if (val !== null && typeof val === 'object' && !Array.isArray(obj)) { - obj[key] = normalizeFunctions(val) - } - if (typeof obj[key] === 'function') { - const asString = obj[key].toString() - const match = asString.match(/^([^{(]+)=>\s*([\0-\uFFFF]*)/) - if (match) { - const fullFunctionBody = match[2].match(/^{?(\s*return\s+)?([\0-\uFFFF]*?)}?$/) - let functionBody = fullFunctionBody[2].trim() - if (fullFunctionBody[1] || !match[2].trim().match(/^\s*{/)) { - functionBody = `return ${functionBody}` - } - // eslint-disable-next-line no-new-func - obj[key] = new Function(...match[1].split(',').map((arg: string) => arg.trim()), functionBody) - } - } - } - return obj -} - -export function serializeFunction (func: Function) { - let open = false - func = normalizeFunctions(func) - 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(`${func.name || 'function'}(`, 'function (') - .replace('function function', 'function') -} - -serializeFunction.internalFunctionRE = /^(\s*)(?!(?:if)|(?:for)|(?:while)|(?:switch)|(?:catch))(\w+)\s*\((.*?)\)\s*\{/gm -serializeFunction.assignmentRE = /^(\s*):(\w+)\(/gm diff --git a/packages/nuxt3/src/utils/timer.ts b/packages/nuxt3/src/utils/timer.ts deleted file mode 100644 index 43982e0cbe..0000000000 --- a/packages/nuxt3/src/utils/timer.ts +++ /dev/null @@ -1,93 +0,0 @@ -async function promiseFinally ( - fn: (() => Promise) | Promise, - finalFn: () => any -) { - let result: T - try { - if (typeof fn === 'function') { - result = await fn() - } else { - result = await fn - } - } finally { - finalFn() - } - return result -} - -export const timeout = function timeout ( - fn: Promise, - ms: number, - msg: string -) { - let timerId: NodeJS.Timeout - const warpPromise = promiseFinally(fn, () => clearTimeout(timerId)) - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const timerPromise = new Promise((resolve, reject) => { - timerId = setTimeout(() => reject(new Error(msg)), ms) - }) - return Promise.race([warpPromise, timerPromise]) -} - -export const waitFor = function waitFor (ms: number) { - return new Promise(resolve => setTimeout(resolve, ms || 0)) -} - -interface Time { - name: string - description: string - start: [number, number] | bigint - duration?: bigint | [number, number] -} -export class Timer { - _times: Map - - constructor () { - this._times = new Map() - } - - start (name: string, description: string) { - const time: Time = { - name, - description, - start: this.hrtime() - } - this._times.set(name, time) - return time - } - - end (name: string) { - if (this._times.has(name)) { - const time = this._times.get(name)! - if (typeof time.start === 'bigint') { - time.duration = this.hrtime(time.start) - } else { - time.duration = this.hrtime(time.start) - } - this._times.delete(name) - return time - } - } - - hrtime (start?: bigint): bigint - hrtime (start?: [number, number]): [number, number] - hrtime (start?: [number, number] | bigint) { - const useBigInt = typeof process.hrtime.bigint === 'function' - if (start) { - if (typeof start === 'bigint') { - if (!useBigInt) { throw new Error('bigint is not supported.') } - - const end = process.hrtime.bigint() - return (end - start) / BigInt(1000000) - } - - const end = process.hrtime(start) - return end[0] * 1e3 + end[1] * 1e-6 - } - return useBigInt ? process.hrtime.bigint() : process.hrtime() - } - - clear () { - this._times.clear() - } -}