Compare commits

...

196 Commits

Author SHA1 Message Date
Leo Lamprecht
ba7bf2e4a6 Publish Canary
- @vercel/build-utils@2.12.3-canary.32
 - vercel@23.1.3-canary.53
 - @vercel/client@10.2.3-canary.33
 - vercel-plugin-go@1.0.0-canary.20
 - vercel-plugin-node@1.12.2-canary.24
 - vercel-plugin-python@1.0.0-canary.21
 - vercel-plugin-ruby@1.0.0-canary.19
2021-12-02 23:51:51 +01:00
Leo Lamprecht
00641037fc Corrected input paths for CLI Plugins (#7121)
* Use correct paths for outputs

* Fixed tests

This reverts commit 7c4baeaafaf41609f47c97a09f5e9647fd8b89ee.

* Revert "Fixed tests"

This reverts commit 59c10d18c63f8404c3b0c361c3769b62524316f1.

* Revert "Use correct paths for outputs"

This reverts commit 23a0b34fad1e4932755a39975ae1dfa07acb2dd9.

* Corrected input paths for CLI Plugins

* Fixed tests

This reverts commit 7c4baeaafaf41609f47c97a09f5e9647fd8b89ee.

* Revert "Fixed tests"

This reverts commit 9612d2a9eb19240a5a4489406ada17a6a5bb3806.

* Fixed tests

* Delete vc__handler__python.py
2021-12-02 23:51:39 +01:00
Leo Lamprecht
6f4a1b527b Publish Canary
- @vercel/build-utils@2.12.3-canary.31
 - vercel@23.1.3-canary.52
 - @vercel/client@10.2.3-canary.32
 - vercel-plugin-go@1.0.0-canary.19
 - vercel-plugin-node@1.12.2-canary.23
 - vercel-plugin-python@1.0.0-canary.20
 - vercel-plugin-ruby@1.0.0-canary.18
2021-12-02 22:41:17 +01:00
Leo Lamprecht
1b95576dd2 Fixed Go, Ruby, and Python CLI Plugin output generation (#7117)
* Fixed error with API directory

* Made output work

* Use handler as API Route

* Correctly find the handler

* Fixed a missing instance

* Made handler logic work

* Made it work as expected

* Exclude unnecessary files

* Use a method that always works

* Additional comment

* Made everything work

* Cleaner tests

* Clean up all the useless files

* Fixed missing instance

* Speed up the code

* Removed useless lines

* Update packages/build-utils/src/convert-runtime-to-plugin.ts

Co-authored-by: Andy <AndyBitz@users.noreply.github.com>

* Clarified comment

* Use relative logic again

* Fixed tests

* Deleted useless file

Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
2021-12-02 22:18:43 +01:00
Leo Lamprecht
9227471aca Publish Canary
- @vercel/build-utils@2.12.3-canary.30
 - vercel@23.1.3-canary.51
 - @vercel/client@10.2.3-canary.31
 - vercel-plugin-go@1.0.0-canary.18
 - vercel-plugin-node@1.12.2-canary.22
 - vercel-plugin-python@1.0.0-canary.19
 - vercel-plugin-ruby@1.0.0-canary.17
2021-12-02 15:24:34 +01:00
Leo Lamprecht
bf060296eb Fixed typo (#7115) 2021-12-02 15:19:32 +01:00
Leo Lamprecht
9b3aa41f2e Publish Canary
- @vercel/build-utils@2.12.3-canary.29
 - vercel@23.1.3-canary.50
 - @vercel/client@10.2.3-canary.30
 - vercel-plugin-go@1.0.0-canary.17
 - vercel-plugin-node@1.12.2-canary.21
 - vercel-plugin-python@1.0.0-canary.18
 - vercel-plugin-ruby@1.0.0-canary.16
2021-12-02 15:02:00 +01:00
Leo Lamprecht
ae36585cdb Filter CLI Plugin output (#7114)
* Filter CLI Plugin output

* Only apply ignorefile check in the beginning
2021-12-02 15:01:17 +01:00
Leo Lamprecht
e4c636ddd2 Publish Canary
- vercel-plugin-go@1.0.0-canary.16
 - vercel-plugin-python@1.0.0-canary.17
 - vercel-plugin-ruby@1.0.0-canary.15
2021-12-02 14:14:14 +01:00
Leo Lamprecht
ae3b25be4b Made CLI Plugin publishing work (#7113) 2021-12-02 14:10:23 +01:00
Andy Bitz
a64ed13a40 Publish Canary
- vercel@23.1.3-canary.49
2021-12-02 12:55:04 +01:00
Andy
6c1c0e6676 [cli] Ignore required-server-files.json if it does not exist (#7111) 2021-12-02 12:54:30 +01:00
Leo Lamprecht
82fdd5d121 Publish Canary
- vercel@23.1.3-canary.48
 - vercel-plugin-go@1.0.0-canary.15
 - vercel-plugin-node@1.12.2-canary.20
 - vercel-plugin-python@1.0.0-canary.16
 - vercel-plugin-ruby@1.0.0-canary.14
 - @vercel/static-config@0.0.1-canary.1
2021-12-02 11:46:28 +01:00
Nathan Rajlich
8b40f4435e [api] Use the new File System API (#7108)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2021-12-02 11:45:57 +01:00
Leo Lamprecht
38c87602bb Renamed runtime to use in static JS config (#7106)
### Related Issues

This applies what was mentioned in https://github.com/vercel/runtimes/issues/288#issuecomment-984101750.

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
2021-12-02 00:37:09 +00:00
Nathan Rajlich
7aef3013e7 [cli] Use "127.0.0.1" instead of "localhost" in vc dev (#7094)
Node.js doesn't like when a hostname resolves to an IPv6 address (https://stackoverflow.com/a/15244890/376773) so use the IPv4 localhost IP address instead. Specifically this fixes vc dev on Node.js 17 which now prefers IPv6 by default.

Slack thread: https://vercel.slack.com/archives/C01A2M9R8RZ/p1638330248263400
2021-12-01 23:29:26 +00:00
Nathan Rajlich
c18676ab4d Publish Canary
- vercel-plugin-go@1.0.0-canary.14
 - vercel-plugin-python@1.0.0-canary.15
 - vercel-plugin-ruby@1.0.0-canary.13
2021-12-01 14:28:40 -08:00
Leo Lamprecht
df450c815d Properly publish CLI Plugins (#7103)
After https://github.com/vercel/vercel/pull/7088, `dist` now contains `package.json`, which made `tsc` move `index.js` a level deeper, effectively breaking the `main` property of all of the affected CLI Plugins.

This change makes them work again. 

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
2021-12-01 20:59:46 +00:00
Andy Bitz
792ab38760 Publish Canary
- @vercel/build-utils@2.12.3-canary.28
 - vercel@23.1.3-canary.47
 - @vercel/client@10.2.3-canary.29
 - vercel-plugin-go@1.0.0-canary.13
 - vercel-plugin-node@1.12.2-canary.19
 - vercel-plugin-python@1.0.0-canary.14
 - vercel-plugin-ruby@1.0.0-canary.12
 - @vercel/ruby@1.2.8-canary.6
2021-12-01 15:32:05 +01:00
Leo Lamprecht
0bba3e76c1 Corrected dependency installation systems (#7088)
* Avoid unnecessary Gemfile installations

* Do not bundle `.output` or `.vercel` into Lambdas

* Use the same input hash format for all CLI Plugins and `vercel build`

* Fixed unit tests

* Fixed the unit tests again

* Fixed the unit tests

* Fixed all the tests

* Exclude useless files

* Consider `.vercelignore` and `.nowignore`

* Fixed error

* Reverted changes

* Deleted useless file

* Fixed tests

* Share input hash format with `vercel-plugin-node`

* Make output inspectable

* Fixed build error

* Extended comment

* Bump Ruby version

* Update Gemfiles

* Update bundles

* Fixed tests

Co-authored-by: Andy Bitz <artzbitz@gmail.com>
2021-12-01 15:31:27 +01:00
Andy Bitz
3d961ffbb9 Publish Canary
- vercel@23.1.3-canary.46
2021-11-30 19:25:13 +01:00
Andy
a3039f57bb [cli] Fix vc build with nested app dir (#7083)
* [cli] Fix `vc build` with nested app dir

* Set NEXT_PRIVATE_OUTPUT_TRACE_ROOT
2021-11-30 18:30:51 +01:00
Andy Bitz
5499fa9a04 Publish Canary
- @vercel/build-utils@2.12.3-canary.27
 - vercel@23.1.3-canary.45
 - @vercel/client@10.2.3-canary.28
 - vercel-plugin-go@1.0.0-canary.12
 - vercel-plugin-node@1.12.2-canary.18
 - vercel-plugin-python@1.0.0-canary.13
 - vercel-plugin-ruby@1.0.0-canary.11
2021-11-30 16:17:47 +01:00
Leo Lamprecht
b9fd64faff Stop passing functions and regions to Runtimes (#7085)
* Stop passing `functions` and `regions` to Runtimes

* Added required types back

* Removed `vercelConfig` from `vercel-plugin-node`

* Fixed unit test

* Fixed test
2021-11-30 16:16:53 +01:00
Andy Bitz
1202ff7b2b Publish Canary
- @vercel/build-utils@2.12.3-canary.26
 - vercel@23.1.3-canary.44
 - @vercel/client@10.2.3-canary.27
 - @vercel/frameworks@0.5.1-canary.16
 - vercel-plugin-go@1.0.0-canary.11
 - vercel-plugin-node@1.12.2-canary.17
 - vercel-plugin-python@1.0.0-canary.12
 - vercel-plugin-ruby@1.0.0-canary.10
 - @vercel/python@2.1.2-canary.1
 - @vercel/ruby@1.2.8-canary.5
2021-11-30 14:37:53 +01:00
Leo Lamprecht
abd9f019f1 Don't install Ruby or Python dependencies unnecessarily (#7084)
* Don't install Ruby or Python dependencies unnecessarily

* Less repeated code

* Cleaner code
2021-11-30 14:36:27 +01:00
Leo Lamprecht
edb5eead81 Speed up Remix Template (#7077)
* Replaced Remix Template

* Added npm lockfile for Remix Template

* Added npm lockfile for Next.js Template

* Added Remix logo
2021-11-29 16:01:23 +01:00
Andy Bitz
6b865ff753 Publish Canary
- @vercel/build-utils@2.12.3-canary.25
 - vercel@23.1.3-canary.43
 - @vercel/client@10.2.3-canary.26
 - @vercel/frameworks@0.5.1-canary.15
 - vercel-plugin-go@1.0.0-canary.10
 - vercel-plugin-node@1.12.2-canary.16
 - vercel-plugin-python@1.0.0-canary.11
 - vercel-plugin-ruby@1.0.0-canary.9
2021-11-29 14:26:12 +01:00
Andy
4fd0734c48 [cli] Consider envPrefix and outputDirectory for vercel build (#7069)
* [cli] Consider `envPrefix` for the framework

* Fix env

* Remove type

* Resolve .nft.json files correctly

* Fix public and static directory handling

* Do not use .replace

* Consider the output directory
2021-11-29 14:23:10 +01:00
Leo Lamprecht
f815421acb Renamed the Remix logo file (#7074) 2021-11-29 12:14:09 +01:00
Logan McAnsh
5da926fee1 chore: update remix logo (#7070) 2021-11-29 11:37:46 +01:00
Andy Bitz
3559531e4c Publish Canary
- @vercel/build-utils@2.12.3-canary.24
 - vercel@23.1.3-canary.42
 - @vercel/client@10.2.3-canary.25
 - @vercel/frameworks@0.5.1-canary.14
 - vercel-plugin-go@1.0.0-canary.9
 - vercel-plugin-node@1.12.2-canary.15
 - vercel-plugin-python@1.0.0-canary.10
 - vercel-plugin-ruby@1.0.0-canary.8
2021-11-25 12:01:09 +01:00
Leo Lamprecht
449a3b3648 Updated Remix template and ensured correct headers (#7064)
* Updated Remix Example

* Adjusted config as necessary

* Updated gitignore

* Fixed default Remix headers

* Removed useless files

* Fixed README

* Added newline
2021-11-25 11:57:57 +01:00
Steven
7bd338618c Publish Canary
- @vercel/build-utils@2.12.3-canary.23
 - vercel@23.1.3-canary.41
 - @vercel/client@10.2.3-canary.24
 - vercel-plugin-go@1.0.0-canary.8
 - vercel-plugin-node@1.12.2-canary.14
 - vercel-plugin-python@1.0.0-canary.9
 - vercel-plugin-ruby@1.0.0-canary.7
2021-11-24 22:03:54 -05:00
Steven
9048a6f584 [build-utils] Fix zero config routes for vercel build (#7063) 2021-11-24 22:00:49 -05:00
Steven
0cacb1bdac Publish Canary
- @vercel/build-utils@2.12.3-canary.22
 - vercel@23.1.3-canary.40
 - @vercel/client@10.2.3-canary.23
 - vercel-plugin-go@1.0.0-canary.7
 - vercel-plugin-node@1.12.2-canary.13
 - vercel-plugin-python@1.0.0-canary.8
 - vercel-plugin-ruby@1.0.0-canary.6
2021-11-24 18:12:26 -05:00
Steven
318bf35f82 [build-utils] Add support for writing routes-manifest.json (#7062)
* [build-utils] Add support for writing routes-manifest.json

* Add support for dynamicRoutes

* Add another test with multiple named params
2021-11-24 18:00:12 -05:00
Andy Bitz
cc7b2691c1 Publish Canary
- @vercel/build-utils@2.12.3-canary.21
 - vercel@23.1.3-canary.39
 - @vercel/client@10.2.3-canary.22
 - @vercel/frameworks@0.5.1-canary.13
 - vercel-plugin-go@1.0.0-canary.6
 - vercel-plugin-node@1.12.2-canary.12
 - vercel-plugin-python@1.0.0-canary.7
 - vercel-plugin-ruby@1.0.0-canary.5
 - @vercel/python@2.1.2-canary.0
2021-11-24 17:41:53 +01:00
Leo Lamprecht
3a75c37adc Added Remix to the list of frameworks (#7061)
* Added Remix to the list of frameworks

* Replaced Development Command

* Polished config

* Added headers

* Added example

* Fixed logo

* Trigger a Deployment

* Added vercel.json

* Port is automatically parsed through remix.config.js

* Fixed sorting

* Moved it down a bit

* Trigger a Deployment

* Removed useless property

* Reverted readme

* Fully reverted readme
2021-11-24 17:40:55 +01:00
Steven
acd0e84e73 [cli] Pass vercel.json to plugins during vercel build (#7059)
* [cli] Pass vercel.json to plugins during `vercel build`

* Add missing `vercelConfig` param

* Add type

* Fix test

* Update test
2021-11-23 19:12:57 -05:00
Jared Palmer
49087d5aac Change nextjs detection (#7020)
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
2021-11-23 19:06:36 +01:00
Steven
7d7f3df980 Publish Stable
- @vercel/python@2.1.1
2021-11-23 09:04:08 -05:00
Steven
5cf0c316e9 Publish Stable
- @vercel/python@2.1.0
2021-11-23 08:57:58 -05:00
Steven
f4501433c8 Publish Canary
- vercel@23.1.3-canary.38
 - vercel-plugin-python@1.0.0-canary.6
 - @vercel/python@2.0.6-canary.7
2021-11-22 18:43:37 -05:00
Steven
19831593ce [python] Add warning for deprecated version (#7053)
- Print warning when python 3.6 is selected
- Print warning when invalid python version is selected
2021-11-22 23:36:30 +00:00
Steven
5d85bb1426 [tests] Bump cancel action to 0.9.1 (#7055) 2021-11-22 17:24:35 -05:00
Andy Bitz
f194d54b0c Publish Canary
- vercel@23.1.3-canary.37
2021-11-22 23:14:32 +01:00
Andy
6542086843 Revert "[cli] Switch from hardlinks to symlinks in vc build" (#7054)
* Revert "[cli] Switch from hardlinks to symlinks in vc build (#7026)"

This reverts commit 6dff0875f5.

* Keep copy logic
2021-11-22 23:12:46 +01:00
Andy Bitz
2721b3449d Publish Canary
- @vercel/build-utils@2.12.3-canary.20
 - vercel@23.1.3-canary.36
 - @vercel/client@10.2.3-canary.21
 - @vercel/node@1.12.2-canary.7
 - vercel-plugin-go@1.0.0-canary.5
 - vercel-plugin-node@1.12.2-canary.11
 - vercel-plugin-python@1.0.0-canary.5
 - vercel-plugin-ruby@1.0.0-canary.4
2021-11-22 13:22:56 +01:00
Andy
adb284519a [plugin-node][node] Fix dependency installation, handler path, and build script (#7043)
* [plugin-node][node] Fix dependency installation, handler path, and build script

* Use smaller library for testing

* Make test work on windows

* Remove .output before fixture runs and update routes update

* Apply suggestions from code review

Co-authored-by: Steven <steven@ceriously.com>

Co-authored-by: Steven <steven@ceriously.com>
2021-11-22 13:21:20 +01:00
Steven
b2d91f3121 [cli] Fix metrics crash on some platforms (#7034) 2021-11-20 20:31:39 -05:00
Steven
32664cd13b Publish Canary
- @vercel/build-utils@2.12.3-canary.19
 - vercel@23.1.3-canary.35
 - @vercel/client@10.2.3-canary.20
 - @vercel/frameworks@0.5.1-canary.12
 - vercel-plugin-go@1.0.0-canary.4
 - vercel-plugin-node@1.12.2-canary.10
 - vercel-plugin-python@1.0.0-canary.4
 - vercel-plugin-ruby@1.0.0-canary.3
2021-11-20 10:20:05 -05:00
Sam Ko
db468c489a [frameworks] Fix Parcel default output directory to dist (#7029)
### Related Issues

The Parcel template via the Project Creating Flow returns a build error because the default output directory for the Parcel **Framework Preset** is searching for `public` instead of `dist`. The default behavior of Parcel's CLI I believe is `dist`.

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-11-20 01:44:22 +00:00
Steven
edd9bb506c [frameworks][cli] Consolidate buildCommand and devCommand (#7032)
* [frameworks] Consolidate buildCommand and devCommand

* Fix default build command when no override or package.json found
2021-11-19 19:07:52 -05:00
Steven
a72549a290 [tests] Make test more reliable for function timeout (#7033) 2021-11-19 17:26:32 -05:00
Steven
4aa6a13912 Publish Canary
- vercel@23.1.3-canary.34
 - vercel-plugin-python@1.0.0-canary.3
 - @vercel/python@2.0.6-canary.6
2021-11-19 14:42:02 -05:00
Steven
81ea0082f1 [python] Upgrade python 3.9 (#7008)
* [python] Upgrade python 3.9

* Fix python path

* Improve testing

* Add support for version selection via Pipfile

* Parse the "Pipfile.lock" instead

* Fix support for Node.js 12
2021-11-19 13:42:17 -05:00
Jared Palmer
6dff0875f5 [cli] Switch from hardlinks to symlinks in vc build (#7026)
* Switch from hardlinks to symlinks in vc build

* Remove error handling that fs-extra already takes care of

* Add comment

* Put back symlink error handling
2021-11-19 12:36:31 -05:00
Steven
30aa392c0a [tests] Increase CI duration (#7030)
Seems like macOS sometimes exceeds 60 min so this bumps the timeout.

The build can be between 3 minutes and 5 minutes. The tests can be between 45 minutes and 55 minutes.
2021-11-19 14:59:12 +00:00
Miroslav Simulcik
c4fc060030 [cli] Fix spinner output outside of TTY (#7017)
* Fix spinner output outside of TTY

* Use console.log

* Fix tests

* Revert "Fix tests"

This reverts commit 44383eea2dc3bb699d943079d77961ed86fe65d6.

* Revert "Use console.log"

This reverts commit 251bd1d624532e9ecfb4aee5b31538aa4ba740ef.
2021-11-17 14:04:59 +01:00
Steven
3fa08bf64f [cli] Fix update command to favor npm (#7018) 2021-11-16 16:07:31 -05:00
Steven
43056bde1f Publish Canary
- vercel@23.1.3-canary.33
2021-11-15 18:07:17 -05:00
Steven
a49966b9b4 [cli] Change vc build to use stdout (#7005) 2021-11-15 18:06:48 -05:00
Steven
7f55de71bb Publish Canary
- vercel@23.1.3-canary.32
 - @vercel/go@1.2.4-canary.4
 - vercel-plugin-go@1.0.0-canary.3
2021-11-15 13:37:04 -05:00
Steven
db8e36e04c [go] Add support for version 1.17 (#7002)
* Support more Go versions

Co-authored-by: Stefan M <StefMa@users.noreply.github.com>
2021-11-15 13:36:26 -05:00
Andy Bitz
82924bb5c4 Publish Canary
- vercel@23.1.3-canary.31
 - vercel-plugin-node@1.12.2-canary.9
2021-11-15 14:11:55 +01:00
Andy
18b5fac93e [vercel-plugin-node] Use .nft.json files instead of directories. (#6988)
* Ignore install step if package.json does not exist in entrypoint directory

* [plugin-node] Use `.nft.json` files

* Bump @vercel/fun

* Update package.json

* Remove package

* Remove import

* Update paths

* Revert "Update paths"

This reverts commit fa304e90381f475c64b2333402dca489813522da.

* Update path for windows

* Update handler path
2021-11-15 14:08:49 +01:00
Miroslav Simulcik
a6012e600b [cli] Fix updating of gitignore in vercel link (#6986)
* Fix updating of gitignore in link

* Fix modification of gitignore file during linking

* Fix empty file case
2021-11-12 17:11:21 +01:00
Steven
c3abf73f58 Publish Canary
- @vercel/build-utils@2.12.3-canary.18
 - vercel@23.1.3-canary.30
 - @vercel/client@10.2.3-canary.19
 - vercel-plugin-go@1.0.0-canary.2
 - vercel-plugin-node@1.12.2-canary.8
 - vercel-plugin-python@1.0.0-canary.2
 - vercel-plugin-ruby@1.0.0-canary.2
2021-11-11 14:54:33 -05:00
Steven
4873b8b379 [build-utils][node] Add updateFunctionsManifest function (#6971) 2021-11-11 14:53:43 -05:00
Miroslav Simulcik
6248139281 [cli] Prevent recursion of vercel build and vercel dev (#6960)
* Prevent infinite recursion of vercel build and dev

* Improved text

* Improved the text further

* Add tests

* Debug test

* Add debug log

* Debug test

* debug test

* Debug test

* Fix test

* Debug tests

* Debug test

* Remove only from tests

* Add error documentation

* Improved docs

* Fix other test

* Fixed links to error docs

* Remove legacy error page

* Use nicer error links

Co-authored-by: Leo Lamprecht <leo@vercel.com>
2021-11-11 10:51:30 -05:00
Miroslav Simulcik
507a5de3cd [tests] Fix getting of config paths (#6969)
Co-authored-by: Steven <steven@ceriously.com>
2021-11-09 14:34:41 -05:00
Gary Borton
be1c78e72f Publish Canary
- vercel@23.1.3-canary.29
 - vercel-plugin-middleware@0.0.0-canary.7
2021-11-09 11:07:01 -08:00
Gary Borton
c277c649c6 Fix middleware build result. Return middleware next when invalid result. (#6963)
* Fix middleware build result. Return middleware next when invalid result.

* Add a unit test that would have failed before previous commit.

* Copy next.js behavior.

* Add a test for invalid responses from middleware.

Co-authored-by: Leo Lamprecht <leo@vercel.com>
2021-11-09 11:06:16 -08:00
Steven
ed1dacd276 Publish Canary
- @vercel/build-utils@2.12.3-canary.17
 - vercel@23.1.3-canary.28
 - @vercel/client@10.2.3-canary.18
 - vercel-plugin-go@1.0.0-canary.1
 - vercel-plugin-python@1.0.0-canary.1
 - vercel-plugin-ruby@1.0.0-canary.1
 - @vercel/python@2.0.6-canary.5
 - @vercel/ruby@1.2.8-canary.4
2021-11-09 12:50:34 -05:00
Steven
144e890bfa Add plugin packages for go/python/ruby (#6961)
* Add plugin packages

* Fix usage

* Fix build

* Fix workspace linking to build-utils
2021-11-09 12:48:40 -05:00
Andy Bitz
af097c2c06 Publish Canary
- vercel@23.1.3-canary.27
2021-11-09 16:44:14 +01:00
Andy
873a582986 [cli] Ignore .next/cache in vc build (#6968)
* [cli] Ignore .next/cache in `vc build`

* Handle middleware-manifest.json

* Update manifest update
2021-11-09 16:43:26 +01:00
Andy Bitz
986b4c0b1a Publish Canary
- vercel@23.1.3-canary.26
2021-11-09 01:31:30 +01:00
Andy
14071819ac [cli] Fix NFT output path for monorepos (#6965)
* [cli] Fix `output` path for `.output` for `node_modules`

* Use baseDir instead of cwd

* Update comment

* Update output for requiredServerFiles
2021-11-09 01:30:49 +01:00
jj@jjsweb.site
2a8588a0c5 Publish Canary
- @vercel/build-utils@2.12.3-canary.16
 - vercel@23.1.3-canary.25
 - @vercel/client@10.2.3-canary.17
 - @vercel/frameworks@0.5.1-canary.11
 - @vercel/routing-utils@1.11.4-canary.6
2021-11-08 14:42:18 -06:00
JJ Kasper
0f7e89f76c [routing-utils] Add caseSensitive field to routes schema (#6952)
### Related Issues

x-ref: https://github.com/vercel/customer-issues/issues/34

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-11-08 20:29:31 +00:00
Andy Bitz
e68ed33a88 Publish Canary
- vercel@23.1.3-canary.24
 - vercel-plugin-middleware@0.0.0-canary.6
2021-11-08 19:38:58 +01:00
Gary Borton
d3e98cdb73 [cli] Run middleware as a plugin instead of running directly (#6941)
* Move loadPlugins to a utils file to be shared w/ dev server.

* Update loadCliPlugins to also return startDevServer and runDevMiddleware based plugins.

* Move plugins back to dependencies.

These can't be bundled as it interferes with plugin resolution.

* Hook up middleware plugins to dev server.

* Pass output object to loadCliPlugins instead of a logging function.

* Allow more than one runDevMiddleware defining plugins.

* Bundle esbuild w/ middleware plugin.

* Keep esbuild as an external

* Update middleware's esbuild.

* set old space size

* Revert "set old space size"

This reverts commit b579194a862949a11769e9087f01c31f2e1f3b60.

* Use --max-old-space-size for CLI unit tests

* Increase memory

* Use `run.js` to set the memory

* Make NODE_OPTIONS optional

Co-authored-by: Leo Lamprecht <leo@vercel.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
2021-11-08 19:38:13 +01:00
Andy Bitz
bf4e77110f Publish Canary
- vercel@23.1.3-canary.23
 - @vercel/node@1.12.2-canary.6
 - vercel-plugin-node@1.12.2-canary.7
2021-11-08 15:00:01 +01:00
Nathan Rajlich
5b5197d2c5 [node] Create vercel-plugin-node (#6874)
* [node] Refactor to Vercel CLI Plugin

* Enforce "index" suffix on output Serverless Functions

So that nesting works properly

* Some cleanup

* Add version

* Use `@vercel/static-config`

* .

* Add support for wildcard routes

* Don't compile dotfiles, underscore prefixed files, files within `node_modules`, nor TypeScript definition files

Matches the logic from `maybeGetBuilder()` in `@vercel/build-utils`.

* Bump version

* Introduce testing framework

* Debug

* Add test without any deps

* Longer timeout to install Node.js for vercel/fun

* Install deps

* Add legacy Node.js server interface test

* More tests

* Test "assets" fixture

* Test "helpers" fixture

* fix

* Support AWS native API

* Remove debugging `console.log()` calls

* Use plugin-node for new plugin instead

* Revert "Use plugin-node for new plugin instead"

This reverts commit f317b8c6ecdc67a74d5f2b12a2e7567a27d4b6b8.

* Move to `plugin-node` directory

* Update plugin-node version in package.json

* Checkout node from main

* Add yarn.lock files for tests

* Update node-bridge

Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
2021-11-08 14:59:01 +01:00
Steven
a6ccf6c180 Publish Canary
- @vercel/build-utils@2.12.3-canary.15
 - vercel@23.1.3-canary.22
 - @vercel/client@10.2.3-canary.16
 - @vercel/node-bridge@2.1.1-canary.2
 - @vercel/node@1.12.2-canary.5
2021-11-05 18:40:08 -04:00
Steven
8d848ebe8b [node] Fix launcher ESM on Windows dev (#6953) 2021-11-05 18:38:55 -04:00
Steven
6ef2c16d63 [build-utils] Add convertRuntimeToPlugin() (#6942) 2021-11-05 16:12:21 -04:00
Andy Bitz
6c71ceaaeb Publish Canary
- vercel@23.1.3-canary.21
2021-11-05 10:26:15 +01:00
Andy
1dcb6dfc6f [cli] Rename certain outputs in vercel build (#6948) 2021-11-05 10:24:49 +01:00
Steven
4fd24575e5 Publish Canary
- vercel@23.1.3-canary.20
 - vercel-plugin-middleware@0.0.0-canary.5
2021-11-03 09:06:27 -04:00
Gary Borton
8714f1905e [cli] Render an error page when middleware explodes. (#6934)
### Related Issues

This adds error handling for middleware in `vc dev`

Local looks a little different than production:
Local
![image](https://user-images.githubusercontent.com/4172067/139951848-efa08a88-aeee-446f-8319-35c8bb0b1d75.png)

Production
![image](https://user-images.githubusercontent.com/4172067/139951580-33a4ad0f-18a5-4aa1-bfb0-5e1da646a4b8.png)


### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-11-02 23:57:46 +00:00
Jared Palmer
2e69f2513d [cli] Make sure vc pull properly sets currentTeam (#6936)
### Related Issues

> Fixes https://github.com/vercel/runtimes/issues/219

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-11-02 23:07:28 +00:00
Gary Borton
979e4b674a [cli] Bundle middleware deps (#6932)
* Use ncc to bundle middleware plugin, move dependencies to devDependencies, remove querystring

* Switch from globby (deprecated dependencies) to glob in middleware plugin.

* Bundle the node-plugin and middleware-plugin into cli.
2021-11-02 17:08:02 -04:00
Nathan Rajlich
07fa47bcfb Publish Canary
- vercel@23.1.3-canary.19
 - vercel-plugin-middleware@0.0.0-canary.4
2021-10-29 18:17:08 -07:00
Nathan Rajlich
307c4fc377 [cli] Bump vercel-plugin-node to latest 2021-10-29 18:16:16 -07:00
Nathan Rajlich
44868d79b6 Add initial vercel-plugin-middleware (#6892)
* Add initial `vercel-plugin-middleware`

* Ignore `entries.js` from ESLint

* Add `runDevMiddleware()` stub

* Add test

* Add support for "_middleware.{js,ts}" to `vercel dev` (#6880)

* Add websandbox from next.js codebase.

* Use node-fetch instead of next's polyfilled fetch.

* Handle middleware rewrites.

* Add response, headers, and request to websandbox context.

* Move websandbox dependency to middleware plugin.

* Add integration tests, update websandbox to support ts files and json imports.

* commit yarn.lock changes after rebasing

* Clean up left over console.logs, fix some tsc issues, and rebase issue.

* Fix failing test and eslint.

* Fix middleware test on windows.

* [examples] Update Vercel Next.js example template to 12.0.1 (#6905)

* Mark the Plugins as external to CLI's ncc build

* [cli] Improve tracing in vc build (#6898)

* [cli] Fix tracing for `vc build`

* Ignore object when there are no changes

* Make Next < 12 work with FS API w/ nft

* Update packages/cli/src/commands/build.ts

Co-authored-by: Nathan Rajlich <n@n8.io>

* Document how Next.js processing works in build

* [cli] Fix static assets (#6906)

* Make sure output path is .next

* Fix up require-server-files for processing

* Fix typo

* Move static

* Update static rename

Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>

* Publish Canary

 - vercel@23.1.3-canary.17
 - @vercel/client@10.2.3-canary.15
 - @vercel/static-config@0.0.1-canary.0

* [cli] Ignore `.env` and `.gitignore` in "vc build" (#6910)

* Publish Canary

 - vercel@23.1.3-canary.18

* Pass workPath to plugins.

The new plugin architecture doesn't pass a full BuildOptions object, previous
to this commit it wasn't passing any options at all. I've added workingPath to
support running dev/build from directories other than the project root.

* Remove error state when package.json exists, but no build script

This allows vercel build to continue working for projects that are not using
frameworks, but use package.json to manage dependencies.

* Fix types, pull in middleware header fix from next.js

Next js PR w/ the header fix:
https://github.com/vercel/next.js/pull/30560

* Fix missing entries file for vc build.

* Update call signature of middleware when using vc build.

Co-authored-by: Drew Bredvick <dbredvick@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>

Co-authored-by: Gary Borton <gdborton@gmail.com>
Co-authored-by: Drew Bredvick <dbredvick@gmail.com>
Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
2021-10-29 17:15:20 -07:00
Nathan Rajlich
df9a4afa5c Publish Canary
- vercel@23.1.3-canary.18
2021-10-29 12:22:35 -07:00
Nathan Rajlich
8a6869bae2 [cli] Ignore .env and .gitignore in "vc build" (#6910) 2021-10-29 12:21:46 -07:00
Andy Bitz
a3fc3c1ca7 Publish Canary
- vercel@23.1.3-canary.17
 - @vercel/client@10.2.3-canary.15
 - @vercel/static-config@0.0.1-canary.0
2021-10-29 20:49:54 +02:00
Jared Palmer
44037c58be [cli] Improve tracing in vc build (#6898)
* [cli] Fix tracing for `vc build`

* Ignore object when there are no changes

* Make Next < 12 work with FS API w/ nft

* Update packages/cli/src/commands/build.ts

Co-authored-by: Nathan Rajlich <n@n8.io>

* Document how Next.js processing works in build

* [cli] Fix static assets (#6906)

* Make sure output path is .next

* Fix up require-server-files for processing

* Fix typo

* Move static

* Update static rename

Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
2021-10-29 20:49:21 +02:00
Drew Bredvick
1a9419b690 [examples] Update Vercel Next.js example template to 12.0.1 (#6905) 2021-10-29 13:03:31 -04:00
Nathan Rajlich
93d0e5966c [cli] Fix integration tests that check .gitignore (#6904) 2021-10-28 12:37:39 -07:00
Nathan Rajlich
306f3a1312 Add to "static-config" to run.js script 2021-10-27 17:36:32 -07:00
Nathan Rajlich
9c67e8115e Add @vercel/static-config (#6897) 2021-10-27 17:03:12 -07:00
Andy
b890ac1e44 [cli] Fix tracing for vc build (#6896)
* [cli] Fix tracing for `vc build`

* Ignore object when there are no changes
2021-10-28 00:20:44 +02:00
Andy
28e71ff109 [cli][client] Add step for checks (#6889)
* [cli][client] Add step for checks

* Update output

* Remove skipped message

* Correctly use `finishedEvents`

* Update packages/cli/src/commands/deploy/index.ts

Co-authored-by: Chris <7249920+chriswdmr@users.noreply.github.com>

* Add back deleted files

Co-authored-by: Chris <7249920+chriswdmr@users.noreply.github.com>
2021-10-27 20:22:35 +02:00
Andy Bitz
2bf060c708 Publish Canary
- @vercel/build-utils@2.12.3-canary.14
 - vercel@23.1.3-canary.16
 - @vercel/client@10.2.3-canary.14
 - @vercel/frameworks@0.5.1-canary.10
2021-10-26 14:10:32 +02:00
Jared Palmer
c8ef1d71d1 [cli] Add vercel build (#6861)
* Add PoC pull command

* Improve pull's linking logic

* Remove `__VERCEL_SKIP_PULL_CMD` env var and unneeded type narrowing

* Improve pull's link logic

* Fix team mock

* Add smoke test for vc pull

* Add setupFixture helper

* Remove debug duplicate

* Use a fixture in pull test

* Put back debug

* Fix unit test

* Fix test on windows

* Remove mock-stdin

* Pass cwd to link and pull

* Add help command for `vc pull`

* Organize imports

* Update packages/cli/src/commands/deploy/args.ts

Co-authored-by: Steven <steven@ceriously.com>

* Use tmp-promise instead of tmp

* Update packages/cli/src/commands/pull.ts

Co-authored-by: Steven <steven@ceriously.com>

* Update packages/cli/src/commands/pull.ts

Co-authored-by: Steven <steven@ceriously.com>

* Clean up pull comments and variable declarations

* Remove graceful tmp directory cleanup

* Put back graceful cleanup

* Print output for debugging

* Moar debug

* Set 10s timeout for `vc pull` test

* Change fixture to now-pull-next

* Fix pull test name

* Switch project mock to use encrypted env

* Add --env flag

* Update fixtures

* Remove now- from everywhere

* Remove instrumentation

* Rename setupFixture to setup-fixture

* Add deprecation warning to `vc env pull`

* Update packages/cli/src/commands/deploy/args.ts

Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>

* Update packages/cli/src/commands/env/pull.ts

Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>

* Fix pull and update imports

* Revamped build command

* printConfig -> renderConfig

* Remove frameworks

* Add build state unit test for gatsby

* Update packages/cli/src/commands/pull.ts

Co-authored-by: Steven <steven@ceriously.com>

* Update packages/cli/src/commands/env/index.ts

Co-authored-by: Steven <steven@ceriously.com>

* Update packages/cli/src/util/projects/write-project-settings.ts

Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>

* Update packages/cli/src/commands/pull.ts

Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>

* Don't writeProjectSettings in env pull

* Cleanup fixtures once afterAll

* Add help text for --env and -y

* Add output for pull

* Write project settings output after env output

* Pushing for Nate

* Add todo about handling Other's build output directory

* Add support for plugins

* Improve prompt logic loop

* Pluralize plugin output

* Better plugin failure handling

* Refactor away from BuildState class

* Remove unused file

* Correct framework detection logic, smart copy w/hardlinks

* Generate build manifest

* Generate routes-manifest.json

* Remove ambiguity when calling vc build

* Make sure manifests have all keys

* Ensure that .output is added to .gitignore in vc link

* Remove directoryListing from project settings

* Add support for default cli plugins

* Remove directory listing

* Install vercel-plugin-node

* Patch console.log and console.error for plugins

* Improve build output

* Remove unused unit tests

* Allow build without token

* Add vercel plugin middleware

* Bump vercel-plugin-middleware

* Bump middleware plugin

* Tweak require.resolve

* Tweak require.resolve to __dirname

* Update `vercel-plugin-node`

* Fix prefixed logs when using formatters i.e. `%j`

* Pretty print the manifest files

* Get unique CLI deps

For the case where the local project has one of the CLI default plugins
specified.

* Update packages/cli/package.json

Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>

* Add help output

* Remove p-limit properly

* Confirm before pull in build

* Bump `vercel-plugin-node`

* [cli] Make Next.js move files into .output (#6885)

* Use OUTPUT_DIR

* Return properly if no package.json exists and no build command

* Invert logic for runPackageJsonScript

* Bump `vercel-plugin-middleware`

* Fix defaultHeaders in frameworks

* Fix build when nft files is object

* Update `yarn.lock`

* 2nd attempt at --prebuilt (#6888)

Co-authored-by: Andy Bitz <artzbitz@gmail.com>

* Add beta and feedback to vc build

Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
2021-10-26 14:04:52 +02:00
Nathan Rajlich
3d2efc7dcd [frameworks] Fix small typo in "Other" preset description (#6882) 2021-10-23 14:56:22 +00:00
jj@jjsweb.site
cd7185a872 Publish Canary
- @vercel/build-utils@2.12.3-canary.13
 - vercel@23.1.3-canary.15
 - @vercel/client@10.2.3-canary.13
 - @vercel/frameworks@0.5.1-canary.9
 - @vercel/routing-utils@1.11.4-canary.5
2021-10-21 17:58:50 -05:00
Kiko Beats
981a76fbe2 [routing-utils] Add missing fields (#6872)
* chore: add missing fields

* Update types.ts

* Update types.ts

* chore add missing as part of the schema

* test: add missing case
2021-10-21 17:57:48 -05:00
Nathan Rajlich
c35c05446b [cli] Add CLI login unit test (#6866)
This has just been sitting in my working tree for a while, might as well push it up.
2021-10-19 20:38:29 +00:00
Jared Palmer
b88e65c4ad [cli] Add vercel pull command (#6822)
Add `vercel pull` command. Closes https://github.com/vercel/runtimes/issues/142. 

![CleanShot 2021-10-19 at 08 50 07](https://user-images.githubusercontent.com/4060187/137946853-860204ba-afaa-42da-be8a-d35bec97c808.png)

It does the following:
- Pull the `.env` file (it calls `pull` internally)
- Adds the following to `.vercel/project.json` (which will then be used by `vercel build`):
   ```tsx
   interface ProjectLink {
        projectId: string
        orgId: string
        settings: {
          buildCommand: string | null,
          devCommand:  string | null,
          directoryListing:  string | null,
          outputDirectory:  string | null,
          rootDirectory:  string | null,
          framework: string | null,
        }
    }
   ```
This PR also deprecates `vc env pull` with a warning:

![CleanShot 2021-10-19 at 08 50 21](https://user-images.githubusercontent.com/4060187/137946847-e102bd99-943a-4f07-b457-fe886007c044.png)

### 📋 Checklist

- [x] Help output
- [x] Flags (need to combine flags from `env pull`)

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
2021-10-19 19:10:31 +00:00
Javi Velasco
9e16ce750b Publish Canary
- @vercel/build-utils@2.12.3-canary.12
 - vercel@23.1.3-canary.14
 - @vercel/client@10.2.3-canary.12
 - @vercel/frameworks@0.5.1-canary.8
 - @vercel/routing-utils@1.11.4-canary.4
2021-10-19 14:52:11 +02:00
Javi Velasco
2105d31730 Update middleware route (#6863) 2021-10-19 14:50:41 +02:00
jj@jjsweb.site
3d7e01ebf0 Publish Canary
- @vercel/build-utils@2.12.3-canary.11
 - vercel@23.1.3-canary.13
 - @vercel/client@10.2.3-canary.11
 - @vercel/frameworks@0.5.1-canary.7
 - @vercel/routing-utils@1.11.4-canary.3
2021-10-18 16:50:01 -05:00
JJ Kasper
dccacc4ca0 [routing-utils] Update routes schema for new property (#6860)
Adds an additional property for the `routes` schema. 

### Related Issues

N/A

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-10-18 21:45:42 +00:00
Devon Govett
be5c0da521 [example][frameworks] Add support for Parcel framework (#6836) 2021-10-14 14:53:57 -07:00
Katie Byers
f985d953ed [cli] Fix swapped error messages in executeBuild() (#6724) 2021-10-14 14:31:02 -07:00
Nathan Rajlich
b8f8289afe [cli] Use getters for Now props that mirror Client (#6838)
This will prevent any issues where the `Now` instance is out-of-sync with the `Client` instance, for example, during a re-auth where a new auth token is issued. Also reduces a bit of code which is nice.
2021-10-13 22:40:06 +00:00
Nathan Rajlich
e01a1cebfd [cli] Don't pass teamId query param to /verify token endpoint (#6841)
Fixes an issue where the token would not be properly upgraded while
a Team scope was currently active, causing a new auth token to be issued
and lose the previous access scope(s).
2021-10-13 14:39:24 -07:00
Matt Netkow
2515d522a3 [frameworks] Make "vercel dev" work with Ionic Angular projects (#6658) 2021-10-13 11:32:26 -07:00
Nathan Rajlich
32e935d632 [cli] Use GET /v2/user endpoint (#6828)
The `/www/user` endpoint is deprecated.
2021-10-13 17:20:54 +00:00
Miroslav Simulcik
e6818dd3f9 Publish Canary
- @vercel/build-utils@2.12.3-canary.10
 - vercel@23.1.3-canary.12
 - @vercel/client@10.2.3-canary.10
2021-10-13 16:52:12 +02:00
Miroslav Simulcik
e510415a66 Add regions to lambda options (#6829) 2021-10-13 16:47:18 +02:00
Nathan Rajlich
1be75712e0 [cli] Add outputBuffer getter and mutable isTTY for tests (#6827)
These changes originally from #6652, but pulled out to be merged
separately.

`outputBuffer` is a simpler way of asserting tests against the CLI
output instead of working directly withe Jest mock function.

`output.isTTY` is also now mutable, so that we can write tests for both
cases when the output is different based on TTY-ness (for example,
see the updated `vc whoami` tests in this PR).
2021-10-12 16:16:55 -07:00
Andy Bitz
f682aefc9d Publish Canary
- @vercel/build-utils@2.12.3-canary.9
 - vercel@23.1.3-canary.11
 - @vercel/client@10.2.3-canary.9
 - @vercel/frameworks@0.5.1-canary.6
2021-10-12 12:56:49 +02:00
Andy
cd485c1866 [frameworks] Add Nuxt 3 to framework detection (#6823) 2021-10-12 12:43:40 +02:00
Steven
f7de7227b4 Publish Canary
- @vercel/build-utils@2.12.3-canary.8
 - vercel@23.1.3-canary.10
 - @vercel/client@10.2.3-canary.8
2021-09-23 14:28:52 -04:00
Steven
abea217177 [build-utils] Add allowQuery to Prerender (#6766) 2021-09-23 14:25:44 -04:00
Steven
4e52f8532b Publish Canary
- @vercel/build-utils@2.12.3-canary.7
 - vercel@23.1.3-canary.9
 - @vercel/client@10.2.3-canary.7
 - @vercel/go@1.2.4-canary.3
 - @vercel/node@1.12.2-canary.4
 - @vercel/python@2.0.6-canary.4
 - @vercel/ruby@1.2.8-canary.3
2021-09-21 22:20:00 -04:00
Steven
702cb9e29c [all] Revert to @vercel/ncc@0.24.0 (#6749) 2021-09-21 22:17:06 -04:00
jj@jjsweb.site
d3d5555d79 Publish Canary
- @vercel/build-utils@2.12.3-canary.6
 - vercel@23.1.3-canary.8
 - @vercel/client@10.2.3-canary.6
 - @vercel/frameworks@0.5.1-canary.5
 - @vercel/routing-utils@1.11.4-canary.2
2021-09-20 19:35:05 -05:00
JJ Kasper
2fd3fc73e5 [routing-utils] Allow passing internal params to convertRewrites (#6742)
This adds an argument to allow passing internal param names that should be ignored when considering whether params should be auto-added to a rewrite's destination query. After adding this we should be able to resolve https://github.com/vercel/next.js/issues/27563 in the runtime where `convertRewrites` is called. 

This matches Next.js' handling for internal params which can be seen [here](e90825ad88/packages/next/shared/lib/router/utils/prepare-destination.ts (L203))

### Related Issues

x-ref: https://github.com/vercel/next.js/issues/27563

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-09-21 00:15:29 +00:00
Steven
de0b13a46e Publish Canary
- vercel@23.1.3-canary.7
 - @vercel/node@1.12.2-canary.3
2021-09-16 12:54:47 -04:00
Steven
d0fe85db92 [node] Bump nft to 0.14.0 (#6727) 2021-09-16 12:49:04 -04:00
jj@jjsweb.site
bfbd927320 Publish Canary
- @vercel/build-utils@2.12.3-canary.5
 - vercel@23.1.3-canary.6
 - @vercel/client@10.2.3-canary.5
 - @vercel/frameworks@0.5.1-canary.4
 - @vercel/routing-utils@1.11.4-canary.1
2021-09-14 15:02:32 -05:00
JJ Kasper
90bacf88b8 [routing-utils] Fix host segment replacing (#6713)
* Fix host segment replacing

* Add additional check
2021-09-14 13:20:35 -05:00
Steven
07c369c542 Publish Canary
- @vercel/build-utils@2.12.3-canary.4
 - vercel@23.1.3-canary.5
 - @vercel/client@10.2.3-canary.4
 - @vercel/go@1.2.4-canary.2
 - @vercel/node@1.12.2-canary.2
 - @vercel/python@2.0.6-canary.3
 - @vercel/ruby@1.2.8-canary.2
2021-09-13 16:32:45 -04:00
Steven
a2e4186ccb [all] Bump ncc to 0.31.1 (#6700)
https://github.com/vercel/ncc/releases/tag/0.31.0

https://github.com/vercel/ncc/releases/tag/0.31.1
2021-09-13 20:20:48 +00:00
Steven
6e1d708e3f Publish Canary
- vercel@23.1.3-canary.4
 - @vercel/python@2.0.6-canary.2
2021-09-08 13:56:20 -04:00
Noa
38503103c3 [python] Use pip --upgrade when installing function dependencies (#6683)
Co-authored-by: Steven <steven@ceriously.com>
2021-09-08 13:54:03 -04:00
jj@jjsweb.site
e8fec4b69c Publish Canary
- @vercel/build-utils@2.12.3-canary.3
 - vercel@23.1.3-canary.3
 - @vercel/client@10.2.3-canary.3
 - @vercel/frameworks@0.5.1-canary.3
 - @vercel/routing-utils@1.11.4-canary.0
2021-09-07 11:52:01 -05:00
JJ Kasper
b3ffcdf80d [routing-utils] Ensure headers with only has items are replaced correctly (#6686)
This ensures we replace header values correctly when no named segments are used and only has items are used. 

### Related Issues

Fixes: https://vercel.slack.com/archives/CHTTGQYQ4/p1631023974185700

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-09-07 16:17:01 +00:00
Leo Lamprecht
43c1a93c1d Enabled blank issues temporarily 2021-09-06 18:24:53 +02:00
Leo Lamprecht
5b118fd4e6 Disable blank issues again 2021-09-06 14:47:15 +02:00
Leo Lamprecht
8916b674af Temporarily enable blank issues 2021-09-06 14:41:32 +02:00
Brody McKee
1807f83c69 Update NPM publish token (#6672) 2021-09-03 19:44:59 +03:00
Steven
74e8ec7c64 Fix lerna publish for automation token (#6666)
Related to https://github.com/lerna/lerna/issues/2788
2021-09-03 00:20:20 +00:00
Steven
2644e3127b Publish Canary
- @vercel/build-utils@2.12.3-canary.2
 - vercel@23.1.3-canary.2
 - @vercel/client@10.2.3-canary.2
2021-09-02 08:42:33 -04:00
Leo Lamprecht
d77ac04b0c Disable blank issues again 2021-09-02 13:52:18 +02:00
Leo Lamprecht
0ef9c8df4d Temporarily enable issues 2021-09-02 13:45:20 +02:00
Steven
dfc4c98820 [build-utils] Fix custom 404 route (#6657)
The Custom 404 feature was originally implemented in #4563 but was matching too broadly (see [gist](https://gist.github.com/kjk/4dc57da62d7e715c687cc7914847ffb2))

This PR fixes the custom 404 route and updates the tests.
2021-09-02 00:12:45 +00:00
Steven
0e51884725 Publish Canary
- @vercel/build-utils@2.12.3-canary.1
 - vercel@23.1.3-canary.1
 - @vercel/client@10.2.3-canary.1
 - @vercel/frameworks@0.5.1-canary.2
 - @vercel/go@1.2.4-canary.1
 - @vercel/node-bridge@2.1.1-canary.1
 - @vercel/node@1.12.2-canary.1
 - @vercel/python@2.0.6-canary.1
 - @vercel/ruby@1.2.8-canary.1
2021-08-31 17:18:35 -04:00
Steven
1b264fe60e [build-utils] Add allowQuery to Lambda (#6651) 2021-08-31 17:17:31 -04:00
Nathan Rajlich
f18bca9718 [cli] Refactor legacy Now client to TypeScript (#6650) 2021-08-31 12:47:17 -07:00
Steven
c23dc73f41 [examples] Bump Next.js to 11.1.2 (#6648)
* Bump Next.js to 11.1.1

* Bump Next.js to 11.1.2
2021-08-31 10:53:18 -04:00
Nathan Rajlich
273718e0b7 [cli] Rewrite Unit tests to TypeScript + Jest (#6638)
* Rewrites the CLI unit tests to be TypeScript and use Jest (consistent with the unit tests in the other packages in this repo).
* The file structure of the new test files mirrors that of the `src` directory, so that it's easy to find the relevant tests.
* Code coverage is also properly set up through Jest - you can already see a big increase in coverage from this PR.
* Adds a mock API server framework, with the intention of making it possible to write granular tests of the CLI commands. Using mocks also has the benefit of not requiring `VERCEL_TOKEN` env var to be set, so 3rd party PRs will be able to have their tests run. Ultimately this will also help with test coverage, since we will be writing unit tests that test the commands' code directly.
* Converts `Output` into a proper class (which is subclassed for the mocks).
2021-08-30 22:07:09 +00:00
Nathan Rajlich
230b88bf9b [cli] Remove broken vc downgrade command (#6643)
It maps to an "upgrade" command, which does not exist.

Fixes:

```
$ vc downgrade
Vercel CLI 23.1.2
Error! Cannot find module './upgrade'
```
2021-08-28 18:01:31 +00:00
Nathan Rajlich
676a3d2568 [cli] Refactor src/index to TypeScript (#6602)
Refactors the CLI entrypoint `src/index.js` to TypeScript.
2021-08-27 19:48:31 +00:00
Nathan Rajlich
f221f041d0 Update @vercel/ncc to v0.29.2 (#6605) 2021-08-27 10:03:36 -07:00
Kaitlyn
aca42b2aac [examples] Update angular example to npm 7 (#6636) 2021-08-25 17:24:37 -07:00
Kaitlyn Carter
cf11a8efb5 Revert "delete yarn.lock"
This reverts commit b941715d7b.
2021-08-25 18:43:29 -04:00
Kaitlyn Carter
be09349daf Revert "update npm peer dependencies"
This reverts commit a01372bcbb.
2021-08-25 18:34:21 -04:00
Kaitlyn Carter
a01372bcbb update npm peer dependencies 2021-08-25 17:51:22 -04:00
Kaitlyn Carter
b941715d7b delete yarn.lock 2021-08-25 17:48:44 -04:00
Nathan Rajlich
ee9a8a0415 [cli] Refactor vc teams to TypeScript (#6610) 2021-08-24 11:08:30 -07:00
jj@jjsweb.site
2ad27eefb0 Publish Canary
- @vercel/build-utils@2.12.3-canary.0
 - vercel@23.1.3-canary.0
 - @vercel/client@10.2.3-canary.0
 - @vercel/frameworks@0.5.1-canary.1
 - @vercel/go@1.2.4-canary.0
 - @vercel/node-bridge@2.1.1-canary.0
 - @vercel/node@1.12.2-canary.0
 - @vercel/python@2.0.6-canary.0
 - @vercel/ruby@1.2.8-canary.0
2021-08-24 09:36:40 -05:00
Nathan Rajlich
578fe8a930 [cli] Support --project flag in vc link command (#6614)
To make setting up local dev README instructions easier for new users being introduced to a Vercel project, support flags to make the `vc link` command be non-interactive, in the case where the project name does not match the name of the directory where the code is located:

```
$ vc link --scope acme --project docs
```

Related to https://github.com/vercel/front/pull/10732.
2021-08-23 23:22:57 +00:00
JJ Kasper
04ea3bb88d [node-bridge] Fix error in node-bridge from decoded path (#6583)
* Fix error in node-bridge from decoded path

* Apply suggestions from code review

Co-authored-by: Steven <steven@ceriously.com>
2021-08-23 14:50:18 -05:00
Steven
46116022b7 [cli] Update readme (#6622) 2021-08-23 12:04:38 -04:00
Lee Robinson
f80539df82 Update README (#6618) 2021-08-22 23:39:04 +00:00
Johan Eliasson
daf06307b4 Fix deprecation message for NowRequestBody (#6613) 2021-08-20 12:58:47 -07:00
Nathan Rajlich
0bd028cd84 [cli] Show server-side errorMessage upon deployment UNEXPECTED_ERROR (#6606)
Before:

```
Error! Unexpected error. Please try again later. ()
```

After:

```
Error! An unexpected error happened when running this build. We have been notified of the problem. If you have any questions, please contact support@vercel.com.
```
2021-08-17 18:28:56 -07:00
Nathan Rajlich
1c48030e1e [cli] Stop installing @now/build-utils for vc dev (#6604)
Users should not be using any legacy Runtimes that depend on `@now/build-utils` at this point, since those have not received updates in a long time.
2021-08-17 17:35:55 +00:00
Nathan Rajlich
1dc05428d7 [go][node][python][ruby] Remove @now/build-utils backwards compat hack (#6603)
`@now/build-utils` has not been published in a long time, so let's remove this logic.
2021-08-17 15:29:52 +00:00
Nathan Rajlich
288dca045c [cli] Refactor a handful of util modules to TypeScript (#6584) 2021-08-13 20:26:02 +00:00
Steven
8c5bc04fde Fix publish script for Windows (#6591)
* Fix publish script for Windows

* Update changelog.js
2021-08-13 12:03:54 -04:00
Steven
a07e6fc103 [examples] Bump Next.js to 11.1.0 (#6582) 2021-08-11 15:41:38 -04:00
Nathan Rajlich
9af3054d41 [cli] Use client.fetch() in vc init (#6575)
Gives us debug logging and retries, etc.
2021-08-11 19:04:01 +00:00
Nathan Rajlich
9fb254e14a [cli] Attempt to fix the "lambda-with-3-second-timeout" E2E test (#6579) 2021-08-11 00:50:57 -07:00
William Li
3616bdf17a bump react-scripts to @latest (#6577) 2021-08-11 11:11:43 +08:00
Nathan Rajlich
52a89fd4b7 [cli] Remove withSpinner() helper (#6576)
It's not really necessary and doesn't use the common `Output` instance.
2021-08-10 10:41:44 -07:00
Nathan Rajlich
d4db6635f1 [cli] Remove unnecessary await in Dev tests (#6572)
This is the result of VS Code's "remove all unneeded await calls" formatter.
2021-08-10 02:01:56 -07:00
Nathan Rajlich
f1009a80cd [api] Fix GET /api/examples/list output (#6574)
A regression from #6554 caused the return value to contain a nested
object with a `name` property for the `name` key of the response in the
list.
2021-08-09 22:24:17 -07:00
Steven
2756d1e323 [client][frameworks][api] Update readdir() call with withFileTypes (#6554)
Avoids running unnecessary code such as `stat().isDirectory()`.
2021-08-09 14:27:50 -07:00
Nathan Rajlich
5b61b16bd1 Publish Stable
- @vercel/build-utils@2.12.2
 - vercel@23.1.2
 - @vercel/client@10.2.2
 - @vercel/node@1.12.1
2021-08-09 11:21:40 -07:00
Nathan Rajlich
41c61f8f8b Publish Canary
- vercel@23.1.2-canary.1
2021-08-09 10:00:43 -07:00
Nathan Rajlich
6c52e1fad7 [cli] Add "outDir" to tsconfig.json (#6566)
Fixes TypeScript errors.
2021-08-09 09:58:30 -07:00
Nathan Rajlich
d2e82fdc3a [cli] Fix in-flight re-login when there are no existing credentials (#6565) 2021-08-08 00:57:23 -07:00
Nathan Rajlich
a60b1b225b Publish Canary
- @vercel/build-utils@2.12.2-canary.0
 - vercel@23.1.2-canary.0
 - @vercel/client@10.2.2-canary.0
 - @vercel/node@1.12.1-canary.0
2021-08-06 17:15:13 -07:00
Kaitlyn
18bec983ae [build-utils] check to see that the node version is less then 16 befo… (#6553)
### Related Issues

Check the project's nodeVersion setting for when we release Node 16 and later

### 📋 Checklist

<!--
  Please keep your PR as a Draft until the checklist is complete
-->

#### Tests

- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`

#### Code Review

- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
2021-08-07 00:14:21 +00:00
Nathan Rajlich
e6fb2ffe05 Publish Stable
- @vercel/build-utils@2.12.1
 - vercel@23.1.1
 - @vercel/client@10.2.1
2021-08-06 13:00:16 -07:00
Nathan Rajlich
0533cfd566 [build-utils] Fix test name 2021-08-06 12:48:58 -07:00
667 changed files with 66130 additions and 14997 deletions

View File

@@ -1,11 +1,10 @@
node_modules
dist
examples
packages/build-utils/test/fixtures
packages/*/test/fixtures
packages/cli/@types
packages/cli/download
packages/cli/dist
packages/cli/test/fixtures
packages/cli/test/dev/fixtures
packages/cli/bin
packages/cli/link
@@ -13,6 +12,6 @@ packages/cli/src/util/dev/templates/*.ts
packages/client/tests/fixtures
packages/client/lib
packages/node/src/bridge.ts
packages/node/test/fixtures
packages/node-bridge/bridge.js
packages/node-bridge/launcher.js
packages/middleware/src/entries.js

View File

@@ -1,4 +1,4 @@
blank_issues_enabled: false
blank_issues_enabled: true
contact_links:
- name: Bug Report
url: https://vercel.com/support/request

View File

@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 2
steps:
- uses: styfle/cancel-workflow-action@0.4.1
- uses: styfle/cancel-workflow-action@0.9.1
with:
workflow_id: 849295, 849296, 849297, 849298
access_token: ${{ github.token }}

View File

@@ -29,6 +29,6 @@ jobs:
- name: Publish
run: yarn publish-from-github
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN_ELEVATED }}
GA_TRACKING_ID: ${{ secrets.GA_TRACKING_ID }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}

View File

@@ -11,7 +11,7 @@ on:
jobs:
test:
name: Dev
timeout-minutes: 60
timeout-minutes: 75
strategy:
fail-fast: false
matrix:

1
.gitignore vendored
View File

@@ -27,3 +27,4 @@ test/lib/deployment/failed-page.txt
/public
__pycache__
.vercel
.output

View File

@@ -332,7 +332,7 @@ This is an abstract enumeration type that is implemented by one of the following
- `nodejs10.x`
- `go1.x`
- `java11`
- `python3.8`
- `python3.9`
- `python3.6`
- `dotnetcore2.1`
- `ruby2.5`
@@ -398,12 +398,12 @@ This utility allows you to _scan_ the filesystem and return a [`Files`](#files)
The following trivial example downloads everything to the filesystem, only to return it back (therefore just re-creating the passed-in [`Files`](#files)):
```js
const { glob, download } = require('@vercel/build-utils')
const { glob, download } = require('@vercel/build-utils');
exports.build = ({ files, workPath }) => {
await download(files, workPath)
return glob('**', workPath)
}
await download(files, workPath);
return glob('**', workPath);
};
```
### `getWritableDirectory()`

View File

@@ -11,7 +11,11 @@
## Usage
Vercel is the optimal workflow for frontend teams. All-in-one: Static and Jamstack deployment, Serverless Functions, and Global CDN.
Vercel is a platform for **static sites and frontend frameworks**, built to integrate with your headless content, commerce, or database.
We provide a **frictionless developer experience** to take care of the hard things: deploy instantly, scale automatically, and serve personalized content around the globe.
We make it easy for frontend teams to **develop, preview, and ship** delightful user experiences, where performance is the default.
Get started by [Importing a Git Project](https://vercel.com/new) and use `git push` to deploy. Alternatively, you can [install Vercel CLI](https://vercel.com/cli).

View File

@@ -2,19 +2,19 @@
* Get example list from extracted folder
*/
import { join } from 'path';
import { lstatSync, existsSync, readdirSync } from 'fs';
const exists = (path: string) => existsSync(path);
const isDotFile = (name: string) => name.startsWith('.');
const isDirectory = (path: string) => lstatSync(path).isDirectory();
export function summary(source: string) {
export function summary(source: string): string[] {
if (!exists(source) || !isDirectory(source)) {
return [];
}
return readdirSync(source)
.filter(name => !isDotFile(name))
.filter(name => isDirectory(join(source, name)));
return readdirSync(source, { withFileTypes: true })
.filter(d => !isDotFile(d.name))
.filter(d => d.isDirectory())
.map(d => d.name);
}

View File

@@ -14,8 +14,6 @@ const frameworks = (_frameworks as Framework[])
sort: undefined,
dependency: undefined,
defaultRoutes: undefined,
devCommand: undefined,
buildCommand: undefined,
};
if (framework.logo) {

View File

@@ -5,7 +5,7 @@
"description": "API for the vercel/vercel repo",
"main": "index.js",
"scripts": {
"vercel-build": "yarn --cwd .. && node ../utils/run.js build all"
"vercel-build": "node ../utils/run.js build all"
},
"dependencies": {
"@sentry/node": "5.11.1",

View File

@@ -6,3 +6,5 @@ coverage:
project: off
patch: off
fixes:
- "::packages/cli/" # move root e.g., "path/" => "after/path/"

13218
examples/angular/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -12,37 +12,38 @@
},
"private": true,
"dependencies": {
"@angular/animations": "~8.1.0",
"@angular/common": "~8.1.0",
"@angular/compiler": "~8.1.0",
"@angular/core": "~8.1.0",
"@angular/forms": "~8.1.0",
"@angular/platform-browser": "~8.1.0",
"@angular/platform-browser-dynamic": "~8.1.0",
"@angular/router": "~8.1.0",
"@angular/animations": "^8.1.0",
"@angular/common": "^8.1.0",
"@angular/core": "^8.1.0",
"@angular/forms": "^8.1.0",
"@angular/platform-browser": "^8.1.0",
"@angular/platform-browser-dynamic": "^8.1.0",
"@angular/router": "^8.1.0",
"rxjs": "~6.4.0",
"tslib": "^1.9.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.801.0",
"@angular/cli": "~8.1.0",
"@angular/compiler-cli": "~8.1.0",
"@angular-devkit/build-angular": "^12.2.2",
"@angular/cli": "^12.2.2",
"@angular/compiler": "^12.2.2",
"@angular/compiler-cli": "^12.2.2",
"@angular/language-service": "~8.1.0",
"@types/node": "~8.9.4",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"glob-parent": "^5.1.2",
"jasmine-core": "^3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma": "^6.3.4",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"protractor": "^7.0.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.4.3"
"typescript": "^4.2.4"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,7 @@
"dependencies": {
"react": "^16.6.1",
"react-dom": "^16.6.1",
"react-scripts": "2.1.1"
"react-scripts": "^4.0.3"
},
"scripts": {
"dev": "BROWSER=none react-scripts start",

View File

@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

View File

@@ -29,6 +29,6 @@ You can check out [the Next.js GitHub repository](https://github.com/vercel/next
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/import?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View File

@@ -0,0 +1,3 @@
module.exports = {
reactStrictMode: true,
}

15787
examples/nextjs/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,20 @@
{
"name": "nextjs",
"version": "0.1.0",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "10.x",
"react": "17.x",
"react-dom": "17.x"
"next": "12.0.1",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-config-next": "11.1.0"
}
}

View File

@@ -1,6 +1,5 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}

View File

@@ -1,4 +1,5 @@
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
export default function Home() {
@@ -6,6 +7,7 @@ export default function Home() {
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
@@ -21,12 +23,12 @@ export default function Home() {
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h3>Documentation &rarr;</h3>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
<h3>Learn &rarr;</h3>
<h2>Learn &rarr;</h2>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>
@@ -34,15 +36,15 @@ export default function Home() {
href="https://github.com/vercel/next.js/tree/master/examples"
className={styles.card}
>
<h3>Examples &rarr;</h3>
<h2>Examples &rarr;</h2>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>
<a
href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h3>Deploy &rarr;</h3>
<h2>Deploy &rarr;</h2>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
@@ -57,7 +59,9 @@ export default function Home() {
rel="noopener noreferrer"
>
Powered by{' '}
<img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>

View File

@@ -5,6 +5,7 @@
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
.main {
@@ -25,14 +26,11 @@
align-items: center;
}
.footer img {
margin-left: 0.5rem;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title a {
@@ -82,7 +80,6 @@
.card {
margin: 1rem;
flex-basis: 45%;
padding: 1.5rem;
text-align: left;
color: inherit;
@@ -90,6 +87,7 @@
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
width: 45%;
}
.card:hover,
@@ -99,7 +97,7 @@
border-color: #0070f3;
}
.card h3 {
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
@@ -112,6 +110,7 @@
.logo {
height: 1em;
margin-left: 0.5rem;
}
@media (max-width: 600px) {

File diff suppressed because it is too large Load Diff

7
examples/parcel/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
node_modules
.parcel-cache
dist
/.pnp
.pnp.js
.DS_Store
.vercel

34
examples/parcel/README.md Normal file
View File

@@ -0,0 +1,34 @@
This is a vanilla web app built with [Parcel](https://parceljs.org).
## Getting Started
Run the dev server:
```bash
yarn start
# or
npm start
```
And open [localhost:1234](http://localhost:1234) in your browser!
As you make changes, you should see your app automatically update in the browser without even refreshing the page!
## Learn More
- [Getting started guide](https://parceljs.org/getting-started/webapp/)
- [Documentation](https://parceljs.org/docs/)
## Deploy Your Own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/vercel/tree/main/examples/parcel&template=parcel)
_Live Example: https://parcel.examples.vercel.com_
### Deploying From Your Terminal
You can deploy your new Parcel project with a single command from your terminal using [Vercel CLI](https://vercel.com/download):
```shell
$ vercel
```

View File

@@ -0,0 +1,12 @@
{
"name": "parcel-app",
"private": true,
"source": "src/index.html",
"scripts": {
"start": "parcel",
"build": "parcel build"
},
"devDependencies": {
"parcel": "^2.0.0"
}
}

View File

@@ -0,0 +1 @@
console.log('Hello world!');

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My First Parcel App</title>
<link rel="stylesheet" href="styles.css" />
<script type="module" src="app.js"></script>
</head>
<body>
<h1>Hello, Parcel!</h1>
<p>This is a vanilla web app built with Parcel 2!<br>Check out the <a href="https://parceljs.org/getting-started/webapp/" target="_blank">getting started guide</a> and the <a href="https://parceljs.org/docs/" target="_blank">documentation</a> to learn more!</p>
</body>
</html>

View File

@@ -0,0 +1,18 @@
body {
text-align: center;
}
h1 {
color: hotpink;
font-family: cursive;
font-size: 55px;
}
p {
font-family: Helvetica, Arial, sans-serif;
line-height: 1.5em;
}
a {
color: dodgerblue;
}

4541
examples/parcel/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

8
examples/remix/.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
node_modules
.cache
.vercel
.output
public/build
api/_build

34
examples/remix/README.md Normal file
View File

@@ -0,0 +1,34 @@
# Welcome to Remix!
- [Remix Docs](https://remix.run/docs)
## Deployment
After having run the `create-remix` command and selected "Vercel" as a deployment target, you only need to [import your Git repository](https://vercel.com/new) into Vercel, and it will be deployed.
If you'd like to avoid using a Git repository, you can also deploy the directory by running [Vercel CLI](https://vercel.com/cli):
```sh
npm i -g vercel
vercel
```
It is generally recommended to use a Git repository, because future commits will then automatically be deployed by Vercel, through its [Git Integration](https://vercel.com/docs/concepts/git).
## Development
To run your Remix app locally, make sure your project's local dependencies are installed:
```sh
npm install
```
Afterwards, start the Remix development server like so:
```sh
npm run dev
```
Open up [http://localhost:3000](http://localhost:3000) and you should be ready to go!
If you're used to using the `vercel dev` command provided by [Vercel CLI](https://vercel.com/cli) instead, you can also use that, but it's not needed.

View File

@@ -0,0 +1,5 @@
const { createRequestHandler } = require("@remix-run/vercel");
module.exports = createRequestHandler({
build: require("./_build")
});

View File

@@ -0,0 +1,4 @@
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";
hydrate(<RemixBrowser />, document);

View File

@@ -0,0 +1,21 @@
import { renderToString } from "react-dom/server";
import { RemixServer } from "remix";
import type { EntryContext } from "remix";
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
let markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
responseHeaders.set("Content-Type", "text/html");
return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders
});
}

178
examples/remix/app/root.tsx Normal file
View File

@@ -0,0 +1,178 @@
import {
Link,
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useCatch
} from "remix";
import type { LinksFunction } from "remix";
import globalStylesUrl from "~/styles/global.css";
import darkStylesUrl from "~/styles/dark.css";
// https://remix.run/api/app#links
export let links: LinksFunction = () => {
return [
{ rel: "stylesheet", href: globalStylesUrl },
{
rel: "stylesheet",
href: darkStylesUrl,
media: "(prefers-color-scheme: dark)"
}
];
};
// https://remix.run/api/conventions#default-export
// https://remix.run/api/conventions#route-filenames
export default function App() {
return (
<Document>
<Layout>
<Outlet />
</Layout>
</Document>
);
}
// https://remix.run/docs/en/v1/api/conventions#errorboundary
export function ErrorBoundary({ error }: { error: Error }) {
console.error(error);
return (
<Document title="Error!">
<Layout>
<div>
<h1>There was an error</h1>
<p>{error.message}</p>
<hr />
<p>
Hey, developer, you should replace this with what you want your
users to see.
</p>
</div>
</Layout>
</Document>
);
}
// https://remix.run/docs/en/v1/api/conventions#catchboundary
export function CatchBoundary() {
let caught = useCatch();
let message;
switch (caught.status) {
case 401:
message = (
<p>
Oops! Looks like you tried to visit a page that you do not have access
to.
</p>
);
break;
case 404:
message = (
<p>Oops! Looks like you tried to visit a page that does not exist.</p>
);
break;
default:
throw new Error(caught.data || caught.statusText);
}
return (
<Document title={`${caught.status} ${caught.statusText}`}>
<Layout>
<h1>
{caught.status}: {caught.statusText}
</h1>
{message}
</Layout>
</Document>
);
}
function Document({
children,
title
}: {
children: React.ReactNode;
title?: string;
}) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
{title ? <title>{title}</title> : null}
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
{process.env.NODE_ENV === "development" && <LiveReload />}
</body>
</html>
);
}
function Layout({ children }: { children: React.ReactNode }) {
return (
<div className="remix-app">
<header className="remix-app__header">
<div className="container remix-app__header-content">
<Link to="/" title="Remix" className="remix-app__header-home-link">
<RemixLogo />
</Link>
<nav aria-label="Main navigation" className="remix-app__header-nav">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<a href="https://remix.run/docs">Remix Docs</a>
</li>
<li>
<a href="https://github.com/remix-run/remix">GitHub</a>
</li>
</ul>
</nav>
</div>
</header>
<div className="remix-app__main">
<div className="container remix-app__main-content">{children}</div>
</div>
<footer className="remix-app__footer">
<div className="container remix-app__footer-content">
<p>&copy; You!</p>
</div>
</footer>
</div>
);
}
function RemixLogo() {
return (
<svg
viewBox="0 0 659 165"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
aria-labelledby="remix-run-logo-title"
role="img"
width="106"
height="30"
fill="currentColor"
>
<title id="remix-run-logo-title">Remix Logo</title>
<path d="M0 161V136H45.5416C53.1486 136 54.8003 141.638 54.8003 145V161H0Z M133.85 124.16C135.3 142.762 135.3 151.482 135.3 161H92.2283C92.2283 158.927 92.2653 157.03 92.3028 155.107C92.4195 149.128 92.5411 142.894 91.5717 130.304C90.2905 111.872 82.3473 107.776 67.7419 107.776H54.8021H0V74.24H69.7918C88.2407 74.24 97.4651 68.632 97.4651 53.784C97.4651 40.728 88.2407 32.816 69.7918 32.816H0V0H77.4788C119.245 0 140 19.712 140 51.2C140 74.752 125.395 90.112 105.665 92.672C122.32 96 132.057 105.472 133.85 124.16Z" />
<path d="M229.43 120.576C225.59 129.536 218.422 133.376 207.158 133.376C194.614 133.376 184.374 126.72 183.35 112.64H263.478V101.12C263.478 70.1437 243.254 44.0317 205.11 44.0317C169.526 44.0317 142.902 69.8877 142.902 105.984C142.902 142.336 169.014 164.352 205.622 164.352C235.83 164.352 256.822 149.76 262.71 123.648L229.43 120.576ZM183.862 92.6717C185.398 81.9197 191.286 73.7277 204.598 73.7277C216.886 73.7277 223.542 82.4317 224.054 92.6717H183.862Z" />
<path d="M385.256 66.5597C380.392 53.2477 369.896 44.0317 349.672 44.0317C332.52 44.0317 320.232 51.7117 314.088 64.2557V47.1037H272.616V161.28H314.088V105.216C314.088 88.0638 318.952 76.7997 332.52 76.7997C345.064 76.7997 348.136 84.9917 348.136 100.608V161.28H389.608V105.216C389.608 88.0638 394.216 76.7997 408.04 76.7997C420.584 76.7997 423.4 84.9917 423.4 100.608V161.28H464.872V89.5997C464.872 65.7917 455.656 44.0317 424.168 44.0317C404.968 44.0317 391.4 53.7597 385.256 66.5597Z" />
<path d="M478.436 47.104V161.28H519.908V47.104H478.436ZM478.18 36.352H520.164V0H478.18V36.352Z" />
<path d="M654.54 47.1035H611.788L592.332 74.2395L573.388 47.1035H527.564L568.78 103.168L523.98 161.28H566.732L589.516 130.304L612.3 161.28H658.124L613.068 101.376L654.54 47.1035Z" />
</svg>
);
}

View File

@@ -0,0 +1,44 @@
import { Outlet } from "remix";
import type { MetaFunction, LinksFunction } from "remix";
import stylesUrl from "~/styles/demos/about.css";
export let meta: MetaFunction = () => {
return {
title: "About Remix"
};
};
export let links: LinksFunction = () => {
return [{ rel: "stylesheet", href: stylesUrl }];
};
export default function Index() {
return (
<div className="about">
<div className="about__intro">
<h2>About Us</h2>
<p>
Ok, so this page isn't really <em>about us</em>, but we did want to
show you a few more things Remix can do.
</p>
<p>
Did you notice that things look a little different on this page? The
CSS that we import in the route file and include in its{" "}
<code>links</code> export is only included on this route and its
children.
</p>
<p>
Wait a sec...<em>its children</em>? To understand what we mean by
this,{" "}
<a href="https://remix.run/tutorial/4-nested-routes-params">
read all about nested routes in the docs
</a>
.
</p>
<hr />
<Outlet />
</div>
</div>
);
}

View File

@@ -0,0 +1,17 @@
import { Link } from "remix";
export default function AboutIndex() {
return (
<div>
<p>
You are looking at the index route for the <code>/about</code> URL
segment, but there are nested routes as well!
</p>
<p>
<strong>
<Link to="whoa">Check out one of them here.</Link>
</strong>
</p>
</div>
);
}

View File

@@ -0,0 +1,20 @@
import { Link } from "remix";
export default function AboutIndex() {
return (
<div>
<p>
Whoa, this is a nested route! We render the <code>/about</code> layout
route component, and its <code>Outlet</code> renders our route
component. 🤯
</p>
<p>
<strong>
<Link to="..">
Go back to the <code>/about</code> index.
</Link>
</strong>
</p>
</div>
);
}

View File

@@ -0,0 +1,101 @@
import { useEffect, useRef } from "react";
import type { ActionFunction } from "remix";
import { Form, json, useActionData, redirect } from "remix";
export function meta() {
return { title: "Actions Demo" };
}
// When your form sends a POST, the action is called on the server.
// - https://remix.run/api/conventions#action
// - https://remix.run/guides/data-updates
export let action: ActionFunction = async ({ request }) => {
let formData = await request.formData();
let answer = formData.get("answer");
// Typical action workflows start with validating the form data that just came
// over the network. Clientside validation is fine, but you definitely need it
// server side. If there's a problem, return the the data and the component
// can render it.
if (typeof answer !== "string") {
return json("Come on, at least try!", { status: 400 });
}
if (answer !== "egg") {
return json(`Sorry, ${answer} is not right.`, { status: 400 });
}
// Finally, if the data is valid, you'll typically write to a database or send or
// email or log the user in, etc. It's recommended to redirect after a
// successful action, even if it's to the same place so that non-JavaScript workflows
// from the browser doesn't repost the data if the user clicks back.
return redirect("/demos/correct");
};
export default function ActionsDemo() {
// https://remix.run/api/remix#useactiondata
let actionMessage = useActionData<string>();
let answerRef = useRef<HTMLInputElement>(null);
// This form works without JavaScript, but when we have JavaScript we can make
// the experience better by selecting the input on wrong answers! Go ahead, disable
// JavaScript in your browser and see what happens.
useEffect(() => {
if (actionMessage && answerRef.current) {
answerRef.current.select();
}
}, [actionMessage]);
return (
<div className="remix__page">
<main>
<h2>Actions!</h2>
<p>
This form submission will send a post request that we handle in our
`action` export. Any route can export an action to handle data
mutations.
</p>
<Form method="post" className="remix__form">
<h3>Post an Action</h3>
<p>
<i>What is more useful when it is broken?</i>
</p>
<label>
<div>Answer:</div>
<input ref={answerRef} name="answer" type="text" />
</label>
<div>
<button>Answer!</button>
</div>
{actionMessage ? (
<p>
<b>{actionMessage}</b>
</p>
) : null}
</Form>
</main>
<aside>
<h3>Additional Resources</h3>
<ul>
<li>
Guide:{" "}
<a href="https://remix.run/guides/data-writes">Data Writes</a>
</li>
<li>
API:{" "}
<a href="https://remix.run/api/conventions#action">
Route Action Export
</a>
</li>
<li>
API:{" "}
<a href="https://remix.run/api/remix#useactiondata">
<code>useActionData</code>
</a>
</li>
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,3 @@
export default function NiceWork() {
return <h1>You got it right!</h1>;
}

View File

@@ -0,0 +1,43 @@
import { useCatch, Link, json, useLoaderData, Outlet } from "remix";
export function meta() {
return { title: "Boundaries Demo" };
}
export default function Boundaries() {
return (
<div className="remix__page">
<main>
<Outlet />
</main>
<aside>
<h2>Click these Links</h2>
<ul>
<li>
<Link to=".">Start over</Link>
</li>
<li>
<Link to="one">
Param: <i>one</i>
</Link>
</li>
<li>
<Link to="two">
Param: <i>two</i>
</Link>
</li>
<li>
<Link to="this-record-does-not-exist">This will be a 404</Link>
</li>
<li>
<Link to="shh-its-a-secret">And this will be 401 Unauthorized</Link>
</li>
<li>
<Link to="kaboom">This one will throw an error</Link>
</li>
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,110 @@
import { useCatch, Link, json, useLoaderData } from "remix";
import type { LoaderFunction, MetaFunction } from "remix";
// The `$` in route filenames becomes a pattern that's parsed from the URL and
// passed to your loaders so you can look up data.
// - https://remix.run/api/conventions#loader-params
export let loader: LoaderFunction = async ({ params }) => {
// pretend like we're using params.id to look something up in the db
if (params.id === "this-record-does-not-exist") {
// If the record doesn't exist we can't render the route normally, so
// instead we throw a 404 reponse to stop running code here and show the
// user the catch boundary.
throw new Response("Not Found", { status: 404 });
}
// now pretend like the record exists but the user just isn't authorized to
// see it.
if (params.id === "shh-its-a-secret") {
// Again, we can't render the component if the user isn't authorized. You
// can even put data in the response that might help the user rectify the
// issue! Like emailing the webmaster for access to the page. (Oh, right,
// `json` is just a Response helper that makes it easier to send JSON
// responses).
throw json({ webmasterEmail: "hello@remix.run" }, { status: 401 });
}
// Sometimes your code just blows up and you never anticipated it. Remix will
// automatically catch it and send the UI to the error boundary.
if (params.id === "kaboom") {
lol();
}
// but otherwise the record was found, user has access, so we can do whatever
// else we needed to in the loader and return the data. (This is boring, we're
// just gonna return the params.id).
return { param: params.id };
};
export default function ParamDemo() {
let data = useLoaderData();
return (
<h1>
The param is <i style={{ color: "red" }}>{data.param}</i>
</h1>
);
}
// https://remix.run/api/conventions#catchboundary
// https://remix.run/api/remix#usecatch
// https://remix.run/api/guides/not-found
export function CatchBoundary() {
let caught = useCatch();
let message: React.ReactNode;
switch (caught.status) {
case 401:
message = (
<p>
Looks like you tried to visit a page that you do not have access to.
Maybe ask the webmaster ({caught.data.webmasterEmail}) for access.
</p>
);
case 404:
message = (
<p>Looks like you tried to visit a page that does not exist.</p>
);
default:
message = (
<p>
There was a problem with your request!
<br />
{caught.status} {caught.statusText}
</p>
);
}
return (
<>
<h2>Oops!</h2>
<p>{message}</p>
<p>
(Isn't it cool that the user gets to stay in context and try a different
link in the parts of the UI that didn't blow up?)
</p>
</>
);
}
// https://remix.run/api/conventions#errorboundary
// https://remix.run/api/guides/not-found
export function ErrorBoundary({ error }: { error: Error }) {
console.error(error);
return (
<>
<h2>Error!</h2>
<p>{error.message}</p>
<p>
(Isn't it cool that the user gets to stay in context and try a different
link in the parts of the UI that didn't blow up?)
</p>
</>
);
}
export let meta: MetaFunction = ({ data }) => {
return {
title: data ? `Param: ${data.param}` : "Oops...",
};
};

View File

@@ -0,0 +1,40 @@
import { useCatch, Link, json, useLoaderData, Outlet } from "remix";
import type { LoaderFunction } from "remix";
export default function Boundaries() {
return (
<>
<h2>Params</h2>
<p>
When you name a route segment with $ like{" "}
<code>routes/users/$userId.js</code>, the $ segment will be parsed from
the URL and sent to your loaders and actions by the same name.
</p>
<h2>Errors</h2>
<p>
When a route throws and error in it's action, loader, or component,
Remix automatically catches it, won't even try to render the component,
but it will render the route's ErrorBoundary instead. If the route
doesn't have one, it will bubble up to the routes above it until it hits
the root.
</p>
<p>So be as granular as you want with your error handling.</p>
<h2>Not Found</h2>
<p>
(and other{" "}
<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses">
client errors
</a>
)
</p>
<p>
Loaders and Actions can throw a <code>Response</code> instead of an
error and Remix will render the CatchBoundary instead of the component.
This is great when loading data from a database isn't found. As soon as
you know you can't render the component normally, throw a 404 response
and send your app into the catch boundary. Just like error boundaries,
catch boundaries bubble, too.
</p>
</>
);
}

View File

@@ -0,0 +1,100 @@
import type { MetaFunction, LoaderFunction } from "remix";
import { useLoaderData, json, Link } from "remix";
type IndexData = {
resources: Array<{ name: string; url: string }>;
demos: Array<{ name: string; to: string }>;
};
// Loaders provide data to components and are only ever called on the server, so
// you can connect to a database or run any server side code you want right next
// to the component that renders it.
// https://remix.run/api/conventions#loader
export let loader: LoaderFunction = () => {
let data: IndexData = {
resources: [
{
name: "Remix Docs",
url: "https://remix.run/docs"
},
{
name: "React Router Docs",
url: "https://reactrouter.com/docs"
},
{
name: "Remix Discord",
url: "https://discord.gg/VBePs6d"
}
],
demos: [
{
to: "demos/actions",
name: "Actions"
},
{
to: "demos/about",
name: "Nested Routes, CSS loading/unloading"
},
{
to: "demos/params",
name: "URL Params and Error Boundaries"
}
]
};
// https://remix.run/api/remix#json
return json(data);
};
// https://remix.run/api/conventions#meta
export let meta: MetaFunction = () => {
return {
title: "Remix Starter",
description: "Welcome to remix!"
};
};
// https://remix.run/guides/routing#index-routes
export default function Index() {
let data = useLoaderData<IndexData>();
return (
<div className="remix__page">
<main>
<h2>Welcome to Remix!</h2>
<p>We're stoked that you're here. 🥳</p>
<p>
Feel free to take a look around the code to see how Remix does things,
it might be a bit different than what youre used to. When you're
ready to dive deeper, we've got plenty of resources to get you
up-and-running quickly.
</p>
<p>
Check out all the demos in this starter, and then just delete the{" "}
<code>app/routes/demos</code> and <code>app/styles/demos</code>{" "}
folders when you're ready to turn this into your next project.
</p>
</main>
<aside>
<h2>Demos In This App</h2>
<ul>
{data.demos.map(demo => (
<li key={demo.to} className="remix__page__resource">
<Link to={demo.to} prefetch="intent">
{demo.name}
</Link>
</li>
))}
</ul>
<h2>Resources</h2>
<ul>
{data.resources.map(resource => (
<li key={resource.url} className="remix__page__resource">
<a href={resource.url}>{resource.name}</a>
</li>
))}
</ul>
</aside>
</div>
);
}

View File

@@ -0,0 +1,7 @@
:root {
--color-foreground: hsl(0, 0%, 100%);
--color-background: hsl(0, 0%, 7%);
--color-links: hsl(213, 100%, 73%);
--color-links-hover: hsl(213, 100%, 80%);
--color-border: hsl(0, 0%, 25%);
}

View File

@@ -0,0 +1,26 @@
/*
* Whoa whoa whoa, wait a sec...why are we overriding global CSS selectors?
* Isn't that kind of scary? How do we know this won't have side effects?
*
* In Remix, CSS that is included in a route file will *only* show up on that
* route (and for nested routes, its children). When the user navigates away
* from that route the CSS files linked from those routes will be automatically
* unloaded, making your styles much easier to predict and control.
*
* Read more about styling routes in the docs:
* https://remix.run/guides/styling
*/
:root {
--color-foreground: hsl(0, 0%, 7%);
--color-background: hsl(56, 100%, 50%);
--color-links: hsl(345, 56%, 39%);
--color-links-hover: hsl(345, 51%, 49%);
--color-border: rgb(184, 173, 20);
--font-body: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
Liberation Mono, Courier New, monospace;
}
.about__intro {
max-width: 500px;
}

View File

@@ -0,0 +1,216 @@
/*
* You can just delete everything here or keep whatever you like, it's just a
* quick baseline!
*/
:root {
--color-foreground: hsl(0, 0%, 7%);
--color-background: hsl(0, 0%, 100%);
--color-links: hsl(213, 100%, 52%);
--color-links-hover: hsl(213, 100%, 43%);
--color-border: hsl(0, 0%, 82%);
--font-body: -apple-system, "Segoe UI", Helvetica Neue, Helvetica, Roboto,
Arial, sans-serif, system-ui, "Apple Color Emoji", "Segoe UI Emoji";
}
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
:-moz-focusring {
outline: auto;
}
:focus {
outline: var(--color-links) solid 2px;
outline-offset: 2px;
}
html,
body {
padding: 0;
margin: 0;
background-color: var(--color-background);
color: var(--color-foreground);
}
body {
font-family: var(--font-body);
line-height: 1.5;
}
a {
color: var(--color-links);
text-decoration: none;
}
a:hover {
color: var(--color-links-hover);
text-decoration: underline;
}
hr {
display: block;
height: 1px;
border: 0;
background-color: var(--color-border);
margin-top: 2rem;
margin-bottom: 2rem;
}
input:where([type="text"]),
input:where([type="search"]) {
display: block;
border: 1px solid var(--color-border);
width: 100%;
font: inherit;
line-height: 1;
height: calc(1ch + 1.5em);
padding-right: 0.5em;
padding-left: 0.5em;
background-color: hsl(0 0% 100% / 20%);
color: var(--color-foreground);
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border-width: 0;
}
.container {
--gutter: 16px;
width: 1024px;
max-width: calc(100% - var(--gutter) * 2);
margin-right: auto;
margin-left: auto;
}
.remix-app {
display: flex;
flex-direction: column;
min-height: 100vh;
min-height: calc(100vh - env(safe-area-inset-bottom));
}
.remix-app > * {
width: 100%;
}
.remix-app__header {
padding-top: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--color-border);
}
.remix-app__header-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.remix-app__header-home-link {
width: 106px;
height: 30px;
color: var(--color-foreground);
}
.remix-app__header-nav ul {
list-style: none;
margin: 0;
display: flex;
align-items: center;
gap: 1.5em;
}
.remix-app__header-nav li {
font-weight: bold;
}
.remix-app__main {
flex: 1 1 100%;
}
.remix-app__footer {
padding-top: 1rem;
padding-bottom: 1rem;
border-top: 1px solid var(--color-border);
}
.remix-app__footer-content {
display: flex;
justify-content: center;
align-items: center;
}
.remix__page {
--gap: 1rem;
--space: 2rem;
display: grid;
grid-auto-rows: min-content;
gap: var(--gap);
padding-top: var(--space);
padding-bottom: var(--space);
}
@media print, screen and (min-width: 640px) {
.remix__page {
--gap: 2rem;
grid-auto-rows: unset;
grid-template-columns: repeat(2, 1fr);
}
}
@media screen and (min-width: 1024px) {
.remix__page {
--gap: 4rem;
}
}
.remix__page > main > :first-child {
margin-top: 0;
}
.remix__page > main > :last-child {
margin-bottom: 0;
}
.remix__page > aside {
margin: 0;
padding: 1.5ch 2ch;
border: solid 1px var(--color-border);
border-radius: 0.5rem;
}
.remix__page > aside > :first-child {
margin-top: 0;
}
.remix__page > aside > :last-child {
margin-bottom: 0;
}
.remix__form {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
border: 1px solid var(--color-border);
border-radius: 0.5rem;
}
.remix__form > * {
margin-top: 0;
margin-bottom: 0;
}

8345
examples/remix/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
{
"private": true,
"name": "remix-app-template",
"description": "",
"license": "",
"scripts": {
"build": "remix build",
"dev": "remix dev",
"postinstall": "remix setup node"
},
"dependencies": {
"@remix-run/react": "^1.0.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"remix": "^1.0.6",
"@remix-run/serve": "^1.0.6",
"@remix-run/vercel": "^1.0.6"
},
"devDependencies": {
"@remix-run/dev": "^1.0.6",
"@types/react": "^17.0.24",
"@types/react-dom": "^17.0.9",
"typescript": "^4.1.2"
},
"engines": {
"node": ">=14"
},
"sideEffects": false
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,9 @@
/**
* @type {import('@remix-run/dev/config').AppConfig}
*/
module.exports = {
appDirectory: "app",
browserBuildDirectory: "public/build",
publicPath: "/build/",
serverBuildDirectory: "api/_build"
};

2
examples/remix/remix.env.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
/// <reference types="@remix-run/dev" />
/// <reference types="@remix-run/node/globals" />

View File

@@ -0,0 +1,18 @@
{
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2019"],
"esModuleInterop": true,
"jsx": "react-jsx",
"moduleResolution": "node",
"resolveJsonModule": true,
"target": "ES2019",
"strict": true,
"paths": {
"~/*": ["./app/*"]
},
// Remix takes care of building everything in `remix build`.
"noEmit": true
}
}

View File

@@ -0,0 +1,7 @@
{
"build": {
"env": {
"ENABLE_FILE_SYSTEM_API": "1"
}
}
}

View File

@@ -17,7 +17,6 @@
"devDependencies": {
"@typescript-eslint/eslint-plugin": "4.28.0",
"@typescript-eslint/parser": "4.28.0",
"@vercel/ncc": "0.24.0",
"async-retry": "1.2.3",
"buffer-replace": "1.0.0",
"cheerio": "1.0.0-rc.3",
@@ -25,7 +24,7 @@
"eslint-config-prettier": "8.3.0",
"eslint-plugin-jest": "24.3.6",
"husky": "6.0.0",
"jest": "27.0.6",
"jest": "27.3.1",
"json5": "2.1.1",
"lint-staged": "9.2.5",
"node-fetch": "2.6.1",
@@ -37,7 +36,7 @@
"lerna": "lerna",
"bootstrap": "lerna bootstrap",
"publish-stable": "echo 'Run `yarn changelog` for instructions'",
"publish-canary": "git checkout main && git pull && lerna version prerelease --preid canary --message 'Publish Canary' --exact",
"publish-canary": "git checkout main && git pull && lerna version prerelease --preid canary --message \"Publish Canary\" --exact",
"publish-from-github": "./utils/publish.sh",
"changelog": "node utils/changelog.js",
"build": "node utils/run.js build all",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "2.12.1-canary.0",
"version": "2.12.3-canary.32",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",
@@ -21,16 +21,16 @@
"@types/async-retry": "^1.2.1",
"@types/cross-spawn": "6.0.0",
"@types/end-of-stream": "^1.4.0",
"@types/fs-extra": "^5.0.5",
"@types/fs-extra": "9.0.13",
"@types/glob": "^7.1.1",
"@types/jest": "26.0.24",
"@types/jest": "27.0.1",
"@types/js-yaml": "3.12.1",
"@types/ms": "0.7.31",
"@types/multistream": "2.1.1",
"@types/node-fetch": "^2.1.6",
"@types/semver": "6.0.0",
"@types/yazl": "^2.4.1",
"@vercel/frameworks": "0.5.1-canary.0",
"@vercel/frameworks": "0.5.1-canary.16",
"@vercel/ncc": "0.24.0",
"aggregate-error": "3.0.1",
"async-retry": "1.2.3",
@@ -38,7 +38,7 @@
"boxen": "4.2.0",
"cross-spawn": "6.0.5",
"end-of-stream": "1.4.1",
"fs-extra": "7.0.0",
"fs-extra": "10.0.0",
"glob": "7.1.3",
"into-stream": "5.0.0",
"js-yaml": "3.13.1",

View File

@@ -0,0 +1,366 @@
import fs from 'fs-extra';
import { join, dirname, parse, relative } from 'path';
import glob from './fs/glob';
import { normalizePath } from './fs/normalize-path';
import { FILES_SYMBOL, Lambda } from './lambda';
import type FileBlob from './file-blob';
import type { BuildOptions, Files } from './types';
import { getIgnoreFilter } from '.';
// `.output` was already created by the Build Command, so we have
// to ensure its contents don't get bundled into the Lambda. Similarily,
// we don't want to bundle anything from `.vercel` either. Lastly,
// Builders/Runtimes didn't have `vercel.json` or `now.json`.
const ignoredPaths = ['.output', '.vercel', 'vercel.json', 'now.json'];
const shouldIgnorePath = (
file: string,
ignoreFilter: any,
ignoreFile: boolean
) => {
const isNative = ignoredPaths.some(item => {
return file.startsWith(item);
});
if (!ignoreFile) {
return isNative;
}
return isNative || ignoreFilter(file);
};
const getSourceFiles = async (workPath: string, ignoreFilter: any) => {
const list = await glob('**', {
cwd: workPath,
});
// We're not passing this as an `ignore` filter to the `glob` function above,
// so that we can re-use exactly the same `getIgnoreFilter` method that the
// Build Step uses (literally the same code). Note that this exclusion only applies
// when deploying. Locally, another exclusion is needed, which is handled
// further below in the `convertRuntimeToPlugin` function.
for (const file in list) {
if (shouldIgnorePath(file, ignoreFilter, true)) {
delete list[file];
}
}
return list;
};
/**
* Convert legacy Runtime to a Plugin.
* @param buildRuntime - a legacy build() function from a Runtime
* @param packageName - the name of the package, for example `vercel-plugin-python`
* @param ext - the file extension, for example `.py`
*/
export function convertRuntimeToPlugin(
buildRuntime: (options: BuildOptions) => Promise<{ output: Lambda }>,
packageName: string,
ext: string
) {
// This `build()` signature should match `plugin.build()` signature in `vercel build`.
return async function build({ workPath }: { workPath: string }) {
// We also don't want to provide any files to Runtimes that were ignored
// through `.vercelignore` or `.nowignore`, because the Build Step does the same.
const ignoreFilter = await getIgnoreFilter(workPath);
// Retrieve the files that are currently available on the File System,
// before the Legacy Runtime has even started to build.
const sourceFilesPreBuild = await getSourceFiles(workPath, ignoreFilter);
// Instead of doing another `glob` to get all the matching source files,
// we'll filter the list of existing files down to only the ones
// that are matching the entrypoint pattern, so we're first creating
// a clean new list to begin.
const entrypoints = Object.assign({}, sourceFilesPreBuild);
const entrypointMatch = new RegExp(`^api/.*${ext}$`);
// Up next, we'll strip out the files from the list of entrypoints
// that aren't actually considered entrypoints.
for (const file in entrypoints) {
if (!entrypointMatch.test(file)) {
delete entrypoints[file];
}
}
const pages: { [key: string]: any } = {};
const pluginName = packageName.replace('vercel-plugin-', '');
const traceDir = join(
workPath,
`.output`,
`inputs`,
// Legacy Runtimes can only provide API Routes, so that's
// why we can use this prefix for all of them. Here, we have to
// make sure to not use a cryptic hash name, because people
// need to be able to easily inspect the output.
`api-routes-${pluginName}`
);
await fs.ensureDir(traceDir);
for (const entrypoint of Object.keys(entrypoints)) {
const { output } = await buildRuntime({
files: sourceFilesPreBuild,
entrypoint,
workPath,
config: {
zeroConfig: true,
},
meta: {
avoidTopLevelInstall: true,
},
});
// Legacy Runtimes tend to pollute the `workPath` with compiled results,
// because the `workPath` used to be a place that was a place where they could
// just put anything, but nowadays it's the working directory of the `vercel build`
// command, which is the place where the developer keeps their source files,
// so we don't want to pollute this space unnecessarily. That means we have to clean
// up files that were created by the build, which is done further below.
const sourceFilesAfterBuild = await getSourceFiles(
workPath,
ignoreFilter
);
// Further down, we will need the filename of the Lambda handler
// for placing it inside `server/pages/api`, but because Legacy Runtimes
// don't expose the filename directly, we have to construct it
// from the handler name, and then find the matching file further below,
// because we don't yet know its extension here.
const handler = output.handler;
const handlerMethod = handler.split('.').reverse()[0];
const handlerFileName = handler.replace(`.${handlerMethod}`, '');
pages[entrypoint] = {
handler: handler,
runtime: output.runtime,
memory: output.memory,
maxDuration: output.maxDuration,
environment: output.environment,
allowQuery: output.allowQuery,
};
// @ts-ignore This symbol is a private API
const lambdaFiles: Files = output[FILES_SYMBOL];
// When deploying, the `files` that are passed to the Legacy Runtimes already
// have certain files that are ignored stripped, but locally, that list of
// files isn't used by the Legacy Runtimes, so we need to apply the filters
// to the outputs that they are returning instead.
for (const file in lambdaFiles) {
if (shouldIgnorePath(file, ignoreFilter, false)) {
delete lambdaFiles[file];
}
}
const handlerFilePath = Object.keys(lambdaFiles).find(item => {
return parse(item).name === handlerFileName;
});
const handlerFileOrigin = lambdaFiles[handlerFilePath || ''].fsPath;
if (!handlerFileOrigin) {
throw new Error(
`Could not find a handler file. Please ensure that the list of \`files\` defined for the returned \`Lambda\` contains a file with the name ${handlerFileName} (+ any extension).`
);
}
const entry = join(workPath, '.output', 'server', 'pages', entrypoint);
await fs.ensureDir(dirname(entry));
await linkOrCopy(handlerFileOrigin, entry);
const toRemove = [];
// You can find more details about this at the point where the
// `sourceFilesAfterBuild` is created originally.
for (const file in sourceFilesAfterBuild) {
if (!sourceFilesPreBuild[file]) {
const path = sourceFilesAfterBuild[file].fsPath;
toRemove.push(fs.remove(path));
}
}
await Promise.all(toRemove);
const tracedFiles: {
absolutePath: string;
relativePath: string;
}[] = [];
Object.entries(lambdaFiles).forEach(async ([relPath, file]) => {
const newPath = join(traceDir, relPath);
// The handler was already moved into position above.
if (relPath === handlerFilePath) {
return;
}
tracedFiles.push({ absolutePath: newPath, relativePath: relPath });
if (file.fsPath) {
await linkOrCopy(file.fsPath, newPath);
} else if (file.type === 'FileBlob') {
const { data, mode } = file as FileBlob;
await fs.writeFile(newPath, data, { mode });
} else {
throw new Error(`Unknown file type: ${file.type}`);
}
});
const nft = join(
workPath,
'.output',
'server',
'pages',
`${entrypoint}.nft.json`
);
const json = JSON.stringify({
version: 1,
files: tracedFiles.map(file => ({
input: normalizePath(relative(dirname(nft), file.absolutePath)),
output: normalizePath(file.relativePath),
})),
});
await fs.ensureDir(dirname(nft));
await fs.writeFile(nft, json);
}
await updateFunctionsManifest({ workPath, pages });
};
}
async function linkOrCopy(existingPath: string, newPath: string) {
try {
await fs.createLink(existingPath, newPath);
} catch (err: any) {
if (err.code !== 'EEXIST') {
await fs.copyFile(existingPath, newPath);
}
}
}
async function readJson(filePath: string): Promise<{ [key: string]: any }> {
try {
const str = await fs.readFile(filePath, 'utf8');
return JSON.parse(str);
} catch (err) {
if (err.code === 'ENOENT') {
return {};
}
throw err;
}
}
/**
* If `.output/functions-manifest.json` exists, append to the pages
* property. Otherwise write a new file.
*/
export async function updateFunctionsManifest({
workPath,
pages,
}: {
workPath: string;
pages: { [key: string]: any };
}) {
const functionsManifestPath = join(
workPath,
'.output',
'functions-manifest.json'
);
const functionsManifest = await readJson(functionsManifestPath);
if (!functionsManifest.version) functionsManifest.version = 1;
if (!functionsManifest.pages) functionsManifest.pages = {};
for (const [pageKey, pageConfig] of Object.entries(pages)) {
functionsManifest.pages[pageKey] = { ...pageConfig };
}
await fs.writeFile(functionsManifestPath, JSON.stringify(functionsManifest));
}
/**
* Append routes to the `routes-manifest.json` file.
* If the file does not exist, it will be created.
*/
export async function updateRoutesManifest({
workPath,
redirects,
rewrites,
headers,
dynamicRoutes,
staticRoutes,
}: {
workPath: string;
redirects?: {
source: string;
destination: string;
statusCode: number;
regex: string;
}[];
rewrites?: {
source: string;
destination: string;
regex: string;
}[];
headers?: {
source: string;
headers: {
key: string;
value: string;
}[];
regex: string;
}[];
dynamicRoutes?: {
page: string;
regex: string;
namedRegex?: string;
routeKeys?: { [named: string]: string };
}[];
staticRoutes?: {
page: string;
regex: string;
namedRegex?: string;
routeKeys?: { [named: string]: string };
}[];
}) {
const routesManifestPath = join(workPath, '.output', 'routes-manifest.json');
const routesManifest = await readJson(routesManifestPath);
if (!routesManifest.version) routesManifest.version = 3;
if (routesManifest.pages404 === undefined) routesManifest.pages404 = true;
if (redirects) {
if (!routesManifest.redirects) routesManifest.redirects = [];
routesManifest.redirects.push(...redirects);
}
if (rewrites) {
if (!routesManifest.rewrites) routesManifest.rewrites = [];
routesManifest.rewrites.push(...rewrites);
}
if (headers) {
if (!routesManifest.headers) routesManifest.headers = [];
routesManifest.headers.push(...headers);
}
if (dynamicRoutes) {
if (!routesManifest.dynamicRoutes) routesManifest.dynamicRoutes = [];
routesManifest.dynamicRoutes.push(...dynamicRoutes);
}
if (staticRoutes) {
if (!routesManifest.staticRoutes) routesManifest.staticRoutes = [];
routesManifest.staticRoutes.push(...staticRoutes);
}
await fs.writeFile(routesManifestPath, JSON.stringify(routesManifest));
}

View File

@@ -96,6 +96,7 @@ export async function detectBuilders(
redirectRoutes: Route[] | null;
rewriteRoutes: Route[] | null;
errorRoutes: Route[] | null;
limitedRoutes: LimitedRoutes | null;
}> {
const errors: ErrorResponse[] = [];
const warnings: ErrorResponse[] = [];
@@ -114,6 +115,7 @@ export async function detectBuilders(
redirectRoutes: null,
rewriteRoutes: null,
errorRoutes: null,
limitedRoutes: null,
};
}
@@ -179,6 +181,7 @@ export async function detectBuilders(
redirectRoutes: null,
rewriteRoutes: null,
errorRoutes: null,
limitedRoutes: null,
};
}
@@ -257,6 +260,7 @@ export async function detectBuilders(
defaultRoutes: null,
rewriteRoutes: null,
errorRoutes: null,
limitedRoutes: null,
};
}
@@ -299,6 +303,7 @@ export async function detectBuilders(
defaultRoutes: null,
rewriteRoutes: null,
errorRoutes: null,
limitedRoutes: null,
};
}
@@ -326,6 +331,7 @@ export async function detectBuilders(
}
const routesResult = getRouteResult(
pkg,
apiRoutes,
dynamicRoutes,
usedOutputDirectory,
@@ -342,6 +348,7 @@ export async function detectBuilders(
defaultRoutes: routesResult.defaultRoutes,
rewriteRoutes: routesResult.rewriteRoutes,
errorRoutes: routesResult.errorRoutes,
limitedRoutes: routesResult.limitedRoutes,
};
}
@@ -932,7 +939,14 @@ function createRouteFromPath(
return { route, isDynamic };
}
interface LimitedRoutes {
defaultRoutes: Route[];
redirectRoutes: Route[];
rewriteRoutes: Route[];
}
function getRouteResult(
pkg: PackageJson | undefined | null,
apiRoutes: Source[],
dynamicRoutes: Source[],
outputDirectory: string,
@@ -944,11 +958,18 @@ function getRouteResult(
redirectRoutes: Route[];
rewriteRoutes: Route[];
errorRoutes: Route[];
limitedRoutes: LimitedRoutes;
} {
const deps = Object.assign({}, pkg?.dependencies, pkg?.devDependencies);
const defaultRoutes: Route[] = [];
const redirectRoutes: Route[] = [];
const rewriteRoutes: Route[] = [];
const errorRoutes: Route[] = [];
const limitedRoutes: LimitedRoutes = {
defaultRoutes: [],
redirectRoutes: [],
rewriteRoutes: [],
};
const framework = frontendBuilder?.config?.framework || '';
const isNextjs =
framework === 'nextjs' || isOfficialRuntime('next', frontendBuilder?.use);
@@ -956,14 +977,43 @@ function getRouteResult(
if (apiRoutes && apiRoutes.length > 0) {
if (options.featHandleMiss) {
// Exclude extension names if the corresponding plugin is not found in package.json
// detectBuilders({ignoreRoutesForBuilders: ['@vercel/python']})
// return a copy of routes.
// We should exclud errorRoutes and
const extSet = detectApiExtensions(apiBuilders);
const withTag = options.tag ? `@${options.tag}` : '';
const extSetLimited = detectApiExtensions(
apiBuilders.filter(b => {
if (
b.use === `@vercel/python${withTag}` &&
!('vercel-plugin-python' in deps)
) {
return false;
}
if (
b.use === `@vercel/go${withTag}` &&
!('vercel-plugin-go' in deps)
) {
return false;
}
if (
b.use === `@vercel/ruby${withTag}` &&
!('vercel-plugin-ruby' in deps)
) {
return false;
}
return true;
})
);
if (extSet.size > 0) {
const exts = Array.from(extSet)
const extGroup = `(?:\\.(?:${Array.from(extSet)
.map(ext => ext.slice(1))
.join('|');
const extGroup = `(?:\\.(?:${exts}))`;
.join('|')}))`;
const extGroupLimited = `(?:\\.(?:${Array.from(extSetLimited)
.map(ext => ext.slice(1))
.join('|')}))`;
if (options.cleanUrls) {
redirectRoutes.push({
@@ -979,6 +1029,20 @@ function getRouteResult(
},
status: 308,
});
limitedRoutes.redirectRoutes.push({
src: `^/(api(?:.+)?)/index${extGroupLimited}?/?$`,
headers: { Location: options.trailingSlash ? '/$1/' : '/$1' },
status: 308,
});
limitedRoutes.redirectRoutes.push({
src: `^/api/(.+)${extGroupLimited}/?$`,
headers: {
Location: options.trailingSlash ? '/api/$1/' : '/api/$1',
},
status: 308,
});
} else {
defaultRoutes.push({ handle: 'miss' });
defaultRoutes.push({
@@ -986,10 +1050,18 @@ function getRouteResult(
dest: '/api/$1',
check: true,
});
limitedRoutes.defaultRoutes.push({ handle: 'miss' });
limitedRoutes.defaultRoutes.push({
src: `^/api/(.+)${extGroupLimited}$`,
dest: '/api/$1',
check: true,
});
}
}
rewriteRoutes.push(...dynamicRoutes);
limitedRoutes.rewriteRoutes.push(...dynamicRoutes);
if (typeof ignoreRuntimes === 'undefined') {
// This route is only necessary to hide the directory listing
@@ -1030,7 +1102,7 @@ function getRouteResult(
// https://nextjs.org/docs/advanced-features/custom-error-page
errorRoutes.push({
status: 404,
src: '^/(?!.*api).*$',
src: '^(?!/api).*$',
dest: options.cleanUrls ? '/404' : '/404.html',
});
}
@@ -1040,6 +1112,7 @@ function getRouteResult(
redirectRoutes,
rewriteRoutes,
errorRoutes,
limitedRoutes,
};
}

View File

@@ -100,4 +100,4 @@ class FileFsRef implements File {
}
}
export = FileFsRef;
export default FileFsRef;

View File

@@ -3,6 +3,7 @@ import assert from 'assert';
import vanillaGlob_ from 'glob';
import { promisify } from 'util';
import { lstat, Stats } from 'fs-extra';
import { normalizePath } from './normalize-path';
import FileFsRef from '../file-fs-ref';
export type GlobOptions = vanillaGlob_.IOptions;
@@ -45,7 +46,7 @@ export default async function glob(
const files = await vanillaGlob(pattern, options);
for (const relativePath of files) {
const fsPath = path.join(options.cwd!, relativePath).replace(/\\/g, '/');
const fsPath = normalizePath(path.join(options.cwd!, relativePath));
let stat: Stats = options.statCache![fsPath] as Stats;
assert(
stat,

View File

@@ -0,0 +1,8 @@
const isWin = process.platform === 'win32';
/**
* Convert Windows separators to Unix separators.
*/
export function normalizePath(p: string): string {
return isWin ? p.replace(/\\/g, '/') : p;
}

View File

@@ -313,7 +313,8 @@ export async function runNpmInstall(
destPath: string,
args: string[] = [],
spawnOpts?: SpawnOptions,
meta?: Meta
meta?: Meta,
nodeVersion?: NodeVersion
) {
if (meta?.isDev) {
debug('Skipping dependency installation because dev mode is enabled');
@@ -337,7 +338,12 @@ export async function runNpmInstall(
.filter(a => a !== '--prefer-offline')
.concat(['install', '--no-audit', '--unsafe-perm']);
if (typeof lockfileVersion === 'number' && lockfileVersion >= 2) {
// If the lockfile version is 2 or greater and the node version is less than 16 than we will force npm7 to be used
if (
typeof lockfileVersion === 'number' &&
lockfileVersion >= 2 &&
(nodeVersion?.major || 0) < 16
) {
// Ensure that npm 7 is at the beginning of the `$PATH`
env.PATH = `/node16/bin-npm7:${env.PATH}`;
console.log('Detected `package-lock.json` generated by npm 7...');

View File

@@ -0,0 +1,84 @@
import path from 'path';
import fs from 'fs-extra';
import ignore from 'ignore';
interface CodedError extends Error {
code: string;
}
function isCodedError(error: unknown): error is CodedError {
return (
error !== null &&
error !== undefined &&
(error as CodedError).code !== undefined
);
}
function clearRelative(s: string) {
return s.replace(/(\n|^)\.\//g, '$1');
}
export default async function (
downloadPath: string,
rootDirectory?: string | undefined
) {
const readFile = async (p: string) => {
try {
return await fs.readFile(p, 'utf8');
} catch (error: any) {
if (
error.code === 'ENOENT' ||
(error instanceof Error && error.message.includes('ENOENT'))
) {
return undefined;
}
throw error;
}
};
const vercelIgnorePath = path.join(
downloadPath,
rootDirectory || '',
'.vercelignore'
);
const nowIgnorePath = path.join(
downloadPath,
rootDirectory || '',
'.nowignore'
);
const ignoreContents = [];
try {
ignoreContents.push(
...(
await Promise.all([readFile(vercelIgnorePath), readFile(nowIgnorePath)])
).filter(Boolean)
);
} catch (error) {
if (isCodedError(error) && error.code === 'ENOTDIR') {
console.log(`Warning: Cannot read ignore file from ${vercelIgnorePath}`);
} else {
throw error;
}
}
if (ignoreContents.length === 2) {
throw new Error(
'Cannot use both a `.vercelignore` and `.nowignore` file. Please delete the `.nowignore` file.'
);
}
if (ignoreContents.length === 0) {
return () => false;
}
const ignoreFilter: any = ignore().add(clearRelative(ignoreContents[0]!));
return function (p: string) {
// we should not ignore now.json and vercel.json if it asked to.
// we depend on these files for building the app with sourceless
if (p === 'now.json' || p === 'vercel.json') return false;
return ignoreFilter.test(p).ignored;
};
}

View File

@@ -1,3 +1,4 @@
import { createHash } from 'crypto';
import FileBlob from './file-blob';
import FileFsRef from './file-fs-ref';
import FileRef from './file-ref';
@@ -33,6 +34,7 @@ import { NowBuildError } from './errors';
import streamToBuffer from './fs/stream-to-buffer';
import shouldServe from './should-serve';
import debug from './debug';
import getIgnoreFilter from './get-ignore-filter';
export {
FileBlob,
@@ -70,6 +72,7 @@ export {
isSymbolicLink,
getLambdaOptionsFromFunction,
scanParentDirs,
getIgnoreFilter,
};
export {
@@ -81,6 +84,12 @@ export {
export { detectFramework } from './detect-framework';
export { DetectorFilesystem } from './detectors/filesystem';
export { readConfigFile } from './fs/read-config-file';
export { normalizePath } from './fs/normalize-path';
export {
convertRuntimeToPlugin,
updateFunctionsManifest,
updateRoutesManifest,
} from './convert-runtime-to-plugin';
export * from './schemas';
export * from './types';
@@ -126,3 +135,11 @@ export const getPlatformEnv = (name: string): string | undefined => {
}
return n;
};
/**
* Helper function for generating file or directories names in `.output/inputs`
* for dependencies of files provided to the File System API.
*/
export const getInputHash = (source: Buffer | string): string => {
return createHash('sha1').update(source).digest('hex');
};

View File

@@ -19,6 +19,8 @@ interface LambdaOptions {
memory?: number;
maxDuration?: number;
environment: Environment;
allowQuery?: string[];
regions?: string[];
}
interface CreateLambdaOptions {
@@ -28,13 +30,17 @@ interface CreateLambdaOptions {
memory?: number;
maxDuration?: number;
environment?: Environment;
allowQuery?: string[];
regions?: string[];
}
interface GetLambdaOptionsFromFunctionOptions {
sourceFile: string;
config?: Config;
config?: Pick<Config, 'functions'>;
}
export const FILES_SYMBOL = Symbol('files');
export class Lambda {
public type: 'Lambda';
public zipBuffer: Buffer;
@@ -43,6 +49,8 @@ export class Lambda {
public memory?: number;
public maxDuration?: number;
public environment: Environment;
public allowQuery?: string[];
public regions?: string[];
constructor({
zipBuffer,
@@ -51,6 +59,8 @@ export class Lambda {
maxDuration,
memory,
environment,
allowQuery,
regions,
}: LambdaOptions) {
this.type = 'Lambda';
this.zipBuffer = zipBuffer;
@@ -59,6 +69,8 @@ export class Lambda {
this.memory = memory;
this.maxDuration = maxDuration;
this.environment = environment;
this.allowQuery = allowQuery;
this.regions = regions;
}
}
@@ -72,6 +84,8 @@ export async function createLambda({
memory,
maxDuration,
environment = {},
allowQuery,
regions,
}: CreateLambdaOptions): Promise<Lambda> {
assert(typeof files === 'object', '"files" must be an object');
assert(typeof handler === 'string', '"handler" is not a string');
@@ -86,18 +100,38 @@ export async function createLambda({
assert(typeof maxDuration === 'number', '"maxDuration" is not a number');
}
if (allowQuery !== undefined) {
assert(Array.isArray(allowQuery), '"allowQuery" is not an Array');
assert(
allowQuery.every(q => typeof q === 'string'),
'"allowQuery" is not a string Array'
);
}
if (regions !== undefined) {
assert(Array.isArray(regions), '"regions" is not an Array');
assert(
regions.every(r => typeof r === 'string'),
'"regions" is not a string Array'
);
}
await sema.acquire();
try {
const zipBuffer = await createZip(files);
return new Lambda({
const lambda = new Lambda({
zipBuffer,
handler,
runtime,
memory,
maxDuration,
environment,
regions,
});
// @ts-ignore This symbol is a private API
lambda[FILES_SYMBOL] = files;
return lambda;
} finally {
sema.release();
}
@@ -131,9 +165,7 @@ export async function createZip(files: Files): Promise<Buffer> {
}
zipFile.end();
streamToBuffer(zipFile.outputStream)
.then(resolve)
.catch(reject);
streamToBuffer(zipFile.outputStream).then(resolve).catch(reject);
});
return zipBuffer;

View File

@@ -9,6 +9,7 @@ interface PrerenderOptions {
fallback: FileBlob | FileFsRef | FileRef | null;
group?: number;
bypassToken?: string | null /* optional to be non-breaking change */;
allowQuery?: string[];
}
export class Prerender {
@@ -18,6 +19,7 @@ export class Prerender {
public fallback: FileBlob | FileFsRef | FileRef | null;
public group?: number;
public bypassToken: string | null;
public allowQuery?: string[];
constructor({
expiration,
@@ -25,6 +27,7 @@ export class Prerender {
fallback,
group,
bypassToken,
allowQuery,
}: PrerenderOptions) {
this.type = 'Prerender';
this.expiration = expiration;
@@ -62,5 +65,19 @@ export class Prerender {
);
}
this.fallback = fallback;
if (allowQuery !== undefined) {
if (!Array.isArray(allowQuery)) {
throw new Error(
'The `allowQuery` argument for `Prerender` must be Array.'
);
}
if (!allowQuery.every(q => typeof q === 'string')) {
throw new Error(
'The `allowQuery` argument for `Prerender` must be Array of strings.'
);
}
this.allowQuery = allowQuery;
}
}
}

View File

@@ -10,6 +10,7 @@ export interface File {
mode: number;
contentType?: string;
toStream: () => NodeJS.ReadableStream;
toStreamAsync?: () => Promise<NodeJS.ReadableStream>;
/**
* The absolute path to the file in the filesystem
*/
@@ -57,6 +58,7 @@ export interface Meta {
filesRemoved?: string[];
env?: Env;
buildEnv?: Env;
avoidTopLevelInstall?: boolean;
}
export interface AnalyzeOptions {

View File

@@ -0,0 +1 @@
# users.rb

View File

@@ -0,0 +1,10 @@
{
"functions": {
"api/users.rb": {
"memory": 3008
},
"api/doesnt-exist.rb": {
"memory": 768
}
}
}

View File

@@ -0,0 +1 @@
# [id].py

View File

@@ -0,0 +1 @@
# index

View File

@@ -0,0 +1 @@
# project/[aid]/[bid]/index.py

View File

@@ -0,0 +1 @@
# get

View File

@@ -0,0 +1 @@
# post

View File

@@ -0,0 +1 @@
This file should also be included

View File

@@ -0,0 +1 @@
# date

View File

@@ -0,0 +1 @@
# math

View File

@@ -0,0 +1,7 @@
{
"functions": {
"api/users/post.py": {
"memory": 3008
}
}
}

View File

@@ -1,5 +1,5 @@
{
"version": 2,
"builds": [{ "src": "package.json", "use": "@vercel/static-build" }],
"probes": [{ "path": "/", "mustContain": "npm version: 7" }]
"probes": [{ "path": "/", "mustContain": "npm version: 8" }]
}

View File

@@ -2013,15 +2013,11 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
framework: 'redwoodjs',
};
const {
builders,
defaultRoutes,
rewriteRoutes,
errorRoutes,
} = await detectBuilders(files, null, {
projectSettings,
featHandleMiss,
});
const { builders, defaultRoutes, rewriteRoutes, errorRoutes } =
await detectBuilders(files, null, {
projectSettings,
featHandleMiss,
});
expect(builders).toStrictEqual([
{
@@ -2038,7 +2034,7 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
expect(errorRoutes).toStrictEqual([
{
status: 404,
src: '^/(?!.*api).*$',
src: '^(?!/api).*$',
dest: '/404.html',
},
]);
@@ -2050,15 +2046,11 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
framework: 'redwoodjs',
};
const {
builders,
defaultRoutes,
rewriteRoutes,
errorRoutes,
} = await detectBuilders(files, null, {
projectSettings,
featHandleMiss,
});
const { builders, defaultRoutes, rewriteRoutes, errorRoutes } =
await detectBuilders(files, null, {
projectSettings,
featHandleMiss,
});
expect(builders).toStrictEqual([
{
@@ -2096,7 +2088,7 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
expect(errorRoutes).toStrictEqual([
{
status: 404,
src: '^/(?!.*api).*$',
src: '^(?!/api).*$',
dest: '/404.html',
},
]);
@@ -2393,13 +2385,10 @@ it('Test `detectRoutes` with `featHandleMiss=true`', async () => {
{
const files = ['api/user.go', 'api/team.js', 'api/package.json'];
const { defaultRoutes, rewriteRoutes, errorRoutes } = await detectBuilders(
files,
null,
{
const { defaultRoutes, rewriteRoutes, errorRoutes, limitedRoutes } =
await detectBuilders(files, null, {
featHandleMiss,
}
);
});
expect(defaultRoutes).toStrictEqual([
{ handle: 'miss' },
{
@@ -2417,11 +2406,27 @@ it('Test `detectRoutes` with `featHandleMiss=true`', async () => {
expect(errorRoutes).toStrictEqual([
{
status: 404,
src: '^/(?!.*api).*$',
src: '^(?!/api).*$',
dest: '/404.html',
},
]);
// Limited routes should have js but not go since the go plugin is not installed
expect(limitedRoutes).toStrictEqual({
redirectRoutes: [],
rewriteRoutes: [],
defaultRoutes: [
{
handle: 'miss',
},
{
src: '^/api/(.+)(?:\\.(?:js))$',
dest: '/api/$1',
check: true,
},
],
});
const pattern = new RegExp(errorRoutes![0].src!);
[
@@ -2435,6 +2440,11 @@ it('Test `detectRoutes` with `featHandleMiss=true`', async () => {
'/another/sub/index.html',
'/another/sub/page.html',
'/another/sub/page',
'/another/api',
'/another/api/page.html',
'/rapid',
'/rapid/page.html',
'/health-api.html',
].forEach(file => {
expect(file).toMatch(pattern);
});
@@ -2443,12 +2453,12 @@ it('Test `detectRoutes` with `featHandleMiss=true`', async () => {
'/api',
'/api/',
'/api/index.html',
'/api/page.html',
'/api/page',
'/api/users.js',
'/api/users',
'/api/sub',
'/api/sub/index.html',
'/api/sub/page.html',
'/api/sub/page',
'/api/sub/users.js',
'/api/sub/users',
].forEach(file => {
expect(file).not.toMatch(pattern);
});
@@ -2824,6 +2834,7 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
redirectRoutes,
rewriteRoutes,
errorRoutes,
limitedRoutes,
} = await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
@@ -2836,11 +2847,33 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
expect(errorRoutes).toStrictEqual([
{
status: 404,
src: '^/(?!.*api).*$',
src: '^(?!/api).*$',
dest: '/404',
},
]);
// Limited routes should have js but not go since the go plugin is not installed
expect(limitedRoutes).toStrictEqual({
redirectRoutes: [
{
src: '^/(api(?:.+)?)/index(?:\\.(?:js))?/?$',
headers: {
Location: '/$1',
},
status: 308,
},
{
src: '^/api/(.+)(?:\\.(?:js))/?$',
headers: {
Location: '/api/$1',
},
status: 308,
},
],
rewriteRoutes: [],
defaultRoutes: [],
});
// expected redirect should match inputs
const getLocation = createReplaceLocation(redirectRoutes);
@@ -2904,11 +2937,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
{
const files = ['api/[endpoint].js', 'api/[endpoint]/[id].js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -2936,11 +2966,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
'api/[endpoint]/[id].js',
];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -2974,11 +3001,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
const files = ['public/index.html', 'api/[endpoint].js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, pkg, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, pkg, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3004,11 +3028,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
{
const files = ['api/date/index.js', 'api/date.js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3022,11 +3043,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
{
const files = ['api/date.js', 'api/[date]/index.js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3051,11 +3069,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
'api/food.ts',
'api/ts/gold.ts',
];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3071,11 +3086,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, { functions, ...options });
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, { functions, ...options });
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3105,11 +3117,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
{
const files = ['api/user.go', 'api/team.js', 'api/package.json'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes, limitedRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3119,6 +3128,28 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
},
]);
// Limited routes should have js but not go since the go plugin is not installed
expect(limitedRoutes).toStrictEqual({
redirectRoutes: [
{
src: '^/(api(?:.+)?)/index(?:\\.(?:js))?/?$',
headers: {
Location: '/$1/',
},
status: 308,
},
{
src: '^/api/(.+)(?:\\.(?:js))/?$',
headers: {
Location: '/api/$1/',
},
status: 308,
},
],
rewriteRoutes: [],
defaultRoutes: [],
});
// expected redirect should match inputs
const getLocation = createReplaceLocation(redirectRoutes);
@@ -3152,11 +3183,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
{
const files = ['api/[endpoint].js', 'api/[endpoint]/[id].js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3184,11 +3212,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
'api/[endpoint]/[id].js',
];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3222,11 +3247,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
const files = ['public/index.html', 'api/[endpoint].js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, pkg, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, pkg, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3245,11 +3267,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
{
const files = ['api/date/index.js', 'api/date.js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3263,11 +3282,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
{
const files = ['api/date.js', 'api/[date]/index.js'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3292,11 +3308,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
'api/food.ts',
'api/ts/gold.ts',
];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, options);
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, options);
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([
@@ -3312,11 +3325,8 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const {
defaultRoutes,
redirectRoutes,
rewriteRoutes,
} = await detectBuilders(files, null, { functions, ...options });
const { defaultRoutes, redirectRoutes, rewriteRoutes } =
await detectBuilders(files, null, { functions, ...options });
testHeaders(redirectRoutes);
expect(defaultRoutes).toStrictEqual([]);
expect(rewriteRoutes).toStrictEqual([

View File

@@ -0,0 +1,231 @@
import { join } from 'path';
import fs from 'fs-extra';
import { BuildOptions, createLambda, FileFsRef } from '../src';
import { convertRuntimeToPlugin } from '../src/convert-runtime-to-plugin';
async function fsToJson(dir: string, output: Record<string, any> = {}) {
const files = await fs.readdir(dir);
for (const file of files) {
const fsPath = join(dir, file);
const stat = await fs.stat(fsPath);
if (stat.isDirectory()) {
output[file] = {};
await fsToJson(fsPath, output[file]);
} else {
output[file] = await fs.readFile(fsPath, 'utf8');
}
}
return output;
}
const invalidFuncWorkpath = join(
__dirname,
'convert-runtime',
'invalid-functions'
);
const pythonApiWorkpath = join(__dirname, 'convert-runtime', 'python-api');
describe('convert-runtime-to-plugin', () => {
afterEach(async () => {
await fs.remove(join(invalidFuncWorkpath, '.output'));
await fs.remove(join(pythonApiWorkpath, '.output'));
});
it('should create correct fileystem for python', async () => {
const ext = '.py';
const workPath = pythonApiWorkpath;
const handlerName = 'vc__handler__python';
const handlerFileName = handlerName + ext;
const lambdaOptions = {
handler: `${handlerName}.vc_handler`,
runtime: 'python3.9',
memory: 512,
maxDuration: 5,
environment: {},
};
const buildRuntime = async (opts: BuildOptions) => {
const handlerPath = join(workPath, handlerFileName);
// This is the usual time at which a Legacy Runtime writes its Lambda launcher.
await fs.writeFile(handlerPath, '# handler');
opts.files[handlerFileName] = new FileFsRef({
fsPath: handlerPath,
});
const lambda = await createLambda({
files: opts.files,
...lambdaOptions,
});
return { output: lambda };
};
const lambdaFiles = await fsToJson(workPath);
const packageName = 'vercel-plugin-python';
const build = await convertRuntimeToPlugin(buildRuntime, packageName, ext);
await build({ workPath });
const output = await fsToJson(join(workPath, '.output'));
delete lambdaFiles['vercel.json'];
delete lambdaFiles['vc__handler__python.py'];
expect(output).toMatchObject({
'functions-manifest.json': expect.stringContaining('{'),
inputs: {
'api-routes-python': lambdaFiles,
},
server: {
pages: {
api: {
'index.py': expect.stringContaining('handler'),
'index.py.nft.json': expect.stringContaining('{'),
users: {
'get.py': expect.stringContaining('handler'),
'get.py.nft.json': expect.stringContaining('{'),
'post.py': expect.stringContaining('handler'),
'post.py.nft.json': expect.stringContaining('{'),
},
},
},
},
});
const funcManifest = JSON.parse(output['functions-manifest.json']);
expect(funcManifest).toMatchObject({
version: 1,
pages: {
'api/index.py': lambdaOptions,
'api/users/get.py': lambdaOptions,
'api/users/post.py': { ...lambdaOptions, memory: 512 },
},
});
const indexJson = JSON.parse(output.server.pages.api['index.py.nft.json']);
expect(indexJson).toMatchObject({
version: 1,
files: [
{
input: `../../../inputs/api-routes-python/api/db/[id].py`,
output: 'api/db/[id].py',
},
{
input: `../../../inputs/api-routes-python/api/index.py`,
output: 'api/index.py',
},
{
input: `../../../inputs/api-routes-python/api/project/[aid]/[bid]/index.py`,
output: 'api/project/[aid]/[bid]/index.py',
},
{
input: `../../../inputs/api-routes-python/api/users/get.py`,
output: 'api/users/get.py',
},
{
input: `../../../inputs/api-routes-python/api/users/post.py`,
output: 'api/users/post.py',
},
{
input: `../../../inputs/api-routes-python/file.txt`,
output: 'file.txt',
},
{
input: `../../../inputs/api-routes-python/util/date.py`,
output: 'util/date.py',
},
{
input: `../../../inputs/api-routes-python/util/math.py`,
output: 'util/math.py',
},
],
});
const getJson = JSON.parse(
output.server.pages.api.users['get.py.nft.json']
);
expect(getJson).toMatchObject({
version: 1,
files: [
{
input: `../../../../inputs/api-routes-python/api/db/[id].py`,
output: 'api/db/[id].py',
},
{
input: `../../../../inputs/api-routes-python/api/index.py`,
output: 'api/index.py',
},
{
input: `../../../../inputs/api-routes-python/api/project/[aid]/[bid]/index.py`,
output: 'api/project/[aid]/[bid]/index.py',
},
{
input: `../../../../inputs/api-routes-python/api/users/get.py`,
output: 'api/users/get.py',
},
{
input: `../../../../inputs/api-routes-python/api/users/post.py`,
output: 'api/users/post.py',
},
{
input: `../../../../inputs/api-routes-python/file.txt`,
output: 'file.txt',
},
{
input: `../../../../inputs/api-routes-python/util/date.py`,
output: 'util/date.py',
},
{
input: `../../../../inputs/api-routes-python/util/math.py`,
output: 'util/math.py',
},
],
});
const postJson = JSON.parse(
output.server.pages.api.users['post.py.nft.json']
);
expect(postJson).toMatchObject({
version: 1,
files: [
{
input: `../../../../inputs/api-routes-python/api/db/[id].py`,
output: 'api/db/[id].py',
},
{
input: `../../../../inputs/api-routes-python/api/index.py`,
output: 'api/index.py',
},
{
input: `../../../../inputs/api-routes-python/api/project/[aid]/[bid]/index.py`,
output: 'api/project/[aid]/[bid]/index.py',
},
{
input: `../../../../inputs/api-routes-python/api/users/get.py`,
output: 'api/users/get.py',
},
{
input: `../../../../inputs/api-routes-python/api/users/post.py`,
output: 'api/users/post.py',
},
{
input: `../../../../inputs/api-routes-python/file.txt`,
output: 'file.txt',
},
{
input: `../../../../inputs/api-routes-python/util/date.py`,
output: 'util/date.py',
},
{
input: `../../../../inputs/api-routes-python/util/math.py`,
output: 'util/math.py',
},
],
});
expect(output.server.pages['file.txt']).toBeUndefined();
expect(output.server.pages.api['file.txt']).toBeUndefined();
});
});

View File

@@ -318,7 +318,7 @@ it('should return lockfileVersion 1 with older versions of npm', async () => {
expect(result.lockfileVersion).toEqual(1);
});
it('should return lockfileVersion 1 with older versions of npm', async () => {
it('should detect npm Workspaces', async () => {
const fixture = path.join(__dirname, 'fixtures', '21-npm-workspaces/a');
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('npm');

View File

@@ -1,11 +0,0 @@
declare module 'intercept-stdout' {
export default function (fn?: InterceptFn): UnhookIntercept
}
interface InterceptFn {
(text: string): string | void
}
interface UnhookIntercept {
(): void
}

View File

@@ -1,5 +0,0 @@
declare module 'promisepipe' {
export default function (
...streams: Array<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>
): Promise<void>
}

View File

@@ -10,9 +10,13 @@
## Usage
Vercel is the optimal workflow for frontend teams. All-in-one: Static and Jamstack deployment, Serverless Functions, and Global CDN.
Vercel is a platform for **static sites and frontend frameworks**, built to integrate with your headless content, commerce, or database.
To install the latest version of Vercel CLI, visit [vercel.com/download](https://vercel.com/download) or run this command:
We provide a **frictionless developer experience** to take care of the hard things: deploy instantly, scale automatically, and serve personalized content around the globe.
We make it easy for frontend teams to **develop, preview, and ship** delightful user experiences, where performance is the default.
To install the latest version of Vercel CLI, run this command:
```bash
npm i -g vercel
@@ -26,6 +30,8 @@ cd <PROJECT> # Change directory to the new project
vercel # Deploy to the cloud
```
Finally, [connect your Git repository to Vercel](https://vercel.com/docs/git) and deploy with `git push`.
## Documentation
For details on how to use Vercel CLI, check out our [documentation](https://vercel.com/docs).

View File

@@ -1,6 +1,6 @@
{
"name": "vercel",
"version": "23.1.1-canary.0",
"version": "23.1.3-canary.53",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Vercel",
@@ -12,33 +12,15 @@
},
"scripts": {
"preinstall": "node ./scripts/preinstall.js",
"test-unit": "nyc ava test/unit.js test/dev-builder.unit.js test/dev-router.unit.js test/dev-server.unit.js test/dev-validate.unit.js --serial --fail-fast --verbose",
"test": "jest",
"test-unit": "jest --coverage --verbose",
"test-integration-cli": "rimraf test/fixtures/integration && ava test/integration.js --serial --fail-fast --verbose",
"test-integration-dev": "ava test/dev/integration.js --serial --fail-fast --verbose",
"prepublishOnly": "yarn build",
"coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov",
"coverage": "codecov",
"build": "node -r ts-eager/register ./scripts/build.ts",
"build-dev": "node -r ts-eager/register ./scripts/build.ts --dev"
},
"nyc": {
"include": [
"src/**"
],
"extension": [
".js",
".ts"
],
"require": [
"ts-node/register"
],
"reporter": [
"text",
"html"
],
"sourceMap": true,
"instrument": true,
"all": true
},
"bin": {
"vc": "./dist/index.js",
"vercel": "./dist/index.js"
@@ -61,14 +43,17 @@
"node": ">= 12"
},
"dependencies": {
"@vercel/build-utils": "2.12.1-canary.0",
"@vercel/go": "1.2.3",
"@vercel/node": "1.12.0",
"@vercel/python": "2.0.5",
"@vercel/ruby": "1.2.7",
"update-notifier": "4.1.0"
"@vercel/build-utils": "2.12.3-canary.32",
"@vercel/go": "1.2.4-canary.4",
"@vercel/node": "1.12.2-canary.7",
"@vercel/python": "2.1.2-canary.1",
"@vercel/ruby": "1.2.8-canary.6",
"update-notifier": "4.1.0",
"vercel-plugin-middleware": "0.0.0-canary.7",
"vercel-plugin-node": "1.12.2-canary.24"
},
"devDependencies": {
"@next/env": "11.1.2",
"@sentry/node": "5.5.0",
"@sindresorhus/slugify": "0.11.0",
"@tootallnate/once": "1.1.2",
@@ -76,13 +61,16 @@
"@types/ansi-regex": "4.0.0",
"@types/async-retry": "1.2.1",
"@types/bytes": "3.0.0",
"@types/chance": "1.1.3",
"@types/debug": "0.0.31",
"@types/dotenv": "6.1.1",
"@types/escape-html": "0.0.20",
"@types/fs-extra": "5.0.5",
"@types/express": "4.17.13",
"@types/fs-extra": "9.0.13",
"@types/glob": "7.1.1",
"@types/http-proxy": "1.16.2",
"@types/inquirer": "7.3.1",
"@types/jest": "27.0.1",
"@types/load-json-file": "2.0.7",
"@types/mime-types": "2.1.0",
"@types/minimatch": "3.0.3",
@@ -97,11 +85,14 @@
"@types/semver": "6.0.1",
"@types/tar-fs": "1.16.1",
"@types/text-table": "0.2.0",
"@types/title": "3.4.1",
"@types/universal-analytics": "0.4.2",
"@types/update-notifier": "5.1.0",
"@types/which": "1.3.2",
"@types/write-json-file": "2.2.1",
"@vercel/frameworks": "0.5.1-canary.0",
"@vercel/frameworks": "0.5.1-canary.16",
"@vercel/ncc": "0.24.0",
"@vercel/nft": "0.17.0",
"@zeit/fun": "0.11.2",
"@zeit/source-map-support": "0.6.2",
"ajv": "6.12.2",
@@ -115,6 +106,7 @@
"ava": "2.2.0",
"bytes": "3.0.0",
"chalk": "4.1.0",
"chance": "1.1.7",
"chokidar": "3.3.1",
"clipboardy": "2.1.0",
"codecov": "3.8.2",
@@ -130,8 +122,9 @@
"escape-html": "1.0.3",
"esm": "3.1.4",
"execa": "3.2.0",
"express": "4.17.1",
"fast-deep-equal": "3.1.3",
"fs-extra": "7.0.1",
"fs-extra": "10.0.0",
"get-port": "5.1.1",
"glob": "7.1.2",
"http-proxy": "1.18.1",
@@ -148,7 +141,6 @@
"ms": "2.1.2",
"node-fetch": "2.6.1",
"npm-package-arg": "6.1.0",
"nyc": "13.2.0",
"open": "8.2.0",
"ora": "3.4.0",
"pcre-to-regexp": "1.0.0",
@@ -161,7 +153,6 @@
"rimraf": "3.0.2",
"semver": "5.5.0",
"serve-handler": "6.1.1",
"sinon": "4.4.2",
"strip-ansi": "5.2.0",
"stripe": "5.1.0",
"tar-fs": "1.16.3",
@@ -178,5 +169,19 @@
"which": "2.0.2",
"write-json-file": "2.2.0",
"xdg-app-paths": "5.1.0"
},
"jest": {
"preset": "ts-jest",
"globals": {
"ts-jest": {
"diagnostics": false,
"isolatedModules": true
}
},
"verbose": false,
"testEnvironment": "node",
"testMatch": [
"<rootDir>/test/**/*.test.ts"
]
}
}

View File

@@ -4,6 +4,7 @@ import { join } from 'path';
import { remove, writeFile } from 'fs-extra';
const dirRoot = join(__dirname, '..');
const distRoot = join(dirRoot, 'dist');
async function createConstants() {
console.log('Creating constants.ts');
@@ -48,13 +49,12 @@ async function main() {
// Do the initial `ncc` build
console.log();
const src = join(dirRoot, 'src');
const args = ['ncc', 'build', '--external', 'update-notifier'];
if (isDev) {
args.push('--source-map');
}
args.push(src);
await execa('yarn', args, { stdio: 'inherit' });
args.push('src/index.ts');
await execa('yarn', args, { stdio: 'inherit', cwd: dirRoot });
// `ncc` has some issues with `@zeit/fun`'s runtime files:
// - Executable bits on the `bootstrap` files appear to be lost:
@@ -72,19 +72,13 @@ async function main() {
dirRoot,
'../../node_modules/@zeit/fun/dist/src/runtimes'
);
const dest = join(dirRoot, 'dist/runtimes');
await cpy('**/*', dest, { parents: true, cwd: runtimes });
await cpy('**/*', join(distRoot, 'runtimes'), {
parents: true,
cwd: runtimes,
});
// Band-aid to delete stuff that `ncc` bundles, but it shouldn't:
// TypeScript definition files from `@vercel/build-utils`
await remove(join(dirRoot, 'dist', 'dist'));
// The Readme and `package.json` from "config-chain" module
await remove(join(dirRoot, 'dist', 'config-chain'));
// A bunch of source `.ts` files from CLI's `util` directory
await remove(join(dirRoot, 'dist', 'util'));
// Band-aid to bundle stuff that `ncc` neglects to bundle
await cpy(join(dirRoot, 'src/util/projects/VERCEL_DIR_README.txt'), distRoot);
console.log('Finished building Vercel CLI');
}

View File

@@ -421,7 +421,7 @@ function handleCreateAliasError<T>(
return error;
}
function getTargetsForAlias(args: string[], { alias }: VercelConfig) {
function getTargetsForAlias(args: string[], { alias }: VercelConfig = {}) {
if (args.length) {
return [args[args.length - 1]]
.map(target => (target.indexOf('.') !== -1 ? toHost(target) : target))

View File

@@ -6,12 +6,11 @@ import cardBrands from '../../util/billing/card-brands';
import success from '../../util/output/success';
import wait from '../../util/output/wait';
import chars from '../../util/output/chars';
import rightPad from '../../util/output/right-pad';
import error from '../../util/output/error';
const expDateMiddleware = data => data;
export default async function({ creditCards, clear = false, contextName }) {
export default async function ({ creditCards, clear = false, contextName }) {
const state = {
error: undefined,
cardGroupLabel: `> ${chalk.bold(
@@ -19,13 +18,13 @@ export default async function({ creditCards, clear = false, contextName }) {
)}`,
name: {
label: rightPad('Full Name', 12),
label: 'Full Name'.padEnd(12),
placeholder: 'John Appleseed',
validateValue: data => data.trim().length > 0,
},
cardNumber: {
label: rightPad('Number', 12),
label: 'Number'.padEnd(12),
mask: 'cc',
placeholder: '#### #### #### ####',
validateKeypress: (data, value) => /\d/.test(data) && value.length < 19,
@@ -40,7 +39,7 @@ export default async function({ creditCards, clear = false, contextName }) {
},
ccv: {
label: rightPad('CCV', 12),
label: 'CCV'.padEnd(12),
mask: 'ccv',
placeholder: '###',
validateValue: data => {
@@ -50,7 +49,7 @@ export default async function({ creditCards, clear = false, contextName }) {
},
expDate: {
label: rightPad('Exp. Date', 12),
label: 'Exp. Date'.padEnd(12),
mask: 'expDate',
placeholder: 'mm / yyyy',
middleware: expDateMiddleware,
@@ -147,9 +146,9 @@ export default async function({ creditCards, clear = false, contextName }) {
console.log(
success(
`${state.cardNumber.brand ||
state.cardNumber.card.brand} ending in ${res.last4 ||
res.card.last4} was added to ${chalk.bold(contextName)}`
`${state.cardNumber.brand || state.cardNumber.card.brand} ending in ${
res.last4 || res.card.last4
} was added to ${chalk.bold(contextName)}`
)
);
} catch (err) {

View File

@@ -3,7 +3,7 @@ import ms from 'ms';
import plural from 'pluralize';
import { error } from '../../util/error';
import NowCreditCards from '../../util/credit-cards';
import indent from '../../util/indent';
import indent from '../../util/output/indent';
import listInput from '../../util/input/list';
import success from '../../util/output/success';
import promptBool from '../../util/input/prompt-bool';
@@ -51,8 +51,6 @@ const help = () => {
};
let argv;
let debug;
let apiUrl;
let subcommand;
export default async client => {
@@ -65,8 +63,6 @@ export default async client => {
argv._ = argv._.slice(1);
debug = argv['--debug'];
apiUrl = client.apiUrl;
subcommand = argv._[0];
if (argv['--help'] || !subcommand) {
@@ -76,17 +72,13 @@ export default async client => {
const {
output,
authConfig: { token },
config: { currentTeam },
} = client;
const start = new Date();
const creditCards = new NowCreditCards({
apiUrl,
token,
debug,
client,
currentTeam,
output,
});
let contextName = null;

View File

@@ -0,0 +1,879 @@
import { loadEnvConfig, processEnv } from '@next/env';
import {
execCommand,
getScriptName,
GlobOptions,
scanParentDirs,
spawnAsync,
} from '@vercel/build-utils';
import { nodeFileTrace } from '@vercel/nft';
import Sema from 'async-sema';
import chalk from 'chalk';
import { SpawnOptions } from 'child_process';
import { assert } from 'console';
import { createHash } from 'crypto';
import fs from 'fs-extra';
import ogGlob from 'glob';
import { dirname, isAbsolute, join, parse, relative, resolve } from 'path';
import pluralize from 'pluralize';
import Client from '../util/client';
import { VercelConfig } from '../util/dev/types';
import { emoji, prependEmoji } from '../util/emoji';
import getArgs from '../util/get-args';
import handleError from '../util/handle-error';
import confirm from '../util/input/confirm';
import { isSettingValue } from '../util/is-setting-value';
import cmd from '../util/output/cmd';
import logo from '../util/output/logo';
import param from '../util/output/param';
import stamp from '../util/output/stamp';
import { getCommandName, getPkgName } from '../util/pkg-name';
import { loadCliPlugins } from '../util/plugins';
import { findFramework } from '../util/projects/find-framework';
import { VERCEL_DIR } from '../util/projects/link';
import { readProjectSettings } from '../util/projects/project-settings';
import pull from './pull';
const sema = new Sema(16, {
capacity: 100,
});
const help = () => {
return console.log(`
${chalk.bold(`${logo} ${getPkgName()} build`)}
${chalk.dim('Options:')}
-h, --help Output usage information
-A ${chalk.bold.underline('FILE')}, --local-config=${chalk.bold.underline(
'FILE'
)} Path to the local ${'`vercel.json`'} file
-Q ${chalk.bold.underline('DIR')}, --global-config=${chalk.bold.underline(
'DIR'
)} Path to the global ${'`.vercel`'} directory
--cwd [path] The current working directory
-d, --debug Debug mode [off]
-y, --yes Skip the confirmation prompt
${chalk.dim('Examples:')}
${chalk.gray('')} Build the project
${chalk.cyan(`$ ${getPkgName()} build`)}
${chalk.cyan(`$ ${getPkgName()} build --cwd ./path-to-project`)}
`);
};
const OUTPUT_DIR = '.output';
export default async function main(client: Client) {
if (process.env.__VERCEL_BUILD_RUNNING) {
client.output.error(
`${cmd(
`${getPkgName()} build`
)} must not recursively invoke itself. Check the Build Command in the Project Settings or the ${cmd(
'build'
)} script in ${cmd('package.json')}`
);
client.output.error(
`Learn More: https://vercel.link/recursive-invocation-of-commands`
);
return 1;
} else {
process.env.__VERCEL_BUILD_RUNNING = '1';
}
let argv;
const buildStamp = stamp();
try {
argv = getArgs(client.argv.slice(2), {
'--debug': Boolean,
'--cwd': String,
});
} catch (err) {
handleError(err);
return 1;
}
if (argv['--help']) {
help();
return 2;
}
let cwd = argv['--cwd'] || process.cwd();
let project = await readProjectSettings(join(cwd, VERCEL_DIR));
// If there are no project settings, only then do we pull them down
while (!project?.settings) {
const confirmed = await confirm(
`No Project Settings found locally. Run ${getCommandName(
'pull'
)} for retrieving them?`,
true
);
if (!confirmed) {
client.output.print(`Aborted. No Project Settings retrieved.\n`);
return 0;
}
const result = await pull(client);
if (result !== 0) {
return result;
}
project = await readProjectSettings(join(cwd, VERCEL_DIR));
}
// If `rootDirectory` exists, then `baseDir` will be the repo's root directory.
const baseDir = cwd;
cwd = project.settings.rootDirectory
? join(cwd, project.settings.rootDirectory)
: cwd;
// Load the environment
const { combinedEnv, loadedEnvFiles } = loadEnvConfig(cwd, false, {
info: () => ({}), // we don't want to log this yet.
error: (...args: any[]) => client.output.error(args.join(' ')),
});
// Set process.env with loaded environment variables
processEnv(loadedEnvFiles);
const spawnOpts: {
env: Record<string, string | undefined>;
} = {
env: { ...combinedEnv, VERCEL: '1' },
};
process.chdir(cwd);
const framework = findFramework(project.settings.framework);
// If this is undefined, we bail. If it is null, then findFramework should return "Other",
// so this should really never happen, but just in case....
if (framework === undefined) {
client.output.error(
`Framework detection failed or is malformed. Please run ${getCommandName(
'pull'
)} again.`
);
return 1;
}
const buildState = { ...project.settings };
const formatSetting = (
name: string,
override: string | null | undefined,
defaults: typeof framework.settings.outputDirectory
) =>
` - ${chalk.bold(`${name}:`)} ${`${
override
? override + ` (override)`
: 'placeholder' in defaults
? chalk.italic(`${defaults.placeholder}`)
: defaults.value
}`}`;
console.log(`Retrieved Project Settings:`);
console.log(
chalk.dim(` - ${chalk.bold(`Framework Preset:`)} ${framework.name}`)
);
console.log(
chalk.dim(
formatSetting(
'Build Command',
project.settings.buildCommand,
framework.settings.buildCommand
)
)
);
console.log(
chalk.dim(
formatSetting(
'Output Directory',
project.settings.outputDirectory,
framework.settings.outputDirectory
)
)
);
buildState.outputDirectory =
project.settings.outputDirectory ||
(isSettingValue(framework.settings.outputDirectory)
? framework.settings.outputDirectory.value
: null);
buildState.rootDirectory = project.settings.rootDirectory;
if (loadedEnvFiles.length > 0) {
console.log(
`Loaded Environment Variables from ${loadedEnvFiles.length} ${pluralize(
'file',
loadedEnvFiles.length
)}:`
);
for (let envFile of loadedEnvFiles) {
console.log(chalk.dim(` - ${envFile.path}`));
}
}
// Load plugins
const debug = argv['--debug'];
let plugins;
try {
plugins = await loadCliPlugins(cwd, client.output);
} catch (error) {
client.output.error('Failed to load CLI Plugins');
handleError(error, { debug });
return 1;
}
const origLog = console.log;
const origErr = console.error;
const prefixedLog = (
prefix: string,
args: any[],
logger: (...args: any[]) => void
) => {
if (typeof args[0] === 'string') {
args[0] = `${prefix} ${args[0]}`;
} else {
args.unshift(prefix);
}
return logger(...args);
};
if (plugins?.pluginCount && plugins?.pluginCount > 0) {
console.log(
`Loaded ${plugins.pluginCount} CLI ${pluralize(
'Plugin',
plugins.pluginCount
)}`
);
// preBuild Plugins
if (plugins.preBuildPlugins.length > 0) {
console.log(
`Running ${plugins.pluginCount} CLI ${pluralize(
'Plugin',
plugins.pluginCount
)} before Build Command:`
);
for (let item of plugins.preBuildPlugins) {
const { name, plugin, color } = item;
if (typeof plugin.preBuild === 'function') {
const pluginStamp = stamp();
const fullName = name + '.preBuild';
const prefix = chalk.gray(' > ') + color(fullName + ':');
client.output.debug(`Running ${fullName}:`);
try {
console.log = (...args: any[]) =>
prefixedLog(prefix, args, origLog);
console.error = (...args: any[]) =>
prefixedLog(prefix, args, origErr);
await plugin.preBuild();
client.output.debug(
`Completed ${fullName} ${chalk.dim(`${pluginStamp()}`)}`
);
} catch (error) {
client.output.error(`${prefix} failed`);
handleError(error, { debug });
return 1;
} finally {
console.log = origLog;
console.error = origErr;
}
}
}
}
}
// Clean the output directory
fs.removeSync(join(cwd, OUTPUT_DIR));
if (framework && process.env.VERCEL_URL && 'envPrefix' in framework) {
for (const key of Object.keys(process.env)) {
if (key.startsWith('VERCEL_')) {
const newKey = `${framework.envPrefix}${key}`;
// Set `process.env` and `spawnOpts.env` to make sure the variables are
// available to the `build` step and the CLI Plugins.
process.env[newKey] = process.env[newKey] || process.env[key];
spawnOpts.env[newKey] = process.env[newKey];
}
}
}
// Required for Next.js to produce the correct `.nft.json` files.
spawnOpts.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT = baseDir;
// Yarn v2 PnP mode may be activated, so force
// "node-modules" linker style
const env = {
YARN_NODE_LINKER: 'node-modules',
...spawnOpts.env,
};
if (typeof buildState.buildCommand === 'string') {
console.log(`Running Build Command: ${cmd(buildState.buildCommand)}`);
await execCommand(buildState.buildCommand, {
...spawnOpts,
env,
cwd,
});
} else if (fs.existsSync(join(cwd, 'package.json'))) {
await runPackageJsonScript(
client,
cwd,
['vercel-build', 'now-build', 'build'],
spawnOpts
);
} else if (typeof framework.settings.buildCommand.value === 'string') {
console.log(
`Running Build Command: ${cmd(framework.settings.buildCommand.value)}`
);
await execCommand(framework.settings.buildCommand.value, {
...spawnOpts,
env,
cwd,
});
}
if (!fs.existsSync(join(cwd, OUTPUT_DIR))) {
let dotNextDir: string | null = null;
// If a custom `outputDirectory` was set, we'll need to verify
// if it's `.next` output, or just static output.
const userOutputDirectory = project.settings.outputDirectory;
if (typeof userOutputDirectory === 'string') {
if (fs.existsSync(join(cwd, userOutputDirectory, 'BUILD_ID'))) {
dotNextDir = join(cwd, userOutputDirectory);
client.output.debug(
`Consider ${param(userOutputDirectory)} as ${param('.next')} output.`
);
}
} else if (fs.existsSync(join(cwd, '.next'))) {
dotNextDir = join(cwd, '.next');
client.output.debug(`Found ${param('.next')} directory.`);
}
// We cannot rely on the `framework` alone, as it might be a static export,
// and the current build might use a differnt project that's not in the settings.
const isNextOutput = Boolean(dotNextDir);
const outputDir = isNextOutput ? OUTPUT_DIR : join(OUTPUT_DIR, 'static');
const distDir =
dotNextDir ||
userOutputDirectory ||
(await framework.getFsOutputDir(cwd));
await fs.ensureDir(join(cwd, outputDir));
const copyStamp = stamp();
client.output.spinner(
`Copying files from ${param(distDir)} to ${param(outputDir)}`
);
const files = await glob(join(relative(cwd, distDir), '**'), {
ignore: [
'node_modules/**',
'.vercel/**',
'.env',
'.env.*',
'.*ignore',
'_middleware.ts',
'_middleware.mts',
'_middleware.cts',
'_middleware.mjs',
'_middleware.cjs',
'_middleware.js',
'api/**',
'.git/**',
'.next/cache/**',
],
nodir: true,
dot: true,
cwd,
absolute: true,
});
await Promise.all(
files.map(f =>
smartCopy(
client,
f,
distDir === '.'
? join(cwd, outputDir, relative(cwd, f))
: f.replace(distDir, outputDir)
)
)
);
client.output.stopSpinner();
console.log(
`Copied ${files.length.toLocaleString()} files from ${param(
distDir
)} to ${param(outputDir)} ${copyStamp()}`
);
const buildManifestPath = join(cwd, OUTPUT_DIR, 'build-manifest.json');
const routesManifestPath = join(cwd, OUTPUT_DIR, 'routes-manifest.json');
if (!fs.existsSync(buildManifestPath)) {
client.output.debug(
`Generating build manifest: ${param(buildManifestPath)}`
);
const buildManifest = {
version: 1,
cache: framework.cachePattern ? [framework.cachePattern] : [],
};
await fs.writeJSON(buildManifestPath, buildManifest, { spaces: 2 });
}
if (!fs.existsSync(routesManifestPath)) {
client.output.debug(
`Generating routes manifest: ${param(routesManifestPath)}`
);
const routesManifest = {
version: 3,
pages404: true,
basePath: '',
redirects: framework.defaultRedirects ?? [],
headers: framework.defaultHeaders ?? [],
dynamicRoutes: [],
dataRoutes: [],
rewrites: framework.defaultRewrites ?? [],
};
await fs.writeJSON(
join(cwd, OUTPUT_DIR, 'routes-manifest.json'),
routesManifest,
{ spaces: 2 }
);
}
// Special Next.js processing.
if (isNextOutput) {
// The contents of `.output/static` should be placed inside of `.output/static/_next/static`
const tempStatic = '___static';
await fs.rename(
join(cwd, OUTPUT_DIR, 'static'),
join(cwd, OUTPUT_DIR, tempStatic)
);
await fs.mkdirp(join(cwd, OUTPUT_DIR, 'static', '_next', 'static'));
await fs.rename(
join(cwd, OUTPUT_DIR, tempStatic),
join(cwd, OUTPUT_DIR, 'static', '_next', 'static')
);
// Next.js might reference files from the `static` directory in `middleware-manifest.json`.
// Since we move all files from `static` to `static/_next/static`, we'll need to change
// those references as well and update the manifest file.
const middlewareManifest = join(
cwd,
OUTPUT_DIR,
'server',
'middleware-manifest.json'
);
if (fs.existsSync(middlewareManifest)) {
const manifest = await fs.readJSON(middlewareManifest);
Object.keys(manifest.middleware).forEach(key => {
const files = manifest.middleware[key].files.map((f: string) => {
if (f.startsWith('static/')) {
const next = f.replace(/^static\//gm, 'static/_next/static/');
client.output.debug(
`Replacing file in \`middleware-manifest.json\`: ${f} => ${next}`
);
return next;
}
return f;
});
manifest.middleware[key].files = files;
});
await fs.writeJSON(middlewareManifest, manifest);
}
// We want to pick up directories for user-provided static files into `.`output/static`.
// More specifically, the static directory contents would then be mounted to `output/static/static`,
// and the public directory contents would be mounted to `output/static`. Old Next.js versions
// allow `static`, and newer ones allow both, but since there's nobody that actually uses both,
// we can check for the existence of both and pick the first match that we find (first
// `public`, then`static`). We can't read both at the same time because that would mean we'd
// read public for old Next.js versions that don't support it, which might be breaking (and
// we don't want to make vercel build specific framework versions).
const nextSrcDirectory = dirname(distDir);
const publicFiles = await glob('public/**', {
nodir: true,
dot: true,
cwd: nextSrcDirectory,
absolute: true,
});
if (publicFiles.length > 0) {
await Promise.all(
publicFiles.map(f =>
smartCopy(
client,
f,
join(
OUTPUT_DIR,
'static',
relative(join(dirname(distDir), 'public'), f)
)
)
)
);
} else {
const staticFiles = await glob('static/**', {
nodir: true,
dot: true,
cwd: nextSrcDirectory,
absolute: true,
});
await Promise.all(
staticFiles.map(f =>
smartCopy(
client,
f,
join(
OUTPUT_DIR,
'static',
'static',
relative(join(dirname(distDir), 'static'), f)
)
)
)
);
}
// Regardless of the Next.js version, we make sure that it is compatible with
// the Filesystem API. We get there by moving all the files needed
// into the outputs directory `inputs` folder. Next.js is > 12, we can
// read the .nft.json files directly. If there aren't .nft.json files
// we trace and create them. We then resolve the files in each nft file list
// and move them into the "inputs" directory. We rename them with hashes to
// prevent collisions and then update the related .nft files accordingly
// to point to the newly named input files. Again, all of this is so that Next.js
// works with the Filesystem API (and so .output contains all inputs
// needed to run Next.js) and `vc --prebuilt`.
const nftFiles = await glob(join(OUTPUT_DIR, '**', '*.nft.json'), {
nodir: true,
dot: true,
ignore: ['cache/**'],
cwd,
absolute: true,
});
// If there are no .nft.json files, we know that Next.js < 12. We then
// execute the tracing on our own.
if (nftFiles.length === 0) {
const serverFiles = await glob(
join(OUTPUT_DIR, 'server', 'pages', '**', '*.js'),
{
nodir: true,
dot: true,
cwd,
ignore: ['webpack-runtime.js'],
absolute: true,
}
);
for (let f of serverFiles) {
const { ext, dir } = parse(f);
const { fileList } = await nodeFileTrace([f], {
ignore: [
relative(cwd, f),
'node_modules/next/dist/pages/**/*',
'node_modules/next/dist/compiled/webpack/(bundle4|bundle5).js',
'node_modules/react/**/*.development.js',
'node_modules/react-dom/**/*.development.js',
'node_modules/use-subscription/**/*.development.js',
'node_modules/sharp/**/*',
],
});
fileList.delete(relative(cwd, f));
await resolveNftToOutput({
client,
baseDir,
outputDir: OUTPUT_DIR,
nftFileName: f.replace(ext, '.js.nft.json'),
distDir,
nft: {
version: 1,
files: Array.from(fileList).map(fileListEntry =>
relative(dir, fileListEntry)
),
},
});
}
} else {
for (let f of nftFiles) {
const json = await fs.readJson(f);
await resolveNftToOutput({
client,
baseDir,
outputDir: OUTPUT_DIR,
nftFileName: f,
nft: json,
distDir,
});
}
}
const requiredServerFilesPath = join(
OUTPUT_DIR,
'required-server-files.json'
);
if (fs.existsSync(requiredServerFilesPath)) {
client.output.debug(`Resolve ${param('required-server-files.json')}.`);
const requiredServerFilesJson = await fs.readJSON(
requiredServerFilesPath
);
await fs.writeJSON(requiredServerFilesPath, {
...requiredServerFilesJson,
appDir: '.',
files: requiredServerFilesJson.files.map((i: string) => {
const originalPath = join(requiredServerFilesJson.appDir, i);
const relPath = join(OUTPUT_DIR, relative(distDir, originalPath));
const absolutePath = join(cwd, relPath);
const output = relative(baseDir, absolutePath);
return relPath === output
? relPath
: {
input: relPath,
output,
};
}),
});
}
}
}
// Build Plugins
if (plugins?.buildPlugins && plugins.buildPlugins.length > 0) {
console.log(
`Running ${plugins.pluginCount} CLI ${pluralize(
'Plugin',
plugins.pluginCount
)} after Build Command:`
);
let vercelConfig: VercelConfig = {};
try {
vercelConfig = await fs.readJSON(join(cwd, 'vercel.json'));
} catch (error) {
if (error.code !== 'ENOENT') {
throw new Error(`Failed to read vercel.json: ${error.message}`);
}
}
for (let item of plugins.buildPlugins) {
const { name, plugin, color } = item;
if (typeof plugin.build === 'function') {
const pluginStamp = stamp();
const fullName = name + '.build';
const prefix = chalk.gray(' > ') + color(fullName + ':');
client.output.debug(`Running ${fullName}:`);
try {
console.log = (...args: any[]) => prefixedLog(prefix, args, origLog);
console.error = (...args: any[]) =>
prefixedLog(prefix, args, origErr);
await plugin.build({
vercelConfig,
workPath: cwd,
});
client.output.debug(
`Completed ${fullName} ${chalk.dim(`${pluginStamp()}`)}`
);
} catch (error) {
client.output.error(`${prefix} failed`);
handleError(error, { debug });
return 1;
} finally {
console.log = origLog;
console.error = origLog;
}
}
}
}
console.log(
`${prependEmoji(
`Build Completed in ${chalk.bold(OUTPUT_DIR)} ${chalk.gray(
buildStamp()
)}`,
emoji('success')
)}`
);
return 0;
}
export async function runPackageJsonScript(
client: Client,
destPath: string,
scriptNames: string | Iterable<string>,
spawnOpts?: SpawnOptions
) {
assert(isAbsolute(destPath));
const { packageJson, cliType, lockfileVersion } = await scanParentDirs(
destPath,
true
);
const scriptName = getScriptName(
packageJson,
typeof scriptNames === 'string' ? [scriptNames] : scriptNames
);
if (!scriptName) return false;
client.output.debug('Running user script...');
const runScriptTime = Date.now();
const opts: any = { cwd: destPath, ...spawnOpts };
const env = (opts.env = { ...process.env, ...opts.env });
if (cliType === 'npm') {
opts.prettyCommand = `npm run ${scriptName}`;
if (typeof lockfileVersion === 'number' && lockfileVersion >= 2) {
// Ensure that npm 7 is at the beginning of the `$PATH`
env.PATH = `/node16/bin-npm7:${env.PATH}`;
}
} else {
opts.prettyCommand = `yarn run ${scriptName}`;
// Yarn v2 PnP mode may be activated, so force "node-modules" linker style
if (!env.YARN_NODE_LINKER) {
env.YARN_NODE_LINKER = 'node-modules';
}
}
console.log(`Running Build Command: ${cmd(opts.prettyCommand)}\n`);
await spawnAsync(cliType, ['run', scriptName], opts);
console.log(); // give it some room
client.output.debug(`Script complete [${Date.now() - runScriptTime}ms]`);
return true;
}
async function linkOrCopy(existingPath: string, newPath: string) {
try {
if (
newPath.endsWith('.nft.json') ||
newPath.endsWith('middleware-manifest.json') ||
newPath.endsWith('required-server-files.json')
) {
await fs.copy(existingPath, newPath, {
overwrite: true,
});
} else {
await fs.createLink(existingPath, newPath);
}
} catch (err: any) {
// eslint-disable-line
// If a symlink to the same file already exists
// then trying to copy it will make an empty file from it.
if (err['code'] === 'EEXIST') return;
// In some VERY rare cases (1 in a thousand), symlink creation fails on Windows.
// In that case, we just fall back to copying.
// This issue is reproducible with "pnpm add @material-ui/icons@4.9.1"
await fs.copy(existingPath, newPath, {
overwrite: true,
});
}
}
async function smartCopy(client: Client, from: string, to: string) {
sema.acquire();
try {
client.output.debug(`Copying from ${from} to ${to}`);
await linkOrCopy(from, to);
} finally {
sema.release();
}
}
async function glob(pattern: string, options: GlobOptions): Promise<string[]> {
return new Promise((resolve, reject) => {
ogGlob(pattern, options, (err, files) => {
err ? reject(err) : resolve(files);
});
});
}
/**
* Computes a hash for the given buf.
*
* @param {Buffer} file data
* @return {String} hex digest
*/
function hash(buf: Buffer): string {
return createHash('sha1').update(buf).digest('hex');
}
interface NftFile {
version: number;
files: (string | { input: string; output: string })[];
}
// resolveNftToOutput takes nft file and moves all of its trace files
// into the specified directory + `inputs`, (renaming them to their hash + ext) and
// subsequently updating the original nft file accordingly. This is done
// to make the `.output` directory be self-contained, so that it works
// properly with `vc --prebuilt`.
async function resolveNftToOutput({
client,
baseDir,
outputDir,
nftFileName,
distDir,
nft,
}: {
client: Client;
baseDir: string;
outputDir: string;
nftFileName: string;
distDir: string;
nft: NftFile;
}) {
client.output.debug(`Processing and resolving ${nftFileName}`);
await fs.ensureDir(join(outputDir, 'inputs'));
const newFilesList: NftFile['files'] = [];
// If `distDir` is a subdirectory, then the input has to be resolved to where the `.output` directory will be.
const relNftFileName = relative(outputDir, nftFileName);
const origNftFilename = join(distDir, relNftFileName);
if (relNftFileName.startsWith('cache/')) {
// No need to process the `cache/` directory.
// Paths in it might also not be relative to `cache` itself.
return;
}
for (let fileEntity of nft.files) {
const relativeInput =
typeof fileEntity === 'string' ? fileEntity : fileEntity.input;
const fullInput = resolve(join(parse(origNftFilename).dir, relativeInput));
// if the resolved path is NOT in the .output directory we move in it there
if (!fullInput.includes(distDir)) {
const { ext } = parse(fullInput);
const raw = await fs.readFile(fullInput);
const newFilePath = join(outputDir, 'inputs', hash(raw) + ext);
smartCopy(client, fullInput, newFilePath);
// We have to use `baseDir` instead of `cwd`, because we want to
// mount everything from there (especially `node_modules`).
// This is important for NPM Workspaces where `node_modules` is not
// in the directory of the workspace.
const output = relative(baseDir, fullInput).replace('.output', '.next');
newFilesList.push({
input: relative(parse(nftFileName).dir, newFilePath),
output,
});
} else {
newFilesList.push(relativeInput);
}
}
// Update the .nft.json with new input and output mapping
await fs.writeJSON(nftFileName, {
...nft,
files: newFilesList,
});
}

View File

@@ -18,9 +18,10 @@ export const help = () => `
init [example] Initialize an example project
ls | list [app] Lists deployments
inspect [id] Displays information related to a deployment
link Link local directory to a Vercel Project
link [path] Link local directory to a Vercel Project
login [email] Logs into your account or creates a new one
logout Logs out of your account
pull [path] Pull your Project Settings from the cloud
switch [scope] Switches between teams and your personal account
help [cmd] Displays complete help for [cmd]

View File

@@ -1,14 +1,66 @@
import ms from 'ms';
import fs from 'fs-extra';
import { resolve, basename } from 'path';
import { VercelConfig, fileNameSymbol } from '@vercel/client';
import bytes from 'bytes';
import chalk from 'chalk';
import { join, resolve, basename } from 'path';
import { Dictionary, fileNameSymbol, VercelConfig } from '@vercel/client';
import code from '../../util/output/code';
import highlight from '../../util/output/highlight';
import { readLocalConfig } from '../../util/config/files';
import getArgs from '../../util/get-args';
import { handleError } from '../../util/error';
import { help } from './args';
import deploy from './latest';
import Client from '../../util/client';
import { write as copy } from 'clipboardy';
import { getPrettyError } from '@vercel/build-utils';
import toHumanPath from '../../util/humanize-path';
import Now from '../../util';
import stamp from '../../util/output/stamp';
import createDeploy from '../../util/deploy/create-deploy';
import getDeploymentByIdOrHost from '../../util/deploy/get-deployment-by-id-or-host';
import parseMeta from '../../util/parse-meta';
import linkStyle from '../../util/output/link';
import param from '../../util/output/param';
import {
BuildsRateLimited,
DeploymentNotFound,
DeploymentPermissionDenied,
InvalidDeploymentId,
DomainNotFound,
DomainNotVerified,
DomainPermissionDenied,
DomainVerificationFailed,
InvalidDomain,
TooManyRequests,
UserAborted,
DeploymentsRateLimited,
AliasDomainConfigured,
MissingBuildScript,
ConflictingFilePath,
ConflictingPathSegment,
BuildError,
NotDomainOwner,
} from '../../util/errors-ts';
import { SchemaValidationFailed } from '../../util/errors';
import purchaseDomainIfAvailable from '../../util/domains/purchase-domain-if-available';
import confirm from '../../util/input/confirm';
import editProjectSettings from '../../util/input/edit-project-settings';
import {
getLinkedProject,
linkFolderToProject,
} from '../../util/projects/link';
import getProjectName from '../../util/get-project-name';
import selectOrg from '../../util/input/select-org';
import inputProject from '../../util/input/input-project';
import { prependEmoji, emoji } from '../../util/emoji';
import { inputRootDirectory } from '../../util/input/input-root-directory';
import validatePaths, {
validateRootDirectory,
} from '../../util/validate-paths';
import { getCommandName } from '../../util/pkg-name';
import { getPreferredPreviewURL } from '../../util/deploy/get-preferred-preview-url';
import { Output } from '../../util/output';
import { help } from './args';
import { getDeploymentChecks } from '../../util/deploy/get-deployment-checks';
export default async (client: Client) => {
const { output } = client;
@@ -27,6 +79,7 @@ export default async (client: Client) => {
// This is not an array in favor of matching
// the config property name.
'--regions': String,
'--prebuilt': Boolean,
'--prod': Boolean,
'--confirm': Boolean,
'-f': '--force',
@@ -65,10 +118,7 @@ export default async (client: Client) => {
paths = [process.cwd()];
}
let localConfig: VercelConfig | null = client.localConfig;
if (!localConfig || localConfig instanceof Error) {
localConfig = readLocalConfig(paths[0]);
}
let localConfig = client.localConfig || readLocalConfig(paths[0]);
for (const path of paths) {
try {
@@ -105,5 +155,755 @@ export default async (client: Client) => {
}
}
return deploy(client, paths, localConfig, argv);
const { log, debug, error, warn, isTTY } = output;
const quiet = !isTTY;
// check paths
const pathValidation = await validatePaths(output, paths);
if (!pathValidation.valid) {
return pathValidation.exitCode;
}
const { isFile, path } = pathValidation;
const autoConfirm = argv['--confirm'] || isFile;
// deprecate --name
if (argv['--name']) {
output.print(
`${prependEmoji(
`The ${param(
'--name'
)} option is deprecated (https://vercel.link/name-flag)`,
emoji('warning')
)}\n`
);
}
// retrieve `project` and `org` from .vercel
const link = await getLinkedProject(client, path);
if (link.status === 'error') {
return link.exitCode;
}
let { org, project, status } = link;
let newProjectName = null;
let rootDirectory = project ? project.rootDirectory : null;
let sourceFilesOutsideRootDirectory = true;
if (status === 'not_linked') {
const shouldStartSetup =
autoConfirm ||
(await confirm(
`Set up and deploy ${chalk.cyan(`${toHumanPath(path)}`)}?`,
true
));
if (!shouldStartSetup) {
output.print(`Aborted. Project not set up.\n`);
return 0;
}
try {
org = await selectOrg(
client,
'Which scope do you want to deploy to?',
autoConfirm
);
} catch (err) {
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
output.error(err.message);
return 1;
}
throw err;
}
// We use `localConfig` here to read the name
// even though the `vercel.json` file can change
// afterwards, this is fine since the property
// will be deprecated and can be replaced with
// user input.
const detectedProjectName = getProjectName({
argv,
nowConfig: localConfig || {},
isFile,
paths,
});
const projectOrNewProjectName = await inputProject(
client,
org,
detectedProjectName,
autoConfirm
);
if (typeof projectOrNewProjectName === 'string') {
newProjectName = projectOrNewProjectName;
rootDirectory = await inputRootDirectory(path, output, autoConfirm);
} else {
project = projectOrNewProjectName;
rootDirectory = project.rootDirectory;
sourceFilesOutsideRootDirectory = project.sourceFilesOutsideRootDirectory;
// we can already link the project
await linkFolderToProject(
output,
path,
{
projectId: project.id,
orgId: org.id,
},
project.name,
org.slug
);
status = 'linked';
}
}
// At this point `org` should be populated
if (!org) {
throw new Error(`"org" is not defined`);
}
// Set the `contextName` and `currentTeam` as specified by the
// Project Settings, so that API calls happen with the proper scope
const contextName = org.slug;
client.config.currentTeam = org.type === 'team' ? org.id : undefined;
// if we have `sourceFilesOutsideRootDirectory` set to `true`, we use the current path
// and upload the entire directory.
const sourcePath =
rootDirectory && !sourceFilesOutsideRootDirectory
? join(path, rootDirectory)
: path;
if (
rootDirectory &&
(await validateRootDirectory(
output,
path,
sourcePath,
project
? `To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`
: ''
)) === false
) {
return 1;
}
// If Root Directory is used we'll try to read the config
// from there instead and use it if it exists.
if (rootDirectory) {
const rootDirectoryConfig = readLocalConfig(join(path, rootDirectory));
if (rootDirectoryConfig) {
debug(`Read local config from root directory (${rootDirectory})`);
localConfig = rootDirectoryConfig;
} else if (localConfig) {
output.print(
`${prependEmoji(
`The ${highlight(
localConfig[fileNameSymbol]!
)} file should be inside of the provided root directory.`,
emoji('warning')
)}\n`
);
}
}
localConfig = localConfig || {};
if (localConfig.name) {
output.print(
`${prependEmoji(
`The ${code('name')} property in ${highlight(
localConfig[fileNameSymbol]!
)} is deprecated (https://vercel.link/name-prop)`,
emoji('warning')
)}\n`
);
}
// build `env`
const isObject = (item: any) =>
Object.prototype.toString.call(item) === '[object Object]';
// This validation needs to happen on the client side because
// the data is merged with other data before it is passed to the API (which
// also does schema validation).
if (typeof localConfig.env !== 'undefined' && !isObject(localConfig.env)) {
error(
`The ${code('env')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
if (typeof localConfig.build !== 'undefined') {
if (!isObject(localConfig.build)) {
error(
`The ${code('build')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
if (
typeof localConfig.build.env !== 'undefined' &&
!isObject(localConfig.build.env)
) {
error(
`The ${code('build.env')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
}
// build `meta`
const meta = Object.assign(
{},
parseMeta(localConfig.meta),
parseMeta(argv['--meta'])
);
// Merge dotenv config, `env` from vercel.json, and `--env` / `-e` arguments
const deploymentEnv = Object.assign(
{},
parseEnv(localConfig.env),
parseEnv(argv['--env'])
);
// Merge build env out of `build.env` from vercel.json, and `--build-env` args
const deploymentBuildEnv = Object.assign(
{},
parseEnv(localConfig.build && localConfig.build.env),
parseEnv(argv['--build-env'])
);
// If there's any undefined values, then inherit them from this process
try {
await addProcessEnv(log, deploymentEnv);
await addProcessEnv(log, deploymentBuildEnv);
} catch (err) {
error(err.message);
return 1;
}
// build `regions`
const regionFlag = (argv['--regions'] || '')
.split(',')
.map((s: string) => s.trim())
.filter(Boolean);
const regions = regionFlag.length > 0 ? regionFlag : localConfig.regions;
// build `target`
let target;
if (argv['--target']) {
const deprecatedTarget = argv['--target'];
if (!['staging', 'production'].includes(deprecatedTarget)) {
error(
`The specified ${param('--target')} ${code(
deprecatedTarget
)} is not valid`
);
return 1;
}
if (deprecatedTarget === 'production') {
warn(
'We recommend using the much shorter `--prod` option instead of `--target production` (deprecated)'
);
}
output.debug(`Setting target to ${deprecatedTarget}`);
target = deprecatedTarget;
} else if (argv['--prod']) {
output.debug('Setting target to production');
target = 'production';
}
const currentTeam = org?.type === 'team' ? org.id : undefined;
const now = new Now({
client,
currentTeam,
});
let deployStamp = stamp();
let deployment = null;
try {
const createArgs: any = {
name: project ? project.name : newProjectName,
env: deploymentEnv,
build: { env: deploymentBuildEnv },
forceNew: argv['--force'],
withCache: argv['--with-cache'],
prebuilt: argv['--prebuilt'],
quiet,
wantsPublic: argv['--public'] || localConfig.public,
isFile,
type: null,
nowConfig: localConfig,
regions,
meta,
deployStamp,
target,
skipAutoDetectionConfirmation: autoConfirm,
};
if (!localConfig.builds || localConfig.builds.length === 0) {
// Only add projectSettings for zero config deployments
createArgs.projectSettings = { sourceFilesOutsideRootDirectory };
}
deployment = await createDeploy(
client,
now,
contextName,
[sourcePath],
createArgs,
org,
!project && !isFile,
path
);
if (deployment.code === 'missing_project_settings') {
let { projectSettings, framework } = deployment;
if (rootDirectory) {
projectSettings.rootDirectory = rootDirectory;
}
if (typeof sourceFilesOutsideRootDirectory !== 'undefined') {
projectSettings.sourceFilesOutsideRootDirectory =
sourceFilesOutsideRootDirectory;
}
const settings = await editProjectSettings(
output,
projectSettings,
framework
);
// deploy again, but send projectSettings this time
createArgs.projectSettings = settings;
deployStamp = stamp();
createArgs.deployStamp = deployStamp;
deployment = await createDeploy(
client,
now,
contextName,
[sourcePath],
createArgs,
org,
false,
path
);
}
if (deployment instanceof NotDomainOwner) {
output.error(deployment.message);
return 1;
}
if (deployment instanceof Error) {
output.error(
deployment.message ||
'An unexpected error occurred while deploying your project',
undefined,
'https://vercel.link/help',
'Contact Support'
);
return 1;
}
if (deployment.readyState === 'CANCELED') {
output.print('The deployment has been canceled.\n');
return 1;
}
if (deployment.checksConclusion === 'failed') {
const { checks } = await getDeploymentChecks(client, deployment.id);
const counters = new Map<string, number>();
checks.forEach(c => {
counters.set(c.conclusion, (counters.get(c.conclusion) ?? 0) + 1);
});
const counterList = Array.from(counters)
.map(([name, no]) => `${no} ${name}`)
.join(', ');
output.error(`Running Checks: ${counterList}`);
return 1;
}
const deploymentResponse = await getDeploymentByIdOrHost(
client,
contextName,
deployment.id,
'v10'
);
if (
deploymentResponse instanceof DeploymentNotFound ||
deploymentResponse instanceof DeploymentPermissionDenied ||
deploymentResponse instanceof InvalidDeploymentId
) {
output.error(deploymentResponse.message);
return 1;
}
if (deployment === null) {
error('Uploading failed. Please try again.');
return 1;
}
} catch (err) {
debug(`Error: ${err}\n${err.stack}`);
if (err instanceof NotDomainOwner) {
output.error(err.message);
return 1;
}
if (err instanceof DomainNotFound && err.meta && err.meta.domain) {
output.debug(
`The domain ${err.meta.domain} was not found, trying to purchase it`
);
const purchase = await purchaseDomainIfAvailable(
output,
client,
err.meta.domain,
contextName
);
if (purchase === true) {
output.success(`Successfully purchased the domain ${err.meta.domain}!`);
// We exit if the purchase is completed since
// the domain verification can take some time
return 0;
}
if (purchase === false || purchase instanceof UserAborted) {
handleCreateDeployError(output, deployment, localConfig);
return 1;
}
handleCreateDeployError(output, purchase, localConfig);
return 1;
}
if (
err instanceof DomainNotFound ||
err instanceof DomainNotVerified ||
err instanceof NotDomainOwner ||
err instanceof DomainPermissionDenied ||
err instanceof DomainVerificationFailed ||
err instanceof SchemaValidationFailed ||
err instanceof InvalidDomain ||
err instanceof DeploymentNotFound ||
err instanceof BuildsRateLimited ||
err instanceof DeploymentsRateLimited ||
err instanceof AliasDomainConfigured ||
err instanceof MissingBuildScript ||
err instanceof ConflictingFilePath ||
err instanceof ConflictingPathSegment
) {
handleCreateDeployError(output, err, localConfig);
return 1;
}
if (err instanceof BuildError) {
output.error(err.message || 'Build failed');
output.error(
`Check your logs at https://${now.url}/_logs or run ${getCommandName(
`logs ${now.url}`
)}`
);
return 1;
}
if (err.keyword === 'additionalProperties' && err.dataPath === '.scale') {
const { additionalProperty = '' } = err.params || {};
const message = `Invalid DC name for the scale option: ${additionalProperty}`;
error(message);
}
if (err.code === 'size_limit_exceeded') {
const { sizeLimit = 0 } = err;
const message = `File size limit exceeded (${bytes(sizeLimit)})`;
error(message);
return 1;
}
handleError(err);
return 1;
}
return printDeploymentStatus(
output,
client,
deployment,
deployStamp,
!argv['--no-clipboard'],
isFile
);
};
function handleCreateDeployError(
output: Output,
error: Error,
localConfig: VercelConfig
) {
if (error instanceof InvalidDomain) {
output.error(`The domain ${error.meta.domain} is not valid`);
return 1;
}
if (error instanceof DomainVerificationFailed) {
output.error(
`The domain used as a suffix ${chalk.underline(
error.meta.domain
)} is not verified and can't be used as custom suffix.`
);
return 1;
}
if (error instanceof DomainPermissionDenied) {
output.error(
`You don't have permissions to access the domain used as a suffix ${chalk.underline(
error.meta.domain
)}.`
);
return 1;
}
if (error instanceof SchemaValidationFailed) {
const niceError = getPrettyError(error.meta);
const fileName = localConfig[fileNameSymbol] || 'vercel.json';
niceError.message = `Invalid ${fileName} - ${niceError.message}`;
output.prettyError(niceError);
return 1;
}
if (error instanceof TooManyRequests) {
output.error(
`Too many requests detected for ${error.meta.api} API. Try again in ${ms(
error.meta.retryAfter * 1000,
{
long: true,
}
)}.`
);
return 1;
}
if (error instanceof DomainNotVerified) {
output.error(
`The domain used as an alias ${chalk.underline(
error.meta.domain
)} is not verified yet. Please verify it.`
);
return 1;
}
if (error instanceof BuildsRateLimited) {
output.error(error.message);
output.note(
`Run ${getCommandName('upgrade')} to increase your builds limit.`
);
return 1;
}
if (
error instanceof DeploymentNotFound ||
error instanceof NotDomainOwner ||
error instanceof DeploymentsRateLimited ||
error instanceof AliasDomainConfigured ||
error instanceof MissingBuildScript ||
error instanceof ConflictingFilePath ||
error instanceof ConflictingPathSegment
) {
output.error(error.message);
return 1;
}
return error;
}
const addProcessEnv = async (
log: (str: string) => void,
env: typeof process.env
) => {
let val;
for (const key of Object.keys(env)) {
if (typeof env[key] !== 'undefined') {
continue;
}
val = process.env[key];
if (typeof val === 'string') {
log(
`Reading ${chalk.bold(
`"${chalk.bold(key)}"`
)} from your env (as no value was specified)`
);
// Escape value if it begins with @
env[key] = val.replace(/^@/, '\\@');
} else {
throw new Error(
`No value specified for env ${chalk.bold(
`"${chalk.bold(key)}"`
)} and it was not found in your env.`
);
}
}
};
const printDeploymentStatus = async (
output: Output,
client: Client,
{
readyState,
alias: aliasList,
aliasError,
target,
indications,
url: deploymentUrl,
aliasWarning,
}: {
readyState: string;
alias: string[];
aliasError: Error;
target: string;
indications: any;
url: string;
aliasWarning?: {
code: string;
message: string;
link?: string;
action?: string;
};
},
deployStamp: () => string,
isClipboardEnabled: boolean,
isFile: boolean
) => {
indications = indications || [];
const isProdDeployment = target === 'production';
if (readyState !== 'READY') {
output.error(
`Your deployment failed. Please retry later. More: https://err.sh/vercel/deployment-error`
);
return 1;
}
if (aliasError) {
output.warn(
`Failed to assign aliases${
aliasError.message ? `: ${aliasError.message}` : ''
}`
);
} else {
// print preview/production url
let previewUrl: string;
let isWildcard: boolean;
if (!isFile && Array.isArray(aliasList) && aliasList.length > 0) {
const previewUrlInfo = await getPreferredPreviewURL(client, aliasList);
if (previewUrlInfo) {
isWildcard = previewUrlInfo.isWildcard;
previewUrl = previewUrlInfo.previewUrl;
} else {
isWildcard = false;
previewUrl = `https://${deploymentUrl}`;
}
} else {
// fallback to deployment url
isWildcard = false;
previewUrl = `https://${deploymentUrl}`;
}
// copy to clipboard
let isCopiedToClipboard = false;
if (isClipboardEnabled && !isWildcard) {
try {
await copy(previewUrl);
isCopiedToClipboard = true;
} catch (err) {
output.debug(`Error copyind to clipboard: ${err}`);
}
}
output.print(
prependEmoji(
`${isProdDeployment ? 'Production' : 'Preview'}: ${chalk.bold(
previewUrl
)}${
isCopiedToClipboard ? chalk.gray(` [copied to clipboard]`) : ''
} ${deployStamp()}`,
emoji('success')
) + `\n`
);
}
if (aliasWarning?.message) {
indications.push({
type: 'warning',
payload: aliasWarning.message,
link: aliasWarning.link,
action: aliasWarning.action,
});
}
const newline = '\n';
for (let indication of indications) {
const message =
prependEmoji(chalk.dim(indication.payload), emoji(indication.type)) +
newline;
let link = '';
if (indication.link)
link =
chalk.dim(
`${indication.action || 'Learn More'}: ${linkStyle(indication.link)}`
) + newline;
output.print(message + link);
}
};
// Converts `env` Arrays, Strings and Objects into env Objects.
const parseEnv = (env?: string[] | Dictionary<string>) => {
if (!env) {
return {};
}
if (typeof env === 'string') {
// a single `--env` arg comes in as a String
env = [env];
}
if (Array.isArray(env)) {
return env.reduce((o, e) => {
let key;
let value;
const equalsSign = e.indexOf('=');
if (equalsSign === -1) {
key = e;
} else {
key = e.substr(0, equalsSign);
value = e.substr(equalsSign + 1);
}
o[key] = value;
return o;
}, {} as Dictionary<string | undefined>);
}
// assume it's already an Object
return env;
};

View File

@@ -1,808 +0,0 @@
import ms from 'ms';
import bytes from 'bytes';
import { join } from 'path';
import { write as copy } from 'clipboardy';
import chalk from 'chalk';
import { Dictionary, fileNameSymbol, VercelConfig } from '@vercel/client';
import { getPrettyError } from '@vercel/build-utils';
import { handleError } from '../../util/error';
import toHumanPath from '../../util/humanize-path';
import Now from '../../util';
import stamp from '../../util/output/stamp';
import createDeploy from '../../util/deploy/create-deploy';
import getDeploymentByIdOrHost from '../../util/deploy/get-deployment-by-id-or-host';
import parseMeta from '../../util/parse-meta';
import code from '../../util/output/code';
import linkStyle from '../../util/output/link';
import param from '../../util/output/param';
import highlight from '../../util/output/highlight';
import {
BuildsRateLimited,
DeploymentNotFound,
DeploymentPermissionDenied,
InvalidDeploymentId,
DomainNotFound,
DomainNotVerified,
DomainPermissionDenied,
DomainVerificationFailed,
InvalidDomain,
TooManyRequests,
UserAborted,
DeploymentsRateLimited,
AliasDomainConfigured,
MissingBuildScript,
ConflictingFilePath,
ConflictingPathSegment,
BuildError,
NotDomainOwner,
} from '../../util/errors-ts';
import { SchemaValidationFailed } from '../../util/errors';
import purchaseDomainIfAvailable from '../../util/domains/purchase-domain-if-available';
import confirm from '../../util/input/confirm';
import editProjectSettings from '../../util/input/edit-project-settings';
import {
getLinkedProject,
linkFolderToProject,
} from '../../util/projects/link';
import getProjectName from '../../util/get-project-name';
import selectOrg from '../../util/input/select-org';
import inputProject from '../../util/input/input-project';
import { prependEmoji, emoji } from '../../util/emoji';
import { inputRootDirectory } from '../../util/input/input-root-directory';
import validatePaths, {
validateRootDirectory,
} from '../../util/validate-paths';
import { readLocalConfig } from '../../util/config/files';
import { getCommandName } from '../../util/pkg-name';
import { getPreferredPreviewURL } from '../../util/deploy/get-preferred-preview-url';
import { Output } from '../../util/output';
import Client from '../../util/client';
const addProcessEnv = async (
log: (str: string) => void,
env: typeof process.env
) => {
let val;
for (const key of Object.keys(env)) {
if (typeof env[key] !== 'undefined') {
continue;
}
val = process.env[key];
if (typeof val === 'string') {
log(
`Reading ${chalk.bold(
`"${chalk.bold(key)}"`
)} from your env (as no value was specified)`
);
// Escape value if it begins with @
env[key] = val.replace(/^@/, '\\@');
} else {
throw new Error(
`No value specified for env ${chalk.bold(
`"${chalk.bold(key)}"`
)} and it was not found in your env.`
);
}
}
};
const printDeploymentStatus = async (
output: Output,
client: Client,
{
readyState,
alias: aliasList,
aliasError,
target,
indications,
url: deploymentUrl,
aliasWarning,
}: {
readyState: string;
alias: string[];
aliasError: Error;
target: string;
indications: any;
url: string;
aliasWarning?: {
code: string;
message: string;
link?: string;
action?: string;
};
},
deployStamp: () => string,
isClipboardEnabled: boolean,
isFile: boolean
) => {
indications = indications || [];
const isProdDeployment = target === 'production';
if (readyState !== 'READY') {
output.error(
`Your deployment failed. Please retry later. More: https://err.sh/vercel/deployment-error`
);
return 1;
}
if (aliasError) {
output.warn(
`Failed to assign aliases${
aliasError.message ? `: ${aliasError.message}` : ''
}`
);
} else {
// print preview/production url
let previewUrl: string;
let isWildcard: boolean;
if (!isFile && Array.isArray(aliasList) && aliasList.length > 0) {
const previewUrlInfo = await getPreferredPreviewURL(client, aliasList);
if (previewUrlInfo) {
isWildcard = previewUrlInfo.isWildcard;
previewUrl = previewUrlInfo.previewUrl;
} else {
isWildcard = false;
previewUrl = `https://${deploymentUrl}`;
}
} else {
// fallback to deployment url
isWildcard = false;
previewUrl = `https://${deploymentUrl}`;
}
// copy to clipboard
let isCopiedToClipboard = false;
if (isClipboardEnabled && !isWildcard) {
try {
await copy(previewUrl);
isCopiedToClipboard = true;
} catch (err) {
output.debug(`Error copyind to clipboard: ${err}`);
}
}
output.print(
prependEmoji(
`${isProdDeployment ? 'Production' : 'Preview'}: ${chalk.bold(
previewUrl
)}${
isCopiedToClipboard ? chalk.gray(` [copied to clipboard]`) : ''
} ${deployStamp()}`,
emoji('success')
) + `\n`
);
}
if (aliasWarning?.message) {
indications.push({
type: 'warning',
payload: aliasWarning.message,
link: aliasWarning.link,
action: aliasWarning.action,
});
}
const newline = '\n';
for (let indication of indications) {
const message =
prependEmoji(chalk.dim(indication.payload), emoji(indication.type)) +
newline;
let link = '';
if (indication.link)
link =
chalk.dim(
`${indication.action || 'Learn More'}: ${linkStyle(indication.link)}`
) + newline;
output.print(message + link);
}
};
// Converts `env` Arrays, Strings and Objects into env Objects.
const parseEnv = (env?: string[] | Dictionary<string>) => {
if (!env) {
return {};
}
if (typeof env === 'string') {
// a single `--env` arg comes in as a String
env = [env];
}
if (Array.isArray(env)) {
return env.reduce((o, e) => {
let key;
let value;
const equalsSign = e.indexOf('=');
if (equalsSign === -1) {
key = e;
} else {
key = e.substr(0, equalsSign);
value = e.substr(equalsSign + 1);
}
o[key] = value;
return o;
}, {} as Dictionary<string | undefined>);
}
// assume it's already an Object
return env;
};
export default async function main(
client: Client,
paths: string[],
localConfig: VercelConfig | null,
argv: any
) {
const {
apiUrl,
output,
authConfig: { token },
} = client;
const { log, debug, error, warn } = output;
const debugEnabled = argv['--debug'];
const { isTTY } = process.stdout;
const quiet = !isTTY;
// check paths
const pathValidation = await validatePaths(output, paths);
if (!pathValidation.valid) {
return pathValidation.exitCode;
}
const { isFile, path } = pathValidation;
const autoConfirm = argv['--confirm'] || isFile;
// deprecate --name
if (argv['--name']) {
output.print(
`${prependEmoji(
`The ${param(
'--name'
)} option is deprecated (https://vercel.link/name-flag)`,
emoji('warning')
)}\n`
);
}
// retrieve `project` and `org` from .vercel
const link = await getLinkedProject(client, path);
if (link.status === 'error') {
return link.exitCode;
}
let { org, project, status } = link;
let newProjectName = null;
let rootDirectory = project ? project.rootDirectory : null;
let sourceFilesOutsideRootDirectory = true;
if (status === 'not_linked') {
const shouldStartSetup =
autoConfirm ||
(await confirm(
`Set up and deploy ${chalk.cyan(`${toHumanPath(path)}`)}?`,
true
));
if (!shouldStartSetup) {
output.print(`Aborted. Project not set up.\n`);
return 0;
}
try {
org = await selectOrg(
client,
'Which scope do you want to deploy to?',
autoConfirm
);
} catch (err) {
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
output.error(err.message);
return 1;
}
throw err;
}
// We use `localConfig` here to read the name
// even though the `vercel.json` file can change
// afterwards, this is fine since the property
// will be deprecated and can be replaced with
// user input.
const detectedProjectName = getProjectName({
argv,
nowConfig: localConfig || {},
isFile,
paths,
});
const projectOrNewProjectName = await inputProject(
output,
client,
org,
detectedProjectName,
autoConfirm
);
if (typeof projectOrNewProjectName === 'string') {
newProjectName = projectOrNewProjectName;
rootDirectory = await inputRootDirectory(path, output, autoConfirm);
} else {
project = projectOrNewProjectName;
rootDirectory = project.rootDirectory;
sourceFilesOutsideRootDirectory = project.sourceFilesOutsideRootDirectory;
// we can already link the project
await linkFolderToProject(
output,
path,
{
projectId: project.id,
orgId: org.id,
},
project.name,
org.slug
);
status = 'linked';
}
}
// At this point `org` should be populated
if (!org) {
throw new Error(`"org" is not defined`);
}
// Set the `contextName` and `currentTeam` as specified by the
// Project Settings, so that API calls happen with the proper scope
const contextName = org.slug;
client.config.currentTeam = org.type === 'team' ? org.id : undefined;
// if we have `sourceFilesOutsideRootDirectory` set to `true`, we use the current path
// and upload the entire directory.
const sourcePath =
rootDirectory && !sourceFilesOutsideRootDirectory
? join(path, rootDirectory)
: path;
if (
rootDirectory &&
(await validateRootDirectory(
output,
path,
sourcePath,
project
? `To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`
: ''
)) === false
) {
return 1;
}
// If Root Directory is used we'll try to read the config
// from there instead and use it if it exists.
if (rootDirectory) {
const rootDirectoryConfig = readLocalConfig(join(path, rootDirectory));
if (rootDirectoryConfig) {
debug(`Read local config from root directory (${rootDirectory})`);
localConfig = rootDirectoryConfig;
} else if (localConfig) {
output.print(
`${prependEmoji(
`The ${highlight(
localConfig[fileNameSymbol]!
)} file should be inside of the provided root directory.`,
emoji('warning')
)}\n`
);
}
}
localConfig = localConfig || {};
if (localConfig.name) {
output.print(
`${prependEmoji(
`The ${code('name')} property in ${highlight(
localConfig[fileNameSymbol]!
)} is deprecated (https://vercel.link/name-prop)`,
emoji('warning')
)}\n`
);
}
// build `env`
const isObject = (item: any) =>
Object.prototype.toString.call(item) === '[object Object]';
// This validation needs to happen on the client side because
// the data is merged with other data before it is passed to the API (which
// also does schema validation).
if (typeof localConfig.env !== 'undefined' && !isObject(localConfig.env)) {
error(
`The ${code('env')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
if (typeof localConfig.build !== 'undefined') {
if (!isObject(localConfig.build)) {
error(
`The ${code('build')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
if (
typeof localConfig.build.env !== 'undefined' &&
!isObject(localConfig.build.env)
) {
error(
`The ${code('build.env')} property in ${highlight(
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
}
}
// build `meta`
const meta = Object.assign(
{},
parseMeta(localConfig.meta),
parseMeta(argv['--meta'])
);
// Merge dotenv config, `env` from vercel.json, and `--env` / `-e` arguments
const deploymentEnv = Object.assign(
{},
parseEnv(localConfig.env),
parseEnv(argv['--env'])
);
// Merge build env out of `build.env` from vercel.json, and `--build-env` args
const deploymentBuildEnv = Object.assign(
{},
parseEnv(localConfig.build && localConfig.build.env),
parseEnv(argv['--build-env'])
);
// If there's any undefined values, then inherit them from this process
try {
await addProcessEnv(log, deploymentEnv);
await addProcessEnv(log, deploymentBuildEnv);
} catch (err) {
error(err.message);
return 1;
}
// build `regions`
const regionFlag = (argv['--regions'] || '')
.split(',')
.map((s: string) => s.trim())
.filter(Boolean);
const regions = regionFlag.length > 0 ? regionFlag : localConfig.regions;
// build `target`
let target;
if (argv['--target']) {
const deprecatedTarget = argv['--target'];
if (!['staging', 'production'].includes(deprecatedTarget)) {
error(
`The specified ${param('--target')} ${code(
deprecatedTarget
)} is not valid`
);
return 1;
}
if (deprecatedTarget === 'production') {
warn(
'We recommend using the much shorter `--prod` option instead of `--target production` (deprecated)'
);
}
output.debug(`Setting target to ${deprecatedTarget}`);
target = deprecatedTarget;
} else if (argv['--prod']) {
output.debug('Setting target to production');
target = 'production';
}
const currentTeam = org?.type === 'team' ? org.id : undefined;
const now = new Now({ apiUrl, token, debug: debugEnabled, currentTeam });
let deployStamp = stamp();
let deployment = null;
try {
const createArgs: any = {
name: project ? project.name : newProjectName,
env: deploymentEnv,
build: { env: deploymentBuildEnv },
forceNew: argv['--force'],
withCache: argv['--with-cache'],
quiet,
wantsPublic: argv['--public'] || localConfig.public,
isFile,
type: null,
nowConfig: localConfig,
regions,
meta,
deployStamp,
target,
skipAutoDetectionConfirmation: autoConfirm,
};
if (!localConfig.builds || localConfig.builds.length === 0) {
// Only add projectSettings for zero config deployments
createArgs.projectSettings = { sourceFilesOutsideRootDirectory };
}
deployment = await createDeploy(
client,
now,
contextName,
[sourcePath],
createArgs,
org,
!project && !isFile,
path
);
if (deployment.code === 'missing_project_settings') {
let { projectSettings, framework } = deployment;
if (rootDirectory) {
projectSettings.rootDirectory = rootDirectory;
}
if (typeof sourceFilesOutsideRootDirectory !== 'undefined') {
projectSettings.sourceFilesOutsideRootDirectory =
sourceFilesOutsideRootDirectory;
}
const settings = await editProjectSettings(
output,
projectSettings,
framework
);
// deploy again, but send projectSettings this time
createArgs.projectSettings = settings;
deployStamp = stamp();
createArgs.deployStamp = deployStamp;
deployment = await createDeploy(
client,
now,
contextName,
[sourcePath],
createArgs,
org,
false,
path
);
}
if (deployment instanceof NotDomainOwner) {
output.error(deployment.message);
return 1;
}
if (deployment instanceof Error) {
output.error(
deployment.message ||
'An unexpected error occurred while deploying your project',
undefined,
'https://vercel.link/help',
'Contact Support'
);
return 1;
}
if (deployment.readyState === 'CANCELED') {
output.print('The deployment has been canceled.\n');
return 1;
}
const deploymentResponse = await getDeploymentByIdOrHost(
client,
contextName,
deployment.id,
'v10'
);
if (
deploymentResponse instanceof DeploymentNotFound ||
deploymentResponse instanceof DeploymentPermissionDenied ||
deploymentResponse instanceof InvalidDeploymentId
) {
output.error(deploymentResponse.message);
return 1;
}
if (deployment === null) {
error('Uploading failed. Please try again.');
return 1;
}
} catch (err) {
debug(`Error: ${err}\n${err.stack}`);
if (err instanceof NotDomainOwner) {
output.error(err.message);
return 1;
}
if (err instanceof DomainNotFound && err.meta && err.meta.domain) {
output.debug(
`The domain ${err.meta.domain} was not found, trying to purchase it`
);
const purchase = await purchaseDomainIfAvailable(
output,
client,
err.meta.domain,
contextName
);
if (purchase === true) {
output.success(`Successfully purchased the domain ${err.meta.domain}!`);
// We exit if the purchase is completed since
// the domain verification can take some time
return 0;
}
if (purchase === false || purchase instanceof UserAborted) {
handleCreateDeployError(output, deployment, localConfig);
return 1;
}
handleCreateDeployError(output, purchase, localConfig);
return 1;
}
if (
err instanceof DomainNotFound ||
err instanceof DomainNotVerified ||
err instanceof NotDomainOwner ||
err instanceof DomainPermissionDenied ||
err instanceof DomainVerificationFailed ||
err instanceof SchemaValidationFailed ||
err instanceof InvalidDomain ||
err instanceof DeploymentNotFound ||
err instanceof BuildsRateLimited ||
err instanceof DeploymentsRateLimited ||
err instanceof AliasDomainConfigured ||
err instanceof MissingBuildScript ||
err instanceof ConflictingFilePath ||
err instanceof ConflictingPathSegment
) {
handleCreateDeployError(output, err, localConfig);
return 1;
}
if (err instanceof BuildError) {
output.error(err.message || 'Build failed');
output.error(
`Check your logs at https://${now.url}/_logs or run ${getCommandName(
`logs ${now.url}`
)}`
);
return 1;
}
if (err.keyword === 'additionalProperties' && err.dataPath === '.scale') {
const { additionalProperty = '' } = err.params || {};
const message = `Invalid DC name for the scale option: ${additionalProperty}`;
error(message);
}
if (err.code === 'size_limit_exceeded') {
const { sizeLimit = 0 } = err;
const message = `File size limit exceeded (${bytes(sizeLimit)})`;
error(message);
return 1;
}
handleError(err);
return 1;
}
return printDeploymentStatus(
output,
client,
deployment,
deployStamp,
!argv['--no-clipboard'],
isFile
);
}
function handleCreateDeployError(
output: Output,
error: Error,
localConfig: VercelConfig
) {
if (error instanceof InvalidDomain) {
output.error(`The domain ${error.meta.domain} is not valid`);
return 1;
}
if (error instanceof DomainVerificationFailed) {
output.error(
`The domain used as a suffix ${chalk.underline(
error.meta.domain
)} is not verified and can't be used as custom suffix.`
);
return 1;
}
if (error instanceof DomainPermissionDenied) {
output.error(
`You don't have permissions to access the domain used as a suffix ${chalk.underline(
error.meta.domain
)}.`
);
return 1;
}
if (error instanceof SchemaValidationFailed) {
const niceError = getPrettyError(error.meta);
const fileName = localConfig[fileNameSymbol] || 'vercel.json';
niceError.message = `Invalid ${fileName} - ${niceError.message}`;
output.prettyError(niceError);
return 1;
}
if (error instanceof TooManyRequests) {
output.error(
`Too many requests detected for ${error.meta.api} API. Try again in ${ms(
error.meta.retryAfter * 1000,
{
long: true,
}
)}.`
);
return 1;
}
if (error instanceof DomainNotVerified) {
output.error(
`The domain used as an alias ${chalk.underline(
error.meta.domain
)} is not verified yet. Please verify it.`
);
return 1;
}
if (error instanceof BuildsRateLimited) {
output.error(error.message);
output.note(
`Run ${getCommandName('upgrade')} to increase your builds limit.`
);
return 1;
}
if (
error instanceof DeploymentNotFound ||
error instanceof NotDomainOwner ||
error instanceof DeploymentsRateLimited ||
error instanceof AliasDomainConfigured ||
error instanceof MissingBuildScript ||
error instanceof ConflictingFilePath ||
error instanceof ConflictingPathSegment
) {
output.error(error.message);
return 1;
}
return error;
}

View File

@@ -6,15 +6,13 @@ import { ProjectEnvVariable } from '../../types';
import Client from '../../util/client';
import { getLinkedProject } from '../../util/projects/link';
import { getFrameworks } from '../../util/get-frameworks';
import { isSettingValue } from '../../util/is-setting-value';
import { ProjectSettings } from '../../types';
import getDecryptedEnvRecords from '../../util/get-decrypted-env-records';
import setupAndLink from '../../util/link/setup-and-link';
import getSystemEnvValues from '../../util/env/get-system-env-values';
type Options = {
'--debug'?: boolean;
'--listen'?: string;
'--listen': string;
'--confirm': boolean;
};
@@ -27,7 +25,6 @@ export default async function dev(
const [dir = '.'] = args;
let cwd = resolve(dir);
const listen = parseListen(opts['--listen'] || '3000');
const debug = opts['--debug'] || false;
// retrieve dev command
let [link, frameworks] = await Promise.all([
@@ -36,17 +33,11 @@ export default async function dev(
]);
if (link.status === 'not_linked' && !process.env.__VERCEL_SKIP_DEV_CMD) {
const autoConfirm = opts['--confirm'] || false;
const forceDelete = false;
link = await setupAndLink(
client,
cwd,
forceDelete,
autoConfirm,
'link',
'Set up and develop'
);
link = await setupAndLink(client, cwd, {
autoConfirm: opts['--confirm'],
successEmoji: 'link',
setupMsg: 'Set up and develop',
});
if (link.status === 'not_linked') {
// User aborted project linking questions
@@ -79,9 +70,9 @@ export default async function dev(
frameworkSlug = framework.slug;
}
const defaults = framework.settings.devCommand;
if (isSettingValue(defaults)) {
devCommand = defaults.value;
const defaults = framework.settings.devCommand.value;
if (defaults) {
devCommand = defaults;
}
}
}
@@ -100,7 +91,6 @@ export default async function dev(
const devServer = new DevServer(cwd, {
output,
debug,
devCommand,
frameworkSlug,
projectSettings,

View File

@@ -48,6 +48,22 @@ const help = () => {
};
export default async function main(client: Client) {
if (process.env.__VERCEL_DEV_RUNNING) {
client.output.error(
`${cmd(
`${getPkgName()} dev`
)} must not recursively invoke itself. Check the Development Command in the Project Settings or the ${cmd(
'dev'
)} script in ${cmd('package.json')}`
);
client.output.error(
`Learn More: https://vercel.link/recursive-invocation-of-commands`
);
return 1;
} else {
process.env.__VERCEL_DEV_RUNNING = '1';
}
let argv;
let args;
const { output } = client;
@@ -90,22 +106,21 @@ export default async function main(client: Client) {
if (pkg) {
const { scripts } = pkg as PackageJson;
if (scripts && scripts.dev && /\bnow\b\W+\bdev\b/.test(scripts.dev)) {
output.error(
`The ${cmd('dev')} script in ${cmd(
'package.json'
)} must not contain ${cmd('now dev')}`
if (
scripts &&
scripts.dev &&
/\b(now|vercel)\b\W+\bdev\b/.test(scripts.dev)
) {
client.output.error(
`${cmd(
`${getPkgName()} dev`
)} must not recursively invoke itself. Check the Development Command in the Project Settings or the ${cmd(
'dev'
)} script in ${cmd('package.json')}`
);
output.error(`Learn More: http://err.sh/vercel/now-dev-as-dev-script`);
return 1;
}
if (scripts && scripts.dev && /\bvercel\b\W+\bdev\b/.test(scripts.dev)) {
output.error(
`The ${cmd('dev')} script in ${cmd(
'package.json'
)} must not contain ${cmd('vercel dev')}`
client.output.error(
`Learn More: https://vercel.link/recursive-invocation-of-commands`
);
output.error(`Learn More: http://err.sh/vercel/now-dev-as-dev-script`);
return 1;
}
}
@@ -121,7 +136,7 @@ export default async function main(client: Client) {
} catch (err) {
if (err.code === 'ENOTFOUND') {
// Error message will look like the following:
// "request to https://api.vercel.com/www/user failed, reason: getaddrinfo ENOTFOUND api.vercel.com"
// "request to https://api.vercel.com/v2/user failed, reason: getaddrinfo ENOTFOUND api.vercel.com"
const matches = /getaddrinfo ENOTFOUND (.*)$/.exec(err.message || '');
if (matches && matches[1]) {
const hostname = matches[1];

View File

@@ -5,7 +5,6 @@ import { User, Team } from '../../types';
import * as ERRORS from '../../util/errors-ts';
import Client from '../../util/client';
import getScope from '../../util/get-scope';
import withSpinner from '../../util/with-spinner';
import moveOutDomain from '../../util/domains/move-out-domain';
import isRootDomain from '../../util/is-root-domain';
import textInput from '../../util/input/text';
@@ -13,7 +12,7 @@ import param from '../../util/output/param';
import getDomainAliases from '../../util/alias/get-domain-aliases';
import getDomainByName from '../../util/domains/get-domain-by-name';
import promptBool from '../../util/input/prompt-bool';
import getTeams from '../../util/get-teams';
import getTeams from '../../util/teams/get-teams';
import { getCommandName } from '../../util/pkg-name';
type Options = {
@@ -106,9 +105,14 @@ export default async function move(
}
const context = contextName;
const moveTokenResult = await withSpinner('Moving', () => {
return moveOutDomain(client, context, domainName, matchId || destination);
});
output.spinner('Moving');
const moveTokenResult = await moveOutDomain(
client,
context,
domainName,
matchId || destination
);
if (moveTokenResult instanceof ERRORS.DomainMoveConflict) {
const { suffix, pendingAsyncPurchase } = moveTokenResult.meta;
if (suffix) {
@@ -190,8 +194,8 @@ async function findDestinationMatch(
user: User,
teams: Team[]
) {
if (user.uid === destination || user.username === destination) {
return user.uid;
if (user.id === destination || user.username === destination) {
return user.id;
}
for (const team of teams) {

Some files were not shown because too many files have changed in this diff Show More