bun-types 1.2.6 → 1.2.8-canary.20250327T140605

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/globals.d.ts CHANGED
@@ -1,1954 +1,1726 @@
1
- export {};
2
-
3
- type _Event = {
4
- /** This is not used in Node.js and is provided purely for completeness. */
5
- readonly bubbles: boolean;
6
- /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
7
- cancelBubble: () => void;
8
- /** True if the event was created with the cancelable option */
9
- readonly cancelable: boolean;
10
- /** This is not used in Node.js and is provided purely for completeness. */
11
- readonly composed: boolean;
12
- /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
13
- composedPath(): [EventTarget?];
14
- /** Alias for event.target. */
15
- readonly currentTarget: EventTarget | null;
16
- /** Is true if cancelable is true and event.preventDefault() has been called. */
17
- readonly defaultPrevented: boolean;
18
- /** This is not used in Node.js and is provided purely for completeness. */
19
- readonly eventPhase: 0 | 2;
20
- /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
21
- readonly isTrusted: boolean;
22
- /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
23
- preventDefault(): void;
24
- /** This is not used in Node.js and is provided purely for completeness. */
25
- returnValue: boolean;
26
- /** Alias for event.target. */
27
- readonly srcElement: EventTarget | null;
28
- /** Stops the invocation of event listeners after the current one completes. */
29
- stopImmediatePropagation(): void;
30
- /** This is not used in Node.js and is provided purely for completeness. */
31
- stopPropagation(): void;
32
- /** The `EventTarget` dispatching the event */
33
- readonly target: EventTarget | null;
34
- /** The millisecond timestamp when the Event object was created. */
35
- readonly timeStamp: number;
36
- /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
37
- readonly type: string;
1
+ declare module "bun" {
2
+ namespace __internal {
3
+ type NodeWorkerThreadsWorker = import("worker_threads").Worker;
4
+ type LibWorkerOrNodeWorkerThreadsWorker = Bun.__internal.UseLibDomIfAvailable<"Worker", NodeWorkerThreadsWorker>;
5
+
6
+ type NodePerfHooksPerformance = import("perf_hooks").Performance;
7
+ type LibPerformanceOrNodePerfHooksPerformance = Bun.__internal.UseLibDomIfAvailable<
8
+ "Performance",
9
+ NodePerfHooksPerformance
10
+ >;
11
+
12
+ type NodeCryptoWebcryptoSubtleCrypto = import("crypto").webcrypto.SubtleCrypto;
13
+ type NodeCryptoWebcryptoCryptoKey = import("crypto").webcrypto.CryptoKey;
14
+ type NodeUtilTextEncoder = import("util").TextEncoder;
15
+ type NodeUtilTextDecoder = import("util").TextDecoder;
16
+
17
+ type LibEmptyOrNodeReadableStream<T = any> = LibDomIsLoaded extends true
18
+ ? {}
19
+ : import("stream/web").ReadableStream<T>;
20
+
21
+ type LibEmptyOrNodeWritableStream<T = any> = LibDomIsLoaded extends true
22
+ ? {}
23
+ : import("stream/web").WritableStream<T>;
24
+
25
+ type LibEmptyOrNodeTransformStream<I = any, O = any> = LibDomIsLoaded extends true
26
+ ? {}
27
+ : import("stream/web").TransformStream<I, O>;
28
+ }
29
+ }
30
+
31
+ interface ReadableStream<R = any> extends Bun.__internal.LibEmptyOrNodeReadableStream {}
32
+ declare var ReadableStream: Bun.__internal.UseLibDomIfAvailable<
33
+ "ReadableStream",
34
+ {
35
+ prototype: ReadableStream;
36
+ new <R = any>(underlyingSource?: Bun.UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
37
+ new <R = any>(underlyingSource?: Bun.DirectUnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
38
+ }
39
+ >;
40
+
41
+ interface WritableStream<W = any> extends Bun.__internal.LibEmptyOrNodeWritableStream {}
42
+ declare var WritableStream: Bun.__internal.UseLibDomIfAvailable<
43
+ "WritableStream",
44
+ {
45
+ prototype: WritableStream;
46
+ new <W = any>(underlyingSink?: Bun.UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
47
+ }
48
+ >;
49
+
50
+ interface Worker extends Bun.__internal.LibWorkerOrNodeWorkerThreadsWorker {}
51
+ declare var Worker: Bun.__internal.UseLibDomIfAvailable<
52
+ "Worker",
53
+ {
54
+ prototype: Worker;
55
+ new (scriptURL: string | URL, options?: Bun.WorkerOptions | undefined): Worker;
56
+ /**
57
+ * This is the cloned value of the `data` property passed to `new Worker()`
58
+ *
59
+ * This is Bun's equivalent of `workerData` in Node.js.
60
+ */
61
+ data: any;
62
+ }
63
+ >;
64
+
65
+ declare var WebSocket: Bun.__internal.UseLibDomIfAvailable<"WebSocket", typeof import("ws").WebSocket>;
66
+
67
+ interface Crypto {}
68
+ declare var Crypto: {
69
+ prototype: Crypto;
70
+ new (): Crypto;
71
+ };
72
+
73
+ declare var crypto: Crypto;
74
+
75
+ /**
76
+ * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
77
+ * instances of `TextEncoder` only support UTF-8 encoding.
78
+ *
79
+ * ```js
80
+ * const encoder = new TextEncoder();
81
+ * const uint8array = encoder.encode('this is some data');
82
+ * ```
83
+ */
84
+ interface TextEncoder extends Bun.__internal.NodeUtilTextEncoder {
85
+ /**
86
+ * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
87
+ * containing the read Unicode code units and written UTF-8 bytes.
88
+ *
89
+ * ```js
90
+ * const encoder = new TextEncoder();
91
+ * const src = 'this is some data';
92
+ * const dest = new Uint8Array(10);
93
+ * const { read, written } = encoder.encodeInto(src, dest);
94
+ * ```
95
+ * @param src The text to encode.
96
+ * @param dest The array to hold the encode result.
97
+ */
98
+ encodeInto(src?: string, dest?: Bun.BufferSource): import("util").EncodeIntoResult;
99
+ }
100
+ declare var TextEncoder: Bun.__internal.UseLibDomIfAvailable<
101
+ "TextEncoder",
102
+ {
103
+ prototype: TextEncoder;
104
+ new (encoding?: Bun.Encoding, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextEncoder;
105
+ }
106
+ >;
107
+
108
+ /**
109
+ * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. All
110
+ * instances of `TextDecoder` only support UTF-8 decoding.
111
+ *
112
+ * ```js
113
+ * const decoder = new TextDecoder();
114
+ * const uint8array = decoder.decode('this is some data');
115
+ */
116
+ declare var TextDecoder: Bun.__internal.UseLibDomIfAvailable<
117
+ "TextDecoder",
118
+ {
119
+ prototype: Bun.__internal.NodeUtilTextDecoder;
120
+ new (
121
+ encoding?: Bun.Encoding,
122
+ options?: { fatal?: boolean; ignoreBOM?: boolean },
123
+ ): Bun.__internal.NodeUtilTextDecoder;
124
+ }
125
+ >;
126
+
127
+ // interface Event {
128
+ // /** This is not used in Node.js and is provided purely for completeness. */
129
+ // readonly bubbles: boolean;
130
+ // /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
131
+ // cancelBubble: () => void;
132
+ // /** True if the event was created with the cancelable option */
133
+ // readonly cancelable: boolean;
134
+ // /** This is not used in Node.js and is provided purely for completeness. */
135
+ // readonly composed: boolean;
136
+ // /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
137
+ // composedPath(): [EventTarget?];
138
+ // /** Alias for event.target. */
139
+ // readonly currentTarget: EventTarget | null;
140
+ // /** Is true if cancelable is true and event.preventDefault() has been called. */
141
+ // readonly defaultPrevented: boolean;
142
+ // /** This is not used in Node.js and is provided purely for completeness. */
143
+ // readonly eventPhase: typeof globalThis extends { Event: infer T extends {eventPhase: number} } ? T['eventPhase'] : 0 | 2;
144
+ // /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
145
+ // readonly isTrusted: boolean;
146
+ // /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
147
+ // preventDefault(): void;
148
+ // /** This is not used in Node.js and is provided purely for completeness. */
149
+ // returnValue: boolean;
150
+ // /** Alias for event.target. */
151
+ // readonly srcElement: EventTarget | null;
152
+ // /** Stops the invocation of event listeners after the current one completes. */
153
+ // stopImmediatePropagation(): void;
154
+ // /** This is not used in Node.js and is provided purely for completeness. */
155
+ // stopPropagation(): void;
156
+ // /** The `EventTarget` dispatching the event */
157
+ // readonly target: EventTarget | null;
158
+ // /** The millisecond timestamp when the Event object was created. */
159
+ // readonly timeStamp: number;
160
+ // /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
161
+ // readonly type: string;
162
+ // }
163
+ declare var Event: {
164
+ prototype: Event;
165
+ readonly NONE: 0;
166
+ readonly CAPTURING_PHASE: 1;
167
+ readonly AT_TARGET: 2;
168
+ readonly BUBBLING_PHASE: 3;
169
+ new (type: string, eventInitDict?: Bun.EventInit): Event;
170
+ };
171
+
172
+ interface EventTarget {
173
+ /**
174
+ * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
175
+ *
176
+ * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
177
+ *
178
+ * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
179
+ * Specifically, the `capture` option is used as part of the key when registering a `listener`.
180
+ * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
181
+ */
182
+ addEventListener(
183
+ type: string,
184
+ listener: EventListener | EventListenerObject,
185
+ options?: AddEventListenerOptions | boolean,
186
+ ): void;
187
+ /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
188
+ dispatchEvent(event: Event): boolean;
189
+ /** Removes the event listener in target's event listener list with the same type, callback, and options. */
190
+ removeEventListener(
191
+ type: string,
192
+ listener: EventListener | EventListenerObject,
193
+ options?: Bun.EventListenerOptions | boolean,
194
+ ): void;
195
+ }
196
+ declare var EventTarget: {
197
+ prototype: EventTarget;
198
+ new (): EventTarget;
199
+ };
200
+
201
+ interface File extends Blob {
202
+ readonly lastModified: number;
203
+ readonly name: string;
204
+ }
205
+
206
+ declare var File: typeof globalThis extends { onabort: any }
207
+ ? typeof globalThis extends { File: infer T }
208
+ ? T
209
+ : never
210
+ : {
211
+ prototype: File;
212
+ /**
213
+ * Create a new [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
214
+ *
215
+ * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
216
+ * @param `name` - The name of the file
217
+ * @param `options` - An object containing properties to be added to the [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
218
+ */
219
+ new (
220
+ parts: Bun.BlobPart[],
221
+ name: string,
222
+ options?: BlobPropertyBag & { lastModified?: Date | number | undefined },
223
+ ): File;
224
+ };
225
+
226
+ /**
227
+ * ShadowRealms are a distinct global environment, with its own global object
228
+ * containing its own intrinsics and built-ins (standard objects that are not
229
+ * bound to global variables, like the initial value of Object.prototype).
230
+ *
231
+ * @example
232
+ *
233
+ * ```js
234
+ * const red = new ShadowRealm();
235
+ *
236
+ * // realms can import modules that will execute within it's own environment.
237
+ * // When the module is resolved, it captured the binding value, or creates a new
238
+ * // wrapped function that is connected to the callable binding.
239
+ * const redAdd = await red.importValue('./inside-code.js', 'add');
240
+ *
241
+ * // redAdd is a wrapped function exotic object that chains it's call to the
242
+ * // respective imported binding.
243
+ * let result = redAdd(2, 3);
244
+ *
245
+ * console.assert(result === 5); // yields true
246
+ *
247
+ * // The evaluate method can provide quick code evaluation within the constructed
248
+ * // shadowRealm without requiring any module loading, while it still requires CSP
249
+ * // relaxing.
250
+ * globalThis.someValue = 1;
251
+ * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
252
+ * console.assert(globalThis.someValue === 1);
253
+ *
254
+ * // The wrapped functions can also wrap other functions the other way around.
255
+ * const setUniqueValue =
256
+ * await red.importValue('./inside-code.js', 'setUniqueValue');
257
+ *
258
+ * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);
259
+ *
260
+ * result = setUniqueValue((x) => x ** 3);
261
+ *
262
+ * console.assert(result === 16); // yields true
263
+ * ```
264
+ */
265
+ interface ShadowRealm {
266
+ /**
267
+ * Creates a new [ShadowRealm](https://github.com/tc39/proposal-shadowrealm/blob/main/explainer.md#introduction)
268
+ *
269
+ * @example
270
+ *
271
+ * ```js
272
+ * const red = new ShadowRealm();
273
+ *
274
+ * // realms can import modules that will execute within it's own environment.
275
+ * // When the module is resolved, it captured the binding value, or creates a new
276
+ * // wrapped function that is connected to the callable binding.
277
+ * const redAdd = await red.importValue('./inside-code.js', 'add');
278
+ *
279
+ * // redAdd is a wrapped function exotic object that chains it's call to the
280
+ * // respective imported binding.
281
+ * let result = redAdd(2, 3);
282
+ *
283
+ * console.assert(result === 5); // yields true
284
+ *
285
+ * // The evaluate method can provide quick code evaluation within the constructed
286
+ * // shadowRealm without requiring any module loading, while it still requires CSP
287
+ * // relaxing.
288
+ * globalThis.someValue = 1;
289
+ * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
290
+ * console.assert(globalThis.someValue === 1);
291
+ *
292
+ * // The wrapped functions can also wrap other functions the other way around.
293
+ * const setUniqueValue =
294
+ * await red.importValue('./inside-code.js', 'setUniqueValue');
295
+ *
296
+ * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);
297
+ *
298
+ * result = setUniqueValue((x) => x ** 3);
299
+ *
300
+ * console.assert(result === 16); // yields true
301
+ * ```
302
+ */
303
+ importValue(specifier: string, bindingName: string): Promise<any>;
304
+ evaluate(sourceText: string): any;
305
+ }
306
+
307
+ declare var ShadowRealm: {
308
+ prototype: ShadowRealm;
309
+ new (): ShadowRealm;
310
+ };
311
+
312
+ declare function queueMicrotask(callback: (...args: any[]) => void): void;
313
+ /**
314
+ * Log an error using the default exception handler
315
+ * @param error Error or string
316
+ */
317
+ declare function reportError(error: any): void;
318
+
319
+ interface Timer {
320
+ ref(): Timer;
321
+ unref(): Timer;
322
+ hasRef(): boolean;
323
+ refresh(): Timer;
324
+
325
+ [Symbol.toPrimitive](): number;
326
+ }
327
+
328
+ /**
329
+ * Cancel a repeating timer by its timer ID.
330
+ * @param id timer id
331
+ */
332
+ declare function clearInterval(id?: number | Timer): void;
333
+ /**
334
+ * Cancel a delayed function call by its timer ID.
335
+ * @param id timer id
336
+ */
337
+ declare function clearTimeout(id?: number | Timer): void;
338
+ /**
339
+ * Cancel an immediate function call by its immediate ID.
340
+ * @param id immediate id
341
+ */
342
+ declare function clearImmediate(id?: number | Timer): void;
343
+ /**
344
+ * Run a function immediately after main event loop is vacant
345
+ * @param handler function to call
346
+ */
347
+ declare function setImmediate(handler: Bun.TimerHandler, ...arguments: any[]): Timer;
348
+ /**
349
+ * Run a function every `interval` milliseconds
350
+ * @param handler function to call
351
+ * @param interval milliseconds to wait between calls
352
+ */
353
+ declare function setInterval(handler: Bun.TimerHandler, interval?: number, ...arguments: any[]): Timer;
354
+ /**
355
+ * Run a function after `timeout` (milliseconds)
356
+ * @param handler function to call
357
+ * @param timeout milliseconds to wait between calls
358
+ */
359
+ declare function setTimeout(handler: Bun.TimerHandler, timeout?: number, ...arguments: any[]): Timer;
360
+
361
+ declare function addEventListener<K extends keyof EventMap>(
362
+ type: K,
363
+ listener: (this: object, ev: EventMap[K]) => any,
364
+ options?: boolean | AddEventListenerOptions,
365
+ ): void;
366
+ declare function addEventListener(
367
+ type: string,
368
+ listener: Bun.EventListenerOrEventListenerObject,
369
+ options?: boolean | AddEventListenerOptions,
370
+ ): void;
371
+ declare function removeEventListener<K extends keyof EventMap>(
372
+ type: K,
373
+ listener: (this: object, ev: EventMap[K]) => any,
374
+ options?: boolean | Bun.EventListenerOptions,
375
+ ): void;
376
+ declare function removeEventListener(
377
+ type: string,
378
+ listener: Bun.EventListenerOrEventListenerObject,
379
+ options?: boolean | Bun.EventListenerOptions,
380
+ ): void;
381
+
382
+ /**
383
+ * Events providing information related to errors in scripts or in files.
384
+ */
385
+ interface ErrorEvent extends Event {
386
+ readonly colno: number;
387
+ readonly error: any;
388
+ readonly filename: string;
389
+ readonly lineno: number;
390
+ readonly message: string;
391
+ }
392
+
393
+ declare var ErrorEvent: {
394
+ prototype: ErrorEvent;
395
+ new (type: string, eventInitDict?: Bun.ErrorEventInit): ErrorEvent;
396
+ };
397
+
398
+ /** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
399
+ interface CloseEvent extends Event {
400
+ /** Returns the WebSocket connection close code provided by the server. */
401
+ readonly code: number;
402
+ /** Returns the WebSocket connection close reason provided by the server. */
403
+ readonly reason: string;
404
+ /** Returns true if the connection closed cleanly; false otherwise. */
405
+ readonly wasClean: boolean;
406
+ }
407
+
408
+ declare var CloseEvent: {
409
+ prototype: CloseEvent;
410
+ new (type: string, eventInitDict?: Bun.CloseEventInit): CloseEvent;
411
+ };
412
+
413
+ interface MessageEvent<T = any> extends Bun.MessageEvent<T> {}
414
+ declare var MessageEvent: Bun.__internal.UseLibDomIfAvailable<"MessageEvent", MessageEvent>;
415
+
416
+ interface CustomEvent<T = any> extends Event {
417
+ /** Returns any custom data event was created with. Typically used for synthetic events. */
418
+ readonly detail: T;
419
+ }
420
+
421
+ declare var CustomEvent: {
422
+ prototype: CustomEvent;
423
+ new <T>(type: string, eventInitDict?: Bun.CustomEventInit<T>): CustomEvent<T>;
424
+ };
425
+
426
+ interface EventListener {
427
+ (evt: Event): void;
428
+ }
429
+
430
+ interface EventListenerObject {
431
+ handleEvent(object: Event): void;
432
+ }
433
+
434
+ interface FetchEvent extends Event {
435
+ readonly request: Request;
436
+ readonly url: string;
437
+
438
+ waitUntil(promise: Promise<any>): void;
439
+ respondWith(response: Response | Promise<Response>): void;
440
+ }
441
+
442
+ interface EventMap {
443
+ fetch: FetchEvent;
444
+ message: MessageEvent;
445
+ messageerror: MessageEvent;
446
+ // exit: Event;
447
+ }
448
+
449
+ interface AddEventListenerOptions extends Bun.EventListenerOptions {
450
+ once?: boolean;
451
+ passive?: boolean;
452
+ signal?: AbortSignal;
453
+ }
454
+
455
+ /**
456
+ * Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API)
457
+ *
458
+ * Before using this, be aware of a few things:
459
+ *
460
+ * **Using this incorrectly will crash your application**.
461
+ *
462
+ * This API may change any time JavaScriptCore is updated.
463
+ *
464
+ * Bun may rewrite ESM import specifiers to point to bundled code. This will
465
+ * be confusing when using this API, as it will return a string like
466
+ * "/node_modules.server.bun".
467
+ *
468
+ * Bun may inject additional imports into your code. This usually has a `bun:` prefix.
469
+ */
470
+ declare var Loader: {
471
+ /**
472
+ * ESM module registry
473
+ *
474
+ * This lets you implement live reload in Bun. If you
475
+ * delete a module specifier from this map, the next time it's imported, it
476
+ * will be re-transpiled and loaded again.
477
+ *
478
+ * The keys are the module specifiers and the
479
+ * values are metadata about the module.
480
+ *
481
+ * The keys are an implementation detail for Bun that will change between
482
+ * versions.
483
+ *
484
+ * - Userland modules are an absolute file path
485
+ * - Virtual modules have a `bun:` prefix or `node:` prefix
486
+ * - JS polyfills start with `"/bun-vfs/"`. `"buffer"` is an example of a JS polyfill
487
+ * - If you have a `node_modules.bun` file, many modules will point to that file
488
+ *
489
+ * Virtual modules and JS polyfills are embedded in bun's binary. They don't
490
+ * point to anywhere in your local filesystem.
491
+ */
492
+ registry: Map<
493
+ string,
494
+ {
495
+ key: string;
496
+ /**
497
+ * This refers to the state the ESM module is in
498
+ *
499
+ * TODO: make an enum for this number
500
+ */
501
+ state: number;
502
+ fetch: Promise<any>;
503
+ instantiate: Promise<any>;
504
+ satisfy: Promise<any>;
505
+ dependencies: Array<(typeof Loader)["registry"] extends Map<any, infer V> ? V : any>;
506
+ /**
507
+ * Your application will probably crash if you mess with this.
508
+ */
509
+ module: {
510
+ dependenciesMap: (typeof Loader)["registry"];
511
+ };
512
+ linkError?: any;
513
+ linkSucceeded: boolean;
514
+ evaluated: boolean;
515
+ then?: any;
516
+ isAsync: boolean;
517
+ }
518
+ >;
519
+ /**
520
+ * For an already-evaluated module, return the dependencies as module specifiers
521
+ *
522
+ * This list is already sorted and uniqued.
523
+ *
524
+ * @example
525
+ *
526
+ * For this code:
527
+ * ```js
528
+ * // /foo.js
529
+ * import classNames from 'classnames';
530
+ * import React from 'react';
531
+ * import {createElement} from 'react';
532
+ * ```
533
+ *
534
+ * This would return:
535
+ * ```js
536
+ * Loader.dependencyKeysIfEvaluated("/foo.js")
537
+ * ["bun:wrap", "/path/to/node_modules/classnames/index.js", "/path/to/node_modules/react/index.js"]
538
+ * ```
539
+ *
540
+ * @param specifier - module specifier as it appears in transpiled source code
541
+ */
542
+ dependencyKeysIfEvaluated: (specifier: string) => string[];
543
+ /**
544
+ * The function JavaScriptCore internally calls when you use an import statement.
545
+ *
546
+ * This may return a path to `node_modules.server.bun`, which will be confusing.
547
+ *
548
+ * Consider {@link Bun.resolve} or {@link ImportMeta.resolve}
549
+ * instead.
550
+ *
551
+ * @param specifier - module specifier as it appears in transpiled source code
552
+ * @param referrer - module specifier that is resolving this specifier
553
+ */
554
+ resolve: (specifier: string, referrer: string) => string;
555
+ };
556
+
557
+ interface QueuingStrategy<T = any> {
558
+ highWaterMark?: number;
559
+ size?: QueuingStrategySize<T>;
560
+ }
561
+
562
+ interface QueuingStrategyInit {
563
+ /**
564
+ * Creates a new ByteLengthQueuingStrategy with the provided high water mark.
565
+ *
566
+ * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.
567
+ */
568
+ highWaterMark: number;
569
+ }
570
+
571
+ /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */
572
+ interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
573
+ readonly highWaterMark: number;
574
+ // changed from QueuingStrategySize<BufferSource>
575
+ // to avoid conflict with lib.dom.d.ts
576
+ readonly size: QueuingStrategySize<ArrayBufferView>;
577
+ }
578
+
579
+ declare var ByteLengthQueuingStrategy: {
580
+ prototype: ByteLengthQueuingStrategy;
581
+ new (init: QueuingStrategyInit): ByteLengthQueuingStrategy;
582
+ };
583
+
584
+ interface ReadableStreamDefaultController<R = any> {
585
+ readonly desiredSize: number | null;
586
+ close(): void;
587
+ enqueue(chunk?: R): void;
588
+ error(e?: any): void;
589
+ }
590
+
591
+ interface ReadableStreamDirectController {
592
+ close(error?: Error): void;
593
+ write(data: Bun.BufferSource | ArrayBuffer | string): number | Promise<number>;
594
+ end(): number | Promise<number>;
595
+ flush(): number | Promise<number>;
596
+ start(): void;
597
+ }
598
+
599
+ declare var ReadableStreamDefaultController: {
600
+ prototype: ReadableStreamDefaultController;
601
+ new (): ReadableStreamDefaultController;
602
+ };
603
+
604
+ interface ReadableStreamDefaultReader<R = any> extends ReadableStreamGenericReader {
605
+ read(): Promise<Bun.ReadableStreamDefaultReadResult<R>>;
606
+ /**
607
+ * Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time.
608
+ * Will only return a promise if the data is not immediately available.
609
+ */
610
+ readMany(): Promise<Bun.ReadableStreamDefaultReadManyResult<R>> | Bun.ReadableStreamDefaultReadManyResult<R>;
611
+ releaseLock(): void;
612
+ }
613
+
614
+ declare var ReadableStreamDefaultReader: {
615
+ prototype: ReadableStreamDefaultReader;
616
+ new <R = any>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>;
617
+ };
618
+
619
+ interface ReadableStreamGenericReader {
620
+ readonly closed: Promise<void>;
621
+ cancel(reason?: any): Promise<void>;
622
+ }
623
+
624
+ interface ReadableStreamDefaultReadDoneResult {
625
+ done: true;
626
+ value?: undefined;
627
+ }
628
+
629
+ interface ReadableStreamDefaultReadValueResult<T> {
630
+ done: false;
631
+ value: T;
632
+ }
633
+
634
+ interface ReadableWritablePair<R = any, W = any> {
635
+ readable: ReadableStream<R>;
636
+ /**
637
+ * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.
638
+ *
639
+ * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
640
+ */
641
+ writable: WritableStream<W>;
642
+ }
643
+
644
+ interface WritableStreamDefaultController {
645
+ error(e?: any): void;
646
+ }
647
+
648
+ declare var WritableStreamDefaultController: {
649
+ prototype: WritableStreamDefaultController;
650
+ new (): WritableStreamDefaultController;
651
+ };
652
+
653
+ /** This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */
654
+ interface WritableStreamDefaultWriter<W = any> {
655
+ readonly closed: Promise<void>;
656
+ readonly desiredSize: number | null;
657
+ readonly ready: Promise<void>;
658
+ abort(reason?: any): Promise<void>;
659
+ close(): Promise<void>;
660
+ releaseLock(): void;
661
+ write(chunk?: W): Promise<void>;
662
+ }
663
+
664
+ declare var WritableStreamDefaultWriter: {
665
+ prototype: WritableStreamDefaultWriter;
666
+ new <W = any>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>;
38
667
  };
39
668
 
40
- type _EventTarget = {
41
- /**
42
- * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
43
- *
44
- * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
45
- *
46
- * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
47
- * Specifically, the `capture` option is used as part of the key when registering a `listener`.
48
- * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
49
- */
50
- addEventListener(
51
- type: string,
52
- listener: EventListener | EventListenerObject,
53
- options?: AddEventListenerOptions | boolean,
54
- ): void;
55
- /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
56
- dispatchEvent(event: Event): boolean;
57
- /** Removes the event listener in target's event listener list with the same type, callback, and options. */
58
- removeEventListener(
59
- type: string,
60
- listener: EventListener | EventListenerObject,
61
- options?: Bun.EventListenerOptions | boolean,
62
- ): void;
669
+ interface TransformStream<I = any, O = any> {
670
+ readonly readable: ReadableStream<O>;
671
+ readonly writable: WritableStream<I>;
672
+ }
673
+
674
+ declare var TransformStream: {
675
+ prototype: TransformStream;
676
+ new <I = any, O = any>(
677
+ transformer?: Transformer<I, O>,
678
+ writableStrategy?: QueuingStrategy<I>,
679
+ readableStrategy?: QueuingStrategy<O>,
680
+ ): TransformStream<I, O>;
681
+ };
682
+
683
+ interface TransformStreamDefaultController<O = any> {
684
+ readonly desiredSize: number | null;
685
+ enqueue(chunk?: O): void;
686
+ error(reason?: any): void;
687
+ terminate(): void;
688
+ }
689
+
690
+ declare var TransformStreamDefaultController: {
691
+ prototype: TransformStreamDefaultController;
692
+ new (): TransformStreamDefaultController;
693
+ };
694
+
695
+ interface StreamPipeOptions {
696
+ preventAbort?: boolean;
697
+ preventCancel?: boolean;
698
+ /**
699
+ * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
700
+ *
701
+ * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
702
+ *
703
+ * Errors and closures of the source and destination streams propagate as follows:
704
+ *
705
+ * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.
706
+ *
707
+ * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.
708
+ *
709
+ * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.
710
+ *
711
+ * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.
712
+ *
713
+ * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.
714
+ */
715
+ preventClose?: boolean;
716
+ signal?: AbortSignal;
717
+ }
718
+
719
+ /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */
720
+ interface CountQueuingStrategy extends QueuingStrategy {
721
+ readonly highWaterMark: number;
722
+ readonly size: QueuingStrategySize;
723
+ }
724
+
725
+ declare var CountQueuingStrategy: {
726
+ prototype: CountQueuingStrategy;
727
+ new (init: QueuingStrategyInit): CountQueuingStrategy;
63
728
  };
64
729
 
65
- declare global {
66
- var Bun: typeof import("bun");
67
-
68
- namespace NodeJS {
69
- interface Process {
70
- readonly version: string;
71
- browser: boolean;
72
-
73
- /** Whether you are using Bun */
74
- isBun: true;
75
- /** The current git sha of Bun **/
76
- revision: string;
77
- reallyExit(code?: number): never;
78
- dlopen(module: { exports: any }, filename: string, flags?: number): void;
79
- _exiting: boolean;
80
- noDeprecation: boolean;
81
-
82
- binding(m: string): object;
83
- binding(m: "constants"): {
84
- os: typeof import("node:os").constants;
85
- fs: typeof import("node:fs").constants;
86
- crypto: typeof import("node:crypto").constants;
87
- zlib: typeof import("node:zlib").constants;
88
- trace: typeof import("node:trace").constants;
89
- };
90
- }
91
- }
92
-
93
- namespace Bun {
94
- type ArrayBufferView = NodeJS.TypedArray | DataView;
95
- type StringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike;
96
- type PathLike = import("bun").PathLike;
97
- type BodyInit = ReadableStream | XMLHttpRequestBodyInit | URLSearchParams;
98
- type XMLHttpRequestBodyInit = Blob | BufferSource | string | FormData;
99
- type ReadableStreamController<T> = ReadableStreamDefaultController<T>;
100
- type ReadableStreamDefaultReadResult<T> =
101
- | ReadableStreamDefaultReadValueResult<T>
102
- | ReadableStreamDefaultReadDoneResult;
103
- type ReadableStreamReader<T> = ReadableStreamDefaultReader<T>;
104
- type Transferable = ArrayBuffer | import("worker_threads").MessagePort;
105
- type MessageEventSource = undefined;
106
- type Encoding = "utf-8" | "windows-1252" | "utf-16";
107
- type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection";
108
- type MultipleResolveType = "resolve" | "reject";
109
- type BeforeExitListener = (code: number) => void;
110
- type DisconnectListener = () => void;
111
- type ExitListener = (code: number) => void;
112
- type RejectionHandledListener = (promise: Promise<unknown>) => void;
113
- type FormDataEntryValue = File | string;
114
- type WarningListener = (warning: Error) => void;
115
- type MessageListener = (message: unknown, sendHandle: unknown) => void;
116
- type SignalsListener = (signal: NodeJS.Signals) => void;
117
- type BlobPart = string | Blob | BufferSource;
118
- type TimerHandler = (...args: any[]) => void;
119
- type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike;
120
- type DOMHighResTimeStamp = number;
121
- type EventListenerOrEventListenerObject =
122
- | EventListener
123
- | EventListenerObject;
124
-
125
- type BlobOrStringOrBuffer =
126
- | string
127
- | NodeJS.TypedArray
128
- | ArrayBufferLike
129
- | Blob;
130
-
131
- type Platform =
132
- | "aix"
133
- | "android"
134
- | "darwin"
135
- | "freebsd"
136
- | "haiku"
137
- | "linux"
138
- | "openbsd"
139
- | "sunos"
140
- | "win32"
141
- | "cygwin"
142
- | "netbsd";
143
- type Architecture =
144
- | "arm"
145
- | "arm64"
146
- | "ia32"
147
- | "mips"
148
- | "mipsel"
149
- | "ppc"
150
- | "ppc64"
151
- | "s390"
152
- | "s390x"
153
- | "x64";
154
-
155
- type UncaughtExceptionListener = (
156
- error: Error,
157
- origin: UncaughtExceptionOrigin,
158
- ) => void;
159
- /**
160
- * Most of the time the unhandledRejection will be an Error, but this should not be relied upon
161
- * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error.
162
- */
163
- type UnhandledRejectionListener = (
164
- reason: unknown,
165
- promise: Promise<unknown>,
166
- ) => void;
167
-
168
- type MultipleResolveListener = (
169
- type: MultipleResolveType,
170
- promise: Promise<unknown>,
171
- value: unknown,
172
- ) => void;
173
-
174
- type HeadersInit =
175
- | Headers
176
- | Record<string, string>
177
- | Array<[string, string]>
178
- | IterableIterator<[string, string]>;
179
-
180
- type ResponseType =
181
- | "basic"
182
- | "cors"
183
- | "default"
184
- | "error"
185
- | "opaque"
186
- | "opaqueredirect";
187
-
188
- type _TextEncoder = import("util").TextEncoder;
189
- interface TextEncoder extends _TextEncoder {
190
- new (
191
- encoding?: Bun.Encoding,
192
- options?: { fatal?: boolean; ignoreBOM?: boolean },
193
- ): TextEncoder;
194
- /**
195
- * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
196
- * containing the read Unicode code units and written UTF-8 bytes.
197
- *
198
- * ```js
199
- * const encoder = new TextEncoder();
200
- * const src = 'this is some data';
201
- * const dest = new Uint8Array(10);
202
- * const { read, written } = encoder.encodeInto(src, dest);
203
- * ```
204
- * @param src The text to encode.
205
- * @param dest The array to hold the encode result.
206
- */
207
- encodeInto(
208
- src?: string,
209
- dest?: Bun.BufferSource,
210
- ): import("util").EncodeIntoResult;
211
- }
212
-
213
- type _TextDecoder = import("util").TextDecoder;
214
- interface TextDecoder extends _TextDecoder {
215
- new (
216
- encoding?: Bun.Encoding,
217
- options?: { fatal?: boolean; ignoreBOM?: boolean },
218
- ): TextDecoder;
219
- }
220
-
221
- interface ErrorEventInit extends EventInit {
222
- colno?: number;
223
- error?: any;
224
- filename?: string;
225
- lineno?: number;
226
- message?: string;
227
- }
228
-
229
- interface CloseEventInit extends EventInit {
230
- code?: number;
231
- reason?: string;
232
- wasClean?: boolean;
233
- }
234
-
235
- interface MessageEventInit<T = any> extends EventInit {
236
- data?: T;
237
- lastEventId?: string;
238
- origin?: string;
239
- source?: Bun.MessageEventSource | null;
240
- }
241
-
242
- interface EventInit {
243
- bubbles?: boolean;
244
- cancelable?: boolean;
245
- composed?: boolean;
246
- }
247
-
248
- interface EventListenerOptions {
249
- capture?: boolean;
250
- }
251
-
252
- interface CustomEventInit<T = any> extends Bun.EventInit {
253
- detail?: T;
254
- }
255
-
256
- /** A message received by a target object. */
257
- interface MessageEvent<T = any> extends Event {
258
- /** Returns the data of the message. */
259
- readonly data: T;
260
- /** Returns the last event ID string, for server-sent events. */
261
- readonly lastEventId: string;
262
- /** Returns the origin of the message, for server-sent events and cross-document messaging. */
263
- readonly origin: string;
264
- /** Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. */
265
- readonly ports: readonly (typeof MessagePort)[]; // ReadonlyArray<typeof import("worker_threads").MessagePort["prototype"]>;
266
- readonly source: Bun.MessageEventSource | null;
267
- }
268
-
269
- interface ReadableStreamDefaultReadManyResult<T> {
270
- done: boolean;
271
- /** Number of bytes */
272
- size: number;
273
- value: T[];
274
- }
275
-
276
- interface ResponseInit {
277
- headers?: HeadersInit;
278
- /** @default 200 */
279
- status?: number;
280
-
281
- /** @default "OK" */
282
- statusText?: string;
283
- }
284
-
285
- interface EventSourceEventMap {
286
- error: Event;
287
- message: MessageEvent;
288
- open: Event;
289
- }
290
-
291
- interface EventInit {
292
- bubbles?: boolean;
293
- cancelable?: boolean;
294
- composed?: boolean;
295
- }
296
-
297
- interface EventListenerOptions {
298
- /** Not directly used by Node.js. Added for API completeness. Default: `false`. */
299
- capture?: boolean;
300
- }
301
-
302
- interface AddEventListenerOptions extends EventListenerOptions {
303
- /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */
304
- once?: boolean;
305
- /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */
306
- passive?: boolean;
307
- signal?: AbortSignal;
308
- }
309
-
310
- interface EventListener {
311
- (evt: Event): void;
312
- }
313
-
314
- interface EventListenerObject {
315
- handleEvent(object: Event): void;
316
- }
317
-
318
- interface FetchEvent extends Event {
319
- readonly request: Request;
320
- readonly url: string;
321
-
322
- waitUntil(promise: Promise<any>): void;
323
- respondWith(response: Response | Promise<Response>): void;
324
- }
325
-
326
- interface EventMap {
327
- fetch: FetchEvent;
328
- message: MessageEvent;
329
- messageerror: MessageEvent;
330
- // exit: Event;
331
- }
332
-
333
- interface StructuredSerializeOptions {
334
- transfer?: Bun.Transferable[];
335
- }
336
-
337
- interface EventSource extends EventTarget {
338
- new (
339
- url: string | URL,
340
- eventSourceInitDict?: EventSourceInit,
341
- ): EventSource;
342
-
343
- onerror: ((this: EventSource, ev: Event) => any) | null;
344
- onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;
345
- onopen: ((this: EventSource, ev: Event) => any) | null;
346
- /** Returns the state of this EventSource object's connection. It can have the values described below. */
347
- readonly readyState: number;
348
- /** Returns the URL providing the event stream. */
349
- readonly url: string;
350
- /** Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
351
- *
352
- * Not supported in Bun
353
- */
354
- readonly withCredentials: boolean;
355
- /** Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. */
356
- close(): void;
357
- readonly CLOSED: 2;
358
- readonly CONNECTING: 0;
359
- readonly OPEN: 1;
360
- addEventListener<K extends keyof EventSourceEventMap>(
361
- type: K,
362
- listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
363
- options?: boolean | AddEventListenerOptions,
364
- ): void;
365
- addEventListener(
366
- type: string,
367
- listener: (this: EventSource, event: MessageEvent) => any,
368
- options?: boolean | AddEventListenerOptions,
369
- ): void;
370
- addEventListener(
371
- type: string,
372
- listener: EventListenerOrEventListenerObject,
373
- options?: boolean | AddEventListenerOptions,
374
- ): void;
375
- removeEventListener<K extends keyof EventSourceEventMap>(
376
- type: K,
377
- listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
378
- options?: boolean | EventListenerOptions,
379
- ): void;
380
- removeEventListener(
381
- type: string,
382
- listener: (this: EventSource, event: MessageEvent) => any,
383
- options?: boolean | EventListenerOptions,
384
- ): void;
385
- removeEventListener(
386
- type: string,
387
- listener: EventListenerOrEventListenerObject,
388
- options?: boolean | EventListenerOptions,
389
- ): void;
390
-
391
- /**
392
- * Keep the event loop alive while connection is open or reconnecting
393
- *
394
- * Not available in browsers
395
- */
396
- ref(): void;
397
-
398
- /**
399
- * Do not keep the event loop alive while connection is open or reconnecting
400
- *
401
- * Not available in browsers
402
- */
403
- unref(): void;
404
- }
405
-
406
- interface TransformerFlushCallback<O> {
407
- (
408
- controller: TransformStreamDefaultController<O>,
409
- ): void | PromiseLike<void>;
410
- }
411
-
412
- interface TransformerStartCallback<O> {
413
- (controller: TransformStreamDefaultController<O>): any;
414
- }
415
-
416
- interface TransformerTransformCallback<I, O> {
417
- (
418
- chunk: I,
419
- controller: TransformStreamDefaultController<O>,
420
- ): void | PromiseLike<void>;
421
- }
422
-
423
- interface UnderlyingSinkAbortCallback {
424
- (reason?: any): void | PromiseLike<void>;
425
- }
426
-
427
- interface UnderlyingSinkCloseCallback {
428
- (): void | PromiseLike<void>;
429
- }
430
-
431
- interface UnderlyingSinkStartCallback {
432
- (controller: WritableStreamDefaultController): any;
433
- }
434
-
435
- interface UnderlyingSinkWriteCallback<W> {
436
- (
437
- chunk: W,
438
- controller: WritableStreamDefaultController,
439
- ): void | PromiseLike<void>;
440
- }
441
-
442
- interface UnderlyingSourceCancelCallback {
443
- (reason?: any): void | PromiseLike<void>;
444
- }
445
-
446
- interface UnderlyingSink<W = any> {
447
- abort?: UnderlyingSinkAbortCallback;
448
- close?: UnderlyingSinkCloseCallback;
449
- start?: UnderlyingSinkStartCallback;
450
- type?: undefined | "default" | "bytes";
451
- write?: UnderlyingSinkWriteCallback<W>;
452
- }
453
-
454
- interface UnderlyingSource<R = any> {
455
- cancel?: UnderlyingSourceCancelCallback;
456
- pull?: UnderlyingSourcePullCallback<R>;
457
- start?: UnderlyingSourceStartCallback<R>;
458
- /**
459
- * Mode "bytes" is not currently supported.
460
- */
461
- type?: undefined;
462
- }
463
-
464
- interface DirectUnderlyingSource<R = any> {
465
- cancel?: UnderlyingSourceCancelCallback;
466
- pull: (
467
- controller: ReadableStreamDirectController,
468
- ) => void | PromiseLike<void>;
469
- type: "direct";
470
- }
471
-
472
- interface UnderlyingSourcePullCallback<R> {
473
- (controller: ReadableStreamController<R>): void | PromiseLike<void>;
474
- }
475
-
476
- interface UnderlyingSourceStartCallback<R> {
477
- (controller: ReadableStreamController<R>): any;
478
- }
479
-
480
- interface GenericTransformStream {
481
- readonly readable: ReadableStream;
482
- readonly writable: WritableStream;
483
- }
484
-
485
- interface AbstractWorkerEventMap {
486
- error: ErrorEvent;
487
- }
488
-
489
- interface WorkerEventMap extends AbstractWorkerEventMap {
490
- message: MessageEvent;
491
- messageerror: MessageEvent;
492
- close: CloseEvent;
493
- open: Event;
494
- }
495
-
496
- type WorkerType = "classic" | "module";
497
-
498
- interface AbstractWorker {
499
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */
500
- onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;
501
- addEventListener<K extends keyof AbstractWorkerEventMap>(
502
- type: K,
503
- listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any,
504
- options?: boolean | AddEventListenerOptions,
505
- ): void;
506
- addEventListener(
507
- type: string,
508
- listener: EventListenerOrEventListenerObject,
509
- options?: boolean | AddEventListenerOptions,
510
- ): void;
511
- removeEventListener<K extends keyof AbstractWorkerEventMap>(
512
- type: K,
513
- listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any,
514
- options?: boolean | EventListenerOptions,
515
- ): void;
516
- removeEventListener(
517
- type: string,
518
- listener: EventListenerOrEventListenerObject,
519
- options?: boolean | EventListenerOptions,
520
- ): void;
521
- }
522
-
523
- /**
524
- * Bun's Web Worker constructor supports some extra options on top of the API browsers have.
525
- */
526
- interface WorkerOptions {
527
- /**
528
- * A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of
529
- * the worker, which is mainly useful for debugging purposes.
530
- */
531
- name?: string;
532
-
533
- /**
534
- * Use less memory, but make the worker slower.
535
- *
536
- * Internally, this sets the heap size configuration in JavaScriptCore to be
537
- * the small heap instead of the large heap.
538
- */
539
- smol?: boolean;
540
-
541
- /**
542
- * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d.
543
- * When `false`, the worker will not keep the parent thread alive.
544
- *
545
- * By default, this is `false`.
546
- */
547
- ref?: boolean;
548
-
549
- /**
550
- * In Bun, this does nothing.
551
- */
552
- type?: Bun.WorkerType | undefined;
553
-
554
- /**
555
- * List of arguments which would be stringified and appended to
556
- * `Bun.argv` / `process.argv` in the worker. This is mostly similar to the `data`
557
- * but the values will be available on the global `Bun.argv` as if they
558
- * were passed as CLI options to the script.
559
- */
560
- argv?: any[] | undefined;
561
-
562
- /** If `true` and the first argument is a string, interpret the first argument to the constructor as a script that is executed once the worker is online. */
563
- // eval?: boolean | undefined;
564
-
565
- /**
566
- * If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env.
567
- */
568
- env?:
569
- | Record<string, string>
570
- | typeof import("node:worker_threads")["SHARE_ENV"]
571
- | undefined;
572
-
573
- /**
574
- * In Bun, this does nothing.
575
- */
576
- credentials?: import("undici-types").RequestCredentials | undefined;
577
-
578
- /**
579
- * @default true
580
- */
581
- // trackUnmanagedFds?: boolean;
582
- // resourceLimits?: import("worker_threads").ResourceLimits;
583
-
584
- /**
585
- * An array of module specifiers to preload in the worker.
586
- *
587
- * These modules load before the worker's entry point is executed.
588
- *
589
- * Equivalent to passing the `--preload` CLI argument, but only for this Worker.
590
- */
591
- preload?: string[] | string | undefined;
592
- }
593
-
594
- interface Worker extends EventTarget, AbstractWorker {
595
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/message_event) */
596
- onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
597
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/messageerror_event) */
598
- onmessageerror: ((this: Worker, ev: MessageEvent) => any) | null;
599
- /**
600
- * Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned.
601
- *
602
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/postMessage)
603
- */
604
- postMessage(message: any, transfer: Transferable[]): void;
605
- postMessage(message: any, options?: StructuredSerializeOptions): void;
606
- /**
607
- * Aborts worker's associated global environment.
608
- *
609
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/terminate)
610
- */
611
- terminate(): void;
612
- addEventListener<K extends keyof WorkerEventMap>(
613
- type: K,
614
- listener: (this: Worker, ev: WorkerEventMap[K]) => any,
615
- options?: boolean | AddEventListenerOptions,
616
- ): void;
617
- addEventListener(
618
- type: string,
619
- listener: EventListenerOrEventListenerObject,
620
- options?: boolean | AddEventListenerOptions,
621
- ): void;
622
- removeEventListener<K extends keyof WorkerEventMap>(
623
- type: K,
624
- listener: (this: Worker, ev: WorkerEventMap[K]) => any,
625
- options?: boolean | EventListenerOptions,
626
- ): void;
627
- removeEventListener(
628
- type: string,
629
- listener: EventListenerOrEventListenerObject,
630
- options?: boolean | EventListenerOptions,
631
- ): void;
632
-
633
- /**
634
- * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default
635
- * behavior). If the worker is `ref()`ed, calling `ref()` again has
636
- * no effect.
637
- * @since v10.5.0
638
- */
639
- ref(): void;
640
-
641
- /**
642
- * Calling `unref()` on a worker allows the thread to exit if this is the only
643
- * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect.
644
- * @since v10.5.0
645
- */
646
- unref(): void;
647
-
648
- /**
649
- * An integer identifier for the referenced thread. Inside the worker thread,
650
- * it is available as `require('node:worker_threads').threadId`.
651
- * This value is unique for each `Worker` instance inside a single process.
652
- * @since v10.5.0
653
- */
654
- threadId: number;
655
- }
656
- }
657
-
658
- type _ReadableStream = import("stream/web").ReadableStream;
659
- interface ReadableStream<R = any> extends _ReadableStream {}
660
- var ReadableStream: {
661
- prototype: ReadableStream;
662
- new <R = any>(
663
- underlyingSource?: Bun.UnderlyingSource<R>,
664
- strategy?: QueuingStrategy<R>,
665
- ): ReadableStream<R>;
666
- new <R = any>(
667
- underlyingSource?: Bun.DirectUnderlyingSource<R>,
668
- strategy?: QueuingStrategy<R>,
669
- ): ReadableStream<R>;
670
- };
671
-
672
- type _WritableStream = import("stream/web").WritableStream;
673
- interface WritableStream<W = any> extends _WritableStream {}
674
- var WritableStream: {
675
- prototype: WritableStream;
676
- new <W = any>(
677
- underlyingSink?: Bun.UnderlyingSink<W>,
678
- strategy?: QueuingStrategy<W>,
679
- ): WritableStream<W>;
680
- };
681
-
682
- type _Worker = import("worker_threads").Worker;
683
- interface Worker extends _Worker {}
684
- var Worker: {
685
- prototype: Worker;
686
- new (
687
- scriptURL: string | URL,
688
- options?: Bun.WorkerOptions | undefined,
689
- ): Worker;
690
- /**
691
- * This is the cloned value of the `data` property passed to `new Worker()`
692
- *
693
- * This is Bun's equivalent of `workerData` in Node.js.
694
- */
695
- data: any;
696
- };
697
-
698
- var WebSocket: typeof import("ws").WebSocket;
699
-
700
- type _Crypto = import("crypto").webcrypto.Crypto;
701
- interface Crypto extends _Crypto {}
702
- var Crypto: {
703
- prototype: Crypto;
704
- new (): Crypto;
705
- };
706
-
707
- var crypto: Crypto;
708
-
709
- /**
710
- * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
711
- * instances of `TextEncoder` only support UTF-8 encoding.
712
- *
713
- * ```js
714
- * const encoder = new TextEncoder();
715
- * const uint8array = encoder.encode('this is some data');
716
- * ```
717
- */
718
- interface TextEncoder extends Bun.TextEncoder {}
719
- var TextEncoder: typeof TextEncoder;
720
-
721
- interface TextDecoder extends Bun.TextDecoder {}
722
- var TextDecoder: typeof TextDecoder;
723
-
724
- type _Performance = import("perf_hooks").Performance;
725
- interface Performance extends _Performance {}
726
- var performance: Performance;
727
-
728
- interface Event extends _Event {}
729
- var Event: {
730
- prototype: Event;
731
- new (type: string, eventInitDict?: Bun.EventInit): Event;
732
- };
733
-
734
- interface EventTarget extends _EventTarget {}
735
- var EventTarget: {
736
- prototype: EventTarget;
737
- new (): EventTarget;
738
- };
739
-
740
- interface File extends Blob {
741
- /**
742
- * Create a new [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
743
- *
744
- * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
745
- * @param `name` - The name of the file
746
- * @param `options` - An object containing properties to be added to the [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
747
- */
748
- new (
749
- parts: Bun.BlobPart[],
750
- name: string,
751
- options?: BlobPropertyBag & { lastModified?: Date | number },
752
- ): File;
753
- readonly lastModified: number;
754
- readonly name: string;
755
- }
756
-
757
- var File: typeof File;
758
-
759
- type _RequestInit = import("undici-types").RequestInit;
760
- interface RequestInit extends _RequestInit {
761
- /**
762
- * Log the raw HTTP request & response to stdout. This API may be
763
- * removed in a future version of Bun without notice.
764
- * This is a custom property that is not part of the Fetch API specification.
765
- * It exists mostly as a debugging tool
766
- */
767
- verbose?: boolean;
768
- /**
769
- * Override http_proxy or HTTPS_PROXY
770
- * This is a custom property that is not part of the Fetch API specification.
771
- */
772
- proxy?: string;
773
-
774
- /**
775
- * Override the default S3 options
776
- */
777
- s3?: import("bun").S3Options;
778
- }
779
-
780
- /**
781
- * ShadowRealms are a distinct global environment, with its own global object
782
- * containing its own intrinsics and built-ins (standard objects that are not
783
- * bound to global variables, like the initial value of Object.prototype).
784
- *
785
- * @example
786
- *
787
- * ```js
788
- * const red = new ShadowRealm();
789
- *
790
- * // realms can import modules that will execute within it's own environment.
791
- * // When the module is resolved, it captured the binding value, or creates a new
792
- * // wrapped function that is connected to the callable binding.
793
- * const redAdd = await red.importValue('./inside-code.js', 'add');
794
- *
795
- * // redAdd is a wrapped function exotic object that chains it's call to the
796
- * // respective imported binding.
797
- * let result = redAdd(2, 3);
798
- *
799
- * console.assert(result === 5); // yields true
800
- *
801
- * // The evaluate method can provide quick code evaluation within the constructed
802
- * // shadowRealm without requiring any module loading, while it still requires CSP
803
- * // relaxing.
804
- * globalThis.someValue = 1;
805
- * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
806
- * console.assert(globalThis.someValue === 1);
807
- *
808
- * // The wrapped functions can also wrap other functions the other way around.
809
- * const setUniqueValue =
810
- * await red.importValue('./inside-code.js', 'setUniqueValue');
811
- *
812
- * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);
813
- *
814
- * result = setUniqueValue((x) => x ** 3);
815
- *
816
- * console.assert(result === 16); // yields true
817
- * ```
818
- */
819
- interface ShadowRealm {
820
- /**
821
- * Creates a new [ShadowRealm](https://github.com/tc39/proposal-shadowrealm/blob/main/explainer.md#introduction)
822
- *
823
- * @example
824
- *
825
- * ```js
826
- * const red = new ShadowRealm();
827
- *
828
- * // realms can import modules that will execute within it's own environment.
829
- * // When the module is resolved, it captured the binding value, or creates a new
830
- * // wrapped function that is connected to the callable binding.
831
- * const redAdd = await red.importValue('./inside-code.js', 'add');
832
- *
833
- * // redAdd is a wrapped function exotic object that chains it's call to the
834
- * // respective imported binding.
835
- * let result = redAdd(2, 3);
836
- *
837
- * console.assert(result === 5); // yields true
838
- *
839
- * // The evaluate method can provide quick code evaluation within the constructed
840
- * // shadowRealm without requiring any module loading, while it still requires CSP
841
- * // relaxing.
842
- * globalThis.someValue = 1;
843
- * red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
844
- * console.assert(globalThis.someValue === 1);
845
- *
846
- * // The wrapped functions can also wrap other functions the other way around.
847
- * const setUniqueValue =
848
- * await red.importValue('./inside-code.js', 'setUniqueValue');
849
- *
850
- * // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);
851
- *
852
- * result = setUniqueValue((x) => x ** 3);
853
- *
854
- * console.assert(result === 16); // yields true
855
- * ```
856
- */
857
- importValue(specifier: string, bindingName: string): Promise<any>;
858
- evaluate(sourceText: string): any;
859
- }
860
-
861
- var ShadowRealm: {
862
- prototype: ShadowRealm;
863
- new (): ShadowRealm;
864
- };
865
-
866
- function queueMicrotask(callback: (...args: any[]) => void): void;
867
- /**
868
- * Log an error using the default exception handler
869
- * @param error Error or string
870
- */
871
- function reportError(error: any): void;
872
-
873
- interface Timer {
874
- ref(): Timer;
875
- unref(): Timer;
876
- hasRef(): boolean;
877
- refresh(): Timer;
878
-
879
- [Symbol.toPrimitive](): number;
880
- }
881
-
882
- /**
883
- * Cancel a repeating timer by its timer ID.
884
- * @param id timer id
885
- */
886
- function clearInterval(id?: number | Timer): void;
887
- /**
888
- * Cancel a delayed function call by its timer ID.
889
- * @param id timer id
890
- */
891
- function clearTimeout(id?: number | Timer): void;
892
- /**
893
- * Cancel an immediate function call by its immediate ID.
894
- * @param id immediate id
895
- */
896
- function clearImmediate(id?: number | Timer): void;
897
- /**
898
- * Run a function immediately after main event loop is vacant
899
- * @param handler function to call
900
- */
901
- function setImmediate(handler: Bun.TimerHandler, ...arguments: any[]): Timer;
902
- /**
903
- * Run a function every `interval` milliseconds
904
- * @param handler function to call
905
- * @param interval milliseconds to wait between calls
906
- */
907
- function setInterval(
908
- handler: Bun.TimerHandler,
909
- interval?: number,
910
- ...arguments: any[]
911
- ): Timer;
912
- /**
913
- * Run a function after `timeout` (milliseconds)
914
- * @param handler function to call
915
- * @param timeout milliseconds to wait between calls
916
- */
917
- function setTimeout(
918
- handler: Bun.TimerHandler,
919
- timeout?: number,
920
- ...arguments: any[]
921
- ): Timer;
922
-
923
- function addEventListener<K extends keyof EventMap>(
924
- type: K,
925
- listener: (this: object, ev: EventMap[K]) => any,
926
- options?: boolean | AddEventListenerOptions,
927
- ): void;
928
- function addEventListener(
929
- type: string,
930
- listener: Bun.EventListenerOrEventListenerObject,
931
- options?: boolean | AddEventListenerOptions,
932
- ): void;
933
- function removeEventListener<K extends keyof EventMap>(
934
- type: K,
935
- listener: (this: object, ev: EventMap[K]) => any,
936
- options?: boolean | Bun.EventListenerOptions,
937
- ): void;
938
- function removeEventListener(
939
- type: string,
940
- listener: Bun.EventListenerOrEventListenerObject,
941
- options?: boolean | Bun.EventListenerOptions,
942
- ): void;
943
-
944
- /**
945
- * Events providing information related to errors in scripts or in files.
946
- */
947
- interface ErrorEvent extends Event {
948
- readonly colno: number;
949
- readonly error: any;
950
- readonly filename: string;
951
- readonly lineno: number;
952
- readonly message: string;
953
- }
954
-
955
- var ErrorEvent: {
956
- prototype: ErrorEvent;
957
- new (type: string, eventInitDict?: Bun.ErrorEventInit): ErrorEvent;
958
- };
959
-
960
- /** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
961
- interface CloseEvent extends Event {
962
- /** Returns the WebSocket connection close code provided by the server. */
963
- readonly code: number;
964
- /** Returns the WebSocket connection close reason provided by the server. */
965
- readonly reason: string;
966
- /** Returns true if the connection closed cleanly; false otherwise. */
967
- readonly wasClean: boolean;
968
- }
969
-
970
- var CloseEvent: {
971
- prototype: CloseEvent;
972
- new (type: string, eventInitDict?: Bun.CloseEventInit): CloseEvent;
973
- };
974
-
975
- interface MessageEvent<T = any> extends Bun.MessageEvent<T> {}
976
- var MessageEvent: {
977
- prototype: MessageEvent;
978
- new <T>(
979
- type: string,
980
- eventInitDict?: Bun.MessageEventInit<T>,
981
- ): MessageEvent<T>;
982
- };
983
-
984
- interface CustomEvent<T = any> extends Event {
985
- /** Returns any custom data event was created with. Typically used for synthetic events. */
986
- readonly detail: T;
987
- }
988
-
989
- var CustomEvent: {
990
- prototype: CustomEvent;
991
- new <T>(
992
- type: string,
993
- eventInitDict?: Bun.CustomEventInit<T>,
994
- ): CustomEvent<T>;
995
- };
996
-
997
- // /**
998
- // * The URL interface represents an object providing static methods used for
999
- // * creating object URLs.
1000
- // */
1001
- // interface URL extends _URL {
1002
- // new (url: string | URL, base?: string | URL): URL;
1003
- // /** Not implemented yet */
1004
- // createObjectURL(obj: Blob): string;
1005
- // /** Not implemented yet */
1006
- // revokeObjectURL(url: string): void;
1007
-
1008
- // /**
1009
- // * Check if `url` is a valid URL string
1010
- // *
1011
- // * @param url URL string to parse
1012
- // * @param base URL to resolve against
1013
- // */
1014
- // canParse(url: string, base?: string): boolean;
1015
- // }
1016
-
1017
- interface EventListener {
1018
- (evt: Event): void;
1019
- }
1020
-
1021
- interface EventListenerObject {
1022
- handleEvent(object: Event): void;
1023
- }
1024
-
1025
- interface FetchEvent extends Event {
1026
- readonly request: Request;
1027
- readonly url: string;
1028
-
1029
- waitUntil(promise: Promise<any>): void;
1030
- respondWith(response: Response | Promise<Response>): void;
1031
- }
1032
-
1033
- interface EventMap {
1034
- fetch: FetchEvent;
1035
- message: MessageEvent;
1036
- messageerror: MessageEvent;
1037
- // exit: Event;
1038
- }
1039
-
1040
- interface AddEventListenerOptions extends Bun.EventListenerOptions {
1041
- once?: boolean;
1042
- passive?: boolean;
1043
- signal?: AbortSignal;
1044
- }
1045
-
1046
- /**
1047
- * Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API)
1048
- *
1049
- * Before using this, be aware of a few things:
1050
- *
1051
- * **Using this incorrectly will crash your application**.
1052
- *
1053
- * This API may change any time JavaScriptCore is updated.
1054
- *
1055
- * Bun may rewrite ESM import specifiers to point to bundled code. This will
1056
- * be confusing when using this API, as it will return a string like
1057
- * "/node_modules.server.bun".
1058
- *
1059
- * Bun may inject additional imports into your code. This usually has a `bun:` prefix.
1060
- */
1061
- var Loader: {
1062
- /**
1063
- * ESM module registry
1064
- *
1065
- * This lets you implement live reload in Bun. If you
1066
- * delete a module specifier from this map, the next time it's imported, it
1067
- * will be re-transpiled and loaded again.
1068
- *
1069
- * The keys are the module specifiers and the
1070
- * values are metadata about the module.
1071
- *
1072
- * The keys are an implementation detail for Bun that will change between
1073
- * versions.
1074
- *
1075
- * - Userland modules are an absolute file path
1076
- * - Virtual modules have a `bun:` prefix or `node:` prefix
1077
- * - JS polyfills start with `"/bun-vfs/"`. `"buffer"` is an example of a JS polyfill
1078
- * - If you have a `node_modules.bun` file, many modules will point to that file
1079
- *
1080
- * Virtual modules and JS polyfills are embedded in bun's binary. They don't
1081
- * point to anywhere in your local filesystem.
1082
- */
1083
- registry: Map<
1084
- string,
1085
- {
1086
- key: string;
1087
- /**
1088
- * This refers to the state the ESM module is in
1089
- *
1090
- * TODO: make an enum for this number
1091
- */
1092
- state: number;
1093
- fetch: Promise<any>;
1094
- instantiate: Promise<any>;
1095
- satisfy: Promise<any>;
1096
- dependencies: Array<
1097
- (typeof Loader)["registry"] extends Map<any, infer V> ? V : any
1098
- >;
1099
- /**
1100
- * Your application will probably crash if you mess with this.
1101
- */
1102
- module: {
1103
- dependenciesMap: (typeof Loader)["registry"];
1104
- };
1105
- linkError?: any;
1106
- linkSucceeded: boolean;
1107
- evaluated: boolean;
1108
- then?: any;
1109
- isAsync: boolean;
1110
- }
1111
- >;
1112
- /**
1113
- * For an already-evaluated module, return the dependencies as module specifiers
1114
- *
1115
- * This list is already sorted and uniqued.
1116
- *
1117
- * @example
1118
- *
1119
- * For this code:
1120
- * ```js
1121
- * // /foo.js
1122
- * import classNames from 'classnames';
1123
- * import React from 'react';
1124
- * import {createElement} from 'react';
1125
- * ```
1126
- *
1127
- * This would return:
1128
- * ```js
1129
- * Loader.dependencyKeysIfEvaluated("/foo.js")
1130
- * ["bun:wrap", "/path/to/node_modules/classnames/index.js", "/path/to/node_modules/react/index.js"]
1131
- * ```
1132
- *
1133
- * @param specifier - module specifier as it appears in transpiled source code
1134
- */
1135
- dependencyKeysIfEvaluated: (specifier: string) => string[];
1136
- /**
1137
- * The function JavaScriptCore internally calls when you use an import statement.
1138
- *
1139
- * This may return a path to `node_modules.server.bun`, which will be confusing.
1140
- *
1141
- * Consider {@link Bun.resolve} or {@link ImportMeta.resolve}
1142
- * instead.
1143
- *
1144
- * @param specifier - module specifier as it appears in transpiled source code
1145
- * @param referrer - module specifier that is resolving this specifier
1146
- */
1147
- resolve: (specifier: string, referrer: string) => string;
1148
- };
1149
-
1150
- interface QueuingStrategy<T = any> {
1151
- highWaterMark?: number;
1152
- size?: QueuingStrategySize<T>;
1153
- }
1154
-
1155
- interface QueuingStrategyInit {
1156
- /**
1157
- * Creates a new ByteLengthQueuingStrategy with the provided high water mark.
1158
- *
1159
- * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.
1160
- */
1161
- highWaterMark: number;
1162
- }
1163
-
1164
- /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */
1165
- interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
1166
- readonly highWaterMark: number;
1167
- // changed from QueuingStrategySize<BufferSource>
1168
- // to avoid conflict with lib.dom.d.ts
1169
- readonly size: QueuingStrategySize<ArrayBufferView>;
1170
- }
1171
-
1172
- var ByteLengthQueuingStrategy: {
1173
- prototype: ByteLengthQueuingStrategy;
1174
- new (init: QueuingStrategyInit): ByteLengthQueuingStrategy;
1175
- };
1176
-
1177
- interface ReadableStreamDefaultController<R = any> {
1178
- readonly desiredSize: number | null;
1179
- close(): void;
1180
- enqueue(chunk?: R): void;
1181
- error(e?: any): void;
1182
- }
1183
-
1184
- interface ReadableStreamDirectController {
1185
- close(error?: Error): void;
1186
- write(
1187
- data: Bun.BufferSource | ArrayBuffer | string,
1188
- ): number | Promise<number>;
1189
- end(): number | Promise<number>;
1190
- flush(): number | Promise<number>;
1191
- start(): void;
1192
- }
1193
-
1194
- var ReadableStreamDefaultController: {
1195
- prototype: ReadableStreamDefaultController;
1196
- new (): ReadableStreamDefaultController;
1197
- };
1198
-
1199
- interface ReadableStreamDefaultReader<R = any>
1200
- extends ReadableStreamGenericReader {
1201
- read(): Promise<Bun.ReadableStreamDefaultReadResult<R>>;
1202
- /**
1203
- * Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time.
1204
- * Will only return a promise if the data is not immediately available.
1205
- */
1206
- readMany():
1207
- | Promise<Bun.ReadableStreamDefaultReadManyResult<R>>
1208
- | Bun.ReadableStreamDefaultReadManyResult<R>;
1209
- releaseLock(): void;
1210
- }
1211
-
1212
- var ReadableStreamDefaultReader: {
1213
- prototype: ReadableStreamDefaultReader;
1214
- new <R = any>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>;
1215
- };
1216
-
1217
- interface ReadableStreamGenericReader {
1218
- readonly closed: Promise<undefined>;
1219
- cancel(reason?: any): Promise<void>;
1220
- }
1221
-
1222
- interface ReadableStreamDefaultReadDoneResult {
1223
- done: true;
1224
- value?: undefined;
1225
- }
1226
-
1227
- interface ReadableStreamDefaultReadValueResult<T> {
1228
- done: false;
1229
- value: T;
1230
- }
1231
-
1232
- interface ReadableWritablePair<R = any, W = any> {
1233
- readable: ReadableStream<R>;
1234
- /**
1235
- * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.
1236
- *
1237
- * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
1238
- */
1239
- writable: WritableStream<W>;
1240
- }
1241
-
1242
- interface WritableStreamDefaultController {
1243
- error(e?: any): void;
1244
- }
1245
-
1246
- var WritableStreamDefaultController: {
1247
- prototype: WritableStreamDefaultController;
1248
- new (): WritableStreamDefaultController;
1249
- };
1250
-
1251
- /** This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */
1252
- interface WritableStreamDefaultWriter<W = any> {
1253
- readonly closed: Promise<undefined>;
1254
- readonly desiredSize: number | null;
1255
- readonly ready: Promise<undefined>;
1256
- abort(reason?: any): Promise<void>;
1257
- close(): Promise<void>;
1258
- releaseLock(): void;
1259
- write(chunk?: W): Promise<void>;
1260
- }
1261
-
1262
- var WritableStreamDefaultWriter: {
1263
- prototype: WritableStreamDefaultWriter;
1264
- new <W = any>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>;
1265
- };
1266
-
1267
- interface TransformStream<I = any, O = any> {
1268
- readonly readable: ReadableStream<O>;
1269
- readonly writable: WritableStream<I>;
1270
- }
1271
-
1272
- var TransformStream: {
1273
- prototype: TransformStream;
1274
- new <I = any, O = any>(
1275
- transformer?: Transformer<I, O>,
1276
- writableStrategy?: QueuingStrategy<I>,
1277
- readableStrategy?: QueuingStrategy<O>,
1278
- ): TransformStream<I, O>;
1279
- };
1280
-
1281
- interface TransformStreamDefaultController<O = any> {
1282
- readonly desiredSize: number | null;
1283
- enqueue(chunk?: O): void;
1284
- error(reason?: any): void;
1285
- terminate(): void;
1286
- }
1287
-
1288
- var TransformStreamDefaultController: {
1289
- prototype: TransformStreamDefaultController;
1290
- new (): TransformStreamDefaultController;
1291
- };
1292
-
1293
- interface StreamPipeOptions {
1294
- preventAbort?: boolean;
1295
- preventCancel?: boolean;
1296
- /**
1297
- * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
1298
- *
1299
- * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
1300
- *
1301
- * Errors and closures of the source and destination streams propagate as follows:
1302
- *
1303
- * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.
1304
- *
1305
- * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.
1306
- *
1307
- * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.
1308
- *
1309
- * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.
1310
- *
1311
- * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.
1312
- */
1313
- preventClose?: boolean;
1314
- signal?: AbortSignal;
1315
- }
1316
-
1317
- /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */
1318
- interface CountQueuingStrategy extends QueuingStrategy {
1319
- readonly highWaterMark: number;
1320
- readonly size: QueuingStrategySize;
1321
- }
1322
-
1323
- var CountQueuingStrategy: {
1324
- prototype: CountQueuingStrategy;
1325
- new (init: QueuingStrategyInit): CountQueuingStrategy;
1326
- };
1327
-
1328
- interface QueuingStrategySize<T = any> {
1329
- (chunk?: T): number;
1330
- }
1331
-
1332
- interface Transformer<I = any, O = any> {
1333
- flush?: Bun.TransformerFlushCallback<O>;
1334
- readableType?: undefined;
1335
- start?: Bun.TransformerStartCallback<O>;
1336
- transform?: Bun.TransformerTransformCallback<I, O>;
1337
- writableType?: undefined;
1338
- }
1339
-
1340
- interface Dict<T> {
1341
- [key: string]: T | undefined;
1342
- }
1343
-
1344
- interface ReadOnlyDict<T> {
1345
- readonly [key: string]: T | undefined;
1346
- }
1347
-
1348
- interface ErrnoException extends Error {
1349
- errno?: number | undefined;
1350
- code?: string | undefined;
1351
- path?: string | undefined;
1352
- syscall?: string | undefined;
1353
- }
1354
-
1355
- /** An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */
1356
- interface DOMException extends Error {
1357
- readonly message: string;
1358
- readonly name: string;
1359
- readonly INDEX_SIZE_ERR: 1;
1360
- readonly DOMSTRING_SIZE_ERR: 2;
1361
- readonly HIERARCHY_REQUEST_ERR: 3;
1362
- readonly WRONG_DOCUMENT_ERR: 4;
1363
- readonly INVALID_CHARACTER_ERR: 5;
1364
- readonly NO_DATA_ALLOWED_ERR: 6;
1365
- readonly NO_MODIFICATION_ALLOWED_ERR: 7;
1366
- readonly NOT_FOUND_ERR: 8;
1367
- readonly NOT_SUPPORTED_ERR: 9;
1368
- readonly INUSE_ATTRIBUTE_ERR: 10;
1369
- readonly INVALID_STATE_ERR: 11;
1370
- readonly SYNTAX_ERR: 12;
1371
- readonly INVALID_MODIFICATION_ERR: 13;
1372
- readonly NAMESPACE_ERR: 14;
1373
- readonly INVALID_ACCESS_ERR: 15;
1374
- readonly VALIDATION_ERR: 16;
1375
- readonly TYPE_MISMATCH_ERR: 17;
1376
- readonly SECURITY_ERR: 18;
1377
- readonly NETWORK_ERR: 19;
1378
- readonly ABORT_ERR: 20;
1379
- readonly URL_MISMATCH_ERR: 21;
1380
- readonly QUOTA_EXCEEDED_ERR: 22;
1381
- readonly TIMEOUT_ERR: 23;
1382
- readonly INVALID_NODE_TYPE_ERR: 24;
1383
- readonly DATA_CLONE_ERR: 25;
1384
- }
1385
-
1386
- var DOMException: {
1387
- prototype: DOMException;
1388
- new (message?: string, name?: string): DOMException;
1389
- };
1390
-
1391
- function alert(message?: string): void;
1392
- function confirm(message?: string): boolean;
1393
- function prompt(message?: string, _default?: string): string | null;
1394
-
1395
- type _SubtleCrypto = import("crypto").webcrypto.SubtleCrypto;
1396
- var SubtleCrypto: {
1397
- prototype: _SubtleCrypto;
1398
- new (): _SubtleCrypto;
1399
- };
1400
-
1401
- type _CryptoKey = import("crypto").webcrypto.CryptoKey;
1402
- interface CryptoKey extends _CryptoKey {}
1403
- var CryptoKey: {
1404
- prototype: CryptoKey;
1405
- new (): CryptoKey;
1406
- };
1407
-
1408
- interface Position {
1409
- lineText: string;
1410
- file: string;
1411
- namespace: string;
1412
- line: number;
1413
- column: number;
1414
- length: number;
1415
- offset: number;
1416
- }
1417
-
1418
- class ResolveMessage {
1419
- readonly name: "ResolveMessage";
1420
- readonly position: Position | null;
1421
- readonly code: string;
1422
- readonly message: string;
1423
- readonly referrer: string;
1424
- readonly specifier: string;
1425
- readonly importKind:
1426
- | "entry_point"
1427
- | "stmt"
1428
- | "require"
1429
- | "import"
1430
- | "dynamic"
1431
- | "require_resolve"
1432
- | "at"
1433
- | "at_conditional"
1434
- | "url"
1435
- | "internal";
1436
- readonly level: "error" | "warning" | "info" | "debug" | "verbose";
1437
-
1438
- toString(): string;
1439
- }
1440
-
1441
- class BuildMessage {
1442
- readonly name: "BuildMessage";
1443
- readonly position: Position | null;
1444
- readonly message: string;
1445
- readonly level: "error" | "warning" | "info" | "debug" | "verbose";
1446
- }
1447
-
1448
- // Declare "static" methods in Error
1449
- interface ErrorConstructor {
1450
- /** Create .stack property on a target object */
1451
- // eslint-disable-next-line @typescript-eslint/ban-types
1452
- captureStackTrace(targetObject: object, constructorOpt?: Function): void;
1453
-
1454
- /**
1455
- * Optional override for formatting stack traces
1456
- *
1457
- * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1458
- */
1459
- prepareStackTrace?:
1460
- | ((err: Error, stackTraces: NodeJS.CallSite[]) => any)
1461
- | undefined;
1462
-
1463
- stackTraceLimit: number;
1464
- }
1465
-
1466
- interface ArrayBufferConstructor {
1467
- new (byteLength: number, options: { maxByteLength?: number }): ArrayBuffer;
1468
- }
1469
-
1470
- interface ArrayBuffer {
1471
- /**
1472
- * Read-only. The length of the ArrayBuffer (in bytes).
1473
- */
1474
- readonly byteLength: number;
1475
- /**
1476
- * Resize an ArrayBuffer in-place.
1477
- */
1478
- resize(byteLength: number): ArrayBuffer;
1479
-
1480
- /**
1481
- * Returns a section of an ArrayBuffer.
1482
- */
1483
- slice(begin: number, end?: number): ArrayBuffer;
1484
- readonly [Symbol.toStringTag]: string;
1485
- }
1486
-
1487
- interface SharedArrayBuffer {
1488
- /**
1489
- * Grow the SharedArrayBuffer in-place.
1490
- */
1491
- grow(size: number): SharedArrayBuffer;
1492
- }
1493
-
1494
- interface ArrayConstructor {
1495
- /**
1496
- * Create an array from an iterable or async iterable object.
1497
- * Values from the iterable are awaited.
1498
- *
1499
- * ```ts
1500
- * await Array.fromAsync([1]); // [1]
1501
- * await Array.fromAsync([Promise.resolve(1)]); // [1]
1502
- * await Array.fromAsync((async function*() { yield 1 })()); // [1]
1503
- * ```
1504
- *
1505
- * @param arrayLike - The iterable or async iterable to convert to an array.
1506
- * @returns A {@link Promise} whose fulfillment is a new {@link Array} instance containing the values from the iterator.
1507
- */
1508
- fromAsync<T>(
1509
- arrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>,
1510
- ): Promise<Awaited<T>[]>;
1511
-
1512
- /**
1513
- * Create an array from an iterable or async iterable object.
1514
- * Values from the iterable are awaited. Results of the map function are also awaited.
1515
- *
1516
- * ```ts
1517
- * await Array.fromAsync([1]); // [1]
1518
- * await Array.fromAsync([Promise.resolve(1)]); // [1]
1519
- * await Array.fromAsync((async function*() { yield 1 })()); // [1]
1520
- * await Array.fromAsync([1], (n) => n + 1); // [2]
1521
- * await Array.fromAsync([1], (n) => Promise.resolve(n + 1)); // [2]
1522
- * ```
1523
- *
1524
- * @param arrayLike - The iterable or async iterable to convert to an array.
1525
- * @param mapFn - A mapper function that transforms each element of `arrayLike` after awaiting them.
1526
- * @param thisArg - The `this` to which `mapFn` is bound.
1527
- * @returns A {@link Promise} whose fulfillment is a new {@link Array} instance containing the values from the iterator.
1528
- */
1529
- fromAsync<T, U>(
1530
- arrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>,
1531
- mapFn?: (value: T, index: number) => U,
1532
- thisArg?: any,
1533
- ): Promise<Awaited<U>[]>;
1534
- }
1535
-
1536
- interface ConsoleOptions {
1537
- stdout: import("stream").Writable;
1538
- stderr?: import("stream").Writable;
1539
- ignoreErrors?: boolean;
1540
- colorMode?: boolean | "auto";
1541
- inspectOptions?: import("util").InspectOptions;
1542
- groupIndentation?: number;
1543
- }
1544
-
1545
- interface Console {
1546
- /**
1547
- * Asynchronously read lines from standard input (fd 0)
1548
- *
1549
- * ```ts
1550
- * for await (const line of console) {
1551
- * console.log(line);
1552
- * }
1553
- * ```
1554
- */
1555
- [Symbol.asyncIterator](): AsyncIterableIterator<string>;
1556
-
1557
- /**
1558
- * Write text or bytes to stdout
1559
- *
1560
- * Unlike {@link console.log}, this does no formatting and doesn't add a
1561
- * newline or spaces between arguments. You can pass it strings or bytes or
1562
- * any combination of the two.
1563
- *
1564
- * ```ts
1565
- * console.write("hello world!", "\n"); // "hello world\n"
1566
- * ```
1567
- *
1568
- * @param data - The data to write
1569
- * @returns The number of bytes written
1570
- *
1571
- * This function is not available in the browser.
1572
- */
1573
- write(...data: Array<string | ArrayBufferView | ArrayBuffer>): number;
1574
-
1575
- /**
1576
- * Clear the console
1577
- */
1578
- clear(): void;
1579
-
1580
- assert(condition?: boolean, ...data: any[]): void;
1581
-
1582
- /**
1583
- * Increment a [count](https://www.youtube.com/watch?v=2AoxCkySv34&t=22s)
1584
- * @param label label counter
1585
- */
1586
- count(label?: string): void;
1587
- countReset(label?: string): void;
1588
- debug(...data: any[]): void;
1589
- dir(item?: any, options?: any): void;
1590
- dirxml(...data: any[]): void;
1591
- /**
1592
- * Log to stderr in your terminal
1593
- *
1594
- * Appears in red
1595
- *
1596
- * @param data something to display
1597
- */
1598
- error(...data: any[]): void;
1599
- /** Does nothing currently */
1600
- group(...data: any[]): void;
1601
- /** Does nothing currently */
1602
- groupCollapsed(...data: any[]): void;
1603
- /** Does nothing currently */
1604
- groupEnd(): void;
1605
- info(...data: any[]): void;
1606
- log(...data: any[]): void;
1607
- /**
1608
- * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just
1609
- * logging the argument if it can't be parsed as tabular.
1610
- *
1611
- * ```js
1612
- * // These can't be parsed as tabular data
1613
- * console.table(Symbol());
1614
- * // Symbol()
1615
- *
1616
- * console.table(undefined);
1617
- * // undefined
1618
- *
1619
- * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
1620
- * // ┌────┬─────┬─────┐
1621
- * // │ │ a │ b │
1622
- * // ├────┼─────┼─────┤
1623
- * // │ 0 │ 1 │ 'Y' │
1624
- * // │ 1 │ 'Z' │ 2 │
1625
- * // └────┴─────┴─────┘
1626
- *
1627
- * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
1628
- * // ┌────┬─────┐
1629
- * // │ │ a │
1630
- * // ├────┼─────┤
1631
- * // │ 0 │ 1 │
1632
- * // │ 1 │ 'Z' │
1633
- * // └────┴─────┘
1634
- * ```
1635
- * @param properties Alternate properties for constructing the table.
1636
- */
1637
- table(tabularData?: any, properties?: string[]): void;
1638
- /**
1639
- * Begin a timer to log with {@link console.timeEnd}
1640
- *
1641
- * @param label - The label to use for the timer
1642
- *
1643
- * ```ts
1644
- * console.time("how long????");
1645
- * for (let i = 0; i < 999999; i++) {
1646
- * // do stuff
1647
- * let x = i * i;
1648
- * }
1649
- * console.timeEnd("how long????");
1650
- * ```
1651
- */
1652
- time(label?: string): void;
1653
- /**
1654
- * End a timer to log with {@link console.time}
1655
- *
1656
- * @param label - The label to use for the timer
1657
- *
1658
- * ```ts
1659
- * console.time("how long????");
1660
- * for (let i = 0; i < 999999; i++) {
1661
- * // do stuff
1662
- * let x = i * i;
1663
- * }
1664
- * console.timeEnd("how long????");
1665
- * ```
1666
- */
1667
- timeEnd(label?: string): void;
1668
- timeLog(label?: string, ...data: any[]): void;
1669
- timeStamp(label?: string): void;
1670
- trace(...data: any[]): void;
1671
- warn(...data: any[]): void;
1672
-
1673
- /**
1674
- * Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr.
1675
- */
1676
- // Console: {
1677
- // new (options: ConsoleOptions): Console;
1678
- // new (
1679
- // stdout: import("stream").Writable,
1680
- // stderr?: import("stream").Writable,
1681
- // ignoreErrors?: boolean,
1682
- // ): Console;
1683
- // };
1684
- }
1685
-
1686
- var console: Console;
1687
-
1688
- interface ImportMeta {
1689
- /**
1690
- * `file://` url string for the current module.
1691
- *
1692
- * @example
1693
- * ```ts
1694
- * console.log(import.meta.url);
1695
- * "file:///Users/me/projects/my-app/src/my-app.ts"
1696
- * ```
1697
- */
1698
- url: string;
1699
- /**
1700
- * Absolute path to the source file
1701
- */
1702
- readonly path: string;
1703
- /**
1704
- * Absolute path to the directory containing the source file.
1705
- *
1706
- * Does not have a trailing slash
1707
- */
1708
- readonly dir: string;
1709
- /**
1710
- * Filename of the source file
1711
- */
1712
- readonly file: string;
1713
- /**
1714
- * The environment variables of the process
1715
- *
1716
- * ```ts
1717
- * import.meta.env === process.env
1718
- * ```
1719
- */
1720
- readonly env: NodeJS.ProcessEnv;
1721
-
1722
- /**
1723
- * @deprecated Use `require.resolve` or `Bun.resolveSync(moduleId, path.dirname(parent))` instead
1724
- *
1725
- * Resolve a module ID the same as if you imported it
1726
- *
1727
- * The `parent` argument is optional, and defaults to the current module's path.
1728
- */
1729
- resolveSync(moduleId: string, parent?: string): string;
1730
-
1731
- /**
1732
- * Load a CommonJS module within an ES Module. Bun's transpiler rewrites all
1733
- * calls to `require` with `import.meta.require` when transpiling ES Modules
1734
- * for the runtime.
1735
- *
1736
- * Warning: **This API is not stable** and may change or be removed in the
1737
- * future. Use at your own risk.
1738
- */
1739
- require: NodeJS.Require;
1740
-
1741
- /**
1742
- * Did the current file start the process?
1743
- *
1744
- * @example
1745
- * ```ts
1746
- * if (import.meta.main) {
1747
- * console.log("I started the process!");
1748
- * }
1749
- * ```
1750
- *
1751
- * @example
1752
- * ```ts
1753
- * console.log(
1754
- * import.meta.main === (import.meta.path === Bun.main)
1755
- * )
1756
- * ```
1757
- */
1758
- readonly main: boolean;
1759
-
1760
- /** Alias of `import.meta.dir`. Exists for Node.js compatibility */
1761
- dirname: string;
1762
-
1763
- /** Alias of `import.meta.path`. Exists for Node.js compatibility */
1764
- filename: string;
1765
- }
1766
-
1767
- /**
1768
- * NodeJS-style `require` function
1769
- *
1770
- * @param moduleId - The module ID to resolve
1771
- */
1772
- var require: NodeJS.Require;
1773
-
1774
- /** Same as module.exports */
1775
- var exports: any;
1776
-
1777
- interface NodeModule {
1778
- exports: any;
1779
- }
1780
-
1781
- var module: NodeModule;
1782
-
1783
- /**
1784
- * Creates a deep clone of an object.
1785
- *
1786
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone)
1787
- */
1788
- function structuredClone<T>(
1789
- value: T,
1790
- options?: Bun.StructuredSerializeOptions,
1791
- ): T;
1792
-
1793
- /**
1794
- * Post a message to the parent thread.
1795
- *
1796
- * Only useful in a worker thread; calling this from the main thread does nothing.
1797
- */
1798
- function postMessage(message: any, transfer?: Bun.Transferable[]): void;
1799
-
1800
- interface EventSourceInit {
1801
- withCredentials?: boolean;
1802
- }
1803
-
1804
- interface PromiseConstructor {
1805
- /**
1806
- * Create a deferred promise, with exposed `resolve` and `reject` methods which can be called
1807
- * separately.
1808
- *
1809
- * This is useful when you want to return a Promise and have code outside the Promise
1810
- * resolve or reject it.
1811
- *
1812
- * ## Example
1813
- * ```ts
1814
- * const { promise, resolve, reject } = Promise.withResolvers();
1815
- *
1816
- * setTimeout(() => {
1817
- * resolve("Hello world!");
1818
- * }, 1000);
1819
- *
1820
- * await promise; // "Hello world!"
1821
- * ```
1822
- *
1823
- * `Promise.withResolvers()` is a [stage3 proposal](https://github.com/tc39/proposal-promise-with-resolvers).
1824
- */
1825
- withResolvers<T>(): {
1826
- promise: Promise<T>;
1827
- resolve: (value?: T | PromiseLike<T>) => void;
1828
- reject: (reason?: any) => void;
1829
- };
1830
- }
1831
-
1832
- interface Navigator {
1833
- readonly userAgent: string;
1834
- readonly platform: "MacIntel" | "Win32" | "Linux x86_64";
1835
- readonly hardwareConcurrency: number;
1836
- }
1837
-
1838
- var navigator: Navigator;
1839
-
1840
- interface BlobPropertyBag {
1841
- /** Set a default "type". Not yet implemented. */
1842
- type?: string;
1843
- /** Not implemented in Bun yet. */
1844
- // endings?: "transparent" | "native";
1845
- }
1846
-
1847
- interface Blob {
1848
- /**
1849
- * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
1850
- *
1851
- * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
1852
- * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
1853
- */
1854
- new (parts?: Bun.BlobPart[], options?: BlobPropertyBag): Blob;
1855
- /**
1856
- * Read the data from the blob as a JSON object.
1857
- *
1858
- * This first decodes the data from UTF-8, then parses it as JSON.
1859
- */
1860
- // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1861
- json(): Promise<any>;
1862
-
1863
- /**
1864
- * Read the data from the blob as a {@link FormData} object.
1865
- *
1866
- * This first decodes the data from UTF-8, then parses it as a
1867
- * `multipart/form-data` body or a `application/x-www-form-urlencoded` body.
1868
- *
1869
- * The `type` property of the blob is used to determine the format of the
1870
- * body.
1871
- *
1872
- * This is a non-standard addition to the `Blob` API, to make it conform more
1873
- * closely to the `BodyMixin` API.
1874
- */
1875
- formData(): Promise<FormData>;
1876
-
1877
- arrayBuffer(): Promise<ArrayBuffer>;
1878
-
1879
- /**
1880
- * Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as `new Uint8Array(await blob.arrayBuffer())`
1881
- */
1882
- bytes(): Promise<Uint8Array>;
1883
- }
1884
- var Blob: typeof Blob;
1885
-
1886
- interface Uint8Array {
1887
- /**
1888
- * Convert the Uint8Array to a base64 encoded string
1889
- * @returns The base64 encoded string representation of the Uint8Array
1890
- */
1891
- toBase64(options?: {
1892
- alphabet?: "base64" | "base64url";
1893
- omitPadding?: boolean;
1894
- }): string;
1895
-
1896
- /**
1897
- * Set the contents of the Uint8Array from a base64 encoded string
1898
- * @param base64 The base64 encoded string to decode into the array
1899
- * @param offset Optional starting index to begin setting the decoded bytes (default: 0)
1900
- */
1901
- setFromBase64(
1902
- base64: string,
1903
- offset?: number,
1904
- ): {
1905
- /**
1906
- * The number of bytes read from the base64 string
1907
- */
1908
- read: number;
1909
- /**
1910
- * The number of bytes written to the Uint8Array
1911
- * Will never be greater than the `.byteLength` of this Uint8Array
1912
- */
1913
- written: number;
1914
- };
1915
-
1916
- /**
1917
- * Convert the Uint8Array to a hex encoded string
1918
- * @returns The hex encoded string representation of the Uint8Array
1919
- */
1920
- toHex(): string;
1921
-
1922
- /**
1923
- * Set the contents of the Uint8Array from a hex encoded string
1924
- * @param hex The hex encoded string to decode into the array. The string must have
1925
- * an even number of characters, be valid hexadecimal characters and contain no whitespace.
1926
- */
1927
- setFromHex(hex: string): {
1928
- /**
1929
- * The number of bytes read from the hex string
1930
- */
1931
- read: number;
1932
- /**
1933
- * The number of bytes written to the Uint8Array
1934
- * Will never be greater than the `.byteLength` of this Uint8Array
1935
- */
1936
- written: number;
1937
- };
1938
- }
1939
-
1940
- interface Uint8ArrayConstructor {
1941
- /**
1942
- * Create a new Uint8Array from a base64 encoded string
1943
- * @param base64 The base64 encoded string to convert to a Uint8Array
1944
- * @returns A new Uint8Array containing the decoded data
1945
- */
1946
- fromBase64(
1947
- base64: string,
1948
- options?: {
1949
- alphabet?: "base64" | "base64url";
1950
- lastChunkHandling?: "loose" | "strict" | "stop-before-partial";
1951
- },
1952
- ): Uint8Array;
1953
- }
730
+ interface QueuingStrategySize<T = any> {
731
+ (chunk?: T): number;
732
+ }
733
+
734
+ interface Transformer<I = any, O = any> {
735
+ flush?: Bun.TransformerFlushCallback<O>;
736
+ readableType?: undefined;
737
+ start?: Bun.TransformerStartCallback<O>;
738
+ transform?: Bun.TransformerTransformCallback<I, O>;
739
+ writableType?: undefined;
740
+ }
741
+
742
+ interface Dict<T> {
743
+ [key: string]: T | undefined;
744
+ }
745
+
746
+ interface ReadOnlyDict<T> {
747
+ readonly [key: string]: T | undefined;
748
+ }
749
+
750
+ interface ErrnoException extends Error {
751
+ errno?: number | undefined;
752
+ code?: string | undefined;
753
+ path?: string | undefined;
754
+ syscall?: string | undefined;
755
+ }
756
+
757
+ /** An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */
758
+ interface DOMException extends Error {
759
+ readonly message: string;
760
+ readonly name: string;
761
+ readonly INDEX_SIZE_ERR: 1;
762
+ readonly DOMSTRING_SIZE_ERR: 2;
763
+ readonly HIERARCHY_REQUEST_ERR: 3;
764
+ readonly WRONG_DOCUMENT_ERR: 4;
765
+ readonly INVALID_CHARACTER_ERR: 5;
766
+ readonly NO_DATA_ALLOWED_ERR: 6;
767
+ readonly NO_MODIFICATION_ALLOWED_ERR: 7;
768
+ readonly NOT_FOUND_ERR: 8;
769
+ readonly NOT_SUPPORTED_ERR: 9;
770
+ readonly INUSE_ATTRIBUTE_ERR: 10;
771
+ readonly INVALID_STATE_ERR: 11;
772
+ readonly SYNTAX_ERR: 12;
773
+ readonly INVALID_MODIFICATION_ERR: 13;
774
+ readonly NAMESPACE_ERR: 14;
775
+ readonly INVALID_ACCESS_ERR: 15;
776
+ readonly VALIDATION_ERR: 16;
777
+ readonly TYPE_MISMATCH_ERR: 17;
778
+ readonly SECURITY_ERR: 18;
779
+ readonly NETWORK_ERR: 19;
780
+ readonly ABORT_ERR: 20;
781
+ readonly URL_MISMATCH_ERR: 21;
782
+ readonly QUOTA_EXCEEDED_ERR: 22;
783
+ readonly TIMEOUT_ERR: 23;
784
+ readonly INVALID_NODE_TYPE_ERR: 24;
785
+ readonly DATA_CLONE_ERR: 25;
786
+ }
787
+
788
+ // declare var DOMException: {
789
+ // prototype: DOMException;
790
+ // new (message?: string, name?: string): DOMException;
791
+ // };
792
+
793
+ declare function alert(message?: string): void;
794
+ declare function confirm(message?: string): boolean;
795
+ declare function prompt(message?: string, _default?: string): string | null;
796
+
797
+ interface SubtleCrypto extends Bun.__internal.NodeCryptoWebcryptoSubtleCrypto {}
798
+ declare var SubtleCrypto: {
799
+ prototype: SubtleCrypto;
800
+ new (): SubtleCrypto;
801
+ };
802
+
803
+ interface CryptoKey extends Bun.__internal.NodeCryptoWebcryptoCryptoKey {}
804
+ declare var CryptoKey: {
805
+ prototype: CryptoKey;
806
+ new (): CryptoKey;
807
+ };
808
+
809
+ interface Position {
810
+ lineText: string;
811
+ file: string;
812
+ namespace: string;
813
+ line: number;
814
+ column: number;
815
+ length: number;
816
+ offset: number;
817
+ }
818
+
819
+ declare class ResolveMessage {
820
+ readonly name: "ResolveMessage";
821
+ readonly position: Position | null;
822
+ readonly code: string;
823
+ readonly message: string;
824
+ readonly referrer: string;
825
+ readonly specifier: string;
826
+ readonly importKind:
827
+ | "entry_point"
828
+ | "stmt"
829
+ | "require"
830
+ | "import"
831
+ | "dynamic"
832
+ | "require_resolve"
833
+ | "at"
834
+ | "at_conditional"
835
+ | "url"
836
+ | "internal";
837
+ readonly level: "error" | "warning" | "info" | "debug" | "verbose";
838
+
839
+ toString(): string;
840
+ }
841
+
842
+ declare class BuildMessage {
843
+ readonly name: "BuildMessage";
844
+ readonly position: Position | null;
845
+ readonly message: string;
846
+ readonly level: "error" | "warning" | "info" | "debug" | "verbose";
847
+ }
848
+
849
+ interface ErrorConstructor {
850
+ isError(value: unknown): value is Error;
851
+
852
+ /**
853
+ * Create .stack property on a target object
854
+ */
855
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
856
+
857
+ /**
858
+ * Optional override for formatting stack traces
859
+ *
860
+ * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
861
+ */
862
+ prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
863
+
864
+ /**
865
+ * The maximum number of stack frames to capture.
866
+ */
867
+ stackTraceLimit: number;
868
+ }
869
+
870
+ interface ArrayBufferConstructor {
871
+ new (byteLength: number, options: { maxByteLength?: number }): ArrayBuffer;
872
+ }
873
+
874
+ interface ArrayBuffer {
875
+ /**
876
+ * Read-only. The length of the ArrayBuffer (in bytes).
877
+ */
878
+ readonly byteLength: number;
879
+ /**
880
+ * Resize an ArrayBuffer in-place.
881
+ */
882
+ resize(byteLength: number): ArrayBuffer;
883
+
884
+ /**
885
+ * Returns a section of an ArrayBuffer.
886
+ */
887
+ slice(begin: number, end?: number): ArrayBuffer;
888
+ readonly [Symbol.toStringTag]: string;
889
+ }
890
+
891
+ interface SharedArrayBuffer {
892
+ /**
893
+ * Grow the SharedArrayBuffer in-place.
894
+ */
895
+ grow(size: number): SharedArrayBuffer;
896
+ }
897
+
898
+ interface ArrayConstructor {
899
+ /**
900
+ * Create an array from an iterable or async iterable object.
901
+ * Values from the iterable are awaited.
902
+ *
903
+ * ```ts
904
+ * await Array.fromAsync([1]); // [1]
905
+ * await Array.fromAsync([Promise.resolve(1)]); // [1]
906
+ * await Array.fromAsync((async function*() { yield 1 })()); // [1]
907
+ * ```
908
+ *
909
+ * @param arrayLike - The iterable or async iterable to convert to an array.
910
+ * @returns A {@link Promise} whose fulfillment is a new {@link Array} instance containing the values from the iterator.
911
+ */
912
+ fromAsync<T>(arrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>): Promise<Awaited<T>[]>;
913
+
914
+ /**
915
+ * Create an array from an iterable or async iterable object.
916
+ * Values from the iterable are awaited. Results of the map function are also awaited.
917
+ *
918
+ * ```ts
919
+ * await Array.fromAsync([1]); // [1]
920
+ * await Array.fromAsync([Promise.resolve(1)]); // [1]
921
+ * await Array.fromAsync((async function*() { yield 1 })()); // [1]
922
+ * await Array.fromAsync([1], (n) => n + 1); // [2]
923
+ * await Array.fromAsync([1], (n) => Promise.resolve(n + 1)); // [2]
924
+ * ```
925
+ *
926
+ * @param arrayLike - The iterable or async iterable to convert to an array.
927
+ * @param mapFn - A mapper function that transforms each element of `arrayLike` after awaiting them.
928
+ * @param thisArg - The `this` to which `mapFn` is bound.
929
+ * @returns A {@link Promise} whose fulfillment is a new {@link Array} instance containing the values from the iterator.
930
+ */
931
+ fromAsync<T, U>(
932
+ arrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>,
933
+ mapFn?: (value: T, index: number) => U,
934
+ thisArg?: any,
935
+ ): Promise<Awaited<U>[]>;
936
+ }
937
+
938
+ interface ConsoleOptions {
939
+ stdout: import("stream").Writable;
940
+ stderr?: import("stream").Writable;
941
+ ignoreErrors?: boolean;
942
+ colorMode?: boolean | "auto";
943
+ inspectOptions?: import("util").InspectOptions;
944
+ groupIndentation?: number;
945
+ }
946
+
947
+ interface Console {
948
+ /**
949
+ * Asynchronously read lines from standard input (fd 0)
950
+ *
951
+ * ```ts
952
+ * for await (const line of console) {
953
+ * console.log(line);
954
+ * }
955
+ * ```
956
+ */
957
+ [Symbol.asyncIterator](): AsyncIterableIterator<string>;
958
+
959
+ /**
960
+ * Write text or bytes to stdout
961
+ *
962
+ * Unlike {@link console.log}, this does no formatting and doesn't add a
963
+ * newline or spaces between arguments. You can pass it strings or bytes or
964
+ * any combination of the two.
965
+ *
966
+ * ```ts
967
+ * console.write("hello world!", "\n"); // "hello world\n"
968
+ * ```
969
+ *
970
+ * @param data - The data to write
971
+ * @returns The number of bytes written
972
+ *
973
+ * This function is not available in the browser.
974
+ */
975
+ write(...data: Array<string | ArrayBufferView | ArrayBuffer>): number;
976
+
977
+ /**
978
+ * Clear the console
979
+ */
980
+ clear(): void;
981
+
982
+ assert(condition?: boolean, ...data: any[]): void;
983
+
984
+ /**
985
+ * Increment a [count](https://www.youtube.com/watch?v=2AoxCkySv34&t=22s)
986
+ * @param label label counter
987
+ */
988
+ count(label?: string): void;
989
+ countReset(label?: string): void;
990
+ debug(...data: any[]): void;
991
+ dir(item?: any, options?: any): void;
992
+ dirxml(...data: any[]): void;
993
+ /**
994
+ * Log to stderr in your terminal
995
+ *
996
+ * Appears in red
997
+ *
998
+ * @param data something to display
999
+ */
1000
+ error(...data: any[]): void;
1001
+ /** Does nothing currently */
1002
+ group(...data: any[]): void;
1003
+ /** Does nothing currently */
1004
+ groupCollapsed(...data: any[]): void;
1005
+ /** Does nothing currently */
1006
+ groupEnd(): void;
1007
+ info(...data: any[]): void;
1008
+ log(...data: any[]): void;
1009
+ /**
1010
+ * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just
1011
+ * logging the argument if it can't be parsed as tabular.
1012
+ *
1013
+ * ```js
1014
+ * // These can't be parsed as tabular data
1015
+ * console.table(Symbol());
1016
+ * // Symbol()
1017
+ *
1018
+ * console.table(undefined);
1019
+ * // undefined
1020
+ *
1021
+ * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
1022
+ * // ┌────┬─────┬─────┐
1023
+ * // │ │ a │ b │
1024
+ * // ├────┼─────┼─────┤
1025
+ * // │ 0 │ 1 │ 'Y' │
1026
+ * // │ 1 │ 'Z' │ 2 │
1027
+ * // └────┴─────┴─────┘
1028
+ *
1029
+ * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
1030
+ * // ┌────┬─────┐
1031
+ * // │ │ a │
1032
+ * // ├────┼─────┤
1033
+ * // 0 │ 1 │
1034
+ * // │ 1 │ 'Z' │
1035
+ * // └────┴─────┘
1036
+ * ```
1037
+ * @param properties Alternate properties for constructing the table.
1038
+ */
1039
+ table(tabularData?: any, properties?: string[]): void;
1040
+ /**
1041
+ * Begin a timer to log with {@link console.timeEnd}
1042
+ *
1043
+ * @param label - The label to use for the timer
1044
+ *
1045
+ * ```ts
1046
+ * console.time("how long????");
1047
+ * for (let i = 0; i < 999999; i++) {
1048
+ * // do stuff
1049
+ * let x = i * i;
1050
+ * }
1051
+ * console.timeEnd("how long????");
1052
+ * ```
1053
+ */
1054
+ time(label?: string): void;
1055
+ /**
1056
+ * End a timer to log with {@link console.time}
1057
+ *
1058
+ * @param label - The label to use for the timer
1059
+ *
1060
+ * ```ts
1061
+ * console.time("how long????");
1062
+ * for (let i = 0; i < 999999; i++) {
1063
+ * // do stuff
1064
+ * let x = i * i;
1065
+ * }
1066
+ * console.timeEnd("how long????");
1067
+ * ```
1068
+ */
1069
+ timeEnd(label?: string): void;
1070
+ timeLog(label?: string, ...data: any[]): void;
1071
+ timeStamp(label?: string): void;
1072
+ trace(...data: any[]): void;
1073
+ warn(...data: any[]): void;
1074
+
1075
+ /**
1076
+ * Creates a new Console with one or two writable stream instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr is not provided, stdout is used for stderr.
1077
+ */
1078
+ // Console: {
1079
+ // new (options: ConsoleOptions): Console;
1080
+ // new (
1081
+ // stdout: import("stream").Writable,
1082
+ // stderr?: import("stream").Writable,
1083
+ // ignoreErrors?: boolean,
1084
+ // ): Console;
1085
+ // };
1086
+ }
1087
+
1088
+ declare var console: Console;
1089
+
1090
+ interface ImportMeta {
1091
+ /**
1092
+ * `file://` url string for the current module.
1093
+ *
1094
+ * @example
1095
+ * ```ts
1096
+ * console.log(import.meta.url);
1097
+ * "file:///Users/me/projects/my-app/src/my-app.ts"
1098
+ * ```
1099
+ */
1100
+ url: string;
1101
+ /**
1102
+ * Absolute path to the source file
1103
+ */
1104
+ readonly path: string;
1105
+ /**
1106
+ * Absolute path to the directory containing the source file.
1107
+ *
1108
+ * Does not have a trailing slash
1109
+ */
1110
+ readonly dir: string;
1111
+ /**
1112
+ * Filename of the source file
1113
+ */
1114
+ readonly file: string;
1115
+ /**
1116
+ * The environment variables of the process
1117
+ *
1118
+ * ```ts
1119
+ * import.meta.env === process.env
1120
+ * ```
1121
+ */
1122
+ readonly env: NodeJS.ProcessEnv;
1123
+
1124
+ /**
1125
+ * @deprecated Use `require.resolve` or `Bun.resolveSync(moduleId, path.dirname(parent))` instead
1126
+ *
1127
+ * Resolve a module ID the same as if you imported it
1128
+ *
1129
+ * The `parent` argument is optional, and defaults to the current module's path.
1130
+ */
1131
+ resolveSync(moduleId: string, parent?: string): string;
1132
+
1133
+ /**
1134
+ * Load a CommonJS module within an ES Module. Bun's transpiler rewrites all
1135
+ * calls to `require` with `import.meta.require` when transpiling ES Modules
1136
+ * for the runtime.
1137
+ *
1138
+ * Warning: **This API is not stable** and may change or be removed in the
1139
+ * future. Use at your own risk.
1140
+ */
1141
+ require: NodeJS.Require;
1142
+
1143
+ /**
1144
+ * Did the current file start the process?
1145
+ *
1146
+ * @example
1147
+ * ```ts
1148
+ * if (import.meta.main) {
1149
+ * console.log("I started the process!");
1150
+ * }
1151
+ * ```
1152
+ *
1153
+ * @example
1154
+ * ```ts
1155
+ * console.log(
1156
+ * import.meta.main === (import.meta.path === Bun.main)
1157
+ * )
1158
+ * ```
1159
+ */
1160
+ readonly main: boolean;
1161
+
1162
+ /** Alias of `import.meta.dir`. Exists for Node.js compatibility */
1163
+ dirname: string;
1164
+
1165
+ /** Alias of `import.meta.path`. Exists for Node.js compatibility */
1166
+ filename: string;
1167
+ }
1168
+
1169
+ /**
1170
+ * NodeJS-style `require` function
1171
+ *
1172
+ * @param moduleId - The module ID to resolve
1173
+ */
1174
+ declare var require: NodeJS.Require;
1175
+
1176
+ /** Same as module.exports */
1177
+ declare var exports: any;
1178
+
1179
+ interface NodeModule {
1180
+ exports: any;
1181
+ }
1182
+
1183
+ declare var module: NodeModule;
1184
+
1185
+ /**
1186
+ * Creates a deep clone of an object.
1187
+ *
1188
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/structuredClone)
1189
+ */
1190
+ declare function structuredClone<T>(value: T, options?: Bun.StructuredSerializeOptions): T;
1191
+
1192
+ /**
1193
+ * Post a message to the parent thread.
1194
+ *
1195
+ * Only useful in a worker thread; calling this from the main thread does nothing.
1196
+ */
1197
+ declare function postMessage(message: any, transfer?: Bun.Transferable[]): void;
1198
+
1199
+ interface EventSourceInit {
1200
+ withCredentials?: boolean;
1201
+ }
1202
+
1203
+ interface PromiseConstructor {
1204
+ /**
1205
+ * Create a deferred promise, with exposed `resolve` and `reject` methods which can be called
1206
+ * separately.
1207
+ *
1208
+ * This is useful when you want to return a Promise and have code outside the Promise
1209
+ * resolve or reject it.
1210
+ *
1211
+ * ## Example
1212
+ * ```ts
1213
+ * const { promise, resolve, reject } = Promise.withResolvers();
1214
+ *
1215
+ * setTimeout(() => {
1216
+ * resolve("Hello world!");
1217
+ * }, 1000);
1218
+ *
1219
+ * await promise; // "Hello world!"
1220
+ * ```
1221
+ *
1222
+ * `Promise.withResolvers()` is a [stage3 proposal](https://github.com/tc39/proposal-promise-with-resolvers).
1223
+ */
1224
+ withResolvers<T>(): {
1225
+ promise: Promise<T>;
1226
+ resolve: (value?: T | PromiseLike<T>) => void;
1227
+ reject: (reason?: any) => void;
1228
+ };
1229
+
1230
+ /**
1231
+ * Try to run a function and return the result.
1232
+ * If the function throws, return the result of the `catch` function.
1233
+ *
1234
+ * @param fn - The function to run
1235
+ * @param args - The arguments to pass to the function. This is similar to `setTimeout` and avoids the extra closure.
1236
+ * @returns The result of the function or the result of the `catch` function
1237
+ */
1238
+ try<T, A extends any[] = []>(fn: (...args: A) => T | PromiseLike<T>, ...args: A): Promise<T>;
1239
+ }
1240
+
1241
+ interface Navigator {
1242
+ readonly userAgent: string;
1243
+ readonly platform: "MacIntel" | "Win32" | "Linux x86_64";
1244
+ readonly hardwareConcurrency: number;
1245
+ }
1246
+
1247
+ declare var navigator: Navigator;
1248
+
1249
+ interface BlobPropertyBag {
1250
+ /** Set a default "type". Not yet implemented. */
1251
+ type?: string;
1252
+ /** Not implemented in Bun yet. */
1253
+ // endings?: "transparent" | "native";
1254
+ }
1255
+
1256
+ interface WorkerOptions extends Bun.WorkerOptions {}
1257
+
1258
+ interface Blob {
1259
+ /**
1260
+ * Read the data from the blob as a JSON object.
1261
+ *
1262
+ * This first decodes the data from UTF-8, then parses it as JSON.
1263
+ */
1264
+ // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1265
+ json(): Promise<any>;
1266
+
1267
+ /**
1268
+ * Read the data from the blob as a {@link FormData} object.
1269
+ *
1270
+ * This first decodes the data from UTF-8, then parses it as a
1271
+ * `multipart/form-data` body or a `application/x-www-form-urlencoded` body.
1272
+ *
1273
+ * The `type` property of the blob is used to determine the format of the
1274
+ * body.
1275
+ *
1276
+ * This is a non-standard addition to the `Blob` API, to make it conform more
1277
+ * closely to the `BodyMixin` API.
1278
+ */
1279
+ formData(): Promise<FormData>;
1280
+
1281
+ /**
1282
+ * Returns a promise that resolves to the contents of the blob as a string
1283
+ */
1284
+ text(): Promise<string>;
1285
+
1286
+ /**
1287
+ * Returns a promise that resolves to the contents of the blob as an ArrayBuffer
1288
+ */
1289
+ arrayBuffer(): Promise<ArrayBuffer>;
1290
+
1291
+ /**
1292
+ * Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as `new Uint8Array(await blob.arrayBuffer())`
1293
+ */
1294
+ bytes(): Promise<Uint8Array>;
1295
+
1296
+ /**
1297
+ * Returns a readable stream of the blob's contents
1298
+ */
1299
+ stream(): ReadableStream;
1300
+ }
1301
+
1302
+ declare var Blob: Bun.__internal.UseLibDomIfAvailable<
1303
+ "Blob",
1304
+ {
1305
+ prototype: Blob;
1306
+ new (blobParts?: Bun.BlobPart[], options?: BlobPropertyBag): Blob;
1307
+ }
1308
+ >;
1309
+
1310
+ interface Uint8Array {
1311
+ /**
1312
+ * Convert the Uint8Array to a base64 encoded string
1313
+ * @returns The base64 encoded string representation of the Uint8Array
1314
+ */
1315
+ toBase64(options?: { alphabet?: "base64" | "base64url"; omitPadding?: boolean }): string;
1316
+
1317
+ /**
1318
+ * Set the contents of the Uint8Array from a base64 encoded string
1319
+ * @param base64 The base64 encoded string to decode into the array
1320
+ * @param offset Optional starting index to begin setting the decoded bytes (default: 0)
1321
+ */
1322
+ setFromBase64(
1323
+ base64: string,
1324
+ offset?: number,
1325
+ ): {
1326
+ /**
1327
+ * The number of bytes read from the base64 string
1328
+ */
1329
+ read: number;
1330
+ /**
1331
+ * The number of bytes written to the Uint8Array
1332
+ * Will never be greater than the `.byteLength` of this Uint8Array
1333
+ */
1334
+ written: number;
1335
+ };
1336
+
1337
+ /**
1338
+ * Convert the Uint8Array to a hex encoded string
1339
+ * @returns The hex encoded string representation of the Uint8Array
1340
+ */
1341
+ toHex(): string;
1342
+
1343
+ /**
1344
+ * Set the contents of the Uint8Array from a hex encoded string
1345
+ * @param hex The hex encoded string to decode into the array. The string must have
1346
+ * an even number of characters, be valid hexadecimal characters and contain no whitespace.
1347
+ */
1348
+ setFromHex(hex: string): {
1349
+ /**
1350
+ * The number of bytes read from the hex string
1351
+ */
1352
+ read: number;
1353
+ /**
1354
+ * The number of bytes written to the Uint8Array
1355
+ * Will never be greater than the `.byteLength` of this Uint8Array
1356
+ */
1357
+ written: number;
1358
+ };
1359
+ }
1360
+
1361
+ interface Uint8ArrayConstructor {
1362
+ /**
1363
+ * Create a new Uint8Array from a base64 encoded string
1364
+ * @param base64 The base64 encoded string to convert to a Uint8Array
1365
+ * @param options Optional options for decoding the base64 string
1366
+ * @returns A new Uint8Array containing the decoded data
1367
+ */
1368
+ fromBase64(
1369
+ base64: string,
1370
+ options?: {
1371
+ alphabet?: "base64" | "base64url";
1372
+ lastChunkHandling?: "loose" | "strict" | "stop-before-partial";
1373
+ },
1374
+ ): Uint8Array;
1375
+
1376
+ /**
1377
+ * Create a new Uint8Array from a hex encoded string
1378
+ * @param hex The hex encoded string to convert to a Uint8Array
1379
+ * @returns A new Uint8Array containing the decoded data
1380
+ */
1381
+ fromHex(hex: string): Uint8Array;
1382
+ }
1383
+
1384
+ interface BroadcastChannel {}
1385
+ declare var BroadcastChannel: Bun.__internal.UseLibDomIfAvailable<
1386
+ "BroadcastChannel",
1387
+ import("node:worker_threads").BroadcastChannel
1388
+ >;
1389
+
1390
+ declare var URL: Bun.__internal.UseLibDomIfAvailable<
1391
+ "URL",
1392
+ {
1393
+ prototype: URL;
1394
+ new (url: string | URL, base?: string | URL): URL;
1395
+ /**
1396
+ * Check if a URL can be parsed.
1397
+ *
1398
+ * @param url - The URL to check.
1399
+ * @param base - The base URL to use.
1400
+ */
1401
+ canParse(url: string, base?: string): boolean;
1402
+ /**
1403
+ * Create a URL from an object.
1404
+ *
1405
+ * @param object - The object to create a URL from.
1406
+ */
1407
+ createObjectURL(object: Blob): `blob:${string}`;
1408
+ /**
1409
+ * Revoke a URL.
1410
+ *
1411
+ * @param url - The URL to revoke.
1412
+ */
1413
+ revokeObjectURL(url: string): void;
1414
+ /**
1415
+ * Parse a URL.
1416
+ *
1417
+ * @param url - The URL to parse.
1418
+ * @param base - The base URL to use.
1419
+ */
1420
+ parse(url: string, base?: string): URL | null;
1421
+ }
1422
+ >;
1423
+
1424
+ declare var AbortController: Bun.__internal.UseLibDomIfAvailable<
1425
+ "AbortController",
1426
+ {
1427
+ prototype: AbortController;
1428
+ new (): AbortController;
1429
+ }
1430
+ >;
1431
+
1432
+ declare var AbortSignal: Bun.__internal.UseLibDomIfAvailable<
1433
+ "AbortSignal",
1434
+ {
1435
+ prototype: AbortSignal;
1436
+ new (): AbortSignal;
1437
+ }
1438
+ >;
1439
+
1440
+ interface DOMException {}
1441
+ declare var DOMException: Bun.__internal.UseLibDomIfAvailable<
1442
+ "DOMException",
1443
+ { prototype: DOMException; new (): DOMException }
1444
+ >;
1445
+
1446
+ interface FormData {}
1447
+ declare var FormData: Bun.__internal.UseLibDomIfAvailable<"FormData", { prototype: FormData; new (): FormData }>;
1448
+
1449
+ interface EventSource {}
1450
+ declare var EventSource: Bun.__internal.UseLibDomIfAvailable<
1451
+ "EventSource",
1452
+ { prototype: EventSource; new (): EventSource }
1453
+ >;
1454
+
1455
+ interface Performance extends Bun.__internal.LibPerformanceOrNodePerfHooksPerformance {}
1456
+ declare var performance: Bun.__internal.UseLibDomIfAvailable<"performance", Performance>;
1457
+
1458
+ interface PerformanceEntry {}
1459
+ declare var PerformanceEntry: Bun.__internal.UseLibDomIfAvailable<
1460
+ "PerformanceEntry",
1461
+ { prototype: PerformanceEntry; new (): PerformanceEntry }
1462
+ >;
1463
+
1464
+ interface PerformanceMark {}
1465
+ declare var PerformanceMark: Bun.__internal.UseLibDomIfAvailable<
1466
+ "PerformanceMark",
1467
+ { prototype: PerformanceMark; new (): PerformanceMark }
1468
+ >;
1469
+
1470
+ interface PerformanceMeasure {}
1471
+ declare var PerformanceMeasure: Bun.__internal.UseLibDomIfAvailable<
1472
+ "PerformanceMeasure",
1473
+ { prototype: PerformanceMeasure; new (): PerformanceMeasure }
1474
+ >;
1475
+
1476
+ interface PerformanceObserver {}
1477
+ declare var PerformanceObserver: Bun.__internal.UseLibDomIfAvailable<
1478
+ "PerformanceObserver",
1479
+ { prototype: PerformanceObserver; new (): PerformanceObserver }
1480
+ >;
1481
+
1482
+ interface PerformanceObserverEntryList {}
1483
+ declare var PerformanceObserverEntryList: Bun.__internal.UseLibDomIfAvailable<
1484
+ "PerformanceObserverEntryList",
1485
+ { prototype: PerformanceObserverEntryList; new (): PerformanceObserverEntryList }
1486
+ >;
1487
+
1488
+ interface PerformanceResourceTiming {}
1489
+ declare var PerformanceResourceTiming: Bun.__internal.UseLibDomIfAvailable<
1490
+ "PerformanceResourceTiming",
1491
+ { prototype: PerformanceResourceTiming; new (): PerformanceResourceTiming }
1492
+ >;
1493
+
1494
+ interface ReadableByteStreamController {}
1495
+ declare var ReadableByteStreamController: Bun.__internal.UseLibDomIfAvailable<
1496
+ "ReadableByteStreamController",
1497
+ { prototype: ReadableByteStreamController; new (): ReadableByteStreamController }
1498
+ >;
1499
+
1500
+ interface ReadableStreamBYOBReader {}
1501
+ declare var ReadableStreamBYOBReader: Bun.__internal.UseLibDomIfAvailable<
1502
+ "ReadableStreamBYOBReader",
1503
+ { prototype: ReadableStreamBYOBReader; new (): ReadableStreamBYOBReader }
1504
+ >;
1505
+
1506
+ interface ReadableStreamBYOBRequest {}
1507
+ declare var ReadableStreamBYOBRequest: Bun.__internal.UseLibDomIfAvailable<
1508
+ "ReadableStreamBYOBRequest",
1509
+ { prototype: ReadableStreamBYOBRequest; new (): ReadableStreamBYOBRequest }
1510
+ >;
1511
+
1512
+ interface TextDecoderStream {}
1513
+ declare var TextDecoderStream: Bun.__internal.UseLibDomIfAvailable<
1514
+ "TextDecoderStream",
1515
+ { prototype: TextDecoderStream; new (): TextDecoderStream }
1516
+ >;
1517
+
1518
+ interface TextEncoderStream {}
1519
+ declare var TextEncoderStream: Bun.__internal.UseLibDomIfAvailable<
1520
+ "TextEncoderStream",
1521
+ { prototype: TextEncoderStream; new (): TextEncoderStream }
1522
+ >;
1523
+
1524
+ interface URLSearchParams {}
1525
+ declare var URLSearchParams: Bun.__internal.UseLibDomIfAvailable<
1526
+ "URLSearchParams",
1527
+ { prototype: URLSearchParams; new (): URLSearchParams }
1528
+ >;
1529
+
1530
+ interface MessageChannel {}
1531
+ declare var MessageChannel: Bun.__internal.UseLibDomIfAvailable<
1532
+ "MessageChannel",
1533
+ { prototype: MessageChannel; new (): MessageChannel }
1534
+ >;
1535
+
1536
+ interface MessagePort {}
1537
+ declare var MessagePort: Bun.__internal.UseLibDomIfAvailable<
1538
+ "MessagePort",
1539
+ {
1540
+ prototype: MessagePort;
1541
+ new (): MessagePort;
1542
+ }
1543
+ >;
1544
+
1545
+ //#region Fetch
1546
+ interface RequestInit extends Bun.__internal.LibOrFallbackRequestInit {}
1547
+ interface ResponseInit extends Bun.__internal.LibOrFallbackResponseInit {}
1548
+
1549
+ interface Headers extends Bun.__internal.BunHeadersOverride {}
1550
+ declare var Headers: Bun.__internal.UseLibDomIfAvailable<
1551
+ "Headers",
1552
+ {
1553
+ prototype: Headers;
1554
+ new (init?: Bun.HeadersInit): Headers;
1555
+ }
1556
+ >;
1557
+
1558
+ interface Request extends Bun.__internal.BunRequestOverride {}
1559
+ declare var Request: Bun.__internal.UseLibDomIfAvailable<
1560
+ "Request",
1561
+ {
1562
+ prototype: Request;
1563
+ new (requestInfo: string, init?: RequestInit): Request;
1564
+ new (requestInfo: RequestInit & { url: string }): Request;
1565
+ new (requestInfo: Request, init?: RequestInit): Request;
1566
+ }
1567
+ >;
1568
+
1569
+ interface Response extends Bun.__internal.BunResponseOverride {}
1570
+ declare var Response: Bun.__internal.UseLibDomIfAvailable<
1571
+ "Response",
1572
+ {
1573
+ new (body?: Bun.BodyInit | null | undefined, init?: ResponseInit | undefined): Response;
1574
+ /**
1575
+ * Create a new {@link Response} with a JSON body
1576
+ *
1577
+ * @param body - The body of the response
1578
+ * @param options - options to pass to the response
1579
+ *
1580
+ * @example
1581
+ *
1582
+ * ```ts
1583
+ * const response = Response.json({hi: "there"});
1584
+ * console.assert(
1585
+ * await response.text(),
1586
+ * `{"hi":"there"}`
1587
+ * );
1588
+ * ```
1589
+ * -------
1590
+ *
1591
+ * This is syntactic sugar for:
1592
+ * ```js
1593
+ * new Response(JSON.stringify(body), {headers: { "Content-Type": "application/json" }})
1594
+ * ```
1595
+ * @link https://github.com/whatwg/fetch/issues/1389
1596
+ */
1597
+ json(body?: any, init?: ResponseInit | number): Response;
1598
+
1599
+ /**
1600
+ * Create a new {@link Response} that redirects to url
1601
+ *
1602
+ * @param url - the URL to redirect to
1603
+ * @param status - the HTTP status code to use for the redirect
1604
+ */
1605
+ redirect(url: string, status?: number): Response;
1606
+
1607
+ /**
1608
+ * Create a new {@link Response} that redirects to url
1609
+ *
1610
+ * @param url - the URL to redirect to
1611
+ * @param options - options to pass to the response
1612
+ */
1613
+ redirect(url: string, init?: ResponseInit): Response;
1614
+
1615
+ /**
1616
+ * Create a new {@link Response} that has a network error
1617
+ */
1618
+ error(): Response;
1619
+ }
1620
+ >;
1621
+
1622
+ /**
1623
+ * Extends Bun.TLSOptions with extra properties that are only supported in `fetch(url, {tls: ...})`
1624
+ */
1625
+ interface BunFetchRequestInitTLS extends Bun.TLSOptions {
1626
+ /**
1627
+ * Custom function to check the server identity
1628
+ * @param hostname - The hostname of the server
1629
+ * @param cert - The certificate of the server
1630
+ * @returns An error if the server is unauthorized, otherwise undefined
1631
+ */
1632
+ checkServerIdentity?: NonNullable<import("node:tls").ConnectionOptions["checkServerIdentity"]>;
1633
+ }
1634
+
1635
+ /**
1636
+ * BunFetchRequestInit represents additional options that Bun supports in `fetch()` only.
1637
+ *
1638
+ * Bun extends the `fetch` API with some additional options, except
1639
+ * this interface is not quite a `RequestInit`, because they won't work
1640
+ * if passed to `new Request()`. This is why it's a separate type.
1641
+ */
1642
+ interface BunFetchRequestInit extends RequestInit {
1643
+ /**
1644
+ * Override the default TLS options
1645
+ */
1646
+ tls?: BunFetchRequestInitTLS;
1647
+
1648
+ /**
1649
+ * Log the raw HTTP request & response to stdout. This API may be
1650
+ * removed in a future version of Bun without notice.
1651
+ * This is a custom property that is not part of the Fetch API specification.
1652
+ * It exists mostly as a debugging tool
1653
+ */
1654
+ verbose?: boolean;
1655
+
1656
+ /**
1657
+ * Override http_proxy or HTTPS_PROXY
1658
+ * This is a custom property that is not part of the Fetch API specification.
1659
+ */
1660
+ proxy?: string;
1661
+
1662
+ /**
1663
+ * Override the default S3 options
1664
+ */
1665
+ s3?: Bun.S3Options;
1666
+ }
1667
+
1668
+ /**
1669
+ * Send a HTTP(s) request
1670
+ *
1671
+ * @param request Request object
1672
+ * @param init A structured value that contains settings for the fetch() request.
1673
+ *
1674
+ * @returns A promise that resolves to {@link Response} object.
1675
+ */
1676
+ declare function fetch(request: Request, init?: BunFetchRequestInit): Promise<Response>;
1677
+
1678
+ /**
1679
+ * Send a HTTP(s) request
1680
+ *
1681
+ * @param url URL string
1682
+ * @param init A structured value that contains settings for the fetch() request.
1683
+ *
1684
+ * @returns A promise that resolves to {@link Response} object.
1685
+ */
1686
+ declare function fetch(url: string | URL | Request, init?: BunFetchRequestInit): Promise<Response>;
1687
+
1688
+ /**
1689
+ * Send a HTTP(s) request
1690
+ *
1691
+ * @param input URL string or Request object
1692
+ * @param init A structured value that contains settings for the fetch() request.
1693
+ *
1694
+ * @returns A promise that resolves to {@link Response} object.
1695
+ */
1696
+ declare function fetch(input: string | URL | Request, init?: BunFetchRequestInit): Promise<Response>;
1697
+
1698
+ /**
1699
+ * Bun's extensions of the `fetch` API
1700
+ *
1701
+ * @see {@link fetch} The `fetch` function itself
1702
+ */
1703
+ declare namespace fetch {
1704
+ /**
1705
+ * Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.
1706
+ *
1707
+ * This is a custom property that is not part of the Fetch API specification.
1708
+ *
1709
+ * @param url - The URL to preconnect to
1710
+ * @param options - Options for the preconnect
1711
+ */
1712
+ export function preconnect(
1713
+ url: string | URL,
1714
+ options?: {
1715
+ /** Preconnect to the DNS of the URL */
1716
+ dns?: boolean;
1717
+ /** Preconnect to the TCP connection of the URL */
1718
+ tcp?: boolean;
1719
+ /** Preconnect to the HTTP connection of the URL */
1720
+ http?: boolean;
1721
+ /** Preconnect to the HTTPS connection of the URL */
1722
+ https?: boolean;
1723
+ },
1724
+ ): void;
1954
1725
  }
1726
+ //#endregion