wrangler 0.0.0-cd05d20 → 0.0.0-ce2d7d1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-cd05d20",
3
+ "version": "0.0.0-ce2d7d1",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
6
  "bin": {
@@ -38,41 +38,42 @@
38
38
  "dependencies": {
39
39
  "@cloudflare/pages-functions-compiler": "0.3.8",
40
40
  "esbuild": "0.14.1",
41
- "miniflare": "2.0.0-rc.3",
42
- "semiver": "^1.1.0",
43
- "serve": "^13.0.2"
41
+ "miniflare": "2.0.0-rc.4",
42
+ "semiver": "^1.1.0"
44
43
  },
45
44
  "optionalDependencies": {
46
45
  "fsevents": "~2.3.2"
47
46
  },
48
47
  "devDependencies": {
49
48
  "@iarna/toml": "^2.2.5",
50
- "@types/cloudflare": "^2.7.6",
51
- "@types/express": "^4.17.13",
49
+ "@types/mime": "^2.0.3",
52
50
  "@types/react": "^17.0.37",
51
+ "@types/serve-static": "^1.13.10",
53
52
  "@types/signal-exit": "^3.0.1",
54
53
  "@types/ws": "^8.2.1",
55
54
  "@types/yargs": "^17.0.7",
55
+ "chokidar": "^3.5.2",
56
56
  "clipboardy": "^3.0.0",
57
57
  "command-exists": "^1.2.9",
58
58
  "execa": "^6.0.0",
59
- "express": "^4.17.1",
59
+ "faye-websocket": "^0.11.4",
60
60
  "finalhandler": "^1.1.2",
61
61
  "find-up": "^6.2.0",
62
62
  "formdata-node": "^4.3.1",
63
- "http-proxy": "^1.18.1",
64
- "http-proxy-middleware": "^2.0.1",
65
63
  "ink": "^3.2.0",
66
64
  "ink-select-input": "^4.2.1",
67
65
  "ink-table": "^3.0.0",
68
66
  "ink-text-input": "^4.0.2",
67
+ "mime": "^3.0.0",
69
68
  "node-fetch": "^3.1.0",
70
69
  "open": "^8.4.0",
71
70
  "path-to-regexp": "^6.2.0",
72
71
  "react": "^17.0.2",
72
+ "react-error-boundary": "^3.1.4",
73
73
  "serve-static": "^1.14.1",
74
74
  "signal-exit": "^3.0.6",
75
75
  "tmp-promise": "^3.0.3",
76
+ "undici": "^4.11.1",
76
77
  "ws": "^8.3.0",
77
78
  "yargs": "^17.3.0"
78
79
  },
@@ -96,6 +97,7 @@
96
97
  "node": ">=16.7.0"
97
98
  },
98
99
  "jest": {
100
+ "restoreMocks": true,
99
101
  "testRegex": ".*.(test|spec)\\.[jt]sx?$",
100
102
  "transformIgnorePatterns": [
101
103
  "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
@@ -110,6 +112,9 @@
110
112
  "sourcemap": true
111
113
  }
112
114
  ]
113
- }
115
+ },
116
+ "setupFilesAfterEnv": [
117
+ "<rootDir>/src/__tests__/jest.setup.ts"
118
+ ]
114
119
  }
115
120
  }
@@ -1,153 +1,391 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as fsp from "node:fs/promises";
3
+ import * as os from "node:os";
3
4
  import * as path from "node:path";
4
5
  import * as TOML from "@iarna/toml";
5
6
  import { main } from "../index";
6
- // @ts-expect-error we're mocking cfetch, so of course setMock isn't a thing
7
- import { setMock, unsetAllMocks } from "../cfetch";
7
+ import { setMock, unsetAllMocks } from "./mock-cfetch";
8
+ import { mockConfirm } from "./mock-dialogs";
8
9
 
9
- jest.mock("../cfetch", () => {
10
- return jest.requireActual("./mock-cfetch");
11
- });
12
-
13
- async function w(cmd: void | string, options?: { tap: boolean }) {
14
- const tapped = options?.tap ? tap() : undefined;
15
- await main([...(cmd ? cmd.split(" ") : [])]);
16
- tapped?.off();
17
- return { stdout: tapped?.out, stderr: tapped?.err };
18
- }
10
+ jest.mock("../cfetch", () => jest.requireActual("./mock-cfetch"));
19
11
 
20
- function tap() {
21
- const oldLog = console.log;
22
- const oldError = console.error;
23
-
24
- const toReturn = {
25
- off: () => {
26
- console.log = oldLog;
27
- console.error = oldError;
28
- },
29
- out: "",
30
- err: "",
31
- };
32
-
33
- console.log = (...args) => {
34
- toReturn.out += args.join("");
35
- oldLog.apply(console, args);
36
- // console.trace(...args); // use this if you want to find the true source of your console.log
37
- };
38
- console.error = (...args) => {
39
- toReturn.err += args.join("");
40
- oldError.apply(console, args);
41
- };
42
-
43
- return toReturn;
12
+ async function w(cmd?: string) {
13
+ const logSpy = jest.spyOn(console, "log").mockImplementation();
14
+ const errorSpy = jest.spyOn(console, "error").mockImplementation();
15
+ const warnSpy = jest.spyOn(console, "warn").mockImplementation();
16
+ try {
17
+ await main(cmd?.split(" ") ?? []);
18
+ return {
19
+ stdout: logSpy.mock.calls.flat(2).join("\n"),
20
+ stderr: errorSpy.mock.calls.flat(2).join("\n"),
21
+ warnings: warnSpy.mock.calls.flat(2).join("\n"),
22
+ };
23
+ } finally {
24
+ logSpy.mockRestore();
25
+ errorSpy.mockRestore();
26
+ warnSpy.mockRestore();
27
+ }
44
28
  }
45
29
 
46
30
  describe("wrangler", () => {
47
- it("should run", async () => {
48
- const { stdout } = await w(undefined, { tap: true });
49
-
50
- expect(stdout).toMatchInlineSnapshot(`
51
- "wrangler
52
-
53
- Commands:
54
- wrangler init [name] 📥 Create a wrangler.toml configuration file
55
- wrangler dev <filename> 👂 Start a local server for developing your worker
56
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
57
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
58
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
59
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
60
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
61
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
62
- wrangler pages ⚡️ Configure Cloudflare Pages
63
-
64
- Flags:
65
- -c, --config Path to .toml configuration file [string]
66
- -h, --help Show help [boolean]
67
- -v, --version Show version number [boolean]
68
-
69
- Options:
70
- -l, --local Run on my machine [boolean] [default: false]"
71
- `);
31
+ describe("no command", () => {
32
+ it("should display a list of available commands", async () => {
33
+ const { stdout, stderr } = await w();
34
+
35
+ expect(stdout).toMatchInlineSnapshot(`
36
+ "wrangler
37
+
38
+ Commands:
39
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
40
+ wrangler dev <filename> 👂 Start a local server for developing your worker
41
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
42
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
43
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
44
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
45
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
46
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
47
+ wrangler pages ⚡️ Configure Cloudflare Pages
48
+
49
+ Flags:
50
+ -c, --config Path to .toml configuration file [string]
51
+ -h, --help Show help [boolean]
52
+ -v, --version Show version number [boolean]
53
+
54
+ Options:
55
+ -l, --local Run on my machine [boolean] [default: false]"
56
+ `);
57
+
58
+ expect(stderr).toMatchInlineSnapshot(`""`);
59
+ });
60
+ });
61
+
62
+ describe("invalid command", () => {
63
+ it("should display an error", async () => {
64
+ const { stdout, stderr } = await w("invalid-command");
65
+
66
+ expect(stdout).toMatchInlineSnapshot(`
67
+ "wrangler
68
+
69
+ Commands:
70
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
71
+ wrangler dev <filename> 👂 Start a local server for developing your worker
72
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
73
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
74
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
75
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
76
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
77
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
78
+ wrangler pages ⚡️ Configure Cloudflare Pages
79
+
80
+ Flags:
81
+ -c, --config Path to .toml configuration file [string]
82
+ -h, --help Show help [boolean]
83
+ -v, --version Show version number [boolean]
84
+
85
+ Options:
86
+ -l, --local Run on my machine [boolean] [default: false]"
87
+ `);
88
+
89
+ expect(stderr).toMatchInlineSnapshot(`
90
+ "
91
+ Unknown command: invalid-command."
92
+ `);
93
+ });
72
94
  });
73
95
 
74
96
  describe("init", () => {
75
97
  const ogcwd = process.cwd();
98
+ let tmpDir: string;
76
99
 
77
- beforeEach(() => {
78
- process.chdir(path.join(__dirname, "fixtures", "init"));
100
+ beforeEach(async () => {
101
+ tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "init-"));
102
+ process.chdir(tmpDir);
79
103
  });
80
104
 
81
105
  afterEach(async () => {
82
- await fsp.rm("./wrangler.toml");
83
106
  process.chdir(ogcwd);
107
+ await fsp.rm(tmpDir, { recursive: true });
84
108
  });
85
109
 
86
110
  it("should create a wrangler.toml", async () => {
111
+ mockConfirm({
112
+ text: "No package.json found. Would you like to create one?",
113
+ result: false,
114
+ });
87
115
  await w("init");
88
116
  const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
89
117
  expect(typeof parsed.compatibility_date).toBe("string");
118
+ expect(fs.existsSync("./package.json")).toBe(false);
119
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
90
120
  });
91
121
 
92
- it("should error when wrangler.toml already exists", async () => {
122
+ it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
93
123
  fs.closeSync(fs.openSync("./wrangler.toml", "w"));
94
- const { stderr } = await w("init", { tap: true });
95
- expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
124
+ mockConfirm({
125
+ text: "Do you want to continue initializing this project?",
126
+ result: false,
127
+ });
128
+ const { stderr } = await w("init");
129
+ expect(stderr).toContain("wrangler.toml file already exists!");
130
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
131
+ expect(typeof parsed.compatibility_date).toBe("undefined");
132
+ });
133
+
134
+ it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
135
+ fs.closeSync(fs.openSync("./wrangler.toml", "w"));
136
+ mockConfirm(
137
+ {
138
+ text: "Do you want to continue initializing this project?",
139
+ result: true,
140
+ },
141
+ {
142
+ text: "No package.json found. Would you like to create one?",
143
+ result: false,
144
+ }
145
+ );
146
+ const { stderr } = await w("init");
147
+ expect(stderr).toContain("wrangler.toml file already exists!");
148
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
149
+ expect(typeof parsed.compatibility_date).toBe("string");
150
+ });
151
+
152
+ it("should create a package.json if none is found and user confirms", async () => {
153
+ mockConfirm(
154
+ {
155
+ text: "No package.json found. Would you like to create one?",
156
+ result: true,
157
+ },
158
+ {
159
+ text: "Would you like to use typescript?",
160
+ result: false,
161
+ }
162
+ );
163
+ await w("init");
164
+ expect(fs.existsSync("./package.json")).toBe(true);
165
+ const packageJson = JSON.parse(
166
+ fs.readFileSync("./package.json", "utf-8")
167
+ );
168
+ expect(packageJson.name).toEqual("worker"); // TODO: should we infer the name from the directory?
169
+ expect(packageJson.version).toEqual("0.0.1");
170
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
171
+ });
172
+
173
+ it("should not touch an existing package.json in the same directory", async () => {
174
+ mockConfirm({
175
+ text: "Would you like to use typescript?",
176
+ result: false,
177
+ });
178
+
179
+ fs.writeFileSync(
180
+ "./package.json",
181
+ JSON.stringify({ name: "test", version: "1.0.0" }),
182
+ "utf-8"
183
+ );
184
+
185
+ await w("init");
186
+ const packageJson = JSON.parse(
187
+ fs.readFileSync("./package.json", "utf-8")
188
+ );
189
+ expect(packageJson.name).toEqual("test");
190
+ expect(packageJson.version).toEqual("1.0.0");
191
+ });
192
+
193
+ it("should not touch an existing package.json in an ancestor directory", async () => {
194
+ mockConfirm({
195
+ text: "Would you like to use typescript?",
196
+ result: false,
197
+ });
198
+
199
+ fs.writeFileSync(
200
+ "./package.json",
201
+ JSON.stringify({ name: "test", version: "1.0.0" }),
202
+ "utf-8"
203
+ );
204
+
205
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
206
+ process.chdir("./sub-1/sub-2");
207
+
208
+ await w("init");
209
+ expect(fs.existsSync("./package.json")).toBe(false);
210
+ expect(fs.existsSync("../../package.json")).toBe(true);
211
+
212
+ const packageJson = JSON.parse(
213
+ fs.readFileSync("../../package.json", "utf-8")
214
+ );
215
+ expect(packageJson.name).toEqual("test");
216
+ expect(packageJson.version).toEqual("1.0.0");
217
+ });
218
+
219
+ it("should create a tsconfig.json and install `workers-types` if none is found and user confirms", async () => {
220
+ mockConfirm(
221
+ {
222
+ text: "No package.json found. Would you like to create one?",
223
+ result: true,
224
+ },
225
+ {
226
+ text: "Would you like to use typescript?",
227
+ result: true,
228
+ }
229
+ );
230
+ await w("init");
231
+ expect(fs.existsSync("./tsconfig.json")).toBe(true);
232
+ const tsconfigJson = JSON.parse(
233
+ fs.readFileSync("./tsconfig.json", "utf-8")
234
+ );
235
+ expect(tsconfigJson.compilerOptions.types).toEqual([
236
+ "@cloudflare/workers-types",
237
+ ]);
238
+ const packageJson = JSON.parse(
239
+ fs.readFileSync("./package.json", "utf-8")
240
+ );
241
+ expect(packageJson.devDependencies).toEqual({
242
+ "@cloudflare/workers-types": expect.any(String),
243
+ });
244
+ });
245
+
246
+ it("should not touch an existing tsconfig.json in the same directory", async () => {
247
+ fs.writeFileSync(
248
+ "./package.json",
249
+ JSON.stringify({ name: "test", version: "1.0.0" }),
250
+ "utf-8"
251
+ );
252
+ fs.writeFileSync(
253
+ "./tsconfig.json",
254
+ JSON.stringify({ compilerOptions: {} }),
255
+ "utf-8"
256
+ );
257
+
258
+ await w("init");
259
+ const tsconfigJson = JSON.parse(
260
+ fs.readFileSync("./tsconfig.json", "utf-8")
261
+ );
262
+ expect(tsconfigJson.compilerOptions).toEqual({});
263
+ });
264
+
265
+ it("should not touch an existing package.json in an ancestor directory", async () => {
266
+ fs.writeFileSync(
267
+ "./package.json",
268
+ JSON.stringify({ name: "test", version: "1.0.0" }),
269
+ "utf-8"
270
+ );
271
+ fs.writeFileSync(
272
+ "./tsconfig.json",
273
+ JSON.stringify({ compilerOptions: {} }),
274
+ "utf-8"
275
+ );
276
+
277
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
278
+ process.chdir("./sub-1/sub-2");
279
+
280
+ await w("init");
281
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
282
+ expect(fs.existsSync("../../tsconfig.json")).toBe(true);
283
+
284
+ const tsconfigJson = JSON.parse(
285
+ fs.readFileSync("../../tsconfig.json", "utf-8")
286
+ );
287
+ expect(tsconfigJson.compilerOptions).toEqual({});
288
+ });
289
+
290
+ it("should error if `--type` is used", async () => {
291
+ const noValue = await w("init --type");
292
+ expect(noValue.stderr).toMatchInlineSnapshot(
293
+ `"The --type option is no longer supported."`
294
+ );
295
+ });
296
+
297
+ it("should error if `--type javascript` is used", async () => {
298
+ const javascriptValue = await w("init --type javascript");
299
+ expect(javascriptValue.stderr).toMatchInlineSnapshot(
300
+ `"The --type option is no longer supported."`
301
+ );
302
+ });
303
+
304
+ it("should error if `--type rust` is used", async () => {
305
+ const rustValue = await w("init --type rust");
306
+ expect(rustValue.stderr).toMatchInlineSnapshot(
307
+ `"The --type option is no longer supported."`
308
+ );
309
+ });
310
+
311
+ it("should error if `--type webpack` is used", async () => {
312
+ const webpackValue = await w("init --type webpack");
313
+ expect(webpackValue.stderr).toMatchInlineSnapshot(`
314
+ "The --type option is no longer supported.
315
+ If you wish to use webpack then you will need to create a custom build."
316
+ `);
96
317
  });
97
318
  });
98
319
 
99
320
  describe("kv:namespace", () => {
100
- afterAll(() => {
321
+ afterEach(() => {
101
322
  unsetAllMocks();
102
323
  });
103
- let KVNamespaces: { title: string; id: string }[] = [];
324
+
104
325
  it("can create a namespace", async () => {
326
+ const KVNamespaces: { title: string; id: string }[] = [];
105
327
  setMock("/accounts/:accountId/storage/kv/namespaces", (uri, init) => {
106
328
  expect(init.method === "POST");
107
- const body = JSON.parse(init.body);
108
- expect(body.title).toBe("worker-UnitTestNamespace");
109
- KVNamespaces.push({ title: body.title, id: "some-namespace-id" });
329
+ expect(uri[0]).toEqual(
330
+ "/accounts/some-account-id/storage/kv/namespaces"
331
+ );
332
+ const { title } = JSON.parse(init.body);
333
+ expect(title).toEqual("worker-UnitTestNamespace");
334
+ KVNamespaces.push({ title, id: "some-namespace-id" });
110
335
  return { id: "some-namespace-id" };
111
336
  });
112
337
 
113
338
  await w("kv:namespace create UnitTestNamespace");
114
- expect(
115
- KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
- ).toBeTruthy();
339
+
340
+ expect(KVNamespaces).toEqual([
341
+ {
342
+ title: "worker-UnitTestNamespace",
343
+ id: "some-namespace-id",
344
+ },
345
+ ]);
117
346
  });
118
347
 
119
- let createdNamespace: { id: string; title: string };
120
348
  it("can list namespaces", async () => {
349
+ const KVNamespaces: { title: string; id: string }[] = [
350
+ { title: "title-1", id: "id-1" },
351
+ { title: "title-2", id: "id-2" },
352
+ ];
121
353
  setMock(
122
354
  "/accounts/:accountId/storage/kv/namespaces\\?:qs",
123
355
  (uri, init) => {
356
+ expect(uri[0]).toContain(
357
+ "/accounts/some-account-id/storage/kv/namespaces"
358
+ );
359
+ expect(uri[2]).toContain("per_page=100");
360
+ expect(uri[2]).toContain("order=title");
361
+ expect(uri[2]).toContain("direction=asc");
362
+ expect(uri[2]).toContain("page=1");
124
363
  expect(init).toBe(undefined);
125
364
  return KVNamespaces;
126
365
  }
127
366
  );
128
- const { stdout } = await w("kv:namespace list", { tap: true });
129
- const namespaces = JSON.parse(stdout);
130
- createdNamespace = namespaces.find(
131
- (ns) => ns.title === "worker-UnitTestNamespace"
132
- );
133
- expect(createdNamespace.title).toBe("worker-UnitTestNamespace");
367
+ const { stdout } = await w("kv:namespace list");
368
+ const namespaces = JSON.parse(stdout) as { id: string; title: string }[];
369
+ expect(namespaces).toEqual(KVNamespaces);
134
370
  });
135
371
 
136
372
  it("can delete a namespace", async () => {
137
- const namespaceIdToDelete = createdNamespace.id;
373
+ let accountId = "";
374
+ let namespaceId = "";
138
375
  setMock(
139
376
  "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
140
377
  (uri, init) => {
141
- expect(init.method).toBe("DELETE");
142
- KVNamespaces = KVNamespaces.filter(
143
- (ns) => ns.id !== namespaceIdToDelete
378
+ accountId = uri[1];
379
+ namespaceId = uri[2];
380
+ expect(uri[0]).toEqual(
381
+ "/accounts/some-account-id/storage/kv/namespaces/some-namespace-id"
144
382
  );
383
+ expect(init.method).toBe("DELETE");
145
384
  }
146
385
  );
147
- await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
- expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
- undefined
150
- );
386
+ await w(`kv:namespace delete --namespace-id some-namespace-id`);
387
+ expect(accountId).toEqual("some-account-id");
388
+ expect(namespaceId).toEqual("some-namespace-id");
151
389
  });
152
390
  });
153
391
  });
@@ -0,0 +1,17 @@
1
+ import { confirm, prompt } from "../dialogs";
2
+
3
+ jest.mock("../dialogs");
4
+
5
+ // By default (if not configured by mockConfirm()) calls to `confirm()` should throw.
6
+ (confirm as jest.Mock).mockImplementation(() => {
7
+ throw new Error(
8
+ "Unexpected call to `confirm()`. You should use `mockConfirm()` to mock calls to `confirm()` with expectations. Search the codebase for `mockConfirm` to learn more."
9
+ );
10
+ });
11
+
12
+ // By default (if not configured by mockPrompt()) calls to `prompt()` should throw.
13
+ (prompt as jest.Mock).mockImplementation(() => {
14
+ throw new Error(
15
+ "Unexpected call to `prompt()`. You should use `mockPrompt()` to mock calls to `prompt()` with expectations. Search the codebase for `mockPrompt` to learn more."
16
+ );
17
+ });
@@ -1,23 +1,26 @@
1
1
  // This file mocks ../cfetch.ts
2
2
  // so we can insert whatever responses we want from it
3
3
 
4
- const pathToRegexp = require("path-to-regexp");
4
+ const { pathToRegexp } = require("path-to-regexp");
5
5
  // TODO: add jsdoc style types here
6
6
 
7
7
  // type MockHandler = (resource: string, init?: RequestInit) => any; // TODO: use a generic here
8
8
 
9
9
  let mocks = [];
10
10
 
11
- function mockCfetch(resource, init) {
11
+ export function mockCfetch(resource, init) {
12
12
  for (const { regexp, handler } of mocks) {
13
- if (regexp.test(resource)) {
14
- return handler(resource, init); // should we have some kind of fallthrough system? we'll see.
13
+ // The `resource` regular expression will extract the labelled groups from the URL.
14
+ // Let's pass these through to the handler, to allow it to do additional checks or behaviour.
15
+ const uri = regexp.exec(resource);
16
+ if (uri !== null) {
17
+ return handler(uri, init); // TODO: should we have some kind of fallthrough system? we'll see.
15
18
  }
16
19
  }
17
20
  throw new Error(`no mocks found for ${resource}`);
18
21
  }
19
22
 
20
- function setMock(resource, handler) {
23
+ export function setMock(resource, handler) {
21
24
  const mock = {
22
25
  resource,
23
26
  handler,
@@ -29,18 +32,11 @@ function setMock(resource, handler) {
29
32
  };
30
33
  }
31
34
 
32
- function unsetAllMocks() {
35
+ export function unsetAllMocks() {
33
36
  mocks = [];
34
37
  }
35
38
 
36
- const CF_API_BASE_URL =
39
+ export const CF_API_BASE_URL =
37
40
  process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
38
41
 
39
- Object.assign(module.exports, {
40
- __esModule: true,
41
- default: mockCfetch,
42
- mockCfetch,
43
- setMock,
44
- unsetAllMocks,
45
- CF_API_BASE_URL,
46
- });
42
+ export default mockCfetch;