wrangler 0.0.0-e928f94 → 0.0.0-e978986

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