wrangler 0.0.0-e88a54e → 0.0.0-e89ee2a5

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 (174) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +168 -86
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +167 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +3 -3
  31. package/templates/new-worker.ts +22 -4
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +6 -103
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23948 -0
  48. package/wrangler-dist/cli.js +164439 -134006
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -79
  55. package/miniflare-dist/index.mjs.map +0 -7
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -223
  58. package/pages/functions/filepath-routing.ts +0 -181
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -151
  61. package/pages/functions/template-worker.ts +0 -130
  62. package/src/__tests__/configuration.test.ts +0 -2796
  63. package/src/__tests__/dev.test.tsx +0 -496
  64. package/src/__tests__/dev2.test.tsx +0 -154
  65. package/src/__tests__/guess-worker-format.test.ts +0 -58
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  72. package/src/__tests__/helpers/mock-console.ts +0 -70
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  76. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  77. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  78. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  79. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  80. package/src/__tests__/https-options.test.ts +0 -127
  81. package/src/__tests__/index.test.ts +0 -991
  82. package/src/__tests__/jest.setup.ts +0 -69
  83. package/src/__tests__/kv.test.ts +0 -1382
  84. package/src/__tests__/logout.test.ts +0 -52
  85. package/src/__tests__/package-manager.test.ts +0 -206
  86. package/src/__tests__/pages.test.ts +0 -44
  87. package/src/__tests__/parse.test.ts +0 -322
  88. package/src/__tests__/publish.test.ts +0 -2704
  89. package/src/__tests__/r2.test.ts +0 -198
  90. package/src/__tests__/route.test.ts +0 -45
  91. package/src/__tests__/secret.test.ts +0 -425
  92. package/src/__tests__/sentry.test.ts +0 -146
  93. package/src/__tests__/tail.test.ts +0 -564
  94. package/src/__tests__/whoami.test.tsx +0 -100
  95. package/src/bundle.ts +0 -142
  96. package/src/cfetch/index.ts +0 -104
  97. package/src/cfetch/internal.ts +0 -139
  98. package/src/cli.ts +0 -19
  99. package/src/config/README.md +0 -107
  100. package/src/config/config.ts +0 -218
  101. package/src/config/diagnostics.ts +0 -80
  102. package/src/config/environment.ts +0 -366
  103. package/src/config/index.ts +0 -62
  104. package/src/config/validation-helpers.ts +0 -486
  105. package/src/config/validation.ts +0 -1090
  106. package/src/create-worker-preview.ts +0 -166
  107. package/src/create-worker-upload-form.ts +0 -217
  108. package/src/dev/dev.tsx +0 -364
  109. package/src/dev/local.tsx +0 -232
  110. package/src/dev/remote.tsx +0 -203
  111. package/src/dev/use-esbuild.ts +0 -100
  112. package/src/dialogs.tsx +0 -77
  113. package/src/entry.ts +0 -208
  114. package/src/environment-variables.ts +0 -33
  115. package/src/https-options.ts +0 -122
  116. package/src/index.tsx +0 -2373
  117. package/src/inspect.ts +0 -617
  118. package/src/kv.ts +0 -319
  119. package/src/miniflare-cli/README.md +0 -30
  120. package/src/miniflare-cli/enum-keys.ts +0 -17
  121. package/src/miniflare-cli/index.ts +0 -37
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -25
  124. package/src/package-manager.ts +0 -126
  125. package/src/pages.tsx +0 -1047
  126. package/src/parse.ts +0 -183
  127. package/src/paths.ts +0 -26
  128. package/src/proxy.ts +0 -440
  129. package/src/publish.ts +0 -347
  130. package/src/r2.ts +0 -50
  131. package/src/reporting.ts +0 -131
  132. package/src/selfsigned.d.ts +0 -29
  133. package/src/sites.tsx +0 -280
  134. package/src/tail/filters.ts +0 -279
  135. package/src/tail/index.ts +0 -299
  136. package/src/tail/printing.ts +0 -62
  137. package/src/user.tsx +0 -1118
  138. package/src/whoami.tsx +0 -69
  139. package/src/worker.ts +0 -163
  140. package/templates/static-asset-facade.js +0 -47
  141. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  143. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  144. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  146. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  148. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  156. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  157. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  158. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  159. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  162. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  163. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  164. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  165. package/vendor/wrangler-mime/LICENSE +0 -21
  166. package/vendor/wrangler-mime/Mime.js +0 -97
  167. package/vendor/wrangler-mime/README.md +0 -187
  168. package/vendor/wrangler-mime/cli.js +0 -46
  169. package/vendor/wrangler-mime/index.js +0 -4
  170. package/vendor/wrangler-mime/lite.js +0 -4
  171. package/vendor/wrangler-mime/package.json +0 -52
  172. package/vendor/wrangler-mime/types/other.js +0 -1
  173. package/vendor/wrangler-mime/types/standard.js +0 -1
  174. package/wrangler-dist/cli.js.map +0 -7
package/src/inspect.ts DELETED
@@ -1,617 +0,0 @@
1
- import assert from "node:assert";
2
- import { createServer } from "node:http";
3
- import { URL } from "node:url";
4
-
5
- import { useEffect, useRef, useState } from "react";
6
- import WebSocket, { WebSocketServer } from "ws";
7
- import { version } from "../package.json";
8
- import { waitForPortToBeAvailable } from "./proxy";
9
- import type Protocol from "devtools-protocol";
10
- import type { IncomingMessage, Server, ServerResponse } from "node:http";
11
- import type { MessageEvent } from "ws";
12
-
13
- /**
14
- * `useInspector` is a hook for debugging Workers applications
15
- * when using `wrangler dev`.
16
- *
17
- * When we start a session with `wrangler dev`, the Workers platform
18
- * also exposes a debugging websocket that implements the DevTools
19
- * Protocol. While we could just start up DevTools and connect to this
20
- * URL, that URL changes every time we make a change to the
21
- * worker, or when the session expires. Instead, we start up a proxy
22
- * server locally that acts as a bridge between the remote DevTools
23
- * server and the local DevTools instance. So whenever the URL changes,
24
- * we can can silently connect to it and keep the local DevTools instance
25
- * up to date. Further, we also intercept these messages and selectively
26
- * log them directly to the terminal (namely, calls to `console.<x>`,
27
- * and exceptions)
28
- */
29
-
30
- /**
31
- * TODO:
32
- * - clear devtools whenever we save changes to the worker
33
- * - clear devtools when we switch between local/remote modes
34
- * - handle more methods from console
35
- */
36
-
37
- interface InspectorProps {
38
- /**
39
- * The port that the local proxy server should listen on.
40
- */
41
- port: number;
42
- /**
43
- * The websocket URL exposed by Workers that the inspector should connect to.
44
- */
45
- inspectorUrl: undefined | string;
46
- /**
47
- * Whether console statements and exceptions should be logged to the terminal.
48
- * (We don't log them in local mode because they're already getting
49
- * logged to the terminal by nature of them actually running in node locally.)
50
- */
51
- logToTerminal: boolean;
52
- }
53
-
54
- export default function useInspector(props: InspectorProps) {
55
- /** A unique ID for this session. */
56
- const inspectorIdRef = useRef(randomId());
57
-
58
- /** The websocket from the devtools instance. */
59
- const [localWebSocket, setLocalWebSocket] = useState<WebSocket>();
60
- /** The websocket from the edge */
61
- const [remoteWebSocket, setRemoteWebSocket] = useState<WebSocket>();
62
-
63
- /**
64
- * The local proxy server that acts as the bridge between
65
- * the remote websocket and the local DevTools instance.
66
- */
67
- const serverRef = useRef<Server>();
68
- if (serverRef.current === undefined) {
69
- serverRef.current = createServer(
70
- (req: IncomingMessage, res: ServerResponse) => {
71
- switch (req.url) {
72
- // We implement a couple of well known end points
73
- // that are queried for metadata by chrome://inspect
74
- case "/json/version":
75
- res.setHeader("Content-Type", "application/json");
76
- res.end(
77
- JSON.stringify({
78
- Browser: `wrangler/v${version}`,
79
- // TODO: (someday): The DevTools protocol should match that of Edge Worker.
80
- // This could be exposed by the preview API.
81
- "Protocol-Version": "1.3",
82
- })
83
- );
84
- return;
85
- case "/json":
86
- case "/json/list":
87
- {
88
- res.setHeader("Content-Type", "application/json");
89
- const localHost = `localhost:${props.port}/ws`;
90
- const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
91
- const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
92
- res.end(
93
- JSON.stringify([
94
- {
95
- id: inspectorIdRef.current,
96
- type: "node",
97
- description: "workers",
98
- webSocketDebuggerUrl: `ws://${localHost}`,
99
- devtoolsFrontendUrl,
100
- devtoolsFrontendUrlCompat,
101
- // Below are fields that are visible in the DevTools UI.
102
- title: "Cloudflare Worker",
103
- faviconUrl: "https://workers.cloudflare.com/favicon.ico",
104
- url:
105
- "https://" +
106
- (remoteWebSocket
107
- ? new URL(remoteWebSocket.url).host
108
- : "workers.dev"),
109
- },
110
- ])
111
- );
112
- }
113
- return;
114
- default:
115
- break;
116
- }
117
- }
118
- );
119
- }
120
- const server = serverRef.current;
121
-
122
- /**
123
- * The websocket server that runs on top of the proxy server.
124
- */
125
- const wsServerRef = useRef<WebSocketServer>();
126
- if (wsServerRef.current === undefined) {
127
- wsServerRef.current = new WebSocketServer({
128
- server,
129
- clientTracking: true,
130
- });
131
- }
132
- const wsServer = wsServerRef.current;
133
-
134
- wsServer.on("connection", (ws: WebSocket) => {
135
- if (wsServer.clients.size > 1) {
136
- /** We only want to have one active Devtools instance at a time. */
137
- console.error(
138
- "Tried to open a new devtools window when a previous one was already open."
139
- );
140
- ws.close(1013, "Too many clients; only one can be connected at a time");
141
- } else {
142
- // As promised, save the created websocket in a state hook
143
- setLocalWebSocket(ws);
144
-
145
- ws.addEventListener("close", () => {
146
- // And and cleanup when devtools closes
147
- setLocalWebSocket(undefined);
148
- });
149
- }
150
- });
151
-
152
- /**
153
- * We start and stop the server in an effect to take advantage
154
- * of the component lifecycle. Convenient.
155
- */
156
- useEffect(() => {
157
- async function startInspectorProxy() {
158
- await waitForPortToBeAvailable(props.port, {
159
- retryPeriod: 200,
160
- timeout: 2000,
161
- });
162
- server.listen(props.port);
163
- }
164
- startInspectorProxy().catch((err) => console.error(err));
165
- return () => {
166
- server.close();
167
- // Also disconnect any open websockets/devtools connections
168
- wsServer.clients.forEach((ws) => ws.close());
169
- wsServer.close();
170
- };
171
- }, [props.port, server, wsServer]);
172
-
173
- /**
174
- * When connecting to the remote websocket, if we don't start either
175
- * the devtools instance or make an actual request to the worker in time,
176
- * then the connecting process can error out. When this happens, we
177
- * want to simply retry the connection. We use a state hook to trigger retries
178
- * of the effect that connects to the remote websocket.
179
- */
180
- const [
181
- retryRemoteWebSocketConnectionSigil,
182
- setRetryRemoteWebSocketConnectionSigil,
183
- ] = useState<number>(0);
184
- function retryRemoteWebSocketConnection() {
185
- setRetryRemoteWebSocketConnectionSigil((x) => x + 1);
186
- }
187
-
188
- /** A simple incrementing id to attach to messages we send to devtools */
189
- const messageCounterRef = useRef(1);
190
-
191
- // This effect tracks the connection to the remote websocket
192
- // (stored in, no surprises here, `remoteWebSocket`)
193
- useEffect(() => {
194
- if (!props.inspectorUrl) {
195
- return;
196
- }
197
- // The actual websocket instance
198
- const ws = new WebSocket(props.inspectorUrl);
199
- setRemoteWebSocket(ws);
200
-
201
- /**
202
- * A handle to the interval we run to keep the websocket alive
203
- */
204
- let keepAliveInterval: NodeJS.Timer;
205
-
206
- /**
207
- * Test if the websocket is closed
208
- */
209
- function isClosed() {
210
- return (
211
- ws.readyState === WebSocket.CLOSED ||
212
- ws.readyState === WebSocket.CLOSING
213
- );
214
- }
215
-
216
- /**
217
- * Send a message to the remote websocket
218
- */
219
- function send(event: Record<string, unknown>): void {
220
- if (!isClosed()) {
221
- ws.send(JSON.stringify(event));
222
- }
223
- }
224
-
225
- /**
226
- * Closes the inspector.
227
- */
228
- function close(): void {
229
- if (!isClosed()) {
230
- try {
231
- ws.close();
232
- } catch (err) {
233
- // Closing before the websocket is ready will throw an error.
234
- }
235
- }
236
- }
237
-
238
- /**
239
- * Since we have a handle on the remote websocket, we can tap
240
- * into its events, and log any pertinent ones directly to
241
- * the terminal (which means you have insight into your worker
242
- * without having to open the devtools).
243
- */
244
- if (props.logToTerminal) {
245
- ws.addEventListener("message", (event: MessageEvent) => {
246
- if (typeof event.data === "string") {
247
- const evt = JSON.parse(event.data);
248
- if (evt.method === "Runtime.exceptionThrown") {
249
- const params = evt.params as Protocol.Runtime.ExceptionThrownEvent;
250
- console.error(
251
- "🚨", // cheesy, but it works
252
- // maybe we could use color here too.
253
- params.exceptionDetails.text,
254
- params.exceptionDetails.exception?.description ?? ""
255
- );
256
- }
257
- if (evt.method === "Runtime.consoleAPICalled") {
258
- logConsoleMessage(
259
- evt.params as Protocol.Runtime.ConsoleAPICalledEvent
260
- );
261
- }
262
- } else {
263
- // We should never get here, but who know is 2022...
264
- console.error("unrecognised devtools event:", event);
265
- }
266
- });
267
- }
268
-
269
- ws.addEventListener("open", () => {
270
- send({ method: "Runtime.enable", id: messageCounterRef.current });
271
- // TODO: This doesn't actually work. Must fix.
272
- send({ method: "Network.enable", id: messageCounterRef.current++ });
273
-
274
- keepAliveInterval = setInterval(() => {
275
- send({
276
- method: "Runtime.getIsolateId",
277
- id: messageCounterRef.current++,
278
- });
279
- }, 10_000);
280
- });
281
-
282
- ws.on("unexpected-response", () => {
283
- console.log("waiting for connection...");
284
- /**
285
- * This usually means the worker is not "ready" yet
286
- * so we'll just retry the connection process
287
- */
288
- retryRemoteWebSocketConnection();
289
- });
290
-
291
- ws.addEventListener("close", () => {
292
- clearInterval(keepAliveInterval);
293
- });
294
-
295
- return () => {
296
- // clean up! Let's first stop the heartbeat interval
297
- clearInterval(keepAliveInterval);
298
- // Then we'll send a message to the devtools instance to
299
- // tell it to clear the console.
300
- wsServer.clients.forEach((client) => {
301
- // We could've used `localSocket` here, but
302
- // then we would have had to add it to the effect
303
- // change detection array, which would have made a
304
- // bunch of other stuff complicated. So we'll just
305
- // cycle through all of the server's connected clients
306
- // (in practice, there should only be one or zero) and send
307
- // the Log.clear message.
308
- client.send(
309
- JSON.stringify({
310
- // TODO: This doesn't actually work. Must fix.
311
- method: "Log.clear",
312
- // we can disable the next eslint warning since
313
- // we're referencing a ref that stays alive
314
- // eslint-disable-next-line react-hooks/exhaustive-deps
315
- id: messageCounterRef.current++,
316
- params: {},
317
- })
318
- );
319
- });
320
- // Finally, we'll close the websocket
321
- close();
322
- // And we'll clear `remoteWebsocket`
323
- setRemoteWebSocket(undefined);
324
- };
325
- }, [
326
- props.inspectorUrl,
327
- props.logToTerminal,
328
- wsServer,
329
- // We use a state value as a sigil to trigger a retry of the
330
- // remote websocket connection. It's not used inside the effect,
331
- // so react-hooks/exhaustive-deps doesn't complain if it's not
332
- // included in the dependency array. But its presence is critical,
333
- // so do NOT remove it from the dependency list.
334
- retryRemoteWebSocketConnectionSigil,
335
- ]);
336
-
337
- /**
338
- * We want to make sure we don't lose any messages we receive from the
339
- * remote websocket before devtools connects. So we use a ref to buffer
340
- * messages, and flush them whenever devtools connects.
341
- */
342
- const messageBufferRef = useRef<MessageEvent[]>([]);
343
-
344
- // This effect tracks the state changes _between_ the local
345
- // and remote websockets, and handles how messages flow between them.
346
- useEffect(() => {
347
- /**
348
- * This event listener is used for buffering messages from
349
- * the remote websocket, and flushing them
350
- * when the local websocket connects.
351
- */
352
- function bufferMessageFromRemoteSocket(event: MessageEvent) {
353
- messageBufferRef.current.push(event);
354
- // TODO: maybe we should have a max limit on this?
355
- // if so, we should be careful when removing messages
356
- // from the front, because they could be critical for
357
- // devtools (like execution context creation, etc)
358
- }
359
-
360
- if (remoteWebSocket && !localWebSocket) {
361
- // The local websocket hasn't connected yet, so we'll
362
- // buffer messages until it does.
363
- remoteWebSocket.addEventListener(
364
- "message",
365
- bufferMessageFromRemoteSocket
366
- );
367
- }
368
-
369
- /** Send a message from the local websocket to the remote websocket */
370
- function sendMessageToRemoteWebSocket(event: MessageEvent) {
371
- try {
372
- assert(
373
- remoteWebSocket,
374
- "Trying to send a message to an undefined `remoteWebSocket`"
375
- );
376
- remoteWebSocket.send(event.data);
377
- } catch (e) {
378
- if (
379
- (e as Error).message !==
380
- "WebSocket is not open: readyState 0 (CONNECTING)"
381
- ) {
382
- /**
383
- * ^ this just means we haven't opened a websocket yet
384
- * usually happens until there's at least one request
385
- * which is weird, because we may miss something that
386
- * happens on the first request. Maybe we should buffer
387
- * these messages too?
388
- */
389
- console.error(e);
390
- }
391
- }
392
- }
393
-
394
- /** Send a message from the local websocket to the remote websocket */
395
- function sendMessageToLocalWebSocket(event: MessageEvent) {
396
- assert(
397
- localWebSocket,
398
- "Trying to send a message to an undefined `localWebSocket`"
399
- );
400
- localWebSocket.send(event.data);
401
- }
402
-
403
- if (localWebSocket && remoteWebSocket) {
404
- // Both the remote and local websockets are connected, so let's
405
- // start sending messages between them.
406
- localWebSocket.addEventListener("message", sendMessageToRemoteWebSocket);
407
- remoteWebSocket.addEventListener("message", sendMessageToLocalWebSocket);
408
-
409
- // Also, let's flush any buffered messages
410
- messageBufferRef.current.forEach(sendMessageToLocalWebSocket);
411
- messageBufferRef.current = [];
412
- }
413
-
414
- return () => {
415
- // Cleanup like good citizens
416
- if (remoteWebSocket) {
417
- remoteWebSocket.removeEventListener(
418
- "message",
419
- bufferMessageFromRemoteSocket
420
- );
421
- remoteWebSocket.removeEventListener(
422
- "message",
423
- sendMessageToLocalWebSocket
424
- );
425
- }
426
- if (localWebSocket) {
427
- localWebSocket.removeEventListener(
428
- "message",
429
- sendMessageToRemoteWebSocket
430
- );
431
- }
432
- };
433
- }, [localWebSocket, remoteWebSocket]);
434
- }
435
-
436
- // Credit: https://stackoverflow.com/a/2117523
437
- function randomId(): string {
438
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
439
- const r = (Math.random() * 16) | 0,
440
- v = c == "x" ? r : (r & 0x3) | 0x8;
441
- return v.toString(16);
442
- });
443
- }
444
-
445
- /**
446
- * This function converts a message serialised as a devtools event
447
- * into arguments suitable to be called by a console method, and
448
- * then actually calls the method with those arguments. Effectively,
449
- * we're just doing a little bit of the work of the devtools console,
450
- * directly in the terminal.
451
- */
452
-
453
- export const mapConsoleAPIMessageTypeToConsoleMethod: {
454
- [key in Protocol.Runtime.ConsoleAPICalledEvent["type"]]: Exclude<
455
- keyof Console,
456
- "Console"
457
- >;
458
- } = {
459
- log: "log",
460
- debug: "debug",
461
- info: "info",
462
- warning: "warn",
463
- error: "error",
464
- dir: "dir",
465
- dirxml: "dirxml",
466
- table: "table",
467
- trace: "trace",
468
- clear: "clear",
469
- count: "count",
470
- assert: "assert",
471
- profile: "profile",
472
- profileEnd: "profileEnd",
473
- timeEnd: "timeEnd",
474
- startGroup: "group",
475
- startGroupCollapsed: "groupCollapsed",
476
- endGroup: "groupEnd",
477
- };
478
-
479
- function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
480
- const args: string[] = [];
481
- for (const ro of evt.args) {
482
- switch (ro.type) {
483
- case "string":
484
- case "number":
485
- case "boolean":
486
- case "undefined":
487
- case "symbol":
488
- case "bigint":
489
- args.push(ro.value);
490
- break;
491
- case "function":
492
- args.push(`[Function: ${ro.description ?? "<no-description>"}]`);
493
- break;
494
- case "object":
495
- if (!ro.preview) {
496
- args.push(
497
- ro.subtype === "null"
498
- ? "null"
499
- : ro.description ?? "<no-description>"
500
- );
501
- } else {
502
- args.push(ro.preview.description ?? "<no-description>");
503
-
504
- switch (ro.preview.subtype) {
505
- case "array":
506
- args.push(
507
- "[ " +
508
- ro.preview.properties
509
- .map(({ value }) => {
510
- return value;
511
- })
512
- .join(", ") +
513
- (ro.preview.overflow ? "..." : "") +
514
- " ]"
515
- );
516
-
517
- break;
518
- case "weakmap":
519
- case "map":
520
- args.push(
521
- "{\n" +
522
- // Maps always have entries
523
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
524
- ro.preview
525
- .entries!.map(({ key, value }) => {
526
- return ` ${key?.description ?? "<unknown>"} => ${
527
- value.description
528
- }`;
529
- })
530
- .join(",\n") +
531
- (ro.preview.overflow ? "\n ..." : "") +
532
- "\n}"
533
- );
534
-
535
- break;
536
- case "weakset":
537
- case "set":
538
- args.push(
539
- "{ " +
540
- // Sets always have entries
541
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
542
- ro.preview
543
- .entries!.map(({ value }) => {
544
- return `${value.description}`;
545
- })
546
- .join(", ") +
547
- (ro.preview.overflow ? ", ..." : "") +
548
- " }"
549
- );
550
- break;
551
- case "regexp":
552
- break;
553
- case "date":
554
- break;
555
- case "generator":
556
- args.push(ro.preview.properties[0].value || "");
557
- break;
558
- case "promise":
559
- if (ro.preview.properties[0].value === "pending") {
560
- args.push(`{<${ro.preview.properties[0].value}>}`);
561
- } else {
562
- args.push(
563
- `{<${ro.preview.properties[0].value}>: ${ro.preview.properties[1].value}}`
564
- );
565
- }
566
- break;
567
- case "node":
568
- case "iterator":
569
- case "proxy":
570
- case "typedarray":
571
- case "arraybuffer":
572
- case "dataview":
573
- case "webassemblymemory":
574
- case "wasmvalue":
575
- break;
576
- case "error":
577
- default:
578
- // just a pojo
579
- args.push(
580
- "{\n" +
581
- ro.preview.properties
582
- .map(({ name, value }) => {
583
- return ` ${name}: ${value}`;
584
- })
585
- .join(",\n") +
586
- (ro.preview.overflow ? "\n ..." : "") +
587
- "\n}"
588
- );
589
- }
590
- }
591
- break;
592
- default:
593
- args.push(ro.description || ro.unserializableValue || "🦋");
594
- break;
595
- }
596
- }
597
-
598
- const method = mapConsoleAPIMessageTypeToConsoleMethod[evt.type];
599
-
600
- if (method in console) {
601
- switch (method) {
602
- case "dir":
603
- console.dir(args);
604
- break;
605
- case "table":
606
- console.table(args);
607
- break;
608
- default:
609
- // eslint-disable-next-line prefer-spread
610
- console[method].apply(console, args);
611
- break;
612
- }
613
- } else {
614
- console.warn(`Unsupported console method: ${method}`);
615
- console.log("console event:", evt);
616
- }
617
- }