This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathloaders.ts
308 lines (270 loc) · 7.07 KB
/
loaders.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
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
import type { MessagePort } from 'node:worker_threads';
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';
import type {
ResolveFnOutput, ResolveHookContext, LoadHook, GlobalPreloadHook,
} from 'module';
import {
transform,
transformDynamicImport,
resolveTsPath,
compareNodeVersion,
} from '@esbuild-kit/core-utils';
import type { TransformOptions } from 'esbuild';
import {
applySourceMap,
tsconfigPathsMatcher,
fileMatcher,
tsExtensionsPattern,
isJsonPattern,
getFormatFromFileUrl,
fileProtocol,
type MaybePromise,
type NodeError,
} from './utils.js';
const isDirectoryPattern = /\/(?:$|\?)/;
type NextResolve = (
specifier: string,
context?: ResolveHookContext,
) => MaybePromise<ResolveFnOutput>;
type resolve = (
specifier: string,
context: ResolveHookContext,
nextResolve: NextResolve,
recursiveCall?: boolean,
) => MaybePromise<ResolveFnOutput>;
const isolatedLoader = compareNodeVersion([20, 0, 0]) >= 0;
type SendToParent = (data: {
type: 'dependency';
path: string;
}) => void;
let sendToParent: SendToParent | undefined = process.send ? process.send.bind(process) : undefined;
/**
* Technically globalPreload is deprecated so it should be in loaders-deprecated
* but it shares a closure with the new load hook
*/
let mainThreadPort: MessagePort | undefined;
const _globalPreload: GlobalPreloadHook = ({ port }) => {
mainThreadPort = port;
sendToParent = port.postMessage.bind(port);
return `
const require = getBuiltin('module').createRequire("${import.meta.url}");
require('@esbuild-kit/core-utils').installSourceMapSupport(port);
if (process.send) {
port.addListener('message', (message) => {
if (message.type === 'dependency') {
process.send(message);
}
});
}
port.unref(); // Allows process to exit without waiting for port to close
`;
};
export const globalPreload = isolatedLoader ? _globalPreload : undefined;
const resolveExplicitPath = async (
defaultResolve: NextResolve,
specifier: string,
context: ResolveHookContext,
) => {
const resolved = await defaultResolve(specifier, context);
if (
!resolved.format
&& resolved.url.startsWith(fileProtocol)
) {
resolved.format = await getFormatFromFileUrl(resolved.url);
}
return resolved;
};
const extensions = ['.js', '.json', '.ts', '.tsx', '.jsx'] as const;
async function tryExtensions(
specifier: string,
context: ResolveHookContext,
defaultResolve: NextResolve,
) {
const [specifierWithoutQuery, query] = specifier.split('?');
let throwError: Error | undefined;
for (const extension of extensions) {
try {
return await resolveExplicitPath(
defaultResolve,
specifierWithoutQuery + extension + (query ? `?${query}` : ''),
context,
);
} catch (_error) {
if (
throwError === undefined
&& _error instanceof Error
) {
const { message } = _error;
_error.message = _error.message.replace(`${extension}'`, "'");
_error.stack = _error.stack!.replace(message, _error.message);
throwError = _error;
}
}
}
throw throwError;
}
async function tryDirectory(
specifier: string,
context: ResolveHookContext,
defaultResolve: NextResolve,
) {
const isExplicitDirectory = isDirectoryPattern.test(specifier);
const appendIndex = isExplicitDirectory ? 'index' : '/index';
const [specifierWithoutQuery, query] = specifier.split('?');
try {
return await tryExtensions(
specifierWithoutQuery + appendIndex + (query ? `?${query}` : ''),
context,
defaultResolve,
);
} catch (_error) {
if (!isExplicitDirectory) {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
const error = _error as Error;
const { message } = error;
error.message = error.message.replace(`${appendIndex.replace('/', path.sep)}'`, "'");
error.stack = error.stack!.replace(message, error.message);
throw error;
}
}
const isRelativePathPattern = /^\.{1,2}\//;
const supportsNodePrefix = (
compareNodeVersion([14, 13, 1]) >= 0
|| compareNodeVersion([12, 20, 0]) >= 0
);
export const resolve: resolve = async function (
specifier,
context,
defaultResolve,
recursiveCall,
) {
// Added in v12.20.0
// https://nodejs.org/api/esm.html#esm_node_imports
if (!supportsNodePrefix && specifier.startsWith('node:')) {
specifier = specifier.slice(5);
}
// If directory, can be index.js, index.ts, etc.
if (isDirectoryPattern.test(specifier)) {
return await tryDirectory(specifier, context, defaultResolve);
}
const isPath = (
specifier.startsWith(fileProtocol)
|| isRelativePathPattern.test(specifier)
);
if (
tsconfigPathsMatcher
&& !isPath // bare specifier
&& !context.parentURL?.includes('/node_modules/')
) {
const possiblePaths = tsconfigPathsMatcher(specifier);
for (const possiblePath of possiblePaths) {
try {
return await resolve(
pathToFileURL(possiblePath).toString(),
context,
defaultResolve,
);
} catch {}
}
}
/**
* Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions
*/
if (tsExtensionsPattern.test(context.parentURL!)) {
const tsPath = resolveTsPath(specifier);
if (tsPath) {
try {
return await resolveExplicitPath(defaultResolve, tsPath, context);
} catch (error) {
const { code } = error as NodeError;
if (
code !== 'ERR_MODULE_NOT_FOUND'
&& code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED'
) {
throw error;
}
}
}
}
try {
return await resolveExplicitPath(defaultResolve, specifier, context);
} catch (error) {
if (
error instanceof Error
&& !recursiveCall
) {
const { code } = error as NodeError;
if (code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
try {
return await tryDirectory(specifier, context, defaultResolve);
} catch (error_) {
if ((error_ as NodeError).code !== 'ERR_PACKAGE_IMPORT_NOT_DEFINED') {
throw error_;
}
}
}
if (code === 'ERR_MODULE_NOT_FOUND') {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
}
throw error;
}
};
export const load: LoadHook = async function (
url,
context,
defaultLoad,
) {
if (sendToParent) {
sendToParent({
type: 'dependency',
path: url,
});
}
if (isJsonPattern.test(url)) {
if (!context.importAssertions) {
context.importAssertions = {};
}
context.importAssertions.type = 'json';
}
const loaded = await defaultLoad(url, context);
if (!loaded.source) {
return loaded;
}
const filePath = url.startsWith('file://') ? fileURLToPath(url) : url;
const code = loaded.source.toString();
if (
// Support named imports in JSON modules
loaded.format === 'json'
|| tsExtensionsPattern.test(url)
) {
const transformed = await transform(
code,
filePath,
{
tsconfigRaw: fileMatcher?.(filePath) as TransformOptions['tsconfigRaw'],
},
);
return {
format: 'module',
source: applySourceMap(transformed, url, mainThreadPort),
};
}
if (loaded.format === 'module') {
const dynamicImportTransformed = transformDynamicImport(filePath, code);
if (dynamicImportTransformed) {
loaded.source = applySourceMap(
dynamicImportTransformed,
url,
mainThreadPort,
);
}
}
return loaded;
};