wrangler 0.0.0-e6733a3 → 0.0.0-e9307365

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 (220) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +159 -27
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5416 -0
  6. package/package.json +171 -124
  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 +4022 -0
  10. package/src/__tests__/dev.test.tsx +1290 -62
  11. package/src/__tests__/generate.test.ts +93 -0
  12. package/src/__tests__/guess-worker-format.test.ts +85 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +263 -0
  18. package/src/__tests__/helpers/mock-console.ts +97 -0
  19. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  31. package/src/__tests__/https-options.test.ts +163 -0
  32. package/src/__tests__/index.test.ts +242 -284
  33. package/src/__tests__/init.test.ts +1992 -0
  34. package/src/__tests__/jest.setup.ts +138 -10
  35. package/src/__tests__/kv.test.ts +1459 -886
  36. package/src/__tests__/logger.test.ts +141 -0
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +353 -0
  39. package/src/__tests__/pages.test.ts +1261 -0
  40. package/src/__tests__/parse.test.ts +330 -0
  41. package/src/__tests__/publish.test.ts +6914 -0
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +317 -0
  44. package/src/__tests__/route.test.ts +45 -0
  45. package/src/__tests__/secret.test.ts +492 -0
  46. package/src/__tests__/tail.test.ts +698 -0
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +144 -0
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +289 -0
  52. package/src/__tests__/worker-namespace.test.ts +327 -0
  53. package/src/abort.d.ts +3 -0
  54. package/src/api/dev.ts +86 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +472 -0
  58. package/src/cfetch/index.ts +88 -69
  59. package/src/cfetch/internal.ts +156 -44
  60. package/src/cli.ts +24 -6
  61. package/src/config/README.md +107 -0
  62. package/src/config/config.ts +263 -0
  63. package/src/config/diagnostics.ts +80 -0
  64. package/src/config/environment.ts +485 -0
  65. package/src/config/index.ts +251 -0
  66. package/src/config/validation-helpers.ts +584 -0
  67. package/src/config/validation.ts +1856 -0
  68. package/src/config-cache.ts +84 -0
  69. package/src/create-worker-preview.ts +257 -0
  70. package/src/create-worker-upload-form.ts +288 -0
  71. package/src/dev/dev-vars.ts +36 -0
  72. package/src/dev/dev.tsx +531 -0
  73. package/src/dev/local.tsx +385 -0
  74. package/src/dev/remote.tsx +413 -0
  75. package/src/dev/use-esbuild.ts +175 -0
  76. package/src/dev/validate-dev-props.ts +31 -0
  77. package/src/dev-registry.tsx +157 -0
  78. package/src/dev.tsx +603 -758
  79. package/src/dialogs.tsx +117 -59
  80. package/src/durable.ts +102 -0
  81. package/src/entry.ts +328 -0
  82. package/src/environment-variables.ts +35 -0
  83. package/src/errors.ts +11 -0
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +127 -0
  89. package/src/index.tsx +2166 -1956
  90. package/src/init.ts +549 -0
  91. package/src/inspect.ts +703 -477
  92. package/src/intl-polyfill.d.ts +139 -0
  93. package/src/is-interactive.ts +12 -0
  94. package/src/kv.ts +430 -0
  95. package/src/logger.ts +73 -0
  96. package/src/metrics/index.ts +5 -0
  97. package/src/metrics/is-ci.ts +14 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/README.md +30 -0
  103. package/src/miniflare-cli/assets.ts +543 -0
  104. package/src/miniflare-cli/enum-keys.ts +17 -0
  105. package/src/miniflare-cli/index.ts +85 -0
  106. package/src/miniflare-cli/request-context.ts +40 -0
  107. package/src/module-collection.ts +247 -53
  108. package/src/open-in-browser.ts +17 -0
  109. package/src/package-manager.ts +219 -0
  110. package/src/pages/build.tsx +204 -0
  111. package/src/pages/constants.ts +8 -0
  112. package/src/pages/deployments.tsx +106 -0
  113. package/src/pages/dev.tsx +414 -0
  114. package/src/pages/functions/buildPlugin.ts +105 -0
  115. package/src/pages/functions/buildWorker.ts +151 -0
  116. package/src/pages/functions/filepath-routing.test.ts +234 -0
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes.ts +151 -0
  120. package/src/pages/index.tsx +84 -0
  121. package/src/pages/projects.tsx +163 -0
  122. package/src/pages/publish.tsx +338 -0
  123. package/src/pages/types.ts +40 -0
  124. package/src/pages/upload.tsx +415 -0
  125. package/src/pages/utils.ts +12 -0
  126. package/src/parse.ts +286 -0
  127. package/src/paths.ts +26 -0
  128. package/src/preview.ts +31 -0
  129. package/src/proxy.ts +434 -252
  130. package/src/publish.ts +794 -345
  131. package/src/pubsub/index.ts +286 -0
  132. package/src/pubsub/pubsub-commands.tsx +623 -0
  133. package/src/r2.ts +118 -0
  134. package/src/selfsigned.d.ts +29 -0
  135. package/src/sites.tsx +357 -99
  136. package/src/tail/filters.ts +279 -0
  137. package/src/tail/index.ts +299 -0
  138. package/src/tail/printing.ts +67 -0
  139. package/src/update-check.ts +19 -0
  140. package/src/user/choose-account.tsx +69 -0
  141. package/src/user/env-vars.ts +46 -0
  142. package/src/user/generate-auth-url.ts +33 -0
  143. package/src/user/generate-random-state.ts +16 -0
  144. package/src/user/index.ts +3 -0
  145. package/src/user/user.tsx +1189 -0
  146. package/src/whoami.tsx +169 -0
  147. package/src/worker-namespace.ts +206 -0
  148. package/src/worker.ts +203 -0
  149. package/src/zones.ts +76 -0
  150. package/templates/checked-fetch.js +17 -0
  151. package/templates/first-party-worker-module-facade.ts +18 -0
  152. package/templates/format-dev-errors.ts +32 -0
  153. package/templates/gitignore +171 -0
  154. package/templates/new-worker-scheduled.js +17 -0
  155. package/templates/new-worker-scheduled.ts +32 -0
  156. package/templates/new-worker.js +15 -0
  157. package/templates/new-worker.ts +30 -0
  158. package/templates/no-op-worker.js +10 -0
  159. package/templates/pages-shim.ts +9 -0
  160. package/templates/pages-template-plugin.ts +155 -0
  161. package/templates/pages-template-worker.ts +161 -0
  162. package/templates/serve-static-assets.ts +63 -0
  163. package/templates/service-bindings-module-facade.js +51 -0
  164. package/templates/service-bindings-sw-facade.js +39 -0
  165. package/templates/tsconfig.json +105 -0
  166. package/wrangler-dist/cli.d.ts +327 -0
  167. package/wrangler-dist/cli.js +134880 -109997
  168. package/pages/functions/buildWorker.ts +0 -62
  169. package/pages/functions/filepath-routing.test.ts +0 -39
  170. package/pages/functions/filepath-routing.ts +0 -221
  171. package/pages/functions/identifiers.ts +0 -78
  172. package/pages/functions/routes.ts +0 -158
  173. package/pages/functions/template-worker.ts +0 -144
  174. package/src/__tests__/mock-cfetch.ts +0 -171
  175. package/src/__tests__/mock-dialogs.ts +0 -65
  176. package/src/__tests__/run-in-tmp.ts +0 -19
  177. package/src/__tests__/run-wrangler.ts +0 -32
  178. package/src/api/form_data.ts +0 -131
  179. package/src/api/preview.ts +0 -128
  180. package/src/api/worker.ts +0 -155
  181. package/src/config.ts +0 -487
  182. package/src/kv.tsx +0 -267
  183. package/src/pages.tsx +0 -1031
  184. package/src/tail.tsx +0 -73
  185. package/src/user.tsx +0 -1025
  186. package/static-asset-facade.js +0 -47
  187. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  188. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  189. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  190. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  191. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  192. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  193. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  194. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  196. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  201. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  202. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  203. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  204. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  205. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  206. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  207. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  209. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  210. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  211. package/vendor/wrangler-mime/LICENSE +0 -21
  212. package/vendor/wrangler-mime/Mime.js +0 -97
  213. package/vendor/wrangler-mime/README.md +0 -187
  214. package/vendor/wrangler-mime/cli.js +0 -46
  215. package/vendor/wrangler-mime/index.js +0 -4
  216. package/vendor/wrangler-mime/lite.js +0 -4
  217. package/vendor/wrangler-mime/package.json +0 -52
  218. package/vendor/wrangler-mime/types/other.js +0 -1
  219. package/vendor/wrangler-mime/types/standard.js +0 -1
  220. package/wrangler-dist/cli.js.map +0 -7
@@ -1,9 +1,21 @@
1
- import fetch from "node-fetch";
2
- import type { RequestInit, HeadersInit } from "node-fetch";
3
- 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";
8
+ import type { URLSearchParams } from "node:url";
9
+ import type { RequestInit, HeadersInit, Response } from "undici";
4
10
 
5
- export const CF_API_BASE_URL =
6
- 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
+ });
7
19
 
8
20
  /**
9
21
  * Make a fetch request to the Cloudflare API.
@@ -15,55 +27,155 @@ export const CF_API_BASE_URL =
15
27
  * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
16
28
  */
17
29
  export async function fetchInternal<ResponseType>(
18
- resource: string,
19
- init: RequestInit = {},
20
- queryParams?: URLSearchParams
30
+ resource: string,
31
+ init: RequestInit = {},
32
+ queryParams?: URLSearchParams,
33
+ abortSignal?: AbortSignal
21
34
  ): Promise<ResponseType> {
22
- await requireLoggedIn();
23
- const apiToken = requireApiToken();
24
- const headers = cloneHeaders(init.headers);
25
- 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);
44
+
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
+ }
26
73
 
27
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
28
- const response = await fetch(`${CF_API_BASE_URL}${resource}${queryString}`, {
29
- method: "GET",
30
- ...init,
31
- headers,
32
- });
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})`;
80
+ }
33
81
 
34
- if (response.ok) {
35
- return (await response.json()) as ResponseType;
36
- } else {
37
- throw new Error(
38
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
39
- );
40
- }
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 };
41
90
  }
42
91
 
43
92
  async function requireLoggedIn(): Promise<void> {
44
- const loggedIn = await loginOrRefreshIfRequired();
45
- if (!loggedIn) {
46
- throw new Error("Not logged in.");
47
- }
93
+ const loggedIn = await loginOrRefreshIfRequired();
94
+ if (!loggedIn) {
95
+ throw new Error("Not logged in.");
96
+ }
48
97
  }
49
98
 
50
- function requireApiToken(): string {
51
- const apiToken = getAPIToken();
52
- if (!apiToken) {
53
- throw new Error("No API token found.");
54
- }
55
- return apiToken;
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
+ }
56
111
  }
57
112
 
58
- function cloneHeaders(headers: HeadersInit): HeadersInit {
59
- return { ...headers };
113
+ function addUserAgent(headers: Record<string, string>): void {
114
+ headers["User-Agent"] = `wrangler/${wranglerVersion}`;
60
115
  }
61
116
 
62
- function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
63
- if (headers["Authorization"]) {
64
- throw new Error(
65
- "The request already specifies an authorisation header - cannot add a new one."
66
- );
67
- }
68
- 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
+ export async function fetchKVGetValue(
128
+ accountId: string,
129
+ namespaceId: string,
130
+ key: string
131
+ ): Promise<ArrayBuffer> {
132
+ await requireLoggedIn();
133
+ const auth = requireApiToken();
134
+ const headers: Record<string, string> = {};
135
+ addAuthorizationHeaderIfUnspecified(headers, auth);
136
+ const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
137
+ const response = await fetch(resource, {
138
+ method: "GET",
139
+ headers,
140
+ });
141
+ if (response.ok) {
142
+ return await response.arrayBuffer();
143
+ } else {
144
+ throw new Error(
145
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
146
+ );
147
+ }
148
+ }
149
+
150
+ /**
151
+ * The implementation for fetching a R2 object from Cloudflare API.
152
+ * We have a special implementation to handle the non-standard API response
153
+ * that doesn't return JSON, likely due to the streaming nature.
154
+ *
155
+ * note: The implementation should be called from light wrappers for
156
+ * different methods (GET, PUT)
157
+ */
158
+ type ResponseWithBody = Response & { body: NonNullable<Response["body"]> };
159
+ export async function fetchR2Objects(
160
+ resource: string,
161
+ bodyInit: RequestInit = {}
162
+ ): Promise<ResponseWithBody> {
163
+ await requireLoggedIn();
164
+ const auth = requireApiToken();
165
+ const headers = cloneHeaders(bodyInit.headers);
166
+ addAuthorizationHeaderIfUnspecified(headers, auth);
167
+ addUserAgent(headers);
168
+
169
+ const response = await fetch(`${getCloudflareAPIBaseURL()}${resource}`, {
170
+ ...bodyInit,
171
+ headers,
172
+ });
173
+
174
+ if (response.ok && response.body) {
175
+ return response as ResponseWithBody;
176
+ } else {
177
+ throw new Error(
178
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
179
+ );
180
+ }
69
181
  }
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.
@@ -0,0 +1,263 @@
1
+ import type { Environment, RawEnvironment } from "./environment";
2
+
3
+ /**
4
+ * This is the static type definition for the configuration object.
5
+ *
6
+ * It reflects a normalized and validated version of the configuration that you can write in wrangler.toml,
7
+ * and optionally augment with arguments passed directly to wrangler.
8
+ *
9
+ * For more information about the configuration object, see the
10
+ * documentation at https://developers.cloudflare.com/workers/cli-wrangler/configuration
11
+ *
12
+ * Notes:
13
+ *
14
+ * - Fields that are only specified in `ConfigFields` and not `Environment` can only appear
15
+ * in the top level config and should not appear in any environments.
16
+ * - All top level fields in config and environments are optional in the wrangler.toml file.
17
+ *
18
+ * Legend for the annotations:
19
+ *
20
+ * - `@breaking`: the deprecation/optionality is a breaking change from wrangler 1.
21
+ * - `@todo`: there's more work to be done (with details attached).
22
+ */
23
+ export type Config = ConfigFields<DevConfig> & Environment;
24
+
25
+ export type RawConfig = Partial<ConfigFields<RawDevConfig>> &
26
+ RawEnvironment &
27
+ DeprecatedConfigFields &
28
+ EnvironmentMap;
29
+
30
+ export interface ConfigFields<Dev extends RawDevConfig> {
31
+ configPath: string | undefined;
32
+
33
+ /**
34
+ * A boolean to enable "legacy" style wrangler environments (from wrangler 1).
35
+ * These have been superseded by Services, but there may be projects that won't
36
+ * (or can't) use them. If you're using a legacy environment, you can set this
37
+ * to `true` to enable it.
38
+ */
39
+ legacy_env: boolean;
40
+
41
+ /**
42
+ * Whether Wrangler should send usage metrics to Cloudflare for this project.
43
+ *
44
+ * When defined this will override any user settings.
45
+ * Otherwise, Wrangler will use the user's preference.
46
+ */
47
+ send_metrics: boolean | undefined;
48
+
49
+ /**
50
+ * Options to configure the development server that your worker will use.
51
+ */
52
+ dev: Dev;
53
+
54
+ /**
55
+ * A list of migrations that should be uploaded with your Worker.
56
+ *
57
+ * These define changes in your Durable Object declarations.
58
+ *
59
+ * More details at https://developers.cloudflare.com/workers/learning/using-durable-objects#configuring-durable-object-classes-with-migrations
60
+ *
61
+ * @default `[]`
62
+ */
63
+ migrations: {
64
+ /** A unique identifier for this migration. */
65
+ tag: string;
66
+ /** The new Durable Objects being defined. */
67
+ new_classes?: string[];
68
+ /** The Durable Objects being renamed. */
69
+ renamed_classes?: {
70
+ from: string;
71
+ to: string;
72
+ }[];
73
+ /** The Durable Objects being removed. */
74
+ deleted_classes?: string[];
75
+ }[];
76
+
77
+ /**
78
+ * The definition of a Worker Site, a feature that lets you upload
79
+ * static assets with your Worker.
80
+ *
81
+ * More details at https://developers.cloudflare.com/workers/platform/sites
82
+ */
83
+ site:
84
+ | {
85
+ /**
86
+ * The directory containing your static assets.
87
+ *
88
+ * It must be a path relative to your wrangler.toml file.
89
+ * Example: bucket = "./public"
90
+ *
91
+ * If there is a `site` field then it must contain this `bucket` field.
92
+ */
93
+ bucket: string;
94
+
95
+ /**
96
+ * The location of your Worker script.
97
+ *
98
+ * @deprecated DO NOT use this (it's a holdover from wrangler 1.x). Either use the top level `main` field, or pass the path to your entry file as a command line argument.
99
+ * @breaking
100
+ */
101
+ "entry-point"?: string;
102
+
103
+ /**
104
+ * An exclusive list of .gitignore-style patterns that match file
105
+ * or directory names from your bucket location. Only matched
106
+ * items will be uploaded. Example: include = ["upload_dir"]
107
+ *
108
+ * @optional
109
+ * @default `[]`
110
+ */
111
+ include?: string[];
112
+
113
+ /**
114
+ * A list of .gitignore-style patterns that match files or
115
+ * directories in your bucket that should be excluded from
116
+ * uploads. Example: exclude = ["ignore_dir"]
117
+ *
118
+ * @optional
119
+ * @default `[]`
120
+ */
121
+ exclude?: string[];
122
+ }
123
+ | undefined;
124
+
125
+ /**
126
+ * Serve a folder of static assets with your Worker, without any additional code.
127
+ * This can either be a string, or an object with additional config fields.
128
+ */
129
+ assets:
130
+ | {
131
+ bucket: string;
132
+ include: string[];
133
+ exclude: string[];
134
+ browser_TTL: number | undefined;
135
+ serve_single_page_app: boolean;
136
+ }
137
+ | undefined;
138
+
139
+ /**
140
+ * A list of wasm modules that your worker should be bound to. This is
141
+ * the "legacy" way of binding to a wasm module. ES module workers should
142
+ * do proper module imports.
143
+ */
144
+ wasm_modules:
145
+ | {
146
+ [key: string]: string;
147
+ }
148
+ | undefined;
149
+
150
+ /**
151
+ * A list of text files that your worker should be bound to. This is
152
+ * the "legacy" way of binding to a text file. ES module workers should
153
+ * do proper module imports.
154
+ */
155
+ text_blobs:
156
+ | {
157
+ [key: string]: string;
158
+ }
159
+ | undefined;
160
+
161
+ /**
162
+ * A list of data files that your worker should be bound to. This is
163
+ * the "legacy" way of binding to a data file. ES module workers should
164
+ * do proper module imports.
165
+ */
166
+ data_blobs:
167
+ | {
168
+ [key: string]: string;
169
+ }
170
+ | undefined;
171
+ }
172
+
173
+ export interface DevConfig {
174
+ /**
175
+ * IP address for the local dev server to listen on,
176
+ *
177
+ * @default `localhost`
178
+ */
179
+ ip: string;
180
+
181
+ /**
182
+ * Port for the local dev server to listen on
183
+ *
184
+ * @default `8787`
185
+ */
186
+ port: number | undefined;
187
+
188
+ /**
189
+ * Port for the local dev server's inspector to listen on
190
+ *
191
+ * @default `9229`
192
+ */
193
+ inspector_port: number | undefined;
194
+
195
+ /**
196
+ * Protocol that local wrangler dev server listens to requests on.
197
+ *
198
+ * @default `http`
199
+ */
200
+ local_protocol: "http" | "https";
201
+
202
+ /**
203
+ * Protocol that wrangler dev forwards requests on
204
+ *
205
+ * Setting this to `http` is not currently implemented.
206
+ * See https://github.com/cloudflare/wrangler2/issues/583
207
+ *
208
+ * @default `https`
209
+ * @todo this needs to be implemented https://github.com/cloudflare/wrangler2/issues/583
210
+ */
211
+ upstream_protocol: "https" | "http";
212
+
213
+ /**
214
+ * Host to forward requests to, defaults to the host of the first route of project
215
+ */
216
+ host: string | undefined;
217
+ }
218
+
219
+ export type RawDevConfig = Partial<DevConfig>;
220
+
221
+ export interface DeprecatedConfigFields {
222
+ /**
223
+ * The project "type". A holdover from wrangler 1.x.
224
+ * Valid values were "webpack", "javascript", and "rust".
225
+ *
226
+ * @deprecated DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.
227
+ * @breaking
228
+ */
229
+ type?: "webpack" | "javascript" | "rust";
230
+
231
+ /**
232
+ * Path to the webpack config to use when building your worker.
233
+ * A holdover from wrangler 1.x, used with `type: "webpack"`.
234
+ *
235
+ * @deprecated DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.
236
+ * @breaking
237
+ */
238
+ webpack_config?: string;
239
+
240
+ /**
241
+ * Configuration only used by a standalone use of the miniflare binary.
242
+ * @deprecated
243
+ */
244
+ miniflare?: unknown;
245
+ }
246
+
247
+ interface EnvironmentMap {
248
+ /**
249
+ * The `env` section defines overrides for the configuration for different environments.
250
+ *
251
+ * All environment fields can be specified at the top level of the config indicating the default environment settings.
252
+ *
253
+ * - Some fields are inherited and overridable in each environment.
254
+ * - But some are not inherited and must be explicitly specified in every environment, if they are specified at the top level.
255
+ *
256
+ * For more information, see the documentation at https://developers.cloudflare.com/workers/cli-wrangler/configuration#environments
257
+ *
258
+ * @default `{}`
259
+ */
260
+ env?: {
261
+ [envName: string]: RawEnvironment;
262
+ };
263
+ }