wrangler 0.0.0-e88a54e → 0.0.0-e8e684c7

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 (222) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +161 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5484 -21
  6. package/package.json +173 -143
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4016 -2786
  10. package/src/__tests__/dev.test.tsx +1305 -483
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +75 -48
  13. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  14. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  15. package/src/__tests__/helpers/mock-bin.ts +20 -20
  16. package/src/__tests__/helpers/mock-cfetch.ts +182 -93
  17. package/src/__tests__/helpers/mock-console.ts +59 -32
  18. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  19. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +26 -26
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  25. package/src/__tests__/helpers/mock-process.ts +39 -0
  26. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  27. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  28. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  29. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  30. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  31. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  32. package/src/__tests__/https-options.test.ts +144 -108
  33. package/src/__tests__/index.test.ts +229 -975
  34. package/src/__tests__/init.test.ts +2170 -0
  35. package/src/__tests__/jest.setup.ts +122 -34
  36. package/src/__tests__/kv.test.ts +1376 -1087
  37. package/src/__tests__/logger.test.ts +141 -0
  38. package/src/__tests__/metrics.test.ts +450 -0
  39. package/src/__tests__/package-manager.test.ts +312 -165
  40. package/src/__tests__/pages.test.ts +1270 -39
  41. package/src/__tests__/parse.test.ts +253 -245
  42. package/src/__tests__/publish.test.ts +6878 -2627
  43. package/src/__tests__/pubsub.test.ts +367 -0
  44. package/src/__tests__/r2.test.ts +328 -190
  45. package/src/__tests__/route.test.ts +22 -22
  46. package/src/__tests__/secret.test.ts +474 -407
  47. package/src/__tests__/tail.test.ts +679 -441
  48. package/src/__tests__/test-old-node-version.js +31 -0
  49. package/src/__tests__/user.test.ts +155 -0
  50. package/src/__tests__/validate-dev-props.test.ts +56 -0
  51. package/src/__tests__/version.test.ts +35 -0
  52. package/src/__tests__/whoami.test.tsx +276 -87
  53. package/src/__tests__/worker-namespace.test.ts +329 -0
  54. package/src/abort.d.ts +3 -0
  55. package/src/api/dev.ts +93 -0
  56. package/src/api/index.ts +1 -0
  57. package/src/bundle-reporter.tsx +29 -0
  58. package/src/bundle.ts +441 -110
  59. package/src/cfetch/index.ts +83 -66
  60. package/src/cfetch/internal.ts +251 -92
  61. package/src/cli.ts +22 -14
  62. package/src/config/README.md +1 -1
  63. package/src/config/config.ts +224 -179
  64. package/src/config/diagnostics.ts +61 -61
  65. package/src/config/environment.ts +430 -311
  66. package/src/config/index.ts +227 -38
  67. package/src/config/validation-helpers.ts +414 -303
  68. package/src/config/validation.ts +1745 -973
  69. package/src/config-cache.ts +85 -0
  70. package/src/create-worker-preview.ts +209 -118
  71. package/src/create-worker-upload-form.ts +275 -201
  72. package/src/dev/dev-vars.ts +36 -0
  73. package/src/dev/dev.tsx +488 -307
  74. package/src/dev/local.tsx +427 -210
  75. package/src/dev/remote.tsx +407 -188
  76. package/src/dev/use-esbuild.ts +156 -78
  77. package/src/dev/validate-dev-props.ts +31 -0
  78. package/src/dev-registry.tsx +160 -0
  79. package/src/dev.tsx +696 -0
  80. package/src/dialogs.tsx +115 -57
  81. package/src/dispatch-namespace.ts +206 -0
  82. package/src/durable.ts +102 -0
  83. package/src/entry.ts +267 -147
  84. package/src/environment-variables.ts +25 -23
  85. package/src/errors.ts +11 -0
  86. package/src/faye-websocket.d.ts +6 -0
  87. package/src/generate.ts +131 -0
  88. package/src/git-client.ts +42 -0
  89. package/src/global-wrangler-config-path.ts +26 -0
  90. package/src/https-options.ts +85 -80
  91. package/src/index.tsx +2191 -2304
  92. package/src/init.ts +622 -0
  93. package/src/inspect.ts +687 -557
  94. package/src/intl-polyfill.d.ts +139 -0
  95. package/src/is-ci.ts +14 -0
  96. package/src/is-interactive.ts +12 -0
  97. package/src/kv.ts +353 -242
  98. package/src/logger.ts +73 -0
  99. package/src/metrics/index.ts +5 -0
  100. package/src/metrics/metrics-config.ts +239 -0
  101. package/src/metrics/metrics-dispatcher.ts +96 -0
  102. package/src/metrics/metrics-usage-headers.ts +24 -0
  103. package/src/metrics/send-event.ts +92 -0
  104. package/src/miniflare-cli/assets.ts +554 -0
  105. package/src/miniflare-cli/enum-keys.ts +8 -8
  106. package/src/miniflare-cli/index.ts +199 -29
  107. package/src/miniflare-cli/request-context.ts +40 -0
  108. package/src/module-collection.ts +213 -213
  109. package/src/open-in-browser.ts +8 -16
  110. package/src/package-manager.ts +183 -90
  111. package/src/pages/build.tsx +238 -0
  112. package/src/pages/constants.ts +12 -0
  113. package/src/pages/deployments.tsx +106 -0
  114. package/src/pages/dev.tsx +528 -0
  115. package/src/pages/errors.ts +22 -0
  116. package/src/pages/functions/buildPlugin.ts +109 -0
  117. package/src/pages/functions/buildWorker.ts +155 -0
  118. package/src/pages/functions/filepath-routing.test.ts +234 -0
  119. package/src/pages/functions/filepath-routing.ts +189 -0
  120. package/src/pages/functions/identifiers.ts +78 -0
  121. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  122. package/src/pages/functions/routes-consolidation.ts +73 -0
  123. package/src/pages/functions/routes-transformation.test.ts +271 -0
  124. package/src/pages/functions/routes-transformation.ts +122 -0
  125. package/src/pages/functions/routes.ts +151 -0
  126. package/src/pages/functions.tsx +96 -0
  127. package/src/pages/index.tsx +94 -0
  128. package/src/pages/projects.tsx +169 -0
  129. package/src/pages/publish.tsx +391 -0
  130. package/src/pages/types.ts +49 -0
  131. package/src/pages/upload.tsx +413 -0
  132. package/src/pages/utils.ts +12 -0
  133. package/src/parse.ts +224 -121
  134. package/src/paths.ts +6 -6
  135. package/src/preview.ts +31 -0
  136. package/src/proxy.ts +416 -370
  137. package/src/publish.ts +796 -321
  138. package/src/pubsub/index.ts +286 -0
  139. package/src/pubsub/pubsub-commands.tsx +623 -0
  140. package/src/r2.ts +100 -19
  141. package/src/selfsigned.d.ts +23 -23
  142. package/src/sites.tsx +281 -189
  143. package/src/tail/filters.ts +111 -109
  144. package/src/tail/index.ts +230 -217
  145. package/src/tail/printing.ts +92 -47
  146. package/src/update-check.ts +19 -0
  147. package/src/user/choose-account.tsx +69 -0
  148. package/src/user/env-vars.ts +46 -0
  149. package/src/user/generate-auth-url.ts +33 -0
  150. package/src/user/generate-random-state.ts +16 -0
  151. package/src/user/index.ts +3 -0
  152. package/src/user/user.tsx +1191 -0
  153. package/src/whoami.tsx +142 -42
  154. package/src/worker.ts +135 -94
  155. package/src/zones.ts +167 -0
  156. package/templates/checked-fetch.js +17 -0
  157. package/templates/first-party-worker-module-facade.ts +18 -0
  158. package/templates/format-dev-errors.ts +32 -0
  159. package/templates/gitignore +171 -0
  160. package/templates/new-worker-scheduled.js +17 -0
  161. package/templates/new-worker-scheduled.ts +32 -0
  162. package/templates/new-worker.js +3 -3
  163. package/templates/new-worker.ts +18 -3
  164. package/templates/no-op-worker.js +10 -0
  165. package/templates/pages-shim.ts +9 -0
  166. package/templates/pages-template-plugin.ts +167 -0
  167. package/templates/pages-template-worker.ts +172 -0
  168. package/templates/serve-static-assets.ts +63 -0
  169. package/templates/service-bindings-module-facade.js +54 -0
  170. package/templates/service-bindings-sw-facade.js +42 -0
  171. package/templates/tsconfig.json +95 -95
  172. package/wrangler-dist/cli.d.ts +338 -0
  173. package/wrangler-dist/cli.js +124611 -112403
  174. package/miniflare-dist/index.mjs.map +0 -7
  175. package/pages/functions/buildWorker.ts +0 -62
  176. package/pages/functions/filepath-routing.test.ts +0 -223
  177. package/pages/functions/filepath-routing.ts +0 -181
  178. package/pages/functions/identifiers.ts +0 -78
  179. package/pages/functions/routes.ts +0 -151
  180. package/pages/functions/template-worker.ts +0 -130
  181. package/src/__tests__/dev2.test.tsx +0 -154
  182. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  183. package/src/__tests__/logout.test.ts +0 -52
  184. package/src/__tests__/sentry.test.ts +0 -146
  185. package/src/pages.tsx +0 -1047
  186. package/src/reporting.ts +0 -131
  187. package/src/user.tsx +0 -1118
  188. package/templates/static-asset-facade.js +0 -47
  189. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  191. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  192. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  194. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  196. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  202. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  204. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  205. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  206. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  207. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  210. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  211. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  212. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  213. package/vendor/wrangler-mime/LICENSE +0 -21
  214. package/vendor/wrangler-mime/Mime.js +0 -97
  215. package/vendor/wrangler-mime/README.md +0 -187
  216. package/vendor/wrangler-mime/cli.js +0 -46
  217. package/vendor/wrangler-mime/index.js +0 -4
  218. package/vendor/wrangler-mime/lite.js +0 -4
  219. package/vendor/wrangler-mime/package.json +0 -52
  220. package/vendor/wrangler-mime/types/other.js +0 -1
  221. package/vendor/wrangler-mime/types/standard.js +0 -1
  222. package/wrangler-dist/cli.js.map +0 -7
@@ -1,24 +1,26 @@
1
+ import { Readable } from "node:stream";
1
2
  import { URL, URLSearchParams } from "node:url";
2
3
  import { pathToRegexp } from "path-to-regexp";
4
+ import { Response } from "undici";
3
5
  import { getCloudflareApiBaseUrl } from "../../cfetch";
4
6
  import type { FetchResult, FetchError } from "../../cfetch";
5
- import type { RequestInit } from "undici";
7
+ import type { RequestInit, BodyInit, HeadersInit } from "undici";
6
8
 
7
9
  /**
8
10
  * The signature of the function that will handle a mock request.
9
11
  */
10
12
  export type MockHandler<ResponseType> = (
11
- uri: RegExpExecArray,
12
- init: RequestInit,
13
- queryParams: URLSearchParams
13
+ uri: RegExpExecArray,
14
+ init: RequestInit,
15
+ queryParams: URLSearchParams
14
16
  ) => ResponseType | Promise<ResponseType>;
15
17
 
16
18
  type RemoveMockFn = () => void;
17
19
 
18
20
  interface MockFetch<ResponseType> {
19
- regexp: RegExp;
20
- method: string | undefined;
21
- handler: MockHandler<ResponseType>;
21
+ regexp: RegExp;
22
+ method: string | undefined;
23
+ handler: MockHandler<ResponseType>;
22
24
  }
23
25
  const mocks: MockFetch<unknown>[] = [];
24
26
 
@@ -30,23 +32,23 @@ const mocks: MockFetch<unknown>[] = [];
30
32
  * Once found the handler will be used to generate a mock response.
31
33
  */
32
34
  export async function mockFetchInternal(
33
- resource: string,
34
- init: RequestInit = {},
35
- queryParams: URLSearchParams = new URLSearchParams()
35
+ resource: string,
36
+ init: RequestInit = {},
37
+ queryParams: URLSearchParams = new URLSearchParams()
36
38
  ) {
37
- for (const { regexp, method, handler } of mocks) {
38
- const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
39
- const uri = regexp.exec(resourcePath);
40
- // Do the resource path and (if specified) the HTTP method match?
41
- if (uri !== null && (!method || method === (init.method ?? "GET"))) {
42
- // The `resource` regular expression will extract the labelled groups from the URL.
43
- // These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
44
- return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
45
- }
46
- }
47
- throw new Error(
48
- `no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
49
- );
39
+ for (const { regexp, method, handler } of mocks) {
40
+ const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
41
+ const uri = regexp.exec(resourcePath);
42
+ // Do the resource path and (if specified) the HTTP method match?
43
+ if (uri !== null && (!method || method === (init.method ?? "GET"))) {
44
+ // The `resource` regular expression will extract the labelled groups from the URL.
45
+ // These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
46
+ return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
47
+ }
48
+ }
49
+ throw new Error(
50
+ `no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
51
+ );
50
52
  }
51
53
 
52
54
  /**
@@ -57,8 +59,8 @@ export async function mockFetchInternal(
57
59
  * @param handler The function that will generate the mock response for this request.
58
60
  */
59
61
  export function setMockRawResponse<ResponseType>(
60
- resource: string,
61
- handler: MockHandler<ResponseType>
62
+ resource: string,
63
+ handler: MockHandler<ResponseType>
62
64
  ): RemoveMockFn;
63
65
  /**
64
66
  * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
@@ -69,32 +71,32 @@ export function setMockRawResponse<ResponseType>(
69
71
  * @param handler The function that will generate the mock response for this request.
70
72
  */
71
73
  export function setMockRawResponse<ResponseType>(
72
- resource: string,
73
- method: string,
74
- handler: MockHandler<ResponseType>
74
+ resource: string,
75
+ method: string,
76
+ handler: MockHandler<ResponseType>
75
77
  ): RemoveMockFn;
76
78
  /**
77
79
  * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
78
80
  */
79
81
  export function setMockRawResponse<ResponseType>(
80
- resource: string,
81
- ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
82
+ resource: string,
83
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
82
84
  ): RemoveMockFn {
83
- const handler = args.pop() as MockHandler<ResponseType>;
84
- const method = args.pop() as string;
85
- const mock = {
86
- resource,
87
- method,
88
- handler,
89
- regexp: pathToRegexp(resource),
90
- };
91
- mocks.push(mock);
92
- return () => {
93
- const mockIndex = mocks.indexOf(mock);
94
- if (mockIndex !== -1) {
95
- mocks.splice(mockIndex, 1);
96
- }
97
- };
85
+ const handler = args.pop() as MockHandler<ResponseType>;
86
+ const method = args.pop() as string;
87
+ const mock = {
88
+ resource,
89
+ method,
90
+ handler,
91
+ regexp: pathToRegexp(resource),
92
+ };
93
+ mocks.push(mock);
94
+ return () => {
95
+ const mockIndex = mocks.indexOf(mock);
96
+ if (mockIndex !== -1) {
97
+ mocks.splice(mockIndex, 1);
98
+ }
99
+ };
98
100
  }
99
101
 
100
102
  /**
@@ -107,8 +109,8 @@ export function setMockRawResponse<ResponseType>(
107
109
  * @param handler The function that will generate the mock response for this request.
108
110
  */
109
111
  export function setMockResponse<ResponseType>(
110
- resource: string,
111
- handler: MockHandler<ResponseType>
112
+ resource: string,
113
+ handler: MockHandler<ResponseType>
112
114
  ): RemoveMockFn;
113
115
  /**
114
116
  * Specify an expected resource path that is to be handled, resulting in a FetchRequest..
@@ -119,48 +121,48 @@ export function setMockResponse<ResponseType>(
119
121
  * @param handler The function that will generate the mock response for this request.
120
122
  */
121
123
  export function setMockResponse<ResponseType>(
122
- resource: string,
123
- method: string,
124
- handler: MockHandler<ResponseType>
124
+ resource: string,
125
+ method: string,
126
+ handler: MockHandler<ResponseType>
125
127
  ): RemoveMockFn;
126
128
  /**
127
129
  * Specify an expected resource path that is to be handled, resulting in a FetchRequest.
128
130
  */
129
131
  export function setMockResponse<ResponseType>(
130
- resource: string,
131
- ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
132
+ resource: string,
133
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
132
134
  ): RemoveMockFn {
133
- const handler = args.pop() as MockHandler<ResponseType>;
134
- const method = args.pop() as string;
135
- return setMockRawResponse(resource, method, (...handlerArgs) =>
136
- createFetchResult(handler(...handlerArgs))
137
- );
135
+ const handler = args.pop() as MockHandler<ResponseType>;
136
+ const method = args.pop() as string;
137
+ return setMockRawResponse(resource, method, (...handlerArgs) =>
138
+ createFetchResult(handler(...handlerArgs))
139
+ );
138
140
  }
139
141
 
140
142
  /**
141
143
  * A helper to make it easier to create `FetchResult` objects in tests.
142
144
  */
143
145
  export async function createFetchResult<ResponseType>(
144
- result: ResponseType | Promise<ResponseType>,
145
- success = true,
146
- errors: FetchError[] = [],
147
- messages: string[] = [],
148
- result_info?: unknown
146
+ result: ResponseType | Promise<ResponseType>,
147
+ success = true,
148
+ errors: FetchError[] = [],
149
+ messages: string[] = [],
150
+ result_info?: unknown
149
151
  ): Promise<FetchResult<ResponseType>> {
150
- return result_info
151
- ? {
152
- result: await result,
153
- success,
154
- errors,
155
- messages,
156
- result_info,
157
- }
158
- : {
159
- result: await result,
160
- success,
161
- errors,
162
- messages,
163
- };
152
+ return result_info
153
+ ? {
154
+ result: await result,
155
+ success,
156
+ errors,
157
+ messages,
158
+ result_info,
159
+ }
160
+ : {
161
+ result: await result,
162
+ success,
163
+ errors,
164
+ messages,
165
+ };
164
166
  }
165
167
 
166
168
  /**
@@ -169,7 +171,7 @@ export async function createFetchResult<ResponseType>(
169
171
  * This should be called in an `afterEach()` block to ensure that mock handlers do not leak between tests.
170
172
  */
171
173
  export function unsetAllMocks() {
172
- mocks.length = 0;
174
+ mocks.length = 0;
173
175
  }
174
176
 
175
177
  /**
@@ -179,29 +181,116 @@ export function unsetAllMocks() {
179
181
  * special-case mocking it here.
180
182
  */
181
183
 
182
- const kvGetMocks = new Map<string, string>();
184
+ const kvGetMocks = new Map<string, string | Buffer>();
185
+ const r2GetMocks = new Map<string, string | undefined>();
186
+ const dashScriptMocks = new Map<string, string | undefined>();
183
187
 
188
+ /**
189
+ * @mocked typeof fetchKVGetValue
190
+ */
184
191
  export function mockFetchKVGetValue(
185
- accountId: string,
186
- namespaceId: string,
187
- key: string
192
+ accountId: string,
193
+ namespaceId: string,
194
+ key: string
188
195
  ) {
189
- const mapKey = `${accountId}/${namespaceId}/${key}`;
190
- if (kvGetMocks.has(mapKey)) {
191
- return kvGetMocks.get(mapKey);
192
- }
193
- throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
196
+ const mapKey = `${accountId}/${namespaceId}/${key}`;
197
+ if (kvGetMocks.has(mapKey)) {
198
+ const value = kvGetMocks.get(mapKey);
199
+ if (value !== undefined) return Promise.resolve(value);
200
+ }
201
+ throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
194
202
  }
195
203
 
196
204
  export function setMockFetchKVGetValue(
197
- accountId: string,
198
- namespaceId: string,
199
- key: string,
200
- value: string
205
+ accountId: string,
206
+ namespaceId: string,
207
+ key: string,
208
+ value: string | Buffer
201
209
  ) {
202
- kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
210
+ kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
203
211
  }
204
212
 
205
- export function unsetMockFetchKVGetValues() {
206
- kvGetMocks.clear();
213
+ /**
214
+ * @mocked typeof fetchR2Objects
215
+ */
216
+ export async function mockFetchR2Objects(
217
+ resource: string,
218
+ bodyInit: {
219
+ body: BodyInit | Readable;
220
+ headers: HeadersInit | undefined;
221
+ method: "PUT" | "GET" | "DELETE";
222
+ }
223
+ ): Promise<Response> {
224
+ /**
225
+ * Here we destroy & removeListeners to "drain" the stream, for testing purposes
226
+ * mimicking the fetch request taking in the stream and draining it.
227
+ */
228
+ if (bodyInit.body instanceof Readable) {
229
+ bodyInit.body.destroy();
230
+ bodyInit.body.removeAllListeners();
231
+ }
232
+
233
+ if (r2GetMocks.has(resource)) {
234
+ const value = r2GetMocks.get(resource);
235
+
236
+ return new Response(value);
237
+ }
238
+ throw new Error(`no mock found for \`r2 object\` - ${resource}`);
239
+ }
240
+
241
+ /**
242
+ * Mock setter for usage within test blocks, companion helper to `mockFetchR2Objects`
243
+ */
244
+ export function setMockFetchR2Objects({
245
+ accountId,
246
+ bucketName,
247
+ objectName,
248
+ mockResponse,
249
+ }: {
250
+ accountId: string;
251
+ bucketName: string;
252
+ objectName: string;
253
+ mockResponse?: string;
254
+ }) {
255
+ r2GetMocks.set(
256
+ `/accounts/${accountId}/r2/buckets/${bucketName}/objects/${objectName}`,
257
+ mockResponse
258
+ );
259
+ }
260
+
261
+ export function unsetSpecialMockFns() {
262
+ kvGetMocks.clear();
263
+ r2GetMocks.clear();
264
+ dashScriptMocks.clear();
265
+ }
266
+
267
+ /**
268
+ * @mocked typeof fetchDashScript
269
+ * multipart/form-data is the response for modules and raw text for the Script endpoint.
270
+ */
271
+ export async function mockFetchDashScript(resource: string): Promise<string> {
272
+ if (dashScriptMocks.has(resource)) {
273
+ const value = dashScriptMocks.get(resource) ?? "";
274
+
275
+ return value;
276
+ }
277
+ throw new Error(`no mock found for \`init from-dash\` - ${resource}`);
278
+ }
279
+
280
+ /**
281
+ * Mock setter for usage within test blocks, companion helper to `mockFetchDashScript`
282
+ */
283
+ export function setMockFetchDashScript({
284
+ accountId,
285
+ fromDashScriptName,
286
+ mockResponse,
287
+ }: {
288
+ accountId: string;
289
+ fromDashScriptName: string;
290
+ mockResponse?: string;
291
+ }) {
292
+ dashScriptMocks.set(
293
+ `/accounts/${accountId}/workers/scripts/${fromDashScriptName}`,
294
+ mockResponse
295
+ );
207
296
  }
@@ -1,50 +1,69 @@
1
1
  import * as util from "node:util";
2
+ import { logger } from "../../logger";
2
3
 
3
4
  /**
4
5
  * We use this module to mock console methods, and optionally
5
6
  * assert on the values they're called with in our tests.
6
7
  */
7
8
 
8
- let logSpy: jest.SpyInstance,
9
- errorSpy: jest.SpyInstance,
10
- warnSpy: jest.SpyInstance;
9
+ let debugSpy: jest.SpyInstance,
10
+ logSpy: jest.SpyInstance,
11
+ errorSpy: jest.SpyInstance,
12
+ warnSpy: jest.SpyInstance;
11
13
 
12
14
  const std = {
13
- get out() {
14
- return normalizeOutput(logSpy);
15
- },
16
- get err() {
17
- return normalizeOutput(errorSpy);
18
- },
19
- get warn() {
20
- return normalizeOutput(warnSpy);
21
- },
15
+ get debug() {
16
+ return normalizeOutput(debugSpy);
17
+ },
18
+ get out() {
19
+ return normalizeOutput(logSpy);
20
+ },
21
+ get err() {
22
+ return normalizeOutput(errorSpy);
23
+ },
24
+ get warn() {
25
+ return normalizeOutput(warnSpy);
26
+ },
22
27
  };
23
28
 
24
29
  function normalizeOutput(spy: jest.SpyInstance): string {
25
- return stripTrailingWhitespace(
26
- normalizeSlashes(stripTimings(captureCalls(spy)))
27
- );
30
+ return normalizeErrorMarkers(
31
+ replaceByte(
32
+ stripTrailingWhitespace(normalizeSlashes(stripTimings(captureCalls(spy))))
33
+ )
34
+ );
28
35
  }
29
36
 
30
37
  function captureCalls(spy: jest.SpyInstance): string {
31
- return spy.mock.calls
32
- .map((args: unknown[]) => util.format("%s", ...args))
33
- .join("\n");
38
+ return spy.mock.calls
39
+ .map((args: unknown[]) => util.format("%s", ...args))
40
+ .join("\n");
34
41
  }
35
42
 
36
43
  export function mockConsoleMethods() {
37
- beforeEach(() => {
38
- logSpy = jest.spyOn(console, "log").mockImplementation();
39
- errorSpy = jest.spyOn(console, "error").mockImplementation();
40
- warnSpy = jest.spyOn(console, "warn").mockImplementation();
41
- });
42
- afterEach(() => {
43
- logSpy.mockRestore();
44
- errorSpy.mockRestore();
45
- warnSpy.mockRestore();
46
- });
47
- return std;
44
+ beforeEach(() => {
45
+ logger.columns = 100;
46
+ debugSpy = jest.spyOn(console, "debug").mockImplementation();
47
+ logSpy = jest.spyOn(console, "log").mockImplementation();
48
+ errorSpy = jest.spyOn(console, "error").mockImplementation();
49
+ warnSpy = jest.spyOn(console, "warn").mockImplementation();
50
+ });
51
+ afterEach(() => {
52
+ debugSpy.mockRestore();
53
+ logSpy.mockRestore();
54
+ errorSpy.mockRestore();
55
+ warnSpy.mockRestore();
56
+ });
57
+ return std;
58
+ }
59
+
60
+ /**
61
+ * Normalize error `X` markers.
62
+ *
63
+ * Windows gets a different character.
64
+ */
65
+ function normalizeErrorMarkers(str: string): string {
66
+ return str.replaceAll("✘", "X");
48
67
  }
49
68
 
50
69
  /**
@@ -53,7 +72,7 @@ export function mockConsoleMethods() {
53
72
  * Use this in snapshot tests to be resilient to file-system differences.
54
73
  */
55
74
  export function normalizeSlashes(str: string): string {
56
- return str.replace(/\\/g, "/");
75
+ return str.replace(/\\/g, "/");
57
76
  }
58
77
 
59
78
  /**
@@ -62,9 +81,17 @@ export function normalizeSlashes(str: string): string {
62
81
  * Use this in snapshot tests to be resilient to slight changes in timing of processing.
63
82
  */
64
83
  export function stripTimings(stdout: string): string {
65
- return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
84
+ return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
66
85
  }
67
86
 
68
87
  export function stripTrailingWhitespace(str: string): string {
69
- return str.replace(/[^\S\n]+\n/g, "\n");
88
+ return str.replace(/[^\S\n]+\n/g, "\n");
89
+ }
90
+
91
+ /**
92
+ * Removing leading kilobit (tenth of a byte) from test output due to
93
+ * variation causing every few tests the value to change by ± .01
94
+ */
95
+ function replaceByte(stdout: string): string {
96
+ return stdout.replaceAll(/.[0-9][0-9] KiB/g, "xx KiB");
70
97
  }
@@ -1,13 +1,14 @@
1
- import { confirm, prompt } from "../../dialogs";
1
+ import { confirm, prompt, select } from "../../dialogs";
2
+ import { normalizeSlashes } from "./mock-console";
2
3
 
3
4
  /**
4
5
  * The expected values for a confirmation request.
5
6
  */
6
7
  export interface ConfirmExpectation {
7
- /** The text expected to be seen in the confirmation dialog. */
8
- text: string;
9
- /** The mock response send back from the confirmation dialog. */
10
- result: boolean;
8
+ /** The text expected to be seen in the confirmation dialog. */
9
+ text: string;
10
+ /** The mock response send back from the confirmation dialog. */
11
+ result: boolean;
11
12
  }
12
13
 
13
14
  /**
@@ -18,26 +19,47 @@ export interface ConfirmExpectation {
18
19
  * then an error is thrown.
19
20
  */
20
21
  export function mockConfirm(...expectations: ConfirmExpectation[]) {
21
- (confirm as jest.Mock).mockImplementation((text: string) => {
22
- for (const { text: expectedText, result } of expectations) {
23
- if (text === expectedText) {
24
- return Promise.resolve(result);
25
- }
26
- }
27
- throw new Error(`Unexpected confirmation message: ${text}`);
28
- });
22
+ (confirm as jest.Mock).mockImplementation((text: string) => {
23
+ for (const expectation of expectations) {
24
+ if (normalizeSlashes(text) === normalizeSlashes(expectation.text)) {
25
+ expectations = expectations.filter((e) => e !== expectation);
26
+ return Promise.resolve(expectation.result);
27
+ }
28
+ }
29
+ throw new Error(`Unexpected confirmation message: ${text}`);
30
+ });
31
+ return () => {
32
+ if (expectations.length > 0) {
33
+ throw new Error(
34
+ "The following expected confirmation dialogs were not used:\n" +
35
+ expectations.map((e) => `- "${e.text}"`).join("\n")
36
+ );
37
+ }
38
+ };
39
+ }
40
+
41
+ export function clearConfirmMocks() {
42
+ (confirm as jest.Mock).mockReset();
43
+ // Because confirm was originally a spy, calling mockReset will simply reset
44
+ // it as a function with no return value (!), so we need to accitionally reset
45
+ // the mock implementation to the one that throws (from jest.setup.js).
46
+ (confirm as jest.Mock).mockImplementation((text: string) => {
47
+ throw new Error(
48
+ `Unexpected call to \`confirm("${text}")\`.\nYou should use \`mockConfirm()\` to mock calls to \`confirm()\` with expectations. Search the codebase for \`mockConfirm\` to learn more.`
49
+ );
50
+ });
29
51
  }
30
52
 
31
53
  /**
32
54
  * The expected values for a prompt request.
33
55
  */
34
56
  export interface PromptExpectation {
35
- /** The text expected to be seen in the prompt dialog. */
36
- text: string;
37
- /** The type of the prompt. */
38
- type: "text" | "password";
39
- /** The mock response send back from the prompt dialog. */
40
- result: string;
57
+ /** The text expected to be seen in the prompt dialog. */
58
+ text: string;
59
+ /** The type of the prompt. */
60
+ type: "text" | "password";
61
+ /** The mock response send back from the prompt dialog. */
62
+ result: string;
41
63
  }
42
64
 
43
65
  /**
@@ -48,18 +70,84 @@ export interface PromptExpectation {
48
70
  * then an error is thrown.
49
71
  */
50
72
  export function mockPrompt(...expectations: PromptExpectation[]) {
51
- (prompt as jest.Mock).mockImplementation(
52
- (text: string, type: "text" | "password") => {
53
- for (const {
54
- text: expectedText,
55
- type: expectedType,
56
- result,
57
- } of expectations) {
58
- if (text === expectedText && type == expectedType) {
59
- return Promise.resolve(result);
60
- }
61
- }
62
- throw new Error(`Unexpected confirmation message: ${text}`);
63
- }
64
- );
73
+ (prompt as jest.Mock).mockImplementation(
74
+ (text: string, type: "text" | "password") => {
75
+ for (const expectation of expectations) {
76
+ if (text === expectation.text && type == expectation.type) {
77
+ expectations = expectations.filter((e) => e !== expectation);
78
+ return Promise.resolve(expectation.result);
79
+ }
80
+ }
81
+ throw new Error(`Unexpected confirmation message: ${text}`);
82
+ }
83
+ );
84
+ return () => {
85
+ if (expectations.length > 0) {
86
+ throw new Error(
87
+ "The following expected prompt dialogs were not used:\n" +
88
+ expectations.map((e) => `- "${e.text}"`).join("\n")
89
+ );
90
+ }
91
+ };
92
+ }
93
+
94
+ export function clearPromptMocks() {
95
+ (prompt as jest.Mock).mockReset();
96
+ // Because prompt was originally a spy, calling mockReset will simply reset
97
+ // it as a function with no return value (!), so we need to accitionally reset
98
+ // the mock implementation to the one that throws (from jest.setup.js).
99
+ (prompt as jest.Mock).mockImplementation((text: string) => {
100
+ throw new Error(
101
+ `Unexpected call to \`prompt(${text}, ...)\`.\nYou should use \`mockPrompt()\` to mock calls to \`prompt()\` with expectations. Search the codebase for \`mockPrompt\` to learn more.`
102
+ );
103
+ });
104
+ }
105
+
106
+ /**
107
+ * The expected values for a select request.
108
+ */
109
+ export interface SelectExpectation {
110
+ /** The text expected to be seen in the select dialog. */
111
+ text: string;
112
+ /** The mock response send back from the select dialog. */
113
+ result: string;
114
+ }
115
+
116
+ /**
117
+ * Mock the implementation of `select()` that will respond with configured results
118
+ * for configured select text messages.
119
+ *
120
+ * If there is a call to `select()` that does not match any of the expectations
121
+ * then an error is thrown.
122
+ */
123
+ export function mockSelect(...expectations: SelectExpectation[]) {
124
+ (select as jest.Mock).mockImplementation((text: string) => {
125
+ for (const expectation of expectations) {
126
+ if (normalizeSlashes(text) === normalizeSlashes(expectation.text)) {
127
+ expectations = expectations.filter((e) => e !== expectation);
128
+ return Promise.resolve(expectation.result);
129
+ }
130
+ }
131
+ throw new Error(`Unexpected select message: ${text}`);
132
+ });
133
+ return () => {
134
+ if (expectations.length > 0) {
135
+ throw new Error(
136
+ "The following expected select dialogs were not used:\n" +
137
+ expectations.map((e) => `- "${e.text}"`).join("\n")
138
+ );
139
+ }
140
+ };
141
+ }
142
+
143
+ export function clearSelectMocks() {
144
+ (select as jest.Mock).mockReset();
145
+ // Because select was originally a spy, calling mockReset will simply reset
146
+ // it as a function with no return value (!), so we need to additionally reset
147
+ // the mock implementation to the one that throws (from jest.setup.js).
148
+ (select as jest.Mock).mockImplementation((text: string) => {
149
+ throw new Error(
150
+ `Unexpected call to \`select("${text}")\`.\nYou should use \`mockSelect()\` to mock calls to \`select()\` with expectations. Search the codebase for \`mockSelect\` to learn more.`
151
+ );
152
+ });
65
153
  }
@@ -0,0 +1,8 @@
1
+ import { setMockResponse } from "./mock-cfetch";
2
+
3
+ export function mockGetZoneFromHostRequest(host: string, zone?: string) {
4
+ setMockResponse("/zones", (_uri, _init, queryParams) => {
5
+ expect(queryParams.get("name")).toEqual(host);
6
+ return zone ? [{ id: zone }] : [];
7
+ });
8
+ }