Nuxt/packages/utils/src/route.js

237 lines
6.4 KiB
JavaScript
Raw Normal View History

2018-03-16 19:11:24 +00:00
import path from 'path'
import get from 'lodash/get'
import consola from 'consola'
2018-03-16 06:26:23 +00:00
2018-12-22 21:05:13 +00:00
import { r } from './resolve'
export const flatRoutes = function flatRoutes(router, fileName = '', routes = []) {
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(/^\/+$/, '/')
routes.push(
(r.path === '' && fileName[fileName.length - 1] === '/'
? fileName.slice(0, -1)
: fileName) + r.path
)
})
return routes
}
function cleanChildrenRoutes(routes, isChild = false, routeNameSplitter = '-') {
let start = -1
const regExpIndex = new RegExp(`${routeNameSplitter}index$`)
2018-08-08 10:54:05 +00:00
const routesIndex = []
routes.forEach((route) => {
if (regExpIndex.test(route.name) || route.name === 'index') {
// Save indexOf 'index' key in name
const res = route.name.split(routeNameSplitter)
2018-08-08 10:54:05 +00:00
const s = res.indexOf('index')
2018-01-11 14:11:49 +00:00
start = start === -1 || s < start ? s : start
routesIndex.push(res)
}
})
routes.forEach((route) => {
2018-01-11 14:11:49 +00:00
route.path = isChild ? route.path.replace('/', '') : route.path
if (route.path.includes('?')) {
const names = route.name.split(routeNameSplitter)
2018-08-08 10:54:05 +00:00
const paths = route.path.split('/')
if (!isChild) {
paths.shift()
} // clean first / for parents
routesIndex.forEach((r) => {
2018-08-08 10:54:05 +00:00
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('/')
}
route.name = route.name.replace(regExpIndex, '')
if (route.children) {
2018-01-11 14:11:49 +00:00
if (route.children.find(child => child.path === '')) {
delete route.name
}
route.children = cleanChildrenRoutes(route.children, true, routeNameSplitter)
}
})
return routes
}
2018-12-12 06:31:49 +00:00
const DYNAMIC_ROUTE_REGEX = /^\/([:*])/
const sortRoutes = function sortRoutes(routes) {
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
}
export const createRoutes = function createRoutes(files, srcDir, pagesDir = '', routeNameSplitter = '-') {
2018-12-22 22:42:20 +00:00
const supportedExtensions = ['vue', 'js', 'ts', 'tsx']
2018-08-08 10:54:05 +00:00
const routes = []
files.forEach((file) => {
2018-08-08 10:54:05 +00:00
const keys = file
.replace(new RegExp(`^${pagesDir}`), '')
.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '')
2018-01-11 14:11:49 +00:00
.replace(/\/{2,}/g, '/')
.split('/')
.slice(1)
2018-08-08 10:54:05 +00:00
const route = { name: '', path: '', component: r(srcDir, file) }
let parent = routes
keys.forEach((key, i) => {
2018-03-11 13:59:37 +00:00
// remove underscore only, if its the prefix
const sanitizedKey = key.startsWith('_') ? key.substr(1) : key
2018-01-11 14:11:49 +00:00
route.name = route.name
? route.name + routeNameSplitter + sanitizedKey
2018-07-18 14:39:48 +00:00
: sanitizedKey
2018-01-11 14:11:49 +00:00
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 += '?'
}
}
})
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, key1, key2) {
const dir1 = get(options, key1, false)
const dir2 = get(options, key2, false)
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.fatal(errorMessage)
throw new Error(errorMessage)
}
}
const getRoutePathExtension = (key) => {
if (key === '_') {
return '*'
}
if (key.startsWith('_')) {
return `:${key.substr(1)}`
}
return key
}
2018-12-22 21:05:13 +00:00
export const promisifyRoute = function promisifyRoute(fn, ...args) {
// If routes is an array
if (Array.isArray(fn)) {
return Promise.resolve(fn)
}
2018-12-22 21:05:13 +00:00
// 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)
})
2018-12-22 21:05:13 +00:00
}
let promise = fn(...args)
if (
!promise ||
(!(promise instanceof Promise) && typeof promise.then !== 'function')
) {
promise = Promise.resolve(promise)
}
return promise
}