wrangler 0.0.0-e64812e → 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 (214) hide show
  1. package/README.md +27 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +663 -7
  5. package/package.json +173 -152
  6. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  7. package/src/__tests__/config-cache.test.ts +30 -24
  8. package/src/__tests__/configuration.test.ts +4015 -3363
  9. package/src/__tests__/dev.test.tsx +1290 -952
  10. package/src/__tests__/generate.test.ts +91 -0
  11. package/src/__tests__/guess-worker-format.test.ts +68 -68
  12. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  13. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  14. package/src/__tests__/helpers/mock-bin.ts +20 -20
  15. package/src/__tests__/helpers/mock-cfetch.ts +179 -94
  16. package/src/__tests__/helpers/mock-console.ts +49 -39
  17. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  18. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  20. package/src/__tests__/helpers/mock-istty.ts +65 -18
  21. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  22. package/src/__tests__/helpers/mock-kv.ts +26 -26
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  26. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  27. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  28. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  29. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  31. package/src/__tests__/https-options.test.ts +142 -109
  32. package/src/__tests__/index.test.ts +222 -233
  33. package/src/__tests__/init.test.ts +2139 -1603
  34. package/src/__tests__/jest.setup.ts +114 -34
  35. package/src/__tests__/kv.test.ts +1222 -1032
  36. package/src/__tests__/logger.test.ts +100 -74
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +303 -303
  39. package/src/__tests__/pages.test.ts +1173 -652
  40. package/src/__tests__/parse.test.ts +252 -252
  41. package/src/__tests__/publish.test.ts +6788 -5301
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +328 -225
  44. package/src/__tests__/route.test.ts +18 -18
  45. package/src/__tests__/secret.test.ts +470 -459
  46. package/src/__tests__/tail.test.ts +676 -564
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +136 -112
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +267 -83
  52. package/src/__tests__/worker-namespace.test.ts +329 -0
  53. package/src/abort.d.ts +1 -1
  54. package/src/api/dev.ts +93 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +430 -157
  58. package/src/cfetch/index.ts +80 -80
  59. package/src/cfetch/internal.ts +244 -91
  60. package/src/cli.ts +21 -7
  61. package/src/config/config.ts +224 -195
  62. package/src/config/diagnostics.ts +61 -61
  63. package/src/config/environment.ts +422 -357
  64. package/src/config/index.ts +219 -193
  65. package/src/config/validation-helpers.ts +379 -357
  66. package/src/config/validation.ts +1690 -1367
  67. package/src/config-cache.ts +81 -41
  68. package/src/create-worker-preview.ts +208 -136
  69. package/src/create-worker-upload-form.ts +275 -238
  70. package/src/dev/dev-vars.ts +13 -13
  71. package/src/dev/dev.tsx +477 -351
  72. package/src/dev/local.tsx +426 -295
  73. package/src/dev/remote.tsx +406 -211
  74. package/src/dev/use-esbuild.ts +154 -94
  75. package/src/dev/validate-dev-props.ts +31 -0
  76. package/src/dev-registry.tsx +160 -0
  77. package/src/dev.tsx +696 -0
  78. package/src/dialogs.tsx +97 -97
  79. package/src/dispatch-namespace.ts +206 -0
  80. package/src/durable.ts +87 -87
  81. package/src/entry.ts +234 -228
  82. package/src/environment-variables.ts +23 -23
  83. package/src/errors.ts +6 -6
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +84 -80
  89. package/src/index.tsx +2164 -2768
  90. package/src/init.ts +622 -0
  91. package/src/inspect.ts +678 -593
  92. package/src/intl-polyfill.d.ts +123 -123
  93. package/src/is-ci.ts +14 -0
  94. package/src/is-interactive.ts +12 -0
  95. package/src/kv.ts +299 -277
  96. package/src/logger.ts +46 -39
  97. package/src/metrics/index.ts +5 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/assets.ts +554 -0
  103. package/src/miniflare-cli/enum-keys.ts +8 -8
  104. package/src/miniflare-cli/index.ts +198 -32
  105. package/src/miniflare-cli/request-context.ts +18 -18
  106. package/src/module-collection.ts +212 -212
  107. package/src/open-in-browser.ts +4 -6
  108. package/src/package-manager.ts +173 -128
  109. package/src/pages/build.tsx +238 -0
  110. package/src/pages/constants.ts +12 -0
  111. package/src/pages/deployments.tsx +106 -0
  112. package/src/pages/dev.tsx +528 -0
  113. package/src/pages/errors.ts +22 -0
  114. package/src/pages/functions/buildPlugin.ts +109 -0
  115. package/src/pages/functions/buildWorker.ts +155 -0
  116. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  120. package/src/pages/functions/routes-consolidation.ts +73 -0
  121. package/src/pages/functions/routes-transformation.test.ts +271 -0
  122. package/src/pages/functions/routes-transformation.ts +122 -0
  123. package/src/pages/functions/routes.ts +151 -0
  124. package/src/pages/functions.tsx +96 -0
  125. package/src/pages/index.tsx +94 -0
  126. package/src/pages/projects.tsx +169 -0
  127. package/src/pages/publish.tsx +391 -0
  128. package/src/pages/types.ts +49 -0
  129. package/src/pages/upload.tsx +413 -0
  130. package/src/pages/utils.ts +12 -0
  131. package/src/parse.ts +209 -125
  132. package/src/paths.ts +6 -6
  133. package/src/preview.ts +31 -0
  134. package/src/proxy.ts +410 -389
  135. package/src/publish.ts +773 -534
  136. package/src/pubsub/index.ts +286 -0
  137. package/src/pubsub/pubsub-commands.tsx +623 -0
  138. package/src/r2.ts +100 -19
  139. package/src/selfsigned.d.ts +23 -23
  140. package/src/sites.tsx +278 -201
  141. package/src/tail/filters.ts +111 -109
  142. package/src/tail/index.ts +230 -217
  143. package/src/tail/printing.ts +86 -46
  144. package/src/update-check.ts +11 -11
  145. package/src/user/choose-account.tsx +69 -0
  146. package/src/user/env-vars.ts +46 -0
  147. package/src/user/generate-auth-url.ts +33 -0
  148. package/src/user/generate-random-state.ts +16 -0
  149. package/src/user/index.ts +3 -0
  150. package/src/user/user.tsx +1191 -0
  151. package/src/whoami.tsx +141 -42
  152. package/src/worker.ts +123 -99
  153. package/src/zones.ts +167 -0
  154. package/templates/checked-fetch.js +17 -0
  155. package/templates/first-party-worker-module-facade.ts +18 -0
  156. package/templates/format-dev-errors.ts +32 -0
  157. package/templates/new-worker-scheduled.js +3 -3
  158. package/templates/new-worker-scheduled.ts +15 -15
  159. package/templates/new-worker.js +3 -3
  160. package/templates/new-worker.ts +15 -15
  161. package/templates/no-op-worker.js +10 -0
  162. package/templates/pages-shim.ts +9 -0
  163. package/templates/pages-template-plugin.ts +167 -0
  164. package/templates/pages-template-worker.ts +172 -0
  165. package/templates/serve-static-assets.ts +63 -0
  166. package/templates/service-bindings-module-facade.js +54 -0
  167. package/templates/service-bindings-sw-facade.js +42 -0
  168. package/templates/tsconfig.json +95 -95
  169. package/wrangler-dist/cli.d.ts +338 -0
  170. package/wrangler-dist/cli.js +95449 -67524
  171. package/pages/functions/buildPlugin.ts +0 -105
  172. package/pages/functions/buildWorker.ts +0 -151
  173. package/pages/functions/filepath-routing.ts +0 -189
  174. package/pages/functions/identifiers.ts +0 -78
  175. package/pages/functions/routes.ts +0 -156
  176. package/pages/functions/template-plugin.ts +0 -147
  177. package/pages/functions/template-worker.ts +0 -143
  178. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  179. package/src/pages.tsx +0 -2038
  180. package/src/user.tsx +0 -1203
  181. package/templates/static-asset-facade.js +0 -47
  182. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  183. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  184. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  185. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  186. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  187. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  188. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  189. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  190. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  191. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  192. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  193. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  194. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  196. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  197. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  198. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  199. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  200. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  201. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  202. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  203. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  204. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  205. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  206. package/vendor/wrangler-mime/LICENSE +0 -21
  207. package/vendor/wrangler-mime/Mime.js +0 -97
  208. package/vendor/wrangler-mime/README.md +0 -187
  209. package/vendor/wrangler-mime/cli.js +0 -46
  210. package/vendor/wrangler-mime/index.js +0 -4
  211. package/vendor/wrangler-mime/lite.js +0 -4
  212. package/vendor/wrangler-mime/package.json +0 -52
  213. package/vendor/wrangler-mime/types/other.js +0 -1
  214. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -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,33 +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
 
184
188
  /**
185
189
  * @mocked typeof fetchKVGetValue
186
190
  */
187
191
  export function mockFetchKVGetValue(
188
- accountId: string,
189
- namespaceId: string,
190
- key: string
192
+ accountId: string,
193
+ namespaceId: string,
194
+ key: string
191
195
  ) {
192
- const mapKey = `${accountId}/${namespaceId}/${key}`;
193
- if (kvGetMocks.has(mapKey)) {
194
- const value = kvGetMocks.get(mapKey);
195
- if (value !== undefined) return Promise.resolve(value);
196
- }
197
- 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}`);
198
202
  }
199
203
 
200
204
  export function setMockFetchKVGetValue(
201
- accountId: string,
202
- namespaceId: string,
203
- key: string,
204
- value: string
205
+ accountId: string,
206
+ namespaceId: string,
207
+ key: string,
208
+ value: string | Buffer
205
209
  ) {
206
- kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
210
+ kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
207
211
  }
208
212
 
209
- export function unsetMockFetchKVGetValues() {
210
- 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
+ );
211
296
  }
@@ -7,52 +7,54 @@ import { logger } from "../../logger";
7
7
  */
8
8
 
9
9
  let debugSpy: jest.SpyInstance,
10
- logSpy: jest.SpyInstance,
11
- errorSpy: jest.SpyInstance,
12
- warnSpy: jest.SpyInstance;
10
+ logSpy: jest.SpyInstance,
11
+ errorSpy: jest.SpyInstance,
12
+ warnSpy: jest.SpyInstance;
13
13
 
14
14
  const std = {
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
- },
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
+ },
27
27
  };
28
28
 
29
29
  function normalizeOutput(spy: jest.SpyInstance): string {
30
- return normalizeErrorMarkers(
31
- stripTrailingWhitespace(normalizeSlashes(stripTimings(captureCalls(spy))))
32
- );
30
+ return normalizeErrorMarkers(
31
+ replaceByte(
32
+ stripTrailingWhitespace(normalizeSlashes(stripTimings(captureCalls(spy))))
33
+ )
34
+ );
33
35
  }
34
36
 
35
37
  function captureCalls(spy: jest.SpyInstance): string {
36
- return spy.mock.calls
37
- .map((args: unknown[]) => util.format("%s", ...args))
38
- .join("\n");
38
+ return spy.mock.calls
39
+ .map((args: unknown[]) => util.format("%s", ...args))
40
+ .join("\n");
39
41
  }
40
42
 
41
43
  export function mockConsoleMethods() {
42
- beforeEach(() => {
43
- logger.columns = 100;
44
- debugSpy = jest.spyOn(console, "debug").mockImplementation();
45
- logSpy = jest.spyOn(console, "log").mockImplementation();
46
- errorSpy = jest.spyOn(console, "error").mockImplementation();
47
- warnSpy = jest.spyOn(console, "warn").mockImplementation();
48
- });
49
- afterEach(() => {
50
- debugSpy.mockRestore();
51
- logSpy.mockRestore();
52
- errorSpy.mockRestore();
53
- warnSpy.mockRestore();
54
- });
55
- 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;
56
58
  }
57
59
 
58
60
  /**
@@ -61,7 +63,7 @@ export function mockConsoleMethods() {
61
63
  * Windows gets a different character.
62
64
  */
63
65
  function normalizeErrorMarkers(str: string): string {
64
- return str.replaceAll("✘", "X");
66
+ return str.replaceAll("✘", "X");
65
67
  }
66
68
 
67
69
  /**
@@ -70,7 +72,7 @@ function normalizeErrorMarkers(str: string): string {
70
72
  * Use this in snapshot tests to be resilient to file-system differences.
71
73
  */
72
74
  export function normalizeSlashes(str: string): string {
73
- return str.replace(/\\/g, "/");
75
+ return str.replace(/\\/g, "/");
74
76
  }
75
77
 
76
78
  /**
@@ -79,9 +81,17 @@ export function normalizeSlashes(str: string): string {
79
81
  * Use this in snapshot tests to be resilient to slight changes in timing of processing.
80
82
  */
81
83
  export function stripTimings(stdout: string): string {
82
- return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
84
+ return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
83
85
  }
84
86
 
85
87
  export function stripTrailingWhitespace(str: string): string {
86
- 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");
87
97
  }