-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathimport-resolver.ts
More file actions
378 lines (320 loc) · 10.3 KB
/
import-resolver.ts
File metadata and controls
378 lines (320 loc) · 10.3 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
* Flattened file set for quick lookups.
* Maps file paths to true for existence checks.
*/
export type FileSet = Set<string>
/**
* Flatten a nested file tree into a set of file paths for quick lookups.
*/
export function flattenFileTree(tree: PackageFileTree[]): FileSet {
const files = new Set<string>()
function traverse(nodes: PackageFileTree[]) {
for (const node of nodes) {
if (node.type === 'file') {
files.add(node.path)
} else if (node.children) {
traverse(node.children)
}
}
}
traverse(tree)
return files
}
/**
* Normalize a path by resolving . and .. segments
*/
function normalizePath(path: string): string {
const parts = path.split('/')
const result: string[] = []
for (const part of parts) {
if (part === '.' || part === '') {
continue
}
if (part === '..') {
result.pop()
} else {
result.push(part)
}
}
return result.join('/')
}
/**
* Get the directory of a file path.
*/
function dirname(path: string): string {
const lastSlash = path.lastIndexOf('/')
return lastSlash === -1 ? '' : path.substring(0, lastSlash)
}
/**
* Get file extension priority order based on source file type.
*/
function getExtensionPriority(sourceFile: string): string[][] {
const ext = sourceFile.split('.').slice(1).join('.')
// Declaration files prefer other declaration files
if (ext === 'd.ts' || ext === 'd.mts' || ext === 'd.cts') {
return [
[], // exact match first
['.d.ts', '.d.mts', '.d.cts'],
['.ts', '.mts', '.cts'],
['.js', '.mjs', '.cjs'],
['.tsx', '.jsx'],
['.json'],
]
}
// TypeScript files
if (ext === 'ts' || ext === 'tsx') {
return [[], ['.ts', '.tsx'], ['.d.ts'], ['.js', '.jsx'], ['.json']]
}
if (ext === 'mts') {
return [[], ['.mts'], ['.d.mts', '.d.ts'], ['.mjs', '.js'], ['.json']]
}
if (ext === 'cts') {
return [[], ['.cts'], ['.d.cts', '.d.ts'], ['.cjs', '.js'], ['.json']]
}
// JavaScript files
if (ext === 'js' || ext === 'jsx') {
return [[], ['.js', '.jsx'], ['.ts', '.tsx'], ['.json']]
}
if (ext === 'mjs') {
return [[], ['.mjs'], ['.js'], ['.mts', '.ts'], ['.json']]
}
if (ext === 'cjs') {
return [[], ['.cjs'], ['.js'], ['.cts', '.ts'], ['.json']]
}
// Default for other files (vue, svelte, etc.)
return [[], ['.ts', '.js'], ['.d.ts'], ['.json']]
}
/**
* Resolve an alias specifier to the directory path within a file path.
* Supports #, ~, and @ prefixes (e.g. #app, ~/app, @/app).
* The alias must match a path segment exactly (no partial matches).
*/
export function resolveAliasToDir(aliasSpec: string, filePath?: string | null): string | null {
if (
(!aliasSpec.startsWith('#') && !aliasSpec.startsWith('~') && !aliasSpec.startsWith('@')) ||
!filePath
) {
return null
}
// Support #app, #/app, ~app, ~/app, @app, @/app
const alias = aliasSpec.replace(/^[#~@]\/?/, '')
const segments = filePath.split('/')
let lastMatchIndex = -1
for (let i = 0; i < segments.length; i++) {
if (segments[i] === alias) {
lastMatchIndex = i
}
}
if (lastMatchIndex === -1) {
return null
}
return segments.slice(0, lastMatchIndex + 1).join('/')
}
/**
* Get index file extensions to try for directory imports.
*/
function getIndexExtensions(sourceFile: string): string[] {
const ext = sourceFile.split('.').slice(1).join('.')
if (ext === 'd.ts' || ext === 'd.mts' || ext === 'd.cts') {
return ['index.d.ts', 'index.d.mts', 'index.d.cts', 'index.ts', 'index.js']
}
if (ext === 'mts' || ext === 'mjs') {
return ['index.mts', 'index.mjs', 'index.ts', 'index.js']
}
if (ext === 'cts' || ext === 'cjs') {
return ['index.cts', 'index.cjs', 'index.ts', 'index.js']
}
if (ext === 'ts' || ext === 'tsx') {
return ['index.ts', 'index.tsx', 'index.js', 'index.jsx']
}
return ['index.js', 'index.ts', 'index.mjs', 'index.cjs']
}
export interface ResolvedImport {
/** The resolved file path (relative to package root) */
path: string
}
export type InternalImportTarget = string | { default?: string; import?: string } | null | undefined
export type InternalImportsMap = Record<string, InternalImportTarget>
/**
* Resolve a relative import specifier to an actual file path.
*
* @param specifier - The import specifier (e.g., './utils', '../types')
* @param currentFile - The current file path (e.g., 'dist/index.js')
* @param files - Set of all file paths in the package
* @returns The resolved path or null if not found
*/
export function resolveRelativeImport(
specifier: string,
currentFile: string,
files: FileSet,
): ResolvedImport | null {
// Remove quotes if present
const cleanSpecifier = specifier.replace(/^['"]|['"]$/g, '').trim()
// Only handle relative imports
if (!cleanSpecifier.startsWith('.')) {
return null
}
// Get the directory of the current file
const currentDir = dirname(currentFile)
// Resolve the path relative to current directory
const basePath = currentDir
? normalizePath(`${currentDir}/${cleanSpecifier}`)
: normalizePath(cleanSpecifier)
// If path is empty or goes above root, return null
if (!basePath || basePath.startsWith('..')) {
return null
}
// Get extension priority based on source file
const extensionGroups = getExtensionPriority(currentFile)
const indexExtensions = getIndexExtensions(currentFile)
// Try each extension group in priority order
for (const extensions of extensionGroups) {
if (extensions.length === 0) {
// Try exact match
if (files.has(basePath)) {
return { path: basePath }
}
} else {
// Try with extensions
for (const ext of extensions) {
const pathWithExt = basePath + ext
if (files.has(pathWithExt)) {
return { path: pathWithExt }
}
}
}
}
// Try as directory with index file
for (const indexFile of indexExtensions) {
const indexPath = `${basePath}/${indexFile}`
if (files.has(indexPath)) {
return { path: indexPath }
}
}
return null
}
function normalizeInternalImportTarget(target: InternalImportTarget): string | null {
if (typeof target === 'string') {
return target
}
if (target && typeof target === 'object') {
if (typeof target.import === 'string') {
return target.import
}
if (typeof target.default === 'string') {
return target.default
}
}
return null
}
function normalizeAliasPrefix(value: string): string {
return value.replace(/^([#~@])\//, '$1')
}
function guessInternalImportTarget(
imports: InternalImportsMap,
specifier: string,
files: FileSet,
currentFile: string,
): string | null {
for (const [key, value] of Object.entries(imports)) {
const normalizedSpecifier = normalizeAliasPrefix(specifier)
const normalizedKey = normalizeAliasPrefix(key)
if (
normalizedSpecifier === normalizedKey ||
normalizedSpecifier.startsWith(`${normalizedKey}/`)
) {
const basePath = resolveAliasToDir(key, normalizeInternalImportTarget(value))
if (!basePath) continue
const suffix = normalizedSpecifier.slice(normalizedKey.length).replace(/^\//, '')
const pathWithoutExt = suffix ? `${basePath}/${suffix}` : basePath
const toCheckPath = (p: string) => files.has(normalizePath(p)) || files.has(p)
// Path already has an extension-like suffix on the last segment - return as is if exists
const filename = pathWithoutExt.split('/').pop() ?? ''
if (filename.includes('.') && !filename.endsWith('.')) {
if (toCheckPath(pathWithoutExt)) {
return pathWithoutExt.startsWith('./') ? pathWithoutExt : `./${pathWithoutExt}`
}
return null
}
// Try adding extensions based on currentFile type
const extensionGroups = getExtensionPriority(currentFile)
for (const extensions of extensionGroups) {
if (extensions.length === 0) {
if (toCheckPath(pathWithoutExt)) {
return pathWithoutExt.startsWith('./') ? pathWithoutExt : `./${pathWithoutExt}`
}
} else {
for (const ext of extensions) {
const pathWithExt = pathWithoutExt + ext
if (toCheckPath(pathWithExt)) {
return pathWithExt.startsWith('./') ? pathWithExt : `./${pathWithExt}`
}
}
}
}
// Try as directory with index file
for (const indexFile of getIndexExtensions(currentFile)) {
const indexPath = `${pathWithoutExt}/${indexFile}`
if (toCheckPath(indexPath)) {
return indexPath.startsWith('./') ? indexPath : `./${indexPath}`
}
}
}
}
return null
}
/**
* import ... from '#components/Button.vue'
* import ... from '#/components/Button.vue'
* import ... from '~/components/Button.vue'
* import ... from '~components/Button.vue'
*/
export function resolveInternalImport(
specifier: string,
currentFile: string,
imports: InternalImportsMap | undefined,
files: FileSet,
): ResolvedImport | null {
const cleanSpecifier = specifier.replace(/^['"]|['"]$/g, '').trim()
if (
(!cleanSpecifier.startsWith('#') &&
!cleanSpecifier.startsWith('~') &&
!cleanSpecifier.startsWith('@')) ||
!imports
) {
return null
}
const importTarget = normalizeInternalImportTarget(imports[cleanSpecifier])
const target =
importTarget != null
? importTarget
: guessInternalImportTarget(imports, cleanSpecifier, files, currentFile)
if (!target || !target.startsWith('./')) {
return null
}
const path = normalizePath(target)
if (!path || path.startsWith('..') || !files.has(path)) {
return null
}
return { path }
}
/**
* Create a resolver function bound to a specific file tree and current file.
*/
export function createImportResolver(
files: FileSet,
currentFile: string,
packageName: string,
version: string,
internalImports?: InternalImportsMap,
): (specifier: string) => string | null {
return (specifier: string) => {
const relativeResolved = resolveRelativeImport(specifier, currentFile, files)
const internalResolved = resolveInternalImport(specifier, currentFile, internalImports, files)
const resolved = relativeResolved != null ? relativeResolved : internalResolved
if (resolved) {
return `/package-code/${packageName}/v/${version}/${resolved.path}`
}
return null
}
}