wrangler 0.0.0-e64812e → 0.0.0-e6c71262

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 (374) hide show
  1. package/README.md +24 -4
  2. package/bin/wrangler.js +170 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +1637 -81
  5. package/package.json +198 -152
  6. package/src/__tests__/access.test.ts +25 -0
  7. package/src/__tests__/api-dev.test.ts +238 -0
  8. package/src/__tests__/api-devregistry.test.ts +121 -0
  9. package/src/__tests__/api.test.ts +102 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4660 -3363
  13. package/src/__tests__/constellation.test.ts +371 -0
  14. package/src/__tests__/d1/d1.test.ts +82 -0
  15. package/src/__tests__/d1/execute.test.ts +66 -0
  16. package/src/__tests__/d1/migrate.test.ts +257 -0
  17. package/src/__tests__/d1/splitter.test.ts +255 -0
  18. package/src/__tests__/delete.test.ts +272 -0
  19. package/src/__tests__/deployments.test.ts +369 -0
  20. package/src/__tests__/dev.test.tsx +1589 -952
  21. package/src/__tests__/generate.test.ts +254 -0
  22. package/src/__tests__/get-host-from-url.test.ts +16 -0
  23. package/src/__tests__/guess-worker-format.test.ts +103 -68
  24. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  25. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  26. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  27. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  28. package/src/__tests__/helpers/mock-bin.ts +20 -20
  29. package/src/__tests__/helpers/mock-console.ts +64 -39
  30. package/src/__tests__/helpers/mock-dialogs.ts +88 -79
  31. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  32. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  33. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  34. package/src/__tests__/helpers/mock-istty.ts +65 -18
  35. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  36. package/src/__tests__/helpers/mock-kv.ts +41 -28
  37. package/src/__tests__/helpers/mock-oauth-flow.ts +241 -233
  38. package/src/__tests__/helpers/mock-process.ts +34 -0
  39. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  40. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  41. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  42. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  43. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  44. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  45. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  46. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  47. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  48. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  49. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  50. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  51. package/src/__tests__/helpers/msw/index.ts +52 -0
  52. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  53. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  54. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  55. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  56. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  57. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  58. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  59. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  60. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  61. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  62. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  63. package/src/__tests__/https-options.test.ts +142 -109
  64. package/src/__tests__/index.test.ts +262 -236
  65. package/src/__tests__/init.test.ts +3388 -1603
  66. package/src/__tests__/jest.setup.ts +152 -50
  67. package/src/__tests__/kv.test.ts +1789 -1471
  68. package/src/__tests__/logger.test.ts +167 -75
  69. package/src/__tests__/logout.test.ts +47 -0
  70. package/src/__tests__/metrics.test.ts +493 -0
  71. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  72. package/src/__tests__/middleware.test.ts +816 -0
  73. package/src/__tests__/mtls-certificates.test.ts +589 -0
  74. package/src/__tests__/package-manager.test.ts +303 -303
  75. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  76. package/src/__tests__/pages/functions-build.test.ts +528 -0
  77. package/src/__tests__/pages/pages.test.ts +81 -0
  78. package/src/__tests__/pages/project-create.test.ts +63 -0
  79. package/src/__tests__/pages/project-list.test.ts +110 -0
  80. package/src/__tests__/pages/project-upload.test.ts +500 -0
  81. package/src/__tests__/pages/publish.test.ts +2864 -0
  82. package/src/__tests__/pages-deployment-tail.test.ts +957 -0
  83. package/src/__tests__/parse.test.ts +358 -252
  84. package/src/__tests__/paths.test.ts +39 -0
  85. package/src/__tests__/publish.test.ts +8736 -5355
  86. package/src/__tests__/pubsub.test.ts +496 -0
  87. package/src/__tests__/queues.test.ts +532 -0
  88. package/src/__tests__/r2.test.ts +369 -228
  89. package/src/__tests__/route.test.ts +18 -18
  90. package/src/__tests__/secret.test.ts +681 -469
  91. package/src/__tests__/tail.test.ts +866 -567
  92. package/src/__tests__/test-old-node-version.js +31 -0
  93. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  94. package/src/__tests__/tsconfig-sanity.ts +12 -0
  95. package/src/__tests__/tsconfig.json +8 -0
  96. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  97. package/src/__tests__/type-generation.test.ts +234 -0
  98. package/src/__tests__/unstableDev.test.ts +61 -0
  99. package/src/__tests__/user.test.ts +107 -120
  100. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  101. package/src/__tests__/validate-dev-props.test.ts +56 -0
  102. package/src/__tests__/version.test.ts +35 -0
  103. package/src/__tests__/whoami.test.tsx +165 -98
  104. package/src/__tests__/worker-namespace.test.ts +340 -0
  105. package/src/abort.d.ts +1 -1
  106. package/src/api/dev.ts +321 -0
  107. package/src/api/index.ts +11 -0
  108. package/src/api/mtls-certificate.ts +148 -0
  109. package/src/api/pages/create-worker-bundle-contents.ts +79 -0
  110. package/src/api/pages/index.ts +5 -0
  111. package/src/api/pages/publish.tsx +371 -0
  112. package/src/bundle-reporter.ts +68 -0
  113. package/src/bundle.ts +890 -161
  114. package/src/cfetch/index.ts +120 -83
  115. package/src/cfetch/internal.ts +215 -97
  116. package/src/cli.ts +23 -8
  117. package/src/config/config.ts +244 -196
  118. package/src/config/diagnostics.ts +61 -61
  119. package/src/config/environment.ts +587 -357
  120. package/src/config/index.ts +395 -196
  121. package/src/config/validation-helpers.ts +379 -357
  122. package/src/config/validation.ts +2285 -1367
  123. package/src/config-cache.ts +81 -41
  124. package/src/constellation/createProject.tsx +51 -0
  125. package/src/constellation/deleteProject.ts +51 -0
  126. package/src/constellation/deleteProjectModel.ts +76 -0
  127. package/src/constellation/index.ts +75 -0
  128. package/src/constellation/listCatalog.tsx +35 -0
  129. package/src/constellation/listModel.tsx +49 -0
  130. package/src/constellation/listProject.tsx +28 -0
  131. package/src/constellation/listRuntime.tsx +28 -0
  132. package/src/constellation/options.ts +17 -0
  133. package/src/constellation/types.ts +17 -0
  134. package/src/constellation/uploadModel.tsx +84 -0
  135. package/src/constellation/utils.ts +90 -0
  136. package/src/create-worker-preview.ts +250 -142
  137. package/src/create-worker-upload-form.ts +364 -238
  138. package/src/d1/backups.tsx +219 -0
  139. package/src/d1/constants.ts +5 -0
  140. package/src/d1/create.tsx +102 -0
  141. package/src/d1/delete.ts +53 -0
  142. package/src/d1/execute.tsx +371 -0
  143. package/src/d1/formatTimeAgo.ts +14 -0
  144. package/src/d1/index.ts +100 -0
  145. package/src/d1/list.tsx +62 -0
  146. package/src/d1/migrations/apply.tsx +235 -0
  147. package/src/d1/migrations/create.tsx +79 -0
  148. package/src/d1/migrations/helpers.ts +171 -0
  149. package/src/d1/migrations/index.ts +3 -0
  150. package/src/d1/migrations/list.tsx +95 -0
  151. package/src/d1/migrations/options.ts +23 -0
  152. package/src/d1/options.ts +22 -0
  153. package/src/d1/splitter.ts +161 -0
  154. package/src/d1/types.ts +32 -0
  155. package/src/d1/utils.ts +49 -0
  156. package/src/delete.ts +100 -0
  157. package/src/deployments.ts +368 -0
  158. package/src/deprecated/index.ts +144 -0
  159. package/src/dev/dev-vars.ts +20 -17
  160. package/src/dev/dev.tsx +538 -352
  161. package/src/dev/get-local-persistence-path.ts +31 -0
  162. package/src/dev/local.tsx +932 -298
  163. package/src/dev/remote.tsx +623 -215
  164. package/src/dev/start-server.ts +545 -0
  165. package/src/dev/use-esbuild.ts +194 -97
  166. package/src/dev/validate-dev-props.ts +40 -0
  167. package/src/dev-registry.ts +213 -0
  168. package/src/dev.tsx +937 -0
  169. package/src/dialogs.ts +136 -0
  170. package/src/dispatch-namespace.ts +211 -0
  171. package/src/docs/helpers.ts +50 -0
  172. package/src/docs/index.ts +54 -0
  173. package/src/durable.ts +87 -87
  174. package/src/entry.ts +253 -231
  175. package/src/environment-variables/factory.ts +89 -0
  176. package/src/environment-variables/misc-variables.ts +30 -0
  177. package/src/errors.ts +6 -6
  178. package/src/generate/index.ts +304 -0
  179. package/src/git-client.ts +135 -0
  180. package/src/global-wrangler-config-path.ts +26 -0
  181. package/src/https-options.ts +84 -80
  182. package/src/index.ts +769 -0
  183. package/src/init.ts +1123 -0
  184. package/src/inspect.ts +816 -595
  185. package/src/intl-polyfill.d.ts +123 -123
  186. package/src/is-ci.ts +14 -0
  187. package/src/is-interactive.ts +16 -0
  188. package/src/jest.d.ts +4 -0
  189. package/src/kv/helpers.ts +433 -0
  190. package/src/kv/index.ts +594 -0
  191. package/src/logger.ts +100 -43
  192. package/src/metrics/index.ts +5 -0
  193. package/src/metrics/metrics-config.ts +239 -0
  194. package/src/metrics/metrics-dispatcher.ts +96 -0
  195. package/src/metrics/metrics-usage-headers.ts +24 -0
  196. package/src/metrics/send-event.ts +99 -0
  197. package/src/miniflare-cli/assets.ts +251 -0
  198. package/src/miniflare-cli/index.ts +202 -33
  199. package/src/miniflare-cli/request-context.ts +18 -18
  200. package/src/miniflare-cli/tsconfig.json +9 -0
  201. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  202. package/src/miniflare-cli/types.ts +11 -0
  203. package/src/module-collection.ts +290 -215
  204. package/src/mtls-certificate/cli.ts +155 -0
  205. package/src/open-in-browser.ts +4 -6
  206. package/src/package-manager.ts +173 -128
  207. package/src/pages/build.ts +423 -0
  208. package/src/pages/buildFunctions.ts +140 -0
  209. package/src/pages/constants.ts +18 -0
  210. package/src/pages/deployment-tails.ts +281 -0
  211. package/src/pages/deployments.tsx +84 -0
  212. package/src/pages/dev.ts +734 -0
  213. package/src/pages/errors.ts +67 -0
  214. package/src/pages/functions/buildPlugin.ts +114 -0
  215. package/src/pages/functions/buildWorker.ts +350 -0
  216. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  217. package/src/pages/functions/filepath-routing.ts +189 -0
  218. package/src/pages/functions/identifiers.ts +78 -0
  219. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  220. package/src/pages/functions/routes-consolidation.ts +73 -0
  221. package/src/pages/functions/routes-transformation.test.ts +282 -0
  222. package/src/pages/functions/routes-transformation.ts +115 -0
  223. package/src/pages/functions/routes-validation.test.ts +403 -0
  224. package/src/pages/functions/routes-validation.ts +202 -0
  225. package/src/pages/functions/routes.ts +151 -0
  226. package/src/pages/functions/tsconfig.json +8 -0
  227. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  228. package/src/pages/functions.ts +86 -0
  229. package/src/pages/hash.ts +13 -0
  230. package/src/pages/index.ts +102 -0
  231. package/src/pages/projects.tsx +159 -0
  232. package/src/pages/prompt-select-project.tsx +31 -0
  233. package/src/pages/publish.tsx +267 -0
  234. package/src/pages/types.ts +46 -0
  235. package/src/pages/upload.tsx +469 -0
  236. package/src/pages/utils.ts +23 -0
  237. package/src/parse.ts +232 -126
  238. package/src/paths.ts +53 -8
  239. package/src/proxy.ts +623 -394
  240. package/src/publish/index.ts +274 -0
  241. package/src/publish/publish.ts +1067 -0
  242. package/src/pubsub/index.ts +286 -0
  243. package/src/pubsub/pubsub-commands.ts +623 -0
  244. package/src/queues/cli/commands/consumer/add.ts +71 -0
  245. package/src/queues/cli/commands/consumer/index.ts +19 -0
  246. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  247. package/src/queues/cli/commands/create.ts +25 -0
  248. package/src/queues/cli/commands/delete.ts +26 -0
  249. package/src/queues/cli/commands/index.ts +35 -0
  250. package/src/queues/cli/commands/list.ts +25 -0
  251. package/src/queues/client.ts +136 -0
  252. package/src/queues/utils.ts +18 -0
  253. package/src/r2/constants.ts +4 -0
  254. package/src/r2/helpers.ts +132 -0
  255. package/src/r2/index.ts +289 -0
  256. package/src/routes.ts +140 -0
  257. package/src/secret/index.ts +379 -0
  258. package/src/selfsigned.d.ts +23 -23
  259. package/src/sites.ts +484 -0
  260. package/src/tail/createTail.ts +415 -0
  261. package/src/tail/filters.ts +109 -111
  262. package/src/tail/index.ts +208 -296
  263. package/src/tail/printing.ts +116 -51
  264. package/src/traverse-module-graph.ts +54 -0
  265. package/src/tsconfig-sanity.ts +16 -0
  266. package/src/type-generation.ts +187 -0
  267. package/src/update-check.ts +11 -11
  268. package/src/user/access.ts +68 -0
  269. package/src/user/auth-variables.ts +113 -0
  270. package/src/user/choose-account.tsx +39 -0
  271. package/src/user/generate-auth-url.ts +33 -0
  272. package/src/user/generate-random-state.ts +16 -0
  273. package/src/user/index.ts +2 -0
  274. package/src/user/user.ts +1234 -0
  275. package/src/utils/collectKeyValues.ts +14 -0
  276. package/src/utils/render.ts +93 -0
  277. package/src/whoami.ts +135 -0
  278. package/src/worker.ts +220 -106
  279. package/src/yargs-types.ts +37 -0
  280. package/src/zones.ts +191 -0
  281. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  282. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  283. package/templates/__tests__/tsconfig.json +8 -0
  284. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  285. package/templates/checked-fetch.js +23 -0
  286. package/templates/d1-beta-facade.js +244 -0
  287. package/templates/facade.d.ts +14 -0
  288. package/templates/first-party-worker-module-facade.ts +19 -0
  289. package/templates/format-dev-errors.ts +34 -0
  290. package/templates/gitignore +1 -0
  291. package/templates/init-tests/test-jest-new-worker.js +23 -0
  292. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  293. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  294. package/templates/middleware/common.ts +62 -0
  295. package/templates/middleware/loader-modules.ts +84 -0
  296. package/templates/middleware/loader-sw.ts +233 -0
  297. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  298. package/templates/middleware/middleware-pretty-error.ts +40 -0
  299. package/templates/middleware/middleware-scheduled.ts +15 -0
  300. package/templates/new-worker-scheduled.js +3 -3
  301. package/templates/new-worker-scheduled.ts +15 -15
  302. package/templates/new-worker.js +3 -3
  303. package/templates/new-worker.ts +18 -15
  304. package/templates/no-op-worker.js +10 -0
  305. package/templates/pages-dev-pipeline.ts +31 -0
  306. package/templates/pages-dev-util.ts +55 -0
  307. package/templates/pages-shim.ts +12 -0
  308. package/templates/pages-template-plugin.ts +180 -0
  309. package/templates/pages-template-worker.ts +189 -0
  310. package/templates/serve-static-assets.ts +66 -0
  311. package/templates/service-bindings-module-facade.js +55 -0
  312. package/templates/service-bindings-sw-facade.js +42 -0
  313. package/templates/tsconfig-sanity.ts +11 -0
  314. package/templates/tsconfig.init.json +105 -0
  315. package/templates/tsconfig.json +6 -103
  316. package/templates/tsconfig.tsbuildinfo +1 -0
  317. package/wrangler-dist/cli.d.ts +1673 -0
  318. package/wrangler-dist/cli.js +119141 -91468
  319. package/wrangler-dist/wasm-sync.wasm +0 -0
  320. package/pages/functions/buildPlugin.ts +0 -105
  321. package/pages/functions/buildWorker.ts +0 -151
  322. package/pages/functions/filepath-routing.ts +0 -189
  323. package/pages/functions/identifiers.ts +0 -78
  324. package/pages/functions/routes.ts +0 -156
  325. package/pages/functions/template-plugin.ts +0 -147
  326. package/pages/functions/template-worker.ts +0 -143
  327. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  328. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  329. package/src/__tests__/pages.test.ts +0 -754
  330. package/src/dialogs.tsx +0 -135
  331. package/src/environment-variables.ts +0 -35
  332. package/src/index.tsx +0 -2864
  333. package/src/kv.ts +0 -408
  334. package/src/miniflare-cli/enum-keys.ts +0 -17
  335. package/src/pages.tsx +0 -2038
  336. package/src/publish.ts +0 -583
  337. package/src/r2.ts +0 -50
  338. package/src/sites.tsx +0 -295
  339. package/src/user.tsx +0 -1203
  340. package/src/whoami.tsx +0 -70
  341. package/templates/static-asset-facade.js +0 -47
  342. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  343. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  344. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  345. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  346. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  347. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  348. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  349. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  350. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  351. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  352. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  353. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  354. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  355. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  356. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  357. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  358. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  359. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  360. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  361. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  362. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  363. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  364. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  365. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  366. package/vendor/wrangler-mime/LICENSE +0 -21
  367. package/vendor/wrangler-mime/Mime.js +0 -97
  368. package/vendor/wrangler-mime/README.md +0 -187
  369. package/vendor/wrangler-mime/cli.js +0 -46
  370. package/vendor/wrangler-mime/index.js +0 -4
  371. package/vendor/wrangler-mime/lite.js +0 -4
  372. package/vendor/wrangler-mime/package.json +0 -52
  373. package/vendor/wrangler-mime/types/other.js +0 -1
  374. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/index.tsx DELETED
@@ -1,2864 +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 { setTimeout } from "node:timers/promises";
5
- import TOML from "@iarna/toml";
6
- import chalk from "chalk";
7
- import { execa } from "execa";
8
- import { findUp } from "find-up";
9
- import getPort from "get-port";
10
- import { render } from "ink";
11
- import React from "react";
12
- import onExit from "signal-exit";
13
- import supportsColor from "supports-color";
14
- import { setGlobalDispatcher, ProxyAgent } from "undici";
15
- import makeCLI from "yargs";
16
- import { version as wranglerVersion } from "../package.json";
17
- import { fetchResult } from "./cfetch";
18
- import { findWranglerToml, printBindings, readConfig } from "./config";
19
- import { createWorkerUploadForm } from "./create-worker-upload-form";
20
- import Dev from "./dev/dev";
21
- import { getVarsForDev } from "./dev/dev-vars";
22
- import { confirm, prompt, select } from "./dialogs";
23
- import { getEntry } from "./entry";
24
- import { DeprecationError } from "./errors";
25
- import {
26
- getKVNamespaceId,
27
- listKVNamespaces,
28
- listKVNamespaceKeys,
29
- putKVKeyValue,
30
- putKVBulkKeyValue,
31
- deleteKVBulkKeyValue,
32
- createKVNamespace,
33
- isValidKVNamespaceBinding,
34
- getKVKeyValue,
35
- isKVKeyValue,
36
- unexpectedKVKeyValueProps,
37
- deleteKVNamespace,
38
- deleteKVKeyValue,
39
- } from "./kv";
40
- import { logger } from "./logger";
41
- import { getPackageManager } from "./package-manager";
42
- import { pages, pagesBetaWarning } from "./pages";
43
- import {
44
- formatMessage,
45
- ParseError,
46
- parseJSON,
47
- parsePackageJSON,
48
- parseTOML,
49
- readFileSync,
50
- } from "./parse";
51
- import publish from "./publish";
52
- import { createR2Bucket, deleteR2Bucket, listR2Buckets } from "./r2";
53
- import { getAssetPaths } from "./sites";
54
- import {
55
- createTail,
56
- jsonPrintLogs,
57
- prettyPrintLogs,
58
- translateCLICommandToFilterMessage,
59
- } from "./tail";
60
- import { updateCheck } from "./update-check";
61
- import {
62
- login,
63
- logout,
64
- listScopes,
65
- validateScopeKeys,
66
- requireAuth,
67
- } from "./user";
68
- import { whoami } from "./whoami";
69
-
70
- import type { Config } from "./config";
71
- import type { TailCLIFilters } from "./tail";
72
- import type { RawData } from "ws";
73
- import type { CommandModule } from "yargs";
74
- import type Yargs from "yargs";
75
-
76
- type ConfigPath = string | undefined;
77
-
78
- const resetColor = "\x1b[0m";
79
- const fgGreenColor = "\x1b[32m";
80
- const DEFAULT_LOCAL_PORT = 8787;
81
-
82
- const proxy =
83
- process.env.https_proxy ||
84
- process.env.HTTPS_PROXY ||
85
- process.env.http_proxy ||
86
- process.env.HTTP_PROXY ||
87
- undefined;
88
-
89
- if (proxy) {
90
- setGlobalDispatcher(new ProxyAgent(proxy));
91
- }
92
-
93
- function getRules(config: Config): Config["rules"] {
94
- const rules = config.rules ?? config.build?.upload?.rules ?? [];
95
-
96
- if (config.rules && config.build?.upload?.rules) {
97
- throw new Error(
98
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
99
- );
100
- }
101
-
102
- if (config.build?.upload?.rules) {
103
- logger.warn(
104
- `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:
105
-
106
- ${TOML.stringify({ rules: config.build.upload.rules })}`
107
- );
108
- }
109
- return rules;
110
- }
111
-
112
- async function printWranglerBanner() {
113
- // Let's not print this in tests
114
- if (typeof jest !== "undefined") {
115
- return;
116
- }
117
-
118
- const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
119
-
120
- logger.log(
121
- text +
122
- "\n" +
123
- (supportsColor.stdout
124
- ? chalk.hex("#FF8800")("-".repeat(text.length))
125
- : "-".repeat(text.length))
126
- );
127
- }
128
-
129
- function isLegacyEnv(config: Config): boolean {
130
- // We only read from config here, because we've already accounted for
131
- // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
132
- return config.legacy_env;
133
- }
134
-
135
- function getScriptName(
136
- args: { name: string | undefined; env: string | undefined },
137
- config: Config
138
- ): string | undefined {
139
- if (args.name && isLegacyEnv(config) && args.env) {
140
- throw new CommandLineArgsError(
141
- "In legacy environment mode you cannot use --name and --env together. If you want to specify a Worker name for a specific environment you can add the following to your wrangler.toml config:" +
142
- `
143
- [env.${args.env}]
144
- name = "${args.name}"
145
- `
146
- );
147
- }
148
-
149
- return args.name ?? config.name;
150
- }
151
-
152
- /**
153
- * Alternative to the getScriptName() because special Legacy cases allowed "name", and "env" together in Wrangler1
154
- */
155
- function getLegacyScriptName(
156
- args: { name: string | undefined; env: string | undefined },
157
- config: Config
158
- ) {
159
- return args.name && args.env && isLegacyEnv(config)
160
- ? `${args.name}-${args.env}`
161
- : args.name ?? config.name;
162
- }
163
-
164
- /**
165
- * Get a promise to the streamed input from stdin.
166
- *
167
- * This function can be used to grab the incoming stream of data from, say,
168
- * piping the output of another process into the wrangler process.
169
- */
170
- function readFromStdin(): Promise<string> {
171
- return new Promise((resolve, reject) => {
172
- const stdin = process.stdin;
173
- const chunks: string[] = [];
174
-
175
- // When there is data ready to be read, the `readable` event will be triggered.
176
- // In the handler for `readable` we call `read()` over and over until all the available data has been read.
177
- stdin.on("readable", () => {
178
- let chunk;
179
- while (null !== (chunk = stdin.read())) {
180
- chunks.push(chunk);
181
- }
182
- });
183
-
184
- // When the streamed data is complete the `end` event will be triggered.
185
- // In the handler for `end` we join the chunks together and resolve the promise.
186
- stdin.on("end", () => {
187
- resolve(chunks.join(""));
188
- });
189
-
190
- // If there is an `error` event then the handler will reject the promise.
191
- stdin.on("error", (err) => {
192
- reject(err);
193
- });
194
- });
195
- }
196
-
197
- // a helper to demand one of a set of options
198
- // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
199
- function demandOneOfOption(...options: string[]) {
200
- return function (argv: Yargs.Arguments) {
201
- const count = options.filter((option) => argv[option]).length;
202
- const lastOption = options.pop();
203
-
204
- if (count === 0) {
205
- throw new CommandLineArgsError(
206
- `Exactly one of the arguments ${options.join(
207
- ", "
208
- )} and ${lastOption} is required`
209
- );
210
- } else if (count > 1) {
211
- throw new CommandLineArgsError(
212
- `Arguments ${options.join(
213
- ", "
214
- )} and ${lastOption} are mutually exclusive`
215
- );
216
- }
217
-
218
- return true;
219
- };
220
- }
221
-
222
- /**
223
- * Remove trailing white space from inputs.
224
- * Matching Wrangler legacy behavior with handling inputs
225
- */
226
- function trimTrailingWhitespace(str: string) {
227
- return str.trimEnd();
228
- }
229
-
230
- class CommandLineArgsError extends Error {}
231
-
232
- function createCLIParser(argv: string[]) {
233
- const wrangler = makeCLI(argv)
234
- .strict()
235
- // We handle errors ourselves in a try-catch around `yargs.parse`.
236
- // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
237
- // Otherwise we just log the error that was thrown without any "help info".
238
- .showHelpOnFail(false)
239
- .fail((msg, error) => {
240
- if (!error || error.name === "YError") {
241
- // If there is no error or the error is a "YError", then this came from yargs own validation
242
- // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
243
- error = new CommandLineArgsError(msg);
244
- }
245
- throw error;
246
- })
247
- .scriptName("wrangler")
248
- .wrap(null);
249
-
250
- // Default help command that supports the subcommands
251
- const subHelp: CommandModule = {
252
- command: ["*"],
253
- handler: async (args) => {
254
- setImmediate(() =>
255
- wrangler.parse([...args._.map((a) => `${a}`), "--help"])
256
- );
257
- },
258
- };
259
- wrangler.command(
260
- ["*"],
261
- false,
262
- () => {},
263
- (args) => {
264
- if (args._.length > 0) {
265
- throw new CommandLineArgsError(`Unknown command: ${args._}.`);
266
- } else {
267
- wrangler.showHelp("log");
268
- }
269
- }
270
- );
271
-
272
- // You will note that we use the form for all commands where we use the builder function
273
- // to define options and subcommands.
274
- // Further we return the result of this builder even though it's not completely necessary.
275
- // The reason is that it's required for type inference of the args in the handle function.
276
- // I wish we could enforce this pattern, but this comment will have to do for now.
277
- // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
278
-
279
- // [DEPRECATED] generate
280
- wrangler.command(
281
- // we definitely want to move away from us cloning github templates
282
- // we can do something better here, let's see
283
- "generate [name] [template]",
284
- false,
285
- (yargs) => {
286
- return yargs
287
- .positional("name", {
288
- describe: "Name of the Workers project",
289
- default: "worker",
290
- })
291
- .positional("template", {
292
- describe: "The URL of a GitHub template",
293
- default: "https://github.com/cloudflare/worker-template",
294
- });
295
- },
296
- (generateArgs) => {
297
- // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
298
- throw new DeprecationError(
299
- "`wrangler generate` has been deprecated.\n" +
300
- "Try running `wrangler init` to generate a basic Worker, or cloning the template repository instead:\n\n" +
301
- "```\n" +
302
- `git clone ${generateArgs.template}\n` +
303
- "```\n\n" +
304
- "Please refer to https://developers.cloudflare.com/workers/wrangler/deprecations/#generate for more information."
305
- );
306
- }
307
- );
308
-
309
- // init
310
- wrangler.command(
311
- "init [name]",
312
- "📥 Create a wrangler.toml configuration file",
313
- (yargs) => {
314
- return yargs
315
- .positional("name", {
316
- describe: "The name of your worker",
317
- type: "string",
318
- })
319
- .option("type", {
320
- describe: "The type of worker to create",
321
- type: "string",
322
- choices: ["rust", "javascript", "webpack"],
323
- hidden: true,
324
- deprecated: true,
325
- })
326
- .option("site", {
327
- hidden: true,
328
- type: "boolean",
329
- deprecated: true,
330
- })
331
- .option("yes", {
332
- describe: 'Answer "yes" to any prompts for new projects',
333
- type: "boolean",
334
- alias: "y",
335
- });
336
- },
337
- async (args) => {
338
- await printWranglerBanner();
339
- if (args.type) {
340
- let message = "The --type option is no longer supported.";
341
- if (args.type === "webpack") {
342
- message +=
343
- "\nIf you wish to use webpack then you will need to create a custom build.";
344
- // TODO: Add a link to docs
345
- }
346
- throw new CommandLineArgsError(message);
347
- }
348
-
349
- const devDepsToInstall: string[] = [];
350
- const instructions: string[] = [];
351
- let shouldRunPackageManagerInstall = false;
352
- const creationDirectory = path.resolve(process.cwd(), args.name ?? "");
353
-
354
- if (args.site) {
355
- const gitDirectory =
356
- creationDirectory !== process.cwd()
357
- ? path.basename(creationDirectory)
358
- : "my-site";
359
- const message =
360
- "The --site option is no longer supported.\n" +
361
- "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
362
- "```\n" +
363
- `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
364
- `cd ${gitDirectory}\n` +
365
- "```\n\n" +
366
- "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
367
- "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
368
- throw new CommandLineArgsError(message);
369
- }
370
-
371
- // TODO: make sure args.name is a valid identifier for a worker name
372
- const workerName = path
373
- .basename(creationDirectory)
374
- .toLowerCase()
375
- .replaceAll(/[^a-z0-9\-_]/gm, "-");
376
-
377
- const packageManager = await getPackageManager(creationDirectory);
378
-
379
- // TODO: ask which directory to make the worker in (defaults to args.name)
380
- // TODO: if args.name isn't provided, ask what to name the worker
381
-
382
- const wranglerTomlDestination = path.join(
383
- creationDirectory,
384
- "./wrangler.toml"
385
- );
386
- let justCreatedWranglerToml = false;
387
-
388
- if (fs.existsSync(wranglerTomlDestination)) {
389
- logger.warn(
390
- `${path.relative(
391
- process.cwd(),
392
- wranglerTomlDestination
393
- )} already exists!`
394
- );
395
- const shouldContinue = await confirm(
396
- "Do you want to continue initializing this project?"
397
- );
398
- if (!shouldContinue) {
399
- return;
400
- }
401
- } else {
402
- await mkdir(creationDirectory, { recursive: true });
403
- const compatibilityDate = new Date().toISOString().substring(0, 10);
404
-
405
- try {
406
- await writeFile(
407
- wranglerTomlDestination,
408
- TOML.stringify({
409
- name: workerName,
410
- compatibility_date: compatibilityDate,
411
- }) + "\n"
412
- );
413
-
414
- logger.log(
415
- `✨ Created ${path.relative(
416
- process.cwd(),
417
- wranglerTomlDestination
418
- )}`
419
- );
420
- justCreatedWranglerToml = true;
421
- } catch (err) {
422
- throw new Error(
423
- `Failed to create ${path.relative(
424
- process.cwd(),
425
- wranglerTomlDestination
426
- )}.\n${(err as Error).message ?? err}`
427
- );
428
- }
429
- }
430
-
431
- const yesFlag = args.yes ?? false;
432
-
433
- const isInsideGitProject = Boolean(
434
- await findUp(".git", { cwd: creationDirectory, type: "directory" })
435
- );
436
- let isGitInstalled;
437
- try {
438
- isGitInstalled = (await execa("git", ["--version"])).exitCode === 0;
439
- } catch (err) {
440
- isGitInstalled = false;
441
- }
442
- if (!isInsideGitProject && isGitInstalled) {
443
- const shouldInitGit =
444
- yesFlag ||
445
- (await confirm("Would you like to use git to manage this Worker?"));
446
- if (shouldInitGit) {
447
- await execa("git", ["init", "--initial-branch=main"], {
448
- cwd: creationDirectory,
449
- });
450
- await writeFile(
451
- path.join(creationDirectory, ".gitignore"),
452
- readFileSync(path.join(__dirname, "../templates/gitignore"))
453
- );
454
- logger.log(
455
- args.name && args.name !== "."
456
- ? `✨ Initialized git repository at ${path.relative(
457
- process.cwd(),
458
- creationDirectory
459
- )}`
460
- : `✨ Initialized git repository`
461
- );
462
- }
463
- }
464
-
465
- let pathToPackageJson = await findUp("package.json", {
466
- cwd: creationDirectory,
467
- });
468
- let shouldCreatePackageJson = false;
469
-
470
- if (!pathToPackageJson) {
471
- // If no package.json exists, ask to create one
472
- shouldCreatePackageJson =
473
- yesFlag ||
474
- (await confirm(
475
- "No package.json found. Would you like to create one?"
476
- ));
477
-
478
- if (shouldCreatePackageJson) {
479
- await writeFile(
480
- path.join(creationDirectory, "./package.json"),
481
- JSON.stringify(
482
- {
483
- name: workerName,
484
- version: "0.0.0",
485
- devDependencies: {
486
- wrangler: wranglerVersion,
487
- },
488
- private: true,
489
- },
490
- null,
491
- " "
492
- ) + "\n"
493
- );
494
-
495
- shouldRunPackageManagerInstall = true;
496
- pathToPackageJson = path.join(creationDirectory, "package.json");
497
- logger.log(
498
- `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
499
- );
500
- } else {
501
- return;
502
- }
503
- } else {
504
- // If package.json exists and wrangler isn't installed,
505
- // then ask to add wrangler to devDependencies
506
- const packageJson = parsePackageJSON(
507
- readFileSync(pathToPackageJson),
508
- pathToPackageJson
509
- );
510
- if (
511
- !(
512
- packageJson.devDependencies?.wrangler ||
513
- packageJson.dependencies?.wrangler
514
- )
515
- ) {
516
- const shouldInstall =
517
- yesFlag ||
518
- (await confirm(
519
- `Would you like to install wrangler into ${path.relative(
520
- process.cwd(),
521
- pathToPackageJson
522
- )}?`
523
- ));
524
- if (shouldInstall) {
525
- devDepsToInstall.push(`wrangler@${wranglerVersion}`);
526
- }
527
- }
528
- }
529
-
530
- let isTypescriptProject = false;
531
- let pathToTSConfig = await findUp("tsconfig.json", {
532
- cwd: creationDirectory,
533
- });
534
- if (!pathToTSConfig) {
535
- // If there's no tsconfig, offer to create one
536
- // and install @cloudflare/workers-types
537
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
538
- isTypescriptProject = true;
539
- await writeFile(
540
- path.join(creationDirectory, "./tsconfig.json"),
541
- readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
542
- );
543
- devDepsToInstall.push("@cloudflare/workers-types");
544
- devDepsToInstall.push("typescript");
545
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
546
- logger.log(
547
- `✨ Created ${path.relative(process.cwd(), pathToTSConfig)}`
548
- );
549
- }
550
- } else {
551
- isTypescriptProject = true;
552
- // If there's a tsconfig, check if @cloudflare/workers-types
553
- // is already installed, and offer to install it if not
554
- const packageJson = parsePackageJSON(
555
- readFileSync(pathToPackageJson),
556
- pathToPackageJson
557
- );
558
- if (
559
- !(
560
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
561
- packageJson.dependencies?.["@cloudflare/workers-types"]
562
- )
563
- ) {
564
- const shouldInstall = await confirm(
565
- "Would you like to install the type definitions for Workers into your package.json?"
566
- );
567
- if (shouldInstall) {
568
- devDepsToInstall.push("@cloudflare/workers-types");
569
- // We don't update the tsconfig.json because
570
- // it could be complicated in existing projects
571
- // and we don't want to break them. Instead, we simply
572
- // tell the user that they need to update their tsconfig.json
573
- instructions.push(
574
- `🚨 Please add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
575
- process.cwd(),
576
- pathToTSConfig
577
- )}`
578
- );
579
- }
580
- }
581
- }
582
-
583
- const packageJsonContent = parsePackageJSON(
584
- readFileSync(pathToPackageJson),
585
- pathToPackageJson
586
- );
587
- const shouldWritePackageJsonScripts =
588
- !packageJsonContent.scripts?.start &&
589
- !packageJsonContent.scripts?.publish &&
590
- shouldCreatePackageJson;
591
-
592
- /*
593
- * Passes the array of accumulated devDeps to install through to
594
- * the package manager. Also generates a human-readable list
595
- * of packages it installed.
596
- * If there are no devDeps to install, optionally runs
597
- * the package manager's install command.
598
- */
599
- async function installPackages(
600
- shouldRunInstall: boolean,
601
- depsToInstall: string[]
602
- ) {
603
- //lets install the devDeps they asked for
604
- //and run their package manager's install command if needed
605
- if (depsToInstall.length > 0) {
606
- const formatter = new Intl.ListFormat("en", {
607
- style: "long",
608
- type: "conjunction",
609
- });
610
- await packageManager.addDevDeps(...depsToInstall);
611
- const versionlessPackages = depsToInstall.map((dep) =>
612
- dep === `wrangler@${wranglerVersion}` ? "wrangler" : dep
613
- );
614
-
615
- logger.log(
616
- `✨ Installed ${formatter.format(
617
- versionlessPackages
618
- )} into devDependencies`
619
- );
620
- } else {
621
- if (shouldRunInstall) {
622
- await packageManager.install();
623
- }
624
- }
625
- }
626
-
627
- async function writePackageJsonScriptsAndUpdateWranglerToml(
628
- isWritingScripts: boolean,
629
- isCreatingWranglerToml: boolean,
630
- packagePath: string,
631
- scriptPath: string,
632
- extraToml: TOML.JsonMap
633
- ) {
634
- if (isCreatingWranglerToml) {
635
- // rewrite wrangler.toml with main = "path/to/script" and any additional config specified in `extraToml`
636
- const parsedWranglerToml = parseTOML(
637
- readFileSync(wranglerTomlDestination)
638
- );
639
- const newToml = {
640
- name: parsedWranglerToml.name,
641
- main: scriptPath,
642
- compatibility_date: parsedWranglerToml.compatibility_date,
643
- ...extraToml,
644
- };
645
- fs.writeFileSync(wranglerTomlDestination, TOML.stringify(newToml));
646
- }
647
- const isNamedWorker =
648
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
649
-
650
- if (isWritingScripts) {
651
- await writeFile(
652
- packagePath,
653
- JSON.stringify(
654
- {
655
- ...packageJsonContent,
656
- scripts: {
657
- ...packageJsonContent.scripts,
658
- start: isCreatingWranglerToml
659
- ? `wrangler dev`
660
- : `wrangler dev ${scriptPath}`,
661
- deploy: isCreatingWranglerToml
662
- ? `wrangler publish`
663
- : `wrangler publish ${scriptPath}`,
664
- },
665
- },
666
- null,
667
- 2
668
- ) + "\n"
669
- );
670
- instructions.push(
671
- `\nTo start developing your Worker, run \`${
672
- isNamedWorker ? `cd ${args.name} && ` : ""
673
- }npm start\``
674
- );
675
- instructions.push(
676
- `To publish your Worker to the Internet, run \`npm run deploy\``
677
- );
678
- } else {
679
- instructions.push(
680
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
681
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
682
- }`
683
- );
684
- instructions.push(
685
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
686
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
687
- }`
688
- );
689
- }
690
- }
691
-
692
- async function getNewWorkerType(newWorkerFilename: string) {
693
- return select(
694
- `Would you like to create a Worker at ${newWorkerFilename}?`,
695
- [
696
- {
697
- value: "none",
698
- label: "None",
699
- },
700
- {
701
- value: "fetch",
702
- label: "Fetch handler",
703
- },
704
- {
705
- value: "scheduled",
706
- label: "Scheduled handler",
707
- },
708
- ],
709
- 1
710
- ) as Promise<"none" | "fetch" | "scheduled">;
711
- }
712
-
713
- function getNewWorkerTemplate(
714
- lang: "js" | "ts",
715
- workerType: "fetch" | "scheduled"
716
- ) {
717
- const templates = {
718
- "js-fetch": "new-worker.js",
719
- "js-scheduled": "new-worker-scheduled.js",
720
- "ts-fetch": "new-worker.ts",
721
- "ts-scheduled": "new-worker-scheduled.ts",
722
- };
723
-
724
- return templates[`${lang}-${workerType}`];
725
- }
726
-
727
- function getNewWorkerToml(
728
- workerType: "fetch" | "scheduled"
729
- ): TOML.JsonMap {
730
- if (workerType === "scheduled") {
731
- return {
732
- triggers: {
733
- crons: ["1 * * * *"],
734
- },
735
- };
736
- }
737
-
738
- return {};
739
- }
740
-
741
- if (isTypescriptProject) {
742
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
743
- const newWorkerFilename = path.relative(
744
- process.cwd(),
745
- path.join(creationDirectory, "./src/index.ts")
746
- );
747
-
748
- const newWorkerType = yesFlag
749
- ? "fetch"
750
- : await getNewWorkerType(newWorkerFilename);
751
-
752
- if (newWorkerType !== "none") {
753
- const template = getNewWorkerTemplate("ts", newWorkerType);
754
-
755
- await mkdir(path.join(creationDirectory, "./src"), {
756
- recursive: true,
757
- });
758
- await writeFile(
759
- path.join(creationDirectory, "./src/index.ts"),
760
- readFileSync(path.join(__dirname, `../templates/${template}`))
761
- );
762
-
763
- logger.log(
764
- `✨ Created ${path.relative(
765
- process.cwd(),
766
- path.join(creationDirectory, "./src/index.ts")
767
- )}`
768
- );
769
-
770
- await writePackageJsonScriptsAndUpdateWranglerToml(
771
- shouldWritePackageJsonScripts,
772
- justCreatedWranglerToml,
773
- pathToPackageJson,
774
- "src/index.ts",
775
- getNewWorkerToml(newWorkerType)
776
- );
777
- }
778
- }
779
- } else {
780
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
781
- const newWorkerFilename = path.relative(
782
- process.cwd(),
783
- path.join(creationDirectory, "./src/index.js")
784
- );
785
-
786
- const newWorkerType = yesFlag
787
- ? "fetch"
788
- : await getNewWorkerType(newWorkerFilename);
789
-
790
- if (newWorkerType !== "none") {
791
- const template = getNewWorkerTemplate("js", newWorkerType);
792
-
793
- await mkdir(path.join(creationDirectory, "./src"), {
794
- recursive: true,
795
- });
796
- await writeFile(
797
- path.join(creationDirectory, "./src/index.js"),
798
- readFileSync(path.join(__dirname, `../templates/${template}`))
799
- );
800
-
801
- logger.log(
802
- `✨ Created ${path.relative(
803
- process.cwd(),
804
- path.join(creationDirectory, "./src/index.js")
805
- )}`
806
- );
807
-
808
- await writePackageJsonScriptsAndUpdateWranglerToml(
809
- shouldWritePackageJsonScripts,
810
- justCreatedWranglerToml,
811
- pathToPackageJson,
812
- "src/index.js",
813
- getNewWorkerToml(newWorkerType)
814
- );
815
- }
816
- }
817
- }
818
- // install packages as the final step of init
819
- try {
820
- await installPackages(shouldRunPackageManagerInstall, devDepsToInstall);
821
- } catch (e) {
822
- // fetching packages could fail due to loss of internet, etc
823
- // we should let folks know we failed to fetch, but their
824
- // workers project is still ready to go
825
- logger.error(e instanceof Error ? e.message : e);
826
- instructions.push(
827
- "\n🚨 wrangler was unable to fetch your npm packages, but your project is ready to go"
828
- );
829
- }
830
-
831
- // let users know what to do now
832
- instructions.forEach((instruction) => logger.log(instruction));
833
- }
834
- );
835
-
836
- // build
837
- wrangler.command(
838
- "build",
839
- false,
840
- (yargs) => {
841
- return yargs.option("env", {
842
- describe: "Perform on a specific environment",
843
- type: "string",
844
- });
845
- },
846
- async (buildArgs) => {
847
- // "[DEPRECATED] 🦀 Build your project (if applicable)",
848
-
849
- const envFlag = buildArgs.env ? ` --env=${buildArgs.env}` : "";
850
- logger.log(
851
- formatMessage({
852
- kind: "warning",
853
- text: "Deprecation: `wrangler build` has been deprecated.",
854
- notes: [
855
- {
856
- text: "Please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#build for more information.",
857
- },
858
- {
859
- text: `Attempting to run \`wrangler publish --dry-run --outdir=dist${envFlag}\` for you instead:`,
860
- },
861
- ],
862
- })
863
- );
864
-
865
- await createCLIParser([
866
- "publish",
867
- "--dry-run",
868
- "--outdir=dist",
869
- ...(buildArgs.env ? ["--env", buildArgs.env] : []),
870
- ]).parse();
871
- }
872
- );
873
-
874
- // config
875
- wrangler.command(
876
- "config",
877
- false,
878
- () => {},
879
- () => {
880
- // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
881
- throw new DeprecationError(
882
- "`wrangler config` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#config for alternatives"
883
- );
884
- }
885
- );
886
-
887
- // dev
888
- wrangler.command(
889
- "dev [script]",
890
- "👂 Start a local server for developing your worker",
891
- (yargs) => {
892
- return yargs
893
- .positional("script", {
894
- describe: "The path to an entry point for your worker",
895
- type: "string",
896
- })
897
- .option("name", {
898
- describe: "Name of the worker",
899
- type: "string",
900
- requiresArg: true,
901
- })
902
- .option("format", {
903
- choices: ["modules", "service-worker"] as const,
904
- describe: "Choose an entry type",
905
- deprecated: true,
906
- })
907
- .option("env", {
908
- describe: "Perform on a specific environment",
909
- type: "string",
910
- requiresArg: true,
911
- alias: "e",
912
- })
913
- .option("compatibility-date", {
914
- describe: "Date to use for compatibility checks",
915
- type: "string",
916
- requiresArg: true,
917
- })
918
- .option("compatibility-flags", {
919
- describe: "Flags to use for compatibility checks",
920
- alias: "compatibility-flag",
921
- type: "string",
922
- requiresArg: true,
923
- array: true,
924
- })
925
- .option("latest", {
926
- describe: "Use the latest version of the worker runtime",
927
- type: "boolean",
928
- default: true,
929
- })
930
- .option("ip", {
931
- describe: "IP address to listen on, defaults to `localhost`",
932
- type: "string",
933
- requiresArg: true,
934
- })
935
- .option("port", {
936
- describe: "Port to listen on",
937
- type: "number",
938
- })
939
- .option("inspector-port", {
940
- describe: "Port for devtools to connect to",
941
- type: "number",
942
- })
943
- .option("routes", {
944
- describe: "Routes to upload",
945
- alias: "route",
946
- type: "string",
947
- requiresArg: true,
948
- array: true,
949
- })
950
- .option("host", {
951
- type: "string",
952
- requiresArg: true,
953
- describe:
954
- "Host to forward requests to, defaults to the zone of project",
955
- })
956
- .option("local-protocol", {
957
- describe: "Protocol to listen to requests on, defaults to http.",
958
- choices: ["http", "https"] as const,
959
- })
960
- .option("experimental-public", {
961
- describe: "Static assets to be served",
962
- type: "string",
963
- requiresArg: true,
964
- })
965
- .option("site", {
966
- describe: "Root folder of static assets for Workers Sites",
967
- type: "string",
968
- requiresArg: true,
969
- })
970
- .option("site-include", {
971
- describe:
972
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
973
- type: "string",
974
- requiresArg: true,
975
- array: true,
976
- })
977
- .option("site-exclude", {
978
- describe:
979
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
980
- type: "string",
981
- requiresArg: true,
982
- array: true,
983
- })
984
- .option("upstream-protocol", {
985
- describe:
986
- "Protocol to forward requests to host on, defaults to https.",
987
- choices: ["http", "https"] as const,
988
- })
989
- .option("jsx-factory", {
990
- describe: "The function that is called for each JSX element",
991
- type: "string",
992
- requiresArg: true,
993
- })
994
- .option("jsx-fragment", {
995
- describe: "The function that is called for each JSX fragment",
996
- type: "string",
997
- requiresArg: true,
998
- })
999
- .option("tsconfig", {
1000
- describe: "Path to a custom tsconfig.json file",
1001
- type: "string",
1002
- requiresArg: true,
1003
- })
1004
- .option("local", {
1005
- alias: "l",
1006
- describe: "Run on my machine",
1007
- type: "boolean",
1008
- default: false, // I bet this will a point of contention. We'll revisit it.
1009
- })
1010
- .option("minify", {
1011
- describe: "Minify the script",
1012
- type: "boolean",
1013
- })
1014
- .option("node-compat", {
1015
- describe: "Enable node.js compatibility",
1016
- type: "boolean",
1017
- })
1018
- .option("experimental-enable-local-persistence", {
1019
- describe: "Enable persistence for this session (only for local mode)",
1020
- type: "boolean",
1021
- })
1022
- .option("inspect", {
1023
- describe: "Enable dev tools",
1024
- type: "boolean",
1025
- deprecated: true,
1026
- })
1027
- .option("legacy-env", {
1028
- type: "boolean",
1029
- describe: "Use legacy environments",
1030
- hidden: true,
1031
- });
1032
- },
1033
- async (args) => {
1034
- await printWranglerBanner();
1035
- const configPath =
1036
- (args.config as ConfigPath) ||
1037
- (args.script && findWranglerToml(path.dirname(args.script)));
1038
- const config = readConfig(configPath, args);
1039
- const entry = await getEntry(args, config, "dev");
1040
-
1041
- if (config.services && config.services.length > 0) {
1042
- logger.warn(
1043
- `This worker is bound to live services: ${config.services
1044
- .map(
1045
- (service) =>
1046
- `${service.binding} (${service.service}${
1047
- service.environment ? `@${service.environment}` : ""
1048
- })`
1049
- )
1050
- .join(", ")}`
1051
- );
1052
- }
1053
-
1054
- if (args.inspect) {
1055
- logger.warn(
1056
- "Passing --inspect is unnecessary, now you can always connect to devtools."
1057
- );
1058
- }
1059
-
1060
- if (args["experimental-public"]) {
1061
- logger.warn(
1062
- "The --experimental-public field is experimental and will change in the future."
1063
- );
1064
- }
1065
-
1066
- if (args.public) {
1067
- throw new Error(
1068
- "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1069
- );
1070
- }
1071
-
1072
- const upstreamProtocol =
1073
- args["upstream-protocol"] || config.dev.upstream_protocol;
1074
- if (upstreamProtocol === "http") {
1075
- logger.warn(
1076
- "Setting upstream-protocol to http is not currently implemented.\n" +
1077
- "If this is required in your project, please add your use case to the following issue:\n" +
1078
- "https://github.com/cloudflare/wrangler2/issues/583."
1079
- );
1080
- }
1081
-
1082
- const accountId = !args.local ? await requireAuth(config) : undefined;
1083
-
1084
- // TODO: if worker_dev = false and no routes, then error (only for dev)
1085
-
1086
- /**
1087
- * Given something that resembles a URL,
1088
- * try to extract a host from it
1089
- */
1090
- function getHost(urlLike: string): string | undefined {
1091
- // strip leading * / *.
1092
- urlLike = urlLike.replace(/^\*(\.)?/g, "");
1093
-
1094
- if (
1095
- !(urlLike.startsWith("http://") || urlLike.startsWith("https://"))
1096
- ) {
1097
- urlLike = "http://" + urlLike;
1098
- }
1099
- return new URL(urlLike).host;
1100
- }
1101
-
1102
- /**
1103
- * Given something that resembles a host,
1104
- * try to infer a zone id from it
1105
- */
1106
- async function getZoneId(host: string): Promise<string | undefined> {
1107
- const zones = await fetchResult<{ id: string }[]>(
1108
- `/zones`,
1109
- {},
1110
- new URLSearchParams({ name: host })
1111
- );
1112
- return zones[0]?.id;
1113
- }
1114
-
1115
- // When we're given a host (in one of the above ways), we do 2 things:
1116
- // - We try to extract a host from it
1117
- // - We try to get a zone id from the host
1118
- //
1119
- // So it turns out it's particularly hard to get a 'valid' domain
1120
- // from a string, so we don't even try to validate TLDs, etc.
1121
- // Once we get something that looks like w.x.y.z-ish, we then try to
1122
- // get a zone id for it, by lopping off subdomains until we get a hit
1123
- // from the API. That's it!
1124
-
1125
- let zone: { host: string; id: string } | undefined;
1126
-
1127
- if (!args.local) {
1128
- const hostLike =
1129
- args.host ||
1130
- config.dev.host ||
1131
- (args.routes && args.routes[0]) ||
1132
- config.route ||
1133
- (config.routes && config.routes[0]);
1134
-
1135
- let zoneId: string | undefined =
1136
- typeof hostLike === "object" && "zone_id" in hostLike
1137
- ? hostLike.zone_id
1138
- : undefined;
1139
-
1140
- const host =
1141
- typeof hostLike === "string"
1142
- ? getHost(hostLike)
1143
- : typeof hostLike === "object"
1144
- ? "zone_name" in hostLike
1145
- ? getHost(hostLike.zone_name)
1146
- : getHost(hostLike.pattern)
1147
- : undefined;
1148
-
1149
- const hostPieces =
1150
- typeof host === "string" ? host.split(".") : undefined;
1151
-
1152
- while (!zoneId && hostPieces && hostPieces.length > 1) {
1153
- zoneId = await getZoneId(hostPieces.join("."));
1154
- hostPieces.shift();
1155
- }
1156
-
1157
- if (host && !zoneId) {
1158
- throw new Error(`Could not find zone for ${hostLike}`);
1159
- }
1160
-
1161
- zone =
1162
- typeof zoneId === "string" && typeof host === "string"
1163
- ? {
1164
- host,
1165
- id: zoneId,
1166
- }
1167
- : undefined;
1168
- }
1169
-
1170
- const nodeCompat = args.nodeCompat ?? config.node_compat;
1171
- if (nodeCompat) {
1172
- logger.warn(
1173
- "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1174
- );
1175
- }
1176
-
1177
- const bindings = {
1178
- kv_namespaces: config.kv_namespaces?.map(
1179
- ({ binding, preview_id, id: _id }) => {
1180
- // In `dev`, we make folks use a separate kv namespace called
1181
- // `preview_id` instead of `id` so that they don't
1182
- // break production data. So here we check that a `preview_id`
1183
- // has actually been configured.
1184
- // This whole block of code will be obsoleted in the future
1185
- // when we have copy-on-write for previews on edge workers.
1186
- if (!preview_id) {
1187
- // TODO: This error has to be a _lot_ better, ideally just asking
1188
- // to create a preview namespace for the user automatically
1189
- throw new Error(
1190
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1191
- ); // Ugh, I really don't like this message very much
1192
- }
1193
- return {
1194
- binding,
1195
- id: preview_id,
1196
- };
1197
- }
1198
- ),
1199
- // Use a copy of combinedVars since we're modifying it later
1200
- vars: getVarsForDev(config),
1201
- wasm_modules: config.wasm_modules,
1202
- text_blobs: config.text_blobs,
1203
- data_blobs: config.data_blobs,
1204
- durable_objects: config.durable_objects,
1205
- r2_buckets: config.r2_buckets?.map(
1206
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1207
- // same idea as kv namespace preview id,
1208
- // same copy-on-write TODO
1209
- if (!preview_bucket_name) {
1210
- throw new Error(
1211
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1212
- );
1213
- }
1214
- return {
1215
- binding,
1216
- bucket_name: preview_bucket_name,
1217
- };
1218
- }
1219
- ),
1220
- services: config.services,
1221
- unsafe: config.unsafe?.bindings,
1222
- };
1223
-
1224
- // mask anything that was overridden in .dev.vars
1225
- // so that we don't log potential secrets into the terminal
1226
- const maskedVars = { ...bindings.vars };
1227
- for (const key of Object.keys(maskedVars)) {
1228
- if (maskedVars[key] !== config.vars[key]) {
1229
- // This means it was overridden in .dev.vars
1230
- // so let's mask it
1231
- maskedVars[key] = "(hidden)";
1232
- }
1233
- }
1234
-
1235
- // now log all available bindings into the terminal
1236
- printBindings({
1237
- ...bindings,
1238
- vars: maskedVars,
1239
- });
1240
-
1241
- const { waitUntilExit } = render(
1242
- <Dev
1243
- name={getScriptName(args, config)}
1244
- entry={entry}
1245
- env={args.env}
1246
- zone={zone}
1247
- rules={getRules(config)}
1248
- legacyEnv={isLegacyEnv(config)}
1249
- minify={args.minify ?? config.minify}
1250
- nodeCompat={nodeCompat}
1251
- build={config.build || {}}
1252
- initialMode={args.local ? "local" : "remote"}
1253
- jsxFactory={args["jsx-factory"] || config.jsx_factory}
1254
- jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
1255
- tsconfig={args.tsconfig ?? config.tsconfig}
1256
- upstreamProtocol={upstreamProtocol}
1257
- localProtocol={args["local-protocol"] || config.dev.local_protocol}
1258
- enableLocalPersistence={
1259
- args["experimental-enable-local-persistence"] || false
1260
- }
1261
- accountId={accountId}
1262
- assetPaths={getAssetPaths(
1263
- config,
1264
- args.site,
1265
- args.siteInclude,
1266
- args.siteExclude
1267
- )}
1268
- port={
1269
- args.port ||
1270
- config.dev.port ||
1271
- (await getPort({ port: DEFAULT_LOCAL_PORT }))
1272
- }
1273
- ip={args.ip || config.dev.ip}
1274
- inspectorPort={
1275
- args["inspector-port"] ?? (await getPort({ port: 9229 }))
1276
- }
1277
- public={args["experimental-public"]}
1278
- compatibilityDate={getDevCompatibilityDate(
1279
- config,
1280
- args["compatibility-date"]
1281
- )}
1282
- compatibilityFlags={
1283
- args["compatibility-flags"] || config.compatibility_flags
1284
- }
1285
- usageModel={config.usage_model}
1286
- bindings={bindings}
1287
- crons={config.triggers.crons}
1288
- />
1289
- );
1290
- await waitUntilExit();
1291
- }
1292
- );
1293
-
1294
- // publish
1295
- wrangler.command(
1296
- "publish [script]",
1297
- "🆙 Publish your Worker to Cloudflare.",
1298
- (yargs) => {
1299
- return yargs
1300
- .option("env", {
1301
- type: "string",
1302
- requiresArg: true,
1303
- describe: "Perform on a specific environment",
1304
- alias: "e",
1305
- })
1306
- .positional("script", {
1307
- describe: "The path to an entry point for your worker",
1308
- type: "string",
1309
- requiresArg: true,
1310
- })
1311
- .option("name", {
1312
- describe: "Name of the worker",
1313
- type: "string",
1314
- requiresArg: true,
1315
- })
1316
- .option("outdir", {
1317
- describe: "Output directory for the bundled worker",
1318
- type: "string",
1319
- requiresArg: true,
1320
- })
1321
- .option("format", {
1322
- choices: ["modules", "service-worker"] as const,
1323
- describe: "Choose an entry type",
1324
- deprecated: true,
1325
- })
1326
- .option("compatibility-date", {
1327
- describe: "Date to use for compatibility checks",
1328
- type: "string",
1329
- requiresArg: true,
1330
- })
1331
- .option("compatibility-flags", {
1332
- describe: "Flags to use for compatibility checks",
1333
- alias: "compatibility-flag",
1334
- type: "string",
1335
- requiresArg: true,
1336
- array: true,
1337
- })
1338
- .option("latest", {
1339
- describe: "Use the latest version of the worker runtime",
1340
- type: "boolean",
1341
- default: false,
1342
- })
1343
- .option("experimental-public", {
1344
- describe: "Static assets to be served",
1345
- type: "string",
1346
- requiresArg: true,
1347
- })
1348
- .option("site", {
1349
- describe: "Root folder of static assets for Workers Sites",
1350
- type: "string",
1351
- requiresArg: true,
1352
- })
1353
- .option("site-include", {
1354
- describe:
1355
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
1356
- type: "string",
1357
- requiresArg: true,
1358
- array: true,
1359
- })
1360
- .option("site-exclude", {
1361
- describe:
1362
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
1363
- type: "string",
1364
- requiresArg: true,
1365
- array: true,
1366
- })
1367
- .option("triggers", {
1368
- describe: "cron schedules to attach",
1369
- alias: ["schedule", "schedules"],
1370
- type: "string",
1371
- requiresArg: true,
1372
- array: true,
1373
- })
1374
- .option("routes", {
1375
- describe: "Routes to upload",
1376
- alias: "route",
1377
- type: "string",
1378
- requiresArg: true,
1379
- array: true,
1380
- })
1381
- .option("jsx-factory", {
1382
- describe: "The function that is called for each JSX element",
1383
- type: "string",
1384
- requiresArg: true,
1385
- })
1386
- .option("jsx-fragment", {
1387
- describe: "The function that is called for each JSX fragment",
1388
- type: "string",
1389
- requiresArg: true,
1390
- })
1391
- .option("tsconfig", {
1392
- describe: "Path to a custom tsconfig.json file",
1393
- type: "string",
1394
- requiresArg: true,
1395
- })
1396
- .option("minify", {
1397
- describe: "Minify the script",
1398
- type: "boolean",
1399
- })
1400
- .option("node-compat", {
1401
- describe: "Enable node.js compatibility",
1402
- type: "boolean",
1403
- })
1404
- .option("dry-run", {
1405
- describe: "Don't actually publish",
1406
- type: "boolean",
1407
- })
1408
- .option("legacy-env", {
1409
- type: "boolean",
1410
- describe: "Use legacy environments",
1411
- hidden: true,
1412
- });
1413
- },
1414
- async (args) => {
1415
- await printWranglerBanner();
1416
- if (args["experimental-public"]) {
1417
- logger.warn(
1418
- "The --experimental-public field is experimental and will change in the future."
1419
- );
1420
- }
1421
- if (args.public) {
1422
- throw new Error(
1423
- "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1424
- );
1425
- }
1426
-
1427
- const configPath =
1428
- (args.config as ConfigPath) ||
1429
- (args.script && findWranglerToml(path.dirname(args.script)));
1430
- const config = readConfig(configPath, args);
1431
- const entry = await getEntry(args, config, "publish");
1432
-
1433
- if (args.latest) {
1434
- logger.warn(
1435
- "Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your wrangler.toml.\n"
1436
- );
1437
- }
1438
-
1439
- const accountId = args.dryRun ? undefined : await requireAuth(config);
1440
-
1441
- const assetPaths = getAssetPaths(
1442
- config,
1443
- args["experimental-public"] || args.site,
1444
- args.siteInclude,
1445
- args.siteExclude
1446
- );
1447
-
1448
- await publish({
1449
- config,
1450
- accountId,
1451
- name: getScriptName(args, config),
1452
- rules: getRules(config),
1453
- entry,
1454
- env: args.env,
1455
- compatibilityDate: args.latest
1456
- ? new Date().toISOString().substring(0, 10)
1457
- : args["compatibility-date"],
1458
- compatibilityFlags: args["compatibility-flags"],
1459
- triggers: args.triggers,
1460
- jsxFactory: args["jsx-factory"],
1461
- jsxFragment: args["jsx-fragment"],
1462
- tsconfig: args.tsconfig,
1463
- routes: args.routes,
1464
- assetPaths,
1465
- legacyEnv: isLegacyEnv(config),
1466
- minify: args.minify,
1467
- nodeCompat: args.nodeCompat,
1468
- experimentalPublic: args["experimental-public"] !== undefined,
1469
- outDir: args.outdir,
1470
- dryRun: args.dryRun,
1471
- });
1472
- }
1473
- );
1474
-
1475
- // tail
1476
- wrangler.command(
1477
- "tail [name]",
1478
- "🦚 Starts a log tailing session for a published Worker.",
1479
- (yargs) => {
1480
- return yargs
1481
- .positional("name", {
1482
- describe: "Name of the worker",
1483
- type: "string",
1484
- })
1485
- .option("format", {
1486
- default: process.stdout.isTTY ? "pretty" : "json",
1487
- choices: ["json", "pretty"],
1488
- describe: "The format of log entries",
1489
- })
1490
- .option("status", {
1491
- choices: ["ok", "error", "canceled"],
1492
- describe: "Filter by invocation status",
1493
- array: true,
1494
- })
1495
- .option("header", {
1496
- type: "string",
1497
- requiresArg: true,
1498
- describe: "Filter by HTTP header",
1499
- })
1500
- .option("method", {
1501
- type: "string",
1502
- requiresArg: true,
1503
- describe: "Filter by HTTP method",
1504
- array: true,
1505
- })
1506
- .option("sampling-rate", {
1507
- type: "number",
1508
- describe: "Adds a percentage of requests to log sampling rate",
1509
- })
1510
- .option("search", {
1511
- type: "string",
1512
- requiresArg: true,
1513
- describe: "Filter by a text match in console.log messages",
1514
- })
1515
- .option("ip", {
1516
- type: "string",
1517
- requiresArg: true,
1518
- describe:
1519
- 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
1520
- array: true,
1521
- })
1522
- .option("env", {
1523
- type: "string",
1524
- requiresArg: true,
1525
- describe: "Perform on a specific environment",
1526
- alias: "e",
1527
- })
1528
- .option("debug", {
1529
- type: "boolean",
1530
- hidden: true,
1531
- default: false,
1532
- describe:
1533
- "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
1534
- })
1535
- .option("legacy-env", {
1536
- type: "boolean",
1537
- describe: "Use legacy environments",
1538
- hidden: true,
1539
- });
1540
- },
1541
- async (args) => {
1542
- if (args.format === "pretty") {
1543
- await printWranglerBanner();
1544
- }
1545
- const config = readConfig(args.config as ConfigPath, args);
1546
-
1547
- const scriptName = getLegacyScriptName(args, config);
1548
-
1549
- if (!scriptName) {
1550
- throw new Error("Missing script name");
1551
- }
1552
-
1553
- const accountId = await requireAuth(config);
1554
-
1555
- const cliFilters: TailCLIFilters = {
1556
- status: args.status as ("ok" | "error" | "canceled")[] | undefined,
1557
- header: args.header,
1558
- method: args.method,
1559
- samplingRate: args["sampling-rate"],
1560
- search: args.search,
1561
- clientIp: args.ip,
1562
- };
1563
-
1564
- const filters = translateCLICommandToFilterMessage(
1565
- cliFilters,
1566
- args.debug
1567
- );
1568
-
1569
- const { tail, expiration, deleteTail } = await createTail(
1570
- accountId,
1571
- scriptName,
1572
- filters,
1573
- !isLegacyEnv(config) ? args.env : undefined
1574
- );
1575
-
1576
- const scriptDisplayName = `${scriptName}${
1577
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1578
- }`;
1579
-
1580
- if (args.format === "pretty") {
1581
- logger.log(
1582
- `Successfully created tail, expires at ${expiration.toLocaleString()}`
1583
- );
1584
- }
1585
-
1586
- onExit(async () => {
1587
- tail.terminate();
1588
- await deleteTail();
1589
- });
1590
-
1591
- const printLog: (data: RawData) => void =
1592
- args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
1593
-
1594
- tail.on("message", printLog);
1595
-
1596
- while (tail.readyState !== tail.OPEN) {
1597
- switch (tail.readyState) {
1598
- case tail.CONNECTING:
1599
- await setTimeout(100);
1600
- break;
1601
- case tail.CLOSING:
1602
- await setTimeout(100);
1603
- break;
1604
- case tail.CLOSED:
1605
- throw new Error(
1606
- `Connection to ${scriptDisplayName} closed unexpectedly.`
1607
- );
1608
- }
1609
- }
1610
-
1611
- if (args.format === "pretty") {
1612
- logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
1613
- }
1614
-
1615
- tail.on("close", async () => {
1616
- tail.terminate();
1617
- await deleteTail();
1618
- });
1619
- }
1620
- );
1621
-
1622
- // preview
1623
- wrangler.command(
1624
- "preview [method] [body]",
1625
- false,
1626
- (yargs) => {
1627
- return yargs
1628
- .positional("method", {
1629
- type: "string",
1630
- describe: "Type of request to preview your worker",
1631
- })
1632
- .positional("body", {
1633
- type: "string",
1634
- describe: "Body string to post to your preview worker request.",
1635
- })
1636
- .option("env", {
1637
- type: "string",
1638
- requiresArg: true,
1639
- describe: "Perform on a specific environment",
1640
- })
1641
- .option("watch", {
1642
- default: true,
1643
- describe: "Enable live preview",
1644
- type: "boolean",
1645
- });
1646
- },
1647
- async (args) => {
1648
- if (args.method || args.body) {
1649
- throw new DeprecationError(
1650
- "The `wrangler preview` command has been deprecated.\n" +
1651
- "Try using `wrangler dev` to to try out a worker during development.\n"
1652
- );
1653
- }
1654
-
1655
- // Delegate to `wrangler dev`
1656
- logger.warn(
1657
- "***************************************************\n" +
1658
- "The `wrangler preview` command has been deprecated.\n" +
1659
- "Attempting to run `wrangler dev` instead.\n" +
1660
- "***************************************************\n"
1661
- );
1662
-
1663
- const config = readConfig(args.config as ConfigPath, args);
1664
- const entry = await getEntry({}, config, "dev");
1665
-
1666
- const accountId = await requireAuth(config);
1667
-
1668
- const { waitUntilExit } = render(
1669
- <Dev
1670
- name={config.name}
1671
- entry={entry}
1672
- rules={getRules(config)}
1673
- env={args.env}
1674
- zone={undefined}
1675
- legacyEnv={isLegacyEnv(config)}
1676
- build={config.build || {}}
1677
- minify={undefined}
1678
- nodeCompat={config.node_compat}
1679
- initialMode={args.local ? "local" : "remote"}
1680
- jsxFactory={config.jsx_factory}
1681
- jsxFragment={config.jsx_fragment}
1682
- tsconfig={config.tsconfig}
1683
- upstreamProtocol={config.dev.upstream_protocol}
1684
- localProtocol={config.dev.local_protocol}
1685
- enableLocalPersistence={false}
1686
- accountId={accountId}
1687
- assetPaths={undefined}
1688
- port={
1689
- config.dev.port || (await getPort({ port: DEFAULT_LOCAL_PORT }))
1690
- }
1691
- ip={config.dev.ip}
1692
- public={undefined}
1693
- compatibilityDate={getDevCompatibilityDate(config)}
1694
- compatibilityFlags={config.compatibility_flags}
1695
- usageModel={config.usage_model}
1696
- bindings={{
1697
- kv_namespaces: config.kv_namespaces?.map(
1698
- ({ binding, preview_id, id: _id }) => {
1699
- // In `dev`, we make folks use a separate kv namespace called
1700
- // `preview_id` instead of `id` so that they don't
1701
- // break production data. So here we check that a `preview_id`
1702
- // has actually been configured.
1703
- // This whole block of code will be obsoleted in the future
1704
- // when we have copy-on-write for previews on edge workers.
1705
- if (!preview_id) {
1706
- // TODO: This error has to be a _lot_ better, ideally just asking
1707
- // to create a preview namespace for the user automatically
1708
- throw new Error(
1709
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1710
- ); // Ugh, I really don't like this message very much
1711
- }
1712
- return {
1713
- binding,
1714
- id: preview_id,
1715
- };
1716
- }
1717
- ),
1718
- vars: config.vars,
1719
- wasm_modules: config.wasm_modules,
1720
- text_blobs: config.text_blobs,
1721
- data_blobs: config.data_blobs,
1722
- durable_objects: config.durable_objects,
1723
- r2_buckets: config.r2_buckets?.map(
1724
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1725
- // same idea as kv namespace preview id,
1726
- // same copy-on-write TODO
1727
- if (!preview_bucket_name) {
1728
- throw new Error(
1729
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1730
- );
1731
- }
1732
- return {
1733
- binding,
1734
- bucket_name: preview_bucket_name,
1735
- };
1736
- }
1737
- ),
1738
- services: config.services,
1739
- unsafe: config.unsafe?.bindings,
1740
- }}
1741
- crons={config.triggers.crons}
1742
- inspectorPort={await getPort({ port: 9229 })}
1743
- />
1744
- );
1745
- await waitUntilExit();
1746
- }
1747
- );
1748
-
1749
- // [DEPRECATED] route
1750
- wrangler.command(
1751
- "route",
1752
- false, // I think we want to hide this command
1753
- // "➡️ List or delete worker routes",
1754
- (routeYargs) => {
1755
- return routeYargs
1756
- .command(
1757
- "list",
1758
- "List the routes associated with a zone",
1759
- (yargs) => {
1760
- return yargs
1761
- .option("env", {
1762
- type: "string",
1763
- requiresArg: true,
1764
- describe: "Perform on a specific environment",
1765
- })
1766
- .option("zone", {
1767
- type: "string",
1768
- requiresArg: true,
1769
- describe: "Zone id",
1770
- })
1771
- .positional("zone", {
1772
- describe: "Zone id",
1773
- type: "string",
1774
- });
1775
- },
1776
- () => {
1777
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1778
- const deprecationNotice =
1779
- "`wrangler route list` has been deprecated.";
1780
- const futureRoutes =
1781
- "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
1782
- const presentRoutes =
1783
- "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
1784
- throw new DeprecationError(
1785
- `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
1786
- );
1787
- }
1788
- )
1789
- .command(
1790
- "delete [id]",
1791
- "Delete a route associated with a zone",
1792
- (yargs) => {
1793
- return yargs
1794
- .positional("id", {
1795
- describe: "The hash of the route ID to delete.",
1796
- type: "string",
1797
- })
1798
- .option("zone", {
1799
- type: "string",
1800
- requiresArg: true,
1801
- describe: "zone id",
1802
- })
1803
- .option("env", {
1804
- type: "string",
1805
- requiresArg: true,
1806
- describe: "Perform on a specific environment",
1807
- });
1808
- },
1809
- () => {
1810
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1811
- const deprecationNotice =
1812
- "`wrangler route delete` has been deprecated.";
1813
- const shouldDo =
1814
- "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
1815
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1816
- }
1817
- );
1818
- },
1819
- () => {
1820
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1821
- const deprecationNotice = "`wrangler route` has been deprecated.";
1822
- const shouldDo =
1823
- "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
1824
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1825
- }
1826
- );
1827
-
1828
- // subdomain
1829
- wrangler.command(
1830
- "subdomain [name]",
1831
- false,
1832
- // "👷 Create or change your workers.dev subdomain.",
1833
- (yargs) => {
1834
- return yargs.positional("name", { type: "string" });
1835
- },
1836
- () => {
1837
- throw new DeprecationError(
1838
- "`wrangler subdomain` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#subdomain for alternatives"
1839
- );
1840
- }
1841
- );
1842
-
1843
- // secret
1844
- wrangler.command(
1845
- "secret",
1846
- "🤫 Generate a secret that can be referenced in the worker script",
1847
- (secretYargs) => {
1848
- return secretYargs
1849
- .command(subHelp)
1850
- .option("legacy-env", {
1851
- type: "boolean",
1852
- describe: "Use legacy environments",
1853
- hidden: true,
1854
- })
1855
- .command(
1856
- "put <key>",
1857
- "Create or update a secret variable for a script",
1858
- (yargs) => {
1859
- return yargs
1860
- .positional("key", {
1861
- describe: "The variable name to be accessible in the script",
1862
- type: "string",
1863
- })
1864
- .option("name", {
1865
- describe: "Name of the worker",
1866
- type: "string",
1867
- requiresArg: true,
1868
- })
1869
- .option("env", {
1870
- type: "string",
1871
- requiresArg: true,
1872
- describe:
1873
- "Binds the secret to the Worker of the specific environment",
1874
- alias: "e",
1875
- });
1876
- },
1877
- async (args) => {
1878
- await printWranglerBanner();
1879
- const config = readConfig(args.config as ConfigPath, args);
1880
-
1881
- const scriptName = getLegacyScriptName(args, config);
1882
- if (!scriptName) {
1883
- throw new Error("Missing script name");
1884
- }
1885
-
1886
- const accountId = await requireAuth(config);
1887
-
1888
- const isInteractive = process.stdin.isTTY;
1889
- const secretValue = trimTrailingWhitespace(
1890
- isInteractive
1891
- ? await prompt("Enter a secret value:", "password")
1892
- : await readFromStdin()
1893
- );
1894
-
1895
- logger.log(
1896
- `🌀 Creating the secret for script ${scriptName} ${
1897
- args.env && !isLegacyEnv(config) ? `(${args.env})` : ""
1898
- }`
1899
- );
1900
-
1901
- async function submitSecret() {
1902
- const url =
1903
- !args.env || isLegacyEnv(config)
1904
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1905
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1906
-
1907
- return await fetchResult(url, {
1908
- method: "PUT",
1909
- headers: { "Content-Type": "application/json" },
1910
- body: JSON.stringify({
1911
- name: args.key,
1912
- text: secretValue,
1913
- type: "secret_text",
1914
- }),
1915
- });
1916
- }
1917
-
1918
- const createDraftWorker = async () => {
1919
- // TODO: log a warning
1920
- await fetchResult(
1921
- !isLegacyEnv(config) && args.env
1922
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
1923
- : `/accounts/${accountId}/workers/scripts/${scriptName}`,
1924
- {
1925
- method: "PUT",
1926
- body: createWorkerUploadForm({
1927
- name: scriptName,
1928
- main: {
1929
- name: scriptName,
1930
- content: `export default { fetch() {} }`,
1931
- type: "esm",
1932
- },
1933
- bindings: {
1934
- kv_namespaces: [],
1935
- vars: {},
1936
- durable_objects: { bindings: [] },
1937
- r2_buckets: [],
1938
- services: [],
1939
- wasm_modules: {},
1940
- text_blobs: {},
1941
- data_blobs: {},
1942
- unsafe: [],
1943
- },
1944
- modules: [],
1945
- migrations: undefined,
1946
- compatibility_date: undefined,
1947
- compatibility_flags: undefined,
1948
- usage_model: undefined,
1949
- }),
1950
- }
1951
- );
1952
- };
1953
-
1954
- function isMissingWorkerError(e: unknown): e is { code: 10007 } {
1955
- return (
1956
- typeof e === "object" &&
1957
- e !== null &&
1958
- (e as { code: number }).code === 10007
1959
- );
1960
- }
1961
-
1962
- try {
1963
- await submitSecret();
1964
- } catch (e) {
1965
- if (isMissingWorkerError(e)) {
1966
- // create a draft worker and try again
1967
- await createDraftWorker();
1968
- await submitSecret();
1969
- // TODO: delete the draft worker if this failed too?
1970
- } else {
1971
- throw e;
1972
- }
1973
- }
1974
-
1975
- logger.log(`✨ Success! Uploaded secret ${args.key}`);
1976
- }
1977
- )
1978
- .command(
1979
- "delete <key>",
1980
- "Delete a secret variable from a script",
1981
- async (yargs) => {
1982
- await printWranglerBanner();
1983
- return yargs
1984
- .positional("key", {
1985
- describe: "The variable name to be accessible in the script",
1986
- type: "string",
1987
- })
1988
- .option("name", {
1989
- describe: "Name of the worker",
1990
- type: "string",
1991
- requiresArg: true,
1992
- })
1993
- .option("env", {
1994
- type: "string",
1995
- requiresArg: true,
1996
- describe:
1997
- "Binds the secret to the Worker of the specific environment",
1998
- alias: "e",
1999
- });
2000
- },
2001
- async (args) => {
2002
- const config = readConfig(args.config as ConfigPath, args);
2003
-
2004
- const scriptName = getLegacyScriptName(args, config);
2005
- if (!scriptName) {
2006
- throw new Error("Missing script name");
2007
- }
2008
-
2009
- const accountId = await requireAuth(config);
2010
-
2011
- if (
2012
- await confirm(
2013
- `Are you sure you want to permanently delete the variable ${
2014
- args.key
2015
- } on the script ${scriptName}${
2016
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
2017
- }?`
2018
- )
2019
- ) {
2020
- logger.log(
2021
- `🌀 Deleting the secret ${args.key} on script ${scriptName}${
2022
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
2023
- }`
2024
- );
2025
-
2026
- const url =
2027
- !args.env || isLegacyEnv(config)
2028
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2029
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
2030
-
2031
- await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
2032
- logger.log(`✨ Success! Deleted secret ${args.key}`);
2033
- }
2034
- }
2035
- )
2036
- .command(
2037
- "list",
2038
- "List all secrets for a script",
2039
- (yargs) => {
2040
- return yargs
2041
- .option("name", {
2042
- describe: "Name of the worker",
2043
- type: "string",
2044
- requiresArg: true,
2045
- })
2046
- .option("env", {
2047
- type: "string",
2048
- requiresArg: true,
2049
- describe:
2050
- "Binds the secret to the Worker of the specific environment.",
2051
- alias: "e",
2052
- });
2053
- },
2054
- async (args) => {
2055
- const config = readConfig(args.config as ConfigPath, args);
2056
-
2057
- const scriptName = getLegacyScriptName(args, config);
2058
- if (!scriptName) {
2059
- throw new Error("Missing script name");
2060
- }
2061
-
2062
- const accountId = await requireAuth(config);
2063
-
2064
- const url =
2065
- !args.env || isLegacyEnv(config)
2066
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
2067
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
2068
-
2069
- logger.log(JSON.stringify(await fetchResult(url), null, " "));
2070
- }
2071
- );
2072
- }
2073
- );
2074
-
2075
- // kv
2076
- // :namespace
2077
- wrangler.command(
2078
- "kv:namespace",
2079
- "🗂️ Interact with your Workers KV Namespaces",
2080
- (namespaceYargs) => {
2081
- return namespaceYargs
2082
- .command(subHelp)
2083
- .command(
2084
- "create <namespace>",
2085
- "Create a new namespace",
2086
- (yargs) => {
2087
- return yargs
2088
- .positional("namespace", {
2089
- describe: "The name of the new namespace",
2090
- type: "string",
2091
- demandOption: true,
2092
- })
2093
- .option("env", {
2094
- type: "string",
2095
- requiresArg: true,
2096
- describe: "Perform on a specific environment",
2097
- alias: "e",
2098
- })
2099
- .option("preview", {
2100
- type: "boolean",
2101
- describe: "Interact with a preview namespace",
2102
- });
2103
- },
2104
- async (args) => {
2105
- await printWranglerBanner();
2106
-
2107
- if (!isValidKVNamespaceBinding(args.namespace)) {
2108
- throw new CommandLineArgsError(
2109
- `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
2110
- );
2111
- }
2112
-
2113
- const config = readConfig(args.config as ConfigPath, args);
2114
- if (!config.name) {
2115
- logger.warn(
2116
- "No configured name present, using `worker` as a prefix for the title"
2117
- );
2118
- }
2119
-
2120
- const name = config.name || "worker";
2121
- const environment = args.env ? `-${args.env}` : "";
2122
- const preview = args.preview ? "_preview" : "";
2123
- const title = `${name}${environment}-${args.namespace}${preview}`;
2124
-
2125
- const accountId = await requireAuth(config);
2126
-
2127
- // TODO: generate a binding name stripping non alphanumeric chars
2128
-
2129
- logger.log(`🌀 Creating namespace with title "${title}"`);
2130
- const namespaceId = await createKVNamespace(accountId, title);
2131
-
2132
- logger.log("✨ Success!");
2133
- const envString = args.env ? ` under [env.${args.env}]` : "";
2134
- const previewString = args.preview ? "preview_" : "";
2135
- logger.log(
2136
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
2137
- );
2138
- logger.log(
2139
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
2140
- );
2141
-
2142
- // TODO: automatically write this block to the wrangler.toml config file??
2143
- }
2144
- )
2145
- .command(
2146
- "list",
2147
- "Outputs a list of all KV namespaces associated with your account id.",
2148
- {},
2149
- async (args) => {
2150
- const config = readConfig(args.config as ConfigPath, args);
2151
-
2152
- const accountId = await requireAuth(config);
2153
-
2154
- // TODO: we should show bindings if they exist for given ids
2155
-
2156
- logger.log(
2157
- JSON.stringify(await listKVNamespaces(accountId), null, " ")
2158
- );
2159
- }
2160
- )
2161
- .command(
2162
- "delete",
2163
- "Deletes a given namespace.",
2164
- (yargs) => {
2165
- return yargs
2166
- .option("binding", {
2167
- type: "string",
2168
- requiresArg: true,
2169
- describe: "The name of the namespace to delete",
2170
- })
2171
- .option("namespace-id", {
2172
- type: "string",
2173
- requiresArg: true,
2174
- describe: "The id of the namespace to delete",
2175
- })
2176
- .check(demandOneOfOption("binding", "namespace-id"))
2177
- .option("env", {
2178
- type: "string",
2179
- requiresArg: true,
2180
- describe: "Perform on a specific environment",
2181
- alias: "e",
2182
- })
2183
- .option("preview", {
2184
- type: "boolean",
2185
- describe: "Interact with a preview namespace",
2186
- });
2187
- },
2188
- async (args) => {
2189
- await printWranglerBanner();
2190
- const config = readConfig(args.config as ConfigPath, args);
2191
-
2192
- let id;
2193
- try {
2194
- id = getKVNamespaceId(args, config);
2195
- } catch (e) {
2196
- throw new CommandLineArgsError(
2197
- "Not able to delete namespace.\n" + ((e as Error).message ?? e)
2198
- );
2199
- }
2200
-
2201
- const accountId = await requireAuth(config);
2202
-
2203
- await deleteKVNamespace(accountId, id);
2204
-
2205
- // TODO: recommend they remove it from wrangler.toml
2206
-
2207
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2208
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2209
- // n
2210
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2211
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2212
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2213
- // y
2214
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2215
- // ✨ Success
2216
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
2217
- // ➜ test-mf
2218
-
2219
- // TODO: do it automatically
2220
-
2221
- // TODO: delete the preview namespace as well?
2222
- }
2223
- );
2224
- }
2225
- );
2226
-
2227
- // :key
2228
- wrangler.command(
2229
- "kv:key",
2230
- "🔑 Individually manage Workers KV key-value pairs",
2231
- (kvKeyYargs) => {
2232
- return kvKeyYargs
2233
- .command(subHelp)
2234
- .command(
2235
- "put <key> [value]",
2236
- "Writes a single key/value pair to the given namespace.",
2237
- (yargs) => {
2238
- return yargs
2239
- .positional("key", {
2240
- type: "string",
2241
- describe: "The key to write to",
2242
- demandOption: true,
2243
- })
2244
- .positional("value", {
2245
- type: "string",
2246
- describe: "The value to write",
2247
- })
2248
- .option("binding", {
2249
- type: "string",
2250
- requiresArg: true,
2251
- describe: "The binding of the namespace to write to",
2252
- })
2253
- .option("namespace-id", {
2254
- type: "string",
2255
- requiresArg: true,
2256
- describe: "The id of the namespace to write to",
2257
- })
2258
- .check(demandOneOfOption("binding", "namespace-id"))
2259
- .option("env", {
2260
- type: "string",
2261
- requiresArg: true,
2262
- describe: "Perform on a specific environment",
2263
- alias: "e",
2264
- })
2265
- .option("preview", {
2266
- type: "boolean",
2267
- describe: "Interact with a preview namespace",
2268
- })
2269
- .option("ttl", {
2270
- type: "number",
2271
- describe: "Time for which the entries should be visible",
2272
- })
2273
- .option("expiration", {
2274
- type: "number",
2275
- describe:
2276
- "Time since the UNIX epoch after which the entry expires",
2277
- })
2278
- .option("path", {
2279
- type: "string",
2280
- requiresArg: true,
2281
- describe: "Read value from the file at a given path",
2282
- })
2283
- .check(demandOneOfOption("value", "path"));
2284
- },
2285
- async ({ key, ttl, expiration, ...args }) => {
2286
- await printWranglerBanner();
2287
- const config = readConfig(args.config as ConfigPath, args);
2288
- const namespaceId = getKVNamespaceId(args, config);
2289
- // One of `args.path` and `args.value` must be defined
2290
- const value = args.path
2291
- ? readFileSync(args.path)
2292
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2293
- args.value!;
2294
-
2295
- if (args.path) {
2296
- logger.log(
2297
- `Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}.`
2298
- );
2299
- } else {
2300
- logger.log(
2301
- `Writing the value "${value}" to key "${key}" on namespace ${namespaceId}.`
2302
- );
2303
- }
2304
-
2305
- const accountId = await requireAuth(config);
2306
-
2307
- await putKVKeyValue(accountId, namespaceId, {
2308
- key,
2309
- value,
2310
- expiration,
2311
- expiration_ttl: ttl,
2312
- });
2313
- }
2314
- )
2315
- .command(
2316
- "list",
2317
- "Outputs a list of all keys in a given namespace.",
2318
- (yargs) => {
2319
- return yargs
2320
- .option("binding", {
2321
- type: "string",
2322
- requiresArg: true,
2323
- describe: "The name of the namespace to list",
2324
- })
2325
- .option("namespace-id", {
2326
- type: "string",
2327
- requiresArg: true,
2328
- describe: "The id of the namespace to list",
2329
- })
2330
- .check(demandOneOfOption("binding", "namespace-id"))
2331
- .option("env", {
2332
- type: "string",
2333
- requiresArg: true,
2334
- describe: "Perform on a specific environment",
2335
- alias: "e",
2336
- })
2337
- .option("preview", {
2338
- type: "boolean",
2339
- // In the case of listing keys we will default to non-preview mode
2340
- default: false,
2341
- describe: "Interact with a preview namespace",
2342
- })
2343
- .option("prefix", {
2344
- type: "string",
2345
- requiresArg: true,
2346
- describe: "A prefix to filter listed keys",
2347
- });
2348
- },
2349
- async ({ prefix, ...args }) => {
2350
- // TODO: support for limit+cursor (pagination)
2351
- const config = readConfig(args.config as ConfigPath, args);
2352
- const namespaceId = getKVNamespaceId(args, config);
2353
-
2354
- const accountId = await requireAuth(config);
2355
-
2356
- const results = await listKVNamespaceKeys(
2357
- accountId,
2358
- namespaceId,
2359
- prefix
2360
- );
2361
- logger.log(JSON.stringify(results, undefined, 2));
2362
- }
2363
- )
2364
- .command(
2365
- "get <key>",
2366
- "Reads a single value by key from the given namespace.",
2367
- (yargs) => {
2368
- return yargs
2369
- .positional("key", {
2370
- describe: "The key value to get.",
2371
- type: "string",
2372
- demandOption: true,
2373
- })
2374
- .option("binding", {
2375
- type: "string",
2376
- requiresArg: true,
2377
- describe: "The name of the namespace to get from",
2378
- })
2379
- .option("namespace-id", {
2380
- type: "string",
2381
- requiresArg: true,
2382
- describe: "The id of the namespace to get from",
2383
- })
2384
- .check(demandOneOfOption("binding", "namespace-id"))
2385
- .option("env", {
2386
- type: "string",
2387
- requiresArg: true,
2388
- describe: "Perform on a specific environment",
2389
- alias: "e",
2390
- })
2391
- .option("preview", {
2392
- type: "boolean",
2393
- describe: "Interact with a preview namespace",
2394
- })
2395
- .option("preview", {
2396
- type: "boolean",
2397
- // In the case of getting key values we will default to non-preview mode
2398
- default: false,
2399
- describe: "Interact with a preview namespace",
2400
- });
2401
- },
2402
- async ({ key, ...args }) => {
2403
- const config = readConfig(args.config as ConfigPath, args);
2404
- const namespaceId = getKVNamespaceId(args, config);
2405
-
2406
- const accountId = await requireAuth(config);
2407
-
2408
- logger.log(await getKVKeyValue(accountId, namespaceId, key));
2409
- }
2410
- )
2411
- .command(
2412
- "delete <key>",
2413
- "Removes a single key value pair from the given namespace.",
2414
- (yargs) => {
2415
- return yargs
2416
- .positional("key", {
2417
- describe: "The key value to delete",
2418
- type: "string",
2419
- demandOption: true,
2420
- })
2421
- .option("binding", {
2422
- type: "string",
2423
- requiresArg: true,
2424
- describe: "The name of the namespace to delete from",
2425
- })
2426
- .option("namespace-id", {
2427
- type: "string",
2428
- requiresArg: true,
2429
- describe: "The id of the namespace to delete from",
2430
- })
2431
- .check(demandOneOfOption("binding", "namespace-id"))
2432
- .option("env", {
2433
- type: "string",
2434
- requiresArg: true,
2435
- describe: "Perform on a specific environment",
2436
- alias: "e",
2437
- })
2438
- .option("preview", {
2439
- type: "boolean",
2440
- describe: "Interact with a preview namespace",
2441
- });
2442
- },
2443
- async ({ key, ...args }) => {
2444
- await printWranglerBanner();
2445
- const config = readConfig(args.config as ConfigPath, args);
2446
- const namespaceId = getKVNamespaceId(args, config);
2447
-
2448
- logger.log(
2449
- `Deleting the key "${key}" on namespace ${namespaceId}.`
2450
- );
2451
-
2452
- const accountId = await requireAuth(config);
2453
-
2454
- await deleteKVKeyValue(accountId, namespaceId, key);
2455
- }
2456
- );
2457
- }
2458
- );
2459
-
2460
- // :bulk
2461
- wrangler.command(
2462
- "kv:bulk",
2463
- "💪 Interact with multiple Workers KV key-value pairs at once",
2464
- (kvBulkYargs) => {
2465
- return kvBulkYargs
2466
- .command(subHelp)
2467
- .command(
2468
- "put <filename>",
2469
- "Upload multiple key-value pairs to a namespace",
2470
- (yargs) => {
2471
- return yargs
2472
- .positional("filename", {
2473
- describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
2474
- type: "string",
2475
- demandOption: true,
2476
- })
2477
- .option("binding", {
2478
- type: "string",
2479
- requiresArg: true,
2480
- describe: "The name of the namespace to insert values into",
2481
- })
2482
- .option("namespace-id", {
2483
- type: "string",
2484
- requiresArg: true,
2485
- describe: "The id of the namespace to insert values into",
2486
- })
2487
- .check(demandOneOfOption("binding", "namespace-id"))
2488
- .option("env", {
2489
- type: "string",
2490
- requiresArg: true,
2491
- describe: "Perform on a specific environment",
2492
- alias: "e",
2493
- })
2494
- .option("preview", {
2495
- type: "boolean",
2496
- describe: "Interact with a preview namespace",
2497
- });
2498
- },
2499
- async ({ filename, ...args }) => {
2500
- await printWranglerBanner();
2501
- // The simplest implementation I could think of.
2502
- // This could be made more efficient with a streaming parser/uploader
2503
- // but we'll do that in the future if needed.
2504
-
2505
- const config = readConfig(args.config as ConfigPath, args);
2506
- const namespaceId = getKVNamespaceId(args, config);
2507
- const content = parseJSON(readFileSync(filename), filename);
2508
-
2509
- if (!Array.isArray(content)) {
2510
- throw new Error(
2511
- `Unexpected JSON input from "${filename}".\n` +
2512
- `Expected an array of key-value objects but got type "${typeof content}".`
2513
- );
2514
- }
2515
-
2516
- const errors: string[] = [];
2517
- const warnings: string[] = [];
2518
- for (let i = 0; i < content.length; i++) {
2519
- const keyValue = content[i];
2520
- if (!isKVKeyValue(keyValue)) {
2521
- errors.push(
2522
- `The item at index ${i} is ${JSON.stringify(keyValue)}`
2523
- );
2524
- } else {
2525
- const props = unexpectedKVKeyValueProps(keyValue);
2526
- if (props.length > 0) {
2527
- warnings.push(
2528
- `The item at index ${i} contains unexpected properties: ${JSON.stringify(
2529
- props
2530
- )}.`
2531
- );
2532
- }
2533
- }
2534
- }
2535
- if (warnings.length > 0) {
2536
- logger.warn(
2537
- `Unexpected key-value properties in "${filename}".\n` +
2538
- warnings.join("\n")
2539
- );
2540
- }
2541
- if (errors.length > 0) {
2542
- throw new Error(
2543
- `Unexpected JSON input from "${filename}".\n` +
2544
- `Each item in the array should be an object that matches:\n\n` +
2545
- `interface KeyValue {\n` +
2546
- ` key: string;\n` +
2547
- ` value: string;\n` +
2548
- ` expiration?: number;\n` +
2549
- ` expiration_ttl?: number;\n` +
2550
- ` metadata?: object;\n` +
2551
- ` base64?: boolean;\n` +
2552
- `}\n\n` +
2553
- errors.join("\n")
2554
- );
2555
- }
2556
-
2557
- const accountId = await requireAuth(config);
2558
- await putKVBulkKeyValue(accountId, namespaceId, content);
2559
-
2560
- logger.log("Success!");
2561
- }
2562
- )
2563
- .command(
2564
- "delete <filename>",
2565
- "Delete multiple key-value pairs from a namespace",
2566
- (yargs) => {
2567
- return yargs
2568
- .positional("filename", {
2569
- describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
2570
- type: "string",
2571
- demandOption: true,
2572
- })
2573
- .option("binding", {
2574
- type: "string",
2575
- requiresArg: true,
2576
- describe: "The name of the namespace to delete from",
2577
- })
2578
- .option("namespace-id", {
2579
- type: "string",
2580
- requiresArg: true,
2581
- describe: "The id of the namespace to delete from",
2582
- })
2583
- .check(demandOneOfOption("binding", "namespace-id"))
2584
- .option("env", {
2585
- type: "string",
2586
- requiresArg: true,
2587
- describe: "Perform on a specific environment",
2588
- alias: "e",
2589
- })
2590
- .option("preview", {
2591
- type: "boolean",
2592
- describe: "Interact with a preview namespace",
2593
- })
2594
- .option("force", {
2595
- type: "boolean",
2596
- alias: "f",
2597
- describe: "Do not ask for confirmation before deleting",
2598
- });
2599
- },
2600
- async ({ filename, ...args }) => {
2601
- await printWranglerBanner();
2602
- const config = readConfig(args.config as ConfigPath, args);
2603
- const namespaceId = getKVNamespaceId(args, config);
2604
-
2605
- if (!args.force) {
2606
- const result = await confirm(
2607
- `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
2608
- );
2609
- if (!result) {
2610
- logger.log(`Not deleting keys read from "${filename}".`);
2611
- return;
2612
- }
2613
- }
2614
-
2615
- const content = parseJSON(
2616
- readFileSync(filename),
2617
- filename
2618
- ) as string[];
2619
-
2620
- if (!Array.isArray(content)) {
2621
- throw new Error(
2622
- `Unexpected JSON input from "${filename}".\n` +
2623
- `Expected an array of strings but got:\n${content}`
2624
- );
2625
- }
2626
-
2627
- const errors: string[] = [];
2628
- for (let i = 0; i < content.length; i++) {
2629
- const key = content[i];
2630
- if (typeof key !== "string") {
2631
- errors.push(
2632
- `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
2633
- key
2634
- )}`
2635
- );
2636
- }
2637
- }
2638
- if (errors.length > 0) {
2639
- throw new Error(
2640
- `Unexpected JSON input from "${filename}".\n` +
2641
- `Expected an array of strings.\n` +
2642
- errors.join("\n")
2643
- );
2644
- }
2645
-
2646
- const accountId = await requireAuth(config);
2647
-
2648
- await deleteKVBulkKeyValue(accountId, namespaceId, content);
2649
-
2650
- logger.log("Success!");
2651
- }
2652
- );
2653
- }
2654
- );
2655
-
2656
- wrangler.command(
2657
- "pages",
2658
- "⚡️ Configure Cloudflare Pages",
2659
- async (pagesYargs) => {
2660
- await pages(pagesYargs.command(subHelp).epilogue(pagesBetaWarning));
2661
- }
2662
- );
2663
-
2664
- wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
2665
- return r2Yargs
2666
- .command(subHelp)
2667
- .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
2668
- r2BucketYargs.command(
2669
- "create <name>",
2670
- "Create a new R2 bucket",
2671
- (yargs) => {
2672
- return yargs.positional("name", {
2673
- describe: "The name of the new bucket",
2674
- type: "string",
2675
- demandOption: true,
2676
- });
2677
- },
2678
- async (args) => {
2679
- await printWranglerBanner();
2680
-
2681
- const config = readConfig(args.config as ConfigPath, args);
2682
-
2683
- const accountId = await requireAuth(config);
2684
-
2685
- logger.log(`Creating bucket ${args.name}.`);
2686
- await createR2Bucket(accountId, args.name);
2687
- logger.log(`Created bucket ${args.name}.`);
2688
- }
2689
- );
2690
-
2691
- r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
2692
- const config = readConfig(args.config as ConfigPath, args);
2693
-
2694
- const accountId = await requireAuth(config);
2695
-
2696
- logger.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
2697
- });
2698
-
2699
- r2BucketYargs.command(
2700
- "delete <name>",
2701
- "Delete an R2 bucket",
2702
- (yargs) => {
2703
- return yargs.positional("name", {
2704
- describe: "The name of the bucket to delete",
2705
- type: "string",
2706
- demandOption: true,
2707
- });
2708
- },
2709
- async (args) => {
2710
- await printWranglerBanner();
2711
-
2712
- const config = readConfig(args.config as ConfigPath, args);
2713
-
2714
- const accountId = await requireAuth(config);
2715
-
2716
- logger.log(`Deleting bucket ${args.name}.`);
2717
- await deleteR2Bucket(accountId, args.name);
2718
- logger.log(`Deleted bucket ${args.name}.`);
2719
- }
2720
- );
2721
- return r2BucketYargs;
2722
- });
2723
- });
2724
-
2725
- /**
2726
- * User Group: login, logout, and whoami
2727
- * TODO: group commands into User group similar to .group() for flags in yargs
2728
- */
2729
- // login
2730
- wrangler.command(
2731
- // this needs scopes as an option?
2732
- "login",
2733
- "🔓 Login to Cloudflare",
2734
- (yargs) => {
2735
- // TODO: This needs some copy editing
2736
- // I mean, this entire app does, but this too.
2737
- return yargs
2738
- .option("scopes-list", {
2739
- describe: "List all the available OAuth scopes with descriptions",
2740
- })
2741
- .option("scopes", {
2742
- describe: "Pick the set of applicable OAuth scopes when logging in",
2743
- array: true,
2744
- type: "string",
2745
- requiresArg: true,
2746
- });
2747
-
2748
- // TODO: scopes
2749
- },
2750
- async (args) => {
2751
- await printWranglerBanner();
2752
- if (args["scopes-list"]) {
2753
- listScopes();
2754
- return;
2755
- }
2756
- if (args.scopes) {
2757
- if (args.scopes.length === 0) {
2758
- // don't allow no scopes to be passed, that would be weird
2759
- listScopes();
2760
- return;
2761
- }
2762
- if (!validateScopeKeys(args.scopes)) {
2763
- throw new CommandLineArgsError(
2764
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
2765
- );
2766
- }
2767
- await login({ scopes: args.scopes });
2768
- return;
2769
- }
2770
- await login();
2771
-
2772
- // TODO: would be nice if it optionally saved login
2773
- // credentials inside node_modules/.cache or something
2774
- // this way you could have multiple users on a single machine
2775
- }
2776
- );
2777
-
2778
- // logout
2779
- wrangler.command(
2780
- // this needs scopes as an option?
2781
- "logout",
2782
- "🚪 Logout from Cloudflare",
2783
- () => {},
2784
- async () => {
2785
- await printWranglerBanner();
2786
- await logout();
2787
- }
2788
- );
2789
-
2790
- // whoami
2791
- wrangler.command(
2792
- "whoami",
2793
- "🕵️ Retrieve your user info and test your auth config",
2794
- () => {},
2795
- async () => {
2796
- await printWranglerBanner();
2797
- await whoami();
2798
- }
2799
- );
2800
-
2801
- wrangler.option("config", {
2802
- alias: "c",
2803
- describe: "Path to .toml configuration file",
2804
- type: "string",
2805
- requiresArg: true,
2806
- });
2807
-
2808
- wrangler.group(["config", "help", "version"], "Flags:");
2809
- wrangler.help().alias("h", "help");
2810
- wrangler.version(wranglerVersion).alias("v", "version");
2811
- wrangler.exitProcess(false);
2812
-
2813
- return wrangler;
2814
- }
2815
-
2816
- export async function main(argv: string[]): Promise<void> {
2817
- const wrangler = createCLIParser(argv);
2818
- try {
2819
- await wrangler.parse();
2820
- } catch (e) {
2821
- logger.log(""); // Just adds a bit of space
2822
- if (e instanceof CommandLineArgsError) {
2823
- logger.error(e.message);
2824
- // We are not able to ask the `wrangler` CLI parser to show help for a subcommand programmatically.
2825
- // The workaround is to re-run the parsing with an additional `--help` flag, which will result in the correct help message being displayed.
2826
- // The `wrangler` object is "frozen"; we cannot reuse that with different args, so we must create a new CLI parser to generate the help message.
2827
- await createCLIParser([...argv, "--help"]).parse();
2828
- } else if (e instanceof ParseError) {
2829
- e.notes.push({
2830
- text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new/choose",
2831
- });
2832
- logger.log(formatMessage(e));
2833
- } else {
2834
- logger.error(e instanceof Error ? e.message : e);
2835
- logger.log(
2836
- `${fgGreenColor}%s${resetColor}`,
2837
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
2838
- );
2839
- }
2840
- throw e;
2841
- }
2842
- }
2843
-
2844
- function getDevCompatibilityDate(
2845
- config: Config,
2846
- compatibilityDate = config.compatibility_date
2847
- ) {
2848
- const currentDate = new Date().toISOString().substring(0, 10);
2849
- if (config.configPath !== undefined && compatibilityDate === undefined) {
2850
- logger.warn(
2851
- `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
2852
- "Add one to your wrangler.toml file:\n" +
2853
- "```\n" +
2854
- `compatibility_date = "${currentDate}"\n` +
2855
- "```\n" +
2856
- "or pass it in your terminal:\n" +
2857
- "```\n" +
2858
- `--compatibility-date=${currentDate}\n` +
2859
- "```\n" +
2860
- "See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
2861
- );
2862
- }
2863
- return compatibilityDate ?? currentDate;
2864
- }