wrangler 0.0.0-e9ab55a → 0.0.0-e9e9872

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 (201) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +126 -25
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4894 -0
  6. package/package.json +159 -125
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3946 -0
  10. package/src/__tests__/dev.test.tsx +1155 -63
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  13. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +74 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +163 -0
  31. package/src/__tests__/index.test.ts +259 -284
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +108 -10
  34. package/src/__tests__/kv.test.ts +1433 -909
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1254 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6586 -93
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +492 -0
  44. package/src/__tests__/tail.test.ts +698 -0
  45. package/src/__tests__/user.test.ts +143 -0
  46. package/src/__tests__/whoami.test.tsx +230 -0
  47. package/src/__tests__/worker-namespace.test.ts +327 -0
  48. package/src/abort.d.ts +3 -0
  49. package/src/api/dev.ts +52 -0
  50. package/src/api/index.ts +1 -0
  51. package/src/bundle-reporter.tsx +29 -0
  52. package/src/bundle.ts +212 -0
  53. package/src/cfetch/index.ts +88 -69
  54. package/src/cfetch/internal.ts +124 -44
  55. package/src/cli.ts +24 -6
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +243 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +453 -0
  60. package/src/config/index.ts +238 -0
  61. package/src/config/validation-helpers.ts +584 -0
  62. package/src/config/validation.ts +1745 -0
  63. package/src/config-cache.ts +83 -0
  64. package/src/create-worker-preview.ts +255 -0
  65. package/src/create-worker-upload-form.ts +263 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +417 -0
  68. package/src/dev/local.tsx +354 -0
  69. package/src/dev/remote.tsx +382 -0
  70. package/src/dev/use-esbuild.ts +150 -0
  71. package/src/dev.tsx +527 -773
  72. package/src/dialogs.tsx +117 -59
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +328 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/faye-websocket.d.ts +6 -0
  78. package/src/generate.ts +33 -0
  79. package/src/git-client.ts +42 -0
  80. package/src/global-wrangler-config-path.ts +26 -0
  81. package/src/https-options.ts +127 -0
  82. package/src/index.tsx +1869 -1901
  83. package/src/init.ts +549 -0
  84. package/src/inspect.ts +615 -496
  85. package/src/intl-polyfill.d.ts +139 -0
  86. package/src/is-interactive.ts +12 -0
  87. package/src/kv.ts +430 -0
  88. package/src/logger.ts +73 -0
  89. package/src/miniflare-cli/README.md +30 -0
  90. package/src/miniflare-cli/enum-keys.ts +17 -0
  91. package/src/miniflare-cli/index.ts +53 -0
  92. package/src/miniflare-cli/request-context.ts +40 -0
  93. package/src/module-collection.ts +247 -53
  94. package/src/open-in-browser.ts +17 -0
  95. package/src/package-manager.ts +219 -0
  96. package/src/pages/build.tsx +202 -0
  97. package/src/pages/constants.ts +7 -0
  98. package/src/pages/deployments.tsx +101 -0
  99. package/src/pages/dev.tsx +964 -0
  100. package/src/pages/functions/buildPlugin.ts +105 -0
  101. package/src/pages/functions/buildWorker.ts +151 -0
  102. package/src/pages/functions/filepath-routing.test.ts +234 -0
  103. package/src/pages/functions/filepath-routing.ts +189 -0
  104. package/src/pages/functions/identifiers.ts +78 -0
  105. package/src/pages/functions/routes.ts +151 -0
  106. package/src/pages/index.tsx +84 -0
  107. package/src/pages/projects.tsx +157 -0
  108. package/src/pages/publish.tsx +335 -0
  109. package/src/pages/types.ts +40 -0
  110. package/src/pages/upload.tsx +396 -0
  111. package/src/pages/utils.ts +12 -0
  112. package/src/parse.ts +286 -0
  113. package/src/paths.ts +26 -0
  114. package/src/preview.ts +31 -0
  115. package/src/proxy.ts +428 -254
  116. package/src/publish.ts +764 -366
  117. package/src/pubsub/index.ts +286 -0
  118. package/src/pubsub/pubsub-commands.tsx +577 -0
  119. package/src/r2.ts +50 -0
  120. package/src/selfsigned.d.ts +29 -0
  121. package/src/sites.tsx +357 -103
  122. package/src/tail/filters.ts +279 -0
  123. package/src/tail/index.ts +299 -0
  124. package/src/tail/printing.ts +67 -0
  125. package/src/update-check.ts +19 -0
  126. package/src/user/choose-account.tsx +60 -0
  127. package/src/user/env-vars.ts +46 -0
  128. package/src/user/generate-auth-url.ts +33 -0
  129. package/src/user/generate-random-state.ts +16 -0
  130. package/src/user/index.ts +3 -0
  131. package/src/user/user.tsx +1170 -0
  132. package/src/whoami.tsx +90 -0
  133. package/src/worker-namespace.ts +190 -0
  134. package/src/worker.ts +191 -0
  135. package/src/zones.ts +76 -0
  136. package/templates/checked-fetch.js +17 -0
  137. package/templates/gitignore +171 -0
  138. package/templates/new-worker-scheduled.js +17 -0
  139. package/templates/new-worker-scheduled.ts +32 -0
  140. package/templates/new-worker.js +15 -0
  141. package/templates/new-worker.ts +30 -0
  142. package/templates/no-op-worker.js +10 -0
  143. package/templates/pages-template-plugin.ts +155 -0
  144. package/templates/pages-template-worker.ts +161 -0
  145. package/templates/static-asset-facade.js +49 -0
  146. package/templates/tsconfig.json +105 -0
  147. package/wrangler-dist/cli.d.ts +298 -0
  148. package/wrangler-dist/cli.js +107673 -103262
  149. package/pages/functions/buildWorker.ts +0 -62
  150. package/pages/functions/filepath-routing.test.ts +0 -39
  151. package/pages/functions/filepath-routing.ts +0 -228
  152. package/pages/functions/identifiers.ts +0 -78
  153. package/pages/functions/routes.ts +0 -158
  154. package/pages/functions/template-worker.ts +0 -136
  155. package/src/__tests__/mock-cfetch.ts +0 -171
  156. package/src/__tests__/mock-dialogs.ts +0 -65
  157. package/src/__tests__/run-in-tmp.ts +0 -19
  158. package/src/__tests__/run-wrangler.ts +0 -32
  159. package/src/api/form_data.ts +0 -131
  160. package/src/api/preview.ts +0 -128
  161. package/src/api/worker.ts +0 -155
  162. package/src/config.ts +0 -646
  163. package/src/kv.tsx +0 -276
  164. package/src/pages.tsx +0 -1040
  165. package/src/tail.tsx +0 -73
  166. package/src/user.tsx +0 -1027
  167. package/static-asset-facade.js +0 -47
  168. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  169. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  170. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  171. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  172. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  173. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  174. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  175. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  176. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  177. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  178. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  179. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  180. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  181. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  182. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  183. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  184. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  185. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  186. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  187. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  188. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  189. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  190. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  191. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  192. package/vendor/wrangler-mime/LICENSE +0 -21
  193. package/vendor/wrangler-mime/Mime.js +0 -97
  194. package/vendor/wrangler-mime/README.md +0 -187
  195. package/vendor/wrangler-mime/cli.js +0 -46
  196. package/vendor/wrangler-mime/index.js +0 -4
  197. package/vendor/wrangler-mime/lite.js +0 -4
  198. package/vendor/wrangler-mime/package.json +0 -52
  199. package/vendor/wrangler-mime/types/other.js +0 -1
  200. package/vendor/wrangler-mime/types/standard.js +0 -1
  201. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,698 @@
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
+ }