* [now-static-build] Handle `buildCommand`, `devCommand` and `outputDirectory`
* Adjust tests
* Swap order
* Add `node_modules/.bin` to PATH
* Remove @types/execa
* Append PATH only to spawn options
* Remove test check
* Only add when there is a command
This PR reduces the time running Circle CI tests.
Since creating the monorepo in #2812, the coverage broke and then was fixed in #2876 with a workaround which would run unit tests twice.
More recently, we enabled Now CLI to always run tests in #3305 so that means coverage data is always generated.
This PR is a final proper fix so that unit tests run once which saves approximately 2 minutes per push (CI workflow).
We used to have a default `maxLambdaSize` and allow the user to increase to 50 MB.
However, this is no longer true. Today, the `maxLambdaSize` for every function is 50 MB and is not configurable, it's a hard limit.
This PR removes the dead link to avoid confusion like in Issue #3416.
* [now-build-utils] Consider `yarn build` and `npm run build` as `buildCommand`
* [@now/build-utils] Update new detectors
* Update unit tests
* [@now/build-utils] Update detect-builder and detect-routes
* Update tests
* Run prettier
* Add more tests
* [now-cli] Use default detectors
* Add now-dev test
* Add a generic node project fallback
* Fix build
* Use public as default
* Ensure generic node project is last
* Update tests
* Update tests again
* Update packages/now-build-utils/src/detectors/filesystem.ts
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Remove parentheses
* Revert "Remove parentheses"
This reverts commit 03f9aba07b0a6d4088719ca9afd602ce8fb1e9c1.
* Use getDependencyVersion instead of hasDependency
* [@now/build-utils] Add functions schema
* [now-cli] Use functions schema from build-utils
* Move buildsSchema to build-utils
* Add retries to test
* Add await
Follow up to #3408 .
```
> Error! Checking for updates failed
> Now CLI 16.6.3 dev (beta) — https://zeit.co/feedback/dev
> Error! Invalid `functions` property: ['api/test.js'] should NOT have additional properties
```
This PR adds a `discontinueDate` to Node 8 and prints a warning if the current deployment is using it.
```
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ │
│ WARNING │
│ │
│ Node.js 8.10.x will be discontinued on 2020-01-06. │
│ Deployments created on or after 2020-01-06 will fail to build. │
│ Please use one of the following supported `engines` in `package.json`: ["12.x","10.x"] │
│ This change is a result of a decision made by an upstream infrastructure provider (AWS). │
│ Read more: https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html │
│ │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
```
Starting January 2020, Node 8 deployments will fail to build and print an error.
```
Found `engines` in `package.json` with an unsupported Node.js version range: 8.10.x
Please use one of the following supported ranges: ["12.x","10.x"]
```
[PRODUCT-796]
[PRODUCT-796]: https://zeit.atlassian.net/browse/PRODUCT-796
Before, the debug log message "Downloading user files..." was copy+pasted to all the builders.
This change centralizes that log message to be inside the `download()` function for consistency and DRY purposes.
Additionally, the wording has changed as per [INFRA-289], and a resulting timestamp message is also printed.
[INFRA-289]: https://zeit.atlassian.net/browse/INFRA-289
Before this change, in `@now/next` when running via `now dev`,
the runtime env vars get passed to the child `dev-server.js`
process via argv.
This is problematic because it causes the env vars to be visible in
the process listing, and also causes the command itself to be very
large.
In some cases, with a lot of env vars, we've seen the command be too
large and it will fail to spawn (https://serverfault.com/a/163390/294389).
This changes the start-up process such that the env vars are passed
in via Node.js `fork()` IPC, rather than via `argv`.
Saw my `pre-commit` hook wasn't being triggered after running `yarn` and noticed it was due to an un-used `pre-commit` dependency in `now-cli` overriding the changes to my `.git/hooks/pre-commit` file done by `husky`
**Note**: you will probably need to run `yarn install --force` after this is applied before the correct `pre-commit` changes are applied by `husky`
We've shut down our Typeform for feedback, so we can simply the feedback link. The old one will continue working, but we should start using the new one.
Pending on https://github.com/zeit/front/pull/5874.
Fixes#3377
The lock files should not be cached because the user may wish to make a new deployment without a `yarn.lock` or `package-lock.json`.
This recently started causing problems because of the order of downloading cache changed from before user files to after user files.
So we need to be extra careful to only cache outputs and not source files.
This PR will reduce deployment time when a `package-lock.json` file is found by avoiding the audit step which usually [sends audit reports](https://docs.npmjs.com/cli/audit#description) to the registry.
The [--no-audit](https://docs.npmjs.com/cli/install) flag was introduced in [npm@6](
https://medium.com/npm-inc/announcing-npm-6-5d0b1799a905) which shipped with Node 10. However, using the flag with npm@5 does not do anything which is great because npm@5 doesn't audit. So this PR is backwards compatible.
### Performance
I tried `npm install` and `npm install --no-audit` with a large project, [StateOfJS](a9fa6d47f9/homepages/stateofjs), which has 2206 packages (audited 21778 packages).
I made sure to `rm -rf node_modules` each time and ran both commands 5 times to make sure it was always faster with `--no-audit`.
- Before: 61 seconds
- After: 49 seconds
Since we switched to a single branch (instead of master/canary), lerna gets confused about which packages to publish because stable and canary releases are in the same branch.
This PR fixes the confusion by looking at the git history and using [--force-publish](https://github.com/lerna/lerna/tree/master/commands/version#--force-publish) on the changed packages.
In order to avoid confusion for the person publishing, I removed the `yarn publish-stable` script in favor of `yarn changelog` which will print the change log and emit a script that can be used to publish stable.
<details><summary>View Example Output</summary>
<p>
```
$ yarn changelog
yarn run v1.19.1
$ node changelog.js
Changes since the last Stable release (21fe0a2):
- [now-cli] Change `--debug` to avoid debugging builders (#3386) [Steven]
- [now-next] Update routes for new check: true behavior (#3383) [JJ Kasper]
- [now-build-utils] Update Detectors API (#3384) [Nathan Rajlich]
- [now-client] Bump version (#3385) [Andy]
- [now-client] (Major) Split `now-client` options (#3382) [Andy]
- [now-cli][now-client] Fix user agent (#3381) [Steven]
- [now-client] Fix `main` in package.json (#3344) [Max]
- [now-build-utils] Change `script` to `scripts` in error message (#3376) [Andy]
- [now-cli] Add support for `check: true` routes in `now dev` (#3364) [Steven]
- [now-cli] Fix preinstall script on windows when `LOCALAPPDATA` is missing (#3365) [Steven]
- [now dev] skip installing already installed versioned runtimes (#3354) [Tommaso De Rossi]
- [now-routing-utils] Update `path-to-regexp` to v6.1.0 (#3361) [Steven]
- [now-routing-utils] Add mergeRoutes function (#3358) [Steven]
- [docs] Remove deprecated LambdaRuntimes (#3346) [Steven]
- [now-routing-utils] Add support for `check: true` (#3343) [Steven]
- [now-static-build] Cache `.cache` folder for gatsby deployments (#3260) (#3342) [Luc]
To publish a stable release, execute the following:
git pull && lerna version --message 'Publish Stable' --exact --force-publish=@now/build-utils,now,now-client,@now/next,@now/routing-utils,@now/static-build
```
</p>
</details>
* [now-cli] Remove `github` property from payload before sending it
* Add test and remove unused one
* Remove .only
* Remove unused fixture
* Use correct github properties
Since switching to a single branch, each package in the monorepo can be independently versioned so that some packages are using a canary version and others using a stable version.
This PR fixes an issue where a canary version of `now-cli` is bundling a stable version of `now-client` and thus does does not deploy zero config using canary builders.
The solution is to pass the User Agent from `now-cli` to `now-client` in a new option.
A nice side-effect of this PR is that we will switch the User Agent back to what it used to be pre-now-client days. It will look something like `now 16.6.1-canary.0 node-v10.17.0 darwin (x64)`.
This PR adds `now dev` support for routes that define `check: true`.
The algorithm is as follows:
- If a matching `dest` file is found, then serve it
- If a matching `src` file is found, then serve it
- Otherwise, behave the same as `continue: true` and continue processing routes
Fixes#3353
The current solution might break if a user interrupts `now dev` while yarn wrote the package in the cache package.json but has not yet added to node_modules.
This happens in like 20 ms but is possible, so we could execute `yarn` every time to be sure.
Tell me if the above is a problem or not
This moves the merging logic to `@now/routing-utils` and adds support for `check: true`.
- Builder before filesystem, continue: true
- User before filesystem
- Builder before filesystem, check: true
- Builder before filesystem, continue: false
- Handle filesystem
- Builder after filesystem, continue: true
- User after filesystem
- Builder after filesystem, check: true
- Builder after filesystem, continue: false
Apply 77348ea71e again.
> Adds `.cache` folder to the Now cache for Gatsby deployments.
> Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
Fixes a confusing error message.
<details>
<summary>Click to view error message</summary>
<pre>> Ready! Available at http://localhost:3000
> Building @now/node:index.js
Installing dependencies...
Running "yarn run now-build"
yarn run v1.17.3
error @: The engine "node" is incompatible with this module. Expected version "10.x". Got "12.13.1"
error Commands cannot run with an incompatible environment.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Exited with 1
at ChildProcess.<anonymous> (/Users/styfle/Library/Caches/co.zeit.now/dev/builders/node_modules/@now/node/dist/index.js:78518:24)
at ChildProcess.emit (events.js:210:5)
at ChildProcess.EventEmitter.emit (domain.js:475:20)
at maybeClose (internal/child_process.js:1021:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5) {
message: 'Exited with 1'
}</pre>
</details>
The `--ignore-engines` flag was added to `yarn install` many months ago but not `yarn run`.
This PR adds the flag to `yarn run`.
This is useful in `now dev` when the user might have a different Node version installed than what is specified by `engines` in `package.json`.
Reverts #3311
Previously, we thought we were going to use version 4 to support builder rewrites/redirects => routes. But that is no longer necessary. So instead version 4 will be builders that accept multiple file entrypoints.
Until v4 can be implemented, this reverts v4 changes.
Additionally, I added a helpful error message when the CLI does not support the builder version. In a future PR, we will add better version locking to avoid this type of version mismatch.
We expect `now@canary` to use canary builders. This PR fixes a bug where a zero config deployment was selecting `@now/static-build` instead of `@now/static-build@canary`.
Fixes#3334.
```
$ node ~/now-cli/dist/index.js --token $'he˚ll,o\n'
> Error! You defined "--token", but its contents are invalid. Must not contain: "\n", ",", "˚"
> More details: https://err.sh/now/invalid-token-value
```
Renames `test/unit.test.detectors.ts` -> `test/unit.detectors.test.ts`
and adjusts npm `test-unit` command.
Jest only runs tests for files that end in `*.test.ts` or `*.test.js`.
* [now-build-utils] Add framework detector functions
As described in [PRODUCT-399]. This is similar in nature to the
current framework detection logic in static-build, however the detectors
are now functions which allow for detection of frameworks without
a `package.json` file (i.e. jekyll), and also includes detection of
build and dev commands for use in project settings.
* Dedup `aggregate-error` dep in yarn.lock
* Simplify `hasDependency()`
* Adjust hugo detect logic
* Add "jekyll" detector
* Add "next" detector
* Optimize "gatsby" detector
Check the `package.json` first
* Add optimization to check "package.json" based detectors first
They're by far the most common and only rely on checking the single
`package.json` file. If no pkg-based detector succeeds then the non-pkg
detectors are consulted afterwards.
* Add "vue" detector
* Add "angular" detector
* Add "polymer" detector
* Add "svelte" detector
* Add "create-react-app-ejected" detector
* Add "gridsome" detector
* Add "umi" detector
* Add "sapper" detector
* Add "saber" detector
* Add "stencil" detector
* Add CRA ejected commands
* Add "brunch" detector
* Add "middleman" detector
* Add missing commands
* `buildCommand` is required
* Add initial unit tests
* Fix unit tests on Circle
* Move "jest" and "ts-jest" to the root of the monorepo
* Fix integration tests
* Fix test again
* Update packages/now-build-utils/src/detectors/middleman.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Move `@types/jest` to root level package.json
* Update packages/now-build-utils/src/detectors/ember.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Add `cachePattern`
* Address PR comments
* Add missing `$PORT` entries for devCommands
* Add `firstTruthy()` tests
* Revert some changes
Maybe it fixes CI build?
* Test remove `yaml` module
* Update packages/now-build-utils/src/detectors/next.ts
* Remove `toml`
* Test out "@iarna/toml" module
* Fix build
* Test out "js-yaml" module
* Add new routing properties
* Rename `test/unit.test.ts` to `test/unit.test.detectors.ts`
* Remove `@types/yaml`
Converts `reportError()` to typescript and adds an ignore list.
In particular, `uv_cwd` comes from `process.cwd()` so we don't need to track these errors in the case the user deletes their current working directory.
This is a follow up to #3194 which handled only one scenario.
* [now-build-utils] Ensure function paths are relative to the project and improve the error message
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
- Add now dev `BuildResultV4` type similar to V3 but no routes, only superstatic keys
- Add validation to `@now/routing-utils` to ensure V4 Builders do not return `routes`
Note, no builders have been changed yet because this needs to be shipped first so we can bump build-utils and then builders will work in production. Then in a separate PR, we can update builders to V4.
Fixes#3310
The root `package.json` file is copied to `dist` by tsc because of a relative import. This causes npm `files` property to be nested and therefore skip publishing most of the files.
```ts
import pkg from '../../package.json';
```
Disabling `resolveJsonModule` and using `require()` instead fixed it.
However, this change caused `now-cli` build to fail so I had to change the way `now-client` gets imported.
Previously, the `typescript` dependency resolution was using the package.json beside the `now.json` base directory.
This PR changes the behavior to start looking for package.json in the entrypoint directory.
Fixes#3258
This test was failing for the last week.
The issue was fixed in the build environment. The root cause was [ruby-build](https://github.com/rbenv/ruby-build) which is used to install the version of Ruby used in `@now/ruby`. It started using an older (possible broken) version of `bundler`. I pinned `ruby-build` to a previous version so that deployments continue working.
So now we can enable the Rails test again (which uses nokogiri).
Fixes#3246Closes#3274
This PR is an attempt to automatically inject `gatsby-plugin-now` in Gatsby projects, as an optimisation.
- [x] avoid conflicts with existing files
- [x] refactor
* [now-node] Use builder version 3
* [now-cgi] Use builder version 3
* [now-go] Use builder version 3
* [now-python] Use builder version 3
* [now-ruby] Use builder version 3
* Adjust docs
* [now-ruby] Remove unused import
* Temp. test in iad1
* Revert "Temp. test in iad1"
This reverts commit 4c495baa5888dda5ae8f184f679613e91ab7268c.
* [now-cli] Adjust `now dev` for builder version 3
* [now-build-utils] Do not allow non Community Runtimes
* Temp. Force Build in iad1
* Update DEVELOPING_A_RUNTIME.md
Co-Authored-By: Steven <steven@ceriously.com>
* Update docs
* Update test/lib/deployment/now-deploy.js
Co-Authored-By: Steven <steven@ceriously.com>
* Remove temp. iad1 check
* Check memory and maxDuration
* Use memory for Lambda
* Only cast once
* Skip tests
* Allow functions + next.js
* Don't allow empty or invalid functions
* Make sure runtimes match a source
* Update now-dev to use the functions property
* Functions must match a source file
* Split up functions
* Make sure @now/next does not receive any unused functions
* Allow memory and maxDuration properties on Lambdas
* Add lambda options to @now/node
* Add lambda options to @now/go
* Add lambda options to @now/python
* Add lambda options to @now/ruby
* Update lambda options on @now/node
* Add lambda optiosn to @now/cgi
* Make options optional
* Add lambda options to @now/next
* Fix assertion
* Add test
* Fix tests
* Skip 06-ruby test
* Skip correct tests
* Fix options and cache src check
* Adjust memory test
Fix https://github.com/zeit/now/issues/3247.
Adds `.cache` folder to the Now cache for Gatsby deployments.
Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
This PR implements `cleanUrls` for now dev which is similar to the implementation in fmeta-util.
I also added an integration test to ensure correctness.
This PR fixes a regression introduced in #3174 when removing the `^` and `$` normalization.
The previous PR was normalizing user-defined routes but forgot to normalize builder routes.
This PR normalizes builder routes 👍
This PR does 3 things:
- add default caching headers
- redirect all missed requests to Gatsby's own 404.html page
- add deprecation message to `gatsby-plugin-now` since we're auto injecting it and it's not needed anymore
Fixes#2859
This allows us to start de-coupling the builder from relying on inner utils of Next.js to generate dynamic routes for Now by leveraging a `routes-manifest` output during the build
Relies on: https://github.com/zeit/next.js/pull/9347
There was a regression since 16.3.0 (now-client refactor) causing file permissions for source files to be not be preserved.
The solution was to add the FS `mode` to each file.
Fixes#3172
This PR updates the link to the missing build script FAQ, pending a change to the structure of the documentation.
This PR should be merged only when the documentation PR has been - https://github.com/zeit/docs/pull/1423
If someone uses a wildcard in the root of pages, it could collide with internal `_next` files:
```
pages/
[slug]/
[slug]/
[slug]/
[slug].js
```
For example:
`/_next/static/runtime/webpack-hash.js` exists and has no problem routing
`/_next/static/runtime/webpack-old-hash.js` doesn't exist on the server any more but would route to `/[slug].js` with status 200
This could cause strange edge cases related to loading a new version of a Next.js site along with the possible cost of execution if it's a lambda plus the cost of however large the response is.
# Side Notes
Should this:
92d9f2d809/packages/now-next/src/index.ts (L839)
Instead be this?
```
src: path.join('/', entryDirectory, '_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'),
```
If this is the case, I need to adjust my PR to do the same
* [now-cli][now-client] Add support for `functions` property
* Fix typo
* Update yarn.lock for test
* Update all yarn.lock files for now dev
* Log fixture that failed
* Use catch instead
* Run dev tests not serial
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Do not throw
* Skip nextjs tests on node 8
* Remove only flag
* Ignore 19-mithril
* Revert "Ignore 19-mithril"
This reverts commit d438c40c26a8ef2227a0a0dd7caba8600503d585.
* Revert "Remove only flag"
This reverts commit caff05ad82a184706eb48b6b39df550f8d17bb1d.
* Revert "Skip nextjs tests on node 8"
This reverts commit 3b45ca33b969a56da0bccce4c95cae3b34af98e0.
* Revert "Do not throw"
This reverts commit 55624b9193d7751e1dc16cbee9005fe23ff19662.
* Revert "Revert "Run dev tests not serial""
This reverts commit cd5260a205b6478cb7a44c9ea982b99f26f2f2e9.
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Revert "Use catch instead"
This reverts commit fe652995c08e1e8b2ba581aaf7304b5432718161.
* Revert "Log fixture that failed"
This reverts commit feb0e7b393626ce1c117ef95f9e95f7a148e3dab.
* Revert "Update all yarn.lock files for now dev"
This reverts commit 36be4dd98ca6d65850843dc958727952dd7461ee.
* Update yarn.lock for 14-svelte-node
* Update es-abstract in all yarn.lock files
* Skip node test
* Revert "Skip node test"
This reverts commit c9c45ec8d6fcef13cbd300db410699b167d76ed2.
* Remove test.only
* Only execute node test in now-dev
* Revert "Only execute node test in now-dev"
This reverts commit 8ab7a88d696c1faa5fe0fbcca9dcfb0dd375925f.
* Clean cache on macos node8
* Fix query
* Use --skip-integrity-check
* Add --skip-integrity-check to different yarn call
* Add --network-concurrency 1
* Add retry
This fixes the scenario where the user defines `trailingSlash: true` and creates a file `/api/users.js`. They would expect to be able to visit `/api/users/` and it should run that function.
This PR removes the individual lambda zip prints since they're not very useful. We've already printed this information above and will time them as a group!
This fixes the scenario when both `{ cleanUrls: true, and trailingSlash: true }` so that only one redirect occurs when visiting `/file.html`.
Previously, this would have redirected twice from `/file.html` => `/file` => `/file/`.
Now it will redirect once from `/file.html` => `/file/`.
This PR refactors a few things:
- enhance validation so that invalid regex is caught before transforming to routes
- remove `filePaths` input parameter since it is no longer used
After this PR is merged and released, we'll be able to perform validation earlier in the build pipeline and report the errors to the user.
* [now-build-utils] Validate functions and allow them as config
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Change memory check
* Adjust test
We used to read the output files and create a route for each redirect when `cleanUrls: true`.
Instead, this PR will add 2 redirects for `cleanUrls: true` no matter how many files are in the outputs.
This updates `@now/build-utils` to add support for the function property including types and tests.
Related: [PRODUCT-27]
[PRODUCT-27]: https://zeit.atlassian.net/browse/PRODUCT-27
This allows us to start de-coupling the builder from relying on inner utils of Next.js to generate dynamic routes for Now by leveraging a `routes-manifest` output during the build
Relies on: https://github.com/zeit/next.js/pull/9347
* [now-node] Use builder version 3
* [now-cgi] Use builder version 3
* [now-go] Use builder version 3
* [now-python] Use builder version 3
* [now-ruby] Use builder version 3
* Adjust docs
* [now-ruby] Remove unused import
* Temp. test in iad1
* Revert "Temp. test in iad1"
This reverts commit 4c495baa5888dda5ae8f184f679613e91ab7268c.
* [now-cli] Adjust `now dev` for builder version 3
* [now-build-utils] Do not allow non Community Runtimes
* Temp. Force Build in iad1
* Update DEVELOPING_A_RUNTIME.md
Co-Authored-By: Steven <steven@ceriously.com>
* Update docs
* Update test/lib/deployment/now-deploy.js
Co-Authored-By: Steven <steven@ceriously.com>
* Remove temp. iad1 check
* Check memory and maxDuration
* Use memory for Lambda
* Only cast once
* Skip tests
There was a regression since 16.3.0 (now-client refactor) causing file permissions for source files to be not be preserved.
The solution was to add the FS `mode` to each file.
Fixes#3172
Fix https://github.com/zeit/now/issues/3247.
Adds `.cache` folder to the Now cache for Gatsby deployments.
Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
After upgrading to macOS Catalina I get this error on some now-deploys:
```
> Error! ENOENT: no such file or directory, stat '<file that not exist>'
```
and the file is below a folder that should be ignored by `.nowignore`, think this is due to some fs-bug in my node version, but did also discover that the ignore-array returned from `getNowIgnore` did not include the ignores from my `.nowignore`, but only the default defined in the top of the function.
Is this a bug?
* Allow functions + next.js
* Don't allow empty or invalid functions
* Make sure runtimes match a source
* Update now-dev to use the functions property
* Functions must match a source file
* Split up functions
* Make sure @now/next does not receive any unused functions
* Allow memory and maxDuration properties on Lambdas
* Add lambda options to @now/node
* Add lambda options to @now/go
* Add lambda options to @now/python
* Add lambda options to @now/ruby
* Update lambda options on @now/node
* Add lambda optiosn to @now/cgi
* Make options optional
* Add lambda options to @now/next
* Fix assertion
* Add test
* Fix tests
* Skip 06-ruby test
* Skip correct tests
* Fix options and cache src check
* Adjust memory test
This PR updates the link to the missing build script FAQ, pending a change to the structure of the documentation.
This PR should be merged only when the documentation PR has been - https://github.com/zeit/docs/pull/1423
If someone uses a wildcard in the root of pages, it could collide with internal `_next` files:
```
pages/
[slug]/
[slug]/
[slug]/
[slug].js
```
For example:
`/_next/static/runtime/webpack-hash.js` exists and has no problem routing
`/_next/static/runtime/webpack-old-hash.js` doesn't exist on the server any more but would route to `/[slug].js` with status 200
This could cause strange edge cases related to loading a new version of a Next.js site along with the possible cost of execution if it's a lambda plus the cost of however large the response is.
# Side Notes
Should this:
92d9f2d809/packages/now-next/src/index.ts (L839)
Instead be this?
```
src: path.join('/', entryDirectory, '_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'),
```
If this is the case, I need to adjust my PR to do the same
This PR implements `cleanUrls` for now dev which is similar to the implementation in fmeta-util.
I also added an integration test to ensure correctness.
This PR fixes a regression introduced in #3174 when removing the `^` and `$` normalization.
The previous PR was normalizing user-defined routes but forgot to normalize builder routes.
This PR normalizes builder routes 👍
* [now-cli][now-client] Add support for `functions` property
* Fix typo
* Update yarn.lock for test
* Update all yarn.lock files for now dev
* Log fixture that failed
* Use catch instead
* Run dev tests not serial
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Do not throw
* Skip nextjs tests on node 8
* Remove only flag
* Ignore 19-mithril
* Revert "Ignore 19-mithril"
This reverts commit d438c40c26a8ef2227a0a0dd7caba8600503d585.
* Revert "Remove only flag"
This reverts commit caff05ad82a184706eb48b6b39df550f8d17bb1d.
* Revert "Skip nextjs tests on node 8"
This reverts commit 3b45ca33b969a56da0bccce4c95cae3b34af98e0.
* Revert "Do not throw"
This reverts commit 55624b9193d7751e1dc16cbee9005fe23ff19662.
* Revert "Revert "Run dev tests not serial""
This reverts commit cd5260a205b6478cb7a44c9ea982b99f26f2f2e9.
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Revert "Use catch instead"
This reverts commit fe652995c08e1e8b2ba581aaf7304b5432718161.
* Revert "Log fixture that failed"
This reverts commit feb0e7b393626ce1c117ef95f9e95f7a148e3dab.
* Revert "Update all yarn.lock files for now dev"
This reverts commit 36be4dd98ca6d65850843dc958727952dd7461ee.
* Update yarn.lock for 14-svelte-node
* Update es-abstract in all yarn.lock files
* Skip node test
* Revert "Skip node test"
This reverts commit c9c45ec8d6fcef13cbd300db410699b167d76ed2.
* Remove test.only
* Only execute node test in now-dev
* Revert "Only execute node test in now-dev"
This reverts commit 8ab7a88d696c1faa5fe0fbcca9dcfb0dd375925f.
* Clean cache on macos node8
* Fix query
* Use --skip-integrity-check
* Add --skip-integrity-check to different yarn call
* Add --network-concurrency 1
* Add retry
This fixes the scenario where the user defines `trailingSlash: true` and creates a file `/api/users.js`. They would expect to be able to visit `/api/users/` and it should run that function.
This PR removes the individual lambda zip prints since they're not very useful. We've already printed this information above and will time them as a group!
This fixes the scenario when both `{ cleanUrls: true, and trailingSlash: true }` so that only one redirect occurs when visiting `/file.html`.
Previously, this would have redirected twice from `/file.html` => `/file` => `/file/`.
Now it will redirect once from `/file.html` => `/file/`.
This PR does 3 things:
- add default caching headers
- redirect all missed requests to Gatsby's own 404.html page
- add deprecation message to `gatsby-plugin-now` since we're auto injecting it and it's not needed anymore
Fixes#2859
This PR refactors a few things:
- enhance validation so that invalid regex is caught before transforming to routes
- remove `filePaths` input parameter since it is no longer used
After this PR is merged and released, we'll be able to perform validation earlier in the build pipeline and report the errors to the user.
* [now-build-utils] Validate functions and allow them as config
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Change memory check
* Adjust test
We used to read the output files and create a route for each redirect when `cleanUrls: true`.
Instead, this PR will add 2 redirects for `cleanUrls: true` no matter how many files are in the outputs.
This updates `@now/build-utils` to add support for the function property including types and tests.
Related: [PRODUCT-27]
[PRODUCT-27]: https://zeit.atlassian.net/browse/PRODUCT-27
This PR is an attempt to automatically inject `gatsby-plugin-now` in Gatsby projects, as an optimisation.
- [x] avoid conflicts with existing files
- [x] refactor
There have been Sentry errors where `process.cwd()` fails and throws an error. This patch handles that scenario gracefully by printing a more clear error message to the user and avoids sending a report to Sentry.
Fixes#3193.
* Update version of deployment API
* Add `alias-assigned` event and handling
* Replace v9 api with v10
* Don't return on immediate ready
* Handle alias-assigned for v1 deployments
* Improve event ordering
* Detect upload deployment readiness by `alias-assigned`
* rebuild
* Fix upload readiness event type
* Check for aliases before running status checks
* Improve event flow and wait for `ready` in v1 deployments
* Remove console.log
Disables `--user` parameter of the `pip` utility, which is forcibly set under the hood on Debian systems and causes an error in the `pipInstall` function:
`distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base`
Fixes#3089
This PR disables Now 1.0 production deployments with the following error message:
> Option --prod is not supported for Now 1.0 deployments. To manually alias a deployment, use `now alias` instead.
It looks like this:
<img width="835" alt="Capture d’écran 2019-10-23 à 19 42 09" src="https://user-images.githubusercontent.com/6616955/67419574-3e125380-f5cd-11e9-81ff-63bde292539b.png">
Also disables `--target` for Now 1.0 deployments.
* Update version of deployment API
* Add `alias-assigned` event and handling
* Replace v9 api with v10
* Don't return on immediate ready
* Handle alias-assigned for v1 deployments
* Improve event ordering
* Detect upload deployment readiness by `alias-assigned`
* rebuild
* Fix upload readiness event type
* Check for aliases before running status checks
* Improve event flow and wait for `ready` in v1 deployments
* Remove console.log
When `cleanUrls` is true, the redirects will be applied to the routes however there are no longer any rewrites. Instead (through a different PR to fmeta-util) we will rename the file output to remove the `.html` extension.
When `cleanUrls` is true, the redirects will be applied to the routes however there are no longer any rewrites. Instead (through a different PR to fmeta-util) we will rename the file output to remove the `.html` extension.
There have been Sentry errors where `process.cwd()` fails and throws an error. This patch handles that scenario gracefully by printing a more clear error message to the user and avoids sending a report to Sentry.
Fixes#3193.
This PR disables Now 1.0 production deployments with the following error message:
> Option --prod is not supported for Now 1.0 deployments. To manually alias a deployment, use `now alias` instead.
It looks like this:
<img width="835" alt="Capture d’écran 2019-10-23 à 19 42 09" src="https://user-images.githubusercontent.com/6616955/67419574-3e125380-f5cd-11e9-81ff-63bde292539b.png">
Also disables `--target` for Now 1.0 deployments.
Disables `--user` parameter of the `pip` utility, which is forcibly set under the hood on Debian systems and causes an error in the `pipInstall` function:
`distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base`
Fixes#3089
This PR adds a `contentType` to the File interface.
This is necessary for [PRODUCT-341] to work properly with `cleanUrls` which will strip the file name but we will still need specify `contentType: 'text/html'`.
This is required for @dav-is `api-builds` PR 633 to work properly.
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
The `@now/node` helpers json parsing is too strict and doesn't match the behavior of Express when an incoming request has `{ method: 'POST', Content-Type: 'application/json', body: '' }`.
Instead of returning 400, this PR will continue with `body = {}` to match Express.
Fixes https://spectrum.chat/zeit/now/klarna-with-zeit-now~60852003-4db6-4ec4-a611-83b2349ece08
This PR does a few things
- Separate tests into `integration.test.js` and `unit.test.js`
- Use one static build instead of many to avoid `should NOT have more than 128 items` error
- Add a new unit test so we don't regress
Fixes#3159
This implements a new function `getTransformedRoutes()` which transforms some [superstatic](https://github.com/firebase/superstatic#configuration) configuration keys to Now routes so we can eventually use this new keys in `now.json`.
In particular, the following new keys are transformed to `routes`.
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
Our tests periodically fail because we're creating too many v1 deployments on a free plan and it times out.
This limits the number of deployments by running v1 exclusively under Node 12.
It also adds a missing waitForDeployment().
This makes it so that a programatically created `DevServer` instance that has `debug` mode enabled also gets set on the builder child processes as expected, rather than only when invoked via CLI.
For example, the `dev-server.unit.js` tests can set `debug: true` and with this change the builder child processes will also have debug logs enabled. See [here](https://git.io/JeW0O).
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR should fixes `ENOENT` related errors
```
> Error! ENOENT: no such file or directory, stat '.../node_modules/.bin/...'
```
Related: https://github.com/zeit/now/issues/3104
As of https://github.com/zeit/now-builders/pull/679, this logic is unnecessary because the `@now/static-build` builder will never end up executing the `dev` script when there is a `now.json` file present (and thus, no builds present, aka zero config mode).
Also, statically detecting the `now dev` command from the script command is brittle, as the command could execute a separate shell script that ends up executing `now dev` (and this detection logic would be a false negative).
This PR is a followup to #3138 so that `now dev` will validate and transform the following `now.json` config keys to routes:
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
This PR adds a `contentType` to the File interface.
This is necessary for [PRODUCT-341] to work properly with `cleanUrls` which will strip the file name but we will still need specify `contentType: 'text/html'`.
This is required for @dav-is `api-builds` PR 633 to work properly.
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
The `@now/node` helpers json parsing is too strict and doesn't match the behavior of Express when an incoming request has `{ method: 'POST', Content-Type: 'application/json', body: '' }`.
Instead of returning 400, this PR will continue with `body = {}` to match Express.
Fixes https://spectrum.chat/zeit/now/klarna-with-zeit-now~60852003-4db6-4ec4-a611-83b2349ece08
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR does a few things
- Separate tests into `integration.test.js` and `unit.test.js`
- Use one static build instead of many to avoid `should NOT have more than 128 items` error
- Add a new unit test so we don't regress
Fixes#3159
This implements a new function `getTransformedRoutes()` which transforms some [superstatic](https://github.com/firebase/superstatic#configuration) configuration keys to Now routes so we can eventually use this new keys in `now.json`.
In particular, the following new keys are transformed to `routes`.
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
Our tests periodically fail because we're creating too many v1 deployments on a free plan and it times out.
This limits the number of deployments by running v1 exclusively under Node 12.
It also adds a missing waitForDeployment().
This makes it so that a programatically created `DevServer` instance that has `debug` mode enabled also gets set on the builder child processes as expected, rather than only when invoked via CLI.
For example, the `dev-server.unit.js` tests can set `debug: true` and with this change the builder child processes will also have debug logs enabled. See [here](https://git.io/JeW0O).
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR should fixes `ENOENT` related errors
```
> Error! ENOENT: no such file or directory, stat '.../node_modules/.bin/...'
```
Related: https://github.com/zeit/now/issues/3104
As of https://github.com/zeit/now-builders/pull/679, this logic is unnecessary because the `@now/static-build` builder will never end up executing the `dev` script when there is a `now.json` file present (and thus, no builds present, aka zero config mode).
Also, statically detecting the `now dev` command from the script command is brittle, as the command could execute a separate shell script that ends up executing `now dev` (and this detection logic would be a false negative).
This is a follow up to #3117 which added a fix for `files` but did not observe directories.
This PR fixes the scenario where a directory is defined such that all files inside the directory should be added uploaded (recursively).
Thanks to @williamli
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
This is a follow up to #3117 which added a fix for `files` but did not observe directories.
This PR fixes the scenario where a directory is defined such that all files inside the directory should be added uploaded (recursively).
Thanks to @williamli
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
Since `@now/static-build` is no longer sniffing the stdio streams for the bound port number in `now dev`, there's no need to have separate stdio streams for the "dev" script. Instead, inherit stdio from the parent process, which will allow for ANSI colors to be used when stdout is a TTY in `now dev`.
Also simplifies the `checkForPort()` function and removes the `promise-timeout` dependency.
When now-client was implemented, it did not work with `--local-config` flag from now-cli because the only parameters it looks at are the files in a directory.
This fixes the regression in now@16.3.0 so that now-client can accept an optional `nowConfig` object or fallback to the `now.json` file.
Fixes#3099Fixes#3105Fixes#3107Fixes#3109
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
For context, when you have a script that generates a new static file at build time (`sitemap.xml` for example), it has to be inside `.next/static`, and then you'll need a Now route for it, with this change you could generate the file inside `public`/`static` and the builder will now take care of it.
The util `includeOnlyEntryDirectory` is no longer being used after this change, should I remove it?
This PR integrates v2 of Projects API that fixes an issue for projects named `list` or `remove`, because of the naming of the endpoints in v1. For listing all projects, previously in v1 it was `GET /v1/projects/list` and now it is `GET /v2/projects/`, and for removing a project it was `DELETE /v1/projects/remove`.
Since `@now/static-build` is no longer sniffing the stdio streams for the bound port number in `now dev`, there's no need to have separate stdio streams for the "dev" script. Instead, inherit stdio from the parent process, which will allow for ANSI colors to be used when stdout is a TTY in `now dev`.
Also simplifies the `checkForPort()` function and removes the `promise-timeout` dependency.
When now-client was implemented, it did not work with `--local-config` flag from now-cli because the only parameters it looks at are the files in a directory.
This fixes the regression in now@16.3.0 so that now-client can accept an optional `nowConfig` object or fallback to the `now.json` file.
Fixes#3099Fixes#3105Fixes#3107Fixes#3109
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
For context, when you have a script that generates a new static file at build time (`sitemap.xml` for example), it has to be inside `.next/static`, and then you'll need a Now route for it, with this change you could generate the file inside `public`/`static` and the builder will now take care of it.
The util `includeOnlyEntryDirectory` is no longer being used after this change, should I remove it?
This PR integrates v2 of Projects API that fixes an issue for projects named `list` or `remove`, because of the naming of the endpoints in v1. For listing all projects, previously in v1 it was `GET /v1/projects/list` and now it is `GET /v2/projects/`, and for removing a project it was `DELETE /v1/projects/remove`.
It will print `[v2]` for 1.0 deployments when logging initially:
```
• go $ now --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v2] [1s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [22s]
> Success! Deployment ready
```
Expected:
```
• go $ nowl --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v1] [2s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [23s]
> Success! Deployment ready
```
For v2 it shouldn't print anything, as it's the default.
This makes downstream compilation with `tsc` work correctly.
Otherwise, compilation fails with errors such as:
```
../now-client/dist/src/index.d.ts:1:40 - error TS2304: Cannot find name 'CreateDeploymentFunction'.
1 export declare const createDeployment: CreateDeploymentFunction;
~~~~~~~~~~~~~~~~~~~~~~~~
````
As of https://github.com/zeit/now/pull/3081, we make it necessary to group `Prerenders` together for being invalidated at the same time.
However, you might not want that. In turn, we'll make it optional.
This pull request removes the `PrerenderGroup` type in favor of a `group` parameter for the existing `Prerender` type.
This parameter takes in an integer that defines a group of prerenders that should be invalidated at the same time:
```
interface Prerender {
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
group: number;
}
```
**Example:** If two `Prerender` instances exist that have `group` set to `1`, they will both be invalidated at the same time.
This PR adds extensive debug logging to `now-client` and enables it in CLI based on the `--debug` flag
Debug logging works in either of the following two conditions:
- `debug: true` is provided in the `options` object of `createDeployment`/`createLegacyDeployment`
- `process.env.NOW_CLIENT_DEBUG` environment variable is set
It will print `[v2]` for 1.0 deployments when logging initially:
```
• go $ now --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v2] [1s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [22s]
> Success! Deployment ready
```
Expected:
```
• go $ nowl --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v1] [2s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [23s]
> Success! Deployment ready
```
For v2 it shouldn't print anything, as it's the default.
This makes downstream compilation with `tsc` work correctly.
Otherwise, compilation fails with errors such as:
```
../now-client/dist/src/index.d.ts:1:40 - error TS2304: Cannot find name 'CreateDeploymentFunction'.
1 export declare const createDeployment: CreateDeploymentFunction;
~~~~~~~~~~~~~~~~~~~~~~~~
````
As of https://github.com/zeit/now/pull/3081, we make it necessary to group `Prerenders` together for being invalidated at the same time.
However, you might not want that. In turn, we'll make it optional.
This pull request removes the `PrerenderGroup` type in favor of a `group` parameter for the existing `Prerender` type.
This parameter takes in an integer that defines a group of prerenders that should be invalidated at the same time:
```
interface Prerender {
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
group: number;
}
```
**Example:** If two `Prerender` instances exist that have `group` set to `1`, they will both be invalidated at the same time.
This PR adds extensive debug logging to `now-client` and enables it in CLI based on the `--debug` flag
Debug logging works in either of the following two conditions:
- `debug: true` is provided in the `options` object of `createDeployment`/`createLegacyDeployment`
- `process.env.NOW_CLIENT_DEBUG` environment variable is set
Previously, if you ran `now ls` with a URL for a path alias, then an
error message `Cannot read property 'replace' of undefined` would occur.
Now, a message is logged saying to instead run `now alias ls $url` which
is the correct command to get path rules relevant to a path alias URL.
> Found matching path alias: rules.domain.com
> Please run `now alias ls rules.domain.com` instead
Fixes#2987.
* [now-static-build] Run `bundle install` for Gemfile
* Add logs
* Add timeout in case proc hangs
* Rename test
* Remove console.log()
* Hide warnings
* Use runBundleInstall()
* [now-build-utils] Remove --deployment flag
* Run tests for build-utils
* [now-build-utils] Add function `runBundleInstall`
* Add additional flags
* Set jobs to number of cpus
* Format
* Fix formatting
* Add BUNDLE_APP_CONFIG
* [now-static-build] Fix dev server detection
* Code review
* Remove unused dependency
* Fix the checking by really waiting until the port is reachable
* [now-build-utils][now-cli] Warn instead of throwing on `api` and `pages/api`
* Remove slash and adjust tests
* Remove @now/build-utils
* Hardcode builders
* Add build-utils
* Change default flag
* More logging
* Add static-build
* Remove other packages from package.json
* New file for bundled function
No functionality change here, this just removes the `Package` and
`BuildConfig` types from `src/util/dev/types.ts` in favor of the
matching types from `@now/build-utils`.
Also a lot of prettier formatting…
No improvements, per say, but the module has been converted to
TypeScript so it supplies its own type definitions now, and we
can delete our hand-crafted typings from this repo.
* [now-cli] Use `xdg-app-paths` for `now dev` cache dir
For consistency, because #2877 uses this module.
No need for multiple modules that do the same thing.
* Update `@zeit/fun` to v0.9.3
* [now-cli] Fix `now certs ls` when the user or team has no certs
* Add tests and move to typescript
* Move index and add to typescript
* Fix reduce function in ls
* Added linebreak
* Update packages/now-cli/src/commands/certs/add.ts
Co-Authored-By: Naoyuki Kanezawa <naoyuki.kanezawa@gmail.com>
* [now-cli] Install dependencies before running `now dev` in tests
* Check install exit code
* Add more logging
* Add more logging
* More logging
* Include yarn.lock file
* Add lock files to dev fixtures
* Ignore test
* Ignore another test
* Ignore another test
* Whitespace
* Install deps for unit tests
* Whitespace
* add gatsby-plugin-now
* add test
* adjust with lerna
* fix test
* add tests to circleci
* add support for defaultRoutes functions
* add defaultRoutes to gatsby
* fix types
* add test case for gatsby redirects
* remove gatsby, react, react-dom from monorepo deps
* chmod +x build.sh
* add missing build script in fixtures
* do stuff during tests to avoid persistence issue
* move tests setup to build step
* copy gatsby plugin files in test case
* bring back ncc step
* prettier gatsby-plugin-now
* add missing semicolons
* remove eslint, prettier from plugin
* persist build step copied file
* fetch without following redirects
* add files in package.json
* remove force
* fix tests probes
* fetch location is not raw location
* fix test
* add readme
* fix type error
* adjust tests
* add support for `force`
* add tests for `force`
* adjust tests again
* gatsby-plugin-now@1.1.0
* `"` -> `'`
* tweak redirect names in test by precaution
* change file name and delete when consumed
* format files
* gatsby-plugin-now@1.2.0
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* tests -> test
* add --verbose
* adjust circleci to persist fixtures
* trigger tests
* add repository and homepage in package.json
* glob files after `defaultRoute` invocation
* Optimize zipping lambdas for now-next
* Update to use jszip to get around bug in yazl
* Add pseudo layer utils
* Apply suggestions from code review
Co-Authored-By: Joe Haddad <joe.haddad@zeit.co>
* Update sema concurrency from tests
* Update packages/now-next/src/index.ts
* Use custom types to fix broken @types package
* Add license header
* Revert "Use custom types to fix broken @types package"
This reverts commit 82441285155f6e0899c43dffdd5e000ecbd7b1b6.
* Fix CI Yarn installation
* TypeScript types should never be hoisted
* Fix all typechecking
* [now-go] Use `debug()` from build-utils (#923)
* Use `debug()` from build-utils
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Print errors
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Use XDG standard instead of writing to home directory
* Fix typos
* Use dependencies as dev dependencies
* Remove lodash dependency
* Use xdg-app-paths instead of xdg-portable
* use find instead of filter(...)[0]
Otherwise, JavaScript Object built-ins such as `hasOwnProperty` are
incorrectly considered a valid subcommand, but fail afterwards with
a `require()` error and confusing error message.
* [now-cli] Validate inputs for alias, list and remove
* Log test output
* Add more logging to test
* Change to execa
* Use `split`
* Only validate when it exists
* [now-cli] Change success message after login
* Linting
* Test now login
* Linting
* Revert "Test now login"
This reverts commit 690360db3f148552a456b4ee1bd2a59b8d09216c.
* Revert "Linting"
This reverts commit 3d5ebfaa76ecdcc2152c8344c8e1205b241abe09.
* Adjust test
* Remove binaryPath from args
* Fix loggin test
This enables https://github.com/zeit/now-cli/pull/2747 from @nkzawa again.
We had to revert the previous one, because we didn't want to include it in
the next stable release.
This further makes sure that we don't display `https://` in front of a
wildcard alias, since `https://*.mydomain.tld` is not a valid URL.
* [now-cli] Validate builds and routes for `now dev`
* Remove @ts-ignore
* Sort the matches such that `utils` modules are compiled first
Because other packages may rely on them
* Prettier
* Add `reject: false` to tests
* Prettier
* Make validation async
* Fix syntax
* Fix type
* Linting
* Fix error check
* [now dev] Update `yarn` to v1.17.3
* Wait longer for angular integration test
It keeps on failing
* Only run angular test on Node 10.x
* Revert "Wait longer for angular integration test"
This reverts commit 19d70d4ba9aee49a5114b65f00ef97e2a88dc7ef.
* Update links to `now-builders` repo to `now` repo
Also copies over the `.md` files from the now-builders' `errors`
directory so that the https://err.sh links work correctly.
Part of #2782.
* Update `err.sh` links that were formerly `now-cli`
* Empty commit for CI
* Make CircleCI `run.sh` script a bit better
Before it would fail with exit code 1 if there were no matching modified
files because of the `grep` call failing without any `packages` prefixed
files.
* [tests] Change run script from bash to node
* Fix loop for runScript
* Fix `all` script test
* Improve console.log() messages
* Use -l instead of -p
* Delete yarn.lock from now-python
* Move now-cli to /packages/now-cli
* Fix .gitignore paths
* Add now-client
* Add lerna to top level
* Add scripts
* Update codeowners
* Fix `/now-cli/build.ts` script
* Fix circleci path to artifacts
* Use relative paths
* Fix path to scripts
* Add test-lint script
* Add missing return type
* Fix typo in test-lint
* Fix string match in shell scripts
* Fix path to hugo
* Add package node_modules
* Delete lock files in packages, use root yarn.lock
* Add missing b.js file
* Add test-integration-now-dev script
* Add missing test files
* Add missing integration test script
* Add missing test files
* Delete travis.yml
* Fix ts-jest in now-client
* Add support for Node 8 (ES2015 target)
* Add support for Node 8
* Add polyfill for Node 8
* Fix polyfill for Node 8
* Only run coverage for now-cli
* Add packages from now-builders
* Run integration tests for builders
* Add node_modules to cache
* Add root readme.md
* Move readme to top level
* Add yarn bootstrap
* Add bootstrap step
* Add dist to `persist_to_workspace`
* Fix 08-yarn-npm integration test
* Remove duplicate path
* Change stdio to inherit
* Add back store_artifacts
* testing - remove bootstrap step
* Add back now-build-utils
* Remove bootstrap step
* Fix test again
* Add console.log()
* Fix lint
* Use local ncc version
* Install go
* Revert changes to stdio and console.log()
* Add missing now-go test
* Add missing integration tests
* Add --runInBand flag
* Fix now-node-bridge persistence
* Add missing symlinks
* Add codeowners
* Consolidate into single run.sh function
* Run uniq
* Fix typo
* Change now-routing-utils to test-unit
* Special case test for node 8
* Add docs from builders
* Only run script for modified packages
* Add test-integration-once which only runs once
* Fix set intersection
* [now deploy] Add `--production` and `--staging` flag
* Change message
* Fix tests
* Fix test
* Add another test
* Fix production test
* Update message and add `--prod`
* Update help
* Remove `--staging`
* Use only `--prod`
* Add test
* Add aliasError output
* Fix output
* [now rm] Use the proper `client` so that the process does not hang
The crux of this fix is that `getDeploymentByIdOrHost()` and
`getProjectByIdOrName()` were improperly being passed the `Now`
instance instead of the expected `Client` instance, and for some
reason that would cause the process to hang until the underlying
`http.Agent` timed out its connection to the API server.
Also ran `prettier` on this file.
Fixes#2760.
* Remove `console.error()`
* Add integration test
* Fix syntax error
* Add `now rm` 404 integration test
* Remove `.only`
* Use canary builders for the canary version
* Use the `getDistTag` function instead
* Fix function call
* Add tests
* Remove unused code
* Remove logging
* [now dev] Add `--bind` / `-b` flag
This changes the default network interface that `now dev` binds to, in
order to prevent operating system firewalls from showing a confirmation
prompt in order to run.
Fixes#2704.
* Change to `--listen`
* Default port 3000
* Fix unit
* Fix `--port`
* Use `-l` for integration tests
* Add unit tests
* [now update] Show correct global or local install command
* Remove `canRead` check
* Change bin to lib since the actual script will be there
* Use realpath
* Remove console.error
All of the APIs already support JSON by default, so this is a no-op for
our APIs, however the proxy layer _does_ respect the `Accept` header to
send JSON error responses, which is useful for more gracefully handling
outage responses (previously they were being returned as plain text,
which Now CLI blindfully tries to parse as JSON and fails with an
unhelpful error message).
Related to #2681.
For some reason, `ava` was silently skipping these tests on CI because
the process was crashing. According to sindre, this is a bug in `ava`,
but with some digging I was able to determine that the root cause of the
crash was that the `builders.tar.gz` file from the `assets` dir was not
being persisted from the previous `build` job in CI.
With the `assets` dir being persisted I now see the `dev-server` unit
tests being executed once again as expected.
Related to: https://twitter.com/sindresorhus/status/1157614353375551493
* [now deploy] Use the project when checking the platform version
* Update src/util/prefer-v2-deployment.ts
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Update src/util/prefer-v2-deployment.ts
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Adjust message
* Fallback for local config
* [now dev] Render warning upon empty `cwd` directory
The warning matches the one that `now deploy` prints, and only
prints the warning once (rather then upon every HTTP request).
Closes#2696.
* Fix eslint warning
* Add "pipe"
* Debugging…
* Fix integration test
* Debugging…
* Add `--verbose` to "test-integration-now-dev" script
* Ignore `yarn.lock` and `node_modules` in test dir
* Ignore `hugo` binary
* Ignore `public` dir in hugo test fixture
* Add `.gitignore` to `empty` test fixture
* Revert "Debugging…"
This reverts commit 27c6d2e06fe7eff12077a0e88915cf46b39b00ea.
* Ignore `public` / `dist` dirs in fixtures
This is to prevent false-positives like this from occurring,
and fixes the warning from `node`:
```
$ ts-node ./scripts/build.ts
Creating builders tarball with: @now/build-utils@canary, @now/go@canary, @now/next@canary, @now/node@canary, @now/php@canary, @now/static-build@canary
(node:156) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '/home/circleci/repo/assets/builders.tar.gz'
at ReadStream.evt.error.err (/home/circleci/repo/node_modules/promisepipe/index.js:30:23)
at ReadStream.emit (events.js:198:13)
at ReadStream.EventEmitter.emit (domain.js:448:20)
at /home/circleci/repo/node_modules/graceful-fs/graceful-fs.js:207:14
at /home/circleci/repo/node_modules/graceful-fs/graceful-fs.js:258:16
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
(node:156) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:156) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```
* [now deploy] Check if builds are ready right away
* Adjust tests
* Remove test
* Log more while testing
* Remove check in tests
* Adjust all tests
* Log more
* [now dev] Support JSON and HTML redirect responses
Matches the production behavior.
* Set Now response headers during redirect
* Set `location` header
* Remove unused `matched_route` var
* [now dev] Allow custom 404 pages via `routes`
This matches the behavior in production, which allows a `dest` to be
provided when defining a `status: 404` in the routes configuration.
Related to #2638.
* Fix typo
* [preinstall/now update] Check if now is installed locally and adjust messages
* Adjust test
* Add tests
* Wait for deployment to be ready
* Removed log
* Adjust prefix in test
* Adjust path
* Only wait 4 minutes
* More logging
* Change binPrefix to prefix
* Remove all linting warnings
* Adjust env vars for test
* Don't test on node 8
* Log more error information and fail right after 500
* Move docker test up
* [now dev] Support JSON and HTML error responses
Closes#2609.
* Compile templates for unit tests in CircleCI
* Update `ts-node` to v8.3.0
* Convert doT.js compiled templates to TypeScript
* Compile templates for lint tests in CircleCI
* Print convert time
* Add 502 error template
* Remove `message` param from `sendError()`
* Prettier
* Add 404 tests
* Fix test
* [now deploy] Change link for legacy warning
* Remove trailing slash
Co-Authored-By: Steven <steven@ceriously.com>
* Simplify `link` function
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Determine which link to show and add test
* Adjust link for configuration
Co-Authored-By: Steven <steven@ceriously.com>
* Adjust Package type
* [CircleCI] Add more tests for macos support
* Change xcode version since node 8.9.x is required
* Log stderr and stdout
* Add custom start script
* Make tests use custom start script
* Made start script executable
* Use correct node path
* Fix script path
* Handle status code
* Use latest Node.js version for macos tests
* Include yarn.lock for ember test
* Only use start script in tests
* Change start script for macos
* Change start script for linux
* Change start script for linux
* Update `NOW_BUILDER_DEBUG` base on `--debug` flag
* No need to reset `NOW_BUILDER_DEBUG`
* Add comment for `NOW_BUILDER_DEBUG`
* Apply suggestions from code review
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* [now dev] Bundle `canary` builders for Now CLI canary
Closes#2641.
* Add unit tests
* More unit tests
* Use `semver.parse()` in `getDistTag()`
* Convert build script to TypeScript, DRY the `getDistTag()` function
* Prettier
Run the `now dev` integration tests in parallel with the "standard"
integration tests, since they both take a long time. This should
cut the CI testing time in about half.
* Support Node 8
This changes the TypeScript compilation target to "es2015" so that
async generator functions are transpiled, which enables Node 8 to be
supported.
As a side-effect, any of the files that utilize `async function*` or
`for await` needed to be converted to TypeScript so that the
transpilation actually happens.
It was painful to do this process for `src/commands/deploy/legacy.ts`,
and since it is legacy code I did not want to make too many changes to
the code, so there's a log of `@ts-ignore` and `any` types being used.
But the behavior of the file should not have changed at all.
* Make `engines` field be ">= 8"
* Add Node 8 to CircleCI matrix
* Remove `console.error()`
* Remove `.ts` extension on import calls
* Use `Now` instead of `any`
* Use native `url` module instead of `whatwg-url`
* Debug integration test
* Skip `02-angular-node` test on Node 8
* Remove debugging
* Add "Downloading Hugo" step to Node 8 tests
* Skip `03-aurelia` test on Node 8
* Skip `03-aurelia` test for all
All node versions are failing with the same error:
https://circleci.com/gh/zeit/now-cli/29922
* Use `fs-extra` instead of `fs.promises` for Node 8
* [now deploy] Consider `--npm` and `--docker` for platform detection
* Change order
* Change prepare
* Await fixtures
* Remove check
* Revert "Remove check"
This reverts commit 7a5c1c901085d4e22c5a34cc48b5d929a9ee3b80.
* Use async-retry
* Fix fetch
* Log token
* Retry user creation
* Add async
* Add try-catch
* Decrease the retries
* Use original way to get context name
* Using `stdio` to resolve `now dev` Ready
* Update test/dev/integration.js
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* Improve `testFixtureStdio` and update aurelia fixture
* Remove duplicate test
* Update `create-react-app` and `gatsby` test fixture
* Update `gridsome` test fixture
* Update `hugo` test fixture
* Update `jekyll` test fixture
* Add `marko` test fixture
* Add `mithril` test fixture
* Add `riot` test fixture
* Add `charge` test fixture
* Add `brunch` test fixture
* Add `docusaurus` and `ember` test fixtures
* Install ruby for `jekyll`
* Update base on platform for `jekyll` and `hugo`
* Use `sudo` to when installing `gem`
* Remove `09-jekyll`
* Extract the right filename
* Remove `-L` flag from `curl` for macOS
* Use different version of `hugo`
* Remove `min_version` from `08-hugo` theme
* [CircleCI] Run integration tests on multiple versions of Node.js
* Test Node 10 and Node 12
* Remove `fs.promises` usage for Node 8
* More `fs.promises` removal
* Remove Node 8, it is unsupported due to `async` function usage
* [now update] Render the proper tag and improve `yarn` detection logic
Before this the suggested command would always have you install the
stable version of `now`.
With this change the `@canary` tag will be suggested if the version of
`now` is from the canary release channel.
Also updates the `isYarn` detection logic to not consider the cwd, and
instead check the installed version of now's `package.json` for clues.
* Move `getUpdateCommand` to util
* Add a unit test
* Use integration test instead
* Remove `pkg` bundling
* Remove `(dev)` from `--version`
* Remove `test/dev-builder.unit.js`
* Temporary disable `update now to canary test`
* Update `now update` command
* Removed useless jobs
* Removed useless code
* Removed more useless code
* Use update command
* Only run publish upon tag
* Removed code
* No need bin, use dist directly
* Update test, using the right file
* Reslove `iconv-lite@0.5.0` version
* Removed useless file
* Added scripts directory
* Removed useless stuff
* Fixed build script
* Fix `now dev` integration test
* Also block coverage on linting
While debugging #2606, I noticed that the `Client` instances for
`now deploy` were not being supplied the appropriate `debug` flag
based on the command line args.
PR #2562 caused an issue with blocking builds at bootup being built
twice, which is problematic when i.e. running `yarn` simultaneously
on the same directory causing cache corruption issues.
The `getNowConfig(false)` used to be within this `if` branch, so the
debug call made sense there at the time, but as of zero config it got
moved to always be invoked, so this `debug()` call doesn't make sense
anymore.
* [now dev] Wait for blocking builds to complete before handling requests
After the `now dev` server has already booted, if you delete a build
match that previously required a build at bootup time (i.e. `@now/next`)
from the `builds` array in `now.json` (i.e. change the builder to
`@now/static`), and then change it back to `@now/next`, then previously
the build would never execute.
With this change, the blocking build occurs as expected, and any HTTP
requests that occur are blocked until that build has completed.
* Prettier
* Better diff
* Add test
* [now dev] Add warning when there are no build matches
This matches the error in production, except it's just a non-fatal
warning when running in `now dev`. This is so that the user can fix
the warning without having to restart the `now dev` server.
* Add integration test
* [now update] Render the proper tag and improve `yarn` detection logic
Before this the suggested command would always have you install the
stable version of `now`.
With this change the `@canary` tag will be suggested if the version of
`now` is from the canary release channel.
Also updates the `isYarn` detection logic to not consider the cwd, and
instead check the installed version of now's `package.json` for clues.
* Move `getUpdateCommand` to util
* Add a unit test
* Use integration test instead
* [now dev] Print `Serving all files as static` only once
* Track the config state
* Revert "Track the config state"
This reverts commit 9766941ca8cd1ffeae5fb0729800f05f2547099c.
* Revert "[now dev] Print `Serving all files as static` only once"
This reverts commit 3e30c2440b6c4deed8a14f2359696e7bf8dcdcad.
* Add `isInitialLoad` param
* Add configuration and basic integration tests for `now dev`
* Add test fixtures from `now-examples`
* Add `include` to `tsconfig.json`
* Increase retries for 00-list-directory
* Increase retries for `03-aurelia-node`
* Enable test fixtures for hexo, hugo, next, polymer, preact, svelte, vue, and vuepress
* Increase retries for `08-hugo-node`
* Disable `08-hugo-node` fixture
* Enable `04-create-react-app-node` test
* Disable `04-create-react-app-node` test
* Better name for now dev test job
* [now init] Add suggestions for old examples
* Add support for selecting an old example
* Add message for selection
* Wait for user interaction
* Fix typo
* Use v2 api instead
* Move message label to first param
* Bump api url to latest, update download to v2
* Rename found to visible
The `getNowConfig()` function gets invoked frequently, and it is also
async and makes mutations to the cached now config object. This ends
up being a race condition when `getNowConfig()` is invoked concurrently,
since one of the invocations may end up with an incomplete `NowConfig`
object (namely, with missing `builds`/`routes` arrays due to the
zero-config processing).
This change makes it so that there's only one `getNowConfig()` invocation
being executed at a time, and other concurrent executions will await the
same promise that the original invocation is responsible for.
* Update deps of deps in `yarn.lock` file
To fix #lodashgate:
* Upgrade `lodash.merge` to version 4.6.2 or later.
* Upgrade `lodash` to version 4.17.13 or later.
* Regenerate `yarn.lock`
* [now dev] Wait for `updateBuilders()` to complete before `stop()` completes
Since #2477, the unit tests related to `now dev` have become flaky, and
need to be retried a couple of times before running successfully. My
theory is that this is related to having concurrent `yarn` processes
operating on the builders module directory, causing corruption with yarn's
cache. Waiting for the lazy updating `yarn` process to complete makes
sense to me, hopefully CircleCI agrees.
* Debugging "list the scopes" integration test
* Moar debug
* Use regular `require()` when not in a webpack build (ava tests)
* Remove debug
Fixes this error from the pkg'd binary:
```
Error: File or directory '/**/now-cli/dist/builders.tar.gz'
was not included into executable at compilation stage.
Please recompile adding it as asset or script.
```
* [now dev] Bundle the most popular core builders into CLI binary
Makes Now CLI bundle a tarball inside its snapshot filesystem that
includes the following builders:
* @now/go
* @now/next
* @now/node
* @now/php
* @now/static-build
The tarball is generated by the `build.js` script and ensures the
"latest" version of the builders are included into the tarball.
When `now dev` is run, the tarball will be extracted upon the first
run to make these builders "pre-installed" to avoid the "Installing
builders" phase during boot-up.
Overall, this should make booting up `now dev` a lot faster, and help
with offline support.
* Don't install builders if they are bundled
* Persist `assets` dir to CircleCI workspace
* Delete build assets
* Fix installing builders from URL
* Finish builder installation filtering logic
* Still install `@now/build-utils`
* Implement builders installation "stale-while-revalidate"
* Remove `console.time()`
* Fix unit test
* Add `Readonly<>` to `BuilderWithPackage` type props
* Add debug log stack trace upon builder update failure
* Disable automatic signup
* Use shorter error message
* Update tests
* Update tests with user info
* Create tmpDir before tests
* Tweak fixtures and assertions for new login
* Don't pre-create the test directory in CI
* Use `os.homedir` instead of `~` in tests
* Pre-create auth directory conditionally
* [now dev] Render directory listing for Now v2 projects
Before directory listings only worked for "all static" deployments since
`now dev` would shell out to `serve-handler` to do the rendering.
Now the directory listing rendering logic is moved into `now dev` which
allows projects with Lambdas to also serve the directory listing
(previously they would just 404).
This removes the special-casing of "all static" deployments so that
there's only one code path.
Fixes#2161.
Fixes#2417.
* Move `serve-handler/src/directory` types to root
* Set `Content-Length` header for dir listing
* Add unit tests for directory listing
* Fix unit test
* [now dev] Update @now/build-utils and handle warnings
* Display warnings from response headers for deployment creation
* Update src/util/dev/server.ts
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Apply routes only when there are no builds
* Updated the build utils
* [now dev] Update `serve-handler` to v6.1.0 and enable `etag` option
Sending the `ETag` response header matches how Now in production works.
* Test file contents as well
* [now dev] Revert "Add `etag` response header for Lambda invocations"
This reverts commit f80f1f79a6 (#2502).
`ETag` header is only sent in production when the lambda function sets
the "stale-while-revalidate" cache-control header, which will be
implemented in a separate PR.
* Remove `etag` test assertion
* [now-dev] Add zero config
* Update @now/build-utils
* Update @now/build-utils
* Escape glob
* Fix windows and group globbing
* Made sure routes and builds get updated on file events
* Removed useless check
* Add unit tests
* Use fetch instead of get
Before this change, the `installBuilders()` function was only run at
bootup, so if you modify `now.json` during runtime and add a builder
that's not installed, then a `MODULE_NOT_FOUND` error occurs.
Now the `installBuilders()` function is run with the missing builder
so that the builder can be properly loaded.
`validateEnvConfig()` used to be invoked inside of `validateNowConfig()`,
but now it is invoked separately.
Explicitly exiting the process avoids reports going to Sentry.
* [now dev] Allow `cache-control` header to be overwritten
This matches the behavior in production.
* Add `now-dev-headers` unit test fixture
* Remove `console.error()` call
This matches the production router behavior, and prevents running `now
dev` on a different project from serving stale content from a different
project.
Also update the `x-now-id` header to match the production behavior (it
changed at some point).
* [now update] Add message saying that Windows is not supported
And direct the user back to the download page in order to re-install.
Closes#2492.
* Exit 1
Co-Authored-By: Steven <steven@ceriously.com>
* [now dev] Use system installed version of Node.js for builds
Rather than downloading the 8.10 Node.js binary, simply assume that the
user has their preferred version of `node` already installed onto the
system and use that version.
If there is no `node` binary in the $PATH, then `process.execPath` is
used instead, meaning that the pkg binary node version will be used.
* Simplify `getNodeBin()` using `nothrow` option
* Fix build
* ignore metrics with environment variable
* collect exception and exit code
* add deprecated warning for `now alias [id] [url]`
* add exception in util error
* consistent format
* ensure no duplicate warning
* using the right error message
* refactor metrics util
This error happens when Ctrl+C is pressed before the `http.Server`
instance is listening, meaning that the user attempted to quit very
quickly after starting `now dev`.
This change makes the process exit immediately instead of throwing,
which also causes the error to be sent to Sentry (which we do not want).
* More cert errors handling for deploy command
* Apply suggestions from code review
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* Revisions based on review
* Minor revision
* Adds get-deployment-by-id which uses latest v9 endpoint
* Refactor to use apiVersion
* Update now rm
* Fixed typo
* Don't use .flat() because of node 10
* Exit process
* Remove only the project instead of all deployments of it
* Changed output text
* Headlines for projects and deployments
* Typo and number prefix
1. Handle permissions errors in both update mechanisms
2. Handle `EBUSY` (Windows) as a file busy error
3. Update permissions error prompt to say "Administrator Command Prompt" on Windows
4. Add message about "unexpected end of file" error
Rather then throwing which causes the process to exit.
Better to give the developer a chance to fix the syntax
error without having to restart the dev server afterwards.
* Use v4 instead to prevent listing the same deployment multiple times
* Remove the latestDeployments since it is depracted and doesn't have the
`readyState` property and only get 35 projects instead of 50 to lower
the rate limit
* Fix tests
* [now dev] Strip prefixed `/` when doing routes matching
The prefixed `/` is implicit when matching routes, so strip them
so that they are optional. This matches the behavior in production.
* Fix unit tests
* More readable
* Add unit test
* integrate universal metrics
* Update src/index.js
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Add default `collectMetrics` config
* Remove flag, only using global config to disable metrics
* Add GA tracking ID
* Move constant to file
* Rename constant to constants
* Rename `dsn` to `SENTRY_DSN`
* Apply suggestions from code review
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Remove extra space
* Update event category and action
* Remove usagestate to use universal-analytics
* Chain timing and event function
* Make sure to user are unique
* Ensure unique User ID
* Add extra User-Agent and move metrics into its own file
* Use default export
People are often trying to store secrets starting with dashes such as
private keys. These dashes get interpreted as command line options which
effectively prevents a storage of private keys.
Fortunately, this is easily resolved by using bash -- convention to mark
an end of options, such as:
`now secret add google-secret-key -- "-----BEGIN PRIVATE KEY-----
abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ+/a
-----END PRIVATE KEY-----"
The problem is also discussed in following issues:
https://github.com/zeit/now-cli/issues/749https://github.com/zeit/now-cli/issues/80
* [now dev] Use `chokidar` for file watching
`nsfw` is not suitable for very large projects because it does not
have any "ignore" functionality implemented.
For macOS, the `useFsEvents` option is _disabled_, so that the
`fsevents.node` binary file does not need to be cached onto the
filesystem, which simplifies things for use with `pkg` binaries.
* Delete the `fsevents` module during build
* Add proper `.nowignore` logic to the chokidar watcher
Alpha versions of `now dev` that used npm instead of yarn were
installing the packages to `devDependencies` rather than `dependencies`,
so this fixes package name lookup when a legacy cache like that is on
the user's machine.
* [now dev] Use the dev server `cwd` as builder's `workPath`
Rather than copying the source files into a temporary directory,
simply use the existing source files in the `cwd`. This will make
subsequent boots of `now dev` be faster (i.e. because the `node_modules`
directory will already be in place), as well as use much less space on
the filesystem because temporary directory are no longer being used.
This will require some changes to the builders and `@now/build-utils`,
to ensure that the `download()` function is always installing into
`workPath`, and that the `meta` object passed to the `build()` function
is also passed into the `download()` function.
For example:
- https://github.com/zeit/now-builders/pull/474
- https://github.com/zeit/now-builders/pull/475
* Update `@now/build-utils` to v0.5.5-canary.1
This makes `download()` be a no-op when running in `now dev`.
* Add test case for `@now/next`
* Fix debug log formatting
* [now dev] Mix in routes query params when proxying to a URL
Fixes#2289.
* Refactor unit tests and add a unit test for proxy passing with query params
* Fix TypeScript compile error
* [DEBUG] Disable proxy pass unit test
* Run unit tests serially
* Remove `console.error()` in unit test
* Temporarily disable integration test "try to create a builds deployments with wrong config"
* Adjust `now init` and `now dev` to not require a login token
These two commands should not require a login token because
they do not interact with the Now API.
* Remove `config` from `subcommandsWithoutToken` array
It's not an existing command.
* [now dev] Inherit env vars from `now.json`
Before it was only using env vars defined in the `.env` and `.env.build`
dotenv files.
* Fix secrets validation
Some builders require access to the runtime env vars, i.e. `@now/next`
since it spawns a `next dev` subprocess and should be passing the
runtime env vars to that.
Before it was only respecting the status code for 301, 302 and 303
status codes. Now it handles any status code defined in the routes
config.
Fixes#2294.
* [now dev] Show build logs if a build fails during bootup
Before, the logs were never shown because `buildProcess` does not emit
an `error` event when the child process exits.
Also updates `ora` to the latest version.
* Remove `@types/ora`
`ora` includes its own TypeScript definitions now.
Which includes this fix: https://github.com/zeit/pkg/issues/671
Relevant to `now dev` invoking `yarn` when a package includes
a postinstall script that invokes `node`.
* [now dev] Install builders with `yarn` instead of `npm`
Also invokes via `process.execPath` so that the pkg'd node is used
instead of a global one.
Depends on #2270.
* Install `yarn` to the builder cache dir
Not the `node_modules/.bin` dir, because `yarn` cleans up that directory
when installing modules, so it deletes itself.
* Remove unnecessary unit test
* Always install `yarn`
* Pass in the `yarnPath` to `installBuilders()`
* Restore unit test
* Remove unused `delimiter` import
Co-Authored-By: TooTallNate <n@n8.io>
This is important for builders like `@now/next` and `@now/static-build`
which launch a child process dev server, and we want those logs to be
visible from the `now dev` console output.
* Do not report env errors to Sentry
* Added guide for missing env file in dev mode
* Update errors/missing-env-file.md
Co-Authored-By: leo <mindrun@icloud.com>
* Update errors/missing-env-file.md
Co-Authored-By: leo <mindrun@icloud.com>
* [now dev] Refactor builders installation logic
- Don't run `npm update`, only `npm install`, so no more "Checking for
builder updates".
- Don't save `package-lock.json`, to allow builders with newer versions
than already installed to be updated.
- Properly supports non-npm-registry builders (i.e. an HTTP URL,
`github:` syntax, etc.
* Use `Object.entries()`
- Have the builder exit if a rejection occurs
- Respawn the builder upon next rebuild after the builder has exited
- Log when builder is starting and completed with build time
- Render build error in the HTTP response
This forces all the files to be served as static assets using
`@now/static`, rather than having a special branch that dishes
out to `serve-static`. This is better because it keeps the logic
consistent with when a `now.json` is supplied vs. when it is not,
and allows the code to be simplified by removing checks for if
`getNowJson()` returned anything (previously it could return `null`,
but now that is not the case). Also allows us to remove the now-unused
`serveProjectAsStatic()` function.
* [now dev] Force `@now/static` to run in-memory
The logic for `@now/static` builder is bundled into the `pkg` binary,
and thus is not requireable, so it must instead be run in-memory.
* Also check for stdout TTY before doing the erase lines stuff
* Update `@zeit/fun` to v0.7.0
* Remove `builderCachePromise`
No longer used.
* Remove `intercept-stdout`
* WIP invoke the builder in a forked child process
* WIP Add `builder.js` file
* Remove `BuildResultV1 | BuildResultV2` distinction
Prefer normalizing the `build()` function result to `BuildResult` v2
shape so that we don't have to cast everywhere else.
* Apply build env vars to builder child process
* Copy the `builder.js` file from the pkg filesystem snapshot to the builder cache dir
* Map `FileFsRef` and `FileBlob` of the builder's output back into instances
* Fix `@now/next` :/
* Cleanup
* Print number of initial builds
* Add spinner for building process
* Refine logs
* Support none-tty
* Crop long lines
* Clean up imports
* Refine logs wording
The `entrypoint` should always be watched, since we know that it was used
to produce the build output. This is for builders that don't implement
a fully featured `watch` return value.
* [now dev] Don't include a file in both `filesChanged` and `filesRemoved` list
This makes it so that if a file is added to the "changed" array, then it
is also removed from the "deleted" array, and vice-versa.
* Only render the "files changed/remove" debug log if there are entries
This will be necessary for `@now/static-build` since it needs to watch
all files in the dir containing the entrypoint. For example:
```
watch: [ path.join(path.dirname(entrypoint), '**/*') ]
```
The file watcher logic expects that there is no `'./'` prefix on the
watched file paths/patterns, but `path.dirname('foo')` returns `'.'`
which turns into `'./foo'` with `path.join()`. So this allows those
file paths to be returned from the builder and `now dev` normalizes the
paths after the build has completed.
The dev server `cwd` is not correct working path of a build match, so
pass in the correct one. This property will be used by
`@now/static-build`'s dev mode.
* [now dev] Remove `requiresInitialBuild` and make `shouldServe()` optional for v2 Builders
`@now/next` will be removing `shouldServe()` in favor of returning
a `routes` config array upon bootup. This makes now dev's
`shouldServe()` wrapper function support matching a `routes` config
entry when `shouldServe()` is not defined.
* Remove `console.error()` debugging calls
* Remove `mergeRoutes()` logic
This was incorrect behavior, and more like what `continue: true` is
supposed to do.
* Remove invalid test case
* Remove from the `files` array when ENOENT occurs in file watcher
* Prettier
* Pass workPath to builder.shouldServe() (#2211)
* [now dev] Resolve built routes after matching builder
This removes the `combineRoutes()` function since it was problematic and
triggered rebuilds upon every HTTP request, which is not necessary and
makes development slower.
Now, when an HTTP request comes in, the `now.json` routes are resolved
first, and then the matched build is checked if it defines any `routes`
in the build output. If it does, and a matching route is found then the
route is handled accordingly.
* Fix dev router unit tests
* Only try to match build routes if `.length > 0`
* Remove `routes` config from `@now/static` build results
This would cause an infinite loop of resolving `entrypoint` to
`entrypoint`, and is not necessary for this builder.
* [now dev] Reuse the same `workPath` for subsequent builds
Reusing the same `workPath` for subsequent builds makes rebuilding
faster, as well as it's necessary for webpack's watcher to work
correctly as it relies on the full filesystem paths being intact.
`prepareCache()` also no longer needs to be invoked, since the
previous `workPath` directory will already contain the necessary files
that the cache would otherwise produce.
* Prettier
* [now dev] Don't trigger a rebuild if an asset was deleted
This handles the case where an asset was deleted and should no longer be
served after a filesystem watcher event. For example, if a Next.js page
was previously built and the files was deleted from the `pages`
directory, then the rebuild should not happen since it will fail in the
`build()` function anyways.
* Add `config` to `shouldServe()`
* Remove unused `builder` var
* Show a upgrade message if the build limit is exceeded
* Typo
* Update src/commands/deploy/latest.js
Co-Authored-By: AndyBitz <AndyBitz@users.noreply.github.com>
Editors like `vim` like to use temporary files in the file's working
directory and quickly rename / delete them. This makes `now dev` handle
that gracefully and not crash.
This matches the behavior in production, so it is more correct.
This new common `getMimeType()` function also centralizes a place where
we can overwrite the `mime-types` return value to other values to match
production for other future discrepancies.
* [now dev] Add `nsfw` file watcher
WIP for triggering background rebuilds. So far the `files` mapping is
now kept in sync via the events produced by `nsfw`.
* Add `now.json` caching and invalidation from nsfw events
* Add initial rebuilding logic from filesystem watching
* Remove previously built assets when a rebuild occurs
* Make `@now/static` not require a hard refresh
* Shut down the `nsfw` instance when stopping the DevServer
* Prettier and some minor tweaks
* Ship module
* Support private deps
* Fixed tests
* Fixed integration tests
* Revert "Support private deps"
This reverts commit 0b4991b87641d693fa61f81223e0efc2b7006f83.
* Support multiple platforms
* Typed
* Consider Alpine
* Bumped @zeit/nsfw to latest version
* Update src/commands/dev/lib/nsfw-module.ts
Co-Authored-By: leo <mindrun@icloud.com>
* Pass module path differently
* Bumped package
* Make binary executable
* Wait until piping is complete
* Added debug statements
If you run `yarn build-dev`, then now source maps are enabled, allowing
us to see the proper line of an error in the source code file instead of
the huge `dist/index.js` file.
Previously they were only enabled for production builds.
* Handle additional errors when issuing a certificate
* Rename errors
* Provide more context in CertsDNSError
* Fix CertsDNSError structure
* Display cns with join
* Fix CertsDNSError
* WIP refactor to Now Builders v2 API
* More WIP
* Finish up refactor
* Remove `BuiltAsset` type
These properties are on the the `BuildMatch` interface now.
* Fix `handle: filesystem` route post-refactor
* Prettier
* Update src/commands/dev/lib/builder-cache.ts
Co-Authored-By: leo <mindrun@icloud.com>
- Get `.ts` files covered 🎉
- Update eslint related dependencies
- Add typescript-eslint [recommended rules](3e26ab684a/packages/eslint-plugin/src/configs/recommended.json), but only enabled ones we already followed, commented ones causing errors.
Commented rules including:
```yaml
# '@typescript-eslint/no-unused-vars': 1
# '@typescript-eslint/indent': ['error', 2]
# '@typescript-eslint/array-type': error
# '@typescript-eslint/ban-types': error
# '@typescript-eslint/explicit-member-accessibility': error
# '@typescript-eslint/member-delimiter-style': error
# '@typescript-eslint/no-angle-bracket-type-assertion': error
# '@typescript-eslint/no-explicit-any': warn
# '@typescript-eslint/no-object-literal-type-assertion': error
# '@typescript-eslint/no-use-before-define': error
# '@typescript-eslint/no-var-requires': error
# '@typescript-eslint/prefer-interface': error
```
### TODO
Go through these commented rules one by one, enable & fix for it or confirm it's disabled. Since enabling some rules would cause massive code change (like `'@typescript-eslint/indent': ['error', 2]`), which might conflict with our ongoing development, we better do this in separated PRs.
* Revert "Stop indicating whether CDN is enabled (#2132)"
This reverts commit 3dda3e84bf.
* Add a note about the CDN always being enabled
* Removed useless flag
* Added correct table heading
This is the same de-duping logic that occurs when you hard refresh,
but the unbuilt case was still not being considered. This fixes clicking
on an unbuilt link more than once from triggering multiple builds of the
same asset.
* [now dev] Run `prepareCache()` asynchronous
And also wait a few seconds before running the actual logic,
since the `prepareCache()` function may be computationally expensive,
and its run in the same process as `now dev` (for now), so allow
some time for the current HTTP request to complete.
* Add symlinks support to `glob()`, instrument prepareCache time
If a builder defines the `prepareCache()` function, then it gets invoked
after `build()` has completed to set up the initial build state of the
next build for this same asset.
For example, the goal for `@now/node` if the package.json has not
changed is to have yarn produce the "Already up-to-date" message on the
next build, because installing dependencies ends up taking a long time
on bigger projects.
This is more inline with how a fresh Now deployment works, where
is has to download fresh files each time. This will also fix the issue
with `@now/next` that deleted the `.next` output dir and deleting static
files upon subsequent builds.
This is still a bit unoptimized because `prepareCache()` from the
builder is not yet being invoked, but it's still more correct than
reusing the `workPath`.
Because `now dev` uses these dotenv files to define the Now secrets to
use, it would be bad practice to include them in the deployment files
since they will be using development values instead of production values.
* [now dev] Clean up `dev-router` a bit
This is a follow up to #2095 to move the `resolveRouteParameters()`
funcrtion to the top-level and other slight optimizations like not
re-parsing the URL multiple times.
* Remove unused `qs` import
This test is very flaky causing us to constantly restart CircleCI jobs
in order to do releases of `now-cli`. Considering that it's testing the
1.0 pipeline, let's just remove this one to make life easier.
This passes in the resolved `assetKey` instead of `req.url` to the
builder `requestPath` when a hard-refresh is requested, allowing the
proper single-page rebuild to happen.
* [now dev] Fix subscription resolving logic
Strip the leading `/` since the builder outputs don't have one, match
index routes, and pass the resulting subscription key to the builder.
* Fix `index` matching
* Update `@now/build-utils` to v0.4.39-canary.0
* Update `@now/build-utils` to v0.4.39
In the case of a keep-alive connection from the web browser, and a page
continuing to send HTTP requests to the dev server, sometimes the server
never shuts down. So send a 404 response with `Connection: close` to
force the web browser to close the connection.
If the builder has a `subscribe()` function, then the initial
builds are not run and instead an array of "subscriptions" is
created. When an HTTP request comes in that matches one of the
subscription patterns, then this builder will be actually be
executed.
This introduces a new object called `meta` that gets passed to the
Now Builders' `build()` function. The `isDev` property is moved to
this object, and a new property `requestPath` is also introduced.
`requestPath` represents the URL that was requested to trigger the
`build()` to be called. It may be used by builders to do incremental
compilation and only re-build the assets related to the URL that was
requested. For example, `@now/next` may use this property to only build
the page that was requested.
For `now dev`, this fixes an edge case in named capture groups
in some `routes` definitions that would lead to an error being thrown:
```
Cannot read property '1' of null
```
Also ignoring "handler" routes for now.
* Group builds with similar paths together to reduce the output
* Style the new output
* Ensure space between state and time
* Update src/util/output/builds.js
Co-Authored-By: AndyBitz <AndyBitz@users.noreply.github.com>
* Add comma between ready states
* Tell what is hidden
* Change builds and items
* [now dev] Add support for `.env` file to define Now secrets
If a `now.json` files relies on secret env vars, then they must be
defined in the user's local `.env` file otherwise `now dev` exits with
an error.
* Prettier
* Fix multi-line error output
* Use `code()` to format the dotenv file name
* Add "file" to error message for clarity
* Use `hasOwnProperty()` instead of `in`
* Apply `build.env` vars during builder `build()` invocations
Fixes#2046.
Consider the scenario where an HTML asset is built and references other
files that were produced by the build (CSS/JS/img/etc. files). The build
will happen and then the HTML page will be served, and then the browser
will request the assets on the page also with the `no-cache` header,
which would cause a second build right after the first one completed,
which is bad DX and unnecessary.
This commit introduces "build deduping logic" so that this scenario is
avoided by doing two things:
1. Not allowing the same entrypoint to be built at the same time (so if
a concurrent request happens for an asset that was produced by the same
entrypoint, the subsequent requests will wait on the already running build
instead of triggering a new one in parallel.
2. Not allowing an asset to be rebuilt if the previous build completed
less than two seconds ago. This is to catch the scenario where the
HTML page is served and the browser quickly requests the assets on
the page to avoid triggering a second rebuild.
* [now dev] Set the Now proxy and response headers
* Add `X-Real-IP` proxy header
* Set any headers defined in the matched `route` config
* Apply @amio's suggestions
This is mostly to appease TypeScript since `fn` is an optional prop,
but this shouldn't really ever happen since we run the builds before
responding to HTTP requests.
This matches how the Now proxy invokes the lambdas, where the route
`dest` query params are mixed-in to the provided `req.url`, with the
dest query params taking precedence over any conflicting user-provided
query params.
* [now dev] Use `pcre-to-regexp` to match `routes`
The now.json `routes` support PCRE syntax like named captures,
so use the `pcre-to-regexp` module to match the routes.
Fixes#2023.
* Pass the resolved router `dest` and query params to the Lambda
This just DRYs up the code a bit and centralizes the error sending logic
so that we can more easily add the HTML and JSON versions of the
responses as well.
`.gitignore` is not respected anymore for Now v2, so this was a bug.
Also removes `ncc` and `user` from the ignore list, since that issue was
fixed a while back as well.
Fixes#2021.
* [WIP] now-dev
* try invoking lambda
* add error status to dev-server
* add basic routing
* add entry for custom @now/static builder
* honor .gitignore & .nowignore while collecting files
* add route for single static file
* add test fixtures for now-dev (nodejs)
* fix miss typed @now/statics
* import types from @now/build-utils
* fix typo @now/statics -> @now/static
* revamped router
* typescript-eslint-parser -> @typescript-eslint/parser
Eliminate error while running pre-commit hooks:
SUPPORTED TYPESCRIPT VERSIONS: ~3.1.1
YOUR TYPESCRIPT VERSION: 3.2.2
* send files from local @now/static builder
* use serve-handler when no now.json
* remove http-proxy
* add type def for serve-handler
* code cleanup
* move type declarations to types.ts
* dont rely on `this.cwd` while running builder
* more type definitions
* fix invoking error
* clean code
* better debug logging
* refined request handler logic
* handle /favicon.ico with serve-handler
* make builder-cache self contained
* move builder works to dev-builder.ts
* add proxy_pass handler
* support named groups in routes
* fix creating cache dir error
* add "--nodejs-preview" solely for nodejs
* clean require.cache after required user js
* fix router & header issue in nodejs preview
* [wip] add tests for dev-router
* add tests for dev-router
* lookup "/index.*" for indexes
* refine logging
* [WIP] `now dev` progress point
Actually invoking the `@zeit/fun` module at this point.
Still lots of work to be done…
* Update `@zeit/fun` to v0.0.4
* Remove `--nodejs-preview`
To be replaced by `@zeit/fun`.
* Remove `decache` and `import-fresh`
Leftover from the `--nodejs-preview`.
* Remove "declaration: true" from `tsconfig.json`
Otherwise the ncc `dist` dir ends up full of generated `.d.ts` files.
* Remove `ignore` dep, always use `@zeit/dockerignore`
* Use tarball URL for `@zeit/fun`
Because `@zeit/fun` is not yet public on npm.
* Regenerate `yarn.lock` to fix bad integrity check on fun tarball
* Upgrade to `@zeit/fun` v0.0.6
With re-written unzipping logic utilizing `yauzl`.
* Add lambda function handling logic for the HTTP response
* Match the lambda invoke shape that Now's proxy provides
* Move deps to devDependencies
* Update `@zeit/fun` to v0.0.8
* Update `@zeit/ncc` to v0.15.0
* Attempt to fix unit test for `wait()` helper function
* Add `build.sh` script to work around ncc issues
* Fix `build.sh` script for BSD's chmod
No `--changes` flag.
* Update `@zeit/fun` to v0.0.11
* Update `@zeit/fun` to v0.0.12
* Tweak some comments
* Update `@zeit/fun` to v0.0.13
* Add `now.json` env vars to lambda functions
* Finish removing `--nodejs-preview` flag
* Style tweaks
* Use `npm-package-arg` to parse the "use" builder
* Styling
* Use the parsed `pathname` when matching routes
The querystring portion needs to be removed to match properly.
* Update `@zeit/fun` to v0.1.1
* Support `-d` for debug flag
It was already listed as such in the `--help` output.
* List the `dist/runtimes` dir as pkg "assets"
* Update `@now/build-utils` to v0.4.37-canary.0
* Update `@zeit/fun` to v0.2.0
* Update `@zeit/fun` to v0.2.1
* Rewrite the `req.url` to fix serving FileFsRef assets
* Disable re-building, build all `builds` upon server bootup
* 404 is not a redirect
* warning on more than one argument
* Fix `index` without a file extension matching
* Update `@zeit/fun` to v0.2.2
* Use `async-listen`
* Add shutdown cleanup logic
* Rename `buildLambdas()` to `executeBuilds()`
* Rename `lambda` prop to `fn`
* Misc tweaks
* Pass `isDev: true` to the builder `build()` function
* Use `Object.assign()` instead of object spread
* Set `res.statusCode` instead of `writeHead()`
* Create Lambda functions during build-time
This way, the lambda instance is re-used for subsequent HTTP requests
* Wait for cleanup operations to complete in `stop()`
* Destructure `path` for join()
* Add some missing types
* Store the `buildConfig` on the assets for reverse lookup
* Remove `console.log()`
* Attempt to make globbing faster and ignore files more accurately
* Rewrite `installBuilders()` to be idempotent
So that npm is not executed for canary tags, for example.
This is done by comparing the contents of the package.json file rather
then the `node_modules` directory.
* Use `ignore` instead of `@zeit/dockerignore` for glob-gitignore
It seems that the object produced by `@zeit/dockerignore` is not
compatible with the `glob-gitignore` module, so use the vanilla
`ignore` module instead for now as a workaround.
* Implement a `GlobIgnore` class to replace `glob-gitignore`
This allows us to continue using `@zeit/dockerignore` for proper
consistency.
Closes#1899.
* Prettier
* Skip installing built-in builders (i.e. `@now/static`)
* Remove `console.error()` calls
* Use a deterministic `workPath` directory
So that the same one is re-used in-between subsequent boots of `now dev`
* Add `now.json` validation logic
* Fix serving static assets outside the project working directory
This fixes, for example, `@now/mdx-deck` which outputs static files
from its build process.
* Add comment
* Validate the `now.json` file before launching the dev server
* Respect `maxLambdaSize` config
Closes#1950.
* Add `@types/bytes` dependency
* Make `maxLambdaSize` be optional
Co-Authored-By: TooTallNate <n@n8.io>
* WIP force reload in browser = rebuild asset behavior
* Resolve the `asset` again after re-build
* Remove logging
* Update `@zeit/fun` to v0.3.0
* Update `@now/build-utils` to v0.4.37-canary.1
Sets `npm_config_target` to the proper Node.js version for native
modules.
* Update `@zeit/fun` to v0.3.1
* Fix "hard refresh to reload" after the first rebuild
The `buildConfig` and `buildEntry` proper were not being set on the
rebuilt assets, causing the rebuild to only work the first time.
Now fixed.
* Add logic for the `now dev cache clean` command (#1977)
* Added the cache-clean command
* censer code :)
* Fix non-route match `dest` param
This makes the `go-image-to-ascii` work, since the query param URL gets
properly routed to the `/` route.
* Add support for `FileBlob` outputs
Fixes `@now/optipng`, `@now/html-minifier` and `@now/md` builders.
* Remove `console.error()` call
* Add `now dev cache clean` command
* Use the `assetKey` to look up the Content-Type on FileBlobs
Instead of the `fsPath` of the entrypoint file.
This fixes `@now/md` to return `text/html` Content-Type instead of
`text/markdown` which does not render properly in the web browser.
* Update `@zeit/ncc` to v0.16.1
Co-Authored-By: TooTallNate <n@n8.io>
* Regenerate `yarn.lock` file
* Remove leading `/` on build `src` specifications
* Use `rsync` to copy over all of `fun`'s runtime files
* Update `@zeit/fun` to v0.5.0
* Update `@zeit/fun` to v0.5.1
* try/catch the lambda invoke and send 500 upon error
* Add `rsync` to CircleCI build
* Convert `errors.js` to TypeScript to fix compilation errors
* Also accept `Cache-Control: no-cache` for rebuilding
* Prettier
* Update `@now/build-utils` to v0.4.38-canary.1
* Update `@zeit/ncc` to v0.17.0 (#2017)
* Install `@zeit/fun` from npm
* Remove `console.error()` call
Co-Authored-By: TooTallNate <n@n8.io>
* Create `NowError` subclasses
* Add `LambdaSizeExceededError`
* Return early if there's no builds
* Fixed `GET /v3/now/certs`
- Limit the response size to 20 because the endpoint doesn't have a default limit
- If the id in `/v3/now/certs/{id}` isn't a valid id the endpoint responds with a set or certs instead
- The route `/v3/now/certs/{idOrCn}` isn't supported any more
* removed limit of 20, the endpoint was updated
Before this change, only if `user` or `team` could be read from
the scope would stdarg be reported to Sentry, however it's
completely unrelated to the existence of the former and is always
useful debugging information.
* Add support for the target flag
* Show the given alias at the end
* Use the proper naming for the alias properies and include arrays
* Use the correct output
* Make sure that aliasFinal has properties
* Add support for the target flag
* Show the given alias at the end
* Use the proper naming for the alias properies and include arrays
* Use the correct output
* Make sure that aliasFinal has properties
* Added basics for new --scope flag
* Fixed usage information
* Fixed integration test
* Fixed usage information about whoami
* Brought back missing whitespace
* Do not push scope property to API
* Ensure we're only reading local config in one place
* Fixed build
* Added test
* Made scope from config work
* Correctly handle error
* Handle Now errors too when loading local config
* Removed NowError
* Revert "Removed NowError"
This reverts commit cfeebc65251d3eb07f9aeb3e548af1d23c00a18e.
* Fixed CI
* Fixed final bug
* Do not consider switch command
* Made it work as expected
* Added test
* Added yet another test for the scope property
* Added space
* fix unexpected `payment_error`
* fix unexpected `deployment_not_found`
* fix unexpected `not_authorized` and `team_deleted`
* make id optional in DeploymentNotFound
* Display transfer renewal price for domain transfers
* Check domain transferable status immediately on transfer-in
* Transfer status endpoint change to .../registry
* spelling fix
* Enable transferable check
* Update dependencies
* Added default script that will run if now fails to install
* Don't overwrite the default now script before publishing
* Copy the default now binary on publish instead of keeping it inside the dist folder
* Removed download/dist/now
* Changed text
* Send project property to api-deployments.
* Allow to talk to local api-deployments temporarly.
* Introduce the getProjectName utility.
* Use getProjectName on both legacy and latest deploy commands.
* Add now projects ls support.
* Implement 'now project add' and 'now project rm'
* Show project id
* Add basic now ls support with projects.
* Add some cosmetics changes.
* Make the UI colorful.
* Set the name as project
* Notify the user about the project name
* Remove legacy list
* Make sure 'now projects xxx' possible
* Set the project name in the list header
* Remove unwanted package
* Use --project in tests
* Force --project instead of --name
* Force the use of project property inside now.json
* Update ncc to the latest
* Remove -w from ncc
* Deprecate --name and .name instead of throwing errors
* Use the built-in fetch client
* Fix tests
* Change the order of tests
* Reset integration tests
* Remove some debug logs
* Bumped `@zeit/ncc` to latest
* Reverted lockfile
* Make linking build for dev
* Cover line 21 in util/config/local-path.js
* Heavily improved unit test coverage
* Fixed space
* Got to 90% coverage
* Removed useless code
* Made builds work
* Fixed a few lines
* Fully covered read-metadata.js
* Brought coverage to 95.38
* Removed code that was never executed
* Track everything
* Don't show badge for now
* Add now-init
* fix ci error
* refactor: (now-init) js => ts, some improvements.
- now-init works like git-clone
(create new directory / complain about overwritten / can be forced)
- Better guess user intention
(use jaro-winkler algorithm with "-" awareness)
- Stricter on arguments
- Non-TTY frendly
* add now-init to main help message
* fix miss typed args in didYouMean
* clean console.log
* output a new-line after any response to promptBool
Fix the missing '\n' when promptBool get an negative input ("n"/"N"/Enter/Abort).
Before:
~/git » now init koa
> Did you mean nodejs-koa? [y|N] > No changes made.
After:
~/git » now init koa
> Did you mean nodejs-koa? [y|N]
> No changes made.
* refine now-init output messages
* prettier code format
* update tests for now-init
* put "init" before "help" in now-help message
* remove redundant semicolon
* More flexible response error
* Consider async domain purchases
* Jumpline for domains ls
* Jumpline in domains verify
* Remove not needed body performing verification
* Add orderedAt to domains inspect
If a domain is not found the DNS record arrays are aligned
incorrectly and finally some records are shown under wrong domains.
It happens because the length of the domains array differs from the
length of array of record arrays.
* Migrate getDomainDNSRecords to Typescript
* Migrate getDNSRecords to Typescript and fix it
* Migrate cert functions to Typescript and fix issues
* Migrate certs issue to Typescript
* Minor fixes
* Removed legacy dependencies
* Added @zeit/git-hooks
* Added scripts to run before commit
* Format only the modified files
* Revert "Format only the modified files"
This reverts commit 9f4a58d2b978fa286eb7fcf38186bd9d53a2cda1.
* Revert "Added scripts to run before commit"
This reverts commit 07636d945374e404161ad281feed4180801b3509.
* Revert "Added @zeit/git-hooks"
This reverts commit 3f44f401f36fa6965d36ef28b81907c137c08abc.
* Revert "Removed legacy dependencies"
This reverts commit bb02465c59d75bf6b32bd449a04832cf4e2f4bf4.
* Fixed setup
* Print important test parts
* Logged kind
* Added more logs
* No need to remove deployments, we will prune
* Update `now alias` error to mention potentially missing name config
Running `now alias` in a project that has no `package.json` and doesn't
have a `name` property defined in `now.json` fails with a cryptic
error currently. This, in combination with
https://github.com/zeit/docs/pull/378 tries to better guide the user.
* Add a link to the `name` config property
* Handle EPERM errors when creating config files
* Catch errors when retrieving scope
* Added validation for the API URL
* Removed useless whitespace
* Removed useless file
* Cleaned up `setRawMode` mess
* Removed tests that are erroring on non-TTY
* Set environment based on release channel
* Fixed syntax
* Configure releases and environment for Sentry
* Correctly send development errors away
* Report Sentry errors with metadata
* Report username and full name of user too
* Better release name
* Bumped `@zeit/ncc` to latest version
* Do not report user errors
* Do not report mistyped arguments to Sentry
* Do not report when user aborts action
* Removed all occurances of user errors
* Do not report arg errors
* Correctly report teams and billing errors
* Prevent `setRawMode` from causing an error
* Do not report errors while developing
* Revert "Prevent `setRawMode` from causing an error"
This reverts commit 323296f30bfcca70ea5bb736db98357212f86a0a.
* Fixed whitespace
* Added code coverage report
* Correctly include everything
* Ignored useless stuff
* Combine all the coverages
* Corrected requiring
* Persist only what is needed
* Send errors away for inspection
* Allow Sentry to send them away
* Fixed dependency
* Fix credit card input
* Do not test for something that requires TTY
* Track properly
* Make it extra safe
* Added back test
* Added tests for `-V` option
* Pushed for testing
* Correctly set it
* Revert "Correctly set it"
This reverts commit c76286082d90f091ecec4a317856e91b4558e781.
* Create a new deployment each time
Made `--build-env`, `--meta` and `--dotenv` work for v1
* Locked multi static file test to v1
* Correct fix
* Final fix
* Config also adds to count
* Fixed single file test
* legacy => old
* Correctly set it
* Removed external providers
* Renamed sh provider
* Removed serverless stuff
* Fixed paths
* Properly pass token
* Fixed paths
* Check for token correctly
* Remove useless properties
* Fixed unit tests
* Keep certain things
* Adjusted remaining parts
* Fixed login
* Remove user properties that are not needed
* Store `platformVersion` for teams
* Store `platformVersion` for users
* Delete team order when logging out
* Made team commands work with tiny config
* Load data dynamically
* Made billing command show correct context
* Fixed remaining occurences of context name
* Fixed remaining pieces
* Test CI
* Clean strings when testing
* Better error check
* Render correct information when asking for credit card
* Migrate from objects to strings
* Better migration message and keep tips
* Remove the old property
* Use note for migration message
* Don't show spinner for loading missing data
* Allow for current team or user to be deleted
* Two deploy files
* Consume context name correctly
* Removed deployment types from new deployer
* Also check for bigger than 1
* Better file names
* Added upgrade message for legacy deployer
* Make help work when logged out
* Error if sub command doesn't exist when requesting help
* Fixed wording
* Support for version property added
* Better handling
* Removed useless props from deploy help
* Don't show version warnings when rendering help
* Fixed wording in readme
* Migrate even if in the middleground
* Make `now whoami` work
* Deprecated support for deploying Git repo in latest deployer
* Added usage information
* Load config separately
* Don't need local config on root
* Correct status code for help test
* Show error only in correct case
* Properly error if path does not exist
* Fixed types
* Fixed remaining occurances of old config
* Don't show warning when rendering help
* Consider version when outputting help
* Only error if path does not exist if it's not help
* Remove testing logging
* Don't error for no-verify
* Stop logging
* Fixed last test
* Added missing semicolons
* Fix indent
* Fix indent again
* Ran prettier over everything
* Added missing types
* Brought test hashes back to normal
* Exit properly when deploying
* Show clipboard note in gray and remove Node.js version
* Completed usage information
* Ensure `now whoami` only outputs the user
* Don not save user data to config
* Removed last traces of `user` and `.api` and `--team` work
* Made `now upgrade` and `now downgrade` correctly render context
* Fixed upgrade/downgrade URL for teams
* Ability to load required data
* Better file name
* Corrected check for current scope
* Don't render version warning when showing help
* Keep polling for handlers
* Render handlers
* Removed useless file
* Much better transpilation setup
* Sweetened logging
* Shortened time it takes to render ready
* Support for error ready states
* Make sure table is not wobbling
* Show times for every handler
* Attach env and build env
* Don't pass useless stuff
* Re-structured pipeline
* Allow empty config
* Do not support package.json config for new pipeline
* Removed occurances of AWS
* Drop useless packages
* Removed useless file
* Ensure the legacy pipeline is working
* Test staging proxy with legacy pipeline
* Adjust test
* Stop testing staging proxy
* Allow for anything
* Pass `handlers` and `routes` to creation endpoint
* Fixed tests
* Revert "Fixed tests"
This reverts commit e0d18a61b9520728089cb2f9e6877c1b91016312.
* Running tests should not be optional
* Support for `-m` and `--meta` added
* Support reading `meta` in local config
* Allow reading `name` from local config
* The `public` prop in local config should be considered
* Handlers deployments should use `.nowignore` and nothing else
* Allow handlers deployments without `handlers` and `routes` in the config
* Locked legacy tests to legacy platform version
* Support aliasing handlers deployments
* Removed useless condition
* Don't allow scaling handlers deployments
* Don't show warning message when deploying single file
* Fixed tests
* Made `now inspect` work
* No type for handlers deployments in list
* Indicate whether a deployment is legacy in `now inspect`
* Made `--force` work for handlers deployments
* Do not document `--dotenv` for handlers (not supported)
* Do not strip `hdl_` from handler IDs
* Fixed for upgrading to latest platform
* Better error for when `version` property is missing
* Render platform version while deploying
* Strip `hdl_` from handler IDs
This reverts commit 750d38ba9074bdc3e63ad2dab8538e51dbba5f03.
* Removed `https://` from handler list
* Removed demo mock
* Cleaner errors
* Make times and erroring work properly
* Print final deployment error
* Removed useless promise
* Prettified code
* Put config utils into correct location
* Moved even more config files
* Removed useless directory
* Removed last useless file
* Fixed wrong paths
* Fixed unit tests
* Update deployment according to handler state, like the server-side loop
* More robust deployment mechanism
* Poll every 1.5 seconds
* Prevent many requests
* Show spinner while waiting for deployment to be ready
* Render how long the deployment took
* Avoid unnecessary repainting
* Automatically remove useless `user` property from config when migrating
* Fixed property names in `now inspect`
* Render platform version for legacy pipeline
* Shortened error messages
* Support `regions` in the local config
* Support for `--regions` added
* Add metadata support for legacy deployments (#2)
* Share handlers table between deploying and inspecting
* Make `now inspect` work nicely
* Renamed handlers to builds
* Stop sending away description
* Bare UI support for builds
* Simper logic for rendering builds
* Render output of builds
* Indicate lambdas in a better way
* Render size for build output
* Do not show type for version 2 deployments
* Fixed time output for `now inspect`
* Don't handle BUILDS type
* Allow for 100% non-config deployments
* Add metadata support for now ls (#3)
* Add metadata support for now ls
So, we can do things like this:
now ls -m key1=value1 -m key2=value2
* Better description
* Fix wording
* Added final newline
* Add sentry (#4)
* Revert "Add sentry (#4)"
This reverts commit 851d1bdb0e1bbc8f329a45388865b2c41395d8c2.
* Only render build output if it was not copied
* Made `now alias` work with latest staging proxy
* Revert "Made `now alias` work with latest staging proxy"
This reverts commit 16e8998435ef03c50d2737f3ef17fa5c0c2dd33f.
* Bumped deployments API to the latest version
* Made `now rm` work
* Do not print `version` warning for single files
* Removed useless `fs-extra` dependency
* Removed useless dependencies
* Default binaries to Node 10
* Bumped Node.js in Circle CI to latest
* Bumped Xcode to get latest Node.js for integration tests
* Enabled HTTP/2 support
* Removed useless code
* Added integration test for builds
* Bumped `fetch-h2` to the latest version
* Avoid performing network request for rendering help
* Render note when viewing latest help
* Return status code `2` when exiting with help
* Fixed test for usage information
* Removed wrong text in usage info for Now 2.0
* Removed support for `--links` from v2 pipeline
* migrated => upgraded
* Added default routing for single files
* Make `--token` work as expected
* Better message for build errors
* Prevent update notification
* Prevent update notifications from showing
* Only show migration message in debug output
* Prevent flickering of state
* Improved output
* Removed useless assignment
* Corrected padding
* Less padding before state
* Corrected links for global configuration
* Fixed integration tests
* Render region for Lambdas
* Join regions in a better way
* Ensure `now.json` and `.nowignore` (the latter worked anyways) are uploaded
* Fix `build.env` in new deployment API call (#6)
* JSON log the deployment body when debugging (#8)
Otherwise it's just `[object Object]` which is useless.
* Retry to fetch on error on follow mode (#5)
* retry fetch on error on follow mode
* improve logging
* Fixed `--env` and `--build-env` CLI args (#7)
* Fix `--env` and `--build-env` CLI args
* Fall back to `undefined`
* Ensure `now switch` lists active scope in the beginning
* Removed useless code
* Error if `env` or `build.env` have wrong types
* Made `now inspect` look great
* Fixed wrong protocol in URL
* Made `now --team` work with users
* Leave PHP out of integration test for now
* Do not select PHP build
* Fixed integration tests
* Revert "12.0.0-canary.93"
This reverts commit 70a0a594b4.
* Revert "Revert "Add support for top-level "sh" auth""
This reverts commit 4273d62460.
* Revert "12.0.0-canary.92"
This reverts commit 847c71ecf2.
* Revert "Add support for top-level "sh" auth"
This reverts commit c493d651db.
* Revert "12.0.0-canary.91"
This reverts commit 06c954f8fe.
* Revert "Added metadata support for `now inspect` (#1634)"
This reverts commit 9567656b45.
* Revert "12.0.0-canary.90"
This reverts commit 966737be23.
* Revert "Added support for deployment metadata (#1604)"
This reverts commit 6c1188a787.
* Allow to add metadata in the now deploy command.
Use can add multiple items of metadata with:
'-m key1=val1 -m key2=val2'
* Add a test case.
* Update to accept and send metadata as meta.
* Use correct fields in now.create
* Add now ls support.
* Add an integration tests for ls with metadata
* Added newline
* Removed semicolon
`slot` and `limits` are now rendered when it is a Cloud v2 deployment.
Also fixes an issue with static deployments always
rendering `affinity: undefined`.
* Move getDomainNameservers function
* Don't show an error as unexpected if there is a code in the error payload
* Add start and finish cert order functions
* Integrate add wildcard cert for external domains
* Use a different endpoint to get a cert by id
* Add new command to download a certificate
* If there are no pending challenges, try to generate the cert right away
* Remove cert download
* Move DNS table options to an object
* Bugfix: cancel spinner message when finish order fails
* Restore add to work only with cert add
* Refactor obtaining cns
* Add start and finish order commands
```
> Error! An unexpected error occurred in scale: Error: This region (gru1) only accepts Serverless Docker Deployments (400)
```
This is happening because `now-cli` is validating DC names and
expanding "all" locally. However not all DCs have same features but
the client can't be aware of that. Instead of making the client
aware of the differing capabilities of the available DCs we should
pass "all" as a special DC selector, and let the backend handle
scaling properly.
* Have returnify use generators and reinstantiate them upon error
* check for status not_ready instead of 412
* poll every 5s instead of 1s for ready state notification
* poll every 2s for scale verification
* checks it is a npm deployment before reading package.json
* checks if you have a config.type first
* checks if you have a config.type first
* fixed logic for config.type
* Use correct source when listing
* Use correct source when buying domains
* Replaced the rest too
* Make adding work nicely
* Make listing work for all scopes
* Don't require address
* Bumped lockfile
* Removed more useless code
* Renamed file
* Fixed weird zlib error
* Fixed output
* Added some tests
* Add `--build-env` to `now deploy` command
Build env vars are only visible during build-time, compared to
regular env vars which are only exposed during runtime.
This also removes the client-side validation of the deployment
schema, because it makes it difficult to keep the client and server
in sync, especially as new features are added. Instead `now-cli`
should be responsible for knowing how to render the server's error
message in an informative and future-proof way so that we can
update the server and even older clients would show the validation
error properly.
* Remove `only` dependency
* Add `--build-env` CLI flag integration test
* Add more integration tests related to static builds and env
Here we are adding a few more integration tests for static builds and for using env vars in the build step.
* Add build-env related test case.
* Do not allow adding domains with subdomains
* Do not ask for confirmation when the domain exists
* Improve message when the domain is under a different account
* Fix flow errors
* Revamp domains add command
* Remove setting dns records when setting up the domain
* Refactor DNS commands
* Hide fields in system dns records and show creator
* Better formatting for dns ls
* Remove exhaustive check of dns record type
* Remove domain ids from responses in domain commands
* Change all `domains` API references to use `v3`
* Update to domains API v3
* Remove NeedUpgrade error and use CDNNeedsUpgrade where it proceeds
* Update copies when adding domains
* Remove extra blank line
* Fix flow errors
* Change params order in createAlias
* Make setupDomain return domainInfo
* Do not try to get a wildcard cert for alias when domain is external
* Update setup-domain.js
* Revert "12.0.0-canary.51"
This reverts commit 5e17fe5ad6.
* Revert "Update `@zeit/schemas` to v1.6.0"
This reverts commit b216adadc0.
* Revert "Upload the Dockerfile if it's a static deployment. (#1437)"
This reverts commit 5078c95667.
* Revert "Upgrade to webpack 4 and latest Babel (#1436)"
This reverts commit 7612d77647.
* Upload the Dockerfile if it's a static deployment.
This allows us to build the Dockerfile and upload static assets
* Allow to upload package.json as well for static deployments.
* Try to purchase a domain only when there is no other choice
* Allow eventsStream to fail during deployment
* Allow to verify instantiation without events API
* Move domains command to its own folder
* Refactor domains commands
* Add cdn to domain ls
* Add function to patch domains
* Support toggling cdnEnabled
* Better messages
* Add new cdn options to help command in domains
* use push instead of read
* don't auto-clear
* single progress bar that hangs till last chink
* print symmary beofre link
* print smmary faster
* print more discreet timestamps
* fix tests
* fix flow error
* Allow to fallback to passed body parsing a response error
* Extract domain purchase from setup-domain
* Move getCertRequestSettings
* Add create method to Now interface
* Extract print dns table and zeit world table functions
* Add support to generate certificates during deploy
* Point to v5 in deploy endpoint
* Add feedback messages when creating a cert during deployment
* Remove hardcoded references to now.sh
* Dont bump create endpoint version
* Support empty reponses in fetch
* Strip quotes from Dockerfile labels
* remove console.log
* add test
* issue normal cert for nested subdomain (#1344)
* Prefer HTTP challenge for regular certs
* 12.0.0-canary.31
* Update non-existing team test
* 12.0.0-canary.32
* Bumped `update-check` to the latest version (#1354)
* 12.0.0-canary.33
* Strip quotes from Dockerfile labels
* remove console.log
* add test
* Load schema from package
* Send config to deployment endpoint
* Upgraded @zeit/schemas to the latest version
* Removed type for now
* Added config correctly
* Corrected license file name
* Corrected readme name
* Added editorconfig
* Account for npm being down
* Print full error
* Only show full error while debugging
* Initialize polling function from args
* Remove rule of having a mandatory dest field in path alias rules
* Wait 5 seconds after getting the deployment ready
* Ignore errors coming from events stream
* Migrate to arg@2.0.0
* Refactor scale command
* Move alias.js to alias/index.js
* Move alias set to its own file
* Move alias ls to its own file
* Move alias rm to its own file
* Remove old alias and scale files
* Update alias integration test
* Fix scaling to 0
* Read scale params from now.json on deploy
* Move deploy command to its own directory
* Do not show success on downscale message
* Move getDeploymentByIdOrHost to /util/deploy
* Remove unneeded parameter in getAppName
* Better types for copyToClipboard
* Update to babel 7
* Add generator utility functions
* Add function to get deployment events
* Finish getDeploymentEvents after getting one state-change event
* Refactor deploy events and reduce verification timeout
* Reduce verification timeout for scale and alias
* Use output.log for success message in scale
* Fix integration tests
The following page is a reference for how to create a Builder using the available Builder's API.
The following page is a reference for how to create a Runtime using the available Runtime API.
A Builder is an npm module that exposes a `build` function and optionally an `analyze` function and `prepareCache` function.
Official Builders are published to [npmjs.com](https://npmjs.com) as a package and referenced in the `use` property of the `now.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 Builder.
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 `now.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.
See the [Builders Documentation](https://zeit.co/docs/v2/advanced/builders) to view example usage.
See the [Runtimes Documentation](https://zeit.co/docs/runtimes) to view example usage.
## Builder Exports
## Runtime Exports
### `version`
A **required** exported constant that decides which version of the Builder API to use.
A **required** exported constant that decides which version of the Runtime API to use.
A **required** exported function that returns a [Files](#files) data structure that contains the Build outputs, which can be a [Static File](#file) or a [Serverless Function](#serverless-function).
A **required** exported function that returns a [Serverless Function](#serverless-function).
What's a Serverless Function? Read about [Serverless Function concepts](https://zeit.co/docs/v2/deployments/concepts/lambdas) to learn more.
An **optional** exported function that is only used by `now dev` in [Now CLI](https:///download) and indicates whether a [Builder](https://zeit.co/docs/v2/advanced/builders) wants to be responsible for building a certain request path.
An **optional** exported function that is only used by `now dev` in [Now CLI](https:///download) and indicates whether a [Runtime](https://zeit.co/docs/v2/advanced/runtimes) wants to be responsible for building a certain request path.
If this method is not defined, Now CLI will default to [this function](https://github.com/zeit/now/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
### Builder Options
### Runtime Options
The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCache`](#preparecache) receive one argument with the following properties.
@@ -145,78 +145,15 @@ The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCa
- `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 `now.json`.
## Example: html-minifier
## Examples
Let's walk through what it takes to create a simple builder that takes in a HTML source file and yields a minified HTML static file as its build output.
While this is a very simple builder, the approach demonstrated here can be used to return anything: one or more static files and/or one or more lambdas.
## Setting up the module
### Defining the analyze step
The `analyze` hook is optional. Its goal is to give the developer a tool to avoid wasting time _re-computing a build_ that has already occurred.
The return value of `analyze` is a _fingerprint_: a simple string that uniquely identifies the build process.
If `analyze` is not specified, its behavior is to use as the fingerprint the combined checksums of **all the files in the same directory level as the entrypoint**. This is a default that errs on making sure that we re-execute builds when files _other than the entrypoint_ (like dependencies, manifest files, etc) have changed.
For our `html-minify` example, we know that HTML files don't have dependencies. Therefore, our analyze step can just return the `digest` of the entrypoint.
This means that we will only re-minify and re-create the build output _only if the file contents (and therefore its digest) change._
### Defining the build step
Your module will need some utilities to manipulate the data structures we pass you, create new ones and alter the filesystem.
To that end, we expose our API as part of a `@now/build-utils` package. This package is always loaded on your behalf, so make sure it's only included as `peerDependencies` in your `package.json`.
Builders can include dependencies of their liking:
const { data } = await FileBlob.fromStream({ stream })
const content = data.toString()
const minified = htmlMinifier(content, options)
const result = new FileBlob({ data: minified })
return {
output: {
[entrypoint]: result
},
watch: [],
routes: {}
}
}
```
### Defining a `prepareCache` step
If our builder had performed work that could be re-used in the next build invocation, we could define a `prepareCache` step.
In this case, there are not intermediate artifacts that we can cache, and our `analyze` step already takes care of caching the full output based on the fingerprint of the input.
Check out our [Node.js Runtime](https://github.com/zeit/now/tree/master/packages/now-node), [Go Runtime](https://github.com/zeit/now/tree/master/packages/now-go), [Python Runtime](https://github.com/zeit/now/tree/master/packages/now-python) or [Ruby Runtime](https://github.com/zeit/now/tree/master/packages/now-ruby) for examples of how to build one.
## Technical Details
### Execution Context
A [Serverless Function](https://zeit.co/docs/v2/advanced/concepts/lambdas) is created where the builder 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.
A [Serverless Function](https://zeit.co/docs/v2/advanced/concepts/lambdas) 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.
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.
@@ -228,23 +165,23 @@ When a new build is created, we pre-populate the `workPath` supplied to `analyze
The `analyze` step can modify that directory, and it will not be re-created when it's supplied to `build` and `prepareCache`.
To learn how the cache key is computed and invalidated, refer to the [overview](https://zeit.co/docs/v2/advanced/builders#technical-details).
To learn how the cache key is computed and invalidated, refer to the [overview](https://zeit.co/docs/v2/advanced/runtimes#technical-details).
### Accessing Environment and Secrets
The env and secrets specified by the user as `build.env` are passed to the builder process. This means you can access user env via `process.env` in Node.js.
The env and secrets specified by the user as `build.env` are passed to the Runtime process. This means you can access user env via `process.env` in Node.js.
### Utilities as peerDependencies
When you publish your builder to npm, make sure to not specify `@now/build-utils` (as seen below in the API definitions) as a dependency, but rather as part of `peerDependencies`.
When you publish your Runtime to npm, make sure to not specify `@now/build-utils` (as seen below in the API definitions) as a dependency, but rather as part of `peerDependencies`.
## Types
### `Files`
```ts
import { File } from '@now/build-utils'
type Files = { [filePath: string]: File }
import { File } from '@now/build-utils';
type Files = { [filePath: string]: File };
```
This is an abstract type that is implemented as a plain [JavaScript Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). It's helpful to think of it as a virtual filesystem representation.
@@ -265,7 +202,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
import { File } from '@now/build-utils'
import { File } from '@now/build-utils';
```
Valid `File` types include:
@@ -277,7 +214,7 @@ Valid `File` types include:
### `FileRef`
```ts
import { FileRef } from '@now/build-utils'
import { FileRef } from '@now/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`.
@@ -294,7 +231,7 @@ This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaSc
### `FileFsRef`
```ts
import { FileFsRef } from '@now/build-utils'
import { FileFsRef } from '@now/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.
@@ -312,7 +249,7 @@ This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaSc
### `FileBlob`
```ts
import { FileBlob } from '@now/build-utils'
import { FileBlob } from '@now/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.
@@ -330,10 +267,10 @@ This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaSc
### `Lambda`
```ts
import { Lambda } from '@now/build-utils'
import { Lambda } from '@now/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 use a call to [`createLambda`](#createlambda).
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.
**Properties:**
@@ -346,39 +283,39 @@ This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaSc
This is an abstract enumeration type that is implemented by one of the following possible `String` values:
- `nodejs12.x`
- `nodejs10.x`
- `nodejs8.10`
- `go1.x`
- `java-1.8.0-openjdk`
- `java11`
- `python3.8`
- `python3.6`
- `python2.7`
- `dotnetcore2.1`
- `dotnetcore2.0`
- `dotnetcore1.0`
- `ruby2.5`
- `provided`
## JavaScript API
The following is exposed by `@now/build-utils` to simplify the process of writing Builders, manipulating the file system, using the above types, etc.
The following is exposed by `@now/build-utils` to simplify the process of writing Runtimes, manipulating the file system, using the above types, etc.
'index.js': new FileBlob({ data: 'exports.main = () => {}' })
}
})
'index.js': new FileBlob({ data: 'exports.main = () => {}' }),
},
});
```
### `download`
@@ -386,7 +323,7 @@ await createLambda({
Signature: `download() : Files`
```ts
import { download } from '@now/build-utils'
import { download } from '@now/build-utils';
```
This utility allows you to download the contents of a [`Files`](#files) data structure, therefore creating the filesystem represented in it.
@@ -396,7 +333,7 @@ Since `Files` is an abstract way of representing files, you can think of `downlo
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.
This utility allows you to _scan_ the filesystem and return a [`Files`](#files) representation of the matched glob search string. It can be thought of as the reverse of [`download`](#download).
[](https://spectrum.chat/zeit)
**Note**: The [canary](https://github.com/zeit/now/tree/canary) branch is under heavy development – the stable release branch is [master](https://github.com/zeit/now/tree/master).
## Usage
To install the latest version of Now CLI, visit [zeit.co/download](https://zeit.co/download) or run this command:
All PRs are submitted to the `canary` branch. Once a PR is merged into the `canary` branch, it should be published to npm immediately using the Canary Channel.
## Version Selection
Since Builders are published to [npmjs.com](https://npmjs.com), this makes versioning works the same for Builders as it does for any npm package. The `use` statement in [now.json](https://zeit.co/docs/v2/advanced/configuration#builds) has a similar syntax to `npm install`.
The following are valid examples [@now/node](https://www.npmjs.com/package/@now/node?activeTab=versions):
-`@now/node`
-`@now/node@0.7.3`
-`@now/node@canary`
-`@now/node@0.7.2-canary.2`
We always recommend using the latest version by leaving off the dist-tag suffix, `@now/node` for example.
The `--token` flag was specified, but its contents are invalid.
#### Possible Ways to Fix It
The `--token` flag must only contain numbers (0-9) and letters from the alphabet (a-z and A-Z). This needs to be the token of the user account as which you'd like to act.
You can either get the token from the `./now/auth.json` file located in your user directory or [from the dashboard](https://zeit.co/account/tokens).
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.17.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
- Brunch plugins and app dependencies: `npm install`
- Run:
-`npm start` — watches the project with continuous rebuild. This will also launch HTTP server with [pushState](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history).
-`npm run build` — builds minified project for production
- Learn:
-`public/` dir is fully auto-generated and served by HTTP server. Write your code in `app/` dir.
- Place static files you want to be copied from `app/assets/` to `public/`.
- [Brunch site](http://brunch.io), [Getting started guide](https://github.com/brunch/brunch-guide#readme)
## ES-next
To use proposed JS features not included into ES6, do this:
-`npm install --save-dev babel-preset-stage-0`
- in `brunch-config.js`, add the preset: `presets: ['latest', 'stage-0']`
Kick off your project with this default boilerplate. This starter ships with the main Gatsby configuration files you might need to get up and running blazing fast with the blazing fast app generator for React.
_Have another more specific idea? You may want to check out our vibrant collection of [official and community-created starters](https://www.gatsbyjs.org/docs/gatsby-starters/)._
## 🚀 Quick start
1.**Create a Gatsby site.**
Use the Gatsby CLI to create a new site, specifying the default starter.
```shell
# create a new Gatsby site using the default starter
gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default
```
1. **Start developing.**
Navigate into your new site’s directory and start it up.
```shell
cd my-default-starter/
gatsby develop
```
1. **Open the source code and start editing!**
Your site is now running at `http://localhost:8000`!
_Note: You'll also see a second link: _`http://localhost:8000/___graphql`_. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.org/tutorial/part-five/#introducing-graphiql)._
Open the `my-default-starter` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes and the browser will update in real time!
## 🧐 What's inside?
A quick look at the top-level files and directories you'll see in a Gatsby project.
.
├── node_modules
├── src
├── .gitignore
├── .prettierrc
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── LICENSE
├── package-lock.json
├── package.json
└── README.md
1. **`/node_modules`**: This directory contains all of the modules of code that your project depends on (npm packages) are automatically installed.
2. **`/src`**: This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser) such as your site header or a page template. `src` is a convention for “source code”.
3. **`.gitignore`**: This file tells git which files it should not track / not maintain a version history for.
4. **`.prettierrc`**: This is a configuration file for [Prettier](https://prettier.io/). Prettier is a tool to help keep the formatting of your code consistent.
5. **`gatsby-browser.js`**: This file is where Gatsby expects to find any usage of the [Gatsby browser APIs](https://www.gatsbyjs.org/docs/browser-apis/) (if any). These allow customization/extension of default Gatsby settings affecting the browser.
6. **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you’d like to include, etc. (Check out the [config docs](https://www.gatsbyjs.org/docs/gatsby-config/) for more detail).
7. **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby Node APIs](https://www.gatsbyjs.org/docs/node-apis/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process.
8. **`gatsby-ssr.js`**: This file is where Gatsby expects to find any usage of the [Gatsby server-side rendering APIs](https://www.gatsbyjs.org/docs/ssr-apis/) (if any). These allow customization of default Gatsby settings affecting server-side rendering.
9. **`LICENSE`**: Gatsby is licensed under the MIT license.
10. **`package-lock.json`** (See `package.json` below, first). This is an automatically generated file based on the exact versions of your npm dependencies that were installed for your project. **(You won’t change this file directly).**
11. **`package.json`**: A manifest file for Node.js projects, which includes things like metadata (the project’s name, author, etc). This manifest is how npm knows which packages to install for your project.
12. **`README.md`**: A text file containing useful reference information about your project.
## 🎓 Learning Gatsby
Looking for more guidance? Full documentation for Gatsby lives [on the website](https://www.gatsbyjs.org/). Here are some places to start:
- **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby](https://www.gatsbyjs.org/tutorial/).** It starts with zero assumptions about your level of ability and walks through every step of the process.
- **To dive straight into code samples, head [to our documentation](https://www.gatsbyjs.org/docs/).** In particular, check out the _Guides_, _API Reference_, and _Advanced Tutorials_ sections in the sidebar.
## 💫 Deploy
[](https://app.netlify.com/start/deploy?repository=https://github.com/gatsbyjs/gatsby-starter-default)
// You can delete this file if you're not using it
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.