forked from dandv/typescript-modern-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyaml-loader.mjs
78 lines (64 loc) · 2.61 KB
/
yaml-loader.mjs
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
/// <reference types="typings-esm-loader" />
/// @ts-check
import { promises as fs } from 'fs';
import { fileURLToPath } from 'url';
import yaml from 'yaml';
const logger = /** @type {const} */ ({
enabled: false,
/* c8 ignore next 2 */
get log() { return this.enabled ? console.log : () => {} },
get dir() { return this.enabled ? console.dir : () => {} }
});
/** @type {resolve} */
export async function resolve(specifier, context, defaultResolve) {
const result = await defaultResolve(specifier, context, defaultResolve);
const child = new URL(result.url);
if (context.parentURL !== undefined) {
logger.log('\n-----[ESM RESOLVER DEBUG]-----');
logger.log('specifier:', specifier);
logger.log('context.parentURL:', context.parentURL);
logger.log('context.conditions:', context.conditions);
logger.log('result.url:', result.url);
logger.log('child:', child);
logger.log('-----[END RESOLVER DEBUG]-----\n');
}
// Ignore built-in modules and the `node_modules` folder.
if (child.protocol === 'nodejs:' || child.protocol === 'node:' || child.pathname.includes('/node_modules/')) return result;
// Apply our custom behavior for YAML files.
if (/\.ya?ml$/.test(result.url)) return { url: result.url, format: 'yaml' };
// Return the result as-is for all other files.
return result;
}
/** @type {load} */
export async function load(url, context, defaultLoad) {
if (context.format !== 'main') {
logger.log('\n-----[ESM LOADER DEBUG]-----');
logger.log('url:', url);
logger.log('context:', context);
logger.log('-----[END LOADER DEBUG]-----\n');
}
// Perform custom loading for YAML files.
if (context.format === 'yaml') return {
format: 'json',
shortCircuit: true,
source: JSON.stringify(yaml.parse(await fs.readFile(fileURLToPath(url), 'utf8'))),
};
// Defer to Node.js for all other URLs.
return defaultLoad(url, context, defaultLoad);
}
/** @type {globalPreload} */
export function globalPreload() {
logger.log('\n-----[ESM GLOBAL PRELOAD DEBUG]-----');
//!@upcoming logger.log('utilities:', utilities);
logger.log('-----[END GLOBAL PRELOAD DEBUG]-----\n');
/** @ambient @type {getBuiltin} */ let getBuiltin;
/* c8 ignore start */
return (() => {
//@ts-ignore
global.someInjectedProperty = 42;
console.log('Hello from preloaded code!');
const { createRequire } = getBuiltin('module');
const require = createRequire(process.cwd() + '/<preload>');
}).toString().slice(8, -2);
/* c8 ignore stop */
}