wrangler 0.0.0-e0d2f35 → 0.0.0-e1b8ac4

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 (160) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +58 -31
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -28
  10. package/pages/functions/filepath-routing.ts +92 -131
  11. package/pages/functions/routes.ts +16 -18
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +50 -12
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/{mock-kv.ts → helpers/mock-kv.ts} +9 -16
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-process.ts +24 -0
  31. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  32. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  33. package/src/__tests__/{run-in-tmp.ts → helpers/run-in-tmp.ts} +11 -1
  34. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  35. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  36. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  37. package/src/__tests__/https-options.test.ts +130 -0
  38. package/src/__tests__/index.test.ts +171 -338
  39. package/src/__tests__/init.test.ts +1992 -0
  40. package/src/__tests__/jest.setup.ts +86 -8
  41. package/src/__tests__/kv.test.ts +745 -449
  42. package/src/__tests__/logger.test.ts +141 -0
  43. package/src/__tests__/package-manager.test.ts +353 -0
  44. package/src/__tests__/pages.test.ts +754 -0
  45. package/src/__tests__/parse.test.ts +330 -0
  46. package/src/__tests__/publish.test.ts +5631 -903
  47. package/src/__tests__/r2.test.ts +233 -0
  48. package/src/__tests__/route.test.ts +45 -0
  49. package/src/__tests__/secret.test.ts +370 -95
  50. package/src/__tests__/tail.test.ts +690 -0
  51. package/src/__tests__/user.test.ts +132 -0
  52. package/src/__tests__/whoami.test.tsx +58 -20
  53. package/src/abort.d.ts +3 -0
  54. package/src/bundle.ts +204 -0
  55. package/src/cfetch/index.ts +30 -20
  56. package/src/cfetch/internal.ts +101 -30
  57. package/src/cli.ts +6 -2
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +243 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +420 -0
  62. package/src/config/index.ts +225 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1580 -0
  65. package/src/config-cache.ts +45 -0
  66. package/src/create-worker-preview.ts +185 -0
  67. package/src/create-worker-upload-form.ts +254 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +399 -0
  70. package/src/dev/local.tsx +321 -0
  71. package/src/dev/remote.tsx +242 -0
  72. package/src/dev/use-esbuild.ts +112 -0
  73. package/src/dialogs.tsx +66 -8
  74. package/src/durable.ts +102 -0
  75. package/src/entry.ts +322 -0
  76. package/src/environment-variables.ts +35 -0
  77. package/src/errors.ts +11 -0
  78. package/src/generate-auth-url.ts +33 -0
  79. package/src/generate-random-state.ts +16 -0
  80. package/src/https-options.ts +123 -0
  81. package/src/index.tsx +1848 -1019
  82. package/src/inspect.ts +87 -20
  83. package/src/intl-polyfill.d.ts +139 -0
  84. package/src/{kv.tsx → kv.ts} +199 -67
  85. package/src/logger.ts +73 -0
  86. package/src/miniflare-cli/README.md +30 -0
  87. package/src/miniflare-cli/enum-keys.ts +17 -0
  88. package/src/miniflare-cli/index.ts +41 -0
  89. package/src/miniflare-cli/request-context.ts +40 -0
  90. package/src/module-collection.ts +229 -34
  91. package/src/open-in-browser.ts +17 -0
  92. package/src/package-manager.ts +174 -0
  93. package/src/pages.tsx +1145 -95
  94. package/src/parse.ts +222 -0
  95. package/src/paths.ts +26 -0
  96. package/src/proxy.ts +180 -74
  97. package/src/publish.ts +626 -310
  98. package/src/r2.ts +50 -0
  99. package/src/selfsigned.d.ts +29 -0
  100. package/src/sites.tsx +187 -59
  101. package/src/tail/filters.ts +279 -0
  102. package/src/tail/index.ts +299 -0
  103. package/src/tail/printing.ts +67 -0
  104. package/src/update-check.ts +19 -0
  105. package/src/user.tsx +359 -176
  106. package/src/whoami.tsx +5 -3
  107. package/src/{api/worker.ts → worker.ts} +66 -40
  108. package/src/zones.ts +73 -0
  109. package/templates/gitignore +171 -0
  110. package/templates/new-worker-scheduled.js +17 -0
  111. package/templates/new-worker-scheduled.ts +32 -0
  112. package/templates/new-worker.js +15 -0
  113. package/templates/new-worker.ts +30 -0
  114. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  115. package/templates/tsconfig.json +105 -0
  116. package/wrangler-dist/cli.js +112889 -110835
  117. package/src/__tests__/logout.test.ts +0 -64
  118. package/src/__tests__/mock-console.ts +0 -34
  119. package/src/__tests__/mock-dialogs.ts +0 -65
  120. package/src/__tests__/mock-user.ts +0 -27
  121. package/src/__tests__/run-wrangler.ts +0 -8
  122. package/src/api/form_data.ts +0 -135
  123. package/src/api/preview.ts +0 -128
  124. package/src/config.ts +0 -641
  125. package/src/dev.tsx +0 -830
  126. package/src/tail.tsx +0 -73
  127. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  128. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  129. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  130. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  131. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  132. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  133. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  134. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  139. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  140. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  141. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  142. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  143. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  144. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  145. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  147. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  148. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  149. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  150. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  151. package/vendor/wrangler-mime/LICENSE +0 -21
  152. package/vendor/wrangler-mime/Mime.js +0 -97
  153. package/vendor/wrangler-mime/README.md +0 -187
  154. package/vendor/wrangler-mime/cli.js +0 -46
  155. package/vendor/wrangler-mime/index.js +0 -4
  156. package/vendor/wrangler-mime/lite.js +0 -4
  157. package/vendor/wrangler-mime/package.json +0 -52
  158. package/vendor/wrangler-mime/types/other.js +0 -1
  159. package/vendor/wrangler-mime/types/standard.js +0 -1
  160. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,1580 @@
1
+ import path from "node:path";
2
+ import TOML from "@iarna/toml";
3
+ import { Diagnostics } from "./diagnostics";
4
+ import {
5
+ deprecated,
6
+ experimental,
7
+ hasProperty,
8
+ inheritable,
9
+ isBoolean,
10
+ isObjectWith,
11
+ isOneOf,
12
+ isOptionalProperty,
13
+ isRequiredProperty,
14
+ isString,
15
+ isStringArray,
16
+ validateAdditionalProperties,
17
+ notInheritable,
18
+ validateOptionalProperty,
19
+ validateOptionalTypedArray,
20
+ validateRequiredProperty,
21
+ validateTypedArray,
22
+ all,
23
+ isMutuallyExclusiveWith,
24
+ inheritableInLegacyEnvironments,
25
+ appendEnvName,
26
+ getBindingNames,
27
+ isValidName,
28
+ } from "./validation-helpers";
29
+ import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
30
+ import type {
31
+ RawEnvironment,
32
+ DeprecatedUpload,
33
+ Environment,
34
+ Rule,
35
+ } from "./environment";
36
+ import type { ValidatorFn } from "./validation-helpers";
37
+
38
+ const ENGLISH = new Intl.ListFormat("en");
39
+
40
+ /**
41
+ * Validate the given `rawConfig` object that was loaded from `configPath`.
42
+ *
43
+ * The configuration is normalized, which includes using default values for missing field,
44
+ * and copying over inheritable fields into named environments.
45
+ *
46
+ * Any errors or warnings from the validation are available in the returned `diagnostics` object.
47
+ */
48
+ export function normalizeAndValidateConfig(
49
+ rawConfig: RawConfig,
50
+ configPath: string | undefined,
51
+ args: unknown
52
+ ): {
53
+ config: Config;
54
+ diagnostics: Diagnostics;
55
+ } {
56
+ const diagnostics = new Diagnostics(
57
+ `Processing ${
58
+ configPath ? path.relative(process.cwd(), configPath) : "wrangler"
59
+ } configuration:`
60
+ );
61
+
62
+ deprecated(
63
+ diagnostics,
64
+ rawConfig,
65
+ "miniflare",
66
+ "Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.",
67
+ true,
68
+ "😶 Ignored"
69
+ );
70
+
71
+ deprecated(
72
+ diagnostics,
73
+ rawConfig,
74
+ "type",
75
+ "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.",
76
+ true,
77
+ "😶 Ignored"
78
+ );
79
+
80
+ deprecated(
81
+ diagnostics,
82
+ rawConfig,
83
+ "webpack_config",
84
+ "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.",
85
+ true,
86
+ "😶 Ignored"
87
+ );
88
+
89
+ validateOptionalProperty(
90
+ diagnostics,
91
+ "",
92
+ "legacy_env",
93
+ rawConfig.legacy_env,
94
+ "boolean"
95
+ );
96
+
97
+ // TODO: set the default to false to turn on service environments as the default
98
+ const isLegacyEnv =
99
+ (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
100
+ rawConfig.legacy_env ??
101
+ true;
102
+
103
+ // TODO: remove this once service environments goes GA.
104
+ if (!isLegacyEnv) {
105
+ diagnostics.warnings.push(
106
+ "Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
107
+ );
108
+ }
109
+
110
+ const topLevelEnv = normalizeAndValidateEnvironment(
111
+ diagnostics,
112
+ configPath,
113
+ rawConfig
114
+ );
115
+
116
+ //TODO: find a better way to define the type of Args that can be passed to the normalizeAndValidateConfig()
117
+ const envName = (args as { env: string | undefined }).env;
118
+
119
+ let activeEnv = topLevelEnv;
120
+ if (envName !== undefined) {
121
+ const envDiagnostics = new Diagnostics(
122
+ `"env.${envName}" environment configuration`
123
+ );
124
+ const rawEnv = rawConfig.env?.[envName];
125
+ if (rawEnv !== undefined) {
126
+ activeEnv = normalizeAndValidateEnvironment(
127
+ envDiagnostics,
128
+ configPath,
129
+ rawEnv,
130
+ envName,
131
+ topLevelEnv,
132
+ isLegacyEnv,
133
+ rawConfig
134
+ );
135
+ diagnostics.addChild(envDiagnostics);
136
+ } else {
137
+ // An environment was specified, but no configuration for it was found.
138
+ // To cover any legacy environment cases, where the `envName` is used,
139
+ // Let's create a fake active environment with the specified `envName`.
140
+ activeEnv = normalizeAndValidateEnvironment(
141
+ envDiagnostics,
142
+ configPath,
143
+ {},
144
+ envName,
145
+ topLevelEnv,
146
+ isLegacyEnv,
147
+ rawConfig
148
+ );
149
+ const envNames = rawConfig.env
150
+ ? `The available configured environment names are: ${JSON.stringify(
151
+ Object.keys(rawConfig.env)
152
+ )}\n`
153
+ : "";
154
+ const message =
155
+ `No environment found in configuration with name "${envName}".\n` +
156
+ `Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
157
+ `${envNames}\n` +
158
+ `Consider adding an environment configuration section to the wrangler.toml file:\n` +
159
+ "```\n[env." +
160
+ envName +
161
+ "]\n```\n";
162
+
163
+ if (envNames.length > 0) {
164
+ diagnostics.errors.push(message);
165
+ } else {
166
+ // Only warn (rather than error) if there are not actually any environments configured in wrangler.toml.
167
+ diagnostics.warnings.push(message);
168
+ }
169
+ }
170
+ }
171
+
172
+ // Process the top-level default environment configuration.
173
+ const config: Config = {
174
+ configPath,
175
+ legacy_env: isLegacyEnv,
176
+ ...activeEnv,
177
+ dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
178
+ migrations: normalizeAndValidateMigrations(
179
+ diagnostics,
180
+ rawConfig.migrations ?? [],
181
+ activeEnv.durable_objects
182
+ ),
183
+ site: normalizeAndValidateSite(
184
+ diagnostics,
185
+ configPath,
186
+ rawConfig,
187
+ activeEnv.main
188
+ ),
189
+ assets: normalizeAndValidateAssets(diagnostics, configPath, rawConfig),
190
+ wasm_modules: normalizeAndValidateModulePaths(
191
+ diagnostics,
192
+ configPath,
193
+ "wasm_modules",
194
+ rawConfig.wasm_modules
195
+ ),
196
+ text_blobs: normalizeAndValidateModulePaths(
197
+ diagnostics,
198
+ configPath,
199
+ "text_blobs",
200
+ rawConfig.text_blobs
201
+ ),
202
+ data_blobs: normalizeAndValidateModulePaths(
203
+ diagnostics,
204
+ configPath,
205
+ "data_blobs",
206
+ rawConfig.data_blobs
207
+ ),
208
+ };
209
+
210
+ validateBindingsHaveUniqueNames(diagnostics, config);
211
+
212
+ validateAdditionalProperties(
213
+ diagnostics,
214
+ "top-level",
215
+ Object.keys(rawConfig),
216
+ [...Object.keys(config), "env"]
217
+ );
218
+
219
+ experimental(diagnostics, rawConfig, "assets");
220
+
221
+ return { config, diagnostics };
222
+ }
223
+
224
+ /**
225
+ * Validate the `build` configuration and return the normalized values.
226
+ */
227
+ function normalizeAndValidateBuild(
228
+ diagnostics: Diagnostics,
229
+ rawEnv: RawEnvironment,
230
+ rawBuild: Config["build"],
231
+ configPath: string | undefined
232
+ ): Config["build"] & { deprecatedUpload: DeprecatedUpload } {
233
+ const { command, cwd, watch_dir = "./src", upload, ...rest } = rawBuild;
234
+ const deprecatedUpload: DeprecatedUpload = { ...upload };
235
+ validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
236
+
237
+ validateOptionalProperty(diagnostics, "build", "command", command, "string");
238
+ validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
239
+ if (Array.isArray(watch_dir)) {
240
+ validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
241
+ } else {
242
+ validateOptionalProperty(
243
+ diagnostics,
244
+ "build",
245
+ "watch_dir",
246
+ watch_dir,
247
+ "string"
248
+ );
249
+ }
250
+
251
+ deprecated(
252
+ diagnostics,
253
+ rawEnv,
254
+ "build.upload.format",
255
+ "The format is inferred automatically from the code.",
256
+ true
257
+ );
258
+
259
+ if (rawEnv.main !== undefined && rawBuild.upload?.main) {
260
+ diagnostics.errors.push(
261
+ `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
262
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
263
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
264
+ );
265
+ } else {
266
+ deprecated(
267
+ diagnostics,
268
+ rawEnv,
269
+ "build.upload.main",
270
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
271
+ `Then add the top level \`main\` field to your configuration file:\n` +
272
+ `\`\`\`\n` +
273
+ `main = "${path.join(
274
+ rawBuild.upload?.dir ?? "./dist",
275
+ rawBuild.upload?.main ?? "."
276
+ )}"\n` +
277
+ `\`\`\``,
278
+ true
279
+ );
280
+
281
+ deprecated(
282
+ diagnostics,
283
+ rawEnv,
284
+ "build.upload.dir",
285
+ `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
286
+ true
287
+ );
288
+ }
289
+
290
+ return {
291
+ command,
292
+ watch_dir:
293
+ // - `watch_dir` only matters when `command` is defined, so we apply
294
+ // a default only when `command` is defined
295
+ // - `configPath` will always be defined since `build` can only
296
+ // be configured in `wrangler.toml`, but who knows, that may
297
+ // change in the future, so we do a check anyway
298
+ command && configPath
299
+ ? Array.isArray(watch_dir)
300
+ ? watch_dir.map((dir) =>
301
+ path.relative(
302
+ process.cwd(),
303
+ path.join(path.dirname(configPath), `${dir}`)
304
+ )
305
+ )
306
+ : path.relative(
307
+ process.cwd(),
308
+ path.join(path.dirname(configPath), `${watch_dir}`)
309
+ )
310
+ : watch_dir,
311
+ cwd,
312
+ deprecatedUpload,
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Validate the `main` field and return the normalized values.
318
+ */
319
+ function normalizeAndValidateMainField(
320
+ configPath: string | undefined,
321
+ rawMain: string | undefined,
322
+ deprecatedUpload: DeprecatedUpload | undefined
323
+ ): string | undefined {
324
+ const configDir = path.dirname(configPath ?? "wrangler.toml");
325
+ if (rawMain !== undefined) {
326
+ if (typeof rawMain === "string") {
327
+ const directory = path.resolve(configDir);
328
+ return path.resolve(directory, rawMain);
329
+ } else {
330
+ return rawMain;
331
+ }
332
+ } else if (deprecatedUpload?.main !== undefined) {
333
+ const directory = path.resolve(
334
+ configDir,
335
+ deprecatedUpload?.dir || "./dist"
336
+ );
337
+ return path.resolve(directory, deprecatedUpload.main);
338
+ } else {
339
+ return;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Validate the `dev` configuration and return the normalized values.
345
+ */
346
+ function normalizeAndValidateDev(
347
+ diagnostics: Diagnostics,
348
+ rawDev: RawDevConfig
349
+ ): DevConfig {
350
+ const {
351
+ ip = "localhost",
352
+ port,
353
+ local_protocol = "http",
354
+ upstream_protocol = "https",
355
+ host,
356
+ ...rest
357
+ } = rawDev;
358
+ validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
359
+
360
+ validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
361
+ validateOptionalProperty(diagnostics, "dev", "port", port, "number");
362
+ validateOptionalProperty(
363
+ diagnostics,
364
+ "dev",
365
+ "local_protocol",
366
+ local_protocol,
367
+ "string",
368
+ ["http", "https"]
369
+ );
370
+ validateOptionalProperty(
371
+ diagnostics,
372
+ "dev",
373
+ "upstream_protocol",
374
+ upstream_protocol,
375
+ "string",
376
+ ["http", "https"]
377
+ );
378
+ validateOptionalProperty(diagnostics, "dev", "host", host, "string");
379
+ return { ip, port, local_protocol, upstream_protocol, host };
380
+ }
381
+
382
+ /**
383
+ * Validate the `migrations` configuration and return the normalized values.
384
+ */
385
+ function normalizeAndValidateMigrations(
386
+ diagnostics: Diagnostics,
387
+ rawMigrations: Config["migrations"],
388
+ durableObjects: Config["durable_objects"]
389
+ ): Config["migrations"] {
390
+ if (!Array.isArray(rawMigrations)) {
391
+ diagnostics.errors.push(
392
+ `The optional "migrations" field should be an array, but got ${JSON.stringify(
393
+ rawMigrations
394
+ )}`
395
+ );
396
+ return [];
397
+ } else {
398
+ for (let i = 0; i < rawMigrations.length; i++) {
399
+ const { tag, new_classes, renamed_classes, deleted_classes, ...rest } =
400
+ rawMigrations[i];
401
+
402
+ validateAdditionalProperties(
403
+ diagnostics,
404
+ "migrations",
405
+ Object.keys(rest),
406
+ []
407
+ );
408
+
409
+ validateRequiredProperty(
410
+ diagnostics,
411
+ `migrations[${i}]`,
412
+ `tag`,
413
+ tag,
414
+ "string"
415
+ );
416
+ validateOptionalTypedArray(
417
+ diagnostics,
418
+ `migrations[${i}].new_classes`,
419
+ new_classes,
420
+ "string"
421
+ );
422
+ if (renamed_classes !== undefined) {
423
+ if (!Array.isArray(renamed_classes)) {
424
+ diagnostics.errors.push(
425
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
426
+ renamed_classes
427
+ )}.`
428
+ );
429
+ } else if (
430
+ renamed_classes.some(
431
+ (c) =>
432
+ typeof c !== "object" ||
433
+ !isRequiredProperty(c, "from", "string") ||
434
+ !isRequiredProperty(c, "to", "string")
435
+ )
436
+ ) {
437
+ diagnostics.errors.push(
438
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
439
+ renamed_classes
440
+ )}.`
441
+ );
442
+ }
443
+ }
444
+ validateOptionalTypedArray(
445
+ diagnostics,
446
+ `migrations[${i}].deleted_classes`,
447
+ deleted_classes,
448
+ "string"
449
+ );
450
+ }
451
+
452
+ if (
453
+ Array.isArray(durableObjects?.bindings) &&
454
+ durableObjects.bindings.length > 0
455
+ ) {
456
+ // intrinsic [durable_objects] implies [migrations]
457
+ const exportedDurableObjects = (durableObjects.bindings || []).filter(
458
+ (binding) => !binding.script_name
459
+ );
460
+ if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
461
+ if (
462
+ !exportedDurableObjects.some(
463
+ (exportedDurableObject) =>
464
+ typeof exportedDurableObject.class_name !== "string"
465
+ )
466
+ ) {
467
+ const durableObjectClassnames = exportedDurableObjects.map(
468
+ (durable) => durable.class_name
469
+ );
470
+
471
+ diagnostics.warnings.push(
472
+ `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
473
+ ", "
474
+ )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
475
+
476
+ \`\`\`
477
+ [[migrations]]
478
+ tag = "v1" # Should be unique for each entry
479
+ new_classes = [${durableObjectClassnames
480
+ .map((name) => `"${name}"`)
481
+ .join(", ")}]
482
+ \`\`\`
483
+
484
+ Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
485
+ );
486
+ }
487
+ }
488
+ }
489
+
490
+ return rawMigrations;
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Validate the `site` configuration and return the normalized values.
496
+ */
497
+ function normalizeAndValidateSite(
498
+ diagnostics: Diagnostics,
499
+ configPath: string | undefined,
500
+ rawConfig: RawConfig,
501
+ mainEntryPoint: string | undefined
502
+ ): Config["site"] {
503
+ if (rawConfig?.site !== undefined) {
504
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
505
+
506
+ validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
507
+ "entry-point",
508
+ ]);
509
+ validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
510
+ validateTypedArray(diagnostics, "sites.include", include, "string");
511
+ validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
512
+ validateOptionalProperty(
513
+ diagnostics,
514
+ "site",
515
+ "entry-point",
516
+ rawConfig.site["entry-point"],
517
+ "string"
518
+ );
519
+
520
+ deprecated(
521
+ diagnostics,
522
+ rawConfig,
523
+ `site.entry-point`,
524
+ `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:\n` +
525
+ `\`\`\`\n` +
526
+ `main = "${path.join(
527
+ String(rawConfig.site["entry-point"]) || "workers-site",
528
+ path.extname(String(rawConfig.site["entry-point"]) || "workers-site")
529
+ ? ""
530
+ : "index.js"
531
+ )}"\n` +
532
+ `\`\`\``,
533
+ false,
534
+ undefined,
535
+ "warning"
536
+ );
537
+
538
+ let siteEntryPoint = rawConfig.site["entry-point"];
539
+
540
+ if (!mainEntryPoint && !siteEntryPoint) {
541
+ // this means that we're defaulting to "workers-site"
542
+ // so let's add the deprecation warning
543
+ diagnostics.warnings.push(
544
+ `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.\n` +
545
+ `Add the top level \`main\` field to your configuration file:\n` +
546
+ `\`\`\`\n` +
547
+ `main = "workers-site/index.js"\n` +
548
+ `\`\`\``
549
+ );
550
+ siteEntryPoint = "workers-site";
551
+ } else if (mainEntryPoint && siteEntryPoint) {
552
+ diagnostics.errors.push(
553
+ `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.\n` +
554
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
555
+ `Delete the deprecated \`site.entry-point\` field from your config.`
556
+ );
557
+ }
558
+
559
+ if (configPath && siteEntryPoint) {
560
+ // rewrite the path to be relative to the working directory
561
+ siteEntryPoint = path.relative(
562
+ process.cwd(),
563
+ path.join(path.dirname(configPath), siteEntryPoint)
564
+ );
565
+ }
566
+
567
+ return {
568
+ bucket,
569
+ "entry-point": siteEntryPoint,
570
+ include,
571
+ exclude,
572
+ };
573
+ }
574
+ return undefined;
575
+ }
576
+
577
+ /**
578
+ * Validate the `assets` configuration and return normalized values.
579
+ */
580
+ function normalizeAndValidateAssets(
581
+ diagnostics: Diagnostics,
582
+ configPath: string | undefined,
583
+ rawConfig: RawConfig
584
+ ) {
585
+ if (
586
+ typeof rawConfig?.assets === "string" ||
587
+ rawConfig?.assets === undefined
588
+ ) {
589
+ return rawConfig?.assets;
590
+ }
591
+
592
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.assets;
593
+
594
+ validateAdditionalProperties(diagnostics, "assets", Object.keys(rest), []);
595
+ validateRequiredProperty(diagnostics, "assets", "bucket", bucket, "string");
596
+ validateTypedArray(diagnostics, "assets.include", include, "string");
597
+ validateTypedArray(diagnostics, "assets.exclude", exclude, "string");
598
+
599
+ return {
600
+ bucket,
601
+ include,
602
+ exclude,
603
+ };
604
+ }
605
+
606
+ /**
607
+ * Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
608
+ */
609
+ function normalizeAndValidateModulePaths(
610
+ diagnostics: Diagnostics,
611
+ configPath: string | undefined,
612
+ field: "wasm_modules" | "text_blobs" | "data_blobs",
613
+ rawMapping: Record<string, string> | undefined
614
+ ): Record<string, string> | undefined {
615
+ if (rawMapping === undefined) {
616
+ return undefined;
617
+ }
618
+ const mapping: Record<string, string> = {};
619
+ // Rewrite paths to be relative to the cwd, rather than the config path.
620
+ for (const [name, filePath] of Object.entries(rawMapping)) {
621
+ if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
622
+ if (configPath) {
623
+ mapping[name] = configPath
624
+ ? path.relative(
625
+ process.cwd(),
626
+ path.join(path.dirname(configPath), filePath)
627
+ )
628
+ : filePath;
629
+ }
630
+ }
631
+ }
632
+ return mapping;
633
+ }
634
+
635
+ /**
636
+ * Check whether a value has the shape of a route, which can be a string
637
+ * or an object that looks like {pattern: string, zone_id: string }
638
+ */
639
+ function isValidRouteValue(item: unknown): boolean {
640
+ if (!item) {
641
+ return false;
642
+ }
643
+ if (typeof item === "string") {
644
+ return true;
645
+ }
646
+ if (typeof item === "object") {
647
+ if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
648
+ return false;
649
+ }
650
+
651
+ const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
652
+
653
+ const hasZoneId =
654
+ hasProperty(item, "zone_id") && typeof item.zone_id === "string";
655
+ const hasZoneName =
656
+ hasProperty(item, "zone_name") && typeof item.zone_name === "string";
657
+ const hasCustomDomainFlag =
658
+ hasProperty(item, "custom_domain") &&
659
+ typeof item.custom_domain === "boolean";
660
+
661
+ if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
662
+ return true;
663
+ } else if (
664
+ otherKeys === 1 &&
665
+ (hasZoneId || hasZoneName || hasCustomDomainFlag)
666
+ ) {
667
+ return true;
668
+ }
669
+ }
670
+ return false;
671
+ }
672
+
673
+ /**
674
+ * Validate that the field is a route.
675
+ */
676
+ const isRoute: ValidatorFn = (diagnostics, field, value) => {
677
+ if (value !== undefined && !isValidRouteValue(value)) {
678
+ diagnostics.errors.push(
679
+ `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
680
+ value
681
+ )}.`
682
+ );
683
+ return false;
684
+ }
685
+ return true;
686
+ };
687
+
688
+ /**
689
+ * Validate that the field is an array of routes.
690
+ */
691
+ const isRouteArray: ValidatorFn = (diagnostics, field, value) => {
692
+ if (value === undefined) {
693
+ return true;
694
+ }
695
+ if (!Array.isArray(value)) {
696
+ diagnostics.errors.push(
697
+ `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
698
+ );
699
+ return false;
700
+ }
701
+ const invalidRoutes = [];
702
+ for (const item of value) {
703
+ if (!isValidRouteValue(item)) {
704
+ invalidRoutes.push(item);
705
+ }
706
+ }
707
+ if (invalidRoutes.length > 0) {
708
+ diagnostics.errors.push(
709
+ `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
710
+ invalidRoutes,
711
+ null,
712
+ 2
713
+ )}.`
714
+ );
715
+ }
716
+ return invalidRoutes.length === 0;
717
+ };
718
+
719
+ function validateRoute(
720
+ diagnostics: Diagnostics,
721
+ topLevelEnv: Environment | undefined,
722
+ rawEnv: RawEnvironment
723
+ ): Config["route"] {
724
+ return inheritable(
725
+ diagnostics,
726
+ topLevelEnv,
727
+ rawEnv,
728
+ "route",
729
+ isRoute,
730
+ undefined
731
+ );
732
+ }
733
+
734
+ function validateRoutes(
735
+ diagnostics: Diagnostics,
736
+ topLevelEnv: Environment | undefined,
737
+ rawEnv: RawEnvironment
738
+ ): Config["routes"] {
739
+ return inheritable(
740
+ diagnostics,
741
+ topLevelEnv,
742
+ rawEnv,
743
+ "routes",
744
+ all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
745
+ undefined
746
+ );
747
+ }
748
+
749
+ /**
750
+ * Validate top-level environment configuration and return the normalized values.
751
+ */
752
+ function normalizeAndValidateEnvironment(
753
+ diagnostics: Diagnostics,
754
+ configPath: string | undefined,
755
+ topLevelEnv: RawEnvironment
756
+ ): Environment;
757
+ /**
758
+ * Validate the named environment configuration and return the normalized values.
759
+ */
760
+ function normalizeAndValidateEnvironment(
761
+ diagnostics: Diagnostics,
762
+ configPath: string | undefined,
763
+ rawEnv: RawEnvironment,
764
+ envName: string,
765
+ topLevelEnv: Environment,
766
+ isLegacyEnv: boolean,
767
+ rawConfig: RawConfig
768
+ ): Environment;
769
+ function normalizeAndValidateEnvironment(
770
+ diagnostics: Diagnostics,
771
+ configPath: string | undefined,
772
+ rawEnv: RawEnvironment,
773
+ envName = "top level",
774
+ topLevelEnv?: Environment | undefined,
775
+ isLegacyEnv?: boolean,
776
+ rawConfig?: RawConfig | undefined
777
+ ): Environment {
778
+ deprecated(
779
+ diagnostics,
780
+ rawEnv,
781
+ "zone_id",
782
+ "This is unnecessary since we can deduce this from routes directly.",
783
+ false // We need to leave this in-place for the moment since `route` commands might use it.
784
+ );
785
+
786
+ // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
787
+ // TODO: remove this before GA.
788
+ deprecated(
789
+ diagnostics,
790
+ rawEnv,
791
+ "experimental_services",
792
+ `The "experimental_services" field is no longer supported. Simply rename the [experimental_services] field to [services].`,
793
+ true
794
+ );
795
+
796
+ experimental(diagnostics, rawEnv, "unsafe");
797
+ experimental(diagnostics, rawEnv, "services");
798
+
799
+ const route = validateRoute(diagnostics, topLevelEnv, rawEnv);
800
+
801
+ const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
802
+
803
+ const workers_dev = inheritable(
804
+ diagnostics,
805
+ topLevelEnv,
806
+ rawEnv,
807
+ "workers_dev",
808
+ isBoolean,
809
+ undefined
810
+ );
811
+
812
+ const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
813
+ diagnostics,
814
+ rawEnv,
815
+ rawEnv.build ?? topLevelEnv?.build ?? {},
816
+ configPath
817
+ );
818
+
819
+ const environment: Environment = {
820
+ // Inherited fields
821
+ account_id: inheritableInLegacyEnvironments(
822
+ diagnostics,
823
+ isLegacyEnv,
824
+ topLevelEnv,
825
+ rawEnv,
826
+ "account_id",
827
+ isString,
828
+ undefined,
829
+ undefined
830
+ ),
831
+ compatibility_date: inheritable(
832
+ diagnostics,
833
+ topLevelEnv,
834
+ rawEnv,
835
+ "compatibility_date",
836
+ isString,
837
+ undefined
838
+ ),
839
+ compatibility_flags: inheritable(
840
+ diagnostics,
841
+ topLevelEnv,
842
+ rawEnv,
843
+ "compatibility_flags",
844
+ isStringArray,
845
+ []
846
+ ),
847
+ jsx_factory: inheritable(
848
+ diagnostics,
849
+ topLevelEnv,
850
+ rawEnv,
851
+ "jsx_factory",
852
+ isString,
853
+ "React.createElement"
854
+ ),
855
+ jsx_fragment: inheritable(
856
+ diagnostics,
857
+ topLevelEnv,
858
+ rawEnv,
859
+ "jsx_fragment",
860
+ isString,
861
+ "React.Fragment"
862
+ ),
863
+ tsconfig: validateAndNormalizeTsconfig(
864
+ diagnostics,
865
+ topLevelEnv,
866
+ rawEnv,
867
+ configPath
868
+ ),
869
+ rules: validateAndNormalizeRules(
870
+ diagnostics,
871
+ topLevelEnv,
872
+ rawEnv,
873
+ deprecatedUpload?.rules,
874
+ envName
875
+ ),
876
+ name: inheritableInLegacyEnvironments(
877
+ diagnostics,
878
+ isLegacyEnv,
879
+ topLevelEnv,
880
+ rawEnv,
881
+ "name",
882
+ isValidName,
883
+ appendEnvName(envName),
884
+ undefined
885
+ ),
886
+ main: normalizeAndValidateMainField(
887
+ configPath,
888
+ inheritable(
889
+ diagnostics,
890
+ topLevelEnv,
891
+ rawEnv,
892
+ "main",
893
+ isString,
894
+ undefined
895
+ ),
896
+ deprecatedUpload
897
+ ),
898
+ route,
899
+ routes,
900
+ triggers: inheritable(
901
+ diagnostics,
902
+ topLevelEnv,
903
+ rawEnv,
904
+ "triggers",
905
+ isObjectWith("crons"),
906
+ { crons: [] }
907
+ ),
908
+ usage_model: inheritable(
909
+ diagnostics,
910
+ topLevelEnv,
911
+ rawEnv,
912
+ "usage_model",
913
+ isOneOf("bundled", "unbound"),
914
+ undefined
915
+ ),
916
+ build,
917
+ workers_dev,
918
+ // Not inherited fields
919
+ vars: notInheritable(
920
+ diagnostics,
921
+ topLevelEnv,
922
+ rawConfig,
923
+ rawEnv,
924
+ envName,
925
+ "vars",
926
+ validateVars(envName),
927
+ {}
928
+ ),
929
+ durable_objects: notInheritable(
930
+ diagnostics,
931
+ topLevelEnv,
932
+ rawConfig,
933
+ rawEnv,
934
+ envName,
935
+ "durable_objects",
936
+ validateBindingsProperty(envName, validateDurableObjectBinding),
937
+ {
938
+ bindings: [],
939
+ }
940
+ ),
941
+ kv_namespaces: notInheritable(
942
+ diagnostics,
943
+ topLevelEnv,
944
+ rawConfig,
945
+ rawEnv,
946
+ envName,
947
+ "kv_namespaces",
948
+ validateBindingArray(envName, validateKVBinding),
949
+ []
950
+ ),
951
+ r2_buckets: notInheritable(
952
+ diagnostics,
953
+ topLevelEnv,
954
+ rawConfig,
955
+ rawEnv,
956
+ envName,
957
+ "r2_buckets",
958
+ validateBindingArray(envName, validateR2Binding),
959
+ []
960
+ ),
961
+ services: notInheritable(
962
+ diagnostics,
963
+ topLevelEnv,
964
+ rawConfig,
965
+ rawEnv,
966
+ envName,
967
+ "services",
968
+ validateBindingArray(envName, validateServiceBinding),
969
+ []
970
+ ),
971
+ unsafe: notInheritable(
972
+ diagnostics,
973
+ topLevelEnv,
974
+ rawConfig,
975
+ rawEnv,
976
+ envName,
977
+ "unsafe",
978
+ validateBindingsProperty(envName, validateUnsafeBinding),
979
+ {
980
+ bindings: [],
981
+ }
982
+ ),
983
+ zone_id: rawEnv.zone_id,
984
+ minify: inheritable(
985
+ diagnostics,
986
+ topLevelEnv,
987
+ rawEnv,
988
+ "minify",
989
+ isBoolean,
990
+ undefined
991
+ ),
992
+ node_compat: inheritable(
993
+ diagnostics,
994
+ topLevelEnv,
995
+ rawEnv,
996
+ "node_compat",
997
+ isBoolean,
998
+ undefined
999
+ ),
1000
+ };
1001
+
1002
+ return environment;
1003
+ }
1004
+
1005
+ function validateAndNormalizeTsconfig(
1006
+ diagnostics: Diagnostics,
1007
+ topLevelEnv: Environment | undefined,
1008
+ rawEnv: RawEnvironment,
1009
+ configPath: string | undefined
1010
+ ) {
1011
+ const tsconfig = inheritable(
1012
+ diagnostics,
1013
+ topLevelEnv,
1014
+ rawEnv,
1015
+ "tsconfig",
1016
+ isString,
1017
+ undefined
1018
+ );
1019
+
1020
+ return configPath && tsconfig
1021
+ ? path.relative(
1022
+ process.cwd(),
1023
+ path.join(path.dirname(configPath), tsconfig)
1024
+ )
1025
+ : tsconfig;
1026
+ }
1027
+
1028
+ const validateAndNormalizeRules = (
1029
+ diagnostics: Diagnostics,
1030
+ topLevelEnv: Environment | undefined,
1031
+ rawEnv: RawEnvironment,
1032
+ deprecatedRules: Rule[] | undefined,
1033
+ envName: string
1034
+ ): Rule[] => {
1035
+ if (topLevelEnv === undefined) {
1036
+ // Only create errors/warnings for the top-level environment
1037
+ if (rawEnv.rules && deprecatedRules) {
1038
+ diagnostics.errors.push(
1039
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
1040
+ );
1041
+ } else if (deprecatedRules) {
1042
+ diagnostics.warnings.push(
1043
+ `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:\n` +
1044
+ "```\n" +
1045
+ TOML.stringify({ rules: deprecatedRules }) +
1046
+ "```"
1047
+ );
1048
+ }
1049
+ }
1050
+
1051
+ return inheritable(
1052
+ diagnostics,
1053
+ topLevelEnv,
1054
+ rawEnv,
1055
+ "rules",
1056
+ validateRules(envName),
1057
+ deprecatedRules ?? []
1058
+ );
1059
+ };
1060
+
1061
+ const validateRules =
1062
+ (envName: string): ValidatorFn =>
1063
+ (diagnostics, field, envValue, config) => {
1064
+ if (!envValue) {
1065
+ return true;
1066
+ }
1067
+ const fieldPath =
1068
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1069
+ if (!Array.isArray(envValue)) {
1070
+ diagnostics.errors.push(
1071
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1072
+ envValue
1073
+ )}.`
1074
+ );
1075
+ return false;
1076
+ }
1077
+
1078
+ let isValid = true;
1079
+ for (let i = 0; i < envValue.length; i++) {
1080
+ isValid =
1081
+ validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
1082
+ isValid;
1083
+ }
1084
+ return isValid;
1085
+ };
1086
+
1087
+ const validateRule: ValidatorFn = (diagnostics, field, value) => {
1088
+ if (typeof value !== "object" || value === null) {
1089
+ diagnostics.errors.push(
1090
+ `"${field}" should be an object but got ${JSON.stringify(value)}.`
1091
+ );
1092
+ return false;
1093
+ }
1094
+ // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
1095
+ let isValid = true;
1096
+ const rule = value as Rule;
1097
+
1098
+ if (
1099
+ !isRequiredProperty(rule, "type", "string", [
1100
+ "ESModule",
1101
+ "CommonJS",
1102
+ "CompiledWasm",
1103
+ "Text",
1104
+ "Data",
1105
+ ])
1106
+ ) {
1107
+ diagnostics.errors.push(
1108
+ `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
1109
+ );
1110
+ isValid = false;
1111
+ }
1112
+
1113
+ isValid =
1114
+ validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
1115
+ isValid;
1116
+
1117
+ if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
1118
+ diagnostics.errors.push(
1119
+ `the field "fallthrough", when present, should be a boolean.`
1120
+ );
1121
+ isValid = false;
1122
+ }
1123
+
1124
+ return isValid;
1125
+ };
1126
+
1127
+ const validateVars =
1128
+ (envName: string): ValidatorFn =>
1129
+ (diagnostics, field, value, config) => {
1130
+ let isValid = true;
1131
+ const fieldPath =
1132
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1133
+ const configVars = Object.keys(config?.vars ?? {});
1134
+ // If there are no top level vars then there is nothing to do here.
1135
+ if (configVars.length > 0) {
1136
+ if (typeof value !== "object" || value === null) {
1137
+ diagnostics.errors.push(
1138
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1139
+ value
1140
+ )}.\n`
1141
+ );
1142
+ isValid = false;
1143
+ } else {
1144
+ for (const varName of configVars) {
1145
+ if (!(varName in value)) {
1146
+ diagnostics.warnings.push(
1147
+ `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1148
+ `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
1149
+ `Please add "vars.${varName}" to "env.${envName}".`
1150
+ );
1151
+ }
1152
+ }
1153
+ }
1154
+ }
1155
+ return isValid;
1156
+ };
1157
+
1158
+ const validateBindingsProperty =
1159
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1160
+ (diagnostics, field, value, config) => {
1161
+ let isValid = true;
1162
+ const fieldPath =
1163
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1164
+
1165
+ if (value !== undefined) {
1166
+ // Check the validity of the `value` as a bindings container.
1167
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1168
+ diagnostics.errors.push(
1169
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1170
+ value
1171
+ )}.`
1172
+ );
1173
+ isValid = false;
1174
+ } else if (!hasProperty(value, "bindings")) {
1175
+ diagnostics.errors.push(
1176
+ `The field "${fieldPath}" is missing the required "bindings" property.`
1177
+ );
1178
+ isValid = false;
1179
+ } else if (!Array.isArray(value.bindings)) {
1180
+ diagnostics.errors.push(
1181
+ `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
1182
+ value.bindings
1183
+ )}.`
1184
+ );
1185
+ isValid = false;
1186
+ } else {
1187
+ for (let i = 0; i < value.bindings.length; i++) {
1188
+ const binding = value.bindings[i];
1189
+ const bindingDiagnostics = new Diagnostics(
1190
+ `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
1191
+ );
1192
+ isValid =
1193
+ validateBinding(
1194
+ bindingDiagnostics,
1195
+ `${fieldPath}.bindings[${i}]`,
1196
+ binding,
1197
+ config
1198
+ ) && isValid;
1199
+ diagnostics.addChild(bindingDiagnostics);
1200
+ }
1201
+ }
1202
+
1203
+ const configBindingNames = getBindingNames(
1204
+ config?.[field as keyof Environment]
1205
+ );
1206
+ if (isValid && configBindingNames.length > 0) {
1207
+ // If there are top level bindings then check that they all appear in the environment.
1208
+ const envBindingNames = new Set(getBindingNames(value));
1209
+ const missingBindings = configBindingNames.filter(
1210
+ (name) => !envBindingNames.has(name)
1211
+ );
1212
+ if (missingBindings.length > 0) {
1213
+ diagnostics.warnings.push(
1214
+ `The following bindings are at the top level, but not on "env.${envName}".\n` +
1215
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1216
+ `Please add a binding for each to "${fieldPath}.bindings":\n` +
1217
+ missingBindings.map((name) => `- ${name}`).join("\n")
1218
+ );
1219
+ }
1220
+ }
1221
+ }
1222
+ return isValid;
1223
+ };
1224
+
1225
+ /**
1226
+ * Check that the given field is a valid "durable_object" binding object.
1227
+ */
1228
+ const validateDurableObjectBinding: ValidatorFn = (
1229
+ diagnostics,
1230
+ field,
1231
+ value
1232
+ ) => {
1233
+ if (typeof value !== "object" || value === null) {
1234
+ diagnostics.errors.push(
1235
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1236
+ );
1237
+ return false;
1238
+ }
1239
+
1240
+ // Durable Object bindings must have a name and class_name, and optionally a script_name and an environment.
1241
+ let isValid = true;
1242
+ if (!isRequiredProperty(value, "name", "string")) {
1243
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1244
+ isValid = false;
1245
+ }
1246
+ if (!isRequiredProperty(value, "class_name", "string")) {
1247
+ diagnostics.errors.push(`binding should have a string "class_name" field.`);
1248
+ isValid = false;
1249
+ }
1250
+ if (!isOptionalProperty(value, "script_name", "string")) {
1251
+ diagnostics.errors.push(
1252
+ `the field "script_name", when present, should be a string.`
1253
+ );
1254
+ isValid = false;
1255
+ }
1256
+ // environment requires a script_name
1257
+ if (!isOptionalProperty(value, "environment", "string")) {
1258
+ diagnostics.errors.push(
1259
+ `the field "environment", when present, should be a string.`
1260
+ );
1261
+ isValid = false;
1262
+ }
1263
+
1264
+ if ("environment" in value && !("script_name" in value)) {
1265
+ diagnostics.errors.push(
1266
+ `binding should have a "script_name" field if "environment" is present.`
1267
+ );
1268
+ isValid = false;
1269
+ }
1270
+
1271
+ return isValid;
1272
+ };
1273
+
1274
+ /**
1275
+ * Check that the given field is a valid "unsafe" binding object.
1276
+ *
1277
+ * TODO: further validation of known unsafe bindings.
1278
+ */
1279
+ const validateUnsafeBinding: ValidatorFn = (diagnostics, field, value) => {
1280
+ if (typeof value !== "object" || value === null) {
1281
+ diagnostics.errors.push(
1282
+ `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
1283
+ );
1284
+ return false;
1285
+ }
1286
+
1287
+ let isValid = true;
1288
+ // Unsafe bindings must have a name and type.
1289
+ if (!isRequiredProperty(value, "name", "string")) {
1290
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1291
+ isValid = false;
1292
+ }
1293
+ if (isRequiredProperty(value, "type", "string")) {
1294
+ const safeBindings = [
1295
+ "plain_text",
1296
+ "json",
1297
+ "wasm_module",
1298
+ "data_blob",
1299
+ "text_blob",
1300
+ "kv_namespace",
1301
+ "durable_object_namespace",
1302
+ "r2_bucket",
1303
+ "service",
1304
+ ];
1305
+
1306
+ if (safeBindings.includes(value.type)) {
1307
+ diagnostics.warnings.push(
1308
+ `The binding type "${value.type}" is directly supported by wrangler.\n` +
1309
+ `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
1310
+ "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
1311
+ );
1312
+ }
1313
+ } else {
1314
+ diagnostics.errors.push(`binding should have a string "type" field.`);
1315
+ isValid = false;
1316
+ }
1317
+ return isValid;
1318
+ };
1319
+
1320
+ /**
1321
+ * Check that the given environment field is a valid array of bindings.
1322
+ */
1323
+ const validateBindingArray =
1324
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1325
+ (diagnostics, field, envValue, config) => {
1326
+ if (envValue === undefined) {
1327
+ return true;
1328
+ }
1329
+
1330
+ const fieldPath =
1331
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1332
+ if (!Array.isArray(envValue)) {
1333
+ diagnostics.errors.push(
1334
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1335
+ envValue
1336
+ )}.`
1337
+ );
1338
+ return false;
1339
+ }
1340
+
1341
+ let isValid = true;
1342
+ for (let i = 0; i < envValue.length; i++) {
1343
+ isValid =
1344
+ validateBinding(
1345
+ diagnostics,
1346
+ `${fieldPath}[${i}]`,
1347
+ envValue[i],
1348
+ config
1349
+ ) && isValid;
1350
+ }
1351
+ const configValue = config?.[field as keyof Environment] as {
1352
+ binding: unknown;
1353
+ }[];
1354
+ if (Array.isArray(configValue)) {
1355
+ const configBindingNames = configValue.map((value) => value.binding);
1356
+ // If there are no top level bindings then there is nothing to do here.
1357
+ if (configBindingNames.length > 0) {
1358
+ const envBindingNames = new Set(envValue.map((value) => value.binding));
1359
+ for (const configBindingName of configBindingNames) {
1360
+ if (!envBindingNames.has(configBindingName)) {
1361
+ diagnostics.warnings.push(
1362
+ `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1363
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1364
+ `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1365
+ );
1366
+ }
1367
+ }
1368
+ }
1369
+ }
1370
+ return isValid;
1371
+ };
1372
+
1373
+ const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
1374
+ if (typeof value !== "object" || value === null) {
1375
+ diagnostics.errors.push(
1376
+ `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1377
+ value
1378
+ )}`
1379
+ );
1380
+ return false;
1381
+ }
1382
+ let isValid = true;
1383
+ // KV bindings must have a binding and id.
1384
+ if (!isRequiredProperty(value, "binding", "string")) {
1385
+ diagnostics.errors.push(
1386
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1387
+ value
1388
+ )}.`
1389
+ );
1390
+ isValid = false;
1391
+ }
1392
+ if (!isRequiredProperty(value, "id", "string")) {
1393
+ diagnostics.errors.push(
1394
+ `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1395
+ value
1396
+ )}.`
1397
+ );
1398
+ isValid = false;
1399
+ }
1400
+ if (!isOptionalProperty(value, "preview_id", "string")) {
1401
+ diagnostics.errors.push(
1402
+ `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1403
+ value
1404
+ )}.`
1405
+ );
1406
+ isValid = false;
1407
+ }
1408
+ return isValid;
1409
+ };
1410
+
1411
+ const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
1412
+ if (typeof value !== "object" || value === null) {
1413
+ diagnostics.errors.push(
1414
+ `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
1415
+ value
1416
+ )}`
1417
+ );
1418
+ return false;
1419
+ }
1420
+ let isValid = true;
1421
+ // R2 bindings must have a binding and bucket_name.
1422
+ if (!isRequiredProperty(value, "binding", "string")) {
1423
+ diagnostics.errors.push(
1424
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1425
+ value
1426
+ )}.`
1427
+ );
1428
+ isValid = false;
1429
+ }
1430
+ if (!isRequiredProperty(value, "bucket_name", "string")) {
1431
+ diagnostics.errors.push(
1432
+ `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1433
+ value
1434
+ )}.`
1435
+ );
1436
+ isValid = false;
1437
+ }
1438
+ if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1439
+ diagnostics.errors.push(
1440
+ `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1441
+ value
1442
+ )}.`
1443
+ );
1444
+ isValid = false;
1445
+ }
1446
+ return isValid;
1447
+ };
1448
+
1449
+ /**
1450
+ * Check that bindings whose names might conflict, don't.
1451
+ *
1452
+ * We don't want to have, for example, a KV namespace named "DATA"
1453
+ * and a Durable Object also named "DATA". Then it would be ambiguous
1454
+ * what exactly would live at `env.DATA` (or in the case of service-workers,
1455
+ * the `DATA` global).
1456
+ */
1457
+ const validateBindingsHaveUniqueNames = (
1458
+ diagnostics: Diagnostics,
1459
+ {
1460
+ durable_objects,
1461
+ kv_namespaces,
1462
+ r2_buckets,
1463
+ text_blobs,
1464
+ unsafe,
1465
+ vars,
1466
+ wasm_modules,
1467
+ data_blobs,
1468
+ }: Partial<Config>
1469
+ ): boolean => {
1470
+ let hasDuplicates = false;
1471
+
1472
+ const bindingsGroupedByType = {
1473
+ "Durable Object": getBindingNames(durable_objects),
1474
+ "KV Namespace": getBindingNames(kv_namespaces),
1475
+ "R2 Bucket": getBindingNames(r2_buckets),
1476
+ "Text Blob": getBindingNames(text_blobs),
1477
+ Unsafe: getBindingNames(unsafe),
1478
+ "Environment Variable": getBindingNames(vars),
1479
+ "WASM Module": getBindingNames(wasm_modules),
1480
+ "Data Blob": getBindingNames(data_blobs),
1481
+ } as Record<string, string[]>;
1482
+
1483
+ const bindingsGroupedByName: Record<string, string[]> = {};
1484
+
1485
+ for (const bindingType in bindingsGroupedByType) {
1486
+ const bindingNames = bindingsGroupedByType[bindingType];
1487
+
1488
+ for (const bindingName of bindingNames) {
1489
+ if (!(bindingName in bindingsGroupedByName)) {
1490
+ bindingsGroupedByName[bindingName] = [];
1491
+ }
1492
+
1493
+ bindingsGroupedByName[bindingName].push(bindingType);
1494
+ }
1495
+ }
1496
+
1497
+ for (const bindingName in bindingsGroupedByName) {
1498
+ const bindingTypes = bindingsGroupedByName[bindingName];
1499
+ if (bindingTypes.length < 2) {
1500
+ // there's only one (or zero) binding(s) with this name, which is fine, actually
1501
+ continue;
1502
+ }
1503
+
1504
+ hasDuplicates = true;
1505
+
1506
+ // there's two types of duplicates we want to look for:
1507
+ // - bindings with the same name of the same type (e.g. two Durable Objects both named "OBJ")
1508
+ // - bindings with the same name of different types (a KV namespace and DO both named "DATA")
1509
+
1510
+ const sameType = bindingTypes
1511
+ // filter once to find duplicate binding types
1512
+ .filter((type, i) => bindingTypes.indexOf(type) !== i)
1513
+ // filter twice to only get _unique_ duplicate binding types
1514
+ .filter(
1515
+ (type, i, duplicateBindingTypes) =>
1516
+ duplicateBindingTypes.indexOf(type) === i
1517
+ );
1518
+
1519
+ const differentTypes = bindingTypes.filter(
1520
+ (type, i) => bindingTypes.indexOf(type) === i
1521
+ );
1522
+
1523
+ if (differentTypes.length > 1) {
1524
+ // we have multiple different types using the same name
1525
+ diagnostics.errors.push(
1526
+ `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
1527
+ );
1528
+ }
1529
+
1530
+ sameType.forEach((bindingType) => {
1531
+ diagnostics.errors.push(
1532
+ `${bindingName} assigned to multiple ${bindingType} bindings.`
1533
+ );
1534
+ });
1535
+ }
1536
+
1537
+ if (hasDuplicates) {
1538
+ const problem =
1539
+ "Bindings must have unique names, so that they can all be referenced in the worker.";
1540
+ const resolution = "Please change your bindings to have unique names.";
1541
+ diagnostics.errors.push(`${problem}\n${resolution}`);
1542
+ }
1543
+
1544
+ return !hasDuplicates;
1545
+ };
1546
+ const validateServiceBinding: ValidatorFn = (diagnostics, field, value) => {
1547
+ if (typeof value !== "object" || value === null) {
1548
+ diagnostics.errors.push(
1549
+ `"services" bindings should be objects, but got ${JSON.stringify(value)}`
1550
+ );
1551
+ return false;
1552
+ }
1553
+ let isValid = true;
1554
+ // Service bindings must have a binding, service, and environment.
1555
+ if (!isRequiredProperty(value, "binding", "string")) {
1556
+ diagnostics.errors.push(
1557
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1558
+ value
1559
+ )}.`
1560
+ );
1561
+ isValid = false;
1562
+ }
1563
+ if (!isRequiredProperty(value, "service", "string")) {
1564
+ diagnostics.errors.push(
1565
+ `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
1566
+ value
1567
+ )}.`
1568
+ );
1569
+ isValid = false;
1570
+ }
1571
+ if (!isOptionalProperty(value, "environment", "string")) {
1572
+ diagnostics.errors.push(
1573
+ `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
1574
+ value
1575
+ )}.`
1576
+ );
1577
+ isValid = false;
1578
+ }
1579
+ return isValid;
1580
+ };