wrangler 0.0.0-e2a26a0 → 0.0.0-e2b3306e1

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 (136) hide show
  1. package/README.md +44 -25
  2. package/bin/wrangler.js +95 -32
  3. package/config-schema.json +3370 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +146 -92
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +170 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  27. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  28. package/templates/modules-watch-stub.js +4 -0
  29. package/templates/new-worker-scheduled.js +17 -0
  30. package/templates/new-worker-scheduled.ts +32 -0
  31. package/templates/new-worker.js +4 -4
  32. package/templates/new-worker.ts +22 -4
  33. package/templates/no-op-worker.js +10 -0
  34. package/templates/pages-dev-pipeline.ts +32 -0
  35. package/templates/pages-dev-util.ts +55 -0
  36. package/templates/pages-shim.ts +9 -0
  37. package/templates/pages-template-plugin.ts +190 -0
  38. package/templates/pages-template-worker.ts +198 -0
  39. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  40. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  41. package/templates/tsconfig-sanity.ts +11 -0
  42. package/templates/tsconfig.init.json +22 -0
  43. package/templates/tsconfig.json +8 -0
  44. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  45. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  46. package/wrangler-dist/ProxyWorker.js +241 -0
  47. package/wrangler-dist/ProxyWorker.js.map +6 -0
  48. package/wrangler-dist/cli.d.ts +26730 -0
  49. package/wrangler-dist/cli.js +165374 -118597
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/pages/functions/buildWorker.ts +0 -62
  55. package/pages/functions/filepath-routing.test.ts +0 -47
  56. package/pages/functions/filepath-routing.ts +0 -231
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -160
  59. package/pages/functions/template-worker.ts +0 -136
  60. package/src/__tests__/dev.test.tsx +0 -71
  61. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  62. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  63. package/src/__tests__/helpers/mock-account-id.ts +0 -30
  64. package/src/__tests__/helpers/mock-bin.ts +0 -33
  65. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  66. package/src/__tests__/helpers/mock-console.ts +0 -56
  67. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  68. package/src/__tests__/helpers/mock-kv.ts +0 -40
  69. package/src/__tests__/helpers/mock-user.ts +0 -27
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -29
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -14
  72. package/src/__tests__/index.test.ts +0 -543
  73. package/src/__tests__/jest.setup.ts +0 -37
  74. package/src/__tests__/kv.test.ts +0 -1139
  75. package/src/__tests__/logout.test.ts +0 -50
  76. package/src/__tests__/package-manager.test.ts +0 -206
  77. package/src/__tests__/publish.test.ts +0 -1222
  78. package/src/__tests__/secret.test.ts +0 -210
  79. package/src/__tests__/whoami.test.tsx +0 -86
  80. package/src/api/form_data.ts +0 -134
  81. package/src/api/preview.ts +0 -128
  82. package/src/api/worker.ts +0 -155
  83. package/src/cfetch/index.ts +0 -102
  84. package/src/cfetch/internal.ts +0 -101
  85. package/src/cli.ts +0 -9
  86. package/src/config.ts +0 -641
  87. package/src/dev.tsx +0 -834
  88. package/src/dialogs.tsx +0 -77
  89. package/src/index.tsx +0 -2101
  90. package/src/inspect.ts +0 -596
  91. package/src/kv.tsx +0 -284
  92. package/src/module-collection.ts +0 -63
  93. package/src/package-manager.ts +0 -120
  94. package/src/pages.tsx +0 -1046
  95. package/src/paths.ts +0 -26
  96. package/src/proxy.ts +0 -370
  97. package/src/publish.ts +0 -410
  98. package/src/sites.tsx +0 -240
  99. package/src/tail.tsx +0 -73
  100. package/src/user.tsx +0 -1019
  101. package/src/whoami.tsx +0 -69
  102. package/templates/static-asset-facade.js +0 -47
  103. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  104. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  105. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  106. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  107. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  108. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  109. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  110. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  111. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  112. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  113. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  114. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  115. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  116. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  117. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  118. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  119. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  120. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  121. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  122. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  123. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  124. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  125. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  126. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  127. package/vendor/wrangler-mime/LICENSE +0 -21
  128. package/vendor/wrangler-mime/Mime.js +0 -97
  129. package/vendor/wrangler-mime/README.md +0 -187
  130. package/vendor/wrangler-mime/cli.js +0 -46
  131. package/vendor/wrangler-mime/index.js +0 -4
  132. package/vendor/wrangler-mime/lite.js +0 -4
  133. package/vendor/wrangler-mime/package.json +0 -52
  134. package/vendor/wrangler-mime/types/other.js +0 -1
  135. package/vendor/wrangler-mime/types/standard.js +0 -1
  136. package/wrangler-dist/cli.js.map +0 -7
@@ -1,136 +0,0 @@
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
- methods: 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 (
51
- route.methods.length &&
52
- !route.methods.includes(request.method as HTTPMethod)
53
- ) {
54
- continue;
55
- }
56
-
57
- const routeMatcher = match(route.routePath, { end: false });
58
- const matchResult = routeMatcher(requestPath);
59
- if (matchResult) {
60
- for (const handler of route.middlewares.flat()) {
61
- yield {
62
- handler,
63
- params: matchResult.params as Params,
64
- };
65
- }
66
- }
67
- }
68
-
69
- // Then look for the first exact route match and execute its "modules"
70
- for (const route of routes) {
71
- if (
72
- route.methods.length &&
73
- !route.methods.includes(request.method as HTTPMethod)
74
- ) {
75
- continue;
76
- }
77
-
78
- const routeMatcher = match(route.routePath, { end: true });
79
- const matchResult = routeMatcher(requestPath);
80
- if (matchResult && route.modules.length) {
81
- for (const handler of route.modules.flat()) {
82
- yield {
83
- handler,
84
- params: matchResult.params as Params,
85
- };
86
- }
87
- break;
88
- }
89
- }
90
- }
91
-
92
- export default {
93
- async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
94
- const handlerIterator = executeRequest(request, env);
95
- const data = {}; // arbitrary data the user can set between functions
96
- const next = async (input?: RequestInfo, init?: RequestInit) => {
97
- if (input !== undefined) {
98
- request = new Request(input, init);
99
- }
100
-
101
- const result = handlerIterator.next();
102
- // Note we can't use `!result.done` because this doesn't narrow to the correct type
103
- if (result.done == false) {
104
- const { handler, params } = result.value;
105
- const context = {
106
- request: new Request(request.clone()),
107
- next,
108
- params,
109
- data,
110
- env,
111
- waitUntil: workerContext.waitUntil.bind(workerContext),
112
- };
113
-
114
- const response = await handler(context);
115
-
116
- // https://fetch.spec.whatwg.org/#null-body-status
117
- return new Response(
118
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
119
- response
120
- );
121
- } else if (__FALLBACK_SERVICE__) {
122
- // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
123
- return env[__FALLBACK_SERVICE__].fetch(request);
124
- } else {
125
- // There was not fallback service so actually make the request to the origin.
126
- return fetch(request);
127
- }
128
- };
129
-
130
- try {
131
- return next();
132
- } catch (err) {
133
- return new Response("Internal Error", { status: 500 });
134
- }
135
- },
136
- };
@@ -1,71 +0,0 @@
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;
9
- beforeEach(() => (restoreConsole = patchConsole(() => {})));
10
- afterEach(() => restoreConsole());
11
-
12
- it("should throw if format is service-worker and there is a public directory", () => {
13
- const { lastFrame } = renderDev({
14
- format: "service-worker",
15
- accountId: "some-account-id",
16
- public: "some/public/path",
17
- });
18
- expect(lastFrame()?.split("\n").slice(0, 2).join("\n"))
19
- .toMatchInlineSnapshot(`
20
- "Something went wrong:
21
- Error: You cannot use the service worker format with a \`public\` directory."
22
- `);
23
- });
24
- });
25
-
26
- /**
27
- * Helper function to make it easier to setup and render the `Dev` component.
28
- *
29
- * All the `Dev` props are optional here, with sensible defaults for testing.
30
- */
31
- function renderDev({
32
- name,
33
- entry = "some/entry.ts",
34
- port,
35
- format,
36
- accountId,
37
- initialMode = "remote",
38
- jsxFactory,
39
- jsxFragment,
40
- bindings = {},
41
- public: publicDir,
42
- assetPaths,
43
- compatibilityDate,
44
- compatibilityFlags,
45
- usageModel,
46
- buildCommand = {},
47
- enableLocalPersistence = false,
48
- env = undefined,
49
- }: Partial<DevProps>) {
50
- return render(
51
- <Dev
52
- name={name}
53
- entry={entry}
54
- env={env}
55
- port={port}
56
- buildCommand={buildCommand}
57
- format={format}
58
- initialMode={initialMode}
59
- jsxFactory={jsxFactory}
60
- jsxFragment={jsxFragment}
61
- accountId={accountId}
62
- assetPaths={assetPaths}
63
- public={publicDir}
64
- compatibilityDate={compatibilityDate}
65
- compatibilityFlags={compatibilityFlags}
66
- usageModel={usageModel}
67
- bindings={bindings}
68
- enableLocalPersistence={enableLocalPersistence}
69
- />
70
- );
71
- }
@@ -1,4 +0,0 @@
1
- // We use this mock during tests because we're having trouble
2
- // properly compiling clipboardy for jest
3
- // We can revisit this if and when we write tests that test
4
- // the copying part of `dev`
@@ -1,11 +0,0 @@
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
- }
@@ -1,30 +0,0 @@
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
- }
@@ -1,33 +0,0 @@
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
- }
@@ -1,207 +0,0 @@
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
- }
@@ -1,56 +0,0 @@
1
- /**
2
- * We use this module to mock console methods, and optionally
3
- * assert on the values they're called with in our tests.
4
- */
5
-
6
- let logSpy: jest.SpyInstance,
7
- errorSpy: jest.SpyInstance,
8
- warnSpy: jest.SpyInstance;
9
-
10
- const std = {
11
- get out() {
12
- return normalizeSlashes(stripTimings(logSpy.mock.calls.flat(2).join("\n")));
13
- },
14
- get err() {
15
- return normalizeSlashes(
16
- stripTimings(errorSpy.mock.calls.flat(2).join("\n"))
17
- );
18
- },
19
- get warn() {
20
- return normalizeSlashes(
21
- stripTimings(warnSpy.mock.calls.flat(2).join("\n"))
22
- );
23
- },
24
- };
25
-
26
- export function mockConsoleMethods() {
27
- beforeEach(() => {
28
- logSpy = jest.spyOn(console, "log").mockImplementation();
29
- errorSpy = jest.spyOn(console, "error").mockImplementation();
30
- warnSpy = jest.spyOn(console, "warn").mockImplementation();
31
- });
32
- afterEach(() => {
33
- logSpy.mockRestore();
34
- errorSpy.mockRestore();
35
- warnSpy.mockRestore();
36
- });
37
- return std;
38
- }
39
-
40
- /**
41
- * Ensure slashes in the `str` are OS file-system agnostic.
42
- *
43
- * Use this in snapshot tests to be resilient to file-system differences.
44
- */
45
- export function normalizeSlashes(str: string): string {
46
- return str.replace(/\\/g, "/");
47
- }
48
-
49
- /**
50
- * Strip "timing data" out of the `stdout` string, since this is not always deterministic.
51
- *
52
- * Use this in snapshot tests to be resilient to slight changes in timing of processing.
53
- */
54
- export function stripTimings(stdout: string): string {
55
- return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
56
- }
@@ -1,65 +0,0 @@
1
- import { confirm, prompt } from "../../dialogs";
2
-
3
- /**
4
- * The expected values for a confirmation request.
5
- */
6
- 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;
11
- }
12
-
13
- /**
14
- * Mock the implementation of `confirm()` that will respond with configured results
15
- * for configured confirmation text messages.
16
- *
17
- * If there is a call to `confirm()` that does not match any of the expectations
18
- * then an error is thrown.
19
- */
20
- 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
- });
29
- }
30
-
31
- /**
32
- * The expected values for a prompt request.
33
- */
34
- 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;
41
- }
42
-
43
- /**
44
- * Mock the implementation of `prompt()` that will respond with configured results
45
- * for configured prompt text messages.
46
- *
47
- * If there is a call to `prompt()` that does not match any of the expectations
48
- * then an error is thrown.
49
- */
50
- 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
- );
65
- }
@@ -1,40 +0,0 @@
1
- import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
-
3
- export function mockKeyListRequest(
4
- expectedNamespaceId: string,
5
- expectedKeys: string[],
6
- keysPerRequest = 1000,
7
- blankCursorValue: "" | undefined | null = undefined
8
- ) {
9
- const requests = { count: 0 };
10
- // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
11
- const expectedKeyObjects = expectedKeys.map((name) => ({
12
- name,
13
- expiration: 123456789,
14
- metadata: {},
15
- }));
16
- setMockRawResponse(
17
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
18
- "GET",
19
- ([_url, accountId, namespaceId], _init, query) => {
20
- requests.count++;
21
- expect(accountId).toEqual("some-account-id");
22
- expect(namespaceId).toEqual(expectedNamespaceId);
23
- if (expectedKeyObjects.length <= keysPerRequest) {
24
- return createFetchResult(expectedKeyObjects);
25
- } else {
26
- const start = parseInt(query.get("cursor") ?? "0") || 0;
27
- const end = start + keysPerRequest;
28
- const cursor = end < expectedKeyObjects.length ? end : blankCursorValue;
29
- return createFetchResult(
30
- expectedKeyObjects.slice(start, end),
31
- true,
32
- [],
33
- [],
34
- { cursor }
35
- );
36
- }
37
- }
38
- );
39
- return requests;
40
- }
@@ -1,27 +0,0 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
-
5
- export function writeUserConfig(
6
- oauth_token?: string,
7
- refresh_token?: string,
8
- expiration_time?: string
9
- ) {
10
- const lines: string[] = [];
11
- if (oauth_token) {
12
- lines.push(`oauth_token = "${oauth_token}"`);
13
- }
14
- if (refresh_token) {
15
- lines.push(`refresh_token = "${refresh_token}"`);
16
- }
17
- if (expiration_time) {
18
- lines.push(`expiration_time = "${expiration_time}"`);
19
- }
20
- const configPath = path.join(os.homedir(), ".wrangler/config");
21
- mkdirSync(configPath, { recursive: true });
22
- writeFileSync(
23
- path.join(configPath, "default.toml"),
24
- lines.join("\n"),
25
- "utf-8"
26
- );
27
- }