mirror of
https://github.com/LukeHagar/vercel.git
synced 2025-12-11 12:57:46 +00:00
Compare commits
25 Commits
@vercel/py
...
@vercel/py
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e829ce47c3 | ||
|
|
474770e9b0 | ||
|
|
e762d8d4e8 | ||
|
|
6e8935883b | ||
|
|
1c3497dc74 | ||
|
|
9836fdb5ca | ||
|
|
d6f88f019f | ||
|
|
0f720472c4 | ||
|
|
8d0c5114e4 | ||
|
|
e3c4435606 | ||
|
|
234c4dfa84 | ||
|
|
acd756436c | ||
|
|
f26858b735 | ||
|
|
623e43f865 | ||
|
|
3e696513a2 | ||
|
|
285f62c9d0 | ||
|
|
c43db1788c | ||
|
|
fc2eb1a30d | ||
|
|
ecf194b7c1 | ||
|
|
c14e5689f1 | ||
|
|
54dfe747e2 | ||
|
|
2afc8db8e7 | ||
|
|
cc628dd9fb | ||
|
|
dfb6ef949b | ||
|
|
cd4799b5d5 |
@@ -19,6 +19,10 @@ packages/cli/src/util/dev/templates/*.ts
|
||||
packages/client/tests/fixtures
|
||||
packages/client/lib
|
||||
|
||||
# next
|
||||
packages/next/test/integration/middleware
|
||||
packages/next/test/integration/middleware-eval
|
||||
|
||||
# node-bridge
|
||||
packages/node-bridge/bridge.js
|
||||
packages/node-bridge/launcher.js
|
||||
|
||||
39
.github/CODEOWNERS
vendored
39
.github/CODEOWNERS
vendored
@@ -1,29 +1,26 @@
|
||||
# Documentation
|
||||
# https://help.github.com/en/articles/about-code-owners
|
||||
|
||||
* @TooTallNate
|
||||
/.github/workflows @AndyBitz @styfle
|
||||
/packages/frameworks @AndyBitz
|
||||
/packages/cli/src/commands/build @TooTallNate @styfle @AndyBitz @gdborton @jaredpalmer
|
||||
/packages/cli/src/commands/dev @TooTallNate @styfle @AndyBitz
|
||||
/packages/cli/src/util/dev @TooTallNate @styfle @AndyBitz
|
||||
* @TooTallNate @EndangeredMassa @styfle
|
||||
/.github/workflows @TooTallNate @EndangeredMassa @styfle @ijjk
|
||||
/packages/frameworks @TooTallNate @EndangeredMassa @styfle @AndyBitz
|
||||
/packages/cli/src/commands/domains @javivelasco @mglagola @anatrajkovska
|
||||
/packages/cli/src/commands/certs @javivelasco @mglagola @anatrajkovska
|
||||
/packages/cli/src/commands/env @styfle @lucleray
|
||||
/packages/client @styfle @TooTallNate
|
||||
/packages/build-utils @styfle @AndyBitz @TooTallNate
|
||||
/packages/client @TooTallNate @EndangeredMassa @styfle
|
||||
/packages/build-utils @TooTallNate @EndangeredMassa @styfle @AndyBitz
|
||||
/packages/middleware @gdborton @javivelasco
|
||||
/packages/node @styfle @TooTallNate @lucleray
|
||||
/packages/node-bridge @styfle @TooTallNate @lucleray
|
||||
/packages/next @Timer @ijjk
|
||||
/packages/go @styfle @TooTallNate
|
||||
/packages/python @styfle @TooTallNate
|
||||
/packages/ruby @styfle @TooTallNate
|
||||
/packages/static-build @styfle @AndyBitz
|
||||
/packages/routing-utils @styfle @dav-is @ijjk
|
||||
/examples @mcsdevv
|
||||
/packages/node @TooTallNate @EndangeredMassa @styfle
|
||||
/packages/node-bridge @TooTallNate @EndangeredMassa @styfle @ijjk
|
||||
/packages/next @TooTallNate @ijjk
|
||||
/packages/go @TooTallNate @EndangeredMassa @styfle
|
||||
/packages/python @TooTallNate @EndangeredMassa @styfle
|
||||
/packages/ruby @TooTallNate @EndangeredMassa @styfle
|
||||
/packages/static-build @TooTallNate @EndangeredMassa @styfle @AndyBitz
|
||||
/packages/routing-utils @TooTallNate @EndangeredMassa @styfle @ijjk
|
||||
/examples @leerob
|
||||
/examples/create-react-app @Timer
|
||||
/examples/nextjs @timneutkens @Timer
|
||||
/examples/hugo @mcsdevv @styfle
|
||||
/examples/jekyll @mcsdevv @styfle
|
||||
/examples/zola @mcsdevv @styfle
|
||||
/examples/nextjs @timneutkens @ijjk @styfle
|
||||
/examples/hugo @styfle
|
||||
/examples/jekyll @styfle
|
||||
/examples/zola @styfle
|
||||
|
||||
3
.github/workflows/cancel.yml
vendored
3
.github/workflows/cancel.yml
vendored
@@ -13,6 +13,5 @@ jobs:
|
||||
steps:
|
||||
- uses: styfle/cancel-workflow-action@0.9.1
|
||||
with:
|
||||
workflow_id: 849295, 849296, 849297, 849298
|
||||
workflow_id: test.yml, test-integration-cli.yml, test-unit.yml
|
||||
access_token: ${{ github.token }}
|
||||
|
||||
|
||||
4
.github/workflows/test-integration-cli.yml
vendored
4
.github/workflows/test-integration-cli.yml
vendored
@@ -18,6 +18,10 @@ jobs:
|
||||
os: [ubuntu-latest]
|
||||
node: [12]
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
TURBO_REMOTE_ONLY: true
|
||||
TURBO_TEAM: vercel
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
|
||||
43
.github/workflows/test-integration-dev.yml
vendored
43
.github/workflows/test-integration-dev.yml
vendored
@@ -1,43 +0,0 @@
|
||||
name: Dev
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- '!*'
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Dev
|
||||
timeout-minutes: 75
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
node: [12]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '1.13.15'
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 100
|
||||
- run: git --version
|
||||
- run: git fetch origin main --depth=100
|
||||
- run: git fetch origin ${{ github.ref }} --depth=100
|
||||
- run: git diff origin/main...HEAD --name-only
|
||||
- name: Install Hugo
|
||||
if: matrix.os == 'macos-latest'
|
||||
run: curl -L -O https://github.com/gohugoio/hugo/releases/download/v0.56.0/hugo_0.56.0_macOS-64bit.tar.gz && tar -xzf hugo_0.56.0_macOS-64bit.tar.gz && mv ./hugo packages/cli/test/dev/fixtures/08-hugo/
|
||||
- run: yarn install --network-timeout 1000000
|
||||
- run: yarn run build
|
||||
- run: yarn test-integration-dev
|
||||
env:
|
||||
VERCEL_TEAM_TOKEN: ${{ secrets.VERCEL_TEAM_TOKEN }}
|
||||
VERCEL_REGISTRATION_URL: ${{ secrets.VERCEL_REGISTRATION_URL }}
|
||||
35
.github/workflows/test-integration-once.yml
vendored
35
.github/workflows/test-integration-once.yml
vendored
@@ -1,35 +0,0 @@
|
||||
name: E2E
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- '!*'
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: E2E
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '1.13.15'
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 12
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 100
|
||||
- run: git --version
|
||||
- run: git fetch origin main --depth=100
|
||||
- run: git fetch origin ${{ github.ref }} --depth=100
|
||||
- run: git diff origin/main...HEAD --name-only
|
||||
- run: yarn install --network-timeout 1000000
|
||||
- run: yarn run build
|
||||
- run: yarn test-integration-once
|
||||
env:
|
||||
VERCEL_TEAM_TOKEN: ${{ secrets.VERCEL_TEAM_TOKEN }}
|
||||
VERCEL_REGISTRATION_URL: ${{ secrets.VERCEL_REGISTRATION_URL }}
|
||||
12
.github/workflows/test-unit.yml
vendored
12
.github/workflows/test-unit.yml
vendored
@@ -16,8 +16,12 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
node: [12]
|
||||
node: [14]
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
TURBO_REMOTE_ONLY: true
|
||||
TURBO_TEAM: vercel
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
@@ -35,9 +39,9 @@ jobs:
|
||||
- run: yarn install --network-timeout 1000000
|
||||
- run: yarn run build
|
||||
- run: yarn run lint
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node == 12 # only run lint once
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node == 14 # only run lint once
|
||||
- run: yarn run test-unit
|
||||
- run: yarn workspace vercel run coverage
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node == 12 # only run coverage once
|
||||
if: matrix.os == 'ubuntu-latest' && matrix.node == 14 # only run coverage once
|
||||
env:
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
88
.github/workflows/test.yml
vendored
Normal file
88
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- '!*'
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
NODE_VERSION: '14'
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
name: Find Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tests: ${{ steps['set-tests'].outputs['tests'] }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: git --version
|
||||
- run: git fetch origin main
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
cache: 'yarn'
|
||||
- run: yarn install --network-timeout 1000000
|
||||
- id: set-tests
|
||||
run: |
|
||||
TESTS_ARRAY=$(node utils/chunk-tests.js $SCRIPT_NAME)
|
||||
echo "Files to test:"
|
||||
echo "$TESTS_ARRAY"
|
||||
echo "::set-output name=tests::$TESTS_ARRAY"
|
||||
|
||||
test:
|
||||
timeout-minutes: 120
|
||||
runs-on: ${{ matrix.runner }}
|
||||
name: ${{matrix.scriptName}} (${{matrix.packageName}}, ${{matrix.chunkNumber}}, ${{ matrix.runner }})
|
||||
if: ${{ needs.setup.outputs['tests'] != '[]' }}
|
||||
env:
|
||||
TURBO_REMOTE_ONLY: true
|
||||
TURBO_TEAM: vercel
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
needs:
|
||||
- setup
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJson(needs.setup.outputs['tests']) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '1.13.15'
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
cache: 'yarn'
|
||||
|
||||
- name: Install Hugo
|
||||
if: matrix.runner == 'macos-latest'
|
||||
run: curl -L -O https://github.com/gohugoio/hugo/releases/download/v0.56.0/hugo_0.56.0_macOS-64bit.tar.gz && tar -xzf hugo_0.56.0_macOS-64bit.tar.gz && mv ./hugo packages/cli/test/dev/fixtures/08-hugo/
|
||||
|
||||
- run: yarn install --network-timeout 1000000
|
||||
|
||||
- name: Build ${{matrix.packageName}} and all its dependencies
|
||||
run: yarn turbo run build --cache-dir=".turbo" --scope=${{matrix.packageName}} --include-dependencies --no-deps
|
||||
env:
|
||||
FORCE_COLOR: '1'
|
||||
- name: Test ${{matrix.packageName}}
|
||||
run: node_modules/.bin/turbo run test --cache-dir=".turbo" --scope=${{matrix.packageName}} --no-deps -- ${{ join(matrix.testPaths, ' ') }}
|
||||
shell: bash
|
||||
env:
|
||||
VERCEL_TEAM_TOKEN: ${{ secrets.VERCEL_TEAM_TOKEN }}
|
||||
VERCEL_REGISTRATION_URL: ${{ secrets.VERCEL_REGISTRATION_URL }}
|
||||
FORCE_COLOR: '1'
|
||||
|
||||
conclusion:
|
||||
needs:
|
||||
- test
|
||||
runs-on: ubuntu-latest
|
||||
name: E2E
|
||||
steps:
|
||||
- name: Done
|
||||
run: echo "Done."
|
||||
@@ -2,3 +2,4 @@ README.md
|
||||
.nuxt
|
||||
node_modules
|
||||
*.log
|
||||
.output
|
||||
|
||||
1
examples/solidstart/.gitignore
vendored
1
examples/solidstart/.gitignore
vendored
@@ -2,7 +2,6 @@ dist
|
||||
worker
|
||||
.solid
|
||||
.vercel
|
||||
.output
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SolidStart
|
||||
|
||||
This directory is a brief example of a [SolidStart](https://github.com/ryansolid/solid-startp) site that can be deployed to Vercel with zero configuration.
|
||||
This directory is a brief example of a [SolidStart](https://github.com/ryansolid/solid-start) site that can be deployed to Vercel with zero configuration.
|
||||
|
||||
## Deploy Your Own
|
||||
|
||||
|
||||
10
package.json
10
package.json
@@ -31,7 +31,7 @@
|
||||
"prettier": "2.6.2",
|
||||
"ts-eager": "2.0.2",
|
||||
"ts-jest": "28.0.0-next.1",
|
||||
"turbo": "1.2.5"
|
||||
"turbo": "1.2.9"
|
||||
},
|
||||
"scripts": {
|
||||
"lerna": "lerna",
|
||||
@@ -44,10 +44,10 @@
|
||||
"vercel-build": "yarn build && cd api && node -r ts-eager/register ./_lib/script/build.ts",
|
||||
"pre-commit": "lint-staged",
|
||||
"test": "jest --rootDir=\"test\" --testPathPattern=\"\\.test.js\"",
|
||||
"test-unit": "yarn test && node utils/run.js test-unit",
|
||||
"test-integration-cli": "node utils/run.js test-integration-cli",
|
||||
"test-integration-once": "node utils/run.js test-integration-once",
|
||||
"test-integration-dev": "node utils/run.js test-integration-dev",
|
||||
"test-unit": "yarn test && turbo run test-unit",
|
||||
"test-integration-cli": "turbo run test-integration-cli",
|
||||
"test-integration-once": "turbo run test-integration-once",
|
||||
"test-integration-dev": "turbo run test-integration-dev",
|
||||
"lint": "eslint . --ext .ts,.js",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/build-utils",
|
||||
"version": "3.0.1",
|
||||
"version": "3.1.1-canary.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.js",
|
||||
@@ -12,8 +12,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node build",
|
||||
"test-unit": "jest --env node --verbose --runInBand --bail test/unit.*test.*",
|
||||
"test-integration-once": "jest --env node --verbose --runInBand --bail test/integration.test.ts",
|
||||
"test": "jest --env node --verbose --runInBand --bail",
|
||||
"test-unit": "yarn test test/unit.*test.*",
|
||||
"test-integration-once": "yarn test test/integration.test.ts",
|
||||
"prepublishOnly": "node build"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -30,7 +31,7 @@
|
||||
"@types/node-fetch": "^2.1.6",
|
||||
"@types/semver": "6.0.0",
|
||||
"@types/yazl": "2.4.2",
|
||||
"@vercel/frameworks": "0.9.0",
|
||||
"@vercel/frameworks": "0.9.1",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"aggregate-error": "3.0.1",
|
||||
"async-retry": "1.2.3",
|
||||
|
||||
@@ -6,7 +6,12 @@ import debug from '../debug';
|
||||
const allOptions = [
|
||||
{ major: 16, range: '16.x', runtime: 'nodejs16.x' },
|
||||
{ major: 14, range: '14.x', runtime: 'nodejs14.x' },
|
||||
{ major: 12, range: '12.x', runtime: 'nodejs12.x' },
|
||||
{
|
||||
major: 12,
|
||||
range: '12.x',
|
||||
runtime: 'nodejs12.x',
|
||||
discontinueDate: new Date('2022-08-09'),
|
||||
},
|
||||
{
|
||||
major: 10,
|
||||
range: '10.x',
|
||||
|
||||
@@ -327,6 +327,7 @@ export interface ProjectSettings {
|
||||
buildCommand?: string | null;
|
||||
outputDirectory?: string | null;
|
||||
rootDirectory?: string | null;
|
||||
nodeVersion?: string;
|
||||
createdAt?: number;
|
||||
autoExposeSystemEnvs?: boolean;
|
||||
sourceFilesOutsideRootDirectory?: boolean;
|
||||
|
||||
21
packages/build-utils/test/unit.test.ts
vendored
21
packages/build-utils/test/unit.test.ts
vendored
@@ -296,17 +296,20 @@ it('should get latest node version', async () => {
|
||||
it('should throw for discontinued versions', async () => {
|
||||
// Mock a future date so that Node 8 and 10 become discontinued
|
||||
const realDateNow = Date.now.bind(global.Date);
|
||||
global.Date.now = () => new Date('2021-05-01').getTime();
|
||||
global.Date.now = () => new Date('2022-09-01').getTime();
|
||||
|
||||
expect(getSupportedNodeVersion('8.10.x', false)).rejects.toThrow();
|
||||
expect(getSupportedNodeVersion('8.10.x', true)).rejects.toThrow();
|
||||
expect(getSupportedNodeVersion('10.x', false)).rejects.toThrow();
|
||||
expect(getSupportedNodeVersion('10.x', true)).rejects.toThrow();
|
||||
expect(getSupportedNodeVersion('12.x', false)).rejects.toThrow();
|
||||
expect(getSupportedNodeVersion('12.x', true)).rejects.toThrow();
|
||||
|
||||
const discontinued = getDiscontinuedNodeVersions();
|
||||
expect(discontinued.length).toBe(2);
|
||||
expect(discontinued[0]).toHaveProperty('range', '10.x');
|
||||
expect(discontinued[1]).toHaveProperty('range', '8.10.x');
|
||||
expect(discontinued.length).toBe(3);
|
||||
expect(discontinued[0]).toHaveProperty('range', '12.x');
|
||||
expect(discontinued[1]).toHaveProperty('range', '10.x');
|
||||
expect(discontinued[2]).toHaveProperty('range', '8.10.x');
|
||||
|
||||
global.Date.now = realDateNow;
|
||||
});
|
||||
@@ -324,9 +327,19 @@ it('should warn for deprecated versions, soon to be discontinued', async () => {
|
||||
'major',
|
||||
10
|
||||
);
|
||||
expect(await getSupportedNodeVersion('12.x', false)).toHaveProperty(
|
||||
'major',
|
||||
12
|
||||
);
|
||||
expect(await getSupportedNodeVersion('12.x', true)).toHaveProperty(
|
||||
'major',
|
||||
12
|
||||
);
|
||||
expect(warningMessages).toStrictEqual([
|
||||
'Error: Node.js version 10.x is deprecated. Deployments created on or after 2021-04-20 will fail to build. Please set "engines": { "node": "16.x" } in your `package.json` file to use Node.js 16. This change is the result of a decision made by an upstream infrastructure provider (AWS).',
|
||||
'Error: Node.js version 10.x is deprecated. Deployments created on or after 2021-04-20 will fail to build. Please set Node.js Version to 16.x in your Project Settings to use Node.js 16. This change is the result of a decision made by an upstream infrastructure provider (AWS).',
|
||||
'Error: Node.js version 12.x is deprecated. Deployments created on or after 2022-08-09 will fail to build. Please set "engines": { "node": "16.x" } in your `package.json` file to use Node.js 16. This change is the result of a decision made by an upstream infrastructure provider (AWS).',
|
||||
'Error: Node.js version 12.x is deprecated. Deployments created on or after 2022-08-09 will fail to build. Please set Node.js Version to 16.x in your Project Settings to use Node.js 16. This change is the result of a decision made by an upstream infrastructure provider (AWS).',
|
||||
]);
|
||||
|
||||
global.Date.now = realDateNow;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vercel",
|
||||
"version": "24.2.2",
|
||||
"version": "24.2.5-canary.0",
|
||||
"preferGlobal": true,
|
||||
"license": "Apache-2.0",
|
||||
"description": "The command-line interface for Vercel",
|
||||
@@ -12,10 +12,10 @@
|
||||
},
|
||||
"scripts": {
|
||||
"preinstall": "node ./scripts/preinstall.js",
|
||||
"test": "jest",
|
||||
"test-unit": "jest --coverage --verbose",
|
||||
"test": "jest --env node --verbose --runInBand --bail --forceExit",
|
||||
"test-unit": "yarn test test/unit/",
|
||||
"test-integration-cli": "rimraf test/fixtures/integration && ava test/integration.js --serial --fail-fast --verbose",
|
||||
"test-integration-dev": "ava test/dev/integration.js --serial --fail-fast --verbose",
|
||||
"test-integration-dev": "yarn test test/dev/",
|
||||
"prepublishOnly": "yarn build",
|
||||
"coverage": "codecov",
|
||||
"build": "node -r ts-eager/register ./scripts/build.ts",
|
||||
@@ -43,11 +43,15 @@
|
||||
"node": ">= 12"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/build-utils": "3.0.1",
|
||||
"@vercel/go": "1.4.2",
|
||||
"@vercel/node": "1.15.2",
|
||||
"@vercel/python": "2.3.2",
|
||||
"@vercel/ruby": "1.3.5",
|
||||
"@vercel/build-utils": "3.1.1-canary.0",
|
||||
"@vercel/go": "1.4.4-canary.0",
|
||||
"@vercel/next": "2.8.67-canary.0",
|
||||
"@vercel/node": "1.15.4-canary.0",
|
||||
"@vercel/python": "2.3.4-canary.0",
|
||||
"@vercel/redwood": "0.8.4-canary.0",
|
||||
"@vercel/remix": "0.0.2-canary.0",
|
||||
"@vercel/ruby": "1.3.7-canary.0",
|
||||
"@vercel/static-build": "0.25.3-canary.0",
|
||||
"update-notifier": "4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -90,8 +94,9 @@
|
||||
"@types/update-notifier": "5.1.0",
|
||||
"@types/which": "1.3.2",
|
||||
"@types/write-json-file": "2.2.1",
|
||||
"@vercel/client": "11.0.2",
|
||||
"@vercel/frameworks": "0.9.0",
|
||||
"@types/yauzl-promise": "2.1.0",
|
||||
"@vercel/client": "11.0.4-canary.0",
|
||||
"@vercel/frameworks": "0.9.1",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"@zeit/fun": "0.11.2",
|
||||
"@zeit/source-map-support": "0.6.2",
|
||||
@@ -167,7 +172,8 @@
|
||||
"utility-types": "2.1.0",
|
||||
"which": "2.0.2",
|
||||
"write-json-file": "2.2.0",
|
||||
"xdg-app-paths": "5.1.0"
|
||||
"xdg-app-paths": "5.1.0",
|
||||
"yauzl-promise": "2.1.3"
|
||||
},
|
||||
"jest": {
|
||||
"preset": "ts-jest",
|
||||
|
||||
@@ -13,7 +13,7 @@ async function createConstants() {
|
||||
export const GA_TRACKING_ID: string | undefined = ${envToString(
|
||||
'GA_TRACKING_ID'
|
||||
)};
|
||||
export const SENTRY_DSN: string | undefined = ${envToString('SENTRY_DSN')};
|
||||
export const SENTRY_DSN: string | undefined = ${envToString('SENTRY_DSN')};
|
||||
`;
|
||||
await writeFile(filename, contents, 'utf8');
|
||||
}
|
||||
|
||||
502
packages/cli/src/commands/build.ts
Normal file
502
packages/cli/src/commands/build.ts
Normal file
@@ -0,0 +1,502 @@
|
||||
import fs from 'fs-extra';
|
||||
import chalk from 'chalk';
|
||||
import dotenv from 'dotenv';
|
||||
import { join, relative } from 'path';
|
||||
import {
|
||||
detectBuilders,
|
||||
Files,
|
||||
FileFsRef,
|
||||
PackageJson,
|
||||
BuildOptions,
|
||||
Config,
|
||||
Meta,
|
||||
Builder,
|
||||
BuildResultV2,
|
||||
BuildResultV2Typical,
|
||||
BuildResultV3,
|
||||
} from '@vercel/build-utils';
|
||||
import minimatch from 'minimatch';
|
||||
import {
|
||||
appendRoutesToPhase,
|
||||
getTransformedRoutes,
|
||||
mergeRoutes,
|
||||
MergeRoutesProps,
|
||||
Route,
|
||||
} from '@vercel/routing-utils';
|
||||
import { VercelConfig } from '@vercel/client';
|
||||
|
||||
import pull from './pull';
|
||||
import { staticFiles as getFiles } from '../util/get-files';
|
||||
import Client from '../util/client';
|
||||
import getArgs from '../util/get-args';
|
||||
import cmd from '../util/output/cmd';
|
||||
import * as cli from '../util/pkg-name';
|
||||
import cliPkg from '../util/pkg';
|
||||
import readJSONFile from '../util/read-json-file';
|
||||
import { CantParseJSONFile } from '../util/errors-ts';
|
||||
import { readProjectSettings } from '../util/projects/project-settings';
|
||||
import { VERCEL_DIR } from '../util/projects/link';
|
||||
import confirm from '../util/input/confirm';
|
||||
import { emoji, prependEmoji } from '../util/emoji';
|
||||
import stamp from '../util/output/stamp';
|
||||
import {
|
||||
OUTPUT_DIR,
|
||||
PathOverride,
|
||||
writeBuildResult,
|
||||
} from '../util/build/write-build-result';
|
||||
import { importBuilders } from '../util/build/import-builders';
|
||||
|
||||
type BuildResult = BuildResultV2 | BuildResultV3;
|
||||
|
||||
const help = () => {
|
||||
return console.log(`
|
||||
${chalk.bold(`${cli.logo} ${cli.name} build`)}
|
||||
|
||||
${chalk.dim('Options:')}
|
||||
|
||||
-h, --help Output usage information
|
||||
-A ${chalk.bold.underline('FILE')}, --local-config=${chalk.bold.underline(
|
||||
'FILE'
|
||||
)} Path to the local ${'`vercel.json`'} file
|
||||
-Q ${chalk.bold.underline('DIR')}, --global-config=${chalk.bold.underline(
|
||||
'DIR'
|
||||
)} Path to the global ${'`.vercel`'} directory
|
||||
--cwd [path] The current working directory
|
||||
--prod Build a production deployment
|
||||
-d, --debug Debug mode [off]
|
||||
-y, --yes Skip the confirmation prompt
|
||||
|
||||
${chalk.dim('Examples:')}
|
||||
|
||||
${chalk.gray('–')} Build the project
|
||||
|
||||
${chalk.cyan(`$ ${cli.name} build`)}
|
||||
${chalk.cyan(`$ ${cli.name} build --cwd ./path-to-project`)}
|
||||
`);
|
||||
};
|
||||
|
||||
export default async function main(client: Client): Promise<number> {
|
||||
const { output } = client;
|
||||
|
||||
// Ensure that `vc build` is not being invoked recursively
|
||||
if (process.env.__VERCEL_BUILD_RUNNING) {
|
||||
output.error(
|
||||
`${cmd(
|
||||
`${cli.name} build`
|
||||
)} must not recursively invoke itself. Check the Build Command in the Project Settings or the ${cmd(
|
||||
'build'
|
||||
)} script in ${cmd('package.json')}`
|
||||
);
|
||||
output.error(
|
||||
`Learn More: https://vercel.link/recursive-invocation-of-commands`
|
||||
);
|
||||
return 1;
|
||||
} else {
|
||||
process.env.__VERCEL_BUILD_RUNNING = '1';
|
||||
}
|
||||
|
||||
// Parse CLI args
|
||||
const argv = getArgs(client.argv.slice(2), {
|
||||
'--cwd': String,
|
||||
'--prod': Boolean,
|
||||
});
|
||||
|
||||
if (argv['--help']) {
|
||||
help();
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Set the working directory if necessary
|
||||
if (argv['--cwd']) {
|
||||
process.chdir(argv['--cwd']);
|
||||
}
|
||||
const cwd = process.cwd();
|
||||
|
||||
// TODO: read project settings from the API, fall back to local `project.json` if that fails
|
||||
|
||||
// Read project settings, and pull them from Vercel if necessary
|
||||
let project = await readProjectSettings(join(cwd, VERCEL_DIR));
|
||||
const isTTY = process.stdin.isTTY;
|
||||
while (!project?.settings) {
|
||||
if (!isTTY) {
|
||||
client.output.print(
|
||||
`No Project Settings found locally. Run ${cli.getCommandName(
|
||||
'pull --yes'
|
||||
)} to retreive them.`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const confirmed = await confirm(
|
||||
`No Project Settings found locally. Run ${cli.getCommandName(
|
||||
'pull'
|
||||
)} for retrieving them?`,
|
||||
true
|
||||
);
|
||||
if (!confirmed) {
|
||||
client.output.print(`Aborted. No Project Settings retrieved.\n`);
|
||||
return 0;
|
||||
}
|
||||
client.argv = [];
|
||||
const result = await pull(client);
|
||||
if (result !== 0) {
|
||||
return result;
|
||||
}
|
||||
project = await readProjectSettings(join(cwd, VERCEL_DIR));
|
||||
}
|
||||
|
||||
// Build `target` influences which environment variables will be used
|
||||
const target = argv['--prod'] ? 'production' : 'preview';
|
||||
|
||||
// TODO: load env vars from the API, fall back to local files if that fails
|
||||
|
||||
const envPath = await checkExists([
|
||||
join(cwd, VERCEL_DIR, `.env.${target}.local`),
|
||||
join(cwd, `.env`),
|
||||
]);
|
||||
if (envPath) {
|
||||
dotenv.config({ path: envPath, debug: client.output.isDebugEnabled() });
|
||||
output.log(`Loaded env from "${relative(cwd, envPath)}"`);
|
||||
}
|
||||
|
||||
// Some build processes use this env var to platform detect Vercel
|
||||
process.env.NOW_BUILDER = '1';
|
||||
|
||||
const workPath = join(cwd, project.settings.rootDirectory || '.');
|
||||
|
||||
// Load `package.json` and `vercel.json` files
|
||||
const [pkg, vercelConfig] = await Promise.all([
|
||||
readJSONFile<PackageJson>(join(workPath, 'package.json')),
|
||||
readJSONFile<VercelConfig>(join(workPath, 'vercel.json')).then(
|
||||
config => config || readJSONFile<VercelConfig>(join(workPath, 'now.json'))
|
||||
),
|
||||
]);
|
||||
if (pkg instanceof CantParseJSONFile) throw pkg;
|
||||
if (vercelConfig instanceof CantParseJSONFile) throw vercelConfig;
|
||||
|
||||
// Get a list of source files
|
||||
const files = (await getFiles(workPath, client)).map(f =>
|
||||
relative(workPath, f)
|
||||
);
|
||||
|
||||
const routesResult = getTransformedRoutes({ nowConfig: vercelConfig || {} });
|
||||
if (routesResult.error) {
|
||||
output.prettyError(routesResult.error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (vercelConfig?.builds && vercelConfig.functions) {
|
||||
output.prettyError({
|
||||
message:
|
||||
'The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.',
|
||||
link: 'https://vercel.link/functions-and-builds',
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
|
||||
let builds = vercelConfig?.builds || [];
|
||||
let zeroConfigRoutes: Route[] = [];
|
||||
|
||||
if (builds.length > 0) {
|
||||
output.warn(
|
||||
'Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings'
|
||||
);
|
||||
builds = builds.map(b => expandBuild(files, b)).flat();
|
||||
} else {
|
||||
// Zero config
|
||||
|
||||
// Detect the Vercel Builders that will need to be invoked
|
||||
const detectedBuilders = await detectBuilders(files, pkg, {
|
||||
...vercelConfig,
|
||||
projectSettings: project.settings,
|
||||
featHandleMiss: true,
|
||||
});
|
||||
|
||||
if (detectedBuilders.errors && detectedBuilders.errors.length > 0) {
|
||||
output.prettyError(detectedBuilders.errors[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (const w of detectedBuilders.warnings) {
|
||||
console.log(
|
||||
`Warning: ${w.message} ${w.action || 'Learn More'}: ${w.link}`
|
||||
);
|
||||
}
|
||||
|
||||
if (detectedBuilders.builders) {
|
||||
builds = detectedBuilders.builders;
|
||||
} else {
|
||||
builds = [{ src: '**', use: '@vercel/static' }];
|
||||
}
|
||||
|
||||
zeroConfigRoutes.push(...(detectedBuilders.redirectRoutes || []));
|
||||
zeroConfigRoutes.push(
|
||||
...appendRoutesToPhase({
|
||||
routes: [],
|
||||
newRoutes: detectedBuilders.rewriteRoutes,
|
||||
phase: 'filesystem',
|
||||
})
|
||||
);
|
||||
zeroConfigRoutes = appendRoutesToPhase({
|
||||
routes: zeroConfigRoutes,
|
||||
newRoutes: detectedBuilders.errorRoutes,
|
||||
phase: 'error',
|
||||
});
|
||||
zeroConfigRoutes.push(...(detectedBuilders.defaultRoutes || []));
|
||||
}
|
||||
|
||||
const builderSpecs = new Set(builds.map(b => b.use));
|
||||
const buildersWithPkgs = await importBuilders(builderSpecs, cwd, output);
|
||||
|
||||
// Populate Files -> FileFsRef mapping
|
||||
const filesMap: Files = {};
|
||||
for (const path of files) {
|
||||
const fsPath = join(workPath, path);
|
||||
const { mode } = await fs.stat(fsPath);
|
||||
filesMap[path] = new FileFsRef({ mode, fsPath });
|
||||
}
|
||||
|
||||
// Delete output directory from potential previous build
|
||||
await fs.remove(OUTPUT_DIR);
|
||||
|
||||
const buildStamp = stamp();
|
||||
|
||||
// Create fresh new output directory
|
||||
await fs.mkdirp(OUTPUT_DIR);
|
||||
|
||||
const ops: Promise<Error | void>[] = [];
|
||||
|
||||
// Write the `detectedBuilders` result to output dir
|
||||
ops.push(
|
||||
fs.writeJSON(
|
||||
join(OUTPUT_DIR, 'builds.json'),
|
||||
{
|
||||
'//': 'This file was generated by the `vercel build` command. It is not part of the Build Output API.',
|
||||
target,
|
||||
builds: builds.map(build => {
|
||||
const builderWithPkg = buildersWithPkgs.get(build.use);
|
||||
if (!builderWithPkg) {
|
||||
throw new Error(`Failed to load Builder "${build.use}"`);
|
||||
}
|
||||
const { builder, pkg: builderPkg } = builderWithPkg;
|
||||
return {
|
||||
require: builderPkg.name,
|
||||
apiVersion: builder.version,
|
||||
...build,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
spaces: 2,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// The `meta` config property is re-used for each Builder
|
||||
// invocation so that Builders can share state between
|
||||
// subsequent entrypoint builds.
|
||||
const meta: Meta = {
|
||||
skipDownload: true,
|
||||
cliVersion: cliPkg.version,
|
||||
};
|
||||
|
||||
// Execute Builders for detected entrypoints
|
||||
// TODO: parallelize builds
|
||||
const buildResults: Map<Builder, BuildResult> = new Map();
|
||||
const overrides: PathOverride[] = [];
|
||||
for (const build of builds) {
|
||||
if (typeof build.src !== 'string') continue;
|
||||
|
||||
const builderWithPkg = buildersWithPkgs.get(build.use);
|
||||
if (!builderWithPkg) {
|
||||
throw new Error(`Failed to load Builder "${build.use}"`);
|
||||
}
|
||||
const { builder, pkg: builderPkg } = builderWithPkg;
|
||||
|
||||
const buildConfig: Config = {
|
||||
outputDirectory: project.settings.outputDirectory ?? undefined,
|
||||
...build.config,
|
||||
projectSettings: project.settings,
|
||||
installCommand: project.settings.installCommand ?? undefined,
|
||||
devCommand: project.settings.devCommand ?? undefined,
|
||||
buildCommand: project.settings.buildCommand ?? undefined,
|
||||
framework: project.settings.framework,
|
||||
nodeVersion: project.settings.nodeVersion,
|
||||
};
|
||||
const repoRootPath = cwd === workPath ? undefined : cwd;
|
||||
const buildOptions: BuildOptions = {
|
||||
files: filesMap,
|
||||
entrypoint: build.src,
|
||||
workPath,
|
||||
repoRootPath,
|
||||
config: buildConfig,
|
||||
meta,
|
||||
};
|
||||
output.debug(
|
||||
`Building entrypoint "${build.src}" with "${builderPkg.name}"`
|
||||
);
|
||||
const buildResult = await builder.build(buildOptions);
|
||||
|
||||
// Store the build result to generate the final `config.json` after
|
||||
// all builds have completed
|
||||
buildResults.set(build, buildResult);
|
||||
|
||||
// Start flushing the file outputs to the filesystem asynchronously
|
||||
ops.push(
|
||||
writeBuildResult(
|
||||
buildResult,
|
||||
build,
|
||||
builder,
|
||||
builderPkg,
|
||||
vercelConfig?.cleanUrls
|
||||
).then(
|
||||
override => {
|
||||
if (override) overrides.push(override);
|
||||
},
|
||||
err => err
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Wait for filesystem operations to complete
|
||||
// TODO render progress bar?
|
||||
let hadError = false;
|
||||
const errors = await Promise.all(ops);
|
||||
for (const error of errors) {
|
||||
if (error) {
|
||||
hadError = true;
|
||||
output.prettyError(error);
|
||||
}
|
||||
}
|
||||
if (hadError) return 1;
|
||||
|
||||
// Merge existing `config.json` file into the one that will be produced
|
||||
const configPath = join(OUTPUT_DIR, 'config.json');
|
||||
// TODO: properly type
|
||||
const existingConfig = await readJSONFile<any>(configPath);
|
||||
if (existingConfig instanceof CantParseJSONFile) {
|
||||
throw existingConfig;
|
||||
}
|
||||
if (existingConfig) {
|
||||
if (existingConfig.overrides) {
|
||||
overrides.push(existingConfig.overrides);
|
||||
}
|
||||
// Find the `Build` entry for this config file and update the build result
|
||||
for (const [build, buildResult] of buildResults.entries()) {
|
||||
if ('buildOutputPath' in buildResult) {
|
||||
output.debug(`Using "config.json" for "${build.use}`);
|
||||
buildResults.set(build, existingConfig);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const builderRoutes: MergeRoutesProps['builds'] = Array.from(
|
||||
buildResults.entries()
|
||||
)
|
||||
.filter(b => 'routes' in b[1] && Array.isArray(b[1].routes))
|
||||
.map(b => {
|
||||
return {
|
||||
use: b[0].use,
|
||||
entrypoint: b[0].src!,
|
||||
routes: (b[1] as BuildResultV2Typical).routes,
|
||||
};
|
||||
});
|
||||
if (zeroConfigRoutes.length) {
|
||||
builderRoutes.unshift({
|
||||
use: '@vercel/zero-config-routes',
|
||||
entrypoint: '/',
|
||||
routes: zeroConfigRoutes,
|
||||
});
|
||||
}
|
||||
const mergedRoutes = mergeRoutes({
|
||||
userRoutes: routesResult.routes,
|
||||
builds: builderRoutes,
|
||||
});
|
||||
|
||||
const mergedImages = mergeImages(buildResults.values());
|
||||
const mergedWildcard = mergeWildcard(buildResults.values());
|
||||
const mergedOverrides: Record<string, PathOverride> =
|
||||
overrides.length > 0 ? Object.assign({}, ...overrides) : undefined;
|
||||
|
||||
// Write out the final `config.json` file based on the
|
||||
// user configuration and Builder build results
|
||||
// TODO: properly type
|
||||
const config = {
|
||||
version: 3,
|
||||
routes: mergedRoutes,
|
||||
images: mergedImages,
|
||||
wildcard: mergedWildcard,
|
||||
overrides: mergedOverrides,
|
||||
};
|
||||
await fs.writeJSON(join(OUTPUT_DIR, 'config.json'), config, { spaces: 2 });
|
||||
|
||||
output.print(
|
||||
`${prependEmoji(
|
||||
`Build Completed in ${chalk.bold(OUTPUT_DIR)} ${chalk.gray(
|
||||
buildStamp()
|
||||
)}`,
|
||||
emoji('success')
|
||||
)}\n`
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
function expandBuild(files: string[], build: Builder): Builder[] {
|
||||
if (!build.src) return [];
|
||||
|
||||
let pattern = build.src;
|
||||
if (pattern[0] === '/') {
|
||||
// Remove a leading slash so that the globbing is relative
|
||||
// to `cwd` instead of the root of the filesystem.
|
||||
pattern = pattern.substring(1);
|
||||
}
|
||||
|
||||
const matches = files.filter(
|
||||
name => name === pattern || minimatch(name, pattern, { dot: true })
|
||||
);
|
||||
|
||||
return matches.map(m => {
|
||||
return {
|
||||
...build,
|
||||
src: m,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function mergeImages(
|
||||
buildResults: Iterable<BuildResult>
|
||||
): BuildResultV2Typical['images'] {
|
||||
let images: BuildResultV2Typical['images'] = undefined;
|
||||
for (const result of buildResults) {
|
||||
if ('images' in result && result.images) {
|
||||
images = Object.assign({} || images, result.images);
|
||||
}
|
||||
}
|
||||
return images;
|
||||
}
|
||||
|
||||
function mergeWildcard(
|
||||
buildResults: Iterable<BuildResult>
|
||||
): BuildResultV2Typical['wildcard'] {
|
||||
let wildcard: BuildResultV2Typical['wildcard'] = undefined;
|
||||
for (const result of buildResults) {
|
||||
if ('wildcard' in result && result.wildcard) {
|
||||
if (!wildcard) wildcard = [];
|
||||
wildcard.push(...result.wildcard);
|
||||
}
|
||||
}
|
||||
return wildcard;
|
||||
}
|
||||
|
||||
async function checkExists(paths: Iterable<string>) {
|
||||
for (const path of paths) {
|
||||
try {
|
||||
await fs.stat(path);
|
||||
return path;
|
||||
} catch (err: any) {
|
||||
if (err.code !== 'ENOENT') throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export default new Map([
|
||||
['aliases', 'alias'],
|
||||
['billing', 'billing'],
|
||||
['bisect', 'bisect'],
|
||||
['build', 'build'],
|
||||
['cc', 'billing'],
|
||||
['cert', 'certs'],
|
||||
['certs', 'certs'],
|
||||
|
||||
@@ -171,7 +171,7 @@ const main = async () => {
|
||||
// * a subcommand (as in: `vercel ls`)
|
||||
const targetOrSubcommand = argv._[2];
|
||||
|
||||
const betaCommands: string[] = [];
|
||||
const betaCommands: string[] = ['build'];
|
||||
if (betaCommands.includes(targetOrSubcommand)) {
|
||||
console.log(
|
||||
`${chalk.grey(
|
||||
@@ -303,7 +303,14 @@ const main = async () => {
|
||||
|
||||
let authConfig = null;
|
||||
|
||||
const subcommandsWithoutToken = ['login', 'logout', 'help', 'init', 'update'];
|
||||
const subcommandsWithoutToken = [
|
||||
'login',
|
||||
'logout',
|
||||
'help',
|
||||
'init',
|
||||
'update',
|
||||
'build',
|
||||
];
|
||||
|
||||
if (authConfigExists) {
|
||||
try {
|
||||
@@ -524,6 +531,7 @@ const main = async () => {
|
||||
typeof scope === 'string' &&
|
||||
targetCommand !== 'login' &&
|
||||
targetCommand !== 'dev' &&
|
||||
targetCommand !== 'build' &&
|
||||
!(targetCommand === 'teams' && argv._[3] !== 'invite')
|
||||
) {
|
||||
let user = null;
|
||||
@@ -598,6 +606,9 @@ const main = async () => {
|
||||
case 'bisect':
|
||||
func = require('./commands/bisect').default;
|
||||
break;
|
||||
case 'build':
|
||||
func = require('./commands/build').default;
|
||||
break;
|
||||
case 'certs':
|
||||
func = require('./commands/certs').default;
|
||||
break;
|
||||
|
||||
@@ -251,9 +251,6 @@ export interface Project extends ProjectSettings {
|
||||
updatedAt: number;
|
||||
createdAt: number;
|
||||
alias?: ProjectAliasTarget[];
|
||||
devCommand?: string | null;
|
||||
framework?: string | null;
|
||||
rootDirectory?: string | null;
|
||||
latestDeployments?: Partial<Deployment>[];
|
||||
}
|
||||
|
||||
|
||||
197
packages/cli/src/util/build/import-builders.ts
Normal file
197
packages/cli/src/util/build/import-builders.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import npa from 'npm-package-arg';
|
||||
import { satisfies } from 'semver';
|
||||
import { dirname, join } from 'path';
|
||||
import { outputJSON, readJSON } from 'fs-extra';
|
||||
import {
|
||||
BuilderV2,
|
||||
BuilderV3,
|
||||
PackageJson,
|
||||
spawnAsync,
|
||||
} from '@vercel/build-utils';
|
||||
import * as staticBuilder from './static-builder';
|
||||
import { VERCEL_DIR } from '../projects/link';
|
||||
import { Output } from '../output';
|
||||
import readJSONFile from '../read-json-file';
|
||||
import { CantParseJSONFile } from '../errors-ts';
|
||||
|
||||
interface BuilderWithPkg {
|
||||
path: string;
|
||||
pkgPath: string;
|
||||
builder: BuilderV2 | BuilderV3;
|
||||
pkg: PackageJson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports the specified Vercel Builders, installing any missing ones
|
||||
* into `.vercel/builders` if necessary.
|
||||
*/
|
||||
export async function importBuilders(
|
||||
builderSpecs: Set<string>,
|
||||
cwd: string,
|
||||
output: Output
|
||||
): Promise<Map<string, BuilderWithPkg>> {
|
||||
const results = new Map<string, BuilderWithPkg>();
|
||||
const resolvedSpecs = new Map<string, string>();
|
||||
|
||||
const buildersDir = join(cwd, VERCEL_DIR, 'builders');
|
||||
const buildersPkgPath = join(buildersDir, 'package.json');
|
||||
|
||||
do {
|
||||
const buildersToAdd = new Set<string>();
|
||||
|
||||
for (const spec of builderSpecs) {
|
||||
const resolvedSpec = resolvedSpecs.get(spec) || spec;
|
||||
const parsed = npa(resolvedSpec);
|
||||
|
||||
let { name } = parsed;
|
||||
if (!name) {
|
||||
// A URL was specified - will need to install it and resolve the
|
||||
// proper package name from the written `package.json` file
|
||||
buildersToAdd.add(spec);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (name === '@vercel/static') {
|
||||
// `@vercel/static` is a special-case built-in builder
|
||||
results.set(name, {
|
||||
builder: staticBuilder,
|
||||
pkg: { name },
|
||||
path: '',
|
||||
pkgPath: '',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
let pkgPath: string | undefined;
|
||||
let builderPkg: PackageJson | undefined;
|
||||
|
||||
try {
|
||||
// First try `.vercel/builders`. The package name should always be available
|
||||
// at the top-level of `node_modules` since CLI is installing those directly.
|
||||
pkgPath = join(buildersDir, 'node_modules', name, 'package.json');
|
||||
builderPkg = await readJSON(pkgPath);
|
||||
} catch (err: any) {
|
||||
if (err?.code !== 'ENOENT') throw err;
|
||||
// If `pkgPath` wasn't found in `.vercel/builders` then try as a CLI local
|
||||
// dependency. `require.resolve()` will throw if the Builder is not a CLI
|
||||
// dep, in which case we'll install it into `.vercel/builders`.
|
||||
pkgPath = require.resolve(`${name}/package.json`, {
|
||||
paths: [__dirname],
|
||||
});
|
||||
builderPkg = await readJSON(pkgPath);
|
||||
}
|
||||
|
||||
if (!builderPkg || !pkgPath) {
|
||||
throw new Error(`Failed to load \`package.json\` for "${name}"`);
|
||||
}
|
||||
|
||||
if (typeof builderPkg.version !== 'string') {
|
||||
throw new Error(
|
||||
`\`package.json\` for "${name}" does not contain a "version" field`
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.type === 'version' &&
|
||||
parsed.rawSpec !== builderPkg.version
|
||||
) {
|
||||
// An explicit Builder version was specified but it does
|
||||
// not match the version that is currently installed
|
||||
output.debug(
|
||||
`Installed version "${name}@${builderPkg.version}" does not match "${parsed.rawSpec}"`
|
||||
);
|
||||
buildersToAdd.add(spec);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.type === 'range' &&
|
||||
!satisfies(builderPkg.version, parsed.rawSpec)
|
||||
) {
|
||||
// An explicit Builder range was specified but it is not
|
||||
// compatible with the version that is currently installed
|
||||
output.debug(
|
||||
`Installed version "${name}@${builderPkg.version}" is not compatible with "${parsed.rawSpec}"`
|
||||
);
|
||||
buildersToAdd.add(spec);
|
||||
continue;
|
||||
}
|
||||
|
||||
// TODO: handle `parsed.type === 'tag'` ("latest" vs. anything else?)
|
||||
|
||||
const path = join(dirname(pkgPath), builderPkg.main || 'index.js');
|
||||
const builder = require(path);
|
||||
|
||||
results.set(spec, {
|
||||
builder,
|
||||
pkg: builderPkg,
|
||||
path,
|
||||
pkgPath,
|
||||
});
|
||||
output.debug(`Imported Builder "${name}" from "${dirname(pkgPath)}"`);
|
||||
} catch (err: any) {
|
||||
if (err.code === 'MODULE_NOT_FOUND') {
|
||||
output.debug(`Failed to import "${name}": ${err}`);
|
||||
buildersToAdd.add(spec);
|
||||
|
||||
if (err.message.includes('@now/build-utils')) {
|
||||
const upgradeMessage =
|
||||
parsed.scope === '@now'
|
||||
? ` Please update from "@now" to "@vercel".`
|
||||
: '';
|
||||
throw new Error(
|
||||
`The legacy "${name}" Builder is not supported.${upgradeMessage}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add any Builders that are not yet present into `.vercel/builders`
|
||||
if (buildersToAdd.size > 0) {
|
||||
try {
|
||||
const emptyPkgJson = {
|
||||
private: true,
|
||||
license: 'UNLICENSED',
|
||||
};
|
||||
await outputJSON(buildersPkgPath, emptyPkgJson, {
|
||||
flag: 'wx',
|
||||
});
|
||||
} catch (err: any) {
|
||||
if (err.code !== 'EEXIST') throw err;
|
||||
}
|
||||
|
||||
output.debug(
|
||||
`Installing Builders: ${Array.from(buildersToAdd).join(', ')}`
|
||||
);
|
||||
await spawnAsync(
|
||||
'yarn',
|
||||
['add', '@vercel/build-utils', ...buildersToAdd],
|
||||
{ cwd: buildersDir }
|
||||
);
|
||||
|
||||
// Cross-reference any builderSpecs from the saved `package.json` file,
|
||||
// in case they were installed from a URL
|
||||
const buildersPkg = await readJSONFile<PackageJson>(buildersPkgPath);
|
||||
if (buildersPkg instanceof CantParseJSONFile) throw buildersPkg;
|
||||
if (!buildersPkg) {
|
||||
throw new Error(`Failed to load "${buildersPkgPath}"`);
|
||||
}
|
||||
for (const spec of buildersToAdd) {
|
||||
for (const [name, version] of Object.entries(
|
||||
buildersPkg.dependencies || {}
|
||||
)) {
|
||||
if (version === spec) {
|
||||
output.debug(`Resolved Builder spec "${spec}" to name "${name}"`);
|
||||
resolvedSpecs.set(spec, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (results.size !== builderSpecs.size);
|
||||
|
||||
return results;
|
||||
}
|
||||
41
packages/cli/src/util/build/static-builder.ts
Normal file
41
packages/cli/src/util/build/static-builder.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import minimatch from 'minimatch';
|
||||
import { BuildV2, Files } from '@vercel/build-utils';
|
||||
|
||||
export const version = 2;
|
||||
|
||||
export const build: BuildV2 = async ({ entrypoint, files, config }) => {
|
||||
const output: Files = {};
|
||||
const outputDirectory = config.zeroConfig ? config.outputDirectory : '';
|
||||
|
||||
for (let [filename, fileFsRef] of Object.entries(files)) {
|
||||
if (
|
||||
filename.startsWith('.git/') ||
|
||||
filename === 'vercel.json' ||
|
||||
filename === 'now.json'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
entrypoint &&
|
||||
!(
|
||||
entrypoint === filename ||
|
||||
minimatch(filename, entrypoint, { dot: true })
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (outputDirectory) {
|
||||
const outputMatch = outputDirectory + '/';
|
||||
if (filename.startsWith(outputMatch)) {
|
||||
// static output files are moved to the root directory
|
||||
filename = filename.slice(outputMatch.length);
|
||||
}
|
||||
}
|
||||
|
||||
output[filename] = fileFsRef;
|
||||
}
|
||||
|
||||
return { output };
|
||||
};
|
||||
108
packages/cli/src/util/build/unzip.ts
Normal file
108
packages/cli/src/util/build/unzip.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Code modified from `extract-zip` to accept Buffer.
|
||||
* https://github.com/maxogden/extract-zip/blob/master/index.js
|
||||
* BSD-2 Copyright (c) 2014 Max Ogden and other contributors
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import pipe from 'promisepipe';
|
||||
import * as fs from 'fs-extra';
|
||||
import { streamToBuffer } from '@vercel/build-utils';
|
||||
import { Entry, ZipFile, fromBuffer as zipFromBuffer } from 'yauzl-promise';
|
||||
|
||||
async function* createZipIterator(zipFile: ZipFile) {
|
||||
let entry: Entry;
|
||||
while ((entry = await zipFile.readEntry()) !== null) {
|
||||
yield entry;
|
||||
}
|
||||
}
|
||||
|
||||
export async function unzip(buffer: Buffer, dir: string): Promise<void> {
|
||||
const zipFile = await zipFromBuffer(buffer);
|
||||
for await (const entry of createZipIterator(zipFile)) {
|
||||
if (entry.fileName.startsWith('__MACOSX/')) continue;
|
||||
|
||||
try {
|
||||
const destDir = path.dirname(path.join(dir, entry.fileName));
|
||||
await fs.mkdirp(destDir);
|
||||
|
||||
const canonicalDestDir = await fs.realpath(destDir);
|
||||
const relativeDestDir = path.relative(dir, canonicalDestDir);
|
||||
|
||||
if (relativeDestDir.split(path.sep).includes('..')) {
|
||||
throw new Error(
|
||||
`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`
|
||||
);
|
||||
}
|
||||
|
||||
await extractEntry(zipFile, entry, dir);
|
||||
} catch (err) {
|
||||
await zipFile.close();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function extractEntry(
|
||||
zipFile: ZipFile,
|
||||
entry: Entry,
|
||||
dir: string
|
||||
): Promise<void> {
|
||||
const dest = path.join(dir, entry.fileName);
|
||||
|
||||
// convert external file attr int into a fs stat mode int
|
||||
const mode = (entry.externalFileAttributes >> 16) & 0xffff;
|
||||
// check if it's a symlink or dir (using stat mode constants)
|
||||
const IFMT = 61440;
|
||||
const IFDIR = 16384;
|
||||
const IFLNK = 40960;
|
||||
const symlink = (mode & IFMT) === IFLNK;
|
||||
let isDir = (mode & IFMT) === IFDIR;
|
||||
|
||||
// Failsafe, borrowed from jsZip
|
||||
if (!isDir && entry.fileName.endsWith('/')) {
|
||||
isDir = true;
|
||||
}
|
||||
|
||||
// check for windows weird way of specifying a directory
|
||||
// https://github.com/maxogden/extract-zip/issues/13#issuecomment-154494566
|
||||
const madeBy = entry.versionMadeBy >> 8;
|
||||
if (!isDir) isDir = madeBy === 0 && entry.externalFileAttributes === 16;
|
||||
|
||||
const procMode = getExtractedMode(mode, isDir) & 0o777;
|
||||
|
||||
// always ensure folders are created
|
||||
const destDir = isDir ? dest : path.dirname(dest);
|
||||
|
||||
const mkdirOptions = { recursive: true };
|
||||
if (isDir) {
|
||||
// @ts-ignore
|
||||
mkdirOptions.mode = procMode;
|
||||
}
|
||||
await fs.mkdir(destDir, mkdirOptions);
|
||||
if (isDir) return;
|
||||
|
||||
const readStream = await zipFile.openReadStream(entry);
|
||||
|
||||
if (symlink) {
|
||||
const link = await streamToBuffer(readStream);
|
||||
await fs.symlink(link.toString('utf8'), dest);
|
||||
} else {
|
||||
await pipe(readStream, fs.createWriteStream(dest, { mode: procMode }));
|
||||
}
|
||||
}
|
||||
|
||||
function getExtractedMode(entryMode: number, isDir: boolean): number {
|
||||
let mode = entryMode;
|
||||
|
||||
// Set defaults, if necessary
|
||||
if (mode === 0) {
|
||||
if (isDir) {
|
||||
mode = 0o755;
|
||||
} else {
|
||||
mode = 0o644;
|
||||
}
|
||||
}
|
||||
|
||||
return mode;
|
||||
}
|
||||
373
packages/cli/src/util/build/write-build-result.ts
Normal file
373
packages/cli/src/util/build/write-build-result.ts
Normal file
@@ -0,0 +1,373 @@
|
||||
import fs from 'fs-extra';
|
||||
import mimeTypes from 'mime-types';
|
||||
import { basename, dirname, extname, join, relative, resolve } from 'path';
|
||||
import {
|
||||
Builder,
|
||||
BuildResultV2,
|
||||
BuildResultV3,
|
||||
File,
|
||||
FileFsRef,
|
||||
BuilderV2,
|
||||
BuilderV3,
|
||||
Lambda,
|
||||
PackageJson,
|
||||
Prerender,
|
||||
download,
|
||||
EdgeFunction,
|
||||
BuildResultBuildOutput,
|
||||
} from '@vercel/build-utils';
|
||||
import pipe from 'promisepipe';
|
||||
import { unzip } from './unzip';
|
||||
import { VERCEL_DIR } from '../projects/link';
|
||||
|
||||
export const OUTPUT_DIR = join(VERCEL_DIR, 'output');
|
||||
|
||||
export async function writeBuildResult(
|
||||
buildResult: BuildResultV2 | BuildResultV3,
|
||||
build: Builder,
|
||||
builder: BuilderV2 | BuilderV3,
|
||||
builderPkg: PackageJson,
|
||||
cleanUrls?: boolean
|
||||
) {
|
||||
const { version } = builder;
|
||||
if (version === 2) {
|
||||
return writeBuildResultV2(buildResult as BuildResultV2, cleanUrls);
|
||||
} else if (version === 3) {
|
||||
return writeBuildResultV3(buildResult as BuildResultV3, build);
|
||||
}
|
||||
throw new Error(
|
||||
`Unsupported Builder version \`${version}\` from "${builderPkg.name}"`
|
||||
);
|
||||
}
|
||||
|
||||
function isEdgeFunction(v: any): v is EdgeFunction {
|
||||
return v?.type === 'EdgeFunction';
|
||||
}
|
||||
|
||||
function isLambda(v: any): v is Lambda {
|
||||
return v?.type === 'Lambda';
|
||||
}
|
||||
|
||||
function isPrerender(v: any): v is Prerender {
|
||||
return v?.type === 'Prerender';
|
||||
}
|
||||
|
||||
function isFile(v: any): v is File {
|
||||
const type = v?.type;
|
||||
return type === 'FileRef' || type === 'FileFsRef' || type === 'FileBlob';
|
||||
}
|
||||
|
||||
export interface PathOverride {
|
||||
contentType?: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the output from the `build()` return value of a v2 Builder to
|
||||
* the filesystem.
|
||||
*/
|
||||
async function writeBuildResultV2(
|
||||
buildResult: BuildResultV2,
|
||||
cleanUrls?: boolean
|
||||
) {
|
||||
if ('buildOutputPath' in buildResult) {
|
||||
await mergeBuilderOutput(buildResult);
|
||||
return;
|
||||
}
|
||||
|
||||
const lambdas = new Map<Lambda, string>();
|
||||
const overrides: Record<string, PathOverride> = {};
|
||||
for (const [path, output] of Object.entries(buildResult.output)) {
|
||||
if (isLambda(output)) {
|
||||
await writeLambda(output, path, lambdas);
|
||||
} else if (isPrerender(output)) {
|
||||
await writeLambda(output.lambda, path, lambdas);
|
||||
|
||||
// Write the fallback file alongside the Lambda directory
|
||||
let fallback = output.fallback;
|
||||
if (fallback) {
|
||||
const ext = getFileExtension(fallback);
|
||||
const fallbackName = `${path}.prerender-fallback${ext}`;
|
||||
const fallbackPath = join(OUTPUT_DIR, 'functions', fallbackName);
|
||||
const stream = fallback.toStream();
|
||||
await pipe(
|
||||
stream,
|
||||
fs.createWriteStream(fallbackPath, { mode: fallback.mode })
|
||||
);
|
||||
fallback = new FileFsRef({
|
||||
...output.fallback,
|
||||
fsPath: basename(fallbackName),
|
||||
});
|
||||
}
|
||||
|
||||
const prerenderConfigPath = join(
|
||||
OUTPUT_DIR,
|
||||
'functions',
|
||||
`${path}.prerender-config.json`
|
||||
);
|
||||
const prerenderConfig = {
|
||||
...output,
|
||||
lambda: undefined,
|
||||
fallback,
|
||||
};
|
||||
await fs.writeJSON(prerenderConfigPath, prerenderConfig, { spaces: 2 });
|
||||
} else if (isFile(output)) {
|
||||
await writeStaticFile(output, path, overrides, cleanUrls);
|
||||
} else if (isEdgeFunction(output)) {
|
||||
await writeEdgeFunction(output, path);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unsupported output type: "${(output as any).type}" for ${path}`
|
||||
);
|
||||
}
|
||||
}
|
||||
return Object.keys(overrides).length > 0 ? overrides : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the output from the `build()` return value of a v3 Builder to
|
||||
* the filesystem.
|
||||
*/
|
||||
async function writeBuildResultV3(buildResult: BuildResultV3, build: Builder) {
|
||||
const { output } = buildResult;
|
||||
if (isLambda(output)) {
|
||||
const src = build.src!;
|
||||
const ext = extname(src);
|
||||
const path = build.config?.zeroConfig
|
||||
? src.substring(0, src.length - ext.length)
|
||||
: src;
|
||||
await writeLambda(output, path);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Unsupported output type: "${(output as any).type}" for ${build.src}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a static `File` instance to the file system in the "static" directory.
|
||||
* If the filename does not have a file extension then one attempts to be inferred
|
||||
* from the extension of the `fsPath`.
|
||||
*
|
||||
* @param file The `File` instance to write
|
||||
* @param path The URL path where the `File` can be accessed from
|
||||
* @param overrides Record of override configuration when a File is renamed or has other metadata
|
||||
*/
|
||||
async function writeStaticFile(
|
||||
file: File,
|
||||
path: string,
|
||||
overrides: Record<string, PathOverride>,
|
||||
cleanUrls = false
|
||||
) {
|
||||
let fsPath = path;
|
||||
let override: PathOverride | null = null;
|
||||
|
||||
// If the output path doesn't match the determined file extension of
|
||||
// the File then add the extension. This is to help avoid conflicts
|
||||
// where an output path matches a directory name of another output path
|
||||
// (i.e. `blog` -> `blog.html` and `blog/hello` -> `blog/hello.html`)
|
||||
const ext = getFileExtension(file);
|
||||
if (ext && extname(path) !== ext) {
|
||||
fsPath += ext;
|
||||
if (!override) override = {};
|
||||
override.path = path;
|
||||
}
|
||||
|
||||
// If `cleanUrls` is true then remove the `.html` file extension
|
||||
// for HTML files.
|
||||
if (cleanUrls && path.endsWith('.html')) {
|
||||
if (!override) override = {};
|
||||
override.path = path.slice(0, -5);
|
||||
}
|
||||
|
||||
// Ensure an explicit "content-type" on the `File` is returned in
|
||||
// the final output asset.
|
||||
if (file.contentType) {
|
||||
if (!override) override = {};
|
||||
override.contentType = file.contentType;
|
||||
}
|
||||
|
||||
if (override) {
|
||||
overrides[fsPath] = override;
|
||||
}
|
||||
|
||||
const dest = join(OUTPUT_DIR, 'static', fsPath);
|
||||
await fs.mkdirp(dirname(dest));
|
||||
|
||||
// TODO: handle (or skip) symlinks?
|
||||
const stream = file.toStream();
|
||||
await pipe(stream, fs.createWriteStream(dest, { mode: file.mode }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes the `EdgeFunction` instance to the file system.
|
||||
*
|
||||
* @param edgeFunction The `EdgeFunction` instance
|
||||
* @param path The URL path where the `EdgeFunction` can be accessed from
|
||||
*/
|
||||
async function writeEdgeFunction(edgeFunction: EdgeFunction, path: string) {
|
||||
const dest = join(OUTPUT_DIR, 'functions', `${path}.func`);
|
||||
|
||||
await fs.mkdirp(dest);
|
||||
const ops: Promise<any>[] = [];
|
||||
ops.push(download(edgeFunction.files, dest));
|
||||
|
||||
const config = {
|
||||
runtime: 'edge',
|
||||
...edgeFunction,
|
||||
files: undefined,
|
||||
type: undefined,
|
||||
};
|
||||
const configPath = join(dest, '.vc-config.json');
|
||||
ops.push(
|
||||
fs.writeJSON(configPath, config, {
|
||||
spaces: 2,
|
||||
})
|
||||
);
|
||||
await Promise.all(ops);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the file references from the `Lambda` instance to the file system.
|
||||
*
|
||||
* @param lambda The `Lambda` instance
|
||||
* @param path The URL path where the `Lambda` can be accessed from
|
||||
* @param lambdas (optional) Map of `Lambda` instances that have previously been written
|
||||
*/
|
||||
async function writeLambda(
|
||||
lambda: Lambda,
|
||||
path: string,
|
||||
lambdas?: Map<Lambda, string>
|
||||
) {
|
||||
const dest = join(OUTPUT_DIR, 'functions', `${path}.func`);
|
||||
|
||||
// If the `lambda` has already been written to the filesystem at a different
|
||||
// location then create a symlink to the previous location instead of copying
|
||||
// the files again.
|
||||
const existingLambdaPath = lambdas?.get(lambda);
|
||||
if (existingLambdaPath) {
|
||||
const destDir = dirname(dest);
|
||||
const targetDest = join(
|
||||
OUTPUT_DIR,
|
||||
'functions',
|
||||
`${existingLambdaPath}.func`
|
||||
);
|
||||
const target = relative(destDir, targetDest);
|
||||
await fs.mkdirp(destDir);
|
||||
await fs.symlink(target, dest);
|
||||
return;
|
||||
}
|
||||
lambdas?.set(lambda, path);
|
||||
|
||||
await fs.mkdirp(dest);
|
||||
const ops: Promise<any>[] = [];
|
||||
if (lambda.files) {
|
||||
// `files` is defined
|
||||
ops.push(download(lambda.files, dest));
|
||||
} else if (lambda.zipBuffer) {
|
||||
// Builders that use the deprecated `createLambda()` might only have `zipBuffer`
|
||||
ops.push(unzip(lambda.zipBuffer, dest));
|
||||
} else {
|
||||
throw new Error('Malformed `Lambda` - no "files" present');
|
||||
}
|
||||
|
||||
const config = {
|
||||
...lambda,
|
||||
type: undefined,
|
||||
files: undefined,
|
||||
zipBuffer: undefined,
|
||||
};
|
||||
const configPath = join(dest, '.vc-config.json');
|
||||
ops.push(
|
||||
fs.writeJSON(configPath, config, {
|
||||
spaces: 2,
|
||||
})
|
||||
);
|
||||
await Promise.all(ops);
|
||||
|
||||
// XXX: remove any `.vercel/builders` directories that were
|
||||
// extracted into the `dest` dir. This is a temporary band-aid
|
||||
// to make `vercel-php` work since it is inadvertently including
|
||||
// `.vercel/builders` into the Lambda files due to glob syntax.
|
||||
// See: https://github.com/juicyfx/vercel-php/pull/232
|
||||
for await (const dir of findDirs('.vercel', dest)) {
|
||||
const absDir = join(dest, dir);
|
||||
const entries = await fs.readdir(absDir);
|
||||
if (entries.includes('cache')) {
|
||||
// Delete everything except for "cache"
|
||||
await Promise.all(
|
||||
entries
|
||||
.filter(e => e !== 'cache')
|
||||
.map(entry => fs.remove(join(absDir, entry)))
|
||||
);
|
||||
} else {
|
||||
// Delete the entire `.vercel` directory
|
||||
await fs.remove(absDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When the Root Directory setting is utilized, merge the contents of the
|
||||
* `.vercel/output` directory that was specified by the Builder into the
|
||||
* `vc build` output directory.
|
||||
*/
|
||||
async function mergeBuilderOutput(buildResult: BuildResultBuildOutput) {
|
||||
const absOutputDir = resolve(OUTPUT_DIR);
|
||||
if (absOutputDir === buildResult.buildOutputPath) {
|
||||
// `.vercel/output` dir is already in the correct location,
|
||||
// so no need to do anything
|
||||
return;
|
||||
}
|
||||
await fs.copy(buildResult.buildOutputPath, OUTPUT_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to return the file extension (i.e. `.html`) from the given
|
||||
* `File` instance, based on its actual filesystem path and/or the
|
||||
* "content-type" of the File.
|
||||
*/
|
||||
function getFileExtension(file: File): string {
|
||||
let ext = '';
|
||||
if (file.type === 'FileFsRef') {
|
||||
ext = extname(file.fsPath);
|
||||
}
|
||||
if (!ext && file.contentType) {
|
||||
const e = mimeTypes.extension(file.contentType);
|
||||
if (e) {
|
||||
ext = `.${e}`;
|
||||
}
|
||||
}
|
||||
return ext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an async iterator that scans a directory
|
||||
* for sub-directories with the matching `name`.
|
||||
*/
|
||||
export async function* findDirs(
|
||||
name: string,
|
||||
dir: string,
|
||||
root = dir
|
||||
): AsyncIterable<string> {
|
||||
let paths: string[];
|
||||
try {
|
||||
paths = await fs.readdir(dir);
|
||||
} catch (err: any) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
throw err;
|
||||
}
|
||||
paths = [];
|
||||
}
|
||||
for (const path of paths) {
|
||||
const abs = join(dir, path);
|
||||
const s = await fs.stat(abs);
|
||||
if (s.isDirectory()) {
|
||||
if (path === name) {
|
||||
yield relative(root, abs);
|
||||
} else {
|
||||
yield* findDirs(name, abs, root);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,7 @@ import {
|
||||
} from './types';
|
||||
import { ProjectEnvVariable, ProjectSettings } from '../../types';
|
||||
import exposeSystemEnvs from './expose-system-envs';
|
||||
import { treeKill } from '../tree-kill';
|
||||
|
||||
const frontendRuntimeSet = new Set(
|
||||
frameworkList.map(f => f.useRuntime?.use || '@vercel/static-build')
|
||||
@@ -998,20 +999,7 @@ export default class DevServer {
|
||||
}
|
||||
|
||||
if (devProcess) {
|
||||
ops.push(
|
||||
new Promise<void>((resolve, reject) => {
|
||||
devProcess.once('exit', () => resolve());
|
||||
try {
|
||||
process.kill(devProcess.pid);
|
||||
} catch (err) {
|
||||
if (err.code === 'ESRCH') {
|
||||
// Process already exited
|
||||
return resolve();
|
||||
}
|
||||
reject(err);
|
||||
}
|
||||
})
|
||||
);
|
||||
ops.push(treeKill(devProcess.pid));
|
||||
}
|
||||
|
||||
ops.push(close(this.server));
|
||||
@@ -1052,12 +1040,7 @@ export default class DevServer {
|
||||
const { debug } = this.output;
|
||||
debug(`Killing builder dev server with PID ${pid}`);
|
||||
this.devServerPids.delete(pid);
|
||||
try {
|
||||
process.kill(pid, 'SIGTERM');
|
||||
debug(`Killed builder dev server with PID ${pid}`);
|
||||
} catch (err) {
|
||||
debug(`Failed to kill builder dev server with PID ${pid}: ${err}`);
|
||||
}
|
||||
await treeKill(pid);
|
||||
}
|
||||
|
||||
async send404(
|
||||
@@ -2120,7 +2103,7 @@ export default class DevServer {
|
||||
.replace(/%PORT%/g, `${port}`);
|
||||
|
||||
this.output.debug(
|
||||
`Starting dev command with parameters : ${JSON.stringify({
|
||||
`Starting dev command with parameters: ${JSON.stringify({
|
||||
cwd,
|
||||
command,
|
||||
port,
|
||||
@@ -2152,6 +2135,7 @@ export default class DevServer {
|
||||
cwd,
|
||||
env,
|
||||
});
|
||||
this.devProcess = p;
|
||||
|
||||
if (!p.stdout || !p.stderr) {
|
||||
throw new Error('Expected child process to have stdout and stderr');
|
||||
@@ -2164,17 +2148,14 @@ export default class DevServer {
|
||||
process.stdout.write(data.replace(proxyPort, devPort));
|
||||
});
|
||||
|
||||
p.on('exit', (code: number) => {
|
||||
if (code > 0) {
|
||||
process.exit(code);
|
||||
}
|
||||
p.on('exit', (code, signal) => {
|
||||
this.output.debug(`Dev command exited with "${signal || code}"`);
|
||||
this.devProcessPort = undefined;
|
||||
});
|
||||
|
||||
await checkForPort(port, 1000 * 60 * 5);
|
||||
|
||||
this.devProcessPort = port;
|
||||
this.devProcess = p;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,16 @@ import title from 'title';
|
||||
import pkg from './pkg';
|
||||
import cmd from './output/cmd';
|
||||
|
||||
/**
|
||||
* The package name defined in the CLI's `package.json` file (`vercel`).
|
||||
*/
|
||||
export const name = pkg.name;
|
||||
|
||||
/**
|
||||
* Unicode symbol used to represent the CLI.
|
||||
*/
|
||||
export const logo = '▲';
|
||||
|
||||
/**
|
||||
* Returns the package name such as `vercel` or `now`.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,7 @@ import { promisify } from 'util';
|
||||
|
||||
import getProjectByIdOrName from '../projects/get-project-by-id-or-name';
|
||||
import Client from '../client';
|
||||
import { ProjectNotFound } from '../errors-ts';
|
||||
import { InvalidToken, ProjectNotFound } from '../errors-ts';
|
||||
import getUser from '../get-user';
|
||||
import getTeamById from '../teams/get-team-by-id';
|
||||
import { Output } from '../output';
|
||||
@@ -150,15 +150,20 @@ export async function getLinkedProject(
|
||||
getProjectByIdOrName(client, link.projectId, link.orgId),
|
||||
]);
|
||||
} catch (err) {
|
||||
if (err?.status === 403) {
|
||||
if (err && err.status === 403) {
|
||||
output.stopSpinner();
|
||||
throw new NowBuildError({
|
||||
message: `Could not retrieve Project Settings. To link your Project, remove the ${outputCode(
|
||||
VERCEL_DIR
|
||||
)} directory and deploy again.`,
|
||||
code: 'PROJECT_UNAUTHORIZED',
|
||||
link: 'https://vercel.link/cannot-load-project-settings',
|
||||
});
|
||||
|
||||
if (err.missingToken) {
|
||||
throw new InvalidToken();
|
||||
} else {
|
||||
throw new NowBuildError({
|
||||
message: `Could not retrieve Project Settings. To link your Project, remove the ${outputCode(
|
||||
VERCEL_DIR
|
||||
)} directory and deploy again.`,
|
||||
code: 'PROJECT_UNAUTHORIZED',
|
||||
link: 'https://vercel.link/cannot-load-project-settings',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Not a special case 403, we should still throw it
|
||||
|
||||
@@ -5,12 +5,14 @@ import { join } from 'path';
|
||||
|
||||
export type ProjectLinkAndSettings = ProjectLink & {
|
||||
settings: {
|
||||
installCommand: Project['installCommand'];
|
||||
buildCommand: Project['buildCommand'];
|
||||
devCommand: Project['devCommand'];
|
||||
outputDirectory: Project['outputDirectory'];
|
||||
directoryListing: Project['directoryListing'];
|
||||
rootDirectory: Project['rootDirectory'];
|
||||
framework: Project['framework'];
|
||||
nodeVersion: Project['nodeVersion'];
|
||||
};
|
||||
};
|
||||
|
||||
@@ -22,20 +24,22 @@ export async function writeProjectSettings(
|
||||
project: Project,
|
||||
org: Org
|
||||
) {
|
||||
const data = {
|
||||
const projectLinkAndSettings: ProjectLinkAndSettings = {
|
||||
projectId: project.id,
|
||||
orgId: org.id,
|
||||
settings: {
|
||||
buildCommand: project.buildCommand,
|
||||
devCommand: project.devCommand,
|
||||
outputDirectory: project.outputDirectory,
|
||||
directoryListing: project.directoryListing,
|
||||
rootDirectory: project.rootDirectory,
|
||||
framework: project.framework,
|
||||
devCommand: project.devCommand,
|
||||
installCommand: project.installCommand,
|
||||
buildCommand: project.buildCommand,
|
||||
outputDirectory: project.outputDirectory,
|
||||
rootDirectory: project.rootDirectory,
|
||||
directoryListing: project.directoryListing,
|
||||
nodeVersion: project.nodeVersion,
|
||||
},
|
||||
};
|
||||
const path = join(cwd, VERCEL_DIR, VERCEL_DIR_PROJECT);
|
||||
return await outputJSON(path, data, {
|
||||
return await outputJSON(path, projectLinkAndSettings, {
|
||||
spaces: 2,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
ANOTHER_SECRET=runtime
|
||||
@@ -1 +0,0 @@
|
||||
SECRET=buildtime
|
||||
@@ -1,7 +0,0 @@
|
||||
.now
|
||||
.vercel
|
||||
.next
|
||||
.idea
|
||||
node_modules
|
||||
!.env
|
||||
!.env.build
|
||||
@@ -1,10 +0,0 @@
|
||||
console.log({
|
||||
SECRET: process.env.SECRET,
|
||||
ANOTHER_SECRET: process.env.ANOTHER_SECRET,
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
env: {
|
||||
SECRET: process.env.SECRET,
|
||||
},
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
export default async (_req, res) => {
|
||||
return res.end(process.env.ANOTHER_SECRET);
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
export default () => <p>{process.env.SECRET}</p>;
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"build": {
|
||||
"env": {
|
||||
"SECRET": "@buildtime"
|
||||
}
|
||||
},
|
||||
"env": {
|
||||
"ANOTHER_SECRET": "@runtime"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
module.exports = {
|
||||
assetPrefix: '/blog',
|
||||
env: {
|
||||
ASSET_PREFIX: '/blog',
|
||||
},
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
export default function Blog() {
|
||||
return (
|
||||
<div>
|
||||
<h3>This is our blog</h3>
|
||||
<ul>
|
||||
<li>
|
||||
<Link href="/blog/post/[id]" as="/blog/post/1">
|
||||
<a>Post 1</a>
|
||||
</Link>
|
||||
</li>
|
||||
<li>
|
||||
<Link href="/blog/post/[id]" as="/blog/post/2">
|
||||
<a>Post 2</a>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
<a href="/">Home</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/router'
|
||||
|
||||
export default function Post() {
|
||||
const router = useRouter()
|
||||
return (
|
||||
<div>
|
||||
<h3>Post #{router.query.id}</h3>
|
||||
<p>Lorem ipsum</p>
|
||||
<Link href="/blog">
|
||||
<a>Back to blog</a>
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
const Header = () => (
|
||||
<div>
|
||||
<h2>The Company</h2>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Header;
|
||||
@@ -1,21 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
const About = ({ id }) => {
|
||||
return (
|
||||
<div>
|
||||
<p>This is the {id} page with static props.</p>
|
||||
<div>
|
||||
<Link href="/">
|
||||
<a>Go Back</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const getStaticProps = ({ params }) => {
|
||||
return { props: { id: params.id } };
|
||||
};
|
||||
export const getStaticPaths = () => ({ paths: ['/1/dynamic'], fallback: true });
|
||||
|
||||
export default About;
|
||||
@@ -1,19 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
|
||||
const About = () => {
|
||||
const router = useRouter();
|
||||
const { id } = router.query;
|
||||
return (
|
||||
<div>
|
||||
<p>This is the {id} page without static props.</p>
|
||||
<div>
|
||||
<Link href="/">
|
||||
<a>Go Back</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default About;
|
||||
@@ -1,19 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
|
||||
const About = () => {
|
||||
const router = useRouter();
|
||||
const { id } = router.query;
|
||||
return (
|
||||
<div>
|
||||
<p>This is the about static page.</p>
|
||||
<div>
|
||||
<Link href="/">
|
||||
<a>Go Back</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default About;
|
||||
@@ -1,36 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
const Header = dynamic(import('../components/Header'));
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<p>This is our homepage</p>
|
||||
<div>
|
||||
<a href="/blog">Blog</a>
|
||||
</div>
|
||||
<div>
|
||||
<Link href="/about">
|
||||
<a>About us</a>
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<Link href="/foo">
|
||||
<a>foo</a>
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<Link href="/1/dynamic">
|
||||
<a>1/dynamic</a>
|
||||
</Link>
|
||||
</div>
|
||||
<div>
|
||||
<Link href="/1/foo">
|
||||
<a>1/foo</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"name": "with-zones-example",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"home",
|
||||
"blog"
|
||||
],
|
||||
"devDependencies": {
|
||||
"vercel": "canary"
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"builds": [
|
||||
{ "src": "blog/package.json", "use": "@vercel/next@canary" },
|
||||
{ "src": "home/package.json", "use": "@vercel/next@canary" }
|
||||
],
|
||||
"routes": [
|
||||
{ "src": "/blog/_next(.*)", "dest": "blog/_next$1" },
|
||||
{ "src": "/blog(.*)", "dest": "blog/blog$1" },
|
||||
{ "src": "(.*)", "dest": "home$1" }
|
||||
]
|
||||
}
|
||||
356
packages/cli/test/dev/integration-1.test.ts
Normal file
356
packages/cli/test/dev/integration-1.test.ts
Normal file
@@ -0,0 +1,356 @@
|
||||
import os from 'os';
|
||||
import fs from 'fs-extra';
|
||||
import { join } from 'path';
|
||||
|
||||
const {
|
||||
exec,
|
||||
fetch,
|
||||
fixture,
|
||||
testFixture,
|
||||
testFixtureStdio,
|
||||
} = require('./utils.js');
|
||||
|
||||
test('[vercel dev] prints `npm install` errors', async () => {
|
||||
const dir = fixture('runtime-not-installed');
|
||||
const result = await exec(dir);
|
||||
expect(result.stderr.includes('npm ERR! 404')).toBeTruthy();
|
||||
expect(
|
||||
result.stderr.includes('Failed to install `vercel dev` dependencies')
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
result.stderr.includes('https://vercel.link/npm-install-failed-dev')
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
test('[vercel dev] `vercel.json` should be invalidated if deleted', async () => {
|
||||
const dir = fixture('invalidate-vercel-config');
|
||||
const configPath = join(dir, 'vercel.json');
|
||||
const originalConfig = await fs.readJSON(configPath);
|
||||
const { dev, port, readyResolver } = await testFixture(dir);
|
||||
|
||||
try {
|
||||
await readyResolver;
|
||||
|
||||
{
|
||||
// Env var should be set from `vercel.json`
|
||||
const res = await fetch(`http://localhost:${port}/api`);
|
||||
const body = await res.json();
|
||||
expect(body.FOO).toBe('bar');
|
||||
}
|
||||
|
||||
{
|
||||
// Env var should not be set after `vercel.json` is deleted
|
||||
await fs.remove(configPath);
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/api`);
|
||||
const body = await res.json();
|
||||
expect(body.FOO).toBe(undefined);
|
||||
}
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
await fs.writeJSON(configPath, originalConfig);
|
||||
}
|
||||
});
|
||||
|
||||
test('[vercel dev] reflects changes to config and env without restart', async () => {
|
||||
const dir = fixture('node-helpers');
|
||||
const configPath = join(dir, 'vercel.json');
|
||||
const originalConfig = await fs.readJSON(configPath);
|
||||
const { dev, port, readyResolver } = await testFixture(dir);
|
||||
|
||||
try {
|
||||
await readyResolver;
|
||||
|
||||
{
|
||||
// Node.js helpers should be available by default
|
||||
const res = await fetch(`http://localhost:${port}/?foo=bar`);
|
||||
const body = await res.json();
|
||||
expect(body.hasHelpers).toBe(true);
|
||||
expect(body.query.foo).toBe('bar');
|
||||
}
|
||||
|
||||
{
|
||||
// Disable the helpers via `config.helpers = false`
|
||||
const config = {
|
||||
...originalConfig,
|
||||
builds: [
|
||||
{
|
||||
...originalConfig.builds[0],
|
||||
config: {
|
||||
helpers: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
await fs.writeJSON(configPath, config);
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/?foo=bar`);
|
||||
const body = await res.json();
|
||||
expect(body.hasHelpers).toBe(false);
|
||||
expect(body.query).toBe(undefined);
|
||||
}
|
||||
|
||||
{
|
||||
// Enable the helpers via `config.helpers = true`
|
||||
const config = {
|
||||
...originalConfig,
|
||||
builds: [
|
||||
{
|
||||
...originalConfig.builds[0],
|
||||
config: {
|
||||
helpers: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
await fs.writeJSON(configPath, config);
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/?foo=baz`);
|
||||
const body = await res.json();
|
||||
expect(body.hasHelpers).toBe(true);
|
||||
expect(body.query.foo).toBe('baz');
|
||||
}
|
||||
|
||||
{
|
||||
// Disable the helpers via `NODEJS_HELPERS = '0'`
|
||||
const config = {
|
||||
...originalConfig,
|
||||
build: {
|
||||
env: {
|
||||
NODEJS_HELPERS: '0',
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeJSON(configPath, config);
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/?foo=baz`);
|
||||
const body = await res.json();
|
||||
expect(body.hasHelpers).toBe(false);
|
||||
expect(body.query).toBe(undefined);
|
||||
}
|
||||
|
||||
{
|
||||
// Enable the helpers via `NODEJS_HELPERS = '1'`
|
||||
const config = {
|
||||
...originalConfig,
|
||||
build: {
|
||||
env: {
|
||||
NODEJS_HELPERS: '1',
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeJSON(configPath, config);
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/?foo=boo`);
|
||||
const body = await res.json();
|
||||
expect(body.hasHelpers).toBe(true);
|
||||
expect(body.query.foo).toBe('boo');
|
||||
}
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
await fs.writeJSON(configPath, originalConfig);
|
||||
}
|
||||
});
|
||||
|
||||
test('[vercel dev] `@vercel/node` TypeScript should be resolved by default', async () => {
|
||||
// The purpose of this test is to test that `@vercel/node` can properly
|
||||
// resolve the default "typescript" module when the project doesn't include
|
||||
// its own version. To properly test for this, a fixture needs to be created
|
||||
// *outside* of the `vercel` repo, since otherwise the root-level
|
||||
// "node_modules/typescript" is resolved as relative to the project, and
|
||||
// not relative to `@vercel/node` which is what we are testing for here.
|
||||
const dir = join(os.tmpdir(), 'vercel-node-typescript-resolve-test');
|
||||
const apiDir = join(dir, 'api');
|
||||
await fs.mkdirp(apiDir);
|
||||
await fs.writeFile(
|
||||
join(apiDir, 'hello.js'),
|
||||
'export default (req, res) => { res.end("world"); }'
|
||||
);
|
||||
|
||||
const { dev, port, readyResolver } = await testFixture(dir);
|
||||
|
||||
try {
|
||||
await readyResolver;
|
||||
|
||||
const res = await fetch(`http://localhost:${port}/api/hello`);
|
||||
const body = await res.text();
|
||||
expect(body).toBe('world');
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
await fs.remove(dir);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] validate routes that use `check: true`',
|
||||
testFixtureStdio('routes-check-true', async (testPath: any) => {
|
||||
await testPath(200, '/blog/post', 'Blog Home');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] validate routes that use `check: true` and `status` code',
|
||||
testFixtureStdio('routes-check-true-status', async (testPath: any) => {
|
||||
await testPath(403, '/secret');
|
||||
await testPath(200, '/post', 'This is a post.');
|
||||
await testPath(200, '/post.html', 'This is a post.');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] validate routes that use custom 404 page',
|
||||
testFixtureStdio('routes-custom-404', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Home Page');
|
||||
await testPath(404, '/nothing', 'Custom User 404');
|
||||
await testPath(404, '/exact', 'Exact Custom 404');
|
||||
await testPath(200, '/api/hello', 'Hello');
|
||||
await testPath(404, '/api/nothing', 'Custom User 404');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] handles miss after route',
|
||||
testFixtureStdio('handle-miss-after-route', async (testPath: any) => {
|
||||
await testPath(200, '/post', 'Blog Post Page', {
|
||||
test: '1',
|
||||
override: 'one',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] handles miss after rewrite',
|
||||
testFixtureStdio('handle-miss-after-rewrite', async (testPath: any) => {
|
||||
await testPath(200, '/post', 'Blog Post Page', {
|
||||
test: '1',
|
||||
override: 'one',
|
||||
});
|
||||
await testPath(200, '/blog/post', 'Blog Post Page', {
|
||||
test: '1',
|
||||
override: 'two',
|
||||
});
|
||||
await testPath(404, '/blog/about.html', undefined, {
|
||||
test: '1',
|
||||
override: 'two',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] does not display directory listing after 404',
|
||||
testFixtureStdio('handle-miss-hide-dir-list', async (testPath: any) => {
|
||||
await testPath(404, '/post');
|
||||
await testPath(200, '/post/one.html', 'First Post');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should preserve query string even after miss phase',
|
||||
testFixtureStdio('handle-miss-querystring', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
if (process.env.CI && process.platform === 'darwin') {
|
||||
console.log('Skipping since GH Actions hangs for some reason');
|
||||
} else {
|
||||
await testPath(200, '/echo/first/second', 'a=first,b=second');
|
||||
await testPath(200, '/functions/echo.js?a=one&b=two', 'a=one,b=two');
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] handles hit after handle: filesystem',
|
||||
testFixtureStdio('handle-hit-after-fs', async (testPath: any) => {
|
||||
await testPath(200, '/blog.html', 'Blog Page', { test: '1' });
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] handles hit after dest',
|
||||
testFixtureStdio('handle-hit-after-dest', async (testPath: any) => {
|
||||
await testPath(200, '/post', 'Blog Post', { test: '1', override: 'one' });
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] handles hit after rewrite',
|
||||
testFixtureStdio('handle-hit-after-rewrite', async (testPath: any) => {
|
||||
await testPath(200, '/post', 'Blog Post', { test: '1', override: 'one' });
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should serve the public directory and api functions',
|
||||
testFixtureStdio('public-and-api', async (testPath: any) => {
|
||||
await testPath(200, '/', 'This is the home page');
|
||||
await testPath(200, '/about.html', 'This is the about page');
|
||||
await testPath(200, '/.well-known/humans.txt', 'We come in peace');
|
||||
await testPath(200, '/api/date', /current date/);
|
||||
await testPath(200, '/api/rand', /random number/);
|
||||
await testPath(200, '/api/rand.js', /random number/);
|
||||
await testPath(404, '/api/api', /NOT_FOUND/m);
|
||||
await testPath(404, '/nothing', /Custom 404 Page/);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should allow user rewrites for path segment files',
|
||||
testFixtureStdio('test-zero-config-rewrite', async (testPath: any) => {
|
||||
await testPath(404, '/');
|
||||
await testPath(200, '/echo/1', '{"id":"1"}', {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
});
|
||||
await testPath(200, '/echo/2', '{"id":"2"}', {
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test('[vercel dev] validate builds', async () => {
|
||||
const directory = fixture('invalid-builds');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `builds\[0\].src` should be string/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate routes', async () => {
|
||||
const directory = fixture('invalid-routes');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `routes\[0\].src` should be string/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate cleanUrls', async () => {
|
||||
const directory = fixture('invalid-clean-urls');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `cleanUrls` should be boolean/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate trailingSlash', async () => {
|
||||
const directory = fixture('invalid-trailing-slash');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `trailingSlash` should be boolean/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate rewrites', async () => {
|
||||
const directory = fixture('invalid-rewrites');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `rewrites\[0\].destination` should be string/m
|
||||
);
|
||||
});
|
||||
336
packages/cli/test/dev/integration-2.test.ts
Normal file
336
packages/cli/test/dev/integration-2.test.ts
Normal file
@@ -0,0 +1,336 @@
|
||||
// eslint-disable-next-line
|
||||
import path from 'path';
|
||||
|
||||
const { exec, fixture, testFixture, testFixtureStdio } = require('./utils.js');
|
||||
|
||||
test('[vercel dev] validate redirects', async () => {
|
||||
const directory = fixture('invalid-redirects');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `redirects\[0\].statusCode` should be integer/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate headers', async () => {
|
||||
const directory = fixture('invalid-headers');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/Invalid vercel\.json - `headers\[0\].headers\[0\].value` should be string/m
|
||||
);
|
||||
});
|
||||
|
||||
test('[vercel dev] validate mixed routes and rewrites', async () => {
|
||||
const directory = fixture('invalid-mixed-routes-rewrites');
|
||||
const output = await exec(directory);
|
||||
|
||||
expect(output.exitCode).toBe(1);
|
||||
expect(output.stderr).toMatch(
|
||||
/If `rewrites`, `redirects`, `headers`, `cleanUrls` or `trailingSlash` are used, then `routes` cannot be present./m
|
||||
);
|
||||
expect(output.stderr).toMatch(/vercel\.link\/mix-routing-props/m);
|
||||
});
|
||||
|
||||
// Test seems unstable: It won't return sometimes.
|
||||
test('[vercel dev] validate env var names', async () => {
|
||||
const directory = fixture('invalid-env-var-name');
|
||||
const { dev } = await testFixture(directory, { stdio: 'pipe' });
|
||||
|
||||
try {
|
||||
let stderr = '';
|
||||
dev.stderr.setEncoding('utf8');
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
dev.stderr.on('data', (b: any) => {
|
||||
stderr += b.toString();
|
||||
|
||||
if (
|
||||
stderr.includes('Ignoring env var "1" because name is invalid') &&
|
||||
stderr.includes(
|
||||
'Ignoring build env var "_a" because name is invalid'
|
||||
) &&
|
||||
stderr.includes(
|
||||
'Env var names must start with letters, and can only contain alphanumeric characters and underscores'
|
||||
)
|
||||
) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
|
||||
dev.on('error', reject);
|
||||
dev.on('exit', resolve);
|
||||
});
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] test rewrites with segments serve correct content',
|
||||
testFixtureStdio('test-rewrites-with-segments', async (testPath: any) => {
|
||||
await testPath(200, '/api/users/first', 'first');
|
||||
await testPath(200, '/api/fourty-two', '42');
|
||||
await testPath(200, '/rand', '42');
|
||||
await testPath(200, '/api/dynamic', 'dynamic');
|
||||
await testPath(404, '/api');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test rewrites serve correct content',
|
||||
testFixtureStdio('test-rewrites', async (testPath: any) => {
|
||||
await testPath(200, '/hello', 'Hello World');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test rewrites and redirects serve correct external content',
|
||||
testFixtureStdio(
|
||||
'test-external-rewrites-and-redirects',
|
||||
async (testPath: any) => {
|
||||
const vcRobots = `https://vercel.com/robots.txt`;
|
||||
await testPath(200, '/rewrite', /User-Agent: \*/m);
|
||||
await testPath(308, '/redirect', `Redirecting to ${vcRobots} (308)`, {
|
||||
Location: vcRobots,
|
||||
});
|
||||
await testPath(307, '/tempRedirect', `Redirecting to ${vcRobots} (307)`, {
|
||||
Location: vcRobots,
|
||||
});
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test rewrites and redirects is case sensitive',
|
||||
testFixtureStdio('test-routing-case-sensitive', async (testPath: any) => {
|
||||
await testPath(200, '/Path', 'UPPERCASE');
|
||||
await testPath(200, '/path', 'lowercase');
|
||||
await testPath(308, '/GoTo', 'Redirecting to /upper.html (308)', {
|
||||
Location: '/upper.html',
|
||||
});
|
||||
await testPath(308, '/goto', 'Redirecting to /lower.html (308)', {
|
||||
Location: '/lower.html',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test cleanUrls serve correct content',
|
||||
testFixtureStdio('test-clean-urls', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
await testPath(200, '/about', 'About Page');
|
||||
await testPath(200, '/sub', 'Sub Index Page');
|
||||
await testPath(200, '/sub/another', 'Sub Another Page');
|
||||
await testPath(200, '/style.css', 'body { color: green }');
|
||||
await testPath(308, '/index.html', 'Redirecting to / (308)', {
|
||||
Location: '/',
|
||||
});
|
||||
await testPath(308, '/about.html', 'Redirecting to /about (308)', {
|
||||
Location: '/about',
|
||||
});
|
||||
await testPath(308, '/sub/index.html', 'Redirecting to /sub (308)', {
|
||||
Location: '/sub',
|
||||
});
|
||||
await testPath(
|
||||
308,
|
||||
'/sub/another.html',
|
||||
'Redirecting to /sub/another (308)',
|
||||
{ Location: '/sub/another' }
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test cleanUrls serve correct content when using `outputDirectory`',
|
||||
testFixtureStdio(
|
||||
'test-clean-urls-with-output-directory',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
await testPath(200, '/about', 'About Page');
|
||||
await testPath(200, '/sub', 'Sub Index Page');
|
||||
await testPath(200, '/sub/another', 'Sub Another Page');
|
||||
await testPath(200, '/style.css', 'body { color: green }');
|
||||
await testPath(308, '/index.html', 'Redirecting to / (308)', {
|
||||
Location: '/',
|
||||
});
|
||||
await testPath(308, '/about.html', 'Redirecting to /about (308)', {
|
||||
Location: '/about',
|
||||
});
|
||||
await testPath(308, '/sub/index.html', 'Redirecting to /sub (308)', {
|
||||
Location: '/sub',
|
||||
});
|
||||
await testPath(
|
||||
308,
|
||||
'/sub/another.html',
|
||||
'Redirecting to /sub/another (308)',
|
||||
{ Location: '/sub/another' }
|
||||
);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should serve custom 404 when `cleanUrls: true`',
|
||||
testFixtureStdio('test-clean-urls-custom-404', async (testPath: any) => {
|
||||
await testPath(200, '/', 'This is the home page');
|
||||
await testPath(200, '/about', 'The about page');
|
||||
await testPath(200, '/contact/me', 'Contact Me Subdirectory');
|
||||
await testPath(404, '/nothing', 'Custom 404 Page');
|
||||
await testPath(404, '/nothing/', 'Custom 404 Page');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test cleanUrls and trailingSlash serve correct content',
|
||||
testFixtureStdio('test-clean-urls-trailing-slash', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
await testPath(200, '/about/', 'About Page');
|
||||
await testPath(200, '/sub/', 'Sub Index Page');
|
||||
await testPath(200, '/sub/another/', 'Sub Another Page');
|
||||
await testPath(200, '/style.css', 'body { color: green }');
|
||||
//TODO: fix this test so that location is `/` instead of `//`
|
||||
//await testPath(308, '/index.html', 'Redirecting to / (308)', { Location: '/' });
|
||||
await testPath(308, '/about.html', 'Redirecting to /about/ (308)', {
|
||||
Location: '/about/',
|
||||
});
|
||||
await testPath(308, '/sub/index.html', 'Redirecting to /sub/ (308)', {
|
||||
Location: '/sub/',
|
||||
});
|
||||
await testPath(
|
||||
308,
|
||||
'/sub/another.html',
|
||||
'Redirecting to /sub/another/ (308)',
|
||||
{
|
||||
Location: '/sub/another/',
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test cors headers work with OPTIONS',
|
||||
testFixtureStdio('test-cors-routes', async (testPath: any) => {
|
||||
const headers = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers':
|
||||
'Content-Type, Authorization, Accept, Content-Length, Origin, User-Agent',
|
||||
'Access-Control-Allow-Methods':
|
||||
'GET, POST, OPTIONS, HEAD, PATCH, PUT, DELETE',
|
||||
};
|
||||
await testPath(200, '/', 'status api', headers, { method: 'GET' });
|
||||
await testPath(200, '/', 'status api', headers, { method: 'POST' });
|
||||
await testPath(200, '/api/status.js', 'status api', headers, {
|
||||
method: 'GET',
|
||||
});
|
||||
await testPath(200, '/api/status.js', 'status api', headers, {
|
||||
method: 'POST',
|
||||
});
|
||||
await testPath(204, '/', '', headers, { method: 'OPTIONS' });
|
||||
await testPath(204, '/api/status.js', '', headers, { method: 'OPTIONS' });
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test trailingSlash true serve correct content',
|
||||
testFixtureStdio('test-trailing-slash', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
await testPath(200, '/index.html', 'Index Page');
|
||||
await testPath(200, '/about.html', 'About Page');
|
||||
await testPath(200, '/sub/', 'Sub Index Page');
|
||||
await testPath(200, '/sub/index.html', 'Sub Index Page');
|
||||
await testPath(200, '/sub/another.html', 'Sub Another Page');
|
||||
await testPath(200, '/style.css', 'body { color: green }');
|
||||
await testPath(308, '/about.html/', 'Redirecting to /about.html (308)', {
|
||||
Location: '/about.html',
|
||||
});
|
||||
await testPath(308, '/style.css/', 'Redirecting to /style.css (308)', {
|
||||
Location: '/style.css',
|
||||
});
|
||||
await testPath(308, '/sub', 'Redirecting to /sub/ (308)', {
|
||||
Location: '/sub/',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should serve custom 404 when `trailingSlash: true`',
|
||||
testFixtureStdio('test-trailing-slash-custom-404', async (testPath: any) => {
|
||||
await testPath(200, '/', 'This is the home page');
|
||||
await testPath(200, '/about.html', 'The about page');
|
||||
await testPath(200, '/contact/', 'Contact Subdirectory');
|
||||
await testPath(404, '/nothing/', 'Custom 404 Page');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] test trailingSlash false serve correct content',
|
||||
testFixtureStdio('test-trailing-slash-false', async (testPath: any) => {
|
||||
await testPath(200, '/', 'Index Page');
|
||||
await testPath(200, '/index.html', 'Index Page');
|
||||
await testPath(200, '/about.html', 'About Page');
|
||||
await testPath(200, '/sub', 'Sub Index Page');
|
||||
await testPath(200, '/sub/index.html', 'Sub Index Page');
|
||||
await testPath(200, '/sub/another.html', 'Sub Another Page');
|
||||
await testPath(200, '/style.css', 'body { color: green }');
|
||||
await testPath(308, '/about.html/', 'Redirecting to /about.html (308)', {
|
||||
Location: '/about.html',
|
||||
});
|
||||
await testPath(308, '/sub/', 'Redirecting to /sub (308)', {
|
||||
Location: '/sub',
|
||||
});
|
||||
await testPath(
|
||||
308,
|
||||
'/sub/another.html/',
|
||||
'Redirecting to /sub/another.html (308)',
|
||||
{
|
||||
Location: '/sub/another.html',
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] throw when invalid builder routes detected',
|
||||
testFixtureStdio(
|
||||
'invalid-builder-routes',
|
||||
async (testPath: any) => {
|
||||
await testPath(
|
||||
500,
|
||||
'/',
|
||||
/Route at index 0 has invalid `src` regular expression/m
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] support legacy `@now` scope runtimes',
|
||||
testFixtureStdio('legacy-now-runtime', async (testPath: any) => {
|
||||
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 00-list-directory',
|
||||
testFixtureStdio(
|
||||
'00-list-directory',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Files within/m);
|
||||
await testPath(200, '/', /test[0-3]\.txt/m);
|
||||
await testPath(200, '/', /\.well-known/m);
|
||||
await testPath(200, '/.well-known/keybase.txt', 'proof goes here');
|
||||
},
|
||||
{ projectSettings: { directoryListing: true } }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 01-node',
|
||||
testFixtureStdio('01-node', async (testPath: any) => {
|
||||
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
|
||||
})
|
||||
);
|
||||
348
packages/cli/test/dev/integration-3.test.ts
Normal file
348
packages/cli/test/dev/integration-3.test.ts
Normal file
@@ -0,0 +1,348 @@
|
||||
import { resolve, delimiter } from 'path';
|
||||
|
||||
const {
|
||||
fetch,
|
||||
sleep,
|
||||
fixture,
|
||||
isCanary,
|
||||
shouldSkip,
|
||||
testFixture,
|
||||
fetchWithRetry,
|
||||
testFixtureStdio,
|
||||
validateResponseHeaders,
|
||||
} = require('./utils.js');
|
||||
|
||||
// Angular has `engines: { node: "10.x" }` in its `package.json`
|
||||
test('[vercel dev] 02-angular-node', async () => {
|
||||
if (shouldSkip('02-angular-node', '10.x')) return;
|
||||
|
||||
const directory = fixture('02-angular-node');
|
||||
const { dev, port } = await testFixture(directory, { stdio: 'pipe' }, [
|
||||
'--debug',
|
||||
]);
|
||||
|
||||
let stderr = '';
|
||||
|
||||
try {
|
||||
dev.stderr.on('data', async (data: any) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
// start `vercel dev` detached in child_process
|
||||
dev.unref();
|
||||
|
||||
const response = await fetchWithRetry(`http://localhost:${port}`, {
|
||||
retries: 180,
|
||||
status: 200,
|
||||
});
|
||||
|
||||
validateResponseHeaders(response);
|
||||
|
||||
const body = await response.text();
|
||||
expect(body).toMatch(/Angular \+ Node.js API/m);
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
}
|
||||
|
||||
await sleep(5000);
|
||||
|
||||
if (isCanary()) {
|
||||
stderr.includes('@now/build-utils@canary');
|
||||
} else {
|
||||
stderr.includes('@now/build-utils@latest');
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] 03-aurelia',
|
||||
testFixtureStdio(
|
||||
'03-aurelia',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Aurelia Navigation Skeleton/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 04-create-react-app',
|
||||
testFixtureStdio('04-create-react-app', async (testPath: any) => {
|
||||
await testPath(200, '/', /React App/m);
|
||||
})
|
||||
);
|
||||
/*
|
||||
test(
|
||||
'[vercel dev] 05-gatsby',
|
||||
testFixtureStdio('05-gatsby', async (testPath: any) => {
|
||||
await testPath(200, '/', /Gatsby Default Starter/m);
|
||||
})
|
||||
);
|
||||
*/
|
||||
test(
|
||||
'[vercel dev] 06-gridsome',
|
||||
testFixtureStdio('06-gridsome', async (testPath: any) => {
|
||||
await testPath(200, '/');
|
||||
await testPath(200, '/about');
|
||||
await testPath(308, '/support', 'Redirecting to /about?ref=support (308)', {
|
||||
Location: '/about?ref=support',
|
||||
});
|
||||
// Bug with gridsome's dev server: https://github.com/gridsome/gridsome/issues/831
|
||||
// Works in prod only so leave out for now
|
||||
// await testPath(404, '/nothing');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 07-hexo-node',
|
||||
testFixtureStdio('07-hexo-node', async (testPath: any) => {
|
||||
await testPath(200, '/', /Hexo \+ Node.js API/m);
|
||||
await testPath(200, '/api/date', new RegExp(new Date().getFullYear() + ''));
|
||||
await testPath(200, '/contact.html', /Contact Us/m);
|
||||
await testPath(200, '/support', /Contact Us/m);
|
||||
})
|
||||
);
|
||||
|
||||
test('[vercel dev] 08-hugo', async () => {
|
||||
if (process.platform === 'darwin') {
|
||||
// Update PATH to find the Hugo executable installed via GH Actions
|
||||
process.env.PATH = `${resolve(fixture('08-hugo'))}${delimiter}${
|
||||
process.env.PATH
|
||||
}`;
|
||||
const tester = testFixtureStdio('08-hugo', async (testPath: any) => {
|
||||
await testPath(200, '/', /Hugo/m);
|
||||
});
|
||||
await tester();
|
||||
} else {
|
||||
console.log(`Skipping 08-hugo on platform ${process.platform}`);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] 10-nextjs-node',
|
||||
testFixtureStdio('10-nextjs-node', async (testPath: any) => {
|
||||
await testPath(200, '/', /Next.js \+ Node.js API/m);
|
||||
await testPath(200, '/api/date', new RegExp(new Date().getFullYear() + ''));
|
||||
await testPath(200, '/contact', /Contact Page/);
|
||||
await testPath(200, '/support', /Contact Page/);
|
||||
// TODO: Fix this test assertion that fails intermittently
|
||||
// await testPath(404, '/nothing', /Custom Next 404/);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 10a-nextjs-routes',
|
||||
testFixtureStdio('10a-nextjs-routes', async (testPath: any) => {
|
||||
await testPath(200, '/', /Next.js with routes/m);
|
||||
await testPath(200, '/hello', /Hello Routes/m);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 12-polymer-node',
|
||||
testFixtureStdio(
|
||||
'12-polymer-node',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Polymer \+ Node.js API/m);
|
||||
await testPath(
|
||||
200,
|
||||
'/api/date',
|
||||
new RegExp(new Date().getFullYear() + '')
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 13-preact-node',
|
||||
testFixtureStdio(
|
||||
'13-preact-node',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Preact/m);
|
||||
await testPath(
|
||||
200,
|
||||
'/api/date',
|
||||
new RegExp(new Date().getFullYear() + '')
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 14-svelte-node',
|
||||
testFixtureStdio(
|
||||
'14-svelte-node',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Svelte/m);
|
||||
await testPath(
|
||||
200,
|
||||
'/api/date',
|
||||
new RegExp(new Date().getFullYear() + '')
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 16-vue-node',
|
||||
testFixtureStdio(
|
||||
'16-vue-node',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Vue.js \+ Node.js API/m);
|
||||
await testPath(
|
||||
200,
|
||||
'/api/date',
|
||||
new RegExp(new Date().getFullYear() + '')
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 17-vuepress-node',
|
||||
testFixtureStdio(
|
||||
'17-vuepress-node',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /VuePress \+ Node.js API/m);
|
||||
await testPath(
|
||||
200,
|
||||
'/api/date',
|
||||
new RegExp(new Date().getFullYear() + '')
|
||||
);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] double slashes redirect',
|
||||
testFixtureStdio(
|
||||
'01-node',
|
||||
async (_testPath: any, port: any) => {
|
||||
{
|
||||
const res = await fetch(`http://localhost:${port}////?foo=bar`, {
|
||||
redirect: 'manual',
|
||||
});
|
||||
|
||||
validateResponseHeaders(res);
|
||||
|
||||
const body = await res.text();
|
||||
expect(res.status).toBe(301);
|
||||
expect(res.headers.get('location')).toBe(
|
||||
`http://localhost:${port}/?foo=bar`
|
||||
);
|
||||
expect(body).toBe('Redirecting to /?foo=bar (301)\n');
|
||||
}
|
||||
|
||||
{
|
||||
const res = await fetch(`http://localhost:${port}///api////date.js`, {
|
||||
method: 'POST',
|
||||
redirect: 'manual',
|
||||
});
|
||||
|
||||
validateResponseHeaders(res);
|
||||
|
||||
const body = await res.text();
|
||||
expect(res.status).toBe(200);
|
||||
expect(
|
||||
body.startsWith('January') ||
|
||||
body.startsWith('February') ||
|
||||
body.startsWith('March') ||
|
||||
body.startsWith('April') ||
|
||||
body.startsWith('May') ||
|
||||
body.startsWith('June') ||
|
||||
body.startsWith('July') ||
|
||||
body.startsWith('August') ||
|
||||
body.startsWith('September') ||
|
||||
body.startsWith('October') ||
|
||||
body.startsWith('November') ||
|
||||
body.startsWith('December')
|
||||
).toBeTruthy();
|
||||
}
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 18-marko',
|
||||
testFixtureStdio(
|
||||
'18-marko',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Marko Starter/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 19-mithril',
|
||||
testFixtureStdio(
|
||||
'19-mithril',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Mithril on Vercel/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 20-riot',
|
||||
testFixtureStdio(
|
||||
'20-riot',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Riot on Vercel/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 21-charge',
|
||||
testFixtureStdio(
|
||||
'21-charge',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Welcome to my new Charge site/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 22-brunch',
|
||||
testFixtureStdio(
|
||||
'22-brunch',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /Bon Appétit./m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 23-docusaurus',
|
||||
testFixtureStdio(
|
||||
'23-docusaurus',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /My Site/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test('[vercel dev] 24-ember', async () => {
|
||||
if (shouldSkip('24-ember', '>^6.14.0 || ^8.10.0 || >=9.10.0')) return;
|
||||
|
||||
const tester = testFixtureStdio(
|
||||
'24-ember',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/', /HelloWorld/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
);
|
||||
|
||||
await tester();
|
||||
});
|
||||
427
packages/cli/test/dev/integration-4.test.ts
Normal file
427
packages/cli/test/dev/integration-4.test.ts
Normal file
@@ -0,0 +1,427 @@
|
||||
import ms from 'ms';
|
||||
import fs from 'fs-extra';
|
||||
import { isIP } from 'net';
|
||||
import { join } from 'path';
|
||||
|
||||
const {
|
||||
fetch,
|
||||
sleep,
|
||||
fixture,
|
||||
testFixture,
|
||||
testFixtureStdio,
|
||||
validateResponseHeaders,
|
||||
} = require('./utils.js');
|
||||
|
||||
test(
|
||||
'[vercel dev] temporary directory listing',
|
||||
testFixtureStdio(
|
||||
'temporary-directory-listing',
|
||||
async (_testPath: any, port: any) => {
|
||||
const directory = fixture('temporary-directory-listing');
|
||||
await fs.unlink(join(directory, 'index.txt')).catch(() => null);
|
||||
|
||||
await sleep(ms('20s'));
|
||||
|
||||
const firstResponse = await fetch(`http://localhost:${port}`);
|
||||
validateResponseHeaders(firstResponse);
|
||||
const body = await firstResponse.text();
|
||||
console.log(body);
|
||||
expect(firstResponse.status).toBe(404);
|
||||
|
||||
await fs.writeFile(join(directory, 'index.txt'), 'hello');
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const response = await fetch(`http://localhost:${port}`);
|
||||
validateResponseHeaders(response);
|
||||
|
||||
if (response.status === 200) {
|
||||
const body = await response.text();
|
||||
expect(body).toBe('hello');
|
||||
}
|
||||
|
||||
await sleep(ms('1s'));
|
||||
}
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test('[vercel dev] add a `package.json` to trigger `@vercel/static-build`', async () => {
|
||||
const directory = fixture('trigger-static-build');
|
||||
|
||||
await fs.unlink(join(directory, 'package.json')).catch(() => null);
|
||||
|
||||
await fs.unlink(join(directory, 'public', 'index.txt')).catch(() => null);
|
||||
|
||||
await fs.rmdir(join(directory, 'public')).catch(() => null);
|
||||
|
||||
const tester = testFixtureStdio(
|
||||
'trigger-static-build',
|
||||
async (_testPath: any, port: any) => {
|
||||
{
|
||||
const response = await fetch(`http://localhost:${port}`);
|
||||
validateResponseHeaders(response);
|
||||
const body = await response.text();
|
||||
expect(body.trim()).toBe('hello:index.txt');
|
||||
}
|
||||
|
||||
const rnd = Math.random().toString();
|
||||
const pkg = {
|
||||
private: true,
|
||||
scripts: { build: `mkdir -p public && echo ${rnd} > public/index.txt` },
|
||||
};
|
||||
|
||||
await fs.writeFile(join(directory, 'package.json'), JSON.stringify(pkg));
|
||||
|
||||
// Wait until file events have been processed
|
||||
await sleep(ms('2s'));
|
||||
|
||||
{
|
||||
const response = await fetch(`http://localhost:${port}`);
|
||||
validateResponseHeaders(response);
|
||||
const body = await response.text();
|
||||
expect(body.trim()).toBe(rnd);
|
||||
}
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
);
|
||||
|
||||
await tester();
|
||||
});
|
||||
|
||||
test('[vercel dev] no build matches warning', async () => {
|
||||
const directory = fixture('no-build-matches');
|
||||
const { dev } = await testFixture(directory, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
try {
|
||||
// start `vercel dev` detached in child_process
|
||||
dev.unref();
|
||||
|
||||
dev.stderr.setEncoding('utf8');
|
||||
await new Promise<void>(resolve => {
|
||||
dev.stderr.on('data', (str: string) => {
|
||||
if (str.includes('did not match any source files')) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] do not recursivly check the path',
|
||||
testFixtureStdio('handle-filesystem-missing', async (testPath: any) => {
|
||||
await testPath(200, '/', /hello/m);
|
||||
await testPath(404, '/favicon.txt');
|
||||
})
|
||||
);
|
||||
|
||||
test('[vercel dev] render warning for empty cwd dir', async () => {
|
||||
const directory = fixture('empty');
|
||||
const { dev, port } = await testFixture(directory, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
try {
|
||||
dev.unref();
|
||||
|
||||
// Monitor `stderr` for the warning
|
||||
dev.stderr.setEncoding('utf8');
|
||||
const msg = 'There are no files inside your deployment.';
|
||||
await new Promise<void>(resolve => {
|
||||
dev.stderr.on('data', (str: string) => {
|
||||
if (str.includes(msg)) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Issue a request to ensure a 404 response
|
||||
await sleep(ms('3s'));
|
||||
const response = await fetch(`http://localhost:${port}`);
|
||||
validateResponseHeaders(response);
|
||||
expect(response.status).toBe(404);
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
|
||||
test('[vercel dev] do not rebuild for changes in the output directory', async () => {
|
||||
const directory = fixture('output-is-source');
|
||||
|
||||
const { dev, port } = await testFixture(directory, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
try {
|
||||
dev.unref();
|
||||
|
||||
let stderr: any = [];
|
||||
const start = Date.now();
|
||||
|
||||
dev.stderr.on('data', (str: any) => stderr.push(str));
|
||||
|
||||
while (stderr.join('').includes('Ready') === false) {
|
||||
await sleep(ms('3s'));
|
||||
|
||||
if (Date.now() - start > ms('30s')) {
|
||||
console.log('stderr:', stderr.join(''));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const resp1 = await fetch(`http://localhost:${port}`);
|
||||
const text1 = await resp1.text();
|
||||
expect(text1.trim()).toBe('hello first');
|
||||
|
||||
await fs.writeFile(join(directory, 'public', 'index.html'), 'hello second');
|
||||
|
||||
await sleep(ms('3s'));
|
||||
|
||||
const resp2 = await fetch(`http://localhost:${port}`);
|
||||
const text2 = await resp2.text();
|
||||
expect(text2.trim()).toBe('hello second');
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'[vercel dev] 25-nextjs-src-dir',
|
||||
testFixtureStdio('25-nextjs-src-dir', async (testPath: any) => {
|
||||
await testPath(200, '/', /Next.js \+ Node.js API/m);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 27-zero-config-env',
|
||||
testFixtureStdio(
|
||||
'27-zero-config-env',
|
||||
async (testPath: any) => {
|
||||
await testPath(200, '/api/print', /build-and-runtime/m);
|
||||
await testPath(200, '/', /build-and-runtime/m);
|
||||
},
|
||||
{ skipDeploy: true }
|
||||
)
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 28-vercel-json-and-ignore',
|
||||
testFixtureStdio('28-vercel-json-and-ignore', async (testPath: any) => {
|
||||
await testPath(200, '/api/one', 'One');
|
||||
await testPath(404, '/api/two');
|
||||
await testPath(200, '/api/three', 'One');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 30-next-image-optimization',
|
||||
testFixtureStdio('30-next-image-optimization', async (testPath: any) => {
|
||||
const toUrl = (url: any, w: any, q: any) => {
|
||||
// @ts-ignore
|
||||
const query = new URLSearchParams();
|
||||
query.append('url', url);
|
||||
query.append('w', w);
|
||||
query.append('q', q);
|
||||
return `/_next/image?${query}`;
|
||||
};
|
||||
|
||||
const expectHeader = (accept: any) => ({
|
||||
'content-type': accept,
|
||||
'cache-control': 'public, max-age=0, must-revalidate',
|
||||
});
|
||||
const fetchOpts = (accept: any) => ({ method: 'GET', headers: { accept } });
|
||||
await testPath(200, '/', /Home Page/m);
|
||||
await testPath(
|
||||
200,
|
||||
toUrl('/test.jpg', 64, 100),
|
||||
null,
|
||||
expectHeader('image/webp'),
|
||||
fetchOpts('image/webp')
|
||||
);
|
||||
await testPath(
|
||||
200,
|
||||
toUrl('/test.png', 64, 90),
|
||||
null,
|
||||
expectHeader('image/webp'),
|
||||
fetchOpts('image/webp')
|
||||
);
|
||||
/*
|
||||
* Disabled gif in https://github.com/vercel/next.js/pull/22253
|
||||
* Eventually we should enable again when `next dev` supports it
|
||||
await testPath(
|
||||
200,
|
||||
toUrl('/test.gif', 64, 80),
|
||||
null,
|
||||
expectHeader('image/webp'),
|
||||
fetchOpts('image/webp')
|
||||
);
|
||||
*/
|
||||
/*
|
||||
* Disabled svg in https://github.com/vercel/next.js/pull/34431
|
||||
* We can test for 400 status since config option is not enabled.
|
||||
*/
|
||||
await testPath(400, toUrl('/test.svg', 64, 70));
|
||||
/* Disabled bmp because `next dev` bypasses
|
||||
* and production will convert. Eventually
|
||||
* we can enable once `next dev` supports it.
|
||||
await testPath(
|
||||
200,
|
||||
toUrl('/test.bmp', 64, 50),
|
||||
null,
|
||||
expectHeader('image/bmp'),
|
||||
fetchOpts('image/webp')
|
||||
);
|
||||
*/
|
||||
// animated gif should bypass: serve as-is
|
||||
await testPath(
|
||||
200,
|
||||
toUrl('/animated.gif', 64, 60),
|
||||
null,
|
||||
expectHeader('image/gif'),
|
||||
fetchOpts('image/webp')
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 40-mixed-modules',
|
||||
testFixtureStdio('40-mixed-modules', async (testPath: any) => {
|
||||
await testPath(200, '/entrypoint.js', 'mixed-modules:js');
|
||||
await testPath(200, '/entrypoint.mjs', 'mixed-modules:mjs');
|
||||
await testPath(200, '/entrypoint.ts', 'mixed-modules:ts');
|
||||
await testPath(
|
||||
200,
|
||||
'/type-module-package-json/auto.js',
|
||||
'mixed-modules:auto'
|
||||
);
|
||||
await testPath(
|
||||
200,
|
||||
'/type-module-package-json/nested/also.js',
|
||||
'mixed-modules:also'
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] 41-tsconfig-jsx',
|
||||
testFixtureStdio('41-tsconfig-jsx', async (testPath: any) => {
|
||||
await testPath(200, '/', /Solid App/m);
|
||||
await testPath(200, '/api/test', 'working');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Use `@vercel/python` with Flask requirements.txt',
|
||||
testFixtureStdio('python-flask', async (testPath: any) => {
|
||||
const name = 'Alice';
|
||||
const year = new Date().getFullYear();
|
||||
await testPath(200, `/api/user?name=${name}`, new RegExp(`Hello ${name}`));
|
||||
await testPath(200, `/api/date`, new RegExp(`Current date is ${year}`));
|
||||
await testPath(200, `/api/date.py`, new RegExp(`Current date is ${year}`));
|
||||
await testPath(200, `/api/headers`, (body: any, res: any) => {
|
||||
// @ts-ignore
|
||||
const { host } = new URL(res.url);
|
||||
expect(body).toBe(host);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Use custom runtime from the "functions" property',
|
||||
testFixtureStdio('custom-runtime', async (testPath: any) => {
|
||||
await testPath(200, `/api/user`, /Hello, from Bash!/m);
|
||||
await testPath(200, `/api/user.sh`, /Hello, from Bash!/m);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Should work with nested `tsconfig.json` files',
|
||||
testFixtureStdio('nested-tsconfig', async (testPath: any) => {
|
||||
await testPath(200, `/`, /Nested tsconfig.json test page/);
|
||||
await testPath(200, `/api`, 'Nested `tsconfig.json` API endpoint');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Should force `tsc` option "module: commonjs" for `startDevServer()`',
|
||||
testFixtureStdio('force-module-commonjs', async (testPath: any) => {
|
||||
await testPath(200, `/`, /Force "module: commonjs" test page/);
|
||||
await testPath(
|
||||
200,
|
||||
`/api`,
|
||||
'Force "module: commonjs" JavaScript with ES Modules API endpoint'
|
||||
);
|
||||
await testPath(
|
||||
200,
|
||||
`/api/ts`,
|
||||
'Force "module: commonjs" TypeScript API endpoint'
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] should prioritize index.html over other file named index.*',
|
||||
testFixtureStdio('index-html-priority', async (testPath: any) => {
|
||||
await testPath(200, '/', 'This is index.html');
|
||||
await testPath(200, '/index.css', 'This is index.css');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Should support `*.go` API serverless functions',
|
||||
testFixtureStdio('go', async (testPath: any) => {
|
||||
await testPath(200, `/api`, 'This is the index page');
|
||||
await testPath(200, `/api/index`, 'This is the index page');
|
||||
await testPath(200, `/api/index.go`, 'This is the index page');
|
||||
await testPath(200, `/api/another`, 'This is another page');
|
||||
await testPath(200, '/api/another.go', 'This is another page');
|
||||
await testPath(200, `/api/foo`, 'Req Path: /api/foo');
|
||||
await testPath(200, `/api/bar`, 'Req Path: /api/bar');
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Should set the `ts-node` "target" to match Node.js version',
|
||||
testFixtureStdio('node-ts-node-target', async (testPath: any) => {
|
||||
await testPath(200, `/api/subclass`, '{"ok":true}');
|
||||
await testPath(
|
||||
200,
|
||||
`/api/array`,
|
||||
'{"months":[1,2,3,4,5,6,7,8,9,10,11,12]}'
|
||||
);
|
||||
|
||||
await testPath(200, `/api/dump`, (body: any, res: any, isDev: any) => {
|
||||
// @ts-ignore
|
||||
const { host } = new URL(res.url);
|
||||
const { env, headers } = JSON.parse(body);
|
||||
|
||||
// Test that the API endpoint receives the Vercel proxy request headers
|
||||
expect(headers['x-forwarded-host']).toBe(host);
|
||||
expect(headers['x-vercel-deployment-url']).toBe(host);
|
||||
expect(isIP(headers['x-real-ip'])).toBeTruthy();
|
||||
expect(isIP(headers['x-forwarded-for'])).toBeTruthy();
|
||||
expect(isIP(headers['x-vercel-forwarded-for'])).toBeTruthy();
|
||||
|
||||
// Test that the API endpoint has the Vercel platform env vars defined.
|
||||
expect(env.NOW_REGION).toMatch(/^[a-z]{3}\d$/);
|
||||
if (isDev) {
|
||||
// Only dev is tested because in production these are opt-in.
|
||||
expect(env.VERCEL_URL).toBe(host);
|
||||
expect(env.VERCEL_REGION).toBe('dev1');
|
||||
}
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
test(
|
||||
'[vercel dev] Do not fail if `src` is missing',
|
||||
testFixtureStdio('missing-src-property', async (testPath: any) => {
|
||||
await testPath(200, '/', /hello:index.txt/m);
|
||||
await testPath(404, '/i-do-not-exist');
|
||||
})
|
||||
);
|
||||
File diff suppressed because it is too large
Load Diff
495
packages/cli/test/dev/utils.js
Normal file
495
packages/cli/test/dev/utils.js
Normal file
@@ -0,0 +1,495 @@
|
||||
const fs = require('fs-extra');
|
||||
const { join, resolve } = require('path');
|
||||
const _execa = require('execa');
|
||||
const fetch = require('node-fetch');
|
||||
const retry = require('async-retry');
|
||||
const { satisfies } = require('semver');
|
||||
const stripAnsi = require('strip-ansi');
|
||||
const { getDistTag } = require('../../src/util/get-dist-tag');
|
||||
const { version: cliVersion } = require('../../package.json');
|
||||
const {
|
||||
fetchCachedToken,
|
||||
} = require('../../../../test/lib/deployment/now-deploy');
|
||||
|
||||
jest.setTimeout(6 * 60 * 1000);
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const isCanary = () => getDistTag(cliVersion) === 'canary';
|
||||
|
||||
let port = 3000;
|
||||
|
||||
const binaryPath = resolve(__dirname, `../../scripts/start.js`);
|
||||
const fixture = name => join('test', 'dev', 'fixtures', name);
|
||||
const fixtureAbsolute = name => join(__dirname, 'fixtures', name);
|
||||
const exampleAbsolute = name =>
|
||||
join(__dirname, '..', '..', '..', '..', 'examples', name);
|
||||
|
||||
let processCounter = 0;
|
||||
const processList = new Map();
|
||||
|
||||
function execa(...args) {
|
||||
const procId = ++processCounter;
|
||||
const child = _execa(...args);
|
||||
|
||||
processList.set(procId, child);
|
||||
child.on('exit', () => processList.delete(procId));
|
||||
|
||||
return child;
|
||||
}
|
||||
|
||||
function fetchWithRetry(url, opts = {}) {
|
||||
return retry(
|
||||
async () => {
|
||||
const res = await fetch(url, opts);
|
||||
|
||||
if (res.status !== opts.status) {
|
||||
const text = await res.text();
|
||||
throw new Error(
|
||||
`Failed to fetch ${url} with status ${res.status} (expected ${opts.status}):\n\n${text}\n\n`
|
||||
);
|
||||
}
|
||||
|
||||
return res;
|
||||
},
|
||||
{
|
||||
retries: opts.retries || 3,
|
||||
factor: 1,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function createResolver() {
|
||||
let resolver;
|
||||
const p = new Promise(res => (resolver = res));
|
||||
p.resolve = resolver;
|
||||
return p;
|
||||
}
|
||||
|
||||
function formatOutput({ stderr, stdout }) {
|
||||
return `Received:\n"${stderr}"\n"${stdout}"`;
|
||||
}
|
||||
|
||||
function printOutput(fixture, stdout, stderr) {
|
||||
const lines = (
|
||||
`\nOutput for "${fixture}"\n` +
|
||||
`\n----- stdout -----\n` +
|
||||
stdout +
|
||||
`\n----- stderr -----\n` +
|
||||
stderr
|
||||
).split('\n');
|
||||
|
||||
const getPrefix = nr => {
|
||||
return nr === 0 ? '╭' : nr === lines.length - 1 ? '╰' : '│';
|
||||
};
|
||||
|
||||
console.log(
|
||||
lines.map((line, index) => ` ${getPrefix(index)} ${line}`).join('\n')
|
||||
);
|
||||
}
|
||||
|
||||
function shouldSkip(name, versions) {
|
||||
if (!satisfies(process.version, versions)) {
|
||||
console.log(`Skipping "${name}" because it requires "${versions}".`);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function validateResponseHeaders(res) {
|
||||
if (res.status < 500) {
|
||||
expect(res.headers.get('x-vercel-id')).toBeTruthy();
|
||||
expect(res.headers.get('cache-control').length > 0).toBeTruthy;
|
||||
}
|
||||
}
|
||||
|
||||
async function exec(directory, args = []) {
|
||||
const token = await fetchCachedToken();
|
||||
return execa(
|
||||
binaryPath,
|
||||
[
|
||||
'dev',
|
||||
directory,
|
||||
'-t',
|
||||
token,
|
||||
...(process.env.VERCEL_TEAM_ID
|
||||
? ['--scope', process.env.VERCEL_TEAM_ID]
|
||||
: []),
|
||||
...args,
|
||||
],
|
||||
{
|
||||
reject: false,
|
||||
shell: true,
|
||||
env: { __VERCEL_SKIP_DEV_CMD: 1 },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function runNpmInstall(fixturePath) {
|
||||
if (await fs.pathExists(join(fixturePath, 'package.json'))) {
|
||||
await execa('yarn', ['install'], {
|
||||
cwd: fixturePath,
|
||||
shell: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function testPath(
|
||||
isDev,
|
||||
origin,
|
||||
status,
|
||||
path,
|
||||
expectedText,
|
||||
expectedHeaders = {},
|
||||
fetchOpts = {}
|
||||
) {
|
||||
const opts = {
|
||||
...fetchOpts,
|
||||
redirect: 'manual-dont-change',
|
||||
retries: 5,
|
||||
status,
|
||||
};
|
||||
const url = `${origin}${path}`;
|
||||
const res = await fetchWithRetry(url, opts);
|
||||
const msg = `Testing response from ${fetchOpts.method || 'GET'} ${url}`;
|
||||
console.log(msg);
|
||||
expect(res.status).toBe(status);
|
||||
validateResponseHeaders(res);
|
||||
if (typeof expectedText === 'string') {
|
||||
const actualText = await res.text();
|
||||
expect(actualText.trim()).toBe(expectedText.trim());
|
||||
} else if (typeof expectedText === 'function') {
|
||||
const actualText = await res.text();
|
||||
await expectedText(actualText, res, isDev);
|
||||
} else if (expectedText instanceof RegExp) {
|
||||
const actualText = await res.text();
|
||||
expectedText.lastIndex = 0; // reset since we test twice
|
||||
expect(actualText).toMatch(expectedText);
|
||||
}
|
||||
if (expectedHeaders) {
|
||||
Object.entries(expectedHeaders).forEach(([key, expectedValue]) => {
|
||||
let actualValue = res.headers.get(key);
|
||||
if (key.toLowerCase() === 'location' && actualValue === '//') {
|
||||
// HACK: `node-fetch` has strange behavior for location header so fix it
|
||||
// with `manual-dont-change` opt and convert double slash to single.
|
||||
// See https://github.com/node-fetch/node-fetch/issues/417#issuecomment-587233352
|
||||
actualValue = '/';
|
||||
}
|
||||
expect(actualValue).toBe(expectedValue);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function testFixture(directory, opts = {}, args = []) {
|
||||
await runNpmInstall(directory);
|
||||
|
||||
const token = await fetchCachedToken();
|
||||
const dev = execa(
|
||||
binaryPath,
|
||||
[
|
||||
'dev',
|
||||
directory,
|
||||
'-t',
|
||||
token,
|
||||
...(process.env.VERCEL_TEAM_ID
|
||||
? ['--scope', process.env.VERCEL_TEAM_ID]
|
||||
: []),
|
||||
'-l',
|
||||
String(port),
|
||||
...args,
|
||||
],
|
||||
{
|
||||
reject: false,
|
||||
detached: true,
|
||||
shell: true,
|
||||
stdio: 'pipe',
|
||||
...opts,
|
||||
env: { ...opts.env, __VERCEL_SKIP_DEV_CMD: 1 },
|
||||
}
|
||||
);
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
const readyResolver = createResolver();
|
||||
const exitResolver = createResolver();
|
||||
|
||||
dev.stdout.setEncoding('utf8');
|
||||
dev.stderr.setEncoding('utf8');
|
||||
|
||||
dev.stdout.on('data', data => {
|
||||
stdout += data;
|
||||
});
|
||||
dev.stderr.on('data', data => {
|
||||
stderr += data;
|
||||
|
||||
if (stripAnsi(stderr).includes('Ready! Available at')) {
|
||||
readyResolver.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
let printedOutput = false;
|
||||
|
||||
dev.on('exit', () => {
|
||||
if (!printedOutput) {
|
||||
printOutput(directory, stdout, stderr);
|
||||
printedOutput = true;
|
||||
}
|
||||
exitResolver.resolve();
|
||||
readyResolver.resolve();
|
||||
});
|
||||
|
||||
dev.on('error', () => {
|
||||
if (!printedOutput) {
|
||||
printOutput(directory, stdout, stderr);
|
||||
printedOutput = true;
|
||||
}
|
||||
exitResolver.resolve();
|
||||
readyResolver.resolve();
|
||||
});
|
||||
|
||||
dev._kill = dev.kill;
|
||||
dev.kill = async (...args) => {
|
||||
dev._kill(...args);
|
||||
await exitResolver;
|
||||
};
|
||||
|
||||
return {
|
||||
dev,
|
||||
port,
|
||||
readyResolver,
|
||||
};
|
||||
}
|
||||
|
||||
function testFixtureStdio(
|
||||
directory,
|
||||
fn,
|
||||
{ expectedCode = 0, skipDeploy, isExample, projectSettings } = {}
|
||||
) {
|
||||
return async () => {
|
||||
const nodeMajor = Number(process.versions.node.split('.')[0]);
|
||||
if (isExample && nodeMajor < 12) {
|
||||
console.log(`Skipping ${directory} on Node ${process.version}`);
|
||||
return;
|
||||
}
|
||||
const cwd = isExample
|
||||
? exampleAbsolute(directory)
|
||||
: fixtureAbsolute(directory);
|
||||
const token = await fetchCachedToken();
|
||||
let deploymentUrl;
|
||||
|
||||
// Deploy fixture and link project
|
||||
if (!skipDeploy) {
|
||||
const projectJsonPath = join(cwd, '.vercel', 'project.json');
|
||||
await fs.remove(projectJsonPath);
|
||||
const gitignore = join(cwd, '.gitignore');
|
||||
const hasGitignore = await fs.pathExists(gitignore);
|
||||
|
||||
try {
|
||||
// Run `vc link`
|
||||
const linkResult = await execa(
|
||||
binaryPath,
|
||||
[
|
||||
'-t',
|
||||
token,
|
||||
...(process.env.VERCEL_TEAM_ID
|
||||
? ['--scope', process.env.VERCEL_TEAM_ID]
|
||||
: []),
|
||||
'link',
|
||||
'--confirm',
|
||||
],
|
||||
{ cwd, stdio: 'pipe', reject: false }
|
||||
);
|
||||
console.log({
|
||||
stderr: linkResult.stderr,
|
||||
stdout: linkResult.stdout,
|
||||
});
|
||||
expect(linkResult.exitCode).toBe(0);
|
||||
|
||||
// Patch the project with any non-default properties
|
||||
if (projectSettings) {
|
||||
const { projectId } = await fs.readJson(projectJsonPath);
|
||||
const res = await fetchWithRetry(
|
||||
`https://api.vercel.com/v2/projects/${projectId}${
|
||||
process.env.VERCEL_TEAM_ID
|
||||
? `?teamId=${process.env.VERCEL_TEAM_ID}`
|
||||
: ''
|
||||
}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(projectSettings),
|
||||
retries: 3,
|
||||
status: 200,
|
||||
}
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
|
||||
// Run `vc deploy`
|
||||
let deployResult = await execa(
|
||||
binaryPath,
|
||||
[
|
||||
'-t',
|
||||
token,
|
||||
...(process.env.VERCEL_TEAM_ID
|
||||
? ['--scope', process.env.VERCEL_TEAM_ID]
|
||||
: []),
|
||||
'deploy',
|
||||
'--public',
|
||||
'--no-clipboard',
|
||||
'--debug',
|
||||
],
|
||||
{ cwd, stdio: 'pipe', reject: false }
|
||||
);
|
||||
console.log({
|
||||
exitCode: deployResult.exitCode,
|
||||
stdout: deployResult.stdout,
|
||||
stderr: deployResult.stderr,
|
||||
});
|
||||
expect(deployResult.exitCode).toBe(expectedCode);
|
||||
if (expectedCode === 0) {
|
||||
deploymentUrl = new URL(deployResult.stdout).host;
|
||||
}
|
||||
} finally {
|
||||
if (!hasGitignore) {
|
||||
await fs.remove(gitignore);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Start dev
|
||||
let dev;
|
||||
|
||||
await runNpmInstall(cwd);
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
const readyResolver = createResolver();
|
||||
const exitResolver = createResolver();
|
||||
|
||||
try {
|
||||
let printedOutput = false;
|
||||
|
||||
const env = skipDeploy
|
||||
? { ...process.env, __VERCEL_SKIP_DEV_CMD: 1 }
|
||||
: process.env;
|
||||
dev = execa(
|
||||
binaryPath,
|
||||
[
|
||||
'dev',
|
||||
'-l',
|
||||
port,
|
||||
'-t',
|
||||
token,
|
||||
...(process.env.VERCEL_TEAM_ID
|
||||
? ['--scope', process.env.VERCEL_TEAM_ID]
|
||||
: []),
|
||||
'--debug',
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
env,
|
||||
}
|
||||
);
|
||||
|
||||
dev.stdout.setEncoding('utf8');
|
||||
dev.stderr.setEncoding('utf8');
|
||||
|
||||
dev.stdout.pipe(process.stdout);
|
||||
dev.stderr.pipe(process.stderr);
|
||||
|
||||
dev.stdout.on('data', data => {
|
||||
stdout += data;
|
||||
});
|
||||
|
||||
dev.stderr.on('data', data => {
|
||||
stderr += data;
|
||||
|
||||
if (stripAnsi(data).includes('Ready! Available at')) {
|
||||
readyResolver.resolve();
|
||||
}
|
||||
|
||||
if (stderr.includes(`Requested port ${port} is already in use`)) {
|
||||
dev.kill('SIGTERM');
|
||||
throw new Error(
|
||||
`Failed for "${directory}" with port ${port} with stderr "${stderr}".`
|
||||
);
|
||||
}
|
||||
|
||||
if (stderr.includes('Command failed') || stderr.includes('Error!')) {
|
||||
dev.kill('SIGTERM');
|
||||
throw new Error(`Failed for "${directory}" with stderr "${stderr}".`);
|
||||
}
|
||||
});
|
||||
|
||||
dev.on('exit', () => {
|
||||
if (!printedOutput) {
|
||||
printOutput(directory, stdout, stderr);
|
||||
printedOutput = true;
|
||||
}
|
||||
exitResolver.resolve();
|
||||
});
|
||||
|
||||
dev.on('error', () => {
|
||||
if (!printedOutput) {
|
||||
printOutput(directory, stdout, stderr);
|
||||
printedOutput = true;
|
||||
}
|
||||
exitResolver.resolve();
|
||||
});
|
||||
|
||||
await readyResolver;
|
||||
|
||||
const helperTestPath = async (...args) => {
|
||||
if (!skipDeploy) {
|
||||
await testPath(false, `https://${deploymentUrl}`, ...args);
|
||||
}
|
||||
await testPath(true, `http://localhost:${port}`, ...args);
|
||||
};
|
||||
await fn(helperTestPath, port);
|
||||
} finally {
|
||||
dev.kill('SIGTERM');
|
||||
await exitResolver;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
port = ++port;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
Array.from(processList).map(([_procId, proc]) => {
|
||||
if (proc.killed === false) {
|
||||
console.log(
|
||||
`killing process ${proc.pid} "${proc.spawnargs.join(' ')}"`
|
||||
);
|
||||
|
||||
try {
|
||||
process.kill(proc.pid, 'SIGTERM');
|
||||
} catch (err) {
|
||||
// Was already killed
|
||||
console.error(`Failed to kill process`, proc.pid, err);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
sleep,
|
||||
isCanary,
|
||||
testPath,
|
||||
testFixture,
|
||||
testFixtureStdio,
|
||||
exec,
|
||||
formatOutput,
|
||||
shouldSkip,
|
||||
fixture,
|
||||
fetch,
|
||||
validateResponseHeaders,
|
||||
};
|
||||
@@ -1,2 +1,3 @@
|
||||
.next
|
||||
yarn.lock
|
||||
.vercel
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
target: 'serverless'
|
||||
}
|
||||
@@ -5,8 +5,8 @@
|
||||
"now-build": "next build"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "^8.0.0",
|
||||
"react": "^16.7.0",
|
||||
"react-dom": "^16.7.0"
|
||||
"next": "12.1.6",
|
||||
"react": "18.1.0",
|
||||
"react-dom": "18.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { withRouter } from 'next/router';
|
||||
|
||||
function Index({ router }) {
|
||||
const data = {
|
||||
pathname: router.pathname,
|
||||
query: router.query
|
||||
export async function getServerSideProps({ req }) {
|
||||
return {
|
||||
props: {
|
||||
url: req.url,
|
||||
},
|
||||
};
|
||||
return <div>{ JSON.stringify(data) }</div>;
|
||||
}
|
||||
|
||||
export default withRouter(Index);
|
||||
export default function Index(props) {
|
||||
return <pre>{JSON.stringify(props)}</pre>;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
{
|
||||
"version": 2,
|
||||
"name": "now-dev-next",
|
||||
"builds": [{ "src": "package.json", "use": "@vercel/next@canary" }],
|
||||
"routes": [
|
||||
{
|
||||
"src": "/(.*)",
|
||||
"dest": "/index?route-param=b"
|
||||
"src": "/test",
|
||||
"dest": "/?route-param=b"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
.next
|
||||
yarn.lock
|
||||
!.vercel
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
.next
|
||||
yarn.lock
|
||||
!.vercel
|
||||
|
||||
18
packages/cli/test/integration.js
vendored
18
packages/cli/test/integration.js
vendored
@@ -3495,6 +3495,24 @@ test('reject deploying with wrong team .vercel config', async t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('reject deploying with invalid token', async t => {
|
||||
const directory = fixture('unauthorized-vercel-config');
|
||||
const { exitCode, stderr, stdout } = await execa(
|
||||
binaryPath,
|
||||
[...defaultArgs, '--confirm'],
|
||||
{
|
||||
cwd: directory,
|
||||
reject: false,
|
||||
}
|
||||
);
|
||||
|
||||
t.is(exitCode, 1, formatOutput({ stderr, stdout }));
|
||||
t.regex(
|
||||
stderr,
|
||||
/Error! Could not retrieve Project Settings\. To link your Project, remove the `\.vercel` directory and deploy again\./g
|
||||
);
|
||||
});
|
||||
|
||||
test('[vc link] should show prompts to set up project', async t => {
|
||||
const dir = fixture('project-link-zeroconf');
|
||||
const projectName = `project-link-zeroconf-${
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import chance from 'chance';
|
||||
import { client } from './client';
|
||||
|
||||
export function useTeams(teamId?: string) {
|
||||
export function useTeams(
|
||||
teamId?: string,
|
||||
options: {
|
||||
failMissingToken?: boolean;
|
||||
failNoAccess?: boolean;
|
||||
} = {
|
||||
failMissingToken: false,
|
||||
failNoAccess: false,
|
||||
}
|
||||
) {
|
||||
const id = teamId || chance().guid();
|
||||
const teams = [
|
||||
{
|
||||
@@ -16,6 +25,25 @@ export function useTeams(teamId?: string) {
|
||||
|
||||
for (let team of teams) {
|
||||
client.scenario.get(`/teams/${team.id}`, (_req, res) => {
|
||||
if (options.failMissingToken) {
|
||||
res.statusCode = 403;
|
||||
res.json({
|
||||
message: 'The request is missing an authentication token',
|
||||
code: 'forbidden',
|
||||
missingToken: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.failNoAccess) {
|
||||
res.statusCode = 403;
|
||||
res.send({
|
||||
code: 'team_unauthorized',
|
||||
message: 'You are not authorized',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(team);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { join } from 'path';
|
||||
import { fileNameSymbol } from '@vercel/client';
|
||||
import { client } from '../mocks/client';
|
||||
import deploy from '../../src/commands/deploy';
|
||||
import { setupFixture } from '../helpers/setup-fixture';
|
||||
import { defaultProject, useProject } from '../mocks/project';
|
||||
import { useTeams } from '../mocks/team';
|
||||
import { useUser } from '../mocks/user';
|
||||
import { client } from '../../mocks/client';
|
||||
import deploy from '../../../src/commands/deploy';
|
||||
import { setupFixture } from '../../helpers/setup-fixture';
|
||||
import { defaultProject, useProject } from '../../mocks/project';
|
||||
import { useTeams } from '../../mocks/team';
|
||||
import { useUser } from '../../mocks/user';
|
||||
|
||||
describe('deploy', () => {
|
||||
it('should reject deploying a single file', async () => {
|
||||
@@ -1,11 +1,11 @@
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import env from '../../src/commands/env';
|
||||
import { setupFixture } from '../helpers/setup-fixture';
|
||||
import { client } from '../mocks/client';
|
||||
import { defaultProject, useProject } from '../mocks/project';
|
||||
import { useTeams } from '../mocks/team';
|
||||
import { useUser } from '../mocks/user';
|
||||
import env from '../../../src/commands/env';
|
||||
import { setupFixture } from '../../helpers/setup-fixture';
|
||||
import { client } from '../../mocks/client';
|
||||
import { defaultProject, useProject } from '../../mocks/project';
|
||||
import { useTeams } from '../../mocks/team';
|
||||
import { useUser } from '../../mocks/user';
|
||||
|
||||
describe('env', () => {
|
||||
describe('pull', () => {
|
||||
@@ -1,7 +1,7 @@
|
||||
import { client } from '../mocks/client';
|
||||
import { useUser } from '../mocks/user';
|
||||
import { useDeployment } from '../mocks/deployment';
|
||||
import inspect from '../../src/commands/inspect';
|
||||
import { client } from '../../mocks/client';
|
||||
import { useUser } from '../../mocks/user';
|
||||
import { useDeployment } from '../../mocks/deployment';
|
||||
import inspect from '../../../src/commands/inspect';
|
||||
|
||||
describe('inspect', () => {
|
||||
it('should print out deployment information', async () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import login from '../../src/commands/login';
|
||||
import { client } from '../mocks/client';
|
||||
import { useUser } from '../mocks/user';
|
||||
import login from '../../../src/commands/login';
|
||||
import { client } from '../../mocks/client';
|
||||
import { useUser } from '../../mocks/user';
|
||||
|
||||
describe('login', () => {
|
||||
it('should not allow the `--token` flag', async () => {
|
||||
@@ -1,11 +1,11 @@
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import pull from '../../src/commands/pull';
|
||||
import { setupFixture } from '../helpers/setup-fixture';
|
||||
import { client } from '../mocks/client';
|
||||
import { defaultProject, useProject } from '../mocks/project';
|
||||
import { useTeams } from '../mocks/team';
|
||||
import { useUser } from '../mocks/user';
|
||||
import pull from '../../../src/commands/pull';
|
||||
import { setupFixture } from '../../helpers/setup-fixture';
|
||||
import { client } from '../../mocks/client';
|
||||
import { defaultProject, useProject } from '../../mocks/project';
|
||||
import { useTeams } from '../../mocks/team';
|
||||
import { useUser } from '../../mocks/user';
|
||||
|
||||
describe('pull', () => {
|
||||
it('should handle pulling', async () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { client } from '../mocks/client';
|
||||
import { useUser } from '../mocks/user';
|
||||
import whoami from '../../src/commands/whoami';
|
||||
import { client } from '../../mocks/client';
|
||||
import { useUser } from '../../mocks/user';
|
||||
import whoami from '../../../src/commands/whoami';
|
||||
|
||||
describe('whoami', () => {
|
||||
it('should reject invalid arguments', async () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import parseTarget from '../../../src/util/deploy/parse-target';
|
||||
import { Output } from '../../../src/util/output';
|
||||
import parseTarget from '../../../../src/util/deploy/parse-target';
|
||||
import { Output } from '../../../../src/util/output';
|
||||
|
||||
describe('parseTarget', () => {
|
||||
let output: Output;
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
filterPackage,
|
||||
getBuildUtils,
|
||||
isBundledBuilder,
|
||||
} from '../../../src/util/dev/builder-cache';
|
||||
} from '../../../../src/util/dev/builder-cache';
|
||||
|
||||
describe('filterPackage', () => {
|
||||
it('should filter install "latest", cached canary', () => {
|
||||
@@ -1,4 +1,6 @@
|
||||
import parseListen from '../../../src/util/dev/parse-listen';
|
||||
import parseListen from '../../../../src/util/dev/parse-listen';
|
||||
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
|
||||
describe('parseListen', () => {
|
||||
it('should parse "0" as port 0', () => {
|
||||
@@ -34,19 +36,27 @@ describe('parseListen', () => {
|
||||
expect(result[1]).toEqual('127.0.0.1');
|
||||
});
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
it('should parse "unix:/home/user/server.sock" as UNIX socket file', () => {
|
||||
const result = parseListen('unix:/home/user/server.sock');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual('/home/user/server.sock');
|
||||
});
|
||||
it('should parse "unix:/home/user/server.sock" as UNIX socket file', () => {
|
||||
if (IS_WINDOWS) {
|
||||
console.log('Skipping this test on Windows.');
|
||||
return;
|
||||
}
|
||||
|
||||
it('should parse "pipe:\\\\.\\pipe\\PipeName" as UNIX pipe', () => {
|
||||
const result = parseListen('pipe:\\\\.\\pipe\\PipeName');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual('\\\\.\\pipe\\PipeName');
|
||||
});
|
||||
}
|
||||
const result = parseListen('unix:/home/user/server.sock');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual('/home/user/server.sock');
|
||||
});
|
||||
|
||||
it('should parse "pipe:\\\\.\\pipe\\PipeName" as UNIX pipe', () => {
|
||||
if (IS_WINDOWS) {
|
||||
console.log('Skipping this test on Windows.');
|
||||
return;
|
||||
}
|
||||
|
||||
const result = parseListen('pipe:\\\\.\\pipe\\PipeName');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual('\\\\.\\pipe\\PipeName');
|
||||
});
|
||||
|
||||
it('should fail to parse "bad://url"', () => {
|
||||
let err: Error;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { devRouter } from '../../../src/util/dev/router';
|
||||
import { devRouter } from '../../../../src/util/dev/router';
|
||||
|
||||
describe('devRouter', () => {
|
||||
it('should handle 301 redirection', async () => {
|
||||
@@ -6,8 +6,11 @@ import fs from 'fs-extra';
|
||||
import fetch, { Response } from 'node-fetch';
|
||||
import listen from 'async-listen';
|
||||
import { createServer } from 'http';
|
||||
import { client } from '../../mocks/client';
|
||||
import DevServer from '../../../src/util/dev/server';
|
||||
import { client } from '../../../mocks/client';
|
||||
import DevServer from '../../../../src/util/dev/server';
|
||||
import { DevServerOptions } from '../../../../src/util/dev/types';
|
||||
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
|
||||
async function runNpmInstall(fixturePath: string) {
|
||||
if (await fs.pathExists(path.join(fixturePath, 'package.json'))) {
|
||||
@@ -18,19 +21,34 @@ async function runNpmInstall(fixturePath: string) {
|
||||
}
|
||||
}
|
||||
|
||||
interface TestFixtureOptions extends Omit<DevServerOptions, 'output'> {
|
||||
skip?: boolean;
|
||||
}
|
||||
|
||||
const testFixture =
|
||||
(name: string, fn: (server: DevServer) => Promise<void>) => async () => {
|
||||
let server: DevServer | null = null;
|
||||
(
|
||||
name: string,
|
||||
fn: (server: DevServer) => Promise<void>,
|
||||
options?: TestFixtureOptions
|
||||
) =>
|
||||
async () => {
|
||||
if (options?.skip) {
|
||||
console.log('Skipping this test for this platform.');
|
||||
return;
|
||||
}
|
||||
|
||||
let server: DevServer | undefined;
|
||||
const fixturePath = path.join(__dirname, '../../fixtures/unit', name);
|
||||
await runNpmInstall(fixturePath);
|
||||
try {
|
||||
server = new DevServer(fixturePath, { output: client.output });
|
||||
server = new DevServer(fixturePath, {
|
||||
...options,
|
||||
output: client.output,
|
||||
});
|
||||
await server.start(0);
|
||||
await fn(server);
|
||||
} finally {
|
||||
if (server) {
|
||||
await server.stop();
|
||||
}
|
||||
await server?.stop();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -125,29 +143,32 @@ describe('DevServer', () => {
|
||||
|
||||
it(
|
||||
'should maintain query when builder defines routes',
|
||||
testFixture('now-dev-next', async server => {
|
||||
if (process.platform === 'darwin') {
|
||||
// this test very often fails on Mac OS only due to timeouts
|
||||
console.log('Skipping test on macOS');
|
||||
return;
|
||||
testFixture(
|
||||
'now-dev-next',
|
||||
async server => {
|
||||
const res = await fetch(`${server.address}/test?url-param=a`);
|
||||
validateResponseHeaders(res);
|
||||
|
||||
const text = await res.text();
|
||||
|
||||
// Hacky way of getting the page payload from the response
|
||||
// HTML since we don't have a HTML parser handy.
|
||||
const json = text
|
||||
.match(/<pre>(.*)<\/pre>/)![1]
|
||||
.replace('</pre>', '')
|
||||
.replace('<!-- -->', '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"');
|
||||
const parsed = JSON.parse(json);
|
||||
const query = url.parse(parsed.url, true).query;
|
||||
|
||||
expect(query['url-param']).toEqual('a');
|
||||
expect(query['route-param']).toEqual('b');
|
||||
},
|
||||
{
|
||||
devCommand: 'next dev --port $PORT',
|
||||
}
|
||||
|
||||
const res = await fetch(`${server.address}/something?url-param=a`);
|
||||
validateResponseHeaders(res);
|
||||
|
||||
const text = await res.text();
|
||||
|
||||
// Hacky way of getting the page payload from the response
|
||||
// HTML since we don't have a HTML parser handy.
|
||||
const json = text
|
||||
.match(/<div>(.*)<\/div>/)![1]
|
||||
.replace('</div>', '')
|
||||
.replace(/"/g, '"');
|
||||
const parsed = JSON.parse(json);
|
||||
|
||||
expect(parsed.query['url-param']).toEqual('a');
|
||||
expect(parsed.query['route-param']).toEqual('b');
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
it(
|
||||
@@ -164,10 +185,9 @@ describe('DevServer', () => {
|
||||
'should send `etag` header for static files',
|
||||
testFixture('now-dev-headers', async server => {
|
||||
const res = await fetch(`${server.address}/foo.txt`);
|
||||
const expected =
|
||||
process.platform === 'win32'
|
||||
? '9dc423ab77c2e0446cd355256efff2ea1be27cbf'
|
||||
: 'd263af8ab880c0b97eb6c5c125b5d44f9e5addd9';
|
||||
const expected = IS_WINDOWS
|
||||
? '9dc423ab77c2e0446cd355256efff2ea1be27cbf'
|
||||
: 'd263af8ab880c0b97eb6c5c125b5d44f9e5addd9';
|
||||
expect(res.headers.get('etag')).toEqual(`"${expected}"`);
|
||||
const body = await res.text();
|
||||
expect(body.trim()).toEqual('hi');
|
||||
@@ -176,36 +196,36 @@ describe('DevServer', () => {
|
||||
|
||||
it(
|
||||
'should support default builds and routes',
|
||||
testFixture('now-dev-default-builds-and-routes', async server => {
|
||||
if (process.platform === 'darwin') {
|
||||
// this test very often fails on Mac OS only due to timeouts
|
||||
console.log('Skipping test on macOS');
|
||||
return;
|
||||
testFixture(
|
||||
'now-dev-default-builds-and-routes',
|
||||
async server => {
|
||||
let podId: string;
|
||||
|
||||
let res = await fetch(`${server.address}/`);
|
||||
validateResponseHeaders(res);
|
||||
podId = res.headers.get('x-vercel-id')!.match(/:(\w+)-/)![1];
|
||||
let body = await res.text();
|
||||
expect(body.includes('hello, this is the frontend')).toBeTruthy();
|
||||
|
||||
res = await fetch(`${server.address}/api/users`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('users');
|
||||
|
||||
res = await fetch(`${server.address}/api/users/1`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('users/1');
|
||||
|
||||
res = await fetch(`${server.address}/api/welcome`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('hello and welcome');
|
||||
},
|
||||
{
|
||||
devCommand: 'next dev --port $PORT',
|
||||
}
|
||||
|
||||
let podId: string;
|
||||
|
||||
let res = await fetch(`${server.address}/`);
|
||||
validateResponseHeaders(res);
|
||||
podId = res.headers.get('x-vercel-id')!.match(/:(\w+)-/)![1];
|
||||
let body = await res.text();
|
||||
expect(body.includes('hello, this is the frontend')).toBeTruthy();
|
||||
|
||||
res = await fetch(`${server.address}/api/users`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('users');
|
||||
|
||||
res = await fetch(`${server.address}/api/users/1`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('users/1');
|
||||
|
||||
res = await fetch(`${server.address}/api/welcome`);
|
||||
validateResponseHeaders(res, podId);
|
||||
body = await res.text();
|
||||
expect(body).toEqual('hello and welcome');
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
it(
|
||||
@@ -218,22 +238,26 @@ describe('DevServer', () => {
|
||||
})
|
||||
);
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
// This test is currently failing on Windows, so skip for now:
|
||||
// > Creating initial build
|
||||
// $ serve -l $PORT src
|
||||
// 'serve' is not recognized as an internal or external command,
|
||||
// https://github.com/vercel/vercel/pull/6638/checks?check_run_id=3449662836
|
||||
it(
|
||||
'should support `@vercel/static-build` routing',
|
||||
testFixture('now-dev-static-build-routing', async server => {
|
||||
it(
|
||||
'should support `@vercel/static-build` routing',
|
||||
testFixture(
|
||||
'now-dev-static-build-routing',
|
||||
async server => {
|
||||
const res = await fetch(`${server.address}/api/date`);
|
||||
expect(res.status).toEqual(200);
|
||||
const body = await res.text();
|
||||
expect(body.startsWith('The current date:')).toBeTruthy();
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
// This test is currently failing on Windows, so skip for now:
|
||||
// > Creating initial build
|
||||
// $ serve -l $PORT src
|
||||
// 'serve' is not recognized as an internal or external command,
|
||||
// https://github.com/vercel/vercel/pull/6638/checks?check_run_id=3449662836
|
||||
skip: IS_WINDOWS,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
it(
|
||||
'should support directory listing',
|
||||
@@ -1,4 +1,4 @@
|
||||
import { validateConfig } from '../../../src/util/dev/validate';
|
||||
import { validateConfig } from '../../../../src/util/dev/validate';
|
||||
|
||||
describe('validateConfig', () => {
|
||||
it('should not error with empty config', async () => {
|
||||
@@ -1,8 +1,8 @@
|
||||
import fetch from 'node-fetch';
|
||||
import listen from 'async-listen';
|
||||
import { createServer, IncomingMessage, Server, ServerResponse } from 'http';
|
||||
import { JSONValue } from '../../src/types';
|
||||
import { responseError, responseErrorMessage } from '../../src/util/error';
|
||||
import { JSONValue } from '../../../src/types';
|
||||
import { responseError, responseErrorMessage } from '../../../src/util/error';
|
||||
|
||||
const send = (res: ServerResponse, statusCode: number, body: JSONValue) => {
|
||||
res.statusCode = statusCode;
|
||||
@@ -1,11 +1,11 @@
|
||||
import { join, sep } from 'path';
|
||||
// @ts-ignore - Missing types for "alpha-sort"
|
||||
import { asc as alpha } from 'alpha-sort';
|
||||
import createOutput from '../../src/util/output';
|
||||
import { staticFiles as getStaticFiles_ } from '../../src/util/get-files';
|
||||
import createOutput from '../../../src/util/output';
|
||||
import { staticFiles as getStaticFiles_ } from '../../../src/util/get-files';
|
||||
|
||||
const output = createOutput({ debug: false });
|
||||
const prefix = `${join(__dirname, '../fixtures/unit')}${sep}`;
|
||||
const prefix = `${join(__dirname, '../../fixtures/unit')}${sep}`;
|
||||
const base = (path: string) => path.replace(prefix, '');
|
||||
const fixture = (name: string) => join(prefix, name);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import getProjectName from '../../src/util/get-project-name';
|
||||
import getProjectName from '../../../src/util/get-project-name';
|
||||
|
||||
describe('getProjectName', () => {
|
||||
it('should work with argv', () => {
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isCanary } from '../../src/util/is-canary';
|
||||
import getUpdateCommand from '../../src/util/get-update-command';
|
||||
import { isCanary } from '../../../src/util/is-canary';
|
||||
import getUpdateCommand from '../../../src/util/get-update-command';
|
||||
|
||||
describe('getUpdateCommand', () => {
|
||||
it('should detect update command', async () => {
|
||||
@@ -1,4 +1,4 @@
|
||||
import didYouMean from '../../../src/util/init/did-you-mean';
|
||||
import didYouMean from '../../../../src/util/init/did-you-mean';
|
||||
|
||||
describe('didYouMean', () => {
|
||||
const examples = [
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isValidName } from '../../src/util/is-valid-name';
|
||||
import { isValidName } from '../../../src/util/is-valid-name';
|
||||
|
||||
const tests = {
|
||||
'hello world': true,
|
||||
@@ -1,5 +1,5 @@
|
||||
import { basename, join } from 'path';
|
||||
import { getVercelDirectory } from '../../../src/util/projects/link';
|
||||
import { getVercelDirectory } from '../../../../src/util/projects/link';
|
||||
|
||||
const fixture = (name: string) => join(__dirname, '../../fixtures/unit', name);
|
||||
|
||||
71
packages/cli/test/unit/util/projects/link.test.ts
Normal file
71
packages/cli/test/unit/util/projects/link.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { join } from 'path';
|
||||
import { getLinkedProject } from '../../../../src/util/projects/link';
|
||||
import { client } from '../../../mocks/client';
|
||||
|
||||
import { defaultProject, useProject } from '../../../mocks/project';
|
||||
import { useTeams } from '../../../mocks/team';
|
||||
import { useUser } from '../../../mocks/user';
|
||||
|
||||
type UnPromisify<T> = T extends Promise<infer U> ? U : T;
|
||||
|
||||
const fixture = (name: string) => join(__dirname, '../../fixtures/unit', name);
|
||||
|
||||
describe('getLinkedProject', () => {
|
||||
it('should fail to return a link when token is missing', async () => {
|
||||
const cwd = fixture('vercel-pull-next');
|
||||
|
||||
useUser();
|
||||
useTeams('team_dummy', { failMissingToken: true });
|
||||
useProject({
|
||||
...defaultProject,
|
||||
id: 'vercel-pull-next',
|
||||
name: 'vercel-pull-next',
|
||||
});
|
||||
|
||||
let link: UnPromisify<ReturnType<typeof getLinkedProject>> | undefined;
|
||||
let error: Error | undefined;
|
||||
try {
|
||||
link = await getLinkedProject(client, cwd);
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
|
||||
expect(link).toBeUndefined();
|
||||
|
||||
if (!error) {
|
||||
throw new Error(`Expected an error to be thrown.`);
|
||||
}
|
||||
expect(error.message).toBe(
|
||||
'The specified token is not valid. Use `vercel login` to generate a new token.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should fail to return a link when no access to team', async () => {
|
||||
const cwd = fixture('vercel-pull-next');
|
||||
|
||||
useUser();
|
||||
useTeams('team_dummy', { failNoAccess: true });
|
||||
useProject({
|
||||
...defaultProject,
|
||||
id: 'vercel-pull-next',
|
||||
name: 'vercel-pull-next',
|
||||
});
|
||||
|
||||
let link: UnPromisify<ReturnType<typeof getLinkedProject>> | undefined;
|
||||
let error: Error | undefined;
|
||||
try {
|
||||
link = await getLinkedProject(client, cwd);
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
|
||||
expect(link).toBeUndefined();
|
||||
|
||||
if (!error) {
|
||||
throw new Error(`Expected an error to be thrown.`);
|
||||
}
|
||||
expect(error.message).toBe(
|
||||
'Could not retrieve Project Settings. To link your Project, remove the `.vercel` directory and deploy again.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import toHost from '../../src/util/to-host';
|
||||
import toHost from '../../../src/util/to-host';
|
||||
|
||||
describe('toHost', () => {
|
||||
it('should parse simple to host', () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/client",
|
||||
"version": "11.0.2",
|
||||
"version": "11.0.4-canary.0",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
"homepage": "https://vercel.com",
|
||||
@@ -15,8 +15,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test-integration-once": "jest --verbose --runInBand --bail tests/create-deployment.test.ts tests/create-legacy-deployment.test.ts tests/paths.test.ts",
|
||||
"test-unit": "jest --verbose --runInBand --bail tests/unit.*test.*"
|
||||
"test-integration-once": "yarn test tests/create-deployment.test.ts tests/create-legacy-deployment.test.ts tests/paths.test.ts",
|
||||
"test": "jest --env node --verbose --runInBand --bail",
|
||||
"test-unit": "yarn test tests/unit.*test.*"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
@@ -41,7 +42,7 @@
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@vercel/build-utils": "3.0.1",
|
||||
"@vercel/build-utils": "3.1.1-canary.0",
|
||||
"@zeit/fetch": "5.2.0",
|
||||
"async-retry": "1.2.3",
|
||||
"async-sema": "3.0.0",
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
foo
|
||||
@@ -1 +0,0 @@
|
||||
baz
|
||||
@@ -1 +0,0 @@
|
||||
qux
|
||||
@@ -1 +0,0 @@
|
||||
bar
|
||||
@@ -1 +0,0 @@
|
||||
baz
|
||||
@@ -1 +0,0 @@
|
||||
qux
|
||||
@@ -1 +0,0 @@
|
||||
bar
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/frameworks",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.1",
|
||||
"main": "./dist/frameworks.js",
|
||||
"types": "./dist/frameworks.d.ts",
|
||||
"files": [
|
||||
@@ -9,7 +9,8 @@
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test-unit": "jest --env node --verbose --runInBand --bail"
|
||||
"test": "jest --env node --verbose --runInBand --bail",
|
||||
"test-unit": "yarn test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@iarna/toml": "2.2.3",
|
||||
@@ -20,7 +21,7 @@
|
||||
"@types/js-yaml": "3.12.1",
|
||||
"@types/node": "12.0.4",
|
||||
"@types/node-fetch": "2.5.8",
|
||||
"@vercel/routing-utils": "1.13.2",
|
||||
"@vercel/routing-utils": "1.13.3",
|
||||
"ajv": "6.12.2",
|
||||
"typescript": "4.3.4"
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import fetch from 'node-fetch';
|
||||
import { URL, URLSearchParams } from 'url';
|
||||
import frameworkList from '../src/frameworks';
|
||||
|
||||
// bump timeout for Windows as network can be slower
|
||||
jest.setTimeout(15 * 1000);
|
||||
|
||||
const SchemaFrameworkDetectionItem = {
|
||||
type: 'array',
|
||||
items: [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vercel/go",
|
||||
"version": "1.4.2",
|
||||
"version": "1.4.4-canary.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/go",
|
||||
@@ -11,7 +11,8 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node build",
|
||||
"test-integration-once": "jest --env node --verbose --runInBand --bail",
|
||||
"test": "yarn jest --env node --verbose --runInBand --bail",
|
||||
"test-integration-once": "yarn test",
|
||||
"prepublishOnly": "node build"
|
||||
},
|
||||
"files": [
|
||||
@@ -24,7 +25,7 @@
|
||||
"@types/fs-extra": "^5.0.5",
|
||||
"@types/node-fetch": "^2.3.0",
|
||||
"@types/tar": "^4.0.0",
|
||||
"@vercel/build-utils": "3.0.1",
|
||||
"@vercel/build-utils": "3.1.1-canary.0",
|
||||
"@vercel/ncc": "0.24.0",
|
||||
"async-retry": "1.3.1",
|
||||
"execa": "^1.0.0",
|
||||
|
||||
5
packages/go/test/test.js
vendored
5
packages/go/test/test.js
vendored
@@ -21,10 +21,15 @@ beforeAll(async () => {
|
||||
console.log('builderUrl', builderUrl);
|
||||
});
|
||||
|
||||
const skipFixtures = ['08-include-files'];
|
||||
const fixturesPath = path.resolve(__dirname, 'fixtures');
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const fixture of fs.readdirSync(fixturesPath)) {
|
||||
if (skipFixtures.includes(fixture)) {
|
||||
console.log(`Skipping test fixture ${fixture}`);
|
||||
continue;
|
||||
}
|
||||
// eslint-disable-next-line no-loop-func
|
||||
it(`should build ${fixture}`, async () => {
|
||||
await expect(
|
||||
|
||||
2
packages/next/.gitignore
vendored
Normal file
2
packages/next/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/dist
|
||||
test/builder-info.json
|
||||
36
packages/next/build.js
Normal file
36
packages/next/build.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const execa = require('execa');
|
||||
const { remove, rename } = require('fs-extra');
|
||||
const buildEdgeFunctionTemplate = require('./scripts/build-edge-function-template');
|
||||
|
||||
async function main() {
|
||||
const isDevBuild = process.argv.includes('--dev');
|
||||
|
||||
await remove('dist');
|
||||
await execa('tsc', [], { stdio: 'inherit' });
|
||||
await buildEdgeFunctionTemplate();
|
||||
|
||||
if (!isDevBuild) {
|
||||
await execa(
|
||||
'ncc',
|
||||
[
|
||||
'build',
|
||||
'src/index.ts',
|
||||
'--minify',
|
||||
'-e',
|
||||
'esbuild',
|
||||
'-e',
|
||||
'@vercel/build-utils',
|
||||
'-o',
|
||||
'dist/main',
|
||||
],
|
||||
{ stdio: 'inherit' }
|
||||
);
|
||||
await rename('dist/main/index.js', 'dist/index.js');
|
||||
await remove('dist/main');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
73
packages/next/package.json
Normal file
73
packages/next/package.json
Normal file
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "@vercel/next",
|
||||
"version": "2.8.67-canary.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/index",
|
||||
"homepage": "https://vercel.com/docs/runtimes#official-runtimes/next-js",
|
||||
"scripts": {
|
||||
"build": "node build.js",
|
||||
"build-dev": "node build.js --dev",
|
||||
"test": "jest --env node --verbose --bail --runInBand",
|
||||
"test-unit": "yarn test test/build.test.ts test/unit/",
|
||||
"test-next-local": "jest --env node --verbose --bail --forceExit --testTimeout=360000 test/integration/*.test.js test/integration/*.test.ts",
|
||||
"test-next-local:middleware": "jest --env node --verbose --bail --useStderr --testTimeout=360000 test/integration/middleware.test.ts",
|
||||
"test-integration-once": "rm test/builder-info.json; jest --env node --verbose --runInBand --bail test/fixtures/**/*.test.js",
|
||||
"prepublishOnly": "yarn build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/vercel/vercel.git",
|
||||
"directory": "packages/next"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"jest": {
|
||||
"preset": "ts-jest/presets/default",
|
||||
"testEnvironment": "node",
|
||||
"globals": {
|
||||
"ts-jest": {
|
||||
"diagnostics": true,
|
||||
"isolatedModules": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/aws-lambda": "8.10.19",
|
||||
"@types/buffer-crc32": "0.2.0",
|
||||
"@types/convert-source-map": "1.5.2",
|
||||
"@types/find-up": "4.0.0",
|
||||
"@types/fs-extra": "8.0.0",
|
||||
"@types/glob": "7.1.3",
|
||||
"@types/next-server": "8.0.0",
|
||||
"@types/node": "14.17.27",
|
||||
"@types/resolve-from": "5.0.1",
|
||||
"@types/semver": "6.0.0",
|
||||
"@types/text-table": "0.2.1",
|
||||
"@types/webpack-sources": "3.2.0",
|
||||
"@vercel/build-utils": "3.1.1-canary.0",
|
||||
"@vercel/nft": "0.19.0",
|
||||
"@vercel/routing-utils": "1.13.3",
|
||||
"async-sema": "3.0.1",
|
||||
"buffer-crc32": "0.2.13",
|
||||
"cheerio": "1.0.0-rc.10",
|
||||
"convert-source-map": "1.8.0",
|
||||
"esbuild": "0.12.22",
|
||||
"escape-string-regexp": "2.0.0",
|
||||
"execa": "2.0.4",
|
||||
"find-up": "4.1.0",
|
||||
"fs-extra": "7.0.0",
|
||||
"get-port": "5.0.0",
|
||||
"nanoid": "3.3.4",
|
||||
"ndjson": "2.0.0",
|
||||
"pretty-bytes": "5.6.0",
|
||||
"resolve-from": "5.0.0",
|
||||
"semver": "6.1.1",
|
||||
"set-cookie-parser": "2.4.6",
|
||||
"source-map": "0.7.3",
|
||||
"test-listen": "1.1.0",
|
||||
"text-table": "0.2.0",
|
||||
"typescript": "4.5.2",
|
||||
"webpack-sources": "3.2.3"
|
||||
}
|
||||
}
|
||||
46
packages/next/scripts/build-edge-function-template.js
Normal file
46
packages/next/scripts/build-edge-function-template.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const { build } = require('esbuild');
|
||||
const assert = require('assert');
|
||||
const { outputFile } = require('fs-extra');
|
||||
|
||||
/**
|
||||
* @param {Pick<import('esbuild').BuildOptions, 'outfile' | 'format' | 'entryPoints' | 'write'>} options
|
||||
*/
|
||||
async function buildTemplate(options) {
|
||||
return build({
|
||||
bundle: true,
|
||||
entryPoints: options.entryPoints,
|
||||
format: options.format,
|
||||
legalComments: 'none',
|
||||
minify: process.env.NODE_ENV !== 'test',
|
||||
outfile: options.outfile,
|
||||
// Cloudflare Workers uses the V8 JavaScript engine from Google Chrome.
|
||||
// The Workers runtime is updated at least once a week, to at least the version
|
||||
// that is currently used by Chrome's stable release.
|
||||
// To see the latest stable chrome version: https://www.chromestatus.com/features/schedule
|
||||
target: 'esnext',
|
||||
write: options.write,
|
||||
});
|
||||
}
|
||||
|
||||
async function buildNextjsWrapper() {
|
||||
const { outputFiles } = await buildTemplate({
|
||||
entryPoints: ['./src/edge-function-source/get-edge-function'],
|
||||
outfile: 'dist/___get-nextjs-edge-function.js',
|
||||
format: 'cjs', // https://esbuild.github.io/api/#format
|
||||
write: false,
|
||||
});
|
||||
|
||||
assert(outputFiles);
|
||||
const [src] = outputFiles;
|
||||
|
||||
return outputFile(src.path, `module.exports = ${JSON.stringify(src.text)}`);
|
||||
}
|
||||
|
||||
module.exports = buildNextjsWrapper;
|
||||
|
||||
if (!module.parent) {
|
||||
buildNextjsWrapper().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
95
packages/next/src/create-serverless-config.ts
Normal file
95
packages/next/src/create-serverless-config.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import semver from 'semver';
|
||||
|
||||
import { ExperimentalTraceVersion } from './utils';
|
||||
|
||||
function getCustomData(importName: string, target: string) {
|
||||
return `
|
||||
// @ts-nocheck
|
||||
module.exports = function(...args) {
|
||||
let original = require('./${importName}');
|
||||
|
||||
const finalConfig = {};
|
||||
const target = { target: '${target}' };
|
||||
|
||||
if (typeof original === 'function' && original.constructor.name === 'AsyncFunction') {
|
||||
// AsyncFunctions will become promises
|
||||
original = original(...args);
|
||||
}
|
||||
|
||||
if (original instanceof Promise) {
|
||||
// Special case for promises, as it's currently not supported
|
||||
// and will just error later on
|
||||
return original
|
||||
.then((orignalConfig) => Object.assign(finalConfig, orignalConfig))
|
||||
.then((config) => Object.assign(config, target));
|
||||
} else if (typeof original === 'function') {
|
||||
Object.assign(finalConfig, original(...args));
|
||||
} else if (typeof original === 'object') {
|
||||
Object.assign(finalConfig, original);
|
||||
}
|
||||
|
||||
Object.assign(finalConfig, target);
|
||||
|
||||
return finalConfig;
|
||||
}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
function getDefaultData(target: string) {
|
||||
return `
|
||||
// @ts-nocheck
|
||||
module.exports = { target: '${target}' };
|
||||
`.trim();
|
||||
}
|
||||
|
||||
export default async function createServerlessConfig(
|
||||
workPath: string,
|
||||
entryPath: string,
|
||||
nextVersion: string | undefined
|
||||
) {
|
||||
let target = 'serverless';
|
||||
|
||||
if (nextVersion) {
|
||||
try {
|
||||
if (semver.gte(nextVersion, ExperimentalTraceVersion)) {
|
||||
target = 'experimental-serverless-trace';
|
||||
}
|
||||
} catch (
|
||||
_ignored
|
||||
// eslint-disable-next-line
|
||||
) {}
|
||||
}
|
||||
const primaryConfigPath = path.join(entryPath, 'next.config.js');
|
||||
const secondaryConfigPath = path.join(workPath, 'next.config.js');
|
||||
const backupConfigName = `next.config.__vercel_builder_backup__.js`;
|
||||
|
||||
const hasPrimaryConfig = fs.existsSync(primaryConfigPath);
|
||||
const hasSecondaryConfig = fs.existsSync(secondaryConfigPath);
|
||||
|
||||
let configPath: string;
|
||||
let backupConfigPath: string;
|
||||
|
||||
if (hasPrimaryConfig) {
|
||||
// Prefer primary path
|
||||
configPath = primaryConfigPath;
|
||||
backupConfigPath = path.join(entryPath, backupConfigName);
|
||||
} else if (hasSecondaryConfig) {
|
||||
// Work with secondary path (some monorepo setups)
|
||||
configPath = secondaryConfigPath;
|
||||
backupConfigPath = path.join(workPath, backupConfigName);
|
||||
} else {
|
||||
// Default to primary path for creation
|
||||
configPath = primaryConfigPath;
|
||||
backupConfigPath = path.join(entryPath, backupConfigName);
|
||||
}
|
||||
|
||||
if (fs.existsSync(configPath)) {
|
||||
await fs.rename(configPath, backupConfigPath);
|
||||
await fs.writeFile(configPath, getCustomData(backupConfigName, target));
|
||||
} else {
|
||||
await fs.writeFile(configPath, getDefaultData(target));
|
||||
}
|
||||
return target;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user