-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathdeclaration.ts
158 lines (134 loc) · 4.99 KB
/
declaration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import type { ComponentInfo, Options } from '../types'
import type { Context } from './context'
import { existsSync } from 'node:fs'
import { mkdir, readFile, writeFile as writeFile_ } from 'node:fs/promises'
import { dirname, isAbsolute, relative } from 'node:path'
import { notNullish, slash } from '@antfu/utils'
import { resolveTypeImports } from './type-imports/detect'
import { getTransformedPath } from './utils'
const multilineCommentsRE = /\/\*.*?\*\//gs
const singlelineCommentsRE = /\/\/.*$/gm
function extractImports(code: string) {
// eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/no-misleading-capturing-group
return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map(i => [i[1], i[2]]))
}
export function parseDeclaration(code: string): DeclarationImports | undefined {
if (!code)
return
code = code
.replace(multilineCommentsRE, '')
.replace(singlelineCommentsRE, '')
const imports: DeclarationImports = {
component: {},
directive: {},
}
const componentDeclaration = /export\s+interface\s+GlobalComponents\s*\{.*?\}/s.exec(code)?.[0]
if (componentDeclaration)
imports.component = extractImports(componentDeclaration)
const directiveDeclaration = /export\s+interface\s+ComponentCustomProperties\s*\{.*?\}/s.exec(code)?.[0]
if (directiveDeclaration)
imports.directive = extractImports(directiveDeclaration)
return imports
}
/**
* Converts `ComponentInfo` to an array
*
* `[name, "typeof import(path)[importName]"]`
*/
function stringifyComponentInfo(filepath: string, { from: path, as: name, name: importName }: ComponentInfo, importPathTransform?: Options['importPathTransform']): [string, string] | undefined {
if (!name)
return undefined
path = getTransformedPath(path, importPathTransform)
const related = isAbsolute(path)
? `./${relative(dirname(filepath), path)}`
: path
const entry = `typeof import('${slash(related)}')['${importName || 'default'}']`
return [name, entry]
}
/**
* Converts array of `ComponentInfo` to an import map
*
* `{ name: "typeof import(path)[importName]", ... }`
*/
export function stringifyComponentsInfo(filepath: string, components: ComponentInfo[], importPathTransform?: Options['importPathTransform']): Record<string, string> {
return Object.fromEntries(
components.map(info => stringifyComponentInfo(filepath, info, importPathTransform))
.filter(notNullish),
)
}
export interface DeclarationImports {
component: Record<string, string>
directive: Record<string, string>
}
export function getDeclarationImports(ctx: Context, filepath: string): DeclarationImports | undefined {
const component = stringifyComponentsInfo(filepath, [
...Object.values({
...ctx.componentNameMap,
...ctx.componentCustomMap,
}),
...resolveTypeImports(ctx.options.types),
], ctx.options.importPathTransform)
const directive = stringifyComponentsInfo(
filepath,
Object.values(ctx.directiveCustomMap),
ctx.options.importPathTransform,
)
if (
(Object.keys(component).length + Object.keys(directive).length) === 0
)
return
return { component, directive }
}
export function stringifyDeclarationImports(imports: Record<string, string>) {
return Object.entries(imports)
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`
return `${name}: ${v}`
})
}
export function getDeclaration(ctx: Context, filepath: string, originalImports?: DeclarationImports) {
const imports = getDeclarationImports(ctx, filepath)
if (!imports)
return
const declarations = {
component: stringifyDeclarationImports({ ...originalImports?.component, ...imports.component }),
directive: stringifyDeclarationImports({ ...originalImports?.directive, ...imports.directive }),
}
let code = `/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
// biome-ignore lint: disable
export {}
/* prettier-ignore */
declare module 'vue' {`
if (Object.keys(declarations.component).length > 0) {
code += `
export interface GlobalComponents {
${declarations.component.join('\n ')}
}`
}
if (Object.keys(declarations.directive).length > 0) {
code += `
export interface ComponentCustomProperties {
${declarations.directive.join('\n ')}
}`
}
code += '\n}\n'
return code
}
async function writeFile(filePath: string, content: string) {
await mkdir(dirname(filePath), { recursive: true })
return await writeFile_(filePath, content, 'utf-8')
}
export async function writeDeclaration(ctx: Context, filepath: string, removeUnused = false) {
const originalContent = existsSync(filepath) ? await readFile(filepath, 'utf-8') : ''
const originalImports = removeUnused ? undefined : parseDeclaration(originalContent)
const code = getDeclaration(ctx, filepath, originalImports)
if (!code)
return
if (code !== originalContent)
await writeFile(filepath, code)
}