Compare commits

..

56 Commits

Author SHA1 Message Date
JJ Kasper
cf827a8b91 Publish Canary
- @vercel/build-utils@2.11.2-canary.2
 - vercel@23.0.2-canary.3
 - @vercel/client@10.1.2-canary.2
 - @vercel/frameworks@0.4.2-canary.1
 - @vercel/go@1.2.3-canary.0
 - @vercel/node-bridge@2.0.1-canary.1
 - @vercel/node@1.11.2-canary.3
 - @vercel/python@2.0.5-canary.0
 - @vercel/routing-utils@1.11.3-canary.0
 - @vercel/ruby@1.2.7-canary.0
2021-07-06 22:43:13 -05:00
Steven
bed83e829c [routing-utils] Fix rewrites with query string array in destination (#6441)
Related to https://github.com/vercel/next.js/pull/26619
2021-07-06 22:24:40 +00:00
Markoz Peña
0f0ee4e845 [cli] Convert vc whoami to TypeScript (#6435) 2021-07-06 15:10:00 -04:00
Steven
2d70c6c811 [test] Update publish-canary script (#6432) 2021-07-02 11:54:53 -04:00
Nathan Rajlich
887309f0a5 [cli] Convert vc deploy to TypeScript (#6413)
This is a continuation of https://github.com/vercel/vercel/pull/6382 (thank you @markozxuu!) with merge conflicts addressed and pushed to a local branch, so that CI tests run.
2021-06-30 18:26:29 +00:00
Nathan Rajlich
8a7657c80b [cli] Use output.spinner() instead of wait() (#6414) 2021-06-29 18:48:50 -07:00
Nathan Rajlich
279d0bf988 [cli] Set current scope to proper team after SSO login (#6415) 2021-06-29 16:42:40 -07:00
Nathan Rajlich
d2b31d03da [cli] Use Client instead of LoginParams for login (#6409)
* [cli] Use `Client` instead of `LoginParams`

* Use `client.fetch()`

* Fix email verify

* Remove redundant "user-agent" header

* Fix test
2021-06-29 01:48:36 -07:00
Nathan Rajlich
16acf906fc Update to TypeScript 4.3.4 (#6397)
Also updates eslint and related packages to work with the new TypeScript version.
2021-06-25 23:45:53 +00:00
Nathan Rajlich
0127d17703 Fix Ruby E2E tests (#6401)
Currently the `06-rails` test is failing at build time with:

```
16:27:09.550  	    'Your bundle is locked to mimemagic (0.3.3) from rubygems repository\n' +
16:27:09.550  	    'https://rubygems.org/ or installed locally, but that version can no longer be\n' +
16:27:09.550  	    'found in that source. That means the author of mimemagic (0.3.3) has removed it.\n' +
16:27:09.550  	    "You'll need to update your bundle to a version other than mimemagic (0.3.3) that\n" +
16:27:09.550  	    "hasn't been removed in order to install.",
```

So I ran `bundler update` in the "06-rails" Ruby test fixture to update the deps in the Gemfile.lock file.
2021-06-25 14:41:52 -07:00
Steven
0bfc2a3693 Publish Canary
- @vercel/build-utils@2.11.2-canary.1
 - vercel@23.0.2-canary.2
 - @vercel/client@10.1.2-canary.1
 - @vercel/frameworks@0.4.2-canary.0
 - @vercel/node@1.11.2-canary.2
2021-06-25 11:22:56 -04:00
Steven
b9809b140c [node] Fix ESM when package.json type: module (#6399)
* [node] Fix ESM when package.json `type: module`

* Fix cjs and add test fixture
2021-06-25 11:14:05 -04:00
Steven
faaccc1f9f [frameworks] Add missing cachePattern to Next.js (#6396) 2021-06-24 15:31:16 -04:00
Nathan Rajlich
4b61f1dd61 [cli] Set proper currentTeam in vc deploy (#6394)
Fixes an edge case bug when the user has a current scope that is
different than the owner of the project that is being deployed.

When this was the case, the API call to get the certs for a domain at
the end of the `vc deploy` command was using the incorrect `teamId`,
potentially causing a 403 error (when the current auth token does not
have access to the selected scope).
2021-06-24 12:06:27 -07:00
Steven
cdd417455f [frameworks] Add cachePattern to API response (#6395) 2021-06-24 14:44:38 -04:00
Leonardo Merlin
fe671f56c5 chore(examples): update nuxtjs (#6383)
* chore: update nuxtjs example

* fix: remove @nuxtjs/pwa

Co-authored-by: Leonardo Merlin <lmerlin@schubergphilis.com>
2021-06-23 19:19:04 -07:00
Nathan Rajlich
ddf9e6cf3f [cli] Make vc deploy not load current "scope" (#6388)
`vc deploy` doesn't care about the current "scope" that the CLI has selected, since it uses the `.vercel` directory to determine the ownerId and projectId.

Therefore, it should not be fetching the team details of the selected scope during `vc deploy`, since it's possible that the token might not have access to the current scope and returns a 403, even though that API call is unnecessary for the `vc deploy` command to complete.
2021-06-23 12:32:43 -07:00
Steven
13b03c6abd Publish Canary
- @vercel/build-utils@2.11.2-canary.0
 - vercel@23.0.2-canary.1
 - @vercel/client@10.1.2-canary.0
 - @vercel/node@1.11.2-canary.1
2021-06-23 10:54:17 -04:00
Steven
7dd4c629ad [node] Add support for ESM to vc dev (#6385)
Follow up to #6121
2021-06-23 14:48:47 +00:00
Nathan Rajlich
81b3d7f5f1 [cli] Fix vc login hanging for a few seconds before exiting (#6387)
Closing keep-alive HTTP connections was causing the `server.close()` call
to take a few seconds before completing, so set the `Connection: close`
response header in order to make the connections close immediately,
so that `server.close()` is fast.
2021-06-22 20:57:15 -07:00
Steven
3566c32209 [build-utils] Add support for .mjs with zero config (#6386)
Follow up to #6121
2021-06-23 02:21:16 +00:00
Nathan Rajlich
267ca7b379 [cli] Print timestamp for each line for multi-line log entries (#6384) 2021-06-22 16:46:03 -07:00
Steven
7b9d9954b8 Publish Canary
- vercel@23.0.2-canary.0
 - @vercel/node-bridge@2.0.1-canary.0
 - @vercel/node@1.11.2-canary.0
2021-06-22 15:46:21 -04:00
Steven
79675db241 [node][node-bridge] Add support for ESM (#6121) 2021-06-22 15:44:30 -04:00
Nathan Rajlich
3ac8a3f67f [cli] Make vercel dev command exit quickly (#6365)
Considering that it's a development environment, it's not important to wait for ongoing HTTP request connections to complete. Sometimes it takes a long time for all the shutdown operations to complete, which makes the command feel sluggish. So let's just `process.exit()` and exit quickly.
2021-06-18 23:33:37 +00:00
Nathan Rajlich
2f19949133 [cli] Finish executing the original command after login with no credentials (#6364) 2021-06-18 13:10:30 -07:00
Paco
85fd2aed7e Update Next.js example favicon (#6367) 2021-06-18 12:35:01 -07:00
Steven
e659eecf48 Publish Stable
- @vercel/build-utils@2.11.1
 - vercel@23.0.1
 - @vercel/client@10.1.1
 - @vercel/frameworks@0.4.1
 - @vercel/node@1.11.1
 - @vercel/python@2.0.4
 - @vercel/routing-utils@1.11.2
2021-06-15 17:29:53 -04:00
Steven
b428f7ff83 Publish Canary
- vercel@23.0.1-canary.4
2021-06-15 16:37:28 -04:00
Nathan Rajlich
5eb133283d Remove utils/go (#6362)
This code now lives in its own repository, so the code in this repo is not being used.

https://github.com/vercel/go-bridge
2021-06-15 12:49:18 +00:00
Nathan Rajlich
646c29600e [cgi] Remove @vercel/cgi Runtime (#6361)
This Runtime is very old, outdated, unmaintained, and has never been documented.

Additionally, it no longer compiles with the latest version of Go. So
rather than fixing it, let's just remove it since we don't want to
invest any more time into it.
2021-06-14 20:49:05 -07:00
Nathan Rajlich
469eb4315d [cli] Update "open" to v8.2.0 (#6348)
Fixes an issue where the bundled `xdg-open` script would not be used.
2021-06-10 19:14:57 -07:00
JJ Kasper
6dc54d0d64 Publish Canary
- @vercel/build-utils@2.11.1-canary.1
 - vercel@23.0.1-canary.3
 - @vercel/client@10.1.1-canary.1
 - @vercel/frameworks@0.4.1-canary.1
 - @vercel/routing-utils@1.11.2-canary.1
2021-06-08 11:38:01 -05:00
JJ Kasper
adc84d5148 Fix check: true beforeFiles order (#6337) 2021-06-08 11:35:31 -05:00
Nathan Rajlich
88642b1ce8 [cli] Print login URL to terminal (#6336)
In some cases (i.e. when SSH'd to a remote machine) the `open` command will not work reliably. So we need to print the URL to the user as a fallback for those cases when the web browser is not automatically opened.

This also moves where `tokenName` is specified to be in the "verify" endpoint, so that it does not need to be part of the URL that gets printed to the user.

<img width="738" alt="Screen Shot 2021-06-07 at 2 12 47 PM" src="https://user-images.githubusercontent.com/71256/121089239-b5452d00-c79b-11eb-85b2-0e45b817dff0.png">
2021-06-07 22:13:58 +00:00
Steven
4b8d207533 [cli] Warn when vercel.json uses has (#6327) 2021-06-07 14:45:36 -04:00
Steven
36fe5cc4d1 [test] Fix corrupt bmp test (#6328) 2021-06-07 09:31:51 -04:00
JJ Kasper
370b0dbed2 Publish Canary
- vercel@23.0.1-canary.2
 - @vercel/node@1.11.1-canary.0
2021-06-06 15:24:50 -05:00
JJ Kasper
cc7a82fb0a [node] Update nft to 0.13.1 (#6333) 2021-06-06 16:22:56 -04:00
Markoz Peña
6eea26c39e [cli] Convert vc alias to TS (#6325)
* refactor: Remove unncessary file

* feat(cli/alias): Migration to TS

* refactor(cli/alias): Add a line break

* refactor(cli/alias): Remove unnecesary code

* feat(cli): Add `Paginationoptions` type to `pagination`

* feat(cli/commands): Rewrite th `alias ls` command to TS

* refactor: Remove unncessary code

* feat: Create helper function for `getSafeAlias`

* refactor: Remove unnecessary code

* feat: Remove parameter generic, "null" for the fetch

* feat(cli/alias): Rewritten in full TS

* feat: Add Partial to opts

* refactor: Remove comment @ts-ignore

* feat: Add Partial to opts

* feat: Only should be return `alias.uid`

* refactor: Remove `Alias` type from of the parameter `id`

* refactor: Remove destructuring from alias object

* refactor: Remove unnecessary code

* feat: Rename `created` property to `createdAt` of number type

* refactor: Move getSafeAlias function in the same file

* refactor: Simplifying code

* refactor: Intentation did not affect diff on git

* Add null back to type

Co-authored-by: Steven <steven@ceriously.com>
2021-06-04 16:43:39 -04:00
Nathan Rajlich
b8bfae7840 [cli] Fix vc logout command when using Team scope (#6322)
Fixes logout command not working when switched to a Team scope:

```
$ vc login
$ vc switch $some_team
$ vc logout
Failed during logout
```
2021-06-04 19:48:03 +00:00
Nathan Rajlich
dc6a0a1cbb [cli] Upgrade token scopes in vc switch command (#6323)
Pass the `Authorization` request header to the verify endpoint so that the current auth token will be upgraded with the new scope.

[ch22273]
2021-06-04 18:33:49 +00:00
Steven
a6807c9d21 Publish Canary
- vercel@23.0.1-canary.1
 - @vercel/python@2.0.4-canary.0
2021-06-01 14:35:09 -04:00
Steven
c628090d08 [cli] Fix vc projects rm race condition (#6306)
The call to `GET /projects/info` is used to check existence but it can cause a race condition if the project was removed before the `DELETE /v2/projects` is called.

Instead, we rely on the response from `DELETE /v2/projects` to determine if the project exists or not.

This will also allow us to remove a legacy API endpoint in the future (see related API PR)
2021-06-01 18:31:20 +00:00
Hydrophobefireman
4e0b291ed1 [python] Remove imports from werkzeug._compat (#6283) 2021-06-01 09:15:06 -04:00
JJ Kasper
ee0bc9b0c8 Publish Canary
- @vercel/build-utils@2.11.1-canary.0
 - vercel@23.0.1-canary.0
 - @vercel/client@10.1.1-canary.0
 - @vercel/frameworks@0.4.1-canary.0
 - @vercel/routing-utils@1.11.2-canary.0
2021-05-26 13:44:39 -05:00
JJ Kasper
e516c1f49f Ensure beforeFiles rewrites come after redirects when continuing (#6289) 2021-05-26 12:50:51 -05:00
JJ Kasper
01f53f36fc [routing-utils] Ensure header key value casing is normalized (#6284)
This ensures we normalize header `key` values in `has` items to be lower-case as the proxy currently only matches against the lower-case variant. Updated superstatic tests to ensure the header key is normalized correctly. 

### Related Issues

[related thread](https://vercel.slack.com/archives/C01N3RWTE5V/p1621937306006400)

### 📋 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-05-25 22:46:28 +00:00
Nathan Rajlich
f2d396caae Publish Stable
- @vercel/build-utils@2.11.0
 - vercel@23.0.0
 - @vercel/client@10.1.0
 - @vercel/frameworks@0.4.0
 - @vercel/node@1.11.0
 - @vercel/python@2.0.3
 - @vercel/routing-utils@1.11.1
2021-05-25 14:56:11 -07:00
Matheus Fernandes
001f2f60b8 Use proper Apache License format (#6189)
The existing LICENSE file was missing the Appendix, and also
used weird formatting. Now it's an exact copy of the original:

https://www.apache.org/licenses/LICENSE-2.0.txt.
2021-05-25 13:27:32 -07:00
Nathan Rajlich
78ca930287 [cli] Show user's name in vc switch command (#6288)
This more closely matches the Team picker on vercel.com.

Will still show "email" if no "name" is defined.
2021-05-25 13:18:14 -07:00
Nathan Rajlich
b03e18df12 Publish Canary
- vercel@22.0.2-canary.7
 - @vercel/python@2.0.3-canary.0
2021-05-25 11:07:16 -07:00
Nathan Rajlich
3a6b8b072c [cli] Reauthenticate scopes with limited access in vc switch (#6280)
In the `vc switch` command, if your current access token results in
"limited" Team information being returned, then show a lock emoji
next to the team/user name in the select input.

When a locked scope is selected, then pre-emptively prompt the
user to re-authenticate using a valid login method in relation to
the desired scope.

https://user-images.githubusercontent.com/71256/119441172-87abae80-bcda-11eb-801a-cb6837bae353.mov

[ch21964]
2021-05-25 11:03:06 -07:00
Steven
d480cd6bbd [cli] Bump codecov to 3.8.2 (#6279)
Closes #5814
2021-05-24 23:16:02 +00:00
Nathan Rajlich
181b624bf4 [cli] Add SAML reauthentication logic when using different scope (#6263)
When the API returns a SAML error, then show the proper reauthentication prompt depending on the scope being requested:

Team with SAML enforced, shows only SSO login option:

<img width="476" alt="Screen Shot 2021-05-24 at 1 50 29 PM" src="https://user-images.githubusercontent.com/71256/119406131-31694c00-bc97-11eb-858a-52e5fe7052d1.png">

Team with SAML enabled, but not enforced, prompts with all login methods:

<img width="352" alt="Screen Shot 2021-05-24 at 1 50 36 PM" src="https://user-images.githubusercontent.com/71256/119406134-3201e280-bc97-11eb-9166-60fbfec47ee0.png">

Team without SAML enabled, or User scope, shows prompt with SSO option removed:

<img width="366" alt="Screen Shot 2021-05-24 at 1 50 44 PM" src="https://user-images.githubusercontent.com/71256/119406137-3201e280-bc97-11eb-8c5c-b88eb9983500.png">

[ch21964]
2021-05-24 15:16:24 -07:00
Nathan Rajlich
200495e4ce [cli] Use ts-eager to execute build script (#6278)
* [cli] Use `ts-eager` to execute build script

* Use `node -r ts-eager/register` to workaround Windows issue
2021-05-24 18:14:55 -04:00
144 changed files with 3686 additions and 3680 deletions

View File

@@ -1,14 +1,7 @@
node_modules
dist
examples
# gatsby-plugin-now
packages/gatsby-plugin-now/test/fixtures
# build-utils
packages/build-utils/test/fixtures
# cli
packages/cli/@types
packages/cli/download
packages/cli/dist
@@ -17,24 +10,9 @@ packages/cli/test/dev/fixtures
packages/cli/bin
packages/cli/link
packages/cli/src/util/dev/templates/*.ts
# client
packages/client/tests/fixtures
packages/client/lib
# next
packages/next/test/fixtures
# node
packages/node/src/bridge.ts
packages/node/test/fixtures
# node-bridge
packages/node-bridge/bridge.*
# static-build
packages/static-build/test/fixtures
packages/static-build/test/build-fixtures
# redwood
packages/redwood/test/fixtures
packages/node-bridge/bridge.js
packages/node-bridge/launcher.js

332
LICENSE
View File

@@ -1,190 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
1. Definitions.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
1. Definitions.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
END OF TERMS AND CONDITIONS
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
Copyright 2017 Vercel, Inc.
END OF TERMS AND CONDITIONS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
APPENDIX: How to apply the Apache License to your work.
https://www.apache.org/licenses/LICENSE-2.0
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright 2017 Vercel, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -14,7 +14,6 @@ const frameworks = (_frameworks as Framework[])
sort: undefined,
dependency: undefined,
defaultRoutes: undefined,
cachePattern: undefined,
devCommand: undefined,
buildCommand: undefined,
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -80,11 +80,15 @@ dist
# IDE / Editor
.idea
.editorconfig
# Service worker
sw.*
# Mac OSX
# macOS
.DS_Store
# Vim swap files
*.swp
# Vercel
.vercel

View File

@@ -1 +1,4 @@
README.md
.nuxt
node_modules
*.log

View File

@@ -8,7 +8,7 @@ Deploy your own Nuxt.js project with Vercel.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/vercel/vercel/tree/main/examples/nuxtjs)
_Live Example: https://nuxtjs.now-examples.now.sh_
_Live Example: https://nuxtjs.now-examples.vercel.app/_
### How We Created This Example
@@ -17,5 +17,3 @@ To get started with Nuxt.js deployed with Vercel, you can use the [Create-Nuxt-A
```shell
$ npx create-nuxt-app my-app
```
> The only change made is to amend the output directory in `nuxt.config.js` to `"/public"`.

View File

@@ -1,44 +1,37 @@
export default {
mode: 'spa',
/*
** Headers of the page
*/
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: process.env.npm_package_name || '',
title: 'nuxtjs',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || '',
content: 'My astonishing Nuxt.js project',
},
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
// Global CSS: https://go.nuxtjs.dev/config-css
css: [],
/*
** Plugins to load before mounting the App
*/
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [],
/*
** Nuxt.js modules
*/
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [],
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {}
};

View File

@@ -10,9 +10,8 @@
"start": "nuxt start"
},
"dependencies": {
"nuxt": "^2.0.0"
"core-js": "^3.15.0",
"nuxt": "^2.15.7"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
"devDependencies": {}
}

View File

@@ -12,6 +12,7 @@
<a
href="https://nuxtjs.org/"
target="_blank"
rel="noopener"
class="button--green"
>
Documentation
@@ -19,6 +20,7 @@
<a
href="https://github.com/nuxt/nuxt.js"
target="_blank"
rel="noopener"
class="button--grey"
>
GitHub

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@
"name": "vercel-monorepo",
"version": "0.0.0",
"private": true,
"license": "MIT",
"license": "Apache-2.0",
"workspaces": {
"packages": [
"packages/*"
@@ -15,27 +15,27 @@
"lerna": "3.16.4"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "2.0.0",
"@typescript-eslint/parser": "2.0.0",
"@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",
"eslint": "6.2.2",
"eslint-config-prettier": "6.1.0",
"eslint-plugin-jest": "23.8.2",
"eslint": "7.29.0",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-jest": "24.3.6",
"husky": "6.0.0",
"json5": "2.1.1",
"lint-staged": "9.2.5",
"node-fetch": "2.6.1",
"npm-package-arg": "6.1.0",
"prettier": "2.0.5"
"prettier": "2.3.1"
},
"scripts": {
"lerna": "lerna",
"bootstrap": "lerna bootstrap",
"publish-stable": "echo 'Run `yarn changelog` for instructions'",
"publish-canary": "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",
@@ -79,8 +79,7 @@
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier",
"prettier/@typescript-eslint"
"prettier"
],
"env": {
"node": true,
@@ -89,26 +88,19 @@
},
"rules": {
"require-atomic-updates": 0,
"@typescript-eslint/ban-ts-ignore": 0,
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/camelcase": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/no-unused-vars": 2,
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/no-var-requires": 0,
"jest/no-disabled-tests": 2,
"jest/no-focused-tests": 2
},
"overrides": [
{
"files": [
"**/*.js"
],
"rules": {
"@typescript-eslint/no-var-requires": "off"
}
},
{
"files": [
"packages/cli/**/*"
@@ -125,8 +117,7 @@
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-inferrable-types": 0,
"@typescript-eslint/no-var-requires": 0
"@typescript-eslint/no-inferrable-types": 0
}
},
{

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "2.10.3-canary.4",
"version": "2.11.2-canary.2",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",
@@ -29,7 +29,7 @@
"@types/node-fetch": "^2.1.6",
"@types/semver": "6.0.0",
"@types/yazl": "^2.4.1",
"@vercel/frameworks": "0.3.3-canary.3",
"@vercel/frameworks": "0.4.2-canary.1",
"@vercel/ncc": "0.24.0",
"aggregate-error": "3.0.1",
"async-retry": "1.2.3",
@@ -47,7 +47,7 @@
"node-fetch": "2.6.1",
"semver": "6.1.1",
"ts-jest": "24.1.0",
"typescript": "3.9.3",
"typescript": "4.3.4",
"yazl": "2.4.3"
}
}

View File

@@ -424,6 +424,7 @@ function getApiMatches() {
return [
{ src: 'api/**/*.js', use: `@vercel/node`, config },
{ src: 'api/**/*.mjs', use: `@vercel/node`, config },
{ src: 'api/**/*.ts', use: `@vercel/node`, config },
{ src: 'api/**/!(*_test).go', use: `@vercel/go`, config },
{ src: 'api/**/*.py', use: `@vercel/python`, config },

View File

@@ -1346,6 +1346,25 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
expect((errorRoutes![0] as Source).status).toBe(404);
});
it('api detect node mjs files', async () => {
const files = [
'api/index.mjs',
'api/users.mjs',
'api/config/staging.mjs',
'api/config/production.mjs',
'api/src/controllers/health.mjs',
'api/src/controllers/user.module.mjs',
];
const { builders, errorRoutes } = await detectBuilders(files, undefined, {
featHandleMiss,
});
expect(builders!.length).toBe(6);
expect(builders!.every(b => b.src!.endsWith('.mjs'))).toBe(true);
expect(errorRoutes!.length).toBe(1);
expect((errorRoutes![0] as Source).status).toBe(404);
});
it('just public', async () => {
const files = ['public/index.html', 'public/favicon.ico', 'README.md'];

View File

@@ -1 +0,0 @@
handler

View File

@@ -1,25 +0,0 @@
#!/usr/bin/env node
const execa = require('execa');
const { join } = require('path');
const { homedir } = require('os');
async function main() {
process.env.GOOS = 'linux';
process.env.GOARCH = 'amd64';
process.env.GOPATH = join(homedir(), 'go');
await execa('go', ['get', 'github.com/aws/aws-lambda-go/events'], {
stdio: 'inherit',
});
await execa('go', ['get', 'github.com/aws/aws-lambda-go/lambda'], {
stdio: 'inherit',
});
await execa('go', ['build', '-o', 'handler', 'main.go'], {
stdio: 'inherit',
});
}
main().catch(err => {
console.error(err);
process.exit(1);
});

View File

@@ -1,45 +0,0 @@
const path = require('path');
const { mkdirp, copyFile } = require('fs-extra');
const {
glob,
download,
shouldServe,
createLambda,
getWritableDirectory,
} = require('@vercel/build-utils');
exports.analyze = ({ files, entrypoint }) => files[entrypoint].digest;
exports.version = 3;
exports.build = async ({ workPath, files, entrypoint, meta }) => {
const outDir = await getWritableDirectory();
await download(files, workPath, meta);
const handlerPath = path.join(__dirname, 'handler');
await copyFile(handlerPath, path.join(outDir, 'handler'));
const entrypointOutDir = path.join(outDir, path.dirname(entrypoint));
await mkdirp(entrypointOutDir);
// For now only the entrypoint file is copied into the lambda
await copyFile(
path.join(workPath, entrypoint),
path.join(outDir, entrypoint)
);
const lambda = await createLambda({
files: await glob('**', outDir),
handler: 'handler',
runtime: 'go1.x',
environment: {
SCRIPT_FILENAME: entrypoint,
},
});
return { output: lambda };
};
exports.shouldServe = shouldServe;

View File

@@ -1,36 +0,0 @@
package main
import (
now "../../utils/go/bridge"
"net/http"
"net/http/cgi"
"os"
"path/filepath"
)
type CgiHandler struct {
http.Handler
Dir string
Script string
}
func (h *CgiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
handler := cgi.Handler{
Path: h.Script,
Root: "/" + h.Script,
Dir: h.Dir,
Env: []string{
"HTTPS=on",
"SERVER_PORT=443",
"SERVER_SOFTWARE=@vercel/cgi",
},
}
handler.ServeHTTP(w, r)
}
func main() {
workdir, _ := filepath.Abs(".")
script := os.Getenv("SCRIPT_FILENAME")
handler := &CgiHandler{nil, workdir, script}
now.Start(handler)
}

View File

@@ -1,24 +0,0 @@
{
"name": "@vercel/cgi",
"version": "1.0.7",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/vercel/vercel.git",
"directory": "packages/cgi"
},
"scripts": {
"build": "node build",
"prepublishOnly": "node build"
},
"files": [
"index.js",
"handler"
],
"dependencies": {
"fs-extra": "7.0.0"
},
"devDependencies": {
"rmfr": "2.0.0"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "vercel",
"version": "22.0.2-canary.6",
"version": "23.0.2-canary.3",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Vercel",
@@ -17,8 +17,8 @@
"test-integration-dev": "ava test/dev/integration.js --serial --fail-fast --verbose",
"prepublishOnly": "yarn build",
"coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov",
"build": "ts-node ./scripts/build.ts",
"build-dev": "ts-node ./scripts/build.ts --dev"
"build": "node -r ts-eager/register ./scripts/build.ts",
"build-dev": "node -r ts-eager/register ./scripts/build.ts --dev"
},
"nyc": {
"include": [
@@ -61,11 +61,11 @@
"node": ">= 12"
},
"dependencies": {
"@vercel/build-utils": "2.10.3-canary.4",
"@vercel/go": "1.2.2",
"@vercel/node": "1.10.1-canary.2",
"@vercel/python": "2.0.2",
"@vercel/ruby": "1.2.6",
"@vercel/build-utils": "2.11.2-canary.2",
"@vercel/go": "1.2.3-canary.0",
"@vercel/node": "1.11.2-canary.3",
"@vercel/python": "2.0.5-canary.0",
"@vercel/ruby": "1.2.7-canary.0",
"update-notifier": "4.1.0"
},
"devDependencies": {
@@ -89,7 +89,7 @@
"@types/mri": "1.1.0",
"@types/ms": "0.7.30",
"@types/node": "11.11.0",
"@types/node-fetch": "2.1.4",
"@types/node-fetch": "2.5.10",
"@types/npm-package-arg": "6.1.0",
"@types/pluralize": "0.0.29",
"@types/progress": "2.0.3",
@@ -100,7 +100,7 @@
"@types/universal-analytics": "0.4.2",
"@types/which": "1.3.2",
"@types/write-json-file": "2.2.1",
"@vercel/frameworks": "0.3.3-canary.3",
"@vercel/frameworks": "0.4.2-canary.1",
"@vercel/ncc": "0.24.0",
"@zeit/fun": "0.11.2",
"@zeit/source-map-support": "0.6.2",
@@ -117,7 +117,7 @@
"chalk": "4.1.0",
"chokidar": "3.3.1",
"clipboardy": "2.1.0",
"codecov": "3.7.1",
"codecov": "3.8.2",
"cpy": "7.2.0",
"credit-card": "3.0.1",
"date-fns": "1.29.0",
@@ -148,7 +148,7 @@
"node-fetch": "2.6.1",
"npm-package-arg": "6.1.0",
"nyc": "13.2.0",
"open": "8.0.2",
"open": "8.2.0",
"ora": "3.4.0",
"pcre-to-regexp": "1.0.0",
"pluralize": "7.0.0",
@@ -169,8 +169,9 @@
"title": "3.4.1",
"tmp-promise": "1.0.3",
"tree-kill": "1.2.2",
"ts-eager": "2.0.2",
"ts-node": "8.3.0",
"typescript": "3.9.3",
"typescript": "4.3.4",
"universal-analytics": "0.4.20",
"utility-types": "2.1.0",
"which": "2.0.2",

View File

@@ -2,10 +2,11 @@ import chalk from 'chalk';
import { handleError } from '../../util/error';
import Client from '../../util/client';
import getArgs from '../../util/get-args';
import getSubcommand from '../../util/get-subcommand';
import logo from '../../util/output/logo';
import { getPkgName } from '../../util/pkg-name.ts';
import { getPkgName } from '../../util/pkg-name';
import ls from './ls';
import rm from './rm';
@@ -36,6 +37,7 @@ const help = () => {
)} Login token
-S, --scope Set a custom scope
-N, --next Show next page of results
${chalk.dim('Examples:')}
${chalk.gray('')} Add a new alias to ${chalk.underline('my-api.vercel.app')}
@@ -64,13 +66,13 @@ const help = () => {
};
const COMMAND_CONFIG = {
default: 'set',
default: ['set'],
ls: ['ls', 'list'],
rm: ['rm', 'remove'],
set: ['set'],
};
export default async function main(client) {
export default async function main(client: Client) {
let argv;
try {

View File

@@ -1,21 +1,26 @@
import chalk from 'chalk';
import ms from 'ms';
import table from 'text-table';
import Now from '../../util';
import Client from '../../util/client';
import getAliases from '../../util/alias/get-aliases';
import getScope from '../../util/get-scope.ts';
import stamp from '../../util/output/stamp.ts';
import strlen from '../../util/strlen.ts';
import getScope from '../../util/get-scope';
import stamp from '../../util/output/stamp';
import strlen from '../../util/strlen';
import getCommandFlags from '../../util/get-command-flags';
import { getCommandName } from '../../util/pkg-name.ts';
import { getCommandName } from '../../util/pkg-name';
export default async function ls(client, opts, args) {
const {
apiUrl,
authConfig: { token },
output,
config: { currentTeam },
} = client;
import { Alias } from '../../types';
interface Options {
'--next'?: number;
}
export default async function ls(
client: Client,
opts: Options,
args: string[]
) {
const { output } = client;
const { '--next': nextTimestamp } = opts;
let contextName = null;
@@ -36,13 +41,6 @@ export default async function ls(client, opts, args) {
return 1;
}
const now = new Now({
apiUrl,
token,
debug: client.output.isDebugEnabled(),
currentTeam,
output,
});
const lsStamp = stamp();
if (args.length > 0) {
@@ -56,8 +54,9 @@ export default async function ls(client, opts, args) {
output.spinner(`Fetching aliases under ${chalk.bold(contextName)}`);
// Get the list of alias
const { aliases, pagination } = await getAliases(
now,
client,
undefined,
nextTimestamp
);
@@ -73,21 +72,20 @@ export default async function ls(client, opts, args) {
);
}
now.close();
return 0;
}
function printAliasTable(aliases) {
function printAliasTable(aliases: Alias[]) {
return `${table(
[
['source', 'url', 'age'].map(h => chalk.gray(h)),
['source', 'url', 'age'].map(header => chalk.gray(header)),
...aliases.map(a => [
// for legacy reasons, we might have situations
// where the deployment was deleted and the alias
// not collected appropriately, and we need to handle it
a.deployment && a.deployment.url ? a.deployment.url : chalk.gray(''),
a.alias,
ms(Date.now() - new Date(a.createdAt)),
ms(Date.now() - a.createdAt),
]),
],
{

View File

@@ -1,23 +1,29 @@
import chalk from 'chalk';
import ms from 'ms';
import table from 'text-table';
import Now from '../../util';
import getScope from '../../util/get-scope.ts';
import Client from '../../util/client';
import getScope from '../../util/get-scope';
import removeAliasById from '../../util/alias/remove-alias-by-id';
import stamp from '../../util/output/stamp.ts';
import strlen from '../../util/strlen.ts';
import stamp from '../../util/output/stamp';
import strlen from '../../util/strlen';
import confirm from '../../util/input/confirm';
import { isValidName } from '../../util/is-valid-name';
import findAliasByAliasOrId from '../../util/alias/find-alias-by-alias-or-id';
import { getCommandName } from '../../util/pkg-name.ts';
export default async function rm(client, opts, args) {
const {
apiUrl,
authConfig: { token },
output,
config: { currentTeam },
} = client;
import { Alias } from '../../types';
import { Output } from '../../util/output';
import { isValidName } from '../../util/is-valid-name';
import { getCommandName } from '../../util/pkg-name';
type Options = {
'--yes': boolean;
};
export default async function rm(
client: Client,
opts: Partial<Options>,
args: string[]
) {
const { output } = client;
let contextName = null;
@@ -32,13 +38,6 @@ export default async function rm(client, opts, args) {
throw err;
}
const now = new Now({
apiUrl,
token,
debug: client.output.isDebugEnabled(),
currentTeam,
output,
});
const [aliasOrId] = args;
if (args.length !== 1) {
@@ -61,7 +60,8 @@ export default async function rm(client, opts, args) {
return 1;
}
const alias = await findAliasByAliasOrId(output, now, aliasOrId);
const alias = await findAliasByAliasOrId(output, client, aliasOrId);
if (!alias) {
output.error(
`Alias not found by "${aliasOrId}" under ${chalk.bold(contextName)}`
@@ -76,7 +76,7 @@ export default async function rm(client, opts, args) {
return 0;
}
await removeAliasById(now, alias.uid);
await removeAliasById(client, alias.uid);
console.log(
`${chalk.cyan('> Success!')} Alias ${chalk.bold(
alias.alias
@@ -85,7 +85,7 @@ export default async function rm(client, opts, args) {
return 0;
}
async function confirmAliasRemove(output, alias) {
async function confirmAliasRemove(output: Output, alias: Alias) {
const srcUrl = alias.deployment
? chalk.underline(alias.deployment.url)
: null;
@@ -94,7 +94,7 @@ async function confirmAliasRemove(output, alias) {
[
...(srcUrl ? [srcUrl] : []),
chalk.underline(alias.alias),
chalk.gray(`${ms(new Date() - new Date(alias.created))} ago`),
chalk.gray(`${ms(Date.now() - alias.createdAt)} ago`),
],
],
{

View File

@@ -28,7 +28,7 @@ type Options = {
export default async function set(
client: Client,
opts: Options,
opts: Partial<Options>,
args: string[]
) {
const { output, localConfig } = client;

View File

@@ -1,6 +1,6 @@
import chalk from 'chalk';
import logo from '../../util/output/logo';
import { getPkgName } from '../../util/pkg-name.ts';
import { getPkgName } from '../../util/pkg-name';
export const help = () => `
${chalk.bold(`${logo} ${getPkgName()}`)} [options] <command | path>
@@ -92,30 +92,3 @@ export const help = () => `
${chalk.cyan(`$ ${getPkgName()} help list`)}
`;
export const args = {
'--force': Boolean,
'--with-cache': Boolean,
'--public': Boolean,
'--no-clipboard': Boolean,
'--env': [String],
'--build-env': [String],
'--meta': [String],
// This is not an array in favor of matching
// the config property name.
'--regions': String,
'--prod': Boolean,
'--confirm': Boolean,
'-f': '--force',
'-p': '--public',
'-e': '--env',
'-b': '--build-env',
'-C': '--no-clipboard',
'-m': '--meta',
'-c': '--confirm',
// deprecated
'--name': String,
'-n': '--name',
'--target': String,
};

View File

@@ -1,37 +1,62 @@
import fs from 'fs-extra';
import { resolve, basename } from 'path';
import { fileNameSymbol } from '@vercel/client';
import getScope from '../../util/get-scope.ts';
import { VercelConfig, fileNameSymbol } 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, args } from './args';
import { help } from './args';
import deploy from './latest';
import Client from '../../util/client';
export default async client => {
const {
output,
config: { currentTeam },
} = client;
export default async (client: Client) => {
const { output } = client;
let contextName = currentTeam || 'current user';
let argv = null;
try {
argv = getArgs(client.argv.slice(2), args);
argv = getArgs(client.argv.slice(2), {
'--force': Boolean,
'--with-cache': Boolean,
'--public': Boolean,
'--no-clipboard': Boolean,
'--env': [String],
'--build-env': [String],
'--meta': [String],
// This is not an array in favor of matching
// the config property name.
'--regions': String,
'--prod': Boolean,
'--confirm': Boolean,
'-f': '--force',
'-p': '--public',
'-e': '--env',
'-b': '--build-env',
'-C': '--no-clipboard',
'-m': '--meta',
'-c': '--confirm',
// deprecated
'--name': String,
'-n': '--name',
'--target': String,
});
} catch (error) {
handleError(error);
return 1;
}
if (argv['--help']) {
output.print(help());
return 2;
}
if (argv._[0] === 'deploy') {
argv._.shift();
}
let paths = [];
let paths;
if (argv._.length > 0) {
// If path is relative: resolve
// if path is absolute: clear up strange `/` etc
@@ -40,20 +65,14 @@ export default async client => {
paths = [process.cwd()];
}
let { localConfig } = client;
let localConfig: VercelConfig | null = client.localConfig;
if (!localConfig || localConfig instanceof Error) {
localConfig = readLocalConfig(paths[0]);
}
const stats = {};
if (argv['--help']) {
output.print(help());
return 2;
}
for (const path of paths) {
try {
stats[path] = await fs.lstat(path);
await fs.stat(path);
} catch (err) {
output.error(
`The specified file or directory "${basename(path)}" does not exist.`
@@ -62,26 +81,15 @@ export default async client => {
}
}
try {
({ contextName } = await getScope(client));
} catch (err) {
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
output.error(err.message);
return 1;
}
throw err;
}
if (localConfig) {
const { version } = localConfig;
const file = highlight(localConfig[fileNameSymbol]);
const file = highlight(localConfig[fileNameSymbol]!);
const prop = code('version');
if (version) {
if (typeof version === 'number') {
if (version !== 2) {
const two = code(2);
const two = code(String(2));
output.error(
`The value of the ${prop} property within ${file} can only be ${two}.`
@@ -97,5 +105,5 @@ export default async client => {
}
}
return deploy(client, contextName, output, stats, localConfig, args);
return deploy(client, paths, localConfig, argv);
};

View File

@@ -3,13 +3,12 @@ import bytes from 'bytes';
import { join } from 'path';
import { write as copy } from 'clipboardy';
import chalk from 'chalk';
import { fileNameSymbol } from '@vercel/client';
import { Dictionary, fileNameSymbol, VercelConfig } from '@vercel/client';
import { getPrettyError } from '@vercel/build-utils';
import { handleError } from '../../util/error';
import getArgs from '../../util/get-args';
import toHumanPath from '../../util/humanize-path';
import Now from '../../util';
import stamp from '../../util/output/stamp.ts';
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';
@@ -53,10 +52,15 @@ import validatePaths, {
validateRootDirectory,
} from '../../util/validate-paths';
import { readLocalConfig } from '../../util/config/files';
import { getCommandName } from '../../util/pkg-name.ts';
import { getPreferredPreviewURL } from '../../util/deploy/get-preferred-preview-url.ts';
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, env) => {
const addProcessEnv = async (
log: (str: string) => void,
env: typeof process.env
) => {
let val;
for (const key of Object.keys(env)) {
@@ -85,8 +89,8 @@ const addProcessEnv = async (log, env) => {
};
const printDeploymentStatus = async (
output,
client,
output: Output,
client: Client,
{
readyState,
alias: aliasList,
@@ -94,10 +98,17 @@ const printDeploymentStatus = async (
target,
indications,
url: deploymentUrl,
}: {
readyState: string;
alias: string[];
aliasError: Error;
target: string;
indications: any;
url: string;
},
deployStamp,
isClipboardEnabled,
isFile
deployStamp: () => string,
isClipboardEnabled: boolean,
isFile: boolean
) => {
const isProdDeployment = target === 'production';
@@ -116,8 +127,8 @@ const printDeploymentStatus = async (
);
} else {
// print preview/production url
let previewUrl;
let isWildcard;
let previewUrl: string;
let isWildcard: boolean;
if (!isFile && Array.isArray(aliasList) && aliasList.length > 0) {
const previewUrlInfo = await getPreferredPreviewURL(client, aliasList);
if (previewUrlInfo) {
@@ -136,11 +147,12 @@ const printDeploymentStatus = async (
// copy to clipboard
let isCopiedToClipboard = false;
if (isClipboardEnabled && !isWildcard) {
await copy(previewUrl)
.then(() => {
isCopiedToClipboard = true;
})
.catch(error => output.debug(`Error copying to clipboard: ${error}`));
try {
await copy(previewUrl);
isCopiedToClipboard = true;
} catch (err) {
output.debug(`Error copyind to clipboard: ${err}`);
}
}
output.print(
@@ -176,7 +188,7 @@ const printDeploymentStatus = async (
};
// Converts `env` Arrays, Strings and Objects into env Objects.
const parseEnv = env => {
const parseEnv = (env?: string[] | Dictionary<string>) => {
if (!env) {
return {};
}
@@ -201,35 +213,25 @@ const parseEnv = env => {
o[key] = value;
return o;
}, {});
}, {} as Dictionary<string | undefined>);
}
// assume it's already an Object
return env;
};
export default async function main(
client,
contextName,
output,
stats,
localConfig,
args
client: Client,
paths: string[],
localConfig: VercelConfig | null,
argv: any
) {
let argv = null;
try {
argv = getArgs(client.argv.slice(2), args);
} catch (error) {
handleError(error);
return 1;
}
const {
apiUrl,
output,
authConfig: { token },
} = client;
const { log, debug, error, warn } = output;
const paths = Object.keys(stats);
const debugEnabled = argv['--debug'];
const { isTTY } = process.stdout;
@@ -265,6 +267,7 @@ export default async function main(
}
let { org, project, status } = link;
let newProjectName = null;
let rootDirectory = project ? project.rootDirectory : null;
let sourceFilesOutsideRootDirectory = true;
@@ -340,6 +343,16 @@ export default async function main(
}
}
// 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 =
@@ -354,7 +367,7 @@ export default async function main(
path,
sourcePath,
project
? `To change your Project Settings, go to https://vercel.com/${org.slug}/${project.name}/settings`
? `To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`
: ''
)) === false
) {
@@ -373,7 +386,7 @@ export default async function main(
output.print(
`${prependEmoji(
`The ${highlight(
localConfig[fileNameSymbol]
localConfig[fileNameSymbol]!
)} file should be inside of the provided root directory.`,
emoji('warning')
)}\n`
@@ -387,7 +400,7 @@ export default async function main(
output.print(
`${prependEmoji(
`The ${code('name')} property in ${highlight(
localConfig[fileNameSymbol]
localConfig[fileNameSymbol]!
)} is deprecated (https://vercel.link/name-prop)`,
emoji('warning')
)}\n`
@@ -395,7 +408,7 @@ export default async function main(
}
// build `env`
const isObject = item =>
const isObject = (item: any) =>
Object.prototype.toString.call(item) === '[object Object]';
// This validation needs to happen on the client side because
@@ -404,7 +417,7 @@ export default async function main(
if (typeof localConfig.env !== 'undefined' && !isObject(localConfig.env)) {
error(
`The ${code('env')} property in ${highlight(
localConfig[fileNameSymbol]
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
@@ -414,7 +427,7 @@ export default async function main(
if (!isObject(localConfig.build)) {
error(
`The ${code('build')} property in ${highlight(
localConfig[fileNameSymbol]
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
@@ -426,7 +439,7 @@ export default async function main(
) {
error(
`The ${code('build.env')} property in ${highlight(
localConfig[fileNameSymbol]
localConfig[fileNameSymbol]!
)} needs to be an object`
);
return 1;
@@ -466,7 +479,7 @@ export default async function main(
// build `regions`
const regionFlag = (argv['--regions'] || '')
.split(',')
.map(s => s.trim())
.map((s: string) => s.trim())
.filter(Boolean);
const regions = regionFlag.length > 0 ? regionFlag : localConfig.regions;
@@ -497,13 +510,13 @@ export default async function main(
target = 'production';
}
const currentTeam = org.type === 'team' ? org.id : undefined;
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 = {
const createArgs: any = {
name: project ? project.name : newProjectName,
env: deploymentEnv,
build: { env: deploymentBuildEnv },
@@ -527,7 +540,7 @@ export default async function main(
}
deployment = await createDeploy(
output,
client,
now,
contextName,
[sourcePath],
@@ -537,18 +550,15 @@ export default async function main(
path
);
if (
deployment instanceof Error &&
deployment.code === 'missing_project_settings'
) {
if (deployment.code === 'missing_project_settings') {
let { projectSettings, framework } = deployment;
if (rootDirectory) {
projectSettings.rootDirectory = rootDirectory;
}
if (typeof sourceFilesOutsideRootDirectory !== 'undefined') {
projectSettings.sourceFilesOutsideRootDirectory = sourceFilesOutsideRootDirectory;
projectSettings.sourceFilesOutsideRootDirectory =
sourceFilesOutsideRootDirectory;
}
const settings = await editProjectSettings(
@@ -563,7 +573,7 @@ export default async function main(
deployStamp = stamp();
createArgs.deployStamp = deployStamp;
deployment = await createDeploy(
output,
client,
now,
contextName,
[sourcePath],
@@ -575,7 +585,7 @@ export default async function main(
}
if (deployment instanceof NotDomainOwner) {
output.error(deployment);
output.error(deployment.message);
return 1;
}
@@ -583,7 +593,7 @@ export default async function main(
output.error(
deployment.message ||
'An unexpected error occurred while deploying your project',
null,
undefined,
'https://vercel.link/help',
'Contact Support'
);
@@ -596,7 +606,7 @@ export default async function main(
}
const deploymentResponse = await getDeploymentByIdOrHost(
now,
client,
contextName,
deployment.id,
'v10'
@@ -676,12 +686,7 @@ export default async function main(
output.error(err.message || 'Build failed');
output.error(
`Check your logs at https://${now.url}/_logs or run ${getCommandName(
`logs ${now.url}`,
{
// Backticks are interpreted as part of the URL, causing CMD+Click
// behavior to fail in editors like VSCode.
backticks: false,
}
`logs ${now.url}`
)}`
);
@@ -715,7 +720,11 @@ export default async function main(
);
}
function handleCreateDeployError(output, error, localConfig) {
function handleCreateDeployError(
output: Output,
error: Error,
localConfig: VercelConfig
) {
if (error instanceof InvalidDomain) {
output.error(`The domain ${error.meta.domain} is not valid`);
return 1;

View File

@@ -108,8 +108,5 @@ export default async function dev(
systemEnvValues,
});
process.once('SIGINT', () => devServer.stop());
process.once('SIGTERM', () => devServer.stop());
await devServer.start(...listen);
}

View File

@@ -13,7 +13,6 @@ import getDomainPrice from '../../util/domains/get-domain-price';
import { getCommandName } from '../../util/pkg-name';
import { getDomainConfig } from '../../util/domains/get-domain-config';
import code from '../../util/output/code';
import wait from '../../util/output/wait';
import { getDomainRegistrar } from '../../util/domains/get-domain-registrar';
type Options = {};
@@ -59,7 +58,7 @@ export default async function inspect(
output.debug(`Fetching domain info`);
const cancelWait = wait(
output.spinner(
`Fetching Domain ${domainName} under ${chalk.bold(contextName)}`
);
@@ -68,9 +67,6 @@ export default async function inspect(
client,
contextName,
domainName,
cancelWait,
}).finally(() => {
cancelWait();
});
if (typeof information === 'number') {
@@ -207,13 +203,11 @@ async function fetchInformation({
client,
contextName,
domainName,
cancelWait,
}: {
output: Output;
client: Client;
contextName: string;
domainName: string;
cancelWait: () => void;
}) {
const [domain, renewalPrice] = await Promise.all([
getDomainByName(client, contextName, domainName, { ignoreWait: true }),
@@ -223,13 +217,11 @@ async function fetchInformation({
]);
if (domain instanceof DomainNotFound) {
cancelWait();
output.prettyError(domain);
return 1;
}
if (domain instanceof DomainPermissionDenied) {
cancelWait();
output.prettyError(domain);
output.log(`Run ${getCommandName(`domains ls`)} to see your domains.`);
return 1;
@@ -238,7 +230,6 @@ async function fetchInformation({
const projects = await findProjectsForDomain(client, domainName);
if (projects instanceof Error) {
cancelWait();
output.prettyError(projects);
return 1;
}

View File

@@ -2,7 +2,6 @@ import ms from 'ms';
import chalk from 'chalk';
import plural from 'pluralize';
import wait from '../../util/output/wait';
import Client from '../../util/client';
import getDomains from '../../util/domains/get-domains';
import getScope from '../../util/get-scope';
@@ -55,14 +54,9 @@ export default async function ls(
return 1;
}
const cancelWait = wait(`Fetching Domains under ${chalk.bold(contextName)}`);
output.spinner(`Fetching Domains under ${chalk.bold(contextName)}`);
const { domains, pagination } = await getDomains(
client,
nextTimestamp
).finally(() => {
cancelWait();
});
const { domains, pagination } = await getDomains(client, nextTimestamp);
output.log(
`${plural('Domain', domains.length, true)} found under ${chalk.bold(

View File

@@ -12,7 +12,7 @@ import { getCommandName, getPkgName } from '../util/pkg-name';
import getGlobalPathConfig from '../util/config/global-path';
import { writeToAuthConfigFile, writeToConfigFile } from '../util/config/files';
import Client from '../util/client';
import { LoginParams } from '../util/login/types';
import { LoginResult } from '../util/login/types';
const help = () => {
console.log(`
@@ -46,7 +46,7 @@ const help = () => {
export default async function login(client: Client): Promise<number> {
let argv;
const { apiUrl, output } = client;
const { output } = client;
try {
argv = getArgs(client.argv.slice(2));
@@ -67,19 +67,18 @@ export default async function login(client: Client): Promise<number> {
const input = argv._[1];
let result: number | string = 1;
const params: LoginParams = { output, apiUrl };
let result: LoginResult = 1;
if (input) {
// Email or Team slug was provided via command line
if (validateEmail(input)) {
result = await doEmailLogin(input, params);
result = await doEmailLogin(client, input);
} else {
result = await doSsoLogin(input, params);
result = await doSsoLogin(client, input);
}
} else {
// Interactive mode
result = await prompt(params);
result = await prompt(client);
}
// The login function failed, so it returned an exit code
@@ -87,12 +86,20 @@ export default async function login(client: Client): Promise<number> {
return result;
}
// If the token was upgraded (not a new login), then don't modify
// the current scope.
if (!client.authConfig.token) {
if (result.teamId) {
// SSO login, so set the current scope to the appropriate Team
client.config.currentTeam = result.teamId;
} else {
delete client.config.currentTeam;
}
}
// When `result` is a string it's the user's authentication token.
// It needs to be saved to the configuration file.
client.authConfig.token = result;
// New user, so we can't keep the team
delete client.config.currentTeam;
client.authConfig.token = result.token;
writeToAuthConfigFile(client.authConfig);
writeToConfigFile(client.config);

View File

@@ -1,6 +1,5 @@
import chalk from 'chalk';
import logo from '../util/output/logo';
// @ts-ignore
import { handleError } from '../util/error';
import { writeToConfigFile, writeToAuthConfigFile } from '../util/config/files';
import getArgs from '../util/get-args';
@@ -62,6 +61,7 @@ export default async function main(client: Client): Promise<number> {
try {
await client.fetch(`/v3/user/tokens/current`, {
method: 'DELETE',
useCurrentTeam: false,
});
} catch (err) {
if (err.status === 403) {

View File

@@ -243,7 +243,7 @@ function printLogShort(log: any) {
const date = new Date(log.created).toISOString();
data.split('\n').forEach((line, i) => {
data.split('\n').forEach(line => {
if (
line.includes('START RequestId:') ||
line.includes('END RequestId:') ||
@@ -260,18 +260,9 @@ function printLogShort(log: any) {
}
}
if (i === 0) {
console.log(
`${chalk.dim(date)} ${line.replace('[now-builder-debug] ', '')}`
);
} else {
console.log(
`${' '.repeat(date.length)} ${line.replace(
'[now-builder-debug] ',
''
)}`
);
}
console.log(
`${chalk.dim(date)} ${line.replace('[now-builder-debug] ', '')}`
);
});
return 0;

View File

@@ -8,7 +8,6 @@ import exit from '../util/exit';
import logo from '../util/output/logo';
import getScope from '../util/get-scope';
import getCommandFlags from '../util/get-command-flags';
import wait from '../util/output/wait';
import { getPkgName, getCommandName } from '../util/pkg-name.ts';
const e = encodeURIComponent;
@@ -103,6 +102,7 @@ export default async client => {
};
async function run({ client, contextName }) {
const { output } = client;
const args = argv._.slice(1);
const start = Date.now();
@@ -118,7 +118,7 @@ async function run({ client, contextName }) {
return exit(2);
}
const stopSpinner = wait(`Fetching projects in ${chalk.bold(contextName)}`);
output.spinner(`Fetching projects in ${chalk.bold(contextName)}`);
let projectsUrl = '/v4/projects/?limit=20';
@@ -131,7 +131,7 @@ async function run({ client, contextName }) {
method: 'GET',
});
stopSpinner();
output.stopSpinner();
const elapsed = ms(new Date() - start);
@@ -187,25 +187,22 @@ async function run({ client, contextName }) {
const name = args[0];
// Check the existence of the project
try {
await client.fetch(`/projects/info/${e(name)}`);
} catch (err) {
if (err.status === 404) {
console.error(error('No such project exists'));
return exit(1);
}
}
const yes = await readConfirmation(name);
if (!yes) {
console.error(error('User abort'));
return exit(0);
}
await client.fetch(`/v2/projects/${name}`, {
method: 'DELETE',
});
try {
await client.fetch(`/v2/projects/${e(name)}`, {
method: 'DELETE',
});
} catch (err) {
if (err.status === 404) {
console.error(error('No such project exists'));
return exit(1);
}
}
const elapsed = ms(new Date() - start);
console.log(
`${chalk.cyan('> Success!')} Project ${chalk.bold(

View File

@@ -115,8 +115,6 @@ export default async function main(client) {
try {
({ contextName } = await getScope(client));
} catch (err) {
client.close();
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
output.error(err.message);
return 1;
@@ -210,7 +208,6 @@ export default async function main(client) {
.map(id => chalk.bold(`"${id}"`))
.join(', ')}. Run ${getCommandName('ls')} to list.`
);
client.close();
return 1;
}
@@ -233,7 +230,6 @@ export default async function main(client) {
if (confirmation !== 'y' && confirmation !== 'yes') {
output.log('Aborted');
client.close();
return 1;
}
}
@@ -265,7 +261,6 @@ export default async function main(client) {
console.log(`${chalk.gray('-')} ${chalk.bold(project.name)}`);
});
client.close();
return 0;
}

View File

@@ -1,12 +1,9 @@
import chalk from 'chalk';
import stamp from '../../util/output/stamp.ts';
import info from '../../util/output/info';
import error from '../../util/output/error';
import wait from '../../util/output/wait';
import rightPad from '../../util/output/right-pad';
import eraseLines from '../../util/output/erase-lines';
import chars from '../../util/output/chars';
import success from '../../util/output/success';
import note from '../../util/output/note';
import textInput from '../../util/input/text';
import invite from './invite';
@@ -40,14 +37,12 @@ export default async function add(client, teams) {
let slug;
let team;
let elapsed;
let stopSpinner;
const { output } = client;
console.log(
info(
`Pick a team identifier for its url (e.g.: ${chalk.cyan(
'`vercel.com/acme`'
)})`
)
output.log(
`Pick a team identifier for its url (e.g.: ${chalk.cyan(
'`vercel.com/acme`'
)})`
);
do {
try {
@@ -61,7 +56,7 @@ export default async function add(client, teams) {
});
} catch (err) {
if (err.message === 'USER_ABORT') {
console.log(info('Aborted'));
output.log('Aborted');
return 0;
}
@@ -69,26 +64,26 @@ export default async function add(client, teams) {
}
elapsed = stamp();
stopSpinner = wait(teamUrlPrefix + slug);
output.spinner(teamUrlPrefix + slug);
let res;
try {
// eslint-disable-next-line no-await-in-loop
res = await teams.create({ slug });
stopSpinner();
team = res;
} catch (err) {
stopSpinner();
output.stopSpinner();
process.stdout.write(eraseLines(2));
console.error(error(err.message));
output.error(err.message);
}
} while (!team);
output.stopSpinner();
process.stdout.write(eraseLines(2));
console.log(success(`Team created ${elapsed()}`));
console.log(`${chalk.cyan(`${chars.tick} `) + teamUrlPrefix + slug}\n`);
console.log(info('Pick a display name for your team'));
output.success(`Team created ${elapsed()}`);
output.log(`${chalk.cyan(`${chars.tick} `) + teamUrlPrefix + slug}\n`);
output.log('Pick a display name for your team');
let name;
@@ -107,17 +102,16 @@ export default async function add(client, teams) {
}
elapsed = stamp();
stopSpinner = wait(teamNamePrefix + name);
output.spinner(teamNamePrefix + name);
const res = await teams.edit({ id: team.id, name });
stopSpinner();
output.stopSpinner();
process.stdout.write(eraseLines(2));
if (res.error) {
console.error(error(res.error.message));
console.log(`${chalk.red(`${teamNamePrefix}`)}${name}`);
output.error(res.error.message);
output.log(`${chalk.red(`${teamNamePrefix}`)}${name}`);
return 1;
// TODO: maybe we want to ask the user to retry? not sure if
@@ -126,10 +120,10 @@ export default async function add(client, teams) {
team = Object.assign(team, res);
console.log(success(`Team name saved ${elapsed()}`));
console.log(`${chalk.cyan(`${chars.tick} `) + teamNamePrefix + team.name}\n`);
output.success(`Team name saved ${elapsed()}`);
output.log(`${chalk.cyan(`${chars.tick} `) + teamNamePrefix + team.name}\n`);
stopSpinner = wait('Saving');
output.spinner('Saving');
// Update config file
const configCopy = Object.assign({}, client.config);
@@ -142,7 +136,7 @@ export default async function add(client, teams) {
writeToConfigFile(configCopy);
stopSpinner();
output.stopSpinner();
await invite(client, { _: [] }, teams, {
introMsg: 'Invite your teammates! When done, press enter on an empty field',

View File

@@ -1,11 +1,3 @@
// Packages
import chalk from 'chalk';
// Utilities
import wait from '../../util/output/wait';
import info from '../../util/output/info';
import error from '../../util/output/error';
import chars from '../../util/output/chars';
import table from '../../util/output/table';
import getUser from '../../util/get-user.ts';
@@ -23,7 +15,7 @@ export default async function list(client, argv, teams) {
return 1;
}
const stopSpinner = wait('Fetching teams');
output.spinner('Fetching teams');
const { teams: list, pagination } = await teams.ls({
next,
apiVersion: 2,
@@ -31,23 +23,19 @@ export default async function list(client, argv, teams) {
let { currentTeam } = config;
const accountIsCurrent = !currentTeam;
stopSpinner();
const stopUserSpinner = wait('Fetching user information');
output.spinner('Fetching user information');
let user;
try {
user = await getUser(client);
} catch (err) {
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
console.error(error(err.message));
output.error(err.message);
return 1;
}
throw err;
}
stopUserSpinner();
if (accountIsCurrent) {
currentTeam = {
slug: user.username || user.email,
@@ -79,12 +67,12 @@ export default async function list(client, argv, teams) {
const count = teamList.length;
if (!count) {
// Maybe should not happen
console.error(error(`No team found`));
output.error(`No teams found`);
return 1;
}
info(`${chalk.bold(count)} team${count > 1 ? 's' : ''} found`);
console.log();
output.stopSpinner();
console.log(); // empty line
table(
['', 'id', 'email / name'],

View File

@@ -3,9 +3,10 @@ import chalk from 'chalk';
// Utilities
import Client from '../../util/client';
import listInput from '../../util/input/list';
import { emoji } from '../../util/emoji';
import getUser from '../../util/get-user';
import getTeams from '../../util/get-teams';
import listInput from '../../util/input/list';
import { Team, GlobalConfig } from '../../types';
import { writeToConfigFile } from '../../util/config/files';
@@ -31,7 +32,7 @@ export default async function main(client: Client, desiredSlug?: string) {
: teams.find(team => team.id === config.currentTeam);
if (!personalScopeSelected && !currentTeam) {
output.error(`You are not a part of the current team anymore.`);
output.error(`You are not a member of the current team anymore.`);
return 1;
}
@@ -41,30 +42,39 @@ export default async function main(client: Client, desiredSlug?: string) {
.sort((a, b) => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
})
.map(({ id, slug, name }) => {
let title = `${name} (${slug})`;
const selected = id === currentTeam?.id;
.map(team => {
let title = `${team.name} (${team.slug})`;
const selected = team.id === currentTeam?.id;
if (selected) {
title += ` ${chalk.bold('(current)')}`;
}
if (team.limited) {
title += ` ${emoji('locked')}`;
}
return {
name: title,
value: slug,
short: slug,
value: team.slug,
short: team.slug,
selected,
};
});
// Add the User scope entry at the top
const suffix = personalScopeSelected ? ` ${chalk.bold('(current)')}` : '';
let suffix = personalScopeSelected ? ` ${chalk.bold('(current)')}` : '';
// SAML tokens can not interact with the user scope
if (user.limited) {
suffix += ` ${emoji('locked')}`;
}
const choices = [
{ separator: 'Personal Account' },
{
name: `${user.email} (${user.username})${suffix}`,
value: user.email,
name: `${user.name || user.email} (${user.username})${suffix}`,
value: user.username,
short: user.username,
selected: personalScopeSelected,
},
@@ -93,9 +103,18 @@ export default async function main(client: Client, desiredSlug?: string) {
return 0;
}
if (user.limited) {
await client.reauthenticate({
scope: user.username,
teamId: null,
});
}
updateCurrentTeam(config);
output.success(`Your account (${chalk.bold(desiredSlug)}) is now active!`);
output.success(
`Your account (${chalk.bold(user.username)}) is now active!`
);
return 0;
}
@@ -114,6 +133,15 @@ export default async function main(client: Client, desiredSlug?: string) {
return 0;
}
if (newTeam.limited) {
const samlEnabled = newTeam.saml?.connection?.state === 'active';
await client.reauthenticate({
teamId: samlEnabled ? newTeam.id : null,
scope: newTeam.slug,
enforced: samlEnabled && newTeam.saml?.enforced === true,
});
}
updateCurrentTeam(config, newTeam);
output.success(

View File

@@ -1,9 +1,10 @@
import chalk from 'chalk';
import logo from '../util/output/logo';
import getScope from '../util/get-scope.ts';
import { getPkgName } from '../util/pkg-name.ts';
import getArgs from '../util/get-args.ts';
import handleError from '../util/handle-error.ts';
import getScope from '../util/get-scope';
import { getPkgName } from '../util/pkg-name';
import getArgs from '../util/get-args';
import handleError from '../util/handle-error';
import Client from '../util/client';
const help = () => {
console.log(`
@@ -31,7 +32,7 @@ const help = () => {
`);
};
export default async client => {
export default async (client: Client) => {
const { output } = client;
let argv;
try {

View File

@@ -50,6 +50,7 @@ import { SENTRY_DSN } from './util/constants.ts';
import getUpdateCommand from './util/get-update-command';
import { metrics, shouldCollectMetrics } from './util/metrics.ts';
import { getCommandName, getTitleName } from './util/pkg-name.ts';
import doLoginPrompt from './util/login/prompt.ts';
const isCanary = pkg.version.includes('canary');
@@ -422,13 +423,24 @@ const main = async () => {
) {
if (isTTY) {
output.log(info(`No existing credentials found. Please log in:`));
const result = await doLoginPrompt(client);
subcommand = 'login';
client.argv[2] = 'login';
// The login function failed, so it returned an exit code
if (typeof result === 'number') {
return result;
}
// Ensure that subcommands lead to login as well, if
// no credentials are defined
client.argv = client.argv.splice(0, 3);
// When `result` is a string it's the user's authentication token.
// It needs to be saved to the configuration file.
client.authConfig.token = result;
// New user, so we can't keep the team
delete client.config.currentTeam;
configFiles.writeToAuthConfigFile(client.authConfig);
configFiles.writeToConfigFile(client.config);
output.debug(`Saved credentials in "${hp(VERCEL_DIR)}"`);
} else {
output.prettyError({
message:

View File

@@ -1,5 +1,22 @@
export type Primitive =
| bigint
| boolean
| null
| number
| string
| symbol
| undefined;
export type JSONArray = JSONValue[];
export type JSONValue = Primitive | JSONObject | JSONArray;
export interface JSONObject {
[key: string]: JSONValue;
}
export interface AuthConfig {
token: string;
token?: string;
skipWrite?: boolean;
}
@@ -45,18 +62,26 @@ export type User = {
updatedAt: number;
};
name?: string;
limited?: boolean;
};
export type Team = {
export interface Team {
id: string;
avatar?: string;
avatar?: string | null;
billing: Billing;
created: string;
creatorId: string;
membership: { uid: string; role: 'MEMBER' | 'OWNER'; created: number };
name: string;
slug: string;
};
limited?: boolean;
saml?: {
enforced: boolean;
connection?: {
state: string;
};
};
}
export type Domain = {
id: string;
@@ -120,7 +145,7 @@ export type Deployment = {
export type Alias = {
uid: string;
alias: string;
created: string;
createdAt: number;
deployment: {
id: string;
url: string;
@@ -245,6 +270,7 @@ export interface Project extends ProjectSettings {
rootDirectory?: string | null;
latestDeployments?: Partial<Deployment>[];
autoExposeSystemEnvs?: boolean;
sourceFilesOutsideRootDirectory: boolean;
}
export interface Org {
@@ -268,3 +294,13 @@ export type ProjectLinkResult =
| { status: 'linked'; org: Org; project: Project }
| { status: 'not_linked'; org: null; project: null }
| { status: 'error'; exitCode: number };
export interface Token {
id: string;
name: string;
type: string;
origin?: string;
activeAt: number;
createdAt: number;
teamId?: string;
}

View File

@@ -1,5 +1,6 @@
import { Output } from '../output';
import { Alias } from '../../types';
import Client from '../client';
export default async function findAliasByAliasOrId(
@@ -11,7 +12,6 @@ export default async function findAliasByAliasOrId(
`/now/aliases/${encodeURIComponent(getSafeAlias(aliasOrId))}`
);
}
function getSafeAlias(alias: string) {
return alias
.replace(/^https:\/\//i, '')

View File

@@ -1,8 +1,9 @@
import { Alias } from '../../types';
import { Alias, PaginationOptions } from '../../types';
import Client from '../client';
type Response = {
aliases: Alias[];
pagination: PaginationOptions;
};
export default async function getAliases(

View File

@@ -2,6 +2,6 @@ import Client from '../client';
export default async function removeAliasById(client: Client, id: string) {
return client.fetch(`/now/aliases/${id}`, {
method: 'DELETE'
method: 'DELETE',
});
}

View File

@@ -1,6 +1,5 @@
import { readFileSync } from 'fs';
import { resolve } from 'path';
import wait from '../output/wait';
import Client from '../client';
import { Cert } from '../../types';
@@ -10,7 +9,7 @@ export default async function createCertFromFile(
certPath: string,
caPath: string
) {
const cancelWait = wait('Adding your custom certificate');
client.output.spinner('Adding your custom certificate');
try {
const cert = readFileSync(resolve(certPath), 'utf8');
@@ -36,7 +35,5 @@ export default async function createCertFromFile(
}
throw error;
} finally {
cancelWait();
}
}

View File

@@ -3,7 +3,6 @@ import chalk from 'chalk';
import { Cert } from '../../types';
import * as ERRORS from '../errors-ts';
import Client from '../client';
import wait from '../output/wait';
import mapCertError from './map-cert-error';
export default async function startCertOrder(
@@ -11,7 +10,7 @@ export default async function startCertOrder(
cns: string[],
context: string // eslint-disable-line
) {
const cancelWait = wait(
client.output.spinner(
`Issuing a certificate for ${chalk.bold(cns.join(', '))}`
);
try {
@@ -22,10 +21,8 @@ export default async function startCertOrder(
domains: cns,
},
});
cancelWait();
return cert;
} catch (error) {
cancelWait();
if (error.code === 'cert_order_not_found') {
return new ERRORS.CertOrderNotFound(cns);
}

View File

@@ -1,5 +1,4 @@
import chalk from 'chalk';
import wait from '../output/wait';
import Client from '../client';
export type CertificateChallenge = {
@@ -24,23 +23,17 @@ export default async function startCertOrder(
cns: string[],
contextName: string
) {
const cancelWait = wait(
client.output.spinner(
`Starting certificate issuance for ${chalk.bold(
cns.join(', ')
)} under ${chalk.bold(contextName)}`
);
try {
const order = await client.fetch<CertificateOrder>('/v3/now/certs', {
method: 'PATCH',
body: {
op: 'startOrder',
domains: cns
}
});
cancelWait();
return order;
} catch (error) {
cancelWait();
throw error;
}
const order = await client.fetch<CertificateOrder>('/v3/now/certs', {
method: 'PATCH',
body: {
op: 'startOrder',
domains: cns,
},
});
return order;
}

View File

@@ -1,22 +1,28 @@
import { URLSearchParams } from 'url';
import { EventEmitter } from 'events';
import { URLSearchParams } from 'url';
import { parse as parseUrl } from 'url';
import fetch, { RequestInit, Response } from 'node-fetch';
import { VercelConfig } from '@vercel/client';
import retry, { RetryFunction, Options as RetryOptions } from 'async-retry';
import fetch, { BodyInit, Headers, RequestInit, Response } from 'node-fetch';
import ua from './ua';
import { Output } from './output/create-output';
import responseError from './response-error';
import ua from './ua';
import printIndications from './print-indications';
import { AuthConfig, GlobalConfig } from '../types';
import { VercelConfig } from './dev/types';
import doSsoLogin from './login/sso';
import reauthenticate from './login/reauthenticate';
import { SAMLError } from './login/types';
import { writeToAuthConfigFile } from './config/files';
import { AuthConfig, GlobalConfig, JSONObject } from '../types';
import { sharedPromise } from './promise';
import { APIError } from './errors-ts';
import { bold } from 'chalk';
export interface FetchOptions {
body?: NodeJS.ReadableStream | object | string;
headers?: { [key: string]: string };
const isSAMLError = (v: any): v is SAMLError => {
return v && v.saml;
};
export interface FetchOptions extends Omit<RequestInit, 'body'> {
body?: BodyInit | JSONObject;
json?: boolean;
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
retry?: RetryOptions;
useCurrentTeam?: boolean;
accountId?: string;
@@ -31,6 +37,10 @@ export interface ClientOptions {
localConfig: VercelConfig;
}
const isJSONObject = (v: any): v is JSONObject => {
return v && typeof v == 'object' && v.constructor === Object;
};
export default class Client extends EventEmitter {
argv: string[];
apiUrl: string;
@@ -47,7 +57,6 @@ export default class Client extends EventEmitter {
this.output = opts.output;
this.config = opts.config;
this.localConfig = opts.localConfig;
this._onRetry = this._onRetry.bind(this);
}
retry<T>(fn: RetryFunction<T>, { retries = 3, maxTimeout = Infinity } = {}) {
@@ -78,34 +87,32 @@ export default class Client extends EventEmitter {
}
_url = `${apiUrl}${parsedUrl.pathname}?${query}`;
delete opts.useCurrentTeam;
delete opts.accountId;
}
if (opts.json !== false && opts.body && typeof opts.body === 'object') {
Object.assign(opts, {
body: JSON.stringify(opts.body),
headers: Object.assign({}, opts.headers, {
'Content-Type': 'application/json',
}),
});
const headers = new Headers(opts.headers);
headers.set('user-agent', ua);
if (this.authConfig.token) {
headers.set('authorization', `Bearer ${this.authConfig.token}`);
}
opts.headers = opts.headers || {};
opts.headers.Authorization = `Bearer ${this.authConfig.token}`;
opts.headers['user-agent'] = ua;
let body;
if (isJSONObject(opts.body)) {
body = JSON.stringify(opts.body);
headers.set('content-type', 'application/json; charset=utf8');
} else {
body = opts.body;
}
const url = `${apiUrl ? '' : this.apiUrl}${_url}`;
return this.output.time(
`${opts.method || 'GET'} ${url} ${JSON.stringify(opts.body) || ''}`,
fetch(url, opts as RequestInit)
fetch(url, { ...opts, headers, body })
);
}
fetch(url: string, opts: { json: false }): Promise<Response>;
fetch<T>(url: string, opts?: FetchOptions): Promise<T>;
async fetch<T>(url: string, opts: FetchOptions = {}): Promise<T> {
fetch(url: string, opts: FetchOptions = {}) {
return this.retry(async bail => {
const res = await this._fetch(url, opts);
@@ -114,19 +121,11 @@ export default class Client extends EventEmitter {
if (!res.ok) {
const error = await responseError(res);
if (error.saml && error.teamId) {
// If a SAML error is encountered then we re-trigger the SAML
// authentication flow for the team specified in the error.
const result = await doSsoLogin(error.teamId, this);
if (typeof result === 'number') {
this.output.prettyError(error);
process.exit(1);
return;
}
this.authConfig.token = result;
writeToAuthConfigFile(this.authConfig);
if (isSAMLError(error)) {
// A SAML error means the token is expired, or is not
// designated for the requested team, so the user needs
// to re-authenticate
await this.reauthenticate(error);
} else if (res.status >= 400 && res.status < 500) {
// Any other 4xx should bail without retrying
return bail(error);
@@ -140,19 +139,37 @@ export default class Client extends EventEmitter {
return res;
}
if (!res.headers.get('content-type')) {
const contentType = res.headers.get('content-type');
if (!contentType) {
return null;
}
return res.headers.get('content-type').includes('application/json')
? res.json()
: res;
return contentType.includes('application/json') ? res.json() : res;
}, opts.retry);
}
_onRetry(error: Error) {
this.output.debug(`Retrying: ${error}\n${error.stack}`);
}
reauthenticate = sharedPromise(async function (
this: Client,
error: SAMLError
) {
const result = await reauthenticate(this, error);
close() {}
if (typeof result === 'number') {
if (error instanceof APIError) {
this.output.prettyError(error);
} else {
this.output.error(
`Failed to re-authenticate for ${bold(error.scope)} scope`
);
}
process.exit(1);
}
this.authConfig.token = result.token;
writeToAuthConfigFile(this.authConfig);
});
_onRetry = (error: Error) => {
this.output.debug(`Retrying: ${error}\n${error.stack}`);
};
}

View File

@@ -3,17 +3,21 @@ import * as ERRORS_TS from '../errors-ts';
import * as ERRORS from '../errors';
import { NowError } from '../now-error';
import mapCertError from '../certs/map-cert-error';
import { Org } from '../../types';
import Now from '..';
import Client from '../client';
import { DeploymentError } from '../../../../client/dist';
export default async function createDeploy(
output,
now,
contextName,
paths,
createArgs,
org,
isSettingUpProject,
cwd
) {
client: Client,
now: Now,
contextName: string,
paths: string[],
createArgs: any,
org: Org | null,
isSettingUpProject: boolean,
cwd?: string
): Promise<any | DeploymentError> {
try {
return await now.create(paths, createArgs, org, isSettingUpProject, cwd);
} catch (error) {
@@ -83,16 +87,17 @@ export default async function createDeploy(
// If the cert is missing we try to generate a new one and the retry
if (error.code === 'cert_missing') {
const result = await generateCertForDeploy(
output,
now,
client,
contextName,
error.value
);
if (result instanceof NowError) {
return result;
}
return createDeploy(
output,
client,
now,
contextName,
paths,

View File

@@ -1,17 +1,16 @@
import psl from 'psl';
import { NowError } from '../now-error';
import { Output } from '../output';
import Client from '../client';
import createCertForCns from '../certs/create-cert-for-cns';
import setupDomain from '../domains/setup-domain';
import { InvalidDomain } from '../errors-ts';
export default async function generateCertForDeploy(
output: Output,
client: Client,
contextName: string,
deployURL: string
) {
const { output } = client;
const parsedDomain = psl.parse(deployURL);
if (parsedDomain.error) {
return new InvalidDomain(deployURL, parsedDomain.error.message);

View File

@@ -39,7 +39,9 @@ export default async function getDeploymentsByProjectId(
query.set('from', options.from.toString());
}
const { deployments } = await client.fetch<Response>(`/v4/now/deployments?${query}`);
const { deployments } = await client.fetch<Response>(
`/v4/now/deployments?${query}`
);
total += deployments.length;
if (options.max && total >= options.max) {
@@ -49,15 +51,15 @@ export default async function getDeploymentsByProjectId(
if (options.continue && deployments.length === limit) {
const nextFrom = deployments[deployments.length - 1].created;
const nextOptions = Object.assign({}, options, { from: nextFrom });
deployments.push(...(await getDeploymentsByProjectId(client, projectId, nextOptions, total)));
deployments.push(
...(await getDeploymentsByProjectId(
client,
projectId,
nextOptions,
total
))
);
}
return deployments;
}
export async function getAllDeploymentsByProjectId(
client: Client,
projectId: string
) {
return getDeploymentsByProjectId(client, projectId, { from: null, limit: 100, continue: true });
}

View File

@@ -145,6 +145,7 @@ export default class DevServer {
private devServerPids: Set<number>;
private projectSettings?: ProjectSettings;
private vercelConfigWarning: boolean;
private getVercelConfigPromise: Promise<VercelConfig> | null;
private blockingBuildsPromise: Promise<void> | null;
private updateBuildersPromise: Promise<void> | null;
@@ -181,6 +182,7 @@ export default class DevServer {
this.inProgressBuilds = new Map();
this.devCacheDir = join(getVercelDirectory(cwd), 'cache');
this.vercelConfigWarning = false;
this.getVercelConfigPromise = null;
this.blockingBuildsPromise = null;
this.updateBuildersPromise = null;
@@ -636,6 +638,20 @@ export default class DevServer {
await this.validateVercelConfig(config);
// TODO: temporarily strip and warn since `has` is not implemented yet
config.routes = (config.routes || []).filter(route => {
if ('has' in route) {
if (!this.vercelConfigWarning) {
this.vercelConfigWarning = true;
this.output.warn(
`The "has" property in ${config[fileNameSymbol]} will be ignored during development. Deployments will work as expected.`
);
}
return false;
}
return true;
});
this.caseSensitive = hasNewRoutingProperties(config);
this.apiDir = detectApiDirectory(config.builds || []);
this.apiExtensions = detectApiExtensions(config.builds || []);

View File

@@ -4,7 +4,6 @@ import { Output } from '../output';
import Client from '../client';
import getDomainDNSRecords from './get-domain-dns-records';
import getDomains from '../domains/get-domains';
import wait from '../output/wait';
import chalk from 'chalk';
export type DomainRecordsItem = {
@@ -60,11 +59,7 @@ async function getDomainNames(
contextName: string,
next?: number
) {
const cancelWait = wait(`Fetching domains under ${chalk.bold(contextName)}`);
try {
const { domains, pagination } = await getDomains(client, next);
return { domainNames: domains.map(domain => domain.name), pagination };
} finally {
cancelWait();
}
client.output.spinner(`Fetching domains under ${chalk.bold(contextName)}`);
const { domains, pagination } = await getDomains(client, next);
return { domainNames: domains.map(domain => domain.name), pagination };
}

View File

@@ -4,7 +4,6 @@ import { resolve } from 'path';
import { Response } from 'node-fetch';
import { DomainNotFound, InvalidDomain } from '../errors-ts';
import Client from '../client';
import wait from '../output/wait';
type JSONResponse = {
recordIds: string[];
@@ -16,7 +15,7 @@ export default async function importZonefile(
domain: string,
zonefilePath: string
) {
const cancelWait = wait(
client.output.spinner(
`Importing Zone file for domain ${domain} under ${chalk.bold(contextName)}`
);
const zonefile = readFileSync(resolve(zonefilePath), 'utf8');
@@ -33,10 +32,8 @@ export default async function importZonefile(
);
const { recordIds } = (await res.json()) as JSONResponse;
cancelWait();
return recordIds;
} catch (error) {
cancelWait();
if (error.code === 'not_found') {
return new DomainNotFound(domain, contextName);
}

View File

@@ -3,7 +3,6 @@ import retry from 'async-retry';
import { DomainAlreadyExists, InvalidDomain } from '../errors-ts';
import { Domain } from '../../types';
import Client from '../client';
import wait from '../output/wait';
type Response = {
domain: Domain;
@@ -14,17 +13,11 @@ export default async function addDomain(
domain: string,
contextName: string
) {
const cancelWait = wait(
client.output.spinner(
`Adding domain ${domain} under ${chalk.bold(contextName)}`
);
try {
const addedDomain = await performAddRequest(client, domain);
cancelWait();
return addedDomain;
} catch (error) {
cancelWait();
throw error;
}
const addedDomain = await performAddRequest(client, domain);
return addedDomain;
}
async function performAddRequest(client: Client, domainName: string) {

View File

@@ -1,6 +1,5 @@
import chalk from 'chalk';
import Client from '../client';
import wait from '../output/wait';
import { Domain } from '../../types';
import { DomainPermissionDenied, DomainNotFound } from '../errors-ts';
@@ -16,14 +15,15 @@ export default async function getDomainByName(
ignoreWait?: boolean;
} = {}
) {
const cancelWait = options.ignoreWait
? null
: wait(`Fetching domain ${domainName} under ${chalk.bold(contextName)}`);
if (!options.ignoreWait) {
client.output.spinner(
`Fetching domain ${domainName} under ${chalk.bold(contextName)}`
);
}
try {
const { domain } = await client.fetch<Response>(
`/v4/domains/${encodeURIComponent(domainName)}`
);
return domain;
} catch (error) {
if (error.status === 404) {
@@ -35,7 +35,5 @@ export default async function getDomainByName(
}
throw error;
} finally {
cancelWait?.();
}
}

View File

@@ -1,6 +1,5 @@
import chalk from 'chalk';
import Client from '../client';
import wait from '../output/wait';
import { Domain } from '../../types';
type Response = {
@@ -12,7 +11,7 @@ export async function getDomain(
contextName: string,
domainName: string
) {
const cancelWait = wait(
client.output.spinner(
`Fetching domain ${domainName} under ${chalk.bold(contextName)}`
);
try {
@@ -27,7 +26,5 @@ export async function getDomain(
}
throw error;
} finally {
cancelWait();
}
}

View File

@@ -3,22 +3,19 @@ import retry from 'async-retry';
import { Domain } from '../../types';
import * as ERRORS from '../errors-ts';
import Client from '../client';
import wait from '../output/wait';
export default async function verifyDomain(
client: Client,
domainName: string,
contextName: string
) {
const cancelWait = wait(
client.output.spinner(
`Verifying domain ${domainName} under ${chalk.bold(contextName)}`
);
try {
const { domain } = await performVerifyDomain(client, domainName);
cancelWait();
return domain;
} catch (error) {
cancelWait();
if (error.code === 'verification_failed') {
return new ERRORS.DomainVerificationFailed({
purchased: false,

View File

@@ -5,6 +5,7 @@ export const emojiLabels = {
link: '🔗',
inspect: '🔍',
success: '✅',
locked: '🔒',
} as const;
export type EmojiLabel = keyof typeof emojiLabels;

View File

@@ -588,7 +588,7 @@ export class DeploymentNotFound extends NowError<
'DEPLOYMENT_NOT_FOUND',
{ id: string; context: string }
> {
constructor({ context, id = '' }: { context: string; id: string }) {
constructor({ context, id = '' }: { context: string; id?: string }) {
super({
code: 'DEPLOYMENT_NOT_FOUND',
meta: { id, context },

View File

@@ -1,15 +0,0 @@
import { EventEmitter } from 'events';
async function* eventListenerToGenerator(event: string, emitter: EventEmitter) {
while (true) {
yield new Promise(resolve => {
const handler = (...args: any[]) => {
emitter.removeListener(event, handler);
resolve(...args);
};
emitter.on(event, handler);
});
}
}
export default eventListenerToGenerator;

View File

@@ -20,6 +20,7 @@ export default class Now extends EventEmitter {
constructor({
apiUrl,
token,
url = null,
currentTeam = null,
forceNew = false,
withCache = false,
@@ -28,6 +29,7 @@ export default class Now extends EventEmitter {
}) {
super();
this.url = url;
this._token = token;
this._debug = debug;
this._forceNew = forceNew;

View File

@@ -6,15 +6,12 @@ export default async function confirm(
): Promise<boolean> {
require('./patch-inquirer');
const name = `${Date.now()}`;
const answers = await inquirer.prompt({
type: 'confirm',
name,
name: 'value',
message,
default: preferred,
});
const answer = answers[name] as boolean;
return answer;
return answers.value;
}

View File

@@ -22,7 +22,7 @@ export default async function editProjectSettings(
output: Output,
projectSettings: PartialProjectSettings | null,
framework: Framework | null,
autoConfirm: boolean
autoConfirm?: boolean
): Promise<ProjectSettings> {
// create new settings object, missing values will be filled with `null`
const settings: ProjectSettings = Object.assign(

View File

@@ -177,7 +177,7 @@ export default async function setupAndLink(
}
const deployment = await createDeploy(
output,
client,
now,
config.currentTeam || 'current user',
[sourcePath],

View File

@@ -1,13 +1,13 @@
import { URL } from 'url';
import { LoginParams } from './types';
import Client from '../client';
import doOauthLogin from './oauth';
export default function doBitbucketLogin(params: LoginParams) {
export default function doBitbucketLogin(client: Client, ssoUserId?: string) {
const url = new URL(
'/api/registration/bitbucket/connect',
// Can't use `apiUrl` here because this URL sets a
// cookie that the OAuth callback URL depends on
'https://vercel.com'
);
return doOauthLogin(url, 'Bitbucket', params);
return doOauthLogin(client, url, 'Bitbucket', ssoUserId);
}

View File

@@ -4,20 +4,22 @@ import highlight from '../output/highlight';
import eraseLines from '../output/erase-lines';
import verify from './verify';
import executeLogin from './login';
import { LoginParams } from './types';
import Client from '../client';
import { LoginResult } from './types';
export default async function doEmailLogin(
client: Client,
email: string,
params: LoginParams
): Promise<number | string> {
ssoUserId?: string
): Promise<LoginResult> {
let securityCode;
let verificationToken;
const { apiUrl, output } = params;
const { output } = client;
output.spinner('Sending you an email');
try {
const data = await executeLogin(apiUrl, email);
const data = await executeLogin(client, email);
verificationToken = data.token;
securityCode = data.securityCode;
} catch (err) {
@@ -42,9 +44,15 @@ export default async function doEmailLogin(
while (!token) {
try {
await sleep(ms('1s'));
token = await verify(email, verificationToken, params);
token = await verify(
client,
email,
verificationToken,
'Email',
ssoUserId
);
} catch (err) {
if (err.message !== 'Confirmation incomplete') {
if (err.serverMessage !== 'Confirmation incomplete') {
output.error(err.message);
return 1;
}
@@ -52,5 +60,5 @@ export default async function doEmailLogin(
}
output.success(`Email authentication complete for ${email}`);
return token;
return { token };
}

View File

@@ -1,13 +1,13 @@
import { URL } from 'url';
import { LoginParams } from './types';
import Client from '../client';
import doOauthLogin from './oauth';
export default function doGithubLogin(params: LoginParams) {
export default function doGithubLogin(client: Client, ssoUserId?: string) {
const url = new URL(
'/api/registration/login-with-github',
// Can't use `apiUrl` here because this URL sets a
// cookie that the OAuth callback URL depends on
'https://vercel.com'
);
return doOauthLogin(url, 'GitHub', params);
return doOauthLogin(client, url, 'GitHub', ssoUserId);
}

View File

@@ -1,10 +1,10 @@
import { URL } from 'url';
import { LoginParams } from './types';
import Client from '../client';
import doOauthLogin from './oauth';
export default function doGitlabLogin(params: LoginParams) {
export default function doGitlabLogin(client: Client, ssoUserId?: string) {
// Can't use `apiUrl` here because this URL sets a
// cookie that the OAuth callback URL depends on
const url = new URL('/api/registration/gitlab/connect', 'https://vercel.com');
return doOauthLogin(url, 'GitLab', params);
return doOauthLogin(client, url, 'GitLab', ssoUserId);
}

View File

@@ -1,47 +1,28 @@
import fetch from 'node-fetch';
import { hostname } from 'os';
import Client from '../client';
import { InvalidEmail, AccountNotFound } from '../errors-ts';
import ua from '../ua';
import { getTitleName } from '../pkg-name';
import { LoginData } from './types';
export default async function login(
apiUrl: string,
email: string,
mode: 'login' | 'signup' = 'login'
client: Client,
email: string
): Promise<LoginData> {
const hyphens = new RegExp('-', 'g');
const host = hostname().replace(hyphens, ' ').replace('.local', '');
const tokenName = `${getTitleName()} CLI on ${host}`;
const response = await fetch(`${apiUrl}/now/registration?mode=${mode}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': ua,
},
body: JSON.stringify({
tokenName,
email,
}),
});
const body = await response.json();
if (!response.ok) {
const { error = {} } = body;
if (error.code === 'not_exists') {
try {
return await client.fetch<LoginData>(`/registration?mode=login`, {
method: 'POST',
body: { email },
});
} catch (err) {
if (err.code === 'not_exists') {
throw new AccountNotFound(
email,
`Please sign up: https://vercel.com/signup`
);
}
if (error.code === 'invalid_email') {
throw new InvalidEmail(email, error.message);
if (err.code === 'invalid_email') {
throw new InvalidEmail(email, err.message);
}
throw new Error(`Unexpected error: ${error.message}`);
throw new Error(`Unexpected error: ${err.message}`);
}
return body as LoginData;
}

View File

@@ -2,40 +2,40 @@ import http from 'http';
import open from 'open';
import { URL } from 'url';
import listen from 'async-listen';
import { hostname } from 'os';
import { LoginParams } from './types';
import Client from '../client';
import prompt from './prompt';
import verify from './verify';
import { getTitleName } from '../pkg-name';
import highlight from '../output/highlight';
import link from '../output/link';
import eraseLines from '../output/erase-lines';
import { LoginResult } from './types';
export default async function doOauthLogin(
client: Client,
url: URL,
provider: string,
params: LoginParams
): Promise<number | string> {
const { output } = params;
output.spinner(
`Please complete the ${provider} authentication in your web browser`
);
ssoUserId?: string
): Promise<LoginResult> {
const { output } = client;
const server = http.createServer();
const address = await listen(server, 0, '127.0.0.1');
const { port } = new URL(address);
url.searchParams.append('mode', 'login');
url.searchParams.append('next', `http://localhost:${port}`);
url.searchParams.set('mode', 'login');
url.searchParams.set('next', `http://localhost:${port}`);
// Append token name param
const hyphens = new RegExp('-', 'g');
const host = hostname().replace(hyphens, ' ').replace('.local', '');
const tokenName = `${getTitleName()} CLI on ${host} via ${provider}`;
url.searchParams.append('tokenName', tokenName);
output.log(`Please visit the following URL in your web browser:`);
output.log(link(url.href));
output.spinner(`Waiting for ${provider} authentication to be completed`);
try {
const [query] = await Promise.all([
new Promise<URL['searchParams']>((resolve, reject) => {
server.once('request', (req, res) => {
// Close the HTTP connection to prevent
// `server.close()` from hanging
res.setHeader('connection', 'close');
const query = new URL(req.url || '/', 'http://localhost')
.searchParams;
resolve(query);
@@ -78,6 +78,9 @@ export default async function doOauthLogin(
open(url.href),
]);
output.stopSpinner();
output.print(eraseLines(3));
const loginError = query.get('loginError');
if (loginError) {
const err = JSON.parse(loginError);
@@ -88,16 +91,17 @@ export default async function doOauthLogin(
// If an `ssoUserId` was returned, then the SAML Profile is not yet connected
// to a Team member. Prompt the user to log in to a Vercel account now, which
// will complete the connection to the SAML Profile.
const ssoUserId = query.get('ssoUserId');
if (ssoUserId) {
const ssoUserIdParam = query.get('ssoUserId');
if (ssoUserIdParam) {
output.log(
'Please log in to your Vercel account to complete SAML connection.'
);
return prompt({ ...params, ssoUserId });
return prompt(client, undefined, ssoUserIdParam);
}
const email = query.get('email');
const verificationToken = query.get('token');
const teamId = query.get('teamId');
if (!email || !verificationToken) {
output.error(
'Verification token was not provided. Please contact support.'
@@ -106,11 +110,17 @@ export default async function doOauthLogin(
}
output.spinner('Verifying authentication token');
const token = await verify(email, verificationToken, params);
const token = await verify(
client,
email,
verificationToken,
provider,
ssoUserId
);
output.success(
`${provider} authentication complete for ${highlight(email)}`
);
return token;
return { token, teamId };
} finally {
server.close();
}

View File

@@ -1,27 +1,33 @@
import inquirer from 'inquirer';
import Client from '../client';
import error from '../output/error';
import listInput from '../input/list';
import { getCommandName } from '../pkg-name';
import { LoginParams } from './types';
import { LoginResult, SAMLError } from './types';
import doSsoLogin from './sso';
import doEmailLogin from './email';
import doGithubLogin from './github';
import doGitlabLogin from './gitlab';
import doBitbucketLogin from './bitbucket';
export default async function prompt(params: LoginParams) {
let result: number | string = 1;
export default async function prompt(
client: Client,
error?: Pick<SAMLError, 'teamId'>,
ssoUserId?: string
) {
let result: LoginResult = 1;
const choices = [
{ name: 'Continue with GitHub', value: 'github', short: 'github' },
{ name: 'Continue with GitLab', value: 'gitlab', short: 'gitlab' },
{ name: 'Continue with Bitbucket', value: 'bitbucket', short: 'bitbucket' },
{ name: 'Continue with Email', value: 'email', short: 'email' },
{ name: 'Continue with SAML Single Sign-On', value: 'saml', short: 'saml' },
{ name: 'Continue with SAML Single Sign-On', value: 'sso', short: 'sso' },
];
if (params.ssoUserId) {
// Remove SAML login option if we're connecting SAML Profile
if (ssoUserId || (error && !error.teamId)) {
// Remove SAML login option if we're connecting SAML Profile,
// or if this is a SAML error for a user / team without SAML
choices.pop();
}
@@ -31,17 +37,17 @@ export default async function prompt(params: LoginParams) {
});
if (choice === 'github') {
result = await doGithubLogin(params);
result = await doGithubLogin(client, ssoUserId);
} else if (choice === 'gitlab') {
result = await doGitlabLogin(params);
result = await doGitlabLogin(client, ssoUserId);
} else if (choice === 'bitbucket') {
result = await doBitbucketLogin(params);
result = await doBitbucketLogin(client, ssoUserId);
} else if (choice === 'email') {
const email = await readInput('Enter your email address');
result = await doEmailLogin(email, params);
} else if (choice === 'saml') {
const slug = await readInput('Enter your Team slug');
result = await doSsoLogin(slug, params);
result = await doEmailLogin(client, email, ssoUserId);
} else if (choice === 'sso') {
const slug = error?.teamId || (await readInput('Enter your Team slug'));
result = await doSsoLogin(client, slug, ssoUserId);
}
return result;

View File

@@ -0,0 +1,28 @@
import { bold } from 'chalk';
import doSsoLogin from './sso';
import showLoginPrompt from './prompt';
import { LoginResult, SAMLError } from './types';
import confirm from '../input/confirm';
import Client from '../client';
export default async function reauthenticate(
client: Client,
error: Pick<SAMLError, 'enforced' | 'scope' | 'teamId'>
): Promise<LoginResult> {
if (error.teamId && error.enforced) {
// If team has SAML enforced then trigger the SSO login directly
client.output.log(
`You must re-authenticate with SAML to use ${bold(error.scope)} scope.`
);
if (await confirm(`Log in with SAML?`, true)) {
return doSsoLogin(client, error.teamId);
}
} else {
// Personal account, or team that does not have SAML enforced
client.output.log(
`You must re-authenticate to use ${bold(error.scope)} scope.`
);
return showLoginPrompt(client, error);
}
return 1;
}

View File

@@ -1,9 +1,13 @@
import { URL } from 'url';
import { LoginParams } from './types';
import Client from '../client';
import doOauthLogin from './oauth';
export default function doSsoLogin(teamIdOrSlug: string, params: LoginParams) {
const url = new URL('/auth/sso', params.apiUrl);
url.searchParams.append('teamId', teamIdOrSlug);
return doOauthLogin(url, 'SAML Single Sign-On', params);
export default function doSsoLogin(
client: Client,
teamIdOrSlug: string,
ssoUserId?: string
) {
const url = new URL('/auth/sso', client.apiUrl);
url.searchParams.set('teamId', teamIdOrSlug);
return doOauthLogin(client, url, 'SAML Single Sign-On', ssoUserId);
}

View File

@@ -1,12 +1,22 @@
import { Output } from '../output';
export interface LoginParams {
apiUrl: string;
output: Output;
ssoUserId?: string;
}
export interface LoginData {
token: string;
securityCode: string;
}
export type LoginResult = number | LoginResultSuccess;
export interface LoginResultSuccess {
token: string;
teamId?: string | null;
}
export interface VerifyData {
token: string;
}
export interface SAMLError {
saml?: true;
teamId: string | null;
scope: string;
enforced?: boolean;
}

View File

@@ -1,33 +1,34 @@
import { URL } from 'url';
import fetch from 'node-fetch';
import ua from '../ua';
import { LoginParams } from './types';
import Client from '../client';
import { hostname } from 'os';
import { getTitleName } from '../pkg-name';
import { VerifyData } from './types';
export default async function verify(
client: Client,
email: string,
verificationToken: string,
{ apiUrl, ssoUserId }: LoginParams
provider: string,
ssoUserId?: string
): Promise<string> {
const url = new URL('/registration/verify', apiUrl);
url.searchParams.append('email', email);
url.searchParams.append('token', verificationToken);
const url = new URL('/registration/verify', client.apiUrl);
url.searchParams.set('email', email);
url.searchParams.set('token', verificationToken);
if (!client.authConfig.token) {
// Set the "name" of the Token that will be created
const hyphens = new RegExp('-', 'g');
const host = hostname().replace(hyphens, ' ').replace('.local', '');
const tokenName = `${getTitleName()} CLI on ${host} via ${provider}`;
url.searchParams.set('tokenName', tokenName);
}
// If `ssoUserId` is defined then this verification
// will complete the SAML two-step login connection
if (ssoUserId) {
url.searchParams.append('ssoUserId', ssoUserId);
url.searchParams.set('ssoUserId', ssoUserId);
}
const res = await fetch(url.href, {
headers: { 'User-Agent': ua },
});
const body = await res.json();
if (!res.ok) {
const err = new Error(
`Unexpected ${res.status} status code from verify API`
);
Object.assign(err, body.error);
throw err;
}
return body.token;
const { token } = await client.fetch<VerifyData>(url.href);
return token;
}

View File

@@ -1,6 +1,5 @@
import chalk from 'chalk';
import Client from '../client';
import wait from '../output/wait';
import { ProjectAliasTarget } from '../../types';
export async function addDomainToProject(
@@ -8,7 +7,7 @@ export async function addDomainToProject(
projectNameOrId: string,
domain: string
) {
const cancelWait = wait(
client.output.spinner(
`Adding domain ${domain} to project ${chalk.bold(projectNameOrId)}`
);
try {
@@ -40,7 +39,5 @@ export async function addDomainToProject(
}
throw err;
} finally {
cancelWait();
}
}

View File

@@ -1,6 +1,5 @@
import chalk from 'chalk';
import Client from '../client';
import wait from '../output/wait';
import { ProjectAliasTarget } from '../../types';
export async function removeDomainFromProject(
@@ -8,7 +7,7 @@ export async function removeDomainFromProject(
projectNameOrId: string,
domain: string
) {
const cancelWait = wait(
client.output.spinner(
`Removing domain ${domain} from project ${chalk.bold(projectNameOrId)}`
);
try {
@@ -28,7 +27,5 @@ export async function removeDomainFromProject(
}
throw err;
} finally {
cancelWait();
}
}

View File

@@ -0,0 +1,24 @@
/**
* Wraps a function such that only one in-flight invocation is active at a time.
*
* That is, if the returned function is invoked more that one time before the
* promise returned from the initial invocation resolves, then the same promise
* is returned for subsequent invocations.
*
* Once the promise has resolved, the next invocation of the returned function
* will re-invoke the original function again.
*/
export function sharedPromise<P extends any[], V, T>(
fn: (this: T, ...args: P) => Promise<V>
) {
let promise: Promise<V> | null = null;
return function (this: T, ...args: P) {
if (!promise) {
promise = fn.apply(this, args);
promise.finally(() => {
promise = null;
});
}
return promise;
};
}

View File

@@ -7,9 +7,9 @@ import { parse } from 'url';
* google.com => google.com
*/
function toHost(url: string) {
function toHost(url: string): string {
if (/^https?:\/\//.test(url)) {
return parse(url).host;
return parse(url).host!;
}
// Remove any path if present

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -0,0 +1,11 @@
import { dep1 } from './js/ecmascript-module';
const { dep2 } = require('./js/commonjs-module');
module.exports = (req, res) => {
if (req && typeof dep1 === 'string' && typeof dep2 === 'string') {
res.end('mixed-modules:js');
} else {
res.end('import failed');
}
};

View File

@@ -0,0 +1,12 @@
import { dep1 } from './js/em-jay-ess.mjs';
async function handler(_req, res) {
const cjs = await import('./js/commonjs-module.js');
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
res.end('mixed-modules:mjs');
} else {
res.end('import failed');
}
};
export default handler;

View File

@@ -0,0 +1,11 @@
import { IncomingMessage, ServerResponse } from 'http';
import { dep1 } from './ts/ecmascript-module';
const { dep2 } = require('./ts/commonjs-module');
module.exports = (req: IncomingMessage, res: ServerResponse) => {
if (req && typeof dep1 === 'string' && typeof dep2 === 'string') {
res.end('mixed-modules:ts');
} else {
res.end('import failed');
}
};

View File

@@ -0,0 +1 @@
module.exports = { dep2: 'dep2' };

View File

@@ -0,0 +1,2 @@
export const dep1 = 'dep1';
export const another = 'another';

View File

@@ -0,0 +1,2 @@
export const dep1 = 'dep1';
export const another = 'another';

View File

@@ -0,0 +1,3 @@
{
"private": true
}

View File

@@ -0,0 +1 @@
module.exports = { dep2: 'dep2' };

View File

@@ -0,0 +1 @@
export const dep1 = 'dep1';

View File

@@ -0,0 +1,3 @@
{
"private": true
}

View File

@@ -0,0 +1,12 @@
import { dep1 } from '../js/em-jay-ess.mjs';
async function handler(_req, res) {
const cjs = await import('../js/commonjs-module.js');
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
res.end('mixed-modules:auto');
} else {
res.end('import failed');
}
}
export default handler;

View File

@@ -0,0 +1,12 @@
import { dep1 } from '../../js/em-jay-ess.mjs';
async function handler(_req, res) {
const cjs = await import('../../js/commonjs-module.js');
if (dep1 === 'dep1' && cjs.default && cjs.default.dep2 === 'dep2') {
res.end('mixed-modules:also');
} else {
res.end('import failed');
}
}
export default handler;

View File

@@ -0,0 +1,4 @@
{
"private": true,
"type": "module"
}

View File

@@ -0,0 +1,7 @@
{
"version": 2,
"builds": [
{ "src": "entrypoint**", "use": "@vercel/node@canary" },
{ "src": "type-module-package-json/**/*.js", "use": "@vercel/node@canary" }
]
}

View File

@@ -1710,7 +1710,9 @@ test(
expectHeader('image/svg+xml'),
fetchOpts('image/webp')
);
// bmp should bypass: serve as-is
/* Disabled bmp because `next dev` bypasses
* and production will convert. Eventually
* we can enable once `next dev` supports it.
await testPath(
200,
toUrl('/test.bmp', 64, 50),
@@ -1718,6 +1720,7 @@ test(
expectHeader('image/bmp'),
fetchOpts('image/webp')
);
*/
// animated gif should bypass: serve as-is
await testPath(
200,
@@ -1729,6 +1732,25 @@ test(
})
);
test(
'[vercel dev] 40-mixed-modules',
testFixtureStdio('40-mixed-modules', async testPath => {
await testPath(200, '/entrypoint.js', 'mixed-modules:js');
await testPath(200, '/entrypoint.mjs', 'mixed-modules:mjs');
await testPath(200, '/entrypoint.ts', 'mixed-modules:ts');
await testPath(
200,
'/type-module-package-json/auto.js',
'mixed-modules:auto'
);
await testPath(
200,
'/type-module-package-json/nested/also.js',
'mixed-modules:also'
);
})
);
test(
'[vercel dev] Use `@vercel/python` with Flask requirements.txt',
testFixtureStdio('python-flask', async testPath => {

View File

@@ -157,9 +157,10 @@ function mockLoginApi(req, res) {
let { pathname = '/', query = {} } = parseUrl(url, true);
console.log(`[mock-login-server] ${method} ${pathname}`);
const securityCode = 'Bears Beets Battlestar Galactica';
res.setHeader('content-type', 'application/json');
if (
method === 'POST' &&
pathname === '/now/registration' &&
pathname === '/registration' &&
query.mode === 'login'
) {
res.end(JSON.stringify({ token, securityCode }));

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/client",
"version": "10.0.1-canary.5",
"version": "10.1.2-canary.2",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"homepage": "https://vercel.com",
@@ -29,7 +29,7 @@
"@types/node": "12.0.4",
"@types/node-fetch": "2.5.4",
"@types/recursive-readdir": "2.2.0",
"typescript": "3.9.3"
"typescript": "4.3.4"
},
"jest": {
"preset": "ts-jest",
@@ -40,7 +40,7 @@
]
},
"dependencies": {
"@vercel/build-utils": "2.10.3-canary.4",
"@vercel/build-utils": "2.11.2-canary.2",
"@zeit/fetch": "5.2.0",
"async-retry": "1.2.3",
"async-sema": "3.0.0",

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