forked from stenciljs/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-node-module-resolve.ts
More file actions
89 lines (74 loc) · 2.36 KB
/
Copy pathdev-node-module-resolve.ts
File metadata and controls
89 lines (74 loc) · 2.36 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
import { join, relative } from '@utils';
import { basename, dirname } from 'path';
import { ResolveIdResult } from 'rollup';
import type * as d from '../../declarations';
import { InMemoryFileSystem } from '../sys/in-memory-fs';
import { DEV_MODULE_DIR } from './constants';
export const devNodeModuleResolveId = async (
config: d.ValidatedConfig,
inMemoryFs: InMemoryFileSystem,
resolvedId: ResolveIdResult,
importee: string,
) => {
if (!shouldCheckDevModule(resolvedId, importee)) {
return resolvedId;
}
if (typeof resolvedId === 'string' || !resolvedId) {
return resolvedId;
}
const resolvedPath = resolvedId.id;
const pkgPath = getPackageJsonPath(resolvedPath, importee);
if (!pkgPath) {
return resolvedId;
}
const pkgJsonStr = await inMemoryFs.readFile(pkgPath);
if (!pkgJsonStr) {
return resolvedId;
}
let pkgJsonData: d.PackageJsonData;
try {
pkgJsonData = JSON.parse(pkgJsonStr);
} catch (e) {}
if (!pkgJsonData || !pkgJsonData.version) {
return resolvedId;
}
resolvedId.id = serializeDevNodeModuleUrl(config, pkgJsonData.name, pkgJsonData.version, resolvedPath);
resolvedId.external = true;
return resolvedId;
};
const shouldCheckDevModule = (resolvedId: ResolveIdResult, importee: string) =>
resolvedId &&
importee &&
typeof resolvedId !== 'string' &&
resolvedId.id &&
resolvedId.id.includes('node_modules') &&
(resolvedId.id.endsWith('.js') || resolvedId.id.endsWith('.mjs')) &&
!resolvedId.external &&
!importee.startsWith('.') &&
!importee.startsWith('/');
const getPackageJsonPath = (resolvedPath: string, importee: string): string => {
let currentPath = resolvedPath;
for (let i = 0; i < 10; i++) {
currentPath = dirname(currentPath);
const aBasename = basename(currentPath);
const upDir = dirname(currentPath);
const bBasename = basename(upDir);
if (aBasename === importee && bBasename === 'node_modules') {
return join(currentPath, 'package.json');
}
}
return null;
};
const serializeDevNodeModuleUrl = (
config: d.ValidatedConfig,
moduleId: string,
moduleVersion: string,
resolvedPath: string,
) => {
resolvedPath = relative(config.rootDir, resolvedPath);
let id = `/${DEV_MODULE_DIR}/`;
id += encodeURIComponent(moduleId) + '@';
id += encodeURIComponent(moduleVersion) + '.js';
id += '?p=' + encodeURIComponent(resolvedPath);
return id;
};