wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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 (209) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -127
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3950 -0
  10. package/src/__tests__/dev.test.tsx +1199 -67
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +36 -18
  14. package/src/__tests__/helpers/mock-bin.ts +36 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +118 -80
  16. package/src/__tests__/helpers/mock-console.ts +70 -29
  17. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  18. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  19. package/src/__tests__/helpers/mock-istty.ts +74 -0
  20. package/src/__tests__/helpers/mock-kv.ts +28 -35
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  22. package/src/__tests__/helpers/mock-process.ts +39 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  26. package/src/__tests__/helpers/run-wrangler.ts +8 -6
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +163 -0
  30. package/src/__tests__/index.test.ts +255 -399
  31. package/src/__tests__/init.test.ts +1992 -0
  32. package/src/__tests__/jest.setup.ts +102 -16
  33. package/src/__tests__/kv.test.ts +1400 -878
  34. package/src/__tests__/logger.test.ts +141 -0
  35. package/src/__tests__/metrics.test.ts +445 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1261 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6633 -1184
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +484 -202
  44. package/src/__tests__/tail.test.ts +698 -0
  45. package/src/__tests__/test-old-node-version.js +31 -0
  46. package/src/__tests__/user.test.ts +143 -0
  47. package/src/__tests__/version.test.ts +35 -0
  48. package/src/__tests__/whoami.test.tsx +219 -75
  49. package/src/__tests__/worker-namespace.test.ts +327 -0
  50. package/src/abort.d.ts +3 -0
  51. package/src/api/dev.ts +86 -0
  52. package/src/api/index.ts +1 -0
  53. package/src/bundle-reporter.tsx +29 -0
  54. package/src/bundle.ts +236 -0
  55. package/src/cfetch/index.ts +86 -76
  56. package/src/cfetch/internal.ts +122 -45
  57. package/src/cli.ts +24 -6
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +251 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +453 -0
  62. package/src/config/index.ts +238 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1754 -0
  65. package/src/config-cache.ts +84 -0
  66. package/src/create-worker-preview.ts +255 -0
  67. package/src/create-worker-upload-form.ts +263 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +452 -0
  70. package/src/dev/local.tsx +373 -0
  71. package/src/dev/remote.tsx +386 -0
  72. package/src/dev/use-esbuild.ts +150 -0
  73. package/src/dev.tsx +579 -820
  74. package/src/dialogs.tsx +115 -57
  75. package/src/durable.ts +102 -0
  76. package/src/entry.ts +328 -0
  77. package/src/environment-variables.ts +35 -0
  78. package/src/errors.ts +11 -0
  79. package/src/faye-websocket.d.ts +6 -0
  80. package/src/generate.ts +33 -0
  81. package/src/git-client.ts +42 -0
  82. package/src/global-wrangler-config-path.ts +26 -0
  83. package/src/https-options.ts +127 -0
  84. package/src/index.tsx +1969 -2024
  85. package/src/init.ts +549 -0
  86. package/src/inspect.ts +603 -537
  87. package/src/intl-polyfill.d.ts +139 -0
  88. package/src/is-interactive.ts +12 -0
  89. package/src/kv.ts +430 -0
  90. package/src/logger.ts +73 -0
  91. package/src/metrics/index.ts +4 -0
  92. package/src/metrics/is-ci.ts +14 -0
  93. package/src/metrics/metrics-config.ts +239 -0
  94. package/src/metrics/metrics-dispatcher.ts +95 -0
  95. package/src/metrics/send-event.ts +92 -0
  96. package/src/miniflare-cli/README.md +30 -0
  97. package/src/miniflare-cli/assets.ts +543 -0
  98. package/src/miniflare-cli/enum-keys.ts +17 -0
  99. package/src/miniflare-cli/index.ts +85 -0
  100. package/src/miniflare-cli/request-context.ts +40 -0
  101. package/src/module-collection.ts +244 -49
  102. package/src/open-in-browser.ts +17 -0
  103. package/src/package-manager.ts +219 -0
  104. package/src/pages/build.tsx +204 -0
  105. package/src/pages/constants.ts +7 -0
  106. package/src/pages/deployments.tsx +106 -0
  107. package/src/pages/dev.tsx +401 -0
  108. package/src/pages/functions/buildPlugin.ts +105 -0
  109. package/src/pages/functions/buildWorker.ts +151 -0
  110. package/src/pages/functions/filepath-routing.test.ts +234 -0
  111. package/src/pages/functions/filepath-routing.ts +189 -0
  112. package/src/pages/functions/identifiers.ts +78 -0
  113. package/src/pages/functions/routes.ts +151 -0
  114. package/src/pages/index.tsx +84 -0
  115. package/src/pages/projects.tsx +163 -0
  116. package/src/pages/publish.tsx +338 -0
  117. package/src/pages/types.ts +40 -0
  118. package/src/pages/upload.tsx +396 -0
  119. package/src/pages/utils.ts +12 -0
  120. package/src/parse.ts +286 -0
  121. package/src/paths.ts +6 -6
  122. package/src/preview.ts +31 -0
  123. package/src/proxy.ts +417 -311
  124. package/src/publish.ts +774 -391
  125. package/src/pubsub/index.ts +286 -0
  126. package/src/pubsub/pubsub-commands.tsx +623 -0
  127. package/src/r2.ts +50 -0
  128. package/src/selfsigned.d.ts +29 -0
  129. package/src/sites.tsx +291 -159
  130. package/src/tail/filters.ts +279 -0
  131. package/src/tail/index.ts +299 -0
  132. package/src/tail/printing.ts +67 -0
  133. package/src/update-check.ts +19 -0
  134. package/src/user/choose-account.tsx +69 -0
  135. package/src/user/env-vars.ts +46 -0
  136. package/src/user/generate-auth-url.ts +33 -0
  137. package/src/user/generate-random-state.ts +16 -0
  138. package/src/user/index.ts +3 -0
  139. package/src/user/user.tsx +1171 -0
  140. package/src/whoami.tsx +63 -41
  141. package/src/worker-namespace.ts +206 -0
  142. package/src/worker.ts +191 -0
  143. package/src/zones.ts +76 -0
  144. package/templates/checked-fetch.js +17 -0
  145. package/templates/gitignore +171 -0
  146. package/templates/new-worker-scheduled.js +17 -0
  147. package/templates/new-worker-scheduled.ts +32 -0
  148. package/templates/new-worker.js +15 -0
  149. package/templates/new-worker.ts +30 -0
  150. package/templates/no-op-worker.js +10 -0
  151. package/templates/pages-shim.ts +9 -0
  152. package/templates/pages-template-plugin.ts +155 -0
  153. package/templates/pages-template-worker.ts +161 -0
  154. package/templates/static-asset-facade.js +49 -0
  155. package/templates/tsconfig.json +105 -0
  156. package/wrangler-dist/cli.d.ts +327 -0
  157. package/wrangler-dist/cli.js +78107 -79324
  158. package/pages/functions/buildWorker.ts +0 -62
  159. package/pages/functions/filepath-routing.test.ts +0 -47
  160. package/pages/functions/filepath-routing.ts +0 -231
  161. package/pages/functions/identifiers.ts +0 -78
  162. package/pages/functions/routes.ts +0 -160
  163. package/pages/functions/template-worker.ts +0 -136
  164. package/src/__tests__/helpers/mock-user.ts +0 -27
  165. package/src/__tests__/logout.test.ts +0 -50
  166. package/src/api/form_data.ts +0 -134
  167. package/src/api/preview.ts +0 -128
  168. package/src/api/worker.ts +0 -155
  169. package/src/config.ts +0 -641
  170. package/src/kv.tsx +0 -276
  171. package/src/npm-installer.ts +0 -20
  172. package/src/pages.tsx +0 -1045
  173. package/src/tail.tsx +0 -73
  174. package/src/user.tsx +0 -1019
  175. package/static-asset-facade.js +0 -47
  176. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  177. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  178. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  179. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  180. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  181. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  182. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  183. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  184. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  185. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  186. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  190. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  191. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  192. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  193. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  194. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  195. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  196. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  197. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  198. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  199. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  200. package/vendor/wrangler-mime/LICENSE +0 -21
  201. package/vendor/wrangler-mime/Mime.js +0 -97
  202. package/vendor/wrangler-mime/README.md +0 -187
  203. package/vendor/wrangler-mime/cli.js +0 -46
  204. package/vendor/wrangler-mime/index.js +0 -4
  205. package/vendor/wrangler-mime/lite.js +0 -4
  206. package/vendor/wrangler-mime/package.json +0 -52
  207. package/vendor/wrangler-mime/types/other.js +0 -1
  208. package/vendor/wrangler-mime/types/standard.js +0 -1
  209. package/wrangler-dist/cli.js.map +0 -7
@@ -1,52 +1,47 @@
1
1
  import { URLSearchParams } from "node:url";
2
+ import { ParseError } from "../parse";
2
3
  import { fetchInternal } from "./internal";
3
4
  import type { RequestInit } from "undici";
4
5
 
5
6
  // Check out https://api.cloudflare.com/ for API docs.
6
7
 
7
- export { CF_API_BASE_URL } from "./internal";
8
+ export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
8
9
 
9
10
  export interface FetchError {
10
- code: number;
11
- message: string;
11
+ code: number;
12
+ message: string;
13
+ error_chain?: FetchError[];
12
14
  }
13
15
  export interface FetchResult<ResponseType = unknown> {
14
- success: boolean;
15
- result: ResponseType;
16
- errors: FetchError[];
17
- messages: string[];
18
- result_info?: unknown;
16
+ success: boolean;
17
+ result: ResponseType;
18
+ errors: FetchError[];
19
+ messages: string[];
20
+ result_info?: unknown;
19
21
  }
20
22
 
21
- /**
22
- * Make a fetch request for a raw JSON value.
23
- */
24
- export async function fetchRaw<ResponseType>(
25
- resource: string,
26
- init: RequestInit = {},
27
- queryParams?: URLSearchParams
28
- ): Promise<ResponseType> {
29
- return fetchInternal<ResponseType>(resource, init, queryParams);
30
- }
23
+ export { fetchKVGetValue } from "./internal";
31
24
 
32
25
  /**
33
26
  * Make a fetch request, and extract the `result` from the JSON response.
34
27
  */
35
28
  export async function fetchResult<ResponseType>(
36
- resource: string,
37
- init: RequestInit = {},
38
- queryParams?: URLSearchParams
29
+ resource: string,
30
+ init: RequestInit = {},
31
+ queryParams?: URLSearchParams,
32
+ abortSignal?: AbortSignal
39
33
  ): Promise<ResponseType> {
40
- const json = await fetchInternal<FetchResult<ResponseType>>(
41
- resource,
42
- init,
43
- queryParams
44
- );
45
- if (json.success) {
46
- return json.result;
47
- } else {
48
- throwFetchError(resource, json);
49
- }
34
+ const json = await fetchInternal<FetchResult<ResponseType>>(
35
+ resource,
36
+ init,
37
+ queryParams,
38
+ abortSignal
39
+ );
40
+ if (json.success) {
41
+ return json.result;
42
+ } else {
43
+ throwFetchError(resource, json);
44
+ }
50
45
  }
51
46
 
52
47
  /**
@@ -55,57 +50,72 @@ export async function fetchResult<ResponseType>(
55
50
  * and repeating the request if the results are paginated.
56
51
  */
57
52
  export async function fetchListResult<ResponseType>(
58
- resource: string,
59
- init: RequestInit = {},
60
- queryParams?: URLSearchParams
53
+ resource: string,
54
+ init: RequestInit = {},
55
+ queryParams?: URLSearchParams
61
56
  ): Promise<ResponseType[]> {
62
- const results: ResponseType[] = [];
63
- let getMoreResults = true;
64
- let cursor: string | undefined;
65
- while (getMoreResults) {
66
- if (cursor) {
67
- queryParams = new URLSearchParams(queryParams);
68
- queryParams.set("cursor", cursor);
69
- }
70
- const json = await fetchInternal<FetchResult<ResponseType[]>>(
71
- resource,
72
- init,
73
- queryParams
74
- );
75
- if (json.success) {
76
- results.push(...json.result);
77
- if (hasCursor(json.result_info)) {
78
- cursor = json.result_info?.cursor;
79
- } else {
80
- getMoreResults = false;
81
- }
82
- } else {
83
- throwFetchError(resource, json);
84
- }
85
- }
86
- return results;
57
+ const results: ResponseType[] = [];
58
+ let getMoreResults = true;
59
+ let cursor: string | undefined;
60
+ while (getMoreResults) {
61
+ if (cursor) {
62
+ queryParams = new URLSearchParams(queryParams);
63
+ queryParams.set("cursor", cursor);
64
+ }
65
+ const json = await fetchInternal<FetchResult<ResponseType[]>>(
66
+ resource,
67
+ init,
68
+ queryParams
69
+ );
70
+ if (json.success) {
71
+ results.push(...json.result);
72
+ if (hasCursor(json.result_info)) {
73
+ cursor = json.result_info?.cursor;
74
+ } else {
75
+ getMoreResults = false;
76
+ }
77
+ } else {
78
+ throwFetchError(resource, json);
79
+ }
80
+ }
81
+ return results;
87
82
  }
88
83
 
89
84
  function throwFetchError(
90
- resource: string,
91
- response: FetchResult<unknown>
85
+ resource: string,
86
+ response: FetchResult<unknown>
92
87
  ): never {
93
- response.messages.forEach((message) => console.warn(message));
94
- const errors = response.errors
95
- .map((error) => `${error.code}: ${error.message}`)
96
- .join("\n");
97
- const error = new Error(`Failed to fetch ${resource} - \n${errors}`);
98
- // add the first error code directly to this error
99
- // so consumers can use it for specific behaviour
100
- const code = response.errors[0]?.code;
101
- if (code) {
102
- //@ts-expect-error non-standard property on Error
103
- error.code = code;
104
- }
105
- throw error;
88
+ const error = new ParseError({
89
+ text: `A request to the Cloudflare API (${resource}) failed.`,
90
+ notes: response.errors.map((err) => ({
91
+ text: renderError(err),
92
+ })),
93
+ });
94
+ // add the first error code directly to this error
95
+ // so consumers can use it for specific behaviour
96
+ const code = response.errors[0]?.code;
97
+ if (code) {
98
+ //@ts-expect-error non-standard property on Error
99
+ error.code = code;
100
+ }
101
+ throw error;
106
102
  }
107
103
 
108
104
  function hasCursor(result_info: unknown): result_info is { cursor: string } {
109
- const cursor = (result_info as { cursor: string } | undefined)?.cursor;
110
- return cursor !== undefined && cursor !== null && cursor !== "";
105
+ const cursor = (result_info as { cursor: string } | undefined)?.cursor;
106
+ return cursor !== undefined && cursor !== null && cursor !== "";
107
+ }
108
+
109
+ function renderError(err: FetchError, level = 0): string {
110
+ const chainedMessages =
111
+ err.error_chain
112
+ ?.map(
113
+ (chainedError) =>
114
+ `\n${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
115
+ )
116
+ .join("\n") ?? "";
117
+ return (
118
+ (err.code ? `${err.message} [code: ${err.code}]` : err.message) +
119
+ chainedMessages
120
+ );
111
121
  }
@@ -1,10 +1,21 @@
1
- import { fetch } from "undici";
2
- import { getAPIToken, loginOrRefreshIfRequired } from "../user";
1
+ import assert from "node:assert";
2
+ import { fetch, Headers } from "undici";
3
+ import { version as wranglerVersion } from "../../package.json";
4
+ import { getEnvironmentVariableFactory } from "../environment-variables";
5
+ import { ParseError, parseJSON } from "../parse";
6
+ import { loginOrRefreshIfRequired, requireApiToken } from "../user";
7
+ import type { ApiCredentials } from "../user";
3
8
  import type { URLSearchParams } from "node:url";
4
9
  import type { RequestInit, HeadersInit } from "undici";
5
10
 
6
- export const CF_API_BASE_URL =
7
- process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
11
+ /**
12
+ * Get the URL to use to access the Cloudflare API.
13
+ */
14
+ export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
15
+ variableName: "CLOUDFLARE_API_BASE_URL",
16
+ deprecatedName: "CF_API_BASE_URL",
17
+ defaultValue: "https://api.cloudflare.com/client/v4",
18
+ });
8
19
 
9
20
  /**
10
21
  * Make a fetch request to the Cloudflare API.
@@ -16,57 +27,123 @@ export const CF_API_BASE_URL =
16
27
  * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
17
28
  */
18
29
  export async function fetchInternal<ResponseType>(
19
- resource: string,
20
- init: RequestInit = {},
21
- queryParams?: URLSearchParams
30
+ resource: string,
31
+ init: RequestInit = {},
32
+ queryParams?: URLSearchParams,
33
+ abortSignal?: AbortSignal
22
34
  ): Promise<ResponseType> {
23
- await requireLoggedIn();
24
- const apiToken = requireApiToken();
25
- const headers = cloneHeaders(init.headers);
26
- addAuthorizationHeader(headers, apiToken);
35
+ assert(
36
+ resource.startsWith("/"),
37
+ `CF API fetch - resource path must start with a "/" but got "${resource}"`
38
+ );
39
+ await requireLoggedIn();
40
+ const apiToken = requireApiToken();
41
+ const headers = cloneHeaders(init.headers);
42
+ addAuthorizationHeaderIfUnspecified(headers, apiToken);
43
+ addUserAgent(headers);
27
44
 
28
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
29
- const response = await fetch(`${CF_API_BASE_URL}${resource}${queryString}`, {
30
- method: "GET",
31
- ...init,
32
- headers,
33
- });
45
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
46
+ const method = init.method ?? "GET";
47
+ const response = await fetch(
48
+ `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
49
+ {
50
+ method,
51
+ ...init,
52
+ headers,
53
+ signal: abortSignal,
54
+ }
55
+ );
56
+ const jsonText = await response.text();
57
+ try {
58
+ return parseJSON<ResponseType>(jsonText);
59
+ } catch (err) {
60
+ throw new ParseError({
61
+ text: "Received a malformed response from the API",
62
+ notes: [
63
+ {
64
+ text: truncate(jsonText, 100),
65
+ },
66
+ {
67
+ text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
68
+ },
69
+ ],
70
+ });
71
+ }
72
+ }
34
73
 
35
- const jsonText = await response.text();
36
- try {
37
- const json = JSON.parse(jsonText);
38
- return json as ResponseType;
39
- } catch (e) {
40
- throw new Error(
41
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText}\nInvalid JSON response:\n${jsonText}`
42
- );
43
- }
74
+ function truncate(text: string, maxLength: number): string {
75
+ const { length } = text;
76
+ if (length <= maxLength) {
77
+ return text;
78
+ }
79
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
44
80
  }
45
81
 
46
- function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
47
- return { ...headers };
82
+ function cloneHeaders(
83
+ headers: HeadersInit | undefined
84
+ ): Record<string, string> {
85
+ return headers instanceof Headers
86
+ ? Object.fromEntries(headers.entries())
87
+ : Array.isArray(headers)
88
+ ? Object.fromEntries(headers)
89
+ : { ...headers };
48
90
  }
49
91
 
50
92
  async function requireLoggedIn(): Promise<void> {
51
- const loggedIn = await loginOrRefreshIfRequired();
52
- if (!loggedIn) {
53
- throw new Error("Not logged in.");
54
- }
93
+ const loggedIn = await loginOrRefreshIfRequired();
94
+ if (!loggedIn) {
95
+ throw new Error("Not logged in.");
96
+ }
97
+ }
98
+
99
+ function addAuthorizationHeaderIfUnspecified(
100
+ headers: Record<string, string>,
101
+ auth: ApiCredentials
102
+ ): void {
103
+ if (!("Authorization" in headers)) {
104
+ if ("apiToken" in auth) {
105
+ headers["Authorization"] = `Bearer ${auth.apiToken}`;
106
+ } else {
107
+ headers["X-Auth-Key"] = auth.authKey;
108
+ headers["X-Auth-Email"] = auth.authEmail;
109
+ }
110
+ }
55
111
  }
56
112
 
57
- function requireApiToken(): string {
58
- const apiToken = getAPIToken();
59
- if (!apiToken) {
60
- throw new Error("No API token found.");
61
- }
62
- return apiToken;
113
+ function addUserAgent(headers: Record<string, string>): void {
114
+ headers["User-Agent"] = `wrangler/${wranglerVersion}`;
63
115
  }
64
116
 
65
- function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
66
- if (headers["Authorization"]) {
67
- throw new Error(
68
- "The request already specifies an authorisation header - cannot add a new one."
69
- );
70
- }
71
- headers["Authorization"] = `Bearer ${apiToken}`;
117
+ /**
118
+ * The implementation for fetching a kv value from the cloudflare API.
119
+ * We special-case this one call, because it's the only API call that
120
+ * doesn't return json. We inline the implementation and try not to share
121
+ * any code with the other calls. We should push back on any new APIs that
122
+ * try to introduce non-"standard" response structures.
123
+ *
124
+ * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
125
+ * before passing it
126
+ */
127
+
128
+ export async function fetchKVGetValue(
129
+ accountId: string,
130
+ namespaceId: string,
131
+ key: string
132
+ ): Promise<ArrayBuffer> {
133
+ await requireLoggedIn();
134
+ const auth = requireApiToken();
135
+ const headers: Record<string, string> = {};
136
+ addAuthorizationHeaderIfUnspecified(headers, auth);
137
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
138
+ const response = await fetch(resource, {
139
+ method: "GET",
140
+ headers,
141
+ });
142
+ if (response.ok) {
143
+ return await response.arrayBuffer();
144
+ } else {
145
+ throw new Error(
146
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
147
+ );
148
+ }
72
149
  }
package/src/cli.ts CHANGED
@@ -1,9 +1,27 @@
1
+ import "dotenv/config"; // Grab locally specified env params from a `.env` file.
2
+ import process from "process";
1
3
  import { hideBin } from "yargs/helpers";
4
+ import { unstable_dev } from "./api";
5
+ import { FatalError } from "./errors";
2
6
  import { main } from ".";
3
7
 
4
- main(hideBin(process.argv)).catch(() => {
5
- // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
6
- // Here we just want to ensure that the process exits with a non-zero code.
7
- // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
8
- process.exit(1);
9
- });
8
+ /**
9
+ * The main entrypoint for the CLI.
10
+ * main only gets called when the script is run directly, not when it's imported as a module.
11
+ */
12
+ if (typeof jest === "undefined" && require.main) {
13
+ main(hideBin(process.argv)).catch((e) => {
14
+ // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
15
+ // Here we just want to ensure that the process exits with a non-zero code.
16
+ // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
17
+ const exitCode = (e instanceof FatalError && e.code) || 1;
18
+ process.exit(exitCode);
19
+ });
20
+ }
21
+
22
+ /**
23
+ * This is how we're exporting the API.
24
+ * It makes it possible to import wrangler from 'wrangler',
25
+ * and call wrangler.unstable_dev().
26
+ */
27
+ export default { unstable_dev };
@@ -0,0 +1,107 @@
1
+ # Configuration validation
2
+
3
+ The files in this directory define and validate the configuration that is read from a `wrangler.toml` file.
4
+
5
+ The configuration for a Worker is complicated since we can define different "environments", and each environment can have its own configuration.
6
+ There is a default ("top-level") environment and then named environments that provide environment specific configuration.
7
+
8
+ This is further complicated by the fact that there are three kinds of environment configuration:
9
+
10
+ - **non-overridable**: these values are defined once in the top-level configuration, apply to all environments and cannot be overridden by an environment.
11
+ - **inheritable**: these values can be defined at the top-level but can also be overridden by environment specific values.
12
+ Named environments do not need to provide their own values, in which case they inherit the value from the top-level.
13
+ - **non-inheritable**: these values must be explicitly defined in each environment if they are defined at the top-level.
14
+ Named environments do not inherit such configuration and must provide their own values.
15
+
16
+ All configuration values in `wrangler.toml` are optional and will receive a default value if not defined.
17
+
18
+ ## Types
19
+
20
+ ### Environment
21
+
22
+ The fields that can be defined within the `env` containers are defined in the [`Environment`](./environment.ts) type.
23
+ This includes the `EnvironmentInheritable` and `EnvironmentNonInheritable` fields.
24
+
25
+ ### Config
26
+
27
+ The "non-overridable" types are defined in the [`ConfigFields`](./config.ts) type.
28
+ The `Config` type is the overall configuration, which consists of the `ConfigFields` and also an `Environment`.
29
+ In this case the `Environment`, here, corresponds to the "currently active" environment. This is specified by the `--env` command line argument.
30
+ If there is no argument passed then the currently active environment is the "top-level" environment.
31
+ The fields in `Config` and `Environment` are not generally optional and so you can expect they have been filled with suitable inherited or default values.
32
+ These types should be used when you are working with fields that should be passed to commands.
33
+
34
+ ### RawConfig
35
+
36
+ The `RawConfig` type is a version of `Config`, where all the fields are optional.
37
+ The `RawConfig` type includes `DeprecatedConfigFields` and `EnvironmentMap`.
38
+ It also extends the `RawEnvironment` type, which is a version of `Environment` where all the fields are optional.
39
+ These optional fields map to the actual fields found in the `wrangler.toml`.
40
+ These types should be used when you are working with raw configuration that is read or will be written to a `wrangler.toml`.
41
+
42
+ ## Validation
43
+
44
+ Validation is triggered by passing a `RawConfig` object, and the active environment name, to the `normalizeAndValidateConfig()` function.
45
+ This function will return:
46
+
47
+ - a `Config` object, where all the fields have suitable valid values
48
+ - a `Diagnostics` object, which contains any errors or warnings from the validation process
49
+
50
+ The field values may have been parsed directly from the `RawConfig`, inherited into a named environment from the top-level environment, or given a default value.
51
+ Generally, if there are any warnings they should be presented to the user via `logger.warn()` messages,
52
+ and if there are any errors then an `Error` should be thrown describing these errors.
53
+
54
+ The `Diagnostics` object is hierarchical: each `Diagnostics` instance can contain a collection of child `Diagnostics` instance.
55
+ When checking for or rendering warnings and errors, the `Diagnostics` class will automatically traverse down to all its children.
56
+
57
+ ## Usage
58
+
59
+ The [high level API](./index.ts) for configuration processing consists of the `findWranglerToml()` and `readConfig()` functions.
60
+
61
+ ### readConfig()
62
+
63
+ The `readConfig()` function will find the nearest `wrangler.toml` file, load and parse it, then validate and normalize the values into a `Config` object.
64
+ Note that you should pass the current active environment name in as a parameter. The resulting `Config` object will contain only the fields appropriate to that environment.
65
+ If there are validation errors then it will throw a suitable error.
66
+
67
+ ## Changing configuration
68
+
69
+ ### Add a new configuration field
70
+
71
+ When a new field needs to be added to the `wrangler.toml` configuration you will need to add to the types and validation code in this directory.
72
+
73
+ Here are some steps that you should consider when doing this:
74
+
75
+ - add the new field to one of the interface:
76
+ - if the field is not overridable in an environment then add it to the `ConfigFields` interface.
77
+ - if the field can be inherited and overridden in a named environment then add it to the `EnvironmentInheritable` interface.
78
+ - if the field cannot be inherited and must be specified in each named environment then add it to the `EnvironmentNonInheritable` interface.
79
+ - if the field is experimental then add a call to the `experimental()` function:
80
+ - if the field is now in the `ConfigDeprecated` interface then add the call to the `normalizeAndValidateConfig()` function.
81
+ - if the field is now in the `EnvironmentDeprecated` interface then add the call to the `normalizeAndValidateEnvironment()` function.
82
+ - add validation and normalization to the interface
83
+ - if the field is in `ConfigFields` then add validation calls to `normalizeAndValidateConfig()` and assign the normalized value to the appropriate property in the `config` object.
84
+ - if the field is in `EnvironmentInheritable` then call `inheritable()` in `normalizeAndValidateEnvironment()` and assign the normalized value to the appropriate property in the `environment` object.
85
+ - if the field is in `EnvironmentNonInheritable` then call `notInheritable()` in `normalizeAndValidateEnvironment()` and assign the normalized value to the appropriate property in the `environment` object.
86
+ - update the tests in `configuration.test.ts`
87
+ - add to the `"should use defaults for empty configuration"` test to prove the correct default value is assigned
88
+ - if the field is in `ConfigFields` add tests to the `"top-level non-environment configuration"` block to check the validation and normalization of values
89
+ - if the field is in `EnvironmentInheritable` or `EnvironmentNonInheritable`
90
+ - add tests to the `"top-level environment configuration"` block to check the validation and normalization of values
91
+ - add tests to the `"named environment configuration"` block to check the inheritance of values
92
+
93
+ ### Remove a configuration field
94
+
95
+ We should not just remove a field from use, since users would not know that this field is no longer needed, nor how to migrate to any new usage.
96
+ Instead we should first deprecate it, and then then remove it in a future major release.
97
+
98
+ - move the field to a deprecation interface:
99
+ - if the field was originally in `ConfigFields` then move it to the `ConfigDeprecated` interface.
100
+ - if the field was originally in either `EnvironmentInheritable` or `EnvironmentNonInheritable` then move it to the `EnvironmentDeprecatedInterface`.
101
+ - remove the validation for the field
102
+ - the TypeScript compiler should indicate where there is now an unknown field, so that you can remove its validation and normalization from the code base.
103
+ - add a deprecation warning by calling `deprecated()`
104
+ - if the field is now in the `ConfigDeprecated` interface then add the call to the `normalizeAndValidateConfig()` function.
105
+ - if the field is now in the `EnvironmentDeprecated` interface then add the call to the `normalizeAndValidateEnvironment()` function.
106
+ - update the tests in `configuration.test.ts`
107
+ - Find tests where the field is mentioned and either remove them (e.g. validation) or update to show the deprecation message.