* Make Now Routing Utils a Public Library
* Suggestions
* Cleanup
* Update lockfile
* Add to dist to eslint ignore
* v1.2.0-canary.0
* v1.2.0-canary.1
* v1.2.1-canary.0
* Use optional dep instead of peer dep
* Use a more robust library to convert pipfile - closes#841
* Renaming for clarity
* Suppress warnings since we know it will be invoked manually
Co-Authored-By: Steven <steven@ceriously.com>
* Apply the flag while installing not while generating the requirements.
Co-Authored-By: Steven <steven@ceriously.com>
* [now-static-build] Allow to set the `tag` for zero-config builders
This reverts commit 32b6f1d6a9047920d6cc40385de711022f77c4d4.
* Remove unsupported builders
* Fix setting the tag
* Add `debug()` function
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Update packages/now-build-utils/src/debug.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* tests transpilation of yarn workspaces
up until @now/node@0.7.4-canary.28 this used to work out of the box
* tests that typescript workspaces are properly compiled
* update node-file-trace, symlink handling
* update node-file-trace, use index.ts in package.json main
* remove logging!
* adds test with ts files in a subdir
* Updates typescript example to avoid node internal special casing
The initial example ended up passing even with a flawed implementation
because it unknowingly relied on a special case within node module's
resulotion engine which automaticaly resolves index files
within a module if they are located in the same directory as the
module's `package.json`
* upgrade to node-file-trace 0.2.2
* cleanup manual debugging leftovers
* fix yarn lock for node-file-trace 0.2.2
* more cleanup of manual tests
I offer my apologies about this mess
* [now-static-build] Replace `dist` with `public` as output directory
* Fix test
* Revert "Fix test"
This reverts commit 351c84c7bea1313742c165f753e7481fc7c3c0fa.
* Revert "[now-static-build] Replace `dist` with `public` as output directory"
This reverts commit daedfac17729645d9b409d7df3da6b0fb5d3b56a.
* Apply only to zero config
* Fix path
* [now-node] Use ncc before publishing
* Copy entire bridge source file
* Remove node-bridge dependency
* add typescript to build
* ensure typescript reference is not analyzed
* remove duplicate build
* typescript as a compiler
* Revert "typescript as a compiler"
This reverts commit f51178e641b09ea6aff0dc98185c86e8d27de2cc.
* exclude langs
* fixup mkdir
* fixup mv command
* fixup typescript reference
* Change require to use bridge
* Remove copy step for bridge defs
* Change back to require
* Copy bridge again
* Remove dependency on @now/node-bridge
* tests transpilation of yarn workspaces
up until @now/node@0.7.4-canary.28 this used to work out of the box
* tests that typescript workspaces are properly compiled
* update node-file-trace, symlink handling
* update node-file-trace, use index.ts in package.json main
* remove logging!
`yarn` used to be used, but was switched over to `npm` in #636.
The problem with `npm` is that when the `ignoreScripts` config option
is enabled in the user's `.npmrc` file, then `npm run …` does not get
invoked. This makes sense for `npm i`, but doesn't really make sense if
you're explicitly _trying_ to run a package script via `npm run`, and in
fact breaks `now dev`.
`yarn` has a similar option to ignore scripts, however it has the more
understandable behavior that when you do `yarn run` then the script is
actually run.
There isn't a concern about if the user does not have `yarn` installed
since `now dev` bundles its own copy of yarn and uses that version.
* Update dynamic routes to have prefix in src
and not in dest for dev
* Make sure prefix isn't inside of capture
group for dynamic routes
* Prevent double slashes in src regexp
* Make sure leading slash is outside capture group
* Move up removing of leading slash from capture group
Fixes#729.
* [now-static-build] Remove default routes for now dev
* Update packages/now-static-build/src/index.ts
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* [now-static-build] Fix template string
* [now-static-build] Handle different dist dir for Angular
* Fix type issue
* Fix hexo test
* Log more
* Change hexo test
* Adjust Hexo test
* Removed extra logging
* Continue with prev test
* Use @now/node@canary
* Fix tests
* Increase timeout
* Increase timeout
* Add framework
* Reset timeout for now-build-utils
* Increase timeout
* Adjust test
* [now-build-utils] Add support for `_` and `.` prefixes in `api/`
* Remove log statement
* Ignore dot and underscore prefix for api directory
* Set one builder per file if there are files to ignore
* Always return all builds with their exact match
* [now-node] Add support for listener
* Fix listener
* Add hapi-async test
* Add timeout for listening
* Add additional case for invalid export
* Increase timeout to 5 seconds
* bumps ncc to 0.20.0
* upgrades to ncc@0.20.2
this includes the fixes for https://github.com/zeit/ncc/issues/434
* defines filterAssetBase when calling ncc
This prevents assets from being evicted by ncc's filtering.
* scopes includeFiles under the package root
it was previously scoped under the directory of the input file currently
being processed.
This should fix#522 along with fixing the 09-include-files tests for
now-node
* Bump to ncc 0.20.3
* Bump ncc-watcher to 1.1.0
* Optimize frameworks in @now/static-build
* Make it shorter
* Disable build.sh for zero config
* Adjust error message according to zero config prop
* Renamed wrong fixtures
* Added Gatsby fixture
* Ignore static-build fixtures when linting
* Fix test
* Support Svelte
* Added Create React app and Svelte defaults
* Added comma
* Merge routes properly
* Removed test file
* Polished test
* Fixed types
* Added type
* Added correct type
* Added default routes for Svelte
* Extended route type
* Temporarily removed check
* Revert "Temporarily removed check"
This reverts commit bb5e2843eca60753228d499efbb6dd4aa1c28c5b.
* Enable routes
* Added package.json type
* Added Framework type
* Added Route type
* Increase size
* Export Route type
* Added Vue
* Fix test
* Fixed all tests
* Added Angular app
* Removed garbage
* Ignore ts stuff
* Added type
* Added type for function
* Made it async
* Require minimum node version
* Push pretter polishment
* Add support for node version
* Make minNodeVersion optional
* Make node version silent
* Added optional type
* Log everything
* Fixed tests
* Changed version
* Pushed Node.js version update
* Update packages/now-build-utils/src/fs/node-version.ts
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* Cleaner syntax
* Silence more messages
* Hide more text
* Update packages/now-build-utils/src/fs/run-user-scripts.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Update packages/now-build-utils/src/fs/run-user-scripts.ts
Co-Authored-By: Steven <steven@ceriously.com>
Watch assets that `ncc` reports as part of the compiled bundle.
For example, "pug" template files:
```js
app.set("views", path.join(__dirname, "../../", "/views/"));
```
* check for listen method on export
* revert setting helpers on __proto__
* fix launcher
* add missing semicolon
* fix missing bridge parameter
* add server test fixture
* move express test fixtures to servers
* add missing entrypoints in fixtures
* temporary fix before we update node-bridge
* refactor express test fixture
* add fixtures for hapi, fastify, koa
* fix now.json in servers fixtures
* remove fastify as it is not yet supported
* remove fs-extra as a dependency
* remove Stream support
* text/plain -> text/html
* add etags
* bring test suite from expressjs
* add TODO comment
* remove body for 204 and 304
* do not send body when req.method is HEAD
* fix tests
* lazy load etag
* add type safeguards
* avoid type casting
* [now-static-build] Default to `now-dev` when `zeroConfig` is false
* Adjust tests
* Fix build
* Return nowCmd
* Adjusted type
* Changed type
* Removed type
* Cast type
* [now-build-utils] Export config
* [now-static-build] Use `build` and `dev` command if there is no `now-` version
* Fix default dev command
* Get correct command
* Added type
* Add getCommands and replace now-dev occurrences
* Linting
* Added test for build
* Adjusted test
* Adjusted message
* Adjusted tests
* fix res.send/res.json discrepancies with express
* add tests and refactor
* throw error on res.json(undefined)
* re-add streams
* do not console.warn
* move hello to fixtures-helpers folder
* be more explicit about accepted types
* setDefaultCT -> setContentType
* improve error messages
* make `fixtures-helpers/hello` appear in the code
* refactor setContentType
* set correct `content-length` header
* use PassThrough stream to remove fixture
* remove `.only` in test
* improve git diff in jest config
* refactor jest.config.js
* try with empty testMatch
* Revert "try with empty testMatch"
This reverts commit ec69a03cc7953a8e6e2d7b2f3ba2bb08d2fcbfa5.
* Update jest.config.js
Co-Authored-By: Steven <steven@ceriously.com>
* trim branch name
* move trim up
* add empty files to test behaviour
* Remove empty files
* [now-build-utils] Fail if engines does not match
* Add test to throw when invalid semver
* Apply suggestions from leo
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Fix ts error
* Print range so its clear what to add to engines
* proposes a contributing guideline
the guideline outlines the process to open a pull request on this
repository and offers guidance on interpreting test errors.
* Wording improvement
As per @styfle suggestion
Co-Authored-By: Steven <steven@ceriously.com>
* Reword reference to code of conduct
As per @styfle's suggestion.
Co-Authored-By: Steven <steven@ceriously.com>
* fix local developement section title
Co-Authored-By: Steven <steven@ceriously.com>
* Improves project description wording
Co-Authored-By: Steven <steven@ceriously.com>
* Proper setup instructions
The ones provided initially were incomplete (might explain why I had some issues :) )
Co-Authored-By: Steven <steven@ceriously.com>
* updates description of tests
Co-Authored-By: Steven <steven@ceriously.com>
* Improve explanation of integration tests
Co-Authored-By: Steven <steven@ceriously.com>
* Update ncc bug qualification section
Co-Authored-By: Steven <steven@ceriously.com>
* fixes typo
Co-Authored-By: Steven <steven@ceriously.com>
* clarifies when and why to run ncc manually
Co-Authored-By: Steven <steven@ceriously.com>
* clarifies how to access to test deployements and associated logs
Co-Authored-By: Steven <steven@ceriously.com>
* Add engineSatisifies for node
* Rename to enginesMatch
* Add test for node10
* Minor refactor
* Add tests for engines, uses semver.intersect()
* Revert @now/node, new PR later
* lazy load everything ✨
* do not read charset in content-type to set encoding
* add tests
* add tests for express compat
* add test for `res.status().send()`
* update after PR comments
* [now-md] Fix `shouldServe()` logic
Since this builder is not a 1-1 mapping of the input -> output names,
the default `shouldServe()` function needs to be augmented such that
the `.html` requestPath is "considered like" a `.md` file.
* Remove "ends with .html" optimization
It breaks index files, i.e. `GET /`
Some users read this message as a warning that required action (the captain caps lock WARNING didn't help).
Users should never need to define a `now-build` script unless they grow out of running `next build`.
* copy bridge into now-node
* pass body buffer to listener
* only send addon when helpers are added
* ship bridge.js to deployment
* remove raw-body deps
* fix not waiting for server `listening` event
* add test for express compat
* add test for micro compat
* update now-node-bridge
* remove unnecessary yarn.lock
* fix wrong replacement in launcher.ts
* fix listener not defined
* fix unit tests
* add "test" for exports
* add console.log
* add test in node-bridge
* log error before throwing
* revert now-node-bridge to canary state
* remove unused code
* refactor consumeProxyRequests -> consumeEvent
* remove ts-jest
* update tests
* do not transform body to string if not necessary
* fix tests
* remove jest from deps in now-node
* x-bridge-reqid -> x-now-bridge-request-id
* add test for consumeEvent
* do not expose request id header to the client
* pin node-bridge version
* update node-bridge deps to 1.2.0-canary.1
* update yarn.lock
* add await for user's listener
* refactor
* pass async function to `Server`
* first iteration of express-like api for @now/node
* fix error when config is undefined
* add integration test for helpers
* add `res.status()` to helpers integration test
* fix error caused by config values being strings
* add helpers opt-out integration test
* add `helpers.js` to deployed files
* add boolean and number to config values types
* update config.helpers to work with boolean
* add unit tests
* fix type error in config type
* add unit test for req.body
* ignore errors not generated in helpers
* Update packages/now-node/test/fixtures/15-helpers/no-helpers/index.js
Co-Authored-By: Steven <steven@ceriously.com>
* update config type
* use ternary instead of filtering with `Boolean`
* add probe in 15-helpers
* add probe for ts function
* ncc `helpers.js`
* fix Config type
* fix @now/rust type issue
* add comment in build.sh
* test that content-type header is correctly added
* add missing tsconfig.json in fixtures
* add `body` to fix `Invalid JSON` errors
* Revert "add `body` to fix `Invalid JSON` errors"
This reverts commit 9b2ff55409501140f0d7411d121fc3a4dfd34ccc.
* make `helpers` false by default
* add method POST to probe for helpers
* Revert "make `helpers` false by default"
This reverts commit d029a432a0bf2463e1613e6cfd76929ce6e45073.
* replace POST requests by GET in probes
* remove unnecessary comments
* destructure in parseQuery
* keep @now/rust unchanged
* Request -> NowRequest and Response -> NowResponse
* improve config types
* add NowListener type
* export NowRequest and NowResponse
* generate `.d.ts` files
* add types to helpers/ts fixtures
* Update packages/now-build-utils/src/types.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Update packages/now-node/build.sh
Co-Authored-By: Steven <steven@ceriously.com>
* [now-layer] Add meta to BuildLayerResult
* Fix tests
* Fix test for expect entrypoint
* Return entrypoint
* Remove meta
* Remove meta
* Remove npmVerison meta check from layer-node
* Fix missing slash for staticRoute
* Add util for prepending entryDirectory correctly
* Apply suggestions from code review
Co-Authored-By: Connor Davis <mail@connordav.is>
* Don't add export route for dynamic pages
* Fix type error from review commit
* Don't use scopeToEntry on lambdas
* Add `now-layer-npm`
* Change version to 0.0.1-canary.0
* Add now-layer-yarn
* Update version
* Add now-metadata.json
* Read package.json to detect npm version
* Fix tests for windows zip
* Change circleci workflow to build-and-test
* Add branch filter
* Separate into two workflows
* Move both workflows into single file
* Rename to main.workflow
* Add support for `go.mod` in different `entrypoint` directory
* Add tests cover Go Modules
* Workaround solution to make `now dev` support `go.mod` in different folder than `entrypoint`
* Ensure to backup `go.mod` and `go.sum` only in isDev
* Update packages/now-go/index.ts
* Update packages/now-go/index.ts
* Update watcher to work for different local packages under the same `go.mod`
* Improve code readability
* Match static files before checking dynamic routes
* Add Next.js lambda matching
* Apply suggestions from code review
Co-Authored-By: Connor Davis <mail@connordav.is>
* Correct index logic
* Add builder support for handle filesystem
* Check html rewrites first
* fix: Don't try and install rust and openssl during development
* feat: Convert now-rust to typescript
* Fix some typescript errors
* feat: Fix types for now-rust
* fix: Fix typo in type name
* fix: Small cleanups and tweaks from the PR review
* fix: Increase test timeout duration
- Add built JS files from now-build-utils to the eslintignore file
* fix: Compile to dist directory and don't lint now-rust
* fix: Only ignore linting for now-rust's dist dir
* Use GitHub Actions for publishing to npm
* Move publish from CircleCI to GH Actions
* Add npm install
* Fix names
* Use yarn instead of npm
* Fix typo
* Remove publish from circleci
* Fix typo
* Add check for NPM_TOKEN
* Add tag filter
* Remove tag filter
* Make sure to pass decode url params
* Add tests cover default and custom routes behaviour on url param
* Removed `unquote` since `urlparse` already return expected value
* Using unquote in both PATH_INFO and QUERY_STRING
* Better code structure now_init.py
* Better test
* Add option to use private Git
* Update packages/now-go/index.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Fix import error
* Using `GIT_CREDENTIALS` over multiple env vars
* Ignore initialize Git credentials in `meta.isDev`
* [now-go] Ignore folders in `analyze.go` (#503)(#504)
This commit adds some changes to the way the AST for the source is
built.
The `analyze.go` program now ignores every `vendor`, `.git` and
`testdata` folder. This improves performance, since `vendor` and `.git`
are usually large folders (#504).
By ignoring `testdata`, we mimick the behaviour of `go build` and avoid
failing the parsing because of invalid Go code inside of `testdata` (#503)
* [now-go] Don't ignore `.git` in analyze (#506)
If the user wants to ignore `.git`, he should put it into `.nowignore`
The `srcBase` (directory where the entrypoint is located) should not be
in the `dest` proxy pass URL.
Consider an entrypoint like `www/package.json`. The development server
will be running within the `www` directory. A request for `GET
/static/foo.js` comes in, so we want to proxy pass to
`http://localhost:12345/static/foo.js` rather than
`http://localhost:12345/www/static/foo.js` which would lead to a 404.
* [now-static-build] Add `err.sh` link when dev server detection fails
The error message alone doesn't explain how to fix it, so adding this
`err.sh` link to guide the user to instructions on how to fix it.
For example: https://github.com/zeit/now-cli/issues/2339
* Shorter title
* should -> must
This will be necessary for the update in `now dev` to have the builder
`workPath` be equal to the `cwd` source directory of the dev server.
Otherwise, unnecessary file modifications are made (copying the source
file to itself) and file corruption often occurs.
* [now-next] Sync runtime env vars in dev server after `app.prepare()`
* Update packages/now-next/src/index.ts
Co-Authored-By: TooTallNate <n@n8.io>
* Update packages/now-next/src/index.ts
Co-Authored-By: TooTallNate <n@n8.io>
* Add `syncEnvVars()` helper function for common logic
Co-Authored-By: Steven <steven@ceriously.com>
* Add an ephemeral option for files
* Use array destructuring
Co-Authored-By: Timer <joe.haddad@zeit.co>
* Remove mutable option
* Remove code all together
* Introduce `sha+ephemeral` handling
* http => https
* Elaborate more on the cloudfront url
* Update comment a bit more
* Add comment explaining other url
This adds the default `shouldServe()` implementation to the following
builders:
* `@now/bash`
* `@now/cgi`
* `@now/html-minifier`
* `@now/lambda`
* `@now/md`
* `@now/node-server`
* `@now/node`
* `@now/optipng`
* `@now/php`
* `@now/python`
* `@now/rust`
The default implementation may be used for these builders because
they map 1-1 with their entrypoint file -> output file/lambda.
* Warn when now-dev script is missing
* Add link to local dev docs
* Update packages/now-static-build/index.js
Co-Authored-By: styfle <steven@ceriously.com>
* Fix url
* Improve speed for build() `@now/go` `now dev`
* Remove duplicate line
* Improve code flow
* Improve logging information
* no need to download Go if it available
* Migrated `@now/go` to TypeScript
* Add support for Builder v2 API
* Add now-go to .eslintignore
* Update go bin path
* Update packages/now-go/.gitignore
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Update packages/now-go/go-helpers.ts
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Update packages/now-go/go-helpers.ts
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Using American English for consistency
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Rename analyse.go to analyze.go
* Update packages/now-go/go-helpers.ts
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Remove `mkdirp-promise` from now-go
* Ensure `watch` directory-aware given `entrypoint` in subdirectory
* Support export struct type declaration
* Improve log
* Add type to `analyzed`
* Update packages/now-go/index.ts
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Migrate test fixtures from `add/now-go-tests`
* [static-build] Add `now-dev` package.json script
This will cause `now dev` to run the `now-dev` script as defined in the
`package.json` file.
`now dev` sets the `$PORT` env variable for use in the `now-dev` script,
which is expected to launch a file watching server (for example `hugo
dev`) on the specified `$PORT`. `now dev` wait for this port to be bound
before returning the `build()` function with the generated assets.
The `watch` array is just "watch everything in the
`path.dirname(entrypoint)`" so any file changed within that directory
will trigger a "re-sync" of the source files that `now dev` is working
with, which the user spawned static build watcher should pick up on and
return the updated assets.
* Use `routes` instead of globbing the output dir
Proxy passing to the development server is a cleaner approach, since it
removes the race condition about the builder not having knowledge of
when a dev watcher server rebuilds, so it's not possible to know how
long to wait to return outputs upon another call to `build()`.
* Make `watch` be an array
Co-Authored-By: TooTallNate <n@n8.io>
* Fix `promise-timeout` require()
* Inherit from `process.env` for `yarn run`
Otherwise ENOENT happens because there is no `PATH` env var set
* Only validate dist dir in production builds
* Fix `routes` and `watch` output
* Remove dev logging, add better timeout error message
* Populate `routes` upon rebuild
* Pass `meta` to the `download()` function
* Revert version change in `package.json`
* Save devport sooner
* Develop Next.js app inside workPath
* Made file watching work
* Define routes the first time
* Added index handling
* Fixed indexing
* Fixed indexing again
* Removed useless code
* Start server in child process
* Made `now-next` invoke `next dev`
* Even cleaner
* Fixed some types
* Fixed dirs
* Start server if initial build
* Added remaining types
* Added missing type
* Made property optional
* Fixed types
* Expose that the Builder is continuous
* Added more details
* Removed useless code
* Made it work
* Removed useless crap
* Added new version
* Synced up
* Refined logging
* Fixed routes
* Correctly parse request paths
* Fixed routes
* Fixed GET parameter issues
This is a quick fix for our token problem by attempting to retry the fetch.
> FetchError: invalid json response body at NOW_TOKEN_FACTORY_URL reason: Unexpected token A in JSON at position 0
The root cause is in the token factory because it throws `Confirmation incomplete` but that will be harder to track down and fix.
This will increase the lambda size a little bit but it will make for a much better user experience when debugging uncaught errors.
I also added a test so we don't regress.
After #359, creating zip files with symlinks would be corrupted because
the "target" of the symlink was actually the file contents.
This commit fixes the zip file construction logic to handle symlinks by
placing the target of the symlink as the "contents" of the file in the
zip. The unit test relies on GNU `unzip` and checks that it creates the
symlink from the produced zip file as expected.
If the `http.Server` handler function throws an error asynchronously,
then it ends up being an unhandled rejection which doesn't kill the node
process which causes the HTTP request to hang indefinitely. So print the
error here and force the process to exit so that the lambda invocation
returns an Unhandled error quickly.
Fix link to documentation in static builder when the `dist` directory is not created.
I also changed the `build-utils` to use top-level imports like our docs specify.
* [now-build-utils] Add support for symlinks to `download()`
`now dev` is using this function to extract the `prepareCache()`
results, but upon extraction symlinks are lost and turned into
regular files, which breaks relative requires in Node.js modules.
This commit properly creates the symlinks from the files passed to
the `download()` function so that this problem no longer happens.
* Refactor `glob()` to return symlinks properly and add unit test
* Ensure the symlink target dir exists
This updates the `includeFiles` implementation to match how `now-node-server` does it, which is an array of globs rather than a single glob. To avoid making a new major version, this is done in a backwards compatible way to support existing projects using the current single glob API.
Added extra files to ensure that all would be included/processed even though the test just tests for one of them.
cc/ @styfle
Considering that `prepareCache()` is executed directly after `build()`
is run, it seems that deleting the previous `workPath` and re-installing
the dependencies is just extra work, and it would be better to create
a cache from the `workPath` artifacts that `build()` just created.
From the perspective of `now dev`, this is ideal because:
1. The `workPath` shouldn't be deleted since static file assets are
served from the `workPath`, so `prepareCache()` deleting this
directory is problematic.
2. Creating the cache quickly becomes an important goal, because it
reflects how quickly a developer can iterate on a file, and we don't
want them waiting for `yarn` to finish installing dependencies all
the time in order to see the change in their project.
* Strip Carat from version
* Get from next package.json
* Fix require
* Use resolveFrom
* Correctly fetch Next.js version
* Update index.js
* Update package.json
* migrate `@now/python-wsgi to `@now/python`
* Refactor to use build-utils main
* Update install flag `--upgrade` in the right order.
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* using `cwd` in instead in `execa`
* add 01-cowsay test with `pip` and `pipenv`
* add 01-wsgi test
* Fix typo
* Add test script for now-python
* Add now_init.py to support dynamic imports
* Remove redundant files, no more config.wsgi
* replace all occurrences __NOW_HANDLER_FILENAME
* update tests for `@now/python`
`cache clean` was being invoked for legacy purposes back when we were
dealing with Lambda's 500mb runtime filesystem limit. Now that builds
are not running on lambda, this can be removed. It also makes `now dev`
building unnecessarily slow.
This PR adds a builder for Python WSGI web apps. It is heavily based on [`serverless-wsgi`](https://github.com/logandk/serverless-wsgi) and [`requests-wsgi-adapter`](https://github.com/seanbrant/requests-wsgi-adapter), uses [`Werkzeug`](https://github.com/pallets/werkzeug), and works without running an additional web server.
I've tested it manually with a simple Flask app that contains endpoints with `GET` and `POST` methods, nested paths, and JSON and binary response bodies.
Curiously, the `event` parameter in the `now_handler` function does not appear to have the expected structure of AWS Lambda functions. For instance, `event['isBase64Encoded']` does not exist. Instead, this information is encoded in `json.loads(event['body'])['encoding']`. The returned `dict` also expects `encoding='base64'` for a binary response body instead of `isBase64Encoded=True`. I've also noticed that no AWS request headers are included. I assume Now is responsible for these differences to plain AWS Lambda functions.
I'd appreciate code review and feedback to get robust official Python WSGI support into Now as soon as possible.
* fix subdirectory build fail for `@now/go`
* using sep over platform specific forward slash
* Update packages/now-go/index.js
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* Update packages/now-go/index.js
Co-Authored-By: sophearak <t.sophearak@gmail.com>
* add 01-cowsay with subdirectory test case
* Add Codecov
* Using flag for coverage instead
* Revert "Using flag for coverage instead"
This reverts commit 9e14c8c8299267b2ff0431d822391e0538839ae7.
* Update codecov
* Add circle ci test coverage step
* try run jest without `node --expose-gc`
* Revert "try run jest without `node --expose-gc`"
This reverts commit 39fbd7995375ac62529d2d55519abc877b526071.
* run jest --coverage without `node --expose-gc`
* run jest with --runInBand flag
* Run tests and coverage at the same time
* Add shellcheck ignore comments to dynamic imports
* Add shebang to `runtime.sh`
So that vim applies proper syntax highlighting when bash-specific
features like `<<<` are used.
* Send error responses with `errorMessage` property
So that `now dev` can display the error message properly.
This add the ability to include other files into the filesystem of the lambda. This works by providing an `includeFiles` option in the builder config, and then moving those into the lambda when it's created. The `includeFiles` option is a glob matcher relative to the entrypoint.
**Note:** This is the first example I know of that allows a user to add more files to the filesystem through the official now builders. This API is something I came up with, and may not be the best or what y'all are thinking.
## Why?
This is helpful for my specific case, where I need extra binaries on the system when the lambda executes (`wget` and `now`). This could also be useful to include large files to parse, or other things one wouldn't want to include in the rust binary itself due to file size, memory allocation, whatever.
## Example
**Local file structure**
```
now_lambda/
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── static
├── now
└── wget
```
**Now config**
```json
{
"version": 2,
"name": "now-lambda",
"builds": [
{
"src": "Cargo.toml",
"use": "@now/rust",
"config": { "includeFiles": "static/*", "maxLambdaSize": "50mb" }
}
]
}
```
**Lambda file structure**
```
/var/task/
├── bootstrap
└── static
├── now
└── wget
```
## Testing
You can use `https://mike-now-rust-5shu849in.now.sh` as the builder's `"use"` key to test it out. It's a hosted tarball of this PR with a little extra debugging thrown in.
This is important for TypeScript usage with the combined `File` type
declaration. It helps the compiler understand the proper type in
consuming code via `if` checks to avoid casting.
* [now-python] Use `workDir` provided by builder
Instead of generating another temp directory.
* [now-python] Add `--upgrade` flag to `pip install`
This is mainly for `now dev`.
* Add typescript to build utils
* Move file to file.ts
* Move to src directory
* Cast to readable
* Cast to stats
* Ignore js files
* Remove includes
* Run Linting after Building in CircleCI
* Move now-next tsconfig, add build script
* Fix default exports
* Attemp to fix default exports
* Change api to use index
* Add types to package.json
* Add missing fs
* Add shims
* Add missing end-of-stream dep
* Fix shims
* Ignore TS when linting
* Removed the unused top-level typescript
The main idea behind this is we want user be able to specific files in that should be include in the `handler` which later can be use in runtime.
For the most case, `ncc` be able to detect relevant files included in the `handler`. But the case that `ncc` not able to resolve, this option come in handy.
PR #277 does the same thing, but for `@now/node`.
* Fix `packAndDeploy()` for usage with `@now/node`
Since the prepublish script for `@now/node` writes other stuff to
stdout, so relying on `npm pack` outputting the tarball name is not
reliable.
Instead, just `glob()` for a `*.tgz` file and expect that to be the
output package tarball.
Fixes error:
```
Error: ENOENT: no such file or directory, open '/home/circleci/repo/packages/now-node/> @now/node@0.5.2-canary.2 prepublish /home/circleci/repo/packages/now-node
> npm run build
> @now/node@0.5.2-canary.2 build /home/circleci/repo/packages/now-node
> ./build.sh
'/home/circleci/repo/packages/now-node-bridge/bridge.d.ts' -> 'src/bridge.d.ts'
now-node-0.5.2-canary.2.tgz'
```
* Make the `tgzPath` be absolute
* 'ignore' -> 'inherit'
This fixes a subtle bug in the `getExportedFunctionName()` helper
function. It wasn't actually causing any issues in production, since the
`index.js` file also does `await` on the return value of this function
so it was still resolving the promise properly, but this is more correct
and fixes the associated `debug()` call.
* [now-python] Add `setup.cfg` file before running `pip install`
See: https://stackoverflow.com/a/44728772/376773
The `setup.cfg` is required for `now dev` on MacOS, where without
this file being present in the src dir then this error happens:
distutils.errors.DistutilsOptionError: must supply either home
or prefix/exec-prefix -- not both
* Only create the `seup.cfg` file once
In situations where the handler responds very quickly, the `$event` file
path gets deleted before the `_lambda_runtime_body` function can finish
its work. So instead, just read that file once and cache it to
a variable inside that function.
This fixes this issue when the `handler` responds very quickly, causing the
`$events` file to be deleted before the multiple `jq` invocations are able to
read it:
```
/var/task/.import-cache/runtime.sh: line 78: /tmp/T/tmp.DShzjeah: No such file or directory
/var/task/.import-cache/runtime.sh: line 82: /tmp/T/tmp.DShzjeah: No such file or directory
```
* add support go.mod
* add main__mod__.go
* add missing variable and fix import
* fix linter
* remove `gcc` and add `go mod tidy`
* let go build handle the getting the package
This might allow users to use `go.mod`, since on 1.12 they did the following:
> ... the go command now supports module-aware operations outside of a module directory, provided that those operations do not need to resolve import paths relative to the current directory or explicitly edit the go.mod file. ...
Perhaps after that, the users would be simply able to add this to their config files and make it work?
```
"build": {
"env": {
"GO111MODULE": "on"
}
},
```
Also related to #241.
`os.tmpdir()` abstracts away platform differences related to retrieving
the writable temp directory, for example MacOS returns a user-specific
temp directory instead of `/tmp`.
On AWS Lambda, [it returns `/tmp`](https://nexec-v2.n8.io/api/node?arg=-p&arg=require(%27os%27).tmpdir()).
More importantly, it removes the `__dirname/tmp` special-case when not
running in prod. This was problematic for `now dev` because the module
directory is not always writable (i.e. for a `pkg` binary).
* Add `node_modules` caching for Next.js projects
* Use existing work directory instead of redownloading dependencies
* Reorder fns
* Add prettier configuration
* Move entry files to cache folder
* Correct glob base path
* Be sure to include .yarn-integrity
* Save `package.json` and `yarn.lock`, too
* Increase compatibility so Yarn can dedupe
Update `@now/next` to use the latest `@now/node-bridge`, which removes the hard-coded port 3000 that was previously in-place, which was problematic for `now dev`. Now the `http.Server` instance listens on an ephemeral port which is detected by the Now node runtime.
(Similar to 6101ba9d95 and 8dc0c92c58)
Not really sure why this is happening, since `@now/node` and
`@now/node-server` both use this version, but without this commit, then
publish step on CircleCI fails due to a dirty working tree.
Go figure 🤷
Update `@now/node-server` to use the latest `@now/node-bridge`, which
removes the hard-coded port 3000 that was previously in-place,
which was problematic for `now dev`. Now the `http.Server`
instance listens on an ephemeral port which is detected by the
Now node runtime.
This moves `@now/node` to being implemented in TypeScript.
It also updates it to use the latest `@now/node-bridge`, which
removes the hard-coded port 3000 that was previously in-place,
which was problematic for `now dev`. Now the `http.Server`
instance listens on an ephemeral port which is detected by the
Now node runtime.
* [now-node-bridge] Refactor API to be `http.Server` focused
This commit refactors the `@now/node-bridge` helper module to work with
`http.Server` instances directly, instead of expecting the `port` to be
set.
The `Bridge` instance calls the `listen()` function on the server instance
which binds to an ephemeral port. This is especially important for
`now dev`, where using a hard-coded port will cause port conflicts for
multiple lambdas using the same builder.
Also converts to TypeScript and adds some basic unit tests.
Example usage:
```js
const server = new Server(() => {});
const bridge = new Bridge(server);
bridge.listen();
const info = await bridge.listening;
assert.equal(info.address, '127.0.0.1');
assert.equal(typeof info.port, 'number');
```
* Update `yarn.lock`
* Add `pretest` script
* Enable TypeScript `strict` mode
* Throw if a string is returned from `server.address()`
Defensive programming ftw
Co-Authored-By: TooTallNate <n@n8.io>
* Prettier
* Prettier
* Fixes
* Attempt to fix CI
* Add `files` array to package.json
* Check for the `Action` property to avoid type casting
Co-Authored-By: TooTallNate <n@n8.io>
* Split the normalizing functions into separate ones
Also adds additional unit tests.
* export the `NowProxyRequest` and `NowProxyResponse`
* Remove last `as` casting
* Move some up
* Debug CircleCI tests :/
* Fix "Invoke" check
* Attempt to fix CircleCI again
* Fix bad
* Convert tests to use `jest`
* Add `publish.sh` script for CircleCI
Centralize the publishing logic for CircleCI to use.
There was a bug in the previous "Potentially publish stable release"
branch, such that it would be executed for non-tagged commits. The new
publish script checks if there are indeed any tags for the commit, and
bails if there are none.
As an additional bonus, there's now only one publish step in the
CircleCI config, because the publish script determines stable vs. canary
based on the tag name.
* Remove `echo`
* pass body to lambda
* reformat
* look for requirements.txt in lambda root
* single issue PR
* support base64 encoded request body
* support local requirements.txt
* formatting cleanup
* Update packages/now-python/now_handler.py
Co-Authored-By: NathanielHill <nata@goguna.com>
* Avoid error on empty POST body
Just realized I forgot to address the empty POST body error. This should do it
* quick formatting fix
remove double quotes for consistency
* [now-go] Refactor to be platform-aware for `now dev`
This is mostly to have `now dev` work, but also just a general cleanup
of the builder codebase.
Previously, the `get-exported-function-name` Go binary was being
compiled at publish-time for "linux x64" architecture, since that
is what AWS Lambda expects.
In order for `@now/go` to work on MacOS (or any other platform not
compatible with "linux x64") the helper program must be compiled by the
actual host machine, so that it builds a MacOS binary for example.
So building `get-exported-function-name` has been moved from the
"publish" step to the "postinstall" step.
Similarly, the `go` binary itself used to be downloaded explicitly by
the `build()` function during build-time. This step has been moved to
the "postinstall" script as well, so that said binary may be compiled.
This also makes sense because the `@now/go` builder will be downloaded
by `now dev` once, so this way the `go` binary only needs to be
downloaded once as well, rather than once per build.
Any assumptions about `GOOS` and `GOARCH` have also been removed.
* Don't lint the `go` tarball directory
* Use GitHub URL for the go bridge
* Tweak comments
* Use `glob()` instead of `FileFsRef`
`FileFsRef` appears to lose executable permissions on the file,
whereas `glob()` works as expected.
* [now-build-utils] Add `FsFileRef.fromFile()` helper function
This helper function is very similar to the raw `FsFileRef` constructor,
however it stats the file to retrieve the proper `mode`, so that
settings like executable bits are not lost.
* Rename to `FileFsRef.fromFsPath()`
* Update now-next-legacy-mode.md
From `canary` to `latest`.
* Update now-next-no-serverless-pages-built.md
From `canary` to `latest`
* Apply suggestions from code review
Better words...
Co-Authored-By: paulogdm <paulogdemitri@gmail.com>
For `now dev` running on a MacOS machine, some of our builders will need
to be adjusted to be "platform-aware".
In this case, `mktemp` is provided by BSD instead of GNU, which doesn't
support the long form `--dry-run` flag, however both support the `-u`
flag which does the same thing.
* Fix docstrings, remove unused rust dev dependency
* Add support for multiple binaries, prepareCache too
* Remove context from the handler signature, abstract over the AWS error
* Fix Rust tarball URL, caching and lint
* GCC URL
* Fix broken error link
* Added legacy mode error
Standard "Next.js" for all citations of Next.
Add "Legacy Mode" error.
* Update no serverless pages built doc
* Update doc on now/next legacy mode
* Add link after the error message
* Give test more time
* Implement legacy flag
* Move tests
* Add test for new builder
* Add serverless target flow
* Remove prepareCache
* Add semver check
* Upgrade for latest Next.js canary
* now/wordpress copied from new now/php
* download, decompress and merge release url
* static files
* require entrypoint be named 'wp-config.php'
* patch wp-db.php to use persistent connections
* "/wp-admin/index.php" rule is not needed
* emit lambda with name 'index.php'
* more staticRegexps
* make patchForPersistentConnections opt-in
* remove one more extra route
* update they way secrets are passed
* update route regexp a little
When contributing to this repository, please first discuss the change you wish to make via issue or [spectrum](https://spectrum.chat/zeit) with the owners of this repository before submitting a Pull Request.
Please read our [code of conduct](CODE_OF_CONDUCT.md) and follow it in all your interactions with the project.
## Local development
This project is configured in a monorepo pattern where one repo contains multiple npm packages. Dependencies are installed and managed with `yarn`, not `npm` CLI.
To get started, execute the following:
```
git clone https://github.com/zeit/now-builders
yarn install
yarn bootstrap
yarn build
yarn lint
yarn test
```
Make sure all the tests pass before making changes.
## Verifying your change
Once you are done with your changes (we even suggest doing it along the way ), make sure all the test still run by running
```
yarn build && yarn test
```
from the root of the project.
If any test fails, make sure to fix it along with your changes. See [Interpreting test errors](#Interpreting-test-errors) for more information about how the tests are executed, especially the integration tests.
## Pull Request Process
Once you are confident that your changes work properly, open a pull request on the main repository.
The pull request will be reviewed by the maintainers and the tests will be checked by our continuous integration platform.
## Interpreting test errors
There are 2 kinds of tests in this repository – Unit tests and Integration tests.
Unit tests are run locally with `jest` and execute quickly because they are testing the smallest units of code.
### Integration tests
Integration tests create deployments to your ZEIT account using the `test` project name. After each test is deployed, the `probes` key is used to check if the response is the expected value. If the value doesn't match, you'll see a message explaining the difference. If the deployment failed to build, you'll see a more generic message like the following:
```
[Error: Fetched page https://test-8ashcdlew.now.sh/root.js does not contain hello Root!. Instead it contains An error occurred with this application.
NO_STATUS_CODE_FRO Response headers:
cache-control=s-maxage=0
connection=close
content-type=text/plain; charset=utf-8
date=Wed, 19 Jun 2019 18:01:37 GMT
server=now
strict-transport-security=max-age=63072000
transfer-encoding=chunked
x-now-id=iad1:hgtzj-1560967297876-44ae12559f95
x-now-trace=iad1]
```
In such cases you can visit the URL of the failed deployment and append `/_logs` so see the build error. In the case above, that would be https://test-8ashcdlew.now.sh/_logs
The logs of this deployment will contain the actual error which may help you to understand what went wrong.
### @zeit/ncc integration
Some of the builders use `@zeit/ncc` to bundle files before deployment. If you suspect an error with the bundling mechanism, you can run the `ncc` CLI with a couple modifications to the test.
For example if an error occurred in `now-node/test/fixtures/08-assets`
This will compile the test with the specific version of `ncc` and run the resulting file. If it fails here, then there is likely a bug in `ncc` and not the Builder.
The following page is a reference for how to create a Builder using the available Builder's 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.
See the [Builders Documentation](https://zeit.co/docs/v2/advanced/builders) to view example usage.
## Builder Exports
### `version`
A **required** exported constant that decides which version of the Builder API to use.
The latest and suggested version is `2`.
### `analyze`
An **optional** exported function that returns a unique fingerprint used for the purpose of [build de-duplication](https://zeit.co/docs/v2/advanced/concepts/immutability#deduplication-algorithm). If the `analyze` function is not supplied, a random fingerprint is assigned to each build.
```js
exportanalyze({
files:Files,
entrypoint:String,
workPath:String,
config:Object
}):Stringfingerprint
```
If you are using TypeScript, you should use the following types:
```ts
import{AnalyzeOptions}from'@now/build-utils'
exportanalyze(options: AnalyzeOptions){
return'fingerprint goes here'
}
```
### `build`
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).
What's a Serverless Function? Read about [Serverless Function concepts](https://zeit.co/docs/v2/deployments/concepts/lambdas) to learn more.
```js
build({
files:Files,
entrypoint:String,
workPath:String,
config:Object,
meta?:{
isDev?:Boolean,
requestPath?:String,
filesChanged?:Array<String>,
filesRemoved?:Array<String>
}
}):{
watch:Array<String>,
output:Filesoutput,
routes:Object
}
```
If you are using TypeScript, you should use the following types:
```ts
import{BuildOptions}from'@now/build-utils'
exportbuild(options: BuildOptions){
// Build the code here
return{
output:{
'path-to-file':File,
'path-to-lambda':Lambda
},
watch:[],
routes:{}
}
}
```
### `prepareCache`
An **optional** exported function that is equivalent to [`build`](#build), but it executes the instructions necessary to prepare a cache for the next run.
```js
prepareCache({
files:Files,
entrypoint:String,
workPath:String,
cachePath:String,
config:Object
}):FilescacheOutput
```
If you are using TypeScript, you can import the types for each of these functions by using the following:
```ts
import{PrepareCacheOptions}from'@now/build-utils'
exportprepareCache(options: PrepareCacheOptions){
return{'path-to-file':File}
}
```
### `shouldServe`
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.
```js
shouldServe({
entrypoint:String,
files:Files,
config:Object,
requestPath:String,
workPath:String
}):Boolean
```
If you are using TypeScript, you can import the types for each of these functions by using the following:
```ts
import{ShouldServeOptions}from'@now/build-utils'
exportshouldServe(options: ShouldServeOptions){
returnBoolean
}
```
If this method is not defined, Now CLI will default to [this function](https://github.com/zeit/now-builders/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
### Builder Options
The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCache`](#preparecache) receive one argument with the following properties.
**Properties:**
-`files`: All source files of the project as a [Files](#files) data structure.
-`entrypoint`: Name of entrypoint file for this particular build job. Value `files[entrypoint]` is guaranteed to exist and be a valid [File](#files) reference. `entrypoint` is always a discrete file and never a glob, since globs are expanded into separate builds at deployment time.
-`workPath`: A writable temporary directory where you are encouraged to perform your build process. This directory will be populated with the restored cache from the previous run (if any) for [`analyze`](#analyze) and [`build`](#build).
-`cachePath`: A writable temporary directory where you can build a cache for the next run. This is only passed to `prepareCache`.
-`config`: An arbitrary object passed from by the user in the [Build definition](#defining-the-build-step) in `now.json`.
## Example: html-minifier
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.
Our `index.js` file looks as follows:
```js
exports.analyze=function({files,entrypoint}){
returnfiles[entrypoint].digest
}
```
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:
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.
## 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.
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.
If you need to share state between those steps, use the filesystem.
### Directory and Cache Lifecycle
When a new build is created, we pre-populate the `workPath` supplied to `analyze` with the results of the `prepareCache` step of the previous build.
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).
### 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.
### 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`.
## Types
### `Files`
```ts
import{File}from'@now/build-utils'
typeFiles={[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.
When used as an input, the `Files` object will only contain `FileRefs`. When `Files` is an output, it may consist of `Lambda` (Serverless Functions) types as well as `FileRefs`.
An example of a valid output `Files` object is:
```json
{
"index.html":FileRef,
"api/index.js":Lambda
}
```
### `File`
This is an abstract type that can be imported if you are using TypeScript.
```ts
import{File}from'@now/build-utils'
```
Valid `File` types include:
- [`FileRef`](#fileref)
- [`FileFsRef`](#filefsref)
- [`FileBlob`](#fileblob)
### `FileRef`
```ts
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`.
**Properties:**
-`mode : Number` file mode
-`digest : String` a checksum that represents the file
**Methods:**
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileFsRef`
```ts
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.
**Properties:**
-`mode : Number` file mode
-`fsPath : String` the absolute path of the file in file system
**Methods:**
-`static async fromStream({ mode : Number, stream : Stream, fsPath : String }) : FileFsRef` creates an instance of a [FileFsRef](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from `Stream`, placing file at `fsPath` with `mode`
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileBlob`
```ts
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.
**Properties:**
-`mode : Number` file mode
-`data : String | Buffer` the body of the file
**Methods:**
-`static async fromStream({ mode : Number, stream : Stream }) :FileBlob` creates an instance of a [FileBlob](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from [`Stream`](https://nodejs.org/api/stream.html) with `mode`
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `Lambda`
```ts
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).
**Properties:**
-`files : Files` the internal filesystem of the lambda
-`handler : String` path to handler file and (optionally) a function name it exports
-`runtime : LambdaRuntime` the name of the lambda runtime
-`environment : Object` key-value map of handler-related (aside of those passed by user) environment variables
### `LambdaRuntime`
This is an abstract enumeration type that is implemented by one of the following possible `String` values:
-`nodejs10.x`
-`nodejs8.10`
-`go1.x`
-`java-1.8.0-openjdk`
-`python3.6`
-`python2.7`
-`dotnetcore2.1`
-`dotnetcore2.0`
-`dotnetcore1.0`
## 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.
This utility allows you to download the contents of a [`Files`](#files) data structure, therefore creating the filesystem represented in it.
Since `Files` is an abstract way of representing files, you can think of `download` as a way of making that virtual filesystem _real_.
If the **optional**`meta` property is passed (the argument for [build](#build)), only the files that have changed are downloaded. This is decided using `filesRemoved` and `filesChanged` inside that object.
```js
awaitdownload(files,workPath,meta)
```
### `glob`
Signature: `glob() : Files`
```ts
import{glob}from'@now/build-utils'
```
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).
The following trivial example downloads everything to the filesystem, only to return it back (therefore just re-creating the passed-in [`Files`](#files)):
`@now/next` has two modes: `legacy` and `serverless`. You will always want to use the `serverless` mode. `legacy` is to provide backwards compatibility with previous `@now/next` versions.
The differences:
Legacy:
- Minimal lambda size of `2.2Mb` (approximately)
- Forces `next@v7.0.2-canary.49` and `next-server@v7.0.2-canary.49`
- Forces all `dependencies` to be `devDependencies`
- Loads `next.config.js` on bootup, breaking sometimes when users didn't use `phases` to load files
- Used `next-server` which is the full Next.js server with routing etc.
- Runs `npm install`
- Runs `npm run now-build`
- Runs `npm install --production` after build
Serverless:
- Minimal lambda size of `49Kb` (approximately)
- Uses Next.js build targets (`target: 'serverless'`) in `next.config.js`. [documentation](https://github.com/zeit/next.js#summary)
- Does not make changes to your application dependencies
- Does not load `next.config.js` ([as per the serverless target documentation](https://github.com/zeit/next.js#summary))
- Runs `npm install`
- Runs `npm run now-build`
- Does not run `npm install --production` as the output from the build is all that's needed to bundle lambdas.
- No runtime dependencies, meaning smaller lambda functions
- Optimized for fast [cold start](https://zeit.co/blog/serverless-ssr#cold-start)
#### Possible Ways to Fix It
In order to create the smallest possible lambdas Next.js has to be configured to build for the `serverless` target.
1. Serverless Next.js requires Next.js 8 or later, to upgrade you can install the `latest` version:
```
npm install next --save
```
2. Add the `now-build` script to your `package.json`
```json
{
"scripts":{
"now-build":"next build"
}
}
```
3. Add `target: 'serverless'` to `next.config.js`
```js
module.exports={
target:'serverless',
// Other options are still valid
};
```
4. Optionally make sure the `"src"` in `"builds"` points to your application `package.json`
# `@now/static-build` Failed to detect a server running
#### Why This Warning Occurred
When running `now dev`, the `@now/static-build` builder proxies relevant HTTP
requests to the server that is created by the `now-dev` script in the
`package.json` file.
In order for `now dev` to know which port the server is running on, the builder
is provided a `$PORT` environment variable that the server _must_ bind to. The
error "Failed to detect a server running on port" is printed if the builder fails
to detect a server listening on that specific port within five minutes.
#### Possible Ways to Fix It
Please ensure that your `now-dev` script binds the spawned development server on
the provided `$PORT` that the builder expects the server to bind to.
For example, if you are using Gatsby, your `now-dev` script must use the `-p`
(port) option to bind to the `$PORT` specified from the builder:
```
{
...
"scripts": {
...
"now-dev": "gatsby develop -p $PORT"
}
}
```
Consult your static builder program's `--help` or documentation to figure out what
the command line flag to bind to a specific port is (in many cases, it is one of:
`-p` / `-P` / `--port`).
### Useful Links
- [`@now/static-build` Local Development Documentation](https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build#local-development)
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.