wrangler 0.0.0-e41c7e41 → 0.0.0-e44afaf79

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