wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +715 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1381 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
+ import type { UrlPath } from "../../src/paths";
5
+
6
+ export const HTTP_METHODS = [
7
+ "HEAD",
8
+ "OPTIONS",
9
+ "GET",
10
+ "POST",
11
+ "PUT",
12
+ "PATCH",
13
+ "DELETE",
14
+ ] as const;
15
+ export type HTTPMethod = typeof HTTP_METHODS[number];
16
+ export function isHTTPMethod(
17
+ maybeHTTPMethod: string
18
+ ): maybeHTTPMethod is HTTPMethod {
19
+ return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
20
+ }
21
+
22
+ export type RoutesCollection = Array<{
23
+ routePath: UrlPath;
24
+ method?: HTTPMethod;
25
+ modules: string[];
26
+ middlewares: string[];
27
+ }>;
28
+
29
+ export type Config = {
30
+ routes?: RouteConfig[];
31
+ schedules?: unknown;
32
+ };
33
+
34
+ export type RouteConfig = {
35
+ routePath: UrlPath;
36
+ method?: HTTPMethod;
37
+ middleware?: string | string[];
38
+ module?: string | string[];
39
+ };
40
+
41
+ type ImportMap = Map<
42
+ string,
43
+ {
44
+ filepath: string;
45
+ name: string;
46
+ identifier: string;
47
+ }
48
+ >;
49
+
50
+ type Arguments = {
51
+ config: Config;
52
+ outfile: string;
53
+ srcDir: string;
54
+ };
55
+
56
+ export async function writeRoutesModule({
57
+ config,
58
+ srcDir,
59
+ outfile = "_routes.js",
60
+ }: Arguments) {
61
+ const { importMap, routes } = parseConfig(config, srcDir);
62
+ const routesModule = generateRoutesModule(importMap, routes);
63
+
64
+ await fs.writeFile(outfile, routesModule);
65
+
66
+ return outfile;
67
+ }
68
+
69
+ export function parseConfig(config: Config, baseDir: string) {
70
+ const routes: RoutesCollection = [];
71
+ const importMap: ImportMap = new Map();
72
+ const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
73
+
74
+ function parseModuleIdentifiers(paths: string | string[] | undefined) {
75
+ if (typeof paths === "undefined") {
76
+ paths = [];
77
+ }
78
+
79
+ if (typeof paths === "string") {
80
+ paths = [paths];
81
+ }
82
+
83
+ return paths.map((modulePath) => {
84
+ const [filepath, name = "default"] = modulePath.split(":");
85
+ let { identifier } = importMap.get(modulePath) ?? {};
86
+
87
+ const resolvedPath = path.resolve(baseDir, filepath);
88
+
89
+ // ensure the filepath isn't attempting to resolve to anything outside of the project
90
+ if (path.relative(baseDir, resolvedPath).startsWith("..")) {
91
+ throw new Error(`Invalid module path "${filepath}"`);
92
+ }
93
+
94
+ // ensure the module name (if provided) is a valid identifier to guard against injection attacks
95
+ if (name !== "default" && !isValidIdentifier(name)) {
96
+ throw new Error(`Invalid module identifier "${name}"`);
97
+ }
98
+
99
+ if (!identifier) {
100
+ identifier = normalizeIdentifier(`__${filepath}_${name}`);
101
+
102
+ let count = identifierCount.get(identifier) ?? 0;
103
+ identifierCount.set(identifier, ++count);
104
+
105
+ if (count > 1) {
106
+ identifier += `_${count}`;
107
+ }
108
+
109
+ importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
110
+ }
111
+
112
+ return identifier;
113
+ });
114
+ }
115
+
116
+ for (const { routePath, method, ...props } of config.routes ?? []) {
117
+ routes.push({
118
+ routePath,
119
+ method,
120
+ middlewares: parseModuleIdentifiers(props.middleware),
121
+ modules: parseModuleIdentifiers(props.module),
122
+ });
123
+ }
124
+
125
+ return { routes, importMap };
126
+ }
127
+
128
+ export function generateRoutesModule(
129
+ importMap: ImportMap,
130
+ routes: RoutesCollection
131
+ ) {
132
+ return `${[...importMap.values()]
133
+ .map(
134
+ ({ filepath, name, identifier }) =>
135
+ `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
136
+ )
137
+ .join("\n")}
138
+
139
+ export const routes = [
140
+ ${routes
141
+ .map(
142
+ (route) => ` {
143
+ routePath: "${route.routePath}",
144
+ method: "${route.method}",
145
+ middlewares: [${route.middlewares.join(", ")}],
146
+ modules: [${route.modules.join(", ")}],
147
+ },`
148
+ )
149
+ .join("\n")}
150
+ ]`;
151
+ }
@@ -0,0 +1,130 @@
1
+ import { match } from "path-to-regexp";
2
+ import type { HTTPMethod } from "./routes";
3
+
4
+ /* TODO: Grab these from @cloudflare/workers-types instead */
5
+ type Params<P extends string = string> = Record<P, string | string[]>;
6
+
7
+ type EventContext<Env, P extends string, Data> = {
8
+ request: Request;
9
+ waitUntil: (promise: Promise<unknown>) => void;
10
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
+ env: Env & { ASSETS: { fetch: typeof fetch } };
12
+ params: Params<P>;
13
+ data: Data;
14
+ };
15
+
16
+ declare type PagesFunction<
17
+ Env = unknown,
18
+ P extends string = string,
19
+ Data extends Record<string, unknown> = Record<string, unknown>
20
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
21
+ /* end @cloudflare/workers-types */
22
+
23
+ type RouteHandler = {
24
+ routePath: string;
25
+ method?: HTTPMethod;
26
+ modules: PagesFunction[];
27
+ middlewares: PagesFunction[];
28
+ };
29
+
30
+ // inject `routes` via ESBuild
31
+ declare const routes: RouteHandler[];
32
+ // define `__FALLBACK_SERVICE__` via ESBuild
33
+ declare const __FALLBACK_SERVICE__: string;
34
+
35
+ // expect an ASSETS fetcher binding pointing to the asset-server stage
36
+ type FetchEnv = {
37
+ [name: string]: { fetch: typeof fetch };
38
+ ASSETS: { fetch: typeof fetch };
39
+ };
40
+
41
+ type WorkerContext = {
42
+ waitUntil: (promise: Promise<unknown>) => void;
43
+ };
44
+
45
+ function* executeRequest(request: Request, _env: FetchEnv) {
46
+ const requestPath = new URL(request.url).pathname;
47
+
48
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
49
+ for (const route of [...routes].reverse()) {
50
+ if (route.method && route.method !== request.method) {
51
+ continue;
52
+ }
53
+
54
+ const routeMatcher = match(route.routePath, { end: false });
55
+ const matchResult = routeMatcher(requestPath);
56
+ if (matchResult) {
57
+ for (const handler of route.middlewares.flat()) {
58
+ yield {
59
+ handler,
60
+ params: matchResult.params as Params,
61
+ };
62
+ }
63
+ }
64
+ }
65
+
66
+ // Then look for the first exact route match and execute its "modules"
67
+ for (const route of routes) {
68
+ if (route.method && route.method !== request.method) {
69
+ continue;
70
+ }
71
+
72
+ const routeMatcher = match(route.routePath, { end: true });
73
+ const matchResult = routeMatcher(requestPath);
74
+ if (matchResult && route.modules.length) {
75
+ for (const handler of route.modules.flat()) {
76
+ yield {
77
+ handler,
78
+ params: matchResult.params as Params,
79
+ };
80
+ }
81
+ break;
82
+ }
83
+ }
84
+ }
85
+
86
+ export default {
87
+ async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
88
+ const handlerIterator = executeRequest(request, env);
89
+ const data = {}; // arbitrary data the user can set between functions
90
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
91
+ if (input !== undefined) {
92
+ request = new Request(input, init);
93
+ }
94
+
95
+ const result = handlerIterator.next();
96
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
97
+ if (result.done == false) {
98
+ const { handler, params } = result.value;
99
+ const context = {
100
+ request: new Request(request.clone()),
101
+ next,
102
+ params,
103
+ data,
104
+ env,
105
+ waitUntil: workerContext.waitUntil.bind(workerContext),
106
+ };
107
+
108
+ const response = await handler(context);
109
+
110
+ // https://fetch.spec.whatwg.org/#null-body-status
111
+ return new Response(
112
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
113
+ response
114
+ );
115
+ } else if (__FALLBACK_SERVICE__) {
116
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
117
+ return env[__FALLBACK_SERVICE__].fetch(request);
118
+ } else {
119
+ // There was not fallback service so actually make the request to the origin.
120
+ return fetch(request);
121
+ }
122
+ };
123
+
124
+ try {
125
+ return next();
126
+ } catch (err) {
127
+ return new Response("Internal Error", { status: 500 });
128
+ }
129
+ },
130
+ };
@@ -0,0 +1,73 @@
1
+ import { render } from "ink-testing-library";
2
+ import patchConsole from "patch-console";
3
+ import React from "react";
4
+ import Dev from "../dev";
5
+ import type { DevProps } from "../dev";
6
+
7
+ describe("Dev component", () => {
8
+ let restoreConsole: ReturnType<typeof patchConsole>;
9
+ beforeEach(() => (restoreConsole = patchConsole(() => {})));
10
+ afterEach(() => restoreConsole());
11
+
12
+ // This test needs to be rewritten because the error now throws asynchronously
13
+ // and the Ink framework does not yet have async testing support.
14
+ it.skip("should throw if format is service-worker and there is a public directory", () => {
15
+ const { lastFrame } = renderDev({
16
+ format: "service-worker",
17
+ accountId: "some-account-id",
18
+ public: "some/public/path",
19
+ });
20
+ expect(lastFrame()?.split("\n").slice(0, 2).join("\n"))
21
+ .toMatchInlineSnapshot(`
22
+ "Something went wrong:
23
+ Error: You cannot use the service worker format with a \`public\` directory."
24
+ `);
25
+ });
26
+ });
27
+
28
+ /**
29
+ * Helper function to make it easier to setup and render the `Dev` component.
30
+ *
31
+ * All the `Dev` props are optional here, with sensible defaults for testing.
32
+ */
33
+ function renderDev({
34
+ name,
35
+ entry = "some/entry.ts",
36
+ port,
37
+ format,
38
+ accountId,
39
+ initialMode = "local",
40
+ jsxFactory,
41
+ jsxFragment,
42
+ bindings = {},
43
+ public: publicDir,
44
+ assetPaths,
45
+ compatibilityDate,
46
+ compatibilityFlags,
47
+ usageModel,
48
+ buildCommand = {},
49
+ enableLocalPersistence = false,
50
+ env = undefined,
51
+ }: Partial<DevProps>) {
52
+ return render(
53
+ <Dev
54
+ name={name}
55
+ entry={entry}
56
+ env={env}
57
+ port={port}
58
+ buildCommand={buildCommand}
59
+ format={format}
60
+ initialMode={initialMode}
61
+ jsxFactory={jsxFactory}
62
+ jsxFragment={jsxFragment}
63
+ accountId={accountId}
64
+ assetPaths={assetPaths}
65
+ public={publicDir}
66
+ compatibilityDate={compatibilityDate}
67
+ compatibilityFlags={compatibilityFlags}
68
+ usageModel={usageModel}
69
+ bindings={bindings}
70
+ enableLocalPersistence={enableLocalPersistence}
71
+ />
72
+ );
73
+ }
@@ -0,0 +1,51 @@
1
+ import { writeFile } from "fs/promises";
2
+ import path from "path";
3
+ import guessWorkerFormat from "../guess-worker-format";
4
+ import { runInTempDir } from "./helpers/run-in-tmp";
5
+
6
+ describe("guess worker format", () => {
7
+ runInTempDir();
8
+ it('should detect a "modules" worker', async () => {
9
+ await writeFile("./index.ts", "export default {};");
10
+ // Note that this isn't actually a valid worker, because it's missing
11
+ // a fetch handler. Regardless, our heuristic is simply to check for exports.
12
+ const guess = await guessWorkerFormat(
13
+ path.join(process.cwd(), "./index.ts"),
14
+ undefined
15
+ );
16
+ expect(guess).toBe("modules");
17
+ });
18
+
19
+ it('should detect a "service-worker" worker', async () => {
20
+ await writeFile("./index.ts", "");
21
+ // Note that this isn't actually a valid worker, because it's missing
22
+ // a fetch listener. Regardless, our heuristic is simply to check for
23
+ // the lack of exports.
24
+ const guess = await guessWorkerFormat(
25
+ path.join(process.cwd(), "./index.ts"),
26
+ undefined
27
+ );
28
+ expect(guess).toBe("service-worker");
29
+ });
30
+
31
+ it("should throw an error when the hint doesn't match the guess (modules - service-worker)", async () => {
32
+ await writeFile("./index.ts", "export default {};");
33
+ await expect(
34
+ guessWorkerFormat(
35
+ path.join(process.cwd(), "./index.ts"),
36
+ "service-worker"
37
+ )
38
+ ).rejects.toThrow(
39
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have es module exports. Please pass `--format modules`, or simply remove the configuration."
40
+ );
41
+ });
42
+
43
+ it("should throw an error when the hint doesn't match the guess (service-worker - modules)", async () => {
44
+ await writeFile("./index.ts", "");
45
+ await expect(
46
+ guessWorkerFormat(path.join(process.cwd(), "./index.ts"), "modules")
47
+ ).rejects.toThrow(
48
+ "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
49
+ );
50
+ });
51
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The typings file available at `@types/cmd-shim` are out of date.
3
+ */
4
+ module "cmd-shim" {
5
+ /**
6
+ *
7
+ * Create a cmd shim at `to` for the command line program at `from`.
8
+ *
9
+ */
10
+ export default function cmdShim(from: string, to: string): Promise<void>;
11
+ }
@@ -0,0 +1,30 @@
1
+ const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN;
2
+ const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID;
3
+
4
+ /**
5
+ * Mock the API token so that we don't need to read it from user configuration files.
6
+ */
7
+ export function mockApiToken({
8
+ apiToken = "some-api-token",
9
+ }: { apiToken?: string } = {}) {
10
+ beforeEach(() => {
11
+ process.env.CF_API_TOKEN = apiToken;
12
+ });
13
+ afterEach(() => {
14
+ process.env.CF_API_TOKEN = ORIGINAL_CF_API_TOKEN;
15
+ });
16
+ }
17
+
18
+ /**
19
+ * Mock the current account ID so that we don't need to read it from configuration files.
20
+ */
21
+ export function mockAccountId({
22
+ accountId = "some-account-id",
23
+ }: { accountId?: string } = {}) {
24
+ beforeEach(() => {
25
+ process.env.CF_ACCOUNT_ID = accountId;
26
+ });
27
+ afterEach(() => {
28
+ process.env.CF_ACCOUNT_ID = ORIGINAL_CF_ACCOUNT_ID;
29
+ });
30
+ }
@@ -0,0 +1,33 @@
1
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, resolve } from "node:path";
3
+ import cmdShim from "cmd-shim";
4
+
5
+ const nodeShebang = "#!/usr/bin/env node";
6
+
7
+ /**
8
+ * Create a binary file in a temp directory and make it available on the PATH.
9
+ */
10
+ export async function mockBinary(binaryName: string, code: string) {
11
+ // Ensure there is a directory to put the mock binary in.
12
+ const tmpDir = resolve(mkdtempSync(".mock-binary-"));
13
+
14
+ // Use a fake extension on Windows because we will create a cmd-shim to run the binary.
15
+ const extension = process.platform === "win32" ? ".x-mock-bin" : "";
16
+ const filePath = resolve(tmpDir, `${binaryName}${extension}`);
17
+ writeFileSync(filePath, nodeShebang + "\n" + code);
18
+ chmodSync(filePath, 0o777);
19
+
20
+ if (process.platform === "win32") {
21
+ await cmdShim(filePath, basename(filePath, ".x-mock-bin"));
22
+ }
23
+
24
+ // Update PATH using the appropriate separator for the platform.
25
+ const oldPath = process.env.PATH;
26
+ const sep = process.platform === "win32" ? ";" : ":";
27
+ process.env.PATH = tmpDir + sep + oldPath;
28
+
29
+ return function unMock() {
30
+ rmSync(tmpDir, { recursive: true });
31
+ process.env.PATH = process.env.PATH?.replace(tmpDir + sep, "");
32
+ };
33
+ }
@@ -0,0 +1,207 @@
1
+ import { URL, URLSearchParams } from "node:url";
2
+ import { pathToRegexp } from "path-to-regexp";
3
+ import { CF_API_BASE_URL } from "../../cfetch";
4
+ import type { FetchResult } from "../../cfetch";
5
+ import type { RequestInit } from "undici";
6
+
7
+ /**
8
+ * The signature of the function that will handle a mock request.
9
+ */
10
+ export type MockHandler<ResponseType> = (
11
+ uri: RegExpExecArray,
12
+ init: RequestInit,
13
+ queryParams: URLSearchParams
14
+ ) => ResponseType | Promise<ResponseType>;
15
+
16
+ type RemoveMockFn = () => void;
17
+
18
+ interface MockFetch<ResponseType> {
19
+ regexp: RegExp;
20
+ method: string | undefined;
21
+ handler: MockHandler<ResponseType>;
22
+ }
23
+ const mocks: MockFetch<unknown>[] = [];
24
+
25
+ /**
26
+ * The mock implementation of `cfApi.fetch()`.
27
+ *
28
+ * This function will attempt to match the given request to one of the mock handlers configured by calls to `setMock`.
29
+ *
30
+ * Once found the handler will be used to generate a mock response.
31
+ */
32
+ export async function mockFetchInternal(
33
+ resource: string,
34
+ init: RequestInit = {},
35
+ queryParams: URLSearchParams = new URLSearchParams()
36
+ ) {
37
+ for (const { regexp, method, handler } of mocks) {
38
+ const resourcePath = new URL(resource, CF_API_BASE_URL).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
+ );
50
+ }
51
+
52
+ /**
53
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
54
+ *
55
+ * @param resource The path of the resource to be matched.
56
+ * This can include wildcards whose value will be passed to the `handler`.
57
+ * @param handler The function that will generate the mock response for this request.
58
+ */
59
+ export function setMockRawResponse<ResponseType>(
60
+ resource: string,
61
+ handler: MockHandler<ResponseType>
62
+ ): RemoveMockFn;
63
+ /**
64
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
65
+ *
66
+ * @param resource The path of the resource to be matched.
67
+ * This can include wildcards whose value will be passed to the `handler`.
68
+ * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
69
+ * @param handler The function that will generate the mock response for this request.
70
+ */
71
+ export function setMockRawResponse<ResponseType>(
72
+ resource: string,
73
+ method: string,
74
+ handler: MockHandler<ResponseType>
75
+ ): RemoveMockFn;
76
+ /**
77
+ * Specify an expected resource path that is to be handled, resulting in a raw JSON response.
78
+ */
79
+ export function setMockRawResponse<ResponseType>(
80
+ resource: string,
81
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
82
+ ): 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
+ };
98
+ }
99
+
100
+ /**
101
+ * Specify an expected resource path that is to be handled, resulting in a `FetchRequest`.
102
+ *
103
+ * The mock `handler` should return the `result`, which will then be wrapped in a `FetchRequest` object.
104
+ *
105
+ * @param resource The path of the resource to be matched.
106
+ * This can include wildcards whose value will be passed to the `handler`.
107
+ * @param handler The function that will generate the mock response for this request.
108
+ */
109
+ export function setMockResponse<ResponseType>(
110
+ resource: string,
111
+ handler: MockHandler<ResponseType>
112
+ ): RemoveMockFn;
113
+ /**
114
+ * Specify an expected resource path that is to be handled, resulting in a FetchRequest..
115
+ *
116
+ * @param resource The path of the resource to be matched.
117
+ * This can include wildcards whose value will be passed to the `handler`.
118
+ * @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
119
+ * @param handler The function that will generate the mock response for this request.
120
+ */
121
+ export function setMockResponse<ResponseType>(
122
+ resource: string,
123
+ method: string,
124
+ handler: MockHandler<ResponseType>
125
+ ): RemoveMockFn;
126
+ /**
127
+ * Specify an expected resource path that is to be handled, resulting in a FetchRequest.
128
+ */
129
+ export function setMockResponse<ResponseType>(
130
+ resource: string,
131
+ ...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
132
+ ): 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
+ );
138
+ }
139
+
140
+ /**
141
+ * A helper to make it easier to create `FetchResult` objects in tests.
142
+ */
143
+ export async function createFetchResult<ResponseType>(
144
+ result: ResponseType | Promise<ResponseType>,
145
+ success = true,
146
+ errors = [],
147
+ messages = [],
148
+ result_info?: unknown
149
+ ): 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
+ };
164
+ }
165
+
166
+ /**
167
+ * Remove all the configured mock handlers.
168
+ *
169
+ * This should be called in an `afterEach()` block to ensure that mock handlers do not leak between tests.
170
+ */
171
+ export function unsetAllMocks() {
172
+ mocks.length = 0;
173
+ }
174
+
175
+ /**
176
+ * We special-case fetching the request for `kv:key get`, because it's
177
+ * the only cloudflare API endpoint that returns a plain string as the
178
+ * value, and not as the "standard" FetchResult-style json. Hence, we also
179
+ * special-case mocking it here.
180
+ */
181
+
182
+ const kvGetMocks = new Map<string, string>();
183
+
184
+ export function mockFetchKVGetValue(
185
+ accountId: string,
186
+ namespaceId: string,
187
+ key: string
188
+ ) {
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}`);
194
+ }
195
+
196
+ export function setMockFetchKVGetValue(
197
+ accountId: string,
198
+ namespaceId: string,
199
+ key: string,
200
+ value: string
201
+ ) {
202
+ kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
203
+ }
204
+
205
+ export function unsetMockFetchKVGetValues() {
206
+ kvGetMocks.clear();
207
+ }