wrangler 0.0.0-e1c2f5b9 → 0.0.0-e1d50407

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 (287) hide show
  1. package/README.md +12 -14
  2. package/bin/wrangler.js +14 -75
  3. package/package.json +213 -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.ts +1 -1
  9. package/templates/middleware/common.ts +9 -4
  10. package/templates/middleware/loader-modules.ts +64 -9
  11. package/templates/middleware/loader-sw.ts +2 -7
  12. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  13. package/templates/middleware/middleware-miniflare3-json-error.ts +18 -5
  14. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  15. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  16. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  17. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  18. package/templates/modules-watch-stub.js +4 -0
  19. package/templates/new-worker-scheduled.ts +1 -1
  20. package/templates/new-worker.ts +4 -1
  21. package/templates/pages-dev-util.ts +4 -1
  22. package/templates/pages-shim.ts +0 -3
  23. package/templates/pages-template-plugin.ts +30 -11
  24. package/templates/pages-template-worker.ts +11 -2
  25. package/templates/startDevWorker/InspectorProxyWorker.ts +652 -0
  26. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  27. package/templates/tsconfig.init.json +1 -2
  28. package/templates/tsconfig.json +1 -1
  29. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  30. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  31. package/wrangler-dist/ProxyWorker.js +186 -0
  32. package/wrangler-dist/ProxyWorker.js.map +6 -0
  33. package/wrangler-dist/cli.d.ts +23110 -509
  34. package/wrangler-dist/cli.js +133619 -137696
  35. package/wrangler-dist/wasm-sync.wasm +0 -0
  36. package/import_meta_url.js +0 -3
  37. package/miniflare-config-stubs/.env.empty +0 -0
  38. package/miniflare-config-stubs/package.empty.json +0 -1
  39. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  40. package/miniflare-dist/index.mjs +0 -6364
  41. package/src/__tests__/access.test.ts +0 -25
  42. package/src/__tests__/api-dev.test.ts +0 -238
  43. package/src/__tests__/api-devregistry.test.js +0 -64
  44. package/src/__tests__/api.test.ts +0 -80
  45. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  46. package/src/__tests__/config-cache.test.ts +0 -42
  47. package/src/__tests__/configuration.test.ts +0 -4163
  48. package/src/__tests__/d1.test.ts +0 -123
  49. package/src/__tests__/delete.test.ts +0 -263
  50. package/src/__tests__/deployments.test.ts +0 -105
  51. package/src/__tests__/dev.test.tsx +0 -1586
  52. package/src/__tests__/dialogs.test.tsx +0 -40
  53. package/src/__tests__/generate.test.ts +0 -235
  54. package/src/__tests__/get-host-from-url.test.ts +0 -16
  55. package/src/__tests__/guess-worker-format.test.ts +0 -85
  56. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  57. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  58. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  59. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  60. package/src/__tests__/helpers/mock-bin.ts +0 -36
  61. package/src/__tests__/helpers/mock-cfetch.ts +0 -277
  62. package/src/__tests__/helpers/mock-console.ts +0 -106
  63. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  64. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  68. package/src/__tests__/helpers/mock-kv.ts +0 -33
  69. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -271
  70. package/src/__tests__/helpers/mock-process.ts +0 -34
  71. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  72. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  73. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  74. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  75. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  76. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  77. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  78. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  79. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  80. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  81. package/src/__tests__/helpers/msw/index.ts +0 -21
  82. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  83. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  84. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  85. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  86. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  87. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  88. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  89. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  90. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  91. package/src/__tests__/https-options.test.ts +0 -163
  92. package/src/__tests__/index.test.ts +0 -268
  93. package/src/__tests__/init.test.ts +0 -3094
  94. package/src/__tests__/jest.setup.ts +0 -203
  95. package/src/__tests__/kv.test.ts +0 -1786
  96. package/src/__tests__/logger.test.ts +0 -141
  97. package/src/__tests__/logout.test.ts +0 -47
  98. package/src/__tests__/metrics.test.ts +0 -495
  99. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  100. package/src/__tests__/middleware.test.ts +0 -750
  101. package/src/__tests__/package-manager.test.ts +0 -353
  102. package/src/__tests__/pages-deployment-tail.test.ts +0 -884
  103. package/src/__tests__/pages.test.ts +0 -2443
  104. package/src/__tests__/parse.test.ts +0 -330
  105. package/src/__tests__/paths.test.ts +0 -39
  106. package/src/__tests__/publish.test.ts +0 -7757
  107. package/src/__tests__/pubsub.test.ts +0 -490
  108. package/src/__tests__/queues.test.ts +0 -522
  109. package/src/__tests__/r2.test.ts +0 -393
  110. package/src/__tests__/route.test.ts +0 -45
  111. package/src/__tests__/secret.test.ts +0 -694
  112. package/src/__tests__/tail.test.ts +0 -899
  113. package/src/__tests__/test-old-node-version.js +0 -31
  114. package/src/__tests__/tsconfig-sanity.ts +0 -12
  115. package/src/__tests__/tsconfig.json +0 -8
  116. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  117. package/src/__tests__/type-generation.test.ts +0 -233
  118. package/src/__tests__/user.test.ts +0 -129
  119. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  120. package/src/__tests__/validate-dev-props.test.ts +0 -56
  121. package/src/__tests__/version.test.ts +0 -35
  122. package/src/__tests__/whoami.test.tsx +0 -278
  123. package/src/__tests__/worker-namespace.test.ts +0 -326
  124. package/src/abort.d.ts +0 -3
  125. package/src/api/dev.ts +0 -218
  126. package/src/api/index.ts +0 -2
  127. package/src/bundle-reporter.tsx +0 -68
  128. package/src/bundle.ts +0 -823
  129. package/src/cfetch/index.ts +0 -158
  130. package/src/cfetch/internal.ts +0 -261
  131. package/src/cli.ts +0 -28
  132. package/src/config/README.md +0 -107
  133. package/src/config/config.ts +0 -275
  134. package/src/config/diagnostics.ts +0 -80
  135. package/src/config/environment.ts +0 -577
  136. package/src/config/index.ts +0 -358
  137. package/src/config/validation-helpers.ts +0 -597
  138. package/src/config/validation.ts +0 -2151
  139. package/src/config-cache.ts +0 -85
  140. package/src/create-worker-preview.ts +0 -282
  141. package/src/create-worker-upload-form.ts +0 -325
  142. package/src/d1/backups.tsx +0 -223
  143. package/src/d1/constants.ts +0 -2
  144. package/src/d1/create.tsx +0 -63
  145. package/src/d1/delete.tsx +0 -56
  146. package/src/d1/execute.tsx +0 -352
  147. package/src/d1/formatTimeAgo.ts +0 -14
  148. package/src/d1/index.ts +0 -101
  149. package/src/d1/list.tsx +0 -48
  150. package/src/d1/migrations/apply.tsx +0 -196
  151. package/src/d1/migrations/create.tsx +0 -77
  152. package/src/d1/migrations/helpers.ts +0 -147
  153. package/src/d1/migrations/index.tsx +0 -3
  154. package/src/d1/migrations/list.tsx +0 -79
  155. package/src/d1/migrations/options.ts +0 -18
  156. package/src/d1/options.ts +0 -22
  157. package/src/d1/types.tsx +0 -24
  158. package/src/d1/utils.ts +0 -48
  159. package/src/delete.ts +0 -108
  160. package/src/deployments.ts +0 -83
  161. package/src/deprecated/index.ts +0 -145
  162. package/src/dev/dev-vars.ts +0 -39
  163. package/src/dev/dev.tsx +0 -614
  164. package/src/dev/get-local-persistence-path.tsx +0 -31
  165. package/src/dev/local.tsx +0 -932
  166. package/src/dev/remote.tsx +0 -603
  167. package/src/dev/start-server.ts +0 -543
  168. package/src/dev/use-esbuild.ts +0 -204
  169. package/src/dev/validate-dev-props.ts +0 -31
  170. package/src/dev-registry.tsx +0 -201
  171. package/src/dev.tsx +0 -949
  172. package/src/dialogs.tsx +0 -168
  173. package/src/dispatch-namespace.ts +0 -207
  174. package/src/docs/index.ts +0 -97
  175. package/src/durable.ts +0 -102
  176. package/src/entry.ts +0 -329
  177. package/src/environment-variables/factory.ts +0 -88
  178. package/src/environment-variables/misc-variables.ts +0 -30
  179. package/src/errors.ts +0 -11
  180. package/src/generate/index.ts +0 -300
  181. package/src/git-client.ts +0 -135
  182. package/src/global-wrangler-config-path.ts +0 -26
  183. package/src/https-options.ts +0 -127
  184. package/src/index.tsx +0 -694
  185. package/src/init.ts +0 -1025
  186. package/src/inspect.ts +0 -767
  187. package/src/intl-polyfill.d.ts +0 -139
  188. package/src/is-ci.ts +0 -14
  189. package/src/is-interactive.ts +0 -16
  190. package/src/jest.d.ts +0 -4
  191. package/src/kv/helpers.ts +0 -430
  192. package/src/kv/index.ts +0 -596
  193. package/src/logger.ts +0 -92
  194. package/src/metrics/index.ts +0 -5
  195. package/src/metrics/metrics-config.ts +0 -239
  196. package/src/metrics/metrics-dispatcher.ts +0 -96
  197. package/src/metrics/metrics-usage-headers.ts +0 -24
  198. package/src/metrics/send-event.ts +0 -97
  199. package/src/miniflare-cli/README.md +0 -30
  200. package/src/miniflare-cli/assets.ts +0 -250
  201. package/src/miniflare-cli/index.ts +0 -210
  202. package/src/miniflare-cli/request-context.ts +0 -40
  203. package/src/miniflare-cli/tsconfig.json +0 -9
  204. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  205. package/src/miniflare-cli/types.ts +0 -11
  206. package/src/module-collection.ts +0 -267
  207. package/src/open-in-browser.ts +0 -17
  208. package/src/package-manager.ts +0 -219
  209. package/src/pages/build.tsx +0 -270
  210. package/src/pages/constants.ts +0 -18
  211. package/src/pages/deployment-tails.tsx +0 -284
  212. package/src/pages/deployments.tsx +0 -84
  213. package/src/pages/dev.tsx +0 -710
  214. package/src/pages/errors.ts +0 -66
  215. package/src/pages/functions/buildPlugin.ts +0 -107
  216. package/src/pages/functions/buildWorker.ts +0 -166
  217. package/src/pages/functions/filepath-routing.test.ts +0 -234
  218. package/src/pages/functions/filepath-routing.ts +0 -189
  219. package/src/pages/functions/identifiers.ts +0 -78
  220. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  221. package/src/pages/functions/routes-consolidation.ts +0 -73
  222. package/src/pages/functions/routes-transformation.test.ts +0 -282
  223. package/src/pages/functions/routes-transformation.ts +0 -115
  224. package/src/pages/functions/routes-validation.test.ts +0 -403
  225. package/src/pages/functions/routes-validation.ts +0 -202
  226. package/src/pages/functions/routes.ts +0 -151
  227. package/src/pages/functions/tsconfig.json +0 -8
  228. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  229. package/src/pages/functions.tsx +0 -82
  230. package/src/pages/hash.tsx +0 -13
  231. package/src/pages/index.tsx +0 -102
  232. package/src/pages/projects.tsx +0 -169
  233. package/src/pages/prompt-select-project.tsx +0 -31
  234. package/src/pages/publish.tsx +0 -461
  235. package/src/pages/types.ts +0 -41
  236. package/src/pages/upload.tsx +0 -447
  237. package/src/pages/utils.ts +0 -23
  238. package/src/parse.ts +0 -286
  239. package/src/paths.ts +0 -71
  240. package/src/proxy.ts +0 -694
  241. package/src/publish/index.ts +0 -270
  242. package/src/publish/publish.ts +0 -1036
  243. package/src/pubsub/index.ts +0 -286
  244. package/src/pubsub/pubsub-commands.tsx +0 -624
  245. package/src/queues/cli/commands/consumer/add.ts +0 -71
  246. package/src/queues/cli/commands/consumer/index.ts +0 -22
  247. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  248. package/src/queues/cli/commands/create.ts +0 -25
  249. package/src/queues/cli/commands/delete.ts +0 -26
  250. package/src/queues/cli/commands/index.ts +0 -36
  251. package/src/queues/cli/commands/list.ts +0 -25
  252. package/src/queues/client.ts +0 -135
  253. package/src/queues/utils.ts +0 -18
  254. package/src/r2/constants.ts +0 -4
  255. package/src/r2/helpers.ts +0 -131
  256. package/src/r2/index.ts +0 -289
  257. package/src/routes.ts +0 -140
  258. package/src/secret/index.ts +0 -379
  259. package/src/selfsigned.d.ts +0 -29
  260. package/src/sites.tsx +0 -372
  261. package/src/tail/createTail.ts +0 -379
  262. package/src/tail/filters.ts +0 -277
  263. package/src/tail/index.ts +0 -214
  264. package/src/tail/printing.ts +0 -107
  265. package/src/tsconfig-sanity.ts +0 -16
  266. package/src/type-generation.ts +0 -181
  267. package/src/update-check.ts +0 -19
  268. package/src/user/access.ts +0 -68
  269. package/src/user/auth-variables.ts +0 -113
  270. package/src/user/choose-account.tsx +0 -69
  271. package/src/user/generate-auth-url.ts +0 -33
  272. package/src/user/generate-random-state.ts +0 -16
  273. package/src/user/index.ts +0 -2
  274. package/src/user/user.tsx +0 -1238
  275. package/src/utils/collectKeyValues.ts +0 -14
  276. package/src/whoami.tsx +0 -169
  277. package/src/worker.ts +0 -251
  278. package/src/yargs-types.ts +0 -24
  279. package/src/zones.ts +0 -191
  280. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  281. package/templates/d1-beta-facade.js +0 -205
  282. package/templates/first-party-worker-module-facade.ts +0 -19
  283. package/templates/format-dev-errors.ts +0 -33
  284. package/templates/serve-static-assets.ts +0 -65
  285. package/templates/service-bindings-module-facade.js +0 -54
  286. package/templates/service-bindings-sw-facade.js +0 -42
  287. package/templates/tsconfig.tsbuildinfo +0 -1
@@ -1,141 +0,0 @@
1
- import { logger } from "../logger";
2
- import { mockConsoleMethods } from "./helpers/mock-console";
3
-
4
- describe("logger", () => {
5
- const std = mockConsoleMethods();
6
-
7
- it("should add colored markers to error and warning messages", () => {
8
- logger.loggerLevel = "debug";
9
- logger.debug("This is a debug message");
10
- logger.log("This is a log message");
11
- logger.warn("This is a warn message");
12
- logger.error("This is a error message");
13
-
14
- expect(std.debug).toMatchInlineSnapshot(`"This is a debug message"`);
15
- expect(std.out).toMatchInlineSnapshot(`"This is a log message"`);
16
- expect(std.warn).toMatchInlineSnapshot(`
17
- "▲ [WARNING] This is a warn message
18
-
19
- "
20
- `);
21
- expect(std.err).toMatchInlineSnapshot(`
22
- "X [ERROR] This is a error message
23
-
24
- "
25
- `);
26
- });
27
-
28
- describe("loggerLevel=debug", () => {
29
- it("should render messages that are at or above the log level set in the logger", () => {
30
- logger.loggerLevel = "debug";
31
- logger.debug("This is a debug message");
32
- logger.log("This is a log message");
33
- logger.warn("This is a warn message");
34
- logger.error("This is a error message");
35
-
36
- expect(std.debug).toMatchInlineSnapshot(`"This is a debug message"`);
37
- expect(std.out).toMatchInlineSnapshot(`"This is a log message"`);
38
- expect(std.warn).toMatchInlineSnapshot(`
39
- "▲ [WARNING] This is a warn message
40
-
41
- "
42
- `);
43
- expect(std.err).toMatchInlineSnapshot(`
44
- "X [ERROR] This is a error message
45
-
46
- "
47
- `);
48
- });
49
- });
50
-
51
- describe("loggerLevel=log", () => {
52
- it("should render messages that are at or above the log level set in the logger", () => {
53
- logger.loggerLevel = "log";
54
- logger.debug("This is a debug message");
55
- logger.log("This is a log message");
56
- logger.warn("This is a warn message");
57
- logger.error("This is a error message");
58
-
59
- expect(std.debug).toMatchInlineSnapshot(`""`);
60
- expect(std.out).toMatchInlineSnapshot(`"This is a log message"`);
61
- expect(std.warn).toMatchInlineSnapshot(`
62
- "▲ [WARNING] This is a warn message
63
-
64
- "
65
- `);
66
- expect(std.err).toMatchInlineSnapshot(`
67
- "X [ERROR] This is a error message
68
-
69
- "
70
- `);
71
- });
72
- });
73
-
74
- describe("loggerLevel=warn", () => {
75
- it("should render messages that are at or above the log level set in the logger", () => {
76
- logger.loggerLevel = "warn";
77
- logger.debug("This is a debug message");
78
- logger.log("This is a log message");
79
- logger.warn("This is a warn message");
80
- logger.error("This is a error message");
81
-
82
- expect(std.debug).toMatchInlineSnapshot(`""`);
83
- expect(std.out).toMatchInlineSnapshot(`""`);
84
- expect(std.warn).toMatchInlineSnapshot(`
85
- "▲ [WARNING] This is a warn message
86
-
87
- "
88
- `);
89
- expect(std.err).toMatchInlineSnapshot(`
90
- "X [ERROR] This is a error message
91
-
92
- "
93
- `);
94
- });
95
- });
96
-
97
- describe("loggerLevel=error", () => {
98
- it("should render messages that are at or above the log level set in the logger", () => {
99
- logger.loggerLevel = "error";
100
- logger.debug("This is a debug message");
101
- logger.log("This is a log message");
102
- logger.warn("This is a warn message");
103
- logger.error("This is a error message");
104
-
105
- expect(std.debug).toMatchInlineSnapshot(`""`);
106
- expect(std.out).toMatchInlineSnapshot(`""`);
107
- expect(std.warn).toMatchInlineSnapshot(`""`);
108
- expect(std.err).toMatchInlineSnapshot(`
109
- "X [ERROR] This is a error message
110
-
111
- "
112
- `);
113
- });
114
- });
115
-
116
- describe("loggerLevelFromEnvVar=error", () => {
117
- beforeEach(() => {
118
- process.env.WRANGLER_LOG = "error";
119
- });
120
- afterEach(() => {
121
- process.env.WRANGLER_LOG = undefined;
122
- });
123
-
124
- it("should render messages that are at or above the log level set in the env var", () => {
125
- logger.loggerLevel = "error";
126
- logger.debug("This is a debug message");
127
- logger.log("This is a log message");
128
- logger.warn("This is a warn message");
129
- logger.error("This is a error message");
130
-
131
- expect(std.debug).toMatchInlineSnapshot(`""`);
132
- expect(std.out).toMatchInlineSnapshot(`""`);
133
- expect(std.warn).toMatchInlineSnapshot(`""`);
134
- expect(std.err).toMatchInlineSnapshot(`
135
- "X [ERROR] This is a error message
136
-
137
- "
138
- `);
139
- });
140
- });
141
- });
@@ -1,47 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { rest } from "msw";
4
- import { getGlobalWranglerConfigPath } from "../global-wrangler-config-path";
5
- import { USER_AUTH_CONFIG_FILE, writeAuthConfigFile } from "../user";
6
- import { mockConsoleMethods } from "./helpers/mock-console";
7
- import { msw } from "./helpers/msw";
8
- import { runInTempDir } from "./helpers/run-in-tmp";
9
- import { runWrangler } from "./helpers/run-wrangler";
10
-
11
- describe("logout", () => {
12
- runInTempDir();
13
- const std = mockConsoleMethods();
14
-
15
- it("should exit with a message stating the user is not logged in", async () => {
16
- await runWrangler("logout");
17
- expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
18
- });
19
-
20
- it("should logout user that has been properly logged in", async () => {
21
- writeAuthConfigFile({
22
- oauth_token: "some-oauth-tok",
23
- refresh_token: "some-refresh-tok",
24
- });
25
- // Make sure that logout removed the config file containing the auth tokens.
26
- const config = path.join(
27
- getGlobalWranglerConfigPath(),
28
- USER_AUTH_CONFIG_FILE
29
- );
30
- let counter = 0;
31
- msw.use(
32
- rest.post("*/oauth2/revoke", (_, response, context) => {
33
- // Make sure that we made the request to logout.
34
- counter += 1;
35
- return response.once(context.status(200), context.text(""));
36
- })
37
- );
38
-
39
- expect(fs.existsSync(config)).toBeTruthy();
40
-
41
- await runWrangler("logout");
42
-
43
- expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
44
- expect(fs.existsSync(config)).toBeFalsy();
45
- expect(counter).toBe(1);
46
- });
47
- });
@@ -1,495 +0,0 @@
1
- import { mkdirSync } from "node:fs";
2
- import { rest } from "msw";
3
- import { version as wranglerVersion } from "../../package.json";
4
- import { purgeConfigCaches, saveToConfigCache } from "../config-cache";
5
- import { CI } from "../is-ci";
6
- import { logger } from "../logger";
7
- import { getMetricsDispatcher, getMetricsConfig } from "../metrics";
8
- import {
9
- CURRENT_METRICS_DATE,
10
- readMetricsConfig,
11
- USER_ID_CACHE_PATH,
12
- writeMetricsConfig,
13
- } from "../metrics/metrics-config";
14
- import { writeAuthConfigFile } from "../user";
15
- import { mockConsoleMethods } from "./helpers/mock-console";
16
- import { mockConfirm } from "./helpers/mock-dialogs";
17
- import { useMockIsTTY } from "./helpers/mock-istty";
18
- import { msw, mswSuccessOauthHandlers } from "./helpers/msw";
19
- import { runInTempDir } from "./helpers/run-in-tmp";
20
-
21
- declare const global: { SPARROW_SOURCE_KEY: string | undefined };
22
-
23
- describe("metrics", () => {
24
- const ORIGINAL_SPARROW_SOURCE_KEY = global.SPARROW_SOURCE_KEY;
25
- const std = mockConsoleMethods();
26
- runInTempDir();
27
-
28
- beforeEach(() => {
29
- // Tell jest to use the original version of the `getMetricsConfig()` function in these tests.
30
- const mockMetricsConfig = jest.requireMock("../metrics/metrics-config");
31
- mockMetricsConfig.useOriginal = true;
32
- global.SPARROW_SOURCE_KEY = "MOCK_KEY";
33
- logger.loggerLevel = "debug";
34
- // Create a node_modules directory to store config-cache files
35
- mkdirSync("node_modules");
36
- });
37
- afterEach(() => {
38
- global.SPARROW_SOURCE_KEY = ORIGINAL_SPARROW_SOURCE_KEY;
39
- purgeConfigCaches();
40
- });
41
-
42
- describe("getMetricsDispatcher()", () => {
43
- const MOCK_DISPATCHER_OPTIONS = {
44
- // By setting this to true we avoid the `getMetricsConfig()` logic in these tests.
45
- sendMetrics: true,
46
- offline: false,
47
- };
48
-
49
- // These tests should never hit the `/user` API endpoint.
50
- const userRequests = mockUserRequest();
51
- afterEach(() => {
52
- expect(userRequests.count).toBe(0);
53
- });
54
-
55
- describe("identify()", () => {
56
- it("should send a request to the default URL", async () => {
57
- const request = mockMetricRequest(
58
- {
59
- event: "identify",
60
- properties: {
61
- category: "Workers",
62
- wranglerVersion,
63
- os: process.platform + ":" + process.arch,
64
- a: 1,
65
- b: 2,
66
- },
67
- },
68
- { "Sparrow-Source-Key": "MOCK_KEY" },
69
- "identify"
70
- );
71
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
72
- await dispatcher.identify({ a: 1, b: 2 });
73
-
74
- expect(request.count).toBe(1);
75
- expect(std.debug).toMatchInlineSnapshot(
76
- `"Metrics dispatcher: Posting data {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}"`
77
- );
78
- expect(std.out).toMatchInlineSnapshot(`""`);
79
- expect(std.warn).toMatchInlineSnapshot(`""`);
80
- expect(std.err).toMatchInlineSnapshot(`""`);
81
- });
82
-
83
- it("should write a debug log if the dispatcher is disabled", async () => {
84
- const requests = mockMetricRequest({}, {}, "identify");
85
- const dispatcher = await getMetricsDispatcher({
86
- ...MOCK_DISPATCHER_OPTIONS,
87
- sendMetrics: false,
88
- });
89
- await dispatcher.identify({ a: 1, b: 2 });
90
- await flushPromises();
91
-
92
- expect(requests.count).toBe(0);
93
- expect(std.debug).toMatchInlineSnapshot(
94
- `"Metrics dispatcher: Dispatching disabled - would have sent {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}."`
95
- );
96
- expect(std.out).toMatchInlineSnapshot(`""`);
97
- expect(std.warn).toMatchInlineSnapshot(`""`);
98
- expect(std.err).toMatchInlineSnapshot(`""`);
99
- });
100
-
101
- it("should write a debug log if the request fails", async () => {
102
- msw.use(
103
- rest.post("*/identify", async (req, res) => {
104
- return res.networkError("BAD REQUEST");
105
- })
106
- );
107
-
108
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
109
- await dispatcher.identify({ a: 1, b: 2 });
110
- await flushPromises();
111
- expect(std.debug).toMatchInlineSnapshot(`
112
- "Metrics dispatcher: Posting data {\\"type\\":\\"identify\\",\\"name\\":\\"identify\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}
113
- Metrics dispatcher: Failed to send request: request to https://sparrow.cloudflare.com/api/v1/identify failed, reason: BAD REQUEST"
114
- `);
115
- expect(std.out).toMatchInlineSnapshot(`""`);
116
- expect(std.warn).toMatchInlineSnapshot(`""`);
117
- expect(std.err).toMatchInlineSnapshot(`""`);
118
- });
119
-
120
- it("should write a warning log if no source key has been provided", async () => {
121
- global.SPARROW_SOURCE_KEY = undefined;
122
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
123
- await dispatcher.identify({ a: 1, b: 2 });
124
- expect(std.debug).toMatchInlineSnapshot(
125
- `"Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events. { type: 'identify', name: 'identify', properties: { a: 1, b: 2 } }"`
126
- );
127
- expect(std.out).toMatchInlineSnapshot(`""`);
128
- expect(std.warn).toMatchInlineSnapshot(`""`);
129
- expect(std.err).toMatchInlineSnapshot(`""`);
130
- });
131
- });
132
-
133
- describe("sendEvent()", () => {
134
- it("should send a request to the default URL", async () => {
135
- const requests = mockMetricRequest(
136
- {
137
- event: "some-event",
138
- properties: {
139
- category: "Workers",
140
- wranglerVersion,
141
- os: process.platform + ":" + process.arch,
142
- a: 1,
143
- b: 2,
144
- },
145
- },
146
- {
147
- "Sparrow-Source-Key": "MOCK_KEY",
148
- },
149
- "event"
150
- );
151
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
152
- await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
153
-
154
- expect(requests.count).toBe(1);
155
- expect(std.debug).toMatchInlineSnapshot(
156
- `"Metrics dispatcher: Posting data {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}"`
157
- );
158
- expect(std.out).toMatchInlineSnapshot(`""`);
159
- expect(std.warn).toMatchInlineSnapshot(`""`);
160
- expect(std.err).toMatchInlineSnapshot(`""`);
161
- });
162
-
163
- it("should write a debug log if the dispatcher is disabled", async () => {
164
- const requests = mockMetricRequest({}, {}, "event");
165
-
166
- const dispatcher = await getMetricsDispatcher({
167
- ...MOCK_DISPATCHER_OPTIONS,
168
- sendMetrics: false,
169
- });
170
- await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
171
- await flushPromises();
172
-
173
- expect(requests.count).toBe(0);
174
- expect(std.debug).toMatchInlineSnapshot(
175
- `"Metrics dispatcher: Dispatching disabled - would have sent {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}."`
176
- );
177
- expect(std.out).toMatchInlineSnapshot(`""`);
178
- expect(std.warn).toMatchInlineSnapshot(`""`);
179
- expect(std.err).toMatchInlineSnapshot(`""`);
180
- });
181
-
182
- it("should write a debug log if the request fails", async () => {
183
- msw.use(
184
- rest.post("*/event", async (_, res) => {
185
- return res.networkError("BAD REQUEST");
186
- })
187
- );
188
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
189
- await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
190
- await flushPromises();
191
- expect(std.debug).toMatchInlineSnapshot(`
192
- "Metrics dispatcher: Posting data {\\"type\\":\\"event\\",\\"name\\":\\"some-event\\",\\"properties\\":{\\"a\\":1,\\"b\\":2}}
193
- Metrics dispatcher: Failed to send request: request to https://sparrow.cloudflare.com/api/v1/event failed, reason: BAD REQUEST"
194
- `);
195
- expect(std.out).toMatchInlineSnapshot(`""`);
196
- expect(std.warn).toMatchInlineSnapshot(`""`);
197
- expect(std.err).toMatchInlineSnapshot(`""`);
198
- });
199
-
200
- it("should write a warning log if no source key has been provided", async () => {
201
- global.SPARROW_SOURCE_KEY = undefined;
202
- const requests = mockMetricRequest({}, {}, "event");
203
- const dispatcher = await getMetricsDispatcher(MOCK_DISPATCHER_OPTIONS);
204
- await dispatcher.sendEvent("some-event", { a: 1, b: 2 });
205
-
206
- expect(requests.count).toBe(0);
207
- expect(std.debug).toMatchInlineSnapshot(
208
- `"Metrics dispatcher: Source Key not provided. Be sure to initialize before sending events. { type: 'event', name: 'some-event', properties: { a: 1, b: 2 } }"`
209
- );
210
- expect(std.out).toMatchInlineSnapshot(`""`);
211
- expect(std.warn).toMatchInlineSnapshot(`""`);
212
- expect(std.err).toMatchInlineSnapshot(`""`);
213
- });
214
- });
215
- });
216
-
217
- describe("getMetricsConfig()", () => {
218
- let isCISpy: jest.SpyInstance;
219
-
220
- const { setIsTTY } = useMockIsTTY();
221
- beforeEach(() => {
222
- // Default the mock TTY to interactive for all these tests.
223
- setIsTTY(true);
224
- isCISpy = jest.spyOn(CI, "isCI").mockReturnValue(false);
225
- });
226
-
227
- describe("enabled", () => {
228
- const ORIGINAL_ENV = process.env;
229
- beforeEach(() => {
230
- process.env = { ...ORIGINAL_ENV };
231
- });
232
- afterEach(() => {
233
- process.env = ORIGINAL_ENV;
234
- });
235
-
236
- it("should return the WRANGLER_SEND_METRICS environment variable for enabled if it is defined", async () => {
237
- process.env.WRANGLER_SEND_METRICS = "false";
238
- expect(await getMetricsConfig({})).toMatchObject({
239
- enabled: false,
240
- });
241
- process.env.WRANGLER_SEND_METRICS = "true";
242
- expect(await getMetricsConfig({})).toMatchObject({
243
- enabled: true,
244
- });
245
- });
246
-
247
- it("should return false if running in a CI environment", async () => {
248
- isCISpy.mockReturnValue(true);
249
- expect(await getMetricsConfig({})).toMatchObject({
250
- enabled: false,
251
- });
252
- });
253
-
254
- it("should return the sendMetrics argument for enabled if it is defined", async () => {
255
- expect(
256
- await getMetricsConfig({ sendMetrics: false, offline: false })
257
- ).toMatchObject({
258
- enabled: false,
259
- });
260
- expect(
261
- await getMetricsConfig({ sendMetrics: true, offline: false })
262
- ).toMatchObject({
263
- enabled: true,
264
- });
265
- });
266
-
267
- it("should return enabled false if the process is not interactive", async () => {
268
- setIsTTY(false);
269
- expect(
270
- await getMetricsConfig({
271
- sendMetrics: undefined,
272
- offline: false,
273
- })
274
- ).toMatchObject({
275
- enabled: false,
276
- });
277
- });
278
-
279
- it("should return enabled true if the user on this device previously agreed to send metrics", async () => {
280
- await writeMetricsConfig({
281
- permission: {
282
- enabled: true,
283
- date: new Date(2022, 6, 4),
284
- },
285
- });
286
- expect(
287
- await getMetricsConfig({
288
- sendMetrics: undefined,
289
- offline: false,
290
- })
291
- ).toMatchObject({
292
- enabled: true,
293
- });
294
- });
295
-
296
- it("should return enabled false if the user on this device previously refused to send metrics", async () => {
297
- await writeMetricsConfig({
298
- permission: {
299
- enabled: false,
300
- date: new Date(2022, 6, 4),
301
- },
302
- });
303
- expect(
304
- await getMetricsConfig({
305
- sendMetrics: undefined,
306
- offline: false,
307
- })
308
- ).toMatchObject({
309
- enabled: false,
310
- });
311
- });
312
-
313
- it("should accept and store permission granting to send metrics if the user agrees", async () => {
314
- const checkConfirmations = mockConfirm({
315
- text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
316
- result: true,
317
- });
318
- expect(
319
- await getMetricsConfig({
320
- sendMetrics: undefined,
321
- offline: false,
322
- })
323
- ).toMatchObject({
324
- enabled: true,
325
- });
326
- checkConfirmations();
327
- expect((await readMetricsConfig()).permission).toMatchObject({
328
- enabled: true,
329
- });
330
- });
331
-
332
- it("should accept and store permission declining to send metrics if the user declines", async () => {
333
- const checkConfirmations = mockConfirm({
334
- text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
335
- result: false,
336
- });
337
- expect(
338
- await getMetricsConfig({
339
- sendMetrics: undefined,
340
- offline: false,
341
- })
342
- ).toMatchObject({
343
- enabled: false,
344
- });
345
- checkConfirmations();
346
- expect((await readMetricsConfig()).permission).toMatchObject({
347
- enabled: false,
348
- });
349
- });
350
-
351
- it("should ignore the config if the permission date is older than the current metrics date", async () => {
352
- const checkConfirmations = mockConfirm({
353
- text: "Would you like to help improve Wrangler by sending usage metrics to Cloudflare?",
354
- result: false,
355
- });
356
- const OLD_DATE = new Date(2000);
357
- await writeMetricsConfig({
358
- permission: { enabled: true, date: OLD_DATE },
359
- });
360
- expect(
361
- await getMetricsConfig({
362
- sendMetrics: undefined,
363
- offline: false,
364
- })
365
- ).toMatchObject({
366
- enabled: false,
367
- });
368
- checkConfirmations();
369
- const { permission } = await readMetricsConfig();
370
- expect(permission?.enabled).toBe(false);
371
- // The date should be updated to today's date
372
- expect(permission?.date).toEqual(CURRENT_METRICS_DATE);
373
-
374
- expect(std.out).toMatchInlineSnapshot(`
375
- "Usage metrics tracking has changed since you last granted permission.
376
- Your choice has been saved in the following file: test-xdg-config/metrics.json.
377
-
378
- You can override the user level setting for a project in \`wrangler.toml\`:
379
-
380
- - to disable sending metrics for a project: \`send_metrics = false\`
381
- - to enable sending metrics for a project: \`send_metrics = true\`"
382
- `);
383
- });
384
- });
385
-
386
- describe("deviceId", () => {
387
- it("should return a deviceId found in the config file", async () => {
388
- await writeMetricsConfig({ deviceId: "XXXX-YYYY-ZZZZ" });
389
- const { deviceId } = await getMetricsConfig({
390
- sendMetrics: true,
391
- offline: false,
392
- });
393
- expect(deviceId).toEqual("XXXX-YYYY-ZZZZ");
394
- expect((await readMetricsConfig()).deviceId).toEqual(deviceId);
395
- });
396
-
397
- it("should create and store a new deviceId if none is found in the config file", async () => {
398
- await writeMetricsConfig({});
399
- const { deviceId } = await getMetricsConfig({
400
- sendMetrics: true,
401
- offline: false,
402
- });
403
- expect(deviceId).toMatch(
404
- /[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}/
405
- );
406
- expect((await readMetricsConfig()).deviceId).toEqual(deviceId);
407
- });
408
- });
409
-
410
- describe("userId", () => {
411
- const userRequests = mockUserRequest();
412
- it("should return a userId found in a cache file", async () => {
413
- await saveToConfigCache(USER_ID_CACHE_PATH, {
414
- userId: "CACHED_USER_ID",
415
- });
416
- const { userId } = await getMetricsConfig({
417
- sendMetrics: true,
418
- offline: false,
419
- });
420
- expect(userId).toEqual("CACHED_USER_ID");
421
- expect(userRequests.count).toBe(0);
422
- });
423
-
424
- it("should fetch the userId from Cloudflare and store it in a cache file", async () => {
425
- writeAuthConfigFile({ oauth_token: "DUMMY_TOKEN" });
426
- const { userId } = await getMetricsConfig({
427
- sendMetrics: true,
428
- offline: false,
429
- });
430
- await flushPromises();
431
-
432
- expect(userId).toEqual("MOCK_USER_ID");
433
- expect(userRequests.count).toBe(1);
434
- });
435
-
436
- it("should not fetch the userId from Cloudflare if running in `offline` mode", async () => {
437
- writeAuthConfigFile({ oauth_token: "DUMMY_TOKEN" });
438
- const { userId } = await getMetricsConfig({
439
- sendMetrics: true,
440
- offline: true,
441
- });
442
- expect(userId).toBe(undefined);
443
- expect(userRequests.count).toBe(0);
444
- });
445
- });
446
- });
447
- });
448
-
449
- function mockUserRequest() {
450
- const requests = { count: 0 };
451
- beforeEach(() => {
452
- msw.use(
453
- ...mswSuccessOauthHandlers,
454
- rest.get("*/user", (_, res, cxt) => {
455
- requests.count++;
456
- return res(
457
- cxt.status(200),
458
- cxt.json({
459
- success: true,
460
- errors: [],
461
- messages: [],
462
- result: { id: "MOCK_USER_ID" },
463
- })
464
- );
465
- })
466
- );
467
- });
468
- afterEach(() => {
469
- requests.count = 0;
470
- });
471
- return requests;
472
- }
473
-
474
- function mockMetricRequest(
475
- body: unknown,
476
- header: unknown,
477
- endpoint: "identify" | "event"
478
- ) {
479
- const requests = { count: 0 };
480
- msw.use(
481
- rest.post(`*/${endpoint}`, async (req, res, cxt) => {
482
- requests.count++;
483
- expect(await req.json()).toEqual(body);
484
- expect(req.headers).toContain(header);
485
- return res.once(cxt.status(200), cxt.json({}));
486
- })
487
- );
488
-
489
- return requests;
490
- }
491
-
492
- // Forces a tick to allow the non-awaited fetch promise to resolve.
493
- function flushPromises(): Promise<void> {
494
- return new Promise((resolve) => setTimeout(resolve, 0));
495
- }