-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathloader.mjs
More file actions
91 lines (73 loc) · 2.36 KB
/
loader.mjs
File metadata and controls
91 lines (73 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
90
91
import { existsSync, promises as fs } from 'fs';
import { fileURLToPath, URL } from 'url';
import babel from '@babel/core';
const EXTN = /\.\w+(?=\?|$)/;
const isTS = /\.[mc]?tsx?(?=\?|$)/;
function check(fileurl) {
let tmp = fileURLToPath(fileurl);
if (existsSync(tmp)) return fileurl;
}
/**
* extension aliases; runs after checking for extn on disk
* @example `import('./foo.mjs')` but only `foo.mts` exists
*/
const MAPs = {
'.js': ['.ts', '.tsx', '.jsx'],
'.jsx': ['.tsx'],
'.mjs': ['.mts'],
'.cjs': ['.cts'],
};
const root = new URL('file://' + process.cwd() + '/');
const pkgName = '@native-router/react';
export async function resolve(ident, context, fallback) {
if (ident.startsWith('@/')) console.log('----')
// ignore "prefix:" and non-relative identifiers
if (/^\w+\:?/.test(ident)) return fallback(ident, context, fallback);
const target = new URL(ident, context.parentURL || root);
let ext, path, arr;
let match, i=0, base;
// source ident includes extension
if (match = EXTN.exec(target.href)) {
ext = match[0];
if (!context.parentURL || isTS.test(ext)) {
return { url: target.href, shortCircuit: true };
}
// target ident exists
if (path = check(target.href)) {
return { url: path, shortCircuit: true };
}
// target is virtual alias
if (arr = MAPs[ext]) {
base = target.href.substring(0, match.index);
for (; i < arr.length; i++) {
if (path = check(base + arr[i])) {
i = match.index + ext.length;
return {
shortCircuit: true,
url: i > target.href.length
// handle target `?args` trailer
? base + target.href.substring(i)
: path
};
}
}
}
// return original behavior, let it error
return fallback(ident, context, fallback);
}
for (const ext of ['.ts', '.tsx', '/index.ts', '/index.tsx']) {
path = check(target.href + ext);
if (path) return { url: path, shortCircuit: true };
}
return fallback(ident, context, fallback);
}
export const load = async function (uri, context, fallback) {
if (!/\.tsx?$/.test(uri)) return fallback(uri, context);
let format = 'module';
// TODO: decode SAB/U8 correctly
let path = fileURLToPath(uri);
let source = await fs.readFile(path, 'utf8');
// note: inline `transformSource`
let result = await babel.transformAsync(source, {filename: path, sourceMaps: 'inline'});
return { format, source: result.code, shortCircuit: true };
}