wrangler 0.0.0-e6e1daba → 0.0.0-e70806f1

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 (310) hide show
  1. package/README.md +11 -13
  2. package/bin/wrangler.js +14 -103
  3. package/config-schema.json +2947 -0
  4. package/package.json +194 -194
  5. package/templates/__tests__/tsconfig.json +1 -1
  6. package/templates/checked-fetch.js +11 -4
  7. package/templates/facade.d.ts +7 -2
  8. package/templates/gitignore +0 -4
  9. package/templates/init-tests/test-vitest-new-worker.js +1 -1
  10. package/templates/init-tests/test-vitest-new-worker.ts +1 -1
  11. package/templates/middleware/common.ts +9 -4
  12. package/templates/middleware/loader-modules.ts +94 -44
  13. package/templates/middleware/loader-sw.ts +6 -10
  14. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  15. package/templates/middleware/middleware-miniflare3-json-error.ts +17 -5
  16. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  17. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  18. package/templates/modules-watch-stub.js +4 -0
  19. package/templates/new-worker-scheduled.ts +1 -1
  20. package/templates/new-worker.ts +1 -1
  21. package/templates/pages-dev-pipeline.ts +2 -1
  22. package/templates/pages-dev-util.ts +4 -1
  23. package/templates/pages-shim.ts +0 -3
  24. package/templates/pages-template-plugin.ts +14 -4
  25. package/templates/pages-template-worker.ts +12 -3
  26. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  27. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  28. package/templates/tsconfig.init.json +1 -2
  29. package/templates/tsconfig.json +1 -1
  30. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  31. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  32. package/wrangler-dist/ProxyWorker.js +240 -0
  33. package/wrangler-dist/ProxyWorker.js.map +6 -0
  34. package/wrangler-dist/cli.d.ts +23790 -1052
  35. package/wrangler-dist/cli.js +155835 -98941
  36. package/wrangler-dist/wasm-sync.wasm +0 -0
  37. package/Cloudflare_CA.pem +0 -18
  38. package/import_meta_url.js +0 -3
  39. package/miniflare-config-stubs/.env.empty +0 -0
  40. package/miniflare-config-stubs/package.empty.json +0 -1
  41. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  42. package/miniflare-dist/index.mjs +0 -6368
  43. package/src/__tests__/access.test.ts +0 -25
  44. package/src/__tests__/api-dev.test.ts +0 -238
  45. package/src/__tests__/api-devregistry.test.js +0 -64
  46. package/src/__tests__/api.test.ts +0 -80
  47. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  48. package/src/__tests__/config-cache.test.ts +0 -42
  49. package/src/__tests__/configuration.test.ts +0 -4233
  50. package/src/__tests__/d1/d1.test.ts +0 -82
  51. package/src/__tests__/d1/execute.test.ts +0 -64
  52. package/src/__tests__/d1/migrate.test.ts +0 -155
  53. package/src/__tests__/d1/splitter.test.ts +0 -255
  54. package/src/__tests__/delete.test.ts +0 -266
  55. package/src/__tests__/deployments.test.ts +0 -129
  56. package/src/__tests__/dev.test.tsx +0 -1587
  57. package/src/__tests__/generate.test.ts +0 -238
  58. package/src/__tests__/get-host-from-url.test.ts +0 -16
  59. package/src/__tests__/guess-worker-format.test.ts +0 -120
  60. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  61. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  62. package/src/__tests__/helpers/end-event-loop.ts +0 -6
  63. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  64. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  65. package/src/__tests__/helpers/mock-bin.ts +0 -36
  66. package/src/__tests__/helpers/mock-console.ts +0 -106
  67. package/src/__tests__/helpers/mock-dialogs.ts +0 -139
  68. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +0 -25
  69. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -11
  70. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  71. package/src/__tests__/helpers/mock-istty.ts +0 -74
  72. package/src/__tests__/helpers/mock-known-routes.ts +0 -12
  73. package/src/__tests__/helpers/mock-kv.ts +0 -46
  74. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -263
  75. package/src/__tests__/helpers/mock-process.ts +0 -34
  76. package/src/__tests__/helpers/mock-set-timeout.ts +0 -16
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  80. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  81. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -93
  82. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -81
  83. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  84. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -60
  85. package/src/__tests__/helpers/msw/handlers/script.ts +0 -56
  86. package/src/__tests__/helpers/msw/handlers/user.ts +0 -52
  87. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -20
  88. package/src/__tests__/helpers/msw/index.ts +0 -50
  89. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  90. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  91. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  92. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +0 -28
  93. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  94. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  95. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  96. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  97. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  98. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  99. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  100. package/src/__tests__/https-options.test.ts +0 -163
  101. package/src/__tests__/index.test.ts +0 -274
  102. package/src/__tests__/init.test.ts +0 -3164
  103. package/src/__tests__/jest.setup.ts +0 -175
  104. package/src/__tests__/kv.test.ts +0 -1799
  105. package/src/__tests__/logger.test.ts +0 -141
  106. package/src/__tests__/logout.test.ts +0 -47
  107. package/src/__tests__/metrics.test.ts +0 -493
  108. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  109. package/src/__tests__/middleware.test.ts +0 -815
  110. package/src/__tests__/mtls-certificates.test.ts +0 -585
  111. package/src/__tests__/package-manager.test.ts +0 -353
  112. package/src/__tests__/pages/deployment-list.test.ts +0 -78
  113. package/src/__tests__/pages/functions-build.test.ts +0 -402
  114. package/src/__tests__/pages/pages.test.ts +0 -81
  115. package/src/__tests__/pages/project-create.test.ts +0 -63
  116. package/src/__tests__/pages/project-list.test.ts +0 -108
  117. package/src/__tests__/pages/project-upload.test.ts +0 -481
  118. package/src/__tests__/pages/publish.test.ts +0 -2745
  119. package/src/__tests__/pages-deployment-tail.test.ts +0 -955
  120. package/src/__tests__/parse.test.ts +0 -436
  121. package/src/__tests__/paths.test.ts +0 -39
  122. package/src/__tests__/publish.test.ts +0 -8167
  123. package/src/__tests__/pubsub.test.ts +0 -493
  124. package/src/__tests__/queues.test.ts +0 -529
  125. package/src/__tests__/r2.test.ts +0 -374
  126. package/src/__tests__/route.test.ts +0 -45
  127. package/src/__tests__/secret.test.ts +0 -693
  128. package/src/__tests__/tail.test.ts +0 -958
  129. package/src/__tests__/test-old-node-version.js +0 -31
  130. package/src/__tests__/tsconfig-sanity.ts +0 -12
  131. package/src/__tests__/tsconfig.json +0 -8
  132. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  133. package/src/__tests__/type-generation.test.ts +0 -233
  134. package/src/__tests__/user.test.ts +0 -118
  135. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  136. package/src/__tests__/validate-dev-props.test.ts +0 -56
  137. package/src/__tests__/version.test.ts +0 -35
  138. package/src/__tests__/whoami.test.tsx +0 -172
  139. package/src/__tests__/worker-namespace.test.ts +0 -339
  140. package/src/abort.d.ts +0 -3
  141. package/src/api/dev.ts +0 -328
  142. package/src/api/index.ts +0 -11
  143. package/src/api/mtls-certificate.ts +0 -148
  144. package/src/api/pages/create-worker-bundle-contents.ts +0 -75
  145. package/src/api/pages/index.ts +0 -5
  146. package/src/api/pages/publish.tsx +0 -368
  147. package/src/bundle-reporter.ts +0 -68
  148. package/src/bundle.ts +0 -877
  149. package/src/cfetch/index.ts +0 -158
  150. package/src/cfetch/internal.ts +0 -258
  151. package/src/cli.ts +0 -28
  152. package/src/config/README.md +0 -107
  153. package/src/config/config.ts +0 -282
  154. package/src/config/diagnostics.ts +0 -80
  155. package/src/config/environment.ts +0 -586
  156. package/src/config/index.ts +0 -375
  157. package/src/config/validation-helpers.ts +0 -597
  158. package/src/config/validation.ts +0 -2198
  159. package/src/config-cache.ts +0 -85
  160. package/src/create-worker-preview.ts +0 -293
  161. package/src/create-worker-upload-form.ts +0 -334
  162. package/src/d1/backups.tsx +0 -215
  163. package/src/d1/constants.ts +0 -2
  164. package/src/d1/create.tsx +0 -64
  165. package/src/d1/delete.ts +0 -53
  166. package/src/d1/execute.tsx +0 -354
  167. package/src/d1/formatTimeAgo.ts +0 -14
  168. package/src/d1/index.ts +0 -100
  169. package/src/d1/list.tsx +0 -60
  170. package/src/d1/migrations/apply.tsx +0 -206
  171. package/src/d1/migrations/create.tsx +0 -76
  172. package/src/d1/migrations/helpers.ts +0 -172
  173. package/src/d1/migrations/index.ts +0 -3
  174. package/src/d1/migrations/list.tsx +0 -92
  175. package/src/d1/migrations/options.ts +0 -23
  176. package/src/d1/options.ts +0 -22
  177. package/src/d1/splitter.ts +0 -161
  178. package/src/d1/types.ts +0 -25
  179. package/src/d1/utils.ts +0 -49
  180. package/src/delete.ts +0 -100
  181. package/src/deployments.ts +0 -116
  182. package/src/deprecated/index.ts +0 -144
  183. package/src/dev/dev-vars.ts +0 -39
  184. package/src/dev/dev.tsx +0 -600
  185. package/src/dev/get-local-persistence-path.ts +0 -31
  186. package/src/dev/local.tsx +0 -922
  187. package/src/dev/remote.tsx +0 -632
  188. package/src/dev/start-server.ts +0 -538
  189. package/src/dev/use-esbuild.ts +0 -205
  190. package/src/dev/validate-dev-props.ts +0 -31
  191. package/src/dev-registry.ts +0 -201
  192. package/src/dev.tsx +0 -914
  193. package/src/dialogs.ts +0 -136
  194. package/src/dispatch-namespace.ts +0 -211
  195. package/src/docs/index.ts +0 -97
  196. package/src/durable.ts +0 -102
  197. package/src/entry.ts +0 -327
  198. package/src/environment-variables/factory.ts +0 -88
  199. package/src/environment-variables/misc-variables.ts +0 -30
  200. package/src/errors.ts +0 -11
  201. package/src/generate/index.ts +0 -298
  202. package/src/git-client.ts +0 -135
  203. package/src/global-wrangler-config-path.ts +0 -26
  204. package/src/https-options.ts +0 -127
  205. package/src/index.ts +0 -705
  206. package/src/init.ts +0 -1022
  207. package/src/inspect.ts +0 -782
  208. package/src/intl-polyfill.d.ts +0 -139
  209. package/src/is-ci.ts +0 -14
  210. package/src/is-interactive.ts +0 -16
  211. package/src/jest.d.ts +0 -4
  212. package/src/kv/helpers.ts +0 -430
  213. package/src/kv/index.ts +0 -594
  214. package/src/logger.ts +0 -104
  215. package/src/metrics/index.ts +0 -5
  216. package/src/metrics/metrics-config.ts +0 -239
  217. package/src/metrics/metrics-dispatcher.ts +0 -96
  218. package/src/metrics/metrics-usage-headers.ts +0 -24
  219. package/src/metrics/send-event.ts +0 -98
  220. package/src/miniflare-cli/README.md +0 -30
  221. package/src/miniflare-cli/assets.ts +0 -251
  222. package/src/miniflare-cli/index.ts +0 -210
  223. package/src/miniflare-cli/request-context.ts +0 -40
  224. package/src/miniflare-cli/tsconfig.json +0 -9
  225. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  226. package/src/miniflare-cli/types.ts +0 -11
  227. package/src/module-collection.ts +0 -267
  228. package/src/mtls-certificate/cli.ts +0 -155
  229. package/src/open-in-browser.ts +0 -17
  230. package/src/package-manager.ts +0 -219
  231. package/src/pages/build.ts +0 -232
  232. package/src/pages/buildFunctions.ts +0 -130
  233. package/src/pages/constants.ts +0 -18
  234. package/src/pages/deployment-tails.ts +0 -281
  235. package/src/pages/deployments.tsx +0 -86
  236. package/src/pages/dev.ts +0 -716
  237. package/src/pages/errors.ts +0 -66
  238. package/src/pages/functions/buildPlugin.ts +0 -90
  239. package/src/pages/functions/buildWorker.ts +0 -288
  240. package/src/pages/functions/filepath-routing.test.ts +0 -234
  241. package/src/pages/functions/filepath-routing.ts +0 -189
  242. package/src/pages/functions/identifiers.ts +0 -78
  243. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  244. package/src/pages/functions/routes-consolidation.ts +0 -73
  245. package/src/pages/functions/routes-transformation.test.ts +0 -282
  246. package/src/pages/functions/routes-transformation.ts +0 -115
  247. package/src/pages/functions/routes-validation.test.ts +0 -403
  248. package/src/pages/functions/routes-validation.ts +0 -202
  249. package/src/pages/functions/routes.ts +0 -151
  250. package/src/pages/functions/tsconfig.json +0 -8
  251. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  252. package/src/pages/functions.ts +0 -86
  253. package/src/pages/hash.ts +0 -13
  254. package/src/pages/index.ts +0 -102
  255. package/src/pages/projects.tsx +0 -162
  256. package/src/pages/prompt-select-project.tsx +0 -31
  257. package/src/pages/publish.tsx +0 -276
  258. package/src/pages/types.ts +0 -46
  259. package/src/pages/upload.tsx +0 -449
  260. package/src/pages/utils.ts +0 -23
  261. package/src/parse.ts +0 -308
  262. package/src/paths.ts +0 -71
  263. package/src/proxy.ts +0 -694
  264. package/src/publish/index.ts +0 -274
  265. package/src/publish/publish.ts +0 -1065
  266. package/src/pubsub/index.ts +0 -286
  267. package/src/pubsub/pubsub-commands.ts +0 -623
  268. package/src/queues/cli/commands/consumer/add.ts +0 -65
  269. package/src/queues/cli/commands/consumer/index.ts +0 -19
  270. package/src/queues/cli/commands/consumer/remove.ts +0 -31
  271. package/src/queues/cli/commands/create.ts +0 -25
  272. package/src/queues/cli/commands/delete.ts +0 -26
  273. package/src/queues/cli/commands/index.ts +0 -35
  274. package/src/queues/cli/commands/list.ts +0 -25
  275. package/src/queues/client.ts +0 -135
  276. package/src/queues/utils.ts +0 -18
  277. package/src/r2/constants.ts +0 -4
  278. package/src/r2/helpers.ts +0 -132
  279. package/src/r2/index.ts +0 -289
  280. package/src/routes.ts +0 -140
  281. package/src/secret/index.ts +0 -375
  282. package/src/selfsigned.d.ts +0 -29
  283. package/src/sites.ts +0 -372
  284. package/src/tail/createTail.ts +0 -406
  285. package/src/tail/filters.ts +0 -277
  286. package/src/tail/index.ts +0 -211
  287. package/src/tail/printing.ts +0 -122
  288. package/src/tsconfig-sanity.ts +0 -16
  289. package/src/type-generation.ts +0 -181
  290. package/src/update-check.ts +0 -19
  291. package/src/user/access.ts +0 -68
  292. package/src/user/auth-variables.ts +0 -113
  293. package/src/user/choose-account.tsx +0 -39
  294. package/src/user/generate-auth-url.ts +0 -33
  295. package/src/user/generate-random-state.ts +0 -16
  296. package/src/user/index.ts +0 -2
  297. package/src/user/user.ts +0 -1233
  298. package/src/utils/collectKeyValues.ts +0 -14
  299. package/src/whoami.ts +0 -135
  300. package/src/worker.ts +0 -257
  301. package/src/yargs-types.ts +0 -37
  302. package/src/zones.ts +0 -191
  303. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  304. package/templates/d1-beta-facade.js +0 -241
  305. package/templates/first-party-worker-module-facade.ts +0 -19
  306. package/templates/format-dev-errors.ts +0 -34
  307. package/templates/serve-static-assets.ts +0 -66
  308. package/templates/service-bindings-module-facade.js +0 -55
  309. package/templates/service-bindings-sw-facade.js +0 -42
  310. package/templates/tsconfig.tsbuildinfo +0 -1
package/src/init.ts DELETED
@@ -1,1022 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import TOML from "@iarna/toml";
5
- import { findUp } from "find-up";
6
- import { version as wranglerVersion } from "../package.json";
7
-
8
- import { fetchResult } from "./cfetch";
9
- import { fetchDashboardScript } from "./cfetch/internal";
10
- import { readConfig } from "./config";
11
- import { confirm, select } from "./dialogs";
12
- import { initializeGit, getGitVersioon, isInsideGitRepo } from "./git-client";
13
- import { logger } from "./logger";
14
- import { getPackageManager } from "./package-manager";
15
- import { parsePackageJSON, parseTOML, readFileSync } from "./parse";
16
- import { getBasePath } from "./paths";
17
- import { requireAuth } from "./user";
18
- import { CommandLineArgsError, printWranglerBanner } from "./index";
19
-
20
- import type { RawConfig } from "./config";
21
- import type { Route, SimpleRoute } from "./config/environment";
22
- import type { WorkerMetadata } from "./create-worker-upload-form";
23
- import type { PackageManager } from "./package-manager";
24
- import type { PackageJSON } from "./parse";
25
- import type {
26
- CommonYargsArgv,
27
- StrictYargsOptionsToInterface,
28
- } from "./yargs-types";
29
-
30
- export function initOptions(yargs: CommonYargsArgv) {
31
- return yargs
32
- .positional("name", {
33
- describe: "The name of your worker",
34
- type: "string",
35
- })
36
- .option("type", {
37
- describe: "The type of worker to create",
38
- type: "string",
39
- choices: ["rust", "javascript", "webpack"],
40
- hidden: true,
41
- deprecated: true,
42
- })
43
- .option("site", {
44
- hidden: true,
45
- type: "boolean",
46
- deprecated: true,
47
- })
48
- .option("yes", {
49
- describe: 'Answer "yes" to any prompts for new projects',
50
- type: "boolean",
51
- alias: "y",
52
- })
53
- .option("from-dash", {
54
- describe:
55
- "The name of the Worker you wish to download from the Cloudflare dashboard for local development.",
56
- type: "string",
57
- requiresArg: true,
58
- });
59
- }
60
-
61
- type InitArgs = StrictYargsOptionsToInterface<typeof initOptions>;
62
-
63
- export type ServiceMetadataRes = {
64
- id: string;
65
- default_environment: {
66
- environment: string;
67
- created_on: string;
68
- modified_on: string;
69
- script: {
70
- id: string;
71
- tag: string;
72
- etag: string;
73
- handlers: string[];
74
- modified_on: string;
75
- created_on: string;
76
- migration_tag: string;
77
- usage_model: "bundled" | "unbound";
78
- compatibility_date: string;
79
- last_deployed_from?: "wrangler" | "dash" | "api";
80
- };
81
- };
82
- created_on: string;
83
- modified_on: string;
84
- usage_model: "bundled" | "unbound";
85
- environments: [
86
- {
87
- environment: string;
88
- created_on: string;
89
- modified_on: string;
90
- }
91
- ];
92
- };
93
-
94
- export type RawSimpleRoute = { pattern: string };
95
- export type RawRoutes = (RawSimpleRoute | Exclude<Route, SimpleRoute>) & {
96
- id: string;
97
- };
98
- export type RoutesRes = RawRoutes[];
99
-
100
- export type CronTriggersRes = {
101
- schedules: [
102
- {
103
- cron: string;
104
- created_on: Date;
105
- modified_on: Date;
106
- }
107
- ];
108
- };
109
-
110
- export async function initHandler(args: InitArgs) {
111
- await printWranglerBanner();
112
- if (args.type) {
113
- let message = "The --type option is no longer supported.";
114
- if (args.type === "webpack") {
115
- message +=
116
- "\nIf you wish to use webpack then you will need to create a custom build.";
117
- // TODO: Add a link to docs
118
- }
119
- throw new CommandLineArgsError(message);
120
- }
121
-
122
- const devDepsToInstall: string[] = [];
123
- const instructions: string[] = [];
124
- let shouldRunPackageManagerInstall = false;
125
- const fromDashScriptName = args.fromDash;
126
- const creationDirectory = path.resolve(
127
- process.cwd(),
128
- (args.name ? args.name : fromDashScriptName) ?? ""
129
- );
130
-
131
- if (args.site) {
132
- const gitDirectory =
133
- creationDirectory !== process.cwd()
134
- ? path.basename(creationDirectory)
135
- : "my-site";
136
- const message =
137
- "The --site option is no longer supported.\n" +
138
- "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
139
- "```\n" +
140
- `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
141
- `cd ${gitDirectory}\n` +
142
- "```\n\n" +
143
- "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
144
- "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
145
- throw new CommandLineArgsError(message);
146
- }
147
-
148
- // TODO: make sure args.name is a valid identifier for a worker name
149
- const workerName = path
150
- .basename(creationDirectory)
151
- .toLowerCase()
152
- .replaceAll(/[^a-z0-9\-_]/gm, "-");
153
-
154
- const packageManager = await getPackageManager(creationDirectory);
155
-
156
- // TODO: ask which directory to make the worker in (defaults to args.name)
157
- // TODO: if args.name isn't provided, ask what to name the worker
158
- // Note: `--from-dash` will be a fallback creationDir/Worker name if none is provided.
159
-
160
- const wranglerTomlDestination = path.join(
161
- creationDirectory,
162
- "./wrangler.toml"
163
- );
164
- let justCreatedWranglerToml = false;
165
-
166
- let accountId = "";
167
- let serviceMetadata: undefined | ServiceMetadataRes;
168
-
169
- // If --from-dash, check that script actually exists
170
- if (fromDashScriptName) {
171
- const config = readConfig(args.config, args);
172
- accountId = await requireAuth(config);
173
- try {
174
- serviceMetadata = await fetchResult<ServiceMetadataRes>(
175
- `/accounts/${accountId}/workers/services/${fromDashScriptName}`
176
- );
177
- } catch (err) {
178
- if ((err as { code?: number }).code === 10090) {
179
- throw new Error(
180
- "wrangler couldn't find a Worker script with that name in your account.\nRun `wrangler whoami` to confirm you're logged into the correct account."
181
- );
182
- }
183
- throw err;
184
- }
185
- }
186
-
187
- if (fs.existsSync(wranglerTomlDestination)) {
188
- let shouldContinue = false;
189
- logger.warn(
190
- `${path.relative(process.cwd(), wranglerTomlDestination)} already exists!`
191
- );
192
- if (!fromDashScriptName) {
193
- shouldContinue = await confirm(
194
- "Do you want to continue initializing this project?"
195
- );
196
- }
197
- if (!shouldContinue) {
198
- return;
199
- }
200
- } else {
201
- await mkdir(creationDirectory, { recursive: true });
202
- const compatibilityDate = new Date().toISOString().substring(0, 10);
203
-
204
- try {
205
- await writeFile(
206
- wranglerTomlDestination,
207
- TOML.stringify({
208
- name: workerName,
209
- compatibility_date: compatibilityDate,
210
- }) + "\n"
211
- );
212
-
213
- logger.log(
214
- `✨ Created ${path.relative(process.cwd(), wranglerTomlDestination)}`
215
- );
216
- justCreatedWranglerToml = true;
217
- } catch (err) {
218
- throw new Error(
219
- `Failed to create ${path.relative(
220
- process.cwd(),
221
- wranglerTomlDestination
222
- )}.\n${(err as Error).message ?? err}`
223
- );
224
- }
225
- }
226
-
227
- const yesFlag = args.yes ?? false;
228
-
229
- if (!(await isInsideGitRepo(creationDirectory)) && (await getGitVersioon())) {
230
- const shouldInitGit =
231
- yesFlag ||
232
- (await confirm("Would you like to use git to manage this Worker?"));
233
- if (shouldInitGit) {
234
- await initializeGit(creationDirectory);
235
- await writeFile(
236
- path.join(creationDirectory, ".gitignore"),
237
- readFileSync(path.join(getBasePath(), "templates/gitignore"))
238
- );
239
- logger.log(
240
- args.name && args.name !== "."
241
- ? `✨ Initialized git repository at ${path.relative(
242
- process.cwd(),
243
- creationDirectory
244
- )}`
245
- : `✨ Initialized git repository`
246
- );
247
- }
248
- }
249
-
250
- const isolatedInit = !!args.name;
251
- let pathToPackageJson = await findPath(
252
- isolatedInit,
253
- creationDirectory,
254
- "package.json"
255
- );
256
- let shouldCreatePackageJson = false;
257
- let shouldCreateTests = false;
258
- let newWorkerTestType: "jest" | "vitest" = "jest";
259
-
260
- if (!pathToPackageJson) {
261
- // If no package.json exists, ask to create one
262
- shouldCreatePackageJson =
263
- yesFlag ||
264
- (await confirm("No package.json found. Would you like to create one?"));
265
-
266
- if (shouldCreatePackageJson) {
267
- await writeFile(
268
- path.join(creationDirectory, "./package.json"),
269
- JSON.stringify(
270
- {
271
- name: workerName,
272
- version: "0.0.0",
273
- devDependencies: {
274
- wrangler: wranglerVersion,
275
- },
276
- private: true,
277
- },
278
- null,
279
- " "
280
- ) + "\n"
281
- );
282
-
283
- shouldRunPackageManagerInstall = true;
284
- pathToPackageJson = path.join(creationDirectory, "package.json");
285
- logger.log(
286
- `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
287
- );
288
- } else {
289
- return;
290
- }
291
- } else {
292
- // If package.json exists and wrangler isn't installed,
293
- // then ask to add wrangler to devDependencies
294
- const packageJson = parsePackageJSON(
295
- readFileSync(pathToPackageJson),
296
- pathToPackageJson
297
- );
298
- if (
299
- !(
300
- packageJson.devDependencies?.wrangler ||
301
- packageJson.dependencies?.wrangler
302
- )
303
- ) {
304
- const shouldInstall =
305
- yesFlag ||
306
- (await confirm(
307
- `Would you like to install wrangler into ${path.relative(
308
- process.cwd(),
309
- pathToPackageJson
310
- )}?`
311
- ));
312
- if (shouldInstall) {
313
- devDepsToInstall.push(`wrangler@${wranglerVersion}`);
314
- }
315
- }
316
- }
317
-
318
- let isTypescriptProject = false;
319
- let pathToTSConfig = await findPath(
320
- isolatedInit,
321
- creationDirectory,
322
- "tsconfig.json"
323
- );
324
- if (!pathToTSConfig) {
325
- // If there's no tsconfig, offer to create one
326
- // and install @cloudflare/workers-types
327
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
328
- isTypescriptProject = true;
329
- await writeFile(
330
- path.join(creationDirectory, "./tsconfig.json"),
331
- readFileSync(path.join(getBasePath(), "templates/tsconfig.init.json"))
332
- );
333
- devDepsToInstall.push("@cloudflare/workers-types");
334
- devDepsToInstall.push("typescript");
335
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
336
- logger.log(`✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`);
337
- }
338
- } else {
339
- isTypescriptProject = true;
340
- // If there's a tsconfig, check if @cloudflare/workers-types
341
- // is already installed, and offer to install it if not
342
- const packageJson = parsePackageJSON(
343
- readFileSync(pathToPackageJson),
344
- pathToPackageJson
345
- );
346
- if (
347
- !(
348
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
349
- packageJson.dependencies?.["@cloudflare/workers-types"]
350
- )
351
- ) {
352
- const shouldInstall = await confirm(
353
- "Would you like to install the type definitions for Workers into your package.json?"
354
- );
355
- if (shouldInstall) {
356
- devDepsToInstall.push("@cloudflare/workers-types");
357
- // We don't update the tsconfig.json because
358
- // it could be complicated in existing projects
359
- // and we don't want to break them. Instead, we simply
360
- // tell the user that they need to update their tsconfig.json
361
- instructions.push(
362
- `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
363
- process.cwd(),
364
- pathToTSConfig
365
- )}`
366
- );
367
- }
368
- }
369
- }
370
-
371
- const packageJsonContent = parsePackageJSON(
372
- readFileSync(pathToPackageJson),
373
- pathToPackageJson
374
- );
375
- const shouldWritePackageJsonScripts =
376
- !packageJsonContent.scripts?.start &&
377
- !packageJsonContent.scripts?.publish &&
378
- shouldCreatePackageJson;
379
-
380
- async function writePackageJsonScriptsAndUpdateWranglerToml({
381
- isWritingScripts,
382
- isAddingTests,
383
- testRunner,
384
- isCreatingWranglerToml,
385
- packagePath,
386
- scriptPath,
387
- extraToml,
388
- }: {
389
- isWritingScripts: boolean;
390
- isAddingTests?: boolean;
391
- testRunner?: "jest" | "vitest";
392
- isCreatingWranglerToml: boolean;
393
- packagePath: string;
394
- scriptPath: string;
395
- extraToml: TOML.JsonMap;
396
- }) {
397
- if (isAddingTests && !testRunner) {
398
- logger.error("testRunner is required if isAddingTests");
399
- }
400
- if (isCreatingWranglerToml) {
401
- // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
402
- const parsedWranglerToml = parseTOML(
403
- readFileSync(wranglerTomlDestination)
404
- );
405
- const newToml = {
406
- name: parsedWranglerToml.name,
407
- main: scriptPath,
408
- compatibility_date: parsedWranglerToml.compatibility_date,
409
- ...extraToml,
410
- };
411
- fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
412
- }
413
- const isNamedWorker =
414
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
415
- const isAddingTestScripts =
416
- isAddingTests && !packageJsonContent.scripts?.test;
417
- if (isWritingScripts) {
418
- await writeFile(
419
- packagePath,
420
- JSON.stringify(
421
- {
422
- ...packageJsonContent,
423
- scripts: {
424
- ...packageJsonContent.scripts,
425
- start: isCreatingWranglerToml
426
- ? `wrangler dev`
427
- : `wrangler dev ${scriptPath}`,
428
- deploy: isCreatingWranglerToml
429
- ? `wrangler publish`
430
- : `wrangler publish ${scriptPath}`,
431
- ...(isAddingTestScripts && { test: testRunner }),
432
- },
433
- } as PackageJSON,
434
- null,
435
- 2
436
- ) + "\n"
437
- );
438
- instructions.push(
439
- `\nTo start developing your Worker, run \`${
440
- isNamedWorker ? `cd ${args.name || fromDashScriptName} && ` : ""
441
- }npm start\``
442
- );
443
- if (isAddingTestScripts) {
444
- instructions.push(`To start testing your Worker, run \`npm test\``);
445
- }
446
- instructions.push(
447
- `To publish your Worker to the Internet, run \`npm run deploy\``
448
- );
449
- } else {
450
- instructions.push(
451
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
452
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
453
- }`
454
- );
455
- instructions.push(
456
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
457
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
458
- }`
459
- );
460
- }
461
- }
462
-
463
- if (isTypescriptProject) {
464
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
465
- const newWorkerFilename = path.relative(
466
- process.cwd(),
467
- path.join(creationDirectory, "./src/index.ts")
468
- );
469
- if (fromDashScriptName) {
470
- logger.warn(
471
- "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
472
- );
473
-
474
- await mkdir(path.join(creationDirectory, "./src"), {
475
- recursive: true,
476
- });
477
-
478
- const defaultEnvironment =
479
- serviceMetadata?.default_environment.environment;
480
- // I want the default environment, assuming it's the most up to date code.
481
- const dashScript = await fetchDashboardScript(
482
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
483
- );
484
-
485
- await writeFile(
486
- path.join(creationDirectory, "./src/index.ts"),
487
- dashScript
488
- );
489
-
490
- await writePackageJsonScriptsAndUpdateWranglerToml({
491
- isWritingScripts: shouldWritePackageJsonScripts,
492
- isCreatingWranglerToml: justCreatedWranglerToml,
493
- packagePath: pathToPackageJson,
494
- scriptPath: "src/index.ts",
495
- extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
496
- defaultEnvironment,
497
- environments: serviceMetadata?.environments,
498
- })) as TOML.JsonMap,
499
- });
500
- } else {
501
- const newWorkerType = yesFlag
502
- ? "fetch"
503
- : await getNewWorkerType(newWorkerFilename);
504
-
505
- if (newWorkerType !== "none") {
506
- const template = getNewWorkerTemplate("ts", newWorkerType);
507
-
508
- await mkdir(path.join(creationDirectory, "./src"), {
509
- recursive: true,
510
- });
511
-
512
- await writeFile(
513
- path.join(creationDirectory, "./src/index.ts"),
514
- readFileSync(path.join(getBasePath(), `templates/${template}`))
515
- );
516
-
517
- logger.log(
518
- `✨ Created ${path.relative(
519
- process.cwd(),
520
- path.join(creationDirectory, "./src/index.ts")
521
- )}`
522
- );
523
-
524
- shouldCreateTests =
525
- yesFlag ||
526
- (await confirm(
527
- "Would you like us to write your first test with Vitest?"
528
- ));
529
-
530
- if (shouldCreateTests) {
531
- if (yesFlag) {
532
- logger.info("Your project will use Vitest to run your tests.");
533
- }
534
-
535
- newWorkerTestType = "vitest";
536
- devDepsToInstall.push(newWorkerTestType);
537
-
538
- await writeFile(
539
- path.join(creationDirectory, "./src/index.test.ts"),
540
- readFileSync(
541
- path.join(
542
- getBasePath(),
543
- `templates/init-tests/test-${newWorkerTestType}-new-worker.ts`
544
- )
545
- )
546
- );
547
- logger.log(
548
- `✨ Created ${path.relative(
549
- process.cwd(),
550
- path.join(creationDirectory, "./src/index.test.ts")
551
- )}`
552
- );
553
- }
554
-
555
- await writePackageJsonScriptsAndUpdateWranglerToml({
556
- isWritingScripts: shouldWritePackageJsonScripts,
557
- isAddingTests: shouldCreateTests,
558
- isCreatingWranglerToml: justCreatedWranglerToml,
559
- packagePath: pathToPackageJson,
560
- testRunner: newWorkerTestType,
561
- scriptPath: "src/index.ts",
562
- extraToml: getNewWorkerToml(newWorkerType),
563
- });
564
- }
565
- }
566
- }
567
- } else {
568
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
569
- const newWorkerFilename = path.relative(
570
- process.cwd(),
571
- path.join(creationDirectory, "./src/index.js")
572
- );
573
-
574
- if (fromDashScriptName) {
575
- logger.warn(
576
- "After running `wrangler init --from-dash`, modifying your worker via the Cloudflare dashboard is discouraged.\nEdits made via the Dashboard will not be synchronized locally and will be overridden by your local code and config when you publish."
577
- );
578
-
579
- await mkdir(path.join(creationDirectory, "./src"), {
580
- recursive: true,
581
- });
582
-
583
- const defaultEnvironment =
584
- serviceMetadata?.default_environment.environment;
585
-
586
- // I want the default environment, assuming it's the most up to date code.
587
- const dashScript = await fetchDashboardScript(
588
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/content`
589
- );
590
-
591
- await writeFile(
592
- path.join(creationDirectory, "./src/index.js"),
593
- dashScript
594
- );
595
-
596
- await writePackageJsonScriptsAndUpdateWranglerToml({
597
- isWritingScripts: shouldWritePackageJsonScripts,
598
- isCreatingWranglerToml: justCreatedWranglerToml,
599
- packagePath: pathToPackageJson,
600
- scriptPath: "src/index.js",
601
- //? Should we have Environment argument for `wrangler init --from-dash` - Jacob
602
- extraToml: (await getWorkerConfig(accountId, fromDashScriptName, {
603
- defaultEnvironment,
604
- environments: serviceMetadata?.environments,
605
- })) as TOML.JsonMap,
606
- });
607
- } else {
608
- const newWorkerType = yesFlag
609
- ? "fetch"
610
- : await getNewWorkerType(newWorkerFilename);
611
-
612
- if (newWorkerType !== "none") {
613
- const template = getNewWorkerTemplate("js", newWorkerType);
614
-
615
- await mkdir(path.join(creationDirectory, "./src"), {
616
- recursive: true,
617
- });
618
- await writeFile(
619
- path.join(creationDirectory, "./src/index.js"),
620
- readFileSync(path.join(getBasePath(), `templates/${template}`))
621
- );
622
-
623
- logger.log(
624
- `✨ Created ${path.relative(
625
- process.cwd(),
626
- path.join(creationDirectory, "./src/index.js")
627
- )}`
628
- );
629
-
630
- shouldCreateTests =
631
- yesFlag ||
632
- (await confirm("Would you like us to write your first test?"));
633
-
634
- if (shouldCreateTests) {
635
- newWorkerTestType = await getNewWorkerTestType(yesFlag);
636
- devDepsToInstall.push(newWorkerTestType);
637
- await writeFile(
638
- path.join(creationDirectory, "./src/index.test.js"),
639
- readFileSync(
640
- path.join(
641
- getBasePath(),
642
- `templates/init-tests/test-${newWorkerTestType}-new-worker.js`
643
- )
644
- )
645
- );
646
- logger.log(
647
- `✨ Created ${path.relative(
648
- process.cwd(),
649
- path.join(creationDirectory, "./src/index.test.js")
650
- )}`
651
- );
652
- }
653
-
654
- await writePackageJsonScriptsAndUpdateWranglerToml({
655
- isWritingScripts: shouldWritePackageJsonScripts,
656
- isAddingTests: shouldCreateTests,
657
- testRunner: newWorkerTestType,
658
- isCreatingWranglerToml: justCreatedWranglerToml,
659
- packagePath: pathToPackageJson,
660
- scriptPath: "src/index.js",
661
- extraToml: getNewWorkerToml(newWorkerType),
662
- });
663
- }
664
- }
665
- }
666
- }
667
- // install packages as the final step of init
668
- try {
669
- await installPackages(
670
- shouldRunPackageManagerInstall,
671
- devDepsToInstall,
672
- packageManager
673
- );
674
- } catch (e) {
675
- // fetching packages could fail due to loss of internet, etc
676
- // we should let folks know we failed to fetch, but their
677
- // workers project is still ready to go
678
- logger.error(e instanceof Error ? e.message : e);
679
- instructions.push(
680
- "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
681
- );
682
- }
683
-
684
- // let users know what to do now
685
- instructions.forEach((instruction) => logger.log(instruction));
686
- }
687
-
688
- /*
689
- * Passes the array of accumulated devDeps to install through to
690
- * the package manager. Also generates a human-readable list
691
- * of packages it installed.
692
- * If there are no devDeps to install, optionally runs
693
- * the package manager's install command.
694
- */
695
- async function installPackages(
696
- shouldRunInstall: boolean,
697
- depsToInstall: string[],
698
- packageManager: PackageManager
699
- ) {
700
- //lets install the devDeps they asked for
701
- //and run their package manager's install command if needed
702
- if (depsToInstall.length > 0) {
703
- const formatter = new Intl.ListFormat("en", {
704
- style: "long",
705
- type: "conjunction",
706
- });
707
- await packageManager.addDevDeps(...depsToInstall);
708
- const versionlessPackages = depsToInstall.map((dep) =>
709
- dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
710
- );
711
-
712
- logger.log(
713
- `✨ Installed ${formatter.format(
714
- versionlessPackages
715
- )} into devDependencies`
716
- );
717
- } else {
718
- if (shouldRunInstall) {
719
- await packageManager.install();
720
- }
721
- }
722
- }
723
-
724
- async function getNewWorkerType(newWorkerFilename: string) {
725
- return select(`Would you like to create a Worker at ${newWorkerFilename}?`, {
726
- choices: [
727
- {
728
- value: "none",
729
- title: "None",
730
- },
731
- {
732
- value: "fetch",
733
- title: "Fetch handler",
734
- },
735
- {
736
- value: "scheduled",
737
- title: "Scheduled handler",
738
- },
739
- ],
740
- defaultOption: 1,
741
- });
742
- }
743
-
744
- async function getNewWorkerTestType(yesFlag?: boolean) {
745
- return yesFlag
746
- ? "jest"
747
- : select(`Which test runner would you like to use?`, {
748
- choices: [
749
- {
750
- value: "vitest",
751
- title: "Vitest",
752
- },
753
- {
754
- value: "jest",
755
- title: "Jest",
756
- },
757
- ],
758
- defaultOption: 1,
759
- });
760
- }
761
-
762
- function getNewWorkerTemplate(
763
- lang: "js" | "ts",
764
- workerType: "fetch" | "scheduled"
765
- ) {
766
- const templates = {
767
- "js-fetch": "new-worker.js",
768
- "js-scheduled": "new-worker-scheduled.js",
769
- "ts-fetch": "new-worker.ts",
770
- "ts-scheduled": "new-worker-scheduled.ts",
771
- };
772
-
773
- return templates[`${lang}-${workerType}`];
774
- }
775
-
776
- function getNewWorkerToml(workerType: "fetch" | "scheduled"): TOML.JsonMap {
777
- if (workerType === "scheduled") {
778
- return {
779
- triggers: {
780
- crons: ["1 * * * *"],
781
- },
782
- };
783
- }
784
-
785
- return {};
786
- }
787
-
788
- /**
789
- * Find the path to the given `basename` file from the `cwd`.
790
- *
791
- * If `isolatedInit` is true then we only look in the `cwd` directory for the file.
792
- * Otherwise we also search up the tree.
793
- */
794
- async function findPath(
795
- isolatedInit: boolean,
796
- cwd: string,
797
- basename: string
798
- ): Promise<string | undefined> {
799
- if (isolatedInit) {
800
- return fs.existsSync(path.resolve(cwd, basename))
801
- ? path.resolve(cwd, basename)
802
- : undefined;
803
- } else {
804
- return await findUp(basename, {
805
- cwd: cwd,
806
- });
807
- }
808
- }
809
-
810
- async function getWorkerConfig(
811
- accountId: string,
812
- fromDashScriptName: string,
813
- {
814
- defaultEnvironment,
815
- environments,
816
- }: {
817
- defaultEnvironment: string | undefined;
818
- environments: ServiceMetadataRes["environments"] | undefined;
819
- }
820
- ): Promise<RawConfig> {
821
- const [bindings, routes, serviceEnvMetadata, cronTriggers] =
822
- await Promise.all([
823
- fetchResult<WorkerMetadata["bindings"]>(
824
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/bindings`
825
- ),
826
- fetchResult<RoutesRes>(
827
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}/routes`
828
- ),
829
- fetchResult<ServiceMetadataRes["default_environment"]>(
830
- `/accounts/${accountId}/workers/services/${fromDashScriptName}/environments/${defaultEnvironment}`
831
- ),
832
- fetchResult<CronTriggersRes>(
833
- `/accounts/${accountId}/workers/scripts/${fromDashScriptName}/schedules`
834
- ),
835
- ]).catch((e) => {
836
- throw new Error(
837
- `Error Occurred ${e}: Unable to fetch bindings, routes, or services metadata from the dashboard. Please try again later.`
838
- );
839
- });
840
-
841
- const mappedBindings = bindings
842
- .filter((binding) => (binding.type as string) !== "secret_text")
843
- // Combine the same types into {[type]: [binding]}
844
- .reduce((configObj, binding) => {
845
- // Some types have different names in wrangler.toml
846
- // I want the type safety of the binding being destructured after the case narrowing the union but type is unused
847
-
848
- switch (binding.type) {
849
- case "plain_text":
850
- {
851
- configObj.vars = {
852
- ...(configObj.vars ?? {}),
853
- [binding.name]: binding.text,
854
- };
855
- }
856
- break;
857
- case "json":
858
- {
859
- configObj.vars = {
860
- ...(configObj.vars ?? {}),
861
- name: binding.name,
862
- json: binding.json,
863
- };
864
- }
865
- break;
866
- case "kv_namespace":
867
- {
868
- configObj.kv_namespaces = [
869
- ...(configObj.kv_namespaces ?? []),
870
- { id: binding.namespace_id, binding: binding.name },
871
- ];
872
- }
873
- break;
874
- case "durable_object_namespace":
875
- {
876
- configObj.durable_objects = {
877
- bindings: [
878
- ...(configObj.durable_objects?.bindings ?? []),
879
- {
880
- name: binding.name,
881
- class_name: binding.class_name,
882
- script_name: binding.script_name,
883
- environment: binding.environment,
884
- },
885
- ],
886
- };
887
- }
888
- break;
889
- case "r2_bucket":
890
- {
891
- configObj.r2_buckets = [
892
- ...(configObj.r2_buckets ?? []),
893
- { binding: binding.name, bucket_name: binding.bucket_name },
894
- ];
895
- }
896
- break;
897
- case "service":
898
- {
899
- configObj.services = [
900
- ...(configObj.services ?? []),
901
- {
902
- binding: binding.name,
903
- service: binding.service,
904
- environment: binding.environment,
905
- },
906
- ];
907
- }
908
- break;
909
- case "analytics_engine":
910
- {
911
- configObj.analytics_engine_datasets = [
912
- ...(configObj.analytics_engine_datasets ?? []),
913
- { binding: binding.name, dataset: binding.dataset },
914
- ];
915
- }
916
- break;
917
- case "dispatch_namespace":
918
- {
919
- configObj.dispatch_namespaces = [
920
- ...(configObj.dispatch_namespaces ?? []),
921
- { binding: binding.name, namespace: binding.namespace },
922
- ];
923
- }
924
- break;
925
- case "logfwdr":
926
- {
927
- configObj.logfwdr = {
928
- // TODO: Messaging about adding schema file path
929
- schema: "",
930
- bindings: [
931
- ...(configObj.logfwdr?.bindings ?? []),
932
- { name: binding.name, destination: binding.destination },
933
- ],
934
- };
935
- }
936
- break;
937
- case "wasm_module":
938
- {
939
- configObj.wasm_modules = {
940
- ...(configObj.wasm_modules ?? {}),
941
- [binding.name]: binding.part,
942
- };
943
- }
944
- break;
945
- case "text_blob":
946
- {
947
- configObj.text_blobs = {
948
- ...(configObj.text_blobs ?? {}),
949
- [binding.name]: binding.part,
950
- };
951
- }
952
- break;
953
- case "data_blob":
954
- {
955
- configObj.data_blobs = {
956
- ...(configObj.data_blobs ?? {}),
957
- [binding.name]: binding.part,
958
- };
959
- }
960
- break;
961
- default: {
962
- // If we don't know what the type is, its an unsafe binding
963
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
964
- if (!(binding as any)?.type) break;
965
- configObj.unsafe = {
966
- bindings: [...(configObj.unsafe?.bindings ?? []), binding],
967
- };
968
- }
969
- }
970
-
971
- return configObj;
972
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
973
- }, {} as RawConfig);
974
-
975
- const durableObjectClassNames = bindings
976
- .filter((binding) => binding.type === "durable_object_namespace")
977
- .map(
978
- (durableObject) => (durableObject as { class_name: string }).class_name
979
- );
980
-
981
- const routeOrRoutes = routes.map((rawRoute) => {
982
- const { id: _id, ...route } = rawRoute;
983
- if (Object.keys(route).length === 1) {
984
- return route.pattern;
985
- } else {
986
- return route as Route;
987
- }
988
- });
989
- const routeOrRoutesToConfig =
990
- routeOrRoutes.length > 1
991
- ? { routes: routeOrRoutes }
992
- : { route: routeOrRoutes[0] };
993
-
994
- return {
995
- compatibility_date:
996
- serviceEnvMetadata.script.compatibility_date ??
997
- new Date().toISOString().substring(0, 10),
998
- ...routeOrRoutesToConfig,
999
- usage_model: serviceEnvMetadata.script.usage_model,
1000
- ...(durableObjectClassNames.length
1001
- ? {
1002
- migrations: [
1003
- {
1004
- tag: serviceEnvMetadata.script.migration_tag,
1005
- new_classes: durableObjectClassNames,
1006
- },
1007
- ],
1008
- }
1009
- : {}),
1010
- triggers: {
1011
- crons: cronTriggers.schedules.map((scheduled) => scheduled.cron),
1012
- },
1013
- env: environments
1014
- ?.filter((env) => env.environment !== "production")
1015
- // `env` can have multiple Environments, with different configs.
1016
- .reduce((envObj, { environment }) => {
1017
- return { ...envObj, [environment]: {} };
1018
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1019
- }, {} as RawConfig["env"]),
1020
- ...mappedBindings,
1021
- };
1022
- }