wrangler 0.0.0-e1c615f → 0.0.0-e6733a3

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.
@@ -1,430 +0,0 @@
1
- import { Response, Request, Headers } from "node-fetch";
2
- import type { MessageEvent } from "ws";
3
- import WebSocket, { WebSocketServer } from "ws";
4
- import type { IncomingMessage, ServerResponse } from "http";
5
- import { createServer } from "http";
6
-
7
- /**
8
- * A call frame.
9
- *
10
- * @link https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-CallFrame
11
- */
12
- export interface DtCallFrame {
13
- /**
14
- * The module path.
15
- *
16
- * @example
17
- * 'worker.js'
18
- */
19
- url: string;
20
- /**
21
- * The function name.
22
- */
23
- functionName?: string;
24
- /**
25
- * The line number. (0-based)
26
- */
27
- lineNumber: number;
28
- /**
29
- * The column number. (0-based)
30
- */
31
- columnNumber: number;
32
- }
33
-
34
- /**
35
- * A stack trace.
36
- *
37
- * @link https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-StackTrace
38
- */
39
- export interface DtStackTrace {
40
- /**
41
- * A description of the stack, only present in certain contexts.
42
- */
43
- description?: string;
44
- /**
45
- * The call frames.
46
- */
47
- callFrames: DtCallFrame[];
48
- /**
49
- * The parent stack trace.
50
- */
51
- parent?: DtStackTrace;
52
- }
53
-
54
- /**
55
- * A JavaScript object type.
56
- */
57
- export type DtRemoteObjectType =
58
- | "object"
59
- | "function"
60
- | "undefined"
61
- | "string"
62
- | "number"
63
- | "boolean"
64
- | "symbol"
65
- | "bigint";
66
-
67
- /**
68
- * A view of a remote JavaScript object.
69
- *
70
- * @link https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-RemoteObject
71
- */
72
- export interface DtRemoteObject<T> {
73
- /**
74
- * The object type.
75
- *
76
- * @example
77
- * 'string'
78
- */
79
- type: DtRemoteObjectType;
80
- /**
81
- * The specific object type, if the type is `object`.
82
- *
83
- * @example
84
- * 'arraybuffer'
85
- */
86
- subtype?: string;
87
- /**
88
- * The class name, if the type if `object`.
89
- */
90
- className?: string;
91
- /**
92
- * The object as a string.
93
- *
94
- * @example
95
- * 'Array(1)'
96
- * 'TypeError: Oops!\n at worker.js:5:15'
97
- */
98
- description?: string;
99
- /**
100
- * The object.
101
- */
102
- value?: T;
103
- // TODO(soon): add a preview field for more complex types
104
- }
105
-
106
- /**
107
- * An event when `console.log()` is invoked.
108
- *
109
- * @link https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#event-consoleAPICalled
110
- */
111
- export interface DtLogEvent {
112
- timestamp: number;
113
- type: string;
114
- args: DtRemoteObject<unknown>[];
115
- stackTrace?: DtStackTrace;
116
- }
117
-
118
- /**
119
- * An event when an uncaught `Error` is thrown.
120
- *
121
- * @link https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#event-exceptionThrown
122
- */
123
- export interface DtExceptionEvent {
124
- timestamp: number;
125
- exceptionDetails: {
126
- lineNumber: number;
127
- columnNumber: number;
128
- exception: DtRemoteObject<Error>;
129
- stackTrace: DtStackTrace;
130
- };
131
- }
132
-
133
- /**
134
- * A DevTools event.
135
- */
136
- export type DtEvent = DtLogEvent | DtExceptionEvent;
137
-
138
- /**
139
- * A listener that receives DevTools events.
140
- */
141
- export type DtListener = (event: DtEvent) => void;
142
-
143
- /**
144
- * A DevTools inspector that listens to logs and debug events from a Worker.
145
- *
146
- * @example
147
- * const worker: CfWorker
148
- * const inspector: DtInspector = await worker.inspect()
149
- *
150
- * @link https://chromedevtools.github.io/devtools-protocol/
151
- */
152
- export class DtInspector {
153
- #webSocket: WebSocket;
154
- #keepAlive?: NodeJS.Timer;
155
-
156
- constructor(url: string) {
157
- // this.#events = [];
158
- // this.#listeners = [];
159
- this.#webSocket = new WebSocket(url);
160
- this.#webSocket.onopen = () => {
161
- this.enable();
162
- };
163
- this.#webSocket.onclose = () => {
164
- this.disable();
165
- };
166
- this.#webSocket.on("unexpected-response", () => {
167
- console.log("504??"); // TODO: refactor this class to start again
168
- });
169
- this.#webSocket.onmessage = (event: MessageEvent) => {
170
- // TODO: this seems unnecessary, unless we're planning
171
- // on logging to console. We'll see.
172
- if (typeof event.data === "string") {
173
- // this.recv(JSON.parse(event.data));
174
- } else {
175
- // ??
176
- }
177
- };
178
- }
179
-
180
- /**
181
- * Exposes a websocket proxy on a localhost port.
182
- */
183
- proxyTo(port: number): AbortController {
184
- return bind(new DtInspectorBridge(this.#webSocket, port), port);
185
- }
186
-
187
- /**
188
- * If the inspector is closed.
189
- */
190
- get closed(): boolean {
191
- return this.#webSocket.readyState === WebSocket.CLOSED;
192
- }
193
-
194
- /**
195
- * Closes the inspector.
196
- */
197
- close(): void {
198
- if (!this.closed) {
199
- try {
200
- this.#webSocket.close();
201
- } catch (err) {
202
- // Closing before the websocket is ready will throw an error.
203
- }
204
- }
205
- // this.#events = [];
206
- }
207
-
208
- private send(event: Record<string, unknown>): void {
209
- if (!this.closed) {
210
- this.#webSocket.send(JSON.stringify(event));
211
- }
212
- }
213
-
214
- private enable(): void {
215
- let id = 1;
216
- this.send({ method: "Runtime.enable", id });
217
- this.#keepAlive = setInterval(() => {
218
- this.send({ method: "Runtime.getIsolateId", id: id++ });
219
- }, 10_000);
220
- }
221
-
222
- private disable(): void {
223
- if (this.#keepAlive) {
224
- clearInterval(this.#keepAlive);
225
- this.#keepAlive = undefined;
226
- }
227
- }
228
- }
229
-
230
- /**
231
- * A HTTP server that responds to `fetch()` requests.
232
- */
233
- interface FetchServer {
234
- /**
235
- * Responds to a request.
236
- */
237
- fetch(request: Request): Promise<Response>;
238
- /**
239
- * Accepts a websocket connection.
240
- */
241
- upgrade?(webSocket: WebSocket): void;
242
- }
243
-
244
- /**
245
- * A bridge between a remote DevTools inspector and Chrome.
246
- *
247
- * Exposes a localhost HTTP server that responds to informational requests
248
- * from Chrome about the DevTools inspector. Then, when it receives a
249
- * WebSocket upgrade, forwards the connection to the remote inspector.
250
- */
251
- class DtInspectorBridge implements FetchServer {
252
- #webSocket: WebSocket;
253
- #localPort: number;
254
- #connected: boolean;
255
-
256
- constructor(webSocket: WebSocket, localPort?: number) {
257
- this.#webSocket = webSocket;
258
- this.#localPort = localPort;
259
- this.#connected = false;
260
- }
261
-
262
- async fetch(request: Request): Promise<Response> {
263
- const { url } = request;
264
- const { pathname } = new URL(url);
265
- switch (pathname) {
266
- case "/json/version":
267
- return this.version;
268
- case "/json":
269
- case "/json/list":
270
- return this.location;
271
- default:
272
- break;
273
- }
274
- return new Response("Not Found", { status: 404 });
275
- }
276
-
277
- upgrade(webSocket: WebSocket): void {
278
- if (this.#connected) {
279
- webSocket.close(
280
- 1013,
281
- "Too many clients; only one can be connected at a time"
282
- );
283
- } else {
284
- this.#connected = true;
285
- webSocket.addEventListener("close", () => (this.#connected = false));
286
- proxyWebSocket(webSocket, this.#webSocket);
287
- }
288
- }
289
-
290
- private get version(): Response {
291
- const headers = { "Content-Type": "application/json" };
292
- const body = {
293
- Browser: "workers-run/v0.0.0", // TODO: this should pick up version from package.json
294
- // TODO: (someday): The DevTools protocol should match that of edgeworker.
295
- // This could be exposed by the preview API.
296
- "Protocol-Version": "1.3",
297
- };
298
- return new Response(JSON.stringify(body), { headers });
299
- }
300
-
301
- private get location(): Response {
302
- const headers = { "Content-Type": "application/json" };
303
- const localHost = `localhost:${this.#localPort}/ws`;
304
- const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
305
- const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
306
- const body = [
307
- {
308
- id: randomId(),
309
- type: "node",
310
- description: "workers",
311
- webSocketDebuggerUrl: `ws://${localHost}`,
312
- devtoolsFrontendUrl,
313
- devtoolsFrontendUrlCompat,
314
- // Below are fields that are visible in the DevTools UI.
315
- title: "Cloudflare Worker",
316
- faviconUrl: "https://workers.cloudflare.com/favicon.ico",
317
- url: "https://" + new URL(this.#webSocket.url).host,
318
- },
319
- ];
320
- return new Response(JSON.stringify(body), { headers });
321
- }
322
- }
323
-
324
- function bind(fetcher: FetchServer, port?: number): AbortController {
325
- const controller = new AbortController();
326
-
327
- const server = createServer(
328
- (input: IncomingMessage, output: ServerResponse) =>
329
- toRequest(input)
330
- .then((request) => fetcher.fetch(request))
331
- .then((response) => toResponse(response, output))
332
- .catch((error) => console.error(error))
333
- );
334
-
335
- if (fetcher.upgrade) {
336
- const webSocket = new WebSocketServer({ server });
337
- webSocket.on("connection", (ws: WebSocket) => fetcher.upgrade(ws));
338
- }
339
-
340
- const socket = server.listen({ port });
341
- controller.signal.onabort = () => {
342
- server.close();
343
- socket.close();
344
- };
345
- return controller;
346
- }
347
-
348
- /**
349
- * Converts a Node.js request to a Web standard `Request`.
350
- */
351
- async function toRequest(request: IncomingMessage): Promise<Request> {
352
- const host = request.headers.host ?? "localhost";
353
- const { href } = new URL(request.url, "http://" + host);
354
-
355
- const { rawHeaders, method } = request;
356
- const headers = new Headers();
357
- for (let i = 0; i < rawHeaders.length; i += 2) {
358
- headers.append(rawHeaders[i], rawHeaders[i + 1]);
359
- }
360
-
361
- return new Promise((resolve, reject) => {
362
- const chunks = [];
363
- request.on("data", (chunk) => chunks.push(chunk));
364
- request.on("error", (error) => reject(error));
365
- request.on("end", () => {
366
- const buffer = Buffer.concat(chunks);
367
- const body = buffer.length === 0 ? undefined : buffer;
368
- resolve(new Request(href, { method, headers, body }));
369
- });
370
- });
371
- }
372
-
373
- /**
374
- * Converts a Web standard `Response` into a Node.js response.
375
- */
376
- async function toResponse(
377
- input: Response,
378
- response: ServerResponse
379
- ): Promise<void> {
380
- const { status, statusText, headers, body: hasBody } = input;
381
-
382
- for (const [name, value] of headers.entries()) {
383
- response.setHeader(name, value);
384
- }
385
-
386
- let body: Uint8Array;
387
- if (hasBody) {
388
- body = new Uint8Array(await input.arrayBuffer());
389
- response.setHeader("Content-Length", body.byteLength);
390
- }
391
-
392
- response.writeHead(status, statusText);
393
- response.write(body);
394
- }
395
-
396
- /**
397
- * Creates a proxy bridge between two websockets.
398
- */
399
- function proxyWebSocket(webSocket: WebSocket, otherSocket: WebSocket): void {
400
- webSocket.addEventListener("message", (event: MessageEvent) => {
401
- try {
402
- otherSocket.send(event.data);
403
- } catch (e) {
404
- if (e.message !== "WebSocket is not open: readyState 0 (CONNECTING)") {
405
- // this just means we haven't opened a websocket yet
406
- // usually happens until there's at least one request
407
- // which is weird, because we may miss something that happens on
408
- // the first request
409
- console.error(e);
410
- }
411
- }
412
- });
413
- otherSocket.addEventListener("message", (event: MessageEvent) =>
414
- webSocket.send(event.data)
415
- );
416
-
417
- // Some close codes are marked as 'reserved' and will throw an error if used.
418
- // Therefore, it's not worth the effort to passthrough the close code and reason.
419
- webSocket.addEventListener("close", () => otherSocket.close());
420
- otherSocket.addEventListener("close", () => webSocket.close());
421
- }
422
-
423
- // Credit: https://stackoverflow.com/a/2117523
424
- function randomId(): string {
425
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
426
- const r = (Math.random() * 16) | 0,
427
- v = c == "x" ? r : (r & 0x3) | 0x8;
428
- return v.toString(16);
429
- });
430
- }