-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.js
132 lines (97 loc) · 2.21 KB
/
source.js
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
/*!
* source.js - script source for bthreads
* Copyright (c) 2019, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bthreads
*/
'use strict';
const path = require('path');
const url = require('url');
/*
* URL
*/
let {URL, fileURLToPath, pathToFileURL} = url;
/*
* Base
*/
function location(caller) {
const file = toPath(caller, '.');
const url = toURL(caller, '.');
const prepareStackTrace = Error.prepareStackTrace;
const stackTraceLimit = Error.stackTraceLimit;
const dummy = {};
Error.prepareStackTrace = (error, stack) => {
let saw = false;
for (let i = 0; i < stack.length; i++) {
const name = stack[i].getFileName();
if (name !== file && name !== url) {
if (saw)
return name;
continue;
}
saw = true;
}
return '.';
};
Error.stackTraceLimit = 20;
Error.captureStackTrace(dummy);
let result = dummy.stack;
Error.prepareStackTrace = prepareStackTrace;
Error.stackTraceLimit = stackTraceLimit;
if (file.startsWith('file:'))
return new URL(file);
if (!path.isAbsolute(result))
result = path.join(process.cwd(), '[worker eval]');
return pathToFileURL(result);
}
function filename(caller) {
return toPath(location(caller), '.');
}
function dirname(caller) {
return path.dirname(filename(caller));
}
/*
* Resolve
*/
function resolve(req, caller) {
return toPath(req, dirname(caller));
}
/*
* Require
*/
function _require(req, caller) {
return require(resolve(req, caller));
}
/*
* Conversion
*/
function toPath(url, root) {
url = String(url);
if (url.startsWith('file:'))
url = fileURLToPath(url);
return path.resolve(root, url);
}
function toURL(file, root) {
file = String(file);
if (file.startsWith('file:'))
return new URL(file);
return pathToFileURL(path.resolve(root, file));
}
if (!fileURLToPath) {
fileURLToPath = (url) => {
url = new URL(url);
return decodeURI(url.pathname);
};
}
if (!pathToFileURL) {
pathToFileURL = (file) => {
return new URL('file://' + encodeURI(file));
};
}
/*
* Expose
*/
exports.location = location;
exports.filename = filename;
exports.dirname = dirname;
exports.resolve = resolve;
exports.require = _require;