wrangler 0.0.0-e492c10 → 0.0.0-e4ca780f

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 (360) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +25 -5
  3. package/bin/wrangler.js +174 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1590 -81
  6. package/package.json +198 -149
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +238 -0
  9. package/src/__tests__/api-devregistry.test.ts +121 -0
  10. package/src/__tests__/api.test.ts +102 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +30 -24
  13. package/src/__tests__/configuration.test.ts +4498 -3114
  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 +157 -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 +1592 -802
  21. package/src/__tests__/generate.test.ts +237 -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 +104 -55
  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 -224
  65. package/src/__tests__/init.test.ts +3168 -1488
  66. package/src/__tests__/jest.setup.ts +152 -50
  67. package/src/__tests__/kv.test.ts +1789 -1432
  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 +588 -0
  74. package/src/__tests__/package-manager.test.ts +312 -165
  75. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  76. package/src/__tests__/pages/functions-build.test.ts +452 -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 +955 -0
  83. package/src/__tests__/parse.test.ts +358 -248
  84. package/src/__tests__/paths.test.ts +39 -0
  85. package/src/__tests__/publish.test.ts +8322 -4847
  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 -205
  89. package/src/__tests__/route.test.ts +18 -18
  90. package/src/__tests__/secret.test.ts +683 -436
  91. package/src/__tests__/tail.test.ts +835 -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__/user.test.ts +107 -120
  99. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  100. package/src/__tests__/validate-dev-props.test.ts +56 -0
  101. package/src/__tests__/version.test.ts +35 -0
  102. package/src/__tests__/whoami.test.tsx +165 -98
  103. package/src/__tests__/worker-namespace.test.ts +340 -0
  104. package/src/abort.d.ts +3 -0
  105. package/src/api/dev.ts +316 -0
  106. package/src/api/index.ts +11 -0
  107. package/src/api/mtls-certificate.ts +148 -0
  108. package/src/api/pages/create-worker-bundle-contents.ts +76 -0
  109. package/src/api/pages/index.ts +5 -0
  110. package/src/api/pages/publish.tsx +355 -0
  111. package/src/bundle-reporter.ts +68 -0
  112. package/src/bundle.ts +874 -135
  113. package/src/cfetch/index.ts +123 -69
  114. package/src/cfetch/internal.ts +217 -96
  115. package/src/cli.ts +23 -8
  116. package/src/config/config.ts +244 -196
  117. package/src/config/diagnostics.ts +61 -61
  118. package/src/config/environment.ts +563 -339
  119. package/src/config/index.ts +381 -41
  120. package/src/config/validation-helpers.ts +379 -357
  121. package/src/config/validation.ts +2181 -1263
  122. package/src/config-cache.ts +81 -41
  123. package/src/create-worker-preview.ts +250 -132
  124. package/src/create-worker-upload-form.ts +343 -224
  125. package/src/d1/backups.tsx +219 -0
  126. package/src/d1/constants.ts +2 -0
  127. package/src/d1/create.tsx +68 -0
  128. package/src/d1/delete.ts +53 -0
  129. package/src/d1/execute.tsx +357 -0
  130. package/src/d1/formatTimeAgo.ts +14 -0
  131. package/src/d1/index.ts +100 -0
  132. package/src/d1/list.tsx +60 -0
  133. package/src/d1/migrations/apply.tsx +212 -0
  134. package/src/d1/migrations/create.tsx +79 -0
  135. package/src/d1/migrations/helpers.ts +172 -0
  136. package/src/d1/migrations/index.ts +3 -0
  137. package/src/d1/migrations/list.tsx +95 -0
  138. package/src/d1/migrations/options.ts +23 -0
  139. package/src/d1/options.ts +22 -0
  140. package/src/d1/splitter.ts +161 -0
  141. package/src/d1/types.ts +25 -0
  142. package/src/d1/utils.ts +49 -0
  143. package/src/delete.ts +100 -0
  144. package/src/deployments.ts +368 -0
  145. package/src/deprecated/index.ts +144 -0
  146. package/src/dev/dev-vars.ts +20 -17
  147. package/src/dev/dev.tsx +535 -353
  148. package/src/dev/get-local-persistence-path.ts +31 -0
  149. package/src/dev/local.tsx +900 -292
  150. package/src/dev/remote.tsx +620 -201
  151. package/src/dev/start-server.ts +534 -0
  152. package/src/dev/use-esbuild.ts +182 -97
  153. package/src/dev/validate-dev-props.ts +40 -0
  154. package/src/dev-registry.ts +202 -0
  155. package/src/dev.tsx +929 -0
  156. package/src/dialogs.ts +136 -0
  157. package/src/dispatch-namespace.ts +211 -0
  158. package/src/docs/index.ts +97 -0
  159. package/src/durable.ts +102 -0
  160. package/src/entry.ts +259 -189
  161. package/src/environment-variables/factory.ts +88 -0
  162. package/src/environment-variables/misc-variables.ts +30 -0
  163. package/src/errors.ts +6 -6
  164. package/src/generate/index.ts +298 -0
  165. package/src/git-client.ts +135 -0
  166. package/src/global-wrangler-config-path.ts +26 -0
  167. package/src/https-options.ts +84 -80
  168. package/src/index.ts +758 -0
  169. package/src/init.ts +1032 -0
  170. package/src/inspect.ts +721 -562
  171. package/src/intl-polyfill.d.ts +123 -123
  172. package/src/is-ci.ts +14 -0
  173. package/src/is-interactive.ts +16 -0
  174. package/src/jest.d.ts +4 -0
  175. package/src/kv/helpers.ts +430 -0
  176. package/src/kv/index.ts +594 -0
  177. package/src/logger.ts +96 -43
  178. package/src/metrics/index.ts +5 -0
  179. package/src/metrics/metrics-config.ts +239 -0
  180. package/src/metrics/metrics-dispatcher.ts +96 -0
  181. package/src/metrics/metrics-usage-headers.ts +24 -0
  182. package/src/metrics/send-event.ts +99 -0
  183. package/src/miniflare-cli/assets.ts +251 -0
  184. package/src/miniflare-cli/index.ts +202 -33
  185. package/src/miniflare-cli/request-context.ts +18 -18
  186. package/src/miniflare-cli/tsconfig.json +9 -0
  187. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  188. package/src/miniflare-cli/types.ts +11 -0
  189. package/src/module-collection.ts +290 -215
  190. package/src/mtls-certificate/cli.ts +155 -0
  191. package/src/open-in-browser.ts +5 -14
  192. package/src/package-manager.ts +182 -90
  193. package/src/pages/build.ts +410 -0
  194. package/src/pages/buildFunctions.ts +140 -0
  195. package/src/pages/constants.ts +18 -0
  196. package/src/pages/deployment-tails.ts +281 -0
  197. package/src/pages/deployments.tsx +84 -0
  198. package/src/pages/dev.ts +716 -0
  199. package/src/pages/errors.ts +67 -0
  200. package/src/pages/functions/buildPlugin.ts +113 -0
  201. package/src/pages/functions/buildWorker.ts +291 -0
  202. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  203. package/src/pages/functions/filepath-routing.ts +189 -0
  204. package/src/pages/functions/identifiers.ts +78 -0
  205. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  206. package/src/pages/functions/routes-consolidation.ts +73 -0
  207. package/src/pages/functions/routes-transformation.test.ts +282 -0
  208. package/src/pages/functions/routes-transformation.ts +115 -0
  209. package/src/pages/functions/routes-validation.test.ts +403 -0
  210. package/src/pages/functions/routes-validation.ts +202 -0
  211. package/src/pages/functions/routes.ts +151 -0
  212. package/src/pages/functions/tsconfig.json +8 -0
  213. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  214. package/src/pages/functions.ts +86 -0
  215. package/src/pages/hash.ts +13 -0
  216. package/src/pages/index.ts +102 -0
  217. package/src/pages/projects.tsx +159 -0
  218. package/src/pages/prompt-select-project.tsx +31 -0
  219. package/src/pages/publish.tsx +267 -0
  220. package/src/pages/types.ts +46 -0
  221. package/src/pages/upload.tsx +469 -0
  222. package/src/pages/utils.ts +23 -0
  223. package/src/parse.ts +246 -123
  224. package/src/paths.ts +53 -8
  225. package/src/proxy.ts +628 -383
  226. package/src/publish/index.ts +274 -0
  227. package/src/publish/publish.ts +1060 -0
  228. package/src/pubsub/index.ts +286 -0
  229. package/src/pubsub/pubsub-commands.ts +623 -0
  230. package/src/queues/cli/commands/consumer/add.ts +71 -0
  231. package/src/queues/cli/commands/consumer/index.ts +19 -0
  232. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  233. package/src/queues/cli/commands/create.ts +25 -0
  234. package/src/queues/cli/commands/delete.ts +26 -0
  235. package/src/queues/cli/commands/index.ts +35 -0
  236. package/src/queues/cli/commands/list.ts +25 -0
  237. package/src/queues/client.ts +136 -0
  238. package/src/queues/utils.ts +18 -0
  239. package/src/r2/constants.ts +4 -0
  240. package/src/r2/helpers.ts +132 -0
  241. package/src/r2/index.ts +289 -0
  242. package/src/routes.ts +140 -0
  243. package/src/secret/index.ts +376 -0
  244. package/src/selfsigned.d.ts +23 -23
  245. package/src/sites.ts +372 -0
  246. package/src/tail/createTail.ts +406 -0
  247. package/src/tail/filters.ts +109 -111
  248. package/src/tail/index.ts +208 -296
  249. package/src/tail/printing.ts +101 -46
  250. package/src/traverse-module-graph.ts +53 -0
  251. package/src/tsconfig-sanity.ts +16 -0
  252. package/src/type-generation.ts +181 -0
  253. package/src/update-check.ts +11 -11
  254. package/src/user/access.ts +68 -0
  255. package/src/user/auth-variables.ts +113 -0
  256. package/src/user/choose-account.tsx +39 -0
  257. package/src/user/generate-auth-url.ts +33 -0
  258. package/src/user/generate-random-state.ts +16 -0
  259. package/src/user/index.ts +2 -0
  260. package/src/user/user.ts +1233 -0
  261. package/src/utils/collectKeyValues.ts +14 -0
  262. package/src/utils/render.ts +93 -0
  263. package/src/whoami.ts +135 -0
  264. package/src/worker.ts +203 -101
  265. package/src/yargs-types.ts +37 -0
  266. package/src/zones.ts +191 -0
  267. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  268. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  269. package/templates/__tests__/tsconfig.json +8 -0
  270. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  271. package/templates/checked-fetch.js +23 -0
  272. package/templates/d1-beta-facade.js +244 -0
  273. package/templates/facade.d.ts +14 -0
  274. package/templates/first-party-worker-module-facade.ts +19 -0
  275. package/templates/format-dev-errors.ts +34 -0
  276. package/templates/gitignore +1 -0
  277. package/templates/init-tests/test-jest-new-worker.js +23 -0
  278. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  279. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  280. package/templates/middleware/common.ts +62 -0
  281. package/templates/middleware/loader-modules.ts +84 -0
  282. package/templates/middleware/loader-sw.ts +233 -0
  283. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  284. package/templates/middleware/middleware-pretty-error.ts +40 -0
  285. package/templates/middleware/middleware-scheduled.ts +15 -0
  286. package/templates/new-worker-scheduled.js +17 -0
  287. package/templates/new-worker-scheduled.ts +32 -0
  288. package/templates/new-worker.js +3 -3
  289. package/templates/new-worker.ts +21 -3
  290. package/templates/no-op-worker.js +10 -0
  291. package/templates/pages-dev-pipeline.ts +31 -0
  292. package/templates/pages-dev-util.ts +52 -0
  293. package/templates/pages-shim.ts +12 -0
  294. package/templates/pages-template-plugin.ts +180 -0
  295. package/templates/pages-template-worker.ts +189 -0
  296. package/templates/serve-static-assets.ts +66 -0
  297. package/templates/service-bindings-module-facade.js +55 -0
  298. package/templates/service-bindings-sw-facade.js +42 -0
  299. package/templates/tsconfig-sanity.ts +11 -0
  300. package/templates/tsconfig.init.json +105 -0
  301. package/templates/tsconfig.json +6 -103
  302. package/templates/tsconfig.tsbuildinfo +1 -0
  303. package/wrangler-dist/cli.d.ts +1641 -0
  304. package/wrangler-dist/cli.js +129145 -89350
  305. package/wrangler-dist/wasm-sync.wasm +0 -0
  306. package/pages/functions/buildPlugin.ts +0 -92
  307. package/pages/functions/buildWorker.ts +0 -138
  308. package/pages/functions/filepath-routing.ts +0 -189
  309. package/pages/functions/identifiers.ts +0 -78
  310. package/pages/functions/routes.ts +0 -156
  311. package/pages/functions/template-plugin.ts +0 -146
  312. package/pages/functions/template-worker.ts +0 -143
  313. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  314. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  315. package/src/__tests__/pages.test.ts +0 -327
  316. package/src/dialogs.tsx +0 -87
  317. package/src/environment-variables.ts +0 -35
  318. package/src/index.tsx +0 -2698
  319. package/src/kv.ts +0 -319
  320. package/src/miniflare-cli/enum-keys.ts +0 -17
  321. package/src/pages.tsx +0 -1875
  322. package/src/publish.ts +0 -469
  323. package/src/r2.ts +0 -50
  324. package/src/sites.tsx +0 -293
  325. package/src/user.tsx +0 -1203
  326. package/src/whoami.tsx +0 -70
  327. package/templates/static-asset-facade.js +0 -47
  328. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  329. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  330. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  331. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  332. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  333. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  334. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  335. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  336. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  337. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  338. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  339. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  340. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  341. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  342. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  343. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  344. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  345. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  346. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  347. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  348. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  349. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  350. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  351. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  352. package/vendor/wrangler-mime/LICENSE +0 -21
  353. package/vendor/wrangler-mime/Mime.js +0 -97
  354. package/vendor/wrangler-mime/README.md +0 -187
  355. package/vendor/wrangler-mime/cli.js +0 -46
  356. package/vendor/wrangler-mime/index.js +0 -4
  357. package/vendor/wrangler-mime/lite.js +0 -4
  358. package/vendor/wrangler-mime/package.json +0 -52
  359. package/vendor/wrangler-mime/types/other.js +0 -1
  360. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/pages.tsx DELETED
@@ -1,1875 +0,0 @@
1
- /* eslint-disable no-shadow */
2
-
3
- import { execSync, spawn } from "node:child_process";
4
- import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
- import { readdir, readFile, stat } from "node:fs/promises";
6
- import { tmpdir } from "node:os";
7
- import { dirname, join, sep } from "node:path";
8
- import { cwd } from "node:process";
9
- import { URL } from "node:url";
10
- import { hash } from "blake3-wasm";
11
- import { watch } from "chokidar";
12
- import { render, Text } from "ink";
13
- import SelectInput from "ink-select-input";
14
- import Spinner from "ink-spinner";
15
- import Table from "ink-table";
16
- import { getType } from "mime";
17
- import prettyBytes from "pretty-bytes";
18
- import React from "react";
19
- import { format as timeagoFormat } from "timeago.js";
20
- import { File, FormData } from "undici";
21
- import { buildPlugin } from "../pages/functions/buildPlugin";
22
- import { buildWorker } from "../pages/functions/buildWorker";
23
- import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
24
- import { writeRoutesModule } from "../pages/functions/routes";
25
- import { fetchResult } from "./cfetch";
26
- import { getConfigCache, saveToConfigCache } from "./config-cache";
27
- import { prompt } from "./dialogs";
28
- import { FatalError } from "./errors";
29
- import { logger } from "./logger";
30
- import { getRequestContextCheckOptions } from "./miniflare-cli/request-context";
31
- import openInBrowser from "./open-in-browser";
32
- import { toUrlPath } from "./paths";
33
- import { requireAuth } from "./user";
34
- import type { Config } from "../pages/functions/routes";
35
- import type { Headers, Request, fetch } from "@miniflare/core";
36
- import type { BuildResult } from "esbuild";
37
- import type { MiniflareOptions } from "miniflare";
38
- import type { BuilderCallback, CommandModule } from "yargs";
39
-
40
- export type Project = {
41
- name: string;
42
- subdomain: string;
43
- domains: Array<string>;
44
- source?: {
45
- type: string;
46
- };
47
- latest_deployment?: {
48
- modified_on: string;
49
- };
50
- created_on: string;
51
- production_branch: string;
52
- };
53
-
54
- export type Deployment = {
55
- id: string;
56
- environment: string;
57
- deployment_trigger: {
58
- metadata: {
59
- commit_hash: string;
60
- branch: string;
61
- };
62
- };
63
- url: string;
64
- latest_stage: {
65
- status: string;
66
- ended_on: string;
67
- };
68
- project_name: string;
69
- };
70
-
71
- interface PagesConfigCache {
72
- account_id?: string;
73
- project_name?: string;
74
- }
75
-
76
- const PAGES_CONFIG_CACHE_FILENAME = "pages.json";
77
-
78
- // Defer importing miniflare until we really need it. This takes ~0.5s
79
- // and also modifies some `stream/web` and `undici` prototypes, so we
80
- // don't want to do this if pages commands aren't being called.
81
-
82
- export const pagesBetaWarning =
83
- "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
84
-
85
- const isInPagesCI = !!process.env.CF_PAGES;
86
-
87
- const CLEANUP_CALLBACKS: (() => void)[] = [];
88
- const CLEANUP = () => {
89
- CLEANUP_CALLBACKS.forEach((callback) => callback());
90
- RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
91
- };
92
-
93
- process.on("SIGINT", () => {
94
- CLEANUP();
95
- process.exit();
96
- });
97
- process.on("SIGTERM", () => {
98
- CLEANUP();
99
- process.exit();
100
- });
101
-
102
- function isWindows() {
103
- return process.platform === "win32";
104
- }
105
-
106
- const SECONDS_TO_WAIT_FOR_PROXY = 5;
107
-
108
- async function sleep(ms: number) {
109
- await new Promise((resolve) => setTimeout(resolve, ms));
110
- }
111
-
112
- function getPids(pid: number) {
113
- const pids: number[] = [pid];
114
- let command: string, regExp: RegExp;
115
-
116
- if (isWindows()) {
117
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
118
- regExp = new RegExp(/(\d+)/);
119
- } else {
120
- command = `pgrep -P ${pid}`;
121
- regExp = new RegExp(/(\d+)/);
122
- }
123
-
124
- try {
125
- const newPids = (
126
- execSync(command)
127
- .toString()
128
- .split("\n")
129
- .map((line) => line.match(regExp))
130
- .filter((line) => line !== null) as RegExpExecArray[]
131
- ).map((match) => parseInt(match[1]));
132
-
133
- pids.push(...newPids.map(getPids).flat());
134
- } catch {}
135
-
136
- return pids;
137
- }
138
-
139
- function getPort(pid: number) {
140
- let command: string, regExp: RegExp;
141
-
142
- if (isWindows()) {
143
- command = "\\windows\\system32\\netstat.exe -nao";
144
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
145
- } else {
146
- command = "lsof -nPi";
147
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
148
- }
149
-
150
- try {
151
- const matches = execSync(command)
152
- .toString()
153
- .split("\n")
154
- .map((line) => line.match(regExp))
155
- .filter((line) => line !== null) as RegExpExecArray[];
156
-
157
- const match = matches[0];
158
- if (match) return parseInt(match[1]);
159
- } catch (thrown) {
160
- logger.error(
161
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
162
- );
163
- }
164
- }
165
-
166
- async function spawnProxyProcess({
167
- port,
168
- command,
169
- }: {
170
- port?: number;
171
- command: (string | number)[];
172
- }): Promise<void | number> {
173
- if (command.length === 0) {
174
- CLEANUP();
175
- throw new FatalError(
176
- "Must specify a directory of static assets to serve or a command to run.",
177
- 1
178
- );
179
- }
180
-
181
- logger.log(`Running ${command.join(" ")}...`);
182
- const proxy = spawn(
183
- command[0].toString(),
184
- command.slice(1).map((value) => value.toString()),
185
- {
186
- shell: isWindows(),
187
- env: {
188
- BROWSER: "none",
189
- ...process.env,
190
- },
191
- }
192
- );
193
- CLEANUP_CALLBACKS.push(() => {
194
- proxy.kill();
195
- });
196
-
197
- proxy.stdout.on("data", (data) => {
198
- logger.log(`[proxy]: ${data}`);
199
- });
200
-
201
- proxy.stderr.on("data", (data) => {
202
- logger.error(`[proxy]: ${data}`);
203
- });
204
-
205
- proxy.on("close", (code) => {
206
- logger.error(`Proxy exited with status ${code}.`);
207
- });
208
-
209
- // Wait for proxy process to start...
210
- while (!proxy.pid) {}
211
-
212
- if (port === undefined) {
213
- logger.log(
214
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
215
- );
216
- logger.log("To skip, specify the proxy port with --proxy.");
217
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
218
-
219
- port = getPids(proxy.pid)
220
- .map(getPort)
221
- .filter((port) => port !== undefined)[0];
222
-
223
- if (port === undefined) {
224
- CLEANUP();
225
- throw new FatalError(
226
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
227
- 1
228
- );
229
- } else {
230
- logger.log(`Automatically determined the proxy port to be ${port}.`);
231
- }
232
- }
233
-
234
- return port;
235
- }
236
-
237
- function escapeRegex(str: string) {
238
- return str.replace(/[-/\\^$*+?.()|[]{}]/g, "\\$&");
239
- }
240
-
241
- type Replacements = Record<string, string>;
242
-
243
- function replacer(str: string, replacements: Replacements) {
244
- for (const [replacement, value] of Object.entries(replacements)) {
245
- str = str.replace(`:${replacement}`, value);
246
- }
247
- return str;
248
- }
249
-
250
- function generateRulesMatcher<T>(
251
- rules?: Record<string, T>,
252
- replacer: (match: T, replacements: Replacements) => T = (match) => match
253
- ) {
254
- // TODO: How can you test cross-host rules?
255
- if (!rules) return () => [];
256
-
257
- const compiledRules = Object.entries(rules)
258
- .map(([rule, match]) => {
259
- const crossHost = rule.startsWith("https://");
260
-
261
- rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
262
-
263
- const host_matches = rule.matchAll(
264
- /(?<=^https:\\\/\\\/[^/]*?):([^\\]+)(?=\\)/g
265
- );
266
- for (const match of host_matches) {
267
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/.]+)`);
268
- }
269
-
270
- const path_matches = rule.matchAll(/:(\w+)/g);
271
- for (const match of path_matches) {
272
- rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);
273
- }
274
-
275
- rule = "^" + rule + "$";
276
-
277
- try {
278
- const regExp = new RegExp(rule);
279
- return [{ crossHost, regExp }, match];
280
- } catch {}
281
- })
282
- .filter((value) => value !== undefined) as [
283
- { crossHost: boolean; regExp: RegExp },
284
- T
285
- ][];
286
-
287
- return ({ request }: { request: Request }) => {
288
- const { pathname, host } = new URL(request.url);
289
-
290
- return compiledRules
291
- .map(([{ crossHost, regExp }, match]) => {
292
- const test = crossHost ? `https://${host}${pathname}` : pathname;
293
- const result = regExp.exec(test);
294
- if (result) {
295
- return replacer(match, result.groups || {});
296
- }
297
- })
298
- .filter((value) => value !== undefined) as T[];
299
- };
300
- }
301
-
302
- function generateHeadersMatcher(headersFile: string) {
303
- if (existsSync(headersFile)) {
304
- const contents = readFileSync(headersFile).toString();
305
-
306
- // TODO: Log errors
307
- const lines = contents
308
- .split("\n")
309
- .map((line) => line.trim())
310
- .filter((line) => !line.startsWith("#") && line !== "");
311
-
312
- const rules: Record<string, Record<string, string>> = {};
313
- let rule: { path: string; headers: Record<string, string> } | undefined =
314
- undefined;
315
-
316
- for (const line of lines) {
317
- if (/^([^\s]+:\/\/|^\/)/.test(line)) {
318
- if (rule && Object.keys(rule.headers).length > 0) {
319
- rules[rule.path] = rule.headers;
320
- }
321
-
322
- const path = validateURL(line);
323
- if (path) {
324
- rule = {
325
- path,
326
- headers: {},
327
- };
328
- continue;
329
- }
330
- }
331
-
332
- if (!line.includes(":")) continue;
333
-
334
- const [rawName, ...rawValue] = line.split(":");
335
- const name = rawName.trim().toLowerCase();
336
- const value = rawValue.join(":").trim();
337
-
338
- if (name === "") continue;
339
- if (!rule) continue;
340
-
341
- const existingValues = rule.headers[name];
342
- rule.headers[name] = existingValues
343
- ? `${existingValues}, ${value}`
344
- : value;
345
- }
346
-
347
- if (rule && Object.keys(rule.headers).length > 0) {
348
- rules[rule.path] = rule.headers;
349
- }
350
-
351
- const rulesMatcher = generateRulesMatcher(rules, (match, replacements) =>
352
- Object.fromEntries(
353
- Object.entries(match).map(([name, value]) => [
354
- name,
355
- replacer(value, replacements),
356
- ])
357
- )
358
- );
359
-
360
- return (request: Request) => {
361
- const matches = rulesMatcher({
362
- request,
363
- });
364
- if (matches) return matches;
365
- };
366
- } else {
367
- return () => undefined;
368
- }
369
- }
370
-
371
- function generateRedirectsMatcher(redirectsFile: string) {
372
- if (existsSync(redirectsFile)) {
373
- const contents = readFileSync(redirectsFile).toString();
374
-
375
- // TODO: Log errors
376
- const lines = contents
377
- .split("\n")
378
- .map((line) => line.trim())
379
- .filter((line) => !line.startsWith("#") && line !== "");
380
-
381
- const rules = Object.fromEntries(
382
- lines
383
- .map((line) => line.split(" "))
384
- .filter((tokens) => tokens.length === 2 || tokens.length === 3)
385
- .map((tokens) => {
386
- const from = validateURL(tokens[0], true, false, false);
387
- const to = validateURL(tokens[1], false, true, true);
388
- let status: number | undefined = parseInt(tokens[2]) || 302;
389
- status = [301, 302, 303, 307, 308].includes(status)
390
- ? status
391
- : undefined;
392
-
393
- return from && to && status ? [from, { to, status }] : undefined;
394
- })
395
- .filter((rule) => rule !== undefined) as [
396
- string,
397
- { to: string; status?: number }
398
- ][]
399
- );
400
-
401
- const rulesMatcher = generateRulesMatcher(
402
- rules,
403
- ({ status, to }, replacements) => ({
404
- status,
405
- to: replacer(to, replacements),
406
- })
407
- );
408
-
409
- return (request: Request) => {
410
- const match = rulesMatcher({
411
- request,
412
- })[0];
413
- if (match) return match;
414
- };
415
- } else {
416
- return () => undefined;
417
- }
418
- }
419
-
420
- function extractPathname(
421
- path = "/",
422
- includeSearch: boolean,
423
- includeHash: boolean
424
- ) {
425
- if (!path.startsWith("/")) path = `/${path}`;
426
- const url = new URL(`//${path}`, "relative://");
427
- return `${url.pathname}${includeSearch ? url.search : ""}${
428
- includeHash ? url.hash : ""
429
- }`;
430
- }
431
-
432
- function validateURL(
433
- token: string,
434
- onlyRelative = false,
435
- includeSearch = false,
436
- includeHash = false
437
- ) {
438
- const host = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/.exec(token);
439
- if (host && host.groups && host.groups.host) {
440
- if (onlyRelative) return;
441
-
442
- return `https://${host.groups.host}${extractPathname(
443
- host.groups.path,
444
- includeSearch,
445
- includeHash
446
- )}`;
447
- } else {
448
- if (!token.startsWith("/") && onlyRelative) token = `/${token}`;
449
-
450
- const path = /^\//.exec(token);
451
- if (path) {
452
- try {
453
- return extractPathname(token, includeSearch, includeHash);
454
- } catch {}
455
- }
456
- }
457
- return "";
458
- }
459
-
460
- function hasFileExtension(pathname: string) {
461
- return /\/.+\.[a-z0-9]+$/i.test(pathname);
462
- }
463
-
464
- async function generateAssetsFetch(directory: string): Promise<typeof fetch> {
465
- // Defer importing miniflare until we really need it
466
- const { Headers, Request, Response } = await import("@miniflare/core");
467
-
468
- const headersFile = join(directory, "_headers");
469
- const redirectsFile = join(directory, "_redirects");
470
- const workerFile = join(directory, "_worker.js");
471
-
472
- const ignoredFiles = [headersFile, redirectsFile, workerFile];
473
-
474
- const assetExists = (path: string) => {
475
- path = join(directory, path);
476
- return (
477
- existsSync(path) &&
478
- lstatSync(path).isFile() &&
479
- !ignoredFiles.includes(path)
480
- );
481
- };
482
-
483
- const getAsset = (path: string) => {
484
- if (assetExists(path)) {
485
- return join(directory, path);
486
- }
487
- };
488
-
489
- let redirectsMatcher = generateRedirectsMatcher(redirectsFile);
490
- let headersMatcher = generateHeadersMatcher(headersFile);
491
-
492
- watch([headersFile, redirectsFile], {
493
- persistent: true,
494
- }).on("change", (path) => {
495
- switch (path) {
496
- case headersFile: {
497
- logger.log("_headers modified. Re-evaluating...");
498
- headersMatcher = generateHeadersMatcher(headersFile);
499
- break;
500
- }
501
- case redirectsFile: {
502
- logger.log("_redirects modified. Re-evaluating...");
503
- redirectsMatcher = generateRedirectsMatcher(redirectsFile);
504
- break;
505
- }
506
- }
507
- });
508
-
509
- const serveAsset = (file: string) => {
510
- return readFileSync(file);
511
- };
512
-
513
- const generateResponse = (request: Request) => {
514
- const url = new URL(request.url);
515
-
516
- const deconstructedResponse: {
517
- status: number;
518
- headers: Headers;
519
- body?: Buffer;
520
- } = {
521
- status: 200,
522
- headers: new Headers(),
523
- body: undefined,
524
- };
525
-
526
- const match = redirectsMatcher(request);
527
- if (match) {
528
- const { status, to } = match;
529
-
530
- let location = to;
531
- let search;
532
-
533
- if (to.startsWith("/")) {
534
- search = new URL(location, "http://fakehost").search;
535
- } else {
536
- search = new URL(location).search;
537
- }
538
-
539
- location = `${location}${search ? "" : url.search}`;
540
-
541
- if (status && [301, 302, 303, 307, 308].includes(status)) {
542
- deconstructedResponse.status = status;
543
- } else {
544
- deconstructedResponse.status = 302;
545
- }
546
-
547
- deconstructedResponse.headers.set("Location", location);
548
- return deconstructedResponse;
549
- }
550
-
551
- if (!request.method?.match(/^(get|head)$/i)) {
552
- deconstructedResponse.status = 405;
553
- return deconstructedResponse;
554
- }
555
-
556
- const notFound = () => {
557
- let cwd = url.pathname;
558
- while (cwd) {
559
- cwd = cwd.slice(0, cwd.lastIndexOf("/"));
560
-
561
- if ((asset = getAsset(`${cwd}/404.html`))) {
562
- deconstructedResponse.status = 404;
563
- deconstructedResponse.body = serveAsset(asset);
564
- deconstructedResponse.headers.set(
565
- "Content-Type",
566
- getType(asset) || "application/octet-stream"
567
- );
568
- return deconstructedResponse;
569
- }
570
- }
571
-
572
- if ((asset = getAsset(`/index.html`))) {
573
- deconstructedResponse.body = serveAsset(asset);
574
- deconstructedResponse.headers.set(
575
- "Content-Type",
576
- getType(asset) || "application/octet-stream"
577
- );
578
- return deconstructedResponse;
579
- }
580
-
581
- deconstructedResponse.status = 404;
582
- return deconstructedResponse;
583
- };
584
-
585
- let asset;
586
-
587
- if (url.pathname.endsWith("/")) {
588
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
589
- deconstructedResponse.body = serveAsset(asset);
590
- deconstructedResponse.headers.set(
591
- "Content-Type",
592
- getType(asset) || "application/octet-stream"
593
- );
594
- return deconstructedResponse;
595
- } else if (
596
- (asset = getAsset(`${url.pathname.replace(/\/$/, ".html")}`))
597
- ) {
598
- deconstructedResponse.status = 301;
599
- deconstructedResponse.headers.set(
600
- "Location",
601
- `${url.pathname.slice(0, -1)}${url.search}`
602
- );
603
- return deconstructedResponse;
604
- }
605
- }
606
-
607
- if (url.pathname.endsWith("/index")) {
608
- deconstructedResponse.status = 301;
609
- deconstructedResponse.headers.set(
610
- "Location",
611
- `${url.pathname.slice(0, -"index".length)}${url.search}`
612
- );
613
- return deconstructedResponse;
614
- }
615
-
616
- if ((asset = getAsset(url.pathname))) {
617
- if (url.pathname.endsWith(".html")) {
618
- const extensionlessPath = url.pathname.slice(0, -".html".length);
619
- if (getAsset(extensionlessPath) || extensionlessPath === "/") {
620
- deconstructedResponse.body = serveAsset(asset);
621
- deconstructedResponse.headers.set(
622
- "Content-Type",
623
- getType(asset) || "application/octet-stream"
624
- );
625
- return deconstructedResponse;
626
- } else {
627
- deconstructedResponse.status = 301;
628
- deconstructedResponse.headers.set(
629
- "Location",
630
- `${extensionlessPath}${url.search}`
631
- );
632
- return deconstructedResponse;
633
- }
634
- } else {
635
- deconstructedResponse.body = serveAsset(asset);
636
- deconstructedResponse.headers.set(
637
- "Content-Type",
638
- getType(asset) || "application/octet-stream"
639
- );
640
- return deconstructedResponse;
641
- }
642
- } else if (hasFileExtension(url.pathname)) {
643
- notFound();
644
- return deconstructedResponse;
645
- }
646
-
647
- if ((asset = getAsset(`${url.pathname}.html`))) {
648
- deconstructedResponse.body = serveAsset(asset);
649
- deconstructedResponse.headers.set(
650
- "Content-Type",
651
- getType(asset) || "application/octet-stream"
652
- );
653
- return deconstructedResponse;
654
- }
655
-
656
- if ((asset = getAsset(`${url.pathname}/index.html`))) {
657
- deconstructedResponse.status = 301;
658
- deconstructedResponse.headers.set(
659
- "Location",
660
- `${url.pathname}/${url.search}`
661
- );
662
- return deconstructedResponse;
663
- } else {
664
- notFound();
665
- return deconstructedResponse;
666
- }
667
- };
668
-
669
- const attachHeaders = (
670
- request: Request,
671
- deconstructedResponse: { status: number; headers: Headers; body?: Buffer }
672
- ) => {
673
- const headers = deconstructedResponse.headers;
674
- const newHeaders = new Headers({});
675
- const matches = headersMatcher(request) || [];
676
-
677
- matches.forEach((match) => {
678
- Object.entries(match).forEach(([name, value]) => {
679
- newHeaders.append(name, `${value}`);
680
- });
681
- });
682
-
683
- const combinedHeaders = {
684
- ...Object.fromEntries(headers.entries()),
685
- ...Object.fromEntries(newHeaders.entries()),
686
- };
687
-
688
- deconstructedResponse.headers = new Headers({});
689
- Object.entries(combinedHeaders).forEach(([name, value]) => {
690
- if (value) deconstructedResponse.headers.set(name, value);
691
- });
692
- };
693
-
694
- return async (input, init) => {
695
- const request = new Request(input, init);
696
- const deconstructedResponse = generateResponse(request);
697
- attachHeaders(request, deconstructedResponse);
698
-
699
- const headers = new Headers();
700
-
701
- [...deconstructedResponse.headers.entries()].forEach(([name, value]) => {
702
- if (value) headers.set(name, value);
703
- });
704
-
705
- return new Response(deconstructedResponse.body, {
706
- headers,
707
- status: deconstructedResponse.status,
708
- });
709
- };
710
- }
711
-
712
- const RUNNING_BUILDERS: BuildResult[] = [];
713
-
714
- async function buildFunctions({
715
- outfile,
716
- outputConfigPath,
717
- functionsDirectory,
718
- minify = false,
719
- sourcemap = false,
720
- fallbackService = "ASSETS",
721
- watch = false,
722
- onEnd,
723
- plugin = false,
724
- buildOutputDirectory,
725
- }: {
726
- outfile: string;
727
- outputConfigPath?: string;
728
- functionsDirectory: string;
729
- minify?: boolean;
730
- sourcemap?: boolean;
731
- fallbackService?: string;
732
- watch?: boolean;
733
- onEnd?: () => void;
734
- plugin?: boolean;
735
- buildOutputDirectory?: string;
736
- }) {
737
- RUNNING_BUILDERS.forEach(
738
- (runningBuilder) => runningBuilder.stop && runningBuilder.stop()
739
- );
740
-
741
- const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
742
- const baseURL = toUrlPath("/");
743
-
744
- const config: Config = await generateConfigFromFileTree({
745
- baseDir: functionsDirectory,
746
- baseURL,
747
- });
748
-
749
- if (outputConfigPath) {
750
- writeFileSync(
751
- outputConfigPath,
752
- JSON.stringify({ ...config, baseURL }, null, 2)
753
- );
754
- }
755
-
756
- await writeRoutesModule({
757
- config,
758
- srcDir: functionsDirectory,
759
- outfile: routesModule,
760
- });
761
-
762
- if (plugin) {
763
- RUNNING_BUILDERS.push(
764
- await buildPlugin({
765
- routesModule,
766
- outfile,
767
- minify,
768
- sourcemap,
769
- watch,
770
- onEnd,
771
- })
772
- );
773
- } else {
774
- RUNNING_BUILDERS.push(
775
- await buildWorker({
776
- routesModule,
777
- outfile,
778
- minify,
779
- sourcemap,
780
- fallbackService,
781
- watch,
782
- onEnd,
783
- buildOutputDirectory,
784
- })
785
- );
786
- }
787
- }
788
-
789
- interface CreateDeploymentArgs {
790
- directory: string;
791
- projectName?: string;
792
- branch?: string;
793
- commitHash?: string;
794
- commitMessage?: string;
795
- commitDirty?: boolean;
796
- }
797
-
798
- const createDeployment: CommandModule<
799
- CreateDeploymentArgs,
800
- CreateDeploymentArgs
801
- > = {
802
- describe: "🆙 Publish a directory of static assets as a Pages deployment",
803
- builder: (yargs) => {
804
- return yargs
805
- .positional("directory", {
806
- type: "string",
807
- demandOption: true,
808
- description: "The directory of static files to upload",
809
- })
810
- .options({
811
- "project-name": {
812
- type: "string",
813
- description: "The name of the project you want to deploy to",
814
- },
815
- branch: {
816
- type: "string",
817
- description: "The name of the branch you want to deploy to",
818
- },
819
- "commit-hash": {
820
- type: "string",
821
- description: "The SHA to attach to this deployment",
822
- },
823
- "commit-message": {
824
- type: "string",
825
- description: "The commit message to attach to this deployment",
826
- },
827
- "commit-dirty": {
828
- type: "boolean",
829
- description:
830
- "Whether or not the workspace should be considered dirty for this deployment",
831
- },
832
- })
833
- .epilogue(pagesBetaWarning);
834
- },
835
- handler: async ({
836
- directory,
837
- projectName,
838
- branch,
839
- commitHash,
840
- commitMessage,
841
- commitDirty,
842
- }) => {
843
- if (!directory) {
844
- throw new FatalError("Must specify a directory.", 1);
845
- }
846
-
847
- const config = getConfigCache<PagesConfigCache>(
848
- PAGES_CONFIG_CACHE_FILENAME
849
- );
850
- const accountId = await requireAuth(config);
851
-
852
- projectName ??= config.project_name;
853
-
854
- const isInteractive = process.stdin.isTTY;
855
- if (!projectName && isInteractive) {
856
- const projects = (await listProjects({ accountId })).filter(
857
- (project) => !project.source
858
- );
859
-
860
- let existingOrNew: "existing" | "new" = "new";
861
-
862
- if (projects.length > 0) {
863
- existingOrNew = await new Promise<"new" | "existing">((resolve) => {
864
- const { unmount } = render(
865
- <>
866
- <Text>
867
- No project selected. Would you like to create one or use an
868
- existing project?
869
- </Text>
870
- <SelectInput
871
- items={[
872
- {
873
- key: "new",
874
- label: "Create a new project",
875
- value: "new",
876
- },
877
- {
878
- key: "existing",
879
- label: "Use an existing project",
880
- value: "existing",
881
- },
882
- ]}
883
- onSelect={async (selected) => {
884
- resolve(selected.value as "new" | "existing");
885
- unmount();
886
- }}
887
- />
888
- </>
889
- );
890
- });
891
- }
892
-
893
- switch (existingOrNew) {
894
- case "existing": {
895
- projectName = await new Promise((resolve) => {
896
- const { unmount } = render(
897
- <>
898
- <Text>Select a project:</Text>
899
- <SelectInput
900
- items={projects.map((project) => ({
901
- key: project.name,
902
- label: project.name,
903
- value: project,
904
- }))}
905
- onSelect={async (selected) => {
906
- resolve(selected.value.name);
907
- unmount();
908
- }}
909
- />
910
- </>
911
- );
912
- });
913
- break;
914
- }
915
- case "new": {
916
- projectName = await prompt("Enter the name of your new project:");
917
-
918
- if (!projectName) {
919
- throw new FatalError("Must specify a project name.", 1);
920
- }
921
-
922
- let isGitDir = true;
923
- try {
924
- execSync(`git rev-parse --is-inside-work-tree`, {
925
- stdio: "ignore",
926
- });
927
- } catch (err) {
928
- isGitDir = false;
929
- }
930
-
931
- const productionBranch = await prompt(
932
- "Enter the production branch name:",
933
- "text",
934
- isGitDir
935
- ? execSync(`git rev-parse --abbrev-ref HEAD`).toString().trim()
936
- : "production"
937
- );
938
-
939
- if (!productionBranch) {
940
- throw new FatalError("Must specify a production branch.", 1);
941
- }
942
-
943
- await fetchResult<Project>(`/accounts/${accountId}/pages/projects`, {
944
- method: "POST",
945
- body: JSON.stringify({
946
- name: projectName,
947
- production_branch: productionBranch,
948
- }),
949
- });
950
-
951
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
952
- account_id: accountId,
953
- project_name: projectName,
954
- });
955
-
956
- logger.log(`✨ Successfully created the '${projectName}' project.`);
957
- break;
958
- }
959
- }
960
- }
961
-
962
- if (!projectName) {
963
- throw new FatalError("Must specify a project name.", 1);
964
- }
965
-
966
- // We infer git info by default is not passed in
967
-
968
- let isGitDir = true;
969
- try {
970
- execSync(`git rev-parse --is-inside-work-tree`, {
971
- stdio: "ignore",
972
- });
973
- } catch (err) {
974
- isGitDir = false;
975
- }
976
-
977
- let isGitDirty = false;
978
-
979
- if (isGitDir) {
980
- try {
981
- isGitDirty = Boolean(
982
- execSync(`git status --porcelain`).toString().length
983
- );
984
-
985
- if (!branch) {
986
- branch = execSync(`git rev-parse --abbrev-ref HEAD`)
987
- .toString()
988
- .trim();
989
- }
990
-
991
- if (!commitHash) {
992
- commitHash = execSync(`git rev-parse HEAD`).toString().trim();
993
- }
994
-
995
- if (!commitMessage) {
996
- commitMessage = execSync(`git show -s --format=%B ${commitHash}`)
997
- .toString()
998
- .trim();
999
- }
1000
- } catch (err) {}
1001
-
1002
- if (isGitDirty && !commitDirty) {
1003
- logger.warn(
1004
- `Warning: Your working directory is a git repo and has uncommitted changes\nTo silense this warning, pass in --commit-dirty=true`
1005
- );
1006
- }
1007
-
1008
- if (commitDirty === undefined) {
1009
- commitDirty = isGitDirty;
1010
- }
1011
- }
1012
-
1013
- let builtFunctions: string | undefined = undefined;
1014
- const functionsDirectory = join(cwd(), "functions");
1015
- if (existsSync(functionsDirectory)) {
1016
- const outfile = join(tmpdir(), "./functionsWorker.js");
1017
-
1018
- await new Promise((resolve) =>
1019
- buildFunctions({
1020
- outfile,
1021
- functionsDirectory,
1022
- onEnd: () => resolve(null),
1023
- buildOutputDirectory: dirname(outfile),
1024
- })
1025
- );
1026
-
1027
- builtFunctions = readFileSync(outfile, "utf-8");
1028
- }
1029
-
1030
- type File = {
1031
- content: Buffer;
1032
- metadata: Metadata;
1033
- };
1034
-
1035
- type Metadata = {
1036
- sizeInBytes: number;
1037
- hash: string;
1038
- };
1039
-
1040
- const IGNORE_LIST = [
1041
- "_worker.js",
1042
- "_redirects",
1043
- "_headers",
1044
- ".DS_Store",
1045
- "node_modules",
1046
- ];
1047
-
1048
- const walk = async (
1049
- dir: string,
1050
- fileMap: Map<string, File> = new Map(),
1051
- depth = 0
1052
- ) => {
1053
- const files = await readdir(dir);
1054
-
1055
- await Promise.all(
1056
- files.map(async (file) => {
1057
- const filepath = join(dir, file);
1058
- const filestat = await stat(filepath);
1059
-
1060
- if (IGNORE_LIST.includes(file)) {
1061
- return;
1062
- }
1063
-
1064
- if (filestat.isSymbolicLink()) {
1065
- return;
1066
- }
1067
-
1068
- if (filestat.isDirectory()) {
1069
- fileMap = await walk(filepath, fileMap, depth + 1);
1070
- } else {
1071
- let name;
1072
- if (depth) {
1073
- name = filepath.split(sep).slice(1).join("/");
1074
- } else {
1075
- name = file;
1076
- }
1077
-
1078
- // TODO: Move this to later so we don't hold as much in memory
1079
- const fileContent = await readFile(filepath);
1080
-
1081
- const base64Content = fileContent.toString("base64");
1082
- const extension =
1083
- name.split(".").length > 1 ? name.split(".").at(-1) || "" : "";
1084
-
1085
- const content = base64Content + extension;
1086
-
1087
- if (filestat.size > 25 * 1024 * 1024) {
1088
- throw new Error(
1089
- `Error: Pages only supports files up to ${prettyBytes(
1090
- 25 * 1024 * 1024
1091
- )} in size\n${name} is ${prettyBytes(filestat.size)} in size`
1092
- );
1093
- }
1094
-
1095
- fileMap.set(name, {
1096
- content: fileContent,
1097
- metadata: {
1098
- sizeInBytes: filestat.size,
1099
- hash: hash(content).toString("hex").slice(0, 32),
1100
- },
1101
- });
1102
- }
1103
- })
1104
- );
1105
-
1106
- return fileMap;
1107
- };
1108
-
1109
- const fileMap = await walk(directory);
1110
-
1111
- const start = Date.now();
1112
-
1113
- const files: Array<Promise<void>> = [];
1114
-
1115
- if (fileMap.size > 1000) {
1116
- throw new Error(
1117
- `Error: Pages only supports up to 1,000 files in a deployment at the moment.\nTry a smaller project perhaps?`
1118
- );
1119
- }
1120
-
1121
- let counter = 0;
1122
-
1123
- const { rerender, unmount } = render(
1124
- <Progress done={counter} total={fileMap.size} />
1125
- );
1126
-
1127
- fileMap.forEach((file: File, name: string) => {
1128
- const form = new FormData();
1129
- form.append(
1130
- "file",
1131
- new File([new Uint8Array(file.content.buffer)], name)
1132
- );
1133
-
1134
- // TODO: Consider a retry
1135
-
1136
- const promise = fetchResult<{ id: string }>(
1137
- `/accounts/${accountId}/pages/projects/${projectName}/file`,
1138
- {
1139
- method: "POST",
1140
- body: form,
1141
- }
1142
- ).then((response) => {
1143
- counter++;
1144
- rerender(<Progress done={counter} total={fileMap.size} />);
1145
- if (response.id != file.metadata.hash) {
1146
- throw new Error(
1147
- `Looks like there was an issue uploading '${name}'. Try again perhaps?`
1148
- );
1149
- }
1150
- });
1151
-
1152
- files.push(promise);
1153
- });
1154
-
1155
- await Promise.all(files);
1156
-
1157
- unmount();
1158
-
1159
- const uploadMs = Date.now() - start;
1160
-
1161
- logger.log(
1162
- `✨ Success! Uploaded ${fileMap.size} files ${formatTime(uploadMs)}\n`
1163
- );
1164
-
1165
- const formData = new FormData();
1166
-
1167
- formData.append(
1168
- "manifest",
1169
- JSON.stringify(
1170
- Object.fromEntries(
1171
- [...fileMap.entries()].map(([fileName, file]) => [
1172
- `/${fileName}`,
1173
- file.metadata.hash,
1174
- ])
1175
- )
1176
- )
1177
- );
1178
-
1179
- if (branch) {
1180
- formData.append("branch", branch);
1181
- }
1182
-
1183
- if (commitMessage) {
1184
- formData.append("commit_message", commitMessage);
1185
- }
1186
-
1187
- if (commitHash) {
1188
- formData.append("commit_hash", commitHash);
1189
- }
1190
-
1191
- if (commitDirty !== undefined) {
1192
- formData.append("commit_dirty", commitDirty);
1193
- }
1194
-
1195
- let _headers: string | undefined,
1196
- _redirects: string | undefined,
1197
- _workerJS: string | undefined;
1198
-
1199
- try {
1200
- _headers = readFileSync(join(directory, "_headers"), "utf-8");
1201
- } catch {}
1202
-
1203
- try {
1204
- _redirects = readFileSync(join(directory, "_redirects"), "utf-8");
1205
- } catch {}
1206
-
1207
- try {
1208
- _workerJS = readFileSync(join(directory, "_worker.js"), "utf-8");
1209
- } catch {}
1210
-
1211
- if (_headers) {
1212
- formData.append("_headers", new File([_headers], "_headers"));
1213
- }
1214
-
1215
- if (_redirects) {
1216
- formData.append("_redirects", new File([_redirects], "_redirects"));
1217
- }
1218
-
1219
- if (builtFunctions) {
1220
- formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
1221
- } else if (_workerJS) {
1222
- formData.append("_worker.js", new File([_workerJS], "_worker.js"));
1223
- }
1224
-
1225
- const deploymentResponse = await fetchResult<Deployment>(
1226
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`,
1227
- {
1228
- method: "POST",
1229
- body: formData,
1230
- }
1231
- );
1232
-
1233
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1234
- account_id: accountId,
1235
- project_name: projectName,
1236
- });
1237
-
1238
- logger.log(
1239
- `✨ Deployment complete! Take a peek over at ${deploymentResponse.url}`
1240
- );
1241
- },
1242
- };
1243
-
1244
- export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1245
- return yargs
1246
- .command(
1247
- "dev [directory] [-- command]",
1248
- "🧑‍💻 Develop your full-stack Pages application locally",
1249
- (yargs) => {
1250
- return yargs
1251
- .positional("directory", {
1252
- type: "string",
1253
- demandOption: undefined,
1254
- description: "The directory of static assets to serve",
1255
- })
1256
- .positional("command", {
1257
- type: "string",
1258
- demandOption: undefined,
1259
- description: "The proxy command to run",
1260
- })
1261
- .options({
1262
- local: {
1263
- type: "boolean",
1264
- default: true,
1265
- description: "Run on my machine",
1266
- },
1267
- port: {
1268
- type: "number",
1269
- default: 8788,
1270
- description: "The port to listen on (serve from)",
1271
- },
1272
- proxy: {
1273
- type: "number",
1274
- description:
1275
- "The port to proxy (where the static assets are served)",
1276
- },
1277
- "script-path": {
1278
- type: "string",
1279
- default: "_worker.js",
1280
- description:
1281
- "The location of the single Worker script if not using functions",
1282
- },
1283
- binding: {
1284
- type: "array",
1285
- description: "Bind variable/secret (KEY=VALUE)",
1286
- alias: "b",
1287
- },
1288
- kv: {
1289
- type: "array",
1290
- description: "KV namespace to bind",
1291
- alias: "k",
1292
- },
1293
- do: {
1294
- type: "array",
1295
- description: "Durable Object to bind (NAME=CLASS)",
1296
- alias: "o",
1297
- },
1298
- "live-reload": {
1299
- type: "boolean",
1300
- default: false,
1301
- description: "Auto reload HTML pages when change is detected",
1302
- },
1303
- // TODO: Miniflare user options
1304
- })
1305
- .epilogue(pagesBetaWarning);
1306
- },
1307
- async ({
1308
- local,
1309
- directory,
1310
- port,
1311
- proxy: requestedProxyPort,
1312
- "script-path": singleWorkerScriptPath,
1313
- binding: bindings = [],
1314
- kv: kvs = [],
1315
- do: durableObjects = [],
1316
- "live-reload": liveReload,
1317
- _: [_pages, _dev, ...remaining],
1318
- }) => {
1319
- // Beta message for `wrangler pages <commands>` usage
1320
- logger.log(pagesBetaWarning);
1321
-
1322
- if (!local) {
1323
- logger.error("Only local mode is supported at the moment.");
1324
- return;
1325
- }
1326
-
1327
- const functionsDirectory = "./functions";
1328
- const usingFunctions = existsSync(functionsDirectory);
1329
-
1330
- const command = remaining as (string | number)[];
1331
-
1332
- let proxyPort: number | void;
1333
-
1334
- if (directory === undefined) {
1335
- proxyPort = await spawnProxyProcess({
1336
- port: requestedProxyPort,
1337
- command,
1338
- });
1339
- if (proxyPort === undefined) return undefined;
1340
- }
1341
-
1342
- let miniflareArgs: MiniflareOptions = {};
1343
-
1344
- let scriptReadyResolve: () => void;
1345
- const scriptReadyPromise = new Promise<void>(
1346
- (resolve) => (scriptReadyResolve = resolve)
1347
- );
1348
-
1349
- if (usingFunctions) {
1350
- const outfile = join(tmpdir(), "./functionsWorker.js");
1351
-
1352
- logger.log(`Compiling worker to "${outfile}"...`);
1353
-
1354
- try {
1355
- await buildFunctions({
1356
- outfile,
1357
- functionsDirectory,
1358
- sourcemap: true,
1359
- watch: true,
1360
- onEnd: () => scriptReadyResolve(),
1361
- buildOutputDirectory: directory,
1362
- });
1363
- } catch {}
1364
-
1365
- watch([functionsDirectory], {
1366
- persistent: true,
1367
- ignoreInitial: true,
1368
- }).on("all", async () => {
1369
- await buildFunctions({
1370
- outfile,
1371
- functionsDirectory,
1372
- sourcemap: true,
1373
- watch: true,
1374
- onEnd: () => scriptReadyResolve(),
1375
- buildOutputDirectory: directory,
1376
- });
1377
- });
1378
-
1379
- miniflareArgs = {
1380
- scriptPath: outfile,
1381
- };
1382
- } else {
1383
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1384
- scriptReadyResolve!();
1385
-
1386
- const scriptPath =
1387
- directory !== undefined
1388
- ? join(directory, singleWorkerScriptPath)
1389
- : singleWorkerScriptPath;
1390
-
1391
- if (existsSync(scriptPath)) {
1392
- miniflareArgs = {
1393
- scriptPath,
1394
- };
1395
- } else {
1396
- logger.log("No functions. Shimming...");
1397
- miniflareArgs = {
1398
- // TODO: The fact that these request/response hacks are necessary is ridiculous.
1399
- // We need to eliminate them from env.ASSETS.fetch (not sure if just local or prod as well)
1400
- script: `
1401
- export default {
1402
- async fetch(request, env, context) {
1403
- const response = await env.ASSETS.fetch(request.url, request)
1404
- return new Response(response.body, response)
1405
- }
1406
- }`,
1407
- };
1408
- }
1409
- }
1410
-
1411
- // Defer importing miniflare until we really need it
1412
- const { Miniflare, Log, LogLevel } = await import("miniflare");
1413
- const { Response, fetch } = await import("@miniflare/core");
1414
-
1415
- // Wait for esbuild to finish building before starting Miniflare.
1416
- // This must be before the call to `new Miniflare`, as that will
1417
- // asynchronously start loading the script. `await startServer()`
1418
- // internally just waits for that promise to resolve.
1419
- await scriptReadyPromise;
1420
-
1421
- // `assetsFetch()` will only be called if there is `proxyPort` defined.
1422
- // We only define `proxyPort`, above, when there is no `directory` defined.
1423
- const assetsFetch =
1424
- directory !== undefined
1425
- ? await generateAssetsFetch(directory)
1426
- : invalidAssetsFetch;
1427
-
1428
- const requestContextCheckOptions =
1429
- await getRequestContextCheckOptions();
1430
-
1431
- const miniflare = new Miniflare({
1432
- port,
1433
- watch: true,
1434
- modules: true,
1435
-
1436
- log: new Log(LogLevel.ERROR, { prefix: "pages" }),
1437
- logUnhandledRejections: true,
1438
- sourceMap: true,
1439
-
1440
- kvNamespaces: kvs.map((kv) => kv.toString()),
1441
-
1442
- durableObjects: Object.fromEntries(
1443
- durableObjects.map((durableObject) =>
1444
- durableObject.toString().split("=")
1445
- )
1446
- ),
1447
-
1448
- // User bindings
1449
- bindings: {
1450
- ...Object.fromEntries(
1451
- bindings
1452
- .map((binding) => binding.toString().split("="))
1453
- .map(([key, ...values]) => [key, values.join("=")])
1454
- ),
1455
- },
1456
-
1457
- // env.ASSETS.fetch
1458
- serviceBindings: {
1459
- async ASSETS(request: Request) {
1460
- if (proxyPort) {
1461
- try {
1462
- const url = new URL(request.url);
1463
- url.host = `localhost:${proxyPort}`;
1464
- return await fetch(url, request);
1465
- } catch (thrown) {
1466
- logger.error(`Could not proxy request: ${thrown}`);
1467
-
1468
- // TODO: Pretty error page
1469
- return new Response(
1470
- `[wrangler] Could not proxy request: ${thrown}`,
1471
- { status: 502 }
1472
- );
1473
- }
1474
- } else {
1475
- try {
1476
- return await assetsFetch(request);
1477
- } catch (thrown) {
1478
- logger.error(`Could not serve static asset: ${thrown}`);
1479
-
1480
- // TODO: Pretty error page
1481
- return new Response(
1482
- `[wrangler] Could not serve static asset: ${thrown}`,
1483
- { status: 502 }
1484
- );
1485
- }
1486
- }
1487
- },
1488
- },
1489
-
1490
- kvPersist: true,
1491
- durableObjectsPersist: true,
1492
- cachePersist: true,
1493
- liveReload,
1494
-
1495
- ...requestContextCheckOptions,
1496
- ...miniflareArgs,
1497
- });
1498
-
1499
- try {
1500
- // `startServer` might throw if user code contains errors
1501
- const server = await miniflare.startServer();
1502
- logger.log(`Serving at http://localhost:${port}/`);
1503
-
1504
- if (process.env.BROWSER !== "none") {
1505
- await openInBrowser(`http://localhost:${port}/`);
1506
- }
1507
-
1508
- if (directory !== undefined && liveReload) {
1509
- watch([directory], {
1510
- persistent: true,
1511
- ignoreInitial: true,
1512
- }).on("all", async () => {
1513
- await miniflare.reload();
1514
- });
1515
- }
1516
-
1517
- CLEANUP_CALLBACKS.push(() => {
1518
- server.close();
1519
- miniflare.dispose().catch((err) => miniflare.log.error(err));
1520
- });
1521
- } catch (e) {
1522
- miniflare.log.error(e as Error);
1523
- CLEANUP();
1524
- throw new FatalError("Could not start Miniflare.", 1);
1525
- }
1526
- }
1527
- )
1528
- .command("functions", false, (yargs) =>
1529
- // we hide this command from help output because
1530
- // it's not meant to be used directly right now
1531
- yargs.command(
1532
- "build [directory]",
1533
- "Compile a folder of Cloudflare Pages Functions into a single Worker",
1534
- (yargs) =>
1535
- yargs
1536
- .positional("directory", {
1537
- type: "string",
1538
- default: "functions",
1539
- description: "The directory of Pages Functions",
1540
- })
1541
- .options({
1542
- outfile: {
1543
- type: "string",
1544
- default: "_worker.js",
1545
- description: "The location of the output Worker script",
1546
- },
1547
- "output-config-path": {
1548
- type: "string",
1549
- description: "The location for the output config file",
1550
- },
1551
- minify: {
1552
- type: "boolean",
1553
- default: false,
1554
- description: "Minify the output Worker script",
1555
- },
1556
- sourcemap: {
1557
- type: "boolean",
1558
- default: false,
1559
- description:
1560
- "Generate a sourcemap for the output Worker script",
1561
- },
1562
- "fallback-service": {
1563
- type: "string",
1564
- default: "ASSETS",
1565
- description:
1566
- "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
1567
- },
1568
- watch: {
1569
- type: "boolean",
1570
- default: false,
1571
- description:
1572
- "Watch for changes to the functions and automatically rebuild the Worker script",
1573
- },
1574
- plugin: {
1575
- type: "boolean",
1576
- default: false,
1577
- description: "Build a plugin rather than a Worker script",
1578
- },
1579
- })
1580
- .epilogue(pagesBetaWarning),
1581
- async ({
1582
- directory,
1583
- outfile,
1584
- "output-config-path": outputConfigPath,
1585
- minify,
1586
- sourcemap,
1587
- fallbackService,
1588
- watch,
1589
- plugin,
1590
- }) => {
1591
- if (!isInPagesCI) {
1592
- // Beta message for `wrangler pages <commands>` usage
1593
- logger.log(pagesBetaWarning);
1594
- }
1595
-
1596
- await buildFunctions({
1597
- outfile,
1598
- outputConfigPath,
1599
- functionsDirectory: directory,
1600
- minify,
1601
- sourcemap,
1602
- fallbackService,
1603
- watch,
1604
- plugin,
1605
- buildOutputDirectory: dirname(outfile),
1606
- });
1607
- }
1608
- )
1609
- )
1610
- .command("project", "⚡️ Interact with your Pages projects", (yargs) =>
1611
- yargs
1612
- .command(
1613
- "list",
1614
- "List your Cloudflare Pages projects",
1615
- (yargs) => yargs.epilogue(pagesBetaWarning),
1616
- async () => {
1617
- const config = getConfigCache<PagesConfigCache>(
1618
- PAGES_CONFIG_CACHE_FILENAME
1619
- );
1620
-
1621
- const accountId = await requireAuth(config);
1622
-
1623
- const projects: Array<Project> = await listProjects({ accountId });
1624
-
1625
- const data = projects.map((project) => {
1626
- return {
1627
- "Project Name": project.name,
1628
- "Project Domains": `${project.domains.join(", ")}`,
1629
- "Git Provider": project.source ? "Yes" : "No",
1630
- "Last Modified": project.latest_deployment
1631
- ? timeagoFormat(project.latest_deployment.modified_on)
1632
- : timeagoFormat(project.created_on),
1633
- };
1634
- });
1635
-
1636
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1637
- account_id: accountId,
1638
- });
1639
-
1640
- render(<Table data={data}></Table>);
1641
- }
1642
- )
1643
- .command(
1644
- "create [project-name]",
1645
- "Create a new Cloudflare Pages project",
1646
- (yargs) =>
1647
- yargs
1648
- .positional("project-name", {
1649
- type: "string",
1650
- demandOption: true,
1651
- description: "The name of your Pages project",
1652
- })
1653
- .options({
1654
- "production-branch": {
1655
- type: "string",
1656
- description:
1657
- "The name of the production branch of your project",
1658
- },
1659
- })
1660
- .epilogue(pagesBetaWarning),
1661
- async ({ productionBranch, projectName }) => {
1662
- const config = getConfigCache<PagesConfigCache>(
1663
- PAGES_CONFIG_CACHE_FILENAME
1664
- );
1665
- const accountId = await requireAuth(config);
1666
-
1667
- const isInteractive = process.stdin.isTTY;
1668
- if (!projectName && isInteractive) {
1669
- projectName = await prompt("Enter the name of your new project:");
1670
- }
1671
-
1672
- if (!projectName) {
1673
- throw new FatalError("Must specify a project name.", 1);
1674
- }
1675
-
1676
- if (!productionBranch && isInteractive) {
1677
- let isGitDir = true;
1678
- try {
1679
- execSync(`git rev-parse --is-inside-work-tree`, {
1680
- stdio: "ignore",
1681
- });
1682
- } catch (err) {
1683
- isGitDir = false;
1684
- }
1685
-
1686
- productionBranch = await prompt(
1687
- "Enter the production branch name:",
1688
- "text",
1689
- isGitDir
1690
- ? execSync(`git rev-parse --abbrev-ref HEAD`)
1691
- .toString()
1692
- .trim()
1693
- : "production"
1694
- );
1695
- }
1696
-
1697
- if (!productionBranch) {
1698
- throw new FatalError("Must specify a production branch.", 1);
1699
- }
1700
-
1701
- const { subdomain } = await fetchResult<Project>(
1702
- `/accounts/${accountId}/pages/projects`,
1703
- {
1704
- method: "POST",
1705
- body: JSON.stringify({
1706
- name: projectName,
1707
- production_branch: productionBranch,
1708
- }),
1709
- }
1710
- );
1711
-
1712
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1713
- account_id: accountId,
1714
- project_name: projectName,
1715
- });
1716
-
1717
- logger.log(
1718
- `✨ Successfully created the '${projectName}' project. It will be available at https://${subdomain}/ once you create your first deployment.`
1719
- );
1720
- logger.log(
1721
- `To deploy a folder of assets, run 'wrangler pages publish [directory]'.`
1722
- );
1723
- }
1724
- )
1725
- .epilogue(pagesBetaWarning)
1726
- )
1727
- .command(
1728
- "deployment",
1729
- "🚀 Interact with the deployments of a project",
1730
- (yargs) =>
1731
- yargs
1732
- .command(
1733
- "list",
1734
- "List deployments in your Cloudflare Pages project",
1735
- (yargs) =>
1736
- yargs
1737
- .options({
1738
- "project-name": {
1739
- type: "string",
1740
- description:
1741
- "The name of the project you would like to list deployments for",
1742
- },
1743
- })
1744
- .epilogue(pagesBetaWarning),
1745
- async ({ projectName }) => {
1746
- const config = getConfigCache<PagesConfigCache>(
1747
- PAGES_CONFIG_CACHE_FILENAME
1748
- );
1749
- const accountId = await requireAuth(config);
1750
-
1751
- projectName ??= config.project_name;
1752
-
1753
- const isInteractive = process.stdin.isTTY;
1754
- if (!projectName && isInteractive) {
1755
- const projects = await listProjects({ accountId });
1756
- projectName = await new Promise((resolve) => {
1757
- const { unmount } = render(
1758
- <>
1759
- <Text>Select a project:</Text>
1760
- <SelectInput
1761
- items={projects.map((project) => ({
1762
- key: project.name,
1763
- label: project.name,
1764
- value: project,
1765
- }))}
1766
- onSelect={async (selected) => {
1767
- resolve(selected.value.name);
1768
- unmount();
1769
- }}
1770
- />
1771
- </>
1772
- );
1773
- });
1774
- }
1775
-
1776
- if (!projectName) {
1777
- throw new FatalError("Must specify a project name.", 1);
1778
- }
1779
-
1780
- const deployments: Array<Deployment> = await fetchResult(
1781
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`
1782
- );
1783
-
1784
- const titleCase = (word: string) =>
1785
- word.charAt(0).toUpperCase() + word.slice(1);
1786
-
1787
- const shortSha = (sha: string) => sha.slice(0, 7);
1788
-
1789
- const getStatus = (deployment: Deployment) => {
1790
- // Return a pretty time since timestamp if successful otherwise the status
1791
- if (deployment.latest_stage.status === `success`) {
1792
- return timeagoFormat(deployment.latest_stage.ended_on);
1793
- }
1794
- return titleCase(deployment.latest_stage.status);
1795
- };
1796
-
1797
- const data = deployments.map((deployment) => {
1798
- return {
1799
- Environment: titleCase(deployment.environment),
1800
- Branch: deployment.deployment_trigger.metadata.branch,
1801
- Source: shortSha(
1802
- deployment.deployment_trigger.metadata.commit_hash
1803
- ),
1804
- Deployment: deployment.url,
1805
- Status: getStatus(deployment),
1806
- // TODO: Use a url shortener
1807
- Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1808
- };
1809
- });
1810
-
1811
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
1812
- account_id: accountId,
1813
- });
1814
-
1815
- render(<Table data={data}></Table>);
1816
- }
1817
- )
1818
- .command({
1819
- command: "create [directory]",
1820
- ...createDeployment,
1821
- } as CommandModule)
1822
- .epilogue(pagesBetaWarning)
1823
- )
1824
- .command({
1825
- command: "publish [directory]",
1826
- ...createDeployment,
1827
- } as CommandModule);
1828
- };
1829
-
1830
- const invalidAssetsFetch: typeof fetch = () => {
1831
- throw new Error(
1832
- "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1833
- );
1834
- };
1835
-
1836
- const listProjects = async ({
1837
- accountId,
1838
- }: {
1839
- accountId: string;
1840
- }): Promise<Array<Project>> => {
1841
- const pageSize = 10;
1842
- let page = 1;
1843
- const results = [];
1844
- while (results.length % pageSize === 0) {
1845
- const json: Array<Project> = await fetchResult(
1846
- `/accounts/${accountId}/pages/projects`,
1847
- {},
1848
- new URLSearchParams({
1849
- per_page: pageSize.toString(),
1850
- page: page.toString(),
1851
- })
1852
- );
1853
- page++;
1854
- results.push(...json);
1855
- if (json.length < pageSize) {
1856
- break;
1857
- }
1858
- }
1859
- return results;
1860
- };
1861
-
1862
- function formatTime(duration: number) {
1863
- return `(${(duration / 1000).toFixed(2)} sec)`;
1864
- }
1865
-
1866
- function Progress({ done, total }: { done: number; total: number }) {
1867
- return (
1868
- <>
1869
- <Text>
1870
- <Spinner type="earth" />
1871
- {` Uploading... (${done}/${total})\n`}
1872
- </Text>
1873
- </>
1874
- );
1875
- }