2021-11-21 16:14:46 +00:00
|
|
|
import type { AutoImport } from '@nuxt/schema'
|
2022-01-27 11:13:32 +00:00
|
|
|
import escapeRE from 'escape-string-regexp'
|
2021-10-20 09:47:18 +00:00
|
|
|
|
|
|
|
export interface AutoImportContext {
|
|
|
|
autoImports: AutoImport[]
|
|
|
|
matchRE: RegExp
|
2021-12-21 14:28:45 +00:00
|
|
|
transform: {
|
|
|
|
exclude: RegExp[]
|
|
|
|
}
|
2021-10-20 09:47:18 +00:00
|
|
|
map: Map<string, AutoImport>
|
|
|
|
}
|
|
|
|
|
2021-12-21 14:28:45 +00:00
|
|
|
export function createAutoImportContext (opts): AutoImportContext {
|
2021-10-20 09:47:18 +00:00
|
|
|
return {
|
|
|
|
autoImports: [],
|
|
|
|
map: new Map(),
|
2021-12-21 14:28:45 +00:00
|
|
|
matchRE: /__never__/,
|
|
|
|
transform: {
|
|
|
|
exclude: opts.transform.exclude || [/node_modules/]
|
|
|
|
}
|
2021-10-20 09:47:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function updateAutoImportContext (ctx: AutoImportContext) {
|
|
|
|
// Detect duplicates
|
|
|
|
const usedNames = new Set()
|
|
|
|
for (const autoImport of ctx.autoImports) {
|
|
|
|
if (usedNames.has(autoImport.as)) {
|
|
|
|
autoImport.disabled = true
|
|
|
|
console.warn(`Disabling duplicate auto import '${autoImport.as}' (imported from '${autoImport.from}')`)
|
|
|
|
} else {
|
|
|
|
usedNames.add(autoImport.as)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Filter out disabled auto imports
|
|
|
|
ctx.autoImports = ctx.autoImports.filter(i => i.disabled !== true)
|
|
|
|
|
|
|
|
// Create regex
|
2022-01-27 11:13:32 +00:00
|
|
|
ctx.matchRE = new RegExp(`\\b(${ctx.autoImports.map(i => escapeRE(i.as)).join('|')})\\b`, 'g')
|
2021-10-20 09:47:18 +00:00
|
|
|
|
|
|
|
// Create map
|
|
|
|
ctx.map.clear()
|
|
|
|
for (const autoImport of ctx.autoImports) {
|
|
|
|
ctx.map.set(autoImport.as, autoImport)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
}
|