wrangler 0.0.0-e1e2ee5c → 0.0.0-e1f2576e

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 (189) hide show
  1. package/README.md +24 -12
  2. package/bin/wrangler.js +26 -67
  3. package/package.json +226 -167
  4. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +19 -6
  8. package/templates/facade.d.ts +17 -0
  9. package/templates/gitignore +0 -4
  10. package/templates/init-tests/test-jest-new-worker.js +23 -0
  11. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +67 -0
  14. package/templates/middleware/loader-modules.ts +136 -0
  15. package/templates/middleware/loader-sw.ts +229 -0
  16. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  19. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  20. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +15 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +32 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +51 -16
  33. package/templates/pages-template-worker.ts +48 -11
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +5 -102
  39. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  40. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  41. package/wrangler-dist/ProxyWorker.js +237 -0
  42. package/wrangler-dist/ProxyWorker.js.map +6 -0
  43. package/wrangler-dist/cli.d.ts +23779 -186
  44. package/wrangler-dist/cli.js +157746 -110497
  45. package/wrangler-dist/wasm-sync.wasm +0 -0
  46. package/import_meta_url.js +0 -3
  47. package/miniflare-config-stubs/.env.empty +0 -0
  48. package/miniflare-config-stubs/package.empty.json +0 -1
  49. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  50. package/miniflare-dist/index.mjs +0 -5354
  51. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  52. package/src/__tests__/config-cache.test.ts +0 -42
  53. package/src/__tests__/configuration.test.ts +0 -3950
  54. package/src/__tests__/dev.test.tsx +0 -1203
  55. package/src/__tests__/guess-worker-format.test.ts +0 -85
  56. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  57. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  58. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  59. package/src/__tests__/helpers/mock-bin.ts +0 -36
  60. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  61. package/src/__tests__/helpers/mock-console.ts +0 -97
  62. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  63. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  64. package/src/__tests__/helpers/mock-istty.ts +0 -74
  65. package/src/__tests__/helpers/mock-kv.ts +0 -33
  66. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  67. package/src/__tests__/helpers/mock-process.ts +0 -39
  68. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  69. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  72. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  73. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  74. package/src/__tests__/https-options.test.ts +0 -163
  75. package/src/__tests__/index.test.ts +0 -262
  76. package/src/__tests__/init.test.ts +0 -1992
  77. package/src/__tests__/jest.setup.ts +0 -120
  78. package/src/__tests__/kv.test.ts +0 -1671
  79. package/src/__tests__/logger.test.ts +0 -141
  80. package/src/__tests__/metrics.test.ts +0 -445
  81. package/src/__tests__/package-manager.test.ts +0 -353
  82. package/src/__tests__/pages.test.ts +0 -1261
  83. package/src/__tests__/parse.test.ts +0 -330
  84. package/src/__tests__/publish.test.ts +0 -6671
  85. package/src/__tests__/pubsub.test.ts +0 -367
  86. package/src/__tests__/r2.test.ts +0 -233
  87. package/src/__tests__/route.test.ts +0 -45
  88. package/src/__tests__/secret.test.ts +0 -492
  89. package/src/__tests__/tail.test.ts +0 -698
  90. package/src/__tests__/test-old-node-version.js +0 -31
  91. package/src/__tests__/user.test.ts +0 -143
  92. package/src/__tests__/version.test.ts +0 -35
  93. package/src/__tests__/whoami.test.tsx +0 -230
  94. package/src/__tests__/worker-namespace.test.ts +0 -327
  95. package/src/abort.d.ts +0 -3
  96. package/src/api/dev.ts +0 -86
  97. package/src/api/index.ts +0 -1
  98. package/src/bundle-reporter.tsx +0 -29
  99. package/src/bundle.ts +0 -236
  100. package/src/cfetch/index.ts +0 -121
  101. package/src/cfetch/internal.ts +0 -149
  102. package/src/cli.ts +0 -27
  103. package/src/config/README.md +0 -107
  104. package/src/config/config.ts +0 -251
  105. package/src/config/diagnostics.ts +0 -80
  106. package/src/config/environment.ts +0 -453
  107. package/src/config/index.ts +0 -238
  108. package/src/config/validation-helpers.ts +0 -584
  109. package/src/config/validation.ts +0 -1754
  110. package/src/config-cache.ts +0 -84
  111. package/src/create-worker-preview.ts +0 -255
  112. package/src/create-worker-upload-form.ts +0 -263
  113. package/src/dev/dev-vars.ts +0 -36
  114. package/src/dev/dev.tsx +0 -452
  115. package/src/dev/local.tsx +0 -373
  116. package/src/dev/remote.tsx +0 -386
  117. package/src/dev/use-esbuild.ts +0 -150
  118. package/src/dev.tsx +0 -593
  119. package/src/dialogs.tsx +0 -135
  120. package/src/durable.ts +0 -102
  121. package/src/entry.ts +0 -328
  122. package/src/environment-variables.ts +0 -35
  123. package/src/errors.ts +0 -11
  124. package/src/faye-websocket.d.ts +0 -6
  125. package/src/generate.ts +0 -33
  126. package/src/git-client.ts +0 -42
  127. package/src/global-wrangler-config-path.ts +0 -26
  128. package/src/https-options.ts +0 -127
  129. package/src/index.tsx +0 -2005
  130. package/src/init.ts +0 -549
  131. package/src/inspect.ts +0 -662
  132. package/src/intl-polyfill.d.ts +0 -139
  133. package/src/is-interactive.ts +0 -12
  134. package/src/kv.ts +0 -430
  135. package/src/logger.ts +0 -73
  136. package/src/metrics/index.ts +0 -4
  137. package/src/metrics/is-ci.ts +0 -14
  138. package/src/metrics/metrics-config.ts +0 -239
  139. package/src/metrics/metrics-dispatcher.ts +0 -95
  140. package/src/metrics/send-event.ts +0 -92
  141. package/src/miniflare-cli/README.md +0 -30
  142. package/src/miniflare-cli/assets.ts +0 -543
  143. package/src/miniflare-cli/enum-keys.ts +0 -17
  144. package/src/miniflare-cli/index.ts +0 -85
  145. package/src/miniflare-cli/request-context.ts +0 -40
  146. package/src/module-collection.ts +0 -258
  147. package/src/open-in-browser.ts +0 -17
  148. package/src/package-manager.ts +0 -219
  149. package/src/pages/build.tsx +0 -204
  150. package/src/pages/constants.ts +0 -7
  151. package/src/pages/deployments.tsx +0 -106
  152. package/src/pages/dev.tsx +0 -401
  153. package/src/pages/functions/buildPlugin.ts +0 -105
  154. package/src/pages/functions/buildWorker.ts +0 -151
  155. package/src/pages/functions/filepath-routing.test.ts +0 -234
  156. package/src/pages/functions/filepath-routing.ts +0 -189
  157. package/src/pages/functions/identifiers.ts +0 -78
  158. package/src/pages/functions/routes.ts +0 -151
  159. package/src/pages/index.tsx +0 -84
  160. package/src/pages/projects.tsx +0 -163
  161. package/src/pages/publish.tsx +0 -338
  162. package/src/pages/types.ts +0 -40
  163. package/src/pages/upload.tsx +0 -396
  164. package/src/pages/utils.ts +0 -12
  165. package/src/parse.ts +0 -286
  166. package/src/paths.ts +0 -26
  167. package/src/preview.ts +0 -31
  168. package/src/proxy.ts +0 -476
  169. package/src/publish.ts +0 -793
  170. package/src/pubsub/index.ts +0 -286
  171. package/src/pubsub/pubsub-commands.tsx +0 -623
  172. package/src/r2.ts +0 -50
  173. package/src/selfsigned.d.ts +0 -29
  174. package/src/sites.tsx +0 -372
  175. package/src/tail/filters.ts +0 -279
  176. package/src/tail/index.ts +0 -299
  177. package/src/tail/printing.ts +0 -67
  178. package/src/update-check.ts +0 -19
  179. package/src/user/choose-account.tsx +0 -69
  180. package/src/user/env-vars.ts +0 -46
  181. package/src/user/generate-auth-url.ts +0 -33
  182. package/src/user/generate-random-state.ts +0 -16
  183. package/src/user/index.ts +0 -3
  184. package/src/user/user.tsx +0 -1171
  185. package/src/whoami.tsx +0 -91
  186. package/src/worker-namespace.ts +0 -206
  187. package/src/worker.ts +0 -191
  188. package/src/zones.ts +0 -76
  189. package/templates/static-asset-facade.js +0 -49
@@ -1,698 +0,0 @@
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 { useMockIsTTY } from "./helpers/mock-istty";
7
- import { runInTempDir } from "./helpers/run-in-tmp";
8
- import { runWrangler } from "./helpers/run-wrangler";
9
- import type { TailEventMessage, RequestEvent, ScheduledEvent } from "../tail";
10
- import type WebSocket from "ws";
11
-
12
- describe("tail", () => {
13
- runInTempDir();
14
- mockAccountId();
15
- mockApiToken();
16
-
17
- const std = mockConsoleMethods();
18
-
19
- afterEach(() => {
20
- mockWebSockets.forEach((ws) => ws.close());
21
- mockWebSockets.splice(0);
22
- unsetAllMocks();
23
- });
24
-
25
- /**
26
- * Interaction with the tailing API, including tail creation,
27
- * deletion, and connection.
28
- */
29
- describe("API interaction", () => {
30
- it("should throw an error if name isn't provided", async () => {
31
- await expect(
32
- runWrangler("tail")
33
- ).rejects.toThrowErrorMatchingInlineSnapshot(
34
- `"Required Worker name missing. Please specify the Worker name in wrangler.toml, or pass it as an argument with \`wrangler tail <worker-name>\`"`
35
- );
36
- });
37
-
38
- it("creates and then delete tails", async () => {
39
- const api = mockWebsocketAPIs();
40
- expect(api.requests.creation.count).toStrictEqual(0);
41
-
42
- await runWrangler("tail test-worker");
43
-
44
- await expect(api.ws.connected).resolves.toBeTruthy();
45
- expect(api.requests.creation.count).toStrictEqual(1);
46
- expect(api.requests.deletion.count).toStrictEqual(0);
47
-
48
- api.ws.close();
49
- expect(api.requests.deletion.count).toStrictEqual(1);
50
- });
51
-
52
- it("creates and then delete tails: legacy envs", async () => {
53
- const api = mockWebsocketAPIs("some-env", true);
54
- expect(api.requests.creation.count).toStrictEqual(0);
55
-
56
- await runWrangler("tail test-worker --env some-env --legacy-env true");
57
-
58
- await expect(api.ws.connected).resolves.toBeTruthy();
59
- expect(api.requests.creation.count).toStrictEqual(1);
60
- expect(api.requests.deletion.count).toStrictEqual(0);
61
-
62
- api.ws.close();
63
- expect(api.requests.deletion.count).toStrictEqual(1);
64
- });
65
-
66
- it("creates and then delete tails: service envs", async () => {
67
- const api = mockWebsocketAPIs("some-env");
68
- expect(api.requests.creation.count).toStrictEqual(0);
69
-
70
- await runWrangler("tail test-worker --env some-env --legacy-env false");
71
-
72
- await expect(api.ws.connected).resolves.toBeTruthy();
73
- expect(api.requests.creation.count).toStrictEqual(1);
74
- expect(api.requests.deletion.count).toStrictEqual(0);
75
-
76
- api.ws.close();
77
- expect(api.requests.deletion.count).toStrictEqual(1);
78
- });
79
-
80
- it("errors when the websocket closes unexpectedly", async () => {
81
- const api = mockWebsocketAPIs();
82
- api.ws.close();
83
-
84
- await expect(runWrangler("tail test-worker")).rejects.toThrow();
85
- });
86
-
87
- it("activates debug mode when the cli arg is passed in", async () => {
88
- const api = mockWebsocketAPIs();
89
- await runWrangler("tail test-worker --debug");
90
- await expect(api.nextMessageJson()).resolves.toHaveProperty(
91
- "debug",
92
- true
93
- );
94
- });
95
- });
96
-
97
- describe("filtering", () => {
98
- it("sends sampling rate filters", async () => {
99
- const api = mockWebsocketAPIs();
100
- const tooHigh = runWrangler("tail test-worker --sampling-rate 10");
101
- await expect(tooHigh).rejects.toThrow();
102
-
103
- const tooLow = runWrangler("tail test-worker --sampling-rate -5");
104
- await expect(tooLow).rejects.toThrow();
105
-
106
- await runWrangler("tail test-worker --sampling-rate 0.25");
107
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
108
- { sampling_rate: 0.25 },
109
- ]);
110
- });
111
-
112
- it("sends single status filters", async () => {
113
- const api = mockWebsocketAPIs();
114
- await runWrangler("tail test-worker --status error");
115
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
116
- { outcome: ["exception", "exceededCpu", "unknown"] },
117
- ]);
118
- });
119
-
120
- it("sends multiple status filters", async () => {
121
- const api = mockWebsocketAPIs();
122
- await runWrangler("tail test-worker --status error --status canceled");
123
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
124
- { outcome: ["exception", "exceededCpu", "unknown", "canceled"] },
125
- ]);
126
- });
127
-
128
- it("sends single HTTP method filters", async () => {
129
- const api = mockWebsocketAPIs();
130
- await runWrangler("tail test-worker --method POST");
131
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
132
- { method: ["POST"] },
133
- ]);
134
- });
135
-
136
- it("sends multiple HTTP method filters", async () => {
137
- const api = mockWebsocketAPIs();
138
- await runWrangler("tail test-worker --method POST --method GET");
139
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
140
- { method: ["POST", "GET"] },
141
- ]);
142
- });
143
-
144
- it("sends header filters without a query", async () => {
145
- const api = mockWebsocketAPIs();
146
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER");
147
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
148
- { header: { key: "X-CUSTOM-HEADER" } },
149
- ]);
150
- });
151
-
152
- it("sends header filters with a query", async () => {
153
- const api = mockWebsocketAPIs();
154
- await runWrangler("tail test-worker --header X-CUSTOM-HEADER:some-value");
155
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
156
- { header: { key: "X-CUSTOM-HEADER", query: "some-value" } },
157
- ]);
158
- });
159
-
160
- it("sends single IP filters", async () => {
161
- const api = mockWebsocketAPIs();
162
- const fakeIp = "192.0.2.1";
163
-
164
- await runWrangler(`tail test-worker --ip ${fakeIp}`);
165
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
166
- { client_ip: [fakeIp] },
167
- ]);
168
- });
169
-
170
- it("sends multiple IP filters", async () => {
171
- const api = mockWebsocketAPIs();
172
- const fakeIp = "192.0.2.1";
173
-
174
- await runWrangler(`tail test-worker --ip ${fakeIp} --ip self`);
175
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
176
- { client_ip: [fakeIp, "self"] },
177
- ]);
178
- });
179
-
180
- it("sends search filters", async () => {
181
- const api = mockWebsocketAPIs();
182
- const search = "filterMe";
183
-
184
- await runWrangler(`tail test-worker --search ${search}`);
185
- await expect(api.nextMessageJson()).resolves.toHaveProperty("filters", [
186
- { query: search },
187
- ]);
188
- });
189
-
190
- it("sends everything but the kitchen sink", async () => {
191
- const api = mockWebsocketAPIs();
192
- const sampling_rate = 0.69;
193
- const status = ["ok", "error"];
194
- const method = ["GET", "POST", "PUT"];
195
- const header = "X-HELLO:world";
196
- const client_ip = ["192.0.2.1", "self"];
197
- const query = "onlyTheseMessagesPlease";
198
-
199
- const cliFilters =
200
- `--sampling-rate ${sampling_rate} ` +
201
- status.map((s) => `--status ${s} `).join("") +
202
- method.map((m) => `--method ${m} `).join("") +
203
- `--header ${header} ` +
204
- client_ip.map((c) => `--ip ${c} `).join("") +
205
- `--search ${query} ` +
206
- `--debug`;
207
-
208
- const expectedWebsocketMessage = {
209
- filters: [
210
- { sampling_rate },
211
- { outcome: ["ok", "exception", "exceededCpu", "unknown"] },
212
- { method },
213
- { header: { key: "X-HELLO", query: "world" } },
214
- { client_ip },
215
- { query },
216
- ],
217
- debug: true,
218
- };
219
-
220
- await runWrangler(`tail test-worker ${cliFilters}`);
221
- await expect(api.nextMessageJson()).resolves.toEqual(
222
- expectedWebsocketMessage
223
- );
224
- });
225
- });
226
-
227
- describe("printing", () => {
228
- const { setIsTTY } = useMockIsTTY();
229
-
230
- it("logs request messages in JSON format", async () => {
231
- const api = mockWebsocketAPIs();
232
- await runWrangler("tail test-worker --format json");
233
-
234
- const event = generateMockRequestEvent();
235
- const message = generateMockEventMessage({ event });
236
- const serializedMessage = serialize(message);
237
-
238
- api.ws.send(serializedMessage);
239
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
240
- });
241
-
242
- it("logs scheduled messages in JSON format", async () => {
243
- const api = mockWebsocketAPIs();
244
- await runWrangler("tail test-worker --format json");
245
-
246
- const event = generateMockScheduledEvent();
247
- const message = generateMockEventMessage({ event });
248
- const serializedMessage = serialize(message);
249
-
250
- api.ws.send(serializedMessage);
251
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
252
- });
253
-
254
- it("logs request messages in pretty format", async () => {
255
- const api = mockWebsocketAPIs();
256
- await runWrangler("tail test-worker --format pretty");
257
-
258
- const event = generateMockRequestEvent();
259
- const message = generateMockEventMessage({ event });
260
- const serializedMessage = serialize(message);
261
-
262
- api.ws.send(serializedMessage);
263
- expect(
264
- std.out
265
- .replace(
266
- new Date(mockEventTimestamp).toLocaleString(),
267
- "[mock event timestamp]"
268
- )
269
- .replace(
270
- mockTailExpiration.toLocaleString(),
271
- "[mock expiration date]"
272
- )
273
- ).toMatchInlineSnapshot(`
274
- "Successfully created tail, expires at [mock expiration date]
275
- Connected to test-worker, waiting for logs...
276
- GET https://example.org/ - Ok @ [mock event timestamp]"
277
- `);
278
- });
279
-
280
- it("logs scheduled messages in pretty format", async () => {
281
- const api = mockWebsocketAPIs();
282
- await runWrangler("tail test-worker --format pretty");
283
-
284
- const event = generateMockScheduledEvent();
285
- const message = generateMockEventMessage({ event });
286
- const serializedMessage = serialize(message);
287
-
288
- api.ws.send(serializedMessage);
289
- expect(
290
- std.out
291
- .replace(
292
- new Date(mockEventTimestamp).toLocaleString(),
293
- "[mock timestamp string]"
294
- )
295
- .replace(
296
- mockTailExpiration.toLocaleString(),
297
- "[mock expiration date]"
298
- )
299
- ).toMatchInlineSnapshot(`
300
- "Successfully created tail, expires at [mock expiration date]
301
- Connected to test-worker, waiting for logs...
302
- \\"* * * * *\\" @ [mock timestamp string] - Ok"
303
- `);
304
- });
305
-
306
- it("should not crash when the tail message has a void event", async () => {
307
- const api = mockWebsocketAPIs();
308
- await runWrangler("tail test-worker --format pretty");
309
-
310
- const message = generateMockEventMessage({ event: null });
311
- const serializedMessage = serialize(message);
312
-
313
- api.ws.send(serializedMessage);
314
- expect(
315
- std.out
316
- .replace(
317
- new Date(mockEventTimestamp).toLocaleString(),
318
- "[mock timestamp string]"
319
- )
320
- .replace(
321
- mockTailExpiration.toLocaleString(),
322
- "[mock expiration date]"
323
- )
324
- ).toMatchInlineSnapshot(`
325
- "Successfully created tail, expires at [mock expiration date]
326
- Connected to test-worker, waiting for logs...
327
- [missing request] - Ok @ [mock timestamp string]"
328
- `);
329
- });
330
-
331
- it("defaults to logging in pretty format when the output is a TTY", async () => {
332
- setIsTTY(true);
333
- const api = mockWebsocketAPIs();
334
- await runWrangler("tail test-worker");
335
-
336
- const event = generateMockRequestEvent();
337
- const message = generateMockEventMessage({ event });
338
- const serializedMessage = serialize(message);
339
-
340
- api.ws.send(serializedMessage);
341
- expect(
342
- std.out
343
- .replace(
344
- new Date(mockEventTimestamp).toLocaleString(),
345
- "[mock event timestamp]"
346
- )
347
- .replace(
348
- mockTailExpiration.toLocaleString(),
349
- "[mock expiration date]"
350
- )
351
- ).toMatchInlineSnapshot(`
352
- "Successfully created tail, expires at [mock expiration date]
353
- Connected to test-worker, waiting for logs...
354
- GET https://example.org/ - Ok @ [mock event timestamp]"
355
- `);
356
- });
357
-
358
- it("defaults to logging in json format when the output is not a TTY", async () => {
359
- setIsTTY(false);
360
-
361
- const api = mockWebsocketAPIs();
362
- await runWrangler("tail test-worker");
363
-
364
- const event = generateMockRequestEvent();
365
- const message = generateMockEventMessage({ event });
366
- const serializedMessage = serialize(message);
367
-
368
- api.ws.send(serializedMessage);
369
- expect(std.out).toMatch(deserializeToJson(serializedMessage));
370
- });
371
-
372
- it("logs console messages and exceptions", async () => {
373
- setIsTTY(true);
374
- const api = mockWebsocketAPIs();
375
- await runWrangler("tail test-worker");
376
-
377
- const event = generateMockRequestEvent();
378
- const message = generateMockEventMessage({
379
- event,
380
- logs: [
381
- { message: ["some string"], level: "log", timestamp: 1234561 },
382
- {
383
- message: [{ complex: "object" }],
384
- level: "log",
385
- timestamp: 1234562,
386
- },
387
- { message: [1234], level: "error", timestamp: 1234563 },
388
- ],
389
- exceptions: [
390
- { name: "Error", message: "some error", timestamp: 1234564 },
391
- { name: "Error", message: { complex: "error" }, timestamp: 1234564 },
392
- ],
393
- });
394
- const serializedMessage = serialize(message);
395
-
396
- api.ws.send(serializedMessage);
397
- expect(
398
- std.out
399
- .replace(
400
- new Date(mockEventTimestamp).toLocaleString(),
401
- "[mock event timestamp]"
402
- )
403
- .replace(
404
- mockTailExpiration.toLocaleString(),
405
- "[mock expiration date]"
406
- )
407
- ).toMatchInlineSnapshot(`
408
- "Successfully created tail, expires at [mock expiration date]
409
- Connected to test-worker, waiting for logs...
410
- GET https://example.org/ - Ok @ [mock event timestamp]
411
- (log) some string
412
- (log) { complex: 'object' }
413
- (error) 1234"
414
- `);
415
- expect(std.err).toMatchInlineSnapshot(`
416
- "X [ERROR]  Error: some error
417
-
418
-
419
- X [ERROR]  Error: { complex: 'error' }
420
-
421
- "
422
- `);
423
- expect(std.warn).toMatchInlineSnapshot(`""`);
424
- });
425
- });
426
- });
427
-
428
- /* helpers */
429
-
430
- /**
431
- * The built in serialize-to-JSON feature of our mock websocket doesn't work
432
- * for our use-case since we actually expect a raw buffer,
433
- * not a Javascript string. Additionally, we have to do some fiddling
434
- * with `RequestEvent`s to get them to serialize properly.
435
- *
436
- * @param message a message to serialize to JSON
437
- * @returns the same type we expect when deserializing in wrangler
438
- */
439
- function serialize(message: TailEventMessage): WebSocket.RawData {
440
- if (isScheduled(message.event)) {
441
- // `ScheduledEvent`s work just fine
442
- const stringified = JSON.stringify(message);
443
- return Buffer.from(stringified, "utf-8");
444
- } else {
445
- // Since the "properties" of an `undici.Request` are actually getters,
446
- // which don't serialize properly, we need to hydrate them manually.
447
- // This isn't a problem outside of testing since deserialization
448
- // works just fine and wrangler never _sends_ any event messages,
449
- // it only receives them.
450
- const request = ((message.event as RequestEvent | undefined | null) || {})
451
- .request;
452
- const stringified = JSON.stringify(message, (key, value) => {
453
- if (key !== "request") {
454
- return value;
455
- }
456
-
457
- return {
458
- ...request,
459
- url: request?.url,
460
- headers: request?.headers,
461
- method: request?.method,
462
- };
463
- });
464
-
465
- return Buffer.from(stringified, "utf-8");
466
- }
467
- }
468
-
469
- /**
470
- * Small helper to disambiguate the event types possible in a `TailEventMessage`
471
- *
472
- * @param event A TailEvent
473
- * @returns whether event is a ScheduledEvent (true) or a RequestEvent
474
- */
475
- function isScheduled(
476
- event: ScheduledEvent | RequestEvent | undefined | null
477
- ): event is ScheduledEvent {
478
- return Boolean(event && "cron" in event);
479
- }
480
-
481
- /**
482
- * Similarly, we need to deserialize from a raw buffer instead
483
- * of just JSON.parsing a raw string. This deserializer also then
484
- * re-stringifies with some spacing, the same way wrangler tail does.
485
- *
486
- * @param message a buffer of data received from the websocket
487
- * @returns a string ready to be printed to the terminal or compared against
488
- */
489
- function deserializeToJson(message: WebSocket.RawData): string {
490
- return JSON.stringify(JSON.parse(message.toString()), null, 2);
491
- }
492
-
493
- /**
494
- * A mock for all the different API resources wrangler accesses
495
- * when running `wrangler tail`
496
- */
497
- type MockAPI = {
498
- requests: {
499
- creation: RequestCounter;
500
- deletion: RequestCounter;
501
- };
502
- ws: MockWebSocket;
503
- nextMessageJson(): Promise<unknown>;
504
- };
505
-
506
- /**
507
- * A counter used to check how many times a mock API has been hit.
508
- * Useful as a helper in our testing to check if wrangler is making
509
- * the correct API calls without actually sending any web traffic
510
- */
511
- type RequestCounter = {
512
- count: number;
513
- };
514
-
515
- /**
516
- * Mock out the API hit during Tail creation
517
- *
518
- * @param websocketURL a fake URL for wrangler to connect a websocket to
519
- * @returns a `RequestCounter` for counting how many times the API is hit
520
- */
521
- function mockCreateTailRequest(
522
- websocketURL: string,
523
- env?: string,
524
- legacyEnv = false
525
- ): RequestCounter {
526
- const requests = { count: 0 };
527
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
528
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
529
- setMockResponse(
530
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails`,
531
- "POST",
532
- ([_url, accountId, scriptName, envName]) => {
533
- requests.count++;
534
- expect(accountId).toEqual("some-account-id");
535
- expect(scriptName).toEqual(
536
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
537
- );
538
- if (!legacyEnv) {
539
- expect(envName).toEqual(env);
540
- }
541
- return {
542
- id: "tail-id",
543
- url: websocketURL,
544
- expires_at: mockTailExpiration,
545
- };
546
- }
547
- );
548
-
549
- return requests;
550
- }
551
-
552
- /**
553
- * Mock expiration datetime for tails created during testing
554
- */
555
- const mockTailExpiration = new Date(3005, 1);
556
-
557
- /**
558
- * Default value for event timestamps
559
- */
560
- const mockEventTimestamp = 1645454470467;
561
-
562
- /**
563
- * Mock out the API hit during Tail deletion
564
- *
565
- * @returns a `RequestCounter` for counting how many times the API is hit
566
- */
567
- function mockDeleteTailRequest(
568
- env?: string,
569
- legacyEnv = false
570
- ): RequestCounter {
571
- const requests = { count: 0 };
572
- const servicesOrScripts = env && !legacyEnv ? "services" : "scripts";
573
- const environment = env && !legacyEnv ? "/environments/:envName" : "";
574
- setMockResponse(
575
- // "/accounts/:accountId/workers/scripts/:worker/tails",
576
- `/accounts/:accountId/workers/${servicesOrScripts}/:scriptName${environment}/tails/:tailId`,
577
- "DELETE",
578
- ([_url, accountId, scriptName, envNameOrTailId, tailId]) => {
579
- requests.count++;
580
- expect(accountId).toEqual("some-account-id");
581
- expect(scriptName).toEqual(
582
- legacyEnv && env ? `test-worker-${env}` : "test-worker"
583
- );
584
- if (!legacyEnv) {
585
- if (env) {
586
- expect(envNameOrTailId).toEqual(env);
587
- expect(tailId).toEqual("tail-id");
588
- } else {
589
- expect(envNameOrTailId).toEqual("tail-id");
590
- }
591
- } else {
592
- expect(envNameOrTailId).toEqual("tail-id");
593
- }
594
- return null;
595
- }
596
- );
597
-
598
- return requests;
599
- }
600
-
601
- const mockWebSockets: MockWebSocket[] = [];
602
-
603
- /**
604
- * All-in-one convenience method to mock the appropriate API calls before
605
- * each test, and clean up afterwards.
606
- *
607
- * @param websocketURL a fake websocket URL for wrangler to connect to
608
- * @returns a mocked-out version of the API
609
- */
610
- function mockWebsocketAPIs(env?: string, legacyEnv = false): MockAPI {
611
- const websocketURL = "ws://localhost:1234";
612
- const api: MockAPI = {
613
- requests: {
614
- deletion: { count: 0 },
615
- creation: { count: 0 },
616
- },
617
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
618
- ws: null!, // will be set in the `beforeEach()` below.
619
-
620
- /**
621
- * Parse the next message received by the mock websocket as JSON
622
- * @returns JSON.parse of the next message received by the websocket
623
- */
624
- async nextMessageJson() {
625
- const message = await api.ws.nextMessage;
626
- return JSON.parse(message as string);
627
- },
628
- };
629
- api.requests.creation = mockCreateTailRequest(websocketURL, env, legacyEnv);
630
- api.requests.deletion = mockDeleteTailRequest(env, legacyEnv);
631
- api.ws = new MockWebSocket(websocketURL);
632
- mockWebSockets.push(api.ws);
633
-
634
- return api;
635
- }
636
-
637
- /**
638
- * Generate a mock `TailEventMessage` of the same shape sent back by the
639
- * tail worker.
640
- *
641
- * @param opts Any specific parts of the message to use instead of defaults
642
- * @returns a `TailEventMessage` that wrangler can process and display
643
- */
644
- function generateMockEventMessage({
645
- outcome = "ok",
646
- exceptions = [],
647
- logs = [],
648
- eventTimestamp = mockEventTimestamp,
649
- event = generateMockRequestEvent(),
650
- }: Partial<TailEventMessage>): TailEventMessage {
651
- return {
652
- outcome,
653
- exceptions,
654
- logs,
655
- eventTimestamp,
656
- event,
657
- };
658
- }
659
-
660
- /**
661
- * Generate a mock `RequestEvent` that, in an alternate timeline, was used
662
- * to trigger a worker. You can't disprove this!
663
- *
664
- * @param opts Any specific parts of the event to use instead of defaults
665
- * @returns a `RequestEvent` that can be used within an `EventMessage`
666
- */
667
- function generateMockRequestEvent(
668
- opts?: Partial<RequestEvent["request"]>
669
- ): RequestEvent {
670
- return {
671
- request: Object.assign(
672
- new Request(opts?.url || "https://example.org/", {
673
- method: opts?.method || "GET",
674
- headers:
675
- opts?.headers || new Headers({ "X-EXAMPLE-HEADER": "some_value" }),
676
- }),
677
- {
678
- cf: opts?.cf || {
679
- tlsCipher: "AEAD-ENCRYPT-O-MATIC-SHA",
680
- tlsVersion: "TLSv2.0",
681
- asn: 42069,
682
- colo: "ATL",
683
- httpProtocol: "HTTP/4",
684
- asOrganization: "Cloudflare",
685
- },
686
- }
687
- ),
688
- };
689
- }
690
-
691
- function generateMockScheduledEvent(
692
- opts?: Partial<ScheduledEvent>
693
- ): ScheduledEvent {
694
- return {
695
- cron: opts?.cron || "* * * * *",
696
- scheduledTime: opts?.scheduledTime || mockEventTimestamp,
697
- };
698
- }