wrangler 0.0.0-e60dc909 → 0.0.0-e61dba50

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