Compare commits

..

77 Commits

Author SHA1 Message Date
Steven
ee40052cee Publish Stable
- @vercel/next@2.6.9
2020-07-08 13:53:18 -07:00
JJ Kasper
86b730c1cd Publish Canary
- vercel@19.1.2-canary.19
 - @vercel/next@2.6.9-canary.1
2020-07-08 15:08:29 -05:00
JJ Kasper
b440249c26 [next] Don't use potentially invalid routeKeys/regexes (#4803)
The first version of `routeKeys` which was Array based could contain invalid named regexes which would break the build during route validation so this disables using them in that version of the manifest instead of trying to leverage them still. It also adds an additional test fixture with this version of the manifest to ensure it is still working properly
2020-07-08 20:05:00 +00:00
Steven
5380c12569 Publish Canary
- @vercel/frameworks@0.0.16-canary.1
 - @vercel/build-utils@2.4.1-canary.2
 - vercel@19.1.2-canary.18
 - @vercel/client@8.1.1-canary.2
 - @vercel/next@2.6.9-canary.0
2020-07-08 11:27:30 -07:00
Steven
f11eb32b2c [frameworks] Remove blitz demo (#4816)
This is not ready yet. We need to confirm Blitz is working before we deploy the demo.
2020-07-08 14:19:55 -04:00
Brandon Bayer
3d40e343ac [frameworks][examples] Add Blitz.js (#4465)
This adds [Blitz.js](https://github.com/blitz-js/blitz) to the zero-config frameworks.

Blitz compiles to a Next.js app, so it uses the same `@vercel/next` builder.

The change in `packages/now-build-utils/src/detect-builders.ts` was made according to @styfle's suggestion in Slack.

---

**This is a rerun of #4219 which had to be reverted because of this:**

> It looks like the @vercel/next package still requires next in the dependencies.
>
> When I've deployed the example I've got only a file listing, but when I added next to the dependencies it worked. I'll revert for now.

This new PR fixes that problem with a small refactor to `@vercel/next`.

`@vercel/next` was getting the Next version two different ways:

1. By checking project root package.json for `next` in deps or devDeps
2. By trying to resolve the installed next version and get `version` from its package.json

My refactor consolidates those two approaches by changing the existing `getNextVersion()` function to first try and resolve the real next version. If that fails, fall back to checking the project root.

Blitz bundles Next, so the real next package version should always be resolved.
2020-07-08 13:18:01 -04:00
Nathan Rajlich
80f525796f [cli] Make filesystem globbing faster in vercel dev (#4793)
The current code uses `getAllProjectFiles()` which globs for every file
in the project, not considering the `.vercelignore` file and default
ignore list. For example, every file in the `node_modules` directory is
selected, just for `vercel dev` to manually ignore them afterwards,
which is very slow and wasteful. For a simple Next.js project, this
globbing was taking over 3 seconds on my machine 🤯!

Solution is to use the `staticFiles()` function which is the same as
`vercel dev` uses at boot-up time. This function properly considers the
ignore list and thus is much faster, and the manual filtering is no
longer necessary by `vercel dev`. For the same simple Next.js project,
this function takes on average 10 milliseconds.

Also did a bit of cleanup and removed the `getAllProjectFiles()`
function since it is no longer used anywhere.
2020-07-07 20:30:21 +00:00
Nathan Rajlich
af4ad358f2 [cli] Print a warning if both "functions" and "builds" are defined in vercel.json in vercel dev (#4795)
This matches the error message that is used in production when using the
`vercel dev` command.
2020-07-07 19:41:29 +00:00
Nathan Rajlich
e6033d7a2d [client] Add @vercel/build-utils as a "dependency" (#4804)
Fixes: https://github.com/philcockfield/sample.vercel.client-error
2020-07-07 18:56:31 +00:00
JJ Kasper
d3148dffaa Publish Stable
- @vercel/next@2.6.8
2020-07-06 08:40:44 -05:00
JJ Kasper
30048cf4ff Publish Canary
- vercel@19.1.2-canary.17
 - @vercel/next@2.6.8-canary.7
2020-07-06 08:31:35 -05:00
JJ Kasper
07c65fa5c8 [next] Use correct data route regex (#4778)
For `getServerSideProps` routes the non-named data route was being used for routes causing dynamic route params that were being trusted from the proxy to be incorrect. Our tests weren't failing after trusting the values from the proxy was landed in Next.js on canary due to the `21-server-props` test suite not running against the latest canary which is updated in this PR. 

Note: the below Next.js PR is not needed or can be reverted if this PR is landed

x-ref: https://github.com/vercel/next.js/pull/14829
2020-07-05 21:13:01 +00:00
Nathan Rajlich
411ec64986 [cli] Reduce number of times getNowConfig() is invoked in vercel dev (#4760)
* [cli] Reduce number of times `getNowConfig()` is invoked in `vercel dev`

When using the `vercel dev` command, the `getNowConfig()` function was
being invoked many times per HTTP-request. It should only be read _once_
per HTTP request as it may be an expensive function depending on the
project size.

This change reduces the number of times the function is called to once
per HTTP request, and passes around the resulting `nowConfig` object to
the functions that require it.

* Fix default values

* Remove unnecessary type narrowing

* Remove one more `getNowConfig()` invocation

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2020-07-02 17:25:07 -07:00
Joe Haddad
e4d2cc704c Add Lockfile to Fix Gatsby Example (#4771)
This adds the Lockfile from Gatsby's official starter to fix deployments.

```
❯ npx gatsby-cli new ~/Desktop/scratch/test-default
❯ cp ~/Desktop/scratch/test-default/yarn.lock examples/gatsby
❯ cd examples/gatsby
❯ yarn
❯ git add examples/gatsby/yarn.lock
```
2020-07-02 21:06:44 +00:00
Joe Haddad
38db720586 Regenerate yarn.lock file (#4769) 2020-07-02 11:20:35 -07:00
Joe Haddad
c26c7886be [next] Skip Lambda Deployment for Static Sites (#4748) 2020-07-02 11:51:02 -04:00
JJ Kasper
b0e5d308ca [next] Add additiontal test cases for basePath support (#4747)
This adds some additional test cases for `basePath` support in Next.js to ensure it is working properly with `@vercel/next`
2020-07-02 09:40:15 +00:00
JJ Kasper
609b98cc73 Publish Canary
- vercel@19.1.2-canary.16
 - @vercel/next@2.6.8-canary.6
2020-07-01 14:46:28 -05:00
JJ Kasper
e0ec6c792b [next] Re-enable shared lambdas by default (#4757)
This re-enables the shared lambdas optimization by default and also adds additional tests to ensure that when a `now.json` or `vercel.json` contains either `routes` or `functions` configs the shared lambda optimization is disabled. 

Additional test deployments done:

- minimal `now.json` with `builds` config [deploy](https://shared-lambdas-tests-d646fsqju.vercel.app)
- `now.json` with `functions` config [deploy](https://shared-lambdas-tests-ahnuosp4s.vercel.app)
- `now.json` with `routes` config [deploy](https://shared-lambdas-tests-gulam3jda.vercel.app)
- minimal `vercel.json` with `builds` config [deploy](https://shared-lambdas-tests-7ic7wzirs.vercel.app)
- `vercel.json` with `functions` config [deploy](https://shared-lambdas-tests-7ic7wzirs.vercel.app)
- `vercel.json` with `routes` config [deploy](https://shared-lambdas-tests-rja2391tq.vercel.app)
2020-07-01 19:44:09 +00:00
Nathan Rajlich
b29db2fd1d [cli] Pin @vercel/static-build to v0.17.5-canary.0 (#4751)
It got de-synced in fa0f1b90b4.
2020-07-01 10:59:22 -07:00
JJ Kasper
b604ced99d Publish Canary
- vercel@19.1.2-canary.15
 - @vercel/next@2.6.8-canary.5
2020-07-01 10:53:18 -05:00
JJ Kasper
b7fd69517e [next] Fix dynamic route mapping with shared lambdas (#4740)
This fixes mapping dynamic routes to their shared lambdas failing from the `dynamicPageLambdaRoute` not being injected directly after the dynamic route due to dynamic routes now containing a `query` which caused the route lookup to fail. 

This is resolved by making sure to parse the pathname while injecting the `dynamicPageLambdaRoute` so the route can be looked up correctly. This also adds additional test cases to prevent regressing on this along with updating existing fixtures for custom routes being de-experimentalized
2020-07-01 07:30:41 +00:00
Nathan Rajlich
4c821a6fb5 Publish Canary
- vercel@19.1.2-canary.14
 - @vercel/node@1.7.2-canary.1
 - @vercel/static-build@0.17.5-canary.0
2020-06-30 16:27:46 -07:00
Nathan Rajlich
5c4fb319af [cli] Revert "Remove caching of vercel.json config in vc dev" (#4749)
This reverts commit ffb98781f1 (#4697),
because it was realized that `vc dev` reads this configuration file many
times per HTTP request, causing the server to feel extremely slow.

Reverting this optimization for now until the over-reading issue is
addressed.
2020-06-30 16:26:56 -07:00
Nathan Rajlich
fbe9ea0750 [node] Set the TypeScript "target" in vc dev (#4728)
Fixes: https://github.com/vercel/vercel/discussions/4724
2020-06-30 16:07:04 -07:00
Andy Bitz
fa0f1b90b4 Publish Stable 2020-06-30 23:33:47 +02:00
Andy Bitz
2daa0e28d3 Publish Canary
- @vercel/frameworks@0.0.16-canary.0
 - vercel@19.1.2-canary.13
 - @vercel/static-build@0.17.4-canary.1
2020-06-30 13:21:02 +02:00
Andy
48358b4986 [@vercel/build-utils] Cache .cache for Eleventy (#4743) 2020-06-30 12:54:44 +02:00
Steven
c59f44a63b [frameworks] Fix build command placeholder nuxt generate (#4737)
The Nuxt placeholder was wrong, it should be `nuxt generate` like the build command here: ca27864201/packages/now-static-build/src/frameworks.ts (L516)
2020-06-29 11:59:34 -04:00
Joe Haddad
ca27864201 Update "description" in package.json for Vercel (#4735) 2020-06-28 22:05:30 -07:00
Steven
6c81a87338 Publish Canary
- vercel@19.1.2-canary.12
 - @vercel/static-build@0.17.4-canary.0
2020-06-27 01:02:10 -04:00
Steven
a7bef9387b [static-build] Fix error handling for unexpected output directory (#4727)
This PR improves the error handling when a zero config framework has an unexpected output directory.

Previously, setting a Docusaurus 2.0 build command to `docusaurus build && mv build foo` would fail with the following:

```
Error: ENOENT: no such file or directory, scandir '/vercel/514ce14b/build'
```

With this PR, the error message will show the expected:

```
Error: No Output Directory named "build" found after the Build completed. You can configure the Output Directory in your project settings. Learn more: https://vercel.com/docs/v2/platform/frequently-asked-questions#missing-public-directory
```

I also changed the usage of [`promisify(fs)`](https://nodejs.org/docs/latest-v10.x/api/util.html#util_util_promisify_original) to [`fs.promises`](https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_promises_api) which is available in Node 10 or newer.

Lastly, I updated the test suite to check if the correct error message is returned for builds we expect to fail.
2020-06-26 23:56:45 -04:00
Nathan Rajlich
65d6c5e1f4 [cli] Use the configured "Output Directory" from project's settings in vc dev (#4715)
Previously, when a project has a specific "Output Directory" configured
in the project settings page, it was not being correctly considered when
using `vercel dev`.

The main fix here is passing in the full project settings object
(including the `outputDirectory`) to the `detectBuilders()` function.

Also cleaned up a few types and updated the error message that was
previously being rendered to use a short link.
2020-06-26 16:07:07 -07:00
Steven
c09355fdb3 Publish Canary
- vercel@19.1.2-canary.11
 - @vercel/client@8.1.1-canary.1
2020-06-26 13:11:05 -04:00
Steven
d9ac4c45e1 [cli] Fix vc dev serving pure static dot files (#4714)
Fixes ch1233 and discussion #4475
2020-06-26 17:10:11 +00:00
nkzawa
c2ff95714f Publish Canary
- @vercel/build-utils@2.4.1-canary.1
 - vercel@19.1.2-canary.10
 - @vercel/client@8.1.1-canary.0
 - @vercel/go@1.1.3-canary.1
 - @vercel/next@2.6.8-canary.4
2020-06-26 13:47:50 +09:00
Naoyuki Kanezawa
a51feb7a62 add source prop when deploying (#4701) 2020-06-26 13:44:31 +09:00
JJ Kasper
ff10918230 [next] Memoize lstating files (#4712)
Closes: https://github.com/vercel/next.js/issues/14429
2020-06-25 22:55:09 +00:00
Nathan Rajlich
04bea1e3cd [go] Implement startDevServer() function (#4662)
Due to Go's peculiar package importing structure, there's unfortunately no way to _directly_ invoke a Go serverless file, so the approach for this `startDevServer()` function is:

 * Create a temp directory in `.vercel/cache`
 * Run the `analyze` Go program on the entrypoint file to determine the `functionName`
 * Copy the entrypoint file into the temp directory, while modifying it to use `package main`
 * Copy the `dev-server.go` file into the temp directory, replacing the placeholder function name with the `functionName` retrieved from the analysis step from before
 * Execute `go run $tmp_dir` to spawn the Go HTTP server on an ephemeral port
 * Return the Go process id and port number for `vercel dev` to proxy to
 * After the Go process has exited, delete the temp directory
2020-06-24 19:50:00 +00:00
Milan Felix Šulc
bc5e5e8a9c [tests] Change now-php to vercel-php (#4710) 2020-06-24 11:58:17 -07:00
JJ Kasper
2e647175f5 Publish Canary
- vercel@19.1.2-canary.9
 - @vercel/next@2.6.8-canary.3
2020-06-24 10:20:04 -05:00
JJ Kasper
1a4e1d2fdd [next] Update revalidate tests and correct shared lambdas revalidate (#4704)
This adds more fine grained tests for our revalidate behavior to ensure pages are actually being updated instead of only checking the headers, it also corrects page lookups failing with shared lambdas enabled for dynamic pages using revalidate. 

Closes: https://github.com/vercel/next.js/issues/14497
2020-06-24 14:53:43 +00:00
Steven
49e2274d81 Publish Canary
- @vercel/build-utils@2.4.1-canary.0
 - vercel@19.1.2-canary.8
2020-06-24 09:24:46 -04:00
Steven
9af3938544 [cli][build-utils] Refactor ajv error message (#4705)
This PR is a follow up to #4694 so we can use this same helper function in the API.

I tried to follow the existing error message format so that the API can use a different prefix than the CLI.

The API currently returns a 400 with `Invalid request` when a Git deploy fails validation:

![api-comment](https://user-images.githubusercontent.com/229881/85466548-1c140b00-b578-11ea-9bed-1eb14df2685a.png)
2020-06-24 13:23:51 +00:00
Nathan Rajlich
7b5bf061c2 Publish Canary
- vercel@19.1.2-canary.7
 - @vercel/go@1.1.3-canary.0
2020-06-22 19:12:28 -07:00
Nathan Rajlich
ffb98781f1 [cli] Remove caching of vercel.json config in vc dev (#4697)
Since the filesystem watcher may be slow, it's actually faster and more
reliable to simply re-read the `vercel.json` configuration for every
HTTP request. This also simplifies the logic as an added benefit.

Some `sleep()` calls are removed from relevant tests that were
previously necessary due to the lag in the filesystem watcher.
2020-06-22 23:45:23 +00:00
Steven
3411fcbb68 Publish Canary
- vercel@19.1.2-canary.6
2020-06-22 18:42:23 -04:00
Steven
55cfd33338 [cli] Improve validation error message for vercel.json (#4694)
This PR improves the validation error message when the user has an invalid `vercel.json` file.

Previously, the error message did not account for nested properties so `{"foo": "will error"}` looked fine because it would mention there is an additional property `foo`. However, the error message for `{ "routes": [{ "foo": "will error" }] }` did not mention anything about `routes` when it explaining there was an additional property `foo`. This became more apparent as we added nested properties for `rewrites` and `redirects` (see tests in this PR).

This PR also adds suggestions for common mistakes such as `src` vs `source`.
2020-06-22 22:38:13 +00:00
JJ Kasper
93a9e5bed3 Publish Canary
- vercel@19.1.2-canary.5
 - @vercel/next@2.6.8-canary.2
2020-06-22 16:38:23 -05:00
JJ Kasper
b454021234 [next] Update tests to run against latest canary (#4682)
In the latest canary of Next.js pages are no longer nested under the `BUILD_ID` folder and instead are nested under a hash for the page bundle content. To prevent these tests from breaking too often from changes in canary this updates to locate the page bundle using the `buildManifest`. This also updates our latest SSG fixture to test against the latest canary to help ensure the feature doesn't break with a new canary release
2020-06-22 21:31:37 +00:00
Nathan Rajlich
bb705cd091 [docs] Refactor "Developing a Runtime" docs and add startDevServer() (#4675)
Co-authored-by: Steven <steven@ceriously.com>
2020-06-22 13:41:10 -07:00
Naoyuki Kanezawa
0986f4bcb6 [cli] Do not confirm vc env pull overwrite if created by CLI (#4678)
Append `# Created by Vercel CLI` to the head of `.env` file and automatically overwrite the file if it's there next time without confirmation.

https://app.clubhouse.io/vercel/story/316
2020-06-22 18:47:34 +00:00
Steven
83f77223aa Publish Canary
- vercel@19.1.2-canary.4
2020-06-19 16:23:32 -04:00
Steven
effda1fa6c [cli] Fix error message when no internet connectivity (#4687)
This PR fixes the error message when the client does not have internet connectivity or perhaps DNS is misconfigured such that the hostname cannot be resolved.
2020-06-19 15:57:26 -04:00
Steven
2ab6a7ef0c Publish Canary
- vercel@19.1.2-canary.3
 - @vercel/next@2.6.8-canary.1
2020-06-18 19:57:28 -04:00
Jean Helou
200bf5e996 [next] Fix nextjs routes in vercel dev (#4510)
This PR fixes #4239 where using `vercel dev` to work on monorepos where
the Next.js app is not in the topmost directory fails to correctly route
to dynamic pages.
After investigating the devServer router, @styfle prompted me to
investigate the @vercel/next builder. He also suggested restricting
`check` to be false only when running in `now dev`.

Co-authored-by: Steven <steven@ceriously.com>
2020-06-18 19:28:53 -04:00
Steven
94ab2512e9 Publish Canary
- vercel@19.1.2-canary.2
 - @vercel/ruby@1.2.3-canary.0
2020-06-18 17:19:29 -04:00
Jared White
da3207278e [ruby] Fix for UTF-8 responses in Ruby functions (#4593)
There's an unexpected string encoding issue with `Net::HTTP`, so this is a workaround. Further details:
https://bugs.ruby-lang.org/issues/15517

Co-authored-by: Steven <steven@ceriously.com>
2020-06-18 17:12:28 -04:00
nkzawa
8e10a82b43 Publish Canary
- vercel@19.1.2-canary.1
2020-06-18 20:24:49 +09:00
Naoyuki Kanezawa
d7731d191b Fix to not render no token error, prompt login instead (#4659)
When `auth.json` exists but no `token` property exists in it, we currently render error like the following screenshot.
<img width="488" alt="Screen Shot 2020-06-15 at 21 32 55" src="https://user-images.githubusercontent.com/775227/84657782-cd4eeb80-af4f-11ea-901d-2ad4b52b6667.png">

This PR fixes to prompt login instead.
<img width="994" alt="Screen Shot 2020-06-15 at 21 28 09" src="https://user-images.githubusercontent.com/775227/84657706-aa243c00-af4f-11ea-915e-4ada7de9c467.png">
2020-06-17 17:20:08 +00:00
Steven
0f5f99e667 Publish Canary
- vercel@19.1.2-canary.0
 - @vercel/next@2.6.8-canary.0
 - @vercel/node@1.7.2-canary.0
2020-06-16 17:41:45 -04:00
Steven
93a7831943 [node][next] Bump node-file-trace to 0.6.5 (#4667)
Bump `node-file-trace` to version [0.6.5](https://github.com/vercel/node-file-trace/releases/tag/0.6.5) to fix a webpack wrappers bug
2020-06-16 21:41:13 +00:00
Steven
0eacbeae11 Publish Stable
- vercel@19.1.1
 - @vercel/next@2.6.7
 - @vercel/node@1.7.1
 - @vercel/static-build@0.17.3
2020-06-16 13:09:42 -04:00
Steven
e50417dc47 Publish Canary
- vercel@19.1.1-canary.4
 - @vercel/static-build@0.17.3-canary.0
2020-06-16 08:55:29 -04:00
Paco
4840a25d30 [static-build] Apply Gatsby default caching routes automatically (#4645)
CH-702
Fixes #3331

If the file generated by `gatsby-plugin-now` does not exist, we'll set up these routes automatically.
2020-06-15 22:15:14 +00:00
Steven
785e91979d Publish Canary
- vercel@19.1.1-canary.3
 - @vercel/next@2.6.7-canary.1
 - @vercel/node@1.7.1-canary.1
2020-06-15 16:46:03 -04:00
Steven
7a776c54b8 [node][next] Bump node-file-trace to 0.6.4 (#4617)
Bump node-file-trace to fix a webpack tracing bug that looks like the following:


```
TypeError: Cannot read property 'type' of null
    at handleWrappers (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:12763:58)
    at module.exports.447.module.exports (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:14674:3)
    at Job.emitDependency (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11730:40)
    at /vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11755:20
    at async Promise.all (index 9)
    at async Job.emitDependency (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11736:5)
    at async Promise.all (index 1)
    at async Object.module.exports.328.module.exports [as default] (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11514:3)
    at async Object.module.exports.178.exports.build (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:6076:69)
    at async buildStep (/var/task/sandbox-worker.js:20407:20)
```

- [0.6.2](https://github.com/vercel/node-file-trace/releases/tag/0.6.2)
- [0.6.3](https://github.com/vercel/node-file-trace/releases/tag/0.6.3) 
- [0.6.4](https://github.com/vercel/node-file-trace/releases/tag/0.6.4)

Depends on #4355
2020-06-15 20:45:15 +00:00
JJ Kasper
997031c53b [next] Update handling experimental basePath (#3791)
As mentioned by @dav-is we can prefix the outputs with the `basePath` instead of using a rewrite so that we make sure to 404 when the basePath isn't prefixed on the output. This behavior is also matched in Next.js with [this PR](https://github.com/zeit/next.js/pull/9988). 

x-ref: https://github.com/zeit/now/pull/3478
2020-06-15 17:43:37 +00:00
Steven
fdee03a599 Publish Canary
- vercel@19.1.1-canary.2
2020-06-15 12:38:11 -04:00
Steven
c5a93ecdad [cli] Fix vc dev proxy to upstream frontend dev server (#4644)
This PR fixes a longstanding issue introduced in #3673 that prevents routing properties from applying to the framework's upstream dev server.

This mimic's the older proxy logic used in build matches here: 5035fa537f/packages/now-cli/src/util/dev/server.ts (L1535-L1539)

- Related to #3777
- Related to #4510
2020-06-15 16:37:08 +00:00
JJ Kasper
5a9391b7ce Publish Canary
- vercel@19.1.1-canary.1
 - @vercel/next@2.6.7-canary.0
2020-06-15 10:20:38 -05:00
JJ Kasper
99e49473b8 [next] Update dynamic route named regexes and route keys (#4355)
This updates to leverage changes from https://github.com/zeit/next.js/pull/12801 which resolves invalid named regexes being used when the segments contain non-word characters e.g. `/[hello-world]`. 

Failing page names have also been added to the `23-custom-routes-verbose` fixture. Since the routeKeys aren't applied for dynamic routes in this PR until the routes-manifest version is bumped in the latest canary of Next.js the added test cases will be passing now and should be re-run to ensure passing after a new canary of Next.js is released with the routes-manifest version bump
2020-06-15 15:15:38 +00:00
Nathan Rajlich
de1cc6f9a7 [cli] Add a test case for resolving default "typescript" version in @vercel/node (#4656)
Adds a test case for #4655 (it got auto-merged too quickly).
2020-06-14 21:52:33 +00:00
Nathan Rajlich
08eedd8f34 Publish Canary
- vercel@19.1.1-canary.0
 - @vercel/node@1.7.1-canary.0
2020-06-14 14:00:04 -07:00
Nathan Rajlich
5021a71a8e [node] Don't resolve "typescript" from the dist dir (#4655)
On Node 10, the `require.resolve()` with "paths" does not return the
proper value relative to the `node_modules` directory. To wit:

```
$ node -v
v10.16.3

$ node -p "require.resolve('typescript', { paths: [process.cwd()] })"
/Users/nrajlich/Code/vercel/vercel/packages/now-node/dist/typescript.js

$ node -v
v14.4.0

$ node -p "require.resolve('typescript', { paths: [process.cwd()] })"
/Users/nrajlich/Code/vercel/vercel/node_modules/typescript/lib/typescript.js
```

(**Note:** cwd when running these commands is the `dist` dir of `@vercel/node`)

So the solution is to just let `require.resolve()` throw an error so the
default string "typescript" is used instead of a resolved absolute path.
2020-06-14 20:47:23 +00:00
Max Leiter
56671d7c2f [tests] Don't revoke VERCEL_TOKEN after tests run (#4643)
`VERCEL_TOKEN` will no longer be invalidated during tests

Story: https://app.clubhouse.io/vercel/story/2281
2020-06-12 22:49:37 +00:00
Steven
5035fa537f [cli] Add test for gatsby cache (#4447)
This PR adds a E2E CLI test to ensure that the Gatsby example deploys correctly and that the second deployment has the proper cached directories.

Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
2020-06-12 16:51:55 -04:00
197 changed files with 31882 additions and 1527 deletions

View File

@@ -19,6 +19,11 @@ indent_style = space
[*.py]
indent_size = 4
[*.go]
indent_style = tab
indent_size = 4
tab_width = 4
[*.asm]
indent_size = 8

View File

@@ -1,10 +1,33 @@
# Runtime Developer Reference
The following page is a reference for how to create a Runtime using the available Runtime API.
The following page is a reference for how to create a Runtime by implementing
the Runtime API interface.
A Runtime is an npm module that exposes a `build` function and optionally an `analyze` function and `prepareCache` function.
Official Runtimes are published to [npmjs.com](https://npmjs.com) as a package and referenced in the `use` property of the `vercel.json` configuration file.
However, the `use` property will work with any [npm install argument](https://docs.npmjs.com/cli/install) such as a git repo url which is useful for testing your Runtime.
A Runtime is an npm module that implements the following interface:
```typescript
interface Runtime {
version: number;
build: (options: BuildOptions) => Promise<BuildResult>;
analyze?: (options: AnalyzeOptions) => Promise<string>;
prepareCache?: (options: PrepareCacheOptions) => Promise<CacheOutputs>;
shouldServe?: (options: ShouldServeOptions) => Promise<boolean>;
startDevServer?: (
options: StartDevServerOptions
) => Promise<StartDevServerResult>;
}
```
The `version` property and the `build()` function are the only _required_ fields.
The rest are optional extensions that a Runtime _may_ implement in order to
enhance functionality. These functions are documented in more detail below.
Official Runtimes are published to [the npm registry](https://npmjs.com) as a package and referenced in the `use` property of the `vercel.json` configuration file.
> **Note:** The `use` property in the `builds` array will work with any [npm
> install argument](https://docs.npmjs.com/cli/install) such as a git repo URL,
> which is useful for testing your Runtime. Alternatively, the `functions` property
> requires that you specify a specifc tag published to npm, for stability purposes.
See the [Runtimes Documentation](https://vercel.com/docs/runtimes) to view example usage.
@@ -16,146 +39,170 @@ A **required** exported constant that decides which version of the Runtime API t
The latest and suggested version is `3`.
### `analyze`
**Example:**
An **optional** exported function that returns a unique fingerprint used for the purpose of [build de-duplication](https://vercel.com/docs/v2/platform/deployments#deduplication). If the `analyze` function is not supplied, a random fingerprint is assigned to each build.
```js
export analyze({
files: Files,
entrypoint: String,
workPath: String,
config: Object
}) : String fingerprint
```typescript
export const version = 3;
```
If you are using TypeScript, you should use the following types:
### `build()`
```ts
import { AnalyzeOptions } from '@vercel/build-utils'
A **required** exported function that returns a Serverless Function.
export analyze(options: AnalyzeOptions) {
return 'fingerprint goes here'
> What's a Serverless Function? Read about [Serverless Functions](https://vercel.com/docs/v2/serverless-functions/introduction) to learn more.
**Example:**
```typescript
import { BuildOptions, createLambda } from '@vercel/build-utils';
export async function build(options: BuildOptions) {
// Build the code here…
const lambda = createLambda(/* … */);
return {
output: lambda,
watch: [
// Dependent files to trigger a rebuild in `vercel dev` go here…
],
routes: [
// If your Runtime needs to define additional routing, define it here…
],
};
}
```
### `build`
### `analyze()`
A **required** exported function that returns a [Serverless Function](#serverless-function).
An **optional** exported function that returns a unique fingerprint used for the
purpose of [build
de-duplication](https://vercel.com/docs/v2/platform/deployments#deduplication).
If the `analyze()` function is not supplied, then a random fingerprint is
assigned to each build.
What's a Serverless Function? Read about [Serverless Functions](https://vercel.com/docs/v2/serverless-functions/introduction) to learn more.
**Example:**
```js
build({
files: Files,
entrypoint: String,
workPath: String,
config: Object,
meta?: {
isDev?: Boolean,
requestPath?: String,
filesChanged?: Array<String>,
filesRemoved?: Array<String>
}
}) : {
watch?: Array<String>,
output: Lambda,
routes?: Object
```typescript
import { AnalyzeOptions } from '@vercel/build-utils';
export async function analyze(options: AnalyzeOptions) {
// Do calculations to generate a fingerprint based off the source code here…
return 'fingerprint goes here';
}
```
If you are using TypeScript, you should use the following types:
### `prepareCache()`
```ts
import { BuildOptions } from '@vercel/build-utils'
An **optional** exported function that is executed after [`build()`](#build) is
completed. The implementation should return an object of `File`s that will be
pre-populated in the working directory for the next build run in the user's
project. An example use-case is that `@vercel/node` uses this function to cache
the `node_modules` directory, making it faster to install npm dependencies for
future builds.
export build(options: BuildOptions) {
// Build the code here
**Example:**
```typescript
import { PrepareCacheOptions } from '@vercel/build-utils';
export async function prepareCache(options: PrepareCacheOptions) {
// Create a mapping of file names and `File` object instances to cache here…
return {
output: {
'path-to-file': File,
'path-to-lambda': Lambda
},
watch: [],
routes: {}
}
'path-to-file': File,
};
}
```
### `prepareCache`
### `shouldServe()`
An **optional** exported function that is equivalent to [`build`](#build), but it executes the instructions necessary to prepare a cache for the next run.
An **optional** exported function that is only used by `vercel dev` in [Vercel
CLI](https://vercel.com/download) and indicates whether a
[Runtime](https://vercel.com/docs/runtimes) wants to be responsible for responding
to a certain request path.
```js
prepareCache({
files: Files,
entrypoint: String,
workPath: String,
cachePath: String,
config: Object
}) : Files cacheOutput
```
**Example:**
If you are using TypeScript, you can import the types for each of these functions by using the following:
```typescript
import { ShouldServeOptions } from '@vercel/build-utils';
```ts
import { PrepareCacheOptions } from '@vercel/build-utils'
export async function shouldServe(options: ShouldServeOptions) {
// Determine whether or not the Runtime should respond to the request path here…
export prepareCache(options: PrepareCacheOptions) {
return { 'path-to-file': File }
return options.requestPath === options.entrypoint;
}
```
### `shouldServe`
If this function is not defined, Vercel CLI will use the [default implementation](https://github.com/vercel/vercel/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
An **optional** exported function that is only used by `vercel dev` in [Vercel CLI](https:///download) and indicates whether a [Runtime](https://vercel.com/docs/runtimes) wants to be responsible for building a certain request path.
### `startDevServer()`
```js
shouldServe({
entrypoint: String,
files: Files,
config: Object,
requestPath: String,
workPath: String
}) : Boolean
```
An **optional** exported function that is only used by `vercel dev` in [Vercel
CLI](https://vercel.com/download). If this function is defined, Vercel CLI will
**not** invoke the `build()` function, and instead invoke this function for every
HTTP request. It is an opportunity to provide an optimized development experience
rather than going through the entire `build()` process that is used in production.
If you are using TypeScript, you can import the types for each of these functions by using the following:
This function is invoked _once per HTTP request_ and is expected to spawn a child
process which creates an HTTP server that will execute the entrypoint code when
an HTTP request is received. This child process is _single-serve_ (only used for
a single HTTP request). After the HTTP response is complete, `vercel dev` sends
a shut down signal to the child process.
```ts
import { ShouldServeOptions } from '@vercel/build-utils'
The `startDevServer()` function returns an object with the `port` number that the
child process' HTTP server is listening on (which should be an [ephemeral
port](https://stackoverflow.com/a/28050404/376773)) as well as the child process'
Process ID, which `vercel dev` uses to send the shut down signal to.
export shouldServe(options: ShouldServeOptions) {
return Boolean
> **Hint:** To determine which ephemeral port the child process is listening on,
> some form of [IPC](https://en.wikipedia.org/wiki/Inter-process_communication) is
> required. For example, in `@vercel/go` the child process writes the port number
> to [_file descriptor 3_](https://en.wikipedia.org/wiki/File_descriptor), which is read by the `startDevServer()` function
> implementation.
It may also return `null` to opt-out of this behavior for a particular request
path or entrypoint.
**Example:**
```typescript
import { spawn } from 'child_process';
import { StartDevServerOptions } from '@vercel/build-utils';
export async function startDevServer(options: StartDevServerOptions) {
// Create a child process which will create an HTTP server.
//
// Note: `my-runtime-dev-server` is an example dev server program name.
// Your implementation will spawn a different program specific to your runtime.
const child = spawn('my-runtime-dev-server', [options.entrypoint], {
stdio: ['ignore', 'inherit', 'inherit', 'pipe'],
});
// In this example, the child process will write the port number to FD 3…
const portPipe = child.stdio[3];
const childPort = await new Promise(resolve => {
portPipe.setEncoding('utf8');
portPipe.once('data', data => {
resolve(Number(data));
});
});
return { pid: child.pid, port: childPort };
}
```
If this method is not defined, Vercel CLI will default to [this function](https://github.com/vercel/vercel/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
### Runtime Options
The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCache`](#preparecache) receive one argument with the following properties.
**Properties:**
- `files`: All source files of the project as a [Files](#files) data structure.
- `entrypoint`: Name of entrypoint file for this particular build job. Value `files[entrypoint]` is guaranteed to exist and be a valid [File](#files) reference. `entrypoint` is always a discrete file and never a glob, since globs are expanded into separate builds at deployment time.
- `workPath`: A writable temporary directory where you are encouraged to perform your build process. This directory will be populated with the restored cache from the previous run (if any) for [`analyze`](#analyze) and [`build`](#build).
- `cachePath`: A writable temporary directory where you can build a cache for the next run. This is only passed to `prepareCache`.
- `config`: An arbitrary object passed from by the user in the [Build definition](#defining-the-build-step) in `vercel.json`.
## Examples
Check out our [Node.js Runtime](https://github.com/vercel/vercel/tree/master/packages/now-node), [Go Runtime](https://github.com/vercel/vercel/tree/master/packages/now-go), [Python Runtime](https://github.com/vercel/vercel/tree/master/packages/now-python) or [Ruby Runtime](https://github.com/vercel/vercel/tree/master/packages/now-ruby) for examples of how to build one.
## Technical Details
### Execution Context
A [Serverless Function](https://vercel.com/docs/v2/serverless-functions/introduction) is created where the Runtime logic is executed. The lambda is run using the Node.js 8 runtime. A brand new sandbox is created for each deployment, for security reasons. The sandbox is cleaned up between executions to ensure no lingering temporary files are shared from build to build.
- Runtimes are executed in a Linux container that closely matches the Servereless Function runtime environment.
- The Runtime code is executed using Node.js version **12.x**.
- A brand new sandbox is created for each deployment, for security reasons.
- The sandbox is cleaned up between executions to ensure no lingering temporary files are shared from build to build.
All the APIs you export ([`analyze`](#analyze), [`build`](#build) and [`prepareCache`](#preparecache)) are not guaranteed to be run in the same process, but the filesystem we expose (e.g.: `workPath` and the results of calling [`getWriteableDirectory`](#getWriteableDirectory) ) is retained.
All the APIs you export ([`analyze()`](#analyze), [`build()`](#build),
[`prepareCache()`](#preparecache), etc.) are not guaranteed to be run in the
same process, but the filesystem we expose (e.g.: `workPath` and the results
of calling [`getWritableDirectory`](#getWritableDirectory) ) is retained.
If you need to share state between those steps, use the filesystem.
@@ -173,11 +220,11 @@ The env and secrets specified by the user as `build.env` are passed to the Runti
When you publish your Runtime to npm, make sure to not specify `@vercel/build-utils` (as seen below in the API definitions) as a dependency, but rather as part of `peerDependencies`.
## Types
## `@vercel/build-utils` Types
### `Files`
```ts
```typescript
import { File } from '@vercel/build-utils';
type Files = { [filePath: string]: File };
```
@@ -188,7 +235,7 @@ When used as an input, the `Files` object will only contain `FileRefs`. When `Fi
An example of a valid output `Files` object is:
```json
```javascript
{
"index.html": FileRef,
"api/index.js": Lambda
@@ -199,7 +246,7 @@ An example of a valid output `Files` object is:
This is an abstract type that can be imported if you are using TypeScript.
```ts
```typescript
import { File } from '@vercel/build-utils';
```
@@ -211,71 +258,71 @@ Valid `File` types include:
### `FileRef`
```ts
```typescript
import { FileRef } from '@vercel/build-utils';
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract file instance stored in our platform, based on the file identifier string (its checksum). When a `Files` object is passed as an input to `analyze` or `build`, all its values will be instances of `FileRef`.
This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract file instance stored in our platform, based on the file identifier string (its checksum). When a `Files` object is passed as an input to `analyze` or `build`, all its values will be instances of `FileRef`.
**Properties:**
- `mode : Number` file mode
- `digest : String` a checksum that represents the file
- `mode: Number` file mode
- `digest: String` a checksum that represents the file
**Methods:**
- `toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
- `toStream(): Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileFsRef`
```ts
```typescript
import { FileFsRef } from '@vercel/build-utils';
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in the filesystem that the build process is executing in.
This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in the filesystem that the build process is executing in.
**Properties:**
- `mode : Number` file mode
- `fsPath : String` the absolute path of the file in file system
- `mode: Number` file mode
- `fsPath: String` the absolute path of the file in file system
**Methods:**
- `static async fromStream({ mode : Number, stream : Stream, fsPath : String }) : FileFsRef` creates an instance of a [FileFsRef](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from `Stream`, placing file at `fsPath` with `mode`
- `toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
- `static async fromStream({ mode: Number, stream: Stream, fsPath: String }): FileFsRef` creates an instance of a [FileFsRef](#FileFsRef) from `Stream`, placing file at `fsPath` with `mode`
- `toStream(): Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileBlob`
```ts
```typescript
import { FileBlob } from '@vercel/build-utils';
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in memory.
This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in memory.
**Properties:**
- `mode : Number` file mode
- `data : String | Buffer` the body of the file
- `mode: Number` file mode
- `data: String | Buffer` the body of the file
**Methods:**
- `static async fromStream({ mode : Number, stream : Stream }) :FileBlob` creates an instance of a [FileBlob](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from [`Stream`](https://nodejs.org/api/stream.html) with `mode`
- `toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
- `static async fromStream({ mode: Number, stream: Stream }): FileBlob` creates an instance of a [FileBlob](#FileBlob) from [`Stream`](https://nodejs.org/api/stream.html) with `mode`
- `toStream(): Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `Lambda`
```ts
```typescript
import { Lambda } from '@vercel/build-utils';
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), called a Serverless Function, that can be created by supplying `files`, `handler`, `runtime`, and `environment` as an object to the [`createLambda`](#createlambda) helper. The instances of this class should not be created directly. Instead, invoke the [`createLambda`](#createlambda) helper function.
This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents a Serverless Function. An instance can be created by supplying `files`, `handler`, `runtime`, and `environment` as an object to the [`createLambda`](#createlambda) helper. The instances of this class should not be created directly. Instead, invoke the [`createLambda`](#createlambda) helper function.
**Properties:**
- `files : Files` the internal filesystem of the lambda
- `handler : String` path to handler file and (optionally) a function name it exports
- `runtime : LambdaRuntime` the name of the lambda runtime
- `environment : Object` key-value map of handler-related (aside of those passed by user) environment variables
- `files: Files` the internal filesystem of the lambda
- `handler: String` path to handler file and (optionally) a function name it exports
- `runtime: LambdaRuntime` the name of the lambda runtime
- `environment: Object` key-value map of handler-related (aside of those passed by user) environment variables
### `LambdaRuntime`
@@ -291,15 +338,15 @@ This is an abstract enumeration type that is implemented by one of the following
- `ruby2.5`
- `provided`
## JavaScript API
## `@vercel/build-utils` Helper Functions
The following is exposed by `@vercel/build-utils` to simplify the process of writing Runtimes, manipulating the file system, using the above types, etc.
### `createLambda`
### `createLambda()`
Signature: `createLambda(Object spec) : Lambda`
Signature: `createLambda(Object spec): Lambda`
```ts
```typescript
import { createLambda } from '@vercel/build-utils';
```
@@ -316,29 +363,33 @@ await createLambda({
});
```
### `download`
### `download()`
Signature: `download() : Files`
Signature: `download(): Files`
```ts
```typescript
import { download } from '@vercel/build-utils';
```
This utility allows you to download the contents of a [`Files`](#files) data structure, therefore creating the filesystem represented in it.
This utility allows you to download the contents of a [`Files`](#files) data
structure, therefore creating the filesystem represented in it.
Since `Files` is an abstract way of representing files, you can think of `download` as a way of making that virtual filesystem _real_.
Since `Files` is an abstract way of representing files, you can think of
`download()` as a way of making that virtual filesystem _real_.
If the **optional** `meta` property is passed (the argument for [build](#build)), only the files that have changed are downloaded. This is decided using `filesRemoved` and `filesChanged` inside that object.
If the **optional** `meta` property is passed (the argument for
[`build()`](#build)), only the files that have changed are downloaded.
This is decided using `filesRemoved` and `filesChanged` inside that object.
```js
await download(files, workPath, meta);
```
### `glob`
### `glob()`
Signature: `glob() : Files`
Signature: `glob(): Files`
```ts
```typescript
import { glob } from '@vercel/build-utils';
```
@@ -355,21 +406,21 @@ exports.build = ({ files, workPath }) => {
}
```
### `getWriteableDirectory`
### `getWritableDirectory()`
Signature: `getWriteableDirectory() : String`
Signature: `getWritableDirectory(): String`
```ts
import { getWriteableDirectory } from '@vercel/build-utils';
```typescript
import { getWritableDirectory } from '@vercel/build-utils';
```
In some occasions, you might want to write to a temporary directory.
### `rename`
### `rename()`
Signature: `rename(Files) : Files`
Signature: `rename(Files, Function): Files`
```ts
```typescript
import { rename } from '@vercel/build-utils';
```

View File

@@ -0,0 +1,4 @@
module.exports = {
presets: ["next/babel"],
plugins: [],
}

View File

@@ -0,0 +1,10 @@
module.exports = {
extends: ["react-app", "plugin:jsx-a11y/recommended"],
plugins: ["jsx-a11y"],
rules: {
"import/no-anonymous-default-export": "error",
"import/no-webpack-loader-syntax": "off",
"react/react-in-jsx-scope": "off", // React is always in scope with Blitz
"jsx-a11y/anchor-is-valid": "off", //Doesn't play well with Blitz/Next <Link> usage
},
}

56
examples/blitzjs/.gitignore vendored Normal file
View File

@@ -0,0 +1,56 @@
# dependencies
node_modules
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.pnp.*
.npm
web_modules/
# blitz
/.blitz/
/.next/
*.sqlite
.now
.vercel
.blitz-console-history
blitz-log.log
# misc
.DS_Store
# local env files
.env
.envrc
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Testing
coverage
*.lcov
.nyc_output
lib-cov
# Caches
*.tsbuildinfo
.eslintcache
.node_repl_history
.yarn-integrity
# Serverless directories
.serverless/
# Stores VSCode versions used for testing VSCode extensions
.vscode-test

1
examples/blitzjs/.npmrc Normal file
View File

@@ -0,0 +1 @@
save-exact=true

View File

@@ -0,0 +1,6 @@
.gitkeep
.env
*.ico
*.lock
db/migrations

View File

@@ -0,0 +1,21 @@
![Blitz Logo](https://github.com/vercel/vercel/blob/master/packages/frameworks/logos/blitz.svg)
This is a [Blitz.js](https://blitzjs.com/) project bootstrapped with `blitz new`.
## Getting Started
First, run the development server:
```bash
npx blitz start
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
## Learn More
To learn more about Blitz.js, view [Blitzjs.com](https://blitzjs.com)
## Deploy on Vercel
View the [documentation on deploying to Vercel](https://blitzjs.com/docs/deploy-vercel)

View File

View File

@@ -0,0 +1,21 @@
import React from "react"
export default class ErrorBoundary extends React.Component<{
fallback: (error: any) => React.ReactNode
}> {
state = { hasError: false, error: null }
static getDerivedStateFromError(error: any) {
return {
hasError: true,
error,
}
}
render() {
if (this.state.hasError) {
return this.props.fallback(this.state.error)
}
return this.props.children
}
}

View File

View File

@@ -0,0 +1,5 @@
import { AppProps } from "blitz"
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}

View File

@@ -0,0 +1,23 @@
import { Document, Html, DocumentHead, Main, BlitzScript /*DocumentContext*/ } from "blitz"
class MyDocument extends Document {
// Only uncomment if you need to customize this behaviour
// static async getInitialProps(ctx: DocumentContext) {
// const initialProps = await Document.getInitialProps(ctx)
// return {...initialProps}
// }
render() {
return (
<Html lang="en">
<DocumentHead />
<body>
<Main />
<BlitzScript />
</body>
</Html>
)
}
}
export default MyDocument

View File

@@ -0,0 +1,197 @@
import { Head, Link } from "blitz"
const Home = () => (
<div className="container">
<Head>
<title>blitzjs</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div className="logo">
<img src="/logo.png" alt="blitz.js" />
</div>
<p>1. Run this command in your terminal:</p>
<pre>
<code>blitz generate all project name:string</code>
</pre>
<p>2. Then run this command:</p>
<pre>
<code>blitz db migrate</code>
</pre>
<p>
3. Go to{" "}
<Link href="/projects">
<a>/projects</a>
</Link>
</p>
<div className="buttons">
<a
className="button"
href="https://github.com/blitz-js/blitz/blob/master/USER_GUIDE.md?utm_source=blitz-new&utm_medium=app-template&utm_campaign=blitz-new"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
<a
className="button-outline"
href="https://github.com/blitz-js/blitz"
target="_blank"
rel="noopener noreferrer"
>
Github Repo
</a>
<a
className="button-outline"
href="https://slack.blitzjs.com"
target="_blank"
rel="noopener noreferrer"
>
Slack Community
</a>
</div>
</main>
<footer>
<a
href="https://blitzjs.com?utm_source=blitz-new&utm_medium=app-template&utm_campaign=blitz-new"
target="_blank"
rel="noopener noreferrer"
>
Powered by Blitz.js
</a>
</footer>
<style jsx>{`
.container {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
main {
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
main p {
font-size: 1.2rem;
}
footer {
width: 100%;
height: 60px;
border-top: 1px solid #eaeaea;
display: flex;
justify-content: center;
align-items: center;
background-color: #45009d;
}
footer a {
display: flex;
justify-content: center;
align-items: center;
}
footer a {
color: #f4f4f4;
text-decoration: none;
}
.logo {
margin-bottom: 2rem;
}
.logo img {
width: 300px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 0.5rem;
margin-top: 6rem;
}
a.button {
background-color: #6700eb;
padding: 1rem 2rem;
color: #f4f4f4;
text-align: center;
}
a.button:hover {
background-color: #45009d;
}
a.button-outline {
border: 2px solid #6700eb;
padding: 1rem 2rem;
color: #6700eb;
text-align: center;
}
a.button-outline:hover {
border-color: #45009d;
color: #45009d;
}
pre {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
}
code {
font-size: 0.9rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 800px;
margin-top: 3rem;
}
@media (max-width: 600px) {
.grid {
width: 100%;
flex-direction: column;
}
}
`}</style>
<style jsx global>{`
@import url("https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;700&display=swap");
html,
body {
padding: 0;
margin: 0;
font-family: "Libre Franklin", -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
* {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
box-sizing: border-box;
}
`}</style>
</div>
)
export default Home

View File

@@ -0,0 +1,15 @@
module.exports = {
/*
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
return config
},
webpackDevMiddleware: (config) => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config
},
*/
}

View File

@@ -0,0 +1,15 @@
import { PrismaClient } from "@prisma/client"
export * from "@prisma/client"
let prisma: PrismaClient
if (process.env.NODE_ENV === "production") {
prisma = new PrismaClient()
} else {
// Ensure the prisma instance is re-used during hot-reloading
// Otherwise, a new client will be created on every reload
global["prisma"] = global["prisma"] || new PrismaClient()
prisma = global["prisma"]
}
export default prisma

View File

View File

@@ -0,0 +1,27 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource sqlite {
provider = "sqlite"
url = "file:./db.sqlite"
}
// SQLite is easy to start with, but if you use Postgres in production
// you should also use it in development with the following:
//datasource postgresql {
// provider = "postgresql"
// url = env("DATABASE_URL")
//}
generator client {
provider = "prisma-client-js"
}
// --------------------------------------
//model Project {
// id Int @default(autoincrement()) @id
// name String
//}

View File

View File

@@ -0,0 +1,55 @@
{
"name": "blitzjs",
"version": "1.0.0",
"scripts": {
"start": "blitz start",
"studio": "blitz db studio",
"build": "blitz build",
"lint": "eslint --ignore-path .gitignore --ext .js,.ts,.tsx .",
"test": "echo \"No tests yet\""
},
"browserslist": [
"defaults"
],
"prettier": {
"semi": false,
"printWidth": 100
},
"husky": {
"hooks": {
"pre-commit": "lint-staged && pretty-quick --staged",
"pre-push": "blitz test"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix"
]
},
"dependencies": {
"@prisma/cli": "latest",
"@prisma/client": "latest",
"blitz": "latest",
"react": "experimental",
"react-dom": "experimental"
},
"devDependencies": {
"@types/react": "16.9.36",
"@typescript-eslint/eslint-plugin": "2.x",
"@typescript-eslint/parser": "2.x",
"babel-eslint": "10.1.0",
"eslint": "6.8.0",
"eslint-config-react-app": "5.2.1",
"eslint-plugin-flowtype": "4.7.0",
"eslint-plugin-import": "2.21.2",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-react": "7.20.0",
"eslint-plugin-react-hooks": "3.0.0",
"husky": "4.2.5",
"lint-staged": "10.2.10",
"prettier": "2.0.5",
"pretty-quick": "2.0.1",
"typescript": "3.9.5"
},
"private": true
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 556 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"baseUrl": "./",
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

View File

11913
examples/gatsby/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -20,6 +20,7 @@
"@zeit/ncc": "0.20.4",
"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",
@@ -28,7 +29,7 @@
"lint-staged": "9.2.5",
"node-fetch": "2.6.0",
"npm-package-arg": "6.1.0",
"prettier": "1.18.2"
"prettier": "2.0.5"
},
"scripts": {
"lerna": "lerna",

View File

@@ -1,4 +1,31 @@
[
{
"name": "Blitz.js",
"slug": "blitzjs",
"logo": "https://raw.githubusercontent.com/vercel/vercel/master/packages/frameworks/logos/blitz.svg",
"tagline": "Blitz.js: The Fullstack React Framework",
"description": "A brand new Blitz.js app: the output of running `blitz new`",
"website": "https://blitzjs.com",
"detectors": {
"every": [
{
"path": "package.json",
"matchContent": "\"(dev)?(d|D)ependencies\":\\s*{[^}]*\"blitz\":\\s*\".+?\"[^}]*}"
}
]
},
"settings": {
"buildCommand": {
"placeholder": "`npm run build` or `blitz build`"
},
"devCommand": {
"value": "blitz start"
},
"outputDirectory": {
"placeholder": "Next.js default"
}
}
},
{
"name": "Next.js",
"slug": "nextjs",
@@ -640,7 +667,7 @@
},
"settings": {
"buildCommand": {
"placeholder": "`npm run build` or `nuxt build`"
"placeholder": "`npm run build` or `nuxt generate`"
},
"devCommand": {
"value": "nuxt"

View File

@@ -0,0 +1,30 @@
<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path d="M95.4242 249.857H173.991C203.89 249.857 232.049 263.909 250.026 287.799L327.526 390.789C328.991 392.736 329.212 395.349 328.095 397.513L283.421 484.069C281.278 488.221 275.532 488.71 272.719 484.978L95.4242 249.857Z" fill="url(#paint0_linear)"/>
<g filter="url(#filter0_d)">
<path d="M404.558 249.991H325.991C296.093 249.991 267.933 235.939 249.956 212.049L172.456 109.059C170.991 107.112 170.771 104.499 171.888 102.335L216.561 15.7794C218.705 11.6267 224.45 11.1382 227.264 14.8695L404.558 249.991Z" fill="url(#paint1_linear)"/>
</g>
</g>
<defs>
<filter id="filter0_d" x="71.1812" y="-39.6553" width="433.377" height="437.646" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
<feOffset dy="48"/>
<feGaussianBlur stdDeviation="50"/>
<feColorMatrix type="matrix" values="0 0 0 0 0.270588 0 0 0 0 0 0 0 0 0 0.615686 0 0 0 0.2 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
</filter>
<linearGradient id="paint0_linear" x1="163.936" y1="392.775" x2="316.429" y2="155.244" gradientUnits="userSpaceOnUse">
<stop stop-color="#6700EB"/>
<stop offset="1" stop-color="#45009D"/>
</linearGradient>
<linearGradient id="paint1_linear" x1="336.047" y1="107.073" x2="183.554" y2="344.604" gradientUnits="userSpaceOnUse">
<stop stop-color="#6700EB"/>
<stop offset="1" stop-color="#45009D"/>
</linearGradient>
<clipPath id="clip0">
<rect width="500" height="500" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/frameworks",
"version": "0.0.15",
"version": "0.0.16-canary.1",
"main": "frameworks.json",
"license": "UNLICENSED",
"scripts": {

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "2.4.0",
"version": "2.4.1-canary.2",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",

View File

@@ -462,7 +462,7 @@ function detectFrontBuilder(
});
}
if (framework === 'nextjs') {
if (framework === 'nextjs' || framework === 'blitzjs') {
return { src: 'package.json', use: `@vercel/next${withTag}`, config };
}

View File

@@ -38,3 +38,78 @@ interface Props {
*/
action?: string;
}
export function getPrettyError(obj: {
dataPath?: string;
message?: string;
params: any;
}): NowBuildError {
const docsUrl = 'https://vercel.com/docs/configuration';
try {
const { dataPath, params, message: ajvMessage } = obj;
const prop = getTopLevelPropertyName(dataPath);
let message =
dataPath && dataPath.startsWith('.') ? `\`${dataPath.slice(1)}\` ` : '';
if (params && typeof params.additionalProperty === 'string') {
const suggestion = getSuggestion(prop, params.additionalProperty);
message += `should NOT have additional property \`${params.additionalProperty}\`. ${suggestion}`;
} else if (params && typeof params.missingProperty === 'string') {
message += `missing required property \`${params.missingProperty}\`.`;
} else {
message += `${ajvMessage}.`;
}
return new NowBuildError({
code: 'DEV_VALIDATE_CONFIG',
message: message,
link: prop ? `${docsUrl}#project/${prop.toLowerCase()}` : docsUrl,
action: 'View Documentation',
});
} catch (e) {
return new NowBuildError({
code: 'DEV_VALIDATE_CONFIG',
message: `Failed to validate configuration.`,
link: docsUrl,
action: 'View Documentation',
});
}
}
/**
* Get the top level property from the dataPath.
* `.cleanUrls` => `cleanUrls`
* `.headers[0].source` => `headers`
* `.headers[0].headers[0]` => `headers`
* `` => ``
*/
function getTopLevelPropertyName(dataPath?: string): string {
if (dataPath && dataPath.startsWith('.')) {
const lastIndex = dataPath.indexOf('[');
return lastIndex > -1 ? dataPath.slice(1, lastIndex) : dataPath.slice(1);
}
return '';
}
const mapTypoToSuggestion: { [key: string]: { [key: string]: string } } = {
'': {
builder: 'builds',
'build.env': '{ "build": { "env": {"name": "value"} } }',
'builds.env': '{ "build": { "env": {"name": "value"} } }',
},
rewrites: { src: 'source', dest: 'destination' },
redirects: { src: 'source', dest: 'destination', status: 'statusCode' },
headers: { src: 'source', header: 'headers' },
routes: {
source: 'src',
destination: 'dest',
header: 'headers',
method: 'methods',
},
};
function getSuggestion(topLevelProp: string, additionalProperty: string) {
const choices = mapTypoToSuggestion[topLevelProp];
const choice = choices ? choices[additionalProperty] : undefined;
return choice ? `Did you mean \`${choice}\`?` : 'Please remove it.';
}

View File

@@ -493,7 +493,7 @@ describe('Test `detectBuilders`', () => {
});
it('use a custom runtime', async () => {
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const { builders, errors } = await detectBuilders(files, null, {
functions,
@@ -501,11 +501,11 @@ describe('Test `detectBuilders`', () => {
expect(errors).toBe(null);
expect(builders!.length).toBe(1);
expect(builders![0].use).toBe('now-php@0.0.8');
expect(builders![0].use).toBe('vercel-php@0.1.0');
});
it('use a custom runtime but without a source', async () => {
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/team.js'];
const { errors } = await detectBuilders(files, null, {
functions,
@@ -1538,7 +1538,7 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
});
it('use a custom runtime', async () => {
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const { builders, errors } = await detectBuilders(files, null, {
functions,
@@ -1547,11 +1547,11 @@ describe('Test `detectBuilders` with `featHandleMiss=true`', () => {
expect(errors).toBe(null);
expect(builders!.length).toBe(1);
expect(builders![0].use).toBe('now-php@0.0.8');
expect(builders![0].use).toBe('vercel-php@0.1.0');
});
it('use a custom runtime but without a source', async () => {
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/team.js'];
const { errors } = await detectBuilders(files, null, {
functions,
@@ -2081,7 +2081,7 @@ it('Test `detectRoutes`', async () => {
{
// use a custom runtime
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const { defaultRoutes } = await detectBuilders(files, null, { functions });
@@ -2393,7 +2393,7 @@ it('Test `detectRoutes` with `featHandleMiss=true`', async () => {
{
// use a custom runtime
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const { defaultRoutes, rewriteRoutes } = await detectBuilders(files, null, {
@@ -2692,7 +2692,7 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`', async ()
{
// use a custom runtime
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const {
@@ -2941,7 +2941,7 @@ it('Test `detectRoutes` with `featHandleMiss=true`, `cleanUrls=true`, `trailingS
{
// use a custom runtime
const functions = { 'api/user.php': { runtime: 'now-php@0.0.8' } };
const functions = { 'api/user.php': { runtime: 'vercel-php@0.1.0' } };
const files = ['api/user.php'];
const {

View File

@@ -1,9 +1,9 @@
{
"name": "vercel",
"version": "19.1.0",
"version": "19.1.2-canary.19",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Now",
"description": "The command-line interface for Vercel",
"homepage": "https://vercel.com",
"repository": {
"type": "git",
@@ -12,7 +12,7 @@
},
"scripts": {
"preinstall": "node ./scripts/preinstall.js",
"test-unit": "nyc ava test/unit.js test/dev-builder.unit.js test/dev-router.unit.js test/dev-server.unit.js --serial --fail-fast --verbose",
"test-unit": "nyc ava test/unit.js test/dev-builder.unit.js test/dev-router.unit.js test/dev-server.unit.js test/dev-validate.unit.js --serial --fail-fast --verbose",
"test-integration-cli": "ava test/integration.js --serial --fail-fast --verbose",
"test-integration-v1": "ava test/integration-v1.js --serial --fail-fast",
"test-integration-dev": "ava test/dev/integration.js --serial --fail-fast --verbose",
@@ -62,13 +62,13 @@
"node": ">= 10"
},
"dependencies": {
"@vercel/build-utils": "2.4.0",
"@vercel/go": "1.1.2",
"@vercel/next": "2.6.6",
"@vercel/node": "1.7.0",
"@vercel/build-utils": "2.4.1-canary.2",
"@vercel/go": "1.1.3-canary.1",
"@vercel/next": "2.6.9",
"@vercel/node": "1.7.2-canary.1",
"@vercel/python": "1.2.2",
"@vercel/ruby": "1.2.2",
"@vercel/static-build": "0.17.2"
"@vercel/ruby": "1.2.3-canary.0",
"@vercel/static-build": "0.17.5-canary.0"
},
"devDependencies": {
"@sentry/node": "5.5.0",

View File

@@ -3,8 +3,8 @@ import bytes from 'bytes';
import { join } from 'path';
import { write as copy } from 'clipboardy';
import chalk from 'chalk';
import title from 'title';
import { fileNameSymbol } from '@vercel/client';
import { getPrettyError } from '@vercel/build-utils';
import Client from '../../util/client';
import { handleError } from '../../util/error';
import getArgs from '../../util/get-args';
@@ -738,53 +738,10 @@ function handleCreateDeployError(output, error, localConfig) {
return 1;
}
if (error instanceof SchemaValidationFailed) {
const { message, params, keyword, dataPath } = error.meta;
if (params && params.additionalProperty) {
const prop = params.additionalProperty;
output.error(
`The property ${code(prop)} is not allowed in ${highlight(
localConfig[fileNameSymbol]
)} please remove it.`
);
if (prop === 'build.env' || prop === 'builds.env') {
output.note(
`Do you mean ${code('build')} (object) with a property ${code(
'env'
)} (object) instead of ${code(prop)}?`
);
}
return 1;
}
if (dataPath === '.name') {
output.error(message);
return 1;
}
if (keyword === 'type') {
const prop = dataPath.substr(1, dataPath.length);
output.error(
`The property ${code(prop)} in ${highlight(
localConfig[fileNameSymbol]
)} can only be of type ${code(title(params.type))}.`
);
return 1;
}
const link = 'https://vercel.com/docs/configuration';
output.error(
`Failed to validate ${highlight(
localConfig[fileNameSymbol]
)}: ${message}\nDocumentation: ${link}`
);
const niceError = getPrettyError(error.meta);
const fileName = localConfig[fileNameSymbol] || 'vercel.json';
niceError.message = `Invalid ${fileName} - ${niceError.message}`;
output.prettyError(niceError);
return 1;
}
if (error instanceof TooManyRequests) {

View File

@@ -9,6 +9,7 @@ import { getLinkedProject } from '../../util/projects/link';
import { getFrameworks } from '../../util/get-frameworks';
import { isSettingValue } from '../../util/is-setting-value';
import { getCommandName } from '../../util/pkg-name';
import { ProjectSettings } from '../../types';
type Options = {
'--debug'?: boolean;
@@ -50,21 +51,26 @@ export default async function dev(
return 1;
}
let devCommand: undefined | string;
let frameworkSlug: null | string = null;
let devCommand: string | undefined;
let frameworkSlug: string | undefined;
let projectSettings: ProjectSettings | undefined;
if (link.status === 'linked') {
const { project, org } = link;
client.currentTeam = org.type === 'team' ? org.id : undefined;
projectSettings = project;
if (project.devCommand) {
devCommand = project.devCommand;
} else if (project.framework) {
const framework = frameworks.find(f => f.slug === project.framework);
if (framework) {
frameworkSlug = framework.slug;
const defaults = framework.settings.devCommand;
if (framework.slug) {
frameworkSlug = framework.slug;
}
const defaults = framework.settings.devCommand;
if (isSettingValue(defaults)) {
devCommand = defaults.value;
}
@@ -81,6 +87,7 @@ export default async function dev(
debug,
devCommand,
frameworkSlug,
projectSettings,
});
process.once('SIGINT', () => devServer.stop());

View File

@@ -10,6 +10,7 @@ import handleError from '../../util/handle-error';
import createOutput from '../../util/output/create-output';
import logo from '../../util/output/logo';
import cmd from '../../util/output/cmd';
import highlight from '../../util/output/highlight';
import dev from './dev';
import readPackage from '../../util/read-package';
import readConfig from '../../util/config/read-config';
@@ -119,6 +120,21 @@ export default async function main(ctx: NowContext) {
try {
return await dev(ctx, argv, args, output);
} catch (err) {
if (err.code === 'ENOTFOUND') {
// Error message will look like the following:
// "request to https://api.vercel.com/www/user failed, reason: getaddrinfo ENOTFOUND api.vercel.com"
const matches = /getaddrinfo ENOTFOUND (.*)$/.exec(err.message || '');
if (matches && matches[1]) {
const hostname = matches[1];
output.error(
`The hostname ${highlight(
hostname
)} could not be resolved. Please verify your internet connectivity and DNS configuration.`
);
}
output.debug(err.stack);
return 1;
}
output.prettyError(err);
output.debug(stringifyError(err));
return 1;

View File

@@ -9,16 +9,39 @@ import getDecryptedSecret from '../../util/env/get-decrypted-secret';
import param from '../../util/output/param';
import withSpinner from '../../util/with-spinner';
import { join } from 'path';
import { promises, existsSync } from 'fs';
import { promises, openSync, closeSync, readSync } from 'fs';
import { emoji, prependEmoji } from '../../util/emoji';
import { getCommandName } from '../../util/pkg-name';
const { writeFile } = promises;
const CONTENTS_PREFIX = '# Created by Vercel CLI\n';
type Options = {
'--debug': boolean;
'--yes': boolean;
};
function readHeadSync(path: string, length: number) {
const buffer = Buffer.alloc(length);
const fd = openSync(path, 'r');
try {
readSync(fd, buffer, 0, buffer.length, null);
} finally {
closeSync(fd);
}
return buffer.toString();
}
function tryReadHeadSync(path: string, length: number) {
try {
return readHeadSync(path, length);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
}
export default async function pull(
client: Client,
project: Project,
@@ -35,10 +58,14 @@ export default async function pull(
const [filename = '.env'] = args;
const fullPath = join(process.cwd(), filename);
const exists = existsSync(fullPath);
const skipConfirmation = opts['--yes'];
if (
const head = tryReadHeadSync(fullPath, Buffer.byteLength(CONTENTS_PREFIX));
const exists = typeof head !== 'undefined';
if (head === CONTENTS_PREFIX) {
output.print(`Overwriting existing ${chalk.bold(filename)} file\n`);
} else if (
exists &&
!skipConfirmation &&
!(await promptBool(
@@ -83,6 +110,7 @@ export default async function pull(
});
const contents =
CONTENTS_PREFIX +
records
.filter(obj => {
if (!obj.found) {
@@ -95,7 +123,8 @@ export default async function pull(
return true;
})
.map(({ key, value }) => `${key}="${escapeValue(value)}"`)
.join('\n') + '\n';
.join('\n') +
'\n';
await writeFile(fullPath, contents, 'utf8');

View File

@@ -314,21 +314,6 @@ const main = async argv_ => {
// need to migrate.
if (authConfig.credentials) {
authConfigExists = false;
} else if (
!authConfig.token &&
!subcommandsWithoutToken.includes(targetOrSubcommand) &&
!argv['--help'] &&
!argv['--token']
) {
console.error(
error(
`The content of "${hp(VERCEL_AUTH_CONFIG_PATH)}" is invalid. ` +
`No \`token\` property found inside. Run ${getCommandName(
'login'
)} to authorize.`
)
);
return 1;
}
} else {
const results = await getDefaultAuthConfig(authConfig);
@@ -638,12 +623,18 @@ const main = async argv_ => {
.send();
}
} catch (err) {
if (err.code === 'ENOTFOUND' && err.hostname === 'api.vercel.com') {
output.error(
`The hostname ${highlight(
'api.vercel.com'
)} could not be resolved. Please verify your internet connectivity and DNS configuration.`
);
if (err.code === 'ENOTFOUND') {
// Error message will look like the following:
// "request to https://api.vercel.com/www/user failed, reason: getaddrinfo ENOTFOUND api.vercel.com"
const matches = /getaddrinfo ENOTFOUND (.*)$/.exec(err.message || '');
if (matches && matches[1]) {
const hostname = matches[1];
output.error(
`The hostname ${highlight(
hostname
)} could not be resolved. Please verify your internet connectivity and DNS configuration.`
);
}
output.debug(err.stack);
return 1;
}

View File

@@ -244,15 +244,20 @@ export interface ProjectEnvVariable {
system?: boolean;
}
export interface Project {
export interface ProjectSettings {
framework?: string | null;
devCommand?: string | null;
buildCommand?: string | null;
outputDirectory?: string | null;
rootDirectory?: string | null;
}
export interface Project extends ProjectSettings {
id: string;
name: string;
accountId: string;
updatedAt: number;
createdAt: number;
devCommand?: string | null;
framework?: string | null;
rootDirectory?: string | null;
latestDeployments?: Partial<Deployment>[];
}

View File

@@ -56,6 +56,8 @@ async function createBuildProcess(
workPath: string,
output: Output
): Promise<ChildProcess> {
output.debug(`Creating build process for "${match.entrypoint}"`);
const builderWorkerPath = join(__dirname, 'builder-worker.js');
// Ensure that `node` is in the builder's `PATH`
@@ -78,7 +80,7 @@ async function createBuildProcess(
buildProcess.on('exit', (code, signal) => {
output.debug(
`Build process for ${match.src} exited with ${signal || code}`
`Build process for "${match.entrypoint}" exited with ${signal || code}`
);
match.buildProcess = undefined;
});
@@ -128,7 +130,6 @@ export async function executeBuild(
let { buildProcess } = match;
if (!runInProcess && !buildProcess) {
devServer.output.debug(`Creating build process for ${entrypoint}`);
buildProcess = await createBuildProcess(
match,
envConfigs,
@@ -431,7 +432,7 @@ export async function getBuildMatches(
}
const files = fileList
.filter(name => name === src || minimatch(name, src))
.filter(name => name === src || minimatch(name, src, { dot: true }))
.map(name => join(cwd, name));
if (files.length === 0) {

View File

@@ -4,7 +4,7 @@ import PCRE from 'pcre-to-regexp';
import isURL from './is-url';
import DevServer from './server';
import { HttpHeadersConfig, RouteResult } from './types';
import { NowConfig, HttpHeadersConfig, RouteResult } from './types';
import { isHandler, Route, HandleValue } from '@vercel/routing-utils';
export function resolveRouteParameters(
@@ -29,7 +29,7 @@ export function resolveRouteParameters(
export function getRoutesTypes(routes: Route[] = []) {
const handleMap = new Map<HandleValue | null, Route[]>();
let prevHandle: HandleValue | null = null;
routes.forEach(route => {
routes.forEach((route) => {
if (isHandler(route)) {
prevHandle = route.handle;
} else {
@@ -50,6 +50,7 @@ export async function devRouter(
reqMethod?: string,
routes?: Route[],
devServer?: DevServer,
nowConfig?: NowConfig,
previousHeaders?: HttpHeadersConfig,
missRoutes?: Route[],
phase?: HandleValue | null
@@ -117,9 +118,12 @@ export async function devRouter(
continue;
}
if (routeConfig.check && devServer && phase !== 'hit') {
if (routeConfig.check && devServer && nowConfig && phase !== 'hit') {
const { pathname = '/' } = url.parse(destPath);
const hasDestFile = await devServer.hasFilesystem(pathname);
const hasDestFile = await devServer.hasFilesystem(
pathname,
nowConfig
);
if (!hasDestFile) {
if (routeConfig.status && phase !== 'miss') {
@@ -131,6 +135,7 @@ export async function devRouter(
reqMethod,
missRoutes,
devServer,
nowConfig,
combinedHeaders,
[],
'miss'

View File

@@ -12,7 +12,7 @@ import { randomBytes } from 'crypto';
import serveHandler from 'serve-handler';
import { watch, FSWatcher } from 'chokidar';
import { parse as parseDotenv } from 'dotenv';
import { basename, dirname, extname, join } from 'path';
import path, { isAbsolute, basename, dirname, extname, join } from 'path';
import once from '@tootallnate/once';
import directoryTemplate from 'serve-handler/src/directory';
import getPort from 'get-port';
@@ -49,18 +49,8 @@ import getNowConfigPath from '../config/local-path';
import { MissingDotenvVarsError } from '../errors-ts';
import cliPkg from '../pkg';
import { getVercelDirectory } from '../projects/link';
import { staticFiles as getFiles, getAllProjectFiles } from '../get-files';
import {
validateNowConfigBuilds,
validateNowConfigRoutes,
validateNowConfigCleanUrls,
validateNowConfigHeaders,
validateNowConfigRedirects,
validateNowConfigRewrites,
validateNowConfigTrailingSlash,
validateNowConfigFunctions,
} from './validate';
import { staticFiles as getFiles } from '../get-files';
import { validateConfig } from './validate';
import { devRouter, getRoutesTypes } from './router';
import getMimeType from './mime-type';
import { executeBuild, getBuildMatches, shutdownBuilder } from './builder';
@@ -93,12 +83,17 @@ import {
HttpHeadersConfig,
EnvConfigs,
} from './types';
import { ProjectSettings } from '../../types';
interface FSEvent {
type: string;
path: string;
}
type WithFileNameSymbol<T> = T & {
[fileNameSymbol]: string;
};
function sortBuilders(buildA: Builder, buildB: Builder) {
if (buildA && buildA.use && isOfficialRuntime('static-build', buildA.use)) {
return 1;
@@ -117,7 +112,7 @@ export default class DevServer {
public output: Output;
public proxy: httpProxy;
public envConfigs: EnvConfigs;
public frameworkSlug: string | null;
public frameworkSlug?: string;
public files: BuilderInputs;
public address: string;
public devCacheDir: string;
@@ -140,6 +135,7 @@ export default class DevServer {
private devProcess?: ChildProcess;
private devProcessPort?: number;
private devServerPids: Set<number>;
private projectSettings?: ProjectSettings;
private getNowConfigPromise: Promise<NowConfig> | null;
private blockingBuildsPromise: Promise<void> | null;
@@ -154,6 +150,7 @@ export default class DevServer {
this.files = {};
this.address = '';
this.devCommand = options.devCommand;
this.projectSettings = options.projectSettings;
this.frameworkSlug = options.frameworkSlug;
this.cachedNowConfig = null;
this.caseSensitive = false;
@@ -179,10 +176,8 @@ export default class DevServer {
this.watchAggregationEvents = [];
this.watchAggregationTimeout = 500;
this.filter = path => Boolean(path);
this.podId = Math.random()
.toString(32)
.slice(-5);
this.filter = (path) => Boolean(path);
this.podId = Math.random().toString(32).slice(-5);
this.devServerPids = new Set();
}
@@ -220,8 +215,8 @@ export default class DevServer {
}
}
events = events.filter(event =>
distPaths.every(distPath => !event.path.startsWith(distPath))
events = events.filter((event) =>
distPaths.every((distPath) => !event.path.startsWith(distPath))
);
// First, update the `files` mapping of source files
@@ -238,10 +233,9 @@ export default class DevServer {
const nowConfig = await this.getNowConfig(false);
// Update the env vars configuration
const nowConfigBuild = nowConfig.build || {};
const [runEnv, buildEnv] = await Promise.all([
this.getLocalEnv('.env', nowConfig.env),
this.getLocalEnv('.env.build', nowConfigBuild.env),
this.getLocalEnv('.env.build', nowConfig.build?.env),
]);
const allEnv = { ...buildEnv, ...runEnv };
this.envConfigs = { buildEnv, runEnv, allEnv };
@@ -290,18 +284,19 @@ export default class DevServer {
for (const [result, [requestPath, match]] of needsRebuild) {
if (
requestPath === null ||
(await shouldServe(match, this.files, requestPath, this))
(await shouldServe(match, this.files, requestPath, this, nowConfig))
) {
this.triggerBuild(
match,
requestPath,
null,
nowConfig,
result,
filesChangedArray,
filesRemovedArray
).catch((err: Error) => {
this.output.warn(
`An error occurred while rebuilding ${match.src}:`
`An error occurred while rebuilding \`${match.src}\`:`
);
console.error(err.stack);
});
@@ -385,12 +380,10 @@ export default class DevServer {
this,
fileList
);
const sources = matches.map(m => m.src);
const sources = matches.map((m) => m.src);
if (isInitial && fileList.length === 0) {
this.output.warn(
'There are no files (or only files starting with a dot) inside your deployment.'
);
this.output.warn('There are no files inside your deployment.');
}
// Delete build matches that no longer exists
@@ -446,6 +439,9 @@ export default class DevServer {
`Cleaning up "blockingBuildsPromise" after error: ${err}`
);
this.blockingBuildsPromise = null;
if (err) {
this.output.prettyError(err);
}
});
}
@@ -528,40 +524,17 @@ export default class DevServer {
return this.cachedNowConfig;
}
const pkg = await this.getPackageJson();
const configPath = getNowConfigPath(this.cwd);
// The default empty `vercel.json` is used to serve all files as static
// when no `vercel.json` is present
let configPath = 'vercel.json';
let config: NowConfig = {
version: 2,
[fileNameSymbol]: configPath,
};
try {
configPath = getNowConfigPath(this.cwd);
this.output.debug(`Reading ${configPath}`);
config = JSON.parse(await fs.readFile(configPath, 'utf8'));
config[fileNameSymbol] = configPath;
} catch (err) {
if (err.code === 'ENOENT') {
this.output.debug(err.toString());
} else if (err.name === 'SyntaxError') {
this.output.warn(
`There is a syntax error in ${configPath}: ${err.message}`
);
} else {
throw err;
}
}
const allFiles = await getAllProjectFiles(this.cwd, this.output);
const files = allFiles.filter(this.filter);
this.output.debug(
`Found ${allFiles.length} and ` +
`filtered out ${allFiles.length - files.length} files`
);
const [
pkg = null,
// The default empty `vercel.json` is used to serve all
// files as static when no `vercel.json` is present
config = { version: 2, [fileNameSymbol]: 'vercel.json' },
] = await Promise.all([
this.readJsonFile<PackageJson>('package.json'),
this.readJsonFile<NowConfig>(configPath),
]);
await this.validateNowConfig(config);
const { error: routeError, routes: maybeRoutes } = getTransformedRoutes({
@@ -578,6 +551,11 @@ export default class DevServer {
const featHandleMiss = true; // enable for zero config
const { projectSettings, cleanUrls, trailingSlash } = config;
const opts = { output: this.output, isBuilds: true };
const files = (await getFiles(this.cwd, config, opts)).map((f) =>
relative(this.cwd, f)
);
let {
builders,
warnings,
@@ -589,7 +567,7 @@ export default class DevServer {
} = await detectBuilders(files, pkg, {
tag: getDistTag(cliPkg.version) === 'canary' ? 'canary' : 'latest',
functions: config.functions,
...(projectSettings ? { projectSettings } : {}),
projectSettings: projectSettings || this.projectSettings,
featHandleMiss,
cleanUrls,
trailingSlash,
@@ -601,7 +579,7 @@ export default class DevServer {
}
if (warnings && warnings.length > 0) {
warnings.forEach(warning => this.output.warn(warning.message));
warnings.forEach((warning) => this.output.warn(warning.message));
}
if (builders) {
@@ -611,6 +589,8 @@ export default class DevServer {
config.builds = config.builds || [];
config.builds.push(...builders);
delete config.functions;
}
let routes: Route[] = [];
@@ -651,27 +631,35 @@ export default class DevServer {
return config;
}
async getPackageJson(): Promise<PackageJson | null> {
const pkgPath = join(this.cwd, 'package.json');
let pkg: PackageJson | null = null;
this.output.debug('Reading `package.json` file');
async readJsonFile<T>(
filePath: string
): Promise<WithFileNameSymbol<T> | void> {
let rel, abs;
if (isAbsolute(filePath)) {
rel = path.relative(this.cwd, filePath);
abs = filePath;
} else {
rel = filePath;
abs = join(this.cwd, filePath);
}
this.output.debug(`Reading \`${rel}\` file`);
try {
pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
const raw = await fs.readFile(abs, 'utf8');
const parsed: WithFileNameSymbol<T> = JSON.parse(raw);
parsed[fileNameSymbol] = rel;
return parsed;
} catch (err) {
if (err.code === 'ENOENT') {
this.output.debug('No `package.json` file present');
this.output.debug(`No \`${rel}\` file present`);
} else if (err.name === 'SyntaxError') {
this.output.warn(
`There is a syntax error in the \`package.json\` file: ${err.message}`
`There is a syntax error in the \`${rel}\` file: ${err.message}`
);
} else {
throw err;
}
}
return pkg;
}
async tryValidateOrExit(
@@ -693,14 +681,12 @@ export default class DevServer {
return;
}
await this.tryValidateOrExit(config, validateNowConfigBuilds);
await this.tryValidateOrExit(config, validateNowConfigRoutes);
await this.tryValidateOrExit(config, validateNowConfigCleanUrls);
await this.tryValidateOrExit(config, validateNowConfigHeaders);
await this.tryValidateOrExit(config, validateNowConfigRedirects);
await this.tryValidateOrExit(config, validateNowConfigRewrites);
await this.tryValidateOrExit(config, validateNowConfigTrailingSlash);
await this.tryValidateOrExit(config, validateNowConfigFunctions);
const error = validateConfig(config);
if (error) {
this.output.prettyError(error);
await this.exit(1);
}
}
validateEnvConfig(type: string, env: Env = {}, localEnv: Env = {}): Env {
@@ -771,10 +757,9 @@ export default class DevServer {
// Retrieve the path of the native module
const nowConfig = await this.getNowConfig(false);
const nowConfigBuild = nowConfig.build || {};
const [runEnv, buildEnv] = await Promise.all([
this.getLocalEnv('.env', nowConfig.env),
this.getLocalEnv('.env.build', nowConfigBuild.env),
this.getLocalEnv('.env.build', nowConfig.build?.env),
]);
const allEnv = { ...buildEnv, ...runEnv };
this.envConfigs = { buildEnv, runEnv, allEnv };
@@ -805,11 +790,11 @@ export default class DevServer {
// get their "build matches" invalidated so that the new version is used.
this.updateBuildersTimeout = setTimeout(() => {
this.updateBuildersPromise = updateBuilders(builders, this.output)
.then(updatedBuilders => {
.then((updatedBuilders) => {
this.updateBuildersPromise = null;
this.invalidateBuildMatches(nowConfig, updatedBuilders);
})
.catch(err => {
.catch((err) => {
this.updateBuildersPromise = null;
this.output.error(`Failed to update builders: ${err.message}`);
this.output.debug(err.stack);
@@ -1150,6 +1135,7 @@ export default class DevServer {
match: BuildMatch,
requestPath: string | null,
req: http.IncomingMessage | null,
nowConfig: NowConfig,
previousBuildResult?: BuildResult,
filesChanged?: string[],
filesRemoved?: string[]
@@ -1165,10 +1151,11 @@ export default class DevServer {
// A build for `buildKey` is already in progress, so don't trigger
// another rebuild for this request - just wait on the existing one.
let msg = `De-duping build "${buildKey}"`;
if (req) msg += ` for "${req.method} ${req.url}"`;
if (req) {
msg += ` for "${req.method} ${req.url}"`;
}
this.output.debug(msg);
} else {
const nowConfig = await this.getNowConfig();
if (previousBuildResult) {
// Tear down any `output` assets from a previous build, so that they
// are not available to be served while the rebuild is in progress.
@@ -1179,7 +1166,9 @@ export default class DevServer {
}
}
let msg = `Building asset "${buildKey}"`;
if (req) msg += ` for "${req.method} ${req.url}"`;
if (req) {
msg += ` for "${req.method} ${req.url}"`;
}
this.output.debug(msg);
buildPromise = executeBuild(
nowConfig,
@@ -1260,7 +1249,7 @@ export default class DevServer {
const { status, headers, dest } = routeResult;
const location = headers['location'] || dest;
if (status && location && (300 <= status && status <= 399)) {
if (status && location && 300 <= status && status <= 399) {
this.output.debug(`Route found with redirect status code ${status}`);
await this.sendRedirect(req, res, nowRequestId, location, status);
return true;
@@ -1350,6 +1339,7 @@ export default class DevServer {
req.method,
phaseRoutes,
this,
nowConfig,
prevHeaders,
missRoutes,
phase
@@ -1377,7 +1367,8 @@ export default class DevServer {
this.buildMatches,
this.files,
routeResult.dest,
this
this,
nowConfig
);
if (
@@ -1400,6 +1391,7 @@ export default class DevServer {
req.method,
missRoutes,
this,
nowConfig,
routeResult.headers,
[],
'miss'
@@ -1409,7 +1401,8 @@ export default class DevServer {
this.buildMatches,
this.files,
routeResult.dest,
this
this,
nowConfig
);
if (
await this.exitWithStatus(
@@ -1432,6 +1425,7 @@ export default class DevServer {
req.method,
hitRoutes,
this,
nowConfig,
routeResult.headers,
[],
'hit'
@@ -1446,6 +1440,7 @@ export default class DevServer {
req.method,
errorRoutes,
this,
nowConfig,
routeResult.headers,
[],
'error'
@@ -1455,7 +1450,8 @@ export default class DevServer {
this.buildMatches,
this.files,
routeResultForError.dest,
this
this,
nowConfig
);
if (matchForError) {
@@ -1503,16 +1499,15 @@ export default class DevServer {
if (!match) {
// If the dev command is started, then proxy to it
if (this.devProcessPort) {
debug('Proxying to frontend dev server');
const upstream = `http://localhost:${this.devProcessPort}`;
debug(`Proxying to frontend dev server: ${upstream}`);
this.setResponseHeaders(res, nowRequestId);
return proxyPass(
req,
res,
`http://localhost:${this.devProcessPort}`,
this,
nowRequestId,
false
);
const origUrl = url.parse(req.url || '/', true);
delete origUrl.search;
origUrl.pathname = dest;
Object.assign(origUrl.query, uri_args);
req.url = url.format(origUrl);
return proxyPass(req, res, upstream, this, nowRequestId, false);
}
if (
@@ -1544,7 +1539,8 @@ export default class DevServer {
newUrl,
req.method,
buildResult.routes,
this
this,
nowConfig
);
if (matchedRoute.found && callLevel === 0) {
debug(`Found matching route ${matchedRoute.dest} for ${newUrl}`);
@@ -1640,7 +1636,7 @@ export default class DevServer {
let foundAsset = findAsset(match, requestPath, nowConfig);
if (!foundAsset && callLevel === 0) {
await this.triggerBuild(match, buildRequestPath, req);
await this.triggerBuild(match, buildRequestPath, req, nowConfig);
// Since the `asset` was just built, resolve again to get the new asset
foundAsset = findAsset(match, requestPath, nowConfig);
@@ -1672,8 +1668,9 @@ export default class DevServer {
const { asset, assetKey } = foundAsset;
debug(
`Serving asset: [${asset.type}] ${assetKey} ${(asset as any)
.contentType || ''}`
`Serving asset: [${asset.type}] ${assetKey} ${
(asset as any).contentType || ''
}`
);
/* eslint-disable no-case-declarations */
@@ -1792,7 +1789,7 @@ export default class DevServer {
const dirs: Set<string> = new Set();
const files = Array.from(this.buildMatches.keys())
.filter(p => {
.filter((p) => {
const base = basename(p);
if (
base === 'now.json' ||
@@ -1813,7 +1810,7 @@ export default class DevServer {
}
return true;
})
.map(p => {
.map((p) => {
let base = basename(p);
let ext = '';
let type = 'file';
@@ -1865,8 +1862,17 @@ export default class DevServer {
return true;
}
async hasFilesystem(dest: string): Promise<boolean> {
if (await findBuildMatch(this.buildMatches, this.files, dest, this, true)) {
async hasFilesystem(dest: string, nowConfig: NowConfig): Promise<boolean> {
if (
await findBuildMatch(
this.buildMatches,
this.files,
dest,
this,
nowConfig,
true
)
) {
return true;
}
return false;
@@ -2047,13 +2053,23 @@ async function findBuildMatch(
files: BuilderInputs,
requestPath: string,
devServer: DevServer,
isFilesystem?: boolean
nowConfig: NowConfig,
isFilesystem = false
): Promise<BuildMatch | null> {
requestPath = requestPath.replace(/^\//, '');
let bestIndexMatch: undefined | BuildMatch;
for (const match of matches.values()) {
if (await shouldServe(match, files, requestPath, devServer, isFilesystem)) {
if (
await shouldServe(
match,
files,
requestPath,
devServer,
nowConfig,
isFilesystem
)
) {
if (!isIndex(match.src)) {
return match;
} else {
@@ -2075,14 +2091,14 @@ async function shouldServe(
files: BuilderInputs,
requestPath: string,
devServer: DevServer,
isFilesystem?: boolean
nowConfig: NowConfig,
isFilesystem = false
): Promise<boolean> {
const {
src,
config,
builderWithPkg: { builder },
} = match;
const nowConfig = await devServer.getNowConfig();
const cleanSrc = src.endsWith('.html') ? src.slice(0, -5) : src;
const trimmedPath = requestPath.endsWith('/')
? requestPath.slice(0, -1)
@@ -2126,7 +2142,7 @@ async function shouldServe(
return true;
} else if (
!isFilesystem &&
(await findMatchingRoute(match, requestPath, devServer))
(await findMatchingRoute(match, requestPath, devServer, nowConfig))
) {
// If there's no `shouldServe()` function and no matched asset, then look
// up if there's a matching build route on the `match` that has already
@@ -2139,7 +2155,8 @@ async function shouldServe(
async function findMatchingRoute(
match: BuildMatch,
requestPath: string,
devServer: DevServer
devServer: DevServer,
nowConfig: NowConfig
): Promise<RouteResult | void> {
const reqUrl = `/${requestPath}`;
for (const buildResult of match.buildResults.values()) {
@@ -2148,7 +2165,8 @@ async function findMatchingRoute(
reqUrl,
undefined,
buildResult.routes,
devServer
devServer,
nowConfig
);
if (route.found) {
return route;
@@ -2203,7 +2221,9 @@ function isIndex(path: string): boolean {
}
function minimatches(files: string[], pattern: string): boolean {
return files.some(file => file === pattern || minimatch(file, pattern));
return files.some(
(file) => file === pattern || minimatch(file, pattern, { dot: true })
);
}
function fileChanged(
@@ -2232,7 +2252,7 @@ function needsBlockingBuild(buildMatch: BuildMatch): boolean {
}
async function sleep(n: number) {
return new Promise(resolve => setTimeout(resolve, n));
return new Promise((resolve) => setTimeout(resolve, n));
}
async function checkForPort(

View File

@@ -17,14 +17,16 @@ import {
import { NowConfig } from '@vercel/client';
import { HandleValue, Route } from '@vercel/routing-utils';
import { Output } from '../output';
import { ProjectSettings } from '../../types';
export { NowConfig };
export interface DevServerOptions {
output: Output;
debug: boolean;
devCommand: string | undefined;
frameworkSlug: string | null;
devCommand?: string;
frameworkSlug?: string;
projectSettings?: ProjectSettings;
}
export interface EnvConfigs {

View File

@@ -8,71 +8,52 @@ import {
trailingSlashSchema,
} from '@vercel/routing-utils';
import { NowConfig } from './types';
import { functionsSchema, buildsSchema } from '@vercel/build-utils';
import {
functionsSchema,
buildsSchema,
NowBuildError,
getPrettyError,
} from '@vercel/build-utils';
import { fileNameSymbol } from '@vercel/client';
const vercelConfigSchema = {
type: 'object',
// These are not all possibilities because `vc dev`
// doesn't need to know about `regions`, `public`, etc.
additionalProperties: true,
properties: {
builds: buildsSchema,
routes: routesSchema,
cleanUrls: cleanUrlsSchema,
headers: headersSchema,
redirects: redirectsSchema,
rewrites: rewritesSchema,
trailingSlash: trailingSlashSchema,
functions: functionsSchema,
},
};
const ajv = new Ajv();
const validate = ajv.compile(vercelConfigSchema);
const validateBuilds = ajv.compile(buildsSchema);
const validateRoutes = ajv.compile(routesSchema);
const validateCleanUrls = ajv.compile(cleanUrlsSchema);
const validateHeaders = ajv.compile(headersSchema);
const validateRedirects = ajv.compile(redirectsSchema);
const validateRewrites = ajv.compile(rewritesSchema);
const validateTrailingSlash = ajv.compile(trailingSlashSchema);
const validateFunctions = ajv.compile(functionsSchema);
export function validateNowConfigBuilds(config: NowConfig) {
return validateKey(config, 'builds', validateBuilds);
}
export function validateNowConfigRoutes(config: NowConfig) {
return validateKey(config, 'routes', validateRoutes);
}
export function validateNowConfigCleanUrls(config: NowConfig) {
return validateKey(config, 'cleanUrls', validateCleanUrls);
}
export function validateNowConfigHeaders(config: NowConfig) {
return validateKey(config, 'headers', validateHeaders);
}
export function validateNowConfigRedirects(config: NowConfig) {
return validateKey(config, 'redirects', validateRedirects);
}
export function validateNowConfigRewrites(config: NowConfig) {
return validateKey(config, 'rewrites', validateRewrites);
}
export function validateNowConfigTrailingSlash(config: NowConfig) {
return validateKey(config, 'trailingSlash', validateTrailingSlash);
}
export function validateNowConfigFunctions(config: NowConfig) {
return validateKey(config, 'functions', validateFunctions);
}
function validateKey(
config: NowConfig,
key: keyof NowConfig,
validate: Ajv.ValidateFunction
) {
const value = config[key];
if (!value) {
return null;
export function validateConfig(config: NowConfig): NowBuildError | null {
if (!validate(config)) {
if (validate.errors && validate.errors[0]) {
const error = validate.errors[0];
const fileName = config[fileNameSymbol] || 'vercel.json';
const niceError = getPrettyError(error);
niceError.message = `Invalid ${fileName} - ${niceError.message}`;
return niceError;
}
}
if (!validate(value)) {
if (!validate.errors) {
return null;
}
const error = validate.errors[0];
return `Invalid \`${String(key)}\` property: ${error.dataPath} ${
error.message
}`;
if (config.functions && config.builds) {
return new NowBuildError({
code: 'FUNCTIONS_AND_BUILDS',
message:
'The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.',
link: 'https://vercel.link/functions-and-builds',
});
}
return null;

View File

@@ -1,7 +1,7 @@
import { resolve, join } from 'path';
import { resolve } from 'path';
import ignore from 'ignore';
import dockerignore from '@zeit/dockerignore';
import _glob, { IOptions } from 'glob';
import _glob, { IOptions as GlobOptions } from 'glob';
import fs from 'fs-extra';
import { getVercelIgnore } from '@vercel/client';
import IGNORED from './ignored';
@@ -12,11 +12,11 @@ import { NowConfig } from './dev/types';
type NullableString = string | null;
const flatten = (
function flatten(
arr: NullableString[] | NullableString[][],
res: NullableString[] = []
) => {
for (let cur of arr) {
): NullableString[] {
for (const cur of arr) {
if (Array.isArray(cur)) {
flatten(cur, res);
} else {
@@ -24,21 +24,17 @@ const flatten = (
}
}
return res;
};
}
const glob = async function(pattern: string, options: IOptions) {
return new Promise<string[]>((resolve, reject) => {
_glob(pattern, options, (error, files) => {
if (error) {
reject(error);
} else {
resolve(files);
}
async function glob(pattern: string, options: GlobOptions): Promise<string[]> {
return new Promise((resolve, reject) => {
_glob(pattern, options, (err, files) => {
err ? reject(err) : resolve(files);
});
});
};
}
interface WalkSyncOptions {
interface WalkOptions {
output: Output;
}
@@ -51,27 +47,27 @@ interface WalkSyncOptions {
* - `output` {Object} "output" helper object
* @returns {Array}
*/
const walkSync = async (
async function walk(
dir: string,
path: string,
filelist: string[] = [],
opts: WalkSyncOptions
) => {
opts: WalkOptions
) {
const { debug } = opts.output;
const dirc = await fs.readdir(asAbsolute(dir, path));
for (let file of dirc) {
file = asAbsolute(file, dir);
try {
const file_stat = await fs.stat(file);
filelist = file_stat.isDirectory()
? await walkSync(file, path, filelist, opts)
const fileStat = await fs.stat(file);
filelist = fileStat.isDirectory()
? await walk(file, path, filelist, opts)
: filelist.concat(file);
} catch (e) {
debug(`Ignoring invalid file ${file}`);
}
}
return filelist;
};
}
interface FilesInWhitelistOptions {
output: Output;
@@ -85,7 +81,7 @@ interface FilesInWhitelistOptions {
* - `output` {Object} "output" helper object
* @returns {Array} the expanded list of whitelisted files.
*/
const getFilesInWhitelist = async function(
const getFilesInWhitelist = async function (
whitelist: string[],
path: string,
opts: FilesInWhitelistOptions
@@ -97,10 +93,10 @@ const getFilesInWhitelist = async function(
whitelist.map(async (file: string) => {
file = asAbsolute(file, path);
try {
const file_stat = await fs.stat(file);
if (file_stat.isDirectory()) {
const dir_files = await walkSync(file, path, [], opts);
files.push(...dir_files);
const fileStat = await fs.stat(file);
if (fileStat.isDirectory()) {
const dirFiles = await walk(file, path, [], opts);
files.push(...dirFiles);
} else {
files.push(file);
}
@@ -117,7 +113,7 @@ const getFilesInWhitelist = async function(
* because ignore doesn't like them :|
*/
const clearRelative = function(str: string) {
const clearRelative = function (str: string) {
return str.replace(/(\n|^)\.\//g, '$1');
};
@@ -127,7 +123,7 @@ const clearRelative = function(str: string) {
* @return {String} results or `''`
*/
const maybeRead = async function<T>(path: string, default_: T) {
const maybeRead = async function <T>(path: string, default_: T) {
try {
return await fs.readFile(path, 'utf8');
} catch (err) {
@@ -143,7 +139,7 @@ const maybeRead = async function<T>(path: string, default_: T) {
* @param {String} parent full path
*/
const asAbsolute = function(path: string, parent: string) {
const asAbsolute = function (path: string, parent: string) {
if (path[0] === '/') {
return path;
}
@@ -272,7 +268,7 @@ export async function npm(
const search = Array.prototype.concat.apply(
[],
await Promise.all(
search_.map(file =>
search_.map((file) =>
glob(file, { cwd: path, absolute: true, dot: true })
)
)
@@ -364,7 +360,7 @@ export async function docker(
const search_ = ['.'];
// Convert all filenames into absolute paths
const search = search_.map(file => asAbsolute(file, path));
const search = search_.map((file) => asAbsolute(file, path));
// Compile list of ignored patterns and files
const dockerIgnore = await maybeRead(resolve(path, '.dockerignore'), null);
@@ -382,7 +378,7 @@ export async function docker(
.createFilter();
const prefixLength = path.length + 1;
const accepts = function(file: string) {
const accepts = function (file: string) {
const relativePath = file.substr(prefixLength);
if (relativePath === '') {
@@ -415,24 +411,6 @@ export async function docker(
return uniqueStrings(files);
}
/**
* Get a list of all files inside the project folder
*
* @param {String} of the current working directory
* @param {Object} output instance
* @return {Array} of {String}s with the found files
*/
export async function getAllProjectFiles(cwd: string, { debug }: Output) {
// We need a slash at the end to remove it later on from the matched files
const current = join(resolve(cwd), '/');
debug(`Searching files inside of ${current}`);
const list = await glob('**', { cwd: current, absolute: true, nodir: true });
// We need to replace \ with / for windows
return list.map(file => file.replace(current.replace(/\\/g, '/'), ''));
}
interface ExplodeOptions {
accepts: (file: string) => boolean;
output: Output;
@@ -482,7 +460,7 @@ async function explode(
if (s.isDirectory()) {
const all = await fs.readdir(file);
/* eslint-disable no-use-before-define */
const recursive = many(all.map(subdir => asAbsolute(subdir, file)));
const recursive = many(all.map((subdir) => asAbsolute(subdir, file)));
return (recursive as any) as Promise<string | null>;
/* eslint-enable no-use-before-define */
}
@@ -494,7 +472,7 @@ async function explode(
return path;
};
const many = (all: string[]) => Promise.all(all.map(file => list(file)));
const many = (all: string[]) => Promise.all(all.map((file) => list(file)));
const arrayOfArrays = await many(paths);
return flatten(arrayOfArrays).filter(notNull);
}

View File

@@ -145,6 +145,7 @@ export default class Now extends EventEmitter {
regions,
target: target || undefined,
projectSettings,
source: 'cli',
};
// Ignore specific items from vercel.json

View File

@@ -0,0 +1,283 @@
import test from 'ava';
import { validateConfig } from '../src/util/dev/validate';
test('[dev-validate] should not error with empty config', async (t) => {
const config = {};
const error = validateConfig(config);
t.deepEqual(error, null);
});
test('[dev-validate] should not error with complete config', async (t) => {
const config = {
version: 2,
public: true,
regions: ['sfo1', 'iad1'],
cleanUrls: true,
headers: [{ source: '/', headers: [{ key: 'x-id', value: '123' }] }],
rewrites: [{ source: '/help', destination: '/support' }],
redirects: [{ source: '/kb', destination: 'https://example.com' }],
trailingSlash: false,
functions: { 'api/user.go': { memory: 128, maxDuration: 5 } },
};
const error = validateConfig(config);
t.deepEqual(error, null);
});
test('[dev-validate] should not error with builds and routes', async (t) => {
const config = {
builds: [{ src: 'api/index.js', use: '@vercel/node' }],
routes: [{ src: '/(.*)', dest: '/api/index.js' }],
};
const error = validateConfig(config);
t.deepEqual(error, null);
});
test('[dev-validate] should error with invalid rewrites due to additional property and offer suggestion', async (t) => {
const config = {
rewrites: [{ src: '/(.*)', dest: '/api/index.js' }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `rewrites[0]` should NOT have additional property `src`. Did you mean `source`?'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/rewrites'
);
});
test('[dev-validate] should error with invalid routes due to additional property and offer suggestion', async (t) => {
const config = {
routes: [{ source: '/(.*)', destination: '/api/index.js' }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `routes[0]` should NOT have additional property `source`. Did you mean `src`?'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/routes'
);
});
test('[dev-validate] should error with invalid routes array type', async (t) => {
const config = {
routes: { src: '/(.*)', dest: '/api/index.js' },
};
const error = validateConfig(config);
t.deepEqual(error.message, 'Invalid vercel.json - `routes` should be array.');
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/routes'
);
});
test('[dev-validate] should error with invalid redirects array object', async (t) => {
const config = {
redirects: [
{
/* intentionally empty */
},
],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `redirects[0]` missing required property `source`.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/redirects'
);
});
test('[dev-validate] should error with invalid redirects.permanent poperty', async (t) => {
const config = {
redirects: [{ source: '/', destination: '/go', permanent: 'yes' }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `redirects[0].permanent` should be boolean.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/redirects'
);
});
test('[dev-validate] should error with invalid cleanUrls type', async (t) => {
const config = {
cleanUrls: 'true',
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `cleanUrls` should be boolean.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/cleanurls'
);
});
test('[dev-validate] should error with invalid trailingSlash type', async (t) => {
const config = {
trailingSlash: [true],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `trailingSlash` should be boolean.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/trailingslash'
);
});
test('[dev-validate] should error with invalid headers property', async (t) => {
const config = {
headers: [{ 'Content-Type': 'text/html' }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[0]` should NOT have additional property `Content-Type`. Please remove it.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with invalid headers.source type', async (t) => {
const config = {
headers: [{ source: [{ 'Content-Type': 'text/html' }] }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[0].source` should be string.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with invalid headers additional property', async (t) => {
const config = {
headers: [{ source: '/', stuff: [{ 'Content-Type': 'text/html' }] }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[0]` should NOT have additional property `stuff`. Please remove it.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with invalid headers wrong nested headers type', async (t) => {
const config = {
headers: [{ source: '/', headers: [{ 'Content-Type': 'text/html' }] }],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[0].headers[0]` should NOT have additional property `Content-Type`. Please remove it.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with invalid headers wrong nested headers additional property', async (t) => {
const config = {
headers: [
{ source: '/', headers: [{ key: 'Content-Type', val: 'text/html' }] },
],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[0].headers[0]` should NOT have additional property `val`. Please remove it.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with too many redirects', async (t) => {
const config = {
redirects: Array.from({ length: 5000 }).map((_, i) => ({
source: `/${i}`,
destination: `/v/${i}`,
})),
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `redirects` should NOT have more than 1024 items.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/redirects'
);
});
test('[dev-validate] should error with too many nested headers', async (t) => {
const config = {
headers: [
{
source: '/',
headers: [{ key: `x-id`, value: `123` }],
},
{
source: '/too-many',
headers: Array.from({ length: 5000 }).map((_, i) => ({
key: `${i}`,
value: `${i}`,
})),
},
],
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'Invalid vercel.json - `headers[1].headers` should NOT have more than 1024 items.'
);
t.deepEqual(
error.link,
'https://vercel.com/docs/configuration#project/headers'
);
});
test('[dev-validate] should error with "functions" and "builds"', async (t) => {
const config = {
builds: [
{
src: 'index.html',
use: '@vercel/static',
},
],
functions: {
'api/test.js': {
memory: 1024,
},
},
};
const error = validateConfig(config);
t.deepEqual(
error.message,
'The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.'
);
t.deepEqual(error.link, 'https://vercel.link/functions-and-builds');
});

View File

@@ -0,0 +1 @@
proof goes here

View File

@@ -3,7 +3,7 @@
"private": true,
"scripts": {
"build": "gridsome build",
"develop": "gridsome develop",
"dev": "gridsome develop -p $PORT",
"explore": "gridsome explore"
},
"dependencies": {

View File

@@ -0,0 +1,14 @@
<template>
<Layout>
<h1>Not Found</h1>
<p>This is a Custom Gridsome 404.</p>
</Layout>
</template>
<script>
export default {
metaInfo: {
title: 'Not Found'
}
}
</script>

View File

@@ -1,11 +1,11 @@
<template>
<Layout>
<!-- Learn how to use images here: https://gridsome.org/docs/images -->
<g-image alt="Example image" src="~/favicon.png" width="135" />
<h1>Hello, world!</h1>
<h1>Gridsome on Vercel</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur excepturi labore tempore expedita, et iste tenetur suscipit explicabo! Dolores, aperiam non officia eos quod asperiores
</p>

View File

@@ -0,0 +1,3 @@
{
"redirects": [{ "source": "/support", "destination": "/about?ref=support" }]
}

View File

@@ -0,0 +1 @@
<h1>Contact Us</h1>

View File

@@ -0,0 +1,3 @@
{
"rewrites": [{ "source": "/support", "destination": "/contact.html" }]
}

View File

@@ -0,0 +1,3 @@
export default function Contact() {
return <h1>Contact Page</h1>;
}

View File

@@ -0,0 +1,3 @@
{
"rewrites": [{ "source": "/support", "destination": "/contact" }]
}

View File

@@ -0,0 +1 @@
.vercel

View File

@@ -0,0 +1,10 @@
package handler
import (
"fmt"
"net/http"
)
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Req Path: %s", r.URL.Path)
}

View File

@@ -0,0 +1,10 @@
package another
import (
"fmt"
"net/http"
)
func Another(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is another page")
}

View File

@@ -0,0 +1,10 @@
package handler
import (
"fmt"
"net/http"
)
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the index page")
}

View File

@@ -1 +1 @@
{ "env": { "FOO": "bar" } }
{"env":{"FOO":"bar"}}

View File

@@ -0,0 +1,6 @@
module.exports = {
assetPrefix: '/blog',
env: {
ASSET_PREFIX: '/blog',
},
};

View File

@@ -0,0 +1,10 @@
{
"name": "with-zones-blog",
"version": "1.0.0",
"dependencies": {
"next": "latest",
"react": "latest",
"react-dom": "latest"
},
"license": "ISC"
}

View File

@@ -0,0 +1,22 @@
import Link from 'next/link';
export default function Blog() {
return (
<div>
<h3>This is our blog</h3>
<ul>
<li>
<Link href="/blog/post/[id]" as="/blog/post/1">
<a>Post 1</a>
</Link>
</li>
<li>
<Link href="/blog/post/[id]" as="/blog/post/2">
<a>Post 2</a>
</Link>
</li>
</ul>
<a href="/">Home</a>
</div>
);
}

View File

@@ -0,0 +1,15 @@
import Link from 'next/link'
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
return (
<div>
<h3>Post #{router.query.id}</h3>
<p>Lorem ipsum</p>
<Link href="/blog">
<a>Back to blog</a>
</Link>
</div>
)
}

View File

@@ -0,0 +1,7 @@
const Header = () => (
<div>
<h2>The Company</h2>
</div>
);
export default Header;

View File

@@ -0,0 +1,10 @@
{
"name": "with-zones-home",
"version": "1.0.0",
"dependencies": {
"next": "latest",
"react": "latest",
"react-dom": "latest"
},
"license": "ISC"
}

View File

@@ -0,0 +1,21 @@
import Link from 'next/link';
const About = ({ id }) => {
return (
<div>
<p>This is the {id} page with static props.</p>
<div>
<Link href="/">
<a>Go Back</a>
</Link>
</div>
</div>
);
};
export const getStaticProps = ({ params }) => {
return { props: { id: params.id } };
};
export const getStaticPaths = () => ({ paths: ['/1/dynamic'], fallback: true });
export default About;

View File

@@ -0,0 +1,19 @@
import Link from 'next/link';
import { useRouter } from 'next/router';
const About = () => {
const router = useRouter();
const { id } = router.query;
return (
<div>
<p>This is the {id} page without static props.</p>
<div>
<Link href="/">
<a>Go Back</a>
</Link>
</div>
</div>
);
};
export default About;

View File

@@ -0,0 +1,19 @@
import Link from 'next/link';
import { useRouter } from 'next/router';
const About = () => {
const router = useRouter();
const { id } = router.query;
return (
<div>
<p>This is the about static page.</p>
<div>
<Link href="/">
<a>Go Back</a>
</Link>
</div>
</div>
);
};
export default About;

View File

@@ -0,0 +1,36 @@
import Link from 'next/link';
import dynamic from 'next/dynamic';
const Header = dynamic(import('../components/Header'));
export default function Home() {
return (
<div>
<Header />
<p>This is our homepage</p>
<div>
<a href="/blog">Blog</a>
</div>
<div>
<Link href="/about">
<a>About us</a>
</Link>
</div>
<div>
<Link href="/foo">
<a>foo</a>
</Link>
</div>
<div>
<Link href="/1/dynamic">
<a>1/dynamic</a>
</Link>
</div>
<div>
<Link href="/1/foo">
<a>1/foo</a>
</Link>
</div>
</div>
);
}

View File

@@ -0,0 +1,11 @@
{
"name": "with-zones-example",
"private": true,
"workspaces": [
"home",
"blog"
],
"devDependencies": {
"vercel": "canary"
}
}

View File

@@ -0,0 +1,12 @@
{
"version": 2,
"builds": [
{ "src": "blog/package.json", "use": "@vercel/next@canary" },
{ "src": "home/package.json", "use": "@vercel/next@canary" }
],
"routes": [
{ "src": "/blog/_next(.*)", "dest": "blog/_next$1" },
{ "src": "/blog(.*)", "dest": "blog/blog$1" },
{ "src": "(.*)", "dest": "home$1" }
]
}

File diff suppressed because it is too large Load Diff

View File

@@ -1 +1 @@
{ "builds": [{ "src": "index.js", "use": "@vercel/node@canary" }] }
{"builds":[{"src":"index.js","use":"@vercel/node@canary"}]}

View File

@@ -0,0 +1,4 @@
module.exports = (req, res) => {
const months = [...Array(12).keys()].map(month => month + 1);
res.json({ months });
};

View File

@@ -0,0 +1,15 @@
const { PCRE } = require('pcre-to-regexp');
// `ts-node` default "target" is "es5" which transpiles `class` statements and
// is incompatible with dependencies that use ES6 native `class`. Setting the
// "target" to "es2018" or newer prevents the `class` transpilation.
//
// See: https://github.com/vercel/vercel/discussions/4724
// See: https://github.com/TypeStrong/ts-node/issues/903
class P extends PCRE {}
export default (req, res) => {
const p = new P('hi'); // This line should not throw an error
console.log(p);
res.send({ ok: true });
};

View File

@@ -0,0 +1,15 @@
{
"name": "node-ts-node-target",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"pcre-to-regexp": "1.1.0"
}
}

View File

@@ -0,0 +1,5 @@
{
"compilerOptions": {
"module": "CommonJS"
}
}

View File

@@ -0,0 +1,8 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
pcre-to-regexp@1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/pcre-to-regexp/-/pcre-to-regexp-1.1.0.tgz#1c48373d194b982e1416031b41470839fab3ad6c"
integrity sha512-KF9XxmUQJ2DIlMj3TqNqY1AWvyvTuIuq11CuuekxyaYMiFuMKGgQrePYMX5bXKLhLG3sDI4CsGAYHPaT7VV7+g==

View File

@@ -1 +1,2 @@
!public
.vercel

View File

@@ -0,0 +1 @@
We come in peace

View File

@@ -1,4 +1,5 @@
import ms from 'ms';
import os from 'os';
import fs from 'fs-extra';
import test from 'ava';
import { join, resolve, delimiter } from 'path';
@@ -16,8 +17,8 @@ const isCanary = () => getDistTag(cliVersion) === 'canary';
let port = 3000;
const binaryPath = resolve(__dirname, `../../scripts/start.js`);
const fixture = name => join('test', 'dev', 'fixtures', name);
const fixtureAbsolute = name => join(__dirname, 'fixtures', name);
const fixture = (name) => join('test', 'dev', 'fixtures', name);
const fixtureAbsolute = (name) => join(__dirname, 'fixtures', name);
let processCounter = 0;
const processList = new Map();
@@ -56,7 +57,7 @@ function fetchWithRetry(url, retries = 3, opts = {}) {
function createResolver() {
let resolver;
const p = new Promise(res => (resolver = res));
const p = new Promise((res) => (resolver = res));
p.resolve = resolver;
return p;
}
@@ -74,7 +75,7 @@ function printOutput(fixture, stdout, stderr) {
stderr
).split('\n');
const getPrefix = nr => {
const getPrefix = (nr) => {
return nr === 0 ? '╭' : nr === lines.length - 1 ? '╰' : '│';
};
@@ -195,10 +196,10 @@ async function testFixture(directory, opts = {}, args = []) {
dev.stdout.setEncoding('utf8');
dev.stderr.setEncoding('utf8');
dev.stdout.on('data', data => {
dev.stdout.on('data', (data) => {
stdout += data;
});
dev.stderr.on('data', data => {
dev.stderr.on('data', (data) => {
stderr += data;
if (stderr.includes('Ready! Available at')) {
@@ -242,7 +243,7 @@ function testFixtureStdio(
fn,
{ expectedCode = 0, skipDeploy } = {}
) {
return async t => {
return async (t) => {
const cwd = fixtureAbsolute(directory);
const token = await fetchTokenWithRetry();
let deploymentUrl;
@@ -297,11 +298,11 @@ function testFixtureStdio(
dev.stdout.pipe(process.stdout);
dev.stderr.pipe(process.stderr);
dev.stdout.on('data', data => {
dev.stdout.on('data', (data) => {
stdout += data;
});
dev.stderr.on('data', data => {
dev.stderr.on('data', (data) => {
stderr += data;
if (stderr.includes('Ready! Available at')) {
@@ -379,7 +380,7 @@ test.afterEach(async () => {
);
});
test('[vercel dev] prints `npm install` errors', async t => {
test('[vercel dev] prints `npm install` errors', async (t) => {
const dir = fixture('runtime-not-installed');
const result = await exec(dir);
t.truthy(result.stderr.includes('npm ERR! 404'));
@@ -391,7 +392,7 @@ test('[vercel dev] prints `npm install` errors', async t => {
);
});
test('[vercel dev] `vercel.json` should be invalidated if deleted', async t => {
test('[vercel dev] `vercel.json` should be invalidated if deleted', async (t) => {
const dir = fixture('invalidate-vercel-config');
const configPath = join(dir, 'vercel.json');
const originalConfig = await fs.readJSON(configPath);
@@ -422,7 +423,7 @@ test('[vercel dev] `vercel.json` should be invalidated if deleted', async t => {
}
});
test('[vercel dev] reflects changes to config and env without restart', async t => {
test('[vercel dev] reflects changes to config and env without restart', async (t) => {
const dir = fixture('node-helpers');
const configPath = join(dir, 'vercel.json');
const originalConfig = await fs.readJSON(configPath);
@@ -526,16 +527,45 @@ test('[vercel dev] reflects changes to config and env without restart', async t
}
});
test('[vercel dev] `@vercel/node` TypeScript should be resolved by default', async (t) => {
// The purpose of this test is to test that `@vercel/node` can properly
// resolve the default "typescript" module when the project doesn't include
// its own version. To properly test for this, a fixture needs to be created
// *outside* of the `vercel` repo, since otherwise the root-level
// "node_modules/typescript" is resolved as relative to the project, and
// not relative to `@vercel/node` which is what we are testing for here.
const dir = join(os.tmpdir(), 'vercel-node-typescript-resolve-test');
const apiDir = join(dir, 'api');
await fs.mkdirp(apiDir);
await fs.writeFile(
join(apiDir, 'hello.js'),
'export default (req, res) => { res.end("world"); }'
);
const { dev, port, readyResolver } = await testFixture(dir);
try {
await readyResolver;
const res = await fetch(`http://localhost:${port}/api/hello`);
const body = await res.text();
t.is(body, 'world');
} finally {
await dev.kill('SIGTERM');
await fs.remove(dir);
}
});
test(
'[vercel dev] validate routes that use `check: true`',
testFixtureStdio('routes-check-true', async testPath => {
testFixtureStdio('routes-check-true', async (testPath) => {
await testPath(200, '/blog/post', 'Blog Home');
})
);
test(
'[vercel dev] validate routes that use `check: true` and `status` code',
testFixtureStdio('routes-check-true-status', async testPath => {
testFixtureStdio('routes-check-true-status', async (testPath) => {
await testPath(403, '/secret');
await testPath(200, '/post', 'This is a post.');
await testPath(200, '/post.html', 'This is a post.');
@@ -544,7 +574,7 @@ test(
test(
'[vercel dev] validate routes that use custom 404 page',
testFixtureStdio('routes-custom-404', async testPath => {
testFixtureStdio('routes-custom-404', async (testPath) => {
await testPath(200, '/', 'Home Page');
await testPath(404, '/nothing', 'Custom User 404');
await testPath(404, '/exact', 'Exact Custom 404');
@@ -555,7 +585,7 @@ test(
test(
'[vercel dev] handles miss after route',
testFixtureStdio('handle-miss-after-route', async testPath => {
testFixtureStdio('handle-miss-after-route', async (testPath) => {
await testPath(200, '/post', 'Blog Post Page', {
test: '1',
override: 'one',
@@ -565,7 +595,7 @@ test(
test(
'[vercel dev] handles miss after rewrite',
testFixtureStdio('handle-miss-after-rewrite', async testPath => {
testFixtureStdio('handle-miss-after-rewrite', async (testPath) => {
await testPath(200, '/post', 'Blog Post Page', {
test: '1',
override: 'one',
@@ -591,7 +621,7 @@ test(
test(
'[vercel dev] does not display directory listing after 404',
testFixtureStdio('handle-miss-hide-dir-list', async testPath => {
testFixtureStdio('handle-miss-hide-dir-list', async (testPath) => {
await testPath(404, '/post');
await testPath(200, '/post/one.html', 'First Post');
})
@@ -599,7 +629,7 @@ test(
test(
'[vercel dev] should preserve query string even after miss phase',
testFixtureStdio('handle-miss-querystring', async testPath => {
testFixtureStdio('handle-miss-querystring', async (testPath) => {
await testPath(200, '/', 'Index Page');
if (process.env.CI && process.platform === 'darwin') {
console.log('Skipping since GH Actions hangs for some reason');
@@ -612,30 +642,31 @@ test(
test(
'[vercel dev] handles hit after handle: filesystem',
testFixtureStdio('handle-hit-after-fs', async testPath => {
testFixtureStdio('handle-hit-after-fs', async (testPath) => {
await testPath(200, '/blog.html', 'Blog Page', { test: '1' });
})
);
test(
'[vercel dev] handles hit after dest',
testFixtureStdio('handle-hit-after-dest', async testPath => {
testFixtureStdio('handle-hit-after-dest', async (testPath) => {
await testPath(200, '/post', 'Blog Post', { test: '1', override: 'one' });
})
);
test(
'[vercel dev] handles hit after rewrite',
testFixtureStdio('handle-hit-after-rewrite', async testPath => {
testFixtureStdio('handle-hit-after-rewrite', async (testPath) => {
await testPath(200, '/post', 'Blog Post', { test: '1', override: 'one' });
})
);
test(
'[vercel dev] should serve the public directory and api functions',
testFixtureStdio('public-and-api', async testPath => {
testFixtureStdio('public-and-api', async (testPath) => {
await testPath(200, '/', 'This is the home page');
await testPath(200, '/about.html', 'This is the about page');
await testPath(200, '/.well-known/humans.txt', 'We come in peace');
await testPath(200, '/api/date', /current date/);
await testPath(200, '/api/rand', /random number/);
await testPath(200, '/api/rand.js', /random number/);
@@ -646,7 +677,7 @@ test(
test(
'[vercel dev] should allow user rewrites for path segment files',
testFixtureStdio('test-zero-config-rewrite', async testPath => {
testFixtureStdio('test-zero-config-rewrite', async (testPath) => {
await testPath(404, '/');
await testPath(200, '/echo/1', '{"id":"1"}', {
'Access-Control-Allow-Origin': '*',
@@ -657,81 +688,84 @@ test(
})
);
test('[vercel dev] validate builds', async t => {
test('[vercel dev] validate builds', async (t) => {
const directory = fixture('invalid-builds');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `builds` property: \[0\]\.src should be string/m
/Invalid vercel\.json - `builds\[0\].src` should be string/m
);
});
test('[vercel dev] validate routes', async t => {
test('[vercel dev] validate routes', async (t) => {
const directory = fixture('invalid-routes');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `routes` property: \[0\]\.src should be string/m
/Invalid vercel\.json - `routes\[0\].src` should be string/m
);
});
test('[vercel dev] validate cleanUrls', async t => {
test('[vercel dev] validate cleanUrls', async (t) => {
const directory = fixture('invalid-clean-urls');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(output.stderr, /Invalid `cleanUrls` property:\s+should be boolean/m);
t.regex(
output.stderr,
/Invalid vercel\.json - `cleanUrls` should be boolean/m
);
});
test('[vercel dev] validate trailingSlash', async t => {
test('[vercel dev] validate trailingSlash', async (t) => {
const directory = fixture('invalid-trailing-slash');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `trailingSlash` property:\s+should be boolean/m
/Invalid vercel\.json - `trailingSlash` should be boolean/m
);
});
test('[vercel dev] validate rewrites', async t => {
test('[vercel dev] validate rewrites', async (t) => {
const directory = fixture('invalid-rewrites');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `rewrites` property: \[0\]\.destination should be string/m
/Invalid vercel\.json - `rewrites\[0\].destination` should be string/m
);
});
test('[vercel dev] validate redirects', async t => {
test('[vercel dev] validate redirects', async (t) => {
const directory = fixture('invalid-redirects');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `redirects` property: \[0\]\.statusCode should be integer/m
/Invalid vercel\.json - `redirects\[0\].statusCode` should be integer/m
);
});
test('[vercel dev] validate headers', async t => {
test('[vercel dev] validate headers', async (t) => {
const directory = fixture('invalid-headers');
const output = await exec(directory);
t.is(output.exitCode, 1, formatOutput(output));
t.regex(
output.stderr,
/Invalid `headers` property: \[0\]\.headers\[0\]\.value should be string/m
/Invalid vercel\.json - `headers\[0\].headers\[0\].value` should be string/m
);
});
test('[vercel dev] validate mixed routes and rewrites', async t => {
test('[vercel dev] validate mixed routes and rewrites', async (t) => {
const directory = fixture('invalid-mixed-routes-rewrites');
const output = await exec(directory);
@@ -744,7 +778,7 @@ test('[vercel dev] validate mixed routes and rewrites', async t => {
});
// Test seems unstable: It won't return sometimes.
test('[vercel dev] validate env var names', async t => {
test('[vercel dev] validate env var names', async (t) => {
const directory = fixture('invalid-env-var-name');
const { dev } = await testFixture(directory, { stdio: 'pipe' });
@@ -753,7 +787,7 @@ test('[vercel dev] validate env var names', async t => {
dev.stderr.setEncoding('utf8');
await new Promise((resolve, reject) => {
dev.stderr.on('data', b => {
dev.stderr.on('data', (b) => {
stderr += b.toString();
if (
@@ -783,7 +817,7 @@ test('[vercel dev] validate env var names', async t => {
test(
'[vercel dev] test rewrites with segments serve correct content',
testFixtureStdio('test-rewrites-with-segments', async testPath => {
testFixtureStdio('test-rewrites-with-segments', async (testPath) => {
await testPath(200, '/api/users/first', 'first');
await testPath(200, '/api/fourty-two', '42');
await testPath(200, '/rand', '42');
@@ -794,14 +828,14 @@ test(
test(
'[vercel dev] test rewrites serve correct content',
testFixtureStdio('test-rewrites', async testPath => {
testFixtureStdio('test-rewrites', async (testPath) => {
await testPath(200, '/hello', 'Hello World');
})
);
test(
'[vercel dev] test rewrites and redirects is case sensitive',
testFixtureStdio('test-routing-case-sensitive', async testPath => {
testFixtureStdio('test-routing-case-sensitive', async (testPath) => {
await testPath(200, '/Path', 'UPPERCASE');
await testPath(200, '/path', 'lowercase');
await testPath(308, '/GoTo', 'Redirecting to /upper.html (308)', {
@@ -815,7 +849,7 @@ test(
test(
'[vercel dev] test cleanUrls serve correct content',
testFixtureStdio('test-clean-urls', async testPath => {
testFixtureStdio('test-clean-urls', async (testPath) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/about', 'About Page');
await testPath(200, '/sub', 'Sub Index Page');
@@ -841,7 +875,7 @@ test(
test(
'[vercel dev] should serve custom 404 when `cleanUrls: true`',
testFixtureStdio('test-clean-urls-custom-404', async testPath => {
testFixtureStdio('test-clean-urls-custom-404', async (testPath) => {
await testPath(200, '/', 'This is the home page');
await testPath(200, '/about', 'The about page');
await testPath(200, '/contact/me', 'Contact Me Subdirectory');
@@ -852,7 +886,7 @@ test(
test(
'[vercel dev] test cleanUrls and trailingSlash serve correct content',
testFixtureStdio('test-clean-urls-trailing-slash', async testPath => {
testFixtureStdio('test-clean-urls-trailing-slash', async (testPath) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/about/', 'About Page');
await testPath(200, '/sub/', 'Sub Index Page');
@@ -879,7 +913,7 @@ test(
test(
'[vercel dev] test cors headers work with OPTIONS',
testFixtureStdio('test-cors-routes', async testPath => {
testFixtureStdio('test-cors-routes', async (testPath) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
@@ -898,7 +932,7 @@ test(
test(
'[vercel dev] test trailingSlash true serve correct content',
testFixtureStdio('test-trailing-slash', async testPath => {
testFixtureStdio('test-trailing-slash', async (testPath) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/index.html', 'Index Page');
await testPath(200, '/about.html', 'About Page');
@@ -920,7 +954,7 @@ test(
test(
'[vercel dev] should serve custom 404 when `trailingSlash: true`',
testFixtureStdio('test-trailing-slash-custom-404', async testPath => {
testFixtureStdio('test-trailing-slash-custom-404', async (testPath) => {
await testPath(200, '/', 'This is the home page');
await testPath(200, '/about.html', 'The about page');
await testPath(200, '/contact/', 'Contact Subdirectory');
@@ -930,7 +964,7 @@ test(
test(
'[vercel dev] test trailingSlash false serve correct content',
testFixtureStdio('test-trailing-slash-false', async testPath => {
testFixtureStdio('test-trailing-slash-false', async (testPath) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/index.html', 'Index Page');
await testPath(200, '/about.html', 'About Page');
@@ -959,7 +993,7 @@ test(
'[vercel dev] throw when invalid builder routes detected',
testFixtureStdio(
'invalid-builder-routes',
async testPath => {
async (testPath) => {
await testPath(
500,
'/',
@@ -972,28 +1006,43 @@ test(
test(
'[vercel dev] support legacy `@now` scope runtimes',
testFixtureStdio('legacy-now-runtime', async testPath => {
testFixtureStdio('legacy-now-runtime', async (testPath) => {
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
})
);
test(
'[vercel dev] support dynamic next.js routes in monorepos',
testFixtureStdio('monorepo-dynamic-paths', async (testPath) => {
await testPath(200, '/', /This is our homepage/m);
await testPath(200, '/about', /This is the about static page./m);
await testPath(
200,
'/1/dynamic',
/This is the (.*)dynamic(.*) page with static props./m
);
})
);
test(
'[vercel dev] 00-list-directory',
testFixtureStdio('00-list-directory', async testPath => {
testFixtureStdio('00-list-directory', async (testPath) => {
await testPath(200, '/', /Files within/m);
await testPath(200, '/', /test[0-3]\.txt/m);
await testPath(200, '/', /\.well-known/m);
await testPath(200, '/.well-known/keybase.txt', 'proof goes here');
})
);
test(
'[vercel dev] 01-node',
testFixtureStdio('01-node', async testPath => {
testFixtureStdio('01-node', async (testPath) => {
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
})
);
// Angular has `engines: { node: "10.x" }` in its `package.json`
test('[vercel dev] 02-angular-node', async t => {
test('[vercel dev] 02-angular-node', async (t) => {
if (shouldSkip(t, '02-angular-node', '10.x')) return;
const directory = fixture('02-angular-node');
@@ -1004,7 +1053,7 @@ test('[vercel dev] 02-angular-node', async t => {
let stderr = '';
try {
dev.stderr.on('data', async data => {
dev.stderr.on('data', async (data) => {
stderr += data.toString();
});
@@ -1034,7 +1083,7 @@ test(
'[vercel dev] 03-aurelia',
testFixtureStdio(
'03-aurelia',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Aurelia Navigation Skeleton/m);
},
{ skipDeploy: true }
@@ -1043,7 +1092,7 @@ test(
test(
'[vercel dev] 04-create-react-app',
testFixtureStdio('04-create-react-app', async testPath => {
testFixtureStdio('04-create-react-app', async (testPath) => {
await testPath(200, '/', /React App/m);
})
);
@@ -1057,25 +1106,35 @@ test(
*/
test(
'[vercel dev] 06-gridsome',
testFixtureStdio('06-gridsome', async testPath => {
testFixtureStdio('06-gridsome', async (testPath) => {
await testPath(200, '/');
await testPath(200, '/about');
await testPath(308, '/support', 'Redirecting to /about?ref=support (308)', {
Location: '/about?ref=support',
});
// Bug with gridsome's dev server: https://github.com/gridsome/gridsome/issues/831
// Works in prod only so leave out for now
// await testPath(404, '/nothing');
})
);
test(
'[vercel dev] 07-hexo-node',
testFixtureStdio('07-hexo-node', async testPath => {
testFixtureStdio('07-hexo-node', async (testPath) => {
await testPath(200, '/', /Hexo \+ Node.js API/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
await testPath(200, '/contact.html', /Contact Us/m);
await testPath(200, '/support', /Contact Us/m);
})
);
test('[vercel dev] 08-hugo', async t => {
test('[vercel dev] 08-hugo', async (t) => {
if (process.platform === 'darwin') {
// Update PATH to find the Hugo executable installed via GH Actions
process.env.PATH = `${resolve(fixture('08-hugo'))}${delimiter}${
process.env.PATH
}`;
const tester = testFixtureStdio('08-hugo', async testPath => {
const tester = testFixtureStdio('08-hugo', async (testPath) => {
await testPath(200, '/', /Hugo/m);
});
await tester(t);
@@ -1087,9 +1146,11 @@ test('[vercel dev] 08-hugo', async t => {
test(
'[vercel dev] 10-nextjs-node',
testFixtureStdio('10-nextjs-node', async testPath => {
testFixtureStdio('10-nextjs-node', async (testPath) => {
await testPath(200, '/', /Next.js \+ Node.js API/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
await testPath(200, '/contact', /Contact Page/);
await testPath(200, '/support', /Contact Page/);
await testPath(404, '/nothing', /Custom Next 404/);
})
);
@@ -1098,8 +1159,9 @@ test(
'[vercel dev] 12-polymer-node',
testFixtureStdio(
'12-polymer-node',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Polymer \+ Node.js API/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
},
{ skipDeploy: true }
)
@@ -1109,8 +1171,9 @@ test(
'[vercel dev] 13-preact-node',
testFixtureStdio(
'13-preact-node',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Preact/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
},
{ skipDeploy: true }
)
@@ -1120,8 +1183,9 @@ test(
'[vercel dev] 14-svelte-node',
testFixtureStdio(
'14-svelte-node',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Svelte/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
},
{ skipDeploy: true }
)
@@ -1131,8 +1195,9 @@ test(
'[vercel dev] 16-vue-node',
testFixtureStdio(
'16-vue-node',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Vue.js \+ Node.js API/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
},
{ skipDeploy: true }
)
@@ -1142,8 +1207,9 @@ test(
'[vercel dev] 17-vuepress-node',
testFixtureStdio(
'17-vuepress-node',
async testPath => {
async (testPath) => {
await testPath(200, '/', /VuePress \+ Node.js API/m);
await testPath(200, '/api/date', new RegExp(new Date().getFullYear()));
},
{ skipDeploy: true }
)
@@ -1201,7 +1267,7 @@ test(
'[vercel dev] 18-marko',
testFixtureStdio(
'18-marko',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Marko Starter/m);
},
{ skipDeploy: true }
@@ -1212,7 +1278,7 @@ test(
'[vercel dev] 19-mithril',
testFixtureStdio(
'19-mithril',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Mithril on Vercel/m);
},
{ skipDeploy: true }
@@ -1223,7 +1289,7 @@ test(
'[vercel dev] 20-riot',
testFixtureStdio(
'20-riot',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Riot on Vercel/m);
},
{ skipDeploy: true }
@@ -1234,7 +1300,7 @@ test(
'[vercel dev] 21-charge',
testFixtureStdio(
'21-charge',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Welcome to my new Charge site/m);
},
{ skipDeploy: true }
@@ -1245,7 +1311,7 @@ test(
'[vercel dev] 22-brunch',
testFixtureStdio(
'22-brunch',
async testPath => {
async (testPath) => {
await testPath(200, '/', /Bon Appétit./m);
},
{ skipDeploy: true }
@@ -1256,19 +1322,19 @@ test(
'[vercel dev] 23-docusaurus',
testFixtureStdio(
'23-docusaurus',
async testPath => {
async (testPath) => {
await testPath(200, '/', /My Site/m);
},
{ skipDeploy: true }
)
);
test('[vercel dev] 24-ember', async t => {
test('[vercel dev] 24-ember', async (t) => {
if (shouldSkip(t, '24-ember', '>^6.14.0 || ^8.10.0 || >=9.10.0')) return;
const tester = await testFixtureStdio(
'24-ember',
async testPath => {
async (testPath) => {
await testPath(200, '/', /HelloWorld/m);
},
{ skipDeploy: true }
@@ -1310,7 +1376,7 @@ test(
)
);
test('[vercel dev] add a `package.json` to trigger `@vercel/static-build`', async t => {
test('[vercel dev] add a `package.json` to trigger `@vercel/static-build`', async (t) => {
const directory = fixture('trigger-static-build');
await fs.unlink(join(directory, 'package.json')).catch(() => null);
@@ -1353,7 +1419,7 @@ test('[vercel dev] add a `package.json` to trigger `@vercel/static-build`', asyn
await tester(t);
});
test('[vercel dev] no build matches warning', async t => {
test('[vercel dev] no build matches warning', async (t) => {
const directory = fixture('no-build-matches');
const { dev } = await testFixture(directory, {
stdio: ['ignore', 'pipe', 'pipe'],
@@ -1364,8 +1430,8 @@ test('[vercel dev] no build matches warning', async t => {
dev.unref();
dev.stderr.setEncoding('utf8');
await new Promise(resolve => {
dev.stderr.on('data', str => {
await new Promise((resolve) => {
dev.stderr.on('data', (str) => {
if (str.includes('did not match any source files')) {
resolve();
}
@@ -1380,13 +1446,13 @@ test('[vercel dev] no build matches warning', async t => {
test(
'[vercel dev] do not recursivly check the path',
testFixtureStdio('handle-filesystem-missing', async testPath => {
testFixtureStdio('handle-filesystem-missing', async (testPath) => {
await testPath(200, '/', /hello/m);
await testPath(404, '/favicon.txt');
})
);
test('[vercel dev] render warning for empty cwd dir', async t => {
test('[vercel dev] render warning for empty cwd dir', async (t) => {
const directory = fixture('empty');
const { dev, port } = await testFixture(directory, {
stdio: ['ignore', 'pipe', 'pipe'],
@@ -1397,13 +1463,10 @@ test('[vercel dev] render warning for empty cwd dir', async t => {
// Monitor `stderr` for the warning
dev.stderr.setEncoding('utf8');
await new Promise(resolve => {
dev.stderr.on('data', str => {
if (
str.includes(
'There are no files (or only files starting with a dot) inside your deployment'
)
) {
const msg = 'There are no files inside your deployment.';
await new Promise((resolve) => {
dev.stderr.on('data', (str) => {
if (str.includes(msg)) {
resolve();
}
});
@@ -1419,7 +1482,7 @@ test('[vercel dev] render warning for empty cwd dir', async t => {
}
});
test('[vercel dev] do not rebuild for changes in the output directory', async t => {
test('[vercel dev] do not rebuild for changes in the output directory', async (t) => {
const directory = fixture('output-is-source');
// Pack the builder and set it in the `vercel.json`
@@ -1448,7 +1511,7 @@ test('[vercel dev] do not rebuild for changes in the output directory', async t
let stderr = [];
const start = Date.now();
dev.stderr.on('data', str => stderr.push(str));
dev.stderr.on('data', (str) => stderr.push(str));
while (stderr.join('').includes('Ready') === false) {
await sleep(ms('3s'));
@@ -1477,7 +1540,7 @@ test('[vercel dev] do not rebuild for changes in the output directory', async t
test(
'[vercel dev] 25-nextjs-src-dir',
testFixtureStdio('25-nextjs-src-dir', async testPath => {
testFixtureStdio('25-nextjs-src-dir', async (testPath) => {
await testPath(200, '/', /Next.js \+ Node.js API/m);
})
);
@@ -1486,7 +1549,7 @@ test(
'[vercel dev] 26-nextjs-secrets',
testFixtureStdio(
'26-nextjs-secrets',
async testPath => {
async (testPath) => {
await testPath(200, '/api/user', /runtime/m);
await testPath(200, '/', /buildtime/m);
},
@@ -1498,7 +1561,7 @@ test(
'[vercel dev] 27-zero-config-env',
testFixtureStdio(
'27-zero-config-env',
async testPath => {
async (testPath) => {
await testPath(200, '/api/print', /build-and-runtime/m);
await testPath(200, '/', /build-and-runtime/m);
},
@@ -1508,7 +1571,7 @@ test(
test(
'[vercel dev] 28-vercel-json-and-ignore',
testFixtureStdio('28-vercel-json-and-ignore', async testPath => {
testFixtureStdio('28-vercel-json-and-ignore', async (testPath) => {
await testPath(200, '/api/one', 'One');
await testPath(404, '/api/two');
await testPath(200, '/api/three', 'One');
@@ -1517,7 +1580,7 @@ test(
test(
'[vercel dev] Use `@vercel/python` with Flask requirements.txt',
testFixtureStdio('python-flask', async testPath => {
testFixtureStdio('python-flask', async (testPath) => {
const name = 'Alice';
const year = new Date().getFullYear();
await testPath(200, `/api/user?name=${name}`, new RegExp(`Hello ${name}`));
@@ -1528,7 +1591,7 @@ test(
test(
'[vercel dev] Use custom runtime from the "functions" property',
testFixtureStdio('custom-runtime', async testPath => {
testFixtureStdio('custom-runtime', async (testPath) => {
await testPath(200, `/api/user`, /Hello, from Bash!/m);
await testPath(200, `/api/user.sh`, /Hello, from Bash!/m);
})
@@ -1536,7 +1599,7 @@ test(
test(
'[vercel dev] Should work with nested `tsconfig.json` files',
testFixtureStdio('nested-tsconfig', async testPath => {
testFixtureStdio('nested-tsconfig', async (testPath) => {
await testPath(200, `/`, /Nested tsconfig.json test page/);
await testPath(200, `/api`, 'Nested `tsconfig.json` API endpoint');
})
@@ -1544,7 +1607,7 @@ test(
test(
'[vercel dev] Should force `tsc` option "module: commonjs" for `startDevServer()`',
testFixtureStdio('force-module-commonjs', async testPath => {
testFixtureStdio('force-module-commonjs', async (testPath) => {
await testPath(200, `/`, /Force &quot;module: commonjs&quot; test page/);
await testPath(
200,
@@ -1561,8 +1624,33 @@ test(
test(
'[vercel dev] should prioritize index.html over other file named index.*',
testFixtureStdio('index-html-priority', async testPath => {
testFixtureStdio('index-html-priority', async (testPath) => {
await testPath(200, '/', 'This is index.html');
await testPath(200, '/index.css', 'This is index.css');
})
);
test(
'[vercel dev] Should support `*.go` API serverless functions',
testFixtureStdio('go', async (testPath) => {
await testPath(200, `/api`, 'This is the index page');
await testPath(200, `/api/index`, 'This is the index page');
await testPath(200, `/api/index.go`, 'This is the index page');
await testPath(200, `/api/another`, 'This is another page');
await testPath(200, '/api/another.go', 'This is another page');
await testPath(200, `/api/foo`, 'Req Path: /api/foo');
await testPath(200, `/api/bar`, 'Req Path: /api/bar');
})
);
test(
'[vercel dev] Should set the `ts-node` "target" to match Node.js version',
testFixtureStdio('node-ts-node-target', async (testPath) => {
await testPath(200, `/api/subclass`, '{"ok":true}');
await testPath(
200,
`/api/array`,
'{"months":[1,2,3,4,5,6,7,8,9,10,11,12]}'
);
})
);

View File

@@ -122,6 +122,7 @@ module.exports = async session => {
'single-dotfile': {
'.testing': 'i am a dotfile',
},
'empty-directory': {},
'config-scope-property-email': {
'now.json': `{ "scope": "${session}@zeit.pub", "builds": [ { "src": "*.html", "use": "@now/static" } ], "version": 2 }`,
'index.html': '<span>test scope email</span',
@@ -138,6 +139,10 @@ module.exports = async session => {
'vercel.json': '{"fake": 1}',
'index.html': '<h1>Fake</h1>',
},
'builds-wrong-build-env': {
'vercel.json': '{ "build.env": { "key": "value" } }',
'index.html': '<h1>Should fail</h1>',
},
'builds-no-list': {
'now.json': `{
"version": 2,
@@ -467,7 +472,7 @@ CMD ["node", "index.js"]`,
'now.json': JSON.stringify({
functions: {
'api/**/*.php': {
runtime: 'now-php@0.0.8',
runtime: 'vercel-php@0.1.0',
},
},
}),
@@ -478,7 +483,7 @@ CMD ["node", "index.js"]`,
functions: {
'api/**/*.php': {
memory: 128,
runtime: 'now-php@canary',
runtime: 'vercel-php@canary',
},
},
}),
@@ -496,12 +501,7 @@ CMD ["node", "index.js"]`,
}),
},
'project-link': {
'pages/index.js': 'export default () => <div><h1>Now CLI test</h1></div>',
'package.json': JSON.stringify({
dependencies: {
gatsby: 'latest',
},
}),
'package.json': JSON.stringify({}),
},
'project-root-directory': {
'src/index.html': '<h1>I am a website.</h1>',

View File

@@ -31,6 +31,8 @@ function execa(file, args, options) {
const binaryPath = path.resolve(__dirname, `../scripts/start.js`);
const fixture = name => path.join(__dirname, 'fixtures', 'integration', name);
const example = name =>
path.join(__dirname, '..', '..', '..', 'examples', name);
const deployHelpMessage = `${logo} vercel [options] <command | path>`;
let session = 'temp-session';
@@ -243,8 +245,10 @@ test.after.always(async () => {
loginApiServer.close();
}
// Make sure the token gets revoked
await execa(binaryPath, ['logout', ...defaultArgs]);
// Make sure the token gets revoked unless it's passed in via environment
if (!process.env.VERCEL_TOKEN) {
await execa(binaryPath, ['logout', ...defaultArgs]);
}
if (tmpDir) {
// Remove config directory entirely
@@ -252,6 +256,20 @@ test.after.always(async () => {
}
});
test('default command should prompt login with empty auth.json', async t => {
await fs.writeFile(getConfigAuthPath(), JSON.stringify({}));
try {
await execa(binaryPath, [...defaultArgs]);
t.fail();
} catch (err) {
t.true(
err.stderr.includes(
'Error! No existing credentials found. Please run `vercel login` or pass "--token"'
)
);
}
});
test('login', async t => {
t.timeout(ms('1m'));
@@ -511,12 +529,46 @@ test('Deploy `api-env` fixture and test `vercel env` command', async t => {
t.regex(stderr, /Created .env file/gm);
const contents = fs.readFileSync(path.join(target, '.env'), 'utf8');
t.true(contents.startsWith('# Created by Vercel CLI\n'));
const lines = new Set(contents.split('\n'));
t.true(lines.has('MY_ENV_VAR="MY_VALUE"'));
t.true(lines.has('MY_STDIN_VAR="{"expect":"quotes"}"'));
t.true(lines.has('VERCEL_URL=""'));
}
async function nowEnvPullOverwrite() {
const { exitCode, stderr, stdout } = await execa(
binaryPath,
['env', 'pull', ...defaultArgs],
{
reject: false,
cwd: target,
}
);
t.is(exitCode, 0, formatOutput({ stderr, stdout }));
t.regex(stderr, /Overwriting existing .env file/gm);
t.regex(stderr, /Updated .env file/gm);
}
async function nowEnvPullConfirm() {
fs.writeFileSync(path.join(target, '.env'), 'hahaha');
const vc = execa(binaryPath, ['env', 'pull', ...defaultArgs], {
reject: false,
cwd: target,
});
await waitForPrompt(vc, chunk =>
chunk.includes('Found existing file ".env". Do you want to overwrite?')
);
vc.stdin.end('y\n');
const { exitCode, stderr, stdout } = await vc;
t.is(exitCode, 0, formatOutput({ stderr, stdout }));
}
async function nowDeployWithVar() {
const { exitCode, stderr, stdout } = await execa(
binaryPath,
@@ -609,6 +661,8 @@ test('Deploy `api-env` fixture and test `vercel env` command', async t => {
await nowEnvAddSystemEnv();
await nowEnvLsIncludesVar();
await nowEnvPull();
await nowEnvPullOverwrite();
await nowEnvPullConfirm();
await nowDeployWithVar();
await nowEnvRemove();
await nowEnvRemoveWithArgs();
@@ -1304,7 +1358,7 @@ test('set platform version using `--platform-version` to `2`', async t => {
});
test('ensure we render a warning for deployments with no files', async t => {
const directory = fixture('single-dotfile');
const directory = fixture('empty-directory');
const { stderr, stdout, exitCode } = await execa(
binaryPath,
@@ -1327,11 +1381,7 @@ test('ensure we render a warning for deployments with no files', async t => {
console.log(exitCode);
// Ensure the warning is printed
t.true(
stderr.includes(
'There are no files (or only files starting with a dot) inside your deployment.'
)
);
t.regex(stderr, /There are no files inside your deployment/);
// Test if the output is really a URL
const { href, host } = new URL(stdout);
@@ -1341,10 +1391,8 @@ test('ensure we render a warning for deployments with no files', async t => {
t.is(exitCode, 0);
// Send a test request to the deployment
const response = await fetch(href);
const contentType = response.headers.get('content-type');
t.is(contentType, 'text/plain; charset=utf-8');
const res = await fetch(href);
t.is(res.status, 404);
});
test('ensure we render a prompt when deploying home directory', async t => {
@@ -1473,9 +1521,10 @@ test('try to create a builds deployments with wrong now.json', async t => {
t.is(exitCode, 1);
t.true(
stderr.includes(
'Error! The property `builder` is not allowed in now.json please remove it.'
'Error! Invalid now.json - should NOT have additional property `builder`. Did you mean `builds`?'
)
);
t.true(stderr.includes('https://vercel.com/docs/configuration'));
});
test('try to create a builds deployments with wrong vercel.json', async t => {
@@ -1496,9 +1545,35 @@ test('try to create a builds deployments with wrong vercel.json', async t => {
t.is(exitCode, 1);
t.true(
stderr.includes(
'Error! The property `fake` is not allowed in vercel.json please remove it.'
'Error! Invalid vercel.json - should NOT have additional property `fake`. Please remove it.'
)
);
t.true(stderr.includes('https://vercel.com/docs/configuration'));
});
test('try to create a builds deployments with wrong `build.env` property', async t => {
const directory = fixture('builds-wrong-build-env');
const { stderr, stdout, exitCode } = await execa(
binaryPath,
['--public', ...defaultArgs, '--confirm'],
{
cwd: directory,
reject: false,
}
);
t.is(exitCode, 1, formatOutput({ stdout, stderr }));
t.true(
stderr.includes(
'Error! Invalid vercel.json - should NOT have additional property `build.env`. Did you mean `{ "build": { "env": {"name": "value"} } }`?'
),
formatOutput({ stdout, stderr })
);
t.true(
stderr.includes('https://vercel.com/docs/configuration'),
formatOutput({ stdout, stderr })
);
});
test('create a builds deployments with no actual builds', async t => {
@@ -2343,7 +2418,7 @@ test('deploy a Lambda with a specific runtime', async t => {
const { host: url } = new URL(output.stdout);
const [build] = await getDeploymentBuildsByUrl(url);
t.is(build.use, 'now-php@0.0.8', JSON.stringify(build, null, 2));
t.is(build.use, 'vercel-php@0.1.0', JSON.stringify(build, null, 2));
});
test('fail to deploy a Lambda with a specific runtime but without a locked version', async t => {
@@ -2453,7 +2528,7 @@ test('should show prompts to set up project', async t => {
await waitForPrompt(now, chunk =>
chunk.includes(`What's your Development Command?`)
);
now.stdin.write(`yarn dev\n`);
now.stdin.write(`\n`);
await waitForPrompt(now, chunk => chunk.includes('Linked to'));
@@ -2484,6 +2559,41 @@ test('should show prompts to set up project', async t => {
const response = await fetch(new URL(output.stdout).href);
const text = await response.text();
t.is(text.includes('<h1>custom hello</h1>'), true, text);
// Ensure that `vc dev` also uses the configured build command
// and output directory
let stderr = '';
const port = 58351;
const dev = execa(binaryPath, [
'dev',
'--listen',
port,
directory,
...defaultArgs,
]);
dev.stderr.setEncoding('utf8');
try {
dev.stdout.pipe(process.stdout);
dev.stderr.pipe(process.stderr);
await new Promise((resolve, reject) => {
dev.once('exit', (code, signal) => {
reject(`"vc dev" failed with ${signal || code}`);
});
dev.stderr.on('data', data => {
stderr += data;
if (stderr.includes('Ready! Available at')) {
resolve();
}
});
});
const res2 = await fetch(`http://localhost:${port}/`);
const text2 = await res2.text();
t.is(text2.includes('<h1>custom hello</h1>'), true, text2);
} finally {
process.kill(dev.pid, 'SIGTERM');
}
});
test('should prefill "project name" prompt with folder name', async t => {
@@ -2934,3 +3044,36 @@ test('`vc --debug project ls` should output the projects listing', async t => {
formatOutput({ stderr, stdout })
);
});
test('deploy gatsby twice and print cached directories', async t => {
const directory = example('gatsby');
const packageJsonPath = path.join(directory, 'package.json');
const packageJsonOriginal = await readFile(packageJsonPath, 'utf8');
const pkg = JSON.parse(packageJsonOriginal);
async function tryDeploy(cwd) {
await execa(binaryPath, [...defaultArgs, '--public', '--confirm'], {
cwd,
stdio: 'inherit',
reject: true,
});
t.true(true);
}
// Deploy once to populate the cache
await tryDeploy(directory);
// Wait because the cache is not available right away
// See https://codeburst.io/quick-explanation-of-the-s3-consistency-model-6c9f325e3f82
await sleep(60000);
// Update build script to ensure cached files were restored in the next deploy
pkg.scripts.build = `ls -lA && ls .cache && ls public && ${pkg.scripts.build}`;
await writeFile(packageJsonPath, JSON.stringify(pkg));
try {
await tryDeploy(directory);
} finally {
await writeFile(packageJsonPath, packageJsonOriginal);
}
});

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/client",
"version": "8.1.0",
"version": "8.1.1-canary.2",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"homepage": "https://vercel.com",
@@ -38,6 +38,7 @@
]
},
"dependencies": {
"@vercel/build-utils": "2.4.1-canary.2",
"@zeit/fetch": "5.2.0",
"async-retry": "1.2.3",
"async-sema": "3.0.0",

View File

@@ -1,6 +1,6 @@
import { readdir as readRootFolder, lstatSync } from 'fs-extra';
import { relative, isAbsolute, basename } from 'path';
import { relative, isAbsolute } from 'path';
import hashes, { mapToObject } from './utils/hashes';
import { upload } from './upload';
import { buildFileTree, createDebug, parseVercelConfig } from './utils';
@@ -139,17 +139,11 @@ export default function buildCreateDeployment(version: number) {
// This is a useful warning because it prevents people
// from getting confused about a deployment that renders 404.
if (
fileList.length === 0 ||
fileList.every(f => (f ? basename(f).startsWith('.') : true))
) {
debug(
`Deployment path has no files (or only dotfiles). Yielding a warning event`
);
if (fileList.length === 0) {
debug('Deployment path has no files. Yielding a warning event');
yield {
type: 'warning',
payload:
'There are no files (or only files starting with a dot) inside your deployment.',
payload: 'There are no files inside your deployment.',
};
}

View File

@@ -176,6 +176,7 @@ export interface DeploymentOptions extends LegacyDeploymentOptions {
build?: {
env: Dictionary<string>;
};
source?: string;
target?: string;
name?: string;
public?: boolean;

View File

@@ -1,4 +1,13 @@
#!/bin/bash
set -euo pipefail
# Start fresh
rm -rf dist
# Build with `ncc`
ncc build index.ts -e @vercel/build-utils -e @now/build-utils -o dist
ncc build install.ts -e @vercel/build-utils -e @now/build-utils -o dist/install
# Move `install.js` to dist
mv dist/install/index.js dist/install.js
rm -rf dist/install

View File

@@ -0,0 +1,29 @@
package main
import (
"net"
"net/http"
"os"
"strconv"
)
func main() {
// create a new handler
handler := http.HandlerFunc(__HANDLER_FUNC_NAME)
// https://stackoverflow.com/a/43425461/376773
listener, err := net.Listen("tcp", ":0")
if err != nil {
panic(err)
}
port := listener.Addr().(*net.TCPAddr).Port
file := os.NewFile(3, "pipe")
_, err2 := file.Write([]byte(strconv.Itoa(port)))
if err2 != nil {
panic(err2)
}
panic(http.Serve(listener, handler))
}

View File

@@ -3,7 +3,6 @@ import execa from 'execa';
import fetch from 'node-fetch';
import { mkdirp, pathExists } from 'fs-extra';
import { dirname, join } from 'path';
import { homedir } from 'os';
import buildUtils from './build-utils';
import stringArgv from 'string-argv';
const { debug } = buildUtils;
@@ -127,50 +126,35 @@ export async function downloadGo(
platform = process.platform,
arch = process.arch
) {
// Check default `Go` in user machine
const isUserGo = await pathExists(join(homedir(), 'go'));
// Check if `go` is already installed in user's `$PATH`
const { failed, stdout } = await execa('go', ['version'], { reject: false });
// If we found GOPATH in ENV, or default `Go` path exists
// asssume that user have `Go` installed
if (isUserGo || process.env.GOPATH !== undefined) {
const { stdout } = await execa('go', ['version']);
if (parseInt(stdout.split('.')[1]) >= 11) {
return createGo(dir, platform, arch);
}
throw new Error(
`Your current ${stdout} doesn't support Go Modules. Please update.`
);
} else {
// Check `Go` bin in builder CWD
const isGoExist = await pathExists(join(dir, 'bin'));
if (!isGoExist) {
debug(
'Installing `go` v%s to %o for %s %s',
version,
dir,
platform,
arch
);
const url = getGoUrl(version, platform, arch);
debug('Downloading `go` URL: %o', url);
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to download: ${url} (${res.status})`);
}
// TODO: use a zip extractor when `ext === "zip"`
await mkdirp(dir);
await new Promise((resolve, reject) => {
res.body
.on('error', reject)
.pipe(tar.extract({ cwd: dir, strip: 1 }))
.on('error', reject)
.on('finish', resolve);
});
}
if (!failed && parseInt(stdout.split('.')[1]) >= 11) {
debug('Using system installed version of `go`: %o', stdout.trim());
return createGo(dir, platform, arch);
}
// Check `go` bin in builder CWD
const isGoExist = await pathExists(join(dir, 'bin'));
if (!isGoExist) {
debug('Installing `go` v%s to %o for %s %s', version, dir, platform, arch);
const url = getGoUrl(version, platform, arch);
debug('Downloading `go` URL: %o', url);
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to download: ${url} (${res.status})`);
}
// TODO: use a zip extractor when `ext === "zip"`
await mkdirp(dir);
await new Promise((resolve, reject) => {
res.body
.on('error', reject)
.pipe(tar.extract({ cwd: dir, strip: 1 }))
.on('error', reject)
.on('finish', resolve);
});
}
return createGo(dir, platform, arch);
}

View File

@@ -1,8 +1,24 @@
import { join, sep, dirname, basename, normalize } from 'path';
import { readFile, writeFile, pathExists, move } from 'fs-extra';
import { homedir } from 'os';
import execa from 'execa';
import { BuildOptions, Meta, Files } from '@vercel/build-utils';
import { homedir } from 'os';
import { spawn } from 'child_process';
import { Readable } from 'stream';
import once from '@tootallnate/once';
import { join, dirname, basename, normalize, sep } from 'path';
import {
readFile,
writeFile,
pathExists,
mkdirp,
move,
remove,
} from 'fs-extra';
import {
BuildOptions,
Meta,
Files,
StartDevServerOptions,
StartDevServerResult,
} from '@vercel/build-utils';
import buildUtils from './build-utils';
const {
@@ -17,6 +33,8 @@ const {
import { createGo, getAnalyzedEntrypoint, OUT_EXTENSION } from './go-helpers';
const handlerFileName = `handler${OUT_EXTENSION}`;
export { shouldServe };
interface Analyzed {
found?: boolean;
packageName: string;
@@ -24,16 +42,22 @@ interface Analyzed {
watch: string[];
}
interface PortInfo {
port: number;
}
// Initialize private git repo for Go Modules
async function initPrivateGit(credentials: string) {
const gitCredentialsPath = join(homedir(), '.git-credentials');
await execa('git', [
'config',
'--global',
'credential.helper',
`store --file ${join(homedir(), '.git-credentials')}`,
`store --file ${gitCredentialsPath}`,
]);
await writeFile(join(homedir(), '.git-credentials'), credentials);
await writeFile(gitCredentialsPath, credentials);
}
/**
@@ -436,4 +460,121 @@ Learn more: https://vercel.com/docs/runtimes#official-runtimes/go
};
}
export { shouldServe };
function isPortInfo(v: any): v is PortInfo {
return v && typeof v.port === 'number';
}
function isReadable(v: any): v is Readable {
return v && v.readable === true;
}
async function copyEntrypoint(entrypoint: string, dest: string): Promise<void> {
const data = await readFile(entrypoint, 'utf8');
// Modify package to `package main`
const patched = data.replace(/\bpackage\W+\S+\b/, 'package main');
await writeFile(join(dest, 'entrypoint.go'), patched);
}
async function copyDevServer(
functionName: string,
dest: string
): Promise<void> {
const data = await readFile(join(__dirname, 'dev-server.go'), 'utf8');
// Populate the handler function name
const patched = data.replace('__HANDLER_FUNC_NAME', functionName);
await writeFile(join(dest, 'vercel-dev-server-main.go'), patched);
}
export async function startDevServer(
opts: StartDevServerOptions
): Promise<StartDevServerResult> {
const { entrypoint, workPath, meta = {} } = opts;
const { devCacheDir = join(workPath, '.vercel', 'cache') } = meta;
const entrypointDir = dirname(entrypoint);
// For some reason, if `entrypoint` is a path segment (filename contains `[]`
// brackets) then the `.go` suffix on the entrypoint is missing. Fix that here…
let entrypointWithExt = entrypoint;
if (!entrypoint.endsWith('.go')) {
entrypointWithExt += '.go';
}
const tmp = join(
devCacheDir,
'go',
Math.random()
.toString(32)
.substring(2)
);
const tmpPackage = join(tmp, entrypointDir);
await mkdirp(tmpPackage);
let goModAbsPathDir = '';
if (await pathExists(join(workPath, 'go.mod'))) {
goModAbsPathDir = workPath;
}
const analyzedRaw = await getAnalyzedEntrypoint(
entrypointWithExt,
goModAbsPathDir
);
if (!analyzedRaw) {
throw new Error(
`Could not find an exported function in "${entrypointWithExt}"
Learn more: https://vercel.com/docs/runtimes#official-runtimes/go`
);
}
const analyzed: Analyzed = JSON.parse(analyzedRaw);
await Promise.all([
copyEntrypoint(entrypointWithExt, tmpPackage),
copyDevServer(analyzed.functionName, tmpPackage),
]);
const env: typeof process.env = {
...process.env,
...meta.env,
};
const tmpRelative = `.${sep}${entrypointDir}`;
const child = spawn('go', ['run', tmpRelative], {
cwd: tmp,
env,
stdio: ['ignore', 'inherit', 'inherit', 'pipe'],
});
child.once('exit', async () => {
await remove(tmp); // Cleanup
});
const portPipe = child.stdio[3];
if (!isReadable(portPipe)) {
throw new Error('File descriptor 3 is not readable');
}
// `dev-server.go` writes the ephemeral port number to FD 3 to be consumed here
const onPort = new Promise<PortInfo>(resolve => {
portPipe.setEncoding('utf8');
portPipe.once('data', d => {
resolve({ port: Number(d) });
});
});
const onExit = once.spread<[number, string | null]>(child, 'exit');
const result = await Promise.race([onPort, onExit]);
onExit.cancel();
if (isPortInfo(result)) {
return {
port: result.port,
pid: child.pid,
};
} else {
// Got "exit" event from child process
throw new Error(
`Failed to start dev server for "${entrypointWithExt}" (code=${result[0]}, signal=${result[1]})`
);
}
}

View File

@@ -1,8 +1,8 @@
package main
import (
"net/http"
vc "github.com/vercel/go-bridge/go/bridge"
"net/http"
)
func main() {

View File

@@ -1,12 +1,12 @@
package main
import (
"net/http"
"__NOW_HANDLER_PACKAGE_NAME"
"__NOW_HANDLER_PACKAGE_NAME"
"net/http"
vc "github.com/vercel/go-bridge/go/bridge"
vc "github.com/vercel/go-bridge/go/bridge"
)
func main() {
vc.Start(http.HandlerFunc(__NOW_HANDLER_FUNC_NAME))
vc.Start(http.HandlerFunc(__NOW_HANDLER_FUNC_NAME))
}

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/go",
"version": "1.1.2",
"version": "1.1.3-canary.1",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/go",
@@ -19,6 +19,7 @@
"dist"
],
"devDependencies": {
"@tootallnate/once": "1.1.2",
"@types/execa": "^0.9.0",
"@types/fs-extra": "^5.0.5",
"@types/node-fetch": "^2.3.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/next",
"version": "2.6.6",
"version": "2.6.9",
"license": "MIT",
"main": "./dist/index",
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/next-js",
@@ -26,7 +26,7 @@
"@types/resolve-from": "5.0.1",
"@types/semver": "6.0.0",
"@types/yazl": "2.4.1",
"@zeit/node-file-trace": "0.6.1",
"@zeit/node-file-trace": "0.6.5",
"async-sema": "3.0.1",
"buffer-crc32": "0.2.13",
"escape-string-regexp": "3.0.0",

View File

@@ -1,4 +1,5 @@
import buildUtils from './build-utils';
import url from 'url';
const {
createLambda,
debug,
@@ -14,18 +15,18 @@ const {
} = buildUtils;
import {
Lambda,
BuildOptions,
Config,
FileBlob,
FileFsRef,
Files,
Lambda,
NowBuildError,
PackageJson,
PrepareCacheOptions,
Prerender,
NowBuildError,
} from '@vercel/build-utils';
import { Route, Handler } from '@vercel/routing-utils';
import { Handler, Route } from '@vercel/routing-utils';
import {
convertHeaders,
convertRedirects,
@@ -33,8 +34,9 @@ import {
} from '@vercel/routing-utils/dist/superstatic';
import nodeFileTrace, { NodeFileTraceReasons } from '@zeit/node-file-trace';
import { ChildProcess, fork } from 'child_process';
import escapeStringRegexp from 'escape-string-regexp';
import {
lstatSync,
lstat,
pathExists,
readFile,
unlink as unlinkFile,
@@ -45,7 +47,6 @@ import path from 'path';
import resolveFrom from 'resolve-from';
import semver from 'semver';
import createServerlessConfig from './create-serverless-config';
import escapeStringRegexp from 'escape-string-regexp';
import nextLegacyVersions from './legacy-versions';
import {
createLambdaFromPseudoLayers,
@@ -70,7 +71,8 @@ import {
syncEnvVars,
validateEntrypoint,
} from './utils';
// import findUp from 'find-up';
import findUp from 'find-up';
import { Sema } from 'async-sema';
interface BuildParamsMeta {
isDev: boolean | undefined;
@@ -89,7 +91,7 @@ export const version = 2;
const htmlContentType = 'text/html; charset=utf-8';
const nowDevChildProcesses = new Set<ChildProcess>();
['SIGINT', 'SIGTERM'].forEach(signal => {
['SIGINT', 'SIGTERM'].forEach((signal) => {
process.once(signal as NodeJS.Signals, () => {
for (const child of nowDevChildProcesses) {
debug(
@@ -106,7 +108,13 @@ const MAX_AGE_ONE_YEAR = 31536000;
/**
* Read package.json from files
*/
async function readPackageJson(entryPath: string) {
async function readPackageJson(
entryPath: string
): Promise<{
scripts?: { [key: string]: string };
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
}> {
const packagePath = path.join(entryPath, 'package.json');
try {
@@ -137,15 +145,38 @@ async function writeNpmRc(workPath: string, token: string) {
);
}
function getNextVersion(packageJson: {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
}) {
let nextVersion;
if (packageJson.dependencies && packageJson.dependencies.next) {
nextVersion = packageJson.dependencies.next;
} else if (packageJson.devDependencies && packageJson.devDependencies.next) {
nextVersion = packageJson.devDependencies.next;
/**
* Get the installed Next version.
*/
function getRealNextVersion(entryPath: string): string | false {
try {
// First try to resolve the `next` dependency and get the real version from its
// package.json. This allows the builder to be used with frameworks like Blitz that
// bundle Next but where Next isn't in the project root's package.json
const nextVersion: string = require(resolveFrom(
entryPath,
'next/package.json'
)).version;
debug(`Detected Next.js version: ${nextVersion}`);
return nextVersion;
} catch (_ignored) {
debug(
`Could not identify real Next.js version, ensure it is defined as a project dependency.`
);
return false;
}
}
/**
* Get the package.json Next version.
*/
async function getNextVersionRange(entryPath: string): Promise<string | false> {
let nextVersion: string | false = false;
const pkg = await readPackageJson(entryPath);
if (pkg.dependencies && pkg.dependencies.next) {
nextVersion = pkg.dependencies.next;
} else if (pkg.devDependencies && pkg.devDependencies.next) {
nextVersion = pkg.devDependencies.next;
}
return nextVersion;
}
@@ -208,7 +239,7 @@ export const build = async ({
// Limit for max size each lambda can be, 50 MB if no custom limit
const lambdaCompressedByteLimit = config.maxLambdaSize || 50 * 1000 * 1000;
const entryDirectory = path.dirname(entrypoint);
let entryDirectory = path.dirname(entrypoint);
const entryPath = path.join(workPath, entryDirectory);
const outputDirectory = config.outputDirectory || '.next';
const dotNextStatic = path.join(entryPath, outputDirectory, 'static');
@@ -216,60 +247,43 @@ export const build = async ({
await download(files, workPath, meta);
const pkg = await readPackageJson(entryPath);
const nextVersion = getNextVersion(pkg);
const nextVersionRange = await getNextVersionRange(entryPath);
const nodeVersion = await getNodeVersion(entryPath, undefined, config, meta);
const spawnOpts = getSpawnOptions(meta, nodeVersion);
if (!nextVersion) {
throw new NowBuildError({
code: 'NEXT_NO_VERSION',
message:
'No Next.js version could be detected in "package.json". Make sure `"next"` is installed in "dependencies" or "devDependencies"',
});
const nowJsonPath = await findUp(['now.json', 'vercel.json'], {
cwd: path.join(workPath, path.dirname(entrypoint)),
});
let hasLegacyRoutes = false;
const hasFunctionsConfig = !!config.functions;
if (nowJsonPath) {
const nowJsonData = JSON.parse(await readFile(nowJsonPath, 'utf8'));
if (Array.isArray(nowJsonData.routes) && nowJsonData.routes.length > 0) {
hasLegacyRoutes = true;
console.warn(
`WARNING: your application is being opted out of @vercel/next's optimized lambdas mode due to legacy routes in ${path.basename(
nowJsonPath
)}. http://err.sh/vercel/vercel/next-legacy-routes-optimized-lambdas`
);
}
}
// let nowJsonPath = Object.keys(files).find(file => {
// return file.endsWith('now.json') || file.endsWith('vercel.json')
// })
// if (nowJsonPath) nowJsonPath = files[nowJsonPath].fsPath
// if (!nowJsonPath) {
// nowJsonPath = await findUp(['now.json', 'vercel.json'], {
// cwd: path.join(workPath, path.dirname(entrypoint))
// })
// }
// let hasLegacyRoutes = false;
// const hasFunctionsConfig = !!config.functions;
// if (nowJsonPath) {
// const nowJsonData = JSON.parse(await readFile(nowJsonPath, 'utf8'));
// if (Array.isArray(nowJsonData.routes) && nowJsonData.routes.length > 0) {
// hasLegacyRoutes = true;
// console.warn(
// `WARNING: your application is being opted out of @vercel/next's optimized lambdas mode due to legacy routes in ${path.basename(
// nowJsonPath
// )}. http://err.sh/vercel/vercel/next-legacy-routes-optimized-lambdas`
// );
// }
// }
// if (hasFunctionsConfig) {
// console.warn(
// `WARNING: Your application is being opted out of "@vercel/next" optimized lambdas mode due to \`functions\` config.\nMore info: http://err.sh/vercel/vercel/next-functions-config-optimized-lambdas`
// );
// }
if (hasFunctionsConfig) {
console.warn(
`WARNING: Your application is being opted out of "@vercel/next" optimized lambdas mode due to \`functions\` config.\nMore info: http://err.sh/vercel/vercel/next-functions-config-optimized-lambdas`
);
}
// default to true but still allow opting out with the config
const isSharedLambdas = !!config.sharedLambdas;
// !hasLegacyRoutes &&
// !hasFunctionsConfig &&
// typeof config.sharedLambdas === 'undefined'
// ? true
// : !!config.sharedLambdas;
const isSharedLambdas =
!hasLegacyRoutes &&
!hasFunctionsConfig &&
typeof config.sharedLambdas === 'undefined'
? true
: !!config.sharedLambdas;
if (meta.isDev) {
let childProcess: ChildProcess | undefined;
@@ -314,7 +328,7 @@ export const build = async ({
console.warn('WARNING: You should not upload the `.next` directory.');
}
const isLegacy = isLegacyNext(nextVersion);
const isLegacy = nextVersionRange && isLegacyNext(nextVersionRange);
let shouldRunScript = 'now-build';
debug(`MODE: ${isLegacy ? 'legacy' : 'serverless'}`);
@@ -368,18 +382,20 @@ export const build = async ({
console.log('Installing dependencies...');
await runNpmInstall(entryPath, ['--prefer-offline'], spawnOpts, meta);
let realNextVersion: string | undefined;
try {
realNextVersion = require(resolveFrom(entryPath, 'next/package.json'))
.version;
debug(`Detected Next.js version: ${realNextVersion}`);
} catch (_ignored) {
debug(`Could not identify real Next.js version, that's OK!`);
// Refetch Next version now that dependencies are installed.
// This will now resolve the actual installed Next version,
// even if Next isn't in the project package.json
const nextVersion = getRealNextVersion(entryPath);
if (!nextVersion) {
throw new NowBuildError({
code: 'NEXT_NO_VERSION',
message:
'No Next.js version could be detected in your project. Make sure `"next"` is installed in "dependencies" or "devDependencies"',
});
}
if (!isLegacy) {
await createServerlessConfig(workPath, entryPath, realNextVersion);
await createServerlessConfig(workPath, entryPath, nextVersion);
}
debug('Running user script...');
@@ -416,23 +432,22 @@ export const build = async ({
const routesManifest = await getRoutesManifest(
entryPath,
outputDirectory,
realNextVersion
nextVersion
);
const prerenderManifest = await getPrerenderManifest(entryPath);
const headers: Route[] = [];
const rewrites: Route[] = [];
const redirects: Route[] = [];
const nextBasePathRoute: Route[] = [];
const dataRoutes: Route[] = [];
let dynamicRoutes: Route[] = [];
let nextBasePath: string | undefined;
// whether they have enabled pages/404.js as the custom 404 page
let hasPages404 = false;
if (routesManifest) {
switch (routesManifest.version) {
case 1:
case 2: {
case 2:
case 3: {
redirects.push(...convertRedirects(routesManifest.redirects));
rewrites.push(...convertRewrites(routesManifest.rewrites));
@@ -458,17 +473,22 @@ export const build = async ({
}
dataRoutes.push({
src: dataRoute.dataRouteRegex.replace(
/^\^/,
`^${appMountPrefixNoTrailingSlash}`
),
src: (
dataRoute.namedDataRouteRegex || dataRoute.dataRouteRegex
).replace(/^\^/, `^${appMountPrefixNoTrailingSlash}`),
dest: path.join(
'/',
entryDirectory,
// make sure to route SSG data route to the data prerender
// output, we don't do this for SSP routes since they don't
// have a separate data output
(ssgDataRoute && ssgDataRoute.dataRoute) || dataRoute.page
`${(ssgDataRoute && ssgDataRoute.dataRoute) || dataRoute.page}${
dataRoute.routeKeys
? `?${Object.keys(dataRoute.routeKeys)
.map((key) => `${dataRoute.routeKeys![key]}=$${key}`)
.join('&')}`
: ''
}`
),
check: true,
});
@@ -480,7 +500,7 @@ export const build = async ({
}
if (routesManifest.basePath && routesManifest.basePath !== '/') {
nextBasePath = routesManifest.basePath;
const nextBasePath = routesManifest.basePath;
if (!nextBasePath.startsWith('/')) {
throw new NowBuildError({
@@ -497,11 +517,7 @@ export const build = async ({
});
}
nextBasePathRoute.push({
src: `^${nextBasePath}(?:$|/(.*))$`,
dest: `/$1`,
continue: true,
});
entryDirectory = path.join(entryDirectory, nextBasePath);
}
break;
}
@@ -565,9 +581,6 @@ export const build = async ({
routes: [
// TODO: low priority: handle trailingSlash
// Add top level rewrite for basePath if provided
...nextBasePathRoute,
// User headers
...headers,
@@ -597,7 +610,7 @@ export const build = async ({
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
status: 404,
check: true,
@@ -617,7 +630,7 @@ export const build = async ({
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
// Next.js assets contain a hash or entropy in their filenames, so they
// are guaranteed to be unique and cacheable indefinitely.
@@ -703,7 +716,7 @@ export const build = async ({
);
const nodeModules = excludeFiles(
await glob('node_modules/**', entryPath),
file => file.startsWith('node_modules/.cache')
(file) => file.startsWith('node_modules/.cache')
);
const launcherFiles = {
'now__bridge.js': new FileFsRef({
@@ -732,7 +745,7 @@ export const build = async ({
const launcherData = await readFile(launcherPath, 'utf8');
await Promise.all(
Object.keys(pages).map(async page => {
Object.keys(pages).map(async (page) => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
return;
@@ -848,10 +861,7 @@ export const build = async ({
// Assume tracing to be safe, bail if we know we don't need it.
let requiresTracing = hasLambdas;
try {
if (
realNextVersion &&
semver.lt(realNextVersion, ExperimentalTraceVersion)
) {
if (nextVersion && semver.lt(nextVersion, ExperimentalTraceVersion)) {
debug(
'Next.js version is too old for us to trace the required dependencies.\n' +
'Assuming Next.js has handled it!'
@@ -870,6 +880,7 @@ export const build = async ({
[filePath: string]: FileFsRef;
};
let canUsePreviewMode = false;
let pseudoLayerBytes = 0;
let apiPseudoLayerBytes = 0;
const pseudoLayers: PseudoLayer[] = [];
@@ -892,11 +903,12 @@ export const build = async ({
const apiPages: string[] = [];
const nonApiPages: string[] = [];
const allPagePaths = Object.keys(pages).map(page => pages[page].fsPath);
const allPagePaths = Object.keys(pages).map((page) => pages[page].fsPath);
for (const page of allPagePaths) {
if (isApiPage(page)) {
apiPages.push(page);
canUsePreviewMode = true;
} else {
nonApiPages.push(page);
}
@@ -907,23 +919,36 @@ export const build = async ({
reasons: apiReasons,
} = await nodeFileTrace(apiPages, { base: workPath });
const { fileList, reasons: nonApiReasons } = await nodeFileTrace(
nonApiPages,
{ base: workPath }
);
const {
fileList,
reasons: nonApiReasons,
} = await nodeFileTrace(nonApiPages, { base: workPath });
debug(`node-file-trace result for pages: ${fileList}`);
const lstatSema = new Sema(25, {
capacity: fileList.length + apiFileList.length,
});
const lstatResults: { [key: string]: ReturnType<typeof lstat> } = {};
const collectTracedFiles = (
reasons: NodeFileTraceReasons,
files: { [filePath: string]: FileFsRef }
) => (file: string) => {
) => async (file: string) => {
const reason = reasons[file];
if (reason && reason.type === 'initial') {
// Initial files are manually added to the lambda later
return;
}
const { mode } = lstatSync(path.join(workPath, file));
const filePath = path.join(workPath, file);
if (!lstatResults[filePath]) {
lstatResults[filePath] = lstatSema
.acquire()
.then(() => lstat(filePath))
.finally(() => lstatSema.release());
}
const { mode } = await lstatResults[filePath];
files[file] = new FileFsRef({
fsPath: path.join(workPath, file),
@@ -931,8 +956,12 @@ export const build = async ({
});
};
fileList.forEach(collectTracedFiles(nonApiReasons, tracedFiles));
apiFileList.forEach(collectTracedFiles(apiReasons, apiTracedFiles));
await Promise.all(
fileList.map(collectTracedFiles(nonApiReasons, tracedFiles))
);
await Promise.all(
apiFileList.map(collectTracedFiles(apiReasons, apiTracedFiles))
);
console.timeEnd(tracingLabel);
const zippingLabel = 'Compressed shared serverless function files';
@@ -967,7 +996,7 @@ export const build = async ({
debug(
'detected (legacy) assets to be bundled with serverless function:'
);
assetKeys.forEach(assetFile => debug(`\t${assetFile}`));
assetKeys.forEach((assetFile) => debug(`\t${assetFile}`));
debug(
'\nPlease upgrade to Next.js 9.1 to leverage modern asset handling.'
);
@@ -1107,7 +1136,7 @@ export const build = async ({
}
} else {
await Promise.all(
pageKeys.map(async page => {
pageKeys.map(async (page) => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_document.js'].includes(page)) {
return;
@@ -1188,8 +1217,8 @@ export const build = async ({
false,
routesManifest,
new Set(prerenderManifest.omittedRoutes)
).then(arr =>
arr.map(route => {
).then((arr) =>
arr.map((route) => {
route.src = route.src.replace('^', `^${dynamicPrefix}`);
return route;
})
@@ -1209,77 +1238,86 @@ export const build = async ({
`
const url = require('url');
page = function(req, res) {
const pages = {
${groupPageKeys
.map(
page =>
`'${page}': require('./${path.join(
'./',
group.pages[page].pageFileName
)}')`
)
.join(',\n')}
${
'' /*
creates a mapping of the page and the page's module e.g.
'/about': require('./.next/serverless/pages/about.js')
*/
try {
const pages = {
${groupPageKeys
.map(
(page) =>
`'${page}': require('./${path.join(
'./',
group.pages[page].pageFileName
)}')`
)
.join(',\n')}
${
'' /*
creates a mapping of the page and the page's module e.g.
'/about': require('./.next/serverless/pages/about.js')
*/
}
}
}
let toRender = req.headers['x-nextjs-page']
let toRender = req.headers['x-nextjs-page']
if (!toRender) {
try {
const { pathname } = url.parse(req.url)
toRender = pathname
} catch (_) {
// handle failing to parse url
res.statusCode = 400
return res.end('Bad Request')
if (!toRender) {
try {
const { pathname } = url.parse(req.url)
toRender = pathname
} catch (_) {
// handle failing to parse url
res.statusCode = 400
return res.end('Bad Request')
}
}
}
let currentPage = pages[toRender]
let currentPage = pages[toRender]
if (
toRender &&
!currentPage &&
toRender.includes('/_next/data')
) {
toRender = toRender
.replace(new RegExp('/_next/data/${escapedBuildId}/'), '/')
.replace(/\\.json$/, '')
if (
toRender &&
!currentPage
) {
if (toRender.includes('/_next/data')) {
toRender = toRender
.replace(new RegExp('/_next/data/${escapedBuildId}/'), '/')
.replace(/\\.json$/, '')
currentPage = pages[toRender]
currentPage = pages[toRender]
}
if (!currentPage) {
// for prerendered dynamic routes (/blog/post-1) we need to
// find the match since it won't match the page directly
const dynamicRoutes = ${JSON.stringify(
dynamicRoutes.map(route => ({
src: route.src,
dest: route.dest,
}))
)}
if (!currentPage) {
// for prerendered dynamic routes (/blog/post-1) we need to
// find the match since it won't match the page directly
const dynamicRoutes = ${JSON.stringify(
dynamicRoutes.map((route) => ({
src: route.src,
dest: route.dest,
}))
)}
for (const route of dynamicRoutes) {
const matcher = new RegExp(route.src)
for (const route of dynamicRoutes) {
const matcher = new RegExp(route.src)
if (matcher.test(toRender)) {
toRender = route.dest
currentPage = pages[toRender]
break
if (matcher.test(toRender)) {
toRender = url.parse(route.dest).pathname
currentPage = pages[toRender]
break
}
}
}
}
}
if (!currentPage) {
res.statusCode = 500
return res.end('internal server error')
if (!currentPage) {
console.error(
"Failed to find matching page for", toRender, "in lambda"
)
res.statusCode = 500
return res.end('internal server error')
}
const method = currentPage.render || currentPage.default || currentPage
return method(req, res)
} catch (err) {
console.error('Unhandled error during request:', err)
throw err
}
const method = currentPage.render || currentPage.default || currentPage
return method(req, res)
}
`
);
@@ -1435,33 +1473,41 @@ export const build = async ({
message: 'invariant: htmlFsRef != null && jsonFsRef != null',
});
}
if (!canUsePreviewMode) {
htmlFsRef.contentType = htmlContentType;
prerenders[outputPathPage] = htmlFsRef;
prerenders[outputPathData] = jsonFsRef;
}
}
prerenders[outputPathPage] = new Prerender({
expiration: initialRevalidate,
lambda,
fallback: htmlFsRef,
group: prerenderGroup,
bypassToken: prerenderManifest.bypassToken,
});
prerenders[outputPathData] = new Prerender({
expiration: initialRevalidate,
lambda,
fallback: jsonFsRef,
group: prerenderGroup,
bypassToken: prerenderManifest.bypassToken,
});
if (prerenders[outputPathPage] == null) {
prerenders[outputPathPage] = new Prerender({
expiration: initialRevalidate,
lambda,
fallback: htmlFsRef,
group: prerenderGroup,
bypassToken: prerenderManifest.bypassToken,
});
prerenders[outputPathData] = new Prerender({
expiration: initialRevalidate,
lambda,
fallback: jsonFsRef,
group: prerenderGroup,
bypassToken: prerenderManifest.bypassToken,
});
++prerenderGroup;
++prerenderGroup;
}
};
Object.keys(prerenderManifest.staticRoutes).forEach(route =>
Object.keys(prerenderManifest.staticRoutes).forEach((route) =>
onPrerenderRoute(route, { isBlocking: false, isFallback: false })
);
Object.keys(prerenderManifest.fallbackRoutes).forEach(route =>
Object.keys(prerenderManifest.fallbackRoutes).forEach((route) =>
onPrerenderRoute(route, { isBlocking: false, isFallback: true })
);
Object.keys(prerenderManifest.legacyBlockingRoutes).forEach(route =>
Object.keys(prerenderManifest.legacyBlockingRoutes).forEach((route) =>
onPrerenderRoute(route, { isBlocking: true, isFallback: false })
);
@@ -1525,7 +1571,7 @@ export const build = async ({
// We need to delete lambdas from output instead of omitting them from the
// start since we rely on them for powering Preview Mode (read above in
// onPrerenderRoute).
prerenderManifest.omittedRoutes.forEach(routeKey => {
prerenderManifest.omittedRoutes.forEach((routeKey) => {
// Get the route file as it'd be mounted in the builder output
const routeFileNoExt = path.posix.join(
entryDirectory,
@@ -1540,6 +1586,7 @@ export const build = async ({
delete lambdas[routeFileNoExt];
});
}
const mergedDataRoutesLambdaRoutes = [];
const mergedDynamicRoutesLambdaRoutes = [];
if (isSharedLambdas) {
@@ -1554,12 +1601,30 @@ export const build = async ({
mergedDynamicRoutesLambdaRoutes.push(route);
if (pageLambdaMap[route.dest!]) {
const { pathname } = url.parse(route.dest!);
if (pathname && pageLambdaMap[pathname]) {
mergedDynamicRoutesLambdaRoutes.push(
dynamicPageLambdaRoutesMap[route.dest!]
dynamicPageLambdaRoutesMap[pathname]
);
}
}
for (let i = 0; i < dataRoutes.length; i++) {
const route = dataRoutes[i];
mergedDataRoutesLambdaRoutes.push(route);
const { pathname } = url.parse(route.dest!);
if (
pathname &&
pageLambdaMap[pathname] &&
dynamicPageLambdaRoutesMap[pathname]
) {
mergedDataRoutesLambdaRoutes.push(dynamicPageLambdaRoutesMap[pathname]);
}
}
}
return {
@@ -1583,9 +1648,6 @@ export const build = async ({
- Builder rewrites
*/
routes: [
// Add top level rewrite for basePath if provided
...nextBasePathRoute,
// headers
...headers,
@@ -1620,7 +1682,7 @@ export const build = async ({
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
status: 404,
check: true,
@@ -1632,7 +1694,7 @@ export const build = async ({
{ handle: 'rewrite' },
// /_next/data routes for getServerProps/getStaticProps pages
...dataRoutes,
...(isSharedLambdas ? mergedDataRoutesLambdaRoutes : dataRoutes),
// re-check page routes to map them to the lambda
...pageLambdaRoutes,
@@ -1650,7 +1712,7 @@ export const build = async ({
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
// Next.js assets contain a hash or entropy in their filenames, so they
// are guaranteed to be unique and cacheable indefinitely.
@@ -1672,9 +1734,12 @@ export const build = async ({
src: path.join('/', entryDirectory, '.*'),
// if static 404 is not present but we have pages/404.js
// it is a lambda due to _app getInitialProps
dest: path.join('/', (static404Page
? static404Page
: pageLambdaMap[page404Path]) as string),
dest: path.join(
'/',
(static404Page
? static404Page
: pageLambdaMap[page404Path]) as string
),
status: 404,
headers: {
@@ -1714,14 +1779,8 @@ export const prepareCache = async ({
const entryPath = path.join(workPath, entryDirectory);
const outputDirectory = config.outputDirectory || '.next';
const pkg = await readPackageJson(entryPath);
const nextVersion = getNextVersion(pkg);
if (!nextVersion)
throw new NowBuildError({
code: 'NEXT_VERSION_PARSE_FAILED',
message: 'Could not parse Next.js version',
});
const isLegacy = isLegacyNext(nextVersion);
const nextVersionRange = await getNextVersionRange(entryPath);
const isLegacy = nextVersionRange && isLegacyNext(nextVersionRange);
if (isLegacy) {
// skip caching legacy mode (swapping deps between all and production can get bug-prone)

View File

@@ -198,7 +198,7 @@ async function getRoutes(
// If default pages dir isn't found check for `src/pages`
if (
!pagesDir &&
fileKeys.some(file =>
fileKeys.some((file) =>
file.startsWith(path.join(entryDirectory, 'src/pages'))
)
) {
@@ -255,17 +255,21 @@ async function getRoutes(
}
routes.push(
...(await getDynamicRoutes(entryPath, entryDirectory, dynamicPages).then(
arr =>
arr.map((route: Source) => {
// convert to make entire RegExp match as one group
route.src = route.src
.replace('^', `^${prefix}(`)
.replace('(\\/', '(')
.replace('$', ')$');
route.dest = `${url}/$1`;
return route;
})
...(await getDynamicRoutes(
entryPath,
entryDirectory,
dynamicPages,
true
).then((arr) =>
arr.map((route: Source) => {
// convert to make entire RegExp match as one group
route.src = route.src
.replace('^', `^${prefix}(`)
.replace('(\\/', '(')
.replace('$', ')$');
route.dest = `${url}/$1`;
return route;
})
))
);
@@ -283,7 +287,7 @@ async function getRoutes(
};
// Only add the route if a page is not already using it
if (!routes.some(r => (r as Source).src === route.src)) {
if (!routes.some((r) => (r as Source).src === route.src)) {
routes.push(route);
}
}
@@ -312,9 +316,16 @@ export type RoutesManifest = {
dynamicRoutes: {
page: string;
regex: string;
namedRegex?: string;
routeKeys?: { [named: string]: string };
}[];
version: number;
dataRoutes?: Array<{ page: string; dataRouteRegex: string }>;
dataRoutes?: Array<{
page: string;
dataRouteRegex: string;
namedDataRouteRegex?: string;
routeKeys?: { [named: string]: string };
}>;
};
export async function getRoutesManifest(
@@ -352,6 +363,21 @@ export async function getRoutesManifest(
// eslint-disable-next-line @typescript-eslint/no-var-requires
const routesManifest: RoutesManifest = require(pathRoutesManifest);
// remove temporary array based routeKeys from v1/v2 of routes
// manifest since it can result in invalid routes
for (const route of routesManifest.dataRoutes || []) {
if (Array.isArray(route.routeKeys)) {
delete route.routeKeys;
delete route.namedDataRouteRegex;
}
}
for (const route of routesManifest.dynamicRoutes || []) {
if (Array.isArray(route.routeKeys)) {
delete route.routeKeys;
delete route.namedRegex;
}
}
return routesManifest;
}
@@ -383,6 +409,25 @@ export async function getDynamicRoutes(
};
});
}
case 3: {
return routesManifest.dynamicRoutes
.filter(({ page }) =>
omittedRoutes ? !omittedRoutes.has(page) : true
)
.map(({ page, namedRegex, regex, routeKeys }) => {
return {
src: namedRegex || regex,
dest: `${!isDev ? path.join('/', entryDirectory, page) : page}${
routeKeys
? `?${Object.keys(routeKeys)
.map((key) => `${routeKeys[key]}=$${key}`)
.join('&')}`
: ''
}`,
check: true,
};
});
}
default: {
// update MIN_ROUTES_MANIFEST_VERSION
throw new NowBuildError({
@@ -434,13 +479,13 @@ export async function getDynamicRoutes(
});
}
const pageMatchers = getSortedRoutes(dynamicPages).map(pageName => ({
const pageMatchers = getSortedRoutes(dynamicPages).map((pageName) => ({
pageName,
matcher: getRouteRegex && getRouteRegex(pageName).re,
}));
const routes: Source[] = [];
pageMatchers.forEach(pageMatcher => {
pageMatchers.forEach((pageMatcher) => {
// in `vercel dev` we don't need to prefix the destination
const dest = !isDev
? path.join('/', entryDirectory, pageMatcher.pageName)
@@ -450,7 +495,7 @@ export async function getDynamicRoutes(
routes.push({
src: pageMatcher.matcher.source,
dest,
check: true,
check: !isDev,
});
}
});
@@ -817,7 +862,7 @@ export async function getPrerenderManifest(
omittedRoutes: [],
};
routes.forEach(route => {
routes.forEach((route) => {
const {
initialRevalidateSeconds,
dataRoute,
@@ -833,7 +878,7 @@ export async function getPrerenderManifest(
};
});
lazyRoutes.forEach(lazyRoute => {
lazyRoutes.forEach((lazyRoute) => {
const {
routeRegex,
fallback,
@@ -871,7 +916,7 @@ export async function getPrerenderManifest(
omittedRoutes: [],
};
routes.forEach(route => {
routes.forEach((route) => {
const {
initialRevalidateSeconds,
dataRoute,
@@ -887,7 +932,7 @@ export async function getPrerenderManifest(
};
});
lazyRoutes.forEach(lazyRoute => {
lazyRoutes.forEach((lazyRoute) => {
const {
routeRegex,
fallback,

View File

@@ -0,0 +1,5 @@
module.exports = {
generateBuildId() {
return 'testing-build-id';
},
};

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