bun-types 0.1.11 → 0.2.1

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/types.d.ts +1025 -27
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bun-types",
3
- "version": "0.1.11",
3
+ "version": "0.2.1",
4
4
  "description": "Type definitions for Bun, an incredibly fast JavaScript runtime",
5
5
  "types": "types.d.ts",
6
6
  "files": [
package/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Type definitions for bun 0.1.11
1
+ // Type definitions for bun 0.2.1
2
2
  // Project: https://github.com/oven-sh/bun
3
3
  // Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner>
4
4
  // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -823,7 +823,10 @@ interface ResponseInit {
823
823
  * ```
824
824
  */
825
825
  declare class Response implements BlobInterface {
826
- constructor(body: BlobPart | BlobPart[], options?: ResponseInit);
826
+ constructor(
827
+ body?: ReadableStream | BlobPart | BlobPart[] | null,
828
+ options?: ResponseInit
829
+ );
827
830
 
828
831
  /**
829
832
  * Create a new {@link Response} with a JSON body
@@ -885,6 +888,21 @@ declare class Response implements BlobInterface {
885
888
  */
886
889
  readonly headers: Headers;
887
890
 
891
+ /**
892
+ * HTTP response body as a [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
893
+ *
894
+ * This is part of web Streams
895
+ *
896
+ * @example
897
+ * ```ts
898
+ * const {body} = await fetch("https://remix.run");
899
+ * const reader = body.getReader();
900
+ * const {done, value} = await reader.read();
901
+ * console.log(value); // Uint8Array
902
+ * ```
903
+ */
904
+ readonly body: ReadableStream | null;
905
+
888
906
  /**
889
907
  * Has the body of the response already been consumed?
890
908
  */
@@ -1020,7 +1038,9 @@ interface RequestInit {
1020
1038
  /**
1021
1039
  * A boolean to set request's keepalive.
1022
1040
  *
1023
- * Note: as of Bun v0.0.74, this is not implemented yet.
1041
+ * Available in Bun v0.2.0 and above.
1042
+ *
1043
+ * This is enabled by default
1024
1044
  */
1025
1045
  keepalive?: boolean;
1026
1046
  /**
@@ -1055,6 +1075,11 @@ interface RequestInit {
1055
1075
  * This does nothing in Bun
1056
1076
  */
1057
1077
  window?: any;
1078
+
1079
+ /**
1080
+ * Enable or disable HTTP request timeout
1081
+ */
1082
+ timeout?: boolean;
1058
1083
  }
1059
1084
 
1060
1085
  /**
@@ -1105,6 +1130,19 @@ declare class Request implements BlobInterface {
1105
1130
  */
1106
1131
  text(): Promise<string>;
1107
1132
 
1133
+ /**
1134
+ * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a {@link ReadableStream}.
1135
+ *
1136
+ * Streaming **outgoing** HTTP request bodies via `fetch()` is not yet supported in
1137
+ * Bun.
1138
+ *
1139
+ * Reading **incoming** HTTP request bodies via `ReadableStream` in `Bun.serve()` is supported
1140
+ * as of Bun v0.2.0.
1141
+ *
1142
+ *
1143
+ */
1144
+ get body(): ReadableStream | null;
1145
+
1108
1146
  /**
1109
1147
  * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as an ArrayBuffer.
1110
1148
  *
@@ -1436,7 +1474,21 @@ declare function clearTimeout(id?: number): void;
1436
1474
  *
1437
1475
  *
1438
1476
  */
1439
- declare function fetch(url: string, init?: RequestInit): Promise<Response>;
1477
+ declare function fetch(
1478
+ url: string,
1479
+ init?: RequestInit,
1480
+ /**
1481
+ * This is a custom property that is not part of the Fetch API specification.
1482
+ * It exists mostly as a debugging tool
1483
+ */
1484
+ bunOnlyOptions?: {
1485
+ /**
1486
+ * Log the raw HTTP request & response to stdout. This API may be
1487
+ * removed in a future version of Bun without notice.
1488
+ */
1489
+ verbose: boolean;
1490
+ }
1491
+ ): Promise<Response>;
1440
1492
 
1441
1493
  /**
1442
1494
  * Send a HTTP(s) request
@@ -1449,7 +1501,21 @@ declare function fetch(url: string, init?: RequestInit): Promise<Response>;
1449
1501
  *
1450
1502
  */
1451
1503
  // tslint:disable-next-line:unified-signatures
1452
- declare function fetch(request: Request, init?: RequestInit): Promise<Response>;
1504
+ declare function fetch(
1505
+ request: Request,
1506
+ init?: RequestInit,
1507
+ /**
1508
+ * This is a custom property that is not part of the Fetch API specification.
1509
+ * It exists mostly as a debugging tool
1510
+ */
1511
+ bunOnlyOptions?: {
1512
+ /**
1513
+ * Log the raw HTTP request & response to stdout. This API may be
1514
+ * removed in a future version of Bun without notice.
1515
+ */
1516
+ verbose: boolean;
1517
+ }
1518
+ ): Promise<Response>;
1453
1519
 
1454
1520
  declare function queueMicrotask(callback: () => void): void;
1455
1521
  /**
@@ -2108,17 +2174,9 @@ declare var Loader: {
2108
2174
  * instead.
2109
2175
  *
2110
2176
  * @param specifier - module specifier as it appears in transpiled source code
2177
+ * @param referrer - module specifier that is resolving this specifier
2111
2178
  */
2112
- resolve: (specifier: string) => Promise<string>;
2113
- /**
2114
- * Synchronously resolve a module specifier
2115
- *
2116
- * This may return a path to `node_modules.server.bun`, which will be confusing.
2117
- *
2118
- * Consider {@link Bun.resolveSync}
2119
- * instead.
2120
- */
2121
- resolveSync: (specifier: string, from: string) => string;
2179
+ resolve: (specifier: strin, referrer: string) => string;
2122
2180
  };
2123
2181
 
2124
2182
  /** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */
@@ -2139,6 +2197,8 @@ interface ReadableStream<R = any> {
2139
2197
  callbackfn: (value: any, key: number, parent: ReadableStream<R>) => void,
2140
2198
  thisArg?: any
2141
2199
  ): void;
2200
+ [Symbol.asyncIterator](): AsyncIterableIterator<R>;
2201
+ values(options: { preventCancel: boolean }): AsyncIterableIterator<R>;
2142
2202
  }
2143
2203
 
2144
2204
  declare var ReadableStream: {
@@ -13440,6 +13500,28 @@ declare module "bun" {
13440
13500
  end(): ArrayBuffer | Uint8Array;
13441
13501
  }
13442
13502
 
13503
+ /**
13504
+ * Fast incremental writer for files and pipes.
13505
+ *
13506
+ * This uses the same interface as {@link ArrayBufferSink}, but writes to a file or pipe.
13507
+ */
13508
+ export interface FileSink {
13509
+ /**
13510
+ * Write a chunk of data to the file.
13511
+ *
13512
+ * If the file descriptor is not writable yet, the data is buffered.
13513
+ */
13514
+ write(chunk: string | ArrayBufferView | ArrayBuffer): number;
13515
+ /**
13516
+ * Flush the internal buffer, committing the data to disk or the pipe.
13517
+ */
13518
+ flush(): number | Promise<number>;
13519
+ /**
13520
+ * Close the file descriptor. This also flushes the internal buffer.
13521
+ */
13522
+ end(error?: Error): number | Promise<number>;
13523
+ }
13524
+
13443
13525
  /**
13444
13526
  * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
13445
13527
  *
@@ -13476,6 +13558,15 @@ declare module "bun" {
13476
13558
  * @param end - absolute offset in bytes (relative to 0)
13477
13559
  */
13478
13560
  slice(begin?: number, end?: number): FileBlob;
13561
+
13562
+ /**
13563
+ * Incremental writer for files and pipes.
13564
+ */
13565
+ writer(): FileSink;
13566
+
13567
+ readonly readable: ReadableStream;
13568
+
13569
+ // TODO: writable: WritableStream;
13479
13570
  }
13480
13571
 
13481
13572
  /**
@@ -13731,7 +13822,477 @@ declare module "bun" {
13731
13822
  | "entry-point";
13732
13823
  }
13733
13824
 
13734
- export interface ServeOptions {
13825
+ /**
13826
+ * **0** means the message was **dropped**
13827
+ *
13828
+ * **-1** means **backpressure**
13829
+ *
13830
+ * **> 0** is the **number of bytes sent**
13831
+ *
13832
+ */
13833
+ type ServerWebSocketSendStatus = 0 | -1 | number;
13834
+
13835
+ /**
13836
+ * Fast WebSocket API designed for server environments.
13837
+ *
13838
+ * Features:
13839
+ * - **Message compression** - Messages can be compressed
13840
+ * - **Backpressure** - If the client is not ready to receive data, the server will tell you.
13841
+ * - **Dropped messages** - If the client cannot receive data, the server will tell you.
13842
+ * - **Topics** - Messages can be {@link ServerWebSocket.publish}ed to a specific topic and the client can {@link ServerWebSocket.subscribe} to topics
13843
+ *
13844
+ * This is slightly different than the browser {@link WebSocket} which Bun supports for clients.
13845
+ *
13846
+ * Powered by [uWebSockets](https://github.com/uNetworking/uWebSockets)
13847
+ */
13848
+ export interface ServerWebSocket<T = undefined> {
13849
+ /**
13850
+ *
13851
+ * Send a message to the client.
13852
+ *
13853
+ * @param data The message to send
13854
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
13855
+ *
13856
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
13857
+ *
13858
+ * @example
13859
+ *
13860
+ * ```js
13861
+ * const status = ws.send("Hello World");
13862
+ * if (status === 0) {
13863
+ * console.log("Message was dropped");
13864
+ * } else if (status === -1) {
13865
+ * console.log("Backpressure was applied");
13866
+ * } else {
13867
+ * console.log(`Message sent! ${status} bytes sent`);
13868
+ * }
13869
+ * ```
13870
+ *
13871
+ * @example
13872
+ *
13873
+ * ```js
13874
+ * ws.send("Feeling very compressed", true);
13875
+ * ```
13876
+ *
13877
+ * @example
13878
+ *
13879
+ * ```js
13880
+ * ws.send(new Uint8Array([1, 2, 3, 4]));
13881
+ * ```
13882
+ *
13883
+ * @example
13884
+ *
13885
+ * ```js
13886
+ * ws.send(new ArrayBuffer(4));
13887
+ * ```
13888
+ *
13889
+ * @example
13890
+ *
13891
+ * ```js
13892
+ * ws.send(new DataView(new ArrayBuffer(4)));
13893
+ * ```
13894
+ *
13895
+ */
13896
+ send(
13897
+ data: string | ArrayBufferView | ArrayBuffer,
13898
+ compress?: boolean
13899
+ ): ServerWebSocketSendStatus;
13900
+
13901
+ /**
13902
+ *
13903
+ * Send a message to the client.
13904
+ *
13905
+ * This function is the same as {@link ServerWebSocket.send} but it only accepts a string. This function includes a fast path.
13906
+ *
13907
+ * @param data The message to send
13908
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
13909
+ *
13910
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
13911
+ *
13912
+ * @example
13913
+ *
13914
+ * ```js
13915
+ * const status = ws.send("Hello World");
13916
+ * if (status === 0) {
13917
+ * console.log("Message was dropped");
13918
+ * } else if (status === -1) {
13919
+ * console.log("Backpressure was applied");
13920
+ * } else {
13921
+ * console.log(`Message sent! ${status} bytes sent`);
13922
+ * }
13923
+ * ```
13924
+ *
13925
+ * @example
13926
+ *
13927
+ * ```js
13928
+ * ws.send("Feeling very compressed", true);
13929
+ * ```
13930
+ *
13931
+ *
13932
+ */
13933
+ sendText(data: string, compress?: boolean): ServerWebSocketSendStatus;
13934
+
13935
+ /**
13936
+ *
13937
+ * Send a message to the client.
13938
+ *
13939
+ * This function is the same as {@link ServerWebSocket.send} but it only accepts Uint8Array.
13940
+ *
13941
+ * @param data The message to send
13942
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
13943
+ *
13944
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
13945
+ *
13946
+ *
13947
+ * ```js
13948
+ * ws.sendBinary(new Uint8Array([1, 2, 3, 4]));
13949
+ * ```
13950
+ *
13951
+ * @example
13952
+ *
13953
+ * ```js
13954
+ * ws.sendBinary(new ArrayBuffer(4));
13955
+ * ```
13956
+ *
13957
+ * @example
13958
+ *
13959
+ * ```js
13960
+ * ws.sendBinary(new DataView(new ArrayBuffer(4)));
13961
+ * ```
13962
+ *
13963
+ */
13964
+ sendBinary(data: Uint8Array, compress?: boolean): ServerWebSocketSendStatus;
13965
+
13966
+ /**
13967
+ * Gently close the connection.
13968
+ *
13969
+ * @param code The close code
13970
+ *
13971
+ * @param reason The close reason
13972
+ *
13973
+ * To close the connection abruptly, use `close(0, "")`
13974
+ */
13975
+ close(code?: number, reason?: string): void;
13976
+
13977
+ /**
13978
+ * Send a message to all subscribers of a topic
13979
+ *
13980
+ * @param topic The topic to publish to
13981
+ * @param data The data to send
13982
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
13983
+ *
13984
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
13985
+ *
13986
+ * @example
13987
+ *
13988
+ * ```js
13989
+ * ws.publish("chat", "Hello World");
13990
+ * ```
13991
+ *
13992
+ * @example
13993
+ * ```js
13994
+ * ws.publish("chat", new Uint8Array([1, 2, 3, 4]));
13995
+ * ```
13996
+ *
13997
+ * @example
13998
+ * ```js
13999
+ * ws.publish("chat", new ArrayBuffer(4), true);
14000
+ * ```
14001
+ *
14002
+ * @example
14003
+ * ```js
14004
+ * ws.publish("chat", new DataView(new ArrayBuffer(4)));
14005
+ * ```
14006
+ */
14007
+ publish(
14008
+ topic: string,
14009
+ data: string | ArrayBufferView | ArrayBuffer,
14010
+ compress?: boolean
14011
+ ): ServerWebSocketSendStatus;
14012
+
14013
+ /**
14014
+ * Send a message to all subscribers of a topic
14015
+ *
14016
+ * This function is the same as {@link publish} but only accepts string input. This function has a fast path.
14017
+ *
14018
+ * @param topic The topic to publish to
14019
+ * @param data The data to send
14020
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14021
+ *
14022
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14023
+ *
14024
+ * @example
14025
+ *
14026
+ * ```js
14027
+ * ws.publishText("chat", "Hello World");
14028
+ * ```
14029
+ *
14030
+ */
14031
+ publishText(
14032
+ topic: string,
14033
+ data: string,
14034
+ compress?: bool
14035
+ ): ServerWebSocketSendStatus;
14036
+
14037
+ /**
14038
+ * Send a message to all subscribers of a topic
14039
+ *
14040
+ * This function is the same as {@link publish} but only accepts a Uint8Array. This function has a fast path.
14041
+ *
14042
+ * @param topic The topic to publish to
14043
+ * @param data The data to send
14044
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14045
+ *
14046
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14047
+ *
14048
+ * @example
14049
+ *
14050
+ * ```js
14051
+ * ws.publishBinary("chat", "Hello World");
14052
+ * ```
14053
+ *
14054
+ * @example
14055
+ * ```js
14056
+ * ws.publishBinary("chat", new Uint8Array([1, 2, 3, 4]));
14057
+ * ```
14058
+ *
14059
+ * @example
14060
+ * ```js
14061
+ * ws.publishBinary("chat", new ArrayBuffer(4), true);
14062
+ * ```
14063
+ *
14064
+ * @example
14065
+ * ```js
14066
+ * ws.publishBinary("chat", new DataView(new ArrayBuffer(4)));
14067
+ * ```
14068
+ */
14069
+ publishBinary(
14070
+ topic: string,
14071
+ data: Uint8Array,
14072
+ compress?: boolean
14073
+ ): ServerWebSocketSendStatus;
14074
+
14075
+ /**
14076
+ * Subscribe to a topic
14077
+ * @param topic The topic to subscribe to
14078
+ *
14079
+ * @example
14080
+ * ```js
14081
+ * ws.subscribe("chat");
14082
+ * ```
14083
+ */
14084
+ subscribe(topic: string): void;
14085
+
14086
+ /**
14087
+ * Unsubscribe from a topic
14088
+ * @param topic The topic to unsubscribe from
14089
+ *
14090
+ * @example
14091
+ * ```js
14092
+ * ws.unsubscribe("chat");
14093
+ * ```
14094
+ *
14095
+ */
14096
+ unsubscribe(topic: string): void;
14097
+
14098
+ /**
14099
+ * Is the socket subscribed to a topic?
14100
+ * @param topic The topic to check
14101
+ *
14102
+ * @returns `true` if the socket is subscribed to the topic, `false` otherwise
14103
+ */
14104
+ isSubscribed(topic: string): boolean;
14105
+
14106
+ /**
14107
+ * The remote address of the client
14108
+ * @example
14109
+ * ```js
14110
+ * console.log(socket.remoteAddress); // "127.0.0.1"
14111
+ * ```
14112
+ */
14113
+ readonly remoteAddress: string;
14114
+
14115
+ /**
14116
+ * Ready state of the socket
14117
+ *
14118
+ * @example
14119
+ * ```js
14120
+ * console.log(socket.readyState); // 1
14121
+ * ```
14122
+ */
14123
+ readonly readyState: -1 | 0 | 1 | 2 | 3;
14124
+
14125
+ /**
14126
+ * The data from the {@link Server.upgrade} function
14127
+ *
14128
+ * Put any data you want to share between the `fetch` function and the websocket here.
14129
+ *
14130
+ * You can read/write to this property at any time.
14131
+ */
14132
+ data: T;
14133
+
14134
+ /**
14135
+ * Batch data sent to a {@link ServerWebSocket}
14136
+ *
14137
+ * This makes it significantly faster to {@link ServerWebSocket.send} or {@link ServerWebSocket.publish} multiple messages
14138
+ *
14139
+ * The `message`, `open`, and `drain` callbacks are automatically corked, so
14140
+ * you only need to call this if you are sending messages outside of those
14141
+ * callbacks or in async functions
14142
+ */
14143
+ cork?: (callback: (ws: ServerWebSocket<T>) => any) => void | Promise<void>;
14144
+
14145
+ /**
14146
+ * Configure the {@link WebSocketHandler.message} callback to return a {@link ArrayBuffer} instead of a {@link Uint8Array}
14147
+ *
14148
+ * @default "uint8array"
14149
+ */
14150
+ binaryType?: "arraybuffer" | "uint8array";
14151
+ }
14152
+
14153
+ type WebSocketCompressor =
14154
+ | "disable"
14155
+ | "shared"
14156
+ | "dedicated"
14157
+ | "3KB"
14158
+ | "4KB"
14159
+ | "8KB"
14160
+ | "16KB"
14161
+ | "32KB"
14162
+ | "64KB"
14163
+ | "128KB"
14164
+ | "256KB";
14165
+
14166
+ /**
14167
+ * Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve}
14168
+ *
14169
+ * @example
14170
+ * ```ts
14171
+ * import { websocket, serve } from "bun";
14172
+ *
14173
+ * serve({
14174
+ * port: 3000,
14175
+ * websocket: websocket<{name: string}>({
14176
+ * open: (ws) => {
14177
+ * console.log("Client connected");
14178
+ * },
14179
+ * message: (ws, message) => {
14180
+ * console.log(`${ws.data.name}: ${message}`);
14181
+ * },
14182
+ * close: (ws) => {
14183
+ * console.log("Client disconnected");
14184
+ * },
14185
+ * }),
14186
+ *
14187
+ * fetch(req, server) {
14188
+ * if (req.url === "/chat") {
14189
+ * const upgraded = server.upgrade(req, {
14190
+ * data: {
14191
+ * name: new URL(req.url).searchParams.get("name"),
14192
+ * },
14193
+ * });
14194
+ * if (!upgraded) {
14195
+ * return new Response("Upgrade failed", { status: 400 });
14196
+ * }
14197
+ * return;
14198
+ * }
14199
+ * return new Response("Hello World");
14200
+ * },
14201
+ * });
14202
+ */
14203
+ export interface WebSocketHandler<T = undefined> {
14204
+ /**
14205
+ * Handle an incoming message to a {@link ServerWebSocket}
14206
+ *
14207
+ * @param ws The {@link ServerWebSocket} that received the message
14208
+ * @param message The message received
14209
+ *
14210
+ * To change `message` to be an `ArrayBuffer` instead of a `Uint8Array`, set `ws.binaryType = "arraybuffer"`
14211
+ */
14212
+ message: (
14213
+ ws: ServerWebSocket<T>,
14214
+ message: string | Uint8Array
14215
+ ) => void | Promise<void>;
14216
+
14217
+ /**
14218
+ * The {@link ServerWebSocket} has been opened
14219
+ *
14220
+ * @param ws The {@link ServerWebSocket} that was opened
14221
+ */
14222
+ open?: (ws: ServerWebSocket<T>) => void | Promise<void>;
14223
+ /**
14224
+ * The {@link ServerWebSocket} is ready for more data
14225
+ *
14226
+ * @param ws The {@link ServerWebSocket} that is ready
14227
+ */
14228
+ drain?: (ws: ServerWebSocket<T>) => void | Promise<void>;
14229
+ /**
14230
+ * The {@link ServerWebSocket} is being closed
14231
+ * @param ws The {@link ServerWebSocket} that was closed
14232
+ * @param code The close code
14233
+ * @param message The close message
14234
+ */
14235
+ close?: (
14236
+ ws: ServerWebSocket<T>,
14237
+ code: number,
14238
+ message: string
14239
+ ) => void | Promise<void>;
14240
+
14241
+ /**
14242
+ * Enable compression for clients that support it. By default, compression is disabled.
14243
+ *
14244
+ * @default false
14245
+ *
14246
+ * `true` is equivalent to `"shared"
14247
+ */
14248
+ perMessageDeflate?:
14249
+ | true
14250
+ | false
14251
+ | {
14252
+ /**
14253
+ * Enable compression on the {@link ServerWebSocket}
14254
+ *
14255
+ * @default false
14256
+ *
14257
+ * `true` is equivalent to `"shared"
14258
+ */
14259
+ compress?: WebSocketCompressor | false | true;
14260
+ /**
14261
+ * Configure decompression
14262
+ *
14263
+ * @default false
14264
+ *
14265
+ * `true` is equivalent to `"shared"
14266
+ */
14267
+ decompress?: WebSocketCompressor | false | true;
14268
+ };
14269
+
14270
+ /**
14271
+ * The maximum size of a message
14272
+ */
14273
+ maxPayloadLength?: number;
14274
+ /**
14275
+ * After a connection has not received a message for this many seconds, it will be closed.
14276
+ * @default 120 (2 minutes)
14277
+ */
14278
+ idleTimeout?: number;
14279
+ /**
14280
+ * The maximum number of bytes that can be buffered for a single connection.
14281
+ * @default 16MB
14282
+ */
14283
+ backpressureLimit?: number;
14284
+ /**
14285
+ * Close the connection if the backpressure limit is reached.
14286
+ * @default false
14287
+ * @see {@link backpressureLimit}
14288
+ * @see {@link ServerWebSocketSendStatus}
14289
+ * @see {@link ServerWebSocket.send}
14290
+ * @see {@link ServerWebSocket.publish}
14291
+ */
14292
+ closeOnBackpressureLimit?: boolean;
14293
+ }
14294
+
14295
+ interface GenericServeOptions {
13735
14296
  /**
13736
14297
  * What port should the server listen on?
13737
14298
  * @default process.env.PORT || "3000"
@@ -13793,18 +14354,78 @@ declare module "bun" {
13793
14354
  */
13794
14355
  development?: boolean;
13795
14356
 
14357
+ error?: (
14358
+ this: Server,
14359
+ request: Errorlike
14360
+ ) => Response | Promise<Response> | undefined | Promise<undefined>;
14361
+ }
14362
+
14363
+ export interface ServeOptions extends GenericServeOptions {
13796
14364
  /**
13797
14365
  * Handle HTTP requests
13798
14366
  *
13799
14367
  * Respond to {@link Request} objects with a {@link Response} object.
13800
14368
  *
13801
14369
  */
13802
- fetch(this: Server, request: Request): Response | Promise<Response>;
14370
+ fetch(
14371
+ this: Server,
14372
+ request: Request,
14373
+ server: Server
14374
+ ): Response | Promise<Response>;
14375
+ }
13803
14376
 
13804
- error?: (
14377
+ export interface WebSocketServeOptions<WebSocketDataType = undefined>
14378
+ extends GenericServeOptions {
14379
+ /**
14380
+ * Enable websockets with {@link Bun.serve}
14381
+ *
14382
+ * For simpler type safety, see {@link Bun.websocket}
14383
+ *
14384
+ * @example
14385
+ * ```js
14386
+ *import { serve, websocket } from "bun";
14387
+ *serve({
14388
+ * websocket: websocket({
14389
+ * open: (ws) => {
14390
+ * console.log("Client connected");
14391
+ * },
14392
+ * message: (ws, message) => {
14393
+ * console.log("Client sent message", message);
14394
+ * },
14395
+ * close: (ws) => {
14396
+ * console.log("Client disconnected");
14397
+ * },
14398
+ * }),
14399
+ * fetch(req, server) {
14400
+ * if (req.url === "/chat") {
14401
+ * const upgraded = server.upgrade(req);
14402
+ * if (!upgraded) {
14403
+ * return new Response("Upgrade failed", { status: 400 });
14404
+ * }
14405
+ * }
14406
+ * return new Response("Hello World");
14407
+ * },
14408
+ *});
14409
+ *```
14410
+ * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade}
14411
+ *
14412
+ * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property
14413
+ *
14414
+ *
14415
+ */
14416
+ websocket: WebSocketHandler<WebSocketDataType>;
14417
+
14418
+ /**
14419
+ * Handle HTTP requests or upgrade them to a {@link ServerWebSocket}
14420
+ *
14421
+ * Respond to {@link Request} objects with a {@link Response} object.
14422
+ *
14423
+ */
14424
+ fetch(
13805
14425
  this: Server,
13806
- request: Errorlike
13807
- ) => Response | Promise<Response> | undefined | Promise<undefined>;
14426
+ request: Request,
14427
+ server: Server
14428
+ ): Response | undefined | Promise<Response | undefined>;
13808
14429
  }
13809
14430
 
13810
14431
  export interface Errorlike extends Error {
@@ -13840,7 +14461,10 @@ declare module "bun" {
13840
14461
  certFile: string;
13841
14462
  }
13842
14463
 
13843
- export type SSLServeOptions = ServeOptions &
14464
+ export type SSLServeOptions<WebSocketDataType = undefined> = (
14465
+ | WebSocketServeOptions<WebSocketDataType>
14466
+ | ServerWebSocket
14467
+ ) &
13844
14468
  SSLOptions &
13845
14469
  SSLAdvancedOptions & {
13846
14470
  /**
@@ -13855,10 +14479,6 @@ declare module "bun" {
13855
14479
  *
13856
14480
  * To start the server, see {@link serve}
13857
14481
  *
13858
- * Often, you don't need to interact with this object directly. It exists to help you with the following tasks:
13859
- * - Stop the server
13860
- * - How many requests are currently being handled?
13861
- *
13862
14482
  * For performance, Bun pre-allocates most of the data for 2048 concurrent requests.
13863
14483
  * That means starting a new server allocates about 500 KB of memory. Try to
13864
14484
  * avoid starting and stopping the server often (unless it's a new instance of bun).
@@ -13866,7 +14486,7 @@ declare module "bun" {
13866
14486
  * Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you @alexhultman.
13867
14487
  *
13868
14488
  */
13869
- interface Server {
14489
+ export interface Server {
13870
14490
  /**
13871
14491
  * Stop listening to prevent new connections from being accepted.
13872
14492
  *
@@ -13876,16 +14496,129 @@ declare module "bun" {
13876
14496
  */
13877
14497
  stop(): void;
13878
14498
 
14499
+ /**
14500
+ * Update the `fetch` and `error` handlers without restarting the server.
14501
+ *
14502
+ * This is useful if you want to change the behavior of your server without
14503
+ * restarting it or for hot reloading.
14504
+ *
14505
+ * @example
14506
+ *
14507
+ * ```js
14508
+ * // create the server
14509
+ * const server = Bun.serve({
14510
+ * fetch(request) {
14511
+ * return new Response("Hello World v1")
14512
+ * }
14513
+ * });
14514
+ *
14515
+ * // Update the server to return a different response
14516
+ * server.update({
14517
+ * fetch(request) {
14518
+ * return new Response("Hello World v2")
14519
+ * }
14520
+ * });
14521
+ * ```
14522
+ *
14523
+ * Passing other options such as `port` or `hostname` won't do anything.
14524
+ */
14525
+ reload(options: Serve): void;
14526
+
14527
+ /**
14528
+ * Mock the fetch handler for a running server.
14529
+ *
14530
+ * This feature is not fully implemented yet. It doesn't normalize URLs
14531
+ * consistently in all cases and it doesn't yet call the `error` handler
14532
+ * consistently. This needs to be fixed
14533
+ */
14534
+ fetch(request: Request): Response | Promise<Response>;
14535
+
14536
+ /**
14537
+ * Upgrade a {@link Request} to a {@link ServerWebSocket}
14538
+ *
14539
+ * @param request The {@link Request} to upgrade
14540
+ * @param options Pass headers or attach data to the {@link ServerWebSocket}
14541
+ *
14542
+ * @returns `true` if the upgrade was successful and `false` if it failed
14543
+ *
14544
+ * @example
14545
+ * ```js
14546
+ * import { serve, websocket } from "bun";
14547
+ * serve({
14548
+ * websocket: websocket({
14549
+ * open: (ws) => {
14550
+ * console.log("Client connected");
14551
+ * },
14552
+ * message: (ws, message) => {
14553
+ * console.log("Client sent message", message);
14554
+ * },
14555
+ * close: (ws) => {
14556
+ * console.log("Client disconnected");
14557
+ * },
14558
+ * }),
14559
+ * fetch(req, server) {
14560
+ * if (req.url === "/chat") {
14561
+ * const upgraded = server.upgrade(req);
14562
+ * if (!upgraded) {
14563
+ * return new Response("Upgrade failed", { status: 400 });
14564
+ * }
14565
+ * }
14566
+ * return new Response("Hello World");
14567
+ * },
14568
+ * });
14569
+ * ```
14570
+ * What you pass to `data` is available on the {@link ServerWebSocket.data} property
14571
+ *
14572
+ */
14573
+ upgrade<T = undefined>(
14574
+ request: Request,
14575
+ options?: {
14576
+ /**
14577
+ * Send any additional headers while upgrading, like cookies
14578
+ */
14579
+ headers?: HeadersInit;
14580
+ /**
14581
+ * This value is passed to the {@link ServerWebSocket.data} property
14582
+ */
14583
+ data?: T;
14584
+ }
14585
+ ): boolean;
14586
+
13879
14587
  /**
13880
14588
  * How many requests are in-flight right now?
13881
14589
  */
13882
14590
  readonly pendingRequests: number;
14591
+
14592
+ /**
14593
+ * How many {@link ServerWebSocket}s are in-flight right now?
14594
+ */
14595
+ readonly pendingWebSockets: number;
14596
+
13883
14597
  readonly port: number;
14598
+ /**
14599
+ * The hostname the server is listening on. Does not include the port
14600
+ * @example
14601
+ * ```js
14602
+ * "localhost"
14603
+ * ```
14604
+ */
13884
14605
  readonly hostname: string;
14606
+ /**
14607
+ * Is the server running in development mode?
14608
+ *
14609
+ * In development mode, `Bun.serve()` returns rendered error messages with
14610
+ * stack traces instead of a generic 500 error. This makes debugging easier,
14611
+ * but development mode shouldn't be used in production or you will risk
14612
+ * leaking sensitive information.
14613
+ *
14614
+ */
13885
14615
  readonly development: boolean;
13886
14616
  }
13887
14617
 
13888
- export type Serve = SSLServeOptions | ServeOptions;
14618
+ export type Serve<WebSocketDataType = undefined> =
14619
+ | SSLServeOptions<WebSocketDataType>
14620
+ | WebSocketServeOptions<WebSocketDataType>
14621
+ | ServeOptions;
13889
14622
 
13890
14623
  /**
13891
14624
  * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
@@ -14653,6 +15386,271 @@ declare module "bun" {
14653
15386
  }
14654
15387
 
14655
15388
  var plugin: BunPlugin;
15389
+
15390
+ declare namespace SpawnOptions {
15391
+ type Readable =
15392
+ | "inherit"
15393
+ | "pipe"
15394
+ | null
15395
+ | undefined
15396
+ | FileBlob
15397
+ | ArrayBufferView
15398
+ | number;
15399
+
15400
+ type Writable =
15401
+ | "inherit"
15402
+ | "pipe"
15403
+ | null
15404
+ | undefined
15405
+ | FileBlob
15406
+ | ArrayBufferView
15407
+ | Blob
15408
+ | number
15409
+ | Response
15410
+ | Request;
15411
+
15412
+ interface OptionsObject {
15413
+ /**
15414
+ * The current working directory of the process
15415
+ *
15416
+ * Defaults to `process.cwd()`
15417
+ */
15418
+ cwd?: string;
15419
+
15420
+ /**
15421
+ * The environment variables of the process
15422
+ *
15423
+ * Defaults to `process.env` as it was when the current Bun process launched.
15424
+ *
15425
+ * Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly.
15426
+ *
15427
+ */
15428
+ env?: Record<string, string>;
15429
+
15430
+ /**
15431
+ * The standard file descriptors of the process
15432
+ * - `inherit`: The process will inherit the standard input of the current process
15433
+ * - `pipe`: The process will have a new pipe for standard input
15434
+ * - `null`: The process will have no standard input
15435
+ * - `ArrayBufferView`, `Blob`: The process will read from the buffer
15436
+ * - `number`: The process will read from the file descriptor
15437
+ * - `undefined`: The default value
15438
+ */
15439
+ stdio?: [
15440
+ SpawnOptions.Writable,
15441
+ SpawnOptions.Readable,
15442
+ SpawnOptions.Readable
15443
+ ];
15444
+ stdin?: SpawnOptions.Writable;
15445
+ stdout?: SpawnOptions.Readable;
15446
+ stderr?: SpawnOptions.Readable;
15447
+
15448
+ /**
15449
+ * Callback that runs when the {@link Subprocess} exits
15450
+ *
15451
+ * You can also do `await subprocess.exited` to wait for the process to exit.
15452
+ *
15453
+ * @example
15454
+ *
15455
+ * ```ts
15456
+ * const subprocess = spawn({
15457
+ * cmd: ["echo", "hello"],
15458
+ * onExit: (code) => {
15459
+ * console.log(`Process exited with code ${code}`);
15460
+ * },
15461
+ * });
15462
+ * ```
15463
+ */
15464
+ onExit?: (exitCode: number) => void | Promise<void>;
15465
+ }
15466
+ }
15467
+
15468
+ interface Subprocess {
15469
+ readonly stdin: undefined | number | FileSink;
15470
+ readonly stdout: undefined | number | ReadableStream;
15471
+ readonly stderr: undefined | number | ReadableStream;
15472
+
15473
+ /**
15474
+ * This returns the same value as {@link Subprocess.stdout}
15475
+ *
15476
+ * It exists for compatibility with {@link ReadableStream.pipeThrough}
15477
+ */
15478
+ readonly readable: undefined | number | ReadableStream;
15479
+
15480
+ /**
15481
+ * The process ID of the child process
15482
+ * @example
15483
+ * ```ts
15484
+ * const { pid } = Bun.spawn({ cmd: ["echo", "hello"] });
15485
+ * console.log(pid); // 1234
15486
+ * ```
15487
+ */
15488
+ readonly pid: number;
15489
+ /**
15490
+ * The exit code of the process
15491
+ *
15492
+ * The promise will resolve when the process exits
15493
+ */
15494
+ readonly exited: Promise<number>;
15495
+
15496
+ /**
15497
+ * Has the process exited?
15498
+ */
15499
+ readonly killed: boolean;
15500
+
15501
+ /**
15502
+ * Kill the process
15503
+ * @param exitCode The exitCode to send to the process
15504
+ */
15505
+ kill(exitCode?: number): void;
15506
+
15507
+ /**
15508
+ * This method will tell Bun to wait for this process to exit after you already
15509
+ * called `unref()`.
15510
+ *
15511
+ * Before shutting down, Bun will wait for all subprocesses to exit by default
15512
+ */
15513
+ ref(): void;
15514
+
15515
+ /**
15516
+ * Before shutting down, Bun will wait for all subprocesses to exit by default
15517
+ *
15518
+ * This method will tell Bun to not wait for this process to exit before shutting down.
15519
+ */
15520
+ unref(): void;
15521
+ }
15522
+
15523
+ interface SyncSubprocess {
15524
+ stdout?: Buffer;
15525
+ stderr?: Buffer;
15526
+ exitCode: number;
15527
+ success: boolean;
15528
+ }
15529
+
15530
+ /**
15531
+ * Spawn a new process
15532
+ *
15533
+ * ```js
15534
+ * const subprocess = Bun.spawn({
15535
+ * cmd: ["echo", "hello"],
15536
+ * stdout: "pipe",
15537
+ * });
15538
+ * const text = await readableStreamToText(subprocess.stdout);
15539
+ * console.log(text); // "hello\n"
15540
+ * ```
15541
+ *
15542
+ * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html)
15543
+ */
15544
+ function spawn(
15545
+ options: SpawnOptions.OptionsObject & {
15546
+ /**
15547
+ * The command to run
15548
+ *
15549
+ * The first argument will be resolved to an absolute executable path. It must be a file, not a directory.
15550
+ *
15551
+ * If you explicitly set `PATH` in `env`, that `PATH` will be used to resolve the executable instead of the default `PATH`.
15552
+ *
15553
+ * To check if the command exists before running it, use `Bun.which(bin)`.
15554
+ *
15555
+ */
15556
+ cmd: [string, ...string[]];
15557
+ }
15558
+ ): Subprocess;
15559
+
15560
+ /**
15561
+ * Spawn a new process
15562
+ *
15563
+ * ```js
15564
+ * const {stdout} = Bun.spawn(["echo", "hello"]));
15565
+ * const text = await readableStreamToText(stdout);
15566
+ * console.log(text); // "hello\n"
15567
+ * ```
15568
+ *
15569
+ * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html)
15570
+ */
15571
+ function spawn(
15572
+ /**
15573
+ * The command to run
15574
+ * @example
15575
+ * ```ts
15576
+ * const subprocess = Bun.spawn(["echo", "hello"]);
15577
+ */
15578
+ cmds: [
15579
+ /** One command is required */
15580
+ string,
15581
+ /** Additional arguments */
15582
+ ...string[]
15583
+ ],
15584
+ options?: SpawnOptions.OptionsObject
15585
+ ): Subprocess;
15586
+
15587
+ /**
15588
+ * Spawn a new process
15589
+ *
15590
+ * ```js
15591
+ * const {stdout} = Bun.spawnSync({
15592
+ * cmd: ["echo", "hello"],
15593
+ * });
15594
+ * console.log(stdout.toString()); // "hello\n"
15595
+ * ```
15596
+ *
15597
+ * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html)
15598
+ */
15599
+ function spawnSync(
15600
+ options: SpawnOptions.OptionsObject & {
15601
+ /**
15602
+ * The command to run
15603
+ *
15604
+ * The first argument will be resolved to an absolute executable path. It must be a file, not a directory.
15605
+ *
15606
+ * If you explicitly set `PATH` in `env`, that `PATH` will be used to resolve the executable instead of the default `PATH`.
15607
+ *
15608
+ * To check if the command exists before running it, use `Bun.which(bin)`.
15609
+ *
15610
+ */
15611
+ cmd: [string, ...string[]];
15612
+ }
15613
+ ): SyncSubprocess;
15614
+
15615
+ /**
15616
+ * Synchronously spawn a new process
15617
+ *
15618
+ * ```js
15619
+ * const {stdout} = Bun.spawnSync(["echo", "hello"]));
15620
+ * console.log(stdout.toString()); // "hello\n"
15621
+ * ```
15622
+ *
15623
+ * Internally, this uses [posix_spawn(2)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/posix_spawn.2.html)
15624
+ */
15625
+ function spawnSync(
15626
+ /**
15627
+ * The command to run
15628
+ * @example
15629
+ * ```ts
15630
+ * const subprocess = Bun.spawn(["echo", "hello"]);
15631
+ */
15632
+ cmds: [
15633
+ /** One command is required */
15634
+ string,
15635
+ /** Additional arguments */
15636
+ ...string[]
15637
+ ],
15638
+ options?: SpawnOptions.OptionsObject
15639
+ ): SyncSubprocess;
15640
+
15641
+ /**
15642
+ * The current version of Bun
15643
+ * @example
15644
+ * "0.2.0"
15645
+ */
15646
+ export const version: string;
15647
+
15648
+ /**
15649
+ * The git sha at the time the currently-running version of Bun was compiled
15650
+ * @example
15651
+ * "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
15652
+ */
15653
+ export const revision: string;
14656
15654
  }
14657
15655
 
14658
15656
  type TypedArray =