Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
187 lines (167 loc) · 4.89 KB
/
Copy pathutils.ts
File metadata and controls
187 lines (167 loc) · 4.89 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
import { lstatSync, accessSync, constants, readFileSync } from "node:fs";
import nodeCrypto from "node:crypto";
import { isAbsolute, join } from "pathe";
import type { PackageJson } from "pkg-types";
import { pathToFileURL } from "mlly";
import { isWindows } from "std-env";
import type { Context } from "./types";
import { gray, green, blue, yellow, cyan, red } from "yoctocolors";
export function isDir(filename: string | URL): boolean {
if (typeof filename !== "string" || filename.startsWith("file://")) {
return false;
}
try {
const stat = lstatSync(filename);
return stat.isDirectory();
} catch {
// lstatSync throws an error if path doesn't exist
return false;
}
}
export function isWritable(filename: string): boolean {
try {
accessSync(filename, constants.W_OK);
return true;
} catch {
return false;
}
}
export function hash(content: string, len = 8) {
const hash = isFipsMode()
? nodeCrypto.createHash("sha256") // #340
: nodeCrypto.createHash("md5");
return hash.update(content).digest("hex").slice(0, len);
}
export function readNearestPackageJSON(path: string): PackageJson | undefined {
while (path && path !== "." && path !== "/") {
path = join(path, "..");
try {
const pkg = readFileSync(join(path, "package.json"), "utf8");
try {
return JSON.parse(pkg);
} catch {
// Ignore errors
}
break;
} catch {
// Ignore errors
}
}
}
export function wrapModule(source: string, opts?: { async?: boolean }) {
return `(${opts?.async ? "async " : ""}function (exports, require, module, __filename, __dirname, jitiImport, jitiESMResolve) { ${source}\n});`;
}
const debugMap = {
true: green("true"),
false: yellow("false"),
"[rebuild]": yellow("[rebuild]"),
"[esm]": blue("[esm]"),
"[cjs]": green("[cjs]"),
"[import]": blue("[import]"),
"[require]": green("[require]"),
"[native]": cyan("[native]"),
"[transpile]": yellow("[transpile]"),
"[fallback]": red("[fallback]"),
"[unknown]": red("[unknown]"),
"[hit]": green("[hit]"),
"[miss]": yellow("[miss]"),
"[json]": green("[json]"),
"[data]": green("[data]"),
};
export function debug(ctx: Context, ...args: unknown[]) {
if (!ctx.opts.debug) {
return;
}
const cwd = process.cwd();
console.log(
gray(
[
"[jiti]",
...args.map((arg) => {
if ((arg as string) in debugMap) {
return debugMap[arg as keyof typeof debugMap];
}
if (typeof arg !== "string") {
return JSON.stringify(arg);
}
return arg.replace(cwd, ".");
}),
].join(" "),
),
);
}
export function jitiInteropDefault(ctx: Context, mod: any) {
return ctx.opts.interopDefault ? interopDefault(mod) : mod;
}
function interopDefault(mod: any): any {
const modType = typeof mod;
if (mod === null || (modType !== "object" && modType !== "function")) {
return mod;
}
const def = mod.default;
const defType = typeof def;
const defIsNil = def === null || def === undefined;
const defIsObj = defType === "object" || defType === "function";
if (defIsNil && mod instanceof Promise) {
// Hotfix for #388
return mod;
}
// Check if we need the apply trap (default is callable but mod isn't)
const needsApplyTrap = defType === "function" && modType !== "function";
// Check if we need fallback to default export properties
// If default is not an object/function or is a Promise, no fallback needed
const needsDefaultFallback =
defIsObj && !(def instanceof Promise); /** issue: #400 */
// Use Proxy with caching - cache eliminates repeated lookup overhead
const cache = new Map<string | symbol, any>();
return new Proxy(mod, {
get(target, prop) {
if (cache.has(prop)) {
return cache.get(prop);
}
let value: any;
if (prop === "__esModule") {
value = true;
} else if (prop === "default") {
if (defIsNil) {
value = mod;
} else if (typeof def?.default === "function" && mod.__esModule) {
value = def.default; // #396
} else {
value = def;
}
} else if (prop in target) {
value = target[prop];
} else if (needsDefaultFallback) {
value = def[prop];
if (typeof value === "function") {
value = value.bind(def);
}
}
cache.set(prop, value);
return value;
},
apply: needsApplyTrap
? (_target, thisArg, args) => Reflect.apply(def, thisArg, args)
: undefined,
});
}
export function normalizeWindowsImportId(id: string) {
if (!isWindows || !isAbsolute(id)) {
return id;
}
return pathToFileURL(id);
}
let _fipsMode: boolean | undefined;
function isFipsMode() {
if (_fipsMode !== undefined) {
return _fipsMode;
}
try {
_fipsMode = !!nodeCrypto.getFips?.();
return _fipsMode;
} catch {
_fipsMode = false;
return _fipsMode;
}
}