wrangler 0.0.0-e0d2f35 → 0.0.0-e101451a2

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