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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
|
import type {
AnyFunction,
BuildConfig,
BunPlugin,
OnLoadCallback,
OnLoadResult,
OnLoadResultObject,
OnLoadResultSourceCode,
OnResolveCallback,
PluginBuilder,
PluginConstraints,
} from "bun";
// This API expects 4 functions:
// It should be generic enough to reuse for Bun.plugin() eventually, too.
interface BundlerPlugin {
onLoad: Map<string, [RegExp, OnLoadCallback][]>;
onResolve: Map<string, [RegExp, OnResolveCallback][]>;
onLoadAsync(
internalID,
sourceCode: string | Uint8Array | ArrayBuffer | DataView | null,
loaderKey: number | null,
): void;
onResolveAsync(internalID, a, b, c): void;
addError(internalID, error, number): void;
addFilter(filter, namespace, number): void;
}
// Extra types
type Setup = BunPlugin["setup"];
type MinifyObj = Exclude<BuildConfig["minify"], boolean>;
interface BuildConfigExt extends BuildConfig {
// we support esbuild-style entryPoints
entryPoints?: string[];
// plugins is guaranteed to not be null
plugins: BunPlugin[];
}
interface PluginBuilderExt extends PluginBuilder {
// these functions aren't implemented yet, so we dont publicly expose them
resolve: AnyFunction;
onStart: AnyFunction;
onEnd: AnyFunction;
onDispose: AnyFunction;
// we partially support initialOptions. it's read-only and a subset of
// all options mapped to their esbuild names
initialOptions: any;
// we set this to an empty object
esbuild: any;
}
export function runSetupFunction(this: BundlerPlugin, setup: Setup, config: BuildConfigExt) {
var onLoadPlugins = new Map<string, [RegExp, AnyFunction][]>();
var onResolvePlugins = new Map<string, [RegExp, AnyFunction][]>();
function validate(filterObject: PluginConstraints, callback, map) {
if (!filterObject || !$isObject(filterObject)) {
throw new TypeError('Expected an object with "filter" RegExp');
}
if (!callback || !$isCallable(callback)) {
throw new TypeError("callback must be a function");
}
var { filter, namespace = "file" } = filterObject;
if (!filter) {
throw new TypeError('Expected an object with "filter" RegExp');
}
if (!$isRegExpObject(filter)) {
throw new TypeError("filter must be a RegExp");
}
if (namespace && !(typeof namespace === "string")) {
throw new TypeError("namespace must be a string");
}
if ((namespace?.length ?? 0) === 0) {
namespace = "file";
}
if (!/^([/$a-zA-Z0-9_\\-]+)$/.test(namespace)) {
throw new TypeError("namespace can only contain $a-zA-Z0-9_\\-");
}
var callbacks = map.$get(namespace);
if (!callbacks) {
map.$set(namespace, [[filter, callback]]);
} else {
$arrayPush(callbacks, [filter, callback]);
}
}
function onLoad(filterObject, callback) {
validate(filterObject, callback, onLoadPlugins);
}
function onResolve(filterObject, callback) {
validate(filterObject, callback, onResolvePlugins);
}
const processSetupResult = () => {
var anyOnLoad = false,
anyOnResolve = false;
for (var [namespace, callbacks] of onLoadPlugins.entries()) {
for (var [filter] of callbacks) {
this.addFilter(filter, namespace, 1);
anyOnLoad = true;
}
}
for (var [namespace, callbacks] of onResolvePlugins.entries()) {
for (var [filter] of callbacks) {
this.addFilter(filter, namespace, 0);
anyOnResolve = true;
}
}
if (anyOnResolve) {
var onResolveObject = this.onResolve;
if (!onResolveObject) {
this.onResolve = onResolvePlugins;
} else {
for (var [namespace, callbacks] of onResolvePlugins.entries()) {
var existing = onResolveObject.$get(namespace) as [RegExp, AnyFunction][];
if (!existing) {
onResolveObject.$set(namespace, callbacks);
} else {
onResolveObject.$set(namespace, existing.concat(callbacks));
}
}
}
}
if (anyOnLoad) {
var onLoadObject = this.onLoad;
if (!onLoadObject) {
this.onLoad = onLoadPlugins;
} else {
for (var [namespace, callbacks] of onLoadPlugins.entries()) {
var existing = onLoadObject.$get(namespace) as [RegExp, AnyFunction][];
if (!existing) {
onLoadObject.$set(namespace, callbacks);
} else {
onLoadObject.$set(namespace, existing.concat(callbacks));
}
}
}
}
return anyOnLoad || anyOnResolve;
};
var setupResult = setup({
config: config,
onDispose: notImplementedIssueFn(2771, "On-dispose callbacks"),
onEnd: notImplementedIssueFn(2771, "On-end callbacks"),
onLoad,
onResolve,
onStart: notImplementedIssueFn(2771, "On-start callbacks"),
resolve: notImplementedIssueFn(2771, "build.resolve()"),
// esbuild's options argument is different, we provide some interop
initialOptions: {
...config,
bundle: true,
entryPoints: config.entrypoints ?? config.entryPoints ?? [],
minify: typeof config.minify === "boolean" ? config.minify : false,
minifyIdentifiers: config.minify === true || (config.minify as MinifyObj)?.identifiers,
minifyWhitespace: config.minify === true || (config.minify as MinifyObj)?.whitespace,
minifySyntax: config.minify === true || (config.minify as MinifyObj)?.syntax,
outbase: config.root,
platform: config.target === "bun" ? "node" : config.target,
},
esbuild: {},
} satisfies PluginBuilderExt as PluginBuilder);
if (setupResult && $isPromise(setupResult)) {
if ($getPromiseInternalField(setupResult, $promiseFieldFlags) & $promiseStateFulfilled) {
setupResult = $getPromiseInternalField(setupResult, $promiseFieldReactionsOrResult);
} else {
return setupResult.$then(processSetupResult);
}
}
return processSetupResult();
}
export function runOnResolvePlugins(
this: BundlerPlugin,
specifier,
inputNamespace,
importer,
internalID,
kindId,
resolveDir,
) {
// Must be kept in sync with ImportRecord.label
const kind = $ImportKindIdToLabel[kindId];
var promiseResult: any = (async (inputPath, inputNamespace, importer, kind, resolveDir) => {
var { onResolve, onLoad } = this;
var results = onResolve.$get(inputNamespace);
if (!results) {
this.onResolveAsync(internalID, null, null, null);
return null;
}
for (let [filter, callback] of results) {
if (filter.test(inputPath)) {
var result = callback({
path: inputPath,
importer,
namespace: inputNamespace,
resolveDir,
kind,
// pluginData
});
while (
result &&
$isPromise(result) &&
($getPromiseInternalField(result, $promiseFieldFlags) & $promiseStateMask) === $promiseStateFulfilled
) {
result = $getPromiseInternalField(result, $promiseFieldReactionsOrResult);
}
if (result && $isPromise(result)) {
result = await result;
}
if (!result || !$isObject(result)) {
continue;
}
var { path, namespace: userNamespace = inputNamespace, external } = result;
if (!(typeof path === "string")) {
throw new TypeError("onResolve: expected 'path' to be a string");
}
if (!(typeof userNamespace === "string")) {
throw new TypeError("onResolve: expected 'namespace' to be a string");
}
if (!path) {
continue;
}
if (!userNamespace) {
userNamespace = inputNamespace;
}
if (typeof external !== "boolean" && !$isUndefinedOrNull(external)) {
throw new TypeError("onResolve: expected 'external' to be boolean");
}
if (!external) {
if (userNamespace === "file") {
if (process.platform !== "win32") {
if (path[0] !== "/" || path.includes("..")) {
throw new TypeError('onResolve plugin "path" must be absolute when the namespace is "file"');
}
} else {
// TODO: Windows
}
}
if (userNamespace === "dataurl") {
if (!path.startsWith("data:")) {
throw new TypeError('onResolve plugin "path" must start with "data:" when the namespace is "dataurl"');
}
}
if (userNamespace && userNamespace !== "file" && (!onLoad || !onLoad.$has(userNamespace))) {
throw new TypeError(`Expected onLoad plugin for namespace ${userNamespace} to exist`);
}
}
this.onResolveAsync(internalID, path, userNamespace, external);
return null;
}
}
this.onResolveAsync(internalID, null, null, null);
return null;
})(specifier, inputNamespace, importer, kind, resolveDir);
while (
promiseResult &&
$isPromise(promiseResult) &&
($getPromiseInternalField(promiseResult, $promiseFieldFlags) & $promiseStateMask) === $promiseStateFulfilled
) {
promiseResult = $getPromiseInternalField(promiseResult, $promiseFieldReactionsOrResult);
}
if (promiseResult && $isPromise(promiseResult)) {
promiseResult.then(
() => {},
e => {
this.addError(internalID, e, 0);
},
);
}
}
export function runOnLoadPlugins(this: BundlerPlugin, internalID, path, namespace, defaultLoaderId) {
const LOADERS_MAP = $LoaderLabelToId;
const loaderName = $LoaderIdToLabel[defaultLoaderId];
var promiseResult = (async (internalID, path, namespace, defaultLoader) => {
var results = this.onLoad.$get(namespace);
if (!results) {
this.onLoadAsync(internalID, null, null);
return null;
}
for (let [filter, callback] of results) {
if (filter.test(path)) {
var result = callback({
path,
namespace,
// suffix
// pluginData
loader: defaultLoader,
});
while (
result &&
$isPromise(result) &&
($getPromiseInternalField(result, $promiseFieldFlags) & $promiseStateMask) === $promiseStateFulfilled
) {
result = $getPromiseInternalField(result, $promiseFieldReactionsOrResult);
}
if (result && $isPromise(result)) {
result = await result;
}
if (!result || !$isObject(result)) {
continue;
}
var { contents, loader = defaultLoader } = result as OnLoadResultSourceCode & OnLoadResultObject;
// TODO: Support "object" loader
if (!(typeof contents === "string") && !$isTypedArrayView(contents)) {
throw new TypeError('onLoad plugins must return an object with "contents" as a string or Uint8Array');
}
if (!(typeof loader === "string")) {
throw new TypeError('onLoad plugins must return an object with "loader" as a string');
}
const chosenLoader = LOADERS_MAP[loader];
if (chosenLoader === undefined) {
throw new TypeError(`Loader ${loader} is not supported.`);
}
this.onLoadAsync(internalID, contents, chosenLoader);
return null;
}
}
this.onLoadAsync(internalID, null, null);
return null;
})(internalID, path, namespace, loaderName);
while (
promiseResult &&
$isPromise(promiseResult) &&
($getPromiseInternalField(promiseResult, $promiseFieldFlags) & $promiseStateMask) === $promiseStateFulfilled
) {
promiseResult = $getPromiseInternalField(promiseResult, $promiseFieldReactionsOrResult);
}
if (promiseResult && $isPromise(promiseResult)) {
promiseResult.then(
() => {},
e => {
this.addError(internalID, e, 1);
},
);
}
}
|