wrangler 0.0.0-e61907d → 0.0.0-e95bea2

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 (93) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +79 -21
  5. package/pages/functions/buildWorker.ts +62 -0
  6. package/pages/functions/filepath-routing.test.ts +123 -0
  7. package/pages/functions/filepath-routing.ts +178 -0
  8. package/pages/functions/identifiers.ts +78 -0
  9. package/pages/functions/routes.ts +151 -0
  10. package/pages/functions/template-worker.ts +130 -0
  11. package/src/__tests__/configuration.test.ts +2217 -0
  12. package/src/__tests__/dev.test.tsx +405 -0
  13. package/src/__tests__/dev2.test.tsx +152 -0
  14. package/src/__tests__/guess-worker-format.test.ts +58 -0
  15. package/src/__tests__/helpers/clipboardy-mock.js +4 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +44 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +40 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  25. package/src/__tests__/helpers/mock-user.ts +27 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +991 -0
  32. package/src/__tests__/jest.setup.ts +69 -0
  33. package/src/__tests__/kv.test.ts +1408 -0
  34. package/src/__tests__/logout.test.ts +50 -0
  35. package/src/__tests__/package-manager.test.ts +206 -0
  36. package/src/__tests__/pages.test.ts +44 -0
  37. package/src/__tests__/parse.test.ts +322 -0
  38. package/src/__tests__/publish.test.ts +2453 -0
  39. package/src/__tests__/r2.test.ts +198 -0
  40. package/src/__tests__/route.test.ts +45 -0
  41. package/src/__tests__/secret.test.ts +425 -0
  42. package/src/__tests__/sentry.test.ts +146 -0
  43. package/src/__tests__/tail.test.ts +564 -0
  44. package/src/__tests__/whoami.test.tsx +86 -0
  45. package/src/bundle.ts +142 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +135 -0
  48. package/src/cli.ts +19 -0
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +279 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +305 -0
  53. package/src/config/index.ts +52 -0
  54. package/src/config/validation-helpers.ts +388 -0
  55. package/src/config/validation.ts +1027 -0
  56. package/src/create-worker-preview.ts +166 -0
  57. package/src/create-worker-upload-form.ts +217 -0
  58. package/src/dev/dev.tsx +357 -0
  59. package/src/dev/local.tsx +241 -0
  60. package/src/dev/remote.tsx +201 -0
  61. package/src/dev/use-esbuild.ts +100 -0
  62. package/src/dialogs.tsx +77 -0
  63. package/src/entry.ts +159 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/https-options.ts +122 -0
  66. package/src/index.tsx +2329 -0
  67. package/src/inspect.ts +617 -0
  68. package/src/kv/index.tsx +339 -0
  69. package/src/module-collection.ts +253 -0
  70. package/src/open-in-browser.ts +25 -0
  71. package/src/package-manager.ts +126 -0
  72. package/src/pages.tsx +1045 -0
  73. package/src/parse.ts +183 -0
  74. package/src/paths.ts +26 -0
  75. package/src/proxy.ts +438 -0
  76. package/src/publish.ts +354 -0
  77. package/src/r2.ts +50 -0
  78. package/src/reporting.ts +131 -0
  79. package/src/selfsigned.d.ts +29 -0
  80. package/src/sites.tsx +238 -0
  81. package/src/tail/filters.ts +279 -0
  82. package/src/tail/index.ts +299 -0
  83. package/src/tail/printing.ts +62 -0
  84. package/src/user.tsx +1065 -0
  85. package/src/whoami.tsx +69 -0
  86. package/src/worker.ts +163 -0
  87. package/templates/new-worker.js +15 -0
  88. package/templates/new-worker.ts +15 -0
  89. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  90. package/templates/tsconfig.json +105 -0
  91. package/wrangler-dist/{index_node.js → cli.js} +105532 -67432
  92. package/wrangler-dist/cli.js.map +7 -0
  93. package/wrangler-dist/index_node.js.map +0 -7
@@ -0,0 +1,146 @@
1
+ import * as fs from "node:fs";
2
+ import * as fsp from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import * as TOML from "@iarna/toml";
6
+ import * as Sentry from "@sentry/node";
7
+ import prompts from "prompts";
8
+
9
+ import { mockConsoleMethods } from "./helpers/mock-console";
10
+ import { runInTempDir } from "./helpers/run-in-tmp";
11
+ import { runWrangler } from "./helpers/run-wrangler";
12
+ const { reportError } = jest.requireActual("../reporting");
13
+
14
+ describe("Error Reporting", () => {
15
+ runInTempDir({ homedir: "./home" });
16
+ mockConsoleMethods();
17
+ const reportingTOMLPath = ".wrangler/config/reporting.toml";
18
+
19
+ const originalTTY = process.stdout.isTTY;
20
+ beforeEach(() => {
21
+ jest.mock("@sentry/node");
22
+ jest.spyOn(Sentry, "captureException");
23
+ process.stdout.isTTY = true;
24
+ });
25
+
26
+ afterEach(() => {
27
+ jest.unmock("@sentry/node");
28
+ jest.clearAllMocks();
29
+ process.stdout.isTTY = originalTTY;
30
+ });
31
+
32
+ it("should confirm user will allow error reporting usage", async () => {
33
+ jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: true });
34
+
35
+ await reportError(new Error("test error"), "testFalse");
36
+
37
+ const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
38
+ await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
39
+ );
40
+
41
+ expect(error_tracking_opt).toBe(true);
42
+ expect(error_tracking_opt_date).toBeTruthy();
43
+
44
+ expect(Sentry.captureException).toHaveBeenCalledWith(
45
+ new Error("test error")
46
+ );
47
+ });
48
+
49
+ it("should confirm user will disallow error reporting usage", async () => {
50
+ jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: false });
51
+ await reportError(new Error("test error"), "testFalse");
52
+
53
+ const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
54
+ await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
55
+ );
56
+
57
+ expect(error_tracking_opt).toBe(false);
58
+ expect(error_tracking_opt_date).toBeTruthy();
59
+
60
+ expect(Sentry.captureException).not.toHaveBeenCalledWith(
61
+ new Error("test error"),
62
+ "testFalse"
63
+ );
64
+ });
65
+
66
+ it("should confirm user will allow 'once' error reporting usage", async () => {
67
+ jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: "once" });
68
+ await runWrangler();
69
+ await reportError(new Error("test error"), "testFalse");
70
+
71
+ expect(fs.existsSync(path.join(os.homedir(), reportingTOMLPath))).toBe(
72
+ false
73
+ );
74
+
75
+ expect(Sentry.captureException).not.toHaveBeenCalledWith(
76
+ new Error("test error"),
77
+ "testFalse"
78
+ );
79
+ });
80
+
81
+ it("should not prompt w/ subsequent Errors after user disallows error reporting", async () => {
82
+ jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: false });
83
+ await reportError(new Error("test error"), "testFalse");
84
+
85
+ expect(Sentry.captureException).not.toHaveBeenCalledWith(
86
+ new Error("test error"),
87
+ "testFalse"
88
+ );
89
+
90
+ await reportError(new Error("second test error"), "testFalse");
91
+ expect(Sentry.captureException).not.toHaveBeenCalledWith(
92
+ new Error("second test error"),
93
+ "testFalse"
94
+ );
95
+ });
96
+
97
+ it("should not prompt w/ subsequent Errors after user Always allows error reporting", async () => {
98
+ jest.spyOn(prompts, "prompt").mockResolvedValue({ sentryDecision: true });
99
+ await reportError(new Error("test error"), "testFalse");
100
+
101
+ expect(Sentry.captureException).toHaveBeenCalledWith(
102
+ new Error("test error")
103
+ );
104
+
105
+ await reportError(new Error("second test error"), "testFalse");
106
+ expect(Sentry.captureException).toHaveBeenCalledWith(
107
+ new Error("second test error")
108
+ );
109
+ });
110
+
111
+ it("should prompt w/ subsequent Errors after user allows error reporting once", async () => {
112
+ const promptSpy = jest
113
+ .spyOn(prompts, "prompt")
114
+ .mockResolvedValue({ sentryDecision: "once" });
115
+ await reportError(new Error("test error"), "testFalse");
116
+
117
+ expect(Sentry.captureException).toHaveBeenCalledWith(
118
+ new Error("test error")
119
+ );
120
+
121
+ await reportError(new Error("second test error"), "testFalse");
122
+ expect(Sentry.captureException).toHaveBeenCalledWith(
123
+ new Error("second test error")
124
+ );
125
+
126
+ expect(promptSpy).toBeCalledTimes(2);
127
+ });
128
+
129
+ it("should not prompt in non-TTY environment", async () => {
130
+ process.stdout.isTTY = false;
131
+
132
+ await reportError(new Error("test error"), "testFalse");
133
+
134
+ const { error_tracking_opt, error_tracking_opt_date } = TOML.parse(
135
+ await fsp.readFile(path.join(os.homedir(), reportingTOMLPath), "utf-8")
136
+ );
137
+
138
+ expect(error_tracking_opt).toBe(false);
139
+ expect(error_tracking_opt_date).toBeTruthy();
140
+
141
+ expect(Sentry.captureException).not.toHaveBeenCalledWith(
142
+ new Error("test error")
143
+ );
144
+ process.stdout.isTTY = originalTTY;
145
+ });
146
+ });
@@ -0,0 +1,564 @@
1
+ import MockWebSocket from "jest-websocket-mock";
2
+ import { Headers, Request } from "undici";
3
+ import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
+ import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch";
5
+ import { mockConsoleMethods } from "./helpers/mock-console";
6
+ import { runInTempDir } from "./helpers/run-in-tmp";
7
+ import { runWrangler } from "./helpers/run-wrangler";
8
+ import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
9
+ import type WebSocket from "ws";
10
+
11
+ describe("tail", () => {
12
+ runInTempDir();
13
+ mockAccountId();
14
+ mockApiToken();
15
+
16
+ const std = mockConsoleMethods();
17
+
18
+ afterEach(() => {
19
+ mockWebSockets.forEach((ws) => ws.close());
20
+ mockWebSockets.splice(0);
21
+ unsetAllMocks();
22
+ });
23
+
24
+ /**
25
+ * Interaction with the tailing API, including tail creation,
26
+ * deletion, and connection.
27
+ */
28
+ describe("API interaction", () => {
29
+ it("creates and then delete tails", async () => {
30
+ const api = mockWebsocketAPIs();
31
+ expect(api.requests.creation.count).toStrictEqual(0);
32
+
33
+ await runWrangler("tail test-worker");
34
+
35
+ await expect(api.ws.connected).resolves.toBeTruthy();
36
+ expect(api.requests.creation.count).toStrictEqual(1);
37
+ expect(api.requests.deletion.count).toStrictEqual(0);
38
+
39
+ api.ws.close();
40
+ expect(api.requests.deletion.count).toStrictEqual(1);
41
+ });
42
+
43
+ it("creates and then delete tails: legacy envs", async () => {
44
+ const api = mockWebsocketAPIs("some-env", true);
45
+ expect(api.requests.creation.count).toStrictEqual(0);
46
+
47
+ await runWrangler("tail test-worker --env some-env --legacy-env true");
48
+
49
+ await expect(api.ws.connected).resolves.toBeTruthy();
50
+ expect(api.requests.creation.count).toStrictEqual(1);
51
+ expect(api.requests.deletion.count).toStrictEqual(0);
52
+
53
+ api.ws.close();
54
+ expect(api.requests.deletion.count).toStrictEqual(1);
55
+ });
56
+
57
+ it("creates and then delete tails: service envs", async () => {
58
+ const api = mockWebsocketAPIs("some-env");
59
+ expect(api.requests.creation.count).toStrictEqual(0);
60
+
61
+ await runWrangler("tail test-worker --env some-env --legacy-env false");
62
+
63
+ await expect(api.ws.connected).resolves.toBeTruthy();
64
+ expect(api.requests.creation.count).toStrictEqual(1);
65
+ expect(api.requests.deletion.count).toStrictEqual(0);
66
+
67
+ api.ws.close();
68
+ expect(api.requests.deletion.count).toStrictEqual(1);
69
+ });
70
+
71
+ it("errors when the websocket closes unexpectedly", async () => {
72
+ const api = mockWebsocketAPIs();
73
+ api.ws.close();
74
+
75
+ await expect(runWrangler("tail test-worker")).rejects.toThrow();
76
+ });
77
+
78
+ it("activates debug mode when the cli arg is passed in", async () => {
79
+ const api = mockWebsocketAPIs();
80
+ await runWrangler("tail test-worker --debug");
81
+ await expect(api.nextMessageJson()).resolves.toHaveProperty(
82
+ "debug",
83
+ true
84
+ );
85
+ });
86
+ });
87
+
88
+ describe("filtering", () => {
89
+ it("sends sampling rate filters", async () => {
90
+ const api = mockWebsocketAPIs();
91
+ const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
92
+ await expect(tooHigh).rejects.toThrow();
93
+
94
+ const tooLow = runWrangler("tail test-worker --sampling-rate -5");
95
+ await expect(tooLow).rejects.toThrow();
96
+
97
+ await runWrangler("tail test-worker --sampling-rate 0.25");
98
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
99
+ { sampling_rate: 0.25 },
100
+ ]);
101
+ });
102
+
103
+ it("sends single status filters", async () => {
104
+ const api = mockWebsocketAPIs();
105
+ await runWrangler("tail test-worker --status error");
106
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
107
+ { outcome: ["exception", "exceededCpu", "unknown"] },
108
+ ]);
109
+ });
110
+
111
+ it("sends multiple status filters", async () => {
112
+ const api = mockWebsocketAPIs();
113
+ await runWrangler("tail test-worker --status error --status canceled");
114
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
115
+ { outcome: ["exception", "exceededCpu", "unknown", "canceled"] },
116
+ ]);
117
+ });
118
+
119
+ it("sends single HTTP method filters", async () => {
120
+ const api = mockWebsocketAPIs();
121
+ await runWrangler("tail test-worker --method POST");
122
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
123
+ { method: ["POST"] },
124
+ ]);
125
+ });
126
+
127
+ it("sends multiple HTTP method filters", async () => {
128
+ const api = mockWebsocketAPIs();
129
+ await runWrangler("tail test-worker --method POST --method GET");
130
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
131
+ { method: ["POST", "GET"] },
132
+ ]);
133
+ });
134
+
135
+ it("sends header filters without a query", async () => {
136
+ const api = mockWebsocketAPIs();
137
+ await runWrangler("tail test-worker --header X-CUSTOM-HEADER ");
138
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
139
+ { header: { key: "X-CUSTOM-HEADER" } },
140
+ ]);
141
+ });
142
+
143
+ it("sends header filters with a query", async () => {
144
+ const api = mockWebsocketAPIs();
145
+ await runWrangler(
146
+ "tail test-worker --header X-CUSTOM-HEADER:some-value "
147
+ );
148
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
149
+ { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
150
+ ]);
151
+ });
152
+
153
+ it("sends single IP filters", async () => {
154
+ const api = mockWebsocketAPIs();
155
+ const fakeIp = "192.0.2.1";
156
+
157
+ await runWrangler(`tail test-worker --ip ${fakeIp}`);
158
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
159
+ { client_ip: [fakeIp] },
160
+ ]);
161
+ });
162
+
163
+ it("sends multiple IP filters", async () => {
164
+ const api = mockWebsocketAPIs();
165
+ const fakeIp = "192.0.2.1";
166
+
167
+ await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
168
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
169
+ { client_ip: [fakeIp, "self"] },
170
+ ]);
171
+ });
172
+
173
+ it("sends search filters", async () => {
174
+ const api = mockWebsocketAPIs();
175
+ const search = "filterMe";
176
+
177
+ await runWrangler(`tail test-worker --search ${search}`);
178
+ await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
179
+ { query: search },
180
+ ]);
181
+ });
182
+
183
+ it("sends everything but the kitchen sink", async () => {
184
+ const api = mockWebsocketAPIs();
185
+ const sampling_rate = 0.69;
186
+ const status = ["ok", "error"];
187
+ const method = ["GET", "POST", "PUT"];
188
+ const header = "X-HELLO:world";
189
+ const client_ip = ["192.0.2.1", "self"];
190
+ const query = "onlyTheseMessagesPlease";
191
+
192
+ const cliFilters =
193
+ `--sampling-rate ${sampling_rate} ` +
194
+ status.map((s) => `--status ${s} `).join("") +
195
+ method.map((m) => `--method ${m} `).join("") +
196
+ `--header ${header} ` +
197
+ client_ip.map((c) => `--ip ${c} `).join("") +
198
+ `--search ${query} ` +
199
+ `--debug`;
200
+
201
+ const expectedWebsocketMessage = {
202
+ filters: [
203
+ { sampling_rate },
204
+ { outcome: ["ok", "exception", "exceededCpu", "unknown"] },
205
+ { method },
206
+ { header: { key: "X-HELLO", query: "world" } },
207
+ { client_ip },
208
+ { query },
209
+ ],
210
+ debug: true,
211
+ };
212
+
213
+ await runWrangler(`tail test-worker ${cliFilters}`);
214
+ await expect(api.nextMessageJson()).resolves.toEqual(
215
+ expectedWebsocketMessage
216
+ );
217
+ });
218
+ });
219
+
220
+ describe("printing", () => {
221
+ it("logs request messages in JSON format", async () => {
222
+ const api = mockWebsocketAPIs();
223
+ await runWrangler("tail test-worker --format json");
224
+
225
+ const event = generateMockRequestEvent();
226
+ const message = generateMockEventMessage({ event });
227
+ const serializedMessage = serialize(message);
228
+
229
+ api.ws.send(serializedMessage);
230
+ expect(std.out).toMatch(deserializeToJson(serializedMessage));
231
+ });
232
+
233
+ it("logs scheduled messages in JSON format", async () => {
234
+ const api = mockWebsocketAPIs();
235
+ await runWrangler("tail test-worker --format json");
236
+
237
+ const event = generateMockScheduledEvent();
238
+ const message = generateMockEventMessage({ event });
239
+ const serializedMessage = serialize(message);
240
+
241
+ api.ws.send(serializedMessage);
242
+ expect(std.out).toMatch(deserializeToJson(serializedMessage));
243
+ });
244
+
245
+ it("logs request messages in pretty format", async () => {
246
+ const api = mockWebsocketAPIs();
247
+ await runWrangler("tail test-worker --format pretty");
248
+
249
+ const event = generateMockRequestEvent();
250
+ const message = generateMockEventMessage({ event });
251
+ const serializedMessage = serialize(message);
252
+
253
+ api.ws.send(serializedMessage);
254
+ expect(
255
+ std.out
256
+ .replace(
257
+ new Date(mockEventTimestamp).toLocaleString(),
258
+ "[mock event timestamp]"
259
+ )
260
+ .replace(
261
+ mockTailExpiration.toLocaleString(),
262
+ "[mock expiration date]"
263
+ )
264
+ ).toMatchInlineSnapshot(`
265
+ "successfully created tail, expires at [mock expiration date]
266
+ Connected to test-worker, waiting for logs...
267
+ GET https://example.org/ - Ok @ [mock event timestamp]"
268
+ `);
269
+ });
270
+
271
+ it("logs scheduled messages in pretty format", async () => {
272
+ const api = mockWebsocketAPIs();
273
+ await runWrangler("tail test-worker --format pretty");
274
+
275
+ const event = generateMockScheduledEvent();
276
+ const message = generateMockEventMessage({ event });
277
+ const serializedMessage = serialize(message);
278
+
279
+ api.ws.send(serializedMessage);
280
+ expect(
281
+ std.out
282
+ .replace(
283
+ new Date(mockEventTimestamp).toLocaleString(),
284
+ "[mock timestamp string]"
285
+ )
286
+ .replace(
287
+ mockTailExpiration.toLocaleString(),
288
+ "[mock expiration date]"
289
+ )
290
+ ).toMatchInlineSnapshot(`
291
+ "successfully created tail, expires at [mock expiration date]
292
+ Connected to test-worker, waiting for logs...
293
+ \\"* * * * *\\" @ [mock timestamp string] - Ok"
294
+ `);
295
+ });
296
+ });
297
+ });
298
+
299
+ /* helpers */
300
+
301
+ /**
302
+ * The built in serialize-to-JSON feature of our mock websocket doesn't work
303
+ * for our use-case since we actually expect a raw buffer,
304
+ * not a Javascript string. Additionally, we have to do some fiddling
305
+ * with `RequestEvent`s to get them to serialize properly.
306
+ *
307
+ * @param message a message to serialize to JSON
308
+ * @returns the same type we expect when deserializing in wrangler
309
+ */
310
+ function serialize(message: TailEventMessage): WebSocket.RawData {
311
+ if (isScheduled(message.event)) {
312
+ // `ScheduledEvent`s work just fine
313
+ const stringified = JSON.stringify(message);
314
+ return Buffer.from(stringified, "utf-8");
315
+ } else {
316
+ // Since the "properties" of an `undici.Request` are actually getters,
317
+ // which don't serialize properly, we need to hydrate them manually.
318
+ // This isn't a problem outside of testing since deserialization
319
+ // works just fine and wrangler never _sends_ any event messages,
320
+ // it only receives them.
321
+ const request = (message.event as RequestEvent).request;
322
+ const stringified = JSON.stringify(message, (key, value) => {
323
+ if (key !== "request") {
324
+ return value;
325
+ }
326
+
327
+ return {
328
+ ...request,
329
+ url: request.url,
330
+ headers: request.headers,
331
+ method: request.method,
332
+ };
333
+ });
334
+
335
+ return Buffer.from(stringified, "utf-8");
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Small helper to disambiguate the event types possible in a `TailEventMessage`
341
+ *
342
+ * @param event A TailEvent
343
+ * @returns whether event is a ScheduledEvent (true) or a RequestEvent
344
+ */
345
+ function isScheduled(
346
+ event: ScheduledEvent | RequestEvent
347
+ ): event is ScheduledEvent {
348
+ return "cron" in event;
349
+ }
350
+
351
+ /**
352
+ * Similarly, we need to deserialize from a raw buffer instead
353
+ * of just JSON.parsing a raw string. This deserializer also then
354
+ * re-stringifies with some spacing, the same way wrangler tail does.
355
+ *
356
+ * @param message a buffer of data received from the websocket
357
+ * @returns a string ready to be printed to the terminal or compared against
358
+ */
359
+ function deserializeToJson(message: WebSocket.RawData): string {
360
+ return JSON.stringify(JSON.parse(message.toString()), null, 2);
361
+ }
362
+
363
+ /**
364
+ * A mock for all the different API resources wrangler accesses
365
+ * when running `wrangler tail`
366
+ */
367
+ type MockAPI = {
368
+ requests: {
369
+ creation: RequestCounter;
370
+ deletion: RequestCounter;
371
+ };
372
+ ws: MockWebSocket;
373
+ nextMessageJson(): Promise<unknown>;
374
+ };
375
+
376
+ /**
377
+ * A counter used to check how many times a mock API has been hit.
378
+ * Useful as a helper in our testing to check if wrangler is making
379
+ * the correct API calls without actually sending any web traffic
380
+ */
381
+ type RequestCounter = {
382
+ count: number;
383
+ };
384
+
385
+ /**
386
+ * Mock out the API hit during Tail creation
387
+ *
388
+ * @param websocketURL a fake URL for wrangler to connect a websocket to
389
+ * @returns a `RequestCounter` for counting how many times the API is hit
390
+ */
391
+ function mockCreateTailRequest(
392
+ websocketURL: string,
393
+ env?: string,
394
+ legacyEnv = false
395
+ ): RequestCounter {
396
+ const requests = { count: 0 };
397
+ const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
398
+ const environment = env && !legacyEnv ? "/environments/:envName" : "";
399
+ setMockResponse(
400
+ `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
401
+ "POST",
402
+ ([_url, accountId, scriptName, envName]) => {
403
+ requests.count++;
404
+ expect(accountId).toEqual("some-account-id");
405
+ expect(scriptName).toEqual(
406
+ legacyEnv && env ? `test-worker-${env}` : "test-worker"
407
+ );
408
+ if (!legacyEnv) {
409
+ expect(envName).toEqual(env);
410
+ }
411
+ return {
412
+ id: "tail-id",
413
+ url: websocketURL,
414
+ expires_at: mockTailExpiration,
415
+ };
416
+ }
417
+ );
418
+
419
+ return requests;
420
+ }
421
+
422
+ /**
423
+ * Mock expiration datetime for tails created during testing
424
+ */
425
+ const mockTailExpiration = new Date(3005, 1);
426
+
427
+ /**
428
+ * Default value for event timestamps
429
+ */
430
+ const mockEventTimestamp = 1645454470467;
431
+
432
+ /**
433
+ * Mock out the API hit during Tail deletion
434
+ *
435
+ * @returns a `RequestCounter` for counting how many times the API is hit
436
+ */
437
+ function mockDeleteTailRequest(
438
+ env?: string,
439
+ legacyEnv = false
440
+ ): RequestCounter {
441
+ const requests = { count: 0 };
442
+ const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
443
+ const environment = env && !legacyEnv ? "/environments/:envName" : "";
444
+ setMockResponse(
445
+ // "/accounts/:accountId/workers/scripts/:worker/tails",
446
+ `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
447
+ "DELETE",
448
+ ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
449
+ requests.count++;
450
+ expect(accountId).toEqual("some-account-id");
451
+ expect(scriptName).toEqual(
452
+ legacyEnv && env ? `test-worker-${env}` : "test-worker"
453
+ );
454
+ if (!legacyEnv) {
455
+ if (env) {
456
+ expect(envNameOrTailId).toEqual(env);
457
+ expect(tailId).toEqual("tail-id");
458
+ } else {
459
+ expect(envNameOrTailId).toEqual("tail-id");
460
+ }
461
+ } else {
462
+ expect(envNameOrTailId).toEqual("tail-id");
463
+ }
464
+ return null;
465
+ }
466
+ );
467
+
468
+ return requests;
469
+ }
470
+
471
+ const mockWebSockets: MockWebSocket[] = [];
472
+
473
+ /**
474
+ * All-in-one convenience method to mock the appropriate API calls before
475
+ * each test, and clean up afterwards.
476
+ *
477
+ * @param websocketURL a fake websocket URL for wrangler to connect to
478
+ * @returns a mocked-out version of the API
479
+ */
480
+ function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
481
+ const websocketURL = "ws://localhost:1234";
482
+ const api: MockAPI = {
483
+ requests: {
484
+ deletion: { count: 0 },
485
+ creation: { count: 0 },
486
+ },
487
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
488
+ ws: null!, // will be set in the `beforeEach()` below.
489
+
490
+ /**
491
+ * Parse the next message received by the mock websocket as JSON
492
+ * @returns JSON.parse of the next message received by the websocket
493
+ */
494
+ async nextMessageJson() {
495
+ const message = await api.ws.nextMessage;
496
+ return JSON.parse(message as string);
497
+ },
498
+ };
499
+ api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
500
+ api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
501
+ api.ws = new MockWebSocket(websocketURL);
502
+ mockWebSockets.push(api.ws);
503
+
504
+ return api;
505
+ }
506
+
507
+ /**
508
+ * Generate a mock `TailEventMessage` of the same shape sent back by the
509
+ * tail worker.
510
+ *
511
+ * @param opts Any specific parts of the message to use instead of defaults
512
+ * @returns a `TailEventMessage` that wrangler can process and display
513
+ */
514
+ function generateMockEventMessage(
515
+ opts?: Partial<TailEventMessage>
516
+ ): TailEventMessage {
517
+ return {
518
+ outcome: opts?.outcome || "ok",
519
+ exceptions: opts?.exceptions || [],
520
+ logs: opts?.logs || [],
521
+ eventTimestamp: opts?.eventTimestamp || mockEventTimestamp,
522
+ event: opts?.event || generateMockRequestEvent(),
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Generate a mock `RequestEvent` that, in an alternate timeline, was used
528
+ * to trigger a worker. You can't disprove this!
529
+ *
530
+ * @param opts Any specific parts of the event to use instead of defaults
531
+ * @returns a `RequestEvent` that can be used within an `EventMessage`
532
+ */
533
+ function generateMockRequestEvent(
534
+ opts?: Partial<RequestEvent["request"]>
535
+ ): RequestEvent {
536
+ return {
537
+ request: Object.assign(
538
+ new Request(opts?.url || "https://example.org/", {
539
+ method: opts?.method || "GET",
540
+ headers:
541
+ opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
542
+ }),
543
+ {
544
+ cf: opts?.cf || {
545
+ tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
546
+ tlsVersion: "TLSv2.0",
547
+ asn: 42069,
548
+ colo: "ATL",
549
+ httpProtocol: "HTTP/4",
550
+ asOrganization: "Cloudflare",
551
+ },
552
+ }
553
+ ),
554
+ };
555
+ }
556
+
557
+ function generateMockScheduledEvent(
558
+ opts?: Partial<ScheduledEvent>
559
+ ): ScheduledEvent {
560
+ return {
561
+ cron: opts?.cron || "* * * * *",
562
+ scheduledTime: opts?.scheduledTime || mockEventTimestamp,
563
+ };
564
+ }