wrangler 0.0.0-e5a3814 → 0.0.0-e5cdd7fa

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